update chat_room表新增client_read_num 和service_read_num,chat_message 表删除is_read字段。 websocket 返回消息新增一个isCreate 字段。

This commit is contained in:
yyb 2025-04-28 16:05:08 +08:00
parent d941b161f9
commit 099e973f64
21 changed files with 146 additions and 95 deletions

View File

@ -150,7 +150,6 @@ public class RedisService {
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* 获得缓存的list对象
*

View File

@ -1,8 +1,9 @@
package com.m2pool.chat.controller;
import com.m2pool.chat.dto.ChatMessageDto;
import com.m2pool.chat.service.ChatMessageService;
import com.m2pool.chat.vo.MessagePageVo;
import com.m2pool.common.core.web.Result.AjaxResult;
import com.m2pool.common.core.Result.R;
import com.m2pool.common.security.annotation.RequiresLogin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -10,6 +11,8 @@ import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/message")
@Api(tags = "聊天消息相关接口")
@ -25,21 +28,21 @@ public class ChatMessageController {
@PostMapping("/find/history/message")
@ApiOperation(value = "查询7天前的历史记录", notes = "根据ID查询7天前的历史记录")
@RequiresLogin
public AjaxResult findHistoryMessage(@RequestBody MessagePageVo pageVo) {
public R<List<ChatMessageDto>> findHistoryMessage(@RequestBody MessagePageVo pageVo) {
return chatMessageService.findHistoryMessage(pageVo.getId(), pageVo.getPageNum(), pageVo.getRoomId());
}
@PostMapping("/find/recently/message")
@ApiOperation(value = "查询七天内的记录", notes = "根据ID查询七天内的记录")
@RequiresLogin
public AjaxResult findRecentlyMessage(@RequestBody MessagePageVo pageVo) {
public R<List<ChatMessageDto>> findRecentlyMessage(@RequestBody MessagePageVo pageVo) {
return chatMessageService.findRecentlyMessage(pageVo.getId(), pageVo.getPageNum(), pageVo.getRoomId());
}
@GetMapping("/delete/message")
@ApiOperation(value = "消息撤回或删除")
@RequiresLogin
public AjaxResult deleteMessage(
public R<String> deleteMessage(
@ApiParam(value = "消息id", required = true, example = "1")
@RequestParam(defaultValue = "1") Long id,
@ApiParam(value = "消息类型 0 文本 1 图片", example = "0")
@ -51,7 +54,7 @@ public class ChatMessageController {
@PostMapping("/read/message")
@ApiOperation(value = "聊天室消息改已读")
@RequiresLogin
public AjaxResult readMessage(@RequestBody MessagePageVo pageVo) {
return chatMessageService.readMessage(pageVo.getRoomId());
public R<String> readMessage(@RequestBody MessagePageVo pageVo) {
return chatMessageService.readMessage(pageVo.getRoomId(),pageVo.getUserType());
}
}

View File

@ -4,7 +4,7 @@ import com.m2pool.chat.dto.ChatRoomDto;
import com.m2pool.chat.service.ChatRoomService;
import com.m2pool.chat.vo.CharRoomVo;
import com.m2pool.chat.vo.RoomPageVo;
import com.m2pool.common.core.web.Result.AjaxResult;
import com.m2pool.common.core.Result.R;
import com.m2pool.common.core.web.page.TableDataInfo;
import com.m2pool.common.security.annotation.RequiresLogin;
import io.swagger.annotations.Api;
@ -24,7 +24,7 @@ public class ChatRoomController {
@PostMapping("/find/room/list")
@ApiOperation(value = "查询客服人员的聊天室列表")
@ApiOperation(value = "客服端:查询客服人员的聊天室列表")
@RequiresLogin
public TableDataInfo<ChatRoomDto> findRoomList(@RequestBody(required = false) RoomPageVo roomPageVo) {
// 如果请求体为空初始化一个默认的 RoomPageVo 对象
@ -36,17 +36,17 @@ public class ChatRoomController {
}
@GetMapping("/find/room/by/userid")
@ApiOperation(value = "根据当前用户邮箱查询聊天室")
@ApiOperation(value = "客户端:根据当前用户邮箱查询聊天室")
@RequiresLogin
public AjaxResult findRoomByUserid() {
public R<ChatRoomDto> findRoomByUserid() {
return chatRoomService.findRoomByUserid();
}
@PostMapping("/update/room")
@ApiOperation(value = "修改room相关信息")
@ApiOperation(value = "修改聊天室重要标记")
@RequiresLogin
public AjaxResult updateRoom(@RequestBody CharRoomVo charRoomVo) {
public R<String> updateRoom(@RequestBody CharRoomVo charRoomVo) {
return chatRoomService.updateRoom(charRoomVo);
}
}

View File

@ -39,9 +39,6 @@ public class ChatMessageDto {
@ApiModelProperty(value = "聊天室id", example = "")
private Long roomId;
@ApiModelProperty(value = "消息是否已读", example = "")
private Integer isRead;
@ApiModelProperty(value = "是否是自己发送的消息", example = "")
private Integer isSelf;

View File

@ -39,10 +39,10 @@ public class ChatRoomDto {
private Integer flag;
/**
* 未读消息条数
* 客户未读消息条数
*/
@ApiModelProperty(value = "未读消息条数", example = "1")
private Integer unReadNumber;
@ApiModelProperty(value = "客户未读消息条数", example = "1")
private Integer clientReadNum;
/**

View File

@ -54,4 +54,19 @@ public class WebsocketMessageDto {
*/
private Long roomId;
/**
* 是否创建新聊天室
*/
private Boolean isCreate;
/**
* 未读消息数
*/
private Integer clientReadNum;
//
// /**
// * 消息状态码
// */
// private Integer code;
}

View File

@ -17,7 +17,6 @@ public class ChatMessage {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Integer type;
private Integer isRead;
private String sendEmail;
private String content;
private Long roomId;

View File

@ -15,7 +15,6 @@ public class ChatMessageHistory {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Integer type;
private Integer isRead;
private String sendEmail;
private String content;
private Long roomId;

View File

@ -23,5 +23,7 @@ public class ChatRoom {
private Integer flag;
private LocalDateTime createTime;
private LocalDateTime updateTime;
private Integer serviceReadNum;
private Integer clientReadNum;
private Boolean del;
}

View File

@ -13,9 +13,12 @@ public class StompPrincipal implements Principal {
Integer type;
public StompPrincipal(String name,Integer type) {
Boolean isCreate;
public StompPrincipal(String name,Integer type,Boolean create) {
this.name = name;
this.type = type;
this.isCreate = create;
}

View File

@ -83,7 +83,7 @@ public class WebsocketChannelInterceptor implements ChannelInterceptor {
//链接请求头中用户信息存入stomp中
mha.setUser(new StompPrincipal(email,type));
mha.setUser(new StompPrincipal(email,type,true));
}
if (accessor.getCommand() == StompCommand.SEND) {
LOGGER.info("------------websocket send message");

View File

@ -1,6 +1,9 @@
package com.m2pool.chat.service;
import com.m2pool.common.core.web.Result.AjaxResult;
import com.m2pool.chat.dto.ChatMessageDto;
import com.m2pool.common.core.Result.R;
import java.util.List;
public interface ChatMessageService{
@ -12,7 +15,7 @@ public interface ChatMessageService{
* @param roomId 聊天室id
* @return
*/
AjaxResult findHistoryMessage(Long id, Integer pageNum,Long roomId);
R<List<ChatMessageDto>> findHistoryMessage(Long id, Integer pageNum, Long roomId);
/**
* 游标分页 查询7天内数据
@ -21,7 +24,7 @@ public interface ChatMessageService{
* @param roomId 聊天室id
* @return
*/
AjaxResult findRecentlyMessage(Long id,Integer pageNum,Long roomId);
R<List<ChatMessageDto>> findRecentlyMessage(Long id,Integer pageNum,Long roomId);
/**
@ -30,13 +33,14 @@ public interface ChatMessageService{
* @param type 消息类型 0 文本 1 图片
* @return
*/
AjaxResult deleteMessage(Long id,Integer type);
R<String> deleteMessage(Long id,Integer type);
/**
* 根据聊天室修改用户未读信息
* @param roomId
* @param type 用户类型
* @return
*/
AjaxResult readMessage(Long roomId);
R<String> readMessage(Long roomId,Integer type);
}

View File

@ -1,10 +1,11 @@
package com.m2pool.chat.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.m2pool.chat.dto.ChatRoomDto;
import com.m2pool.chat.entity.ChatRoom;
import com.m2pool.chat.vo.CharRoomVo;
import com.m2pool.chat.vo.RoomPageVo;
import com.m2pool.common.core.web.Result.AjaxResult;
import com.m2pool.common.core.Result.R;
import com.m2pool.common.core.web.page.TableDataInfo;
public interface ChatRoomService extends IService<ChatRoom> {
@ -20,13 +21,13 @@ public interface ChatRoomService extends IService<ChatRoom> {
* 根据当前用户邮箱查询聊天室
* @return
*/
AjaxResult findRoomByUserid();
R<ChatRoomDto> findRoomByUserid();
/**
* 修改聊天室信息
* @param charRoomVo
* @return
*/
AjaxResult updateRoom( CharRoomVo charRoomVo);
R<String> updateRoom( CharRoomVo charRoomVo);
}

View File

@ -1,20 +1,22 @@
package com.m2pool.chat.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.m2pool.chat.dto.ChatMessageDto;
import com.m2pool.chat.entity.ChatMessage;
import com.m2pool.chat.entity.ChatRoom;
import com.m2pool.chat.mapper.ChatMessageHistoryMapper;
import com.m2pool.chat.mapper.ChatMessageMapper;
import com.m2pool.chat.mapper.ChatRoomMapper;
import com.m2pool.chat.service.ChatMessageService;
import com.m2pool.common.core.web.Result.AjaxResult;
import com.m2pool.common.core.Result.R;
import com.m2pool.common.security.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import static com.m2pool.chat.constant.UserType.CUSTOMER;
import static com.m2pool.chat.constant.UserType.LOGIN_USER;
@Service
public class ChatMessageServiceImpl implements ChatMessageService {
@ -29,46 +31,45 @@ public class ChatMessageServiceImpl implements ChatMessageService {
private ChatRoomMapper chatRoomMapper;
@Override
public AjaxResult findHistoryMessage(Long id,Integer pageNum,Long roomId) {
public R<List<ChatMessageDto>> findHistoryMessage(Long id,Integer pageNum,Long roomId) {
List<ChatMessageDto> historyMessage = chatMessageHistoryMapper.findHistoryMessage(id, pageNum, roomId);
return AjaxResult.success(historyMessage);
return R.success(historyMessage);
}
@Override
public AjaxResult findRecentlyMessage(Long id,Integer pageNum,Long roomId) {
public R<List<ChatMessageDto>> findRecentlyMessage(Long id,Integer pageNum,Long roomId) {
String email = SecurityUtils.getUsername();
List<ChatMessageDto> recentlyMessage = chatMessageMapper.findRecentlyMessage(email,id, pageNum, roomId);
return AjaxResult.success(recentlyMessage);
return R.success(recentlyMessage);
}
@Override
public AjaxResult deleteMessage(Long id,Integer type) {
public R<String> deleteMessage(Long id,Integer type) {
if(chatMessageMapper.deleteById(id) > 0){
//TODO 对象图片存储删除
return AjaxResult.success("删除成功");
return R.success("删除成功");
}
return AjaxResult.error("删除失败");
return R.fail("删除失败");
}
@Override
@Transactional
public AjaxResult readMessage(Long roomId) {
public R<String> readMessage(Long roomId, Integer type) {
ChatRoom chatRoom = chatRoomMapper.selectById(roomId);
String username = SecurityUtils.getUsername();
ChatRoom build = ChatRoom.builder()
.id(roomId)
.build();
if (chatRoom != null){
String updateUserEmail = "";
if( username.equals(chatRoom.getUserOneEmail())){
updateUserEmail = chatRoom.getUserTwoEmail();
}else if (username.equals(chatRoom.getUserTwoEmail())) {
updateUserEmail = chatRoom.getUserOneEmail();
if (Objects.equals(type, LOGIN_USER)) {
build.setServiceReadNum(0);
}
int update = chatMessageMapper.update(ChatMessage.builder().isRead(1).build(),
new LambdaUpdateWrapper<ChatMessage>()
.eq(ChatMessage::getSendEmail, updateUserEmail)
.eq(ChatMessage::getRoomId, roomId));
return update >= 0 ? AjaxResult.success("已读") : AjaxResult.error("消息读取失败");
if(Objects.equals(type, CUSTOMER)){
build.setClientReadNum(0);
}
return AjaxResult.error("聊天室不存在");
int i = chatRoomMapper.updateById(build);
return i >= 0 ? R.success("已读") : R.fail("消息读取失败");
}
return R.fail("聊天室不存在");
}
}

View File

@ -10,23 +10,22 @@ import com.m2pool.chat.mapper.ChatRoomMapper;
import com.m2pool.chat.service.ChatRoomService;
import com.m2pool.chat.vo.CharRoomVo;
import com.m2pool.chat.vo.RoomPageVo;
import com.m2pool.common.core.Result.R;
import com.m2pool.common.core.constant.HttpStatus;
import com.m2pool.common.core.utils.PageUtils;
import com.m2pool.common.core.web.Result.AjaxResult;
import com.m2pool.common.core.web.page.TableDataInfo;
import com.m2pool.common.security.utils.SecurityUtils;
import com.m2pool.system.api.RemoteUserService;
import com.m2pool.system.api.entity.SysUser;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
@Service
public class ChatRoomServiceImpl extends ServiceImpl<ChatRoomMapper, ChatRoom> implements ChatRoomService {
@ -40,24 +39,16 @@ public class ChatRoomServiceImpl extends ServiceImpl<ChatRoomMapper, ChatRoom> i
@Resource
private RemoteUserService remoteUserService;
@Autowired
private SimpUserRegistry userRegistry;
@Override
public TableDataInfo findRoomList(RoomPageVo roomPageVo) {
String userEmail = SecurityUtils.getUsername();
PageHelper.startPage(1, 20);
// System.out.println("-----时间"+roomPageVo.getSendDateTime()+"-----------用户"+userEmail + "-----当前时间"+ System.currentTimeMillis());
//1.查找当前客服对应的聊天室
List<ChatRoomDto> roomList = chatRoomMapper.findRoomList(userEmail,roomPageVo.getSendDateTime());
List<String> userEmails = roomList.stream().map(ChatRoomDto::getUserEmail).collect(Collectors.toList());
//2.查询未读数量
if (!userEmails.isEmpty()){
Map<String, Map<String,Integer>> unReadNums = chatMessageMapper.findUnReadNums(userEmails);
for (ChatRoomDto room : roomList) {
Map<String, Integer> stringIntegerMap = unReadNums.get(room.getUserEmail());
Integer i = stringIntegerMap != null ? stringIntegerMap.get("unReadNumber") : 0;
room.setUnReadNumber(i);
}
}
PageUtils.clearPage();
return getDataTable(roomList);
}
@ -77,35 +68,35 @@ public class ChatRoomServiceImpl extends ServiceImpl<ChatRoomMapper, ChatRoom> i
@Override
@Transactional
public AjaxResult findRoomByUserid() {
public R<ChatRoomDto> findRoomByUserid() {
//1.查询当前用户与对应用户是否已存在创建的聊天室
String userEmail = SecurityUtils.getUsername();
ChatRoomDto roomByUserEmail = chatRoomMapper.findRoomByUserEmail(userEmail);
if(roomByUserEmail != null){
return AjaxResult.success(roomByUserEmail);
return R.success(roomByUserEmail);
}
//2.不存在创建一个聊天室
List<SysUser> data = remoteUserService.getCSList().getData();
if(Collections.isEmpty(data)){
return AjaxResult.error("客服人数不足");
return R.fail("客服人数不足");
}
Random random = new Random();
SysUser sysUser = data.get(random.nextInt(data.size()));
ChatRoom build = ChatRoom.builder().userOneEmail(userEmail).userTwoEmail(sysUser.getEmail()).build();
int insert = chatRoomMapper.insert(build);
if (insert > 0){
return AjaxResult.success(ChatRoomDto.builder().id(build.getId()).userEmail(build.getUserTwoEmail()).build());
return R.success(ChatRoomDto.builder().id(build.getId()).userEmail(build.getUserTwoEmail()).build());
}
return AjaxResult.error("聊天室不存在,并且创建聊天室失败");
return R.fail("聊天室不存在,并且创建聊天室失败");
}
@Override
public AjaxResult updateRoom(CharRoomVo charRoomVo) {
public R<String> updateRoom(CharRoomVo charRoomVo) {
int i = chatRoomMapper.updateById(ChatRoom.builder().id(charRoomVo.getId()).flag(charRoomVo.getFlag()).build());
if(i > 0){
return AjaxResult.success("修改成功");
return R.success("修改成功");
}
return AjaxResult.error("修改失败,不存在该聊天室");
return R.fail("修改失败,不存在该聊天室");
}
}

View File

@ -45,30 +45,42 @@ public class StompServiceImpl implements StompService {
@Override
public AjaxResult sendMessageToUser(StompPrincipal principal, UserMessageVo userMessageVo) {
Boolean isCreate = principal.getIsCreate();
WebsocketMessageDto build = WebsocketMessageDto.builder()
.type(userMessageVo.getType())
.content(userMessageVo.getContent())
.sendEmail(principal.getName())
.sendUserType(principal.getType())
.sendTime(new Date())
.isCreate(isCreate)
.build();
if(!TOURIST.equals(userMessageVo.getReceiveUserType())){
build.setRoomId(userMessageVo.getRoomId());
if (isCreate){
principal.setIsCreate(false);
}
boolean bool = checkOnline(userMessageVo);
//获取当前聊天室对象
ChatRoom chatRoom = chatRoomMapper.selectById(userMessageVo.getRoomId());
if (chatRoom != null){
build.setClientReadNum(chatRoom.getClientReadNum() + 1);
}
if (checkOnline(userMessageVo)){
//当前用户发送其他人, 发送给指定用户. 否则默认发送给当前发送者
if (bool){
messagingTemplate.convertAndSendToUser(userMessageVo.getEmail(), Destination.QUEUE + "/" + userMessageVo.getEmail(),build);
}
// 接收者和发送者 都不是游客才能存储消息 和修改聊天室信息后续可改为消息中间件解耦形式
if (!TOURIST.equals(userMessageVo.getReceiveUserType()) && !TOURIST.equals(principal.getType())){
if (!TOURIST.equals(userMessageVo.getReceiveUserType()) && !TOURIST.equals(principal.getType()) && chatRoom != null){
build.setRoomId(userMessageVo.getRoomId());
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
// 插入消息并获取 ID
insertMessage(principal,userMessageVo);
// 更新房间信息
updateRoom(userMessageVo.getRoomId(),principal.getType());
//聊天室已读未读数量更新
updateRoom(chatRoom,principal.getType(),bool);
} catch (Exception e) {
// 回滚事务
status.setRollbackOnly();
@ -108,14 +120,18 @@ public class StompServiceImpl implements StompService {
/**
* 修改聊天信息
* @param roomId
* @param sendUserType
* @param chatRoom 本次聊天聊天室信息
* @param sendUserType 发送者类型
* @param bool 发送者是否在线不在线需要更新未读消息数量
*/
private void updateRoom(Long roomId,Integer sendUserType){
ChatRoom room = ChatRoom.builder().id(roomId).build();
private void updateRoom(ChatRoom chatRoom,Integer sendUserType,Boolean bool){
ChatRoom room = ChatRoom.builder().id(chatRoom.getId()).build();
if (CUSTOMER.equals(sendUserType)) {
room.setClientReadNum(chatRoom.getClientReadNum() + 1);
room.setLastCustomerSendTime(LocalDateTime.now());
} else {
room.setServiceReadNum(chatRoom.getServiceReadNum() + 1);
room.setLastUserSendTime(LocalDateTime.now());
}
chatRoomMapper.updateById(room);

View File

@ -1,5 +1,7 @@
package com.m2pool.chat.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
@ -9,7 +11,10 @@ import lombok.Data;
* @Date 2025/4/15 10:42
*/
@Data
@ApiModel(description = "聊天室请求对象")
public class CharRoomVo {
@ApiModelProperty(value = "聊天室id", example = "1")
private Long id;
@ApiModelProperty(value = "聊天室重要程度 0不重要 1重要", example = "1")
private Integer flag;
}

View File

@ -1,5 +1,7 @@
package com.m2pool.chat.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
@ -9,11 +11,20 @@ import lombok.Data;
* @Date 2025/4/22 17:09
*/
@Data
@ApiModel(description = "消息分页对象")
public class MessagePageVo {
@ApiModelProperty(value = "消息id", example = "1")
private Long id;
@ApiModelProperty(value = "页数量", example = "1")
private Integer pageNum;
@ApiModelProperty(value = "聊天室id", example = "1")
private Long roomId;
@ApiModelProperty(value = "用户类型 0 游客 1 登录用户 2 客服", example = "1")
private Integer userType;
public MessagePageVo() {
this.pageNum = 20;
}

View File

@ -1,5 +1,7 @@
package com.m2pool.chat.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
@ -9,33 +11,36 @@ import lombok.Data;
* @Date 2025/4/10 16:28
*/
@Data
@ApiModel(description = "用户发送消息对象")
public class UserMessageVo {
/**
* 消息类型
*/
@ApiModelProperty(value = "消息类型", example = "0 文本 1 图片")
private Integer type;
/**
* 消息内容
*/
@ApiModelProperty(value = "消息内容", example = "消息内容")
private String content;
/**
* 接收者
*/
@ApiModelProperty(value = "接收者", example = "54544@qq.com")
private String email;
/**
* 接受用户类型 0 游客 1 登录用户 2 客服人员
*/
@ApiModelProperty(value = "接受用户类型 0 游客 1 登录用户 2 客服人员", example = "1")
private Integer receiveUserType;
/**
* 聊天室id
*/
@ApiModelProperty(value = "聊天室id", example = "1")
private Long roomId;
}

View File

@ -10,7 +10,6 @@
content,
create_time as createTime,
room_id as roomId,
is_read as isRead,
case when send_email = #{email} then 1
else 0
end as isSelf

View File

@ -8,7 +8,8 @@
user_one_email AS userEmail,
flag,
last_user_send_time as lastUserSendTime,
last_customer_send_time as lastCustomerSendTime
last_customer_send_time as lastCustomerSendTime,
client_read_num AS clientReadNum
FROM
chat_room
<where>
@ -28,7 +29,7 @@
</select>
<select id="findRoomByUserEmail" resultType="com.m2pool.chat.dto.ChatRoomDto">
SELECT
id,user_two_email AS userEmail
id,service_read_num AS clientReadNum ,user_two_email AS userEmail
FROM
chat_room
WHERE