فهرست منبع

bug相关

Signed-off-by: liuyc <56808083@qq.com>
liuyc 8 ماه پیش
والد
کامیت
120f7685f9

+ 4 - 0
blade-ops-api/blade-resource-api/src/main/java/org/springblade/resource/feign/NewIOSSClient.java

@@ -8,6 +8,7 @@ import org.springframework.http.MediaType;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RequestPart;
 import org.springframework.web.multipart.MultipartFile;
 
 import java.io.InputStream;
@@ -51,4 +52,7 @@ public interface NewIOSSClient {
     @PostMapping(value = API_PREFIX + "/excelToPdf", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
     NewBladeFile excelToPdf(MultipartFile file);
 
+    @PostMapping(value = API_PREFIX + "/excelToPdfs", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+    NewBladeFile excelToPdfs(@RequestPart("files") List<MultipartFile> files);
+
 }

+ 76 - 4
blade-ops/blade-resource/src/main/java/org/springblade/resource/feign/CommonFileClientImpl.java

@@ -7,20 +7,19 @@ import com.itextpdf.text.Rectangle;
 import com.itextpdf.text.pdf.PdfWriter;
 import lombok.AllArgsConstructor;
 import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.WorkbookFactory;
+import org.apache.poi.ss.usermodel.*;
 import org.springblade.common.utils.CommonUtil;
 import org.springblade.core.oss.model.BladeFile;
 import org.springblade.core.tenant.annotation.NonDS;
 import org.springblade.core.tool.utils.FileUtil;
 import org.springblade.core.tool.utils.IoUtil;
-import org.springblade.core.tool.utils.ResourceUtil;
 import org.springblade.resource.builder.oss.OssBuilder;
 import org.springblade.resource.vo.NewBladeFile;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.multipart.MultipartFile;
 
 import java.io.*;
+import java.util.List;
 import java.util.Objects;
 
 @NonDS
@@ -57,7 +56,7 @@ public class CommonFileClientImpl implements CommonFileClient {
             document.close();
 
             //上传文件
-            String fileExtension =  "."+FileUtil.getFileExtension(file.getOriginalFilename());
+            String fileExtension = "." + FileUtil.getFileExtension(file.getOriginalFilename());
             pdfInput = new ByteArrayInputStream(bos.toByteArray());
             String originalFilename = Objects.requireNonNull(file.getOriginalFilename()).replaceAll(fileExtension, ".pdf");
 
@@ -231,4 +230,77 @@ public class CommonFileClientImpl implements CommonFileClient {
         return "";
     }
 
+    /**
+     * 多个excel 合并转 pdf
+     *
+     * @param files
+     * @return
+     */
+    public NewBladeFile excelToPdfs(List<MultipartFile> files) {
+        String pdfFileUrl;
+        int totalPage = 0;
+        ByteArrayOutputStream bos = null;
+
+        try {
+            com.aspose.cells.Workbook combinedWorkbook = new com.aspose.cells.Workbook();
+
+            for (MultipartFile file : files) {
+                org.apache.poi.ss.usermodel.Workbook ss = WorkbookFactory.create(file.getInputStream());
+
+                for (int i = 0, l = ss.getNumberOfSheets(); i < l; i++) {
+                    Sheet sheet = ss.getSheetAt(i);
+                    sheet.setPrintGridlines(false);
+                    sheet.setFitToPage(true);
+                }
+
+                ByteArrayOutputStream outReport = new ByteArrayOutputStream();
+                ss.write(outReport);
+
+                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outReport.toByteArray());
+                com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(byteArrayInputStream);
+
+                for (int j = 0; j < wb.getWorksheets().getCount(); j++) {
+                    com.aspose.cells.Worksheet sourceWorksheet = wb.getWorksheets().get(j);
+
+                    String newWorksheetName = sourceWorksheet.getName() + "_" + j;
+
+                    int counter = 1;
+                    while (combinedWorkbook.getWorksheets().get(newWorksheetName) != null) {
+                        newWorksheetName = sourceWorksheet.getName() + "_" + (j + counter);
+                        counter++;
+                    }
+
+                    com.aspose.cells.Worksheet newWorksheet = combinedWorkbook.getWorksheets().add(newWorksheetName);
+                    newWorksheet.copy(sourceWorksheet);
+                    totalPage++;
+                }
+
+                outReport.close();
+                byteArrayInputStream.close();
+                ss.close();
+            }
+
+            bos = new ByteArrayOutputStream();
+            combinedWorkbook.save(bos, SaveFormat.PDF);
+            bos.flush();
+
+            ByteArrayInputStream pdfInput = new ByteArrayInputStream(bos.toByteArray());
+            String originalFilename = "merged.pdf";
+            BladeFile bladeFile = this.ossBuilder.template().putFile(originalFilename, pdfInput);
+            pdfFileUrl = bladeFile.getLink();
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        } finally {
+            IoUtil.closeQuietly(bos);
+        }
+
+        NewBladeFile newBladeFile = new NewBladeFile();
+        newBladeFile.setPdfUrl(pdfFileUrl);
+        newBladeFile.setPage(totalPage);
+        return newBladeFile;
+    }
+
+
 }

+ 5 - 0
blade-ops/blade-resource/src/main/java/org/springblade/resource/feign/NewIOSSClientImpl.java

@@ -77,6 +77,11 @@ public class NewIOSSClientImpl implements NewIOSSClient {
         return commonFileClientImpl.excelToPdf(file);
     }
 
+    @Override
+    public NewBladeFile excelToPdfs(List<MultipartFile> files) {
+        return commonFileClientImpl.excelToPdfs(files);
+    }
+
     @Override
     public BladeFile uploadFile(String fileName, String localFileUrl) {
         try {

+ 1 - 1
blade-service-api/blade-business-api/src/main/java/org/springblade/business/feign/TaskClient.java

@@ -53,7 +53,7 @@ public interface TaskClient {
      * 保存任务
      */
     @PostMapping(SAVE_TASK)
-    void saveTask(@RequestBody Task task);
+    boolean saveTask(@RequestBody Task task);
 
     /**
      * 保存副任务

+ 218 - 76
blade-service/blade-business/src/main/java/org/springblade/business/controller/TrialSummaryController.java

@@ -179,6 +179,7 @@ public class TrialSummaryController {
                 && ObjectUtil.isNotEmpty(classC.getHtmlUrl())
                 && ObjectUtil.isNotEmpty(classC.getTrialTreeIds())) {
 
+            /*获取条件时间段内的试验自检数据*/
             LocalDate startDate = LocalDate.parse(dto.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
             LocalDate endDate = LocalDate.parse(dto.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
             List<TrialSelfInspectionRecord> records = trialSelfInspectionRecordServiceImpl.getBaseMapper().selectList(Wrappers.<TrialSelfInspectionRecord>lambdaQuery()
@@ -200,6 +201,8 @@ public class TrialSummaryController {
                     .collect(Collectors.groupingBy(
                             reflection -> reflection.getTrialTabName() + "###" + reflection.getTrialTabId()
                     ));
+
+            /*构造实体数据map*/
             Map<String, Object> map = new LinkedHashMap<>();
             for (Map.Entry<String, List<TrialSummaryExcelTabReflection>> entry : maps.entrySet()) {
                 String tabName = entry.getKey().split("###")[0];
@@ -230,17 +233,24 @@ public class TrialSummaryController {
                             for (String valueRow : split) {
                                 String[] splitValues = valueRow.split(Pattern.quote("_^_"));
                                 String valueInput = splitValues[0];
-                                String indexKey = splitValues[1];
-                                String keyName = elementKey + "__" + indexKey;
-                                map.put(keyName, valueInput);
+                                /*String indexKey = splitValues[1];*/
+                                String keyName = elementKey + "__";
+
+                                if (map.containsKey(keyName)) {
+                                    String existingValue = (String) map.get(keyName);
+                                    map.put(keyName, existingValue + "@@@###" + valueInput);
+                                } else {
+                                    map.put(keyName, valueInput);
+                                }
                             }
+
                         } else {
                             //非跨行
                             if (tabDataStr.contains(".000Z]") && tabDataStr.contains("T")) {
                                 String[] splitValues = tabDataStr.split(Pattern.quote("_^_"));
                                 String valueInput = splitValues[0];
-                                String indexKey = splitValues[1];
-                                String keyName = elementKey + "__" + indexKey;
+                                /*String indexKey = splitValues[1];*/
+                                String keyName = elementKey + "__";
 
                                 //范围日期
                                 String[] split = valueInput.split(",");
@@ -252,48 +262,66 @@ public class TrialSummaryController {
                                 ZonedDateTime endZonedTime = endTime.atZone(ZoneId.of("UTC"));
                                 String time_1 = startZonedTime.format(DateTimeFormatter.ISO_DATE_TIME);
                                 String time_2 = endZonedTime.format(DateTimeFormatter.ISO_DATE_TIME);
-                                map.put(keyName, time_1 + "~" + time_2);
+
+                                if (map.containsKey(keyName)) {
+                                    String existingValue = (String) map.get(keyName);
+                                    map.put(keyName, existingValue + "@@@###" + time_1 + "~" + time_2);
+                                } else {
+                                    map.put(keyName, time_1 + "~" + time_2);
+                                }
 
                             } else if (tabDataStr.contains(".000Z") && tabDataStr.contains("T")) {
                                 String[] splitValues = tabDataStr.split(Pattern.quote("_^_"));
                                 String valueInput = splitValues[0];
-                                String indexKey = splitValues[1];
-                                String keyName = elementKey + "__" + indexKey;
+                                /*String indexKey = splitValues[1];*/
+                                String keyName = elementKey + "__";
 
                                 //单日期
                                 LocalDateTime time = LocalDateTime.parse(valueInput, DateTimeFormatter.ISO_DATE_TIME);
                                 ZonedDateTime zonedDateTime = time.atZone(ZoneId.of("UTC"));
                                 String timeStr = zonedDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
-                                map.put(keyName, timeStr);
+
+                                if (map.containsKey(keyName)) {
+                                    String existingValue = (String) map.get(keyName);
+                                    map.put(keyName, existingValue + "@@@###" + timeStr);
+                                } else {
+                                    map.put(keyName, timeStr);
+                                }
 
                             } else {
                                 String[] splitValues = tabDataStr.split(Pattern.quote("_^_"));
                                 String valueInput = splitValues[0];
-                                String indexKey = splitValues[1];
-                                String keyName = elementKey + "__" + indexKey;
-                                map.put(keyName, valueInput);
+                                /*String indexKey = splitValues[1];*/
+                                String keyName = elementKey + "__";
+
+                                if (map.containsKey(keyName)) {
+                                    String existingValue = (String) map.get(keyName);
+                                    map.put(keyName, existingValue + "@@@###" + valueInput);
+                                } else {
+                                    map.put(keyName, valueInput);
+                                }
+
                             }
                         }
                     }
                 }
             }
 
-            Map<String, String> needsSavedData = new LinkedHashMap<>();
             String htmlString = this.html(classC.getHtmlUrl());
-            Map<String, String> indexMap = this.indexMap(htmlString, map, needsSavedData);
+            Map<String, String> indexMap = this.indexMap(htmlString, map);
             if (indexMap.size() > 0) {
                 ExcelTab excelTab = jdbcTemplate.query("SELECT file_url FROM m_excel_tab WHERE id = ?", new Object[]{classC.getExcelId()}, new BeanPropertyRowMapper<>(ExcelTab.class)).stream().findAny().orElse(null);
                 if (excelTab != null) {
-                    MultipartFile multipartFile = this.writeDataToMultipartFile(excelTab.getFileUrl(), indexMap);
-                    if (multipartFile != null) {
-                        NewBladeFile newBladeFile = newIOSSClient.excelToPdf(multipartFile);
+                    List<MultipartFile> files = this.writeDataToMultipartFile(excelTab.getFileUrl(), indexMap);
+                    if (files.size() > 0) {
+                        NewBladeFile newBladeFile = newIOSSClient.excelToPdfs(files);
                         if (newBladeFile != null) {
                             TrialSummaryRecord obj = BeanUtil.copyProperties(dto, TrialSummaryRecord.class);
                             if (obj != null) {
                                 obj.setId(SnowFlakeUtil.getId());
                                 obj.setSummaryNumber(sn);
                                 obj.setPdfUrl(newBladeFile.getPdfUrl());
-                                if (trialSummaryRecordServiceImpl.save(obj) && saveData(needsSavedData, obj, classC)) {
+                                if (trialSummaryRecordServiceImpl.save(obj) && saveData(indexMap, obj, classC)) {
                                     return R.success("操作成功");
                                 }
                             }
@@ -336,64 +364,109 @@ public class TrialSummaryController {
      * @return
      * @throws Exception
      */
-    private MultipartFile writeDataToMultipartFile(String fileUrl, Map<String, String> indexMap) throws Exception {
-        InputStream modInput = CommonUtil.getOSSInputStream(fileUrl);
-        if (modInput != null) {
-            try (Workbook workbook = new XSSFWorkbook(modInput)) {
-                Sheet sheet = workbook.getSheetAt(0);
-                for (Map.Entry<String, String> entry : indexMap.entrySet()) {
-                    String key = entry.getKey();
-                    String value = entry.getValue();
-                    String[] coordinates = key.split("@");
-                    String x = coordinates[0];
-                    String y = coordinates[1];
-
-                    int x1 = Integer.parseInt(x.split(":")[0]) - 1;
-                    int x2 = Integer.parseInt(x.split(":")[1]) - 1;
-                    int y1 = Integer.parseInt(y.split(":")[0]) - 1;
-                    int y2 = Integer.parseInt(y.split(":")[1]) - 1;
-
-                    mergeAndCenterCells(sheet, x1, x2, y1, y2, value);
-                }
-                try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
-                    workbook.write(byteArrayOutputStream);
-                    try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray())) {
-                        return new MockMultipartFile("file", fileUrl, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", byteArrayInputStream);
+    private List<MultipartFile> writeDataToMultipartFile(String fileUrl, Map<String, String> indexMap) throws Exception {
+        /*pageSize分页分组*/
+        Map<String, List<Map.Entry<String, String>>> groupedByPageSize = indexMap.entrySet().stream()
+                .collect(Collectors.groupingBy(entry -> {
+                    String[] indexAndPageSize = entry.getKey().split("@pageSize@");
+                    return indexAndPageSize[1];
+                }));
+
+        List<MultipartFile> files = new LinkedList<>();
+
+        /*每一页视为一份新excel*/
+        for (Map.Entry<String, List<Map.Entry<String, String>>> page : groupedByPageSize.entrySet()) {
+            InputStream modInput = CommonUtil.getOSSInputStream(fileUrl);
+            if (modInput != null) {
+                try (Workbook workbook = new XSSFWorkbook(modInput)) {
+                    Sheet sheet = workbook.getSheetAt(0);
+                    for (Map.Entry<String, String> entry : page.getValue()) {
+                        String key = entry.getKey();
+                        String value = entry.getValue();
+                        String[] indexAndPageSize = key.split("@pageSize@");
+
+                        String index = indexAndPageSize[0];
+
+                        String[] coordinates = index.split("@");
+                        String x = coordinates[0];
+                        String y = coordinates[1];
+
+                        int x1 = Integer.parseInt(x.split(":")[0]) - 1;
+                        int x2 = Integer.parseInt(x.split(":")[1]) - 1;
+                        int y1 = Integer.parseInt(y.split(":")[0]) - 1;
+                        int y2 = Integer.parseInt(y.split(":")[1]) - 1;
+
+                        /*根据位置信息,将value写入excel*/
+                        mergeAndCenterCells(sheet, x1, x2, y1, y2, value);
+                    }
+
+                    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
+                        workbook.write(byteArrayOutputStream);
+                        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray())) {
+                            files.add(new MockMultipartFile("file", fileUrl, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", byteArrayInputStream));
+                        }
                     }
                 }
             }
         }
-        return null;
+        return files;
     }
 
     private void mergeAndCenterCells(Sheet sheet, int x1, int x2, int y1, int y2, String value) {
-        if (!isAlreadyMerged(sheet, x1, x2, y1, y2)) {
-            CellRangeAddress mergedRegion = new CellRangeAddress(y1, y2, x1, x2);
-            sheet.addMergedRegion(mergedRegion);
-        }
+        if (x1 == x2 && y1 == y2) {
+            /*单个单元格,直接写入value,不需要合并*/
+            Row row = sheet.getRow(y1);
+            if (row == null) {
+                row = sheet.createRow(y1);
+            }
 
-        Row row = sheet.getRow(y1);
-        if (row == null) {
-            row = sheet.createRow(y1);
-        }
+            Cell cell = row.createCell(x1);
+            cell.setCellValue(value);
+
+            CellStyle style = sheet.getWorkbook().createCellStyle();
+            style.setAlignment(HorizontalAlignment.CENTER);
+            style.setVerticalAlignment(VerticalAlignment.CENTER);
+
+            style.setBorderBottom(BorderStyle.THIN);
+            style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
+            style.setBorderTop(BorderStyle.THIN);
+            style.setTopBorderColor(IndexedColors.BLACK.getIndex());
+            style.setBorderLeft(BorderStyle.THIN);
+            style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
+            style.setBorderRight(BorderStyle.THIN);
+            style.setRightBorderColor(IndexedColors.BLACK.getIndex());
+
+            cell.setCellStyle(style);
+        } else {
+            /*非单个单元格,判断执行合并操作*/
+            if (!isAlreadyMerged(sheet, x1, x2, y1, y2)) {
+                CellRangeAddress mergedRegion = new CellRangeAddress(y1, y2, x1, x2);
+                sheet.addMergedRegion(mergedRegion);
+            }
 
-        Cell cell = row.createCell(x1);
-        cell.setCellValue(value);
+            Row row = sheet.getRow(y1);
+            if (row == null) {
+                row = sheet.createRow(y1);
+            }
 
-        CellStyle style = sheet.getWorkbook().createCellStyle();
-        style.setAlignment(HorizontalAlignment.CENTER);
-        style.setVerticalAlignment(VerticalAlignment.CENTER);
+            Cell cell = row.createCell(x1);
+            cell.setCellValue(value);
 
-        style.setBorderBottom(BorderStyle.THIN);
-        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
-        style.setBorderTop(BorderStyle.THIN);
-        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
-        style.setBorderLeft(BorderStyle.THIN);
-        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
-        style.setBorderRight(BorderStyle.THIN);
-        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
+            CellStyle style = sheet.getWorkbook().createCellStyle();
+            style.setAlignment(HorizontalAlignment.CENTER);
+            style.setVerticalAlignment(VerticalAlignment.CENTER);
 
-        cell.setCellStyle(style);
+            style.setBorderBottom(BorderStyle.THIN);
+            style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
+            style.setBorderTop(BorderStyle.THIN);
+            style.setTopBorderColor(IndexedColors.BLACK.getIndex());
+            style.setBorderLeft(BorderStyle.THIN);
+            style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
+            style.setBorderRight(BorderStyle.THIN);
+            style.setRightBorderColor(IndexedColors.BLACK.getIndex());
+
+            cell.setCellStyle(style);
+        }
     }
 
     private boolean isAlreadyMerged(Sheet sheet, int x1, int x2, int y1, int y2) {
@@ -438,26 +511,95 @@ public class TrialSummaryController {
      *
      * @param htmlString
      * @param values
-     * @param needsSavedData 需要保存入库的数据(历史记录,其他接口需要使用)
      * @return
      */
-    private Map<String, String> indexMap(String htmlString, Map<String, Object> values, Map<String, String> needsSavedData) {
+    private Map<String, String> indexMap(String htmlString, Map<String, Object> values) {
         Map<String, String> resultIndex = new LinkedHashMap<>();
         Document doc = Jsoup.parse(htmlString);
         String[] tagNames = {"el-input", "el-date-picker", "el-time-picker", "hc-form-select-search",
                 "hc-table-form-upload", "hc-form-checkbox-group", "el-radio-group", "el-select"};
         for (String tagName : tagNames) {
             Elements matchedElements = doc.select(tagName);
-            for (Element element : matchedElements) {
-                String keyName = element.attr("keyname");
-                if (values.containsKey(keyName)) {
-                    String value = values.get(keyName).toString();
-                    String colIndex_1 = element.attr("x1");
-                    String colIndex_2 = element.attr("x2");
-                    String rowIndex_1 = element.attr("y1");
-                    String rowIndex_2 = element.attr("y2");
-                    resultIndex.put(colIndex_1 + ":" + colIndex_2 + "@" + rowIndex_1 + ":" + rowIndex_2, value);
-                    needsSavedData.put(keyName, value);
+
+            for (Map.Entry<String, Object> map : values.entrySet()) {
+                /*key:key_1__*/
+                String key = map.getKey();
+                String value = (String) map.getValue();
+                String[] data = value.split("@@@###");
+
+                /*排序,取data[]个数标签,依次构造数据*/
+                Elements keyElementGroup = new Elements();
+                for (Element element : matchedElements) {
+                    /*模糊匹配,取包含部分key的标签*/
+                    if (element.hasAttr("keyname") && element.attr("keyname").contains(key)) {
+                        keyElementGroup.add(element);
+                    }
+                }
+
+                if (keyElementGroup.size() <= 0) {
+                    continue;
+                }
+
+                /*输入框排序*/
+                Comparator<Element> elementComparator = Comparator
+                        .comparingInt(element -> {
+                            int x1 = Integer.parseInt(element.attr("x1"));
+                            int x2 = Integer.parseInt(element.attr("x2"));
+                            int y1 = Integer.parseInt(element.attr("y1"));
+                            int y2 = Integer.parseInt(element.attr("y2"));
+                            return x1 + x2 + y1 + y2;
+                        });
+                List<Element> sortedElements = keyElementGroup.stream()
+                        .sorted(elementComparator)
+                        .collect(Collectors.toList());
+
+                if (sortedElements.size() < data.length) {
+                    /*html输入框数量 < 试验自检实体数据 ,存在多页,需翻页*/
+                    int countInputAdd = data.length - sortedElements.size();
+                    /*每页需要sortedElements.size()个输入框,共需要countPage页*/
+                    int countPage = (countInputAdd + sortedElements.size()) / sortedElements.size();
+                    countPage += (countInputAdd + sortedElements.size() - 1) % sortedElements.size() > 0 ? 1 : 0;
+
+                    List<Element> sortedElementsAll = new LinkedList<>();
+                    for (int i = 0; i < countPage; i++) {
+                        sortedElementsAll.addAll(sortedElements);
+                    }
+
+                    int pageSize = 0;
+                    Elements sortedKeyElements = new Elements(sortedElementsAll);
+                    for (int i = 0; i < sortedElementsAll.size(); i++) {
+                        String dataResult = data[i];
+                        Element keyElement = sortedKeyElements.get(i);
+                        String colIndex_1 = keyElement.attr("x1");
+                        String colIndex_2 = keyElement.attr("x2");
+                        String rowIndex_1 = keyElement.attr("y1");
+                        String rowIndex_2 = keyElement.attr("y2");
+                        resultIndex.put(colIndex_1 + ":" + colIndex_2 + "@" + rowIndex_1 + ":" + rowIndex_2 + "@pageSize@" + pageSize, dataResult);
+                        if ((i + 1) % sortedElements.size() == 0) {
+                            pageSize++;
+                        }
+                        if (i == data.length - 1) {
+                            break;
+                        }
+                    }
+
+                } else {
+                    /*html输入框数量 >= 试验自检实体数据 ,默认一页,直接写入当前页*/
+                    List<Element> firstThreeElements = sortedElements.stream()
+                            .limit(data.length)
+                            .collect(Collectors.toList());
+                    Elements sortedKeyElements = new Elements(firstThreeElements);
+
+                    for (int i = 0; i < sortedKeyElements.size(); i++) {
+                        String dataResult = data[i];
+                        Element keyElement = sortedKeyElements.get(i);
+                        String colIndex_1 = keyElement.attr("x1");
+                        String colIndex_2 = keyElement.attr("x2");
+                        String rowIndex_1 = keyElement.attr("y1");
+                        String rowIndex_2 = keyElement.attr("y2");
+                        //默认第一页@pageSize@0
+                        resultIndex.put(colIndex_1 + ":" + colIndex_2 + "@" + rowIndex_1 + ":" + rowIndex_2 + "@pageSize@0", dataResult);
+                    }
                 }
             }
         }

+ 2 - 2
blade-service/blade-business/src/main/java/org/springblade/business/feignClient/TaskClientImpl.java

@@ -60,8 +60,8 @@ public class TaskClientImpl implements TaskClient {
     }
 
     @Override
-    public void saveTask(Task task) {
-        taskService.save(task);
+    public boolean saveTask(Task task) {
+        return taskService.save(task);
     }
 
     @Override

+ 76 - 51
blade-service/blade-meter/src/main/java/org/springblade/meter/controller/TaskController.java

@@ -75,6 +75,7 @@ import java.io.*;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.math.BigDecimal;
+import java.sql.SQLException;
 import java.text.SimpleDateFormat;
 import java.time.LocalDate;
 import java.time.Month;
@@ -186,10 +187,10 @@ public class TaskController extends BladeController {
         /*加锁*/
         String redisValue = bladeRedis.get("meter:report:contractId-" + approvalDTO.getContractId());
         if (StringUtils.isNotEmpty(redisValue) && redisValue.equals("1")) {
-            return R.fail(400, "请勿重复提交,10秒后再尝试");
+            return R.fail(400, "请勿重复提交,30秒后再尝试");
         }
         bladeRedis.set("meter:report:contractId-" + approvalDTO.getContractId(), "1");
-        bladeRedis.expire("meter:report:contractId-" + approvalDTO.getContractId(), 10);
+        bladeRedis.expire("meter:report:contractId-" + approvalDTO.getContractId(), 30);
 
         if (ObjectUtil.isNotEmpty(approvalDTO.getType()) && (approvalDTO.getType().equals(1) || approvalDTO.getType().equals(2) || approvalDTO.getType().equals(3) || approvalDTO.getType().equals(4))) {
             if (approvalDTO.getType().equals(1)) {
@@ -571,7 +572,16 @@ public class TaskController extends BladeController {
         task.setFixedFlowId(ObjectUtil.isNotEmpty(approvalDTO.getFixedFlowId()) ? Long.parseLong(approvalDTO.getFixedFlowId()) : 0L);
         task.setStatus(1); //待审批
         task.setIsDeleted(0);
-        taskClient.saveTask(task);
+
+        try {
+            boolean taskBool = taskClient.saveTask(task);
+            if (!taskBool) {
+                throw new ServiceException("任务创建失败");
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new ServiceException("任务创建失败:" + e.getMessage());
+        }
 
         /*副任务*/
         /*1.非预设流程*/
@@ -737,14 +747,15 @@ public class TaskController extends BladeController {
     @ApiOperationSupport(order = 3)
     @ApiOperation(value = "任务废除(任务撤销、驳回审批)", notes = "按一期废除,即按整条任务废除(中期计量申请、材料计量单、开工预付款计量单、变更令、任务查看-废除任务)")
     @PushMessage(clientId = ClientIdConstant.METER_CLIENT_ID)
+    @Transactional(rollbackFor = Exception.class)
     public R<Object> repeal(@RequestBody TaskRepealDTO taskRepealDTO) throws JsonProcessingException {
         /*加锁*/
         String redisValue = bladeRedis.get("meter:repeal:user:" + SecureUtil.getUserId());
         if (StringUtils.isNotEmpty(redisValue) && redisValue.equals("1")) {
-            return R.fail(400, "请勿重复提交,10秒后再尝试");
+            return R.fail(400, "请勿重复提交,30秒后再尝试");
         }
         bladeRedis.set("meter:repeal:user:" + SecureUtil.getUserId(), "1");
-        bladeRedis.expire("meter:repeal:user:" + SecureUtil.getUserId(), 10);
+        bladeRedis.expire("meter:repeal:user:" + SecureUtil.getUserId(), 30);
 
         if (ObjectUtil.isNotEmpty(taskRepealDTO) && ObjectUtil.isNotEmpty(taskRepealDTO.getTaskId())) {
             if (ObjectUtil.isNotEmpty(taskRepealDTO.getMeterTaskRepealDesc()) && taskRepealDTO.getMeterTaskRepealDesc().length() > 1000) {
@@ -805,9 +816,13 @@ public class TaskController extends BladeController {
                                 .set(ContractMeterPeriod::getApproveStatus, 0)
                                 .eq(ContractMeterPeriod::getId, periodId));
 
-                        /*删除业务复制数据taskVO*/
-                        jdbcTemplate.execute("DELETE FROM s_middle_meter_apply_task WHERE contract_period_id = '" + periodId + "' AND task_id = " + taskRepealDTO.getTaskId());
-                        jdbcTemplate.execute("DELETE FROM s_inventory_form_apply_task WHERE contract_period_id = '" + periodId + "' AND task_id = " + taskRepealDTO.getTaskId());
+                        try {
+                            /*删除业务复制数据taskVO*/
+                            jdbcTemplate.execute("DELETE FROM s_middle_meter_apply_task WHERE contract_period_id = '" + periodId + "' AND task_id = " + taskRepealDTO.getTaskId());
+                            jdbcTemplate.execute("DELETE FROM s_inventory_form_apply_task WHERE contract_period_id = '" + periodId + "' AND task_id = " + taskRepealDTO.getTaskId());
+                        } catch (Exception e) {
+                            throw new ServiceException("删除业务复制数据taskVO失败");
+                        }
 
                         /*还原修改过的清单信息*/
                         List<InventoryFormApply> restoreInventoryFormApplyList = new ArrayList<>();
@@ -866,7 +881,11 @@ public class TaskController extends BladeController {
                                 .eq(MeterPeriod::getId, periodId));
 
                         /*删除业务复制数据taskVO*/
-                        jdbcTemplate.execute("DELETE FROM s_material_meter_form_task WHERE meter_period_id = '" + periodId + "' AND task_id = " + taskRepealDTO.getTaskId());
+                        try {
+                            jdbcTemplate.execute("DELETE FROM s_material_meter_form_task WHERE meter_period_id = '" + periodId + "' AND task_id = " + taskRepealDTO.getTaskId());
+                        } catch (Exception e) {
+                            throw new ServiceException("删除业务复制数据taskVO失败");
+                        }
 
                     } else if (task.getMeterTaskType().equals(3)) {
                         /*==================== 开工预付款计量单 ====================*/
@@ -890,7 +909,11 @@ public class TaskController extends BladeController {
                                 .eq(MeterPeriod::getId, periodId));
 
                         /*删除业务复制数据taskVO*/
-                        jdbcTemplate.execute("DELETE FROM s_start_pay_meter_form_task WHERE meter_period_id = '" + periodId + "' AND task_id = " + taskRepealDTO.getTaskId());
+                        try {
+                            jdbcTemplate.execute("DELETE FROM s_start_pay_meter_form_task WHERE meter_period_id = '" + periodId + "' AND task_id = " + taskRepealDTO.getTaskId());
+                        } catch (Exception e) {
+                            throw new ServiceException("删除业务复制数据taskVO失败");
+                        }
 
                     } else if (task.getMeterTaskType().equals(4)) {
                         for (String dataId : periodId.split(",")) {
@@ -1352,7 +1375,8 @@ public class TaskController extends BladeController {
     @GetMapping("/data/detail")
     @ApiOperationSupport(order = 6)
     @ApiOperation(value = "任务数据信息详情", notes = "传入任务id,数据dataId")
-    public R<TaskDataDetailVO> dataDetail(@RequestParam String id, @RequestParam String dataId) throws JsonProcessingException {
+    public R<TaskDataDetailVO> dataDetail(@RequestParam String id, @RequestParam String dataId) throws
+            JsonProcessingException {
         if (ObjectUtil.isEmpty(id) || ObjectUtil.isEmpty(dataId)) {
             throw new ServiceException("任务id、数据id不能为空");
         }
@@ -1655,7 +1679,8 @@ public class TaskController extends BladeController {
     @PostMapping("/data/inventoryFormApplyTask/update")
     @ApiOperationSupport(order = 8)
     @ApiOperation(value = "清单数据修改", notes = "传入InventoryFormApplyTaskDTO")
-    public R<Object> dataInventoryFormApplyTaskUpdate(@RequestBody InventoryFormApplyTaskDTO dto) throws JsonProcessingException {
+    public R<Object> dataInventoryFormApplyTaskUpdate(@RequestBody InventoryFormApplyTaskDTO dto) throws
+            JsonProcessingException {
         if (ObjectUtil.isEmpty(dto.getTaskId())) {
             throw new ServiceException("未获取到taskId");
         }
@@ -2207,8 +2232,8 @@ public class TaskController extends BladeController {
             /*最终审批轮次*/
             if (isCurrentUserLastApprove) {
                 //TODO 重新生成报表,执行电签(电签失败直接return或抛出异常,不修改下方状态)
-                if(task.getMeterTaskType()==3 || task.getMeterTaskType()==2){ //2材料,3开工
-                    MaterialStartStatement materialS = materialStartStatementService.getBaseMapper().selectOne(Wrappers.<MaterialStartStatement>lambdaQuery().eq(MaterialStartStatement::getContractId, task.getContractId()).eq(MaterialStartStatement::getMeterPeriodId, task.getFormDataId()).eq(MaterialStartStatement::getType, task.getMeterTaskType()-1));
+                if (task.getMeterTaskType() == 3 || task.getMeterTaskType() == 2) { //2材料,3开工
+                    MaterialStartStatement materialS = materialStartStatementService.getBaseMapper().selectOne(Wrappers.<MaterialStartStatement>lambdaQuery().eq(MaterialStartStatement::getContractId, task.getContractId()).eq(MaterialStartStatement::getMeterPeriodId, task.getFormDataId()).eq(MaterialStartStatement::getType, task.getMeterTaskType() - 1));
                     if (materialS == null || Func.isNull(materialS)) {
                         MeterPeriod me = periodService.getById(task.getFormDataId());
                         MaterialStartStatement data = new MaterialStartStatement();
@@ -2218,7 +2243,7 @@ public class TaskController extends BladeController {
                         data.setPrintDate(me.getFormPrintDate());
                         data.setPeriodNumber(me.getPeriodNumber());
                         data.setProjectId(me.getProjectId());
-                        if(task.getMeterTaskType()==2){
+                        if (task.getMeterTaskType() == 2) {
                             data.setRepaymentCause("材料预付款");
                             data.setStatementName("材料预付款--" + me.getPeriodName());
                             data.setType(1);
@@ -2230,14 +2255,14 @@ public class TaskController extends BladeController {
                             data.setType(2);
                         }
                         materialStartStatementService.saveOrUpdate(data);
-                        reportId = data.getId()+"";
+                        reportId = data.getId() + "";
                     } else {
-                        reportId = materialS.getId()+"";
+                        reportId = materialS.getId() + "";
                     }
                 } else if (task.getMeterTaskType() == 1) { // 1中间
                     // 获取总金额
                     MiddleMeterApply middleMeterApply = new MiddleMeterApply();
-                    middleMeterApply.setContractId(Func.toLong(task.getContractId()) );
+                    middleMeterApply.setContractId(Func.toLong(task.getContractId()));
                     middleMeterApply.setContractPeriodId(Func.toLong(task.getFormDataId()));
                     BigDecimal currentMeterMoney = middleMeterApplyService.getCurrentMeterMoney(middleMeterApply);
 
@@ -2256,9 +2281,9 @@ public class TaskController extends BladeController {
                         inData2.setProjectId(me.getProjectId());
                         inData2.setPayMoney(currentMeterMoney);
                         interimPayCertificateService.save(inData2);
-                        reportId = inData2.getId()+"";
-                    }else{
-                        reportId = inData.getId()+"";
+                        reportId = inData2.getId() + "";
+                    } else {
+                        reportId = inData.getId() + "";
                     }
                 }
                 /**计量公式执行 0中间,1材料,2开工*/
@@ -2275,8 +2300,8 @@ public class TaskController extends BladeController {
                 aopParamsSet.add(param);
             }
             //
-            if(reportId!=null && StringUtils.isNotEmpty(reportId) && (task.getMeterTaskType()==3 ||task.getMeterTaskType()==1 || task.getMeterTaskType()==2)){
-                meterPdfInfo(reportId + "", task.getMeterTaskType()-1);
+            if (reportId != null && StringUtils.isNotEmpty(reportId) && (task.getMeterTaskType() == 3 || task.getMeterTaskType() == 1 || task.getMeterTaskType() == 2)) {
+                meterPdfInfo(reportId + "", task.getMeterTaskType() - 1);
             }
 
             return R.data(200, aopParamsSet, "操作成功");
@@ -2692,7 +2717,7 @@ public class TaskController extends BladeController {
                 Report report = generateReport(Long.parseLong(reportId), type);
                 return generateReportsPdf(report);
             }
-        }catch (Exception e){
+        } catch (Exception e) {
             e.printStackTrace();
         }
         return R.fail("计算失败");
@@ -2764,10 +2789,10 @@ public class TaskController extends BladeController {
                                         if (row != null) {
                                             Cell cell = row.getCell(x1 - 1);
                                             if (cell != null) {
-                                                String value=dataMap.getOrDefault(keys, StringPool.EMPTY).toString();
-                                                if(value.startsWith("http")){
+                                                String value = dataMap.getOrDefault(keys, StringPool.EMPTY).toString();
+                                                if (value.startsWith("http")) {
                                                     InputStream imageIn = CommonUtil.getOSSInputStream(value);
-                                                    if(imageIn!=null) {
+                                                    if (imageIn != null) {
                                                         byte[] bytes = CommonUtil.compressImage(IOUtils.toByteArray(imageIn));
                                                         CreationHelper helper = workbook.getCreationHelper();
                                                         ClientAnchor anchor = helper.createClientAnchor();
@@ -2777,7 +2802,7 @@ public class TaskController extends BladeController {
                                                         pict.resize(1, 1);
                                                         CollectionUtils.imageOrientation(sheet, anchor, new DataVO(x1 - 1, y1 - 1));
                                                     }
-                                                }else {
+                                                } else {
                                                     cell.setCellValue(value);
                                                 }
                                             } else {
@@ -2789,7 +2814,7 @@ public class TaskController extends BladeController {
                                 /*设置表头*/
                                 setTitle(sheet, tile);
                                 /*添加电签*/
-                                setDQInfo(sheet,rs.getUrl(),tile);
+                                setDQInfo(sheet, rs.getUrl(), tile);
                                 //去掉表格虚线
                                 sheet.setPrintGridlines(false);
                                 //设置 整个工作表为一页
@@ -2797,7 +2822,7 @@ public class TaskController extends BladeController {
                                 sheet.getPrintSetup().setPaperSize(PrintSetup.A4_PAPERSIZE);
                                 ByteArrayOutputStream out = new ByteArrayOutputStream();
                                 workbook.write(out);
-                               // workbook.write(new FileOutputStream(rs.getExcelPath()));
+                                // workbook.write(new FileOutputStream(rs.getExcelPath()));
                                 com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(new ByteArrayInputStream(out.toByteArray()));
                                 out.reset();
                                 wb.save(out, SaveFormat.PDF);
@@ -2817,11 +2842,11 @@ public class TaskController extends BladeController {
                         if (reader != null) reader.close();
                         doc.close();
                         rs.setPdfOssPath(CompletableFuture.supplyAsync(() -> {
-                            String url="无效链接";
+                            String url = "无效链接";
                             try {
                                 BladeFile bladeFile = newIOSSClient.uploadFile(rs.getName() + SnowFlakeUtil.getId() + ".pdf", rs.getPdfPath());
-                                 url = bladeFile.getLink();
-                            }catch (Exception e){
+                                url = bladeFile.getLink();
+                            } catch (Exception e) {
                                 e.printStackTrace();
                             }
                             return url;
@@ -2845,13 +2870,13 @@ public class TaskController extends BladeController {
     }
 
     // 添加电签任务列表
-    public void addSignTaskBatch(Report report){
+    public void addSignTaskBatch(Report report) {
         try {
-            String sql=" insert INTO u_task_batch(id,task_parallel_id,json_data,create_user,create_dept,create_time,update_user,update_time,status,is_deleted,nick_name) "+
-                    " SELECT a.id,a.process_instance_id,json_object('approvalFileList',json_array(),'approvalType',4+b.meter_task_type,'comment','','flag','OK','formDataId',b.form_data_id,'parallelProcessInstanceId',a.parallel_process_instance_id,'pass',true,'taskId',b.id) as  json_data,a.task_user,a.create_dept,a.create_time,a.update_user,a.update_time,1 as status,0 as is_deleted,a.task_user_name as nick_name "+
-                    " from u_task_parallel a,u_task b where a.process_instance_id=b.process_instance_id and b.form_data_id="+report.getPeriodId()+" and b.meter_task_type="+(Func.toInt(report.getType())+1);
+            String sql = " insert INTO u_task_batch(id,task_parallel_id,json_data,create_user,create_dept,create_time,update_user,update_time,status,is_deleted,nick_name) " +
+                    " SELECT a.id,a.process_instance_id,json_object('approvalFileList',json_array(),'approvalType',4+b.meter_task_type,'comment','','flag','OK','formDataId',b.form_data_id,'parallelProcessInstanceId',a.parallel_process_instance_id,'pass',true,'taskId',b.id) as  json_data,a.task_user,a.create_dept,a.create_time,a.update_user,a.update_time,1 as status,0 as is_deleted,a.task_user_name as nick_name " +
+                    " from u_task_parallel a,u_task b where a.process_instance_id=b.process_instance_id and b.form_data_id=" + report.getPeriodId() + " and b.meter_task_type=" + (Func.toInt(report.getType()) + 1);
             jdbcTemplate.execute(sql);
-        }catch (Exception e){
+        } catch (Exception e) {
             e.printStackTrace();
         }
     }
@@ -2875,7 +2900,7 @@ public class TaskController extends BladeController {
     }
 
     // 添加电签信息数据
-    public void setDQInfo(Sheet sheet, String htmlUrl,String title) {
+    public void setDQInfo(Sheet sheet, String htmlUrl, String title) {
         String file_path = "/www/wwwroot/Users/hongchuangyanfa/Desktop/";//CollectionUtils.getSysLocalFileUrl();
         // 添加电签关键字Id
         String sys_file_net_url = ParamCache.getValue(CommonConstant.SYS_FILE_NET_URL);
@@ -2892,18 +2917,18 @@ public class TaskController extends BladeController {
             String htmlString = IoUtil.readToString(fileInputStream);
             org.jsoup.nodes.Document htmldoc = Jsoup.parse(htmlString);
             Elements dqlist = htmldoc.getElementsByAttribute("dqid");
-            if(dqlist!=null && dqlist.size()>0){
+            if (dqlist != null && dqlist.size() > 0) {
                 dqlist.forEach(element -> {
                     System.out.println(element.hasAttr("y1"));
-                    int y1=0;
-                    int x1=0;
-                    if(!element.hasAttr("y1") && !element.hasAttr("x1")){
+                    int y1 = 0;
+                    int x1 = 0;
+                    if (!element.hasAttr("y1") && !element.hasAttr("x1")) {
                         Element element2 = element.children().get(0);
                         y1 = Func.toInt(element2.attr("y1"));
                         x1 = Func.toInt(element2.attr("x1"));
-                    }else{
-                         y1 = Func.toInt(element.attr("y1"));
-                         x1 = Func.toInt(element.attr("x1"));
+                    } else {
+                        y1 = Func.toInt(element.attr("y1"));
+                        x1 = Func.toInt(element.attr("x1"));
                     }
 
                     Row row = sheet.getRow(y1 - 1);
@@ -2921,19 +2946,19 @@ public class TaskController extends BladeController {
                             Font newFont = workbook.createFont();
                             newFont.setFontHeightInPoints(workbook.getFontAt(cell.getCellStyle().getFontIndex()).getFontHeightInPoints());
 
-                            if (dataInfo==null||StringUtil.isEmpty(dataInfo)){
+                            if (dataInfo == null || StringUtil.isEmpty(dataInfo)) {
                                 cell.setCellValue(dqVal);
                                 newFont.setFontHeightInPoints((short) 1);
                                 newFont.setColor(IndexedColors.WHITE.getIndex());
                                 cellStyle.setFont(newFont);
-                            }else{
-                                String lastData = dataInfo+"*"+dqVal;
+                            } else {
+                                String lastData = dataInfo + "*" + dqVal;
                                 RichTextString richString = new XSSFRichTextString(lastData);
                                 richString.clearFormatting();
-                                richString.applyFont(0,dataInfo.length(),newFont);
+                                richString.applyFont(0, dataInfo.length(), newFont);
                                 newFont.setFontHeightInPoints((short) 1);
                                 newFont.setColor(IndexedColors.WHITE.getIndex());
-                                richString.applyFont(dataInfo.length(),lastData.length(),newFont);
+                                richString.applyFont(dataInfo.length(), lastData.length(), newFont);
                                 cell.setCellValue(richString);
                             }
                             cell.setCellStyle(cellStyle);