Commit 4f9c938e by 林永健

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

- 新增MerchantBiFollowDetailMapper,支持查询关注明细相关操作
- 新增MerchantBiFollowMapper,支持门店关注记录查询及多场景过滤
- 新增StrategyInfoMapper,实现策略记录的分页查询与统计
- 新增StrategyStaffRelMapper,支持按策略ID查询关联员工信息
- 新增MerchantBiCommentRemoteImpl,实现门店留言相关远程接口逻辑
- 新增MerchantBiFollowRemoteImpl,实现门店关注相关远程接口逻辑
- ServiceMerchantMapper新增招聘负责人和技师督导关联查询方法
- BusinessSceneAnalysisService重构并增强产值权限查询、趋势计算和指标转换逻辑
- 优化产值趋势的周期数据聚合和时间匹配算法
- 增加门店列表关注状态及留言数填充,支持预警门店优先排序
- 门店详情增加招聘负责人和技师督导信息填充逻辑
- 统一指标数据百分比和数值缩放使用MetricsValueUtils工具方法
1 parent e701ed78
Showing 25 changed files with 1511 additions and 20 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());
}
}
}
......@@ -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.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!