Browse Source

feature 增加调查问卷导出功能

xiahan 1 year ago
parent
commit
fa43800aea

+ 1 - 1
rw-training/training-common/src/main/java/com/rongwei/trainingcommon/sys/dao/DemandSurveyContentDao.java

@@ -12,7 +12,7 @@ import java.util.List;
  */
 public interface DemandSurveyContentDao extends BaseMapper<DemandSurveyContentDo> {
 
-    List<TrainingDemandVo> getSurveyContent(@Param("surverId") String surverId);
+    List<TrainingDemandVo> getSurveyContent(@Param("surverId") String surverId,@Param("userId") String userId);
 
 }
 

+ 5 - 0
rw-training/training-common/src/main/java/com/rongwei/trainingcommon/sys/dao/TraningCommonDao.java

@@ -1,5 +1,7 @@
 package com.rongwei.trainingcommon.sys.dao;
 
+import com.rongwei.rwadmincommon.system.vo.SysUserVo;
+import com.rongwei.training.vo.DemandUserVo;
 import com.rongwei.training.vo.WordEmpInfoVo;
 import org.apache.ibatis.annotations.Param;
 import org.apache.ibatis.annotations.Select;
@@ -21,4 +23,7 @@ public interface TraningCommonDao {
     List<WordEmpInfoVo> getEmpInfo(@Param("empIds") List<String> empId);
 
     Set<String> getAllUserIdAndNameByOrgId(@Param("orgIds") List<String> orgIds);
+
+
+    List<DemandUserVo> getDemandUserInfo(@Param("userIds") List<String> userIds);
 }

+ 38 - 0
rw-training/training-common/src/main/java/com/rongwei/trainingcommon/sys/service/ExportTrainingDemandService.java

@@ -0,0 +1,38 @@
+package com.rongwei.trainingcommon.sys.service;
+
+import com.aspose.words.Document;
+import com.aspose.words.MailMergeCleanupOptions;
+import com.aspose.words.SaveFormat;
+import com.aspose.words.net.System.Data.DataTable;
+import com.rongwei.rwcommon.base.exception.CustomException;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+
+import javax.servlet.http.HttpServletResponse;
+
+
+public interface ExportTrainingDemandService {
+    void generatePaper(String surveyId, HttpServletResponse response);
+
+    void  generateUserPaper(String surveyId,String userId, HttpServletResponse response);
+
+    default void exportSingleWord(String[] wordKey, String[] wordValue, DataTable dataTable, HttpServletResponse response, String tempPatch) {
+        try {
+            Resource resource = new ClassPathResource(tempPatch);
+            Document doc = new Document(resource.getInputStream());
+            doc.getMailMerge().execute(wordKey, wordValue);
+            doc.getMailMerge().executeWithRegions(dataTable);
+            //自定义字段
+            doc.getMailMerge().setUseNonMergeFields(true);
+            //去除未替换到的域,防止页面显示域代码
+            doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS);
+            doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_TABLE_ROWS);
+            doc.getMailMerge().deleteFields();
+            response.setContentType("application/octet-stream;charset=ISO8859-1");
+            response.setHeader("Content-Disposition", "attachment;filename=paper.docx");
+            doc.save(response.getOutputStream(), SaveFormat.DOCX);
+        } catch (Exception e) {
+            throw new CustomException("文件导出异常");
+        }
+    }
+}

+ 218 - 0
rw-training/training-common/src/main/java/com/rongwei/trainingcommon/sys/service/impl/ExportTrainingDemandServiceImpl.java

