Quellcode durchsuchen

fix :智能对话

zzf vor 1 Jahr
Ursprung
Commit
1961f8909c

+ 14 - 0
src/main/java/com/rf/kjb/chat/dao/domain/ChatEntity.java

@@ -0,0 +1,14 @@
+package com.rf.kjb.chat.dao.domain;
+
+import lombok.Data;
+
+/**
+ * @Author:zzf
+ * @Date:2023/9/14:15:36
+ * @Description:
+ */
+@Data
+public class ChatEntity {
+    private String question;
+    private String answer;
+}

+ 28 - 0
src/main/java/com/rf/kjb/chat/dao/domain/ChatRecordEntity.java

@@ -0,0 +1,28 @@
+package com.rf.kjb.chat.dao.domain;
+
+import com.rf.kjb.base.model.BaseEntry;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.Column;
+
+/**
+ * @Author:zzf
+ * @Date:2023/9/14:15:19
+ * @Description:
+ */
+@Data
+@NoArgsConstructor
+public class ChatRecordEntity extends BaseEntry {
+    @Column(name = "identifier" ,columnDefinition = "varchar(20) not null  comment '编号'")
+    private String identifier;
+
+    @Column(name = "label",columnDefinition = "varchar(2) not null comment '分类:1-焦虑;2-抑郁;3-失眠;4-压力'")
+    private String label;
+
+    @Column(name = "content",columnDefinition = "text not null comment '对话内容'")
+    private String content;
+
+    @Column(name = "file_path",columnDefinition = "varchar(200) comment '文件路径'")
+    private String filePath;
+}

+ 2 - 0
src/main/java/com/rf/kjb/chat/dao/repository/ChatAnswerRepository.java

@@ -10,4 +10,6 @@ public interface ChatAnswerRepository extends BaseRepository<ChatAnswerEntity,St
     List<ChatAnswerEntity> findByQuestionNo(String questionNo);
 
     List<ChatAnswerEntity> findByQuestionNoAndLabel(String questionNo, String label);
+
+    void deleteByLabel(String label);
 }

+ 2 - 0
src/main/java/com/rf/kjb/chat/dao/repository/ChatQuestionRepository.java

@@ -7,4 +7,6 @@ import com.rf.kjb.chat.dao.domain.ChatQuestionId;
 
 public interface ChatQuestionRepository extends BaseRepository<ChatQuestionEntity, ChatQuestionId> {
     ChatQuestionEntity findByIdAndLabel(String id, String label);
+
+    void deleteByLabel(String label);
 }

+ 7 - 0
src/main/java/com/rf/kjb/chat/dao/repository/ChatRecordRepository.java

@@ -0,0 +1,7 @@
+package com.rf.kjb.chat.dao.repository;
+
+import com.rf.kjb.base.repository.BaseRepository;
+import com.rf.kjb.chat.dao.domain.ChatRecordEntity;
+
+public interface ChatRecordRepository extends BaseRepository<ChatRecordEntity,String> {
+}

+ 162 - 10
src/main/java/com/rf/kjb/chat/rest/ChatController.java

@@ -1,22 +1,41 @@
 package com.rf.kjb.chat.rest;
 
+import com.alibaba.fastjson.JSONObject;
 import com.rf.kjb.base.rest.BaseController;
-import com.rf.kjb.chat.dao.domain.ChatAnswerEntity;
-import com.rf.kjb.chat.dao.domain.ChatQuestionEntity;
-import com.rf.kjb.chat.dao.domain.ResultQuestionEntity;
+import com.rf.kjb.chat.dao.domain.*;
 import com.rf.kjb.chat.service.ChatAnswerService;
 import com.rf.kjb.chat.service.ChatQuestionService;
+import com.rf.kjb.chat.service.ChatRecordService;
 import com.rf.kjb.chat.service.ResultQuestionService;
+import com.rf.kjb.excel.ExcelUtil;
 import com.rf.kjb.exception.ErrorCode;
+import com.rf.kjb.scale.util.DateUtil;
+import com.rf.kjb.utils.FileUtils;
 import com.rf.kjb.utils.Result;
+import com.rf.kjb.utils.ZipUtils;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.time.DateUtils;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFCell;
+import org.apache.poi.xssf.usermodel.XSSFRow;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
 import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 
 @Slf4j
 @RestController
