feat(shipping-notice): 新增发货批次和任务管理功能,支持批次创建与任务处理

This commit is contained in:
hugo committed 2026-06-17 20:45:19 +08:00
1 parent 457f0f4e5e
commit 634dee4b81
81 files changed
+9088 -3625

No files matched your search

+287 -14
View File
@@ -1,23 +1,40 @@
"""
api/workspace_shipping_notice.py
用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。
依赖:auth_jwt、query_service、shipping_notice.tools、notice_upload、chat_actions。
逻辑:前端通过本 Blueprint 访问用户鉴权路由;本文件做权限校验与参数编排,再调用 shipping_notice service/workflow 返回页面所需数据。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request, send_file
from pathlib import Path
from app import db
from app.auth_jwt import get_current_user
from app.models import ShippingTask
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_batch_for_user,
get_focus_task_for_batch,
get_task_for_user,
list_batches_for_user,
list_tasks_for_batch,
list_tasks_for_user,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_detail,
serialize_task_summary,
task_export_error_message,
)
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
def _require_user():
"""校验当前请求用户,统一返回 `(user, error_response)` 结构。"""
user = get_current_user()
if not user:
return None, (jsonify({"error": "Unauthorized"}), 401)
@@ -26,16 +43,163 @@ def _require_user():
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
def workspace_shipping_tasks():
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
user, err = _require_user()
if err:
return err
batch_no = str(request.args.get("batch_no") or "").strip() or None
process_status = str(request.args.get("process_status") or "").strip() or None
limit = int(request.args.get("limit") or 100)
return jsonify(list_tasks_for_user(user.id, process_status=process_status, limit=limit))
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
@workspace_shipping_notice_bp.route("/shipping-batches", methods=["GET"])
def workspace_shipping_batches():
"""列出当前用户的发货批次摘要。"""
user, err = _require_user()
if err:
return err
limit = int(request.args.get("limit") or 100)
return jsonify(list_batches_for_user(user.id, limit=limit))
@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
uploads = request.files.getlist("files")
if not uploads:
single = request.files.get("file")
if single:
uploads = [single]
if not uploads:
return jsonify({"error": "files is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import (
extract_notice_text,
guess_source_type,
max_notice_chars,
save_task_notice_upload,
)
conversation_id = str(request.form.get("conversation_id") or "").strip()
notice_items: list[dict] = []
for upload in uploads:
raw = upload.read() or b""
filename = upload.filename or "notice"
source_type = guess_source_type(filename)
text = ""
warnings: list[str] = []
try:
temp_task_no = f"TMP-{len(notice_items) + 1}"
saved_path = save_task_notice_upload(temp_task_no, filename, raw)
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
except Exception as exc:
warnings = [f"notice_extract_failed:{exc}"]
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
warnings.append(f"notice_text_truncated:{limit}")
notice_items.append(
{
"source_type": source_type,
"source_file_name": filename,
"source_file_type": str(getattr(upload, "mimetype", "") or "").strip() or None,
"raw_text": text,
"warnings": warnings,
}
)
payload = {
"user_id": user.id,
"conversation_id": conversation_id or None,
"file_count": len(notice_items),
"notice_items": notice_items,
}
return jsonify(shipping_tools.create_batch_tasks(payload))
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>", methods=["GET"])
def workspace_shipping_batch_detail(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
focus_task = get_focus_task_for_batch(batch_no, user.id)
return jsonify(
{
**serialize_batch_summary(batch),
"tasks": list_tasks_for_batch(batch_no, user.id),
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
}
)
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/tasks", methods=["GET"])
def workspace_shipping_batch_tasks(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
return jsonify(list_tasks_for_batch(batch_no, user.id))
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["GET"])
def workspace_shipping_batch_focus_task(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
focus_task = get_focus_task_for_batch(batch_no, user.id)
if not focus_task:
return jsonify({"error": "Focus task not found"}), 404
return jsonify(serialize_task_summary(focus_task))
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["POST"])
def workspace_switch_shipping_batch_focus_task(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
data = request.get_json(silent=True) or {}
task_no = str(data.get("task_no") or data.get("target_task_no") or "").strip()
if not task_no:
return jsonify({"error": "task_no is required"}), 400
task = get_task_for_user(task_no, user.id)
if not task or task.batch_id != batch.id:
return jsonify({"error": "Task not found in batch"}), 404
batch.current_focus_task_no = task.task_no
db.session.commit()
return jsonify(
{
"batch": serialize_batch_summary(batch),
"focus_task": serialize_task_summary(task),
}
)
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
def workspace_create_shipping_task():
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
user, err = _require_user()
if err:
return err
@@ -58,6 +222,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():
"""接收单个发货通知附件,建单后抽取文本并立即触发解析。"""
user, err = _require_user()
if err:
return err
@@ -123,6 +288,7 @@ def workspace_create_shipping_task_from_notice():
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>", methods=["GET"])
def workspace_shipping_task_detail(task_no: str):
"""返回指定任务的详情快照。"""
user, err = _require_user()
if err:
return err
@@ -134,6 +300,7 @@ def workspace_shipping_task_detail(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/chat-actions", methods=["GET"])
def workspace_shipping_task_chat_actions(task_no: str):
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
user, err = _require_user()
if err:
return err
@@ -145,7 +312,7 @@ def workspace_shipping_task_chat_actions(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/upload-inventory", methods=["POST"])
def workspace_upload_shipping_inventory(task_no: str):
"""Hxops chat UI: upload inventory Excel with user auth (not Tool Key)."""
"""用户态上传库存 Excel,并在服务端完成解析。"""
user, err = _require_user()
if err:
return err
@@ -161,6 +328,7 @@ def workspace_upload_shipping_inventory(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/apply-inventory-mapping", methods=["POST"])
def workspace_apply_inventory_mapping(task_no: str):
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
user, err = _require_user()
if err:
return err
@@ -183,7 +351,7 @@ def workspace_apply_inventory_mapping(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/submit-decision", methods=["POST"])
def workspace_submit_shipping_decision(task_no: str):
"""Hxops chat UI: submit shipping decision with user auth (bypass Dify tool routing)."""
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
user, err = _require_user()
if err:
return err
@@ -205,9 +373,110 @@ def workspace_submit_shipping_decision(task_no: str):
return jsonify(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-fields", methods=["POST"])
def workspace_update_shipping_notice_fields(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
data = request.get_json(silent=True) or {}
fields = data.get("fields")
if not isinstance(fields, dict) or not fields:
return jsonify({"error": "fields is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "fields": fields}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.update_notice_fields(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-line", methods=["POST"])
def workspace_update_shipping_notice_line(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
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get("line_index"))
except (TypeError, ValueError):
return jsonify({"error": "line_index is required"}), 400
patch = data.get("patch")
if not isinstance(patch, dict) or not patch:
return jsonify({"error": "patch is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "line_index": line_index, "patch": patch}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.update_notice_line(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/add-notice-line", methods=["POST"])
def workspace_add_shipping_notice_line(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
data = request.get_json(silent=True) or {}
line = data.get("line")
if not isinstance(line, dict) or not line:
return jsonify({"error": "line is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "line": line}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.add_notice_line(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/remove-notice-line", methods=["POST"])
def workspace_remove_shipping_notice_line(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
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get("line_index"))
except (TypeError, ValueError):
return jsonify({"error": "line_index is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "line_index": line_index}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.remove_notice_line(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/auto-progress", methods=["POST"])
def workspace_auto_progress_shipping_task(task_no: str):
"""Hxops chat fallback: same as Dify auto_progress tool."""
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
user, err = _require_user()
if err:
return err
@@ -234,6 +503,7 @@ def workspace_auto_progress_shipping_task(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
def workspace_match_shipping_inventory(task_no: str):
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
user, err = _require_user()
if err:
return err
@@ -272,7 +542,7 @@ def workspace_match_shipping_inventory(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
def workspace_mark_manual_uploaded(task_no: str):
"""Hxops chat: mark freight manual upload complete (no ref no required)."""
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
user, err = _require_user()
if err:
return err
@@ -289,6 +559,7 @@ def workspace_mark_manual_uploaded(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
def workspace_generate_shipping_excel(task_no: str):
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
user, err = _require_user()
if err:
return err
@@ -310,18 +581,20 @@ def workspace_generate_shipping_excel(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel。"""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task or not task.export_file_path:
return jsonify({"error": "export file not found"}), 404
path = Path(task.export_file_path)
if not path.is_file():
return jsonify({"error": "export file missing on disk"}), 404
err_msg = task_export_error_message(task)
if err_msg:
return jsonify({"error": err_msg}), 404
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(
path,
as_attachment=True,
download_name=task.export_file_name or path.name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
download_name=download_name,
mimetype=EXPORT_MIME_TYPE,
)