BusinessExportController.java
17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package cn.com.glsx.dj.controller;
import cn.com.glsx.dj.converter.StoreListResponseConvert;
import cn.com.glsx.dj.peanalysis.dto.req.UserdCarDataStats.StoreListReq;
import cn.com.glsx.dj.peanalysis.dto.req.output.BaseReq;
import cn.com.glsx.dj.peanalysis.dto.req.output.SceneBaseReq;
import cn.com.glsx.dj.peanalysis.dto.res.UserdCarDataStats.StoreListRes;
import cn.com.glsx.dj.peanalysis.dto.res.output.ProvinceOutputResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.StoreListResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.TotalOutputResponse;
import cn.com.glsx.dj.peanalysis.enums.LoginRoleEnum;
import cn.com.glsx.dj.peanalysis.remote.BusinessAnalysisRemote;
import cn.com.glsx.dj.peanalysis.remote.BusinessSceneAnalysisRemote;
import cn.com.glsx.dj.peanalysis.remote.UsedCarDataStatsRemote;
import cn.com.glsx.dj.request.output.BusinessExportRequest;
import cn.com.glsx.dj.response.LoginUserInfoResponse;
import cn.com.glsx.dj.response.bianalysis.BusinessExportResponse;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.rop.response.RopResponse;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.rop.annotation.NeedInSessionType;
import com.rop.annotation.ServiceMethod;
import com.rop.annotation.ServiceMethodBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import javax.annotation.Resource;
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.core.io.FileSystemResource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
@Slf4j
@ServiceMethodBean(version = "1.0.0", needInSession = NeedInSessionType.NO)
@Api("BI业务数据导出")
public class BusinessExportController {
@Resource
private BusinessAnalysisRemote businessAnalysisRemote;
@Resource
private BusinessSceneAnalysisRemote businessSceneAnalysisRemote;
@Resource
private UsedCarDataStatsRemote usedCarDataStatsRemote;
@Autowired
private TaskExecutor taskExecutor;
@Resource
private Environment environment;
@ApiOperation("BI业务数据下载")
@ServiceMethod(method = "dj.api.smartcarlife.business.data.download", needInSession = NeedInSessionType.NO)
public RopResponse<BusinessExportResponse> dataDownload(BusinessExportRequest request) {
log.info("BI业务数据下载开始:{}", request);
// 处理日期格式
if (request.getStartDate() != null) {
request.setStartDate(formatDateToYyyyMmDd(request.getStartDate()));
}
if (request.getEndDate() != null) {
request.setEndDate(formatDateToYyyyMmDd(request.getEndDate()));
}
long startTime = System.currentTimeMillis();
BusinessExportResponse res = new BusinessExportResponse();
// 文件名
String fileName = buildFileName(request.getStartDate(), request.getEndDate());
// 文件存储路径
String filePath = null;
try {
// 超管
LoginUserInfoResponse loginUserInfo = LoginUserInfoResponse.builder()
.loginRole(LoginRoleEnum.OTHER.getValue()).build();
TotalOutputResponse sheet1 = queryProvinceTotalOutput(loginUserInfo, request.getStartDate(), request.getEndDate());
List<StoreListResponse> sheet2 = queryBizStoreList(loginUserInfo, (byte) 0, 1, request.getStartDate(), request.getEndDate());
List<StoreListResponse> sheet3 = queryBizStoreList(loginUserInfo, (byte) 0, 3, request.getStartDate(), request.getEndDate());
List<StoreListResponse> sheet4 = queryBizStoreList(loginUserInfo, (byte) 1, 2, request.getStartDate(), request.getEndDate());
List<cn.com.glsx.dj.response.UserdCarDataStats.StoreListResponse> sheet5 = queryUsedCarStoreList(loginUserInfo, request.getStartDate(), request.getEndDate());
// 写入磁盘
filePath = writeExcelToDiskByEasyExcel(fileName, request.getStartDate(), request.getEndDate(),
sheet1, sheet2, sheet3, sheet4, sheet5);
log.info("filePath:{}", filePath);
// 异步推送BI报表到大数据平台
if (StringUtils.isNotEmpty(filePath)){
syncSendBusinessReportFile(filePath);
}
} catch (Exception e) {
log.error("BI业务数据下载Excel异常", e);
throw new RuntimeException(e.getMessage());
}
res.setDownloadUrl(fileName);
long endTime = System.currentTimeMillis();
log.info("BI业务数据下载结束:{}", endTime-startTime);
return RopResponse.success(res);
}
/**
* 异步推送BI报表
*/
private void syncSendBusinessReportFile(String filePath) {
taskExecutor.execute(() -> {
try {
String url = environment == null ? null : environment.getProperty("rop.pe.bi.file.push.url");
if(StringUtils.isBlank(url)){
return;
}
RestTemplate restTemplate = new RestTemplate();
// 准备文件
FileSystemResource fileResource = new FileSystemResource(new File(filePath));
// 构造请求体
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", fileResource);
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// 构造请求
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
// 发送请求
log.info("异步推送BI报表开始");
long beginTime = System.currentTimeMillis();
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
log.info("异步推送BI报表结束,返回值:{},耗时:{}ms",response.getBody(),(System.currentTimeMillis() - beginTime));
} catch (Exception e) {
log.info("异步推送BI报表失败,失败原因:{}",e.getMessage());
log.error(e.getMessage(),e);
}
});
}
private String writeExcelToDiskByEasyExcel(String fileName, String startTime, String endTime,
TotalOutputResponse sheet1, List<StoreListResponse> sheet2, List<StoreListResponse> sheet3,
List<StoreListResponse> sheet4, List<cn.com.glsx.dj.response.UserdCarDataStats.StoreListResponse> sheet5) throws Exception {
String baseDir = environment == null ? null : environment.getProperty("rop.pe.bi.excel.tem.path");
if (StringUtils.isBlank(baseDir)) {
log.info("未配置bi报表导出文件路径");
throw new RuntimeException("未配置bi报表导出文件路径");
}
File dir = new File(baseDir);
if (!dir.exists() && !dir.mkdirs()) {
throw new RuntimeException("创建导出目录失败:" + dir.getAbsolutePath());
}
File file = new File(dir, fileName);
ExcelWriter writer = EasyExcel.write(file).build();
try {
WriteSheet s1 = EasyExcel.writerSheet(0, "全业务")
.head(buildHead(Arrays.asList("开始日期", "结束日期", "省份", "总产值", "门店总数", "店均产值", "门店占比(%)", "多品类门店占比(%)")))
.registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))
.build();
writer.write(buildSheet1Rows(startTime, endTime, sheet1), s1);
List<String> storeHeads = Arrays.asList("开始日期", "结束日期", "门店名称", "商户号", "产值", "达成率(%)", "触客率(%)", "转化率(%)", "渗透率(%)", "升客价", "平客价");
WriteSheet s2 = EasyExcel.writerSheet(1, "延保业务").head(buildHead(storeHeads)).registerWriteHandler(new SimpleColumnWidthStyleStrategy(20)).build();
writer.write(buildBizStoreRows(startTime, endTime, sheet2), s2);
WriteSheet s3 = EasyExcel.writerSheet(2, "权益业务").head(buildHead(storeHeads)).registerWriteHandler(new SimpleColumnWidthStyleStrategy(20)).build();
writer.write(buildBizStoreRows(startTime, endTime, sheet3), s3);
WriteSheet s4 = EasyExcel.writerSheet(3, "轻改业务").head(buildHead(storeHeads)).registerWriteHandler(new SimpleColumnWidthStyleStrategy(20)).build();
writer.write(buildBizStoreRows(startTime, endTime, sheet4), s4);
WriteSheet s5 = EasyExcel.writerSheet(4, "二手车业务")
.head(buildHead(Arrays.asList("开始日期", "结束日期", "门店名称", "商户号", "收车数", "单车毛利", "评估转化率(%)", "置换率(%)", "平均周转天数")))
.registerWriteHandler(new SimpleColumnWidthStyleStrategy(20)).build();
writer.write(buildUsedCarRows(startTime, endTime, sheet5), s5);
} finally {
writer.finish();
}
return file.getAbsolutePath();
}
private List<List<String>> buildHead(List<String> heads) {
List<List<String>> res = new ArrayList<>();
for (String h : heads) {
res.add(Arrays.asList(h));
}
return res;
}
private List<List<Object>> buildSheet1Rows(String startTime, String endTime, TotalOutputResponse data) {
List<List<Object>> rows = new ArrayList<>();
List<ProvinceOutputResponse> list = data == null ? null : data.getProvinceOutput();
if (CollectionUtils.isEmpty(list)) {
return rows;
}
for (ProvinceOutputResponse p : list) {
rows.add(Arrays.asList(
startTime,
endTime,
p == null ? null : p.getProvinceName(),
p == null ? null : p.getTotalOutput(),
p == null ? null : p.getStoreNumber(),
p == null ? null : p.getAvgOutput(),
p == null ? null : p.getStoreNumberRate(),
p == null ? null : p.getMultiCategoryStoreNumberRate()
));
}
return rows;
}
private List<List<Object>> buildBizStoreRows(String startTime, String endTime, List<StoreListResponse> list) {
List<List<Object>> rows = new ArrayList<>();
if (CollectionUtils.isEmpty(list)) {
return rows;
}
for (StoreListResponse s : list) {
rows.add(Arrays.asList(
startTime,
endTime,
s == null ? null : s.getStoreName(),
s == null ? null : s.getStoreId(),
s == null ? null : s.getOutputValue(),
s == null ? null : s.getAchievementRate(),
s == null ? null : s.getCustomerContactRate(),
s == null ? null : s.getConversionRate(),
s == null ? null : s.getPenetrationRate(),
s == null ? null : s.getUpgradeCustomerPrice(),
s == null ? null : s.getAvgCustomerPrice()
));
}
return rows;
}
private List<List<Object>> buildUsedCarRows(String startTime, String endTime, List<cn.com.glsx.dj.response.UserdCarDataStats.StoreListResponse> list) {
List<List<Object>> rows = new ArrayList<>();
if (CollectionUtils.isEmpty(list)) {
return rows;
}
for (cn.com.glsx.dj.response.UserdCarDataStats.StoreListResponse s : list) {
rows.add(Arrays.asList(
startTime,
endTime,
s == null ? null : s.getMerchantName(),
s == null ? null : s.getMerchantId(),
s == null ? null : s.getReceiptCount(),
s == null ? null : s.getSingleCarGrossProfit(),
s == null ? null : s.getAssessmentConversionRate(),
s == null ? null : s.getReplacementRate(),
s == null ? null : s.getAverageTurnoverDays()
));
}
return rows;
}
private String buildFileName(String startTime, String endTime) {
String s = StringUtils.defaultString(startTime, "");
String e = StringUtils.defaultString(endTime, "");
String base = "【BI数据分析表】BI数据分析表";
if (StringUtils.isNotBlank(s) || StringUtils.isNotBlank(e)) {
base = base + "(" + s + "~" + e+ ")";
}
return base + ".xlsx";
}
private TotalOutputResponse queryProvinceTotalOutput(LoginUserInfoResponse loginUserInfo, String startTime, String endTime) {
BaseReq req = BaseReq.builder()
.cycleType(4)
.startTime(startTime)
.endTime(endTime)
.build();
fillBaseReqByLogin(req, loginUserInfo);
RpcResponse<TotalOutputResponse> rpc = businessAnalysisRemote.provinceOutput(req);
if (rpc == null || rpc.isFailed()) {
throw new RuntimeException(rpc == null ? "全业务省份排名接口无响应" : rpc.getMessage());
}
TotalOutputResponse result = rpc.getResult();
if (result != null && CollectionUtils.isNotEmpty(result.getProvinceOutput())) {
List<ProvinceOutputResponse> provinceList = result.getProvinceOutput();
Comparator<ProvinceOutputResponse> comparator = buildComparator(ProvinceOutputResponse::getTotalOutput, true);
provinceList.sort(comparator);
}
return result;
}
private <T extends Comparable<? super T>>
Comparator<ProvinceOutputResponse> buildComparator(
Function<ProvinceOutputResponse, T> keyExtractor,
boolean descending) {
Comparator<T> comp = Comparator.naturalOrder();
if (descending) {
comp = comp.reversed();
}
return Comparator.comparing(keyExtractor, Comparator.nullsLast(comp));
}
private void fillBaseReqByLogin(BaseReq req, LoginUserInfoResponse loginUserInfo) {
req.setLoginRole(loginUserInfo.getLoginRole());
}
private List<StoreListResponse> queryBizStoreList(LoginUserInfoResponse loginUserInfo, byte sceneType, int bizs, String startTime, String endTime) {
// 超管角色 OTHER,不做门店权限过滤
SceneBaseReq req = new SceneBaseReq();
req.setSceneType(sceneType);
req.setBizs(bizs);
req.setCycleType(4);
req.setStartTime(startTime);
req.setEndTime(endTime);
req.setOrderBy("outputValue");
req.setOrderType(1);
req.setRole(loginUserInfo.getLoginRole());
RpcResponse<List<StoreListResponse>> rpc = businessSceneAnalysisRemote.storeList(req);
if (rpc == null || rpc.isFailed()) {
throw new RuntimeException(rpc == null ? "门店列表接口无响应" : rpc.getMessage());
}
return rpc.getResult();
}
private List<cn.com.glsx.dj.response.UserdCarDataStats.StoreListResponse> queryUsedCarStoreList(LoginUserInfoResponse loginUserInfo, String startTime, String endTime) {
StoreListReq req = new StoreListReq();
req.setBusinessType(5);
req.setCycleType(4);
req.setStartTime(startTime);
req.setEndTime(endTime);
req.setSortType(1);
req.setSortOrder(1);
// 超管角色 OTHER,不做门店权限过滤
req.setRole(loginUserInfo.getLoginRole());
RpcResponse<List<StoreListRes>> rpc = usedCarDataStatsRemote.getStoreList(req);
if (rpc == null || rpc.isFailed()) {
throw new RuntimeException(rpc == null ? "二手车门店列表接口无响应" : rpc.getMessage());
}
List<StoreListRes> resList = rpc.getResult();
if (CollectionUtils.isEmpty(resList)) {
return null;
}
return StoreListResponseConvert.INSTANCE.toListStoreListResponse(resList);
}
/**
* 将日期字符串统一转换为 yyyy-MM-dd 格式
*/
private String formatDateToYyyyMmDd(String dateStr) {
if (StringUtils.isEmpty(dateStr)) {
return dateStr;
}
dateStr = dateStr.trim();
String targetFormat = "yyyy-MM-dd";
try {
if (dateStr.length() == 10) {
return dateStr;
} else if (dateStr.length() == 16) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = sdf.parse(dateStr);
return new SimpleDateFormat(targetFormat).format(date);
} else if (dateStr.length() == 19) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateStr);
return new SimpleDateFormat(targetFormat).format(date);
} else {
log.warn("不支持的日期格式: {}", dateStr);
return dateStr;
}
} catch (ParseException e) {
log.error("日期格式转换失败: {}", dateStr, e);
return dateStr;
}
}
}