refactor(会话管理): 移除对话详情冗余接口,优化前端滚动事件处理

This commit is contained in:
zstar 2025-05-17 12:15:00 +08:00
parent ef7a48ace8
commit f910ec0bb7
3 changed files with 36 additions and 105 deletions

View File

@ -44,20 +44,3 @@ def get_messages(conversation_id):
except Exception as e:
# 错误处理
return jsonify({"code": 500, "message": f"获取消息列表失败: {str(e)}"}), 500
@conversation_bp.route("/<conversation_id>", methods=["GET"])
def get_conversation(conversation_id):
"""获取特定对话的详细信息"""
try:
# 调用服务函数获取对话详情
conversation = get_conversation_detail(conversation_id)
if not conversation:
return jsonify({"code": 404, "message": "对话不存在"}), 404
# 返回符合前端期望格式的数据
return jsonify({"code": 0, "data": conversation, "message": "获取对话详情成功"})
except Exception as e:
# 错误处理
return jsonify({"code": 500, "message": f"获取对话详情失败: {str(e)}"}), 500

View File

@ -23,8 +23,6 @@ def get_conversations_by_user_id(user_id, page=1, size=20, sort_by="update_time"
# 直接使用user_id作为tenant_id
tenant_id = user_id
print(f"查询用户ID: {user_id}, 租户ID: {tenant_id}")
# 查询总记录数
count_sql = """
SELECT COUNT(*) as total
@ -34,7 +32,7 @@ def get_conversations_by_user_id(user_id, page=1, size=20, sort_by="update_time"
cursor.execute(count_sql, (tenant_id,))
total = cursor.fetchone()["total"]
print(f"查询到总记录数: {total}")
# print(f"查询到总记录数: {total}")
# 计算分页偏移量
offset = (page - 1) * size
@ -59,8 +57,8 @@ def get_conversations_by_user_id(user_id, page=1, size=20, sort_by="update_time"
LIMIT %s OFFSET %s
"""
print(f"执行查询: {query}")
print(f"参数: tenant_id={tenant_id}, size={size}, offset={offset}")
# print(f"执行查询: {query}")
# print(f"参数: tenant_id={tenant_id}, size={size}, offset={offset}")
cursor.execute(query, (tenant_id, size, offset))
results = cursor.fetchall()
@ -200,68 +198,3 @@ def get_messages_by_conversation_id(conversation_id, page=1, size=30):
traceback.print_exc()
return None, 0
def get_conversation_detail(conversation_id):
"""
获取特定对话的详细信息
参数:
conversation_id (str): 对话ID
返回:
dict: 对话详情
"""
try:
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor(dictionary=True)
# 查询对话信息
query = """
SELECT c.*, d.name as dialog_name, d.icon as dialog_icon
FROM conversation c
LEFT JOIN dialog d ON c.dialog_id = d.id
WHERE c.id = %s
"""
cursor.execute(query, (conversation_id,))
result = cursor.fetchone()
if not result:
print(f"未找到对话ID: {conversation_id}")
return None
# 格式化对话详情
conversation = {
"id": result["id"],
"name": result.get("name", ""),
"dialogId": result.get("dialog_id", ""),
"dialogName": result.get("dialog_name", ""),
"dialogIcon": result.get("dialog_icon", ""),
"createTime": result["create_date"].strftime("%Y-%m-%d %H:%M:%S") if result.get("create_date") else "",
"updateTime": result["update_date"].strftime("%Y-%m-%d %H:%M:%S") if result.get("update_date") else "",
"messages": result.get("message", []),
}
# 打印调试信息
print(f"获取到对话详情: ID={conversation_id}")
print(f"消息数量: {len(conversation['messages']) if conversation['messages'] else 0}")
# 关闭连接
cursor.close()
conn.close()
return conversation
except mysql.connector.Error as err:
print(f"数据库错误: {err}")
# 更详细的错误日志
import traceback
traceback.print_exc()
return None
except Exception as e:
print(f"未知错误: {e}")
import traceback
traceback.print_exc()
return None

View File

@ -1,11 +1,8 @@
<script lang="ts" setup>
import type { CreateOrUpdateTableRequestData, TableData } from "@@/apis/tables/type"
import type { FormInstance, FormRules } from "element-plus"
import { createTableDataApi, deleteTableDataApi, getTableDataApi, resetPasswordApi, updateTableDataApi } from "@@/apis/tables"
import { usePagination } from "@@/composables/usePagination"
import { ChatDotRound, CirclePlus, Delete, Edit, Key, Refresh, RefreshRight, Search, User } from "@element-plus/icons-vue"
import type { TableData } from "@@/apis/tables/type"
import { getTableDataApi } from "@@/apis/tables"
import { ChatDotRound, User } from "@element-plus/icons-vue"
import axios from "axios"
import { cloneDeep } from "lodash-es"
defineOptions({
//
@ -79,10 +76,16 @@ function loadMoreUsers() {
/**
* 监听用户列表滚动事件
* @param event 滚动事件
* @param event DOM滚动事件对象
*/
function handleUserListScroll(event) {
const { scrollTop, scrollHeight, clientHeight } = event.target
function handleUserListScroll(event: Event) {
// event.target HTMLElement
const target = event.target as HTMLElement
if (!target) return
//
const { scrollTop, scrollHeight, clientHeight } = target
// 100px
if (scrollHeight - scrollTop - clientHeight < 100 && userHasMore.value && !userLoading.value) {
loadMoreUsers()
@ -203,10 +206,16 @@ function loadMoreConversations() {
/**
* 监听对话列表滚动事件
* @param event 滚动事件
* @param event DOM滚动事件对象
*/
function handleConversationListScroll(event) {
const { scrollTop, scrollHeight, clientHeight } = event.target
function handleConversationListScroll(event: Event) {
// event.target HTMLElement
const target = event.target as HTMLElement
if (!target) return
//
const { scrollTop, scrollHeight, clientHeight } = target
// 100px
if (scrollHeight - scrollTop - clientHeight < 100 && conversationHasMore.value && !conversationLoading.value) {
loadMoreConversations()
@ -247,7 +256,7 @@ function getMessagesByConversationId(conversationId: string, isLoadMore = false)
const parsedMessages = JSON.parse(conversation.messages)
//
processedMessages = parsedMessages.map((msg, index) => {
processedMessages = parsedMessages.map((msg: { id: any, role: any, content: any, created_at: number }, index: any) => {
return {
id: msg.id || `msg-${index}`,
conversation_id: conversationId,
@ -268,7 +277,7 @@ function getMessagesByConversationId(conversationId: string, isLoadMore = false)
if (isLoadMore) {
//
const existingIds = new Set(messageList.value.map(msg => msg.id))
const uniqueNewMessages = processedMessages.filter(msg => !existingIds.has(msg.id))
const uniqueNewMessages = processedMessages.filter((msg: { id: number }) => !existingIds.has(msg.id))
//
messageList.value = [...messageList.value, ...uniqueNewMessages]
@ -307,7 +316,7 @@ function getMessagesByConversationId(conversationId: string, isLoadMore = false)
* @param content 消息内容
* @returns 处理后的HTML内容
*/
function renderMessageContent(content) {
function renderMessageContent(content: string) {
if (!content) return ""
// Markdown
@ -331,10 +340,16 @@ function loadMoreMessages() {
/**
* 监听消息列表滚动事件
* @param event 滚动事件
* @param event DOM滚动事件对象
*/
function handleMessageListScroll(event) {
const { scrollTop, scrollHeight, clientHeight } = event.target
function handleMessageListScroll(event: Event) {
// event.target HTMLElement
const target = event.target as HTMLElement
if (!target) return
//
const { scrollTop, scrollHeight, clientHeight } = target
// 100px
if (scrollHeight - scrollTop - clientHeight < 100 && messageHasMore.value && !messageLoading.value) {
loadMoreMessages()