Browse Source

合并代码

wangPH 2 years ago
parent
commit
dce0329422

+ 8 - 0
background-user/src/main/java/cn/kdan/compdf/controller/v1/BackgroundUserBalanceController.java

@@ -13,6 +13,7 @@ import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.bind.annotation.*;
 
 import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 import java.util.List;
 
 /**
@@ -49,6 +50,13 @@ public class BackgroundUserBalanceController {
         return R.ok(balanceRecordList);
     }
 
+    /**
+     * 账户消费充值记录导出
+     */
+    @GetMapping("/exportBalanceRecordList")
+    public void exportBalanceRecordList(HttpServletResponse response) {
+        backgroundUserBalanceService.exportBalanceRecordList(TokenUtil.getRequestHeader().getId(), response);
+    }
 
 
     /**

+ 1 - 0
background-user/src/main/java/cn/kdan/compdf/controller/v1/BackgroundUserWebhookController.java

@@ -67,6 +67,7 @@ public class BackgroundUserWebhookController {
      */
     @PutMapping("/editWebhook")
     public R<Void> editWebhook(@Validated @RequestBody EditWebhookDTO editWebhookDTO) {
+        editWebhookDTO.setUserId(TokenUtil.getRequestHeader().getId());
         backgroundUserWebhookService.editWebhook(editWebhookDTO);
         return R.ok();
     }

+ 6 - 0
background-user/src/main/java/cn/kdan/compdf/dto/EditWebhookDTO.java

@@ -1,5 +1,6 @@
 package cn.kdan.compdf.dto;
 
+import com.fasterxml.jackson.annotation.JsonIgnore;
 import lombok.Data;
 
 import javax.validation.constraints.NotEmpty;
@@ -33,4 +34,9 @@ public class EditWebhookDTO implements Serializable {
     @NotNull(message = "Please select at least one event")
     private List<Long> eventsId;
 
+    /**
+     * 关联用户主键id
+     */
+    @JsonIgnore
+    private Long userId;
 }

+ 1 - 1
background-user/src/main/java/cn/kdan/compdf/entity/dto/AnalysisDataDTO.java

@@ -37,6 +37,6 @@ public class AnalysisDataDTO implements Serializable {
     /**
      * 平均处理时长
      */
-    private BigDecimal averageProcessTime;
+    private String averageProcessTime;
 
 }

+ 8 - 0
background-user/src/main/java/cn/kdan/compdf/service/BackgroundUserBalanceService.java

@@ -8,6 +8,7 @@ import cn.kdan.compdf.vo.BackgroundUserPackageBalanceVO;
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 
+import javax.servlet.http.HttpServletResponse;
 import java.util.List;
 
 /**
@@ -38,6 +39,13 @@ public interface BackgroundUserBalanceService extends IService<BackgroundUserBal
      */
     IPage<BackgroundUserBalanceVO> getBalanceRecordList(Long userId, Integer page, Integer size);
 
+    /**
+     * 账户消费充值记录导出
+     * @param userId 用户id
+     * @param response response
+     */
+    void exportBalanceRecordList(Long userId, HttpServletResponse response);
+
     /**
      * plan 消费记录数据同步 一天一次
      */

+ 58 - 1
background-user/src/main/java/cn/kdan/compdf/service/impl/BackgroundConvertDataServiceImpl.java

@@ -86,15 +86,46 @@ public class BackgroundConvertDataServiceImpl extends ServiceImpl<BackgroundConv
             errorRequest += backgroundConvertDatum.getFileFailedTotal();
             averageProcessTimeTotal = backgroundConvertDatum.getFileConvertTime().add(averageProcessTimeTotal);
         }
+        BigDecimal averageProcessTime1 = averageProcessTimeTotal.divide(new BigDecimal(backgroundConvertData.size()), 2, BigDecimal.ROUND_HALF_UP);
         return AnalysisDataDTO.builder()
                 .fileTotal(fileTotal)
                 .successfulRequest(successfulRequest)
                 .errorRequest(errorRequest)
                 .errorRatio(new BigDecimal(String.format("%.2f", errorRequest * 100.00 / fileTotal)))
