chenrui
2025-03-13 f0afb2b17f2f6e13925ffe1b6fd8c8ae724aec0e
inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsReportServiceImpl.java
@@ -2,8 +2,7 @@
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.aspose.words.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
@@ -20,26 +19,22 @@
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.ruoyi.common.config.MinioConfig;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.enums.AttachmentType;
import com.ruoyi.common.mapper.AttachmentTableMapper;
import com.ruoyi.common.pojo.AttachmentTable;
import com.ruoyi.common.service.AttachmentTableService;
import com.ruoyi.common.utils.QueryWrappers;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.inspect.dto.ReportPageDto;
import com.ruoyi.inspect.mapper.*;
import com.ruoyi.inspect.mapper.InsOrderMapper;
import com.ruoyi.inspect.mapper.InsOrderStateMapper;
import com.ruoyi.inspect.mapper.InsReportApproveConfigMapper;
import com.ruoyi.inspect.mapper.InsReportMapper;
import com.ruoyi.inspect.pojo.InsOrder;
import com.ruoyi.inspect.pojo.InsOrderState;
import com.ruoyi.inspect.pojo.InsReport;
import com.ruoyi.process.pojo.ProcessReport;
import com.ruoyi.inspect.service.InsReportService;
import com.ruoyi.process.mapper.ProcessReportMapper;
import com.ruoyi.process.pojo.ProcessReport;
import com.ruoyi.system.mapper.UserMapper;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
@@ -67,6 +62,7 @@
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
@@ -83,16 +79,6 @@
@Slf4j
public class InsReportServiceImpl extends ServiceImpl<InsReportMapper, InsReport>
        implements InsReportService {
    @Resource
    private AttachmentTableMapper attachmentTableMapper;
    @Resource
    private AttachmentTableService attachmentTableService;
    @Resource
    private MinioConfig minioConfig;
    @Resource
@@ -145,13 +131,14 @@
            }
        }
        QueryWrapper<ReportPageDto> wrapper = QueryWrappers.queryWrappers(reportPageDto);
        if(Objects.nonNull(reportPageDto) && Objects.nonNull(reportPageDto.getCreateTimeRange())){
        if(Objects.nonNull(reportPageDto.getCreateTimeRange())){
            wrapper.gt(reportPageDto.getCreateTimeRange().size()>1,"create_time",reportPageDto.getCreateTimeRange().get(0))
                    .lt(reportPageDto.getCreateTimeRange().size()>1,"create_time",reportPageDto.getCreateTimeRange().get(1));
        }
        IPage<ReportPageDto> iPage = insReportMapper.pageInsReport(page, wrapper, laboratory);
        return iPage;
    }
    @Override
    public int inReport(String url, Integer id) {
@@ -163,20 +150,17 @@
    // 还原
    @Override
    public void upReportUrl(Integer id,Integer type) {
        List<AttachmentTable> attachmentTables = attachmentTableMapper.selectList(new LambdaQueryWrapper<AttachmentTable>()
                .eq(AttachmentTable::getSubclassId, id)
                .eq(AttachmentTable::getOtherTableName, AttachmentType.getAttachmentValue(type))
                .orderByAsc(AttachmentTable::getId));
        if(CollectionUtils.isNotEmpty(attachmentTables)) {
           // 获取所有的id
            List<Integer> collect = attachmentTables.stream().map(AttachmentTable::getId).collect(Collectors.toList());
            // 除了第一个全部删除 删除所有的附件
            collect.remove(0);
            if(collect.size() > 0) {
                attachmentTableMapper.deleteBatchIds(collect);
    public int upReportUrl(Integer id) {
        InsReport insReport = insReportMapper.selectById(id);
        String fileName = insReport.getUrlS().replace("/word/", "");
        if(Strings.isNotEmpty(fileName)) {
            String path = wordUrl + File.separator + fileName;
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
        }
        return insReportMapper.update(null, Wrappers.<InsReport>lambdaUpdate().eq(InsReport::getId, id).set(InsReport::getUrlS, null));
    }
    @Override
@@ -223,91 +207,40 @@
    //提交
    @Override
    public int writeReport(Integer id) {
        int userId = Integer.parseInt(SecurityUtils.getUserId() + "");
        InsReport insReport = insReportMapper.selectById(id);
        insReport.setId(id);
        insReport.setState(1);
        insReport.setWriteTime(LocalDateTime.now());//提交时间
        insReport.setWriteUserId(userId);//提交人
        insReport.setWriteUserId(Integer.getInteger(SecurityUtils.getUserId().toString()));//提交人
        //获取提交人的签名地址
        String signatureUrl;
        try {
            signatureUrl = userMapper.selectById(Integer.getInteger(SecurityUtils.getUserId().toString())).getSignatureUrl();
        } catch (Exception e) {
            throw new ErrorException("找不到编制人的签名");
        }
        //系统生成报告地址
        String url = insReport.getUrl();
        //手动上传报告地址
        String urlS = insReport.getUrlS();
        wordInsertUrl(new HashMap<String, Object>() {{
            put("writeUrl", new FilePictureRenderData(100,50,imgUrl + "/" + signatureUrl));
        }}, (urlS == null ? url : urlS).replace("/word", wordUrl));
        // 修改临时pdf
        String tempUrlPdf = wordToPdfTemp((StrUtil.isBlank(urlS) ? url : urlS).replace("/word", wordUrl));
        insReport.setTempUrlPdf("/word/" + tempUrlPdf);
        return insReportMapper.updateById(insReport);
    }
    /**
     * 创建临时文件
     * @param inputStream 输入流
     * @param suffix 后缀
     * @return
     */
    public String temporaryFile(InputStream inputStream,String suffix) {
        String tempFilePath = "";
        try {
            File tempFile = File.createTempFile(UUID.randomUUID().toString(), suffix);
            tempFile.deleteOnExit();
            // 将输入流内容赋值的临时文件
            try(FileOutputStream fileInputStream = new FileOutputStream(tempFile)) {
                byte[] bytes = new byte[1024];
                int len;
                while((len = inputStream.read(bytes)) != -1) {
                    fileInputStream.write(bytes,0,len);
                }
                // 获取临时文件的路径
                tempFilePath = tempFile.getAbsolutePath();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return tempFilePath;
    }
    /**
     * 将文件上传到Minio
     * @return
     */
    public void  uploadMinio(String url,Integer id) {
        String suffix = url.substring(url.lastIndexOf("."));
        // 重新上传到MinIo
        File file = new File(url);
        String fileName = UUID.randomUUID().toString() + suffix;
        FileInputStream stream = null;
        try {
            MinioClient build = MinioClient.builder().endpoint(minioConfig.getEndpoint(), minioConfig.getPort(), minioConfig.getSecure())
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                    .build();
            stream = new FileInputStream(file);
            build.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .object(fileName)
                            .stream(stream, file.length(), -1)
                            .contentType("application/octet-stream")
                            .userMetadata(Collections.singletonMap("Content-Disposition", "attachment; filename=\"" + fileName + "\""))
                            .build()
            );
            // 保存到数据库
            AttachmentTable attachmentTable = new AttachmentTable();
            attachmentTable.setBucketName(minioConfig.getBucketName());
            attachmentTable.setFileName(fileName);
            attachmentTable.setSubclassId(id);
            attachmentTable.setOtherTableName(AttachmentType.getAttachmentValue(1));
            attachmentTableMapper.insert(attachmentTable);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //审核
    @Override
    public int examineReport(Integer id, Integer isExamine, String examineTell) {
        int userId = Integer.parseInt(SecurityUtils.getUserId() + "");
        InsReport insReport = insReportMapper.selectById(id);
        insReport.setIsExamine(isExamine);
        if (ObjectUtils.isNotEmpty(examineTell)) {
            insReport.setExamineTell(examineTell);
        }
        insReport.setExamineUserId(userId);//审核人
        insReport.setExamineUserId(Integer.getInteger(SecurityUtils.getUserId().toString()));//审核人
        insReport.setExamineTime(LocalDateTime.now());//审核时间
        if (isExamine == 0) {
            //如果审核不通过
@@ -338,13 +271,12 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int ratifyReport(Integer id, Integer isRatify, String ratifyTell) {
        int userId = Integer.parseInt(SecurityUtils.getUserId() + "");
        InsReport insReport = insReportMapper.selectById(id);
        insReport.setIsRatify(isRatify);
        if (ObjectUtils.isNotEmpty(ratifyTell)) {
            insReport.setRatifyTell(ratifyTell);
        }
        insReport.setRatifyUserId(userId);//批准人
        insReport.setRatifyUserId(Integer.getInteger(SecurityUtils.getUserId().toString()));//批准人
        insReport.setRatifyTime(LocalDateTime.now());//批准时间
        if (isRatify == 0) {
            //如果批准不通过
@@ -523,9 +455,8 @@
    @Override
    public Map<String, Object> getReportCountInfo(ReportPageDto reportPageDto) {
        int userId = Integer.parseInt(SecurityUtils.getUserId() + "");
        HashMap<String, Object> map = new HashMap<>();
        User user = userMapper.selectById(userId);//当前登录的人
        User user = userMapper.selectById(SecurityUtils.getUserId());//当前登录的人
        //获取当前人所属实验室id
        String departLimsId = user.getDepartLimsId();
        String laboratory = null;
@@ -538,7 +469,7 @@
            }
        }
        QueryWrapper<ReportPageDto> wrapper = QueryWrappers.queryWrappers(reportPageDto);
        if(Objects.nonNull(reportPageDto) && Objects.nonNull(reportPageDto.getCreateTimeRange())){
        if(Objects.nonNull(reportPageDto.getCreateTimeRange())){
            wrapper.gt(reportPageDto.getCreateTimeRange().size()>1,"create_time",reportPageDto.getCreateTimeRange().get(0))
                    .lt(reportPageDto.getCreateTimeRange().size()>1,"create_time",reportPageDto.getCreateTimeRange().get(1));
@@ -553,7 +484,7 @@
    @Transactional(rollbackFor = Exception.class)
    public void batchApprovalReport(List<Integer> ids) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        Integer userId = Integer.parseInt(SecurityUtils.getUserId() + "");
        Integer userId = Integer.parseInt(SecurityUtils.getUserId().toString());
        String key = SYNC_REPORT_KEY_PREFIX+userId;
        //执行前删除之前的keys
        deleteRedisKeys(key);
@@ -682,7 +613,7 @@
    @Override
    public Map<String, Object> getBatchApprovalProgress() {
        Integer userId =  Integer.parseInt(SecurityUtils.getUserId() + "");
        Integer userId = Integer.parseInt(SecurityUtils.getUserId().toString());
        String key = SYNC_REPORT_KEY_PREFIX + userId;
        Map<String, Object> map = new HashMap<>();
        map.put("hasProgress",false);
@@ -773,7 +704,7 @@
     */
    public String wordToPdfTemp(String path) {
        try {
            return wordToPdf(path, path.replace(".docx", ""));
            return wordToPdf(path, path.replace(".docx", ".pdf"));
        } catch (Exception e) {
            throw new ErrorException("转换失败");
        }
@@ -793,14 +724,13 @@
            //生成一个空的PDF文件
            File file;
            //判断是否是进厂报告
            file = File.createTempFile(pdfPath, ".pdf");
            file.deleteOnExit();
            file = new File(pdfPath);
            os = new FileOutputStream(file);
            //要转换的word文件
            com.aspose.words.Document doc = new com.aspose.words.Document(wordPath);
            doc.save(os, SaveFormat.PDF);
            String name = file.getName();
            return file.getAbsolutePath();
            return file.getName();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
@@ -814,6 +744,73 @@
        }
        return null;
    }
//    @Override
//    public void wordToPdf(String path, String sealUrl) {
//        CompletableFuture.supplyAsync(() -> {
//            try {
//                wordToPdf(path, path.replace(".docx", ".pdf"), sealUrl);
//                return null;
//            } catch (Exception e) {
//                throw new ErrorException("转换失败");
//            }
//        }).thenAccept(res -> {
//        }).exceptionally(e -> {
//            e.printStackTrace();
//            return null;
//        });
//    }
//    public String wordToPdf(String wordPath, String pdfPath, String sealUrl) {
//        FileOutputStream os = null;
//        try {
//            //凭证 不然切换后有水印
////            InputStream inputStream = this.getClass().getResourceAsStream("/lib/license.xml");
//            /*String url;
//            try {
//                InputStream inputStream = this.getClass().getResourceAsStream("/lib/license.xml");
//                File file = File.createTempFile("temp", ".tmp");
//                OutputStream outputStream = new FileOutputStream(file);
//                IOUtils.copy(inputStream, outputStream);
//                url = file.getAbsolutePath();
//            } catch (FileNotFoundException e) {
//                throw new ErrorException("找不到模板文件");
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }*/
//            InputStream is = new ClassPathResource("/lib/license.xml").getInputStream();
//            License license = new License();
//            license.setLicense(is);
//            if (!license.getIsLicensed()) {
//                System.out.println("License验证不通过...");
//                return null;
//            }
//            //生成一个空的PDF文件
//            File file = new File(pdfPath.replace(".pdf", "-1.pdf"));
//            os = new FileOutputStream(file);
//            //要转换的word文件
//            com.aspose.words.Document doc = new com.aspose.words.Document(wordPath);
//            doc.save(os, SaveFormat.PDF);
//
//            //添加骑缝章
//            stamperCheckMarkPDF(pdfPath.replace(".pdf", "-1.pdf"), pdfPath, imgUrl + "/" + sealUrl);
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (os != null) {
//                try {
//                    os.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return null;
//    }
    /**
     * 切割图片
@@ -874,3 +871,9 @@
        stamp.close();
    }
}