Commit 4f9c938e by 林永健

feat(core): 新增门店关注、策略及留言等数据访问层和远程接口实现

- 新增MerchantBiFollowDetailMapper,支持查询关注明细相关操作
- 新增MerchantBiFollowMapper,支持门店关注记录查询及多场景过滤
- 新增StrategyInfoMapper,实现策略记录的分页查询与统计
- 新增StrategyStaffRelMapper,支持按策略ID查询关联员工信息
- 新增MerchantBiCommentRemoteImpl,实现门店留言相关远程接口逻辑
- 新增MerchantBiFollowRemoteImpl,实现门店关注相关远程接口逻辑
- ServiceMerchantMapper新增招聘负责人和技师督导关联查询方法
- BusinessSceneAnalysisService重构并增强产值权限查询、趋势计算和指标转换逻辑
- 优化产值趋势的周期数据聚合和时间匹配算法
- 增加门店列表关注状态及留言数填充,支持预警门店优先排序
- 门店详情增加招聘负责人和技师督导信息填充逻辑
- 统一指标数据百分比和数值缩放使用MetricsValueUtils工具方法
1 parent e701ed78
Showing 25 changed files with 2840 additions and 205 deletions
......@@ -10,26 +10,34 @@
<version>1.0-SNAPSHOT</version>
<name>rpc-dj-pe-analysis</name>
<packaging>war</packaging>
<dependencies>
<properties>
<platform-merchants.api.version>5.5.1-SNAPSHOT</platform-merchants.api.version>
<smartcarlife.api.version>5.6.4-SNAPSHOT</smartcarlife.api.version>
<mindworkplate.api.version>5.6.1-SNAPSHOT</mindworkplate.api.version>
<pe-analysis.api.version>5.7.0-SNAPSHOT</pe-analysis.api.version>
</properties>
<dependencies>
<dependency>
<groupId>cn.com.glsx.dj.peanalysis</groupId>
<artifactId>rpc-dj-pe-analysis-api</artifactId>
<version>5.7.0-SNAPSHOT</version>
<version>${pe-analysis.api.version}</version>
</dependency>
<dependency>
<groupId>cn.com.glsx.merchants</groupId>
<artifactId>platform-merchants-api</artifactId>
<version>5.5.1-SNAPSHOT</version>
<version>${platform-merchants.api.version}</version>
</dependency>
<dependency>
<groupId>cn.com.glsx</groupId>
<artifactId>rpc-dj-mindworkplate-api</artifactId>
<version>5.6.1-SNAPSHOT</version>
<version>${mindworkplate.api.version}</version>
</dependency>
<dependency>
<groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-smartcarlife-api</artifactId>
<version>5.6.1-SNAPSHOT</version>
<version>${smartcarlife.api.version}</version>
</dependency>
<!--
<dependency>
......
package cn.com.glsx.dj.peanalysis.mapper;
import cn.com.glsx.dj.peanalysis.model.MerchantBiFollowDetail;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface MerchantBiFollowDetailMapper extends OreMapper<MerchantBiFollowDetail> {
/**
* 查询我的关注明细
*/
List<MerchantBiFollowDetail> findMyFollowDetails(@Param("staffUuid") String staffUuid);
/**
* 查询他人关注明细 (排除当前用户)
*/
List<MerchantBiFollowDetail> findOthersFollowDetails(@Param("staffUuid") String staffUuid);
/**
* 批量查询关注人姓名 (按 followId 分组)
*/
List<MerchantBiFollowDetail> findFollowersByFollowIds(@Param("followIds") List<Integer> followIds);
/**
* 根据关注 ID 和员工 UUID 查询
*/
MerchantBiFollowDetail findOneByFollowIdAndStaffUuid(@Param("followId") Integer followId, @Param("staffUuid") String staffUuid);
/**
* 根据关注 ID 列表和员工 UUID 列表查询
*/
List<MerchantBiFollowDetail> findByFollowIdsAndStaffUuids(@Param("followIds") List<Integer> followIds, @Param("staffUuid") String staffUuid);
/**
* 根据关注 ID 查询所有明细
*/
List<MerchantBiFollowDetail> findByFollowId(@Param("followId") Integer followId);
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.mapper;
import cn.com.glsx.dj.peanalysis.model.MerchantBiFollow;
import cn.com.glsx.dj.peanalysis.dto.res.output.MyFollowResponse;
import cn.com.glsx.dj.peanalysis.dto.req.output.SceneBaseReq;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface MerchantBiFollowMapper extends OreMapper<MerchantBiFollow> {
/**
* 根据门店和业务查询关注记录
*/
MerchantBiFollow findFollowByMerchantAndBiz(@Param("merchantId") Integer merchantId, @Param("businessType") Byte businessType);
/**
* 根据员工UUID查询其关注的门店+业务组合
*/
List<MyFollowResponse> findMyFollowsByStaffUuid(@Param("staffUuid") String staffUuid);
/**
* 通用查询关注门店+业务组合(支持按员工查询/排除员工、权限门店过滤)
*/
List<MyFollowResponse> findFollowsBySceneReq(@Param("req") SceneBaseReq req,
@Param("staffUuid") String staffUuid,
@Param("excludeStaffUuid") String excludeStaffUuid,
@Param("defaultIsFollow") Integer defaultIsFollow);
/**
* 批量根据门店 ID 查询关注记录
*/
List<MerchantBiFollow> findByMerchantIds(@Param("merchantIds") List<Integer> merchantIds);
/**
* 批量根据门店 ID 和业务查询关注记录
*/
List<MerchantBiFollow> findByMerchantIdsAndBiz(@Param("merchantIds") List<Integer> merchantIds, @Param("businessType") Byte businessType);
/**
* 批量根据主键 ID 查询关注记录
*/
List<MerchantBiFollow> findFollowsByIds(@Param("ids") List<Integer> ids);
/**
* 查询所有有效的关注记录
*/
List<MerchantBiFollow> findAllActiveFollows();
/**
* 查询关注数大于等于指定值的记录
*/
List<MerchantBiFollow> findByMinFollowCount(@Param("minCount") Integer minCount);
}
......@@ -10,6 +10,7 @@ import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface ServiceMerchantMapper extends OreMapper<ServiceMerchant> {
......@@ -20,8 +21,26 @@ public interface ServiceMerchantMapper extends OreMapper<ServiceMerchant> {
List<MerchantInfoDTO> queryMerchantAllInfo(MerchantQueryDTO merchantQueryDTO);
/**
* 查询门店运营人员/督导配置
*
* @param merchantIds 门店ID列表
* @param scene 场景(0=1.1,1=2.1;为空时返回两套场景字段)
*/
List<StoreSettingDTO> findStoreSetting(@Param("merchantIds") List<Integer> merchantIds, @Param("scene") Integer scene);
/**
* 招聘负责人(HRBP)关联查询:
* 通过区域运营手机号反查对应 HRBP(避免姓名重名导致的关联不准)
*/
List<Map<String, Object>> findRecruitmentHrbpByRegionOperationPhones(@Param("phones") List<String> phones);
/**
* 技师督导关联查询:
* 通过门店所属省份反查技师督导信息(按 province 精确匹配)
*/
List<Map<String, Object>> findRecruitmentTechnicalSupervisorByProvinces(@Param("provinces") List<String> provinces);
List<StoreInfo> findYydList(@Param("list") List<Integer> collected);
......
package cn.com.glsx.dj.peanalysis.mapper;
import cn.com.glsx.dj.peanalysis.model.StrategyInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.Date;
import java.util.List;
@Mapper
public interface StrategyInfoMapper extends OreMapper<StrategyInfo> {
/**
* 分页查询策略记录
*/
List<StrategyInfo> findStrategyRecords(@Param("merchantId") Integer merchantId, @Param("biz") Integer biz);
/**
* 批量查询最新动态
*/
List<StrategyInfo> findLatestStrategyRecords(@Param("merchantIds") List<Integer> merchantIds, @Param("biz") Integer biz);
/**
* 批量查询指定时间段内每个门店最新动态
*/
List<StrategyInfo> findLatestStrategyRecordsByTime(@Param("merchantIds") List<Integer> merchantIds,
@Param("biz") Integer biz,
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
/**
* 批量统计记录数
*/
List<StrategyInfo> findStrategyCounts(@Param("merchantIds") List<Integer> merchantIds, @Param("biz") Integer biz);
/**
* 批量查询记录数 + 最新记录摘要(merchantId 维度)
* <p>
* 约定:返回的 StrategyInfo.id 存储 count,createdBy/createdDate 存储最新记录信息
*/
List<StrategyInfo> findStrategyCountAndLatestSummary(@Param("merchantIds") List<Integer> merchantIds, @Param("biz") Integer biz);
/**
* 统计指定时间段内的记录数
*/
int countStrategyByTime(@Param("merchantIds") List<Integer> merchantIds, @Param("biz") Integer biz, @Param("startDate") Date startDate, @Param("endDate") Date endDate);
}
package cn.com.glsx.dj.peanalysis.mapper;
import cn.com.glsx.dj.peanalysis.model.StrategyStaffRel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
@Mapper
public interface StrategyStaffRelMapper extends OreMapper<StrategyStaffRel> {
/**
* 根据策略 ID 查询关联人
*/
List<StrategyStaffRel> findByStrategyId(@Param("strategyId") Integer strategyId);
/**
* 根据策略 ID 列表查询关联人
*/
List<StrategyStaffRel> findByStrategyIds(@Param("strategyIds") List<Integer> strategyIds);
}
package cn.com.glsx.dj.peanalysis.remote;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.dj.peanalysis.dto.analysis.StrategyRecordDTO;
import cn.com.glsx.dj.peanalysis.dto.analysis.StrategyRecordQryDTO;
import cn.com.glsx.dj.peanalysis.service.MerchantBiCommentService;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.Map;
/**
* BI-门店留言远程接口实现 (统一使用策略表存储)
*
* @author lyj
* @version 2.0
* @since 2026/03/12
*/
@Slf4j
@DubboService(validation = "true", version = "1.0.0")
public class MerchantBiCommentRemoteImpl implements MerchantBiCommentRemote {
@Autowired
private MerchantBiCommentService commentService;
@Override
public RpcResponse<Boolean> addComment(@RequestBody MerchantBiCommentReq request) {
try {
return RpcResponse.success(commentService.addComment(request));
} catch (Exception e) {
log.error("新增门店留言异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<Boolean> withdrawComment(Integer id, String staffUuid) {
try {
return RpcResponse.success(commentService.withdrawComment(id, staffUuid));
} catch (Exception e) {
log.error("撤回门店留言异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<RpcPagination<StrategyRecordDTO>> findCombinedRecords(RpcPagination<StrategyRecordQryDTO> pagination, String loginUserUuid) {
try {
return RpcResponse.success(commentService.findCombinedRecords(pagination, loginUserUuid));
} catch (Exception e) {
log.error("查询合并跟进记录异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<StrategyRecordDTO> getStrategyDetail(Integer id, Integer type) {
try {
return RpcResponse.success(commentService.getStrategyDetail(id, type));
} catch (Exception e) {
log.error("查询记录详情异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<Map<Integer, Integer>> findCommentCounts(@RequestBody MerchantBiCommentReq request) {
try {
return RpcResponse.success(commentService.findCommentCounts(request));
} catch (Exception e) {
log.error("查询门店动态条数异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
}
package cn.com.glsx.dj.peanalysis.remote;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiFollowReq;
import cn.com.glsx.dj.peanalysis.dto.req.output.SceneBaseReq;
import cn.com.glsx.dj.peanalysis.dto.res.output.MyFollowResponse;
import cn.com.glsx.dj.peanalysis.service.MerchantBiFollowService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
import java.util.Map;
/**
* BI-门店关注远程接口实现
*
* @author lyj
* @version 1.0
* @since 2026/03/12
*/
@Slf4j
@DubboService(validation = "true", version = "1.0.0")
public class MerchantBiFollowRemoteImpl implements MerchantBiFollowRemote {
@Autowired
private MerchantBiFollowService followService;
@Override
public RpcResponse<Boolean> followMerchant(@RequestBody MerchantBiFollowReq request) {
try {
return RpcResponse.success(followService.followMerchant(request));
} catch (Exception e) {
log.error("关注门店异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<List<MyFollowResponse>> myFollowList(@RequestBody SceneBaseReq request) {
try {
return RpcResponse.success(followService.myFollowList(request));
} catch (Exception e) {
log.error("查询我的关注列表异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<List<MyFollowResponse>> othersFollowList(@RequestBody SceneBaseReq request) {
try {
return RpcResponse.success(followService.othersFollowList(request));
} catch (Exception e) {
log.error("查询他人关注列表异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<Map<Integer, Integer>> findFollowStatus(@RequestBody MerchantBiFollowReq request) {
try {
return RpcResponse.success(followService.findFollowStatus(request));
} catch (Exception e) {
log.error("查询关注状态异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<Map<Integer, Integer>> findFollowCounts(@RequestBody MerchantBiFollowReq request) {
try {
return RpcResponse.success(followService.findFollowCounts(request));
} catch (Exception e) {
log.error("查询关注数异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
}
}
}
......@@ -14,13 +14,12 @@ import cn.com.glsx.dj.peanalysis.dto.job.BiRecord;
import cn.com.glsx.dj.peanalysis.dto.req.SalePotentialCustomersReq;
import cn.com.glsx.dj.peanalysis.dto.req.output.SceneBaseReq;
import cn.com.glsx.dj.peanalysis.dto.res.output.*;
import cn.com.glsx.dj.peanalysis.dto.strategy.GoodsCategorySummaryWithWarn;
import cn.com.glsx.dj.peanalysis.dto.strategy.StaffAnalysisDTO;
import cn.com.glsx.dj.peanalysis.dto.strategy.StaffSummaryDTO;
import cn.com.glsx.dj.peanalysis.dto.strategy.WarningInfo;
import cn.com.glsx.dj.peanalysis.mapper.*;
import cn.com.glsx.dj.peanalysis.util.SortUtils;
import cn.com.glsx.dj.peanalysis.utils.DateUtils;
import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils;
import cn.com.glsx.dj.peanalysis.utils.response.DataResp;
import cn.com.glsx.dj.smartcarlife.dto.StaffInfoDTO;
import cn.com.glsx.dj.smartcarlife.dto.merchantTarget.MerchantOutputTargetConfigDTO;
......@@ -34,6 +33,7 @@ import cn.com.glsx.merchants.dto.merchant.CarBrandProvinceRequestDTO;
import cn.com.glsx.merchants.model.request.MerchantStaffRequest;
import cn.com.glsx.merchants.model.response.MerchantProvinceDTO;
import cn.com.glsx.merchants.model.response.MerchantStaffResponse;
import cn.com.glsx.merchants.model.response.merchant.MerchantBasicInfoListResponse;
import cn.com.glsx.merchants.remote.MerchantRemote;
import cn.com.glsx.merchants.remote.MerchantStaffRemote;
import cn.hutool.core.date.DateField;
......@@ -77,10 +77,14 @@ public class BusinessSceneAnalysisService {
private UsedCarDataStatsService usedCarDataStatsService;
@Resource
private MerchantStaffRemote merchantStaffRemote;
@Resource
private MerchantRemote merchantRemote;
@Resource
private MerchantHrbpRelationService merchantHrbpRelationService;
@Resource
private MerchantOutputTargetConfigRemote merchantOutputTargetConfigRemote;
@Resource
......@@ -99,6 +103,12 @@ public class BusinessSceneAnalysisService {
private BusinessIntelligenceMapper businessIntelligenceMapper;
@Resource
private MerchantBiFollowService merchantBiFollowService;
@Resource
private MerchantBasicInfoService merchantBasicInfoService;
@Resource
private GetDataStatsService getDataStatsService;
@Resource
......@@ -117,7 +127,6 @@ public class BusinessSceneAnalysisService {
private MonitoringRemote monitoringRemote;
/**
* 总产值、目标产值、达成率
*/
......@@ -125,7 +134,7 @@ public class BusinessSceneAnalysisService {
SceneOutputResponse res = new SceneOutputResponse();
try {
req.setMerchantIds(getMerchantIdPermission(req));
}catch (Exception e){
} catch (Exception e) {
return res;
}
......@@ -140,21 +149,21 @@ public class BusinessSceneAnalysisService {
}
log.info("查询总产值:{}", totalOutputList);
DataBusinessDTO totalOutput = mergeDataList(totalOutputList);
res.setOutputValue(scaleItemValue(totalOutput.getItemValue()));
res.setOutputValueMon(scaleItemValue(totalOutput.getRate()));
res.setOutputValue(MetricsValueUtils.scale2(totalOutput.getItemValue()));
res.setOutputValueMon(MetricsValueUtils.scale2(totalOutput.getRate()));
// 查询目标产值(周期=月时才展示)
if (queryParams.getDateType() == 2) {
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
Map<Integer, BigDecimal> storeTargetOutputMap = queryStoreTargetOutput(req);
if (MapUtils.isNotEmpty(storeTargetOutputMap)) {
res.setTargetOutputValue(storeTargetOutputMap.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add));
// 计算达成率
res.setRatio(computeOutputRatio(res.getOutputValue(), res.getTargetOutputValue()));
res.setRatio(MetricsValueUtils.computeOutputRatio(res.getOutputValue(), res.getTargetOutputValue()));
}
}
......@@ -163,27 +172,33 @@ public class BusinessSceneAnalysisService {
/**
* 查询产值门店号列表
*
* @param req
* @return
*/
private List<Integer> getMerchantIdPermission(SceneBaseReq req){
public List<Integer> getMerchantIdPermission(SceneBaseReq req) {
// 上周期+本周期权限范围才能计算环比
return getMerchantIdPermission(req, true);
}
private List<Integer> getMerchantIdPermission(SceneBaseReq req, boolean containLast) {
public List<Integer> getMerchantIdPermission(SceneBaseReq req, boolean containLast) {
return getMerchantIdPermission(req, DataStatsConstants.ITEM_CODE_A036, containLast);
}
private List<Integer> getMerchantIdPermission(SceneBaseReq req, boolean containLast, boolean filterPermission) {
public List<Integer> getMerchantIdPermission(SceneBaseReq req, boolean containLast, boolean filterPermission) {
return getMerchantIdPermission(req, DataStatsConstants.ITEM_CODE_A036, containLast, filterPermission);
}
/**
* 查询指定指标数据的权限门店号列表
*
* @param req
* @return
*/
private List<Integer> getMerchantIdPermission(SceneBaseReq req, String itemCode, boolean containLast) {
return getMerchantIdPermission(req, itemCode, containLast, false);
}
private List<Integer> getMerchantIdPermission(SceneBaseReq req, String itemCode, boolean containLast, boolean filterPermission) {
List<Integer> merchantIds = req.getMerchantIds();
if (StringUtils.isNotBlank(itemCode)) {
......@@ -192,7 +207,7 @@ public class BusinessSceneAnalysisService {
queryParams.setItemCodes(itemCode);
queryParams.setExts("merchantIds");
if (containLast) {
queryParams.setStartDate(DateUtils.offsetDateWithCycleType(queryParams.getStartDate(), req.getCycleType(),-1));
queryParams.setStartDate(DateUtils.offsetDateWithCycleType(queryParams.getStartDate(), req.getCycleType(), -1));
}
List<DataBusinessDTO> totalOutputList = businessAnalysisService.getTotalOutputGroupByMerchant(queryParams);
if (CollectionUtils.isEmpty(totalOutputList)) {
......@@ -224,14 +239,14 @@ public class BusinessSceneAnalysisService {
}
public List<Integer> filterStoreTypeAndCategoryPermission(List<Integer> merchantIdList, SceneBaseReq request) {
if(CollectionUtils.isEmpty(merchantIdList)) {
if (CollectionUtils.isEmpty(merchantIdList)) {
return merchantIdList;
}
if(Objects.isNull(request.getStoreType()) && Objects.isNull(request.getBusinessCategory())) {
if (Objects.isNull(request.getStoreType()) && Objects.isNull(request.getBusinessCategory())) {
return merchantIdList;
}
List<BiRecord> list = getBiRecords(null, merchantIdList, request.getStartTime(), request.getEndTime());
if(CollectionUtils.isEmpty(list)) {
if (CollectionUtils.isEmpty(list)) {
return Collections.emptyList();
}
List<Integer> permissionList = new ArrayList<>();
......@@ -286,7 +301,7 @@ public class BusinessSceneAnalysisService {
/**
* 查询门店产值目标
*/
private Map<Integer, BigDecimal> queryStoreTargetOutput(SceneBaseReq req) {
public Map<Integer, BigDecimal> queryStoreTargetOutput(SceneBaseReq req) {
Map<Integer, BigDecimal> res = new HashMap<>();
DataBizQueryParamsDTO queryParams = req.convertQueryParam();
......@@ -319,25 +334,13 @@ public class BusinessSceneAnalysisService {
}
/**
* 达成率=(总产值/目标产值)*100%,保留百分比两位小数,即xx.xx%;
*/
private BigDecimal computeOutputRatio(BigDecimal outputValue, BigDecimal outputTargetValue) {
if (outputValue == null || outputTargetValue == null || outputTargetValue.compareTo(BigDecimal.ZERO) == 0) {
return null;
}
return outputValue
.multiply(new BigDecimal(100))
.divide(outputTargetValue, 2, RoundingMode.HALF_UP);
}
/**
* 产值趋势及达成率
* 支持指定门店查询,指定员工查询
*/
public List<TrendOutputResponse> trendOutput(SceneBaseReq req) {
long startTime = System.currentTimeMillis(); // 记录开始时间,用于性能监控
log.info("开始查询产值趋势及达成率,请求参数: {}, 开始时间: {}", JSON.toJSONString(req), startTime);
List<TrendOutputResponse> res;
// 判断是否需要计算达成率(仅在周期类型为月且需要显示目标比率时)
boolean isMonth = req.getCycleType() == 3 && req.isWithTargetRatio();
......@@ -355,7 +358,7 @@ public class BusinessSceneAnalysisService {
// 一次性查询全部时间范围内的指标数据,存储为按周期段分组的Map
Map<Pair<String, String>, List<DataBusinessDTO>> datePairDataMap = new HashMap<>();
try {
// 获取门店权限ID列表
List<Integer> merchantIds = getMerchantIdPermission(req, false);
......@@ -365,30 +368,30 @@ public class BusinessSceneAnalysisService {
// 准备查询指标数据的参数 - 利用指标系统本身支持的周期查询和门店聚合
DataBizQueryParamsDTO queryParams = req.convertQueryParam();
queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
// 自定义的周期,在进行指标查询趋势图时,需要改为按日周期去查
if (queryParams.getDateType() == 4) {
queryParams.setDateType(0);
}
if (CollectionUtils.isEmpty(req.getItemCodeList())) {
queryParams.setItemCodes(DataStatsConstants.ITEM_CODE_A036);
} else {
// 暂时只处理一个指标
queryParams.setItemCodes(req.getItemCodeList().get(0));
}
// 设置查询时间范围 - 一次性查询整个时间范围,提高查询效率
queryParams.setStartDate(req.getStartTime());
queryParams.setEndDate(req.getEndTime());
// 使用exts=merchantIds实现按门店聚合
if (isMonth) {
queryParams.setExts("merchantIds");
}
log.info("准备查询参数: {}", JSON.toJSONString(queryParams));
// 一次性查询整个时间范围内的数据,避免按周期段多次查询
String queryJson = JSON.toJSONString(queryParams);
log.info("发送查询请求JSON: {}", queryJson);
......@@ -396,25 +399,25 @@ public class BusinessSceneAnalysisService {
List<DataBusinessDTO> fullRangeDataList = fullRangeDataResp.getContent();
List<DataBusinessDTO> actualDataList = fullRangeDataList != null ? fullRangeDataList : new ArrayList<>();
log.info("获取全范围数据完成,数据条数: {}", actualDataList.size());
// 按周期段对数据进行分组 - 在内存中完成周期聚合,减少数据库查询
log.info("开始按周期段对数据进行分组...");
for (Pair<String, String> datePair : datePairRange) {
String cycleStart = datePair.getKey();
String cycleEnd = datePair.getValue();
// 根据数据的时间字段筛选属于当前周期段的数据
List<DataBusinessDTO> cycleData = actualDataList.stream()
.filter(data -> isDataInPeriod(data, cycleStart, cycleEnd))
.collect(Collectors.toList());
log.info("周期段 {}-{} 匹配到数据条数: {}", cycleStart, cycleEnd, cycleData.size());
// 即使没有数据也添加空列表,确保返回结果数量与查询周期一致
datePairDataMap.put(datePair, cycleData);
}
log.info("数据分组完成");
} catch (Exception e) {
log.error("获取门店产值权限失败,构建默认趋势图,异常信息: ", e);
}
......@@ -423,13 +426,13 @@ public class BusinessSceneAnalysisService {
int range = dateRange.size();
res = new ArrayList<>();
log.info("开始构建返回结果,总共 {} 个周期段", range);
for (int i = 0; i < dateRange.size(); i++) {
DateTime beginTime = dateRange.get(i);
String begin = DateUtil.formatDate(beginTime);
String end = DateUtil.formatDate(DateUtils.getEndTimeWithCycleType(beginTime, req.getCycleType()));
Pair<String, String> key = Pair.of(begin, end);
// 创建趋势输出响应对象,初始化基础字段
TrendOutputResponse item = new TrendOutputResponse();
item.setOutput(BigDecimal.ZERO); // 产值初始化为0
......@@ -437,7 +440,7 @@ public class BusinessSceneAnalysisService {
item.setRatio(BigDecimal.ZERO); // 达成率初始化为0
item.setStartTime(begin); // 设置开始时间
item.setEndTime(end); // 设置结束时间
// 根据周期类型设置时间显示格式
switch (req.getCycleType()) {
case 1: // 按日
......@@ -452,16 +455,16 @@ public class BusinessSceneAnalysisService {
item.setTime(th == 0 ? "当前周" : "前" + th + "周");
break;
}
// 获取当前周期段的数据
List<DataBusinessDTO> dataList = datePairDataMap.get(key);
log.info("周期段 {}-{} 的数据条数: {}", begin, end, CollectionUtils.isEmpty(dataList) ? 0 : dataList.size());
if (!CollectionUtils.isEmpty(dataList)) {
// 提取当前周期段涉及的门店ID列表
List<Integer> merchantIdsInPeriod = dataList.stream().map(p -> p.getMerchantId()).collect(Collectors.toList());
log.info("周期段 {}-{} 涉及门店ID: {}", begin, end, merchantIdsInPeriod);
// 合并当前周期段的所有数据
DataBusinessDTO data = mergeDataList(dataList);
// 设置产值
......@@ -478,23 +481,23 @@ public class BusinessSceneAnalysisService {
pairReq.setEndTime(end); // 设置查询结束时间
log.info("查询目标产值,门店ID: {}, 时间段: {}-{}", merchantIdsInPeriod, begin, end);
// 根据周期节点的门店ID范围查询目标产值
Map<Integer, BigDecimal> targetOutputMap = queryStoreTargetOutput(pairReq);
BigDecimal pairTargetOutput = targetOutputMap.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
log.info("查询时间段: {}, 门店: {}, 累计产值: {}, 目标产值:{}", key, merchantIdsInPeriod, data.getItemValue(), pairTargetOutput);
// 计算达成率 = 产值 / 目标产值
item.setRatio(ObjectUtil.defaultIfNull(computeOutputRatio(item.getOutput(), pairTargetOutput), BigDecimal.ZERO));
item.setRatio(ObjectUtil.defaultIfNull(MetricsValueUtils.computeOutputRatio(item.getOutput(), pairTargetOutput), BigDecimal.ZERO));
}
} else {
log.info("周期段 {}-{} 没有匹配到数据", begin, end);
}
// 添加到结果列表
res.add(item);
}
long endTime = System.currentTimeMillis();
log.info("查询产值趋势及达成率完成,结果数量: {},耗时: {} ms,结果: {}", res.size(), (endTime - startTime), res);
return res;
......@@ -503,33 +506,33 @@ public class BusinessSceneAnalysisService {
/**
* 判断数据是否在指定周期内
* 通过比较数据的时间字段与周期段范围来确定数据归属
*
* @param data 数据对象
*
* @param data 数据对象
* @param cycleStart 周期开始时间
* @param cycleEnd 周期结束时间
* @param cycleEnd 周期结束时间
* @return 如果数据在指定周期内返回true,否则返回false
*/
private boolean isDataInPeriod(DataBusinessDTO data, String cycleStart, String cycleEnd) {
// 使用返回数据的开始和结束时间字段来匹配周期段
String dataStartDate = data.getStartDate();
String dataEndDate = data.getEndDate();
// 检查数据的周期是否与当前查询周期段匹配
// 优先检查startDate/endDate字段,这是数据的标准时间范围字段
if (dataStartDate != null && dataEndDate != null) {
// 确保数据的开始时间在当前周期段内,或者数据的结束时间在当前周期段内
// 或者数据的周期完全覆盖当前周期段(数据周期包含查询周期)
boolean isWithinRange = (dataStartDate.compareTo(cycleStart) >= 0 && dataStartDate.compareTo(cycleEnd) <= 0) ||
(dataEndDate.compareTo(cycleStart) >= 0 && dataEndDate.compareTo(cycleEnd) <= 0) ||
(dataStartDate.compareTo(cycleStart) <= 0 && dataEndDate.compareTo(cycleEnd) >= 0);
(dataEndDate.compareTo(cycleStart) >= 0 && dataEndDate.compareTo(cycleEnd) <= 0) ||
(dataStartDate.compareTo(cycleStart) <= 0 && dataEndDate.compareTo(cycleEnd) >= 0);
// 添加调试日志,帮助排查数据匹配问题
if (log.isDebugEnabled()) {
log.info("数据时间范围匹配 - 数据ID: {}, 数据开始: {}, 数据结束: {}, 查询开始: {}, 查询结束: {}, 匹配结果: {}",
data.getMerchantId(), dataStartDate, dataEndDate, cycleStart, cycleEnd, isWithinRange);
data.getMerchantId(), dataStartDate, dataEndDate, cycleStart, cycleEnd, isWithinRange);
}
return isWithinRange;
}
// 如果startDate/endDate不匹配或为空,尝试使用date字段作为备用
String dataDate = data.getDate();
if (dataDate != null) {
......@@ -537,12 +540,12 @@ public class BusinessSceneAnalysisService {
// 添加调试日志,帮助排查数据匹配问题
if (log.isDebugEnabled()) {
log.info("使用date字段匹配 - 数据ID: {}, 数据日期: {}, 查询开始: {}, 查询结束: {}, 匹配结果: {}",
data.getMerchantId(), dataDate, cycleStart, cycleEnd, isMatch);
data.getMerchantId(), dataDate, cycleStart, cycleEnd, isMatch);
}
// 检查单日期字段是否在周期范围内
return isMatch;
}
// 如果都没有匹配的日期字段,返回false(更安全的做法)
if (log.isDebugEnabled()) {
log.info("数据无有效时间字段 - 数据ID: {}, 数据: {}", data.getMerchantId(), JSON.toJSONString(data));
......@@ -745,6 +748,7 @@ public class BusinessSceneAnalysisService {
req.setTempList(merchantIdList);
return true;
}
/**
* 处理延保预警门店
*/
......@@ -757,6 +761,7 @@ public class BusinessSceneAnalysisService {
res.setEcosystemWarningStoreIds(storeIds);
res.setEcosystemWarningStores(storeIds.size());
}
public List<Integer> handleDelayWarningStore(SceneBaseReq req, String startDate, String endDate) {
//过滤鸿蒙智行门店
if (!filterHarmonyStore(req)) {
......@@ -896,6 +901,7 @@ public class BusinessSceneAnalysisService {
res.setEcosystemWarningStoreIds(storeIds);
res.setEcosystemWarningStores(storeIds.size());
}
public List<Integer> handleLightChangeWarningStore(SceneBaseReq req, String startDate, String endDate) {
//过滤鸿蒙智行门店
if (!filterHarmonyStore(req)) {
......@@ -1033,7 +1039,7 @@ public class BusinessSceneAnalysisService {
List<TrafficSummaryResponse> res = new ArrayList<>();
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
......@@ -1120,7 +1126,7 @@ public class BusinessSceneAnalysisService {
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
......@@ -1134,7 +1140,7 @@ public class BusinessSceneAnalysisService {
if (CollectionUtils.isEmpty(dataResp.getContent())) {
log.warn("查询指标返回空, req:{}, res:{}", queryParams, dataResp);
dataMerchantMap = new HashMap<>();
}else {
} else {
List<DataBusinessDTO> dataList = dataResp.getContent();
if (CollectionUtils.isNotEmpty(req.getExcludeIds())) {
dataList = dataList.stream()
......@@ -1250,7 +1256,7 @@ public class BusinessSceneAnalysisService {
List<ContactRateAnalysisResponse> res = new ArrayList<>();
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
......@@ -1270,12 +1276,12 @@ public class BusinessSceneAnalysisService {
.filter(p -> p.getProvinceCode() != null)
.collect(Collectors.groupingBy(p -> p.getProvinceCode()));
res = groupByProvince.values().stream().map(merchants -> {
ContactRateAnalysisResponse item = new ContactRateAnalysisResponse();
item.setProvinceId(merchants.get(0).getProvinceCode());
item.setProvinceName(merchants.stream().map(MerchantProvinceDTO::getProvinceName).filter(StringUtils::isNotBlank).findFirst().orElse(""));
item.setMerchantIds(merchants.stream().map(p -> p.getMerchantId()).distinct().collect(Collectors.toList()));
return item;
}).collect(Collectors.toList());
ContactRateAnalysisResponse item = new ContactRateAnalysisResponse();
item.setProvinceId(merchants.get(0).getProvinceCode());
item.setProvinceName(merchants.stream().map(MerchantProvinceDTO::getProvinceName).filter(StringUtils::isNotBlank).findFirst().orElse(""));
item.setMerchantIds(merchants.stream().map(p -> p.getMerchantId()).distinct().collect(Collectors.toList()));
return item;
}).collect(Collectors.toList());
// 分区域查指标
Map<String, ContactRateAnalysisResponse> resMap = res.stream()
......@@ -1297,7 +1303,7 @@ public class BusinessSceneAnalysisService {
if (dateList.size() > 1) {
log.warn("聚合数据异常, dateList.size()={}", dateList.size());
}
resMap.get(provinceId).setContactRate(convertPercentage(dateList.get(0).getItemValue()));
resMap.get(provinceId).setContactRate(MetricsValueUtils.toPercentage(dateList.get(0).getItemValue()));
});
res = new ArrayList<>(resMap.values());
......@@ -1346,22 +1352,6 @@ public class BusinessSceneAnalysisService {
}
/**
* 转为百分比
*/
public String convertPercentage(String val) {
if (StringUtils.isBlank(val)) {
return null;
}
return convertPercentage(new BigDecimal(val)).toString();
}
public BigDecimal convertPercentage(BigDecimal val) {
if (val == null) {
return null;
}
return val.multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
}
/**
* 合并多个指标数值,并计算环比
*/
public DataBusinessDTO mergeDataList(List<DataBusinessDTO> dataList) {
......@@ -1372,7 +1362,7 @@ public class BusinessSceneAnalysisService {
DataBusinessDTO first = dataList.get(0);
if (dataList.size() == 1) {
if (StringUtils.isNotBlank(first.getRate())) {
first.setRate(convertPercentage(first.getRate()));
first.setRate(MetricsValueUtils.toPercentageString(first.getRate()));
}
return first;
}
......@@ -1384,7 +1374,7 @@ public class BusinessSceneAnalysisService {
res.setPreValue(dataList.stream().map(p -> p.getPreValue()).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
BigDecimal rate = computeMon(res.getItemValue(), res.getPreValue());
if (rate != null) {
res.setRate(convertPercentage(rate).toString());
res.setRate(MetricsValueUtils.toPercentage(rate).toString());
}
return res;
......@@ -1409,7 +1399,7 @@ public class BusinessSceneAnalysisService {
// 获取产值门店
try {
req.setMerchantIds(getMerchantIdPermission(req, false, true));
}catch (Exception e){
} catch (Exception e) {
return res;
}
// 查询指标
......@@ -1494,7 +1484,7 @@ public class BusinessSceneAnalysisService {
public List<StoreListResponse> storeList(SceneBaseReq req) {
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
}catch (Exception e){
} catch (Exception e) {
return Collections.emptyList();
}
......@@ -1533,27 +1523,27 @@ public class BusinessSceneAnalysisService {
// todo forEach取最后一个元素进行赋值有问题
dataList.stream()
.filter(data -> resMap.containsKey(data.getMerchantId()) && Objects.nonNull(data.getItemValue()))
.forEach(data -> resMap.get(data.getMerchantId()).setCustomerContactRate(convertPercentage(data.getItemValue())));
.forEach(data -> resMap.get(data.getMerchantId()).setCustomerContactRate(MetricsValueUtils.toPercentage(data.getItemValue())));
break;
case DataStatsConstants.ITEM_CODE_A085:
dataList.stream()
.filter(data -> resMap.containsKey(data.getMerchantId()) && Objects.nonNull(data.getItemValue()))
.forEach(data -> resMap.get(data.getMerchantId()).setConversionRate(convertPercentage(data.getItemValue())));
.forEach(data -> resMap.get(data.getMerchantId()).setConversionRate(MetricsValueUtils.toPercentage(data.getItemValue())));
break;
case DataStatsConstants.ITEM_CODE_A077:
dataList.stream()
.filter(data -> resMap.containsKey(data.getMerchantId()) && Objects.nonNull(data.getItemValue()))
.forEach(data -> resMap.get(data.getMerchantId()).setPenetrationRate(convertPercentage(data.getItemValue())));
.forEach(data -> resMap.get(data.getMerchantId()).setPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue())));
break;
case DataStatsConstants.ITEM_CODE_A076:
dataList.stream()
.filter(data -> resMap.containsKey(data.getMerchantId()) && Objects.nonNull(data.getItemValue()))
.forEach(data -> resMap.get(data.getMerchantId()).setUpgradeCustomerPrice(scaleItemValue(data.getItemValue())));
.forEach(data -> resMap.get(data.getMerchantId()).setUpgradeCustomerPrice(MetricsValueUtils.scale2(data.getItemValue())));
break;
case DataStatsConstants.ITEM_CODE_A095:
dataList.stream()
.filter(data -> resMap.containsKey(data.getMerchantId()) && Objects.nonNull(data.getItemValue()))
.forEach(data -> resMap.get(data.getMerchantId()).setAvgCustomerPrice(scaleItemValue(data.getItemValue())));
.forEach(data -> resMap.get(data.getMerchantId()).setAvgCustomerPrice(MetricsValueUtils.scale2(data.getItemValue())));
break;
}
});
......@@ -1563,11 +1553,14 @@ public class BusinessSceneAnalysisService {
if (item == null) {
return;
}
item.setAchievementRate(computeOutputRatio(item.getOutputValue(), outputTargetValue));
item.setAchievementRate(MetricsValueUtils.computeOutputRatio(item.getOutputValue(), outputTargetValue));
});
List<StoreListResponse> res = new ArrayList<>(resMap.values());
// 填充关注状态和留言数
merchantBiFollowService.fillFollowAndComment(res, req);
// 计算兜底预警、生态预警标识
// 兜底预警门店:触发兜底预警的门店数;
String startDate = queryParams.getStartDate();
......@@ -1607,12 +1600,29 @@ public class BusinessSceneAnalysisService {
// merchantBiMatterMapper.selectMyBiMatterCount();
// 排序: 支持选择「按产值」「按达成率」「按触客率」「按转化率」「按渗透率」「按升级客单价」「按平均客单价」及排序顺序「从大到小」「从小到大」切换排序规则;默认=「按产值」+「从大到小」
SortUtils.sortList(res, req);
// 排序: 支持选择「按产值」「按达成率」「按触客率」「按转化率」「按渗透率」「按升级客单价」「按平均客单价」及排序顺序「从大到小」「从小到大」切换排序规则;默认=「按产值」+「从大到小」(存在兜底预警或生态指标异常门店优先置顶)
Comparator<StoreListResponse> priorityComparator = (o1, o2) -> {
boolean w1 = isWarningStore(o1);
boolean w2 = isWarningStore(o2);
if (w1 && !w2) return -1;
if (!w1 && w2) return 1;
return 0;
};
// 先按预警状态排序,再按原有规则排序
res.sort(priorityComparator.thenComparing(SortUtils.getComparator(StoreListResponse.class, req)));
return res;
}
private boolean isWarningStore(StoreListResponse store) {
if (CollectionUtils.isEmpty(store.getStoreStatus())) {
return false;
}
// 2: 兜底预警, 3: 生态指标预警
return store.getStoreStatus().contains("2") || store.getStoreStatus().contains("3");
}
/**
* 门店分析
* <p>
......@@ -1627,12 +1637,14 @@ public class BusinessSceneAnalysisService {
public StoreDetailSummaryResponse storeDetailSummary(SceneBaseReq req) {
StoreDetailSummaryResponse res = new StoreDetailSummaryResponse();
DataBizQueryParamsDTO queryParams = req.convertQueryParam();
long startMs = System.currentTimeMillis();
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
// 查询门店信息、所属服务商、区域运营、销售、线上运营
// 查询门店信息:所属服务商、区域运营、销售、线上运营
Integer sceneType = req.convertToSceneType(queryParams.getBizs());
List<StoreSettingDTO> storeList = serviceMerchantMapper.findStoreSetting(req.getMerchantIds(), sceneType);
if (CollectionUtils.isNotEmpty(storeList)) {
......@@ -1640,13 +1652,27 @@ public class BusinessSceneAnalysisService {
BeanUtils.copyProperties(settingDTO, res);
}
// 查询门店信息:招聘负责人
if (StringUtils.isBlank(res.getRecruitmentManager()) && StringUtils.isNotBlank(res.getRegionalOperationId())) {
Pair<String, String> hrbp = merchantHrbpRelationService
.findRecruitmentManagerByRegionalOperationIds(res.getRegionalOperationId(), req.getBizs() == null ? null : req.getBizs().byteValue());
if (hrbp != null && StringUtils.isNotBlank(hrbp.getKey())) {
res.setRecruitmentManager(hrbp.getKey());
}
}
// 查询门店信息:技师督导
MerchantBasicInfoListResponse merchantInfo = merchantBasicInfoService.queryMerchantBasicInfo(req.getMerchantIds().get(0));
merchantBasicInfoService.fillStoreDetailTechnicianSupervisor(res, merchantInfo, req.getBizs());
// 查询指标
queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
List<String> itemCodes = Lists.newArrayList(DataStatsConstants.ITEM_CODE_A036, DataStatsConstants.ITEM_CODE_A062,
DataStatsConstants.ITEM_CODE_A085, DataStatsConstants.ITEM_CODE_A077, DataStatsConstants.ITEM_CODE_A064,
DataStatsConstants.ITEM_CODE_A063, DataStatsConstants.ITEM_CODE_A096, DataStatsConstants.ITEM_CODE_A084,
DataStatsConstants.ITEM_CODE_A097, DataStatsConstants.ITEM_CODE_A098, DataStatsConstants.ITEM_CODE_A075,
DataStatsConstants.ITEM_CODE_A0104, DataStatsConstants.ITEM_CODE_A0105);
DataStatsConstants.ITEM_CODE_A0104, DataStatsConstants.ITEM_CODE_A0105,
DataStatsConstants.ITEM_CODE_A076, DataStatsConstants.ITEM_CODE_A095);
Map<String, List<DataBusinessDTO>> dataMap = getDataStatsService.parallelCallListMap(itemCodes, queryParams);
if (MapUtils.isEmpty(dataMap)) {
log.warn("查询门店分析指标异常. req: {}, itemCodes: {}", JSON.toJSONString(queryParams), itemCodes);
......@@ -1656,67 +1682,78 @@ public class BusinessSceneAnalysisService {
DataBusinessDTO data = mergeDataList(dataList);
switch (code) {
case DataStatsConstants.ITEM_CODE_A036:
res.setTotalOutputValue(scaleItemValue(data.getItemValue()));
res.setTotalOutputValue(MetricsValueUtils.scale2(data.getItemValue()));
res.setTotalOutputValueMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A062:
res.setNewCarDeliveryCount(scaleItemValue(data.getItemValue()));
res.setNewCarDeliveryCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setNewCarDeliveryCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A085:
res.setConversionRate(convertPercentage(data.getItemValue()));
res.setConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.setConversionRateMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A077:
res.setPenetrationRate(convertPercentage(data.getItemValue()));
res.setPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.setPenetrationRateMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A064:
res.setContactRate(convertPercentage(data.getItemValue()));
res.setContactRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.setContactRateMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A084:
res.setTotalContactCount(scaleItemValue(data.getItemValue()));
res.setTotalContactCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setTotalContactCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A063:
res.setPreSalesContactCount(scaleItemValue(data.getItemValue()));
res.setPreSalesContactCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setPreSalesContactCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A096:
res.setAfterSalesContactCount(scaleItemValue(data.getItemValue()));
res.setAfterSalesContactCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setAfterSalesContactCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A075:
res.setTotalDealCount(scaleItemValue(data.getItemValue()));
res.setTotalDealCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setTotalDealCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A097:
res.setPreSalesDealCount(scaleItemValue(data.getItemValue()));
res.setPreSalesDealCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setPreSalesDealCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A098:
res.setAfterSalesDealCount(scaleItemValue(data.getItemValue()));
res.setAfterSalesDealCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setAfterSalesDealCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A0104:
res.setPreSalesConversionRate(convertPercentage(data.getItemValue()));
res.setPreSalesConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.setPreSalesConversionRateMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A0105:
res.setAfterSalesConversionRate(convertPercentage(data.getItemValue()));
res.setAfterSalesConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.setAfterSalesConversionRateMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A076:
res.setUpgradeCustomerPrice(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A095:
res.setAvgCustomerPrice(MetricsValueUtils.scale2(data.getItemValue()));
break;
}
});
// 填充目标平客价 (取最近一次嘀加上架记录中的预估目标客单价)
res.setTargetAvgCustomerPrice(queryTargetAvgCustomerPrice(req));
// 查询达成率
Map<Integer, BigDecimal> storeTargetOutputMap = queryStoreTargetOutput(req);
storeTargetOutputMap.forEach((merchantId, outputTargetValue) -> {
res.setTargetOutputValue(outputTargetValue);
res.setAchievementRate(computeOutputRatio(res.getTotalOutputValue(), res.getTargetOutputValue()));
res.setAchievementRate(MetricsValueUtils.computeOutputRatio(res.getTotalOutputValue(), res.getTargetOutputValue()));
});
log.info("storeDetailSummary: done, merchantIds={}, biz={}, costMs={}",
req.getMerchantIds(), req.getBizs(), System.currentTimeMillis() - startMs);
return res;
}
......@@ -1732,7 +1769,7 @@ public class BusinessSceneAnalysisService {
try {
req.setMerchantIds(getMerchantIdPermission(req, null, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
......@@ -1750,21 +1787,21 @@ public class BusinessSceneAnalysisService {
case DataStatsConstants.ITEM_CODE_A036:
dataMap.forEach((staffId, data) -> {
StoreEmployeeRankResponse.EmployeeAnalysisItem item = empMap.getOrDefault(staffId, new StoreEmployeeRankResponse.EmployeeAnalysisItem(data));
item.setPersonalOutputValue(scaleItemValue(data.getItemValue()));
item.setPersonalOutputValue(MetricsValueUtils.scale2(data.getItemValue()));
empMap.put(data.getStaffId(), item);
});
break;
case DataStatsConstants.ITEM_CODE_A076:
dataMap.forEach((staffId, data) -> {
StoreEmployeeRankResponse.EmployeeAnalysisItem item = empMap.getOrDefault(staffId, new StoreEmployeeRankResponse.EmployeeAnalysisItem(data));
item.setPersonalCustomerPrice(scaleItemValue(data.getItemValue()));
item.setPersonalCustomerPrice(MetricsValueUtils.scale2(data.getItemValue()));
empMap.put(data.getStaffId(), item);
});
break;
case DataStatsConstants.ITEM_CODE_A085:
dataMap.forEach((staffId, data) -> {
StoreEmployeeRankResponse.EmployeeAnalysisItem item = empMap.getOrDefault(staffId, new StoreEmployeeRankResponse.EmployeeAnalysisItem(data));
item.setPersonalConversionRate(convertPercentage(data.getItemValue()));
item.setPersonalConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
empMap.put(data.getStaffId(), item);
});
break;
......@@ -1783,7 +1820,7 @@ public class BusinessSceneAnalysisService {
DataBusinessDTO merchantData = mergeDataList(dataList);
switch (code) {
case DataStatsConstants.ITEM_CODE_A036:
storeSummary.setTotalOutputValue(scaleItemValue(merchantData.getItemValue()));
storeSummary.setTotalOutputValue(MetricsValueUtils.scale2(merchantData.getItemValue()));
storeSummary.setAverageOutputValue(merchantData.getItemValue()
.divide(BigDecimal.valueOf(empCount), 2, RoundingMode.HALF_UP));
break;
......@@ -1819,7 +1856,7 @@ public class BusinessSceneAnalysisService {
try {
req.setMerchantIds(getMerchantIdPermission(req, null, false));
}catch (Exception e){
} catch (Exception e) {
return Collections.emptyList();
}
......@@ -1854,7 +1891,7 @@ public class BusinessSceneAnalysisService {
DataBizQueryParamsDTO queryParams = req.convertQueryParam();
try {
req.setMerchantIds(getMerchantIdPermission(req, null, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
// 查询指标
......@@ -1875,47 +1912,47 @@ public class BusinessSceneAnalysisService {
DataBusinessDTO data = mergeDataList(dataList);
switch (code) {
case DataStatsConstants.ITEM_CODE_A036:
res.setTotalOutputValue(scaleItemValue(data.getItemValue()));
res.setTotalOutputValue(MetricsValueUtils.scale2(data.getItemValue()));
res.setTotalOutputValueMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A076:
res.setAvgCustomerPrice(scaleItemValue(data.getItemValue()));
res.setAvgCustomerPrice(MetricsValueUtils.scale2(data.getItemValue()));
res.setAvgCustomerPriceMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A063:
res.setPreSalesContactCount(scaleItemValue(data.getItemValue()));
res.setPreSalesContactCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setPreSalesContactCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A096:
res.setAfterSalesContactCount(scaleItemValue(data.getItemValue()));
res.setAfterSalesContactCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setAfterSalesContactCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A084:
res.setTotalContactCount(scaleItemValue(data.getItemValue()));
res.setTotalContactCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setTotalContactCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A097:
res.setPreSalesDealCount(scaleItemValue(data.getItemValue()));
res.setPreSalesDealCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setPreSalesDealCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A098:
res.setAfterSalesDealCount(scaleItemValue(data.getItemValue()));
res.setAfterSalesDealCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setAfterSalesDealCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A075:
res.setTotalDealCount(scaleItemValue(data.getItemValue()));
res.setTotalDealCount(MetricsValueUtils.scale2(data.getItemValue()));
res.setTotalDealCountMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A0104:
res.setPreSalesConversionRate(convertPercentage(data.getItemValue()));
res.setPreSalesConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.setPreSalesConversionRateMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A0105:
res.setAfterSalesConversionRate(convertPercentage(data.getItemValue()));
res.setAfterSalesConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.setAfterSalesConversionRateMom(data.getRate());
break;
case DataStatsConstants.ITEM_CODE_A085:
res.setConversionRate(convertPercentage(data.getItemValue()));
res.setConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.setConversionRateMom(data.getRate());
break;
}
......@@ -1938,20 +1975,6 @@ public class BusinessSceneAnalysisService {
return res;
}
private BigDecimal scaleItemValue(BigDecimal val) {
if (Objects.isNull(val)) {
return null;
}
return val.setScale(2, RoundingMode.HALF_UP);
}
private String scaleItemValue(String val) {
if (StringUtils.isBlank(val)) {
return null;
}
return new BigDecimal(val).setScale(2, RoundingMode.HALF_UP).toString();
}
// public Map<String, StaffAnalysisDTO> queryStaffWarningInfo(SceneBaseReq req) {
// DataBizQueryParamsDTO queryParams = req.convertQueryParam();
// Integer bizs = queryParams.getBizs();
......@@ -1982,97 +2005,97 @@ public class BusinessSceneAnalysisService {
switch (code) {
// 新车交付数
case DataStatsConstants.ITEM_CODE_A062:
res.setNewCarDeliveryCount(scaleItemValue(data.getItemValue()));
res.setNewCarDeliveryCount(MetricsValueUtils.scale2(data.getItemValue()));
break;
// 整车延保
case DataStatsConstants.ITEM_CODE_A066: // 整车延保-成交数
res.setVehicleWarrantyDealCount(scaleItemValue(data.getItemValue()));
res.setVehicleWarrantyDealCount(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A067: // 整车延保-渗透率
case DataStatsConstants.ITEM_CODE_A0100: // 整车延保-渗透率
res.setVehicleWarrantyPenetrationRate(convertPercentage(data.getItemValue()));
res.setVehicleWarrantyPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.computeVehicleWarrantyEcoCoefficient(); // 整车延保-生态系数
break;
case DataStatsConstants.ITEM_CODE_A099: // 整车延保-转化率
res.setVehicleWarrantyConversionRate(convertPercentage(data.getItemValue()));
res.setVehicleWarrantyConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
// 安心包延保
case DataStatsConstants.ITEM_CODE_A086: // 安心包-成交数
res.setSafetyPackageDealCount(scaleItemValue(data.getItemValue()));
res.setSafetyPackageDealCount(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A092: // 安心包-渗透率
case DataStatsConstants.ITEM_CODE_A0101: // 安心包-渗透率
res.setSafetyPackagePenetrationRate(convertPercentage(data.getItemValue()));
res.setSafetyPackagePenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.computeSafetyPackageEcoCoefficient(); // 安心包-生态系数
break;
case DataStatsConstants.ITEM_CODE_A089: // 安心包-转化率
res.setSafetyPackageConversionRate(convertPercentage(data.getItemValue()));
res.setSafetyPackageConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
// 电池延保
case DataStatsConstants.ITEM_CODE_A070: // 电池延保-成交数
res.setBatteryWarrantyDealCount(scaleItemValue(data.getItemValue()));
res.setBatteryWarrantyDealCount(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A094: // 电池延保-渗透率
case DataStatsConstants.ITEM_CODE_A0103: // 电池延保-渗透率
res.setBatteryWarrantyPenetrationRate(convertPercentage(data.getItemValue()));
res.setBatteryWarrantyPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.computeBatteryWarrantyEcoCoefficient(); // 电池延保-生态系数
break;
case DataStatsConstants.ITEM_CODE_A091: // 电池延保-转化率
res.setBatteryWarrantyConversionRate(convertPercentage(data.getItemValue()));
res.setBatteryWarrantyConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
// 轮胎延保
case DataStatsConstants.ITEM_CODE_A087: // 轮胎延保-成交数
res.setTireWarrantyDealCount(scaleItemValue(data.getItemValue()));
res.setTireWarrantyDealCount(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A093: // 轮胎延保-渗透率
case DataStatsConstants.ITEM_CODE_A0102: // 轮胎延保-渗透率
res.setTireWarrantyPenetrationRate(convertPercentage(data.getItemValue()));
res.setTireWarrantyPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
// res.computeTireWarrantyEcoCoefficient(); // 轮胎无需计算生态系数
break;
case DataStatsConstants.ITEM_CODE_A090: // 轮胎延保-转化率
res.setTireWarrantyConversionRate(convertPercentage(data.getItemValue()));
res.setTireWarrantyConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
// 轻改-车窗膜
case DataStatsConstants.ITEM_CODE_A0106: // 车窗膜-成交数
res.setWindowFilmDealCount(scaleItemValue(data.getItemValue()));
res.setWindowFilmDealCount(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A0108: // 车窗膜-渗透率
case DataStatsConstants.ITEM_CODE_A0110: // 车窗膜-渗透率
res.setWindowFilmPenetrationRate(convertPercentage(data.getItemValue()));
res.setWindowFilmPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A0109: // 车窗膜-转化率
res.setWindowFilmConversionRate(convertPercentage(data.getItemValue()));
res.setWindowFilmConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A0107: // 车窗膜-产值
res.setWindowFilmPerCarOutput(scaleItemValue(data.getItemValue()));
res.setWindowFilmPerCarOutput(MetricsValueUtils.scale2(data.getItemValue()));
break;
// 轻改-车身膜
case DataStatsConstants.ITEM_CODE_A0111: // 车身膜-成交数
res.setCarBodyFilmDealCount(scaleItemValue(data.getItemValue()));
res.setCarBodyFilmDealCount(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A0113: // 车身膜-渗透率
case DataStatsConstants.ITEM_CODE_A0115: // 车身膜-渗透率
res.setCarBodyFilmPenetrationRate(convertPercentage(data.getItemValue()));
res.setCarBodyFilmPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A0114: // 车身膜-转化率
res.setCarBodyFilmConversionRate(convertPercentage(data.getItemValue()));
res.setCarBodyFilmConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A0112: // 车身膜-产值
res.setCarBodyFilmPerCarOutput(scaleItemValue(data.getItemValue()));
res.setCarBodyFilmPerCarOutput(MetricsValueUtils.scale2(data.getItemValue()));
break;
// 轻改-精品附件
case DataStatsConstants.ITEM_CODE_A0116: // 精品附件-成交数
res.setAccessoriesDealCount(scaleItemValue(data.getItemValue()));
res.setAccessoriesDealCount(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A0118: // 精品附件-渗透率
case DataStatsConstants.ITEM_CODE_A0120: // 精品附件-渗透率
res.setAccessoriesPenetrationRate(convertPercentage(data.getItemValue()));
res.setAccessoriesPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A0119: // 精品附件-转化率
res.setAccessoriesConversionRate(convertPercentage(data.getItemValue()));
res.setAccessoriesConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A0117: // 精品附件-产值
res.setAccessoriesPerCarOutput(scaleItemValue(data.getItemValue()));
res.setAccessoriesPerCarOutput(MetricsValueUtils.scale2(data.getItemValue()));
break;
}
......@@ -2086,7 +2109,7 @@ public class BusinessSceneAnalysisService {
try {
req.setMerchantIds(getMerchantIdPermission(req, null, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
......@@ -2202,15 +2225,16 @@ public class BusinessSceneAnalysisService {
/**
* 处理员工禁用标识
*
* @param staffList 员工列表
* @param req 场景请求参数
* @param staffIds 员工ID列表
* @param req 场景请求参数
* @param staffIds 员工ID列表
*/
public void handlerStaffStatus(List<StaffAnalysisDTO> staffList, SceneBaseReq req, List<String> staffIds) {
StaffInfoDTO staffParam = new StaffInfoDTO();
staffParam.setStaffUuidList(staffIds);
staffParam.setShopMerchantId(req.getMerchantIds().get(0));
staffParam.setSubMerchantTypeList(Arrays.asList(6,8));
staffParam.setSubMerchantTypeList(Arrays.asList(6, 8));
staffParam.setSceneType(req.getSceneType());
staffParam.setStaffDeletedFlags(Arrays.asList(BaseModel.DeletedFlagEnum.N.name(), BaseModel.DeletedFlagEnum.D.name(), "I"));
RpcResponse<List<StaffInfoDTO>> listRpcResponse = staffInfoRemote.listBySceneShop(staffParam);
......@@ -2225,7 +2249,7 @@ public class BusinessSceneAnalysisService {
.filter(x -> ObjectUtil.isNotNull(x.getStaffUuid()))
.collect(Collectors.toMap(StaffInfoDTO::getStaffUuid, StaffInfoDTO::getDeletedFlag, (oldValue, newValue) -> oldValue));
}
for(StaffAnalysisDTO staff : staffList) {
for (StaffAnalysisDTO staff : staffList) {
String deletedFlag = staffDisabledFlagMap.get(staff.getStaffId());
staff.setStaffStatus(deletedFlag);
}
......@@ -2233,9 +2257,10 @@ public class BusinessSceneAnalysisService {
/**
* 处理员工预警信息
*
* @param staffList 员工列表
* @param req 场景请求参数
* @param staffIds 员工ID列表
* @param req 场景请求参数
* @param staffIds 员工ID列表
*/
public void handlerStaffWarning(List<StaffAnalysisDTO> staffList, SceneBaseReq req, List<String> staffIds) {
//查询预警信息
......@@ -2244,7 +2269,7 @@ public class BusinessSceneAnalysisService {
//根据员工id,匹配预警信息
Map<String, List<MonitoringMsgDTO>> staffWarningMap = warningMsgList.stream().filter(x -> ObjectUtil.isNotNull(x.getStaffId()))
.collect(Collectors.groupingBy(MonitoringMsgDTO::getStaffId));
for(StaffAnalysisDTO staff : staffList) {
for (StaffAnalysisDTO staff : staffList) {
List<MonitoringMsgDTO> warningMsg = staffWarningMap.get(staff.getStaffId());
if (CollectionUtils.isEmpty(warningMsg)) continue;
List<WarningInfo> warningInfoList = warningMsg.stream().map(x -> {
......@@ -2279,7 +2304,6 @@ public class BusinessSceneAnalysisService {
/**
*
* @param bizs 业务类型(1.延保 2.轻改 3.权益)
* @return
*/
......@@ -2296,12 +2320,13 @@ public class BusinessSceneAnalysisService {
return null;
}
}
/**
* 驻店员工时长统计
*/
public Integer summaryStaffDuration(SceneBaseReq req) {
//计算员工驻店时长,直接取业务表中,订单有支付时间就算有产值
Integer businessType =convertBizToBusinessType(req.getBizs());
Integer businessType = convertBizToBusinessType(req.getBizs());
return goodsOrderMapper.summaryStaffDuration(req.getMerchantIds(), req.getStaffUuids(), businessType, req.getSceneType());
}
......@@ -2312,6 +2337,12 @@ public class BusinessSceneAnalysisService {
return wariningList.stream().map(MonitoringMsgDTO::getWarningText).collect(Collectors.toList());
}
private BigDecimal queryTargetAvgCustomerPrice(SceneBaseReq req) {
// 实现获取最近一次嘀加上架记录中的预估目标客单价的逻辑
// 目前暂无该表具体 Mapper,先返回 null
return null;
}
/**
* 查询兜底预警门店
*
......
......@@ -24,6 +24,7 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@Service
@Slf4j
......@@ -52,6 +53,30 @@ public class GetDataStatsService {
return dataResp;
}
public List<DataBusinessDTO> getListData(DataBizQueryParamsDTO queryDataBiz) {
if (queryDataBiz == null) {
return new ArrayList<>();
}
String jsonBody = JSONUtil.toJsonStr(queryDataBiz);
return getListData(jsonBody);
}
/**
* 直接以 JSON 请求体查询指标系统并返回明细列表
* <p>
* 适用于需要传入字符串形式的聚合字段(例如 bizs/itemCodes 以逗号拼接)且保持 exts 维度返回的场景。
*/
public List<DataBusinessDTO> getListData(String jsonBody) {
try {
DataResp<List<DataBusinessDTO>> dataResp = this.getListDataResp(jsonBody);
return dataResp.getContent();
} catch (Exception e) {
log.error("查询统计数据异常,jsonBody={}", jsonBody, e);
throw new RpcServiceException("查询统计数据异常");
}
}
/**
* 通用并行调用方法 - 返回Map: 指标代码 -> 数据
* @param itemCodes 指标编码列表
......@@ -258,4 +283,33 @@ public class GetDataStatsService {
return resultMap;
}
/**
* 串行调用,拿到数据后分组处理
* @param itemCodes 指标编码列表
* @param queryDataBiz 请求参数
* @return
*/
public Map<String, List<DataBusinessDTO>> serialCallListMap(List<String> itemCodes, DataBizQueryParamsDTO queryDataBiz) {
String itemCodeParam = String.join(",", itemCodes);
Map<String, List<DataBusinessDTO>> resultMap = new ConcurrentHashMap<>();
DataBizQueryParamsDTO queryCopy = new DataBizQueryParamsDTO();
BeanUtil.copyProperties(queryDataBiz, queryCopy);
queryCopy.setItemCodes(itemCodeParam);
String jsonBody = JSONUtil.toJsonStr(queryCopy);
try {
DataResp<List<DataBusinessDTO>> dataResp = this.getListDataResp(jsonBody);
List<DataBusinessDTO> content = dataResp.getContent();
if (CollUtil.isEmpty(content)) {
log.info("itemCodeParam:{}, dataResp:{}", itemCodeParam, JSONUtil.toJsonPrettyStr(dataResp));
return null;
}
resultMap = content.stream().collect(Collectors.groupingBy(p -> p.getItemCode()));
} catch (Exception e) {
log.error("Error processing itemCodeParam: {}, cause: {}", itemCodeParam, ExceptionUtils.getStackTrace(e));
return resultMap;
}
return resultMap;
}
}
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.res.output.MyFollowResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.StoreDetailSummaryResponse;
import cn.com.glsx.dj.peanalysis.mapper.ServiceMerchantMapper;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.merchants.model.request.merchant.MerchantBasicInfoRequest;
import cn.com.glsx.merchants.model.request.merchant.MerchantInfoSwitch;
import cn.com.glsx.merchants.model.response.merchant.MerchantBasicInfoListResponse;
import cn.com.glsx.merchants.remote.MerchantRemote;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
public class MerchantBasicInfoService {
@Autowired
private MerchantRemote merchantRemote;
@Autowired
private ServiceMerchantMapper serviceMerchantMapper;
/**
* 批量查询门店基础信息(省/市/主营品牌等),返回 Map<merchantId, info>
*/
public Map<Integer, MerchantBasicInfoListResponse> queryMerchantBasicInfoMap(List<Integer> merchantIds) {
if (CollectionUtils.isEmpty(merchantIds)) {
return Collections.emptyMap();
}
List<Integer> distinctMerchantIds = merchantIds.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
if (CollectionUtils.isEmpty(distinctMerchantIds)) {
return Collections.emptyMap();
}
long startMs = System.currentTimeMillis();
MerchantBasicInfoRequest merchantRequest = new MerchantBasicInfoRequest();
merchantRequest.setPageNum(1);
merchantRequest.setPageSize(Integer.MAX_VALUE);
merchantRequest.setMerchantIdList(distinctMerchantIds);
merchantRequest.setMerchantInfoSwitch(MerchantInfoSwitch.builder().brandFlag(true).build());
RpcResponse<RpcPagination<MerchantBasicInfoListResponse>> merchantInfoResp = merchantRemote.findMerchantBasicInfoList(merchantRequest);
if (merchantInfoResp == null || !merchantInfoResp.hasResult() || merchantInfoResp.getResult() == null) {
log.warn("查询门店基础信息失败:门店数={}, costMs={}", distinctMerchantIds.size(), System.currentTimeMillis() - startMs);
return Collections.emptyMap();
}
List<MerchantBasicInfoListResponse> list = merchantInfoResp.getResult().getList();
if (CollectionUtils.isEmpty(list)) {
log.info("查询门店基础信息为空:门店数={}, costMs={}", distinctMerchantIds.size(), System.currentTimeMillis() - startMs);
return Collections.emptyMap();
}
Map<Integer, MerchantBasicInfoListResponse> map = list.stream()
.filter(p -> p != null && p.getMerchantId() != null)
.collect(Collectors.toMap(MerchantBasicInfoListResponse::getMerchantId, p -> p, (p1, p2) -> p2));
log.info("查询门店基础信息完成:入参门店数={}, 返回门店数={}, costMs={}",
distinctMerchantIds.size(), map.size(), System.currentTimeMillis() - startMs);
return map;
}
/**
* 单门店基础信息查询(复用批量查询逻辑)
*/
public MerchantBasicInfoListResponse queryMerchantBasicInfo(Integer merchantId) {
if (merchantId == null) {
return null;
}
Map<Integer, MerchantBasicInfoListResponse> map = queryMerchantBasicInfoMap(Collections.singletonList(merchantId));
return map.get(merchantId);
}
/**
* 为关注列表回填:主营品牌 + 省/市区域(格式:省/市)
*/
public void fillFollowListMerchantInfo(List<MyFollowResponse> resList) {
if (CollectionUtils.isEmpty(resList)) {
return;
}
List<Integer> merchantIds = resList.stream()
.map(MyFollowResponse::getStoreId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(merchantIds)) {
return;
}
Map<Integer, MerchantBasicInfoListResponse> merchantInfoMap = queryMerchantBasicInfoMap(merchantIds);
if (merchantInfoMap.isEmpty()) {
return;
}
long startMs = System.currentTimeMillis();
resList.forEach(p -> {
Integer storeId = p.getStoreId();
if (storeId == null) {
return;
}
MerchantBasicInfoListResponse merchantInfo = merchantInfoMap.get(storeId);
if (merchantInfo == null) {
return;
}
p.setBrandName(merchantInfo.getMerchantBrandMain());
p.setProvinceName(merchantInfo.getProvinceName());
p.setCityName(merchantInfo.getCityName());
});
log.info("关注列表门店信息填充完成:门店数={}, costMs={}", merchantIds.size(), System.currentTimeMillis() - startMs);
}
/**
* 批量查询技师督导映射(省份 -> 技师督导姓名)
*/
public Map<String, String> queryTechnicianSupervisorMapByProvinces(List<String> provinces) {
if (CollectionUtils.isEmpty(provinces)) {
return Collections.emptyMap();
}
List<String> distinct = provinces.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
if (CollectionUtils.isEmpty(distinct)) {
return Collections.emptyMap();
}
long startMs = System.currentTimeMillis();
List<Map<String, Object>> rows = serviceMerchantMapper.findRecruitmentTechnicalSupervisorByProvinces(distinct);
if (CollectionUtils.isEmpty(rows)) {
log.info("查询技师督导映射为空:省份数={}, costMs={}", distinct.size(), System.currentTimeMillis() - startMs);
return Collections.emptyMap();
}
Map<String, String> result = new HashMap<>();
rows.forEach(row -> {
String province = Objects.toString(row.get("province"), "");
String supervisorName = Objects.toString(row.get("supervisorName"), "");
if (StringUtils.isNotBlank(province) && StringUtils.isNotBlank(supervisorName)) {
result.put(province, supervisorName);
}
});
log.info("查询技师督导映射完成:省份数={}, 映射数={}, costMs={}", distinct.size(), result.size(), System.currentTimeMillis() - startMs);
return result;
}
/**
* 门店详情填充技师督导(依赖门店所属省份与省份督导映射)
* <p>
* 约定:不需要展示或无匹配时保持字段为 null,由前端兜底渲染。
*/
public void fillStoreDetailTechnicianSupervisor(StoreDetailSummaryResponse res, MerchantBasicInfoListResponse merchantInfo, Integer biz) {
if (res == null || merchantInfo == null) {
return;
}
if (biz != null && (biz == 1 || biz == 3)) {
return;
}
String provinceName = merchantInfo.getProvinceName();
if (StringUtils.isBlank(provinceName)) {
return;
}
Map<String, String> map = queryTechnicianSupervisorMapByProvinces(Collections.singletonList(provinceName));
String supervisorName = map.get(provinceName);
if (StringUtils.isNotBlank(supervisorName)) {
res.setTechnicianSupervisor(supervisorName);
}
}
}
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.dj.peanalysis.dto.analysis.StrategyRecordDTO;
import cn.com.glsx.dj.peanalysis.dto.analysis.StrategyRecordQryDTO;
import cn.com.glsx.dj.peanalysis.mapper.StrategyInfoMapper;
import cn.com.glsx.dj.peanalysis.mapper.StrategyStaffRelMapper;
import cn.com.glsx.dj.peanalysis.model.StrategyInfo;
import cn.com.glsx.dj.peanalysis.model.StrategyStaffRel;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/**
* BI-门店留言与策略服务实现 (统一使用策略表存储)
*
* @author lyj
* @version 2.0
* @since 2026/03/16
*/
@Slf4j
@Service
public class MerchantBiCommentService {
@Autowired
private StrategyInfoMapper strategyInfoMapper;
@Autowired
private StrategyStaffRelMapper strategyStaffRelMapper;
@Autowired
private WechatPushService wechatPushService;
private static final Integer STRATEGY_TYPE_COMMENT = 7;
/**
* 新增留言 (映射为策略类型 7)
*/
@Transactional(rollbackFor = Exception.class)
public Boolean addComment(MerchantBiCommentReq request) {
// 1. 插入策略主表
StrategyInfo strategy = StrategyInfo.builder()
.strategyType(STRATEGY_TYPE_COMMENT)
.title("留言-" + request.getStaffName())
.content(request.getContent())
.merchantId(request.getMerchantId())
.merchantName(request.getMerchantName())
.biz(request.getBusinessType() != null ? request.getBusinessType().intValue() : null)
.createdUuid(request.getStaffUuid())
.createdBy(request.getStaffName())
.createdDate(new Date())
.updatedBy(request.getStaffName())
.updatedDate(new Date())
.deletedFlag("N")
.pushType(0)
.pushFlag(0)
.build();
boolean success = strategyInfoMapper.insertSelective(strategy) > 0;
if (success && StringUtils.isNotBlank(request.getHandlerStaffUuid())) {
// 2. 插入处理人关联表 (@ 提醒)
String[] uuids = request.getHandlerStaffUuid().split("/");
String[] names = StringUtils.isNotBlank(request.getHandlerStaffName()) ? request.getHandlerStaffName().split("/") : new String[uuids.length];
for (int i = 0; i < uuids.length; i++) {
StrategyStaffRel rel = StrategyStaffRel.builder()
.strategyId(strategy.getId())
.userUuid(uuids[i])
.userName(i < names.length ? names[i] : "")
.createdBy(request.getStaffName())
.createdDate(new Date())
.deletedFlag("N")
.build();
strategyStaffRelMapper.insertSelective(rel);
}
// 3. 企微推送 (@ 提醒)
try {
wechatPushService.pushMentionMsg(request.getStaffName(), request.getMerchantName(),
getBusinessTypeName(request.getBusinessType()), Arrays.asList(uuids));
} catch (Exception e) {
log.error("触发留言 @ 推送异常", e);
}
}
return success;
}
/**
* 撤回/删除留言 (逻辑删除)
*/
@Transactional(rollbackFor = Exception.class)
public Boolean withdrawComment(Integer id, String staffUuid) {
StrategyInfo strategy = strategyInfoMapper.selectByPrimaryKey(id);
if (strategy == null) {
return false;
}
if (staffUuid != null && !staffUuid.equals(strategy.getCreatedUuid())) {
throw new RpcServiceException("只能撤回本人发布的留言");
}
if (!STRATEGY_TYPE_COMMENT.equals(strategy.getStrategyType())) {
throw new RpcServiceException("仅支持撤回留言类型的记录");
}
strategy.setDeletedFlag("D");
strategy.setUpdatedDate(new Date());
return strategyInfoMapper.updateByPrimaryKeySelective(strategy) > 0;
}
/**
* 获取记录详情 (支持 5 种策略类型)
*/
public StrategyRecordDTO getStrategyDetail(Integer id, Integer type) {
StrategyInfo s = strategyInfoMapper.selectByPrimaryKey(id);
if (s == null || "D".equals(s.getDeletedFlag())) {
return null;
}
StrategyRecordDTO dto = new StrategyRecordDTO();
dto.setId(s.getId());
dto.setType(s.getStrategyType());
dto.setTitle(s.getTitle());
dto.setContent(s.getContent());
dto.setCreatorName(s.getCreatedBy());
dto.setCreatorUuid(s.getCreatedUuid());
dto.setCreatedDate(s.getCreatedDate());
// 查询处理人 (@ 提及的人) (XML Mapper 优化)
List<StrategyStaffRel> rels = strategyStaffRelMapper.findByStrategyId(s.getId());
if (CollectionUtils.isNotEmpty(rels)) {
dto.setHandlerName(rels.stream().map(StrategyStaffRel::getUserName).collect(Collectors.joining("/")));
}
// 根据不同类型填充特定字段 (这里根据需求文档中的详情描述进行扩展)
// ... 学习类、优惠案例等字段填充
return dto;
}
/**
* 批量查询最新动态 (用于列表摘要展示)
*/
public Map<Integer, String> findLatestComments(MerchantBiCommentReq request) {
if (CollectionUtils.isEmpty(request.getMerchantIds())) {
return Collections.emptyMap();
}
long startMs = System.currentTimeMillis();
// XML Mapper 优化: 一次性查出每个门店最晚的记录
List<StrategyInfo> latestDynamics = strategyInfoMapper.findLatestStrategyRecords(
request.getMerchantIds(),
request.getBusinessType() != null ? request.getBusinessType().intValue() : null
);
if (CollectionUtils.isEmpty(latestDynamics)) {
return Collections.emptyMap();
}
Map<Integer, String> result = new HashMap<>();
latestDynamics.forEach(strategy -> {
String timeAgo = cn.com.glsx.dj.peanalysis.utils.DateUtils.formatTimeAgo(strategy.getCreatedDate());
result.put(strategy.getMerchantId(), String.format("「%s」,「%s」已添加跟进策略(留言)", timeAgo, strategy.getCreatedBy()));
});
log.info("查询最新动态摘要完成:biz={}, 门店数={}, 返回数={}, 耗时={}ms",
request.getBusinessType(), request.getMerchantIds().size(), result.size(), System.currentTimeMillis() - startMs);
return result;
}
/**
* 批量查询指定时间范围内的最新动态(按 merchantId 去重,仅取 created_date 最大的一条)
* <p>
* 用于关注列表/门店列表等“只展示最近一条”的场景,避免全量查询导致压力过大。
*/
public Map<Integer, StrategyInfo> findLatestStrategiesByTime(MerchantBiCommentReq request, Date startDate, Date endDate) {
if (request == null || CollectionUtils.isEmpty(request.getMerchantIds()) || startDate == null || endDate == null) {
return Collections.emptyMap();
}
long startMs = System.currentTimeMillis();
List<StrategyInfo> latestDynamics = strategyInfoMapper.findLatestStrategyRecordsByTime(
request.getMerchantIds(),
request.getBusinessType() != null ? request.getBusinessType().intValue() : null,
startDate,
endDate
);
if (CollectionUtils.isEmpty(latestDynamics)) {
log.info("查询最近一月最新动态:为空,biz={}, 门店数={}", request.getBusinessType(), request.getMerchantIds().size());
return Collections.emptyMap();
}
Map<Integer, StrategyInfo> result = new HashMap<>();
latestDynamics.forEach(strategy -> result.put(strategy.getMerchantId(), strategy));
log.info("查询最近一月最新动态完成:biz={}, 门店数={}, 返回数={}, 耗时={}ms",
request.getBusinessType(), request.getMerchantIds().size(), result.size(), System.currentTimeMillis() - startMs);
return result;
}
/**
* 批量查询留言/动态条数
*/
public Map<Integer, Integer> findCommentCounts(MerchantBiCommentReq request) {
if (CollectionUtils.isEmpty(request.getMerchantIds())) {
return Collections.emptyMap();
}
// XML Mapper 优化
List<StrategyInfo> counts = strategyInfoMapper.findStrategyCounts(
request.getMerchantIds(),
request.getBusinessType() != null ? request.getBusinessType().intValue() : null
);
Map<Integer, Integer> result = new HashMap<>();
request.getMerchantIds().forEach(id -> result.put(id, 0));
if (CollectionUtils.isNotEmpty(counts)) {
counts.forEach(c -> result.put(c.getMerchantId(), c.getId())); // 借用 id 字段存储 count
}
return result;
}
/**
* 批量查询留言条数 + 最新留言摘要(一次 SQL 完成)
* <p>
* 约定:StrategyInfo.id 存储 count,createdBy/createdDate 为最新记录信息。
*/
public Map<Integer, StrategyInfo> findCommentCountAndLatestSummary(MerchantBiCommentReq request) {
if (request == null || CollectionUtils.isEmpty(request.getMerchantIds())) {
return Collections.emptyMap();
}
long startMs = System.currentTimeMillis();
List<StrategyInfo> summaries = strategyInfoMapper.findStrategyCountAndLatestSummary(
request.getMerchantIds(),
request.getBusinessType() != null ? request.getBusinessType().intValue() : null
);
if (CollectionUtils.isEmpty(summaries)) {
log.info("查询留言摘要(count+latest)为空:biz={}, 门店数={}, costMs={}",
request.getBusinessType(), request.getMerchantIds().size(), System.currentTimeMillis() - startMs);
return Collections.emptyMap();
}
Map<Integer, StrategyInfo> result = summaries.stream()
.filter(s -> s != null && s.getMerchantId() != null)
.collect(Collectors.toMap(StrategyInfo::getMerchantId, s -> s, (s1, s2) -> s1));
log.info("查询留言摘要(count+latest)完成:biz={}, 门店数={}, 返回数={}, costMs={}",
request.getBusinessType(), request.getMerchantIds().size(), result.size(), System.currentTimeMillis() - startMs);
return result;
}
/**
* 获取合并记录 (留言 + 策略) -> 现在直接查策略表即可
*/
public RpcPagination<StrategyRecordDTO> findCombinedRecords(RpcPagination<StrategyRecordQryDTO> pagination, String loginUserUuid) {
StrategyRecordQryDTO qry = pagination.getCondition();
// 1. 设置 PageHelper
PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
// 2. 查询策略表 (XML Mapper 优化)
List<StrategyInfo> list = strategyInfoMapper.findStrategyRecords(
qry.getMerchantId(),
qry.getBusinessType() != null ? qry.getBusinessType().intValue() : null
);
PageInfo<StrategyInfo> pageInfo = new PageInfo<>(list);
List<StrategyRecordDTO> dtoList = new ArrayList<>();
// 3. 转换并查询处理人 (批量查询以优化性能) (XML Mapper 优化)
if (CollectionUtils.isNotEmpty(list)) {
List<Integer> strategyIds = list.stream().map(StrategyInfo::getId).collect(Collectors.toList());
List<StrategyStaffRel> allRels = strategyStaffRelMapper.findByStrategyIds(strategyIds);
Map<Integer, List<StrategyStaffRel>> relMap = allRels.stream().collect(Collectors.groupingBy(StrategyStaffRel::getStrategyId));
for (StrategyInfo s : list) {
StrategyRecordDTO dto = new StrategyRecordDTO();
dto.setId(s.getId());
dto.setType(s.getStrategyType());
dto.setTitle(s.getStrategyType() == STRATEGY_TYPE_COMMENT ? "留言-" + s.getCreatedBy() : s.getTitle());
dto.setContent(s.getContent());
dto.setCreatorName(s.getCreatedBy());
dto.setCreatorUuid(s.getCreatedUuid());
dto.setCreatedDate(s.getCreatedDate());
dto.setIsMine(s.getCreatedUuid() != null && s.getCreatedUuid().equals(loginUserUuid) ? 1 : 0);
List<StrategyStaffRel> rels = relMap.get(s.getId());
if (CollectionUtils.isNotEmpty(rels)) {
dto.setHandlerName(rels.stream().map(StrategyStaffRel::getUserName).collect(Collectors.joining("/")));
}
dtoList.add(dto);
}
}
// 4. 封装结果
RpcPagination<StrategyRecordDTO> result = new RpcPagination<>();
result.setPageNum(pageInfo.getPageNum());
result.setPageSize(pageInfo.getPageSize());
result.setTotal(pageInfo.getTotal());
result.setList(dtoList);
return result;
}
/**
* 统计昨日新增记录总数
*/
public int countYesterdayComments(MerchantBiCommentReq request) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date yesterdayStart = calendar.getTime();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date yesterdayEnd = calendar.getTime();
// XML Mapper 优化
return strategyInfoMapper.countStrategyByTime(
request.getMerchantIds(),
request.getBusinessType() != null ? request.getBusinessType().intValue() : null,
yesterdayStart,
yesterdayEnd
);
}
private String getBusinessTypeName(Byte businessType) {
if (businessType == null) return "未知业务";
switch (businessType) {
case 1:
return "延保";
case 2:
return "轻改";
case 3:
return "权益";
default:
return "未知业务";
}
}
}
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.config.DataStatsConfig;
import cn.com.glsx.dj.peanalysis.config.DataStatsConstants;
import cn.com.glsx.dj.peanalysis.dto.DataBizQueryParamsDTO;
import cn.com.glsx.dj.peanalysis.dto.DataBusinessDTO;
import cn.com.glsx.dj.peanalysis.dto.StoreSettingDTO;
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.req.output.SceneBaseReq;
import cn.com.glsx.dj.peanalysis.dto.res.output.MyFollowResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.StoreListResponse;
import cn.com.glsx.dj.peanalysis.mapper.MerchantBiFollowDetailMapper;
import cn.com.glsx.dj.peanalysis.mapper.MerchantBiFollowMapper;
import cn.com.glsx.dj.peanalysis.mapper.ServiceMerchantMapper;
import cn.com.glsx.dj.peanalysis.model.MerchantBiFollow;
import cn.com.glsx.dj.peanalysis.model.MerchantBiFollowDetail;
import cn.com.glsx.dj.peanalysis.model.StrategyInfo;
import cn.com.glsx.dj.peanalysis.utils.DateUtils;
import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils;
import cn.com.glsx.dj.smartcarlife.remote.MerchantOutputTargetConfigRemote;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.framework.core.util.RpcAssert;
import cn.hutool.core.lang.Pair;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
* BI-门店关注服务实现
*
* @author lyj
* @version 1.0
* @since 2026/03/12
*/
@Slf4j
@Service
public class MerchantBiFollowService {
@Autowired
private MerchantBiFollowMapper followMapper;
@Autowired
private MerchantBiFollowDetailMapper followDetailMapper;
@Autowired
private ServiceMerchantMapper serviceMerchantMapper;
@Autowired
private BusinessSceneAnalysisService businessSceneAnalysisService;
@Autowired
private MerchantBiCommentService commentService;
@Autowired
private GetDataStatsService getDataStatsService;
@Autowired
private DataStatsConfig dataStatsConfig;
@Autowired
private MerchantOutputTargetConfigRemote merchantOutputTargetConfigRemote;
@Autowired
private MerchantHrbpRelationService merchantHrbpRelationService;
@Autowired
private MerchantBasicInfoService merchantBasicInfoService;
/**
* 关注/取消关注门店
*/
@Autowired
private WechatPushService wechatPushService;
@Transactional(rollbackFor = Exception.class)
public Boolean followMerchant(MerchantBiFollowReq request) {
if (request.getMerchantId() == null || request.getBusinessType() == null || StringUtils.isBlank(request.getStaffUuid())) {
log.warn("关注操作参数不完整,直接返回false: merchantId={}, businessType={}, staffUuid={}",
request.getMerchantId(), request.getBusinessType(), request.getStaffUuid());
return false;
}
long startMs = System.currentTimeMillis();
// 1. 获取或创建门店关注主表记录
MerchantBiFollow follow = getOrCreateFollow(request);
if (follow == null || follow.getId() == null) {
log.error("获取或创建门店关注记录失败: {}", request);
return false;
}
// 2. 检查是否已经关注
MerchantBiFollowDetail existingDetail = followDetailMapper.findOneByFollowIdAndStaffUuid(follow.getId(), request.getStaffUuid());
boolean success = false;
if (Objects.equals(request.getOperateType(), 1)) { // 关注
if (existingDetail != null) {
log.info("关注门店:已关注无需重复关注,merchantId={}, biz={}, staffUuid={}",
request.getMerchantId(), request.getBusinessType(), request.getStaffUuid());
return true; // 已经关注
}
// 插入明细
MerchantBiFollowDetail detail = MerchantBiFollowDetail.builder()
.followId(follow.getId())
.staffUuid(request.getStaffUuid())
.staffPhone(request.getStaffPhone())
.staffName(request.getStaffName())
.createdBy(request.getStaffName())
.createdDate(new Date())
.updatedBy(request.getStaffName())
.updatedDate(new Date())
.deletedFlag("N")
.build();
followDetailMapper.insertSelective(detail);
// 更新计数
follow.setFollowCount((follow.getFollowCount() == null ? 0 : follow.getFollowCount()) + 1);
follow.setUpdatedDate(new Date());
success = followMapper.updateByPrimaryKeySelective(follow) > 0;
// 推送逻辑 (场景1)
if (success) {
triggerFollowPush(request);
}
} else if (Objects.equals(request.getOperateType(), 0)) { // 取消关注
if (existingDetail == null) {
log.info("取消关注门店:本来未关注,无需处理,merchantId={}, biz={}, staffUuid={}",
request.getMerchantId(), request.getBusinessType(), request.getStaffUuid());
return true; // 本来就没关注
}
// 逻辑删除明细
existingDetail.setDeletedFlag("D"); // 修改为 'D' 以匹配通用的逻辑删除标识
existingDetail.setUpdatedDate(new Date());
followDetailMapper.updateByPrimaryKeySelective(existingDetail);
// 更新计数
int newCount = (follow.getFollowCount() == null ? 0 : follow.getFollowCount()) - 1;
follow.setFollowCount(Math.max(0, newCount));
follow.setUpdatedDate(new Date());
success = followMapper.updateByPrimaryKeySelective(follow) > 0;
}
log.info("关注操作完成:merchantId={}, biz={}, staffUuid={}, operateType={}, success={}, costMs={}",
request.getMerchantId(), request.getBusinessType(), request.getStaffUuid(), request.getOperateType(), success, System.currentTimeMillis() - startMs);
return success;
}
public List<MyFollowResponse> myFollowList(SceneBaseReq req) {
RpcAssert.assertNotNull(req.getLoginUserUuid(), DefaultErrorEnum.SERVER_ERROR, "当前用户未登录,返回空列表");
long startMs = System.currentTimeMillis();
List<MyFollowResponse> resList = followMapper.findMyFollowsByStaffUuid(req.getLoginUserUuid());
if (CollectionUtils.isEmpty(resList)) {
log.info("查询我的关注列表:为空,loginUserUuid={}", req.getLoginUserUuid());
return Collections.emptyList();
}
log.info("查询我的关注列表:开始填充扩展信息,loginUserUuid={}, 关注条数={}", req.getLoginUserUuid(), resList.size());
fillFollowDetails(resList, req);
log.info("查询我的关注列表完成:loginUserUuid={}, 条数={}, 耗时={}ms",
req.getLoginUserUuid(), resList.size(), System.currentTimeMillis() - startMs);
return resList;
}
public List<MyFollowResponse> othersFollowList(SceneBaseReq req) {
RpcAssert.assertNotNull(req.getLoginUserUuid(), DefaultErrorEnum.SERVER_ERROR, "当前用户未登录,返回空列表");
long startMs = System.currentTimeMillis();
List<MyFollowResponse> resList;
List<Integer> originMerchantIds = req.getMerchantIds();
try {
List<Integer> permissionMerchantIds = businessSceneAnalysisService.getMerchantIdPermission(req, false);
req.setMerchantIds(permissionMerchantIds);
log.info("查询他人关注列表:权限门店数={}, loginUserUuid={}",
permissionMerchantIds == null ? 0 : permissionMerchantIds.size(), req.getLoginUserUuid());
resList = followMapper.findFollowsBySceneReq(req, null, req.getLoginUserUuid(), 0);
if (CollectionUtils.isEmpty(resList)) {
log.info("查询他人关注列表:为空,loginUserUuid={}, 权限门店数={}",
req.getLoginUserUuid(), permissionMerchantIds == null ? 0 : permissionMerchantIds.size());
return Collections.emptyList();
}
} catch (Exception e) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, e.getMessage());
} finally {
req.setMerchantIds(originMerchantIds);
}
log.info("查询他人关注列表:开始填充扩展信息,loginUserUuid={}, 关注条数={}", req.getLoginUserUuid(), resList.size());
fillFollowDetails(resList, req);
if (CollectionUtils.isNotEmpty(resList)) {
List<Integer> storeIds = resList.stream().map(MyFollowResponse::getStoreId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
List<Integer> originMerchantIds2 = req.getMerchantIds();
try {
req.setMerchantIds(storeIds);
List<MyFollowResponse> myFollowed = followMapper.findFollowsBySceneReq(req, req.getLoginUserUuid(), null, 1);
Set<String> myFollowedKeys = CollectionUtils.isEmpty(myFollowed)
? Collections.emptySet()
: myFollowed.stream()
.filter(i -> i.getStoreId() != null && i.getBusinessType() != null)
.map(i -> i.getStoreId() + "_" + i.getBusinessType())
.collect(Collectors.toSet());
resList.forEach(item -> item.setIsFollow(myFollowedKeys.contains(item.getStoreId() + "_" + item.getBusinessType()) ? 1 : 0));
} finally {
req.setMerchantIds(originMerchantIds2);
}
}
log.info("查询他人关注列表完成:loginUserUuid={}, 条数={}, 耗时={}ms",
req.getLoginUserUuid(), resList.size(), System.currentTimeMillis() - startMs);
return resList;
}
/**
* 关注列表统一填充入口:
* 1)关注人信息、关注人总数、最近一条策略摘要(最近一个月内)
* 2)门店品牌、省市等基础信息(账户中心)
* 3)门店经营指标(一次请求拉取后索引命中)
* 4)按业务类型补齐运营人员/督导/招聘负责人,并计算达成率
*/
public void fillFollowDetails(List<MyFollowResponse> resList, SceneBaseReq req) {
if (CollectionUtils.isEmpty(resList)) {
return;
}
long startMs = System.currentTimeMillis();
// 0) 关注人信息 & 最近一条策略摘要(最近一个月内)
fillFollowerAndComment(resList);
// 1) 门店基础信息:主营品牌、省市等(来自账户中心)
fillMerchantInfo(resList);
List<Integer> allMerchantIds = resList.stream()
.map(MyFollowResponse::getStoreId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(allMerchantIds)) {
log.info("关注列表填充:门店ID为空,关注条数={}", resList.size());
return;
}
req.setMerchantIds(allMerchantIds);
log.info("关注列表填充开始:关注条数={}, 去重门店数={}", resList.size(), allMerchantIds.size());
// 2) 指标查询:一次请求拿回多门店、多指标(依赖 exts 返回维度字段)
List<String> itemCodes = Arrays.asList(
DataStatsConstants.ITEM_CODE_A036,
DataStatsConstants.ITEM_CODE_A085,
DataStatsConstants.ITEM_CODE_A077,
DataStatsConstants.ITEM_CODE_A064,
DataStatsConstants.ITEM_CODE_A076,
DataStatsConstants.ITEM_CODE_A095
);
Map<String, DataBusinessDTO> statsIndex = getFollowBIData(itemCodes, req);
// 3) 目标产值(仅月周期)
Map<Integer, BigDecimal> targetOutputMap = businessSceneAnalysisService.queryStoreTargetOutput(req);
// 4) 按业务类型分组:补齐运营/督导/招聘负责人,并填充指标与达成率
Map<Byte, List<MyFollowResponse>> groupByBiz = resList.stream().collect(Collectors.groupingBy(MyFollowResponse::getBusinessType));
groupByBiz.forEach((businessType, items) ->
fillFollowBizGroupDetails(businessType, items, req, itemCodes, statsIndex, targetOutputMap)
);
log.info("关注列表填充完成:关注条数={}, 耗时={}ms", resList.size(), System.currentTimeMillis() - startMs);
}
private void fillFollowerAndComment(List<MyFollowResponse> resList) {
if (CollectionUtils.isEmpty(resList)) {
return;
}
long startMs = System.currentTimeMillis();
// 1) 批量获取 followId(用于关注人统计)
List<Integer> merchantIds = resList.stream()
.map(MyFollowResponse::getStoreId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
List<MerchantBiFollow> follows = followMapper.findByMerchantIds(merchantIds);
if (CollectionUtils.isEmpty(follows)) {
resList.forEach(res -> {
res.setFollowerCount(0);
res.setFollowerNames("");
res.setLatestComment("");
res.setLatestStrategyId(null);
});
log.info("关注列表-关注人填充:无关注记录,门店数={}, 耗时={}ms", merchantIds.size(), System.currentTimeMillis() - startMs);
return;
}
Map<String, MerchantBiFollow> followMap = follows.stream()
.filter(f -> f.getMerchantId() != null && f.getBusinessType() != null)
.collect(Collectors.toMap(f -> f.getMerchantId() + "_" + f.getBusinessType(), f -> f, (f1, f2) -> f1));
List<Integer> followIds = follows.stream().map(MerchantBiFollow::getId).filter(Objects::nonNull).collect(Collectors.toList());
// 2) 批量查询关注人姓名(按 followId 聚合)
Map<Integer, List<String>> followerNamesMap = new HashMap<>();
if (CollectionUtils.isNotEmpty(followIds)) {
List<MerchantBiFollowDetail> allDetails = followDetailMapper.findFollowersByFollowIds(followIds);
if (CollectionUtils.isNotEmpty(allDetails)) {
followerNamesMap = allDetails.stream()
.collect(Collectors.groupingBy(
MerchantBiFollowDetail::getFollowId,
Collectors.mapping(MerchantBiFollowDetail::getStaffName, Collectors.toList())
));
}
}
// 3) 批量查询最近一个月内最新动态(仅取最新一条用于列表展示,返回策略ID供前端查详情)
Map<Byte, List<MyFollowResponse>> groupByBiz = resList.stream()
.filter(r -> r.getBusinessType() != null)
.collect(Collectors.groupingBy(MyFollowResponse::getBusinessType));
Map<String, String> latestCommentMap = new HashMap<>();
Map<String, Integer> latestStrategyIdMap = new HashMap<>();
Date endDate = DateUtils.now();
Date startDate = DateUtils.offsetMonth(endDate, -1);
groupByBiz.forEach((biz, items) -> {
List<Integer> bizMerchantIds = items.stream()
.map(MyFollowResponse::getStoreId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(bizMerchantIds)) {
return;
}
MerchantBiCommentReq commentReq = MerchantBiCommentReq.builder()
.merchantIds(bizMerchantIds)
.businessType(biz)
.build();
Map<Integer, StrategyInfo> latestStrategies = commentService.findLatestStrategiesByTime(commentReq, startDate, endDate);
if (latestStrategies != null) {
latestStrategies.forEach((mid, strategy) -> {
String timeAgo = DateUtils.formatTimeAgo(strategy.getCreatedDate());
latestCommentMap.put(mid + "_" + biz, String.format("「%s」,「%s」已添加跟进策略(留言)", timeAgo, strategy.getCreatedBy()));
latestStrategyIdMap.put(mid + "_" + biz, strategy.getId());
});
}
});
// 4) 回填
for (MyFollowResponse res : resList) {
String key = res.getStoreId() + "_" + res.getBusinessType();
MerchantBiFollow follow = followMap.get(key);
if (follow != null) {
List<String> names = followerNamesMap.get(follow.getId());
if (CollectionUtils.isNotEmpty(names)) {
LinkedHashSet<String> uniqueNames = names.stream()
.filter(StringUtils::isNotBlank)
.collect(Collectors.toCollection(LinkedHashSet::new));
res.setFollowerCount(uniqueNames.size());
res.setFollowerNames(String.join("/", uniqueNames));
} else {
res.setFollowerCount(0);
res.setFollowerNames("");
}
} else {
res.setFollowerCount(0);
res.setFollowerNames("");
}
res.setLatestComment(latestCommentMap.getOrDefault(key, ""));
res.setLatestStrategyId(latestStrategyIdMap.get(key));
}
log.info("关注列表-关注人&策略摘要填充完成:关注条数={}, 门店数={}, 耗时={}ms",
resList.size(), merchantIds.size(), System.currentTimeMillis() - startMs);
}
/**
* 门店列表(经营分析页)填充关注状态与留言信息:
* 1)关注数
* 2)当前登录人是否关注
* 3)留言条数与最新留言摘要
* <p>
* 说明:该逻辑原在 BusinessSceneAnalysisService 内,迁移到关注域统一维护,便于复用与收敛依赖。
*/
public void fillFollowAndComment(List<StoreListResponse> res, SceneBaseReq req) {
if (CollectionUtils.isEmpty(res)) {
return;
}
long startMs = System.currentTimeMillis();
List<Integer> merchantIds = res.stream()
.map(StoreListResponse::getStoreId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(merchantIds)) {
return;
}
if (req.getBizs() == null) {
log.info("门店列表填充关注信息:bizs为空,跳过填充,门店数={}", merchantIds.size());
return;
}
Byte businessType = req.getBizs().byteValue();
Pair<Map<Integer, Integer>, Map<Integer, Integer>> followMainData = queryFollowMainData(merchantIds, businessType);
Map<Integer, Integer> followCountMap = followMainData.getKey();
Map<Integer, Integer> followIdToMerchantIdMap = followMainData.getValue();
res.forEach(item -> item.setFollowCount(followCountMap.getOrDefault(item.getStoreId(), 0)));
if (StringUtils.isNotBlank(req.getLoginUserUuid()) && !followIdToMerchantIdMap.isEmpty()) {
List<MerchantBiFollowDetail> details = followDetailMapper.findByFollowIdsAndStaffUuids(
new ArrayList<>(followIdToMerchantIdMap.keySet()),
req.getLoginUserUuid()
);
Set<Integer> followedMerchantIds = new HashSet<>();
if (CollectionUtils.isNotEmpty(details)) {
details.forEach(detail -> {
Integer merchantId = followIdToMerchantIdMap.get(detail.getFollowId());
if (merchantId != null) {
followedMerchantIds.add(merchantId);
}
});
}
res.forEach(item -> item.setIsFollow(followedMerchantIds.contains(item.getStoreId()) ? 1 : 0));
} else {
res.forEach(item -> item.setIsFollow(0));
}
MerchantBiCommentReq commentReq = MerchantBiCommentReq.builder()
.merchantIds(merchantIds)
.businessType(businessType)
.build();
Map<Integer, StrategyInfo> commentSummaryMap = commentService.findCommentCountAndLatestSummary(commentReq);
res.forEach(item -> {
StrategyInfo summary = commentSummaryMap.get(item.getStoreId());
int count = summary == null || summary.getId() == null ? 0 : summary.getId();
item.setCommentCount(count);
if (count <= 0 || summary == null || summary.getCreatedDate() == null || StringUtils.isBlank(summary.getCreatedBy())) {
item.setLatestComment("");
return;
}
String timeAgo = DateUtils.formatTimeAgo(summary.getCreatedDate());
item.setLatestComment(String.format("「%s」,「%s」已添加跟进策略(留言)", timeAgo, summary.getCreatedBy()));
});
log.info("门店列表填充关注信息完成:biz={}, 门店数={}, costMs={}", businessType, merchantIds.size(), System.currentTimeMillis() - startMs);
}
private void fillMerchantInfo(List<MyFollowResponse> resList) {
try {
merchantBasicInfoService.fillFollowListMerchantInfo(resList);
} catch (Exception e) {
log.error("关注列表门店信息填充异常", e);
}
}
/**
* 指标查询:依赖指标系统返回 exts=merchantId,biz,itemCode 三维字段
* 返回索引 key = merchantId_biz_itemCode,便于后续 O(1) 命中取值
*/
private Map<String, DataBusinessDTO> getFollowBIData(List<String> itemCodes, SceneBaseReq req) {
long startMs = System.currentTimeMillis();
List<Integer> allMerchantIds = req.getMerchantIds();
if (CollectionUtils.isEmpty(allMerchantIds)) {
return new HashMap<>();
}
SceneBaseReq newReq = new SceneBaseReq();
BeanUtils.copyProperties(req, newReq);
newReq.setExts("merchantId,biz,itemCode");
DataBizQueryParamsDTO queryParams = newReq.convertQueryParam();
queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
queryParams.setItemCodes(String.join(",", itemCodes));
queryParams.setBizs(null);
String jsonBody = JSONUtil.toJsonStr(queryParams);
List<DataBusinessDTO> dataList = getDataStatsService.getListData(jsonBody);
if (CollectionUtils.isEmpty(dataList)) {
log.warn("关注列表指标查询为空:门店数={}, 指标数={}, 耗时={}ms", allMerchantIds.size(), itemCodes.size(), System.currentTimeMillis() - startMs);
return new HashMap<>();
}
Map<String, DataBusinessDTO> index = dataList.stream()
.filter(d -> d != null && d.getMerchantId() != null && StringUtils.isNotBlank(d.getBiz()) && StringUtils.isNotBlank(d.getItemCode()))
.collect(Collectors.toMap(
d -> d.getMerchantId() + "_" + d.getBiz() + "_" + d.getItemCode(),
d -> d,
(d1, d2) -> d1
));
log.info("关注列表指标查询完成:门店数={}, 返回行数={}, 索引条数={}, 耗时={}ms",
allMerchantIds.size(), dataList.size(), index.size(), System.currentTimeMillis() - startMs);
return index;
}
private void fillFollowBizGroupDetails(Byte businessType,
List<MyFollowResponse> items,
SceneBaseReq req,
List<String> itemCodes,
Map<String, DataBusinessDTO> statsIndex,
Map<Integer, BigDecimal> targetOutputMap) {
if (businessType == null || CollectionUtils.isEmpty(items)) {
return;
}
long startMs = System.currentTimeMillis();
List<Integer> merchantIds = items.stream()
.map(MyFollowResponse::getStoreId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(merchantIds)) {
return;
}
Integer sceneType = req.convertToSceneType(businessType.intValue());
List<StoreSettingDTO> settings = serviceMerchantMapper.findStoreSetting(merchantIds, sceneType);
Map<Integer, StoreSettingDTO> settingMap = CollectionUtils.isEmpty(settings)
? new HashMap<>()
: settings.stream().collect(Collectors.toMap(StoreSettingDTO::getMerchantId, s -> s, (s1, s2) -> s1));
Set<String> regionalOperationUuids = new LinkedHashSet<>();
if (CollectionUtils.isNotEmpty(settings)) {
settings.stream()
.map(StoreSettingDTO::getRegionalOperationId)
.filter(StringUtils::isNotBlank)
.forEach(ids -> Arrays.stream(ids.split(","))
.map(String::trim)
.filter(StringUtils::isNotBlank)
.forEach(regionalOperationUuids::add));
}
Map<String, Pair<String, String>> uuidToHrbpMap = merchantHrbpRelationService.buildRegionalOperationUuidToHrbpMap(regionalOperationUuids, businessType);
String bizKey = String.valueOf(businessType.intValue());
for (MyFollowResponse item : items) {
Integer storeId = item.getStoreId();
if (storeId == null) {
continue;
}
StoreSettingDTO setting = settingMap.get(storeId);
if (setting != null) {
item.setMerchantId(setting.getMerchantId());
item.setRegionalOperator(setting.getRegionalOperationName());
item.setRegionalOperatorId(setting.getRegionalOperationId());
item.setOnlineOperator(setting.getOnlineOperationName());
item.setOnlineOperatorId(setting.getOnlineOperationId());
item.setRegionalSupervisor(setting.getRegionalSupervisor());
item.setRegionalSupervisorId(setting.getRegionalSupervisorId());
}
if (setting != null && StringUtils.isNotBlank(setting.getRegionalOperationId()) && !uuidToHrbpMap.isEmpty()) {
LinkedHashSet<String> hrbpNames = new LinkedHashSet<>();
LinkedHashSet<String> hrbpPhones = new LinkedHashSet<>();
Arrays.stream(setting.getRegionalOperationId().split(","))
.map(String::trim)
.filter(StringUtils::isNotBlank)
.forEach(uuid -> {
Pair<String, String> hrbpInfo = uuidToHrbpMap.get(uuid);
if (hrbpInfo == null) {
return;
}
String hrbpName = hrbpInfo.getKey();
String hrbpPhone = hrbpInfo.getValue();
if (StringUtils.isNotBlank(hrbpName)) {
hrbpNames.add(hrbpName);
}
if (StringUtils.isNotBlank(hrbpPhone)) {
hrbpPhones.add(hrbpPhone);
}
});
if (!hrbpNames.isEmpty()) {
item.setRecruitmentManager(String.join("/", hrbpNames));
}
if (!hrbpPhones.isEmpty()) {
item.setRecruitmentManagerId(String.join("/", hrbpPhones));
}
}
for (String code : itemCodes) {
DataBusinessDTO data = statsIndex.get(storeId + "_" + bizKey + "_" + code);
if (data == null || data.getItemValue() == null) {
continue;
}
switch (code) {
case DataStatsConstants.ITEM_CODE_A036:
item.setOutputValue(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A085:
item.setConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A077:
item.setPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A064:
item.setCustomerContactRate(MetricsValueUtils.toPercentage(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A076:
item.setUpgradeCustomerPrice(MetricsValueUtils.scale2(data.getItemValue()));
break;
case DataStatsConstants.ITEM_CODE_A095:
item.setAvgCustomerPrice(MetricsValueUtils.scale2(data.getItemValue()));
break;
}
}
BigDecimal targetOutput = targetOutputMap.get(storeId);
item.setAchievementRate(MetricsValueUtils.computeOutputRatio(item.getOutputValue(), targetOutput));
}
log.info("关注列表填充-按业务处理完成:biz={}, 门店数={}, settings数={}, 耗时={}ms",
businessType, merchantIds.size(), settings == null ? 0 : settings.size(), System.currentTimeMillis() - startMs);
}
private void triggerFollowPush(MerchantBiFollowReq request) {
try {
// 获取门店负责人信息 (区域运营和线上运营)
List<StoreSettingDTO> settings = serviceMerchantMapper.findStoreSetting(Collections.singletonList(request.getMerchantId()), 1); // 场景暂取1
if (CollectionUtils.isNotEmpty(settings)) {
StoreSettingDTO setting = settings.get(0);
List<String> targetUuids = new ArrayList<>();
if (StringUtils.isNotBlank(setting.getRegionalOperationId()))
targetUuids.add(setting.getRegionalOperationId());
if (StringUtils.isNotBlank(setting.getOnlineOperationId()))
targetUuids.add(setting.getOnlineOperationId());
if (CollectionUtils.isNotEmpty(targetUuids)) {
log.info("触发关注推送:merchantId={}, biz={}, 触发人={}, 推送目标人数={}",
request.getMerchantId(), request.getBusinessType(), request.getStaffName(), targetUuids.size());
wechatPushService.pushFollowMsg(request.getStaffName(), request.getMerchantName(),
getBusinessTypeName(request.getBusinessType()), targetUuids);
} else {
log.info("触发关注推送:未找到推送目标,merchantId={}, biz={}", request.getMerchantId(), request.getBusinessType());
}
}
} catch (Exception e) {
log.error("触发关注推送异常", e);
}
}
private String getBusinessTypeName(Byte businessType) {
if (businessType == null) return "未知业务";
switch (businessType) {
case 1:
return "延保";
case 2:
return "轻改";
case 3:
return "权益";
default:
return "未知业务";
}
}
private MerchantBiFollow getOrCreateFollow(MerchantBiFollowReq request) {
MerchantBiFollow follow = followMapper.findFollowByMerchantAndBiz(request.getMerchantId(), request.getBusinessType());
if (follow == null) {
follow = MerchantBiFollow.builder()
.merchantId(request.getMerchantId())
.merchantName(request.getMerchantName())
.businessType(request.getBusinessType())
.followCount(0)
.createdBy(request.getStaffName())
.createdDate(new Date())
.updatedBy(request.getStaffName())
.updatedDate(new Date())
.deletedFlag("N")
.build();
followMapper.insertUseGeneratedKeys(follow);
// insertSelective 会回填 ID
}
return follow;
}
/**
* 查询关注主表数据:
* - key: followCountMap(merchantId -> followCount,无记录默认0)
* - value: followIdToMerchantIdMap(followId -> merchantId,用于反查“当前人是否关注”)
*/
private Pair<Map<Integer, Integer>, Map<Integer, Integer>> queryFollowMainData(List<Integer> merchantIds, Byte businessType) {
Map<Integer, Integer> followCountMap = new HashMap<>();
Map<Integer, Integer> followIdToMerchantIdMap = new HashMap<>();
if (CollectionUtils.isEmpty(merchantIds) || businessType == null) {
return Pair.of(followCountMap, followIdToMerchantIdMap);
}
merchantIds.forEach(id -> followCountMap.put(id, 0));
List<MerchantBiFollow> follows = followMapper.findByMerchantIdsAndBiz(merchantIds, businessType);
if (CollectionUtils.isNotEmpty(follows)) {
follows.forEach(follow -> {
if (follow.getMerchantId() != null) {
followCountMap.put(follow.getMerchantId(), follow.getFollowCount() == null ? 0 : follow.getFollowCount());
}
if (follow.getId() != null && follow.getMerchantId() != null) {
followIdToMerchantIdMap.put(follow.getId(), follow.getMerchantId());
}
});
}
return Pair.of(followCountMap, followIdToMerchantIdMap);
}
/**
* 批量查询关注状态
*/
public Map<Integer, Integer> findFollowStatus(MerchantBiFollowReq request) {
if (CollectionUtils.isEmpty(request.getMerchantIds()) || StringUtils.isBlank(request.getStaffUuid())) {
log.warn("批量查询关注状态:参数不完整,merchantIdsSize={}, staffUuid={}",
request.getMerchantIds() == null ? 0 : request.getMerchantIds().size(), request.getStaffUuid());
return Collections.emptyMap();
}
Pair<Map<Integer, Integer>, Map<Integer, Integer>> followMainData = queryFollowMainData(request.getMerchantIds(), request.getBusinessType());
Map<Integer, Integer> followIdToMerchantIdMap = followMainData.getValue();
if (followIdToMerchantIdMap.isEmpty()) {
log.info("批量查询关注状态:无关注主表记录,biz={}, 门店数={}", request.getBusinessType(), request.getMerchantIds().size());
return Collections.emptyMap();
}
// 再查出当前用户关注了哪些 followId (XML Mapper 优化)
List<MerchantBiFollowDetail> details = followDetailMapper.findByFollowIdsAndStaffUuids(
new ArrayList<>(followIdToMerchantIdMap.keySet()),
request.getStaffUuid()
);
Map<Integer, Integer> result = new HashMap<>();
// 默认全为 0
request.getMerchantIds().forEach(id -> result.put(id, 0));
// 关注了的设为 1
if (CollectionUtils.isNotEmpty(details)) {
details.forEach(detail -> {
Integer merchantId = followIdToMerchantIdMap.get(detail.getFollowId());
if (merchantId != null) {
result.put(merchantId, 1);
}
});
}
return result;
}
/**
* 批量查询关注数
*/
public Map<Integer, Integer> findFollowCounts(MerchantBiFollowReq request) {
if (CollectionUtils.isEmpty(request.getMerchantIds())) {
log.warn("批量查询关注数:门店ID为空");
return Collections.emptyMap();
}
Pair<Map<Integer, Integer>, Map<Integer, Integer>> followMainData = queryFollowMainData(request.getMerchantIds(), request.getBusinessType());
Map<Integer, Integer> followCountMap = followMainData.getKey();
log.info("批量查询关注数完成:biz={}, 门店数={}, 返回数={}",
request.getBusinessType(), request.getMerchantIds().size(), followCountMap.size());
return followCountMap;
}
}
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.mapper.ServiceMerchantMapper;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.hutool.core.lang.Pair;
import cn.com.glsx.merchants.model.request.MerchantStaffRequest;
import cn.com.glsx.merchants.model.response.MerchantStaffResponse;
import cn.com.glsx.merchants.remote.MerchantStaffRemote;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
public class MerchantHrbpRelationService {
@Autowired
private MerchantStaffRemote merchantStaffRemote;
@Autowired
private ServiceMerchantMapper serviceMerchantMapper;
/**
* 招聘负责人关联:
* 区域运营 uuid -> 区域运营手机号 -> 招聘负责人(HRBP)信息。
* <p>
* 说明:优先使用 ID/手机号做关联,避免姓名重名导致关联不准。
*
* @param regionalOperationUuids 区域运营 uuid 集合
* @param businessType 业务类型,仅用于日志定位
* @return uuid -> (hrbpName, hrbpPhone)
*/
public Map<String, Pair<String, String>> buildRegionalOperationUuidToHrbpMap(Set<String> regionalOperationUuids, Byte businessType) {
if (CollectionUtils.isEmpty(regionalOperationUuids)) {
return Collections.emptyMap();
}
long startMs = System.currentTimeMillis();
Map<String, String> uuidPhoneMap = new HashMap<>();
try {
MerchantStaffRequest staffRequest = new MerchantStaffRequest();
staffRequest.setStaffUuidList(new ArrayList<>(regionalOperationUuids));
staffRequest.setDelFlag((byte) 0);
RpcResponse<List<MerchantStaffResponse>> staffResp = merchantStaffRemote.findMerchantStaffListRemote(staffRequest);
if (staffResp != null && staffResp.isSuccess() && staffResp.hasResult()) {
staffResp.getResult().forEach(staff -> {
if (staff != null && StringUtils.isNotBlank(staff.getUuid()) && StringUtils.isNotBlank(staff.getStaffPhone())) {
uuidPhoneMap.put(staff.getUuid(), staff.getStaffPhone());
}
});
} else {
log.info("HRBP关联:查询区域运营手机号为空,biz={}, 区域运营数={}", businessType, regionalOperationUuids.size());
}
} catch (Exception e) {
log.warn("HRBP关联:查询区域运营手机号失败,biz={}, 区域运营数={}", businessType, regionalOperationUuids.size(), e);
}
if (uuidPhoneMap.isEmpty()) {
log.info("HRBP关联完成:biz={}, 区域运营数={}, 有手机号数=0, HRBP关系数=0, 耗时={}ms",
businessType, regionalOperationUuids.size(), System.currentTimeMillis() - startMs);
return Collections.emptyMap();
}
List<String> phones = uuidPhoneMap.values().stream()
.filter(StringUtils::isNotBlank)
.distinct()
.collect(Collectors.toList());
if (phones.isEmpty()) {
log.info("HRBP关联完成:biz={}, 区域运营数={}, 有手机号数=0, HRBP关系数=0, 耗时={}ms",
businessType, regionalOperationUuids.size(), System.currentTimeMillis() - startMs);
return Collections.emptyMap();
}
Map<String, Pair<String, String>> phoneToHrbpMap = new HashMap<>();
try {
List<Map<String, Object>> relations = serviceMerchantMapper.findRecruitmentHrbpByRegionOperationPhones(phones);
if (CollectionUtils.isNotEmpty(relations)) {
relations.forEach(row -> {
String regionOperationPhone = Objects.toString(row.get("regionOperationPhone"), "");
String hrbpName = Objects.toString(row.get("hrbpName"), "");
String hrbpPhone = Objects.toString(row.get("hrbpPhone"), "");
if (StringUtils.isNotBlank(regionOperationPhone) && StringUtils.isNotBlank(hrbpName)) {
phoneToHrbpMap.put(regionOperationPhone, Pair.of(hrbpName, hrbpPhone));
}
});
}
} catch (Exception e) {
log.warn("HRBP关联:查询HRBP关系失败,biz={}, 手机号数={}", businessType, phones.size(), e);
}
Map<String, Pair<String, String>> uuidToHrbpMap = new HashMap<>();
uuidPhoneMap.forEach((uuid, phone) -> {
Pair<String, String> hrbp = phoneToHrbpMap.get(phone);
if (hrbp != null && StringUtils.isNotBlank(hrbp.getKey())) {
uuidToHrbpMap.put(uuid, hrbp);
}
});
log.info("HRBP关联完成:biz={}, 区域运营数={}, 有手机号数={}, HRBP关系数={}, 映射数={}, 耗时={}ms",
businessType, regionalOperationUuids.size(), uuidPhoneMap.size(), phoneToHrbpMap.size(), uuidToHrbpMap.size(), System.currentTimeMillis() - startMs);
return uuidToHrbpMap;
}
/**
* 单门店招聘负责人查询(给门店详情等场景复用):
* 输入区域运营ID串(逗号分隔uuid),返回 HRBP 姓名与 HRBP 电话的展示串(/ 分隔)。
*/
public Pair<String, String> findRecruitmentManagerByRegionalOperationIds(String regionalOperationIdCsv, Byte businessType) {
if (StringUtils.isBlank(regionalOperationIdCsv)) {
return Pair.of(null, null);
}
Set<String> uuids = Arrays.stream(regionalOperationIdCsv.split(","))
.map(String::trim)
.filter(StringUtils::isNotBlank)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (uuids.isEmpty()) {
return Pair.of(null, null);
}
Map<String, Pair<String, String>> uuidToHrbpMap = buildRegionalOperationUuidToHrbpMap(uuids, businessType);
if (uuidToHrbpMap.isEmpty()) {
return Pair.of(null, null);
}
LinkedHashSet<String> hrbpNames = new LinkedHashSet<>();
LinkedHashSet<String> hrbpPhones = new LinkedHashSet<>();
uuids.forEach(uuid -> {
Pair<String, String> hrbpInfo = uuidToHrbpMap.get(uuid);
if (hrbpInfo == null) {
return;
}
String hrbpName = hrbpInfo.getKey();
String hrbpPhone = hrbpInfo.getValue();
if (StringUtils.isNotBlank(hrbpName)) {
hrbpNames.add(hrbpName);
}
if (StringUtils.isNotBlank(hrbpPhone)) {
hrbpPhones.add(hrbpPhone);
}
});
if (hrbpNames.isEmpty() && hrbpPhones.isEmpty()) {
return Pair.of(null, null);
}
return Pair.of(hrbpNames.isEmpty() ? null : String.join("/", hrbpNames), hrbpPhones.isEmpty() ? null : String.join("/", hrbpPhones));
}
}
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.mindworkplate.dto.bianalyse.MatterAddPushWeChatMsgDTO;
import cn.com.glsx.dj.mindworkplate.remote.BiAnalysisRemote;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
/**
* 企业微信推送服务
*
* @author lyj
*/
@Slf4j
@Service
public class WechatPushService {
@Autowired
private BiAnalysisRemote biAnalysisRemote;
private static final List<String> SPECIAL_FOLLOWERS = Arrays.asList("赵展", "普俊鹏", "高军", "王强");
/**
* 关注行为推送
*/
public void pushFollowMsg(String staffName, String merchantName, String businessType, List<String> targetUuids) {
if (!SPECIAL_FOLLOWERS.contains(staffName)) {
return;
}
String content = String.format("「%s」关注了你负责的「%s」门店:「%s」,请及时查看。", staffName, businessType, merchantName);
sendPush(content, targetUuids);
}
/**
* @ 提醒推送
*/
public void pushMentionMsg(String staffName, String merchantName, String businessType, List<String> targetUuids) {
String content = String.format("「%s」在「%s」门店:「%s」添加了留言并@你,请及时查看。", staffName, businessType, merchantName);
sendPush(content, targetUuids);
}
/**
* 每日动态汇总推送
*/
public void pushDailySummaryMsg(String merchantName, String businessType, int count, List<String> targetUuids, boolean isFollower) {
String prefix = isFollower ? "你关注的" : "你负责的";
String content = String.format("%s「%s」门店:「%s」昨日共有「%d」条动态,请及时查看。", prefix, businessType, merchantName, count);
sendPush(content, targetUuids);
}
private void sendPush(String content, List<String> uuids) {
log.info("发送企微推送: {}, 目标用户: {}", content, uuids);
try {
// 这里复用已有的 MatterAddPushWeChatMsgDTO,如果需要更灵活的文案,可能需要扩展该 DTO 或 Remote 接口
MatterAddPushWeChatMsgDTO msg = MatterAddPushWeChatMsgDTO.builder()
.pushUuids(uuids)
// .content(content) // 假设 DTO 支持 content 字段,如果不支持,则需要联系用户扩展
.build();
RpcResponse<Boolean> response = biAnalysisRemote.matterAddPushWeChatMsg(msg);
if (response == null || !response.isSuccess()) {
log.error("企微推送失败: {}", response != null ? response.getMessage() : "null");
}
} catch (Exception e) {
log.error("企微推送异常", e);
}
}
}
......@@ -25,21 +25,26 @@ public class SortUtils {
return;
}
String sortField = req.getOrderBy() != null ? req.getOrderBy() : null;
if (sortField == null || sortField.trim().isEmpty()) {
return; // 如果没有指定排序字段,则不排序
}
Integer orderType = req.getOrderType(); // 1.Desc降序,2.Asc升序
Comparator<T> comparator = getComparator((Class<T>) list.get(0).getClass(), req);
list.sort(comparator);
}
// 获取元素的Class类型
Class<?> clazz = list.get(0).getClass();
/**
* 获取比较器
* @param clazz 类型
* @param req 请求参数
* @param <T> 元素类型
* @return 比较器
*/
public static <T> Comparator<T> getComparator(Class<T> clazz, SceneBaseReq req) {
String sortField = req.getOrderBy() != null ? req.getOrderBy() : "outputValue";
Integer orderType = req.getOrderType(); // 1.Desc降序,2.Asc升序
Comparator<T> comparator = createComparator(clazz, sortField);
if (orderType == null || orderType == 1) { // 默认降序
list.sort(comparator.reversed());
return comparator.reversed();
} else { // 升序
list.sort(comparator);
return comparator;
}
}
......
......@@ -24,6 +24,56 @@ import java.util.List;
@Slf4j
public class DateUtils {
/**
* 格式化时间差 (xx分钟前/xx小时前/xx天前)
* @param date 目标时间
* @return 格式化字符串
*/
public static String formatTimeAgo(Date date) {
if (date == null) {
return "";
}
long now = System.currentTimeMillis();
long diff = now - date.getTime();
if (diff < 0) {
return "刚刚";
}
long minutes = diff / (1000 * 60);
if (minutes < 60) {
return (minutes <= 0 ? 1 : minutes) + "分钟前";
}
long hours = minutes / 60;
if (hours < 24) {
return hours + "小时前";
}
long days = hours / 24;
return days + "天前";
}
/**
* 获取当前时间
* @return 当前时间 Date
*/
public static Date now() {
return new Date();
}
/**
* 日期按月份偏移
* @param date 基准日期
* @param months 偏移月数(负数代表往前)
* @return 偏移后的日期
*/
public static Date offsetMonth(Date date, int months) {
if (date == null) {
return null;
}
return DateUtil.offset(date, DateField.MONTH, months);
}
/**
* 获取上一周期的时间范围(字符串格式)
*
* @param startTime 本期开始时间(字符串)
......
package cn.com.glsx.dj.peanalysis.utils;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 指标数值处理工具类
* <p>
* 用途:
* - 百分比换算(小数 -> 百分比,保留两位小数)
* - 金额/产值类指标保留两位小数
* - 达成率计算(产值/目标*100)
*/
public final class MetricsValueUtils {
private MetricsValueUtils() {
}
/**
* 达成率=(总产值/目标产值)*100,保留两位小数
*/
public static BigDecimal computeOutputRatio(BigDecimal outputValue, BigDecimal outputTargetValue) {
if (outputValue == null || outputTargetValue == null || outputTargetValue.compareTo(BigDecimal.ZERO) == 0) {
return null;
}
return outputValue
.multiply(BigDecimal.valueOf(100))
.divide(outputTargetValue, 2, RoundingMode.HALF_UP);
}
/**
* 数值保留两位小数(常用于产值/客单价等)
*/
public static BigDecimal scale2(BigDecimal val) {
if (val == null) {
return null;
}
return val.setScale(2, RoundingMode.HALF_UP);
}
/**
* 字符串数值保留两位小数
*/
public static String scale2(String val) {
if (StringUtils.isBlank(val)) {
return null;
}
return scale2(new BigDecimal(val)).toString();
}
/**
* 小数转百分比(*100),保留两位小数
*/
public static BigDecimal toPercentage(BigDecimal val) {
if (val == null) {
return null;
}
return val.multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
}
/**
* 字符串小数转百分比字符串(*100),保留两位小数
*/
public static String toPercentageString(String val) {
if (StringUtils.isBlank(val)) {
return null;
}
return toPercentage(new BigDecimal(val)).toString();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.dj.peanalysis.mapper.MerchantBiFollowDetailMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.peanalysis.model.MerchantBiFollowDetail">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="follow_id" jdbcType="INTEGER" property="followId" />
<result column="staff_uuid" jdbcType="VARCHAR" property="staffUuid" />
<result column="staff_phone" jdbcType="VARCHAR" property="staffPhone" />
<result column="staff_name" jdbcType="VARCHAR" property="staffName" />
<result column="created_by" jdbcType="VARCHAR" property="createdBy" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="updated_by" jdbcType="VARCHAR" property="updatedBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="deleted_flag" jdbcType="CHAR" property="deletedFlag" />
</resultMap>
<sql id="Base_Column_List">
id, follow_id, staff_uuid, staff_phone, staff_name, created_by, created_date, updated_by,
updated_date, deleted_flag
</sql>
<select id="findMyFollowDetails" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow_detail
WHERE staff_uuid = #{staffUuid}
AND deleted_flag = 'N'
ORDER BY created_date DESC
</select>
<select id="findOthersFollowDetails" resultMap="BaseResultMap">
SELECT
DISTINCT follow_id
FROM merchant_bi_follow_detail
WHERE staff_uuid != #{staffUuid}
AND deleted_flag = 'N'
ORDER BY created_date DESC
</select>
<select id="findFollowersByFollowIds" resultMap="BaseResultMap">
SELECT
follow_id, staff_name
FROM merchant_bi_follow_detail
WHERE follow_id IN
<foreach collection="followIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
AND deleted_flag = 'N'
</select>
<select id="findOneByFollowIdAndStaffUuid" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow_detail
WHERE follow_id = #{followId}
AND staff_uuid = #{staffUuid}
AND deleted_flag = 'N'
LIMIT 1
</select>
<select id="findByFollowIdsAndStaffUuids" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow_detail
WHERE follow_id IN
<foreach collection="followIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
AND staff_uuid = #{staffUuid}
AND deleted_flag = 'N'
</select>
<select id="findByFollowId" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow_detail
WHERE follow_id = #{followId}
AND deleted_flag = 'N'
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.dj.peanalysis.mapper.MerchantBiFollowMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.peanalysis.model.MerchantBiFollow">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="merchant_id" jdbcType="INTEGER" property="merchantId" />
<result column="merchant_name" jdbcType="VARCHAR" property="merchantName" />
<result column="business_type" jdbcType="TINYINT" property="businessType" />
<result column="follow_count" jdbcType="INTEGER" property="followCount" />
<result column="created_by" jdbcType="VARCHAR" property="createdBy" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="updated_by" jdbcType="VARCHAR" property="updatedBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="deleted_flag" jdbcType="CHAR" property="deletedFlag" />
</resultMap>
<sql id="Base_Column_List">
id, merchant_id, merchant_name, business_type, follow_count, created_by, created_date,
updated_by, updated_date, deleted_flag
</sql>
<select id="findFollowByMerchantAndBiz" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow
WHERE merchant_id = #{merchantId}
AND business_type = #{businessType}
AND deleted_flag = 'N'
LIMIT 1
</select>
<select id="findMyFollowsByStaffUuid" resultType="cn.com.glsx.dj.peanalysis.dto.res.output.MyFollowResponse">
SELECT DISTINCT
f.merchant_id AS storeId,
f.merchant_name AS storeName,
f.business_type AS businessType,
CASE f.business_type
WHEN 1 THEN '延保'
WHEN 2 THEN '轻改'
WHEN 3 THEN '权益'
ELSE '未知'
END AS businessTypeName,
1 AS isFollow
FROM merchant_bi_follow f
INNER JOIN merchant_bi_follow_detail d ON d.follow_id = f.id
WHERE d.staff_uuid = #{staffUuid}
AND f.deleted_flag = 'N'
AND d.deleted_flag = 'N'
ORDER BY d.created_date DESC
</select>
<select id="findFollowsBySceneReq" resultType="cn.com.glsx.dj.peanalysis.dto.res.output.MyFollowResponse">
SELECT
f.merchant_id AS storeId,
f.merchant_name AS storeName,
f.business_type AS businessType,
CASE f.business_type
WHEN 1 THEN '延保'
WHEN 2 THEN '轻改'
WHEN 3 THEN '权益'
ELSE '未知'
END AS businessTypeName,
#{defaultIsFollow,jdbcType=INTEGER} AS isFollow,
MAX(d.created_date) AS followDate
FROM merchant_bi_follow f
INNER JOIN merchant_bi_follow_detail d ON d.follow_id = f.id
WHERE f.deleted_flag = 'N'
AND d.deleted_flag = 'N'
<if test="staffUuid != null and staffUuid != ''">
AND d.staff_uuid = #{staffUuid}
</if>
<if test="excludeStaffUuid != null and excludeStaffUuid != ''">
AND d.staff_uuid != #{excludeStaffUuid}
</if>
<if test="req != null and req.merchantIds != null and req.merchantIds.size() &gt; 0">
AND f.merchant_id IN
<foreach collection="req.merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
GROUP BY f.merchant_id, f.merchant_name, f.business_type
ORDER BY followDate DESC
</select>
<select id="findByMerchantIds" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow
WHERE merchant_id IN
<foreach collection="merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
AND deleted_flag = 'N'
</select>
<select id="findByMerchantIdsAndBiz" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow
WHERE merchant_id IN
<foreach collection="merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
<if test="businessType != null">
AND business_type = #{businessType}
</if>
AND deleted_flag = 'N'
</select>
<select id="findFollowsByIds" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow
WHERE id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
AND deleted_flag = 'N'
</select>
<select id="findAllActiveFollows" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow
WHERE deleted_flag = 'N'
</select>
<select id="findByMinFollowCount" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM merchant_bi_follow
WHERE follow_count >= #{minCount}
AND deleted_flag = 'N'
</select>
</mapper>
......@@ -584,11 +584,23 @@
<select id="findStoreSetting" resultType="cn.com.glsx.dj.peanalysis.dto.StoreSettingDTO">
select
smdc.merchant_id as merchantId,
group_concat(distinct if(smdc.director_type = 7, smdc.director_user_id, null)) as onlineOperationId11,
group_concat(distinct if(smdc.director_type = 7, smdc.director_name, null) separator '/') as onlineOperationName11,
group_concat(distinct if(smdc.director_type = 9, smdc.director_user_id, null)) as regionalOperationId11,
group_concat(distinct if(smdc.director_type = 9, smdc.director_name, null) separator '/') as regionalOperationName11,
group_concat(distinct if(smdc.director_type = 3, smdc.director_user_id, null)) as sellerUserId11,
group_concat(distinct if(smdc.director_type = 3, smdc.director_name, null) separator '/') as sellerUserName11,
group_concat(distinct if(smdc.director_type = 5, smdc.director_user_id, null)) as onlineOperationId21,
group_concat(distinct if(smdc.director_type = 5, smdc.director_name, null) separator '/') as onlineOperationName21,
group_concat(distinct if(smdc.director_type = 8, smdc.director_user_id, null)) as regionalOperationId21,
group_concat(distinct if(smdc.director_type = 8, smdc.director_name, null) separator '/') as regionalOperationName21,
group_concat(distinct if(smdc.director_type = 1, smdc.director_user_id, null)) as sellerUserId21,
group_concat(distinct if(smdc.director_type = 1, smdc.director_name, null) separator '/') as sellerUserName21,
<choose>
<when test="scene == 0">
group_concat(distinct if(smdc.director_type = 7, smdc.director_user_id, null)) as onlineOperationId,
group_concat(distinct if(smdc.director_type = 7, smdc.director_name, null) separator '/') as onlineOperationName,
group_concat(distinct if(smdc.director_type = 9, smdc.director_user_id, null)) as onlineOperationId,
group_concat(distinct if(smdc.director_type = 9, smdc.director_user_id, null)) as regionalOperationId,
group_concat(distinct if(smdc.director_type = 9, smdc.director_name, null) separator '/') as regionalOperationName,
group_concat(distinct if(smdc.director_type = 3, smdc.director_user_id, null)) as sellerUserId,
group_concat(distinct if(smdc.director_type = 3, smdc.director_name, null) separator '/') as sellerUserName,
......@@ -596,20 +608,32 @@
<when test="scene == 1">
group_concat(distinct if(smdc.director_type = 5, smdc.director_user_id, null)) as onlineOperationId,
group_concat(distinct if(smdc.director_type = 5, smdc.director_name, null) separator '/') as onlineOperationName,
group_concat(distinct if(smdc.director_type = 8, smdc.director_user_id, null)) as onlineOperationId,
group_concat(distinct if(smdc.director_type = 8, smdc.director_user_id, null)) as regionalOperationId,
group_concat(distinct if(smdc.director_type = 8, smdc.director_name, null) separator '/') as regionalOperationName,
group_concat(distinct if(smdc.director_type = 1, smdc.director_user_id, null)) as sellerUserId,
group_concat(distinct if(smdc.director_type = 1, smdc.director_name, null) separator '/') as sellerUserName,
</when>
<otherwise>
group_concat(distinct if(smdc.director_type in (5,7), smdc.director_user_id, null)) as onlineOperationId,
group_concat(distinct if(smdc.director_type in (5,7), smdc.director_name, null) separator '/') as onlineOperationName,
group_concat(distinct if(smdc.director_type in (8,9), smdc.director_user_id, null)) as regionalOperationId,
group_concat(distinct if(smdc.director_type in (8,9), smdc.director_name, null) separator '/') as regionalOperationName,
group_concat(distinct if(smdc.director_type in (1,3), smdc.director_user_id, null)) as sellerUserId,
group_concat(distinct if(smdc.director_type in (1,3), smdc.director_name, null) separator '/') as sellerUserName,
</otherwise>
</choose>
group_concat(distinct if(smdc.director_type = 6, smdc.director_user_id, null)) as regionalSupervisorId,
group_concat(distinct if(smdc.director_type = 6, smdc.director_name, null) separator '/') as regionalSupervisor,
group_concat(distinct yqmc.partner_merchant_id) as shopMerchantId,
group_concat(distinct yqmc.partner_merchant_name separator '/') as shopMerchantName
from dj_smartcarlife.dj_car_life_shop_merchant_director_config smdc
left join dj_car_life_scene_merchant_ref a on smdc.merchant_id = a.main_merchant_id and a.deleted_flag = 'N' and a.main_merchant_type = 2 and a.sub_merchant_type in (6,8)
<if test="scene != null">
and a.scene = #{scene}
</if>
left join dj_smartcarlife.dj_car_life_yqmerchant_config yqmc on yqmc.merchant_id = a.sub_merchant_id and yqmc.deleted_flag = 'N'
<where>
smdc.deleted_flag = 'N'
and a.scene = #{scene}
<if test="merchantIds != null and merchantIds.size() > 0">
and smdc.merchant_id in
<foreach item="item" index="index" collection="merchantIds" open="(" separator="," close=")">
......@@ -619,6 +643,36 @@
</where>
group by smdc.merchant_id
</select>
<select id="findRecruitmentHrbpByRegionOperationPhones" resultType="java.util.HashMap">
select
region_operation_phone as regionOperationPhone,
hrbp_name as hrbpName,
hrbp_phone as hrbpPhone
from dj_smartcarlife.dj_car_life_recruitment_region_operation_hrbp_relation
where deleted_flag = 'N'
<if test="phones != null and phones.size() > 0">
and region_operation_phone in
<foreach collection="phones" item="p" open="(" separator="," close=")">
#{p}
</foreach>
</if>
</select>
<select id="findRecruitmentTechnicalSupervisorByProvinces" resultType="java.util.HashMap">
select
province as province,
supervisor_name as supervisorName,
supervisor_phone as supervisorPhone
from dj_smartcarlife.dj_car_life_recruitment_technical_supervisor_mapping
where deleted_flag = 'N'
<if test="provinces != null and provinces.size() > 0">
and province in
<foreach collection="provinces" item="p" open="(" separator="," close=")">
#{p}
</foreach>
</if>
</select>
<select id="findYydList"
resultType="cn.com.glsx.dj.peanalysis.service.model.StoreInfo">
select distinct main_merchant_id as storeId, sub_merchant_id as yydStoreId,
......@@ -633,4 +687,4 @@
and sub_merchant_type in (6, 8);
</select>
</mapper>
\ No newline at end of file
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.dj.peanalysis.mapper.StrategyInfoMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.peanalysis.model.StrategyInfo">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="strategy_type" jdbcType="INTEGER" property="strategyType" />
<result column="title" jdbcType="VARCHAR" property="title" />
<result column="sub_title" jdbcType="VARCHAR" property="subTitle" />
<result column="start_date" jdbcType="TIMESTAMP" property="startDate" />
<result column="end_date" jdbcType="TIMESTAMP" property="endDate" />
<result column="description" jdbcType="VARCHAR" property="description" />
<result column="content" jdbcType="LONGVARCHAR" property="content" />
<result column="handler_type" jdbcType="VARCHAR" property="handlerType" />
<result column="push_type" jdbcType="INTEGER" property="pushType" />
<result column="created_by" jdbcType="VARCHAR" property="createdBy" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="updated_by" jdbcType="VARCHAR" property="updatedBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="deleted_flag" jdbcType="CHAR" property="deletedFlag" />
<result column="merchant_id" jdbcType="INTEGER" property="merchantId" />
<result column="merchant_name" jdbcType="VARCHAR" property="merchantName" />
<result column="biz" jdbcType="INTEGER" property="biz" />
<result column="push_flag" jdbcType="INTEGER" property="pushFlag" />
<result column="created_uuid" jdbcType="VARCHAR" property="createdUuid" />
</resultMap>
<sql id="Base_Column_List">
id, strategy_type, title, sub_title, start_date, end_date, description, content,
handler_type, push_type, created_by, created_date, updated_by, updated_date,
deleted_flag, merchant_id, merchant_name, biz, push_flag, created_uuid
</sql>
<select id="findStrategyRecords" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM dj_smartcarlife.dj_car_life_strategy_info
WHERE merchant_id = #{merchantId}
<if test="biz != null">
AND biz = #{biz}
</if>
AND deleted_flag = 'N'
ORDER BY created_date DESC
</select>
<select id="findLatestStrategyRecords" resultMap="BaseResultMap">
SELECT t1.* FROM dj_smartcarlife.dj_car_life_strategy_info t1
INNER JOIN (
SELECT merchant_id, MAX(created_date) as max_date
FROM dj_smartcarlife.dj_car_life_strategy_info
WHERE merchant_id IN
<foreach collection="merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
<if test="biz != null">
AND biz = #{biz}
</if>
AND deleted_flag = 'N'
GROUP BY merchant_id
) t2 ON t1.merchant_id = t2.merchant_id AND t1.created_date = t2.max_date
WHERE t1.deleted_flag = 'N'
</select>
<select id="findLatestStrategyRecordsByTime" resultMap="BaseResultMap">
SELECT t1.* FROM dj_smartcarlife.dj_car_life_strategy_info t1
INNER JOIN (
SELECT merchant_id, MAX(created_date) as max_date
FROM dj_smartcarlife.dj_car_life_strategy_info
WHERE merchant_id IN
<foreach collection="merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
<if test="biz != null">
AND biz = #{biz}
</if>
AND deleted_flag = 'N'
AND created_date BETWEEN #{startDate} AND #{endDate}
GROUP BY merchant_id
) t2 ON t1.merchant_id = t2.merchant_id AND t1.created_date = t2.max_date
WHERE t1.deleted_flag = 'N'
<if test="biz != null">
AND t1.biz = #{biz}
</if>
AND t1.created_date BETWEEN #{startDate} AND #{endDate}
</select>
<select id="findStrategyCounts" resultMap="BaseResultMap">
SELECT merchant_id, COUNT(*) as id
FROM dj_smartcarlife.dj_car_life_strategy_info
WHERE merchant_id IN
<foreach collection="merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
<if test="biz != null">
AND biz = #{biz}
</if>
AND deleted_flag = 'N'
GROUP BY merchant_id
</select>
<select id="findStrategyCountAndLatestSummary" resultMap="BaseResultMap">
SELECT
merchant_id,
COUNT(*) AS id,
SUBSTRING_INDEX(GROUP_CONCAT(created_by ORDER BY created_date DESC, id DESC), ',', 1) AS created_by,
MAX(created_date) AS created_date
FROM dj_smartcarlife.dj_car_life_strategy_info
WHERE merchant_id IN
<foreach collection="merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
<if test="biz != null">
AND biz = #{biz}
</if>
AND deleted_flag = 'N'
GROUP BY merchant_id
</select>
<select id="countStrategyByTime" resultType="java.lang.Integer">
SELECT COUNT(*)
FROM dj_smartcarlife.dj_car_life_strategy_info
WHERE merchant_id IN
<foreach collection="merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
<if test="biz != null">
AND biz = #{biz}
</if>
AND deleted_flag = 'N'
AND created_date BETWEEN #{startDate} AND #{endDate}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.dj.peanalysis.mapper.StrategyStaffRelMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.peanalysis.model.StrategyStaffRel">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="strategy_id" jdbcType="INTEGER" property="strategyId" />
<result column="user_uuid" jdbcType="VARCHAR" property="userUuid" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="user_phone" jdbcType="VARCHAR" property="userPhone" />
<result column="created_by" jdbcType="VARCHAR" property="createdBy" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="updated_by" jdbcType="VARCHAR" property="updatedBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="deleted_flag" jdbcType="CHAR" property="deletedFlag" />
<result column="user_position" jdbcType="INTEGER" property="userPosition" />
<result column="beisen_userid" jdbcType="INTEGER" property="beisenUserId" />
</resultMap>
<sql id="Base_Column_List">
id, strategy_id, user_uuid, user_name, user_phone, created_by, created_date,
updated_by, updated_date, deleted_flag, user_position, beisen_userid
</sql>
<select id="findByStrategyId" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM dj_smartcarlife.dj_car_life_strategy_staff_rel
WHERE strategy_id = #{strategyId}
AND deleted_flag = 'N'
</select>
<select id="findByStrategyIds" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM dj_smartcarlife.dj_car_life_strategy_staff_rel
WHERE strategy_id IN
<foreach collection="strategyIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
AND deleted_flag = 'N'
</select>
</mapper>
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.dj.peanalysis.dto.analysis.StrategyRecordDTO;
import cn.com.glsx.dj.peanalysis.dto.analysis.StrategyRecordQryDTO;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Collections;
import java.util.Map;
public class MerchantBiCommentServiceTest extends BaseServiceTest {
@Autowired
private MerchantBiCommentService commentService;
@Test
public void testComment() {
MerchantBiCommentReq req = MerchantBiCommentReq.builder()
.merchantId(123)
.merchantName("测试门店")
.businessType((byte) 1)
.staffUuid("test-uuid")
.staffName("测试员工")
.content("这是一条测试留言")
.handlerStaffUuid("handler-uuid")
.handlerStaffName("处理人")
.build();
// 新增
Boolean result = commentService.addComment(req);
Assert.assertTrue(result);
// 查询条数
req.setMerchantIds(Collections.singletonList(123));
Map<Integer, Integer> counts = commentService.findCommentCounts(req);
Assert.assertTrue(counts.get(123) > 0);
// 合并记录查询
RpcPagination<StrategyRecordQryDTO> paginationReq = new RpcPagination<>();
paginationReq.setPageNum(1);
paginationReq.setPageSize(10);
StrategyRecordQryDTO qry = new StrategyRecordQryDTO();
qry.setMerchantId(123);
qry.setBusinessType((byte) 1);
paginationReq.setCondition(qry);
RpcPagination<StrategyRecordDTO> combinedRecords = commentService.findCombinedRecords(paginationReq, "test-uuid");
Assert.assertNotNull(combinedRecords.getList());
Assert.assertTrue(combinedRecords.getList().size() > 0);
Integer strategyId = combinedRecords.getList().get(0).getId();
// 详情
StrategyRecordDTO detail = commentService.getStrategyDetail(strategyId, 7);
Assert.assertNotNull(detail);
Assert.assertEquals("这是一条测试留言", detail.getContent());
// 撤回
commentService.withdrawComment(strategyId, "test-uuid");
combinedRecords = commentService.findCombinedRecords(paginationReq, "test-uuid");
Assert.assertTrue(combinedRecords.getList().stream().noneMatch(c -> c.getId().equals(strategyId)));
}
}
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiFollowReq;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Collections;
import java.util.Map;
public class MerchantBiFollowServiceTest extends BaseServiceTest {
@Autowired
private MerchantBiFollowService followService;
@Test
public void testFollowMerchant() {
MerchantBiFollowReq req = MerchantBiFollowReq.builder()
.merchantId(123)
.merchantName("测试门店")
.businessType((byte) 1)
.staffUuid("test-uuid")
.staffName("测试员工")
.operateType(1)
.build();
Boolean result = followService.followMerchant(req);
Assert.assertTrue(result);
// 查询关注状态
req.setMerchantIds(Collections.singletonList(123));
Map<Integer, Integer> status = followService.findFollowStatus(req);
Assert.assertEquals(Integer.valueOf(1), status.get(123));
// 取消关注
req.setOperateType(0);
followService.followMerchant(req);
status = followService.findFollowStatus(req);
Assert.assertEquals(Integer.valueOf(0), status.get(123));
}
}
  • @wangxw1
    commented
    Master

    你好,我是负责本次代码审查的软件开发工程师。你提交的代码涵盖了 RPC 接口定义、DTO 设计、MyBatis 数据层实现以及核心业务逻辑的调整,整体结构清晰,提交信息规范。

    但在审查过程中,我发现存在严重的越权风险(IDOR)以及潜在的性能与稳定性隐患。以下是 Top 3 关键问题与优化建议。

    一、关键问题与优化建议(Top 3)

    1. 安全性严重漏洞:存在任意用户冒充风险(IDOR)

    • 问题描述:在 MerchantBiCommentReq 和 MerchantBiFollowReq 请求对象中,直接定义了 staffUuid、staffName 等字段,并在 Service 层(如 MerchantBiCommentService.addComment)直接使用请求体中的 staffUuid 作为数据的创建人/操作人。
    • 影响分析:这是极高风险的安全漏洞。恶意用户可以通过抓包修改请求体中的 staffUuid,冒充任意员工(如高管、管理员)发布留言或关注门店,导致数据篡改和审计失效。
    • 优化建议:

      • 严禁信任前端传递的用户身份信息。
      • 应从网关透传的 Header、Session 或 RPC 上下文(如 RpcContext / UserContext)中获取当前登录人的 staffUuid。
      • 代码示例:

        // MerchantBiCommentRemoteImpl.java
        @Override
        public RpcResponse<Boolean> addComment(@RequestBody MerchantBiCommentReq request) {
        // 1. 从安全上下文获取当前登录用户
        String currentStaffUuid = UserContext.getCurrentUser().getUuid(); 
        String currentStaffName = UserContext.getCurrentUser().getName();
        
        // 2. 覆盖请求参数,确保操作人是本人
        request.setStaffUuid(currentStaffUuid);
        request.setStaffName(currentStaffName);
        
        return RpcResponse.success(commentService.addComment(request));
        }
        

    2. 稳定性隐患:RPC 调用未做分批处理,存在 OOM 和超时风险

    • 问题描述:在 MerchantBasicInfoService.queryMerchantBasicInfoMap 方法中,直接设置 merchantRequest.setPageSize(Integer.MAX_VALUE),并将去重后的所有 merchantIds 一次性传入调用远程接口。
    • 影响分析:当 merchantIds 数量较大(如导出或全量列表场景,可能达到数千个)时:
      • 下游服务可能因查询数据量过大导致数据库慢查询或内存溢出(OOM)。
      • Dubbo 响应包体过大,极易导致网络传输超时或反序列化失败,引发服务雪崩。
    • 优化建议:使用 Guava 的 Lists.partition 或类似工具进行分批查询。

      // MerchantBasicInfoService.java
      public Map<Integer, MerchantBasicInfoListResponse> queryMerchantBasicInfoMap(List<Integer> merchantIds) {
          // ... 前置校验 ...
          Map<Integer, MerchantBasicInfoListResponse> resultMap = new HashMap<>();
          // 建议每批次查询 50-100 条
          List<List<Integer>> partitions = Lists.partition(distinctMerchantIds, 100);
      
          for (List<Integer> batchIds : partitions) {
              MerchantBasicInfoRequest req = new MerchantBasicInfoRequest();
              req.setMerchantIdList(batchIds);
              // ... 调用 RPC 并聚合结果 ...
          }
          return resultMap;
      }
      

    3. 性能问题:循环数据库操作(Loop Insert)

    • 问题描述:在 MerchantBiCommentService.addComment 方法中,处理 @提醒人 逻辑时,在 for 循环内部构建 StrategyStaffRel 对象。虽然代码片段截断了,但通常此处紧跟着单条 insert 语句。
    • 影响分析:如果处理人有 10 个,就会产生 10 次额外的数据库交互(I/O)。在高并发场景下,频繁的数据库连接获取与释放会严重拖累系统吞吐量,增加事务锁持有时间。
    • 优化建议:使用 MyBatis 的批量插入功能。 java // 收集所有关联对象 List<StrategyStaffRel> relList = new ArrayList<>(); for (int i = 0; i < uuids.length; i++) { StrategyStaffRel rel = StrategyStaffRel.builder()...build(); relList.add(rel); } // 批量插入 if (CollectionUtils.isNotEmpty(relList)) { strategyStaffRelMapper.insertList(relList); }

    二、评分明细

    评分维度 得分 理由
    功能实现的正确性与健壮性 30/40 业务逻辑基本闭环,BusinessSceneAnalysisService 中的趋势计算使用了内存预聚合,思路不错。但 Integer.MAX_VALUE 的使用严重影响健壮性。
    安全性与潜在风险 10/30 存在严重的越权(IDOR)风险,完全信任前端传递的用户 ID,这是安全红线问题。
    最佳实践与可维护性 15/20 代码结构清晰,DTO 命名规范。StoreSettingDTO 中使用了魔术数字 0 (scene == 0),建议改为枚举或常量定义以提高可读性。
    性能与资源利用 3/5 存在循环插入数据库的隐患;全量 RPC 查询未做分批处理。
    提交信息质量 5/5 Commit Message 非常规范,使用了 feat(scope): 格式,且详细列出了修改点,值得表扬。

    总分:63分

Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!