Commit ad3bb6bd by 林永健

refactor(push): 优化每日BI动态推送逻辑及相关数据查询

- 重构策略数据分组逻辑,按 merchantId + biz 组合键处理
- 改进门店配置缓存获取,支持批量查询多业务类型
- 新增按门店与业务类型批量查询关注明细方法,减少查询次数
- 统一使用 StrategyInfo 替代 MerchantBiFollow 作为推送中数据载体
- 优化推送流程,确保无动态数据或无配置时跳过推送
- 服务层调整,wechatPushService 接口改用 StrategyInfo 参数
- Mapper及XML新增按门店及业务类型查询关注明细接口及映射
- 实体类 MerchantBiFollowDetail 新增 transient 字段存储关联商户和业务类型ID
- 移除冗余导入,提升代码整洁性和可维护性
1 parent cf416a12
...@@ -78,5 +78,10 @@ public class MerchantBiFollowDetail implements Serializable { ...@@ -78,5 +78,10 @@ public class MerchantBiFollowDetail implements Serializable {
@Column(name = "deleted_flag") @Column(name = "deleted_flag")
private String deletedFlag; private String deletedFlag;
@Transient
private Integer merchantId;
@Transient
private Integer businessType;
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
} }
\ No newline at end of file \ No newline at end of file
...@@ -15,7 +15,6 @@ import com.dangdang.ddframe.job.api.ShardingContext; ...@@ -15,7 +15,6 @@ import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob; import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf; import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -65,112 +64,89 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -65,112 +64,89 @@ public class MerchantBiDailyPushJob implements SimpleJob {
} }
List<Integer> merchantIds = yesterdayStrategy.stream().map(StrategyInfo::getMerchantId).distinct().collect(Collectors.toList()); List<Integer> merchantIds = yesterdayStrategy.stream().map(StrategyInfo::getMerchantId).distinct().collect(Collectors.toList());
List<String> merchantNames = yesterdayStrategy.stream().map(StrategyInfo::getMerchantName).distinct().collect(Collectors.toList()); List<String> merchantNames = yesterdayStrategy.stream().map(StrategyInfo::getMerchantName).distinct().collect(Collectors.toList());
List<Byte> actualBusinessTypes = yesterdayStrategy.stream().map(p -> p.getBiz().byteValue()).distinct().collect(Collectors.toList()); List<Byte> bizs = yesterdayStrategy.stream().map(p -> p.getBiz().byteValue()).distinct().collect(Collectors.toList());
log.info("昨日有动态的门店号:{}", merchantIds); log.info("昨日有动态的门店号:{}", merchantIds);
log.info("昨日有动态的门店名:{}", merchantNames); log.info("昨日有动态的门店名:{}", merchantNames);
// 2. 批量查询昨日动态数 (返回 Map<key:merchantId_businessType, count>) // 2. 批量查询昨日动态数 (返回 Map<key:merchantId_businessType, count>)
Map<String, Integer> countMap = commentService.batchCountYesterdayCommentsByBizType(merchantIds, actualBusinessTypes); Map<String, Integer> countMap = commentService.batchCountYesterdayCommentsByBizType(merchantIds, bizs);
// 3. 批量查询门店配置 (按业务类型对应的 scene 查询) // 3. 批量查询门店配置 (按业务类型对应的 scene 查询)
Map<String, StoreSettingDTO> settingMap = new HashMap<>(); Map<String, StoreSettingDTO> settingMap = getMerchantSettingMap(merchantIds, bizs);
cacheMerchantSettingMap(settingMap, merchantIds, actualBusinessTypes);
Map<Integer, List<StrategyInfo>> groupByBiz = yesterdayStrategy.stream().collect(Collectors.groupingBy(StrategyInfo::getBiz));
for (Map.Entry<Integer, List<StrategyInfo>> entry : groupByBiz.entrySet()) {
Byte biz = entry.getKey().byteValue();
List<StrategyInfo> itemList = entry.getValue();
if (CollectionUtils.isEmpty(itemList)) {
log.error("该场景下无策略数据, biz:{}", biz);
continue;
}
List<Integer> subMerchantIds = itemList.stream().map(StrategyInfo::getMerchantId).collect(Collectors.toList()); // 4. 批量查询关注详情信息(门店+业务)
// 4. 批量查询这些门店 + 业务的关注记录 Map<String, List<MerchantBiFollowDetail>> followersMap = getFollowDetailMap(merchantIds, bizs);
List<MerchantBiFollow> follows = followMapper.findByMerchantIdsAndBiz(subMerchantIds, biz);
if (CollectionUtils.isEmpty(follows)) {
log.info("这些门店均无关注记录,但仍需推送给区域运营和线上运营");
// 即使没有关注记录,也需要为每个门店 + 业务生成推送(场景 3)
// 构造临时的 follow 记录用于推送
follows = itemList.stream().map(p -> {
MerchantBiFollow tempFollow = new MerchantBiFollow();
tempFollow.setMerchantId(p.getMerchantId());
tempFollow.setBusinessType(p.getBiz().byteValue());
tempFollow.setMerchantName(p.getMerchantName());
return tempFollow;
}).collect(Collectors.toList());
}
log.info("需要处理的关注记录数:{}", follows.size());
List<Integer> followIds = follows.stream()
.map(MerchantBiFollow::getId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
// 5. 批量查询关注明细 (一次 SQL 查询,内存中分组) Map<String, List<StrategyInfo>> groupByKey = yesterdayStrategy.stream()
Map<Integer, List<MerchantBiFollowDetail>> followersMap = new HashMap<>(); .collect(Collectors.groupingBy(p -> p.getMerchantId() + "_" + p.getBiz()));
if (CollectionUtils.isNotEmpty(followIds)) { groupByKey.forEach((key, itemList) -> {
List<MerchantBiFollowDetail> allDetails = followDetailMapper.batchFindByFollowId(followIds); if (CollectionUtils.isEmpty(itemList)) {
if (allDetails != null && !allDetails.isEmpty()) { log.error("该场景下无策略数据, key:{}", key);
followersMap = allDetails.stream() return;
.filter(detail -> detail != null && detail.getFollowId() != null)
.collect(Collectors.groupingBy(MerchantBiFollowDetail::getFollowId));
}
log.info("followersMap:{}", followersMap);
} }
// 6. 内存匹配并推送 log.info("开始处理推送,key:{}, size:{}", key, itemList.size());
for (MerchantBiFollow follow : follows) { for (StrategyInfo item : itemList) {
try { try {
Integer merchantId = follow.getMerchantId(); Integer merchantId = item.getMerchantId();
Integer followId = follow.getId(); Byte businessType = item.getBiz().byteValue();
Byte businessType = follow.getBusinessType();
// 从 Map 中获取该门店 + 业务昨日的动态数
String countKey = merchantId + "_" + businessType;
Integer yesterdayCount = countMap.getOrDefault(countKey, 0);
// 获取该门店 + 业务昨日的动态数
Integer yesterdayCount = countMap.getOrDefault(key, 0);
// 只推送昨日有动态的组合 // 只推送昨日有动态的组合
if (yesterdayCount <= 0) { if (yesterdayCount <= 0) {
log.info("【{}-{}】门店昨日无动态", merchantId, businessType); log.info("【{}-{}】门店昨日无动态", merchantId, businessType);
continue; continue;
} }
// 获取门店配置 (key: merchantId_bizType) // 获取门店配置
String settingKey = merchantId + "_" + businessType; StoreSettingDTO setting = settingMap.get(key);
StoreSettingDTO setting = settingMap.get(settingKey);
if (setting == null) { if (setting == null) {
log.info("【{}-{}】门店无相关配置", merchantId, businessType); log.info("【{}-{}】门店无相关配置", merchantId, businessType);
continue; continue;
} }
List<MerchantBiFollowDetail> details = followersMap.get(followId);
// 场景 3: 推送给区域运营和线上运营(无论是否有关注人都要推送) // 场景 3: 推送给区域运营和线上运营(无论是否有关注人都要推送)
pushToOperatorsWithData(follow, yesterdayCount, setting); pushToOperatorsWithData(item, yesterdayCount, setting);
// 场景 4: 推送给所有关注人(只有存在关注人才推送) // 场景 4: 推送给所有关注人(只有存在关注人才推送)
if (details != null && !details.isEmpty()) { List<MerchantBiFollowDetail> details = followersMap.get(key);
pushToFollowersWithDetails(follow, yesterdayCount, details); if (CollectionUtils.isNotEmpty(details)) {
pushToFollowersWithDetails(item, yesterdayCount, details);
} else { } else {
log.info("【{}-{}】门店无关注人,仅推送给区域运营和线上运营", merchantId, businessType); log.info("【{}-{}】门店无关注人,仅推送给区域运营和线上运营", merchantId, businessType);
} }
} catch (Exception e) { } catch (Exception e) {
log.error("处理门店关注记录失败,门店 ID:{}, 业务类型:{}, 错误:{}", log.error("处理门店关注记录失败,门店 ID:{}, 业务类型:{}, 错误:{}",
follow.getMerchantId(), follow.getBusinessType(), e.getMessage(), e); item.getMerchantId(), item.getBiz(), e.getMessage(), e);
}
} }
} }
});
log.info("每日 BI 动态汇总推送任务执行完成"); log.info("每日 BI 动态汇总推送任务执行完成");
} }
private Map<String, List<MerchantBiFollowDetail>> getFollowDetailMap(List<Integer> merchantIds, List<Byte> bizs) {
if (merchantIds == null || merchantIds.isEmpty()) {
return Collections.emptyMap();
}
log.info("查询关注人信息, merchantIds:{}, bizs:{}", merchantIds, bizs);
List<MerchantBiFollowDetail> details = followDetailMapper.findByMerchantIdsAndBizs(merchantIds, bizs);
if (CollectionUtils.isEmpty(details)) {
log.info("查询关注人信息为空");
return Collections.emptyMap();
}
return details.stream().collect(Collectors.groupingBy(p -> p.getMerchantId() + "_" + p.getBusinessType()));
}
/** /**
* 处理业务+门店下的配置信息缓存 * 处理业务+门店下的配置信息缓存
*/ */
private void cacheMerchantSettingMap(Map<String, StoreSettingDTO> settingMap, List<Integer> merchantIds, List<Byte> businessTypes) { private Map<String, StoreSettingDTO> getMerchantSettingMap(List<Integer> merchantIds, List<Byte> businessTypes) {
Map<String, StoreSettingDTO> settingMap = new HashMap<>();
for (Byte bizType : businessTypes) { for (Byte bizType : businessTypes) {
List<Integer> unCacheMerchantIds = new ArrayList<>(); List<Integer> unCacheMerchantIds = new ArrayList<>();
for (Integer merchantId : merchantIds) { for (Integer merchantId : merchantIds) {
...@@ -199,15 +175,17 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -199,15 +175,17 @@ public class MerchantBiDailyPushJob implements SimpleJob {
settingMap.put(key, setting); settingMap.put(key, setting);
} }
} }
log.info("settingMap.keySet:{}", settingMap.keySet()); log.info("settingMap.keySet:{}", settingMap.keySet());
return settingMap;
} }
/** /**
* 推送给负责人(使用已查询的配置数据) * 推送给负责人(使用已查询的配置数据)
*/ */
private void pushToOperatorsWithData(MerchantBiFollow follow, int count, StoreSettingDTO setting) { private void pushToOperatorsWithData(StrategyInfo strategyInfo, int count, StoreSettingDTO setting) {
Integer merchantId = follow.getMerchantId(); Integer merchantId = strategyInfo.getMerchantId();
Byte businessType = follow.getBusinessType(); Integer businessType = strategyInfo.getBiz();
List<String> targetUuids = new ArrayList<>(); List<String> targetUuids = new ArrayList<>();
// 此时的uuid已经经过角色有效性过滤 // 此时的uuid已经经过角色有效性过滤
...@@ -221,16 +199,15 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -221,16 +199,15 @@ public class MerchantBiDailyPushJob implements SimpleJob {
return; return;
} }
wechatPushService.pushDailySummaryMsg(follow, count, targetUuids, false); wechatPushService.pushDailySummaryMsg(strategyInfo, count, targetUuids, false);
} }
/** /**
* 推送给关注人(使用已查询的关注明细) * 推送给关注人(使用已查询的关注明细)
*/ */
private void pushToFollowersWithDetails(MerchantBiFollow follow, int count, List<MerchantBiFollowDetail> details) { private void pushToFollowersWithDetails(StrategyInfo strategyInfo, int count, List<MerchantBiFollowDetail> details) {
Integer merchantId = follow.getMerchantId(); Integer merchantId = strategyInfo.getMerchantId();
Byte businessType = follow.getBusinessType(); Byte businessType = strategyInfo.getBiz().byteValue();
Integer followId = follow.getId();
List<String> followerUuids = details.stream() List<String> followerUuids = details.stream()
.map(MerchantBiFollowDetail::getStaffUuid) .map(MerchantBiFollowDetail::getStaffUuid)
...@@ -239,10 +216,11 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -239,10 +216,11 @@ public class MerchantBiDailyPushJob implements SimpleJob {
.collect(Collectors.toList()); .collect(Collectors.toList());
if (CollectionUtils.isEmpty(followerUuids)) { if (CollectionUtils.isEmpty(followerUuids)) {
log.info("【{}-{}】门店无关注人,id:{}", merchantId, businessType, followId); List<Integer> followIds = details.stream().map(MerchantBiFollowDetail::getFollowId).distinct().collect(Collectors.toList());
log.info("【{}-{}】门店无关注人, followIds:{}", merchantId, businessType, followIds);
return; return;
} }
wechatPushService.pushDailySummaryMsg(follow, count, followerUuids, true); wechatPushService.pushDailySummaryMsg(strategyInfo, count, followerUuids, true);
} }
} }
...@@ -49,4 +49,6 @@ public interface MerchantBiFollowDetailMapper extends OreMapper<MerchantBiFollow ...@@ -49,4 +49,6 @@ public interface MerchantBiFollowDetailMapper extends OreMapper<MerchantBiFollow
* @return 所有关注明细列表 * @return 所有关注明细列表
*/ */
List<MerchantBiFollowDetail> batchFindByFollowId(@Param("followIds") List<Integer> followIds); List<MerchantBiFollowDetail> batchFindByFollowId(@Param("followIds") List<Integer> followIds);
List<MerchantBiFollowDetail> findByMerchantIdsAndBizs(@Param("merchantIds") List<Integer> merchantIds, @Param("bizs") List<Byte> bizs);
} }
\ No newline at end of file \ No newline at end of file
...@@ -8,6 +8,7 @@ import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq; ...@@ -8,6 +8,7 @@ import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiFollowReq; import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiFollowReq;
import cn.com.glsx.dj.peanalysis.model.MerchantBiFollow; import cn.com.glsx.dj.peanalysis.model.MerchantBiFollow;
import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils; import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils;
import cn.com.glsx.dj.strategy.model.StrategyInfo;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse; import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException; import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.scrm.wechat.enums.WorkWechatAppMessageTypeEnum; import cn.com.glsx.scrm.wechat.enums.WorkWechatAppMessageTypeEnum;
...@@ -77,17 +78,18 @@ public class WechatPushService { ...@@ -77,17 +78,18 @@ public class WechatPushService {
/** /**
* 每日动态汇总推送 * 每日动态汇总推送
*/ */
public void pushDailySummaryMsg(MerchantBiFollow req, int count, List<String> targetUuids, boolean isFollower) { public void pushDailySummaryMsg(StrategyInfo req, int count, List<String> targetUuids, boolean isFollower) {
byte businessType = req.getBiz().byteValue();
String prefix = isFollower ? "你关注的" : "你负责的"; String prefix = isFollower ? "你关注的" : "你负责的";
String content = String.format("%s「%s」门店:「%s」昨日共有「%d」条动态,请及时查看。", String content = String.format("%s「%s」门店:「%s」昨日共有「%d」条动态,请及时查看。",
prefix, MetricsValueUtils.getBusinessTypeName(req.getBusinessType()), req.getMerchantName(), count); prefix, MetricsValueUtils.getBusinessTypeName(businessType), req.getMerchantName(), count);
WechatPushParam param = WechatPushParam.builder() WechatPushParam param = WechatPushParam.builder()
.title("日常跟进提醒") .title("日常跟进提醒")
.content(content) .content(content)
.storeId(req.getMerchantId()) .storeId(req.getMerchantId())
.storeName(req.getMerchantName()) .storeName(req.getMerchantName())
.businessTypeCode(req.getBusinessType()) .businessTypeCode(businessType)
.targetUuids(targetUuids) .targetUuids(targetUuids)
.build(); .build();
......
...@@ -13,6 +13,10 @@ ...@@ -13,6 +13,10 @@
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" /> <result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="deleted_flag" jdbcType="CHAR" property="deletedFlag" /> <result column="deleted_flag" jdbcType="CHAR" property="deletedFlag" />
</resultMap> </resultMap>
<resultMap id="WithMerchant" extends="BaseResultMap" type="cn.com.glsx.dj.peanalysis.model.MerchantBiFollowDetail">
<result column="merchant_id" jdbcType="INTEGER" property="merchantId" />
<result column="business_type" jdbcType="VARCHAR" property="businessType" />
</resultMap>
<sql id="Base_Column_List"> <sql id="Base_Column_List">
id, follow_id, staff_uuid, staff_phone, staff_name, created_by, created_date, updated_by, id, follow_id, staff_uuid, staff_phone, staff_name, created_by, created_date, updated_by,
...@@ -88,4 +92,25 @@ ...@@ -88,4 +92,25 @@
</foreach> </foreach>
AND deleted_flag = 'N' AND deleted_flag = 'N'
</select> </select>
<select id="findByMerchantIdsAndBizs" resultMap="WithMerchant">
SELECT
d.*, f.merchant_id, f.business_type
FROM dj_merchant_bi_follow_detail d
left join dj_merchant_bi_follow f on d.follow_id = f.id
<where>
AND d.deleted_flag = 'N'
AND f.deleted_flag = 'N'
and f.merchant_id IN
<foreach collection="merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
<if test="bizs != null and bizs.size() > 0">
and f.business_type IN
<foreach collection="bizs" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</where>
</select>
</mapper> </mapper>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!