-                .averageProcessTime(averageProcessTimeTotal.divide(new BigDecimal(backgroundConvertData.size()), 2, BigDecimal.ROUND_HALF_UP))
+                .averageProcessTime(TimeConvert(averageProcessTime1, null))
                 .build();
     }
 
+    /**
+     * ms-s-min-时间处理
+     * @param time 毫秒时间
+     * @param type 指定转换类型1:s;2:min
+     * @return
+     */
+    private String TimeConvert(BigDecimal time, Integer type) {
+        BigDecimal convertTime = time;
+        String convertTimeString = time + "ms";
+        // 自动转换
+        if (null == type) {
+            // ms-s,大于1000毫秒转换
+            if (convertTime.compareTo(new BigDecimal("1000")) >= 0) {
+                convertTimeString = convertTime.divide(new BigDecimal("1000"), 2, BigDecimal.ROUND_HALF_UP) + "s";
+                // s-min,大于60秒转换
+                if (convertTime.compareTo(new BigDecimal("60")) >= 0) {
+                    convertTimeString = convertTime.divide(new BigDecimal("60"), 2, BigDecimal.ROUND_HALF_UP) + "min";
+                }
+            }
+        } else if (type == 1) {
+            // 转换为s
+            convertTimeString = convertTime.divide(new BigDecimal("1000"), 2, BigDecimal.ROUND_HALF_UP) + "s";
+        } else if (type == 2) {
+            // 转换为min
+            convertTime = convertTime.divide(new BigDecimal("1000"), 2, BigDecimal.ROUND_HALF_UP);
+            convertTimeString = convertTime.divide(new BigDecimal("60"), 2, BigDecimal.ROUND_HALF_UP) + "min";
+        }
+        return convertTimeString;
+    }
+
     @Override
     @Cacheable(value = RedisConstantServer.DASHBOARD_SUCCESS_DATA, cacheManager = "myCacheManager", key = "T(String).valueOf(#queryDTO.toString())", unless = "#result == null")
     public List<DashboardDetailedDataDTO> getSuccessfulRequestDetailedData(DashboardQueryDTO queryDTO) {
@@ -392,6 +423,32 @@ public class BackgroundConvertDataServiceImpl extends ServiceImpl<BackgroundConv
             default:
                 throw new CommonException(ResponseEnum.SYSTEM_ERROR);
         }
+
+        // 计算平均值,确定单位
+        BigDecimal average = BigDecimal.ZERO;
+        for (DashboardDetailedDataDTO dataDTO : dataDTOS) {
+            average = average.add(new BigDecimal(dataDTO.getYData()));
+        }
+        average = average.divide(new BigDecimal(dataDTOS.size()), 2, BigDecimal.ROUND_HALF_UP);
+        Integer flag = null;
+        // 平均值大于秒
+        if (average.compareTo(new BigDecimal("1000")) >= 0) {
+            flag = 1;
+        }
+        // 平均值大于分钟
+        if (average.compareTo(new BigDecimal("60000")) >= 0) {
+            flag = 2;
+        }
+        // 转换
+        if (null != flag) {
+            for (DashboardDetailedDataDTO dataDTO : dataDTOS) {
+                dataDTO.setYData(TimeConvert(new BigDecimal(dataDTO.getYData()), flag));
+            }
+        } else {
+            for (DashboardDetailedDataDTO dataDTO : dataDTOS) {
+                dataDTO.setYData(dataDTO.getYData() + "ms");
+            }
+        }
         return dataDTOS;
     }
 

+ 66 - 0
background-user/src/main/java/cn/kdan/compdf/service/impl/BackgroundUserBalanceServiceImpl.java

@@ -4,6 +4,8 @@ import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.collection.CollectionUtil;
 import cn.kdan.compdf.dto.AddFreePlanDTO;
 import cn.kdan.compdf.dto.Asset;
+import cn.hutool.core.date.DateUtil;
+import cn.kdan.compdf.config.ExcelWidthStyleStrategy;
 import cn.kdan.compdf.dto.PlanStatisticsDTO;
 import cn.kdan.compdf.entity.BackgroundUserBalance;
 import cn.kdan.compdf.mapper.BackgroundUserBalanceMapper;
