提交 e3061b1c 编写于 作者: 孙喜旺

Merge remote-tracking branch 'origin/back_end_dev_1.0' into back_end_dev_1.0

# Conflicts:
#	linkwe-wecom/src/main/java/com/linkwechat/wecom/factory/impl/party/WeCallBackCreatePartyImpl.java
#	linkwe-wecom/src/main/java/com/linkwechat/wecom/service/IWeDepartmentService.java
#	linkwe-wecom/src/main/java/com/linkwechat/wecom/service/impl/WeDepartmentServiceImpl.java
......@@ -7,8 +7,11 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableAsync;
import java.io.IOException;
/**
* 启动程序
*
......@@ -20,7 +23,7 @@ import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@EnableDiscoveryClient
public class LinkWeChatApplication {
public static void main(String[] args) {
public static void main(String[] args){
SpringApplication.run(LinkWeChatApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ LinkWeChat启动成功 ლ(´ڡ`ლ)゙ \n" +
......
package com.linkwechat.web.controller.wecom;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkwechat.common.constant.Constants;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.core.domain.model.LoginUser;
import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.common.utils.Threads;
import com.linkwechat.common.utils.wecom.WxCryptUtil;
import com.linkwechat.framework.web.service.SysLoginService;
import com.linkwechat.web.controller.common.CommonController;
import com.linkwechat.wecom.domain.vo.WxCpXmlMessageVO;
import com.linkwechat.wecom.factory.WeCallBackEventFactory;
import com.linkwechat.wecom.factory.WeEventHandle;
import com.linkwechat.wecom.service.IWeCorpAccountService;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.AnyTypePermission;
import lombok.extern.slf4j.Slf4j;
......@@ -14,6 +23,7 @@ import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
......@@ -28,56 +38,86 @@ import javax.servlet.http.HttpServletRequest;
@RequestMapping("/wecom/callback")
public class WeCallBackController extends CommonController {
@Autowired
private WeEventHandle weEventHandle;
WeEventHandle weEventHandle;
@Autowired
IWeCorpAccountService iWeCorpAccountService;
@Autowired
SysLoginService sysLoginService;
@Value("${wecome.callBack.appIdOrCorpId}")
private String appIdOrCorpId;
@Value("${wecome.callBack.token}")
private String token;
@Value("${wecome.callBack.encodingAesKey}")
private String encodingAesKey;
@PostMapping(value = "/recive")
public String recive(@RequestBody String msg, @RequestParam(name = "msg_signature") String signature,
String timestamp, String nonce) {
WxCryptUtil wxCryptUtil = new WxCryptUtil(token, encodingAesKey, appIdOrCorpId);
try {
String decrypt = wxCryptUtil.decrypt(signature, timestamp, nonce, msg);
WxCpXmlMessageVO wxCpXmlMessage = StrXmlToBean(decrypt);
log.info("企微回调通知接口 wxCpXmlMessage:{}", JSONObject.toJSONString(wxCpXmlMessage));
public String recivePost(@RequestBody String msg, @RequestParam(name = "msg_signature") String signature,
String timestamp, String nonce,String corpId) {
if(StrUtil.isEmpty(corpId)){
return "error";
}
WeCorpAccount weCorpAccount = iWeCorpAccountService.getOne(new LambdaQueryWrapper<WeCorpAccount>()
.eq(WeCorpAccount::getCorpId, corpId)
.eq(WeCorpAccount::getStatus, Constants.NORMAL_CODE)
.eq(WeCorpAccount::getDelFlag, Constants.NORMAL_CODE));
if(null != weCorpAccount){
// //校验当前租户账号是否授权登录了,如果未登录,则无密钥登录
// LoginUser loginUser
// = SecurityUtils.getLoginUser();
// if(null == loginUser){
// sysLoginService.noPwdLogin(weCorpAccount.getCorpAccount());
// }
WxCryptUtil wxCryptUtil = new WxCryptUtil(weCorpAccount.getToken(), weCorpAccount.getEncodingAesKey(), weCorpAccount.getCorpId());
try {
WeCallBackEventFactory factory = weEventHandle.factory(wxCpXmlMessage.getEvent());
if (factory !=null){
Threads.SINGLE_THREAD_POOL.submit(() -> factory.eventHandle(wxCpXmlMessage));
String decrypt = wxCryptUtil.decrypt(signature, timestamp, nonce, msg);
WxCpXmlMessageVO wxCpXmlMessage = StrXmlToBean(decrypt);
log.info("企微回调通知接口 wxCpXmlMessage:{}", JSONObject.toJSONString(wxCpXmlMessage));
try {
WeCallBackEventFactory factory = weEventHandle.factory(wxCpXmlMessage.getEvent());
if (factory !=null){
Threads.SINGLE_THREAD_POOL.submit(() -> factory.eventHandle(wxCpXmlMessage));
}
} catch (Exception e) {
e.printStackTrace();
}
return decrypt;
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();;
String sRespData = WxCryptUtil.getTextRespData("success");
return wxCryptUtil.encrypt(sRespData);
}
return decrypt;
} catch (Exception e) {
e.printStackTrace();;
String sRespData = WxCryptUtil.getTextRespData("success");
return wxCryptUtil.encrypt(sRespData);
}
return "error";
}
@GetMapping(value = "/recive")
public String recive(HttpServletRequest request) {
// 微信加密签名
String sVerifyMsgSig = request.getParameter("msg_signature");
// 时间戳
String sVerifyTimeStamp = request.getParameter("timestamp");
// 随机数
String sVerifyNonce = request.getParameter("nonce");
// 随机字符串
String sVerifyEchoStr = request.getParameter("echostr");
WxCryptUtil wxCryptUtil = new WxCryptUtil(token, encodingAesKey, appIdOrCorpId);
try {
return wxCryptUtil.verifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);
} catch (Exception e) {
public String reciveGet(String msg_signature,String timestamp,String nonce,String echostr, String corpId) {
if(StrUtil.isEmpty(corpId)){
return "error";
}
WeCorpAccount weCorpAccount = iWeCorpAccountService.getOne(new LambdaQueryWrapper<WeCorpAccount>()
.eq(WeCorpAccount::getCorpId, corpId)
.eq(WeCorpAccount::getStatus, Constants.NORMAL_CODE)
.eq(WeCorpAccount::getDelFlag, Constants.NORMAL_CODE));
if(null != weCorpAccount){
WxCryptUtil wxCryptUtil = new WxCryptUtil(weCorpAccount.getToken(), weCorpAccount.getEncodingAesKey(), weCorpAccount.getCorpId());
try {
return wxCryptUtil.verifyURL(msg_signature, timestamp, nonce, echostr);
} catch (Exception e) {
return "error";
}
}
return "error";
}
private WxCpXmlMessageVO StrXmlToBean(String xmlStr){
......
......@@ -229,7 +229,7 @@ public class WeTaskFissionController extends BaseController {
public AjaxResult<JSONObject> upload(@RequestParam(value = "file") MultipartFile file) throws IOException {
String url = FileUploadUtils.upload2Cos(file, cosConfig);
JSONObject json = new JSONObject();
json.put("rewardImageUrl", cosConfig.getImgUrlPrefix()+url);
json.put("rewardImageUrl", cosConfig.getCosImgUrlPrefix()+url);
return AjaxResult.success(json);
}
......
......@@ -12,15 +12,20 @@ ruoyi:
# 是否开启文件云上传(使用的是腾讯云,如果开启了,则需要配置腾讯云存储相关信息;如果关闭了则文件存储再本地,需要配置本地路径)
file:
startCosUpload: true
#图片在系统中的访问前缀,图片无论是上传云端还是服务器本地,都通过本地读取资源,然后返回前端
imgUrlPrefix:
#腾讯云对象存储
cos:
#id
secretId:
#密钥
secretKey:
#地区
region:
#区块空间
bucketName:
# 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /app/project/pic)
#profile: /data/jenkins_home/app/project/
#访问前缀
cosImgUrlPrefix:
# 获取ip地址开关
addressEnabled: false
# 验证码类型 math 数组计算 char 字符验证
......@@ -59,7 +64,7 @@ ruoyi:
- /wecom/community/h5/**
- /weixin/auth/**
- /wecom/material/temporaryMaterialMediaId
- /common/findImage
# 开发环境配置
server:
# 服务器的HTTP端口,默认为8090
......@@ -80,15 +85,9 @@ logging:
level:
com.ruoyi: debug
org.springframework: warn
path: ./logs
path:
log: ./logs
#H5地址路径
H5:
url:
fissionUrl:
fissionGroupUrl:
# Spring配置
spring:
# 资源信息
......@@ -101,7 +100,7 @@ spring:
druid:
# 主库数据源
master:
url: jdbc:mysql://127.0.0.1:10179/lw-test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
url: jdbc:mysql://127.0.0.1:10179/link-wechat?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: root
# 从库数据源
......@@ -210,14 +209,6 @@ mybatis-plus:
logic-delete-value: 1
logic-not-delete-value: 0
## MyBatis配置
#mybatis:
# # 搜索指定包别名
# typeAliasesPackage: com.linkwechat.**.domain
# # 配置mapper的扫描,找到所有的mapper.xml映射文件
# mapperLocations: classpath*:mapper/**/*Mapper.xml
# # 加载全局的配置文件
# configLocation: classpath:mybatis/mybatis-config.xml
# PageHelper分页插件
pagehelper:
......@@ -246,8 +237,8 @@ xss:
elasticsearch:
schema: http
address:
userName:
password:
userName: "elastic"
password: "0p-0p-0p-"
connectTimeout: 10000
socketTimeout: 10000
connectionRequestTimeout: 10000
......@@ -264,7 +255,6 @@ forest:
wecome:
chatKey: finance_new
serverUrl: https://qyapi.weixin.qq.com/
weComePrefix: cgi-bin
noAccessTokenUrl:
......@@ -320,16 +310,8 @@ wecome:
- we_user
- we_customer
- we_tag_group
#企微回调通知配置
callBack:
appIdOrCorpId:
token:
encodingAesKey:
# JS SDK 身份校验url
authorizeUrl:
# JS SDK身份校验成功后的redirect url
authorizeRedirectUrl:
weixin:
appid:
secret:
\ No newline at end of file
spring.cloud.nacos.config.server-addr=${NACOS_SERVER:119.45.28.29:10848}
spring.cloud.nacos.config.namespace=01cf833f-249e-4483-a286-46d37f018fe7
spring.cloud.nacos.config.namespace=627a666a-76b2-42ad-a1b0-70a12d2c73fd
spring.application.name=link-wechat
spring.cloud.nacos.config.file-extension=yaml
spring.cloud.nacos.config.enabled=false
\ No newline at end of file
spring.cloud.nacos.config.enabled=true
\ No newline at end of file
......@@ -20,6 +20,6 @@ public class CosConfig {
private String bucketName;
private String imgUrlPrefix;
private String cosImgUrlPrefix;
}
......@@ -34,7 +34,7 @@ public class BaseEntity implements Serializable
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(hidden = true)
private Date createTime=new Date();
private Date createTime;
/** 更新者 */
@ApiModelProperty(hidden = true)
......@@ -43,7 +43,7 @@ public class BaseEntity implements Serializable
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(hidden = true)
private Date updateTime=new Date();
private Date updateTime;
/** 备注 */
@TableField(exist = false)
......
......@@ -56,7 +56,7 @@ public class WeCorpAccount extends BaseEntity
/** 删除标志(0代表存在 2代表删除) */
@ApiModelProperty("删除标志(0代表存在 2代表删除)")
private String delFlag=new String("0");
private String delFlag;
@ApiModelProperty("外部联系人密钥")
......@@ -85,4 +85,38 @@ public class WeCorpAccount extends BaseEntity
@ApiModelProperty("企业管理员账号")
private String corpAccount;
@ApiModelProperty("应用回调token密钥")
private String token;
@ApiModelProperty("应用回调消息体加密密钥")
private String encodingAesKey;
@ApiModelProperty("微信公众号APPID")
private String appId;
@ApiModelProperty("微信公众号密钥")
private String secret;
@ApiModelProperty("任务宝H5访问地址")
private String fissionUrl;
@ApiModelProperty("群裂变H5访问地址")
private String fissionGroupUrl;
@ApiModelProperty("会话私钥")
private String financePrivateKey;
}
package com.linkwechat.common.utils;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
......@@ -224,4 +225,31 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
public static Long strToDate(int days, Integer type) {
Long time = null;
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
Calendar cale = Calendar.getInstance();
cale.add(Calendar.DATE, days);
String tarday = new SimpleDateFormat("yyyy-MM-dd").format(cale.getTime());
if (type.equals(0)) {
tarday += " 00:00:00";
} else {
tarday += " 23:59:59";
}
// String转Date
try {
date = format2.parse(tarday);
System.out.println(date.getTime());
time = date.getTime() / 1000;
System.out.println(time.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
}
......@@ -87,4 +87,8 @@ public class SecurityUtils
{
return userId != null && 1L == userId;
}
}
......@@ -261,13 +261,13 @@ public class WxCryptUtil {
SecretKeySpec keySpec = new SecretKeySpec(this.aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(this.aesKey, 0, 16));
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(cipherText);
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new WeComException(e.getMessage());
}
......
......@@ -2,7 +2,12 @@ package com.tencent.wework;
import com.linkwechat.common.utils.OsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
@Slf4j
public class Finance {
public native static long NewSdk();
......@@ -120,7 +125,12 @@ public class Finance {
System.loadLibrary("libcurl");
System.loadLibrary("WeWorkFinanceSdk");
} else {
System.load("/app/projects/libWeWorkFinanceSdk_Java.so");
try {
System.load( new ClassPathResource("lib/libWeWorkFinanceSdk_Java.so").getURI().getPath());
} catch (IOException e) {
log.error("linux下libWeWorkFinanceSdk_Java加载出错:"+e.getMessage());
}
// System.load("/app/projects/libWeWorkFinanceSdk_Java.so");
}
}
......
......@@ -30,7 +30,6 @@ import java.util.concurrent.atomic.AtomicLong;
* @date 2020/12/2 16:01
**/
@Slf4j
public class FinanceUtils {
/**
* NewSdk返回的sdk指针
......@@ -56,33 +55,6 @@ public class FinanceUtils {
}
}
private final static String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" +
"MIIEpAIBAAKCAQEAjGwIQIMGDJonMQdX3OJzZN0YVoYbORK1FU/8vhwdI9ixxSGW\n" +
"nrAQc6r8k3g1QTXzmKAxdVlAa1OGZCpl5X5A6C9JwDhFpuN+SKJxfxtHNv1oBk0r\n" +
"LnDftsdlibZFQn3fiMomxKyU8eujWBe31+pLQXaTSdSHcNhb+NrBa7AtNUr/c7bK\n" +
"nnFUZHDpXFB4Z0BhK1cRh2NN7ppLNnIJXpduGrwGtLdx++LsBaX2vjO4qW/DKP2Z\n" +
"3gZON1tGoofS1IPhCg0naoRN3lL7ctFAyxOr2ualGOc6hpvBGfjnBKU42aoaKQEi\n" +
"7tVJHChonZXMRcm4mdPu5371IzPeR3NYlP3ESQIDAQABAoIBAEux8MDV4GzqrDXB\n" +
"v5tSduHoTTZXFFWvv+29MIFKpmqsZSfe81KXlkbD5WOZaRu9+ZJMyFx5wEAaxlc4\n" +
"g7UyWcrPsvHrY6CTAYAmEQhzq+/4qhq7fouKTQ46boHNv4gYUmdqkXtzjNbcLzFN\n" +
"l8zMf8TKJpul9VzfRLThN2LVlYkkETcCukzZrK+aSCi6E/dL+noL1ndZYmWF5kbB\n" +
"lk881x5CdbusYBtoxfh6ie0EXfCyK4duX3OdvXRcSpTdqiqTcrtt9oinh4ZHV930\n" +
"BCTPkGGz5UL3C243W3dlzuonNXqwl++FCSyRMVONYSgb4NRJn4fvehjGtXyAv3Sz\n" +
"nSAVoAECgYEA9dhYk4DT2Hclaqo/0ugQvUp7oIPN9qFgrZ6nU94SHkdrBqhFrCmz\n" +
"32GeYGSsQJQx3T9Kuip7oGX9AOKn3f30NrcuAe9VzzWAkCKQgQgmtMVySAPWCVr9\n" +
"4MH77hc3ijxr6iGd70BQ7EDyVQGRvZqOLl1wu7yZ9vhbVHA87KpgHf0CgYEAkjjn\n" +
"mNudh+rs8ibrGu+md8bXJdxHtIbncXF5VsV7wi4HlHfKnWqy+z2If1akm2iacnsi\n" +
"XDVqyYNExdtoxmbPc/R9ZJ8jP0FLPoWACcjP03r9H+5eiXrmniZbElGshnwKHFFh\n" +
"ZlY1xPAXFgEjh10DDG1wK6/9eB13o+NdP7c7yz0CgYEA3HujNOadF84DaJ43j1dB\n" +
"bAKYzWRoG4CvzAY12ymW5kD244mWssjT4MsT1y9yrJg8AEj7I+tl5HyTY2/jTVys\n" +
"4UV3pZSYSLWbD6lwH8jHrehGjf+ivdE1T5Wp8+YukXOO9PQhSKlN6hR1QXee1YT/\n" +
"buWubTDAhJZIknn2qepDOaECgYA/OnITLCwTYOey0ldpn2V5d7cC/RzYmFkuOeZB\n" +
"OkYIsoS+k4o+xau9bl8+yQWG2hWnGU3DV6nkl2m+sOC+oihkuL0cLKA+MwrJb0rt\n" +
"cDNF/HHGQ/oHMujUTDunUT/sK2jn09ztNqwri7I/5qApYXP3BL+zdHeDYCKi8Kca\n" +
"7S3i9QKBgQCgKgQf8u+oRojMH14iJssAyNEhZgmJ85s/BeiUmMuW5K8iZZ5pnVuq\n" +
"8nc/IJGVPHRTObdGCd1L4d5UERiX46Z1BjYv/nuK5DScDcB3mq6K9VXJLNE+MxwW\n" +
"wOVT+6FjmBRucGXczAkWXCH7++y6gYzE+OuRIdv5sVkE24gNG7sawg==\n" +
"-----END RSA PRIVATE KEY-----";
/**
* 拉取聊天记录
......@@ -90,8 +62,9 @@ public class FinanceUtils {
* @param seq 消息的seq值,标识消息的序号
* @param proxy 代理
* @param passwd 密码
* @param privateKey 私钥
*/
public static List<JSONObject> getChatData(long seq, String proxy, String passwd, RedisCache redisCache) {
public static List<JSONObject> getChatData(long seq, String proxy, String passwd, RedisCache redisCache,String privateKey) {
List<JSONObject> resList = new ArrayList<>();
long slice = Finance.NewSlice();
int ret = Finance.GetChatData(sdk, seq, WeConstans.LIMIT, proxy, passwd, timeout, slice);
......@@ -286,7 +259,7 @@ public class FinanceUtils {
getMediaData(sdkfileid, "", "", filePath, fileName);
CosConfig cosConfig = SpringUtils.getBean(CosConfig.class);
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
StringBuilder cosUrl = new StringBuilder(cosConfig.getImgUrlPrefix());
StringBuilder cosUrl = new StringBuilder(cosConfig.getCosImgUrlPrefix());
String cosFilePath = FileUploadUtils.upload2Cos(new FileInputStream(new File(filePath, fileName)), suffix, cosConfig);
cosUrl.append(cosFilePath);
data.put("attachment", cosUrl.toString());
......
......@@ -7,6 +7,7 @@ import com.github.pagehelper.PageInterceptor;
import com.linkwechat.common.config.RuoYiConfig;
import com.linkwechat.common.config.WeComeConfig;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.core.domain.model.LoginUser;
import com.linkwechat.common.utils.SecurityUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
......@@ -44,11 +45,15 @@ public class MyBatisPlusConfig {
public Expression getTenantId() {
try {
WeCorpAccount weCorpAccount
= SecurityUtils.getLoginUser().getUser().getWeCorpAccount();
if(null != weCorpAccount){
return new StringValue(weCorpAccount.getCorpId());
LoginUser loginUser = SecurityUtils.getLoginUser();
if(null != loginUser){
WeCorpAccount weCorpAccount
= loginUser.getUser().getWeCorpAccount();
if(null != weCorpAccount){
return new StringValue(weCorpAccount.getCorpId());
}
}
}catch (Exception e){
return null;
}
......
package com.linkwechat.quartz.task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @description: 客户画像
* @author: HaoN
* @create: 2021-05-02 21:08
**/
@Slf4j
@Component("customerPortraitTask")
public class CustomerPortraitTask {
}
package com.linkwechat.quartz.task;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.core.elasticsearch.ElasticSearch;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.domain.WeCustomer;
import com.linkwechat.wecom.domain.WeCustomerMessageTimeTask;
import com.linkwechat.wecom.mapper.WeCustomerMessageTimeTaskMapper;
import com.linkwechat.wecom.service.*;
import com.tencent.wework.FinanceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicLong;
/**
* 定时任务调度测试
*
* @author ruoyi
*/
* @description: 会话存档定时拉取
* @author: HaoN
* @create: 2021-05-31 10:39
**/
@Slf4j
@Component("ryTask")
public class RyTask {
@Autowired
private ElasticSearch elasticSearch;
@Autowired
private RedisCache redisCache;
@Component("FinanceTask")
public class FinanceTask {
@Autowired
private IWeChatContactMappingService weChatContactMappingService;
ElasticSearch elasticSearch;
@Autowired
private IWeSensitiveService weSensitiveService;
RedisCache redisCache;
@Autowired
private IWeSensitiveActHitService weSensitiveActHitService;
IWeChatContactMappingService weChatContactMappingService;
@Autowired
private IWeCustomerService weCustomerService;
IWeSensitiveService weSensitiveService;
@Autowired
private WeCustomerMessageTimeTaskMapper customerMessageTimeTaskMapper;
IWeSensitiveActHitService weSensitiveActHitService;
@Autowired
private IWeCustomerMessageService weCustomerMessageService;
IWeCorpAccountService iWeCorpAccountService;
@Value("${wecome.chatKey}")
private String chartKey;
public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i));
}
/**
* 会话数据拉取
* @throws IOException
*/
public void FinanceTask(){
List<WeCorpAccount> weCorpAccounts = iWeCorpAccountService.list(
new LambdaQueryWrapper<WeCorpAccount>()
.eq(WeCorpAccount::getDelFlag, 1)
.eq(WeCorpAccount::getStatus, 1)
);
if(CollectionUtil.isNotEmpty(weCorpAccounts)){
weCorpAccounts.stream().forEach(k->{
try {
if(StrUtil.isNotBlank(k.getCorpId()) && StrUtil.isNotBlank(k.getSecret())){
findFinance(k.getCorpId(),k.getSecret(),"ChartKey_"+k.getCorpId(),k.getFinancePrivateKey());
}
} catch (IOException e) {
e.printStackTrace();
}
});
public void ryParams(String params) {
System.out.println("执行有参方法:" + params);
}
}
public void ryNoParams() {
System.out.println("执行无参方法");
}
public void FinanceTask(String corpId, String secret) throws IOException {
private void findFinance(String corpId, String secret,String chartKey,String financePrivateKey) throws IOException {
log.info("执行有参方法: params:{},{}", corpId, secret);
//创建索引
elasticSearch.createIndex2(chartKey, elasticSearch.getFinanceMapping());
//从缓存中获取消息标识
Object seqObject = Optional.ofNullable(redisCache.getCacheObject(WeConstans.CONTACT_SEQ_KEY)).orElse(0L);
Object seqObject = Optional.ofNullable(redisCache.getCacheObject(chartKey+"::"+WeConstans.CONTACT_SEQ_KEY)).orElse(0L);
Long seqLong = Long.valueOf(String.valueOf(seqObject));
AtomicLong index = new AtomicLong(seqLong);
if (index.get() == 0) {
setRedisCacheSeqValue(index);
setRedisCacheSeqValue(index,chartKey);
}
log.info(">>>>>>>seq:{}", index.get());
FinanceUtils.initSDK(corpId, secret);
List<JSONObject> chatDataList = FinanceUtils.getChatData(index.get(),
"",
"", redisCache);
"", redisCache,financePrivateKey);
if (CollectionUtil.isNotEmpty(chatDataList)) {
try {
List<JSONObject> elasticSearchEntities = weChatContactMappingService.saveWeChatContactMapping(chatDataList);
......@@ -100,24 +108,13 @@ public class RyTask {
e.printStackTrace();
}
}
}
public void WeCustomers() {
//查询系统所有客户
List<WeCustomer> cacheList = redisCache.getCacheList(WeConstans.WECUSTOMERS_KEY);
if (CollectionUtils.isEmpty(cacheList)) {
List<WeCustomer> customers = weCustomerService.selectWeCustomerList(null);
redisCache.setCacheList(WeConstans.WECUSTOMERS_KEY, customers);
} else {
List<WeCustomer> customers = weCustomerService.selectWeCustomerList(null);
List<WeCustomer> weCustomers = redisCache.getCacheList(WeConstans.WECUSTOMERS_KEY);
if (CollectionUtils.isNotEmpty(weCustomers) && weCustomers.size() < customers.size()) {
redisCache.setCacheList(WeConstans.WECUSTOMERS_KEY, customers);
}
}
}
private void setRedisCacheSeqValue(AtomicLong index) {
private void setRedisCacheSeqValue(AtomicLong index,String chartKey) {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
SortBuilder<?> sortBuilderPrice = SortBuilders.fieldSort(WeConstans.CONTACT_SEQ_KEY).order(SortOrder.DESC);
searchSourceBuilder.sort(sortBuilderPrice);
......@@ -128,49 +125,4 @@ public class RyTask {
});
redisCache.setCacheObject(WeConstans.CONTACT_SEQ_KEY, index);
}
/**
* @param corpId 企业id
* @param secret 会话密钥
*/
public void getPermitUserList(String corpId, String secret) {
log.info("执行有参方法: params:{},{}", corpId, secret);
}
/**
* 扫描群发消息定时任务
*/
public void messageTask() {
//获的当前时间的毫秒数
long currentTime = System.currentTimeMillis();
//customerMessageTimeTaskMapper
List<WeCustomerMessageTimeTask> weCustomerMessageTimeTasks = customerMessageTimeTaskMapper.selectWeCustomerMessageTimeTaskGteSettingTime(currentTime);
final Semaphore semaphore = new Semaphore(5);
if (CollectionUtils.isNotEmpty(weCustomerMessageTimeTasks)) {
weCustomerMessageTimeTasks.forEach(
s -> {
try {
semaphore.acquire();
if (s.getMessageInfo() != null && s.getMessageId() != null || (s.getMessageInfo().getPushType().equals(WeConstans.SEND_MESSAGE_CUSTOMER)
&& CollectionUtils.isNotEmpty(s.getCustomersInfo())) || (s.getMessageInfo().getPushType().equals(WeConstans.SEND_MESSAGE_GROUP)
&& CollectionUtils.isNotEmpty(s.getGroupsInfo()))) {
weCustomerMessageService.sendMessgae(s.getMessageInfo(), s.getMessageId(), s.getCustomersInfo(), s.getGroupsInfo());
//更新消息处理状态
customerMessageTimeTaskMapper.updateTaskSolvedById(s.getTaskId());
}
semaphore.release();
} catch (JsonProcessingException | InterruptedException e) {
log.error("定时群发消息处理异常:ex:{}", e);
e.printStackTrace();
}
}
);
}
}
}
package com.linkwechat.quartz.task;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkwechat.common.utils.bean.BeanUtils;
import com.linkwechat.wecom.client.WeCustomerClient;
import com.linkwechat.wecom.domain.WeGroup;
import com.linkwechat.wecom.domain.WeGroupStatistic;
import com.linkwechat.wecom.domain.dto.GroupChatStatisticDto;
import com.linkwechat.wecom.domain.query.GroupChatStatisticQuery;
import com.linkwechat.wecom.service.IWeGroupService;
import com.linkwechat.wecom.service.IWeGroupStatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* @author sxw
* @description 群聊数据统计
* @date 2021/2/24 0:42
**/
@Slf4j
@Component("GroupChatStatisticTask")
public class GroupChatStatisticTask {
@Autowired
private WeCustomerClient weCustomerClient;
@Autowired
private IWeGroupService weGroupService;
@Autowired
private IWeGroupStatisticService weGroupStatisticService;
public void getGroupChatData() {
log.info("群聊数据统计>>>>>>>>>>>>>>>>>>>启动");
List<WeGroup> weGroupList = weGroupService.list(new LambdaQueryWrapper<WeGroup>().eq(WeGroup::getStatus, 0));
log.info("群聊数据统计>>>>>>>>>>>>>>>>>>>weGroupList:{}",weGroupList.size());
if (CollectionUtil.isNotEmpty(weGroupList)){
List<WeGroupStatistic> weGroupStatisticList = new ArrayList<>();
GroupChatStatisticQuery query = new GroupChatStatisticQuery();
//前一天的数据
Long startTime = strToDate(-1, 0);
Long endTime = strToDate(-1, 1);
query.setDay_begin_time(startTime);
query.setDay_end_time(endTime);
weGroupList.forEach(weGroup -> {
GroupChatStatisticQuery.OwnerFilter ownerFilter = new GroupChatStatisticQuery.OwnerFilter();
List<String> idList = new ArrayList<>();
idList.add(weGroup.getOwner());
ownerFilter.setUserid_list(idList);
query.setOwnerFilter(ownerFilter);
try {
GroupChatStatisticDto groupChatStatistic = weCustomerClient.getGroupChatStatisticGroupByDay(query);
List<GroupChatStatisticDto.GroupchatStatisticData> items = groupChatStatistic.getItems();
if(CollectionUtil.isNotEmpty(items)){
items.forEach(groupchatStatisticData -> {
WeGroupStatistic weGroupStatistic = new WeGroupStatistic();
GroupChatStatisticDto.StatisticData data = groupchatStatisticData.getData();
BeanUtils.copyPropertiesignoreOther(data, weGroupStatistic);
weGroupStatistic.setChatId(weGroup.getChatId());
weGroupStatistic.setStatTime(groupchatStatisticData.getStatTime());
weGroupStatisticList.add(weGroupStatistic);
});
}
} catch (Exception e) {
e.printStackTrace();
log.error("群聊数据拉取失败: ownerFilter:【{}】,ex:【{}】", JSONObject.toJSONString(ownerFilter),e.getStackTrace());
}
});
weGroupStatisticService.saveBatch(weGroupStatisticList);
}
}
private Long strToDate(int days, Integer type) {
Long time = null;
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
Calendar cale = Calendar.getInstance();
cale.add(Calendar.DATE, days);
String tarday = new SimpleDateFormat("yyyy-MM-dd").format(cale.getTime());
if (type.equals(0)) {
tarday += " 00:00:00";
} else {
tarday += " 23:59:59";
}
// String转Date
try {
date = format2.parse(tarday);
System.out.println(date.getTime());
time = date.getTime() / 1000;
System.out.println(time.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
}
package com.linkwechat.quartz.task;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.wecom.domain.WeCustomerMessageTimeTask;
import com.linkwechat.wecom.mapper.WeCustomerMessageTimeTaskMapper;
import com.linkwechat.wecom.service.IWeCustomerMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.Semaphore;
/**
* @description: 群发任务推送
* @author: HaoN
* @create: 2021-05-31 10:43
**/
@Slf4j
@Component("GroupPushTask")
public class GroupPushTask {
@Autowired
private WeCustomerMessageTimeTaskMapper customerMessageTimeTaskMapper;
@Autowired
private IWeCustomerMessageService weCustomerMessageService;
/**
* 扫描群发消息定时任务
*/
public void messageTask() {
//获的当前时间的毫秒数
long currentTime = System.currentTimeMillis();
//customerMessageTimeTaskMapper
List<WeCustomerMessageTimeTask> weCustomerMessageTimeTasks = customerMessageTimeTaskMapper.selectWeCustomerMessageTimeTaskGteSettingTime(currentTime);
final Semaphore semaphore = new Semaphore(5);
if (CollectionUtils.isNotEmpty(weCustomerMessageTimeTasks)) {
weCustomerMessageTimeTasks.forEach(
s -> {
try {
semaphore.acquire();
if (s.getMessageInfo() != null && s.getMessageId() != null || (s.getMessageInfo().getPushType().equals(WeConstans.SEND_MESSAGE_CUSTOMER)
&& CollectionUtils.isNotEmpty(s.getCustomersInfo())) || (s.getMessageInfo().getPushType().equals(WeConstans.SEND_MESSAGE_GROUP)
&& CollectionUtils.isNotEmpty(s.getGroupsInfo()))) {
weCustomerMessageService.sendMessgae(s.getMessageInfo(), s.getMessageId(), s.getCustomersInfo(), s.getGroupsInfo());
//更新消息处理状态
customerMessageTimeTaskMapper.updateTaskSolvedById(s.getTaskId());
}
semaphore.release();
} catch (JsonProcessingException | InterruptedException e) {
log.error("定时群发消息处理异常:ex:{}", e);
e.printStackTrace();
}
}
);
}
}
}
package com.linkwechat.quartz.task;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.wecom.domain.WeUser;
import com.linkwechat.wecom.domain.dto.WePageCountDto;
import com.linkwechat.wecom.domain.dto.WePageStaticDataDto;
import com.linkwechat.wecom.domain.query.WePageStateQuery;
import com.linkwechat.wecom.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author danmo
* @description 首页数据统计
* @date 2021/2/23 23:51
**/
@Slf4j
@Component("PageHomeDataTask")
public class PageHomeDataTask {
@Autowired
private IWeCorpAccountService weCorpAccountService;
@Autowired
private IWeUserService weUserService;
@Autowired
private IWeCustomerService weCustomerService;
@Autowired
private IWeGroupService weGroupService;
@Autowired
private IWeGroupMemberService weGroupMemberService;
@Autowired
private IWeUserBehaviorDataService weUserBehaviorDataService;
@Autowired
private IWeGroupStatisticService weGroupStatisticService;
@Autowired
private RedisCache redisCache;
public void getPageHomeDataData(){
getCorpBasicData();
getCorpRealTimeData();
}
public void getCorpBasicData(){
//查询当前使用企业
//WeCorpAccount weCorpAccount = weCorpAccountService.findValidWeCorpAccount();
//String corpId = weCorpAccount.getCorpId();
Map<String,Object> totalMap = new HashMap<>(16);
//企业成员总数
int userCount = weUserService.count(new LambdaQueryWrapper<WeUser>().eq(WeUser::getIsActivate, WeConstans.WE_USER_IS_ACTIVATE));
//客户总人数
int customerCount = weCustomerService.count();
//客户群总数
int groupCount = weGroupService.count();
//群成员总数
int groupMemberCount = weGroupMemberService.count();
totalMap.put("userCount",userCount);
totalMap.put("customerCount",customerCount);
totalMap.put("groupCount",groupCount);
totalMap.put("groupMemberCount",groupMemberCount);
redisCache.setCacheMap("getCorpBasicData",totalMap);
}
public void getCorpRealTimeData(){
WePageStaticDataDto wePageStaticDataDto = new WePageStaticDataDto();
//今天
wePageStaticDataDto.setToday(getTodayData());
wePageStaticDataDto.setWeek(getWeekData());
wePageStaticDataDto.setMonth(getMonthData());
wePageStaticDataDto.setUpdateTime(DateUtil.now());
redisCache.setCacheObject("getCorpRealTimeData",wePageStaticDataDto);
}
private WePageStaticDataDto.PageStaticData getTodayData(){
/**
* 今日
*/
String today = DateUtil.today();
String yesterday = DateUtil.yesterday().toDateStr();
//客户统计
WePageCountDto nowData = weUserBehaviorDataService.getCountDataByDay(today,"day");
//客户群统计
WePageCountDto nowTimeGroupChatData = weGroupStatisticService.getCountDataByDay(today, "day");
if(nowTimeGroupChatData != null){
nowData.setChatCnt(nowTimeGroupChatData.getChatCnt());
nowData.setChatTotal(nowTimeGroupChatData.getChatTotal());
nowData.setChatHasMsg(nowTimeGroupChatData.getChatHasMsg());
nowData.setNewChatCnt(nowTimeGroupChatData.getNewChatCnt());
nowData.setNewMemberCnt(nowTimeGroupChatData.getNewMemberCnt());
nowData.setMemberTotal(nowTimeGroupChatData.getMemberTotal());
nowData.setMsgTotal(nowTimeGroupChatData.getMsgTotal());
}
/**
* 昨日
*/
//客户统计
WePageCountDto lastTime = weUserBehaviorDataService.getCountDataByDay(yesterday,"day");
//客户群统计
WePageCountDto lastGroupChatTime = weGroupStatisticService.getCountDataByDay(yesterday,"day");
if(lastGroupChatTime != null){
lastTime.setChatCnt(lastGroupChatTime.getChatCnt());
lastTime.setChatTotal(lastGroupChatTime.getChatTotal());
lastTime.setChatHasMsg(lastGroupChatTime.getChatHasMsg());
lastTime.setNewChatCnt(lastGroupChatTime.getNewChatCnt());
lastTime.setNewMemberCnt(lastGroupChatTime.getNewMemberCnt());
lastTime.setMemberTotal(lastGroupChatTime.getMemberTotal());
lastTime.setMsgTotal(lastGroupChatTime.getMsgTotal());
}
WePageStaticDataDto.PageStaticData pageStaticData = setPageStaticData(nowData, lastTime);
WePageStateQuery wePageStateQuery = new WePageStateQuery();
//获取15天前的时间
wePageStateQuery.setStartTime(DateUtil.offsetDay(new Date(), -15).toDateStr());
wePageStateQuery.setEndTime(today);
wePageStateQuery.setFew(14);
List<WePageCountDto> dayCountData = weUserBehaviorDataService.getDayCountData(wePageStateQuery);
List<WePageCountDto> dayGroupChatCountData = weGroupStatisticService.getDayCountData(wePageStateQuery);
for (WePageCountDto dayData : dayCountData) {
for (WePageCountDto dayGroupChatData : dayGroupChatCountData) {
if (dayData.getXTime().equals(dayGroupChatData.getXTime())){
dayData.setChatCnt(dayGroupChatData.getChatCnt());
dayData.setChatTotal(dayGroupChatData.getChatTotal());
dayData.setChatHasMsg(dayGroupChatData.getChatHasMsg());
dayData.setNewChatCnt(dayGroupChatData.getNewChatCnt());
dayData.setNewMemberCnt(dayGroupChatData.getNewMemberCnt());
dayData.setMemberTotal(dayGroupChatData.getMemberTotal());
dayData.setMsgTotal(dayGroupChatData.getMsgTotal());
break;
}
}
}
pageStaticData.setDataList(dayCountData);
return pageStaticData;
}
private WePageStaticDataDto.PageStaticData getWeekData(){
/**
* 本周
*/
//客户统计
WePageCountDto newTime = weUserBehaviorDataService.getCountDataByDay(DateUtil.today(),"week");
WePageCountDto nowTimeGroupChatData = weGroupStatisticService.getCountDataByDay(DateUtil.today(),"week");
if(nowTimeGroupChatData != null){
newTime.setChatCnt(nowTimeGroupChatData.getChatCnt());
newTime.setChatTotal(nowTimeGroupChatData.getChatTotal());
newTime.setChatHasMsg(nowTimeGroupChatData.getChatHasMsg());
newTime.setNewChatCnt(nowTimeGroupChatData.getNewChatCnt());
newTime.setNewMemberCnt(nowTimeGroupChatData.getNewMemberCnt());
newTime.setMemberTotal(nowTimeGroupChatData.getMemberTotal());
newTime.setMsgTotal(nowTimeGroupChatData.getMsgTotal());
}
/**
* 上周
*/
//客户统计
WePageCountDto lastTime = weUserBehaviorDataService.getCountDataByDay(DateUtil.lastWeek().toDateStr(),"week");
WePageCountDto lastTimeGroupChatData = weGroupStatisticService.getCountDataByDay(DateUtil.lastWeek().toDateStr(),"week");
if(lastTimeGroupChatData != null){
lastTime.setChatCnt(lastTimeGroupChatData.getChatCnt());
lastTime.setChatTotal(lastTimeGroupChatData.getChatTotal());
lastTime.setChatHasMsg(lastTimeGroupChatData.getChatHasMsg());
lastTime.setNewChatCnt(lastTimeGroupChatData.getNewChatCnt());
lastTime.setNewMemberCnt(lastTimeGroupChatData.getNewMemberCnt());
lastTime.setMemberTotal(lastTimeGroupChatData.getMemberTotal());
lastTime.setMsgTotal(lastTimeGroupChatData.getMsgTotal());
}
WePageStaticDataDto.PageStaticData pageStaticData = setPageStaticData(newTime, lastTime);
WePageStateQuery wePageStateQuery = new WePageStateQuery();
wePageStateQuery.setFew(5);
List<WePageCountDto> weekCountData = weUserBehaviorDataService.getWeekCountData(wePageStateQuery);
List<WePageCountDto> weekGroupChatCountData = weGroupStatisticService.getWeekCountData(wePageStateQuery);
for (WePageCountDto weekData : weekCountData) {
for (WePageCountDto weekGroupChatData : weekGroupChatCountData) {
if (weekData.getXTime().equals(weekGroupChatData.getXTime())){
weekData.setChatCnt(weekGroupChatData.getChatCnt());
weekData.setChatTotal(weekGroupChatData.getChatTotal());
weekData.setChatHasMsg(weekGroupChatData.getChatHasMsg());
weekData.setNewChatCnt(weekGroupChatData.getNewChatCnt());
weekData.setNewMemberCnt(weekGroupChatData.getNewMemberCnt());
weekData.setMemberTotal(weekGroupChatData.getMemberTotal());
weekData.setMsgTotal(weekGroupChatData.getMsgTotal());
break;
}
}
}
pageStaticData.setDataList(weekCountData);
return pageStaticData;
}
private WePageStaticDataDto.PageStaticData getMonthData(){
/**
* 本月
*/
//客户统计
WePageCountDto newTime = weUserBehaviorDataService.getCountDataByDay(DateUtil.today(),"month");
WePageCountDto nowTimeGroupChatData = weGroupStatisticService.getCountDataByDay(DateUtil.today(),"month");
if(nowTimeGroupChatData != null){
newTime.setChatCnt(nowTimeGroupChatData.getChatCnt());
newTime.setChatTotal(nowTimeGroupChatData.getChatTotal());
newTime.setChatHasMsg(nowTimeGroupChatData.getChatHasMsg());
newTime.setNewChatCnt(nowTimeGroupChatData.getNewChatCnt());
newTime.setNewMemberCnt(nowTimeGroupChatData.getNewMemberCnt());
newTime.setMemberTotal(nowTimeGroupChatData.getMemberTotal());
newTime.setMsgTotal(nowTimeGroupChatData.getMsgTotal());
}
/**
* 上月
*/
//客户统计
WePageCountDto lastTime = weUserBehaviorDataService.getCountDataByDay(DateUtil.lastMonth().toDateStr(),"month");
WePageCountDto lastTimeGroupChatData = weGroupStatisticService.getCountDataByDay(DateUtil.lastMonth().toDateStr(),"month");
if(lastTimeGroupChatData != null){
lastTime.setChatCnt(lastTimeGroupChatData.getChatCnt());
lastTime.setChatTotal(lastTimeGroupChatData.getChatTotal());
lastTime.setChatHasMsg(lastTimeGroupChatData.getChatHasMsg());
lastTime.setNewChatCnt(lastTimeGroupChatData.getNewChatCnt());
lastTime.setNewMemberCnt(lastTimeGroupChatData.getNewMemberCnt());
lastTime.setMemberTotal(lastTimeGroupChatData.getMemberTotal());
lastTime.setMsgTotal(lastTimeGroupChatData.getMsgTotal());
}
WePageStaticDataDto.PageStaticData pageStaticData = setPageStaticData(newTime, lastTime);
WePageStateQuery wePageStateQuery = new WePageStateQuery();
wePageStateQuery.setFew(5);
List<WePageCountDto> monthCountData = weUserBehaviorDataService.getMonthCountData(wePageStateQuery);
List<WePageCountDto> monthGroupChatCountData = weGroupStatisticService.getMonthCountData(wePageStateQuery);
for (WePageCountDto monthData : monthCountData) {
for (WePageCountDto monthGroupChatData : monthGroupChatCountData) {
if (monthData.getXTime().equals(monthGroupChatData.getXTime())){
monthData.setChatCnt(monthGroupChatData.getChatCnt());
monthData.setChatTotal(monthGroupChatData.getChatTotal());
monthData.setChatHasMsg(monthGroupChatData.getChatHasMsg());
monthData.setNewChatCnt(monthGroupChatData.getNewChatCnt());
monthData.setNewMemberCnt(monthGroupChatData.getNewMemberCnt());
monthData.setMemberTotal(monthGroupChatData.getMemberTotal());
monthData.setMsgTotal(monthGroupChatData.getMsgTotal());
break;
}
}
}
pageStaticData.setDataList(monthCountData);
return pageStaticData;
}
private WePageStaticDataDto.PageStaticData setPageStaticData(WePageCountDto nowTime,WePageCountDto lastTime){
WePageStaticDataDto.PageStaticData pageStaticData = new WePageStaticDataDto.PageStaticData();
pageStaticData.setNewApplyCnt(nowTime.getNewApplyCnt());
pageStaticData.setNewApplyCntDiff(nowTime.getNewApplyCnt() - lastTime.getNewApplyCnt());
pageStaticData.setNegativeFeedbackCnt(nowTime.getNegativeFeedbackCnt());
pageStaticData.setNegativeFeedbackCntDiff(nowTime.getNegativeFeedbackCnt() - lastTime.getNegativeFeedbackCnt());
pageStaticData.setNewContactCnt(nowTime.getNewContactCnt());
pageStaticData.setNewContactCntDiff(nowTime.getNewContactCnt() - lastTime.getNewContactCnt());
pageStaticData.setNewMemberCnt(nowTime.getNewMemberCnt());
pageStaticData.setNewMemberCntDiff(nowTime.getNewMemberCnt() - lastTime.getNewMemberCnt());
return pageStaticData;
}
}
package com.linkwechat.quartz.task;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.utils.bean.BeanUtils;
import com.linkwechat.wecom.client.WeCustomerClient;
import com.linkwechat.wecom.domain.WeUser;
import com.linkwechat.wecom.domain.WeUserBehaviorData;
import com.linkwechat.wecom.domain.dto.UserBehaviorDataDto;
import com.linkwechat.wecom.domain.query.UserBehaviorDataQuery;
import com.linkwechat.wecom.service.IWeUserBehaviorDataService;
import com.linkwechat.wecom.service.IWeUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* @author sxw
* @description 联系客户统计
* @date 2021/2/24 0:41
**/
@Slf4j
@Component("UserBehaviorDataTak")
public class UserBehaviorDataTak {
@Autowired
private WeCustomerClient weCustomerClient;
@Autowired
private IWeUserService weUserService;
@Autowired
private IWeUserBehaviorDataService weUserBehaviorDataService;
private final int offset = 500;
public void getUserBehaviorData() {
log.info("联系客户统计>>>>>>>>>>>>>>>>>>>启动");
LambdaQueryWrapper<WeUser> wrapper = new LambdaQueryWrapper<WeUser>().eq(WeUser::getIsActivate, WeConstans.WE_USER_IS_ACTIVATE);
int userCount = weUserService.count(wrapper);
log.info("联系客户统计>>>>>>>>>>>>>>>>>>>userCount:{}",userCount);
double num = 1;
if (userCount > offset) {
num = Math.ceil((double) userCount / offset);
}
int temp = 0;
for (int i = 0; i < num; i++) {
wrapper.last("limit " + temp + "," + offset);
List<WeUser> list = weUserService.list(wrapper);
if (CollectionUtil.isNotEmpty(list)) {
List<WeUserBehaviorData> dataList = new ArrayList<>();
UserBehaviorDataQuery query = new UserBehaviorDataQuery();
//前一天的数据
Long startTime = strToDate(-1, 0);
Long endTime = strToDate(-1, 1);
query.setStart_time(startTime);
query.setEnd_time(endTime);
list.forEach(weUser -> {
List<String> idList = new ArrayList<>();
idList.add(weUser.getUserId());
query.setUserid(idList);
try {
UserBehaviorDataDto userBehaviorData = weCustomerClient.getUserBehaviorData(query);
List<UserBehaviorDataDto.BehaviorData> behaviorDataList = userBehaviorData.getBehaviorData();
for (UserBehaviorDataDto.BehaviorData data : behaviorDataList) {
WeUserBehaviorData weUserBehaviorData = new WeUserBehaviorData();
BeanUtils.copyPropertiesignoreOther(data, weUserBehaviorData);
weUserBehaviorData.setUserId(weUser.getUserId());
dataList.add(weUserBehaviorData);
}
} catch (ForestRuntimeException e) {
e.printStackTrace();
log.error("员工数据拉取失败: userId:【{}】,ex:【{}】",weUser.getUserId(),e.getStackTrace());
}
});
weUserBehaviorDataService.saveBatch(dataList);
}
temp += offset;
}
}
private Long strToDate(int days, Integer type) {
Long time = null;
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
Calendar cale = Calendar.getInstance();
cale.add(Calendar.DATE, days);
String tarday = new SimpleDateFormat("yyyy-MM-dd").format(cale.getTime());
if (type.equals(0)) {
tarday += " 00:00:00";
} else {
tarday += " 23:59:59";
}
// String转Date
try {
date = format2.parse(tarday);
System.out.println(date.getTime());
time = date.getTime() / 1000;
System.out.println(time.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
}
......@@ -14,6 +14,7 @@ import java.util.concurrent.ConcurrentHashMap;
**/
@Service
public class WeStrategyBeanFactory {
@Autowired
private final Map<String, WeEventStrategy> eventStrategyMap = new ConcurrentHashMap<>();
......
......@@ -166,7 +166,7 @@ public class WeCallBackAddExternalContactImpl extends WeEventStrategy {
// 新客拉群创建的员工活码欢迎语图片(群活码图片)
String codeUrl = weGroupCodeService.selectGroupCodeUrlByEmplCodeState(state);
if (StringUtils.isNotNull(codeUrl)) {
buildWelcomeMsgImg(weWelcomeMsgBuilder, codeUrl, codeUrl.replaceAll(cosConfig.getImgUrlPrefix(), ""));
buildWelcomeMsgImg(weWelcomeMsgBuilder, codeUrl, codeUrl.replaceAll(cosConfig.getCosImgUrlPrefix(), ""));
}
// 普通员工活码欢迎语图片
else if (StringUtils.isNotEmpty(messageMap.getCategoryId())) {
......
package com.linkwechat.wecom.interceptor;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.exceptions.ForestRuntimeException;
......@@ -8,14 +9,16 @@ import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.utils.ForestDataType;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.core.domain.model.LoginUser;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.domain.weixin.dto.WxBaseResultDto;
import com.linkwechat.wecom.domain.weixin.dto.WxTokenDto;
import com.linkwechat.wecom.wxclient.WxCommonClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
......@@ -28,11 +31,9 @@ import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class WeiXinAccessTokenInterceptor implements Interceptor {
//暂时写到配置文件,之后写入数据库
@Value("${weixin.appid}")
private String appId;
@Value("${weixin.secret}")
private String secret;
private final String grantType = "client_credential";
@Autowired
......@@ -51,16 +52,29 @@ public class WeiXinAccessTokenInterceptor implements Interceptor {
private String findAccessToken(){
//获取用户token
String accessToken =redisCache.getCacheObject(WeConstans.WX_ACCESS_TOKEN);
if (StringUtils.isEmpty(accessToken)){
//当用户token失效,重新获取token
WxTokenDto wxTokenDto = wxCommonClient.getToken(grantType, appId, secret);
if(wxTokenDto != null && StringUtils.isNotEmpty(wxTokenDto.getAccessToken())){
redisCache.setCacheObject(WeConstans.WX_AUTH_ACCESS_TOKEN, wxTokenDto.getAccessToken(), wxTokenDto.getExpiresIn(), TimeUnit.SECONDS);
accessToken = wxTokenDto.getAccessToken();
String accessToken=null;
LoginUser loginUser = SecurityUtils.getLoginUser();
if(null != loginUser && null != loginUser.getUser() && null != loginUser.getUser().getWeCorpAccount()){
WeCorpAccount weCorpAccount = loginUser.getUser().getWeCorpAccount();
if(StrUtil.isEmpty(weCorpAccount.getAppId()) && StrUtil.isEmpty(weCorpAccount.getSecret())){
//获取用户token
accessToken =redisCache.getCacheObject(WeConstans.WX_ACCESS_TOKEN);
if (StringUtils.isEmpty(accessToken)){
//当用户token失效,重新获取token
WxTokenDto wxTokenDto = wxCommonClient.getToken(grantType, weCorpAccount.getAppId(), weCorpAccount.getSecret());
if(wxTokenDto != null && StringUtils.isNotEmpty(wxTokenDto.getAccessToken())){
redisCache.setCacheObject(WeConstans.WX_AUTH_ACCESS_TOKEN, wxTokenDto.getAccessToken(), wxTokenDto.getExpiresIn(), TimeUnit.SECONDS);
accessToken = wxTokenDto.getAccessToken();
}
}
}else{
throw new ForestRuntimeException("公众号appid或者secret不可为空");
}
}
return accessToken;
}
......
package com.linkwechat.wecom.interceptor;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.exceptions.ForestRuntimeException;
......@@ -8,8 +9,12 @@ import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.utils.ForestDataType;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.core.domain.model.LoginUser;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.exception.wecom.WeComException;
import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.ServletUtils;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.domain.weixin.dto.WxTokenDto;
import com.linkwechat.wecom.domain.weixin.dto.WxBaseResultDto;
......@@ -26,15 +31,11 @@ import java.util.concurrent.TimeUnit;
* @description 微信授权拦截器
* @date 2021/4/5 15:28
**/
@Slf4j
@Component
public class WeiXinAuthInterceptor implements Interceptor {
//暂时写到配置文件,之后写入数据库
@Value("${weixin.appid}")
private String appId;
@Value("${weixin.secret}")
private String secret;
private final String grantType = "refresh_token";
@Autowired
......@@ -63,9 +64,16 @@ public class WeiXinAuthInterceptor implements Interceptor {
if(StringUtils.isEmpty(refreshToken)){
throw new WeComException(1001,"token失效,请重新授权");
}else {
wxTokenDto = wxAuthClient.refreshToken(appId, grantType, refreshToken);
if(wxTokenDto != null && StringUtils.isNotEmpty(wxTokenDto.getAccessToken())){
redisCache.setCacheObject(WeConstans.WX_AUTH_ACCESS_TOKEN+":"+ openId, wxTokenDto, wxTokenDto.getExpiresIn(), TimeUnit.SECONDS);
LoginUser loginUser = SecurityUtils.getLoginUser();
if(null != loginUser && null != loginUser.getUser() && null != loginUser.getUser().getWeCorpAccount()) {
WeCorpAccount weCorpAccount = loginUser.getUser().getWeCorpAccount();
if (StrUtil.isEmpty(weCorpAccount.getAppId())) {
wxTokenDto = wxAuthClient.refreshToken(weCorpAccount.getAppId(), grantType, refreshToken);
if(wxTokenDto != null && StringUtils.isNotEmpty(wxTokenDto.getAccessToken())){
redisCache.setCacheObject(WeConstans.WX_AUTH_ACCESS_TOKEN+":"+ openId, wxTokenDto, wxTokenDto.getExpiresIn(), TimeUnit.SECONDS);
}
}
}
}
}
......
......@@ -62,16 +62,14 @@ public class WeTaskFissionServiceImpl extends ServiceImpl<WeTaskFissionMapper, W
private IWeCustomerMessagePushService weCustomerMessagePushService;
@Autowired
private IWeTaskFissionRecordService weTaskFissionRecordService;
@Autowired
private IWeUserService weUserService;
@Autowired
private WeExternalContactClient weExternalContactClient;
@Autowired
private IWePosterService wePosterService;
@Autowired
private IWeGroupCodeService weGroupCodeService;
@Autowired
private IWeMaterialService weMaterialService;
@Autowired
private IWeCustomerService weCustomerService;
@Autowired
......@@ -81,10 +79,7 @@ public class WeTaskFissionServiceImpl extends ServiceImpl<WeTaskFissionMapper, W
@Autowired
private CosConfig cosConfig;
@Value("${H5.fissionUrl}")
private String pageUrl;
@Value("${H5.fissionGroupUrl}")
private String pageGroupUrl;
/**
* 查询任务宝
......@@ -203,7 +198,9 @@ public class WeTaskFissionServiceImpl extends ServiceImpl<WeTaskFissionMapper, W
//目标员工id
String fissStaffId = weTaskFission.getFissionTargetId();
//H5生成海报页面路径
StringBuilder pageUrlBuilder = new StringBuilder(pageUrl);
StringBuilder pageUrlBuilder = new StringBuilder(
SecurityUtils.getLoginUser().getUser().getWeCorpAccount().getFissionUrl()
);
pageUrlBuilder.append("?")
.append("fissionId=").append(id)
.append("&")
......@@ -436,7 +433,7 @@ public class WeTaskFissionServiceImpl extends ServiceImpl<WeTaskFissionMapper, W
String qrCode = null;
if (weCustomer != null) {
String avatarUrl = weCustomer.getAvatar();
StringBuilder contentBuilder = new StringBuilder(pageGroupUrl);
StringBuilder contentBuilder = new StringBuilder( SecurityUtils.getLoginUser().getUser().getWeCorpAccount().getFissionGroupUrl());
contentBuilder.append("?")
.append("fissionId=")
.append(taskFissionId)
......@@ -453,7 +450,7 @@ public class WeTaskFissionServiceImpl extends ServiceImpl<WeTaskFissionMapper, W
throw new WeComException("生成二维码异常");
}
}
return cosConfig.getImgUrlPrefix() + qrCode;
return cosConfig.getCosImgUrlPrefix() + qrCode;
} else {
throw new WeComException("生成二维码异常,用户信息不存在");
}
......
......@@ -36,7 +36,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</collection>
</collection>
</resultMap>
<resultMap id="weFlowerCustomerRelsMapper" type="com.linkwechat.wecom.domain.WeFlowerCustomerTagRel">
<result property="flowerCustomerRelId" column="flower_customer_rel_id" />
......@@ -75,8 +78,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
and wt.status = 0
</sql>
<select id="selectWeCustomerList" parameterType="WeCustomer" resultMap="WeCustomerResult">
SELECT
SELECT
*
FROM
(
SELECT
DISTINCT wc.external_userid,
wc.`name`,
wc.avatar,
......@@ -157,7 +165,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
AND wc.is_open_chat=#{isOpenChat}
</if>
</where>
ORDER BY wfcr.create_time DESC
ORDER BY wfcr.create_time ASC
) aa GROUP BY aa.external_userid
</select>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册