@@ -0,0 +1,218 @@
+package com.rongwei.trainingcommon.sys.service.impl;
+
+import com.aspose.words.net.System.Data.DataRow;
+import com.aspose.words.net.System.Data.DataTable;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.rongwei.rwadmincommon.system.domain.SysUserDo;
+import com.rongwei.rwadmincommon.system.vo.SysUserOrgVo;
+import com.rongwei.rwadmincommon.system.vo.SysUserVo;
+import com.rongwei.rwcommon.utils.StringUtils;
+import com.rongwei.training.domain.TrainingDemandSurveyBackupsDo;
+import com.rongwei.training.domain.TrainingDemandSurveyDo;
+import com.rongwei.training.vo.DemandUserVo;
+import com.rongwei.training.vo.TrainingDemandVo;
+import com.rongwei.trainingcommon.sys.dao.DemandSurveyContentDao;
+import com.rongwei.trainingcommon.sys.dao.TrainingDemandSurveyBackupsDao;
+import com.rongwei.trainingcommon.sys.dao.TrainingDemandSurveyDao;
+import com.rongwei.trainingcommon.sys.dao.TraningCommonDao;
+import com.rongwei.trainingcommon.sys.service.ExportTrainingDemandService;
+import lombok.SneakyThrows;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import javax.servlet.http.HttpServletResponse;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * ExportTrainingDemandService class
+ *
+ * @author XH
+ * @date 2023/12/12
+ */
+@Service
+public class ExportTrainingDemandServiceImpl implements ExportTrainingDemandService {
+    public static final String DOCX_FILE_PATH = "template/trainingDemand.doc";
+    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
+    @Autowired
+    private TrainingDemandSurveyBackupsDao trainingDemandSurveyBackupsDao;
+    @Autowired
+    private TrainingDemandSurveyDao trainingDemandSurveyDao;
+    @Autowired
+    private TrainingDemandServiceImpl trainingDemandService;
+    @Autowired
+    private DemandSurveyContentDao demandSurveyContentDao;
+    @Autowired
+    private TraningCommonDao traningCommonDao;
+    // 单选 多选
+    public static final String RADIO = "1";
+    // 单选 多选
+    public static final String CHECK_BOX = "2";
+    // 单选 多选
+    public static final String INPUT = "3";
+    // 题目
+    public static final String INPUT_TOPIC = "%s、%s: \n %s";
+    // 题目
+    public static final String SELECT_TOPIC = "%s、%s: \n%s";
+
+    public static final String CHECK_BOX_ICON = " □  ";
+
+    public static final String RADIO_ICON = " ○  ";
+    public static final String CHECKED_ICON = " √ ";
+
+    public static final String OPTIONS = "%s%s";
+
+    public static final String CUSTOM_QUESTION = "customQuestion";
+
+    public static final String[] WORD_KEY = {"name", "year", "companyname", "username", "zw"};
+
+    /**
+     * 生成问卷调查word
+     *
+     * @param surveyId
+     */
+    @SneakyThrows
+    @Override
+    public void generatePaper(String surveyId, HttpServletResponse response) {
+        log.info("开始生成问卷调查试卷");
+        if (StringUtils.isBlank(surveyId)) {
+            log.error("参数异常");
+            return;
+        }
+        // 判断问卷调查是否生成
+        TrainingDemandSurveyDo trainingDemandSurveyDo = trainingDemandSurveyDao.selectById(surveyId);
+        if (trainingDemandSurveyDo == null) {
+            log.error("问卷调查已删除");
+            return;
+        }
+        List<TrainingDemandSurveyBackupsDo> trainingDemandSurveyBackupsDos = trainingDemandSurveyBackupsDao.selectList(new LambdaQueryWrapper<TrainingDemandSurveyBackupsDo>()
+                .eq(TrainingDemandSurveyBackupsDo::getOldSurveyId, surveyId));
+        if (trainingDemandSurveyBackupsDos.isEmpty()) {
+            log.error("问卷调查暂未发布");
+            return;
+        }
+
+        // 获取问卷调查试卷
+        List<TrainingDemandVo> surveyContent = demandSurveyContentDao.getSurveyContent(trainingDemandSurveyBackupsDos.get(0).getId(), "");
+        DataTable dataTable = createDataTable(surveyContent, false);
+        // 文件导出
+        exportSingleWord(WORD_KEY, createWordValue(trainingDemandSurveyDo, null, ""), dataTable, response, DOCX_FILE_PATH);
+    }
+
+    /**
+     * 生成对应用户的问卷调查结果
+     * @param surveyId
+     * @param userId
+     * @param response
+     */
+    @Override
+    public void generateUserPaper(String surveyId, String userId, HttpServletResponse response) {
+        if(StringUtils.isBlank(surveyId)||StringUtils.isBlank(userId)){
+            throw new RuntimeException("参数异常");
+        }
+        TrainingDemandSurveyBackupsDo trainingDemandSurveyBackupsDo = trainingDemandSurveyBackupsDao.selectById(surveyId);
+        if(trainingDemandSurveyBackupsDo==null){
+            throw new RuntimeException("当前计划已删除");
+        }
+        TrainingDemandSurveyDo trainingDemandSurveyDo = trainingDemandSurveyDao.selectById(trainingDemandSurveyBackupsDo.getOldSurveyId());
+        if(trainingDemandSurveyDo==null){
+            throw new RuntimeException("当前计划已删除");
+        }
+        List<TrainingDemandVo> surveyContent = demandSurveyContentDao.getSurveyContent(surveyId, userId);
+        List<DemandUserVo> demandUserInfo = traningCommonDao.getDemandUserInfo(Arrays.asList(userId));
+        DataTable dataTable = createDataTable(surveyContent, true);
+        // 文件导出
+        exportSingleWord(WORD_KEY, createWordValue(trainingDemandSurveyDo, demandUserInfo, userId), dataTable, response, DOCX_FILE_PATH);
+    }
+
+
+    /**
+     * 创建word模板普通填充内容
+     *
+     * @param trainingDemandSurveyDo
+     * @param sysUserVos
+     * @param userId
+     * @return
+     */
+    public String[] createWordValue(TrainingDemandSurveyDo trainingDemandSurveyDo, List<DemandUserVo> sysUserVos, String userId) {
+        if (StringUtils.isBlank(userId)) {
+           return new String[]{trainingDemandSurveyDo.getName(), trainingDemandSurveyDo.getYear(), "", "", ""};
+        }
+        DemandUserVo demandUserVo = sysUserVos.stream().filter(info -> info.getId().equals(userId)).findFirst().orElse(null);
+        if(demandUserVo==null){
+            return new String[]{trainingDemandSurveyDo.getName(), trainingDemandSurveyDo.getYear(), "", "", ""};
+        }
+        return new String[]{trainingDemandSurveyDo.getName(), trainingDemandSurveyDo.getYear(),
+                demandUserVo.getCompanyName(),demandUserVo.getName() , demandUserVo.getRoleName()};
+    }
+
+    /**
+     * 创建word模板 列表内容
+     *
+     * @param surveyContent
+     * @param showAnswer
+     * @return
+     */
+    public DataTable createDataTable(List<TrainingDemandVo> surveyContent, boolean showAnswer) {
+        surveyContent.stream().forEach(info -> {
+            if (CUSTOM_QUESTION.equals(info.getModelName())) {
+                info.setModelName(info.getQuestionContent());
+                info.setQuestionContent("");
+            }
+        });
+        LinkedHashMap<String, List<TrainingDemandVo>> collect = surveyContent.stream()
+                .collect(Collectors.groupingBy(TrainingDemandVo::getModelName, LinkedHashMap::new, Collectors.toList()));
+        DataTable dataTable = new DataTable("temp");
+        dataTable.getColumns().add("num");
+        dataTable.getColumns().add("tempName");
+        dataTable.getColumns().add("tempContent");
+        int i = 1;
+        for (Map.Entry<String, List<TrainingDemandVo>> entry : collect.entrySet()) {
+            DataRow dataRow = dataTable.newRow();
+            dataRow.set("num", i);
+            dataRow.set("tempName", entry.getKey());
+            int k = 1;
+            List<String> content = new ArrayList<>();
+            for (TrainingDemandVo trainingDemandVo : entry.getValue()) {
+                String questionType = trainingDemandVo.getQuestionType();
+                if (INPUT.equals(questionType)) {
+                    if (StringUtils.isBlank(trainingDemandVo.getQuestionContent())) {
+                        content.add(showAnswer ? trainingDemandVo.getUserAnswer() : "");
+                    } else {
+                        content.add(String.format(INPUT_TOPIC, k, trainingDemandVo.getQuestionContent(), showAnswer ? trainingDemandVo.getUserAnswer() : ""));
+                    }
+                } else {
+                    content.add(
+                            String.format(SELECT_TOPIC, k, trainingDemandVo.getQuestionContent(),
+                                    trainingDemandVo.getQuestionOptions().stream().map(info -> {
+                                        return String.format(OPTIONS, info, selectShowIcon(showAnswer, questionType, info, trainingDemandVo.getUserAnswer()));
+                                    }).collect(Collectors.joining("   ")))
+                    );
+                }
+                k++;
+            }
+            dataRow.set("tempContent", content.stream().collect(Collectors.joining("\n")));
+            dataTable.getRows().add(dataRow);
+            i++;
+        }
+        return dataTable;
+    }
+
+    /**
+     * 单选和多选所展示的图标
+     *
+     * @param showAnswer
+     * @param questionType
+     * @param option
+     * @param userAnswer
+     * @return
+     */
+    public String selectShowIcon(boolean showAnswer, String questionType, String option, String userAnswer) {
+        if (!showAnswer || StringUtils.isBlank(userAnswer) || StringUtils.isBlank(option)) {
+            return CHECK_BOX.equals(questionType) ? CHECK_BOX_ICON : RADIO_ICON;
+        }
+        return Arrays.asList(userAnswer.split("-;-")).contains(option) ? CHECKED_ICON : CHECK_BOX.equals(questionType) ? CHECK_BOX_ICON : RADIO_ICON;
+    }
+}

