3 Revize 2d3e9abc65 ... 6bdd9f2aa5

Autor SHA1 Zpráva Datum
  lyh 6bdd9f2aa5 新增实时及登录推送站内信 před 1 rokem
  lyh 2977a98a40 站内信修改权限 před 1 rokem
  lyh 94b5c57e70 站内信 před 1 rokem

+ 20 - 0
sql/Online.sql

@@ -0,0 +1,20 @@
+DROP TABLE IF EXISTS `sys_message`;
+CREATE TABLE `sys_message`  (
+                                `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
+                                `classify` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '消息分类 1-公告 2-系统通知 3-事件触发',
+                                `type` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '消息类型 1-增员消息 2-审批消息 3-待办消息',
+                                `title` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '消息标题',
+                                `content` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '消息内容',
+                                `jump` varchar(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '是否支持跳转 0-不支持 1-支持',
+                                `jump_url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '跳转目标路径',
+                                `receiver_id` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '消息接收方',
+                                `sender_id` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '消息发送方',
+                                `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
+                                `send_time` datetime(0) NULL DEFAULT NULL COMMENT '发送时间',
+                                `state` varchar(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '状态 0-未读  1-已读',
+                                `high_light` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '高亮字段',
+                                `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建者',
+                                `update_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改者',
+                                `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
+                                PRIMARY KEY (`id`) USING BTREE
+) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '核心系统消息列表' ROW_FORMAT = Dynamic;

+ 4 - 1
src/main/java/com/ydtech/SpringInsApplication.java

@@ -1,9 +1,11 @@
 package com.ydtech;
 
+import com.ydtech.modules.admin.controller.websocket.SendMessageServer;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.context.ConfigurableApplicationContext;
 import org.springframework.scheduling.annotation.EnableAsync;
 import org.springframework.scheduling.annotation.EnableScheduling;
 
@@ -37,7 +39,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
 public class SpringInsApplication {
 
     public static void main(String[] args) {
-        SpringApplication.run(SpringInsApplication.class, args);
+        ConfigurableApplicationContext run = SpringApplication.run(SpringInsApplication.class, args);
+        SendMessageServer.setApplicationContext(run);
     }
 
 }

+ 9 - 0
src/main/java/com/ydtech/constants/enums/dict/organization/OrganizationSource.java