@@ -11,20 +13,29 @@ import cn.kdan.compdf.service.BackgroundUserBalanceService;
 import cn.kdan.compdf.service.BackgroundUserService;
 import cn.kdan.compdf.vo.BackgroundUserBalanceVO;
 import cn.kdan.compdf.vo.BackgroundUserPackageBalanceVO;
+import com.alibaba.excel.EasyExcel;
+import com.alibaba.excel.util.MapUtils;
+import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
+import com.alibaba.fastjson.JSON;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.tomcat.util.http.fileupload.IOUtils;
 import org.assertj.core.util.Lists;
 import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.stereotype.Service;
 
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URLEncoder;
 import java.time.ZoneId;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
+import java.util.Map;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -113,6 +124,61 @@ public class BackgroundUserBalanceServiceImpl extends ServiceImpl<BackgroundUser
         return backgroundUserBalanceVOPage;
     }
 
+    /**
+     * 账户消费充值记录导出
+     * @param userId 用户id
+     * @param response response
+     */
+    @Override
+    public void exportBalanceRecordList(Long userId, HttpServletResponse response) {
+        LambdaQueryWrapper<BackgroundUserBalance> eq = new LambdaQueryWrapper<BackgroundUserBalance>()
+                .eq(BackgroundUserBalance::getUserId, userId)
+                .orderByDesc(BackgroundUserBalance::getCreateDate);
+        List<BackgroundUserBalance> backgroundUserBalanceList = this.baseMapper.selectList(eq);
+        // 处理返回数据
+        List<BackgroundUserBalanceVO> backgroundUserBalanceVOList = new ArrayList<>();
+        if (CollectionUtil.isNotEmpty(backgroundUserBalanceList)) {
+            backgroundUserBalanceList.forEach(c -> {
+                BackgroundUserBalanceVO backgroundUserBalanceVO = new BackgroundUserBalanceVO();
+                BeanUtil.copyProperties(c, backgroundUserBalanceVO);
+                if (c.getChangeType() == 1) {
+                    backgroundUserBalanceVO.setBalanceChange("+" + c.getBalanceChange());
+                } else {
+                    backgroundUserBalanceVO.setBalanceChange("-" + c.getBalanceChange());
+                }
+                backgroundUserBalanceVOList.add(backgroundUserBalanceVO);
+            });
+        }
+
+        // 写入响应导出
+        try {
+            String fileName = URLEncoder.encode("Processing Files Balance (" + DateUtil.date().toString().replaceAll(":", "-") + ")", "UTF-8").replaceAll("\\+", "%20");
+            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+            response.setCharacterEncoding("utf-8");
+            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
+            EasyExcel.write(response.getOutputStream(), BackgroundUserBalanceVO.class)
+                    .registerWriteHandler(new ExcelWidthStyleStrategy())
+                    .autoCloseStream(Boolean.FALSE)
+                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
+                    .sheet("Processing Files Balance")
+                    .doWrite(backgroundUserBalanceVOList);
+
+        } catch (Exception e) {
+            // 重置response
+            response.reset();
+            response.setContentType("application/json");
+            response.setCharacterEncoding("utf-8");
+            Map<String, String> map = MapUtils.newHashMap();
+            map.put("status", "failure");
+            map.put("message", "下载文件失败" + e.getMessage());
+            try {
+                response.getWriter().println(JSON.toJSONString(map));
+            } catch (IOException ioException) {
+                ioException.printStackTrace();
+            }
+        }
+    }
+
     @Override
     public void planSync(List<PlanStatisticsDTO> list) {
         assert list != null : "Dashboard同步数据为空";

+ 25 - 0
background-user/src/main/java/cn/kdan/compdf/service/impl/BackgroundUserWebhookServiceImpl.java

@@ -8,11 +8,14 @@ import cn.kdan.compdf.dto.AddNewWebhookDTO;
 import cn.kdan.compdf.dto.AddNewWebhookSaaSDTO;
 import cn.kdan.compdf.dto.EditWebhookDTO;
 import cn.kdan.compdf.entity.BackgroundEvent;
+import cn.kdan.compdf.entity.BackgroundUserProject;
 import cn.kdan.compdf.entity.BackgroundUserWebhook;
 import cn.kdan.compdf.entity.BackgroundWebhookEvent;
 import cn.kdan.compdf.enums.RabbitMQEnum;
+import cn.kdan.compdf.exception.BusinessException;
 import cn.kdan.compdf.mapper.BackgroundUserWebhookMapper;
 import cn.kdan.compdf.service.BackgroundEventService;
+import cn.kdan.compdf.service.BackgroundUserProjectService;
 import cn.kdan.compdf.service.BackgroundUserWebhookService;
 import cn.kdan.compdf.service.BackgroundWebhookEventService;
 import cn.kdan.compdf.utils.MD5Util;
@@ -44,6 +47,8 @@ public class BackgroundUserWebhookServiceImpl extends ServiceImpl<BackgroundUser
     @Autowired
     private BackgroundWebhookEventService backgroundWebhookEventService;
     @Autowired
+    private BackgroundUserProjectService backgroundUserProjectService;
+    @Autowired
     private RabbitTemplate rabbitTemplate;
 
     @Override
@@ -127,6 +132,16 @@ public class BackgroundUserWebhookServiceImpl extends ServiceImpl<BackgroundUser
      */
     @Override
     public void addNewWebhook(AddNewWebhookDTO addNewWebhookDTO) {
+        // 参数校验
+        LambdaQueryWrapper<BackgroundUserProject> eq = new LambdaQueryWrapper<BackgroundUserProject>()
+                .eq(BackgroundUserProject::getUserId, addNewWebhookDTO.getUserId())
+                .eq(BackgroundUserProject::getId, addNewWebhookDTO.getProjectId());
+        BackgroundUserProject backgroundUserProject = backgroundUserProjectService.getOne(eq);
+        if (null == backgroundUserProject) {
+            log.error("新增webhook项目id错误:" + addNewWebhookDTO.getProjectId());
+            throw new BusinessException("parameter error");
+        }
+
         BackgroundUserWebhook backgroundUserWebhook = new BackgroundUserWebhook();
         BeanUtil.copyProperties(addNewWebhookDTO, backgroundUserWebhook);
         // 设置回调token
@@ -153,6 +168,16 @@ public class BackgroundUserWebhookServiceImpl extends ServiceImpl<BackgroundUser
 
     @Override
     public void editWebhook(EditWebhookDTO editWebhookDTO) {
+        // 参数校验
+        LambdaQueryWrapper<BackgroundUserProject> eq = new LambdaQueryWrapper<BackgroundUserProject>()
+                .eq(BackgroundUserProject::getUserId, editWebhookDTO.getUserId())
+                .eq(BackgroundUserProject::getId, editWebhookDTO.getProjectId());
+        BackgroundUserProject backgroundUserProject = backgroundUserProjectService.getOne(eq);
+        if (null == backgroundUserProject) {
+            log.error("编辑webhook项目id错误:" + editWebhookDTO.getProjectId());
+            throw new BusinessException("parameter error");
+        }
+
         BackgroundUserWebhook backgroundUserWebhook = new BackgroundUserWebhook();
         BeanUtil.copyProperties(editWebhookDTO, backgroundUserWebhook);
         this.baseMapper.updateById(backgroundUserWebhook);

+ 7 - 0
background-user/src/main/java/cn/kdan/compdf/vo/BackgroundUserBalanceVO.java

@@ -1,5 +1,7 @@
 package cn.kdan.compdf.vo;
 
+import com.alibaba.excel.annotation.ExcelIgnore;
+import com.alibaba.excel.annotation.ExcelProperty;
 import lombok.Data;
 
 import java.util.Date;
@@ -13,22 +15,27 @@ public class BackgroundUserBalanceVO {
     /**
      * 日期
      */
+    @ExcelProperty(value = "Date", index = 0)
     private Date date;
     /**
      * 充值/消费具体类型描述
      */
+    @ExcelProperty(value = "Description", index = 1)
     private String description;
     /**
      * 文件数量变动额度
      */
+    @ExcelProperty(value = "Balance change", index = 2)
     private String balanceChange;
     /**
      * 文件数量余额
      */
+    @ExcelProperty(value = "Remaing files", index = 3)
     private Integer remainingFiles;
     /**
      * 过期时间
      */
+    @ExcelIgnore
     private Date expiredDate;
 
 }