+ 2 - 1
rw-training/training-common/src/main/java/com/rongwei/trainingcommon/sys/service/impl/TrainingDemandServiceImpl.java

@@ -296,7 +296,8 @@ public class TrainingDemandServiceImpl implements TrainingDemandService {
             log.debug("问卷调查发布状态异常");
             return R.error("问卷调查已结束");
         }
-        List<TrainingDemandVo> surveyContent = demandSurveyContentDao.getSurveyContent(id);
+        SysUserVo currentUser = TrainingUtils.getCurrentUser();
+        List<TrainingDemandVo> surveyContent = demandSurveyContentDao.getSurveyContent(id, currentUser == null ? "" : currentUser.getId());
 
         LinkedHashMap<String, List<TrainingDemandVo>> collect = surveyContent.stream()
                 .collect(Collectors.groupingBy(TrainingDemandVo::getModelName, LinkedHashMap::new, Collectors.toList()));

+ 1 - 0
rw-training/training-common/src/main/resources/mybatis/DemandSurveyContentDao.xml

@@ -24,6 +24,7 @@
         FROM `demand_survey_content` dsc
                  LEFT JOIN demand_survey_user_answer dsua
                            on dsc.ID = dsua.SURVERCONTENTID and dsc.SURVERID = dsua.SURVERID
