Browse Source

fix:新增会话列表公共字段

master
qiutianhong 7 months ago
parent
commit
ccf667c4e6
  1. 3
      frontend/auto-imports.d.ts
  2. 14
      frontend/src/components/chat/ChatBox.vue
  3. 2
      frontend/src/components/chat/ChatMessage.vue
  4. 4
      frontend/src/components/chat/ChatMsgList.vue
  5. 5
      frontend/src/components/chat/ChatUserList.vue
  6. 4
      frontend/src/components/chat/chatUserInfo.vue
  7. 127
      frontend/src/stores/chat.ts
  8. 6
      frontend/src/stores/db.ts

3
frontend/auto-imports.d.ts

@ -3,6 +3,7 @@
// @ts-nocheck // @ts-nocheck
// noinspection JSUnusedGlobalSymbols // noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import // Generated by unplugin-auto-import
// biome-ignore lint: disable
export {} export {}
declare global { declare global {
const EffectScope: typeof import('vue')['EffectScope'] const EffectScope: typeof import('vue')['EffectScope']
@ -70,6 +71,6 @@ declare global {
// for type re-export // for type re-export
declare global { declare global {
// @ts-ignore // @ts-ignore
export type { Component, ComponentPublicInstance, ComputedRef, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, VNode, WritableComputedRef } from 'vue' export type { Component, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue'
import('vue') import('vue')
} }

14
frontend/src/components/chat/ChatBox.vue

@ -6,14 +6,18 @@
<template> <template>
<div <div
class="chatbox-main" class="chatbox-main"
v-if="store.targetUserId > 0" v-if="store.targetChatId"
> >
<!--聊天顶部区--> <!--聊天顶部区-->
<el-header class="chat-header"> <el-header class="chat-header">
<div class="header-title"> <div class="header-title">
{{ store.targetUserInfo.nickname }} <span v-if="store.targetUserInfo.nickname">{{
store.targetUserInfo.nickname
}}</span>
<span v-else-if="store.targetGroupInfo.name">{{
store.targetGroupInfo.name
}}</span>
</div> </div>
</el-header> </el-header>
<!--聊天主体区--> <!--聊天主体区-->
@ -75,12 +79,12 @@
</el-footer> </el-footer>
</div> </div>
<div class="no-message-container" v-else> <!-- <div class="no-message-container" v-else>
<el-icon :size="180" color="#0078d7"> <el-icon :size="180" color="#0078d7">
<ChatDotSquare /> <ChatDotSquare />
</el-icon> </el-icon>
<p>欢迎使用GodoOS</p> <p>欢迎使用GodoOS</p>
</div> </div> -->
</template> </template>
<style scoped> <style scoped>

2
frontend/src/components/chat/ChatMessage.vue

@ -1,6 +1,6 @@
<template> <template>
<div <div
v-if="store.chatHistory.length > 0" v-if="store.chatHistory && store.chatHistory.length > 0"
v-for="item in store.chatHistory" v-for="item in store.chatHistory"
:key="item.time" :key="item.time"
> >

4
frontend/src/components/chat/ChatMsgList.vue

@ -2,9 +2,9 @@
<div v-if="store.chatList.length > 0" v-for="item in store.chatList" :key="item.id"> <div v-if="store.chatList.length > 0" v-for="item in store.chatList" :key="item.id">
<div <div
class="list-item" class="list-item"
@click="store.changeChatList(item.userId)" @click="store.changeChatList(item.chatId,item.type)"
:style="{ :style="{
backgroundColor: item.userId == store.targetUserId ? '#bae7ff' : '', backgroundColor: item.userId == store.targetChatId ? '#bae7ff' : '',
}" }"
> >
<el-row> <el-row>

5
frontend/src/components/chat/ChatUserList.vue

@ -64,12 +64,13 @@
v-for="item in store.userList" v-for="item in store.userList"
:key="item.id" :key="item.id"
> >
<div <div
class="list-item" class="list-item"
@click="store.changeChatList(item.id)" @click="store.changeChatList(item.id,'user')"
:style="{ :style="{
backgroundColor: backgroundColor:
item.id === store.targetUserId ? '#bae7ff' : '', item.id === store.targetChatId ? '#bae7ff' : '',
}" }"
> >
<el-row> <el-row>

4
frontend/src/components/chat/chatUserInfo.vue

@ -1,6 +1,6 @@
<template> <template>
<div <div
v-if="store.targetUserId == null" v-if="store.targetChatId == null"
class="no-message-container" class="no-message-container"
> >
<el-icon <el-icon
@ -26,7 +26,7 @@
</div> </div>
<el-button <el-button
type="primary" type="primary"
@click="sendMessage(store.targetUserId)" @click="sendMessage(store.targetChatId)"
>发送消息</el-button >发送消息</el-button
> >
</div> </div>

127
frontend/src/stores/chat.ts

@ -59,14 +59,11 @@ export const useChatStore = defineStore('chatStore', () => {
// 聊天消息记录列表 // 聊天消息记录列表
const chatHistory: any = ref([]); const chatHistory: any = ref([]);
const targetNickname: any = ref('');
// 群组数据 // 群组数据
const groupList: any = ref([ const groupList: any = ref([
]); ]);
const targetGroupInfo = ref({})
const activeNames = ref([]); const activeNames = ref([]);
const userInfo: any = ref({}); const userInfo: any = ref({});
const showChooseFile = ref(false); const showChooseFile = ref(false);
@ -78,12 +75,9 @@ export const useChatStore = defineStore('chatStore', () => {
const currentNavId = ref(0); const currentNavId = ref(0);
const message: any = ref(''); const message: any = ref('');
const targetUserInfo: any = ref({}); const targetUserInfo: any = ref({});
const targetUserId = ref(); const targetChatId = ref();
const search = ref(''); const search = ref('');
// 目标群组id
const targetGroupId = ref(0);
// 所有用户列表 // 所有用户列表
const allUserList = ref([]) const allUserList = ref([])
@ -152,7 +146,7 @@ export const useChatStore = defineStore('chatStore', () => {
time: null, time: null,
message: message.value, message: message.value,
userId: userInfo.value.id, userId: userInfo.value.id,
toUserId: targetUserId.value, toUserId: targetChatId.value,
userInfo: { userInfo: {
}, },
}; };
@ -234,43 +228,40 @@ export const useChatStore = defineStore('chatStore', () => {
} }
}; };
const changeChatListAndGetChatHistory = async (userId: number) => { const changeChatListAndGetChatHistory = async (chatId: number) => {
const chatIdSet = new Set(chatList.value.map((chat: { chatId: any }) => chat.chatId));
// todo 优化,需要加唯一标识 // 如果会话存在于 chatList,则获取聊天记录并更新 chatHistory
console.log(chatList.value); if (chatIdSet.has(chatId)) {
let userExists = false;
// 检查 chatList 中是否存在 userId
for (let i = 0; i < chatList.value.length; i++) {
console.log(chatList);
if (chatList.value[i].id === userId) {
userExists = true;
break;
}
}
// 检查 userId 是否已经存
if (userExists) {
// 如果存在,获取聊天记录添加到 historyList
console.log("存在"); console.log("存在");
chatHistory.value = await getHistory(userId, userInfo.value.id); chatHistory.value = await getHistory(chatId, userInfo.value.id);
return; return;
} else { }
// 如果不存在,则从用户表中获取该用户的基本信息
const user = await db.getOne("workbenchusers", userId); // 如果会话不存在,则从用户表中获取该用户的基本信息
if (user) { const user = await db.getOne("workbenchusers", chatId);
if (!user) {
console.warn("User not found in workbenchusers with userId:", chatId);
return;
}
// 将新用户信息添加到 chatList // 将新用户信息添加到 chatList
chatList.value.push({ const newChat = {
id: user.id, userId: user.id,
type: "user", type: "user",
chatId: user.id,
nickname: user.nickname, nickname: user.nickname,
avatar: user.avatar, avatar: user.avatar,
previewTimeFormat: formatTime(Date.now()), previewTimeFormat: formatTime(Date.now()),
previewMessage: "", previewMessage: "",
}); };
chatList.value.push(newChat);
// 持久化 // 持久化数据到数据库
await db.addOne("conversationList", { await db.addOne("conversationList", {
userId: user.id, userId: user.id,
type: "user", type: "user",
chatId: user.id,
username: user.username, username: user.username,
nickname: user.nickname, nickname: user.nickname,
avatar: user.avatar, avatar: user.avatar,
@ -279,13 +270,10 @@ export const useChatStore = defineStore('chatStore', () => {
previewMessage: "", previewMessage: "",
createdAt: Date.now(), createdAt: Date.now(),
}); });
} else {
console.warn("User not found in workbenchusers with userId:", userId);
}
}
}; };
const formatTime = (timestamp: number): string => { const formatTime = (timestamp: number): string => {
const now = new Date(); const now = new Date();
const createdAt = new Date(timestamp); const createdAt = new Date(timestamp);
@ -319,7 +307,6 @@ export const useChatStore = defineStore('chatStore', () => {
// 创建群聊 // 创建群聊
const createGroupChat = async (userIds: number[]) => { const createGroupChat = async (userIds: number[]) => {
try {
const currUserId = userInfo.value.id; const currUserId = userInfo.value.id;
// 将当前用户的 ID 添加到 user_ids 数组中 // 将当前用户的 ID 添加到 user_ids 数组中
@ -364,25 +351,16 @@ export const useChatStore = defineStore('chatStore', () => {
name: departmentName.value, name: departmentName.value,
avatar: "./logo.png", avatar: "./logo.png",
messages: "", messages: "",
chatId: group_id,
type: "group", type: "group",
previewMessage: "", previewMessage: "",
previewTimeFormat: formatTime(Date.now()), previewTimeFormat: formatTime(Date.now()),
createdAt: new Date() createdAt: new Date()
} }
//
db.addOne("groupChatList", groupConversation) db.addOne("groupChatList", groupConversation)
chatList.value.push(groupConversation) chatList.value.push(groupConversation)
// 关闭对话弹窗 // 关闭对话弹窗
setGroupChatInvitedDialogVisible(false) setGroupChatInvitedDialogVisible(false)
} catch (error) {
console.log(error);
}
}; };
// 处理用户消息 // 处理用户消息
@ -444,6 +422,7 @@ export const useChatStore = defineStore('chatStore', () => {
}; };
const handleUserData = async (data: any[]) => { const handleUserData = async (data: any[]) => {
// 创建一个用户数组,将所有在线的用户提取出来 // 创建一个用户数组,将所有在线的用户提取出来
const users: any[] = []; const users: any[] = [];
// 遍历每个数据项 // 遍历每个数据项
@ -605,36 +584,54 @@ export const useChatStore = defineStore('chatStore', () => {
}; };
const changeChatList = async (id) => { const changeChatList = async (chatId: number, type: string) => {
// 设置 targetUserId // 设置 targetUserId
console.log(id) // 根据type去判断
targetUserId.value = id // user会话,查发送和接收发方id
// group会话,查群id(chatId)查到所有消息记录
targetChatId.value = chatId
if (type === 'user') {
// 获取当前用户和目标用户的聊天记录 // 获取当前用户和目标用户的聊天记录
const history = await getHistory(userInfo.value.id, chatId, type)
const history = await getHistory(id, userInfo.value.id)
chatHistory.value = history; chatHistory.value = history;
// 设置目标用户的信息 // 设置目标用户的信息
await setTargetUserInfo(id); await setTargetUserInfo(chatId);
} else if (type === 'group') {
// 获取当前用户和目标用户的聊天记录
const history = await getHistory(userInfo.value.id, chatId, type)
chatHistory.value = history;
// 设置目标用户的信息
await setTargetGrouprInfo(chatId);
}
}; };
const getHistory = async (userId: any, toUserId: any) => { const getHistory = async (sendUserId: number, toUserId: number, type: string) => {
const messagesList = await db.filter('chatRecord', (record: any) => { var messagesHistory
if (type === 'user') {
messagesHistory = await db.filter('chatRecord', (record: any) => {
return ( return (
(record.userId === userId && record.toUserId === toUserId) || (record.userId === sendUserId && record.toUserId === toUserId) ||
(record.toUserId === userId && record.userId === toUserId) (record.toUserId === sendUserId && record.userId === toUserId)
); );
}); });
} else if (type === 'group') {
return messagesList console.log('group')
messagesHistory = await db.getByField('groupChatRecord', "groupId", toUserId);
}
return messagesHistory
} }
// 设置目标用户的信息
const setTargetUserInfo = async (id: number) => { const setTargetUserInfo = async (id: number) => {
targetUserInfo.value = await db.getOne('workbenchusers', id); targetUserInfo.value = await db.getOne('workbenchusers', id);
}; };
// 设置目标群信息
const setTargetGrouprInfo = async (id: number) => {
const info = await db.getByField('group', "groupId", id);
targetGroupInfo.value = info[0]
};
const handleContextMenu = async () => { const handleContextMenu = async () => {
contextMenu.value.visible = false; contextMenu.value.visible = false;
}; };
@ -662,16 +659,16 @@ export const useChatStore = defineStore('chatStore', () => {
innerRef, innerRef,
currentNavId, currentNavId,
targetUserInfo, targetUserInfo,
targetUserId, targetChatId,
message, message,
contextMenu, contextMenu,
activeNames, activeNames,
groupChatInvitedDialogVisible, groupChatInvitedDialogVisible,
groupInfoSettingDrawerVisible, groupInfoSettingDrawerVisible,
targetNickname,
departmentList, departmentList,
allUserList, allUserList,
departmentName, departmentName,
targetGroupInfo,
initChat, initChat,
showContextMenu, showContextMenu,
setCurrentNavId, setCurrentNavId,

6
frontend/src/stores/db.ts

@ -1,6 +1,6 @@
import Dexie from 'dexie'; import Dexie from 'dexie';
export type ChatTable = 'chatuser' | 'chatmsg' | 'chatmessage' | 'groupmessage' | 'chatRecord' | 'workbenchusers' | 'conversationList' | 'group' | 'groupMembers' | 'groupChatList'; export type ChatTable = 'chatuser' | 'chatmsg' | 'chatmessage' | 'groupmessage' | 'chatRecord' | 'workbenchusers' | 'conversationList' | 'group' | 'groupMembers' | 'groupChatList' | 'groupChatRecord';
export const dbInit: any = new Dexie('GodoOSDatabase'); export const dbInit: any = new Dexie('GodoOSDatabase');
dbInit.version(1).stores({ dbInit.version(1).stores({
@ -9,11 +9,11 @@ dbInit.version(1).stores({
// 聊天记录 // 聊天记录
chatRecord: '++id,toUserId,messages,time,createdAt,userInfo', chatRecord: '++id,toUserId,messages,time,createdAt,userInfo',
// 会话列表 // 会话列表
conversationList: '++id,avatar,username,nickname,userId,toUserId,previewMessage,messages,time,createdAt', conversationList: '++id,avatar,chatId,username,nickname,userId,toUserId,previewMessage,messages,time,createdAt',
chatuser: '++id,ip,hostname,userName,avatar,mobile,nickName,isOnline,updatedAt,createdAt', chatuser: '++id,ip,hostname,userName,avatar,mobile,nickName,isOnline,updatedAt,createdAt',
// chatmsg: '++id,toUserId,targetIp,senderInfo,reciperInfo,previewMessage,content,type,status,isRead,isMe,readAt,createdAt', // chatmsg: '++id,toUserId,targetIp,senderInfo,reciperInfo,previewMessage,content,type,status,isRead,isMe,readAt,createdAt',
chatmessage: '++id,userId,toUserId,senderInfo,isMe,isRead,content,type,readAt,createdAt', chatmessage: '++id,userId,toUserId,senderInfo,isMe,isRead,content,type,readAt,createdAt',
groupmessage: '++id,userId,groupId,senderInfo,isMe,isRead,content,type,readAt,createdAt', groupChatRecord: '++id,userId,groupId,senderInfo,message,time,type,createdAt',
// 群组表 // 群组表
group: '++id,avatar,name,groupId,creator,createdAt', group: '++id,avatar,name,groupId,creator,createdAt',
// 群成员表 // 群成员表

Loading…
Cancel
Save