feat(shipping-notice): 完成货代发货通知全流程开发与代码重构
- 新增PO号提取、预约ID解析(支持`PR@xxx`格式)工具,完善库存匹配逻辑 - 新增库存映射缓存、匹配/解析结果格式化摘要,优化用户提示 - 修复数据库迁移脚本未检查表存在的问题,避免全新部署失败 - 新增路径工具类统一管理相对路径,优化配置文件处理逻辑 - 归档旧文档,将部署、Dify配置合并到`shipping_notice.md` - 新增完整单元测试与集成测试覆盖核心流程 - 更新前端国际化与会话管理逻辑,优化界面交互
This commit is contained in:
1 parent
b62082758b
commit
8deae3146b
65 files changed
+6477
-1937
No files matched your search
+16
-16
@@ -344,21 +344,21 @@ def test_agent(id):
|
||||
if agent.type == 'iframe':
|
||||
iframe_url = (agent.extra_config or {}).get('iframe_url')
|
||||
if not iframe_url:
|
||||
return (jsonify({'success': False, 'request_url': '', 'output_info': 'Missing iframe_url in extra_config.', 'analysis': '测试失败:未配置 iframe URL。', 'http_status': 0, 'tested_at': tested_at}), 400)
|
||||
return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing iframe_url in extra_config.', 'analysis': '测试失败:未配置 iframe URL。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||||
try:
|
||||
resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True)
|
||||
success = 200 <= resp.status_code < 400
|
||||
if success and (not agent.is_active):
|
||||
passed = 200 <= resp.status_code < 400
|
||||
if passed and (not agent.is_active):
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return (jsonify({'success': success, 'request_url': iframe_url, 'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}', 'analysis': '测试通过:iframe 地址可访问。' if success else '测试失败:iframe 地址不可访问或返回异常状态。', 'http_status': resp.status_code, 'tested_at': tested_at}), 200)
|
||||
return (jsonify({'passed': passed, 'request_url': iframe_url, 'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}', 'analysis': '测试通过:iframe 地址可访问。' if passed else '测试失败:iframe 地址不可访问或返回异常状态。', 'http_status': resp.status_code, 'tested_at': tested_at}), 200)
|
||||
except requests.RequestException as e:
|
||||
return (jsonify({'success': False, 'request_url': iframe_url, 'output_info': str(e), 'analysis': '测试失败:请求 iframe 地址异常。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||||
return (jsonify({'passed': False, 'request_url': iframe_url, 'output_info': str(e), 'analysis': '测试失败:请求 iframe 地址异常。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||||
if not agent.dify_api_key:
|
||||
return (jsonify({'success': False, 'request_url': '', 'output_info': 'Missing dify_api_key.', 'analysis': '测试失败:未配置 API Key。', 'http_status': 0, 'tested_at': tested_at}), 400)
|
||||
return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing dify_api_key.', 'analysis': '测试失败:未配置 API Key。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||||
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
|
||||
if not base_url:
|
||||
return (jsonify({'success': False, 'request_url': '', 'output_info': 'Missing api_base_url.', 'analysis': '测试失败:未配置 API Base URL。', 'http_status': 0, 'tested_at': tested_at}), 400)
|
||||
return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing api_base_url.', 'analysis': '测试失败:未配置 API Base URL。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||||
extra_config = agent.extra_config or {}
|
||||
dify_app_type = str(extra_config.get('dify_app_type') or 'chatflow').strip().lower()
|
||||
if dify_app_type not in ('chatflow', 'workflow'):
|
||||
@@ -374,10 +374,10 @@ def test_agent(id):
|
||||
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
|
||||
raw_text = (resp.text or '')[:4000]
|
||||
output_info = raw_text
|
||||
success = False
|
||||
passed = False
|
||||
analysis = f'测试失败:HTTP {resp.status_code}。'
|
||||
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
|
||||
success = True
|
||||
passed = True
|
||||
analysis = '测试通过:Workflow 接口可访问且认证通过。'
|
||||
try:
|
||||
data = resp.json()
|
||||
@@ -401,7 +401,7 @@ def test_agent(id):
|
||||
if answer:
|
||||
output_info = str(answer)[:4000]
|
||||
if resp.ok and isinstance(answer, str) and answer.strip():
|
||||
success = True
|
||||
passed = True
|
||||
analysis = '测试通过:Chatflow 接口可访问且已返回回答。'
|
||||
elif resp.ok:
|
||||
analysis = '测试未通过:Chatflow 接口可访问,但未返回有效回答。'
|
||||
@@ -412,17 +412,17 @@ def test_agent(id):
|
||||
except ValueError:
|
||||
if resp.ok and raw_text.strip():
|
||||
if dify_app_type == 'workflow':
|
||||
success = True
|
||||
passed = True
|
||||
analysis = '测试通过:Workflow 接口可访问并返回了文本内容。'
|
||||
else:
|
||||
success = True
|
||||
passed = True
|
||||
analysis = '测试通过:Chatflow 接口可访问并返回了文本内容。'
|
||||
if success and (not agent.is_active):
|
||||
if passed and (not agent.is_active):
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return (jsonify({'success': success, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': output_info, 'analysis': analysis, 'http_status': resp.status_code, 'tested_at': tested_at}), 200)
|
||||
return (jsonify({'passed': passed, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': output_info, 'analysis': analysis, 'http_status': resp.status_code, 'tested_at': tested_at}), 200)
|
||||
except requests.RequestException as e:
|
||||
return (jsonify({'success': False, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': str(e), 'analysis': '测试失败:请求异常(网络、超时或认证问题)。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||||
return (jsonify({'passed': False, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': str(e), 'analysis': '测试失败:请求异常(网络、超时或认证问题)。', 'http_status': 0, 'tested_at': tested_at}), 200)
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
@@ -1076,4 +1076,4 @@ def wecom_notify_metrics():
|
||||
if event_type not in by_event:
|
||||
by_event[event_type] = {'sent': 0, 'failed': 0}
|
||||
by_event[event_type][status] = int(cnt)
|
||||
return jsonify({'window_days': 30, 'total': int(total), 'sent': int(sent), 'failed': int(total - sent), 'send_success_rate': round(sent / total * 100, 2) if total else 0, 'opened_24h': int(opened_24h), 'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0, 'by_event': by_event})
|
||||
return jsonify({'window_days': 30, 'total': int(total), 'sent': int(sent), 'failed': int(total - sent), 'send_success_rate': round(sent / total * 100, 2) if total else 0, 'opened_24h': int(opened_24h), 'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0, 'by_event': by_event})
|
||||
+33
-10
@@ -16,7 +16,7 @@ from datetime import datetime
|
||||
from urllib.parse import urlparse
|
||||
import requests
|
||||
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
|
||||
from sqlalchemy import func, desc, or_
|
||||
from sqlalchemy import func, desc, or_, exists, and_
|
||||
from openpyxl import load_workbook
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
@@ -56,6 +56,21 @@ def _get_chat_session(user_id: int, agent_id: int, session_id: str | None):
|
||||
).first()
|
||||
|
||||
|
||||
def _chat_logs_for_session(user_id: int, agent_id: int, session: ChatSession):
|
||||
match_ids = {session.session_id}
|
||||
external_id = str(session.external_conversation_id or '').strip()
|
||||
if external_id:
|
||||
match_ids.add(external_id)
|
||||
return db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == user_id,
|
||||
ChatLog.agent_id == agent_id,
|
||||
or_(
|
||||
ChatLog.session_id.in_(match_ids),
|
||||
ChatLog.conversation_id.in_(match_ids),
|
||||
),
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
|
||||
def _ensure_chat_session(
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
@@ -742,9 +757,19 @@ def get_chat_sessions():
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
|
||||
session_rows = db.session.query(ChatSession).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
session_rows = db.session.query(ChatSession).filter(
|
||||
ChatSession.user_id == user.id,
|
||||
ChatSession.agent_id == agent.id,
|
||||
or_(
|
||||
ChatSession.status == 'running',
|
||||
exists().where(
|
||||
and_(
|
||||
ChatLog.session_id == ChatSession.session_id,
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
)
|
||||
),
|
||||
),
|
||||
).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all()
|
||||
|
||||
sessions = [_serialize_session(item) for item in session_rows]
|
||||
@@ -857,14 +882,12 @@ def get_chat_messages():
|
||||
|
||||
session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id)
|
||||
if session:
|
||||
logs = _chat_logs_for_session(g.current_user.id, g.current_agent.id, session)
|
||||
else:
|
||||
logs = db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == g.current_user.id,
|
||||
ChatLog.agent_id == g.current_agent.id,
|
||||
ChatLog.session_id == session.session_id,
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
else:
|
||||
logs = db.session.query(ChatLog).filter_by(
|
||||
conversation_id=conversation_id
|
||||
ChatLog.conversation_id == conversation_id,
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
@@ -1325,7 +1348,7 @@ def upload_chat_file():
|
||||
headers=headers,
|
||||
files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')},
|
||||
data={'user': str(getattr(user, 'id', 'system'))},
|
||||
timeout=(5, 60),
|
||||
timeout=(5, 300),
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise ServiceUnavailableError(f'Upload failed: {exc}')
|
||||
|
||||
@@ -45,9 +45,9 @@ def openapi_dify_yaml():
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_case", methods=["POST"])
|
||||
def tool_create_case():
|
||||
return jsonify(shipping_tools.create_case(_payload()))
|
||||
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
|
||||
def tool_create_task():
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
|
||||
@@ -63,9 +63,9 @@ def tool_parse_inventory():
|
||||
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
|
||||
def tool_upload_inventory_file():
|
||||
"""Multipart upload — parse server-side without sending Excel through LLM."""
|
||||
case_id = str(request.form.get("case_id") or request.args.get("case_id") or "").strip()
|
||||
task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip()
|
||||
upload = request.files.get("file")
|
||||
return jsonify(shipping_tools.upload_inventory_file(case_id, upload))
|
||||
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
|
||||
@@ -103,9 +103,9 @@ def tool_upload_to_freight():
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_case_status", methods=["POST"])
|
||||
def tool_get_case_status():
|
||||
return jsonify(shipping_tools.get_case_status(_payload()))
|
||||
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
|
||||
def tool_get_task_status():
|
||||
return jsonify(shipping_tools.get_task_status(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
|
||||
@@ -118,19 +118,19 @@ def rpa_upload_complete():
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/cases/<case_no>/export", methods=["GET"])
|
||||
def download_case_export(case_no: str):
|
||||
from app.services.shipping_notice.tools import _get_case
|
||||
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
|
||||
def download_task_export(task_no: str):
|
||||
from app.services.shipping_notice.tools import _get_task
|
||||
|
||||
case = _get_case(case_no)
|
||||
if not case or not case.export_file_path:
|
||||
task = _get_task(task_no)
|
||||
if not task or not task.export_file_path:
|
||||
return jsonify({"error": "export file not found"}), 404
|
||||
path = Path(case.export_file_path)
|
||||
path = Path(task.export_file_path)
|
||||
if not path.is_file():
|
||||
return jsonify({"error": "export file missing on disk"}), 404
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=case.export_file_name or path.name,
|
||||
download_name=task.export_file_name or path.name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -3,12 +3,14 @@ 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.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_case_for_user,
|
||||
list_cases_for_user,
|
||||
serialize_case_detail,
|
||||
get_task_for_user,
|
||||
list_tasks_for_user,
|
||||
serialize_task_detail,
|
||||
)
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
@@ -21,62 +23,200 @@ def _require_user():
|
||||
return user, None
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-cases", methods=["GET"])
|
||||
def workspace_shipping_cases():
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
|
||||
def workspace_shipping_tasks():
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
process_status = str(request.args.get("process_status") or "").strip() or None
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(list_cases_for_user(user.id, process_status=process_status, limit=limit))
|
||||
return jsonify(list_tasks_for_user(user.id, process_status=process_status, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>", methods=["GET"])
|
||||
def workspace_shipping_case_detail(case_no: str):
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
|
||||
def workspace_create_shipping_task():
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
case = get_case_for_user(case_no, user.id)
|
||||
if not case:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(serialize_case_detail(case))
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {"user_id": user.id}
|
||||
source_type = str(data.get("source_type") or "").strip()
|
||||
if source_type:
|
||||
payload["source_type"] = source_type
|
||||
conversation_id = str(data.get("conversation_id") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
raw_content = str(data.get("raw_content") or "").strip()
|
||||
if raw_content:
|
||||
payload["raw_content"] = raw_content
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.create_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/chat-actions", methods=["GET"])
|
||||
def workspace_shipping_case_chat_actions(case_no: str):
|
||||
@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
|
||||
case = get_case_for_user(case_no, user.id)
|
||||
if not case:
|
||||
|
||||
upload = request.files.get("file")
|
||||
if not upload:
|
||||
return jsonify({"error": "file 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,
|
||||
)
|
||||
|
||||
source_type = guess_source_type(upload.filename or "")
|
||||
created = shipping_tools.create_task({"user_id": user.id, "source_type": source_type})
|
||||
task_id = str(created.get("task_id") or "").strip()
|
||||
if not task_id:
|
||||
return jsonify({"error": "failed to create task"}), 500
|
||||
|
||||
raw = upload.read() or b""
|
||||
saved_path = save_task_notice_upload(task_id, upload.filename or "notice", raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
dify_file_id = ""
|
||||
notice_files = None
|
||||
try:
|
||||
from app.config import Config
|
||||
from app.services.dify import DifyService
|
||||
from app.services.shipping_notice.agent_resolver import resolve_extract_agent
|
||||
import requests
|
||||
|
||||
agent = resolve_extract_agent()
|
||||
api_key = str(getattr(agent, "dify_api_key", "") or "").strip() if agent else ""
|
||||
if api_key:
|
||||
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
|
||||
dify_url = DifyService._build_files_upload_url(base_url)
|
||||
resp = requests.post(
|
||||
dify_url,
|
||||
headers={"Authorization": f"Bearer {api_key}"},
|
||||
files={"file": (upload.filename or "notice", raw, upload.mimetype or "application/octet-stream")},
|
||||
data={"user": str(user.id)},
|
||||
timeout=(5, 300),
|
||||
)
|
||||
if resp.ok:
|
||||
data = resp.json() if resp.content else {}
|
||||
dify_file_id = str(data.get("id") or "").strip()
|
||||
if dify_file_id:
|
||||
notice_files = [
|
||||
{
|
||||
"type": "document",
|
||||
"transfer_method": "local_file",
|
||||
"upload_file_id": dify_file_id,
|
||||
}
|
||||
]
|
||||
else:
|
||||
meta.setdefault("warnings", []).append(f"dify_upload_failed:{resp.status_code}")
|
||||
except Exception as exc:
|
||||
meta.setdefault("warnings", []).append(f"dify_upload_error:{exc}")
|
||||
|
||||
if (not text) and (not notice_files):
|
||||
return jsonify(
|
||||
{
|
||||
"status": "needs_human",
|
||||
"task_id": task_id,
|
||||
"message": "未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。",
|
||||
"data": {"notice_upload": {"filename": upload.filename or "", "dify_file_id": dify_file_id, **meta}},
|
||||
"human_options": ["reparse", "reject"],
|
||||
"checkpoint": "notice_text_extraction_failed",
|
||||
}
|
||||
)
|
||||
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
meta.setdefault("warnings", []).append(f"notice_text_truncated:{limit}")
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = text
|
||||
db.session.commit()
|
||||
|
||||
payload = {"task_id": task_id}
|
||||
if notice_files:
|
||||
payload["notice_files"] = notice_files
|
||||
parsed = shipping_tools.parse_notice(payload)
|
||||
data = parsed.get("data") if isinstance(parsed, dict) else None
|
||||
if isinstance(data, dict):
|
||||
data["notice_upload"] = {"filename": upload.filename or "", "dify_file_id": dify_file_id, **meta}
|
||||
parsed["message"] = f"已上传发货通知文件并创建任务 {task_id}。{parsed.get('message') or ''}".strip()
|
||||
return jsonify(parsed)
|
||||
|
||||
|
||||
@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
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(build_chat_actions_payload(case))
|
||||
return jsonify(serialize_task_detail(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/upload-inventory", methods=["POST"])
|
||||
def workspace_upload_shipping_inventory(case_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
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
|
||||
@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)."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
case = get_case_for_user(case_no, user.id)
|
||||
if not case:
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
upload = request.files.get("file")
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.upload_inventory_file(case.case_no, upload))
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/submit-decision", methods=["POST"])
|
||||
def workspace_submit_shipping_decision(case_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
|
||||
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 {}
|
||||
column_mapping_json = data.get("column_mapping_json")
|
||||
if not isinstance(column_mapping_json, dict) or not column_mapping_json:
|
||||
return jsonify({"error": "column_mapping_json is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "column_mapping_json": column_mapping_json}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
|
||||
@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)."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
case = get_case_for_user(case_no, user.id)
|
||||
if not case:
|
||||
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 {}
|
||||
@@ -86,27 +226,80 @@ def workspace_submit_shipping_decision(case_no: str):
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"case_id": case.case_no, "decision": decision}
|
||||
payload = {"task_id": task.task_no, "decision": decision}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.submit_decision(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/export", methods=["GET"])
|
||||
def workspace_shipping_case_export(case_no: str):
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
case = get_case_for_user(case_no, user.id)
|
||||
if not case or not case.export_file_path:
|
||||
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
|
||||
|
||||
matched = shipping_tools.match_inventory({"task_id": task.task_no})
|
||||
if isinstance(matched, dict) and matched.get("status") == "ok":
|
||||
generated = shipping_tools.generate_excel({"task_id": task.task_no})
|
||||
if isinstance(generated, dict) and generated.get("status") == "ok":
|
||||
msg = "\n".join(
|
||||
[
|
||||
str(matched.get("message") or "").strip(),
|
||||
str(generated.get("message") or "").strip(),
|
||||
]
|
||||
).strip()
|
||||
generated["message"] = msg
|
||||
data = generated.get("data")
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
generated["data"] = data
|
||||
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
|
||||
generated["checkpoint"] = generated.get("checkpoint") or "export_generated"
|
||||
return jsonify(generated)
|
||||
return jsonify(matched)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
|
||||
def workspace_generate_shipping_excel(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
|
||||
|
||||
result = shipping_tools.generate_excel({"task_id": task.task_no})
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
data = result.get("data")
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result["data"] = data
|
||||
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
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(case.export_file_path)
|
||||
path = Path(task.export_file_path)
|
||||
if not path.is_file():
|
||||
return jsonify({"error": "export file missing on disk"}), 404
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=case.export_file_name or path.name,
|
||||
download_name=task.export_file_name or path.name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
Reference in new issue
Block a user