Commit 1dca7f0b by 蔡茜

Merge remote-tracking branch 'origin/v5.5.1' into v5.5.1

2 parents c36a8877 36a758f9
Showing 43 changed files with 1750 additions and 22 deletions
......@@ -15,7 +15,7 @@ import lombok.ToString;
public class DataBizQueryParamsDTO {
/**
* 业务类型:1.延保 2.轻改 3.权益 必传
* 业务类型:1.延保 2.轻改 3.权益 4.二手车 必传
*/
private Integer bizs;
......
......@@ -3,6 +3,7 @@ package cn.com.glsx.dj.peanalysis.dto;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class MerchantInfoDTO implements Serializable {
......@@ -14,6 +15,11 @@ public class MerchantInfoDTO implements Serializable {
private Integer merchantId;
/**
* 商户名称
*/
private String merchantName;
/**
* 1-新店 2-老店
*/
private Integer storeType;
......@@ -22,4 +28,9 @@ public class MerchantInfoDTO implements Serializable {
* 1-多品类 2-单品类
*/
private Integer storeMultiType;
/**
* 业务类型 1:权益, 2:延保, 3:轻改, 4:二手车
*/
List<Integer> businessTypeList;
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.dto.job;
import lombok.Data;
import java.util.Date;
/**
* BI数据插入失败记录
*
* 用于记录插入失败的商户ID和统计日期
*/
@Data
public class BiInsertFailure {
private Integer id; // 主键ID
private Integer merchantId;
private Date statDate;
private String errorMessage;
private Date failureTime;
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.dto.job;
import lombok.Data;
/**
* BI记录实体
*
* 用于存储BI数据
*/
@Data
public class BiRecord {
/**
* 商户ID
*/
private Integer merchantId;
/**
* 统计日期
*/
private String statDate;
/**
* 是否有权益
*/
private Integer hasBenefits;
/**
* 是否有延保
*/
private Integer hasExtWarranty;
/**
* 是否有轻改
*/
private Integer hasLightMod;
/**
* 是否有二手车
*/
private Integer hasUsedCar;
/**
* 权益业务-新店老店
*/
private Integer benefitsStoreType;
/**
* 延保业务-新店老店
*/
private Integer extWarrantyStoreType;
/**
* 轻改业务-新店老店
*/
private Integer lightModStoreType;
/**
* 二手车业务-新店老店
*/
private Integer usedCarStoreType;
/**
* 创建人
*/
private String createdBy;
/**
* 修改人
*/
private String updatedBy;
/**
* 删除标识
*/
private char deletedFlag;
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.dto.job;
import lombok.Data;
import java.util.Date;
/**
* 业务首单时间实体类
*
* 用于接收批量查询的首单时间结果
*/
@Data
public class BusinessFirstTimesEntity {
/**
* 商户id
*/
private Integer merchantId;
/**
* 权益首单时间
*/
private Date benefitsFirstTime;
/**
* 延保首单时间
*/
private Date extWarrantyFirstTime;
/**
* 轻改
*/
private Date lightModFirstTime;
/**
* 二手车首单时间
*/
private Date usedCarFirstTime;
}
package cn.com.glsx.dj.peanalysis.dto.job;
import lombok.Data;
import java.util.Date;
/**
* 业务订单状态实体类
*
* 用于接收批量查询的订单状态结果
*/
@Data
public class BusinessOrderStatusEntity {
/**
* 商户ID
*/
private Integer merchantId;
/**
* 统计日期
*/
private Date statDate;
/**
* 是否有权益订单
*/
private boolean hasBenefits;
/**
* 是否有延保订单
*/
private boolean hasExtWarranty;
/**
* 是否有轻改订单
*/
private boolean hasLightMod;
/**
* 是否有二手车订单
*/
private boolean hasUsedCar;
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.dto.job;
import lombok.Data;
import java.util.Date;
/**
* 商户首单日期
*/
@Data
public class MerchantFirstOrderDate {
/**
* 商户ID
*/
private Integer merchantId;
/**
* 首单时间
*/
private Date firstOrderDate;
}
\ No newline at end of file
......@@ -47,4 +47,13 @@ public class FlowContributionRankingReq implements Serializable {
@ApiModelProperty(notes = "1-从大到小 2-从小到大")
private Integer sortOrder;
/**
* 权限角色
*/
private Integer role;
/**
* 用户id
*/
private String userUuid;
}
......@@ -46,5 +46,14 @@ public class RegionDistributionReq implements Serializable {
@NotNull
private String endTime;
/**
* 权限角色
*/
private Integer role;
/**
* 用户id
*/
private String userUuid;
}
......@@ -52,5 +52,15 @@ public class StockStoreAnalysisReq implements Serializable {
@NotNull
private String endTime;
/**
* 权限角色
*/
private Integer role;
/**
* 用户id
*/
private String userUuid;
}
......@@ -73,4 +73,13 @@ public class StoreListCountReq implements Serializable {
private Integer businessCategory;
/**
* 权限角色
*/
private Integer role;
/**
* 用户id
*/
private String userUuid;
}
......@@ -90,4 +90,14 @@ public class StoreListReq implements Serializable {
@ApiModelProperty(notes = "1-从大到小 2-从小到大")
private Integer sortOrder;
/**
* 权限角色
*/
private Integer role;
/**
* 用户id
*/
private String userUuid;
}
......@@ -43,4 +43,6 @@ public interface UsedCarDataStatsRemote {
RpcResponse<Boolean> updateFirstOrderTime();
RpcResponse<List<MerchantInfoDTO>> queryMerchantInfo(MerchantQueryDTO request);
RpcResponse<Boolean> generateBusinessIntelligenceData();
}
package cn.com.glsx.dj.peanalysis.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* @author Alvin
* @version V1.0
* @Title: BeanConfig.java
* @Description:
* @date 2019年3月9日 下午4:22:04
* @Company: didihu.com.cn
* @Copyright Copyright (c) 2018
*/
@Slf4j
@Configuration
public class BeanConfig {
@Bean
@Primary
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(200);
taskExecutor.setMaxPoolSize(400);
taskExecutor.setQueueCapacity(10002);
taskExecutor.setKeepAliveSeconds(300);
return taskExecutor;
}
}
package cn.com.glsx.dj.peanalysis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* 事务配置类
*/
@Configuration
public class TransactionConfig {
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.listener;
import lombok.Data;
import java.io.Serializable;
/**
* Excel 导入失败的单行记录详情
*/
@Data
public class ImportFailItem implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 4S名称(门店名称)
*/
private String storeName;
/**
* 商户号
*/
private String storeCode;
/**
* 业务类型
*/
private String businessType;
/**
* 所属月份(字符串格式,如 "2024-05")
*/
private String monthYear;
/**
* 毛利额(原始字符串)
*/
private String profitAmount;
/**
* 失败原因
*/
private String failReason;
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.listener;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* Excel 导入结果返回值对象(View Object)
*/
@Data
public class ImportResultVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 成功导入的记录数
*/
private int successCount;
/**
* 失败的记录数
*/
private int failCount;
/**
* 失败明细列表(可用于前端展示错误行)
*/
private List<ImportFailItem> failItems;
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.listener;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class MerchantProfitRecordExcelDTO {
@ExcelProperty("*商户号")
private String storeName;
@ExcelProperty("*门店")
private String storeCode;
@ExcelProperty("*业务类型")
private String businessType;
@ExcelProperty("*所属月份") // 格式:2024-05
private String monthYear;
@ExcelProperty("*毛利额")
private String profitAmount;
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.listener;
import com.alibaba.excel.annotation.ExcelProperty;
import java.math.BigDecimal;
import lombok.Data;
@Data
public class MerchantProfitRecordExportDTO {
@ExcelProperty("门店名称")
private String storeName;
@ExcelProperty("业务类型")
private String businessType;
@ExcelProperty("所属月份")
private String monthYear;
@ExcelProperty("毛利额")
private BigDecimal profitAmount;
@ExcelProperty("导入时间")
private String createdTime;
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.listener;
import cn.com.glsx.dj.peanalysis.model.MerchantProfitRecord;
import cn.com.glsx.dj.peanalysis.service.MerchantProfitRecordService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.commons.httpclient.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;
public class MerchantProfitRecordImportListener extends AnalysisEventListener<MerchantProfitRecordExcelDTO> {
@Autowired
private MerchantProfitRecordService merchantProfitRecordService;
private final String operator;
private final List<MerchantProfitRecord> successList = new ArrayList<>();
private final List<ImportFailItem> failList = new ArrayList<>();
// 业务类型白名单(应从配置或常量类获取)
private static final Set<String> VALID_BUSINESS_TYPES =
Collections.unmodifiableSet(new HashSet<String>() {{
add("延保");
add("权益");
add("轻改");
add("二手车");
}});
public MerchantProfitRecordImportListener(MerchantProfitRecordService service, String operator) {
this.merchantProfitRecordService = service;
this.operator = operator;
}
@Override
public void invoke(MerchantProfitRecordExcelDTO data, AnalysisContext context) {
ImportFailItem failItem = buildFailItem(data);
try {
// 1. 提取字段(假设 DTO 已映射好)
String storeName = Optional.ofNullable(data.getStoreName()).orElse("").trim();
String storeCode = Optional.ofNullable(data.getStoreCode()).orElse("").trim();
String businessType = Optional.ofNullable(data.getBusinessType()).orElse("").trim();
String monthStr = Optional.ofNullable(data.getMonthYear()).orElse("").trim();
String profitStr = Optional.ofNullable(data.getProfitAmount()).map(String::valueOf).orElse("").trim();
// 2. 非空校验(可选)
if (!StringUtils.hasText(storeName) || !StringUtils.hasText(storeCode)) {
failItem.setFailReason("4S名称或商户号为空");
failList.add(failItem);
return;
}
// 3. 校验月份格式 & 是否 <= 当前月
LocalDate monthYear;
try {
monthYear = LocalDate.parse(monthStr + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} catch (DateTimeParseException e) {
failItem.setFailReason("无效月份格式");
failList.add(failItem);
return;
}
if (monthYear.isAfter(LocalDate.now().withDayOfMonth(1))) {
failItem.setFailReason("所属月份不能晚于当前月");
failList.add(failItem);
return;
}
// 4. 校验业务类型
if (!VALID_BUSINESS_TYPES.contains(businessType)) {
failItem.setFailReason("业务识别失败");
failList.add(failItem);
return;
}
// 5. 校验毛利额
BigDecimal profitAmount;
try {
profitAmount = new BigDecimal(profitStr).setScale(2, BigDecimal.ROUND_HALF_UP);
if (profitAmount.compareTo(new BigDecimal("-99999999.99")) < 0 ||
profitAmount.compareTo(new BigDecimal("99999999.99")) > 0) {
throw new NumberFormatException("超出范围");
}
} catch (Exception e) {
failItem.setFailReason("毛利额格式错误或超出范围");
failList.add(failItem);
return;
}
// 6. 【关键】调用 Service 校验商户是否存在 + 是否重复(涉及 DB 查询)
String validateResult = merchantProfitRecordService.validateBeforeImport(
storeName, storeCode, businessType, monthYear
);
if (validateResult != null) {
failItem.setFailReason(validateResult);
failList.add(failItem);
return;
}
// 7. 获取 storeId(再次调用 Service 获取)
Long storeId = merchantProfitRecordService.getStoreId(storeName, storeCode);
if (storeId == null) {
failItem.setFailReason("商户不存在");
failList.add(failItem);
return;
}
// 8. 构建成功记录
MerchantProfitRecord record = new MerchantProfitRecord();
record.setStoreId(storeId);
record.setBusinessType(businessType);
record.setMonthYear(monthYear.format( DateTimeFormatter.ofPattern("yyyy-MM")));
record.setProfitAmount(profitAmount);
successList.add(record);
} catch (Exception e) {
failItem.setFailReason("系统异常: " + e.getMessage());
failList.add(failItem);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 所有数据解析完毕,批量保存(委托给 Service)
if (!successList.isEmpty()) {
merchantProfitRecordService.batchSaveProfitRecords(successList, operator);
}
}
// 提供结果用于返回
public ImportResultVO getResult() {
ImportResultVO result = new ImportResultVO();
result.setSuccessCount(successList.size());
result.setFailCount(failList.size());
result.setFailItems(failList);
return result;
}
private ImportFailItem buildFailItem(MerchantProfitRecordExcelDTO data) {
ImportFailItem item = new ImportFailItem();
item.setStoreName(data.getStoreName());
item.setStoreCode(data.getStoreCode());
item.setBusinessType(data.getBusinessType());
item.setMonthYear(data.getMonthYear());
item.setProfitAmount(String.valueOf(data.getProfitAmount()));
return item;
}
}
\ No newline at end of file
package cn.com.glsx.dj.peanalysis.mapper;
import cn.com.glsx.dj.peanalysis.dto.job.*;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/**
* BI数据生成Mapper接口 - 实体类接收版
* <p>
* 优化点:
* 1. 使用实体类接收查询结果,替代Map结构
* 2. 简化接口定义
*/
@Mapper
public interface BusinessIntelligenceMapper {
/**
* 获取目标商户列表(merchant_type=2 且未删除)
*/
List<Integer> getTargetMerchantIds();
/**
* 获取每个商户的首单日期
*
* @param merchantIds 商户ID列表
* @return 商户ID -> 首单日期映射
*/
List<MerchantFirstOrderDate> getMerchantFirstOrderDates(List<Integer> merchantIds);
/**
* 批量获取指定商户列表的各业务首单时间
*
* @param merchantIds 商户ID列表
* @return 业务首单时间实体列表
*/
List<BusinessFirstTimesEntity> getBusinessFirstTimes(@Param("merchantIds") List<Integer> merchantIds);
/**
* 批量获取指定商户列表在指定日期范围内的业务订单状态
*
* @param merchantIds 商户ID列表
* @param statDates 统计日期列表
* @return 业务订单状态实体列表
*/
List<BusinessOrderStatusEntity> getBusinessOrders(@Param("merchantIds") List<Integer> merchantIds, @Param("statDates") List<Date> statDates);
/**
* 单条插入BI记录
*
* @param record BI记录
* @return 受影响行数
*/
int insertBiRecord(BiRecord record);
/**
* 批量插入BI记录
*
* @param records BI记录
* @return 受影响行数
*/
int insertBatchBiRecord(List<BiRecord> records);
/**
* 插入BI数据插入失败记录
*
* @param failure 失败记录
*/
void insertFailureRecord(BiInsertFailure failure);
/**
* 删除失败记录
*
* @param merchantId 商户ID
* @param statDate 统计日期
*/
void deleteFailureRecord(@Param("merchantId") Integer merchantId, @Param("statDate") String statDate);
/**
* 获取所有失败记录
*/
List<BiInsertFailure> getFailureRecords();
}
\ No newline at end of file
......@@ -14,4 +14,7 @@ public interface ServiceMerchantMapper extends OreMapper<ServiceMerchant> {
void updateFirstPayTime(List<Integer> merchantIds);
List<MerchantInfoDTO> queryMerchantInfo(MerchantQueryDTO merchantQueryDTO);
List<MerchantInfoDTO> queryMerchantAllInfo(MerchantQueryDTO merchantQueryDTO);
}
\ No newline at end of file
......@@ -4,6 +4,7 @@ import cn.com.glsx.dj.peanalysis.dto.MerchantInfoDTO;
import cn.com.glsx.dj.peanalysis.dto.MerchantQueryDTO;
import cn.com.glsx.dj.peanalysis.dto.req.UserdCarDataStats.*;
import cn.com.glsx.dj.peanalysis.dto.res.UserdCarDataStats.*;
import cn.com.glsx.dj.peanalysis.service.BusinessIntelligenceService;
import cn.com.glsx.dj.peanalysis.service.UpdateMerchantService;
import cn.com.glsx.dj.peanalysis.service.UsedCarDataStatsService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
......@@ -19,12 +20,14 @@ import java.util.List;
*/
@Slf4j
@DubboService(validation = "true", version = "1.0.0")
public class UsedCarDataStatsRemoteImpl implements UsedCarDataStatsRemote{
public class UsedCarDataStatsRemoteImpl implements UsedCarDataStatsRemote {
@Resource
private UsedCarDataStatsService usedCarDataStatsService;
@Resource
private UpdateMerchantService updateMerchantService;
@Resource
private BusinessIntelligenceService businessIntelligenceService;
/**
* 经营情况-累计至今
......@@ -32,7 +35,7 @@ public class UsedCarDataStatsRemoteImpl implements UsedCarDataStatsRemote{
@Override
public RpcResponse<OperationStatusRes> getOperationStatus(OperationStatusReq request) {
try {
return RpcResponse.success(usedCarDataStatsService.getOperationStatus(request));
return RpcResponse.success(usedCarDataStatsService.getOperationStatus2(request));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
......@@ -132,7 +135,7 @@ public class UsedCarDataStatsRemoteImpl implements UsedCarDataStatsRemote{
}
/**
* 更新第一笔订单时间
* 查询门店
*/
@Override
public RpcResponse<List<MerchantInfoDTO>> queryMerchantInfo(MerchantQueryDTO request) {
......@@ -145,4 +148,19 @@ public class UsedCarDataStatsRemoteImpl implements UsedCarDataStatsRemote{
}
}
/**
* 处理历史数据
*/
@Override
public RpcResponse<Boolean> generateBusinessIntelligenceData() {
try {
businessIntelligenceService.totalDataHandle();
// businessIntelligenceService.dailyDataHandle();
return RpcResponse.success(true);
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
}
}
}
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.DataBusinessDTO;
import cn.com.glsx.dj.peanalysis.utils.HttpRequestUtils;
import cn.com.glsx.dj.peanalysis.utils.response.DataResp;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.hutool.core.lang.TypeReference;
......@@ -10,23 +11,25 @@ import lombok.extern.slf4j.Slf4j;
import org.oreframework.boot.env.OrePropertyConfigurer;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import static cn.com.glsx.dj.peanalysis.utils.HttpRequestUtils.postJson;
@Service
@Slf4j
public class GetDataStatsService {
public DataResp<List<DataBusinessDTO>> getListDataResp(String jsonBody) throws IOException {
public DataResp<List<DataBusinessDTO>> getListDataResp(String jsonBody) {
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");
// post请求
String jsonResponse = postJson(url, jsonBody, new HashMap<>());
String jsonResponse;
try {
jsonResponse = HttpRequestUtils.postJson(url, jsonBody, new HashMap<>());
} catch (Exception e) {
throw new RpcServiceException("查询统计数据异常");
}
dataResp = JSONUtil.toBean(jsonResponse, new TypeReference<DataResp<List<DataBusinessDTO>>>() {
}, true);
if (ObjectUtil.notEqual(dataResp.getCode(), 200)) {
......
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.DataBizQueryParamsDTO;
import cn.com.glsx.dj.peanalysis.dto.DataBusinessDTO;
import cn.com.glsx.dj.peanalysis.dto.MerchantInfoDTO;
import cn.com.glsx.dj.peanalysis.dto.MerchantQueryDTO;
import cn.com.glsx.dj.peanalysis.dto.req.UserdCarDataStats.*;
import cn.com.glsx.dj.peanalysis.dto.res.UserdCarDataStats.*;
import cn.com.glsx.dj.peanalysis.mapper.ServiceMerchantMapper;
import cn.com.glsx.dj.peanalysis.utils.response.DataResp;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
* 二手车数据统计
......@@ -29,11 +39,15 @@ public class UsedCarDataStatsService {
@Resource
private ServiceMerchantMapper serviceMerchantMapper;
@Resource
private GetDataStatsService getDataStatsService;
@Resource
private TaskExecutor taskExecutor;
/**
* 经营情况-累计至今
*/
public OperationStatusRes getOperationStatus(OperationStatusReq request) {
public OperationStatusRes getOperationStatus2(OperationStatusReq request) {
// todz
// 登录角色 1-其他角色 2-服务商老板 3-区域运营 4-广联销售(业务负责人) 5-飞行督导 6-线上运营 7-区域运营大区经理 8-销售大区经理
// 如果不为其他角色则获取可查看的商户id
......@@ -47,20 +61,97 @@ public class UsedCarDataStatsService {
if (CollUtil.isEmpty(filterMerchantIds)) {
return new OperationStatusRes();
}
OperationStatusRes result = new OperationStatusRes();
// 并行查询指标接口
DataBizQueryParamsDTO queryDataBiz = new DataBizQueryParamsDTO();
queryDataBiz.setBizs(4);
queryDataBiz.setBrandIds("-1,-3");
queryDataBiz.setDateType(4);
queryDataBiz.setExts(null);
queryDataBiz.setMerchantIds(null);
queryDataBiz.setMerchantIds(StrUtil.join(",", filterMerchantIds));
queryDataBiz.setStartDate("2000-01-01");
queryDataBiz.setEndDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
List<String> itemCodes = Arrays.asList("在库车辆", "在库成本", "卖车总产值", "总毛利");
queryDataBiz.setItemCodes("");
return null;
List<String> itemCodes = Arrays.asList("在库车辆", "在库成本", "在库天数>7天", "在库天数>30天",
"卖车总产值", "总毛利", "平均周转天数", "平均收车成本",
"整体收车成本分布 X>5万 车辆数", "整体收车成本分布 2万<X≤5万 车辆数", "整体收车成本分布 X≤2万 车辆数");
for (String itemCode : itemCodes) {
queryDataBiz.setItemCodes(itemCode);
String jsonBody = JSONUtil.toJsonStr(queryDataBiz);
DataResp<List<DataBusinessDTO>> dataResp = getDataStatsService.getListDataResp(jsonBody);
List<DataBusinessDTO> content = dataResp.getContent();
if (CollUtil.isNotEmpty(content)) {
DataBusinessDTO dataBusinessDTO = CollUtil.getFirst(content);
switch (itemCode) {
case "在库车辆":
result.setInStockCar(dataBusinessDTO.getItemValue().intValue());
break;
case "在库成本":
result.setInStockCost(dataBusinessDTO.getItemValue());
break;
case "在库天数>7天":
result.setInStockDaysMore7(dataBusinessDTO.getItemValue().intValue());
break;
case "在库天数>30天":
result.setInStockDaysMore30(dataBusinessDTO.getItemValue().intValue());
break;
case "卖车总产值":
result.setSellCarOutputValue(dataBusinessDTO.getItemValue());
break;
case "总毛利":
result.setTotalProfit(dataBusinessDTO.getItemValue());
break;
case "平均周转天数":
result.setAverageTurnoverDays(dataBusinessDTO.getItemValue());
break;
case "平均收车成本":
result.setAverageReceivingCost(dataBusinessDTO.getItemValue());
break;
case "整体收车成本分布 X>5万 车辆数":
result.setReceivingCostDistribution5WMore(dataBusinessDTO.getItemValue().intValue());
break;
case "整体收车成本分布 2万<X≤5万 车辆数":
result.setReceivingCostDistribution2WMore(dataBusinessDTO.getItemValue().intValue());
break;
case "整体收车成本分布 X≤2万 车辆数":
result.setReceivingCostDistributionLess2W(dataBusinessDTO.getItemValue().intValue());
break;
default:
break;
}
}
}
// 计算占比
List<Integer> totalReceivingCost = Arrays.asList(
result.getReceivingCostDistribution5WMore(),
result.getReceivingCostDistribution2WMore(),
result.getReceivingCostDistributionLess2W());
// totalReceivingCost 排除空值 相加
int total = totalReceivingCost.stream().filter(Objects::nonNull).mapToInt(Integer::intValue).sum();
if (total > 0) {
// 整体收车成本分布 X>5万 车辆数 不为空 X>5万/totalReceivingCost 计算占比 保留两位小数 xx.xx%
if (ObjectUtil.isNotEmpty(result.getReceivingCostDistribution5WMore())) {
result.setReceivingCostDistribution5WMorePercent(
NumberUtil.div(BigDecimal.valueOf(result.getReceivingCostDistribution5WMore()), total,4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP));
}
// 整体收车成本分布 2万<X≤5万 车辆数 不为空 2万<X≤5万/totalReceivingCost 计算占比 保留两位小数 xx.xx%
if (ObjectUtil.isNotEmpty(result.getReceivingCostDistribution2WMore())) {
result.setReceivingCostDistribution2WMorePercent(
NumberUtil.div(BigDecimal.valueOf(result.getReceivingCostDistribution2WMore()), total,4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP));
}
// 整体收车成本分布 X≤2万 车辆数 不为空 X≤2万/totalReceivingCost 计算占比 保留两位小数 xx.xx%
if (ObjectUtil.isNotEmpty(result.getReceivingCostDistributionLess2W())) {
result.setReceivingCostDistributionLess2WPercent(
NumberUtil.div(BigDecimal.valueOf(result.getReceivingCostDistributionLess2W()), total,4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP));
}
}
return result;
}
/**
* 按周期统计数据
*/
......@@ -107,16 +198,15 @@ public class UsedCarDataStatsService {
* 查询商户信息
*/
public List<MerchantInfoDTO> queryMerchantInfo(MerchantQueryDTO request) {
request.setBusinessType(1);
request.setStoreType(2);
request.setStoreMultiType(null);
request.setMerchantIdList(Arrays.asList(44211675,44217638));
request.setBeginTime("2025-12-01");
request.setBusinessType(4);
request.setStoreType(null);
request.setStoreMultiType(1);
// request.setMerchantIdList(Arrays.asList(44211675,44217638));
request.setBeginTime("2000-12-01");
request.setEndTime("2025-12-01");
return serviceMerchantMapper.queryMerchantInfo(request);
List<MerchantInfoDTO> results = serviceMerchantMapper.queryMerchantInfo(request);
return results;
}
}
package cn.com.glsx.dj.peanalysis.util.excel;
import com.alibaba.excel.write.handler.AbstractWorkbookWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import java.util.LinkedHashMap;
import java.util.List;
import org.apache.poi.ss.usermodel.Sheet;
import org.oreframework.commons.office.easyexcel.ExcelMergeEntity;
public class AccountTotalMergeRowStrategy extends AbstractWorkbookWriteHandler {
private List<List<LinkedHashMap<String, ExcelMergeEntity>>> dataList;
//总计行所在行下标
private Integer startRow = 0;
private Integer endRow = 0;
//总计与表头中间的行数
private Integer basicMovePace = 0;
private Boolean removeRow = false;
public AccountTotalMergeRowStrategy(Integer startRow, Integer endRow, Integer basicMovePace, List<List<LinkedHashMap<String,ExcelMergeEntity>>> dataList, Boolean removeRow) {
this.startRow = startRow;
this.endRow = endRow;
this.basicMovePace = basicMovePace;
this.dataList = dataList;
this.removeRow = removeRow;
}
@Override
public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {
super.afterWorkbookDispose(writeWorkbookHolder);
for(int i = 0;i<dataList.size();i++) {
int moveRows = dataList.get(i).size();
//不多移动一行最后一行数据如果是合并行的话,移动后就会变成未合并的
Sheet sheet = writeWorkbookHolder.getWorkbook().getSheetAt(i);
sheet.shiftRows(startRow, endRow, basicMovePace + 1 + moveRows,true,false);
if (removeRow) {
for (int j = startRow; j < endRow; j++) {
sheet.removeRow(sheet.getRow(startRow));
}
sheet.shiftRows(endRow + 1, sheet.getLastRowNum(), -1*(endRow-startRow+1),true,false);
}
}
}
}
package cn.com.glsx.dj.peanalysis.util.excel;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
public class AutoWarpMatchColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy{
private static final int MAX_COLUMN_WIDTH = 255;
private Map<Integer, Map<Integer, Integer>> cache = new HashMap<Integer, Map<Integer, Integer>>(8);
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head,
Integer relativeRowIndex, Boolean isHead) {
boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
if (!needSetWidth) {
return;
}
Map<Integer, Integer> maxColumnWidthMap = cache.get(writeSheetHolder.getSheetNo());
if (maxColumnWidthMap == null) {
maxColumnWidthMap = new HashMap<Integer, Integer>(16);
cache.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
}
Integer columnWidth = dataLength(cellDataList, cell, isHead);
if (columnWidth < 0) {
return;
}
if (columnWidth > MAX_COLUMN_WIDTH) {
columnWidth = MAX_COLUMN_WIDTH;
}
Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
}
}
private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
if (isHead) {
return cell.getStringCellValue().getBytes().length;
}
CellData cellData = cellDataList.get(0);
CellDataTypeEnum type = cellData.getType();
if (type == null) {
return -1;
}
switch (type) {
case STRING:
int index = cellData.getStringValue().indexOf("\n");
return index != -1 ?
cellData.getStringValue().substring(0, index).getBytes().length : cellData.getStringValue().getBytes().length;
case BOOLEAN:
return cellData.getBooleanValue().toString().getBytes().length;
case NUMBER:
return cellData.getNumberValue().toString().getBytes().length;
default:
return -1;
}
}
}
package cn.com.glsx.dj.peanalysis.util.excel;
import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import com.google.common.base.Objects;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
public class AutoWarpMatchRowHeightStyleStrategy extends AbstractRowHeightStyleStrategy{
private Short headRowHeight = 20;
private Short contentRowHeight = 20;
public AutoWarpMatchRowHeightStyleStrategy(Short headRowHeight, Short contentRowHeight) {
this.headRowHeight = headRowHeight;
this.contentRowHeight = contentRowHeight;
}
@Override
protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
if (headRowHeight != null) {
row.setHeightInPoints(headRowHeight);
}
}
@Override
protected void setContentColumnHeight(Row row, int relativeRowIndex) {
Iterator<Cell> cellIterator = row.cellIterator();
int maxHeight = 1;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
CellType type = cell.getCellType();
if(Objects.equal(type, CellType.STRING)) {
int length = cell.getStringCellValue().split("\n").length;
maxHeight = Math.max(length, maxHeight);
}
}
if (contentRowHeight != null) {
row.setHeightInPoints(contentRowHeight * maxHeight);
}
}
}
package cn.com.glsx.dj.peanalysis.util.excel;/*
package cn.com.glsx.dj.mindworkplate.util.excel;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class CustomCellWriteHandler extends AbstractCellWriteHandler {
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
// 设置行高测试
int rowIndex = row.getRowNum();
System.out.println("当前行: " + rowIndex);
short height = 600;
row.setHeight(height);
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
Cell cell = context.getCell();
WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
Sheet sheet = writeSheetHolder.getSheet();
String sheetName = sheet.getSheetName();
System.out.println("当前sheet: " + sheetName);
int rowIndex = cell.getRowIndex();
int cellIndex = cell.getColumnIndex();
// 自定义宽度处理
// 自定义样式处理
// 当前事件会在 数据设置到poi的cell里面才会回调
// 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true
if (BooleanUtils.isNotTrue(context.getHead())) {
if (cell.getColumnIndex() >= 8 && cell.getStringCellValue().contains("好")) {
// 拿到poi的workbook
Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
// 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式
// 不同单元格尽量传同一个 cellStyle
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
// 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确
// 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到
// cell里面去 会导致自己设置的不一样(很关键)
context.getFirstCellData().setWriteCellStyle(null);
} else if (cell.getColumnIndex() >= 8 && cell.getStringCellValue().contains("差")) {
// 拿到poi的workbook
Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
// 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式
// 不同单元格尽量传同一个 cellStyle
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
// 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确
// 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到
// cell里面去 会导致自己设置的不一样(很关键)
context.getFirstCellData().setWriteCellStyle(null);
} else if (cell.getColumnIndex() >= 8 && cell.getStringCellValue().contains("一般")) {
// 拿到poi的workbook
Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
// 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式
// 不同单元格尽量传同一个 cellStyle
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
// 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确
// 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到
// cell里面去 会导致自己设置的不一样
context.getFirstCellData().setWriteCellStyle(null);
}
}
}
}*/
package cn.com.glsx.dj.peanalysis.util.excel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.oreframework.commons.office.easyexcel.EasyExcelImportResult;
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
@ToString(callSuper = true)
public class ExcelImportReadSetting<T> implements Serializable{
/**
*
*/
private static final long serialVersionUID = -829820199174240076L;
@Builder.Default
@ApiModelProperty(notes = "是否启用快速失败校验,为null时不校验导入数据格式,true时快速失败校验(此条数据有一个校验失败不再校验后续字段,false时校验此条数据全部字段)")
private Boolean fastFail = true;
@Builder.Default
@ApiModelProperty(notes = "是否启用合并失败,true时同一个合并组里有一条数据存在失败即全部失败,fastFail不为空且extraReadMerge为true时有效")
private Boolean mergeFail = true;
@Builder.Default
@ApiModelProperty(notes = "excel头所在行(多行表头则为最后行)")
private Integer headRowNumber = 1;
@Builder.Default
@ApiModelProperty(notes = "自动去除单元格内容前后空格")
private Boolean autoTrim = true;
@ApiModelProperty(notes = "excel数据接收对象")
private Class<T> clazz;
private Integer sheetNo;
@Builder.Default
@ApiModelProperty(notes = "是否校验表头,默认不校验")
private Boolean validHeadTitle = false;
//如果启用 接收对象属性需要增加注解索引值 @ExcelProperty(index = 0)
@ApiModelProperty(notes = "是否读取合并单元格信息")
private Boolean extraReadMerge;
private EasyExcelImportResult<T> result;
@ApiModelProperty(notes = "表头校验的结果,true 通过,false不通过")
private Boolean validHeadTitleResult;
}
package cn.com.glsx.dj.peanalysis.util.excel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelNumericCell {
int index();
}
package cn.com.glsx.dj.peanalysis.util.excel;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
public class HiddenColumnWriteHandler implements SheetWriteHandler{
private List<Integer> hiddenColumnIndexes;
public HiddenColumnWriteHandler(List<Integer> hiddenColumnIndexes) {
this.hiddenColumnIndexes = hiddenColumnIndexes;
}
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
if(CollectionUtils.isNotEmpty(hiddenColumnIndexes)) {
for(Integer index:hiddenColumnIndexes) {
writeSheetHolder.getSheet().setColumnHidden(index, true);
}
}
}
}
package cn.com.glsx.dj.peanalysis.util.excel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import org.oreframework.commons.office.easyexcel.BaseExcelImportVo;
@Data
@ToString(callSuper = true)
public class MergeExcelImportVo extends BaseExcelImportVo {/**
*
*/
private static final long serialVersionUID = -6120292157297696326L;
@ApiModelProperty(notes = "合并组ID(非合并行 也有组ID)")
private String mergeGroupId;
@ApiModelProperty(notes = "是否合并组的第一条数据(非合并行 即为首条也是最后条)")
private Boolean firstMergeGroupData;
@ApiModelProperty(notes = "是否合并组的最后条数据(非合并行 即为首条也是最后条)")
private Boolean lastMergeGroupData;
@ApiModelProperty(notes = "excel里行号,从0开始")
private Integer excelRowIndex;
}
package cn.com.glsx.dj.peanalysis.util.excel;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
public class NumberCellTypeWriteHandler implements CellWriteHandler {
private List<Integer> needFixColumnIndex;
public NumberCellTypeWriteHandler(Object dataObject) {
needFixColumnIndex = getFieldIndexes(dataObject);
}
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) {
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) {
}
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {
String stringCellValue = cell.getStringCellValue();
if (Objects.equals(cell.getCellType(), CellType.STRING)
&& needFixColumnIndex.contains(cell.getColumnIndex())
&& isBigDecimal(stringCellValue)) {
BigDecimal cellValue = new BigDecimal(stringCellValue);
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(cellValue.doubleValue());
}
}
public static boolean isBigDecimal(String value) {
try {
new BigDecimal(value);
return true; // 如果没有异常抛出,则是有效的BigDecimal
} catch (NumberFormatException e) {
return false; // 如果抛出NumberFormatException,则不是有效的BigDecimal
}
}
public static List<Integer> getFieldIndexes(Object object) {
List<Integer> indexes = new ArrayList<>();
if (object != null) {
Class<?> clazz = null;
// 检查object是否是集合
if (object instanceof Collection) {
Collection<?> collection = (Collection<?>) object;
// 确保集合不为空
if (!collection.isEmpty()) {
// 获取集合中第一个元素的类类型
clazz = collection.iterator().next().getClass();
} else {
// 如果集合为空,则没有字段索引可以返回
return indexes;
}
} else {
// 如果object不是集合,则直接使用其类类型
clazz = object.getClass();
}
// 遍历类的所有字段,包括嵌套字段的处理
processFields(clazz, indexes);
}
return indexes;
}
private static void processFields(Class<?> clazz, List<Integer> indexes) {
// 遍历类的所有字段
for (Field field : clazz.getDeclaredFields()) {
// 检查字段是否有ExcelNumericCell注解
if (field.isAnnotationPresent(ExcelNumericCell.class)) {
ExcelNumericCell excelNumericCell = field.getAnnotation(
ExcelNumericCell.class);
// 将注解的index属性值添加到列表中
indexes.add(excelNumericCell.index());
}
// 如果字段是集合类型,继续遍历集合元素类型
if (Collection.class.isAssignableFrom(field.getType())) {
Type fieldType = field.getGenericType();
if (fieldType instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType) fieldType;
Type[] typeArgs = paramType.getActualTypeArguments();
if (typeArgs.length > 0 && typeArgs[0] instanceof Class) {
Class<?> elementClass = (Class<?>) typeArgs[0];
// 递归处理集合元素的类
processFields(elementClass, indexes);
}
}
}
}
}
}
package cn.com.glsx.dj.peanalysis.util.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.hibernate.validator.HibernateValidator;
import org.oreframework.commons.office.easyexcel.BaseExcelImportVo;
import org.oreframework.commons.office.easyexcel.EasyExcelImportResult;
public class ReadAnalysisEventListener<T extends BaseExcelImportVo> extends AnalysisEventListener<T> {
private ExcelImportReadSetting<T> setting;
public ReadAnalysisEventListener(ExcelImportReadSetting<T> setting) {
this.setting = setting;
EasyExcelImportResult<T> importResult = new EasyExcelImportResult<>();
importResult.setList(new LinkedList<>());
importResult.setFailList(new LinkedList<>());
setting.setResult(importResult);
}
@Override
public void invoke(T data, AnalysisContext context) {
data.setErrorMsg(null);//防止从excel里读取
if (setting.getFastFail() != null) {
Validator validator = Validation.byProvider(HibernateValidator.class).configure()
.failFast(setting.getFastFail()).buildValidatorFactory().getValidator();
Set<ConstraintViolation<Object>> set =validator .validate(data);
if (set.isEmpty()) {
setting.getResult().getList().add(data);
} else {
Iterator<ConstraintViolation<Object>> iter = set.iterator();
while (iter.hasNext()) {
data.appendErrorMsg(iter.next().getMessage());
}
setting.getResult().getFailList().add(data);
}
}else {
setting.getResult().getList().add(data);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
if (!setting.getResult().getFailList().isEmpty()) {
setting.getResult().setVerfiyFail(true);
}
}
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
if(Objects.equals(setting.getValidHeadTitle(), true)) {
setting.setValidHeadTitleResult(true);
Field[] fields = setting.getClazz().getDeclaredFields();
if(fields == null || fields.length == 0) {
return;
}
for(Field f:fields) {
ExcelProperty ep = f.getAnnotation(ExcelProperty.class);
if(ep == null || ep.index() == -1 || ep.value() == null || ep.value().length == 0) {
continue;
}
if(!Objects.equals(headMap.get(ep.index()),ep.value()[0])){
setting.setValidHeadTitleResult(false);
return;
}
}
}
}
}
package cn.com.glsx.dj.peanalysis.util.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.hibernate.validator.HibernateValidator;
import org.oreframework.commons.office.easyexcel.EasyExcelImportResult;
@Slf4j
public class ReadMergeAnalysisEventListener<T extends MergeExcelImportVo> extends AnalysisEventListener<T>{
private ExcelImportReadSetting<T> setting;
private List<T> originDataList = new ArrayList<>();
private List<CellExtra> cellExtraList = new ArrayList<>();
public ReadMergeAnalysisEventListener(ExcelImportReadSetting<T> setting) {
this.setting = setting;
setting.setResult(new EasyExcelImportResult<>());
}
@Override
public void invoke(T data, AnalysisContext context) {
data.setErrorMsg(null);//防止从excel里读取
data.setMergeGroupId(UUID.randomUUID().toString());
data.setFirstMergeGroupData(true);
data.setLastMergeGroupData(true);
data.setExcelRowIndex(context.readRowHolder().getRowIndex());
originDataList.add(data);
}
public void doAfterAllAnalysed(AnalysisContext context) {
if (CollectionUtils.isEmpty(originDataList)) {
return;
}
EasyExcelImportResult<T> result = setting.getResult();
List<T> list = new LinkedList<>();
mergeExcelData();
if (setting.getFastFail() != null) {
Map<String,Boolean> mergeFailList = new HashMap<>();
Validator validator = Validation.byProvider(HibernateValidator.class).configure()
.failFast(setting.getFastFail()).buildValidatorFactory().getValidator();
for (T data : originDataList) {
Set<ConstraintViolation<Object>> set = validator.validate(data);
if (!set.isEmpty()) {
Iterator<ConstraintViolation<Object>> iter = set.iterator();
while (iter.hasNext()) {
data.appendErrorMsg(iter.next().getMessage());
}
mergeFailList.put(data.getMergeGroupId(), true);
}
}
List<T> failList = new LinkedList<>();
for (T data : originDataList) {
if(Objects.equals(setting.getMergeFail(), true) && mergeFailList.containsKey(data.getMergeGroupId())) {
failList.add(data);
}else {
list.add(data);
}
}
result.setFailList(failList);
result.setVerfiyFail(!failList.isEmpty());
} else {
list.addAll(originDataList);
}
result.setList(list);
}
@Override
public void extra(CellExtra extra, AnalysisContext context) {
int headRowNumber = setting.getHeadRowNumber() != null ? setting.getHeadRowNumber() : 1;
switch (extra.getType()) {
case MERGE:
if(extra.getRowIndex() >= headRowNumber) {
cellExtraList.add(extra);
}
break;
default:
break;
}
}
protected Map<Integer,Field> getIndexFieldMap(){
List<Field> fieldList = FieldUtils.getAllFieldsList(setting.getClazz());
Map<Integer,Field> indexFieldMap = new HashMap<>();
for(Field field:fieldList) {
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
if(excelProperty != null && !Objects.equals(excelProperty.index(),-1)) {
indexFieldMap.put(excelProperty.index(), field);
}
}
return indexFieldMap;
}
protected void mergeExcelData() {
if(CollectionUtils.isEmpty(cellExtraList)) {
return;
}
int headRowNumber = setting.getHeadRowNumber() != null ? setting.getHeadRowNumber() : 1;
Map<Integer,Field> indexFieldMap = getIndexFieldMap();
for(CellExtra extra:cellExtraList) {
int firstRowIndex = extra.getFirstRowIndex() - headRowNumber;
int lastRowIndex = extra.getLastRowIndex() - headRowNumber;
int firstColumnIndex = extra.getFirstColumnIndex();
int lastColumnIndex = extra.getLastColumnIndex();
Object value = getMergeExcelData(indexFieldMap,firstRowIndex,firstColumnIndex);
for(int rowIndex = firstRowIndex;rowIndex <= lastRowIndex;rowIndex++) {
originDataList.get(rowIndex).setMergeGroupId(originDataList.get(firstRowIndex).getMergeGroupId());
if(rowIndex != firstRowIndex) {
originDataList.get(rowIndex).setFirstMergeGroupData(false);
}
if(rowIndex != lastRowIndex) {
originDataList.get(rowIndex).setLastMergeGroupData(false);
}
for(int columnIndex = firstColumnIndex;columnIndex<= lastColumnIndex;columnIndex++) {
fillMergeExcelData(indexFieldMap, value, rowIndex, columnIndex);
}
}
}
}
protected Object getMergeExcelData(Map<Integer,Field> indexFieldMap,int firstRowIndex,int firstColumnIndex) {
Field field = indexFieldMap.get(firstColumnIndex);
if(field != null) {
try {
return FieldUtils.readField(field, originDataList.get(firstRowIndex),true);
}catch(Exception e) {
log.error(e.getMessage(),e);
}
}
return null;
}
protected void fillMergeExcelData(Map<Integer,Field> indexFieldMap,Object fillData,int rowIndex,int columnIndex) {
Field field = indexFieldMap.get(columnIndex);
if(field != null) {
try {
FieldUtils.writeField(field, originDataList.get(rowIndex),fillData,true);
}catch(Exception e) {
log.error(e.getMessage(),e);
}
}
}
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
if(Objects.equals(setting.getValidHeadTitle(), true)) {
setting.setValidHeadTitleResult(true);
Field[] fields = setting.getClazz().getDeclaredFields();
if(fields == null || fields.length == 0) {
return;
}
for(Field f:fields) {
ExcelProperty ep = f.getAnnotation(ExcelProperty.class);
if(ep == null || ep.index() == -1 || ep.value() == null || ep.value().length == 0) {
continue;
}
if(!Objects.equals(headMap.get(ep.index()),ep.value()[0])){
setting.setValidHeadTitleResult(false);
return;
}
}
}
}
}
package cn.com.glsx.dj.peanalysis.util.excel;
import cn.com.glsx.framework.core.enums.ErrorEnum;
import java.util.HashMap;
import java.util.Map;
public enum RopErrorEnum implements ErrorEnum{
//30010101 30固定业务异常,01模块,01模块下第几个接口,01该接口下第几个错误信息
/*******************智享车生活订单模块*************************/
/** 通用**/
SCL_SEARCH_FAILURE("30010102", "查询失败"),
SCL_SMS_CODE_ERROR("30010103", "短信验证码错误"),
SCL_SAVE_ERROR("30010104", "保存失败"),
/** 创建子订单-子订单创建失败**/
SCL_CREATESUBORDER_FAILURE("30010101", "子订单创建失败"),
SCL_CREATEORDER_FAILURE("30010201", "订单创建失败"),
SCL_WAITINPUTORDER_COUNT_FAILURE("30010301", "获取待补录订单统计失败"),
SCL_WAITINPUTORDER_PAGE_FAILURE("30010302", "分页查询待补录订单失败"),
SCL_WAITINPUTORDER_UPDATE_YQ_MERCHANT_FAILURE("30010303", "批量修改待补录订单流水所属园区店失败"),
SCL_WAITINPUTORDER_MARK_AS_NO_USE_FAILURE("30010304", "批量标记待补录订单为无需补录失败"),
SCL_WAITINPUTORDER_BATCH_UPDATE_CONFIRM_INPUT_FAILURE("30010305", "批量标记待确认补录订单为确认补录失败"),
SCL_WAITINPUTORDER_CANCEL_RELATION_ACTIVITY_ORDER("30010306", "取消关联失败"),
SCL_WAITINPUTORDER_RELATION_ACTIVITY_ORDER("30010307", "关联活动订单失败"),
/*******************智享车生活服务serviceMerchant店模块*************************/
/** 获取园区店信息-4S店未绑定园区店**/
SCL_SERVICEMERCHANT_GET_NOT_BIND_YQ("30020101", "4S店未绑定园区店"),
/** 获取园区店信息-商户号不存在**/
SCL_SERVICEMERCHANT_GET_MERCHANT_NOT_EXISTS("30020102", "商户号不存在"),
/** 获取4S店信息-未有4S店未绑定园区店**/
SCL_SERVICEMERCHANT_GET_YQMERCHANT_NOT_EXISTS("30020202", "4S店未绑定园区店"),
/** 获取平台方列表-查询失败**/
SCL_SERVICEMERCHANT_GET_PLATFORMMERCHANT_ERROR("30020203", "获取平台方列表失败"),
/** 保存园区店服务商关联-失败**/
SCL_SERVICEMERCHANT_PARTNERMERCHANT_SAVE_ERROR("30020301", "保存失败"),
/** 保存园区店服务商关联-失败**/
SCL_SERVICEMERCHANT_PARTNERMERCHANT_LISTYQANDSHOP_ERROR("30020302", "查询服务商关联商户信息失败"),
/** 查询4s店关联服务商失败-失败**/
SCL_SERVICEMERCHANT_SHOPMERCHANT_LISTPARTNER_ERROR("30020402", "查询4s店服务商列表失败"),
/*******************智享车生活支付订单模块*************************/
/** 创建支付订单-支付订单创建失败**/
SCL_CREATEPAYORDER_FAILURE("30030101", "支付订单创建失败"),
/** 订单支付成功回调-支付订单创建失败**/
SCL_PAYORDERSUCCESS_CALL_FAILURE("30030201", "订单支付成功回调失败"),
/** 更新请求实付时间-更新请求实付时间失败**/
SCL_PAYORDER_UPDATEREQUESTPAYDATE_FAILURE("30030301", "更新请求实付时间失败"),
/*******************智享车生活订单评论模块*************************/
/** 添加订单评论-添加订单评论失败**/
SCL_ORDERCOMMENT_ADD_FAILURE("30040101", "添加订单评论失败"),
/*******************智享车生活邀约模块*************************/
/** 预约-预约失败**/
SCL_INVITE_ADD_FAILURE("30050101","预约失败"),
/** 获取虚拟号-获取虚拟号失败**/
SCL_INVITE_GET_PRIVATE_NUMBER_FAILURE("30050201","获取虚拟号失败"),
/*******************智享车生活分账记录模块*************************/
/** 创建支付订单-支付订单创建失败**/
SCL_SHOP_DIVISION_COUNT_FAILURE("30060101", "获取4s店分账列表总数统计失败"),
SCL_SHOP_DIVISION_PAGE_FAILURE("30060101", "分页查询商户测分账记录失败"),
SCL_SHOP_DIVISION_EXPORT_FAILURE("30060101", "导出商户测分账记录失败"),
/*******************智享车生活企业联系人模块*************************/
ADD_MERCHANT_CONCAT_ERROR("30070101", "新建企微联系人失败"),
MODIFY_MERCHANT_CONCAT_ERROR("30070102", "编辑企微联系人失败"),
REMOVE_MERCHANT_CONCAT_ERROR("30070103", "删除企微联系人失败"),
PAGE_MERCHANT_CONCAT_ERROR("30070104", "查询企微联系人失败"),
LIST_OUTPUTVALUE_ACHIEVEMENT_ERROR("30070105", "获取企微联系人相关4s店产值目标达成概况列表失败"),
/*******************智享车生活自定义商户信息模块*************************/
SAVE_MERCHANT_CUSTOM_INFO_ERROR("30080101", "保存客户信息失败"),
PAGE_MERCHANT_CUSTOM_INFO_ERROR("30080102", "分页查询客户信息失败"),
/*******************智享车生活自定义商户财务分账规则模块*************************/
SAVE_MERCHANT_SETTLE_DISTRIBUTE_RULE_ERROR("30090101", "保存商户财务分账规则失败"),
MERCHANT_SETTLE_DISTRIBUTE_GET_LAST_RULE_ERROR("30090101", "获取商户最新财务分账规则失败"),
MERCHANT_DIVISION_RULE_TEST_GET_ERROR("30090201", "获取商户财务设置进度失败"),
MERCHANT_DIVISION_RULE_GET_BY_MERCHANTID_ERROR("30090301", "获取商户某场景最新的分账规则失败"),
MERCHANT_DIVISION_RULE_GET_ENABLED_ERROR("30090301", "获取商户某场景生效的分账规则失败"),
MERCHANT_DIVISION_RULE_TEST_RULE_ERROR("30090401", "分账测算失败"),
SAVE_MERCHANT_RECONCILIATION_RULE_ERROR("30090201", "保存商户对账规则失败"),
/*******************智享车生活库存管理模块*************************/
PAGE_MERCHANT_GOODS_STOCK_REDUCE_RECORD_ERROR("30100101", "出库记录查询失败"),
PAGE_MERCHANT_GOODS_STOCK_MONTH_REPORT_ERROR("30100201", "库存记录查询失败"),
LIST_MERCHANT_GOODS_STOCK_MONTH_REPORT_BY_GOODS_ERROR("30100201", "按年份查询商品库存记录失败"),
PAGE_MERCHANT_SHOP_GOODS_STOCK_ERROR("30100301", "分页查询门店商品库存失败"),
PAGE_STOCK_VD_CARD_ERROR("30100401", "分页查询库存管理-权益卡失败"),
COUNT_STOCK_VD_CARD_ERROR("30100402", "统计库存管理-权益卡失败"),
/*******************智享车生活生意助手-个人中心模块*************************/
SAVE_MERCHANT_CUSTOMER_ERROR("30110101", "保存客户信息失败"),
UPDATE_MERCHANT_CUSTOMER_ERROR("30110102", "更新客户信息失败"),
PAGE_MERCHANT_CUSTOMER_ERROR("30110103", "分页查询客户信息失败"),
SAVE_SERVICE_CENTER_ERROR("30110201", "保存服务中心失败"),
PAGE_SERVICE_CENTER_ERROR("30110202", "分页查询服务中心失败"),
LIST_SERVICE_CENTER_ERROR("30110203", "查询服务中心列表失败"),
UPDATE_SERVICE_CENTER_ERROR("30110204", "更新服务中心失败"),
DUPLICATE_SERVICE_CENTER_ERROR("30110205", "查询服务商下服务中心是否重复失败"),
/*******************智享车生活生意助手-技师配置模块*************************/
PAGE_TECHNICIAN_CONFIG_ERROR("30120201", "分页查询技师列表失败"),
UPDATE_TECHNICIAN_CONFIG_ERROR("30120202", "同一4S店下,不可重复姓名技师"),
ADD_TECHNICIAN_CONFIG_ERROR("30120203", "同一4S店下,不可新增重复姓名技师"),
DELETE_TECHNICIAN_CONFIG_ERROR("30120204", "删除技师信息失败"),
/*******************智享车生活-场景商户关系*************************/
LIST_SHOP_4S_BY_REF_ERROR("30120101", "获取有关联关系的4s店列表失败"),
LIST_SCENE_SHOP_YQ_REF_ERROR("30120102", "获取某场景4s店与园区店关联关系列表失败"),
/*******************智享车生活-商品*************************/
LIST_MERCHANT_UPGRADE_GOODS_ALIAS_ERROR("30130101", "获取4s店升级商品别名列表失败"),
LIST_MERCHANT_UPGRADE_GOODS_ALIAS_BY_MERCHANTREF_ERROR("30130102", "获取4s店升级商品别名列表失败"),
SAVE_MERCHANT_UPGRADE_GOODS_ALIAS_ERROR("30130103", "保存4s店升级商品别名列表失败"),
LIST_UPGRADE_GOODS_ERROR("30130201", "查询升级商品信息失败"),
/*******************智享车生活企业微信授权登录模块*************************/
/** 登录-企业微信授权失败**/
SCL_WORKWECHAT_LOGIN_AUTH_FAILURE("30990101", "企业微信授权失败"),
/** 登录-获取用户手机号失败**/
SCL_WORKWECHAT_LOGIN_GETPHONE_FAILURE("30990102", "获取用户手机号失败"),
/** 登录-尚未绑定嘀加账号**/
SCL_WORKWECHAT_LOGIN_NOT_BIND_ACCOUNT("30990103", "尚未绑定嘀加账号"),
/** 登录-登录账号异常**/
SCL_WORKWECHAT_SELECT_ACCOUNT_ERROR("30990201", "登录账号异常"),
/** 登录-创建登录令牌失败**/
SYSTEM_LOGIN_SAVE_TOKEN_ERROR("20010105", "创建登录令牌失败"),
/** 选择登录账号异常**/
SELECT_ACCONT_LOGIN_EXCEPTION("30980101","选择账号异常"),
/** 您账户已经过期,请联系管理员续期 **/
LOGIN_ACCOUNT_EXPIRE("30980102","您账户已经过期,请联系管理员续期"),
/** 账号或密码错误 **/
LOGIN_ACCOUNT_ERROR("30980103","账号或密码错误"),
/** 切换子账号-切换子账号异常**/
AYSNC_EXPORT_ERROR("30990502", "异步导出Excel异常"),
/*******************商学院-员工管理*************************/
/** 重置员工查看绩效密码失败**/
STAFF_PERFORMANCE_PASSWORD_RESET_ERROR("30140101", "重置员工查看绩效密码失败"),
XLSX_HEAD_ERROR("30140102", "表头校验失败"),
;
private String value;
private String displayName;
static Map<String, RopErrorEnum> enumMap = new HashMap<String, RopErrorEnum>();
static{
for(RopErrorEnum code:RopErrorEnum.values()){
enumMap.put(code.getValue(), code);
}
}
RopErrorEnum(String value, String displayName){
this.value = value;
this.displayName = displayName;
}
public static RopErrorEnum getEnum(String value){
return enumMap.get(value);
}
@Override
public String getValue() {
return value;
}
@Override
public String getDisplayName() {
return displayName;
}
}
package cn.com.glsx.dj.peanalysis.util.excel;
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!