Переглянути джерело

修复整合前端时发现的bug

nnkwrik 6 роки тому
батько
коміт
09235e95d9

+ 4 - 1
im-service/src/main/java/io/github/nnkwrik/imservice/controller/ChatController.java

@@ -1,5 +1,6 @@
 package io.github.nnkwrik.imservice.controller;
 
+import com.fasterxml.jackson.databind.util.StdDateFormat;
 import io.github.nnkwrik.common.dto.JWTUser;
 import io.github.nnkwrik.common.dto.Response;
 import io.github.nnkwrik.common.token.injection.JWT;
@@ -10,6 +11,7 @@ import io.github.nnkwrik.imservice.service.FormService;
 import io.github.nnkwrik.imservice.service.IndexService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.format.annotation.DateTimeFormat;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestParam;
@@ -51,7 +53,8 @@ public class ChatController {
     //打开消息一览时
     @GetMapping("/chat/index")
     public Response<List<ChatIndex>> getChatIndex(@JWT JWTUser user,
-                                                  @RequestParam(value = "offsetTime", required = false) Date offsetTime,
+                                                  @RequestParam(value = "offsetTime", required = false)
+                                                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date offsetTime,
                                                   @RequestParam(value = "size", defaultValue = "10") int size) {
         if (user == null) {
             return Response.ok(0);

+ 2 - 2
im-service/src/main/java/io/github/nnkwrik/imservice/dao/HistoryMapper.java

@@ -21,7 +21,7 @@ public interface HistoryMapper {
      * @param history
      */
     @Select("insert into history (chat_id, u1_to_u2, message_type, message_body, send_time)\n" +
-            "values (#{chatId}, #{u1ToU2}, #{messageType}, #{messageBody}, #{sendTime});")
+            "values (#{chatId}, #{u1ToU2}, #{messageType}, #{messageBody}, #{sendTime})")
     void addHistory(History history);
 
     /**
@@ -84,7 +84,7 @@ public interface HistoryMapper {
      */
     @Select("select u1_to_u2, message_type, message_body, send_time\n" +
             "from history\n" +
-            "where chat_id = #{chat_id}")
+            "where chat_id = #{chat_id} order by send_time desc")
     List<History> getChatHistory(@Param("chat_id") int chat_id);
 
 

+ 1 - 1
im-service/src/main/java/io/github/nnkwrik/imservice/model/vo/WsMessage.java

@@ -20,6 +20,6 @@ public class WsMessage {
     private Integer messageType;    //0:系统消息,1.用户消息
     private String messageBody;
 
-    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm", locale = "CHINA", timezone = "Asia/Shanghai")
+    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", locale = "CHINA", timezone = "Asia/Shanghai")
     private Date sendTime;
 }

+ 3 - 0
im-service/src/main/java/io/github/nnkwrik/imservice/service/FormService.java

@@ -1,6 +1,7 @@
 package io.github.nnkwrik.imservice.service;
 
 import io.github.nnkwrik.imservice.model.vo.ChatForm;
+import io.github.nnkwrik.imservice.model.vo.WsMessage;
 
 /**
  * @author nnkwrik
@@ -9,4 +10,6 @@ import io.github.nnkwrik.imservice.model.vo.ChatForm;
 public interface FormService {
     
     ChatForm showForm(int chatId, String userId, int page, int size, int offset);
+
+    void addMessageToSQL(WsMessage message);
 }

+ 22 - 3
im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/FormServiceImpl.java

@@ -1,6 +1,7 @@
 package io.github.nnkwrik.imservice.service.impl;
 
 import com.github.pagehelper.PageHelper;
+import com.google.common.collect.Lists;
 import fangxianyu.innerApi.goods.GoodsClientHandler;
 import fangxianyu.innerApi.user.UserClientHandler;
 import io.github.nnkwrik.imservice.dao.ChatMapper;
@@ -47,7 +48,11 @@ public class FormServiceImpl implements FormService {
 
     @Override
     public ChatForm showForm(int chatId, String userId, int page, int size, int offset) {
-        flushUnread(chatId, userId);
+        LastChat lastChat = null;
+        if (page == 1) {
+            lastChat = flushUnread(chatId, userId);
+        }
+
         ChatForm vo = new ChatForm();
 
         Chat chat = chatMapper.getChatById(chatId);
@@ -64,25 +69,39 @@ public class FormServiceImpl implements FormService {
         int pageOffset = (page - 1) * size + offset;
         PageHelper.offsetPage(pageOffset, size);
         List<History> chatHistory = historyMapper.getChatHistory(chatId);
+        chatHistory = Lists.reverse(chatHistory);
+
+        if (lastChat != null) {
+            History lastHistory = new History();
+            BeanUtils.copyProperties(lastChat.getLastMsg(), lastHistory);
+            if (lastChat.getLastMsg().getSenderId().compareTo(lastChat.getLastMsg().getReceiverId()) < 0) {
+                lastHistory.setU1ToU2(true);
+            }
+            chatHistory.add(lastHistory);
+        }
 
         vo.setHistoryList(chatHistory);
 
         return vo;
     }
 
-    private void flushUnread(int chatId, String userId) {
+    private LastChat flushUnread(int chatId, String userId) {
         LastChat lastChat = redisClient.get(chatId + "");
-        if (lastChat.getLastMsg().getReceiverId().equals(userId)) {
+        if (lastChat != null && lastChat.getLastMsg().getReceiverId().equals(userId)) {
             log.info("把chatId={}设为已读消息", chatId);
             addMessageToSQL(lastChat.getLastMsg());
             redisClient.del(chatId + "");
+            return null;
         }
+
+        return lastChat;    //不是receiver访问form,所以仍是未读状态,不刷入sql
     }
 
 //    public void flushWsMsgList(String userId, int chatId,List<WsMessage> wsMsgList){
 //
 //    }
 
+    @Override
     @Transactional
     public void addMessageToSQL(WsMessage message) {
         String u1 = null;

+ 8 - 4
im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/IndexServiceImpl.java

@@ -70,7 +70,7 @@ public class IndexServiceImpl implements IndexService {
         dealRead(read, currentUser, resultVoList, chatGoodsMap, chatUserMap);
 
         //排序后删除超出size的
-        sortAndLimitMsg(size, resultVoList, chatGoodsMap, chatUserMap);
+        resultVoList = sortAndLimitMsg(size, resultVoList, chatGoodsMap, chatUserMap);
 
 
         //添加用户和商品信息
@@ -116,14 +116,16 @@ public class IndexServiceImpl implements IndexService {
         unread.stream().forEach(po -> {
             //稍后去其他服务查询
             chatGoodsMap.put(po.getLastMsg().getChatId(), po.getLastMsg().getGoodsId());
-            chatUserMap.put(po.getLastMsg().getChatId(), po.getLastMsg().getSenderId());
+
 
             //设置未读数,是自己发送的则不显示未读消息数
             ChatIndex vo = new ChatIndex();
             if (po.getLastMsg().getSenderId().equals(currentUserId)) {
+                chatUserMap.put(po.getLastMsg().getChatId(), po.getLastMsg().getReceiverId());
                 vo.setUnreadCount(0);
             } else {
                 vo.setUnreadCount(po.getUnreadCount());
+                chatUserMap.put(po.getLastMsg().getChatId(), po.getLastMsg().getSenderId());
             }
 
             //设置最后一条信息
@@ -164,11 +166,11 @@ public class IndexServiceImpl implements IndexService {
 
     }
 
-    private void sortAndLimitMsg(int size,
+    private List<ChatIndex> sortAndLimitMsg(int size,
                                 List<ChatIndex> voList,
                                 Map<Integer, Integer> chatGoodsMap,
                                 Map<Integer, String> chatUserMap) {
-        voList = voList.stream()
+        List<ChatIndex> limited = voList.stream()
                 .sorted((a, b) -> b.getLastChat().getSendTime().compareTo(a.getLastChat().getSendTime()))
                 .limit(size)
                 .collect(Collectors.toList());
@@ -188,6 +190,8 @@ public class IndexServiceImpl implements IndexService {
             }
         }
 
+        return limited;
+
     }
 
     private List<ChatIndex> setGoodsAndUser4Chat(List<ChatIndex> voList,

+ 5 - 0
im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/WebSocketServiceImpl.java

@@ -8,6 +8,7 @@ import io.github.nnkwrik.imservice.dao.ChatMapper;
 import io.github.nnkwrik.imservice.model.po.LastChat;
 import io.github.nnkwrik.imservice.model.vo.WsMessage;
 import io.github.nnkwrik.imservice.redis.RedisClient;
+import io.github.nnkwrik.imservice.service.FormService;
 import io.github.nnkwrik.imservice.service.WebSocketService;
 import io.github.nnkwrik.imservice.websocket.ChatEndpoint;
 import lombok.extern.slf4j.Slf4j;
@@ -34,6 +35,9 @@ public class WebSocketServiceImpl implements WebSocketService {
     @Autowired
     private RedisClient redisClient;
 
+    @Autowired
+    private FormService formService;
+
     @Override
     public void OnMessage(String senderId, String rawData) {
         WsMessage message = null;
@@ -77,6 +81,7 @@ public class WebSocketServiceImpl implements WebSocketService {
     private void updateRedis(WsMessage message) {
         LastChat lastChat = redisClient.get(message.getChatId() + "");
         if (lastChat != null) {
+            formService.addMessageToSQL(lastChat.getLastMsg());
             lastChat.setUnreadCount(lastChat.getUnreadCount() + 1);
             lastChat.setLastMsg(message);
         } else {

+ 4 - 0
inner-api/src/main/java/fangxianyu/innerApi/goods/GoodsClientHandler.java

@@ -33,6 +33,10 @@ public class GoodsClientHandler {
 
     public Map<Integer, SimpleGoods> getSimpleGoodsList(List<Integer> goodsIdList) {
         log.info("从商品服务查询商品的简单信息");
+        if (goodsIdList.size() < 1){
+            log.info("商品idList为空,返回空的结果");
+            return new HashMap<>();
+        }
         Response<Map<Integer, SimpleGoods>> response = goodsClient.getSimpleGoodsList(goodsIdList);
         if (response.getErrno() != 0) {
             log.info("从商品服务获取商品信息列表失败,errno={},原因={}", response.getErrno(), response.getErrmsg());

+ 4 - 0
inner-api/src/main/java/fangxianyu/innerApi/user/UserClientHandler.java

@@ -32,6 +32,10 @@ public class UserClientHandler {
 
     public Map<String, SimpleUser> getSimpleUserList(List<String> openIdList) {
         log.info("从用户服务查询用户的简单信息");
+        if (openIdList.size() < 1){
+            log.info("用户idList为空,返回空的结果");
+            return new HashMap<>();
+        }
         Response<Map<String, SimpleUser>> response = userClient.getSimpleUserList(openIdList);
         if (response.getErrno() != 0) {
             log.info("从用户服务获取用户信息列表失败,errno={},原因={}", response.getErrno(), response.getErrmsg());