Commit 6ddca1da by 林冲

Merge branch 'v5.7.0' into 'master'

上线合并

See merge request !6
2 parents 4b29ff7a 7c270c05
Showing 46 changed files with 4183 additions and 223 deletions
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
......@@ -7,7 +7,7 @@
</parent>
<groupId>cn.com.glsx.dj.peanalysis</groupId>
<artifactId>rpc-dj-pe-analysis-api</artifactId>
<version>5.6.4-SNAPSHOT</version>
<version>5.7.0-SNAPSHOT</version>
<name>rpc-dj-pe-analysis-api</name>
<properties>
<deploy.scanPackage>cn.com.glsx.dj.peanalysis.remote</deploy.scanPackage>
......@@ -28,7 +28,7 @@
<dependency>
<groupId>cn.com.glsx.dj.peanalysis</groupId>
<artifactId>rpc-dj-pe-analysis-api</artifactId>
<version>5.6.4-SNAPSHOT</version>
<version>${project.version}</version>
</dependency>
</dependencies>
</plugin>
......
......@@ -10,6 +10,7 @@ import java.io.Serializable;
public class StoreSettingDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("商户号")
private Integer merchantId;
@ApiModelProperty("所属服务商")
......@@ -36,5 +37,106 @@ public class StoreSettingDTO implements Serializable {
@ApiModelProperty("线上运营ID")
private String onlineOperationId;
@ApiModelProperty("1.1场景-销售")
private String sellerUserName11;
@ApiModelProperty("1.1场景-销售ID")
private String sellerUserId11;
@ApiModelProperty("1.1场景-区域运营")
private String regionalOperationName11;
@ApiModelProperty("1.1场景-区域运营ID")
private String regionalOperationId11;
@ApiModelProperty("1.1场景-线上运营")
private String onlineOperationName11;
@ApiModelProperty("1.1场景-线上运营ID")
private String onlineOperationId11;
@ApiModelProperty("2.1场景-销售")
private String sellerUserName21;
@ApiModelProperty("2.1场景-销售ID")
private String sellerUserId21;
@ApiModelProperty("2.1场景-区域运营")
private String regionalOperationName21;
@ApiModelProperty("2.1场景-区域运营ID")
private String regionalOperationId21;
@ApiModelProperty("2.1场景-线上运营")
private String onlineOperationName21;
@ApiModelProperty("2.1场景-线上运营ID")
private String onlineOperationId21;
@ApiModelProperty("区域督导")
private String regionalSupervisor;
@ApiModelProperty("区域督导ID")
private String regionalSupervisorId;
@ApiModelProperty("招聘负责人")
private String recruitmentManager;
@ApiModelProperty("技师督导")
private String technicianSupervisor;
private String merchantNo;
@ApiModelProperty("主营品牌")
private String brandName;
@ApiModelProperty("省份名称")
private String provinceName;
@ApiModelProperty("城市名称")
private String cityName;
public String getSellerUserName(Integer scene) {
if (scene == null) {
return sellerUserName;
}
return scene == 0 ? sellerUserName11 : sellerUserName21;
}
public String getSellerUserId(Integer scene) {
if (scene == null) {
return sellerUserId;
}
return scene == 0 ? sellerUserId11 : sellerUserId21;
}
public String getRegionalOperationName(Integer scene) {
if (scene == null) {
return regionalOperationName;
}
return scene == 0 ? regionalOperationName11 : regionalOperationName21;
}
public String getRegionalOperationId(Integer scene) {
if (scene == null) {
return regionalOperationId;
}
return scene == 0 ? regionalOperationId11 : regionalOperationId21;
}
public String getOnlineOperationName(Integer scene) {
if (scene == null) {
return onlineOperationName;
}
return scene == 0 ? onlineOperationName11 : onlineOperationName21;
}
public String getOnlineOperationId(Integer scene) {
if (scene == null) {
return onlineOperationId;
}
return scene == 0 ? onlineOperationId11 : onlineOperationId21;
}
}
package cn.com.glsx.dj.peanalysis.dto.analysis;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 处理人员工信息
*
* @author lyj
* @version 1.0
* @since 2026/03/18
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class HandlerStaffInfo implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 员工编号
*/
private String staffUuid;
/**
* 员工姓名
*/
private String staffName;
/**
* 员工手机号
*/
private String staffPhone;
}
package cn.com.glsx.dj.peanalysis.dto.analysis;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* BI-门店留言请求对象
*
* @author lyj
* @version 1.0
* @since 2026/03/12
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MerchantBiCommentReq implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id (修改/删除时使用)
*/
private Integer id;
/**
* 门店号
*/
@NotNull(message = "门店号不能为空")
private Integer merchantId;
/**
* 门店名称
*/
private String merchantName;
/**
* 业务场景 (1:延保; 2:轻改; 3:权益; 4:二手车)
*/
@NotNull(message = "业务类型不能为空")
private Byte businessType;
/**
* 留言内容
*/
private String content;
/**
* 员工编号 (留言人)
*/
private String staffUuid;
/**
* 员工姓名 (留言人)
*/
private String staffName;
/**
* 员工手机号 (留言人)
*/
private String staffPhone;
/**
* 处理人列表
*/
private List<HandlerStaffInfo> handlerStaffList;
/**
* 批量查询时的门店列表
*/
private List<Integer> merchantIds;
/**
* 页码
*/
private Integer pageNum;
/**
* 每页条数
*/
private Integer pageSize;
private Date startDate;
private Date endDate;
}
package cn.com.glsx.dj.peanalysis.dto.analysis;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
/**
* BI-门店关注数据对象
*
* @author lyj
* @version 1.0
* @since 2026/03/12
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MerchantBiFollowDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
private Integer id;
/**
* 门店号
*/
private Integer merchantId;
/**
* 门店名称
*/
private String merchantName;
/**
* 业务场景
*/
private Byte businessType;
/**
* 关注数
*/
private Integer followCount;
/**
* 是否关注 (1:是; 0:否)
*/
private Integer isFollow;
/**
* 创建人
*/
private String createdBy;
/**
* 创建时间
*/
private Date createdDate;
/**
* 修改人
*/
private String updatedBy;
/**
* 修改时间
*/
private Date updatedDate;
}
package cn.com.glsx.dj.peanalysis.dto.analysis;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
/**
* BI-门店关注请求对象
*
* @author lyj
* @version 1.0
* @since 2026/03/12
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MerchantBiFollowReq implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 门店号
*/
@NotNull(message = "门店号不能为空")
private Integer merchantId;
/**
* 门店名称
*/
private String merchantName;
/**
* 业务场景 (1:延保; 2:轻改; 3:权益; 4:二手车)
*/
@NotNull(message = "业务类型不能为空")
private Byte businessType;
/**
* 员工编号 (关注人)
*/
private String staffUuid;
/**
* 员工手机号 (关注人)
*/
private String staffPhone;
/**
* 员工姓名 (关注人)
*/
private String staffName;
/**
* 批量查询时的门店列表
*/
private List<Integer> merchantIds;
/**
* 操作类型 (1:关注; 0:取消关注)
*/
private Integer operateType;
}
......@@ -73,6 +73,9 @@ public class SceneBaseReq implements Serializable {
@ApiModelProperty(notes = "模糊搜索")
private String search;
@ApiModelProperty(notes = "门店名称 (模糊搜索)")
private String merchantName;
@ApiModelProperty(notes = "指标查询参数")
private DataBizQueryParamsDTO queryParams;
......@@ -99,6 +102,24 @@ public class SceneBaseReq implements Serializable {
private String staffId;
@ApiModelProperty(notes = "驻店员工手机号")
private String staffPhone;
@ApiModelProperty(notes = "当前登录用户UUID")
private String loginUserUuid;
@ApiModelProperty(notes = "当前登录用户姓名")
private String loginUserName;
@ApiModelProperty(notes = "当前登录用户手机号")
private String loginUserPhone;
@ApiModelProperty(notes = "数据类型 1.1 2.1")
private String dataType;
/**
* 员工手机号列表
*/
@ApiModelProperty(notes = "驻店员工手机号列表")
private List<String> staffPhones;
/**
* 权限角色
*/
......@@ -135,6 +156,9 @@ public class SceneBaseReq implements Serializable {
if (!CollectionUtils.isEmpty(staffUuids)) {
res.setStaffIds(staffUuids.stream().map(String::valueOf).filter(StringUtils::hasLength).sorted().collect(Collectors.joining(",")));
}
if (!CollectionUtils.isEmpty(staffPhones)) {
res.setStaffPhones(staffPhones.stream().map(String::valueOf).filter(StringUtils::hasLength).sorted().collect(Collectors.joining(",")));
}
return res;
}
......
package cn.com.glsx.dj.peanalysis.dto.res.output;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.io.Serializable;
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@ApiModel(description = "我的关注/他人关注响应")
public class MyFollowResponse extends StoreListResponse implements Serializable {
@ApiModelProperty(notes = "商户号")
private Integer merchantId;
@ApiModelProperty(notes = "业务场景")
private Byte businessType;
@ApiModelProperty(notes = "业务场景名称")
private String businessTypeName;
@ApiModelProperty(notes = "主营品牌")
private String brandName;
@ApiModelProperty(notes = "所属区域 (省)")
private String provinceName;
@ApiModelProperty(notes = "所属区域 (市)")
private String cityName;
@ApiModelProperty(notes = "区域运营 (多个按“/”区分)")
private String regionalOperator;
@ApiModelProperty(notes = "区域运营ID (多个按“,”区分)")
private String regionalOperatorId;
@ApiModelProperty(notes = "线上运营 (多个按“/”区分)")
private String onlineOperator;
@ApiModelProperty(notes = "线上运营ID (多个按“,”区分)")
private String onlineOperatorId;
@ApiModelProperty(notes = "区域督导 (多个按“/”区分)")
private String regionalSupervisor;
@ApiModelProperty(notes = "区域督导ID (多个按“,”区分)")
private String regionalSupervisorId;
@ApiModelProperty(notes = "招聘负责人 (多个按“/”区分)")
private String recruitmentManager;
@ApiModelProperty(notes = "招聘负责人ID/电话 (多个按“/”区分)")
private String recruitmentManagerId;
@ApiModelProperty(notes = "技师督导 (多个按“/”区分)")
private String technicianSupervisor;
@ApiModelProperty(notes = "关注人姓名 (多个按“/”区分)")
private String followerNames;
@ApiModelProperty(notes = "关注人总数")
private Integer followerCount;
private static final long serialVersionUID = 1L;
}
......@@ -101,6 +101,24 @@ public class StoreDetailSummaryResponse implements Serializable {
@ApiModelProperty(notes = "总成交数环比")
private String totalDealCountMom;
@ApiModelProperty(notes = "区域督导")
private String regionalSupervisor;
@ApiModelProperty(notes = "招聘负责人")
private String recruitmentManager;
@ApiModelProperty(notes = "技师督导")
private String technicianSupervisor;
@ApiModelProperty(notes = "平均客单价")
private BigDecimal avgCustomerPrice;
@ApiModelProperty(notes = "升级客单价")
private BigDecimal upgradeCustomerPrice;
@ApiModelProperty(notes = "目标平客价")
private BigDecimal targetAvgCustomerPrice;
@ApiModelProperty(notes = "售前转化率")
private BigDecimal preSalesConversionRate;
......
......@@ -6,6 +6,7 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.util.CollectionUtils;
import java.io.Serializable;
......@@ -16,6 +17,7 @@ import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class StoreListResponse implements Serializable {
private static final long serialVersionUID = -1L;
......@@ -53,6 +55,18 @@ public class StoreListResponse implements Serializable {
@ApiModelProperty(notes = "事项")
private List<Integer> storeMatter;
@ApiModelProperty(notes = "是否关注 (1:是; 0:否)")
private Integer isFollow;
@ApiModelProperty(notes = "关注数")
private Integer followCount;
@ApiModelProperty(notes = "最新留言/策略摘要")
private String latestComment;
@ApiModelProperty(notes = "最新策略ID (用于详情查询)")
private Integer latestStrategyId;
public StoreListResponse(Integer storeId, String storeName) {
this.storeId = storeId;
this.storeName = storeName;
......
package cn.com.glsx.dj.peanalysis.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
@Table(name = "dj_merchant_bi_follow")
@Accessors(chain = true)
@Data
@ToString(callSuper = true)
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class MerchantBiFollow implements Serializable {
/**
* 主键id
*/
@Id
private Integer id;
/**
* 门店号
*/
@Column(name = "merchant_id")
private Integer merchantId;
/**
* 门店名称
*/
@Column(name = "merchant_name")
private String merchantName;
/**
* 业务场景
*/
@Column(name = "business_type")
private Byte businessType;
/**
* 关注数
*/
@Column(name = "follow_count")
private Integer followCount;
/**
* 创建人
*/
@Column(name = "created_by")
private String createdBy;
/**
* 创建时间
*/
@Column(name = "created_date")
private Date createdDate;
/**
* 修改人
*/
@Column(name = "updated_by")
private String updatedBy;
/**
* 修改时间
*/
@Column(name = "updated_date")
private Date updatedDate;
/**
* 删除标识(D:已删除;N:未删除)
*/
@Column(name = "deleted_flag")
private String deletedFlag;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
@Table(name = "dj_merchant_bi_follow_detail")
@Accessors(chain = true)
@Data
@ToString(callSuper = true)
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class MerchantBiFollowDetail implements Serializable {
/**
* 主键id
*/
@Id
private Integer id;
/**
* dj_merchant_bi_follow.id
*/
@Column(name = "follow_id")
private Integer followId;
/**
* 员工编号
*/
@Column(name = "staff_uuid")
private String staffUuid;
/**
* 员工手机号
*/
@Column(name = "staff_phone")
private String staffPhone;
/**
* 员工姓名
*/
@Column(name = "staff_name")
private String staffName;
/**
* 创建人
*/
@Column(name = "created_by")
private String createdBy;
/**
* 创建时间
*/
@Column(name = "created_date")
private Date createdDate;
/**
* 修改人
*/
@Column(name = "updated_by")
private String updatedBy;
/**
* 修改时间
*/
@Column(name = "updated_date")
private Date updatedDate;
/**
* 删除标识(D:已删除;N:未删除)
*/
@Column(name = "deleted_flag")
private String deletedFlag;
@Transient
private Integer merchantId;
@Transient
private Integer businessType;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
......@@ -86,4 +86,16 @@ public interface BusinessSceneAnalysisRemote {
RpcResponse<List<LostStoreDetailResponse>> findLostStore(SceneBaseReq req);
/**
* 查询督导产值
*/
@ApiMethod("查询督导产值")
RpcResponse<SceneOutputResponse> querySupervisorOutput(SceneBaseReq req);
/**
* 查询督导员工排名
*/
@ApiMethod("查询督导员工产值列表")
RpcResponse<List<StoreEmployeeRankResponse.EmployeeAnalysisItem>> querySupervisorEmployeeOutput(SceneBaseReq req);
}
package cn.com.glsx.dj.peanalysis.remote;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.framework.core.annotation.ApiService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
/**
* BI-门店留言远程接口
* @author lyj
* @version 2.0
* @since 2026/03/12
*/
@ApiService(value = "bi门店留言", owner = "dev", protocol = ApiService.ProtocolEnum.dubbo)
public interface MerchantBiCommentRemote {
/**
* 新增门店留言
*/
RpcResponse<Boolean> addComment(MerchantBiCommentReq request);
/**
* 撤回门店留言 (逻辑删除,限本人)
*/
RpcResponse<Boolean> withdrawComment(Integer id, String staffUuid);
}
package cn.com.glsx.dj.peanalysis.remote;
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.analysis.MerchantBiFollowReq;
import cn.com.glsx.framework.core.annotation.ApiService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import java.util.List;
import java.util.Map;
/**
* BI-门店关注远程接口
* @author lyj
* @version 1.0
* @since 2026/03/12
*/
@ApiService(value = "bi门店关注", owner = "dev", protocol = ApiService.ProtocolEnum.dubbo)
public interface MerchantBiFollowRemote {
/**
* 关注/取消关注门店
* @param request 请求参数
* @return 操作结果
*/
RpcResponse<Boolean> followMerchant(MerchantBiFollowReq request);
/**
* 我的关注列表
* @param request 查询参数
* @return 关注列表
*/
RpcResponse<List<MyFollowResponse>> myFollowList(SceneBaseReq request);
/**
* 他人关注列表
* @param request 查询参数
* @return 关注列表
*/
RpcResponse<List<MyFollowResponse>> othersFollowList(SceneBaseReq request);
/**
* 批量查询门店关注状态
* @param request 请求参数 (含 merchantIds, staffUuid, businessType)
* @return 门店 ID -> 是否关注 (1:是; 0:否)
*/
RpcResponse<Map<Integer, Integer>> findFollowStatus(MerchantBiFollowReq request);
/**
* 批量查询门店关注数
* @param request 请求参数 (含 merchantIds, businessType)
* @return 门店 ID -> 关注数
*/
RpcResponse<Map<Integer, Integer>> findFollowCounts(MerchantBiFollowReq request);
/**
* 查询当前员工关注数
* @param request 请求参数 (含 staffUuid, businessType)
* @return 关注数量
*/
RpcResponse<Integer> countStaffFollows(SceneBaseReq request);
}
# IDE files
.idea/
.vscode/
.trae/
*.iml
# Build output
target/
# Logs
*.log
logging.path_IS_UNDEFINED
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Java
*.class
*.jar
*.war
*.ear
# Maven
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
\ No newline at end of file
......@@ -10,26 +10,41 @@
<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.7.0-SNAPSHOT</mindworkplate.api.version>
<pe-analysis.api.version>5.7.0-SNAPSHOT</pe-analysis.api.version>
<strategy.api.version>5.7.0-SNAPSHOT</strategy.api.version>
<supervisor.api.version>1.0.0-SNAPSHOT</supervisor.api.version>
</properties>
<dependencies>
<dependency>
<groupId>cn.com.glsx.dj.peanalysis</groupId>
<artifactId>rpc-dj-pe-analysis-api</artifactId>
<version>5.6.4-SNAPSHOT</version>
<version>${pe-analysis.api.version}</version>
</dependency>
<dependency>
<groupId>cn.com.glsx.dj.strategy</groupId>
<artifactId>rpc-dj-strategy-api</artifactId>
<version>${strategy.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>
......@@ -67,5 +82,10 @@
<artifactId>hutool-all</artifactId>
<version>5.8.38</version>
</dependency>
<dependency>
<groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-supervisor-api</artifactId>
<version>${supervisor.api.version}</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "asyncTaskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3); // 核心线程数
executor.setMaxPoolSize(8); // 最大线程数
executor.setQueueCapacity(100); // 队列容量
executor.setThreadNamePrefix("async-");
executor.initialize();
return executor;
}
}
package cn.com.glsx.dj.peanalysis.config;
import cn.com.glsx.dj.smartcarlife.remote.StaffInfoRemote;
import cn.com.glsx.dj.supervisor.remote.SupervisorTaskInfoRemote;
import org.oreframework.boot.autoconfigure.dubbo.reference.ReferenceBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
......@@ -32,5 +34,10 @@ public class DubboConfig {
public RpcRemote rpcApiMethodRemote(){
return factory.builder(RpcRemote.class).check(false).timeout(30000).build();
}*/
@Bean
public SupervisorTaskInfoRemote supervisorTaskInfoRemote(){
return factory.builder(SupervisorTaskInfoRemote.class).check(check).timeout(timeout).build();
}
}
package cn.com.glsx.dj.peanalysis.dto;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 企业微信推送参数
*
* @author lyj
* @since 2026/03/20
*/
@Data
@Builder
public class WechatPushParam implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 推送标题
*/
private String title;
/**
* 推送内容
*/
private String content;
/**
* 门店 ID
*/
private Integer storeId;
/**
* 门店名称
*/
private String storeName;
/**
* 业务类型(1:延保 2:轻改 3:权益)
*/
private Byte businessTypeCode;
/**
* 接收人 UUID 列表
*/
private List<String> targetUuids;
/**
* 标签页(默认 message)
*/
@Builder.Default
private String tab = "message";
/**
* 查询类型(默认 month)
*/
@Builder.Default
private String queryType = "month";
/**
* 开始日期(为空则自动计算最近一个月)
*/
private String startDay;
/**
* 结束日期(为空则自动计算最近一个月)
*/
private String endDay;
}
package cn.com.glsx.dj.peanalysis.job;
import cn.com.glsx.dj.peanalysis.dto.StoreSettingDTO;
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.service.MerchantBasicInfoService;
import cn.com.glsx.dj.peanalysis.service.MerchantBiCommentService;
import cn.com.glsx.dj.peanalysis.service.WechatPushService;
import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils;
import cn.com.glsx.dj.strategy.model.StrategyInfo;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
/**
* 每日上午9点,汇总门店+业务的昨日动态推送
*
* @author lyj
*/
@Slf4j
@Component
@ElasticJobConf(name = "MerchantBiDailyPushJob", cron = "0 0 9 * * ?", description = "每日BI动态汇总推送", overwrite = false)
public class MerchantBiDailyPushJob implements SimpleJob {
@Resource
private MerchantBiCommentService commentService;
@Resource
private WechatPushService wechatPushService;
@Resource
private MerchantBiFollowMapper followMapper;
@Resource
private MerchantBiFollowDetailMapper followDetailMapper;
@Resource
private ServiceMerchantMapper serviceMerchantMapper;
@Autowired
private MerchantBasicInfoService merchantBasicInfoService;
@Override
public void execute(ShardingContext shardingContext) {
log.info("开始执行每日 BI 动态汇总推送任务");
// 1. 查询昨日有新增策略/留言的门店 ID 列表
List<StrategyInfo> yesterdayStrategy = commentService.findMerchantIdsWithYesterdayComments();
if (CollectionUtils.isEmpty(yesterdayStrategy)) {
log.info("昨日无新增策略/留言,无需推送");
return;
}
List<Integer> merchantIds = yesterdayStrategy.stream().map(StrategyInfo::getMerchantId).distinct().collect(Collectors.toList());
List<String> merchantNames = yesterdayStrategy.stream().map(StrategyInfo::getMerchantName).distinct().collect(Collectors.toList());
List<Byte> bizs = yesterdayStrategy.stream().map(p -> p.getBiz().byteValue()).distinct().collect(Collectors.toList());
log.info("昨日有动态的门店号:{}", merchantIds);
log.info("昨日有动态的门店名:{}", merchantNames);
// 2. 批量查询昨日动态数 (返回 Map<key:merchantId_businessType, count>)
Map<String, Integer> countMap = commentService.batchCountYesterdayCommentsByBizType(merchantIds, bizs);
// 3. 批量查询门店配置 (按业务类型对应的 scene 查询)
Map<String, StoreSettingDTO> settingMap = getMerchantSettingMap(merchantIds, bizs);
// 4. 批量查询关注详情信息(门店+业务)
Map<String, List<MerchantBiFollowDetail>> followersMap = getFollowDetailMap(merchantIds, bizs);
Map<String, List<StrategyInfo>> groupByKey = yesterdayStrategy.stream()
.collect(Collectors.groupingBy(p -> p.getMerchantId() + "_" + p.getBiz()));
groupByKey.forEach((key, itemList) -> {
if (CollectionUtils.isEmpty(itemList)) {
log.error("该场景下无策略数据, key:{}", key);
return;
}
log.info("开始处理推送,key:{}, size:{}", key, itemList.size());
for (StrategyInfo item : itemList) {
try {
Integer merchantId = item.getMerchantId();
Byte businessType = item.getBiz().byteValue();
// 获取该门店 + 业务昨日的动态数
Integer yesterdayCount = countMap.getOrDefault(key, 0);
// 只推送昨日有动态的组合
if (yesterdayCount <= 0) {
log.info("【{}-{}】门店昨日无动态", merchantId, businessType);
continue;
}
// 获取门店配置
StoreSettingDTO setting = settingMap.get(key);
if (setting == null) {
log.info("【{}-{}】门店无相关配置", merchantId, businessType);
continue;
}
// 场景 3: 推送给区域运营和线上运营(无论是否有关注人都要推送)
pushToOperatorsWithData(item, yesterdayCount, setting);
// 场景 4: 推送给所有关注人(只有存在关注人才推送)
List<MerchantBiFollowDetail> details = followersMap.get(key);
if (CollectionUtils.isNotEmpty(details)) {
pushToFollowersWithDetails(item, yesterdayCount, details);
} else {
log.info("【{}-{}】门店无关注人,仅推送给区域运营和线上运营", merchantId, businessType);
}
} catch (Exception e) {
log.error("处理门店关注记录失败,门店 ID:{}, 业务类型:{}, 错误:{}",
item.getMerchantId(), item.getBiz(), e.getMessage(), e);
}
}
});
log.info("每日 BI 动态汇总推送任务执行完成");
}
private Map<String, List<MerchantBiFollowDetail>> getFollowDetailMap(List<Integer> merchantIds, List<Byte> bizs) {
if (merchantIds == null || merchantIds.isEmpty()) {
return Collections.emptyMap();
}
log.info("查询关注人信息, merchantIds:{}, bizs:{}", merchantIds, bizs);
List<MerchantBiFollowDetail> details = followDetailMapper.findByMerchantIdsAndBizs(merchantIds, bizs);
if (CollectionUtils.isEmpty(details)) {
log.info("查询关注人信息为空");
return Collections.emptyMap();
}
return details.stream().collect(Collectors.groupingBy(p -> p.getMerchantId() + "_" + p.getBusinessType()));
}
/**
* 处理业务+门店下的配置信息缓存
*/
private Map<String, StoreSettingDTO> getMerchantSettingMap(List<Integer> merchantIds, List<Byte> businessTypes) {
Map<String, StoreSettingDTO> settingMap = new HashMap<>();
for (Byte bizType : businessTypes) {
List<Integer> unCacheMerchantIds = new ArrayList<>();
for (Integer merchantId : merchantIds) {
String key = merchantId + "_" + bizType;
if (settingMap.containsKey(key)) {
continue;
}
unCacheMerchantIds.add(merchantId);
}
if (CollectionUtils.isEmpty(unCacheMerchantIds)) {
continue;
}
Integer scene = MetricsValueUtils.convertBizsToScene(bizType.intValue());
List<StoreSettingDTO> settings = serviceMerchantMapper.findStoreSetting(unCacheMerchantIds, scene);
for (StoreSettingDTO setting : settings) {
if (setting == null || setting.getMerchantId() == null) {
continue;
}
String key = setting.getMerchantId() + "_" + bizType;
// 处理区域运营,重新赋值
setting.setRegionalOperationId(String.join(",", merchantBasicInfoService.getOperationStaffUuid(setting)));
// setting.setOnlineOperationId(String.join(",", merchantBasicInfoService.getOnlineStaffUuid(setting)));
settingMap.put(key, setting);
}
}
log.info("settingMap.keySet:{}", settingMap.keySet());
return settingMap;
}
/**
* 推送给负责人(使用已查询的配置数据)
*/
private void pushToOperatorsWithData(StrategyInfo strategyInfo, int count, StoreSettingDTO setting) {
Integer merchantId = strategyInfo.getMerchantId();
Integer businessType = strategyInfo.getBiz();
List<String> targetUuids = new ArrayList<>();
// 此时的uuid已经经过角色有效性过滤
if (StringUtils.isNotBlank(setting.getRegionalOperationId()))
targetUuids.addAll(Arrays.asList(StringUtils.split(setting.getRegionalOperationId(), ",")));
if (StringUtils.isNotBlank(setting.getOnlineOperationId()))
targetUuids.addAll(Arrays.asList(StringUtils.split(setting.getOnlineOperationId(), ",")));
if (CollectionUtils.isEmpty(targetUuids)) {
log.info("【{}-{}】门店配置无相应人员", merchantId, businessType);
return;
}
wechatPushService.pushDailySummaryMsg(strategyInfo, count, targetUuids, false);
}
/**
* 推送给关注人(使用已查询的关注明细)
*/
private void pushToFollowersWithDetails(StrategyInfo strategyInfo, int count, List<MerchantBiFollowDetail> details) {
Integer merchantId = strategyInfo.getMerchantId();
Byte businessType = strategyInfo.getBiz().byteValue();
List<String> followerUuids = details.stream()
.map(MerchantBiFollowDetail::getStaffUuid)
.filter(StringUtils::isNotBlank)
.distinct()
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(followerUuids)) {
List<Integer> followIds = details.stream().map(MerchantBiFollowDetail::getFollowId).distinct().collect(Collectors.toList());
log.info("【{}-{}】门店无关注人, followIds:{}", merchantId, businessType, followIds);
return;
}
wechatPushService.pushDailySummaryMsg(strategyInfo, count, followerUuids, true);
}
}
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);
/**
* 批量根据关注 ID 查询所有明细
*
* @param followIds 关注 ID 列表
* @return 所有关注明细列表
*/
List<MerchantBiFollowDetail> batchFindByFollowId(@Param("followIds") List<Integer> followIds);
List<MerchantBiFollowDetail> findByMerchantIdsAndBizs(@Param("merchantIds") List<Integer> merchantIds, @Param("bizs") List<Byte> bizs);
}
\ No newline at end of file
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, @Param("merchantName") String merchantName);
/**
* 通用查询关注门店+业务组合(支持按员工查询/排除员工、权限门店过滤)
*/
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);
/**
* 根据员工 UUID 查询关注数量
* @param staffUuid 员工 UUID
* @param businessType 业务类型(可选)
* @return 关注数量
*/
Integer countFollowsByStaffUuid(@Param("staffUuid") String staffUuid, @Param("businessType") Byte businessType);
}
......@@ -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.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.dj.strategy.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;
import java.util.Map;
@Mapper
public interface StrategyInfoMapper extends OreMapper<StrategyInfo> {
/**
* 查询门店最新动态
*/
List<StrategyInfo> findLatestStrategyRecords(MerchantBiCommentReq req);
/**
* 统计指定时间段内的记录数
*/
int countStrategyByTime(@Param("merchantIds") List<Integer> merchantIds, @Param("biz") Integer biz, @Param("startDate") Date startDate, @Param("endDate") Date endDate);
/**
* 批量统计指定时间段内的记录数(按门店分组)
*
* @param merchantIds 门店 ID 列表
* @param biz 业务类型
* @param startDate 开始时间
* @param endDate 结束时间
* @return List<Map>, 每个 Map 包含 merchant_id 和 count
*/
List<Map<String, Object>> batchCountStrategyByTime(
@Param("merchantIds") List<Integer> merchantIds,
@Param("biz") Integer biz,
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
/**
* 查询指定时间段内有新增策略/留言的门店 ID 列表
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return List<Map>, 每个 Map 包含 merchant_id
*/
List<StrategyInfo> findMerchantIdsWithCommentsByTime(
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
}
package cn.com.glsx.dj.peanalysis.mapper;
import cn.com.glsx.dj.strategy.model.StrategyStaffRel;
import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
@Mapper
public interface StrategyStaffRelMapper extends OreMapper<StrategyStaffRel> {
}
......@@ -20,7 +20,7 @@ import java.util.List;
*/
@Slf4j
@DubboService(validation = "true", version = "1.0.0")
public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRemote{
public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRemote {
@Resource
private BusinessSceneAnalysisService businessSceneAnalysisService;
......@@ -127,7 +127,7 @@ public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRem
}
@Override
public RpcResponse<List<StoreListResponse>> storeList(SceneBaseReq req){
public RpcResponse<List<StoreListResponse>> storeList(SceneBaseReq req) {
try {
return RpcResponse.success(businessSceneAnalysisService.storeList(req));
} catch (RpcServiceException e) {
......@@ -140,7 +140,7 @@ public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRem
}
@Override
public RpcResponse<StoreDetailSummaryResponse> storeDetailSummary(SceneBaseReq req){
public RpcResponse<StoreDetailSummaryResponse> storeDetailSummary(SceneBaseReq req) {
try {
return RpcResponse.success(businessSceneAnalysisService.storeDetailSummary(req));
} catch (RpcServiceException e) {
......@@ -153,7 +153,7 @@ public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRem
}
@Override
public RpcResponse<StoreEmployeeRankResponse> storeEmployeeRank(SceneBaseReq req){
public RpcResponse<StoreEmployeeRankResponse> storeEmployeeRank(SceneBaseReq req) {
try {
return RpcResponse.success(businessSceneAnalysisService.storeEmployeeRank(req));
} catch (RpcServiceException e) {
......@@ -166,7 +166,7 @@ public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRem
}
@Override
public RpcResponse<List<TrafficContributionRankResponse>> storeTrafficRank(SceneBaseReq req){
public RpcResponse<List<TrafficContributionRankResponse>> storeTrafficRank(SceneBaseReq req) {
try {
return RpcResponse.success(businessSceneAnalysisService.storeTrafficRank(req));
} catch (RpcServiceException e) {
......@@ -179,7 +179,7 @@ public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRem
}
@Override
public RpcResponse<EmployeeDetailSummaryResponse> storeEmployeeSummary(SceneBaseReq req){
public RpcResponse<EmployeeDetailSummaryResponse> storeEmployeeSummary(SceneBaseReq req) {
try {
return RpcResponse.success(businessSceneAnalysisService.storeEmployeeSummary(req));
} catch (RpcServiceException e) {
......@@ -192,7 +192,7 @@ public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRem
}
@Override
public RpcResponse<GoodsCategorySummaryResponse> goodsSummary(SceneBaseReq req){
public RpcResponse<GoodsCategorySummaryResponse> goodsSummary(SceneBaseReq req) {
try {
return RpcResponse.success(businessSceneAnalysisService.goodsSummary(req));
} catch (RpcServiceException e) {
......@@ -205,7 +205,7 @@ public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRem
}
@Override
public RpcResponse<List<BiRecord>> getBiRecords(Integer businessType, List<Integer> merchantIds, String startDate, String endDate){
public RpcResponse<List<BiRecord>> getBiRecords(Integer businessType, List<Integer> merchantIds, String startDate, String endDate) {
try {
return RpcResponse.success(businessSceneAnalysisService.getBiRecords(businessType, merchantIds, startDate, endDate));
} catch (RpcServiceException e) {
......@@ -295,4 +295,30 @@ public class BusinessSceneAnalysisRemoteImpl implements BusinessSceneAnalysisRem
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<SceneOutputResponse> querySupervisorOutput(SceneBaseReq req) {
try {
return RpcResponse.success(businessSceneAnalysisService.querySupervisorOutput(req));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
} catch (Exception e) {
log.error("系统异常", e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<List<StoreEmployeeRankResponse.EmployeeAnalysisItem>> querySupervisorEmployeeOutput(SceneBaseReq req) {
try {
return RpcResponse.success(businessSceneAnalysisService.querySupervisorEmployeeOutput(req));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
} catch (Exception e) {
log.error("系统异常", e);
return RpcResponse.error(e);
}
}
}
package cn.com.glsx.dj.peanalysis.remote;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.dj.peanalysis.service.MerchantBiCommentService;
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;
/**
* 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());
}
}
}
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());
}
}
@Override
public RpcResponse<Integer> countStaffFollows(@RequestBody SceneBaseReq request) {
try {
return RpcResponse.success(followService.countStaffFollows(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();
......@@ -296,13 +311,15 @@ public class BusinessSceneAnalysisService {
}
String targetMonth = queryParams.getStartDate();
byte businessType = req.convertToBusinessType(queryParams.getBizs());
RpcPagination<MerchantOutputTargetConfigDTO> pagination = new RpcPagination<>();
pagination.setPageSize(Integer.MAX_VALUE);
pagination.setPageNum(1);
MerchantOutputTargetConfigDTO condition = new MerchantOutputTargetConfigDTO();
condition.setMerchantIdList(req.getMerchantIds());
condition.setBusinessType(businessType);
if (queryParams.getBizs() != null) {
byte businessType = req.convertToBusinessType(queryParams.getBizs());
condition.setBusinessType(businessType);
}
condition.setTargetMonth(targetMonth.substring(0, targetMonth.length() - 3));
pagination.setCondition(condition);
RpcResponse<RpcPagination<MerchantOutputTargetConfigDTO>> outputTargetConfigResp = merchantOutputTargetConfigRemote.listWithPage(pagination);
......@@ -319,25 +336,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 +360,7 @@ public class BusinessSceneAnalysisService {
// 一次性查询全部时间范围内的指标数据,存储为按周期段分组的Map
Map<Pair<String, String>, List<DataBusinessDTO>> datePairDataMap = new HashMap<>();
try {
// 获取门店权限ID列表
List<Integer> merchantIds = getMerchantIdPermission(req, false);
......@@ -365,30 +370,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 +401,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 +428,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 +442,7 @@ public class BusinessSceneAnalysisService {
item.setRatio(BigDecimal.ZERO); // 达成率初始化为0
item.setStartTime(begin); // 设置开始时间
item.setEndTime(end); // 设置结束时间
// 根据周期类型设置时间显示格式
switch (req.getCycleType()) {
case 1: // 按日
......@@ -452,16 +457,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 +483,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 +508,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 +542,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 +750,7 @@ public class BusinessSceneAnalysisService {
req.setTempList(merchantIdList);
return true;
}
/**
* 处理延保预警门店
*/
......@@ -757,6 +763,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 +903,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 +1041,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 +1128,7 @@ public class BusinessSceneAnalysisService {
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
......@@ -1134,7 +1142,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 +1258,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 +1278,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 +1305,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 +1354,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 +1364,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 +1376,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 +1401,7 @@ public class BusinessSceneAnalysisService {
// 获取产值门店
try {
req.setMerchantIds(getMerchantIdPermission(req, false, true));
}catch (Exception e){
} catch (Exception e) {
return res;
}
// 查询指标
......@@ -1494,7 +1486,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 +1525,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 +1555,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 +1602,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 +1639,9 @@ public class BusinessSceneAnalysisService {
public StoreDetailSummaryResponse storeDetailSummary(SceneBaseReq req) {
StoreDetailSummaryResponse res = new StoreDetailSummaryResponse();
DataBizQueryParamsDTO queryParams = req.convertQueryParam();
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
}catch (Exception e){
return res;
}
// 查询门店信息、所属服务商、区域运营、销售、线上运营
long startMs = System.currentTimeMillis();
// 查询门店信息:所属服务商、区域运营、销售、线上运营
Integer sceneType = req.convertToSceneType(queryParams.getBizs());
List<StoreSettingDTO> storeList = serviceMerchantMapper.findStoreSetting(req.getMerchantIds(), sceneType);
if (CollectionUtils.isNotEmpty(storeList)) {
......@@ -1640,13 +1649,34 @@ 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());
// 产值权限过滤
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
} catch (Exception e) {
return res;
}
// 查询指标
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 +1686,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 +1773,7 @@ public class BusinessSceneAnalysisService {
try {
req.setMerchantIds(getMerchantIdPermission(req, null, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
......@@ -1750,21 +1791,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 +1824,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 +1860,7 @@ public class BusinessSceneAnalysisService {
try {
req.setMerchantIds(getMerchantIdPermission(req, null, false));
}catch (Exception e){
} catch (Exception e) {
return Collections.emptyList();
}
......@@ -1854,7 +1895,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 +1916,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 +1979,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 +2009,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 +2113,7 @@ public class BusinessSceneAnalysisService {
try {
req.setMerchantIds(getMerchantIdPermission(req, null, false));
}catch (Exception e){
} catch (Exception e) {
return res;
}
......@@ -2202,15 +2229,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 +2253,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 +2261,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 +2273,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 +2308,6 @@ public class BusinessSceneAnalysisService {
/**
*
* @param bizs 业务类型(1.延保 2.轻改 3.权益)
* @return
*/
......@@ -2296,12 +2324,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 +2341,12 @@ public class BusinessSceneAnalysisService {
return wariningList.stream().map(MonitoringMsgDTO::getWarningText).collect(Collectors.toList());
}
private BigDecimal queryTargetAvgCustomerPrice(SceneBaseReq req) {
// 实现获取最近一次嘀加上架记录中的预估目标客单价的逻辑
// 目前暂无该表具体 Mapper,先返回 null
return null;
}
/**
* 查询兜底预警门店
*
......@@ -2369,7 +2404,6 @@ public class BusinessSceneAnalysisService {
if (CollectionUtils.isEmpty(collect)){
return Collections.EMPTY_LIST;
}
List<Integer> merchantIds = collect.stream().map(LostStoreDetailResponse::getStoreId)
.collect(Collectors.toList());
......@@ -2389,6 +2423,51 @@ public class BusinessSceneAnalysisService {
return collect;
}
/**
* 查询产值
*/
public SceneOutputResponse querySupervisorOutput(SceneBaseReq req) {
SceneOutputResponse outputResponse = new SceneOutputResponse();
DataBizQueryParamsDTO queryParams = req.convertQueryParam();
queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
queryParams.setItemCodes(DataStatsConstants.ITEM_CODE_A036);
List<DataBusinessDTO> totalOutputList = businessAnalysisService.getTotalOutputGroupByMerchant(queryParams);
if (CollectionUtils.isNotEmpty(totalOutputList)) {
outputResponse.setOutputValue(totalOutputList.get(0).getItemValue());
}
return outputResponse;
}
/**
* 查询督导员工产值列表
*/
public List<StoreEmployeeRankResponse.EmployeeAnalysisItem> querySupervisorEmployeeOutput(SceneBaseReq req) {
DataBizQueryParamsDTO queryParams = req.convertQueryParam();
queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
queryParams.setItemCodes(DataStatsConstants.ITEM_CODE_A036);
queryParams.setExts("staffIds");
List<DataBusinessDTO> totalOutputList = businessAnalysisService.getTotalOutputGroupByMerchant(queryParams);
if (CollectionUtils.isNotEmpty(totalOutputList)) {
Map<String, StoreEmployeeRankResponse.EmployeeAnalysisItem> employeeMap = totalOutputList.stream()
.filter(x -> StringUtils.isNotBlank(x.getStaffPhone())) // 过滤无效手机号
.collect(Collectors.toMap(
DataBusinessDTO::getStaffPhone,
x -> new StoreEmployeeRankResponse.EmployeeAnalysisItem()
.setEmployeePhone(x.getStaffPhone())
// 处理初始值为 null 的情况,默认为 0
.setPersonalOutputValue(x.getItemValue() != null ? x.getItemValue() : BigDecimal.ZERO),
(a, b) -> {
// 安全相加
BigDecimal valA = a.getPersonalOutputValue();
BigDecimal valB = b.getPersonalOutputValue();
return a.setPersonalOutputValue(valA.add(valB));
}
));
return new ArrayList<>(employeeMap.values());
}
return Collections.emptyList();
}
/**
* 查询门店产值目标
......
......@@ -36,6 +36,8 @@ public class GetDataStatsService {
DataResp<List<DataBusinessDTO>> dataResp;
// String url = OrePropertyConfigurer.getProperty("total.data.url", String.class, "http://dc.glsx.com.cn/data");
String url = OrePropertyConfigurer.getProperty("total.data.url", String.class, "http://192.168.3.211:8021/data");
long l = System.currentTimeMillis();
// post请求
String jsonResponse;
try {
......@@ -43,6 +45,8 @@ public class GetDataStatsService {
jsonResponse = HttpRequestUtils.postJson(url, jsonBody, new HashMap<>());
} catch (Exception e) {
throw new RpcServiceException("查询统计数据异常");
} finally {
log.info("查询统计数据耗时: {}ms", System.currentTimeMillis() - l);
}
dataResp = JSONUtil.toBean(jsonResponse, new TypeReference<DataResp<List<DataBusinessDTO>>>() {
}, true);
......@@ -53,6 +57,22 @@ public class GetDataStatsService {
}
/**
* 直接以 JSON 请求体查询指标系统并返回明细列表
* <p>
* 适用于需要传入字符串形式的聚合字段(例如 bizs/itemCodes 以逗号拼接)且保持 exts 维度返回的场景。
* 注意:不要同时指定多个itemCode去查询,指标系统索引失效导致查询缓慢
*/
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 指标编码列表
* @param queryDataBiz 请求参数
......
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.StoreSettingDTO;
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.dto.merchant.CarbrandResponse;
import cn.com.glsx.merchants.model.request.MerchantStaffRequest;
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.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 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.core.env.Environment;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
public class MerchantBasicInfoService {
@Autowired
private MerchantRemote merchantRemote;
@Autowired
private MerchantStaffRemote merchantStaffRemote;
@Autowired
private ServiceMerchantMapper serviceMerchantMapper;
@Autowired
private Environment environment;
/**
* 批量查询门店基础信息(省/市/主营品牌等),返回 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);
log.debug("查询门店基础信息完成:入参={}, 返回门店={}", merchantRequest, map);
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;
}
List<CarbrandResponse> brandList = merchantInfo.getCarBrandList();
if (CollectionUtils.isNotEmpty(brandList)) {
String firstBrandNames = brandList.stream().map(CarbrandResponse::getName).distinct().collect(Collectors.joining(","));
p.setBrandName(firstBrandNames);
}
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)) {
log.info("省份为空");
return Collections.emptyMap();
}
List<String> distinct = provinces.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
if (CollectionUtils.isEmpty(distinct)) {
log.info("省份为空, raw:{}", provinces);
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);
}
}
/**
* 指定员工uuid和角色查询员工uuid
*/
public List<String> getStaffUuidWithRole(List<String> uuids, String roleName) {
MerchantStaffRequest req = new MerchantStaffRequest();
req.setStaffUuidList(uuids);
req.setRoleName(roleName);
RpcResponse<List<MerchantStaffResponse>> staffListRemote = merchantStaffRemote.findMerchantStaffListRemote(req);
if (staffListRemote.isFailed()) {
log.error("查询账户中心员工异常, req={}, res={}", req, staffListRemote);
return Collections.emptyList();
}
List<MerchantStaffResponse> staffList = staffListRemote.getResult();
if (CollectionUtils.isEmpty(staffList)) {
log.warn("查询账户中心员工为空, req={}, res={}", req, staffListRemote);
return Collections.emptyList();
}
List<String> res = staffList.stream().map(MerchantStaffResponse::getUuid).collect(Collectors.toList());
log.info("原始uuid:{},【{}】结果:{},排除:{}", uuids, roleName, res, CollectionUtils.subtract(uuids, res));
return res;
}
/**
* 指定门店配置,查询相关区域运营员工uuid
*/
public Collection<String> getOperationStaffUuid(StoreSettingDTO setting) {
if (setting == null) {
return Collections.emptyList();
}
if (StringUtils.isBlank(setting.getRegionalOperationId())) {
return Collections.emptyList();
}
List<String> configUuids = Arrays.asList(StringUtils.split(setting.getRegionalOperationId(), ","));
if (CollectionUtils.isEmpty(configUuids)) {
return Collections.emptyList();
}
// 查询账户中心员工角色是否正确,过滤过期数据
String roleName = environment.getProperty("dj.pe.analysis.push.regional.operation.role", "区域运营");
List<String> uuids = getStaffUuidWithRole(configUuids, roleName);
return uuids;
}
/**
* 指定门店配置,查询相关区域运营员工uuid
*/
public Collection<String> getOnlineStaffUuid(StoreSettingDTO setting) {
if (setting == null) {
return Collections.emptyList();
}
if (StringUtils.isBlank(setting.getOnlineOperationId())) {
return Collections.emptyList();
}
List<String> configUuids = Arrays.asList(StringUtils.split(setting.getOnlineOperationId(), ","));
if (CollectionUtils.isEmpty(configUuids)) {
return Collections.emptyList();
}
// 查询账户中心员工角色是否正确,过滤过期数据
// String roleName = environment.getProperty("dj.pe.analysis.push.online.operation.role", "线上运营");
// List<String> uuids = getStaffUuidWithRole(configUuids, roleName);
// return uuids;
// 线上运营不用过滤
return configUuids;
}
}
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.analysis.HandlerStaffInfo;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.dj.peanalysis.mapper.StrategyInfoMapper;
import cn.com.glsx.dj.peanalysis.mapper.StrategyStaffRelMapper;
import cn.com.glsx.dj.strategy.model.StrategyInfo;
import cn.com.glsx.dj.strategy.model.StrategyStaffRel;
import cn.com.glsx.dj.supervisor.dto.CreateSpecialTaskDTO;
import cn.com.glsx.dj.supervisor.remote.SupervisorTaskInfoRemote;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
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;
@Autowired
private SupervisorTaskInfoRemote supervisorTaskInfoRemote;
private static final Integer STRATEGY_TYPE_COMMENT = 7;
/**
* 新增留言 (映射为策略类型 7)
*/
@Transactional(rollbackFor = Exception.class)
public Boolean addComment(MerchantBiCommentReq request) {
StrategyInfo strategy = new StrategyInfo();
strategy.setStrategyType(STRATEGY_TYPE_COMMENT);
strategy.setTitle("留言-" + request.getStaffName());
// strategy.setContent(request.getContent());
strategy.setDescription(request.getContent());
strategy.setMerchantId(request.getMerchantId());
strategy.setMerchantName(request.getMerchantName());
strategy.setBiz(request.getBusinessType() != null ? request.getBusinessType().intValue() : null);
strategy.setCreatedUUid(request.getStaffUuid());
strategy.setCreatedBy(request.getStaffName());
strategy.setCreatedDate(new Date());
strategy.setUpdatedBy(request.getStaffName());
strategy.setUpdatedDate(new Date());
strategy.setDeletedFlag("N");
strategy.setStartDate(new Date());
strategy.setPushType(0);
strategy.setPushFlag(0);
boolean success = strategyInfoMapper.insertSelective(strategy) > 0;
if (success && CollectionUtils.isNotEmpty(request.getHandlerStaffList())) {
// 推送督导小程序任务
List<CreateSpecialTaskDTO> pushSupervisorTaskList = new ArrayList<>();
// 2. 插入处理人关联表 (@ 提醒)
List<String> uuids = new ArrayList<>();
for (HandlerStaffInfo handler : request.getHandlerStaffList()) {
StrategyStaffRel rel = new StrategyStaffRel();
rel.setStrategyId(strategy.getId());
rel.setUserUuid(handler.getStaffUuid());
rel.setUserName(handler.getStaffName() != null ? handler.getStaffName() : "");
rel.setUserPhone(handler.getStaffPhone() != null ? handler.getStaffPhone() : "");
rel.setCreatedBy(request.getStaffName());
rel.setCreatedDate(new Date());
rel.setDeletedFlag("N");
strategyStaffRelMapper.insertSelective(rel);
uuids.add(handler.getStaffUuid());
CreateSpecialTaskDTO pushItem = new CreateSpecialTaskDTO();
pushItem.setMerchantId(strategy.getMerchantId());
pushItem.setMerchantName(strategy.getMerchantName());
pushItem.setTaskDesc(request.getContent());
pushItem.setSupervisorName(rel.getUserName());
pushItem.setSupervisorPhone(rel.getUserPhone());
pushItem.setCreatedBy(rel.getCreatedBy());
pushSupervisorTaskList.add(pushItem);
}
// 3. 企微推送 (@ 提醒)
try {
wechatPushService.pushMentionMsg(request, uuids);
} catch (Exception e) {
log.error("触发留言 @ 推送异常", e);
}
// 4. 推送到督导小程序
pushSupervisorTaskList.forEach(p -> {
try {
RpcResponse<Long> pushResp = supervisorTaskInfoRemote.createSpecialTask(p);
log.info("推送到督导小程序,结果:{}", pushResp);
} catch (Exception e) {
log.error("推送到督导小程序异常, req:{}", p, 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;
}
/**
* 批量查询策略动态(支持时间范围过滤,可选是否统计总数)
*
* @param request 查询参数(包含 merchantIds, businessType)
* @return Map<门店 ID, StrategyInfo>
*/
public Map<Integer, StrategyInfo> queryLatestStrategy(MerchantBiCommentReq request) {
if (request == null || CollectionUtils.isEmpty(request.getMerchantIds())) {
return Collections.emptyMap();
}
if (request.getStartDate() == null && request.getEndDate() == null) {
// 默认查近一月数据
request.setStartDate(DateUtil.beginOfDay(DateUtil.lastMonth()));
}
long startMs = System.currentTimeMillis();
List<StrategyInfo> results = strategyInfoMapper.findLatestStrategyRecords(request);
if (CollectionUtils.isEmpty(results)) {
log.info("查询策略动态为空:biz={}, 门店数={}, 耗时={}ms",
request.getBusinessType(), request.getMerchantIds().size(), System.currentTimeMillis() - startMs);
return Collections.emptyMap();
}
Map<Integer, StrategyInfo> resultMap = results.stream()
.filter(s -> s != null && s.getMerchantId() != null)
.collect(Collectors.toMap(StrategyInfo::getMerchantId, s -> s, (s1, s2) -> s1));
log.info("查询策略动态完成:biz={}, 门店数={}, 返回数={}, 耗时={}ms",
request.getBusinessType(), request.getMerchantIds().size(), resultMap.size(), System.currentTimeMillis() - startMs);
return resultMap;
}
/**
* 统计昨日新增记录总数
*/
public int countYesterdayComments(MerchantBiCommentReq request) {
Date yesterdayStart = DateUtil.beginOfDay(DateUtil.yesterday());
Date yesterdayEnd = DateUtil.endOfDay(DateUtil.yesterday());
return strategyInfoMapper.countStrategyByTime(
request.getMerchantIds(),
request.getBusinessType() != null ? request.getBusinessType().intValue() : null,
yesterdayStart,
yesterdayEnd
);
}
/**
* 批量统计昨日新增记录总数(按门店 ID 和业务类型分组)
*
* @param merchantIds 门店 ID 列表
* @param businessTypes 业务类型列表
* @return Map<key:merchantId_businessType, 数量>
*/
public Map<String, Integer> batchCountYesterdayCommentsByBizType(
List<Integer> merchantIds,
List<Byte> businessTypes) {
if (merchantIds == null || merchantIds.isEmpty()) {
return Collections.emptyMap();
}
long startMs = System.currentTimeMillis();
Date yesterdayStart = DateUtil.beginOfDay(DateUtil.yesterday());
Date yesterdayEnd = DateUtil.endOfDay(DateUtil.yesterday());
Map<String, Integer> finalResult = new HashMap<>();
for (Byte businessType : businessTypes) {
List<Map<String, Object>> results = strategyInfoMapper.batchCountStrategyByTime(
merchantIds,
businessType != null ? businessType.intValue() : null,
yesterdayStart,
yesterdayEnd
);
Map<Integer, Integer> resultMap = results.stream()
.filter(m -> m != null && m.get("merchant_id") != null)
.collect(java.util.stream.Collectors.toMap(
m -> (Integer) m.get("merchant_id"),
m -> ((Long) m.get("count")).intValue(),
(v1, v2) -> v1
));
resultMap.forEach((k, v) -> finalResult.put(k + "_" + businessType, v));
}
log.info("批量统计昨日动态完成 (多业务类型): 门店数={}, 返回={}, 耗时={}ms",
merchantIds.size(), finalResult, System.currentTimeMillis() - startMs);
return finalResult;
}
/**
* 查询昨日有新增策略/留言的门店
*/
public List<StrategyInfo> findMerchantIdsWithYesterdayComments() {
Date yesterdayStart = DateUtil.beginOfDay(DateUtil.yesterday());
Date yesterdayEnd = DateUtil.endOfDay(DateUtil.yesterday());
return strategyInfoMapper.findMerchantIdsWithCommentsByTime(
yesterdayStart,
yesterdayEnd
);
}
}
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.utils.DateUtils;
import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils;
import cn.com.glsx.dj.smartcarlife.remote.MerchantOutputTargetConfigRemote;
import cn.com.glsx.dj.strategy.model.StrategyInfo;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.util.RpcAssert;
import cn.hutool.core.lang.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
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;
@Autowired
private Environment environment;
@Autowired
@Lazy
private MerchantBiFollowService thiz;
@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 false; // 已经关注
}
// 插入明细
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) {
if (TransactionSynchronizationManager.isActualTransactionActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
thiz.triggerFollowPush(request);
}
});
} else {
thiz.triggerFollowPush(request);
}
}
} else if (Objects.equals(request.getOperateType(), 0)) { // 取消关注
if (existingDetail == null) {
log.info("取消关注门店:本来未关注,无需处理,merchantId={}, biz={}, staffUuid={}",
request.getMerchantId(), request.getBusinessType(), request.getStaffUuid());
return false; // 本来就没关注
}
// 逻辑删除明细
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(), req.getMerchantName());
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();
// 权限过滤
req.setBizs(null);
List<Integer> permissionMerchantIds;
try {
permissionMerchantIds = businessSceneAnalysisService.getMerchantIdPermission(req, false);
}catch (Exception e){
log.error("他人关注前置查询权限异常", e);
return Collections.emptyList();
}
req.setMerchantIds(permissionMerchantIds);
log.info("查询他人关注列表:权限门店数={}, loginUserUuid={}",
permissionMerchantIds == null ? 0 : permissionMerchantIds.size(), req.getLoginUserUuid());
// 查询他人关注门店
List<MyFollowResponse> 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();
}
// 维护当前员工的关注状态
List<MyFollowResponse> myFollowList = followMapper.findMyFollowsByStaffUuid(req.getLoginUserUuid(), req.getMerchantName());
if (CollectionUtils.isNotEmpty(myFollowList)) {
Set<String> myFollowItems = myFollowList.stream()
.map(p -> p.getStoreId() + "_" + p.getBusinessType())
.collect(Collectors.toSet());
resList.forEach(p -> {
String key = p.getStoreId() + "_" + p.getBusinessType();
if (myFollowItems.contains(key)) {
p.setIsFollow(1);
}
});
}
log.info("查询他人关注列表:开始填充扩展信息,loginUserUuid={}, 关注条数={}", req.getLoginUserUuid(), resList.size());
fillFollowDetails(resList, req);
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, req.getLoginUserUuid());
// 1) 门店基础信息:主营品牌、省市等(来自账户中心)
merchantBasicInfoService.fillFollowListMerchantInfo(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<Byte, List<MyFollowResponse>> groupByBiz = resList.stream().collect(Collectors.groupingBy(MyFollowResponse::getBusinessType));
groupByBiz.forEach((businessType, items) -> {
// 目标产值(仅月周期)
req.setBizs(businessType.intValue());
Map<Integer, BigDecimal> targetOutputMap = businessSceneAnalysisService.queryStoreTargetOutput(req);
// 数据填充
fillFollowBizGroupDetails(businessType, items, req, itemCodes, statsIndex, targetOutputMap);
}
);
log.info("关注列表填充完成:关注条数={}, 耗时={}ms", resList.size(), System.currentTimeMillis() - startMs);
}
private void fillFollowerAndComment(List<MyFollowResponse> resList, String excludeStaffUuid) {
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)) {
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<MerchantBiFollowDetail>> followersMap = new HashMap<>();
if (CollectionUtils.isNotEmpty(followIds)) {
List<MerchantBiFollowDetail> allDetails = followDetailMapper.findFollowersByFollowIds(followIds);
if (CollectionUtils.isNotEmpty(allDetails)) {
followersMap = allDetails.stream()
.collect(Collectors.groupingBy(MerchantBiFollowDetail::getFollowId));
}
}
// 3) 批量查询最近一个月内最新动态
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<>();
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.queryLatestStrategy(commentReq);
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<MerchantBiFollowDetail> details = followersMap.get(follow.getId());
if (CollectionUtils.isNotEmpty(details)) {
// 过滤掉需要排除的员工(当前登录用户自己),然后获取姓名列表
LinkedHashSet<String> uniqueNames = details.stream()
.filter(detail -> StringUtils.isNotBlank(detail.getStaffName()))
.filter(detail -> {
// 如果传入了需要排除的员工 UUID,则过滤掉该员工
if (StringUtils.isNotBlank(excludeStaffUuid)) {
return !excludeStaffUuid.equals(detail.getStaffUuid());
}
return true;
})
.map(MerchantBiFollowDetail::getStaffName)
.collect(Collectors.toCollection(LinkedHashSet::new));
res.setFollowerCount(uniqueNames.size());
res.setFollowerNames(String.join("/", uniqueNames));
}
}
res.setLatestComment(latestCommentMap.getOrDefault(key, ""));
res.setLatestStrategyId(latestStrategyIdMap.get(key));
}
log.info("关注列表-关注人&策略摘要填充完成:关注条数={}, 门店数={}, 耗时={}ms",
resList.size(), merchantIds.size(), System.currentTimeMillis() - startMs);
}
/**
* 门店列表(经营分析页)填充关注状态与留言信息:
* 1)关注数
* 2)当前登录人是否关注
* 3)最新留言摘要
*/
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.queryLatestStrategy(commentReq);
res.forEach(item -> {
StrategyInfo summary = commentSummaryMap.get(item.getStoreId());
if (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);
}
/**
* 指标查询:依赖指标系统返回 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");
DataBizQueryParamsDTO queryParams = newReq.convertQueryParam();
queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
queryParams.setBizs(null);
// 使用 parallelCallListMap 并行查询每个指标代码,避免索引失效
Map<String, List<DataBusinessDTO>> dataMap = getDataStatsService.parallelCallListMap(itemCodes, queryParams);
// 直接从 dataMap 构建索引,减少中间列表转换
Map<String, DataBusinessDTO> index = new HashMap<>();
if (MapUtils.isNotEmpty(dataMap)) {
dataMap.forEach((itemCode, dataList) -> {
if (CollectionUtils.isEmpty(dataList)) {
log.info("查询指标itemCode返回数据为空:{}", itemCode);
return;
}
dataList.stream()
.filter(d -> d != null && d.getMerchantId() != null
&& StringUtils.isNotBlank(d.getBiz())
&& StringUtils.isNotBlank(d.getItemCode()))
.forEach(d -> {
String key = d.getMerchantId() + "_" + d.getBiz() + "_" + d.getItemCode();
// 如果 key 已存在,保留第一个值(与原逻辑一致)
index.putIfAbsent(key, d);
});
});
}
if (index.isEmpty()) {
log.warn("关注列表指标查询为空:门店数={}, 指标数={}, 耗时={}ms",
allMerchantIds.size(), itemCodes.size(), System.currentTimeMillis() - startMs);
return new HashMap<>();
}
log.info("关注列表指标查询完成:门店数={}, 返回行数={}, 索引条数={}, 耗时={}ms",
allMerchantIds.size(), index.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 = MetricsValueUtils.convertBizsToScene(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);
// 根据省份名称匹配技师督导属性,通过查询表 dj_car_life_recruitment_technical_supervisor_mapping (仅轻改场景)
List<String> provinceNameList = items.stream()
.filter(p -> p.getBusinessType() != null && p.getBusinessType() == 2)
.map(p -> p.getProvinceName())
.filter(StringUtils::isNotBlank)
.distinct()
.collect(Collectors.toList());
Map<String, String> provinceTechnicianMap = merchantBasicInfoService.queryTechnicianSupervisorMapByProvinces(provinceNameList);
log.info("查询技师督导:req:{}, map{}", provinceNameList, provinceTechnicianMap);
// 填充数据
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));
}
}
if (StringUtils.isNotBlank(item.getProvinceName()) && item.getBusinessType() != null && item.getBusinessType() == 2) {
item.setTechnicianSupervisor(provinceTechnicianMap.get(item.getProvinceName()));
}
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);
}
@Async("asyncTaskExecutor")
public void triggerFollowPush(MerchantBiFollowReq request) {
try {
// 指定人员才推送关注消息
String pushStaffPhone = environment.getProperty("dj.pe.analysis.follow.push.staff", String.class);
if (StringUtils.isBlank(pushStaffPhone)) {
log.info("未配置推送人员");
return;
}
if (!Arrays.asList(pushStaffPhone.split(",")).contains(request.getStaffPhone())) {
log.info("未匹配到指定推送人员, config:{}, current:{}", pushStaffPhone, request.getStaffPhone());
return;
}
// 获取门店负责人信息 (区域运营和线上运营)
Integer scene = MetricsValueUtils.convertBizsToScene(request.getBusinessType().intValue());
List<StoreSettingDTO> settings = serviceMerchantMapper.findStoreSetting(Collections.singletonList(request.getMerchantId()), scene);
if (CollectionUtils.isEmpty(settings)) {
log.info("未找到关联门店配置");
return;
}
StoreSettingDTO setting = settings.get(0);
List<String> targetUuids = new ArrayList<>();
targetUuids.addAll(merchantBasicInfoService.getOperationStaffUuid(setting));
targetUuids.addAll(merchantBasicInfoService.getOnlineStaffUuid(setting));
if (CollectionUtils.isEmpty(targetUuids)) {
log.info("触发关注推送:未找到推送目标,merchantId={}, biz={}", request.getMerchantId(), request.getBusinessType());
return;
}
log.info("触发关注推送:merchantId={}, biz={}, 触发人={}, 推送目标={}",
request.getMerchantId(), request.getBusinessType(), request.getStaffName(), targetUuids);
wechatPushService.pushFollowMsg(request, targetUuids);
} catch (Exception e) {
log.error("触发关注推送异常", e);
}
}
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
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;
}
/**
* 查询当前员工关注数
*/
public Integer countStaffFollows(SceneBaseReq req) {
if (StringUtils.isBlank(req.getLoginUserUuid())) {
log.warn("查询当前员工关注数:loginUserUuid 为空");
return 0;
}
long startMs = System.currentTimeMillis();
Byte businessType = req.getBizs() == null ? null : req.getBizs().byteValue();
Integer count = followMapper.countFollowsByStaffUuid(req.getLoginUserUuid(), businessType);
log.info("查询当前员工关注数完成:loginUserUuid={}, biz={}, count={}, 耗时={}ms",
req.getLoginUserUuid(), req.getBizs(), count, System.currentTimeMillis() - startMs);
return count == null ? 0 : count;
}
}
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.CommonPushWeChatMsgDTO;
import cn.com.glsx.dj.mindworkplate.enums.CommonErrorEnum;
import cn.com.glsx.dj.mindworkplate.remote.BiAnalysisRemote;
import cn.com.glsx.dj.peanalysis.dto.WechatPushParam;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiFollowReq;
import cn.com.glsx.dj.peanalysis.model.MerchantBiFollow;
import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils;
import cn.com.glsx.dj.strategy.model.StrategyInfo;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.scrm.wechat.enums.WorkWechatAppMessageTypeEnum;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
/**
* 企业微信推送服务
*
* @author lyj
*/
@Slf4j
@Service
public class WechatPushService {
@Autowired
private BiAnalysisRemote biAnalysisRemote;
@Autowired
private Environment environment;
/**
* 关注行为推送
*/
public void pushFollowMsg(MerchantBiFollowReq req, List<String> targetUuids) {
String content = String.format("「%s」关注了你负责的「%s」门店:「%s」,请及时查看。",
req.getStaffName(), MetricsValueUtils.getBusinessTypeName(req.getBusinessType()), req.getMerchantName());
WechatPushParam param = WechatPushParam.builder()
.title("重要提醒")
.content(content)
.storeId(req.getMerchantId())
.storeName(req.getMerchantName())
.businessTypeCode(req.getBusinessType())
.targetUuids(targetUuids)
.build();
sendPush(param);
}
/**
* @ 提醒推送
*/
public void pushMentionMsg(MerchantBiCommentReq req, List<String> targetUuids) {
String content = String.format("「%s」在你负责的「%s」门店:「%s」添加了留言并@你,请及时查看。",
req.getStaffName(), MetricsValueUtils.getBusinessTypeName(req.getBusinessType()), req.getMerchantName());
WechatPushParam param = WechatPushParam.builder()
.title("重要提醒")
.content(content)
.storeId(req.getMerchantId())
.storeName(req.getMerchantName())
.businessTypeCode(req.getBusinessType())
.targetUuids(targetUuids)
.build();
sendPush(param);
}
/**
* 每日动态汇总推送
*/
public void pushDailySummaryMsg(StrategyInfo req, int count, List<String> targetUuids, boolean isFollower) {
byte businessType = req.getBiz().byteValue();
String prefix = isFollower ? "你关注的" : "你负责的";
String content = String.format("%s「%s」门店:「%s」昨日共有「%d」条动态,请及时查看。",
prefix, MetricsValueUtils.getBusinessTypeName(businessType), req.getMerchantName(), count);
WechatPushParam param = WechatPushParam.builder()
.title("日常跟进提醒")
.content(content)
.storeId(req.getMerchantId())
.storeName(req.getMerchantName())
.businessTypeCode(businessType)
.targetUuids(targetUuids)
.build();
sendPush(param);
}
/**
* 发送推送
*/
private void sendPush(WechatPushParam param) {
try {
// 构建 URL 参数
String url = buildUrl(param);
CommonPushWeChatMsgDTO msg = CommonPushWeChatMsgDTO.builder()
.uuids(new HashSet<>(param.getTargetUuids()))
.url(url)
.title(param.getTitle())
.btnTxt("查看详情")
.msgType(WorkWechatAppMessageTypeEnum.TEXTCARD.getValue())
.description(param.getContent())
.build();
log.info("发送企微推送:msg:{}", msg);
RpcResponse<Boolean> response = biAnalysisRemote.pushWeChatMsg(msg);
if (response == null || !response.isSuccess()) {
log.error("企微推送失败:{}", response != null ? response.getMessage() : "null");
}
} catch (Exception e) {
log.error("企微推送异常", e);
}
}
/**
* 构建动态 URL
*/
private String buildUrl(WechatPushParam param) {
// 如果没有传入日期,默认计算当前月的月初到月底
String startDay = param.getStartDay();
String endDay = param.getEndDay();
if (startDay == null || endDay == null) {
startDay = DateUtil.formatDate(DateUtil.beginOfMonth(new Date()));
endDay = DateUtil.formatDate(DateUtil.endOfMonth(new Date()));
}
String baseUrl = Optional.ofNullable(environment.getProperty("dj.pe.analysis.follow.work.wechat.message.text.card.url"))
.orElseThrow(() -> new RpcServiceException(CommonErrorEnum.NOT_FOUND_CONFIG, "未找到url配置项"));
// 构建动态 URL,对中文参数进行 URL 编码
String separator = baseUrl.contains("?") ? "&" : "?";
return baseUrl +
separator + "storeId=" + (param.getStoreId() != null ? param.getStoreId() : "") +
"&storeName=" + urlEncode(param.getStoreName()) +
"&businessType=" + convertBizTypeToParam(param.getBusinessTypeCode()) +
"&queryType=" + (param.getQueryType() != null ? param.getQueryType() : "month") +
"&startDay=" + startDay +
"&endDay=" + endDay +
"&tab=" + (param.getTab() != null ? param.getTab() : "message");
}
/**
* 将业务类型转换为 URL 参数格式
* 1->yanbao, 2->qinggai, 3->quanyi
*/
private String convertBizTypeToParam(Byte businessTypeCode) {
if (businessTypeCode == null) {
return "";
}
switch (businessTypeCode) {
case 1:
return "yanbao";
case 2:
return "qinggai";
case 3:
return "quanyi";
default:
return "";
}
}
/**
* URL 编码处理中文
*/
private String urlEncode(String str) {
if (str == null || str.isEmpty()) {
return "";
}
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
// UTF-8 是 Java 标准编码,不会抛出此异常
return str;
}
}
}
......@@ -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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 指标数值处理工具类
* <p>
* 用途:
* - 百分比换算(小数 -> 百分比,保留两位小数)
* - 金额/产值类指标保留两位小数
* - 达成率计算(产值/目标*100)
*/
@Slf4j
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();
}
/**
*
* BI的业务类型传参Bizs: 1.延保 2.轻改 3.权益 4.二手车
* DJ的业务类型传参scene: 0:2.1会员权益; 1:精品升级
*/
public static Integer convertBizsToScene(Integer bizs) {
switch (bizs){
case 1:
case 3:
return 0;
case 2:
return 1;
}
log.error("不支持的bizs参数: {}", bizs);
return -1;
}
public static String getBusinessTypeName(Byte businessType) {
if (businessType == null) return "未知业务";
switch (businessType) {
case 1:
return "延保";
case 2:
return "轻改";
case 3:
return "权益";
default:
return "未知业务";
}
}
}
<?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>
<resultMap id="WithMerchant" extends="BaseResultMap" type="cn.com.glsx.dj.peanalysis.model.MerchantBiFollowDetail">
<result column="merchant_id" jdbcType="INTEGER" property="merchantId" />
<result column="business_type" jdbcType="VARCHAR" property="businessType" />
</resultMap>
<sql id="Base_Column_List">
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 dj_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 dj_merchant_bi_follow_detail
WHERE staff_uuid != #{staffUuid}
AND deleted_flag = 'N'
ORDER BY created_date DESC
</select>
<select id="findFollowersByFollowIds" resultMap="BaseResultMap">
SELECT
*
FROM dj_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 dj_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 dj_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 dj_merchant_bi_follow_detail
WHERE follow_id = #{followId}
AND deleted_flag = 'N'
</select>
<select id="batchFindByFollowId" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM dj_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="findByMerchantIdsAndBizs" resultMap="WithMerchant">
SELECT
d.*, f.merchant_id, f.business_type
FROM dj_merchant_bi_follow_detail d
left join dj_merchant_bi_follow f on d.follow_id = f.id
<where>
AND d.deleted_flag = 'N'
AND f.deleted_flag = 'N'
and f.merchant_id IN
<foreach collection="merchantIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
<if test="bizs != null and bizs.size() > 0">
and f.business_type IN
<foreach collection="bizs" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</where>
</select>
</mapper>
<?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 dj_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 dj_merchant_bi_follow f
INNER JOIN dj_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'
<if test="merchantName != null and merchantName != ''">
AND f.merchant_name LIKE CONCAT('%', #{merchantName}, '%')
</if>
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 dj_merchant_bi_follow f
INNER JOIN dj_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>
<if test="req != null and req.merchantName != null and req.merchantName != ''">
AND f.merchant_name LIKE CONCAT('%', #{req.merchantName}, '%')
</if>
GROUP BY f.merchant_id, f.business_type
ORDER BY followDate DESC
</select>
<select id="findByMerchantIds" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM dj_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 dj_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 dj_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 dj_merchant_bi_follow
WHERE deleted_flag = 'N'
</select>
<select id="findByMinFollowCount" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM dj_merchant_bi_follow
WHERE follow_count >= #{minCount}
AND deleted_flag = 'N'
</select>
<select id="countFollowsByStaffUuid" resultType="java.lang.Integer">
SELECT COUNT(DISTINCT f.merchant_id, f.business_type)
FROM dj_merchant_bi_follow f
INNER JOIN dj_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'
<if test="businessType != null">
AND f.business_type = #{businessType}
</if>
</select>
</mapper>
......@@ -588,7 +588,7 @@
<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,12 +596,28 @@
<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 = 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,
</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
......@@ -619,6 +635,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 +679,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.strategy.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="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="businessType != null">
AND biz = #{businessType}
</if>
AND deleted_flag = 'N'
<if test="startDate != null">
AND created_date &gt;= #{startDate}
</if>
<if test="endDate != null">
AND created_date &lt;= #{endDate}
</if>
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="businessType != null">
AND t1.biz = #{businessType}
</if>
<if test="startDate != null">
AND created_date &gt;= #{startDate}
</if>
<if test="endDate != null">
AND created_date &lt;= #{endDate}
</if>
</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>
<select id="batchCountStrategyByTime" resultType="java.util.HashMap">
SELECT
merchant_id,
COUNT(*) as 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}
GROUP BY merchant_id
</select>
<select id="findMerchantIdsWithCommentsByTime" resultMap="BaseResultMap">
SELECT
merchant_id, biz, merchant_name
FROM dj_smartcarlife.dj_car_life_strategy_info
WHERE deleted_flag = 'N'
AND created_date BETWEEN #{startDate} AND #{endDate}
GROUP BY merchant_id, biz
</select>
</mapper>
......@@ -2,6 +2,8 @@ package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.req.UserdCarDataStats.StockStoreAnalysisReq;
import cn.com.glsx.dj.peanalysis.dto.req.output.SceneBaseReq;
import cn.com.glsx.dj.peanalysis.dto.res.output.SceneOutputResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.StoreEmployeeRankResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.LostStoreDetailResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.StoreSceneSummaryResponse;
import cn.com.glsx.dj.peanalysis.dto.strategy.StaffAnalysisDTO;
......@@ -232,7 +234,7 @@ public class BusinessSceneAnalysisServiceTest extends BaseRemoteTest {
public void testSummaryStaffDuration() {
SceneBaseReq req = new SceneBaseReq();
req.setBizs(1);
req.setSceneType((byte)0);
req.setSceneType((byte) 0);
req.setMerchantIds(Lists.newArrayList(44217638));
req.setStaffUuids(Lists.newArrayList("9a84aa1681ec477586f9f6ed4a6e5377"));
Integer res = service.summaryStaffDuration(req);
......@@ -243,7 +245,7 @@ public class BusinessSceneAnalysisServiceTest extends BaseRemoteTest {
public void testListStaffAnalysis() {
SceneBaseReq req = new SceneBaseReq();
req.setBizs(1);
req.setSceneType((byte)0);
req.setSceneType((byte) 0);
req.setMerchantIds(Lists.newArrayList(44211677));
req.setStartTime("2025-12-01");
req.setEndTime("2025-12-31");
......@@ -298,4 +300,31 @@ public class BusinessSceneAnalysisServiceTest extends BaseRemoteTest {
List<LostStoreDetailResponse> lostStockStore = statsService.getLostStockStore(request);
System.out.println(JSON.toJSONString(lostStockStore));
}
/**
* 测试查询督导员工产值列表
*/
@Test
public void testQuerySupervisorEmployeeOutput() {
SceneBaseReq req = new SceneBaseReq();
req.setCycleType(4);
req.setMerchantIds(Lists.newArrayList(44210894));
req.setStartTime("2025-12-01");
req.setEndTime("2025-12-31");
List<StoreEmployeeRankResponse.EmployeeAnalysisItem> staffOutputDTOS = service.querySupervisorEmployeeOutput(req);
System.out.println(JSON.toJSONString(staffOutputDTOS));
}
/**
* 测试查询督导员工产值列表
*/
@Test
public void testQuerySupervisorOutput() {
SceneBaseReq req = new SceneBaseReq();
req.setCycleType(4);
req.setMerchantIds(Lists.newArrayList(44210894));
SceneOutputResponse staffOutputDTOS = service.querySupervisorOutput(req);
System.out.println(JSON.toJSONString(staffOutputDTOS));
}
}
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));
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!