Commit 0509c0fd by 张富康

refactor(bi): 优化4s店业务数据处理逻辑并集成企业微信通知

- 修正SQL查询中的条件判断及字段拼写错误
- 调整BusinessIntelligenceService配置参数,优化批量插入逻辑并添加调试日志
- 更新HandlerExceptionDataJob和HandlerHistoryDataJob日志及cron配置,完善业务异常与历史数据处理
- 在HandlerHistoryDataJob和HandlerSelfDailyDataJob中增加企业微信消息通知,记录任务开始与结束时间及耗时
- 新增WeComRobotUtil工具类,实现企业微信机器人消息的发送功能
- UsedCarDataStatsService中增加商户名称查询并完善相关请求参数判断
- UsedCarDataStatsRemoteImpl调用业务处理前后发送企业微信消息,监控业务执行状态
- 修正部分API接口及DTO字段命名,保持一致性与准确性
1 parent abc3cb35
......@@ -15,6 +15,18 @@ public class OperationStatusRes implements Serializable {
private static final long serialVersionUID = 2507729541857822347L;
/**
* 门店id
*/
@ApiModelProperty(notes = "门店id")
private Integer merchantId;
/**
* 门店名称
*/
@ApiModelProperty(notes = "门店名称")
private String merchantName;
/**
* 在库车辆:无统计时间要求,按统计品牌+统计区域下,统计系统的全部“在库车辆数”
*/
@ApiModelProperty(notes = "在库车辆")
......
......@@ -9,7 +9,7 @@ import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import javax.annotation.Resource;
@Slf4j
@ElasticJobConf(name = "HandlerExceptionDataJob", cron = "0 0 0 1 1 ? 2100", description = "处理4s店业务历史数据", overwrite = false)
@ElasticJobConf(name = "HandlerExceptionDataJob", cron = "0 0 0 1 1 ? 2100", description = "处理4s店业务异常数据", overwrite = false)
public class HandlerExceptionDataJob implements SimpleJob {
@Resource
......@@ -18,13 +18,13 @@ public class HandlerExceptionDataJob implements SimpleJob {
@Override
public void execute(ShardingContext shardingContext) {
log.info("----------------处理4s店业务历史数据开始-----------------");
log.info("----------------处理4s店业务异常数据开始-----------------");
try {
businessIntelligenceService.retryDBFailedRecords();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
log.info("----------------处理4s店业务历史数据结束-----------------");
log.info("----------------处理4s店业务异常数据结束-----------------");
}
}
package cn.com.glsx.dj.peanalysis.job;
import cn.com.glsx.dj.peanalysis.service.BusinessIntelligenceService;
import cn.com.glsx.dj.peanalysis.utils.WeComRobotUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.oreframework.boot.env.OrePropertyConfigurer;
import javax.annotation.Resource;
@Slf4j
@ElasticJobConf(name = "HandlerHistoryDataJob", cron = "0 0 0 1 1 ? 2100", description = "处理4s店业务异常数据", overwrite = false)
@ElasticJobConf(name = "HandlerHistoryDataJob", cron = "0 0 0 1 1 ? 2100", description = "处理4s店业务历史数据", overwrite = false)
public class HandlerHistoryDataJob implements SimpleJob {
@Resource
private BusinessIntelligenceService businessIntelligenceService;
String roobotUrl = OrePropertyConfigurer.getProperty("roobotUrl", String.class, "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=dfa73ee6-1f85-4f10-a00a-fe73ba94b936");
@Override
public void execute(ShardingContext shardingContext) {
log.info("----------------处理4s店业务异常数据开始-----------------");
try {
String parameters = shardingContext.getJobParameter();
if (StrUtil.isBlank(parameters)) {
businessIntelligenceService.retryDBFailedRecords();
log.info("----------------处理4s店业务历史数据开始-----------------");
long startTime = System.currentTimeMillis();
String messageTemplate = "处理4s店业务历史数据-开始-时间:%s";
String messageContent = String.format(messageTemplate, DateUtil.now());
WeComRobotUtil.sendTextMessage(roobotUrl, messageContent);
businessIntelligenceService.totalDataHandle();
long duration = System.currentTimeMillis() - startTime;
messageTemplate = "处理4s店业务历史数据-结束-时间:%s,耗时:%s 秒";
messageContent = String.format(messageTemplate, DateUtil.now(), duration / 1000);
WeComRobotUtil.sendTextMessage(roobotUrl, messageContent);
log.info("----------------处理4s店业务历史数据结束-----------------");
} else {
// 按逗号分隔层 merchantId,statDate
String[] split = parameters.split(",");
Integer merchantId = Integer.valueOf(split[0].trim());
String statDate = split[1].trim();
log.info("--处理4s店业务单挑数据开始--, merchantId: {}, statDate: {}", merchantId, statDate);
long startTime = System.currentTimeMillis();
String messageTemplate = "处理4s店业务单挑数据-开始-时间:%s, merchantId: %s, statDate: %s";
String messageContent = String.format(messageTemplate, DateUtil.now(), merchantId, statDate);
WeComRobotUtil.sendTextMessage(roobotUrl, messageContent);
businessIntelligenceService.retryRecordsForWrite(merchantId, statDate);
long duration = System.currentTimeMillis() - startTime;
messageTemplate = "处理4s店业务单挑数据-结束-时间:%s, merchantId: %s, statDate: %s,耗时:%s 秒";
messageContent = String.format(messageTemplate, DateUtil.now(), merchantId, statDate, duration / 1000);
WeComRobotUtil.sendTextMessage(roobotUrl, messageContent);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
log.info("----------------处理4s店业务异常数据结束-----------------");
}
}
package cn.com.glsx.dj.peanalysis.job;
import cn.com.glsx.dj.peanalysis.service.BusinessIntelligenceService;
import cn.com.glsx.dj.peanalysis.utils.WeComRobotUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.oreframework.boot.env.OrePropertyConfigurer;
import javax.annotation.Resource;
import java.util.Date;
......@@ -18,14 +20,25 @@ public class HandlerSelfDailyDataJob implements SimpleJob {
@Resource
private BusinessIntelligenceService businessIntelligenceService;
String roobotUrl = OrePropertyConfigurer.getProperty("roobotUrl", String.class, "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=dfa73ee6-1f85-4f10-a00a-fe73ba94b936");
@Override
public void execute(ShardingContext shardingContext) {
log.info("----------------处理4s店业务自定义返回数据,默认前一天-开始-----------------");
try {
String parameters = shardingContext.getJobParameter();
if (StrUtil.isBlank(parameters)) {
log.info("----------------处理4s店业务自定义返回数据,默认前一天-开始-----------------");
long startTime = System.currentTimeMillis();
String messageTemplate = "处理4s店业务自定义返回数据,默认前一天-开始-时间:%s";
String messageContent = String.format(messageTemplate, DateUtil.now());
WeComRobotUtil.sendTextMessage(roobotUrl, messageContent);
businessIntelligenceService.selfDailyDataHandle(null, null);
long duration = System.currentTimeMillis() - startTime;
messageTemplate = "处理4s店业务自定义返回数据,默认前一天-结束-时间:%s,耗时:%s 秒";
messageContent = String.format(messageTemplate, DateUtil.now(), duration / 1000);
WeComRobotUtil.sendTextMessage(roobotUrl, messageContent);
log.info("----------------处理4s店业务自定义返回数据,默认前一天-结束-----------------");
} else {
String[] split = parameters.split(",");
String startDateStr = split[0].trim();
......@@ -44,12 +57,20 @@ public class HandlerSelfDailyDataJob implements SimpleJob {
log.error("参数错误,endDate要小于等于昨天");
return;
}
log.info("----------------处理4s店业务自定义返回数据,{}-开始-----------------", parameters);
long startTime = System.currentTimeMillis();
String messageTemplate = "处理4s店业务自定义返回数据,{}-开始-时间:%s";
String messageContent = String.format(messageTemplate, parameters, DateUtil.now());
WeComRobotUtil.sendTextMessage(roobotUrl, messageContent);
businessIntelligenceService.selfDailyDataHandle(startDateStr, endDateStr);
long duration = System.currentTimeMillis() - startTime;
messageTemplate = "处理4s店业务自定义返回数据,{}-结束-时间:%s,耗时:%s 秒";
messageContent = String.format(messageTemplate, parameters, DateUtil.now(), duration / 1000);
WeComRobotUtil.sendTextMessage(roobotUrl, messageContent);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
log.info("----------------处理4s店业务自定义返回数据,默认前一天-结束-----------------");
}
......
......@@ -7,9 +7,10 @@ import cn.com.glsx.dj.peanalysis.dto.res.UserdCarDataStats.*;
import cn.com.glsx.dj.peanalysis.service.BusinessIntelligenceService;
import cn.com.glsx.dj.peanalysis.service.UpdateMerchantService;
import cn.com.glsx.dj.peanalysis.service.UsedCarDataStatsService;
import cn.com.glsx.dj.peanalysis.utils.WeComRobotUtil;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
......@@ -182,17 +183,22 @@ public class UsedCarDataStatsRemoteImpl implements UsedCarDataStatsRemote {
@Override
public RpcResponse<Boolean> generateBusinessIntelligenceData() {
try {
String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=dfa73ee6-1f85-4f10-a00a-fe73ba94b936";
long startTime = System.currentTimeMillis();
String messageTemplate = "处理4s店业务数据-开始-时间:%s";
String messageContent = String.format(messageTemplate, DateUtil.now());
WeComRobotUtil.sendTextMessage(url, messageContent);
// 全量数据处理
// businessIntelligenceService.totalDataHandle();
businessIntelligenceService.totalDataHandle();
// 按天数据处理
// String parameters = "2023-04-28,2024-04-28";
String parameters = "";
if (StrUtil.isBlank(parameters)) {
businessIntelligenceService.selfDailyDataHandle(null, null);
} else {
String[] split = parameters.split(",");
businessIntelligenceService.selfDailyDataHandle(split[0], split[1]);
}
// String parameters = "";
// if (StrUtil.isBlank(parameters)) {
// businessIntelligenceService.selfDailyDataHandle(null, null);
// } else {
// String[] split = parameters.split(",");
// businessIntelligenceService.selfDailyDataHandle(split[0], split[1]);
// }
// 重试库中异常记录
// businessIntelligenceService.retryDBFailedRecords();
// 指定商户指定日期重试
......@@ -202,6 +208,10 @@ public class UsedCarDataStatsRemoteImpl implements UsedCarDataStatsRemote {
// String[] split = parameters.split(",");
// businessIntelligenceService.retryRecordsForWrite(Integer.valueOf(split[0]), split[1]);
// }
long duration = System.currentTimeMillis() - startTime;
messageTemplate = "处理4s店业务数据-结束-时间:%s,耗时:%s 秒";
messageContent = String.format(messageTemplate, DateUtil.now(), duration / 1000);
WeComRobotUtil.sendTextMessage(url, messageContent);
return RpcResponse.success(true);
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
......
......@@ -44,13 +44,13 @@ public class BusinessIntelligenceService {
private Executor taskExecutor;
// 开始日期
String START_DATE_STR = OrePropertyConfigurer.getProperty("START_DATE_STR", String.class, "2020-11-01");
String START_DATE_STR = OrePropertyConfigurer.getProperty("START_DATE_STR", String.class, "2024-01-01");
// 商户批量处理大小
Integer MERCHANT_BATCH_SIZE = OrePropertyConfigurer.getProperty("MERCHANT_BATCH_SIZE", Integer.class, 50);
// 天批量处理大小
Integer DAY_BATCH_SIZE = OrePropertyConfigurer.getProperty("DAY_BATCH_SIZE", Integer.class, 2000);
// 一次性插入大小设置
Integer INSERT_BATCH_SIZE = OrePropertyConfigurer.getProperty("INSERT_BATCH_SIZE", Integer.class, 250);
Integer INSERT_BATCH_SIZE = OrePropertyConfigurer.getProperty("INSERT_BATCH_SIZE", Integer.class, 200);
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
// 失败记录存储(线程安全)
......@@ -274,7 +274,6 @@ public class BusinessIntelligenceService {
BiRecord record = createBiRecord(merchantId, statDate, firstTimes, orders.get(statDate));
records.add(record);
}
// 2. 尝试批量插入
try {
insertBatchBiRecordWithTransaction(records);
......@@ -359,13 +358,21 @@ public class BusinessIntelligenceService {
try {
// 判断records数量 如果超过INSERT_BATCH_SIZE则分批插入
if (records.size() > INSERT_BATCH_SIZE) {
log.info("插入商户ID:{} 批量记录数量 {} 超过INSERT_BATCH_SIZE,将分批插入", records.get(0).getMerchantId(), records.size());
log.debug("插入商户ID:{} 批量记录数量:{} 超过INSERT_BATCH_SIZE,将分批插入", records.get(0).getMerchantId(), records.size());
long startTime = System.currentTimeMillis();
for (int i = 0; i < records.size(); i += INSERT_BATCH_SIZE) {
List<BiRecord> batch = records.subList(i, Math.min(i + INSERT_BATCH_SIZE, records.size()));
log.info("插入商户ID:{} 批量记录数量:{}, 批次:{}", records.get(0).getMerchantId(), batch.size(), (i / INSERT_BATCH_SIZE) + 1);
log.debug("插入商户ID:{} 批量记录数量:{}, 批次:{}", records.get(0).getMerchantId(), batch.size(), (i / INSERT_BATCH_SIZE) + 1);
biMapper.insertBatchBiRecord(batch);
}
log.info("商户ID:{} 批量插入完成", records.get(0).getMerchantId());
long duration = System.currentTimeMillis() - startTime;
log.debug("商户ID:{} 批量插入完成,耗时:{} ms,数量:{}", records.get(0).getMerchantId(), duration, records.size());
} else{
log.info("商户ID:{} 批量记录数量:{}", records.get(0).getMerchantId(), records.size());
long startTime = System.currentTimeMillis();
biMapper.insertBatchBiRecord(records);
long duration = System.currentTimeMillis() - startTime;
log.debug("商户ID:{} 批量插入完成,耗时:{} ms,数量:{}", records.get(0).getMerchantId(), duration, records.size());
}
transactionManager.commit(status);
} catch (Exception e) {
......
......@@ -168,6 +168,15 @@ public class UsedCarDataStatsService {
}
}
}
if (ObjectUtil.isNotEmpty(request.getMerchantId())) {
// 查询商户名称
result.setMerchantId(request.getMerchantId());
List<MerchantProvinceDTO> merchantInfoDTOs = merchantRemote.findMerchantProvinceListByIds(Collections.singletonList(request.getMerchantId())).getResult();
if (CollUtil.isNotEmpty(merchantInfoDTOs)) {
result.setMerchantName(ObjectUtil.isNotEmpty(CollUtil.getFirst(merchantInfoDTOs))
? CollUtil.getFirst(merchantInfoDTOs).getMerchantName() : null);
}
}
return result;
}
......@@ -1149,7 +1158,7 @@ public class UsedCarDataStatsService {
Boolean isCount = request.getIsCount();
// 2. 判断是否需要品牌/区域过滤 店铺名称
boolean filterBoolean = ObjectUtil.isNotEmpty(request.getBrandId()) || ObjectUtil.isNotEmpty(request.getProvinceId())
|| (isCount && StrUtil.isNotBlank(request.getMerchantName()));
|| (!isCount && StrUtil.isNotBlank(request.getMerchantName()));
if (filterBoolean) {
// 2.1 调用远程服务获取品牌区域筛选后的商户ID
CarBrandProvinceRequestDTO carBrandProvinceRequestDTO = new CarBrandProvinceRequestDTO();
......
package cn.com.glsx.dj.peanalysis.utils;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class WeComRobotUtil {
/**
* 发送文本消息到企业微信机器人
* @param robotUrl 机器人Webhook地址
* @param content 消息内容
* @return 发送是否成功
*/
public static boolean sendTextMessage(String robotUrl, String content) {
try {
// 构建JSON请求体
JSONObject json = new JSONObject();
json.set("msgtype", "text");
JSONObject textContent = new JSONObject();
textContent.set("content", content);
json.set("text", textContent);
// 发送POST请求
HttpResponse response = HttpRequest.post(robotUrl)
.body(json.toString())
.execute();
// 解析响应
if (response.isOk()) {
String body = response.body();
JSONObject result = JSONUtil.parseObj(body);
Integer errcode = result.getInt("errcode");
if (errcode != null && errcode.equals(0)) {
log.info("消息发送成功: {}", content);
return true;
} else {
log.error("消息发送失败: {}, 错误信息: {}", content, result.getStr("errmsg"));
return false;
}
} else {
log.error("HTTP请求失败,状态码: {}", response.getStatus());
return false;
}
} catch (Exception e) {
log.error("发送消息时发生异常: {}", e.getMessage(), e);
return false;
}
}
/**
* 发送简单的欢迎消息
* @param robotUrl 机器人Webhook地址
*/
public static boolean sendWelcomeMessage(String robotUrl, String messageContent) {
boolean success = sendTextMessage(robotUrl, messageContent);
// 可以继续添加其他类型消息的方法,如markdown、图片等
if (success) {
log.info("欢迎消息发送成功");
} else {
log.warn("欢迎消息发送失败");
}
return success;
}
}
\ No newline at end of file
......@@ -610,42 +610,35 @@
</select>
<select id="countLostMerchant" resultType="java.lang.Integer">
SELECT
count(distinct merchant_id) AS lost_merchant_count
FROM dj_smartcarlife.dj_car_life_service_merchant_bi t1
WHERE
t1.deleted_flag = 'N'
SELECT COUNT(1) AS lost_merchant_count
FROM (
SELECT merchant_id
FROM dj_smartcarlife.dj_car_life_service_merchant_bi
WHERE deleted_flag = 'N'
AND has_used_car = 1
<![CDATA[
AND stat_date >= #{statDate} - INTERVAL 59 DAY
AND stat_date <= #{statDate}
]]>
<if test="merchantIds != null and merchantIds.size > 0">
and t1.merchant_id in
AND merchant_id IN
<foreach item="item" index="index" collection="merchantIds" separator="," open="(" close=")">
#{item}
</foreach>
</if>
AND EXISTS (
SELECT 1
FROM dj_smartcarlife.dj_car_life_service_merchant_bi t2
WHERE
t2.merchant_id = t1.merchant_id
<![CDATA[
AND t2.stat_date >= #{statDate} - INTERVAL 59 DAY -- 传入的统计日期
AND t2.stat_date <= #{statDate}
]]>
AND t2.has_used_car = 1
AND t2.deleted_flag = 'N'
)
AND NOT EXISTS (
GROUP BY merchant_id
) a
WHERE NOT EXISTS (
SELECT 1
FROM dj_smartcarlife.dj_car_life_service_merchant_bi t3
WHERE
t3.merchant_id = t1.merchant_id
WHERE t3.merchant_id = a.merchant_id
AND t3.deleted_flag = 'N'
AND t3.has_used_car = 1
<![CDATA[
AND t3.stat_date >= #{statDate} - INTERVAL 29 DAY
AND t3.stat_date <= #{statDate}
]]>
AND t3.has_used_car = 1
AND t3.deleted_flag = 'N'
);
)
</select>
<select id="countHistoryMerchant" resultType="java.lang.Integer">
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!