@@ -33,6 +52,9 @@ public class ChatController extends BaseController {
     @Autowired
     private ResultQuestionService resultQuestionService;
 
+    @Autowired
+    private ChatRecordService chatRecordService;
+
 
     /**
      * 查询会话问题
@@ -49,7 +71,56 @@ public class ChatController extends BaseController {
         return success(questionEntity);
     }
 
+    @PostMapping("/import/{label}/faq")
+    @ApiOperation("智能问答导入")
+    public Result importQuestionAndAnswer(@RequestPart("file") MultipartFile file, @PathVariable String label){
+//        FileInputStream fileInputStream = new FileInputStream(file);
+        String [] fileNames = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
+        File targetFile = null;
+        List<ChatQuestionEntity> chatQuestionEntityList = new ArrayList<>();
+        List<ChatAnswerEntity> chatAnswerEntityList = new ArrayList<>();
+        try {
+//            targetFile = new File("./"+fileNames[0]+ UUID.randomUUID()+"."+fileNames[1]);
+//            FileUtils.copyInputStreamToFile(file.getInputStream(),targetFile);
+            targetFile = File.createTempFile(fileNames[0],"."+fileNames[1]);
+            file.transferTo(targetFile);
+            List<List<List<Object>>> datas = ExcelUtil.getBankListByExcelSheet(Files.newInputStream(Paths.get(targetFile.getAbsolutePath())), targetFile.getName());
+            List<List<Object>> questionList  = datas.get(0);
+            List<List<Object>> answerList  = datas.get(1);
+            questionList.forEach(item ->{
+                ChatQuestionEntity chatQuestionEntity = new ChatQuestionEntity();
+                chatQuestionEntity.setId((String) item.get(0));
+                chatQuestionEntity.setQuestion((String) item.get(1));
+                chatQuestionEntity.setNextQuestionNo((String) item.get(2));
+                chatQuestionEntity.setQuestionType((String) item.get(3));
+                chatQuestionEntity.setScaleFlag((String) item.get(4));
+                chatQuestionEntity.setLabel(label);
+                chatQuestionEntityList.add(chatQuestionEntity);
+            });
+            answerList.forEach(item ->{
+                ChatAnswerEntity chatAnswerEntity = new ChatAnswerEntity();
+                chatAnswerEntity.setQuestionNo((String) item.get(0));
+                chatAnswerEntity.setNextQuestionNo((String) item.get(1));
+                chatAnswerEntity.setAnswer((String) item.get(2));
+                chatAnswerEntity.setLabel(label);
+                chatAnswerEntityList.add(chatAnswerEntity);
+            });
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+
+        if(chatQuestionEntityList.size()>0 && chatAnswerEntityList.size()>0){
+            this.questionService.deleteByLabel(label);
+            this.answerService.deleteByLabel(label);
+
+            this.questionService.saveBatch(chatQuestionEntityList);
+            this.answerService.saveBatch(chatAnswerEntityList);
+        }
+
 
+        return success();
+
+    }
     @GetMapping("/getAnswer/{questionNo}/{label}")
     @ApiOperation("查询答案列表,questionNo为问题的id字段,nextQuestionNo 为此答案被选中后的下一个应该呈现的问题")
     public Result getAnswer(@PathVariable String questionNo,@PathVariable String label){
@@ -73,15 +144,96 @@ public class ChatController extends BaseController {
     }
 
     @PostMapping("/complete/chat")
-    @ApiOperation(value = "结束会话,保存会话记录",notes = "identifier:用户编号;label:只能对话分类 1-焦虑;2-抑郁;3-失眠;4-压力;chatDetail:会话详情")
-    public Result completeChat(@RequestBody String json ){
-
-
-        return success();
+    @ApiOperation(value = "结束会话,保存会话记录",notes = "identifier:用户编号;label:只能对话分类 1-焦虑;2-抑郁;3-失眠;4-压力;content:会话详情")
+    public Result completeChat(@RequestBody String json ) throws IOException {
+        ChatRecordEntity chatRecordEntity = JSONObject.parseObject(json,ChatRecordEntity.class);
+
+        //生成文件
+        List<ChatEntity> chatEntityList = JSONObject.parseArray(chatRecordEntity.getContent(),ChatEntity.class);
+        if(chatEntityList!= null &&chatEntityList.size()>0){
+            String filePath = "./对话记录/"+chatRecordEntity.getIdentifier()+"-对话记录-"+ DateUtil.getNowTime_CN()+".xlsx";
+            File file = new File(filePath);
+            if(!file.exists()){
+                file.createNewFile();
+            }
+            XSSFWorkbook workbook = new XSSFWorkbook();
+            ExcelUtil.createFont(workbook);
+            XSSFSheet sheet = workbook.createSheet("对话记录");
+            XSSFRow titleRow = sheet.createRow(0);
+            XSSFCell cellOrder = titleRow.createCell(0);
+            cellOrder.setCellValue("序号");
+            XSSFCell cellQuestion = titleRow.createCell(1);
+            cellQuestion.setCellValue("问题");
+            XSSFCell cellAnswer = titleRow.createCell(2);
+            cellAnswer.setCellValue("答案");
+            int index = 1;
+            chatEntityList.forEach(item -> {
+                XSSFRow row = sheet.createRow(index);
+                for (int i=0;i<4;i++){
+                    XSSFCell cellOrder1 = row.createCell(0);
+                    cellOrder1.setCellValue(index);
+                    XSSFCell cellQuestion1 = row.createCell(1);
+                    cellQuestion1.setCellValue(item.getQuestion());
+                    XSSFCell cellAnswer1 = row.createCell(2);
+                    cellAnswer1.setCellValue(item.getAnswer());
+                }
+            });
+            OutputStream outputStream = Files.newOutputStream(file.toPath());
+            workbook.write(outputStream);
+            outputStream.close();
+            //保存记录
+            chatRecordEntity.setFilePath(filePath);
+            this.chatRecordService.save(chatRecordEntity);
+            return success();
+        }else {
+            return fail(ErrorCode.CHAT_CONTENT_EMPTY);
+        }
     }
 
+    @GetMapping("/chat/list")
+    @ApiOperation(value = "智能对话列表",notes = "identifier:编号;beginDate:查询起始日期;endDate:查询结束日期;pageNum:页数;pageSize:每页记录数")
+    public Result getChatList(String identifier,String beginDate,String endDate,int pageNum,int pageSize){
+        Page<ChatEntity> chatEntities = this.chatRecordService.find(identifier,beginDate,endDate,pageNum,pageSize);
+        return success(chatEntities);
+    }
 
+    @GetMapping("/chat/download")
+    @ApiOperation(value = "下载对话记录",notes = "")
+    public Result downloadChatList(@RequestBody String json, HttpServletResponse response) throws IOException {
+        List<String> list = JSONObject.parseArray(json,String.class);
+        if(list.size()>0){
+            for (String item : list) {
+                File file = new File(item);
+                if(file.exists()){
+                    InputStream inputStream = null;
+                    OutputStream outputStream = null;
+                    try {
+                        inputStream = Files.newInputStream(file.toPath());
+                        outputStream = new FileOutputStream("./对话列表/"+item);
+                        IOUtils.copy(inputStream,outputStream);
+                    } catch (IOException e) {
+                        log.error("对话记录下载失败:"+e.getMessage());
+                    }finally {
+                        if(inputStream != null){
+                            inputStream.close();
+                        }
+                        if(outputStream != null){
+                            outputStream.close();
+                        }
+                    }
+                }
+            }
+
+            File dir = new File("./对话列表");
+            if(!dir.exists()){
+                return fail(ErrorCode.FAILED);
+            }else {
+                ZipUtils.createZip("./对话列表","./对话列表"+ DateUtil.getNowTime_CN()+".zip",false);
+                FileUtils.downloadFile(new File("./对话列表","对话列表"+ DateUtil.getNowTime_CN()+".zip"),"","对话列表"+ DateUtil.getNowTime_CN()+".zip",response);
+                return success();
+            }
 
-
-
+        }
+        return fail(ErrorCode.FAILED);
+    }
 }

+ 3 - 0
src/main/java/com/rf/kjb/chat/service/ChatAnswerService.java

@@ -9,4 +9,7 @@ public interface ChatAnswerService {
     List<ChatAnswerEntity> findByQuestionNo(String questionNo);
 
     List<ChatAnswerEntity> findByQuestionNoAndLabel(String questionNo, String label);
+    void deleteByLabel(String label);
+
+    void saveBatch(List<ChatAnswerEntity> chatAnswerEntityList);
 }

+ 6 - 0
src/main/java/com/rf/kjb/chat/service/ChatQuestionService.java

@@ -3,6 +3,8 @@ package com.rf.kjb.chat.service;
 
 import com.rf.kjb.chat.dao.domain.ChatQuestionEntity;
 
+import java.util.List;
+
 /**
  * @Author:zzf
  * @Date:2022/10/21:01:04
@@ -12,4 +14,8 @@ public interface ChatQuestionService {
 //    ChatQuestionEntity findById(String id);
 
     ChatQuestionEntity findByIdAndLabel(String id, String label);
+
+    void deleteByLabel(String label);
+
+    void saveBatch(List<ChatQuestionEntity> chatQuestionEntityList);
 }

+ 11 - 0
src/main/java/com/rf/kjb/chat/service/ChatRecordService.java

@@ -0,0 +1,11 @@
+package com.rf.kjb.chat.service;
+
+import com.rf.kjb.chat.dao.domain.ChatEntity;
+import com.rf.kjb.chat.dao.domain.ChatRecordEntity;
+import org.springframework.data.domain.Page;
+
+public interface ChatRecordService {
+    void save(ChatRecordEntity chatRecordEntity);
+
+    Page<ChatEntity> find(String identifier, String beginDate,String endDate, int pageNum, int pageSize);
+}

+ 10 - 0
src/main/java/com/rf/kjb/chat/service/impl/ChatAnswerServiceImpl.java

@@ -27,4 +27,14 @@ public class ChatAnswerServiceImpl implements ChatAnswerService {
     public List<ChatAnswerEntity> findByQuestionNoAndLabel(String questionNo, String label) {
         return this.answerRepository.findByQuestionNoAndLabel(questionNo,label);
     }
+
+    @Override
+    public void deleteByLabel(String label) {
+        this.answerRepository.deleteByLabel(label);
+    }
+
+    @Override
+    public void saveBatch(List<ChatAnswerEntity> chatAnswerEntityList) {
+        this.answerRepository.saveAll(chatAnswerEntityList);
+    }
 }

+ 12 - 0
src/main/java/com/rf/kjb/chat/service/impl/ChatQuestionServiceImpl.java

@@ -6,6 +6,8 @@ import com.rf.kjb.chat.service.ChatQuestionService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
+import java.util.List;
+
 /**
  * @Author:zzf
  * @Date:2022/10/21:01:04
@@ -25,4 +27,14 @@ public class ChatQuestionServiceImpl implements ChatQuestionService {
     public ChatQuestionEntity findByIdAndLabel(String id, String label) {
         return this.questionRepository.findByIdAndLabel(id,label);
     }
+
+    @Override
+    public void deleteByLabel(String label) {
+        this.questionRepository.deleteByLabel(label);
+    }
+
+    @Override
+    public void saveBatch(List<ChatQuestionEntity> chatQuestionEntityList) {
+        this.questionRepository.saveAll(chatQuestionEntityList);
+    }
 }

+ 62 - 0
src/main/java/com/rf/kjb/chat/service/impl/ChatRecordServiceImpl.java

@@ -0,0 +1,62 @@
+package com.rf.kjb.chat.service.impl;
+
+import com.rf.kjb.chat.dao.domain.ChatEntity;
+import com.rf.kjb.chat.dao.domain.ChatRecordEntity;
+import com.rf.kjb.chat.dao.repository.ChatRecordRepository;
+import com.rf.kjb.chat.service.ChatRecordService;
+import com.rf.kjb.scale.dao.model.CategoryEntry;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.jpa.domain.Specification;
+import org.springframework.stereotype.Service;
+
+import javax.persistence.criteria.Predicate;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @Author:zzf
+ * @Date:2023/9/14:15:27
+ * @Description:
+ */
+@Service
+public class ChatRecordServiceImpl implements ChatRecordService {
+    @Autowired
+    private ChatRecordRepository repository;
+    @Override
+    public void save(ChatRecordEntity chatRecordEntity) {
+        repository.save(chatRecordEntity);
+    }
+
+    @Override
+    public Page<ChatEntity> find(String identifier, String beginDate,String endDate, int pageNum, int pageSize) {
+        Specification<ChatEntity> specification = (root, query, cb) -> {
+            List<javax.persistence.criteria.Predicate> predicateList = new ArrayList<>();
+            if(StringUtils.isNotBlank(identifier)){
+                predicateList.add(cb.equal(root.get("identifier"),identifier));
+            }
+
+            if(StringUtils.isNotBlank(beginDate)){
+                cb.greaterThanOrEqualTo(root.get("createTime"),beginDate);
+            }
+
+            if(StringUtils.isNotBlank(endDate)){
+                cb.lessThanOrEqualTo(root.get("createTime"),endDate);
+            }
+
+            query.where(cb.and(predicateList.toArray(new Predicate[0])));
+            query.orderBy(cb.asc(root.get("createTime")));
+            return query.getRestriction();
+        };
+        if (pageNum <= 0) {
+            pageNum = 1;
+        }
+
+        if(pageSize <= 0){
+            pageSize = 10;
+        }
+        return this.repository.findAll(specification, PageRequest.of(pageNum-1,pageSize));
+    }
+}

+ 2 - 1
src/main/java/com/rf/kjb/exception/ErrorCode.java

@@ -6,6 +6,7 @@ import lombok.Getter;
 public enum ErrorCode {
     /** 系统 **/
     SUCCESS(200,"处理完成"),
+    FAILED(201,"失败"),
 
     /** 用户模块错误码 **/
     USER_EXISTS(1001,"用户已存在"),
@@ -21,7 +22,7 @@ public enum ErrorCode {
     SCALE_UNUSEFUL(2002,"量表不可用"),
     NEXT_QUESTION_NO_NOT_FOUND(2003,"未设置下一问题编号"),
     NEXT_QUESTION_NO_ERROR(2004,"下一问题编号设置错误"),
-
+    CHAT_CONTENT_EMPTY(2005,"对话内容为空"),
 
     ;