@@ -29,6 +29,15 @@ public enum OrganizationSource implements IBaseEnum {
     // 状态  0 启用  1 不启用
     private final Integer status;
 
+    public static String getDescByCode(String code) {
+        for (OrganizationSource value : OrganizationSource.values()) {
+            if (value.code.equals(code)) {
+                return value.desc;
+            }
+        }
+        return null;
+    }
+
     @AllArgsConstructor
     @Getter
     public enum Source {

+ 39 - 0
src/main/java/com/ydtech/modules/admin/constants/MessageConstants.java

@@ -0,0 +1,39 @@
+package com.ydtech.modules.admin.constants;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+@AllArgsConstructor
+@Getter
+public enum MessageConstants {
+
+
+    CLASSIFY_1("1","公告", "CLASSIFY"),
+    CLASSIFY_2("2","系统通知", "CLASSIFY"),
+    CLASSIFY_3("3","事件触发", "CLASSIFY"),
+    TYPE_1("1","增员消息", "TYPE"),
+    TYPE_2("2","审批消息", "TYPE"),
+    TYPE_3("3","待办消息", "TYPE");
+
+    private final String code;
+    private final String name;
+    private final String type;
+
+    public static String getMessageConstants(String code) {
+        for (MessageConstants roleConstants : MessageConstants.values()) {
+            if (roleConstants.getCode().equals(code)) {
+                return roleConstants.name;
+            }
+        }
+        return null;
+    }
+
+    public static String getMessageByTypeAndCode(String code, String type) {
+        for (MessageConstants roleConstants : MessageConstants.values()) {
+            if (roleConstants.getCode().equals(code) && roleConstants.getType().equals(type)) {
+                return roleConstants.name;
+            }
+        }
+        return null;
+    }
+}

+ 30 - 0
src/main/java/com/ydtech/modules/admin/constants/MessageModelConstants.java

@@ -0,0 +1,30 @@
+package com.ydtech.modules.admin.constants;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+@AllArgsConstructor
+@Getter
+public enum MessageModelConstants {
+
+    //渠道管理/出单员管理
+    //%添加人员账号姓名%于%创建时间%新增了出单员,%出单员姓名%,%出单员工号%,请及时查看。
+    MODEL_1("1", "有新增的出单员", "${添加人员账号姓名}于${创建时间}新增了出单员,${出单员姓名},${出单员工号},请及时查看。", "/peopleManage/player/playerManage"),
+    //代理人管理/代理人审核
+    //%人员类型% %待审核人员姓名%,%待审核人员工号%,于%审核数据生成时间%申请入司,请及时审批。
+    MODEL_2("2", "有新的入司人员,请注意查收", "${人员类型} ${待审核人员姓名},${待审核人员工号}于${审核数据生成时间}申请入司,请及时审批。", "/peopleManage/agent/agentExamine");
+
+    private final String code;
+    private final String title;
+    private final String content;
+    private final String url;
+
+    public static String getMessageContent(String code) {
+        for (MessageModelConstants roleConstants : MessageModelConstants.values()) {
+            if (roleConstants.getCode().equals(code)) {
+                return roleConstants.content;
+            }
+        }
+        return null;
+    }
+}

+ 194 - 0
src/main/java/com/ydtech/modules/admin/controller/websocket/SendMessageServer.java

@@ -0,0 +1,194 @@
+package com.ydtech.modules.admin.controller.websocket;
+
+import com.github.pagehelper.PageInfo;
+import com.google.gson.Gson;
+import com.google.gson.JsonParser;
+import com.ydtech.modules.message.entity.SystemMessage;
+import com.ydtech.modules.message.entity.SystemMessageVo;
+import com.ydtech.modules.message.entity.dto.SystemMessageDTO;
+import com.ydtech.modules.message.service.SystemMessageService;
+import com.ydtech.utils.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.websocket.*;
+import javax.websocket.server.PathParam;
+import javax.websocket.server.ServerEndpoint;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import cn.hutool.log.Log;
+import cn.hutool.log.LogFactory;
+
+
+@ServerEndpoint(value = "/getMessage/{userId}")
+@Component
+public class SendMessageServer {
+
+
+    private static ApplicationContext applicationContext;
+
+    public static void setApplicationContext(ApplicationContext context) {
+        applicationContext = context;
+    }
+
+    static Log log = LogFactory.get(SendMessageServer.class);
+    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
+    private static int onlineCount = 0;
+    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
+    private static ConcurrentHashMap<String,SendMessageServer> webSocketMap = new ConcurrentHashMap<>();
+    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
+    private Session session;
+    /**接收userId*/
+    private String userId="";
+
+    /**
+     * 连接建立成功调用的方法*/
+    @OnOpen
+    public void onOpen(Session session, @PathParam("userId") String userId) {
+        this.session = session;
+        this.userId=userId;
+        if(webSocketMap.containsKey(userId)){
+            webSocketMap.remove(userId);
+            webSocketMap.put(userId, this);
+            //加入set中
+        }else{
+            webSocketMap.put(userId, this);
+            //加入set中
+            addOnlineCount();
+            //在线数加1
+        }
+
+        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
+
+        try {
+            PageInfo<SystemMessageDTO> message = getMessage(userId);
+            log.info("为用户" + userId + "连接建立成功发送站内信" + new Gson().toJson(message));
+            sendMessage(new Gson().toJson(message));
+        } catch (Exception e) {
+            log.error("用户:"+userId+",网络异常!!!!!!");
+        }
+    }
+
+    /**
+     * 连接关闭调用的方法
+     */
+    @OnClose
+    public void onClose() {
+        if(webSocketMap.containsKey(userId)){
+            webSocketMap.remove(userId);
+            //从set中删除
+            subOnlineCount();
+        }
+        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
+    }
+
+    /**
+     * 收到客户端消息后调用的方法
+     *
+     * @param message 客户端发送过来的消息*/
+    @OnMessage
+    public void onMessage(String message, Session session) {
+        log.info("用户消息:"+userId+",报文:"+message);
+        //可以群发消息
+        //消息保存到数据库、redis
+        if (StringUtils.isNotBlank(message)) {
+            try {
+                //解析发送的报文
+                JSONObject jsonObject = JSON.parseObject(message);
+                //追加发送人(防止串改)
+                jsonObject.put("fromUserId",this.userId);
+                String toUserId=jsonObject.getString("userId");
+
+                //传送给对应toUserId用户的websocket
+                if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
+                    PageInfo<SystemMessageDTO> getMessage = getMessage(toUserId);
+                    log.info("为用户" + toUserId + "登录或刷新发送站内信" + new Gson().toJson(getMessage));
+                    webSocketMap.get(toUserId).sendMessage(new Gson().toJson(getMessage));
+                } else {
+                    log.error("请求的userId:"+toUserId+"不在该服务器上");
+                    //否则不在这个服务器上,发送到mysql或者redis
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    /**
+     *
+     * @param session
+     * @param error
+     */
+    @OnError
+    public void onError(Session session, Throwable error) {
+        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
+        error.printStackTrace();
+    }
+    /**
+     * 实现服务器主动推送
+     */
+    public void sendMessage(String message) throws Exception {
+        this.session.getBasicRemote().sendText(message);
+    }
+
+
+    /**
+     * 每小时发送站内信消息
+     * */
+//    @Scheduled(cron = "0 * * * * *")
+//    public void fixedTime() throws Exception {
+//        log.info("定时任务发送站内信消息到:" + JSONObject.toJSONString(webSocketMap.keySet()));
+//        if (webSocketMap.size() > 0) {
+//            for (String userId : webSocketMap.keySet()) {
+//                PageInfo<SystemMessageDTO> message = getMessage(userId);
+//                log.info("定时任务发送站内信消息内容:" + JSONObject.toJSONString(message));
+//                webSocketMap.get(userId).sendMessage(new Gson().toJson(message));
+//            }
+//        }
+//    }
+
+
+    public void realTime(List<SystemMessage> systemMessageList) throws Exception {
+        log.info("实时发送站内信消息到:" + JSONObject.toJSONString(webSocketMap.keySet()));
+        if (webSocketMap.size() > 0) {
+            for (String userId : webSocketMap.keySet()) {
+                for (SystemMessage systemMessage : systemMessageList) {
+                    if (userId.equals(systemMessage.getReceiverId())) {
+                        log.info("实时发送站内信消息内容:" + JSONObject.toJSONString(systemMessage));
+                        webSocketMap.get(userId).sendMessage(new Gson().toJson(systemMessage));
+                    }
+                }
+            }
+        }
+    }
+
+
+    public static synchronized int getOnlineCount() {
+        return onlineCount;
+    }
+
+    public static synchronized void addOnlineCount() {
+        SendMessageServer.onlineCount++;
+    }
+
+    public static synchronized void subOnlineCount() {
+        SendMessageServer.onlineCount--;
+    }
+
+    public PageInfo<SystemMessageDTO> getMessage(String userId) {
+        SystemMessageVo systemMessageVo = new SystemMessageVo();
+        systemMessageVo.setUserId(userId);
+        systemMessageVo.setPageNum(1);
+        systemMessageVo.setPageSize(10);
+        SystemMessageService socketTableConnService = applicationContext.getBean(SystemMessageService.class);
+        PageInfo<SystemMessageDTO> systemMessageByUser = socketTableConnService.getSystemMessageByUser(systemMessageVo);
+        return systemMessageByUser;
+    }
+
+
+}

+ 4 - 0
src/main/java/com/ydtech/modules/admin/dao/SysUserRoleMapper.java

@@ -2,8 +2,11 @@ package com.ydtech.modules.admin.dao;
 
 import com.ydtech.modules.admin.model.SysUserRole;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import org.apache.ibatis.annotations.Param;
 import org.springframework.stereotype.Repository;
 
+import java.util.List;
+
 /**
  * @author Administrator
  * @description 针对表【sys_user_role(用户角色)】的数据库操作Mapper
@@ -13,6 +16,7 @@ import org.springframework.stereotype.Repository;
 @Repository
 public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
 
+    List<SysUserRole> selectBymenuId(@Param("menuId") int menuId);
 }
 
 

+ 112 - 4
src/main/java/com/ydtech/modules/admin/service/impl/SysUserServiceImpl.java

@@ -13,6 +13,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.google.gson.Gson;
 import com.ydtech.constants.InsuranceImageEnum;
 import com.ydtech.constants.SysConstants;
+import com.ydtech.constants.enums.dict.organization.OrganizationSource;
 import com.ydtech.core.page.HttpResult;
 import com.ydtech.core.page.PageResult;
 import com.ydtech.exception.SystemException;
@@ -21,10 +22,7 @@ import com.ydtech.modules.admin.components.UnionPayRequestApiComponent;
 import com.ydtech.modules.admin.components.request.UnionPayRequest;
 import com.ydtech.modules.admin.components.response.UnionPayResponse;
 import com.ydtech.modules.admin.constants.*;
-import com.ydtech.modules.admin.dao.SysDeptMapper;
-import com.ydtech.modules.admin.dao.SysPartnerMapper;
-import com.ydtech.modules.admin.dao.SysUserLinkAreaMapper;
-import com.ydtech.modules.admin.dao.SysUserMapper;
+import com.ydtech.modules.admin.dao.*;
 import com.ydtech.modules.admin.model.*;
 import com.ydtech.modules.admin.model.dto.*;
 import com.ydtech.modules.admin.model.po.SysUserAgentTrack;
@@ -44,7 +42,9 @@ import com.ydtech.modules.esm.model.vo.EsmUserImageVo;
 import com.ydtech.modules.esm.service.EsmUserImageService;
 import com.ydtech.modules.esm.service.EsmUserReferrerService;
 import com.ydtech.modules.message.constants.MessageTypeConstants;
+import com.ydtech.modules.message.entity.SystemMessage;
 import com.ydtech.modules.message.service.MessageSecretaryService;
+import com.ydtech.modules.message.service.SystemMessageService;
 import com.ydtech.modules.protocol.utils.AssertionUtils;
 import com.ydtech.security.utils.PasswordUtils;
 import com.ydtech.utils.IDCardUtils;
@@ -142,6 +142,12 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
     @Autowired
     private SysUserBankCardService bankCardService;
 
+    @Autowired
+    private SystemMessageService systemMessageService;
+
+    @Autowired
+    private SysUserRoleMapper sysUserRoleMapper;
+
     @Value("${httpUrl}")
     private String httpUrl;
     //晋掌柜APP: 未注册的手机号登录时创建新账户使用 -deptId -referrerId
@@ -872,6 +878,8 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
             SysUserInfo userInfo = sysUserVo.getSysUserInfo();
             userInfo.setId(sysUser.getId());
             sysUserInfoService.save(userInfo);
+            //站内信发送
+            pushMessageOrder(sysUser);
         } else {
             userId = gainNextUserId(sysUser.getDeptId());
 
@@ -896,6 +904,10 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
                 //如果是 团队长或代码人 并且没有推荐人 则默认推荐人为自己
                 esmUserReferrerService.addReferrer(sysUser.getId(), userId);
             }
+            if ("20".equals(sysUser.getRoleId())) {
+                //如果是添加代理人则发送站内信
+                pushMessageAgent(sysUser);
+            }
             SysUserInfo userInfo = sysUserVo.getSysUserInfo();
             if (userInfo != null) {
                 if (null != userInfo.getLiveAddressString() && userInfo.getLiveAddressString().length > 0) {
@@ -914,6 +926,102 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
         return HttpResult.ok("新增成功");
     }
 
+    //新增出单员发送新增站内信
+    private void pushMessageOrder(SysUser sysUser) {
+        //获取有渠道管理权限的用户ID
+        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectBymenuId(454);
+        List<SysUserRole> sysUserRoleList = sysUserRoles.stream()
+                .filter(user -> !StringUtils.isNullOrEmpty(user))
+                .distinct()
+                .collect(Collectors.toList());
+
+        Map<String, String> map = new HashMap<>();
+        List<SystemMessage> systemMessageList = new ArrayList<>();
+
+        SysUser user = BaseController.getUser();
+        StringBuilder loger = new StringBuilder()
+                .append(user.getId())
+                .append(user.getName());
+        Date date = new Date();
+        String dateString = new SimpleDateFormat("yyyy-MM-dd").format(date);
+        map.put("${添加人员账号姓名}", loger.toString());
+        map.put("${创建时间}", dateString);
+        map.put("${出单员姓名}", sysUser.getName());
+        map.put("${出单员工号}", sysUser.getId());
+        String content = systemMessageService.makeMessage(MessageModelConstants.MODEL_1.getContent(), map, null);
+        StringBuilder highLight = new StringBuilder()
+                .append(loger).append(";")
+                .append(dateString).append(";")
+                .append(sysUser.getName()).append(";")
+                .append(sysUser.getId()).append(";");
+
+        for (SysUserRole sysUserRole : sysUserRoleList) {
+            SystemMessage systemMessage = new SystemMessage();
+            systemMessage.setClassify(MessageConstants.CLASSIFY_3.getCode());
+            systemMessage.setType(MessageConstants.TYPE_1.getCode());
+            systemMessage.setTitle(MessageModelConstants.MODEL_1.getTitle());
+            systemMessage.setContent(content);
+            systemMessage.setJump("1");
+            systemMessage.setJumpUrl(MessageModelConstants.MODEL_1.getUrl());
+            systemMessage.setSenderId(BaseController.getUserId());
+            systemMessage.setReceiverId(sysUserRole.getUserId());
+            systemMessage.setState("0");
+            systemMessage.setHighLight(highLight.toString());
+            systemMessage.setSendTime(date);
+            systemMessageList.add(systemMessage);
+        }
+            systemMessageService.addSystemMessageList(systemMessageList);
+    }
+
+    //代理人新增 发送审核站内信
+    private void pushMessageAgent(SysUser sysUser) {
+        //获取有代理人审核按钮权限的用户ID
+        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectBymenuId(323);
+        List<SysUserRole> sysUserRoleList = sysUserRoles.stream()
+                .filter(user -> !StringUtils.isNullOrEmpty(user))
+                .distinct()
+                .collect(Collectors.toList());
+
+        String managementSource = new String();
+        SysDept dept = sysDeptService.getById(sysUser.getDeptId());
+        if (!StringUtils.isNullOrEmpty(dept))
+            managementSource = dept.getManagementSource();
+
+
+        Map<String, String> map = new HashMap<>();
+        List<SystemMessage> systemMessageList = new ArrayList<>();
+
+        Date date = new Date();
+        String dateString = new SimpleDateFormat("yyyy-MM-dd").format(date);
+        map.put("${人员类型}", OrganizationSource.getDescByCode(managementSource));
+        map.put("${审核数据生成时间}", dateString);
+        map.put("${待审核人员姓名}", sysUser.getName());
+        map.put("${待审核人员工号}", sysUser.getId());
+        String content = systemMessageService.makeMessage(MessageModelConstants.MODEL_2.getContent(), map, null);
+        StringBuilder highLight = new StringBuilder()
+                .append(OrganizationSource.getDescByCode(managementSource)).append(";")
+                .append(dateString).append(";")
+                .append(sysUser.getName()).append(";")
+                .append(sysUser.getId()).append(";");
+
+        for (SysUserRole sysUserRole : sysUserRoleList) {
+            SystemMessage systemMessage = new SystemMessage();
+            systemMessage.setClassify(MessageConstants.CLASSIFY_3.getCode());
+            systemMessage.setType(MessageConstants.TYPE_2.getCode());
+            systemMessage.setTitle(MessageModelConstants.MODEL_2.getTitle());
+            systemMessage.setContent(content);
+            systemMessage.setJump("1");
+            systemMessage.setJumpUrl(MessageModelConstants.MODEL_2.getUrl());
+            systemMessage.setSenderId(BaseController.getUserId());
+            systemMessage.setReceiverId(sysUserRole.getUserId());
+            systemMessage.setState("0");
+            systemMessage.setHighLight(highLight.toString());
+            systemMessage.setSendTime(date);
+            systemMessageList.add(systemMessage);
+        }
+            systemMessageService.addSystemMessageList(systemMessageList);
+    }
+
     @Override
     @Transactional(rollbackFor = Exception.class)
     public SysUser saveUserJzgInfo(SysUser2Vo sysUserVo) {

+ 52 - 0
src/main/java/com/ydtech/modules/message/controller/SystemMessageController.java

@@ -0,0 +1,52 @@
+package com.ydtech.modules.message.controller;
+
+import com.github.pagehelper.PageInfo;
+import com.ydtech.core.page.HttpResult;
+import com.ydtech.modules.base.controller.BaseController;
+import com.ydtech.modules.message.entity.SystemMessageVo;
+import com.ydtech.modules.message.entity.dto.SystemMessageDTO;
+import com.ydtech.modules.message.service.SystemMessageService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+
+@Slf4j
+@Api(tags = "站内信")
+@RestController
+@RequestMapping("/sys/message")
+@RequiredArgsConstructor
+public class SystemMessageController {
+
+    @Autowired
+    private SystemMessageService systemMessageService;
+
+    @PostMapping("/get")
+    @ApiOperation("获取站内信信息")
+    public HttpResult<PageInfo<SystemMessageDTO>> getUserMessage(@RequestBody SystemMessageVo systemMessageVo) {
+        String userId = BaseController.getUserId();
+        systemMessageVo.setUserId(userId);
+        try {
+            PageInfo<SystemMessageDTO> systemMessageByUser = systemMessageService.getSystemMessageByUser(systemMessageVo);
+            return HttpResult.ok("success", systemMessageByUser);
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            return HttpResult.error("接口异常请重试!");
+        }
+    }
+
+    @PostMapping("/update")
+    @ApiOperation("修改站内信信息")
+    public HttpResult updateUserMessage(@RequestParam Integer id) {
+        try {
+            systemMessageService.updateSystemMessageByUser(id);
+            return HttpResult.ok("success");
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            return HttpResult.error("接口异常请重试!");
+        }
+    }
+}

+ 13 - 0
src/main/java/com/ydtech/modules/message/dao/SystemMessageMapper.java

@@ -0,0 +1,13 @@
+package com.ydtech.modules.message.dao;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.ydtech.modules.message.entity.SystemMessage;
+
+import java.util.List;
+
+/**
+ * 站内信Mapper
+ */
+public interface SystemMessageMapper extends BaseMapper<SystemMessage> {
+
+}

+ 69 - 0
src/main/java/com/ydtech/modules/message/entity/SystemMessage.java

@@ -0,0 +1,69 @@
+package com.ydtech.modules.message.entity;
+
+import com.baomidou.mybatisplus.annotation.*;
+import com.ydtech.modules.base.model.BaseEntity;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.util.Date;
+
+
+/**
+ * 站内信实体类
+ */
+@Data
+@TableName(value = "sys_message")
+@ApiModel
+public class SystemMessage extends BaseEntity {
+
+    private static final long serialVersionUID = -7650986460741587720L;
+
+    @TableId(type = IdType.AUTO)
+    private Integer id;
+
+    @ApiModelProperty(value = "消息分类 1-公告 2-系统通知 3-事件触发")
+    @TableField(value = "classify")
+    private String classify;
+
+    @ApiModelProperty(value = "消息类型 01-增员消息 02-审批消息 03-待办消息")
+    @TableField(value = "type")
+    private String type;
+
+    @ApiModelProperty(value = "消息标题")
+    @TableField(value = "title")
+    private String title;
+
+    @ApiModelProperty(value = "消息内容")
+    @TableField(value = "content")
+    private String content;
+
+    @ApiModelProperty(value = "是否支持跳转 0-不支持 1-支持")
+    @TableField(value = "jump")
+    private String jump;
+
+    @ApiModelProperty(value = "跳转目标路径")
+    @TableField(value = "jump_url")
+    private String jumpUrl;
+
+    @ApiModelProperty(value = "消息接收方")
+    @TableField(value = "receiver_id")
+    private String receiverId;
+
+    @ApiModelProperty(value = "消息发送方")
+    @TableField(value = "sender_id")
+    private String senderId;
+
+    @ApiModelProperty(value = "状态 0-未读  1-已读")
+    @TableField(value = "state")
+    private String state;
+
+    @ApiModelProperty(value = "高亮字段")
+    @TableField(value = "high_light")
+    private String highLight;
+
+    @ApiModelProperty(value = "发送时间")
+    @TableField(value = "send_time" ,fill = FieldFill.INSERT)
+    private Date sendTime;
+
+}

+ 34 - 0
src/main/java/com/ydtech/modules/message/entity/SystemMessageVo.java

@@ -0,0 +1,34 @@
+package com.ydtech.modules.message.entity;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+
+@Data
+public class SystemMessageVo implements Serializable {
+
+    private static final long serialVersionUID = -4126594748984640557L;
+
+    @ApiModelProperty("消息类型")
+    private String msgType;
+
+    /**
+     * 当前页
+     */
+    @ApiModelProperty("当前页")
+    private Integer pageNum;
+
+    /**
+     * 每页数量
+     */
+    @ApiModelProperty("每页数量")
+    private Integer pageSize;
+
+    /**
+     * 登录人id
+     */
+    @ApiModelProperty("登录人id")
+    private String userId;
+
+}

+ 42 - 0
src/main/java/com/ydtech/modules/message/entity/dto/SystemMessageDTO.java

@@ -0,0 +1,42 @@
+package com.ydtech.modules.message.entity.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+@Data
+public class SystemMessageDTO implements Serializable {
+
+    private static final long serialVersionUID = -6152572194386977084L;
+
+    private Integer id;
+
+    @ApiModelProperty(value = "消息分类 1-公告 2-系统通知 3-事件触发")
+    private String classify;
+
+    @ApiModelProperty(value = "消息类型 1-增员消息 2-审批消息 3-待办消息")
+    private String type;
+
+    @ApiModelProperty(value = "消息标题")
+    private String title;
+
+    @ApiModelProperty(value = "消息内容")
+    private String content;
+
+    @ApiModelProperty(value = "是否支持跳转 0-不支持 1-支持")
+    private String jump;
+
+    @ApiModelProperty(value = "跳转目标路径")
+    private String jumpUrl;
+
+    @ApiModelProperty(value = "状态 0-未读  1-已读")
+    private String state;
+
+    @ApiModelProperty(value = "高亮字段")
+    private String highLight;
+
+    @ApiModelProperty(value = "发送时间")
+    private Date sendTime;
+}

+ 22 - 0
src/main/java/com/ydtech/modules/message/service/SystemMessageService.java

@@ -0,0 +1,22 @@
+package com.ydtech.modules.message.service;
+
+
+import com.github.pagehelper.PageInfo;
+import com.ydtech.modules.message.entity.SystemMessage;
+import com.ydtech.modules.message.entity.SystemMessageVo;
+import com.ydtech.modules.message.entity.dto.SystemMessageDTO;
+
+import java.util.List;
+import java.util.Map;
+
+public interface SystemMessageService {
+
+
+    PageInfo<SystemMessageDTO> getSystemMessageByUser(SystemMessageVo systemMessageVo);
+
+    void addSystemMessageList(List<SystemMessage> systemMessageList);
+
+    void updateSystemMessageByUser(Integer id);
+
+    String makeMessage(String modelId, Map<String, String> map, String defV);
+}

+ 119 - 0
src/main/java/com/ydtech/modules/message/service/impl/SystemMessageServiceImpl.java

@@ -0,0 +1,119 @@
+package com.ydtech.modules.message.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.github.pagehelper.PageHelper;
+import com.github.pagehelper.PageInfo;
+import com.ydtech.modules.admin.constants.MessageConstants;
+import com.ydtech.modules.admin.controller.websocket.SendMessageServer;
+import com.ydtech.modules.message.dao.SystemMessageMapper;
+import com.ydtech.modules.message.entity.SystemMessage;
+import com.ydtech.modules.message.entity.SystemMessageVo;
+import com.ydtech.modules.message.entity.dto.SystemMessageDTO;
+import com.ydtech.modules.message.service.SystemMessageService;
+import com.ydtech.utils.StringUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.ObjectUtils;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+@Service
+@Slf4j
+public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, SystemMessage> implements SystemMessageService {
+
+    @Autowired
+    private SendMessageServer sendMessageServer;
+
+    @Override
+    public PageInfo<SystemMessageDTO> getSystemMessageByUser(SystemMessageVo systemMessageVo){
+        log.info("获取站内信入参:{}", JSONObject.toJSONString(systemMessageVo));
+
+        List<SystemMessageDTO> systemMessageDTOList = new ArrayList<>();
+
+        PageHelper.startPage(systemMessageVo.getPageNum(), systemMessageVo.getPageSize());
+
+        LambdaQueryWrapper<SystemMessage> systemMessageSql = new LambdaQueryWrapper<SystemMessage>()
+                .eq(SystemMessage::getReceiverId, systemMessageVo.getUserId())
+                .orderByDesc(SystemMessage::getSendTime);
+        if (StringUtils.isNotEmpty(systemMessageVo.getMsgType())) {
+            systemMessageSql.eq(SystemMessage::getType, systemMessageVo.getMsgType());
+        }
+        List<SystemMessage> systemMessageList = list(systemMessageSql);
+
+        systemMessageList.stream()
+                .filter(message -> !StringUtils.isNullOrEmpty(message))
+                .forEach(message -> {
+                    message.setClassify(MessageConstants.getMessageByTypeAndCode(message.getClassify(), "CLASSIFY"));
+                    message.setType(MessageConstants.getMessageByTypeAndCode(message.getType(), "TYPE"));
+                    SystemMessageDTO systemMessageDTO = new SystemMessageDTO();
+                    BeanUtils.copyProperties(message, systemMessageDTO);
+                    systemMessageDTOList.add(systemMessageDTO);
+                });
+
+        log.info("获取站内信出参:{}", JSONObject.toJSONString(systemMessageDTOList));
+
+        return new PageInfo<>(systemMessageDTOList);
+    }
+
+    @Override
+    public void addSystemMessageList(List<SystemMessage> systemMessageList){
+        log.info("新增站内信入参:{}", JSONObject.toJSONString(systemMessageList));
+        try {
+            if (ObjectUtils.isNotEmpty(systemMessageList) && !systemMessageList.isEmpty()) {
+                saveBatch(systemMessageList);
+                sendMessageServer.realTime(systemMessageList);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            log.error(e.getMessage());
+        }
+    }
+
+    @Override
+    public void updateSystemMessageByUser(Integer id){
+        log.info("标记已读站内信入参:{}", id);
+        SystemMessage systemMessage = new SystemMessage();
+        systemMessage.setId(id);
+        systemMessage.setState("1");
+        if (ObjectUtils.isNotEmpty(id))
+            this.baseMapper.updateById(systemMessage);
+    }
+
+
+    @Override
+    public String makeMessage(String template, Map<String, String> map, String defV) {
+        Pattern pattern = Pattern.compile("\\$\\{[^}]+}");
+        Matcher matcher = pattern.matcher(template);
+        // 如果模板中没有参数。则直接返回
+        if (!matcher.find()) {
+            return template;
+        }
+        // 重置匹配模式
+        matcher.reset();
+        // 开始正则匹配
+        StringBuffer message = new StringBuffer();
+        while (matcher.find()) {
+            String group = matcher.group();
+            if (map.get(group) == null) {
+                continue;
+            }
+            matcher.appendReplacement(message, map.get(group));
+        }
+        matcher.appendTail(message);
+        Matcher m1 = pattern.matcher(message.toString());
+        // 替换成功或者默认内容为空,则返回
+        if (!m1.find() || StringUtils.isNullOrEmpty(defV)) {
+            return message.toString();
+        }
+        // 替换失败,返回默认值
+        return defV;
+    }
+}

+ 25 - 0
src/main/resources/mapper/modules/message/SystemMessageMapper.xml

@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.ydtech.modules.message.dao.SystemMessageMapper">
+
+    <resultMap id="BaseResultMap" type="com.ydtech.modules.message.entity.SystemMessage">
+        <id property="id" column="id"/>
+        <result property="classify" column="classify"/>
+        <result property="type" column="type"/>
+        <result property="title" column="title"/>
+        <result property="content" column="content"/>
+        <result property="jump" column="jump"/>
+        <result property="jumpUrl" column="jump_url"/>
+        <result property="receiverId" column="receiver_id"/>
+        <result property="senderId" column="sender_id"/>
+        <result property="state" column="state"/>
+        <result property="highLight" column="high_light"/>
+        <result property="sendTime" column="send_time"/>
+        <result property="createTime" column="create_time"/>
+        <result property="createBy" column="create_by"/>
+        <result property="updateTime" column="update_time"/>
+        <result property="updateBy" column="update_by"/>
+    </resultMap>
+
+
+</mapper>

+ 26 - 0
src/main/resources/mapper/modules/userRole/SysUserRoleMapper.xml

@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.ydtech.modules.admin.dao.SysUserRoleMapper">
+
+    <resultMap id="BaseResultMap" type="com.ydtech.modules.admin.model.SysUserRole">
+        <id property="id" column="id" />
+        <result property="userId" column="user_id" />
+        <result property="roleId" column="role_id"/>
+        <result property="createBy" column="create_by" />
+        <result property="createTime" column="create_time"/>
+        <result property="lastUpdateBy" column="last_update_by"/>
+        <result property="lastUpdateTime" column="last_update_time"/>
+    </resultMap>
+
+    <select id="selectBymenuId" resultMap="BaseResultMap">
+        SELECT
+            sur.user_id,
+            sur.role_id
+        FROM
+            sys_user_role sur
+                LEFT JOIN sys_role_menu srm ON sur.role_id = srm.role_id
+        WHERE
+            srm.menu_id = #{menuId}
+    </select>
+
+</mapper>