+                               and dsua.CREATEUSERID = #{userId}
         where dsc.SURVERID = #{surverId}
         order by NUM
     </select>

+ 16 - 0
rw-training/training-common/src/main/resources/mybatis/TraningCommonDao.xml

@@ -49,4 +49,20 @@
         AND suo.DELETED = '0' AND suo.ORGID IN (select ID from orgid)
         where su.DELETED='0'
     </select>
+    <select id="getDemandUserInfo" resultType="com.rongwei.training.vo.DemandUserVo">
+        SELECT
+            su.ID as id ,MAX(su.`NAME`) as name,GROUP_CONCAT(DISTINCT sr.`NAME`)as roleName,so.FULLNAME as companyName
+        FROM
+            sys_user su
+                LEFT JOIN sys_user_role sur on su.ID =sur.USERID AND sur.DELETED='0'
+                left join sys_role sr on sr.ID=sur.ROLEID and sr.DELETED='0'
+                left join sys_organization so on su.TENANTID= so.ID and so.DELETED='0'
+        <where>
+        su.id in
+            <foreach collection="userIds" open="(" close=")" item="user" separator=",">
+                #{user}
+            </foreach>
+        </where>
+        group by su.ID
+    </select>
 </mapper>

+ 17 - 0
rw-training/training-entity/src/main/java/com/rongwei/training/vo/DemandUserVo.java

@@ -0,0 +1,17 @@
+package com.rongwei.training.vo;
+
+import com.rongwei.rwadmincommon.system.domain.SysUserDo;
+import lombok.Data;
+
+/**
+ * DemandUserVo class
+ *
+ * @author XH
+ * @date 2023/12/13
+ */
+@Data
+public class DemandUserVo extends SysUserDo {
+    private String companyName;
+
+    private String roleName;
+}

+ 17 - 0
rw-training/training-server/src/main/java/com/rongwei/training/controller/TrainingDemandController.java

@@ -3,12 +3,14 @@ package com.rongwei.training.controller;
 import com.rongwei.rwcommon.base.R;
 import com.rongwei.training.vo.PreviewTrainDemandVo;
 import com.rongwei.training.vo.TrainingDemandVo;
+import com.rongwei.trainingcommon.sys.service.impl.ExportTrainingDemandServiceImpl;
 import com.rongwei.trainingcommon.sys.service.impl.TrainingDemandServiceImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
+import javax.servlet.http.HttpServletResponse;
 import java.util.List;
 import java.util.Map;
 
@@ -24,6 +26,8 @@ public class TrainingDemandController {
     private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
     @Autowired
     private TrainingDemandServiceImpl trainingDemandService;
+    @Autowired
+    private ExportTrainingDemandServiceImpl exportTrainingDemandService;
 
     /**
      * 发布需求调查
@@ -77,6 +81,19 @@ public class TrainingDemandController {
         return trainingDemandService.submit(trainingDemandVoList);
     }
 
+    @GetMapping("/paper")
+    public void generatePaper(@RequestParam(name = "surveyId") String surveyId,
+                              HttpServletResponse response) {
+        log.info("开始生成培训问卷");
+        exportTrainingDemandService.generatePaper(surveyId, response);
+    }
 
+    @GetMapping("/user/paper")
+    public void generateUserPaper(@RequestParam(name = "surveyId") String surveyId,
+                                  @RequestParam(name = "userId") String userId,
+                                  HttpServletResponse response) {
+        log.info("开始生成用户培训问卷");
+        exportTrainingDemandService.generateUserPaper(surveyId, userId, response);
+    }
 
 }

BIN
rw-training/training-server/src/main/resources/template/trainingDemand.doc