wlzboy
4 天以前 cfe0b79fbea0fb1d7a5a796e71ada7d3b7812046
feat: 企业微信发送微信小程序cetd
12个文件已修改
199 ■■■■■ 已修改文件
app/App.vue 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/pages/login.vue 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/pages/qylogin.vue 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/permission.js 19 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/utils/auth.js 14 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/VehicleMileageStatsController.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-admin/src/main/resources/application.yml 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/java/com/ruoyi/system/listener/TaskMessageListener.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/java/com/ruoyi/system/service/IQyWechatService.java 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/NotifyDispatchServiceImpl.java 19 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/QyWechatServiceImpl.java 100 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysTaskServiceImpl.java 13 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/App.vue
@@ -28,7 +28,7 @@
        if (token) {
          this.lastToken = token
          this.updateUnreadMessageBadge()
          this.startMessagePolling()
          // this.startMessagePolling()
        }
      })
      
app/pages/login.vue
@@ -340,6 +340,12 @@
          // 检查是否有redirect参数指定跳转页面
          let redirectUrl = this.getUrlParam("redirect");
          
          // 如果没有redirect参数,检查是否有保存的目标页面
          if (!redirectUrl) {
            const { getTargetUrl } = require('@/utils/auth')
            redirectUrl = getTargetUrl()
          }
          if (redirectUrl) {
            // 解码redirect参数
            redirectUrl = decodeURIComponent(redirectUrl);
app/pages/qylogin.vue
@@ -223,6 +223,12 @@
        // 检查是否有redirect参数指定跳转页面
        let redirectUrl = this.getUrlParam("redirect");
        
        // 如果没有redirect参数,检查是否有保存的目标页面
        if (!redirectUrl) {
          const { getTargetUrl } = require('@/utils/auth')
          redirectUrl = getTargetUrl()
        }
        if (redirectUrl) {
          // 解码redirect参数
          redirectUrl = decodeURIComponent(redirectUrl);
app/permission.js
@@ -19,20 +19,39 @@
  return whiteList.indexOf(path) !== -1
}
// 保存目标页面URL,用于登录后跳转
function saveTargetUrl(url) {
  try {
    uni.setStorageSync('targetUrl', url)
  } catch (e) {
    console.error('保存目标URL失败:', e)
  }
}
// 页面跳转验证拦截器
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"]
list.forEach(item => {
  uni.addInterceptor(item, {
    invoke(to) {
      if (getToken()) {
        // 已登录
        if (to.url === loginPage) {
          // 如果已经登录还要访问登录页,直接跳转到首页
          uni.reLaunch({ url: "/" })
          return false
        }
        return true
      } else {
        // 未登录
        if (checkWhite(to.url)) {
          // 白名单页面可以直接访问
          return true
        }
        // 保存当前要访问的页面作为登录后跳转的目标
        saveTargetUrl(to.url)
        // 跳转到登录页面
        uni.reLaunch({ url: loginPage })
        return false
      }
app/utils/auth.js
@@ -11,3 +11,17 @@
export function removeToken() {
  return uni.removeStorageSync(TokenKey)
}
// 获取并清除目标页面URL
export function getTargetUrl() {
  try {
    const url = uni.getStorageSync('targetUrl')
    if (url) {
      uni.removeStorageSync('targetUrl')
    }
    return url
  } catch (e) {
    console.error('获取目标URL失败:', e)
    return null
  }
}
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/VehicleMileageStatsController.java
@@ -114,7 +114,7 @@
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setLenient(false); // 严格解析日期
            Date date = sdf.parse(statDate.trim());
            logger.info("---> 手动计算车辆里程汇总,车辆ID: {}, 日期: {}", vehicleId, date);
//            logger.info("---> 手动计算车辆里程汇总,车辆ID: {}, 日期: {}", vehicleId, date);
            VehicleMileageStats stats = vehicleMileageStatsService.calculateAndSaveMileageStats(vehicleId, date);
            // 修复String到Date转换问题,添加更好的错误处理
            if (stats != null) {
ruoyi-admin/src/main/resources/application.yml
@@ -58,7 +58,7 @@
    basename: i18n/messages
  profiles:
    # 环境 dev|test|prod
    active: prod
    active: dev
  # 文件上传
  servlet:
    multipart:
ruoyi-system/src/main/java/com/ruoyi/system/listener/TaskMessageListener.java
@@ -260,7 +260,7 @@
            departure = task.getDepartureAddress();
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        content.append(",出发时间:").append(df.format(dispatchTime));
        content.append(",出发时间:").append(df.format(dispatchTime));
        // 添加目的地信息
        String destination = null;
@@ -271,7 +271,6 @@
        }
        
        if (departure != null || destination != null) {
            content = new StringBuilder();
            if (departure != null) {
                content.append("出发地:").append(departure);
            }
ruoyi-system/src/main/java/com/ruoyi/system/service/IQyWechatService.java
@@ -19,6 +19,17 @@
    boolean sendNotifyMessage(Long userId, String title, String content, String notifyUrl);
    /**
     * 发送企业微信消息,带小程序路径链接
     * @param userId
     * @param title
     * @param content
     * @param appId
     * @param businessUrl 小程序访问路径
     * @return
     */
    boolean sendNotifyMessage(Long userId, String title, String content, String appId,String businessUrl);
    /**
     * 发送企业微信文本消息
     * 
     * @param qyUserId 企业微信用户ID
@@ -29,6 +40,8 @@
     */
    boolean sendTextMessage(String qyUserId, String title, String content, String notifyUrl);
    boolean sendTextMessage(String qyUserId, String title, String content, String appId,String businessUrl);
    /**
     * 获取用户的企业微信ID
     * 
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/NotifyDispatchServiceImpl.java
@@ -1,6 +1,7 @@
package com.ruoyi.system.service.impl;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.WechatConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
@@ -49,6 +50,9 @@
    @Autowired
    private IQyWechatService qyWechatService;
    @Autowired
    private WechatConfig wechatConfig;
    @Autowired
    private ISysEmergencyTaskService sysEmergencyTaskService;
@@ -348,17 +352,18 @@
           if(emergency==null){
               return false;
           }
           Long dispatchOrderId = emergency.getLegacyDispatchOrdId();
          String oldsiteUrl= sysConfigService.selectConfigByKey("oldsite.url");
          if(oldsiteUrl==null){
              oldsiteUrl="https://sys.966120.com.cn/m_DispatchOrder.gds?DispatchOrdID=";
          }
           String url=oldsiteUrl+dispatchOrderId;
//           Long dispatchOrderId = emergency.getLegacyDispatchOrdId();
//          String oldsiteUrl= sysConfigService.selectConfigByKey("oldsite.url");
//          if(oldsiteUrl==null){
//              oldsiteUrl="https://sys.966120.com.cn/m_DispatchOrder.gds?DispatchOrdID=";
//          }
            String appId=wechatConfig.getAppId();
           String pathPage="/pagesTask/detail?id="+taskId;
            // 发送企业微信消息
            boolean success = qyWechatService.sendNotifyMessage(
                    notifyTask.getUserId(), 
                    notifyTask.getTitle(), 
                    notifyTask.getContent(),url
                    notifyTask.getContent(),appId,pathPage
            );
            
            if (success) {
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/QyWechatServiceImpl.java
@@ -65,6 +65,30 @@
        }
    }
    @Override
    public boolean sendNotifyMessage(Long userId, String title, String content, String appId, String businessUrl) {
        try {
            // 检查服务是否启用
            if (!isEnabled()) {
                log.info("企业微信服务未启用,跳过消息发送");
                return false;
            }
            // 获取用户的企业微信ID
            String qyUserId = getQyUserIdByUserId(userId);
            if (StringUtils.isEmpty(qyUserId)) {
                log.warn("用户{}未绑定企业微信ID,无法发送消息", userId);
                return false;
            }
            // 发送文本消息
            return sendTextMessage(qyUserId, title, content, appId, businessUrl);
        } catch (Exception e) {
            log.error("企业微信消息发送异常,userId={}", userId, e);
            return false;
        }
    }
    /**
     * 发送企业微信文本消息
     */
@@ -101,6 +125,7 @@
            article.setTitle(title);
            article.setDescription(content);
            article.setUrl(notifyUrl);
            // 设置默认图片URL,您可以根据需要修改
            
@@ -141,6 +166,81 @@
        }
    }
    @Override
    public boolean sendTextMessage(String qyUserId, String title, String content, String appId, String businessUrl) {
        try {
            // 检查服务是否启用
            if (!isEnabled()) {
                log.info("企业微信服务未启用,跳过消息发送");
                return false;
            }
            // 获取企业微信配置
            String corpId = configService.selectConfigByKey("qy_wechat.corp_id");
            String corpSecret = configService.selectConfigByKey("qy_wechat.miniprogram_secret");
            if (StringUtils.isEmpty(corpId) || StringUtils.isEmpty(corpSecret)) {
                log.error("企业微信配置不完整,缺少corpId或corpSecret");
                return false;
            }
            // 获取AccessToken
            String accessToken = qyWechatAccessTokenService.getQyMiniAccessToken(corpId, corpSecret);
            if (StringUtils.isEmpty(accessToken)) {
                log.error("获取企业微信AccessToken失败");
                return false;
            }
            // 构造请求URL
            String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
            // 构造文章对象
            QyWechatArticle article = new QyWechatArticle();
            article.setTitle(title);
            article.setDescription(content);
            article.setAppid(appId);
            article.setPagepath(businessUrl);
            // 设置默认图片URL,您可以根据需要修改
            // 构造请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("touser", qyUserId);
            params.put("msgtype", "news");
            params.put("agentid", Integer.parseInt(configService.selectConfigByKey("qywechat.miniprogram.agentid")));
            // 构造文章列表
            List<QyWechatArticle> articles = new ArrayList<>();
            articles.add(article);
            params.put("news", Collections.singletonMap("articles", articles));
            // 发送HTTP POST请求
            String response = sendHttpPostRequest(url, params);
            if (StringUtils.isEmpty(response)) {
                log.error("发送企业微信消息失败,响应为空");
                return false;
            }
            // 解析响应结果
            QyWechatResponse result = parseResponse(response);
            if (result != null && result.getErrcode() == 0) {
                log.info("企业微信消息发送成功,用户ID: {}", qyUserId);
                return true;
            } else {
                log.error("企业微信消息发送失败,错误码: {}, 错误信息: {}",
                        result != null ? result.getErrcode() : "unknown",
                        result != null ? result.getErrmsg() : response);
                return false;
            }
        } catch (Exception e) {
            log.error("企业微信文本消息发送异常,qyUserId={}", qyUserId, e);
            return false;
        }
    }
    /**
     * 获取用户的企业微信ID
     */
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysTaskServiceImpl.java
@@ -532,6 +532,11 @@
                }
            }
        }
        if(updateVO.getAssignees()!=null && !updateVO.getAssignees().isEmpty()){
           TaskCreateVO.AssigneeInfo assigneeInfo= updateVO.getAssignees().get(0);
            task.setAssigneeId(assigneeInfo.getUserId());
            task.setAssigneeName(assigneeInfo.getUserName());
        }
        // 用于跟踪是否需要重新同步(车辆、人员、地址、成交价变更)
        boolean needResync = false;
        int result = sysTaskMapper.updateSysTask(task);
@@ -629,7 +634,7 @@
        if(updateVO.getActualEndTime() != null) {
            task.setActualEndTime(updateVO.getActualEndTime());
        }
        task.setAssigneeId(updateVO.getAssigneeId());
//        task.setAssigneeId(updateVO.getAssigneeId());
        task.setUpdateBy(userName);
        task.setUpdateTime(DateUtils.getNowDate());
        task.setRemark(updateVO.getRemark());
@@ -642,7 +647,11 @@
        task.setDepartureLatitude(updateVO.getDepartureLatitude());
        task.setDestinationLongitude(updateVO.getDestinationLongitude());
        task.setDestinationLatitude(updateVO.getDestinationLatitude());
        if(updateVO.getAssignees()!=null && !updateVO.getAssignees().isEmpty()){
            TaskCreateVO.AssigneeInfo assigneeInfo= updateVO.getAssignees().get(0);
            task.setAssigneeId(assigneeInfo.getUserId());
            task.setAssigneeName(assigneeInfo.getUserName());
        }
        // 如果更新了部门ID
        if (updateVO.getDeptId() != null) {
            task.setDeptId(updateVO.getDeptId());