mirror of
https://codeup.aliyun.com/67762337eccfc218f6110e0e/per-boe/java-servers.git
synced 2025-12-07 01:46:47 +08:00
Compare commits
154 Commits
250331-bug
...
8a3899dfd1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a3899dfd1 | ||
|
|
c17a594393 | ||
|
|
09d61ceb9d | ||
|
|
106fde8e6b | ||
|
|
3bf0534d77 | ||
|
|
dd0e10539f | ||
|
|
fceb6ac805 | ||
|
|
24576a4fd1 | ||
|
|
8d7cfac081 | ||
|
|
1d5447cff5 | ||
|
|
ddf3f277cd | ||
|
|
48c6090fb1 | ||
|
|
46f8668cb8 | ||
|
|
09c10e3af6 | ||
|
|
dfba210890 | ||
|
|
f04660d8a3 | ||
|
|
c30283979a | ||
|
|
649f512887 | ||
|
|
56d1a6a509 | ||
|
|
456f7ec061 | ||
|
|
8d31d63be5 | ||
|
|
c592a29ad4 | ||
|
|
b54d78d17b | ||
|
|
30efbd5610 | ||
|
|
1043b7d404 | ||
|
|
d480a53a26 | ||
|
|
d8b2869d80 | ||
|
|
8ee866bf39 | ||
|
|
3bb1f619bf | ||
|
|
4be26921d8 | ||
|
|
748ec8c072 | ||
|
|
e9682dcb61 | ||
|
|
67aa312d2f | ||
|
|
770dc684cd | ||
|
|
aa5c13598d | ||
|
|
a4f67d99ff | ||
|
|
95cb5ba656 | ||
|
|
23f72e7702 | ||
|
|
b9728993ce | ||
|
|
70ad3020d4 | ||
|
|
425611a106 | ||
|
|
9de9eaea7e | ||
|
|
ce05b67039 | ||
|
|
7f905d21a4 | ||
|
|
a27e0eb6c5 | ||
|
|
cf069a9700 | ||
|
|
0e2e0861de | ||
|
|
b55e2fa6e0 | ||
|
|
6feef59a72 | ||
|
|
4900383c98 | ||
|
|
873c3c300a | ||
|
|
26c08631a0 | ||
|
|
e20a20ec43 | ||
|
|
c29dcd5966 | ||
|
|
ceaa0adbf0 | ||
|
|
c671ae5bab | ||
|
|
14aa8a17c6 | ||
|
|
67dfee1f07 | ||
|
|
fe688de8aa | ||
|
|
4e3ce2d762 | ||
|
|
42946fed80 | ||
|
|
079b64d0fd | ||
|
|
d95bf6ee6c | ||
|
|
96342f1170 | ||
|
|
f226f209e9 | ||
|
|
7ef5af09db | ||
|
|
e7558c5526 | ||
|
|
ac12e04a58 | ||
|
|
957ac93a98 | ||
|
|
80b6135534 | ||
|
|
2639936128 | ||
|
|
c244290d1a | ||
|
|
b862128a79 | ||
|
|
58f9cdc5d6 | ||
|
|
cf8237819b | ||
|
|
bc5d78e7cc | ||
|
|
fa740f8f40 | ||
|
|
0a55fbd08f | ||
|
|
bb8bf5e979 | ||
|
|
5a4a560d10 | ||
|
|
08b4feb00c | ||
|
|
16b2d90417 | ||
|
|
bad129a0a1 | ||
|
|
08bd7f155f | ||
|
|
5e20e21e86 | ||
|
|
5666cfeaaa | ||
|
|
9c4cef9dca | ||
|
|
0207826a07 | ||
|
|
11ebb2e38b | ||
|
|
176d2cb800 | ||
|
|
66f437427c | ||
|
|
5f32b8a6fc | ||
|
|
2358c2e881 | ||
|
|
660cee2112 | ||
|
|
7376ea21c7 | ||
|
|
5e02e3ef5f | ||
|
|
12168ff725 | ||
|
|
a3647aa190 | ||
|
|
af503efefc | ||
|
|
9188bcdf30 | ||
|
|
a6eb3b519e | ||
|
|
e8a787e2a3 | ||
|
|
720031c648 | ||
|
|
7d6243e16e | ||
|
|
0c4dbecd79 | ||
|
|
fdfd834ce9 | ||
|
|
249a8d81a6 | ||
|
|
7abb00772b | ||
|
|
04e11f2e71 | ||
|
|
2feb149e92 | ||
|
|
16fa9cb028 | ||
|
|
cac466ba73 | ||
|
|
30d2a0cde2 | ||
|
|
541e542d9b | ||
|
|
aa04e16209 | ||
|
|
57e22492e5 | ||
|
|
1917647a99 | ||
|
|
f5f7ab3bc5 | ||
|
|
413a2ebc33 | ||
|
|
22db916abf | ||
|
|
8ce284ea7e | ||
|
|
c485757061 | ||
|
|
9a00b41cde | ||
|
|
59beaa5b74 | ||
|
|
9b9e97a8d4 | ||
|
|
200ec38038 | ||
|
|
7613f30ca7 | ||
|
|
248e0799bd | ||
|
|
618b0b3f62 | ||
|
|
5836b147c4 | ||
|
|
fb1d11ebab | ||
|
|
add1d6abb2 | ||
|
|
eafe17b99a | ||
|
|
d1b6573c25 | ||
|
|
1039f80aec | ||
|
|
efc0605115 | ||
|
|
d938425151 | ||
|
|
00510562ca | ||
|
|
3e70e71e5a | ||
|
|
24011a4470 | ||
|
|
8948165296 | ||
|
|
076b1828ad | ||
|
|
95312696f6 | ||
|
|
1aca002b8f | ||
|
|
50bdc39ce8 | ||
|
|
4fff780970 | ||
|
|
47813ea565 | ||
|
|
5aa62de3cb | ||
|
|
a309bc1ddf | ||
|
|
74bcec72bc | ||
|
|
b8c171bf86 | ||
|
|
175e7f6c28 | ||
|
|
5705bb8529 | ||
|
|
87e5dd81f8 |
@@ -161,11 +161,21 @@
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpmime</artifactId>
|
||||
<version>4.5.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.mail</groupId>
|
||||
<artifactId>javax.mail-api</artifactId>
|
||||
<version>1.5.6</version>
|
||||
</dependency>
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>com.sun.mail</groupId>-->
|
||||
<!-- <artifactId>javax.mail</artifactId>-->
|
||||
<!-- <version>1.5.6</version>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
@@ -227,6 +237,23 @@
|
||||
<artifactId>elasticsearch-rest-high-level-client</artifactId>
|
||||
<version>7.9.0</version> <!-- 请根据实际需求选择合适的版本 -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>4.2.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp-sse</artifactId>
|
||||
<version>4.2.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>2.0.31</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.xboe</groupId>
|
||||
|
||||
@@ -45,10 +45,7 @@ import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
@@ -98,7 +95,8 @@ public class ThirdApi {
|
||||
private String syncOnLineScore;
|
||||
@Value("${coursesuilt.updateOnLineStatua}")
|
||||
private String updateOnLineStatua;
|
||||
|
||||
@Value("${coursesuilt.delOnLineById}")
|
||||
private String delOnLineById;
|
||||
|
||||
//获取例外人员的id
|
||||
public List<String> getUserId() {
|
||||
@@ -398,4 +396,28 @@ public class ThirdApi {
|
||||
public void syncExamStudyRecord(ExamStudyRecordParam param) {
|
||||
externalRemoteClient.syncExamStudyRecord(param);
|
||||
}
|
||||
|
||||
public void delOnLineById(CourseParam param, String token) {
|
||||
log.info("---------------同步在线课删除 ------- param " + param);
|
||||
String resp = Optional.ofNullable(
|
||||
HttpRequest.post(delOnLineById).body(JSONUtil.toJsonStr(param)).header("token", token).execute()
|
||||
.body()).orElseThrow(() -> new RuntimeException("token校验失败"));
|
||||
log.info("-------delOnLineById = " + resp);
|
||||
}
|
||||
|
||||
//获取字典信息
|
||||
public List<Dict> getDictItems(CommonSearchVo searcher) {
|
||||
try {
|
||||
List<Dict> dictList = dictRemoteClient.getList(searcher);
|
||||
if(!Objects.isNull(dictList) && dictList.size() > 0){
|
||||
// List<String> dicts = dictList.stream().map(Dict::getValue).collect(Collectors.toList());
|
||||
return dictList;
|
||||
}else {
|
||||
return null;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("-------获取字典信息 = " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.xboe.config;
|
||||
|
||||
import com.xboe.module.boecase.service.IElasticSearchIndexService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* ElasticSearch索引初始化器
|
||||
* 在Spring Boot启动完成并监听到配置文件加载完毕后,检查并创建所需的ES索引
|
||||
*
|
||||
* @author AI Assistant
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class ElasticSearchIndexInitializer {
|
||||
|
||||
@Autowired
|
||||
private IElasticSearchIndexService elasticSearchIndexService;
|
||||
|
||||
/**
|
||||
* 监听Spring Boot应用启动完成事件
|
||||
* ApplicationReadyEvent在应用启动完成、所有配置加载完毕后触发
|
||||
*/
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void initializeElasticSearchIndices() {
|
||||
if (elasticSearchIndexService.checkIndexExists()) {
|
||||
log.info("ElasticSearch索引 ai_chat_messages 已存在");
|
||||
} else {
|
||||
log.info("ElasticSearch索引 ai_chat_messages 不存在,开始创建...");
|
||||
elasticSearchIndexService.createIndex();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.xboe.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import okhttp3.Dispatcher;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
/**
|
||||
* 线程池配置类
|
||||
*/
|
||||
@Configuration
|
||||
@Slf4j
|
||||
public class ThreadPoolConfig {
|
||||
|
||||
/**
|
||||
* 执行AI文档接口的的线程池
|
||||
* 策略:单线程等待队列
|
||||
*/
|
||||
@Bean(name = "aiDocExecutor")
|
||||
public ThreadPoolTaskExecutor aiDocExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
// 设置核心线程数
|
||||
int corePoolSize = Runtime.getRuntime().availableProcessors();
|
||||
executor.setCorePoolSize(Math.max(4, corePoolSize));
|
||||
// 设置最大线程数
|
||||
executor.setMaxPoolSize(Math.max(16, corePoolSize * 2));
|
||||
// 设置队列容量(确保任务排队)
|
||||
executor.setQueueCapacity(100);
|
||||
// keepalive
|
||||
executor.setKeepAliveSeconds(30);
|
||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||
executor.setAwaitTerminationSeconds(30);
|
||||
// 设置线程名称前缀
|
||||
executor.setThreadNamePrefix("ai_doc_task-");
|
||||
// 设置拒绝策略(当队列满时,由调用线程处理该任务)
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
// 初始化线程池
|
||||
executor.initialize();
|
||||
log.info("AI文档线程池初始化完成 - 核心线程: {}, 最大线程: {}, 队列容量: {}",
|
||||
executor.getCorePoolSize(),
|
||||
executor.getMaxPoolSize(),
|
||||
executor.getQueueCapacity());
|
||||
return executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* event-stream线程池
|
||||
* @return
|
||||
*/
|
||||
@Bean(name = "eventStreamExecutor")
|
||||
public ThreadPoolTaskExecutor eventStreamExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(10);
|
||||
executor.setMaxPoolSize(500);
|
||||
executor.setQueueCapacity(10);
|
||||
executor.setThreadNamePrefix("event-stream-");
|
||||
executor.setKeepAliveSeconds(300);
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
@Bean(name = "customDispatcher")
|
||||
public Dispatcher customDispatcher(@Qualifier("eventStreamExecutor") ThreadPoolTaskExecutor eventStreamExecutor) {
|
||||
return new Dispatcher(eventStreamExecutor.getThreadPoolExecutor());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.xboe.constants;
|
||||
|
||||
public class CaseAiConstants {
|
||||
|
||||
public static final String CASE_AI_INDEX_NAME = "ai_chat_messages";
|
||||
|
||||
public static final String CASE_DOC_UPLOAD_INTERFACE_NAME = "文档上传";
|
||||
|
||||
public static final String CASE_DOC_DELETE_INTERFACE_NAME = "文档删除";
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
public enum CaseAiChatStatusEnum {
|
||||
|
||||
REFERS(0, "引用文档"),
|
||||
|
||||
CHAT(1, "聊天中"),
|
||||
|
||||
CHAT_COMPLETED(2, "聊天完成"),
|
||||
|
||||
SUGGESTIONS(3, "建议"),
|
||||
|
||||
API_COMPLETED(4, "接口完成"),
|
||||
;
|
||||
|
||||
private final int code;
|
||||
|
||||
private final String label;
|
||||
|
||||
CaseAiChatStatusEnum(int code, String label) {
|
||||
this.code = code;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public static CaseAiChatStatusEnum getByCode(int code) {
|
||||
for (CaseAiChatStatusEnum value : values()) {
|
||||
if (value.code == code) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return API_COMPLETED;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
/**
|
||||
* AI调用日志业务处理状态枚举
|
||||
*/
|
||||
public enum CaseDocumentLogCaseStatusEnum {
|
||||
|
||||
SUCCESS(1, "处理成功"),
|
||||
FAILED(2, "处理失败");
|
||||
|
||||
private final Integer code;
|
||||
private final String desc;
|
||||
|
||||
CaseDocumentLogCaseStatusEnum(Integer code, String desc) {
|
||||
this.code = code;
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取描述
|
||||
*/
|
||||
public static String getDescByCode(Integer code) {
|
||||
for (CaseDocumentLogCaseStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum.getDesc();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取枚举
|
||||
*/
|
||||
public static CaseDocumentLogCaseStatusEnum getByCode(Integer code) {
|
||||
for (CaseDocumentLogCaseStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
/**
|
||||
* AI调用日志接口调用状态枚举
|
||||
*/
|
||||
public enum CaseDocumentLogOptStatusEnum {
|
||||
|
||||
CALLING(0, "调用中"),
|
||||
SUCCESS(1, "调用成功"),
|
||||
FAILED(2, "调用失败");
|
||||
|
||||
private final Integer code;
|
||||
private final String desc;
|
||||
|
||||
CaseDocumentLogOptStatusEnum(Integer code, String desc) {
|
||||
this.code = code;
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取描述
|
||||
*/
|
||||
public static String getDescByCode(Integer code) {
|
||||
for (CaseDocumentLogOptStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum.getDesc();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取枚举
|
||||
*/
|
||||
public static CaseDocumentLogOptStatusEnum getByCode(Integer code) {
|
||||
for (CaseDocumentLogOptStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
/**
|
||||
* AI调用日志操作类型枚举
|
||||
*/
|
||||
public enum CaseDocumentLogOptTypeEnum {
|
||||
|
||||
CREATE("create", "新增"),
|
||||
DELETE("delete", "删除"),
|
||||
UPDATE("update", "更改");
|
||||
|
||||
private final String code;
|
||||
private final String desc;
|
||||
|
||||
CaseDocumentLogOptTypeEnum(String code, String desc) {
|
||||
this.code = code;
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取描述
|
||||
*/
|
||||
public static String getDescByCode(String code) {
|
||||
for (CaseDocumentLogOptTypeEnum typeEnum : values()) {
|
||||
if (typeEnum.getCode().equals(code)) {
|
||||
return typeEnum.getDesc();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
/**
|
||||
* AI调用日志接口运行状态枚举
|
||||
*/
|
||||
public enum CaseDocumentLogRunStatusEnum {
|
||||
|
||||
RUNNING(0, "运行中"),
|
||||
COMPLETED(1, "运行完成");
|
||||
|
||||
private final Integer code;
|
||||
private final String desc;
|
||||
|
||||
CaseDocumentLogRunStatusEnum(Integer code, String desc) {
|
||||
this.code = code;
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取描述
|
||||
*/
|
||||
public static String getDescByCode(Integer code) {
|
||||
for (CaseDocumentLogRunStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum.getDesc();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取枚举
|
||||
*/
|
||||
public static CaseDocumentLogRunStatusEnum getByCode(Integer code) {
|
||||
for (CaseDocumentLogRunStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.xboe.module.assistance.service;
|
||||
|
||||
/**
|
||||
* SMTP邮件服务接口
|
||||
*/
|
||||
public interface ISmtpEmailService {
|
||||
|
||||
/**
|
||||
* 使用SMTP直接发送邮件
|
||||
* @param to 收件人邮箱
|
||||
* @param subject 邮件主题
|
||||
* @param htmlMsg 邮件内容(HTML格式)
|
||||
* @param from 发件人邮箱
|
||||
* @throws Exception 发送异常
|
||||
*/
|
||||
void sendMailBySmtp(String to, String subject, String htmlMsg, String from) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.xboe.module.assistance.service.impl;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.mail.Authenticator;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.PasswordAuthentication;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.xboe.module.assistance.service.ISmtpEmailService;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class SmtpEmailServiceImpl implements ISmtpEmailService {
|
||||
|
||||
//region 默认SMTP服务器配置信息
|
||||
private static final String SMTP_HOST = "mail.boe.com.cn";
|
||||
private static final String SMTP_USERNAME = "boeu_learning@boe.com.cn";
|
||||
private static final String SMTP_PASSWORD = "boeLms20251112Syse";
|
||||
private static final String SMTP_PORT = "465";
|
||||
private static final String SMTP_ENCRYPTION = "ssl";
|
||||
//endregion
|
||||
|
||||
@Override
|
||||
public void sendMailBySmtp(String to, String subject, String htmlMsg, String from) throws Exception {
|
||||
// 检查参数
|
||||
if (StringUtils.isBlank(to)) {
|
||||
throw new Exception("发送邮件失败,未指定收件人");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(subject)) {
|
||||
throw new Exception("发送邮件失败,未指定邮件主题");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(htmlMsg)) {
|
||||
throw new Exception("发送邮件失败,未指定邮件内容");
|
||||
}
|
||||
// 初始化配置项
|
||||
|
||||
// 设置SMTP属性
|
||||
Properties props = new Properties();
|
||||
props.put("mail.smtp.host", SMTP_HOST);
|
||||
props.put("mail.smtp.port", SMTP_PORT);
|
||||
props.put("mail.smtp.auth", "true");
|
||||
|
||||
if ("ssl".equalsIgnoreCase(SMTP_ENCRYPTION)) {
|
||||
props.put("mail.smtp.ssl.enable", "true");
|
||||
props.put("mail.smtp.ssl.trust", SMTP_HOST);
|
||||
// props.put("mail.smtp.ssl.protocols", "TLSv1.2");
|
||||
} else if ("tls".equalsIgnoreCase(SMTP_ENCRYPTION)) {
|
||||
props.put("mail.smtp.starttls.enable", "true");
|
||||
}
|
||||
|
||||
Authenticator authenticator = new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(SMTP_USERNAME, SMTP_PASSWORD);
|
||||
}
|
||||
};
|
||||
// 创建会话
|
||||
Session session = Session.getInstance(props, authenticator);
|
||||
session.setDebug(true); // 查看调试信息
|
||||
|
||||
try {
|
||||
// 创建邮件消息
|
||||
Message message = new MimeMessage(session);
|
||||
|
||||
// 设置发件人
|
||||
message.setFrom(new InternetAddress(SMTP_USERNAME));
|
||||
|
||||
// 设置收件人
|
||||
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
|
||||
|
||||
// 设置邮件主题
|
||||
message.setSubject(subject);
|
||||
|
||||
// 设置邮件内容
|
||||
message.setContent(htmlMsg, "text/html;charset=UTF-8");
|
||||
|
||||
// 发送日期
|
||||
message.setSentDate(new Date());
|
||||
|
||||
// 发送邮件
|
||||
log.info("发送邮件. 发件人: {}, 收件人: {}, 标题: {}", SMTP_USERNAME, to, subject);
|
||||
Transport.send(message);
|
||||
|
||||
} catch (MessagingException e) {
|
||||
throw new Exception("发送邮件失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.xboe.module.boecase.api;
|
||||
|
||||
import com.xboe.core.api.ApiBaseController;
|
||||
import com.xboe.core.JsonResponse;
|
||||
import com.xboe.module.boecase.dto.CaseAiChatDto;
|
||||
import com.xboe.module.boecase.entity.AiChatConversationData;
|
||||
import com.xboe.module.boecase.service.ICaseAiChatService;
|
||||
import com.xboe.module.boecase.service.ICaseAiPermissionService;
|
||||
import com.xboe.module.boecase.service.IElasticSearchIndexService;
|
||||
import com.xboe.module.boecase.vo.CaseAiMessageVo;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* AI对话管理API
|
||||
*/
|
||||
@Slf4j(topic = "caseAiChatLogger")
|
||||
@RestController
|
||||
@RequestMapping(value = "/xboe/m/boe/case/ai")
|
||||
public class CaseAiChatApi extends ApiBaseController {
|
||||
|
||||
/**
|
||||
* 聊天
|
||||
* @param caseAiChatDto
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@Autowired
|
||||
private ICaseAiChatService caseAiChatService;
|
||||
|
||||
@Autowired
|
||||
private ICaseAiPermissionService caseAiPermissionService;
|
||||
|
||||
@Autowired
|
||||
private IElasticSearchIndexService elasticSearchIndexService;
|
||||
|
||||
/**
|
||||
* 聊天
|
||||
* @param caseAiChatDto
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter chat(@RequestBody CaseAiChatDto caseAiChatDto,
|
||||
HttpServletResponse response) {
|
||||
response.setContentType("text/event-stream");
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
|
||||
// 获取当前用户
|
||||
return caseAiChatService.chat(caseAiChatDto, getCurrent());
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止当前聊天输出
|
||||
* @param conversationId 会话ID
|
||||
* @return 是否成功停止
|
||||
*/
|
||||
@PostMapping("/stop")
|
||||
public JsonResponse<Boolean> stopChat(@RequestParam String conversationId) {
|
||||
try {
|
||||
boolean result = caseAiChatService.stopChatOutput(conversationId);
|
||||
if (result) {
|
||||
return success(true, "成功停止输出");
|
||||
} else {
|
||||
return success(false, "未找到对应的会话或会话已结束");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("停止聊天输出异常", e);
|
||||
return error("停止输出失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据conversationId查看会话内消息记录
|
||||
* @param conversationId 会话ID
|
||||
* @return 消息记录列表
|
||||
*/
|
||||
@GetMapping("/messages")
|
||||
public JsonResponse<List<CaseAiMessageVo>> getConversationMessages(@RequestParam String conversationId) {
|
||||
try {
|
||||
List<CaseAiMessageVo> messages = caseAiChatService.getConversationMessages(conversationId);
|
||||
return success(messages);
|
||||
} catch (Exception e) {
|
||||
log.error("查询会话消息记录异常", e);
|
||||
return error("查询失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出会话记录为Excel
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @param response HTTP响应
|
||||
*/
|
||||
@GetMapping("/export-conversations")
|
||||
public void downloadConversationExcel(@RequestParam String startTime,
|
||||
@RequestParam String endTime,
|
||||
HttpServletResponse response) {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
LocalDate startDate = LocalDate.parse(startTime, formatter);
|
||||
LocalDate endDate = LocalDate.parse(endTime, formatter);
|
||||
caseAiChatService.getConversationExcel(startDate.atStartOfDay(), endDate.atTime(23, 59, 59), response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前登录用户是否显示"案例专家"功能入口
|
||||
* @return 是否显示功能入口
|
||||
*/
|
||||
@GetMapping("/show-entrance")
|
||||
public JsonResponse<Boolean> showCaseAiEntrance() {
|
||||
try {
|
||||
String currentUserCode = getCurrent().getCode();
|
||||
boolean shouldShow = caseAiPermissionService.shouldShowCaseAiEntrance(currentUserCode);
|
||||
// return success(shouldShow);
|
||||
JsonResponse<Boolean> result = success(shouldShow);
|
||||
result.setMessage(currentUserCode);
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.error("判断案例专家功能入口显示权限异常", e);
|
||||
return error("判断失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动刷新索引
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/index/refresh")
|
||||
public JsonResponse<String> deleteAndCreateEsIndex() {
|
||||
if (elasticSearchIndexService.checkIndexExists()) {
|
||||
boolean deleteResult = elasticSearchIndexService.deleteIndex();
|
||||
if (deleteResult) {
|
||||
elasticSearchIndexService.createIndex();
|
||||
return success("刷新成功");
|
||||
}
|
||||
} else {
|
||||
elasticSearchIndexService.createIndex();
|
||||
}
|
||||
return error("刷新失败");
|
||||
}
|
||||
|
||||
@PostMapping("/es/create")
|
||||
public JsonResponse<String> createNewConversation(@RequestBody CaseAiMessageVo caseAiMessageVo,
|
||||
@RequestParam String conversationId,
|
||||
@RequestParam String userId) {
|
||||
AiChatConversationData aiChatConversationData = new AiChatConversationData();
|
||||
aiChatConversationData.setConversationId(conversationId);
|
||||
aiChatConversationData.setQuery(caseAiMessageVo.getQuery());
|
||||
aiChatConversationData.appendAnswer(caseAiMessageVo.getAnswer());
|
||||
aiChatConversationData.setCaseRefers(caseAiMessageVo.getCaseRefer());
|
||||
aiChatConversationData.setSuggestions(caseAiMessageVo.getSuggestions());
|
||||
aiChatConversationData.setUserId(userId);
|
||||
if (elasticSearchIndexService.createData(aiChatConversationData)) {
|
||||
return success("创建成功");
|
||||
}
|
||||
return error("创建失败");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package com.xboe.module.boecase.api;
|
||||
|
||||
import com.xboe.common.PageList;
|
||||
import com.xboe.core.JsonResponse;
|
||||
import com.xboe.core.api.ApiBaseController;
|
||||
import com.xboe.core.log.AutoLog;
|
||||
import com.xboe.module.boecase.dto.CaseDocumentLogQueryDto;
|
||||
import com.xboe.module.boecase.service.ICaseDocumentLogService;
|
||||
import com.xboe.module.boecase.service.ICaseKnowledgeService;
|
||||
import com.xboe.module.boecase.service.ICasesService;
|
||||
import com.xboe.module.boecase.entity.Cases;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.common.utils.IDGenerator;
|
||||
import com.xboe.common.utils.StringUtil;
|
||||
import java.time.LocalDateTime;
|
||||
import com.xboe.module.boecase.vo.CaseDocumentLogVo;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* AI调用日志管理API
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping(value = "/xboe/m/boe/caseDocumentLog")
|
||||
public class CaseDocumentLogApi extends ApiBaseController {
|
||||
|
||||
@Resource
|
||||
private ICaseDocumentLogService caseDocumentLogService;
|
||||
|
||||
@Resource
|
||||
private ICaseKnowledgeService caseKnowledgeService;
|
||||
|
||||
@Resource
|
||||
private ICasesService casesService;
|
||||
|
||||
/**
|
||||
* AI调用日志分页查询
|
||||
*
|
||||
* @param queryDto 查询条件
|
||||
* @return 分页结果
|
||||
*/
|
||||
@PostMapping("/pageQuery")
|
||||
@AutoLog(module = "AI调用日志", action = "分页查询", info = "AI调用日志分页查询")
|
||||
public JsonResponse<PageList<CaseDocumentLogVo>> pageQuery(@RequestBody CaseDocumentLogQueryDto queryDto) {
|
||||
try {
|
||||
PageList<CaseDocumentLogVo> result = caseDocumentLogService.pageQuery(
|
||||
queryDto.getPageIndex(),
|
||||
queryDto.getPageSize(),
|
||||
queryDto
|
||||
);
|
||||
return success(result);
|
||||
} catch (Exception e) {
|
||||
log.error("AI调用日志分页查询失败", e);
|
||||
return error("查询失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空日志(根据筛选条件)
|
||||
*
|
||||
* @param queryDto 查询条件
|
||||
* @return 删除结果
|
||||
*/
|
||||
@PostMapping("/clearLogs")
|
||||
@AutoLog(module = "AI调用日志", action = "清空日志", info = "AI调用日志清空操作")
|
||||
public JsonResponse<Integer> clearLogs(@RequestBody CaseDocumentLogQueryDto queryDto) {
|
||||
try {
|
||||
int deletedCount = caseDocumentLogService.clearLogsByCondition(queryDto);
|
||||
return success(deletedCount);
|
||||
} catch (Exception e) {
|
||||
log.error("AI调用日志清空失败", e);
|
||||
return error("清空失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试AI调用
|
||||
*
|
||||
* @param request 重试请求参数
|
||||
* @return 重试结果
|
||||
*/
|
||||
@PostMapping("/retry")
|
||||
@AutoLog(module = "AI调用日志", action = "重试调用", info = "AI调用日志重试操作")
|
||||
public JsonResponse<Boolean> retry(@RequestBody RetryRequest request) {
|
||||
try {
|
||||
boolean result = caseDocumentLogService.retryByLogId(request.getLogId());
|
||||
return success(result);
|
||||
} catch (Exception e) {
|
||||
log.error("AI调用重试失败", e);
|
||||
return error("重试失败", e.getMessage());
|
||||
}
|
||||
// 先走挡板
|
||||
// return success(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据案例ID上传案例文档到知识库
|
||||
*
|
||||
* @param request 上传请求参数
|
||||
* @return 上传结果
|
||||
*/
|
||||
@PostMapping("/uploadCaseByID")
|
||||
@AutoLog(module = "案例文档管理", action = "根据案例ID上传文档", info = "根据案例ID查询案例信息并上传文档到知识库")
|
||||
public JsonResponse<Boolean> uploadCaseById(@RequestBody UploadCaseRequest request) {
|
||||
try {
|
||||
String caseId = request.getCaseId();
|
||||
if (StringUtil.isBlank(caseId)) {
|
||||
return badRequest("案例ID不能为空");
|
||||
}
|
||||
|
||||
// 查询案例信息
|
||||
Cases caseInfo = casesService.selectById(caseId, false);
|
||||
if (caseInfo == null || caseInfo.getDeleted()) {
|
||||
return badRequest("案例不存在或已删除");
|
||||
}
|
||||
|
||||
log.info("开始上传案例文档到知识库,案例ID: {}, 案例标题: {}", caseId, caseInfo.getTitle());
|
||||
|
||||
// 调用ICaseKnowledgeService的uploadCaseDocument方法
|
||||
boolean result = caseKnowledgeService.uploadCaseDocument(caseId);
|
||||
|
||||
if (result) {
|
||||
log.info("案例文档上传成功,案例ID: {}", caseId);
|
||||
return success(result, "案例文档上传成功");
|
||||
} else {
|
||||
log.warn("案例文档上传失败,案例ID: {}", caseId);
|
||||
return success(result, "案例文档上传失败");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("根据案例ID上传文档失败", e);
|
||||
return error("上传失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接创建CaseDocumentLog数据
|
||||
*
|
||||
* @param logData 日志数据
|
||||
* @return 创建结果
|
||||
*/
|
||||
@PostMapping("/createLog")
|
||||
@AutoLog(module = "案例文档日志", action = "创建日志记录", info = "直接创建一条CaseDocumentLog数据")
|
||||
public JsonResponse<String> createLog(@RequestBody CaseDocumentLog logData) {
|
||||
try {
|
||||
// 参数校验
|
||||
if (StringUtil.isBlank(logData.getCaseId())) {
|
||||
return badRequest("案例ID不能为空");
|
||||
}
|
||||
if (StringUtil.isBlank(logData.getOptType())) {
|
||||
return badRequest("操作类型不能为空");
|
||||
}
|
||||
|
||||
// 设置必要的默认值
|
||||
if (StringUtil.isBlank(logData.getId())) {
|
||||
logData.setId(IDGenerator.generate());
|
||||
}
|
||||
if (logData.getOptTime() == null) {
|
||||
logData.setOptTime(LocalDateTime.now());
|
||||
}
|
||||
if (logData.getOptStatus() == null) {
|
||||
logData.setOptStatus(0); // 默认为调用中
|
||||
}
|
||||
if (logData.getDeleted() == null) {
|
||||
logData.setDeleted(false);
|
||||
}
|
||||
|
||||
// 如果提供了案例ID但没有案例标题,尝试查询案例信息补充标题
|
||||
if (StringUtil.isBlank(logData.getCaseTitle()) && StringUtil.isNotBlank(logData.getCaseId())) {
|
||||
try {
|
||||
Cases caseInfo = casesService.selectById(logData.getCaseId(), false);
|
||||
if (caseInfo != null) {
|
||||
logData.setCaseTitle(caseInfo.getTitle());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("查询案例标题失败,案例ID: {}", logData.getCaseId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("创建CaseDocumentLog记录,案例ID: {}, 操作类型: {}",
|
||||
logData.getCaseId(), logData.getOptType());
|
||||
|
||||
// 保存日志记录
|
||||
caseDocumentLogService.save(logData);
|
||||
|
||||
log.info("CaseDocumentLog记录创建成功,日志ID: {}", logData.getId());
|
||||
return success(logData.getId(), "日志记录创建成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("创建CaseDocumentLog记录失败", e);
|
||||
return error("创建失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文档上传回调接口
|
||||
*
|
||||
* @param request 回调请求参数
|
||||
* @return 回调结果
|
||||
*/
|
||||
@PostMapping("/uploadCallback")
|
||||
@AutoLog(module = "AI调用日志", action = "文档上传回调", info = "文档上传回调接口")
|
||||
public CallbackResponse uploadCallback(@RequestBody CallbackRequest request) {
|
||||
try {
|
||||
log.info("收到文档上传回调,taskId: {}, fileStatus: {}, message: {}",
|
||||
request.getTaskId(), request.getFileStatus(), request.getMessage());
|
||||
|
||||
boolean result = caseKnowledgeService.handleUploadCallback(
|
||||
request.getTaskId(),
|
||||
request.getMessage(),
|
||||
request.getFileStatus()
|
||||
);
|
||||
|
||||
CallbackResponse response = new CallbackResponse();
|
||||
response.setSuccess(result);
|
||||
response.setCode(result ? 0 : -1);
|
||||
response.setMessage(result ? "回调处理成功" : "回调处理失败");
|
||||
|
||||
return response;
|
||||
} catch (Exception e) {
|
||||
log.error("文档上传回调处理失败", e);
|
||||
|
||||
CallbackResponse response = new CallbackResponse();
|
||||
response.setSuccess(false);
|
||||
response.setCode(-1);
|
||||
response.setMessage("回调处理异常: " + e.getMessage());
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回调请求参数
|
||||
*/
|
||||
public static class CallbackRequest {
|
||||
private String taskId;
|
||||
private String message;
|
||||
private String fileStatus;
|
||||
|
||||
public String getTaskId() {
|
||||
return taskId;
|
||||
}
|
||||
|
||||
public void setTaskId(String taskId) {
|
||||
this.taskId = taskId;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getFileStatus() {
|
||||
return fileStatus;
|
||||
}
|
||||
|
||||
public void setFileStatus(String fileStatus) {
|
||||
this.fileStatus = fileStatus;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回调响应参数
|
||||
*/
|
||||
public static class CallbackResponse {
|
||||
private boolean success;
|
||||
private int code;
|
||||
private String message;
|
||||
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传案例请求参数
|
||||
*/
|
||||
public static class UploadCaseRequest {
|
||||
private String caseId;
|
||||
|
||||
public String getCaseId() {
|
||||
return caseId;
|
||||
}
|
||||
|
||||
public void setCaseId(String caseId) {
|
||||
this.caseId = caseId;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试请求参数
|
||||
*/
|
||||
public static class RetryRequest {
|
||||
private String logId;
|
||||
|
||||
public String getLogId() {
|
||||
return logId;
|
||||
}
|
||||
|
||||
public void setLogId(String logId) {
|
||||
this.logId = logId;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.xboe.module.boecase.api;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* 案例上传任务API
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/xboe/m/boe/caseUpload")
|
||||
public class CaseUploadTaskApi {
|
||||
|
||||
@Autowired
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
private static final String CASE_UPLOAD_LAST_ID_KEY = "case:upload:last:id";
|
||||
|
||||
/**
|
||||
* 清除处理位置标记,使下次任务从头开始执行
|
||||
*/
|
||||
@PostMapping("/reset")
|
||||
public void resetLastProcessedId() {
|
||||
stringRedisTemplate.delete(CASE_UPLOAD_LAST_ID_KEY);
|
||||
log.info("已清除上次处理位置标记");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.xboe.module.boecase.async;
|
||||
|
||||
import com.xboe.enums.CaseDocumentLogOptTypeEnum;
|
||||
import com.xboe.module.boecase.entity.Cases;
|
||||
import com.xboe.module.boecase.service.ICaseKnowledgeService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class CaseAiDocumentAsyncHandler {
|
||||
|
||||
private final AtomicInteger currentTaskCount = new AtomicInteger(0);
|
||||
|
||||
/**
|
||||
* 限流,默认QPS 40
|
||||
*/
|
||||
private final TokenBucketRateLimiter rateLimiter = new TokenBucketRateLimiter(40);
|
||||
|
||||
@Autowired
|
||||
@Qualifier("aiDocExecutor")
|
||||
private ThreadPoolTaskExecutor aiDocExecutor;
|
||||
|
||||
@Autowired
|
||||
private ICaseKnowledgeService caseKnowledgeService;
|
||||
|
||||
public void process(CaseDocumentLogOptTypeEnum optTypeEnum, Cases... caseList) {
|
||||
for (Cases cases : caseList) {
|
||||
// 控制并发数量
|
||||
while (currentTaskCount.get() >= 5) {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
currentTaskCount.incrementAndGet();
|
||||
|
||||
aiDocExecutor.submit(() -> {
|
||||
try {
|
||||
// 限流
|
||||
rateLimiter.acquire();
|
||||
processCases(cases, optTypeEnum);
|
||||
} finally {
|
||||
currentTaskCount.decrementAndGet();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void processCases(Cases cases, CaseDocumentLogOptTypeEnum optTypeEnum) {
|
||||
try {
|
||||
switch (optTypeEnum) {
|
||||
case UPDATE:
|
||||
caseKnowledgeService.updateCaseDocument(cases);
|
||||
break;
|
||||
case DELETE:
|
||||
caseKnowledgeService.deleteCaseDocument(cases);
|
||||
break;
|
||||
case CREATE:
|
||||
default:
|
||||
caseKnowledgeService.uploadCaseDocument(cases);
|
||||
break;
|
||||
}
|
||||
log.info("处理案例成功,caseId: {}, 操作类型: {}", cases.getId(), optTypeEnum.getDesc());
|
||||
} catch (Exception e) {
|
||||
log.error("处理案例失败,caseId: {}, 操作类型: {}", cases.getId(), optTypeEnum.getDesc(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.xboe.module.boecase.async;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* 令牌桶限流算法实现
|
||||
*/
|
||||
public class TokenBucketRateLimiter {
|
||||
|
||||
private final double permitsPerSecond; // 每秒生成的令牌数(即 TPS)
|
||||
private final AtomicLong nextFreeTicketMicros = new AtomicLong(0); // 下一个令牌可用的时间(微秒)
|
||||
private final AtomicLong storedPermits = new AtomicLong(0); // 当前桶中存储的令牌数(本简化版不支持突发,可省略)
|
||||
private static final long MICROSECONDS_PER_SECOND = 1_000_000L;
|
||||
|
||||
public TokenBucketRateLimiter(double permitsPerSecond) {
|
||||
this.permitsPerSecond = permitsPerSecond;
|
||||
this.nextFreeTicketMicros.set(System.nanoTime() / 1000); // 初始化为当前时间(微秒)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个令牌,阻塞直到可用
|
||||
*/
|
||||
public void acquire() {
|
||||
long waitMicros = reserve(1);
|
||||
if (waitMicros > 0) {
|
||||
try {
|
||||
long waitNanos = waitMicros * 1000; // 转为纳秒
|
||||
TimeUnit.NANOSECONDS.sleep(waitNanos);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 预留 1 个令牌,返回需要等待的微秒数
|
||||
*/
|
||||
private long reserve(int permits) {
|
||||
long nowMicros = System.nanoTime() / 1000;
|
||||
long nextFreeTicket = nextFreeTicketMicros.get();
|
||||
long waitMicros = Math.max(0, nextFreeTicket - nowMicros);
|
||||
|
||||
long newNextFreeTicket = nowMicros + waitMicros + (long) (permits * MICROSECONDS_PER_SECOND / permitsPerSecond);
|
||||
while (!nextFreeTicketMicros.compareAndSet(nextFreeTicket, newNextFreeTicket)) {
|
||||
// CAS 失败,说明其他线程修改了时间,重试
|
||||
nowMicros = System.nanoTime() / 1000;
|
||||
nextFreeTicket = nextFreeTicketMicros.get();
|
||||
waitMicros = Math.max(0, nextFreeTicket - nowMicros);
|
||||
newNextFreeTicket = nowMicros + waitMicros + (long) (permits * MICROSECONDS_PER_SECOND / permitsPerSecond);
|
||||
}
|
||||
|
||||
return waitMicros;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.xboe.module.boecase.dao;
|
||||
|
||||
import com.xboe.core.orm.BaseDao;
|
||||
import com.xboe.core.orm.FieldFilters;
|
||||
import com.xboe.module.boecase.entity.CaseAiConversations;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* 案例AI会话信息DAO
|
||||
*/
|
||||
@Repository
|
||||
public class CaseAiConversationsDao extends BaseDao<CaseAiConversations> {
|
||||
|
||||
/**
|
||||
* 根据主键ID查询AI会话ID
|
||||
* @param conversationId 主键ID
|
||||
* @return AI会话ID
|
||||
*/
|
||||
public String findAiConversationIdById(String conversationId) {
|
||||
CaseAiConversations conversation = this.getGenericDao().findOne(CaseAiConversations.class,
|
||||
FieldFilters.eq("ai_conversation_id", conversationId));
|
||||
return conversation != null ? conversation.getAiConversationId() : conversationId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.xboe.module.boecase.dao;
|
||||
|
||||
import com.xboe.core.orm.BaseDao;
|
||||
import com.xboe.core.orm.FieldFilters;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* AI调用日志DAO
|
||||
*/
|
||||
@Repository
|
||||
@Slf4j
|
||||
public class CaseDocumentLogDao extends BaseDao<CaseDocumentLog> {
|
||||
|
||||
/**
|
||||
* 根据taskId查询文档日志
|
||||
* @param taskId 任务ID
|
||||
* @return 文档日志
|
||||
*/
|
||||
public CaseDocumentLog findByTaskId(String taskId) {
|
||||
return this.getGenericDao().findOne(CaseDocumentLog.class,
|
||||
FieldFilters.eq("taskId", taskId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.xboe.module.boecase.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* AI对话入参
|
||||
*/
|
||||
@Data
|
||||
public class CaseAiChatDto {
|
||||
|
||||
/**
|
||||
* 对话id
|
||||
* 如果是新对话,传空
|
||||
*/
|
||||
private String conversationId;
|
||||
|
||||
/**
|
||||
* 提问内容
|
||||
*/
|
||||
private String query;
|
||||
|
||||
/**
|
||||
* 是否开启思考
|
||||
* 0-否 1-是
|
||||
*/
|
||||
private Integer enableThinking;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.xboe.module.boecase.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* AI调用日志查询条件DTO
|
||||
*/
|
||||
@Data
|
||||
public class CaseDocumentLogQueryDto extends PageDto {
|
||||
|
||||
/**
|
||||
* 案例标题(模糊查询)
|
||||
*/
|
||||
private String caseTitle;
|
||||
|
||||
/**
|
||||
* 操作类型(create-新增,delete-删除,update-更改)
|
||||
*/
|
||||
private String optType;
|
||||
|
||||
/**
|
||||
* 调用时间开始
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime optTimeStart;
|
||||
|
||||
/**
|
||||
* 调用时间结束
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime optTimeEnd;
|
||||
|
||||
/**
|
||||
* 接口调用状态
|
||||
* 0-调用中, 1-调用成功, 2-调用失败
|
||||
*/
|
||||
private Integer optStatus;
|
||||
|
||||
/**
|
||||
* 业务处理状态
|
||||
* 1-处理成功, 2-处理失败
|
||||
*/
|
||||
private Integer caseStatus;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.xboe.module.boecase.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.xboe.module.boecase.vo.CaseReferVo;
|
||||
import lombok.Data;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* AI聊天会话数据实体
|
||||
* 纯数据容器,不与数据库交互
|
||||
*
|
||||
* @author AI Assistant
|
||||
*/
|
||||
@Data
|
||||
@Slf4j
|
||||
public class AiChatConversationData {
|
||||
|
||||
/**
|
||||
* 会话ID
|
||||
*/
|
||||
private String conversationId;
|
||||
|
||||
/**
|
||||
* 用户提问内容
|
||||
*/
|
||||
private String query;
|
||||
|
||||
/**
|
||||
* AI回答内容(使用StringBuilder收集流式数据)
|
||||
*/
|
||||
private StringBuilder answer = new StringBuilder();
|
||||
|
||||
/**
|
||||
* 案例引用列表
|
||||
*/
|
||||
private List<CaseReferVo> caseRefers = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* 建议列表
|
||||
*/
|
||||
private List<String> suggestions = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* 用户ID
|
||||
*/
|
||||
private String userId;
|
||||
|
||||
/**
|
||||
* 用户名称
|
||||
*/
|
||||
private String userName;
|
||||
|
||||
/**
|
||||
* 消息时间戳
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
/**
|
||||
* 消息时间戳
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime timestamp;
|
||||
|
||||
/**
|
||||
* 聊天时长(秒)
|
||||
*/
|
||||
private Integer durationSeconds;
|
||||
|
||||
// ================== 构造函数 ==================
|
||||
|
||||
public AiChatConversationData() {
|
||||
this.startTime = LocalDateTime.now();
|
||||
}
|
||||
|
||||
// ================== 便捷方法 ==================
|
||||
|
||||
/**
|
||||
* 获取回答内容的字符串形式
|
||||
*/
|
||||
public String getAnswerAsString() {
|
||||
return this.answer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加回答内容
|
||||
*/
|
||||
public void appendAnswer(String content) {
|
||||
if (content != null) {
|
||||
this.answer.append(content);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加案例引用
|
||||
*/
|
||||
public void addCaseRefer(CaseReferVo caseRefer) {
|
||||
if (caseRefer != null) {
|
||||
this.caseRefers.add(caseRefer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加建议
|
||||
*/
|
||||
public void addSuggestion(String suggestion) {
|
||||
if (suggestion != null && !suggestion.trim().isEmpty()) {
|
||||
this.suggestions.add(suggestion);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.xboe.module.boecase.entity;
|
||||
|
||||
import com.xboe.core.SysConstant;
|
||||
import com.xboe.core.orm.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Table;
|
||||
|
||||
/**
|
||||
* 案例AI会话信息表
|
||||
*/
|
||||
@Data
|
||||
@Entity
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Table(name = SysConstant.TABLE_PRE + "case_ai_conversations")
|
||||
public class CaseAiConversations extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 会话ID(由AI平台提供)
|
||||
*/
|
||||
@Column(name = "ai_conversation_id", length = 100)
|
||||
private String aiConversationId;
|
||||
|
||||
/**
|
||||
* 会话名称
|
||||
*/
|
||||
@Column(name = "conversation_name", length = 200)
|
||||
private String conversationName;
|
||||
|
||||
/**
|
||||
* 会话对应用户ID
|
||||
*/
|
||||
@Column(name = "conversation_user", length = 50)
|
||||
private String conversationUser;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.xboe.module.boecase.entity;
|
||||
|
||||
import com.xboe.core.SysConstant;
|
||||
import com.xboe.core.orm.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 案例文档日志信息表
|
||||
*/
|
||||
@Data
|
||||
@Entity
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Table(name = SysConstant.TABLE_PRE + "case_document_log")
|
||||
public class CaseDocumentLog extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 任务ID
|
||||
*/
|
||||
@Column(name = "task_id", length = 20)
|
||||
private String taskId;
|
||||
|
||||
/**
|
||||
* 案例id
|
||||
*/
|
||||
@Column(name = "case_id", length = 20)
|
||||
private String caseId;
|
||||
|
||||
/**
|
||||
* 案例标题
|
||||
*/
|
||||
@Column(name = "case_title", length = 200)
|
||||
private String caseTitle;
|
||||
|
||||
/**
|
||||
* 操作类型
|
||||
*/
|
||||
@Column(name = "opt_type")
|
||||
private String optType;
|
||||
|
||||
/**
|
||||
* 请求地址
|
||||
*/
|
||||
@Column(name = "request_url", length = 500)
|
||||
private String requestUrl;
|
||||
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
@Column(name = "request_body", length = 4000)
|
||||
private String requestBody;
|
||||
|
||||
/**
|
||||
* 响应参数
|
||||
*/
|
||||
@Column(name = "response_body", length = 4000)
|
||||
private String responseBody;
|
||||
|
||||
/**
|
||||
* 调用时间
|
||||
*/
|
||||
@Column(name = "opt_time")
|
||||
private LocalDateTime optTime;
|
||||
|
||||
/**
|
||||
* 接口运行状态
|
||||
* 0-运行中, 1-运行完毕
|
||||
*/
|
||||
@Column(name = "run_status")
|
||||
private Integer runStatus;
|
||||
|
||||
/**
|
||||
* 接口调用状态
|
||||
* 0-调用中, 1-调用成功, 2-调用失败
|
||||
*/
|
||||
@Column(name = "opt_status")
|
||||
private Integer optStatus;
|
||||
|
||||
/**
|
||||
* 业务处理状态
|
||||
* 1-处理成功, 2-处理失败
|
||||
*/
|
||||
@Column(name = "case_status")
|
||||
private Integer caseStatus;
|
||||
|
||||
/**
|
||||
* 执行时间(ms)
|
||||
*/
|
||||
@Column(name = "execute_duration")
|
||||
private Long executeDuration;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.xboe.module.boecase.properties;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 案例专家AI相关配置项
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "xboe.case.ai")
|
||||
@Data
|
||||
public class CaseAiProperties {
|
||||
|
||||
/**
|
||||
* 接口地址
|
||||
*/
|
||||
private String baseUrl;
|
||||
|
||||
/**
|
||||
* appKey
|
||||
*/
|
||||
private String appKey;
|
||||
|
||||
/**
|
||||
* appSecret
|
||||
*/
|
||||
private String secretKey;
|
||||
|
||||
/**
|
||||
* ai接口的apiCode
|
||||
*/
|
||||
private String aiApiCode;
|
||||
|
||||
/**
|
||||
* 对话接口的apiCode
|
||||
*/
|
||||
private String chatApiCode;
|
||||
|
||||
/**
|
||||
* 案例知识库id
|
||||
*/
|
||||
private String caseKnowledgeId;
|
||||
|
||||
/**
|
||||
* 默认上传用户
|
||||
* 当获取不到当前登录用户信息时会取这个
|
||||
*/
|
||||
private String defaultUploadUser;
|
||||
|
||||
/**
|
||||
* 案例详情页面地址
|
||||
*/
|
||||
private String caseDetailUrlBase;
|
||||
|
||||
/**
|
||||
* 文件上传是否使用回调接口
|
||||
*/
|
||||
private boolean fileUploadUseCallback;
|
||||
|
||||
/**
|
||||
* 文档上传回调接口地址
|
||||
*/
|
||||
private String fileUploadCallbackUrl;
|
||||
|
||||
/**
|
||||
* 是否启用白名单
|
||||
*/
|
||||
private boolean useWhiteList;
|
||||
|
||||
/**
|
||||
* 白名单用户列表
|
||||
*/
|
||||
private List<String> whiteUserCodeList;
|
||||
|
||||
/**
|
||||
* AI处理失败告警邮件收件人列表
|
||||
*/
|
||||
private List<String> alertEmailRecipients;
|
||||
|
||||
/**
|
||||
* 是否发送AI对话记录到邮箱
|
||||
*/
|
||||
private boolean aiChatDataSendEmail;
|
||||
|
||||
/**
|
||||
* AI对话记录保存根路径
|
||||
*/
|
||||
private String aiChatRootPath;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
/**
|
||||
* 获取accesstoken
|
||||
*/
|
||||
public interface IAiAccessTokenService {
|
||||
|
||||
/**
|
||||
* 获取accesstoken
|
||||
* @return
|
||||
*/
|
||||
String getAccessToken();
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
import com.xboe.core.CurrentUser;
|
||||
import com.xboe.module.boecase.dto.CaseAiChatDto;
|
||||
import com.xboe.module.boecase.entity.CaseAiConversations;
|
||||
import com.xboe.module.boecase.vo.CaseAiMessageVo;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* AI案例对话
|
||||
*/
|
||||
public interface ICaseAiChatService {
|
||||
|
||||
/**
|
||||
* 聊天
|
||||
*
|
||||
* @param caseAiChatDto
|
||||
* @param currentUser
|
||||
* @return
|
||||
*/
|
||||
SseEmitter chat(CaseAiChatDto caseAiChatDto, CurrentUser currentUser);
|
||||
|
||||
/**
|
||||
* 创建新的AI对话会话
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param conversationName 对话名称
|
||||
* @return 创建的会话信息
|
||||
*/
|
||||
CaseAiConversations createNewConversation(String userId, String conversationName);
|
||||
|
||||
/**
|
||||
* 根据conversationId查看会话内消息记录
|
||||
*
|
||||
* @param conversationId 会话ID
|
||||
* @return 消息记录列表
|
||||
*/
|
||||
List<CaseAiMessageVo> getConversationMessages(String conversationId);
|
||||
|
||||
/**
|
||||
* 导出会话记录为Excel
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @param response
|
||||
*/
|
||||
void getConversationExcel(LocalDateTime startTime, LocalDateTime endTime, HttpServletResponse response);
|
||||
|
||||
/**
|
||||
* 导出会话记录为Excel
|
||||
*
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
*/
|
||||
void downloadConversationExcel(LocalDateTime startTime, LocalDateTime endTime);
|
||||
|
||||
/**
|
||||
* 停止当前聊天输出
|
||||
*
|
||||
* @param conversationId 会话ID
|
||||
* @return 是否成功停止
|
||||
*/
|
||||
boolean stopChatOutput(String conversationId);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
/**
|
||||
* 案例AI权限服务接口
|
||||
*/
|
||||
public interface ICaseAiPermissionService {
|
||||
|
||||
/**
|
||||
* 判断指定用户是否显示"案例专家"功能入口
|
||||
* @param userCode 用户编码
|
||||
* @return 是否显示功能入口
|
||||
*/
|
||||
boolean shouldShowCaseAiEntrance(String userCode);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
import com.xboe.common.PageList;
|
||||
import com.xboe.module.boecase.dto.CaseDocumentLogQueryDto;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.module.boecase.vo.CaseDocumentLogVo;
|
||||
|
||||
/**
|
||||
* AI调用日志Service接口
|
||||
*/
|
||||
public interface ICaseDocumentLogService {
|
||||
|
||||
/**
|
||||
* 分页查询AI调用日志
|
||||
*
|
||||
* @param pageIndex 页码
|
||||
* @param pageSize 每页大小
|
||||
* @param queryDto 查询条件
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageList<CaseDocumentLogVo> pageQuery(int pageIndex, int pageSize, CaseDocumentLogQueryDto queryDto);
|
||||
|
||||
/**
|
||||
* 根据查询条件清空日志
|
||||
* 仅删除当前筛选条件下的日志记录,非筛选范围内的日志不受影响
|
||||
*
|
||||
* @param queryDto 查询条件
|
||||
* @return 删除的记录数
|
||||
*/
|
||||
int clearLogsByCondition(CaseDocumentLogQueryDto queryDto);
|
||||
|
||||
/**
|
||||
* 根据logId重试AI调用
|
||||
* 查询原始日志数据,重试执行后添加新的日志记录
|
||||
*
|
||||
* @param logId 日志ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean retryByLogId(String logId);
|
||||
|
||||
/**
|
||||
* 保存日志记录
|
||||
*
|
||||
* @param log 日志对象
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean save(CaseDocumentLog log);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.module.boecase.entity.Cases;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* 案例-知识库
|
||||
*/
|
||||
public interface ICaseKnowledgeService {
|
||||
|
||||
/**
|
||||
* 上传案例文档
|
||||
*
|
||||
* @param caseId 案例ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean uploadCaseDocument(String caseId);
|
||||
|
||||
/**
|
||||
* 上传案例文档
|
||||
*
|
||||
* @param cases 案例
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean uploadCaseDocument(Cases cases);
|
||||
|
||||
/**
|
||||
* 删除案例文档
|
||||
*
|
||||
* @param caseId 案例ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean deleteCaseDocument(String caseId);
|
||||
|
||||
/**
|
||||
* 删除案例文档
|
||||
*
|
||||
* @param cases 案例
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean deleteCaseDocument(Cases cases);
|
||||
|
||||
/**
|
||||
* 更新案例文档
|
||||
*
|
||||
* @param caseId 案例ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean retryCaseDocument(String caseId, CaseDocumentLog originalLog);
|
||||
|
||||
/**
|
||||
* 更新案例文档
|
||||
*
|
||||
* @param cases 案例
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean updateCaseDocument(Cases cases);
|
||||
|
||||
/**
|
||||
* 处理文档上传回调
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
* @param message 回调信息
|
||||
* @param fileStatus 文件状态(vectored: 成功, failed: 失败)
|
||||
* @return 是否处理成功
|
||||
*/
|
||||
boolean handleUploadCallback(String taskId, String message, String fileStatus);
|
||||
|
||||
/**
|
||||
* 批量检查文件状态
|
||||
*/
|
||||
@Transactional(rollbackFor = Throwable.class)
|
||||
void batchCheckFileStatus();
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
import com.xboe.module.boecase.entity.AiChatConversationData;
|
||||
import com.xboe.module.boecase.vo.CaseAiMessageVo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* es索引
|
||||
*/
|
||||
public interface IElasticSearchIndexService {
|
||||
|
||||
/**
|
||||
* 查看索引是否存在
|
||||
* @return
|
||||
*/
|
||||
boolean checkIndexExists();
|
||||
|
||||
/**
|
||||
* 创建索引
|
||||
*/
|
||||
boolean createIndex();
|
||||
|
||||
/**
|
||||
* 删除索引
|
||||
* @return
|
||||
*/
|
||||
boolean deleteIndex();
|
||||
|
||||
/**
|
||||
* 新增数据
|
||||
* @param data
|
||||
* @return
|
||||
*/
|
||||
boolean createData(AiChatConversationData data);
|
||||
|
||||
/**
|
||||
* 查询数据
|
||||
* @param conversationId
|
||||
* @return
|
||||
*/
|
||||
List<CaseAiMessageVo> queryData(String conversationId);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.xboe.module.boecase.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.xboe.common.utils.StringUtil;
|
||||
import com.xboe.module.boecase.properties.CaseAiProperties;
|
||||
import com.xboe.module.boecase.service.IAiAccessTokenService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@EnableConfigurationProperties({CaseAiProperties.class})
|
||||
@Service
|
||||
@Slf4j(topic = "caseAiChatLogger")
|
||||
public class AiAccessTokenServiceImpl implements IAiAccessTokenService {
|
||||
|
||||
private static final String ACCESS_TOKEN_CACHE_KEY = "case_ai_access_token";
|
||||
|
||||
@Autowired
|
||||
private CaseAiProperties caseAiProperties;
|
||||
|
||||
@Autowired
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
@Override
|
||||
public String getAccessToken() {
|
||||
// 1. 先从Redis缓存中获取
|
||||
String cachedToken = stringRedisTemplate.opsForValue().get(ACCESS_TOKEN_CACHE_KEY);
|
||||
if (StringUtil.isNotBlank(cachedToken)) {
|
||||
return cachedToken;
|
||||
}
|
||||
|
||||
// 2. 缓存中没有,重新获取
|
||||
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||
String tokenUrl = caseAiProperties.getBaseUrl() + "/apigateway/secret/getAppAccessToken" +
|
||||
"?appKey=" + URLEncoder.encode(caseAiProperties.getAppKey(), StandardCharsets.UTF_8.name()) +
|
||||
"&secretKey=" + URLEncoder.encode(caseAiProperties.getSecretKey(), StandardCharsets.UTF_8.name());
|
||||
|
||||
HttpGet httpGet = new HttpGet(tokenUrl);
|
||||
|
||||
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
|
||||
int statusCode = response.getStatusLine().getStatusCode();
|
||||
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
|
||||
|
||||
if (statusCode == 200) {
|
||||
JSONObject result = JSON.parseObject(responseBody);
|
||||
if (result.getIntValue("code") == 0 && result.getBooleanValue("success")) {
|
||||
JSONObject data = result.getJSONObject("data");
|
||||
String accessToken = data.getString("accessToken");
|
||||
Integer expiresIn = data.getInteger("expiresIn");
|
||||
if (expiresIn == null) {
|
||||
expiresIn = 7200;
|
||||
}
|
||||
|
||||
// 3. 存储到Redis,设置过期时间(提前5分钟过期)
|
||||
int cacheSeconds = Math.max(expiresIn - 300, 60);
|
||||
stringRedisTemplate.opsForValue().set(ACCESS_TOKEN_CACHE_KEY, accessToken,
|
||||
cacheSeconds, TimeUnit.SECONDS);
|
||||
|
||||
log.info("获取access_token成功,过期时间: {}秒", expiresIn);
|
||||
return accessToken;
|
||||
} else {
|
||||
log.error("获取access_token失败,接口返回失败,response: {}", responseBody);
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
log.error("获取access_token失败,HTTP请求失败,status: {}, response: {}",
|
||||
statusCode, responseBody);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("获取access_token异常", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,860 @@
|
||||
package com.xboe.module.boecase.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.xboe.core.CurrentUser;
|
||||
import com.xboe.core.orm.FieldFilters;
|
||||
import com.xboe.enums.CaseAiChatStatusEnum;
|
||||
import com.xboe.module.boecase.dao.CaseAiConversationsDao;
|
||||
import com.xboe.module.boecase.dao.CaseDocumentLogDao;
|
||||
import com.xboe.module.boecase.dao.CasesDao;
|
||||
import com.xboe.module.boecase.dto.CaseAiChatDto;
|
||||
import com.xboe.module.boecase.entity.CaseAiConversations;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.module.boecase.entity.Cases;
|
||||
import com.xboe.module.boecase.properties.CaseAiProperties;
|
||||
import com.xboe.module.boecase.service.IAiAccessTokenService;
|
||||
import com.xboe.module.boecase.service.ICaseAiChatService;
|
||||
import com.xboe.module.boecase.service.IElasticSearchIndexService;
|
||||
import com.xboe.module.boecase.vo.CaseAiMessageVo;
|
||||
import com.xboe.module.boecase.vo.CaseReferVo;
|
||||
import com.xboe.module.boecase.entity.AiChatConversationData;
|
||||
import com.xboe.module.boecase.vo.ConversationExcelVo;
|
||||
import com.xboe.system.organization.vo.OrgSimpleVo;
|
||||
import com.xboe.system.user.service.IUserService;
|
||||
import lombok.Data;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import okhttp3.*;
|
||||
import okhttp3.sse.EventSource;
|
||||
import okhttp3.sse.EventSourceListener;
|
||||
import okhttp3.sse.EventSources;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.elasticsearch.action.index.IndexRequest;
|
||||
import org.elasticsearch.action.index.IndexResponse;
|
||||
import org.elasticsearch.action.search.SearchRequest;
|
||||
import org.elasticsearch.action.search.SearchResponse;
|
||||
import org.elasticsearch.client.RequestOptions;
|
||||
import org.elasticsearch.client.RestHighLevelClient;
|
||||
import org.elasticsearch.common.xcontent.XContentType;
|
||||
import org.elasticsearch.index.query.QueryBuilders;
|
||||
import org.elasticsearch.search.SearchHit;
|
||||
import org.elasticsearch.search.SearchHits;
|
||||
import org.elasticsearch.search.builder.SearchSourceBuilder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@EnableConfigurationProperties({CaseAiProperties.class})
|
||||
@Service
|
||||
@Slf4j(topic = "caseAiChatLogger")
|
||||
public class CaseAiChatServiceImpl implements ICaseAiChatService {
|
||||
|
||||
private static final String SYS_ERR_MSG = "服务繁忙,请稍后再试。";
|
||||
|
||||
@Autowired
|
||||
private CaseAiProperties caseAiProperties;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("customDispatcher")
|
||||
private Dispatcher dispatcher;
|
||||
|
||||
@Autowired
|
||||
private IAiAccessTokenService aiAccessTokenService;
|
||||
|
||||
@Autowired
|
||||
private IUserService userService;
|
||||
|
||||
@Autowired
|
||||
private CaseAiConversationsDao caseAiConversationsDao;
|
||||
|
||||
@Autowired
|
||||
private IElasticSearchIndexService elasticSearchIndexService;
|
||||
|
||||
@Autowired
|
||||
private CaseDocumentLogDao caseDocumentLogDao;
|
||||
|
||||
@Autowired
|
||||
private CasesDao casesDao;
|
||||
|
||||
// 用于存储会话ID与EventSource的映射关系,以便能够中断特定会话
|
||||
private final Map<String, EventSource> conversationEventSourceMap = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public SseEmitter chat(CaseAiChatDto caseAiChatDto, CurrentUser currentUser) {
|
||||
// 创建SSE响应器
|
||||
SseEmitter sseEmitter = new SseEmitter();
|
||||
// 1. 获取conversationId
|
||||
String conversationId;
|
||||
try {
|
||||
conversationId = getOrCreateConversationId(caseAiChatDto, currentUser);
|
||||
} catch (Exception e) {
|
||||
log.error("获取会话ID失败", e);
|
||||
errMessage(sseEmitter, null, SYS_ERR_MSG);
|
||||
sseEmitter.complete();
|
||||
return sseEmitter;
|
||||
}
|
||||
|
||||
// 2. 查询历史
|
||||
List<CaseAiMessageVo> historyMessages = elasticSearchIndexService.queryData(conversationId);
|
||||
|
||||
// 3. 构建请求参数
|
||||
String userId = currentUser.getCode();
|
||||
|
||||
// 6. 用于收集对话数据的容器
|
||||
AiChatConversationData conversationData = new AiChatConversationData();
|
||||
conversationData.setQuery(caseAiChatDto.getQuery());
|
||||
conversationData.setConversationId(conversationId);
|
||||
conversationData.setUserId(userId);
|
||||
|
||||
String kId = caseAiProperties.getCaseKnowledgeId();
|
||||
JSONObject chatParam = new JSONObject();
|
||||
chatParam.put("userId", userId);
|
||||
JSONArray kIds = new JSONArray();
|
||||
kIds.add(kId);
|
||||
chatParam.put("kIds", kIds);
|
||||
chatParam.put("query", caseAiChatDto.getQuery());
|
||||
chatParam.put("conversationId", conversationId);
|
||||
chatParam.put("enableThinking", Objects.equals(caseAiChatDto.getEnableThinking(), 1));
|
||||
if (historyMessages != null && !historyMessages.isEmpty()) {
|
||||
// 最多10条历史,从后往前
|
||||
JSONArray historyList = new JSONArray();
|
||||
int size = historyMessages.size();
|
||||
int startIndex = Math.max(0, size - 10);
|
||||
for (int i = startIndex; i < size; i++) {
|
||||
JSONObject conversationDetail = new JSONObject();
|
||||
CaseAiMessageVo message = historyMessages.get(i);
|
||||
conversationDetail.put("query", message.getQuery());
|
||||
conversationDetail.put("content", message.getAnswer());
|
||||
historyList.add(conversationDetail);
|
||||
}
|
||||
chatParam.put("historyList", historyList);
|
||||
}
|
||||
String chatParamStr = chatParam.toJSONString();
|
||||
log.info("案例问答接口请求参数: [{}]", chatParamStr);
|
||||
|
||||
// 4. 设置请求头
|
||||
String accessToken;
|
||||
try {
|
||||
accessToken = aiAccessTokenService.getAccessToken();
|
||||
if (org.apache.commons.lang3.StringUtils.isBlank(accessToken)) {
|
||||
errMessage(sseEmitter, conversationId, SYS_ERR_MSG);
|
||||
sseEmitter.complete();
|
||||
conversationData.appendAnswer(SYS_ERR_MSG);
|
||||
elasticSearchIndexService.createData(conversationData);
|
||||
return sseEmitter;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("获取access_token失败", e);
|
||||
errMessage(sseEmitter, conversationId, SYS_ERR_MSG);
|
||||
conversationData.appendAnswer(SYS_ERR_MSG);
|
||||
elasticSearchIndexService.createData(conversationData);
|
||||
sseEmitter.complete();
|
||||
return sseEmitter;
|
||||
}
|
||||
String apiCode = caseAiProperties.getChatApiCode();
|
||||
Request.Builder builder = new Request.Builder();
|
||||
builder.url(caseAiProperties.getBaseUrl() + "/apigateway/chat/knowledge/v1/chat/completions");
|
||||
builder.addHeader("access_token", accessToken);
|
||||
builder.addHeader("X-AI-ApiCode", apiCode);
|
||||
RequestBody bodyRequestBody = RequestBody.create(chatParamStr, MediaType.parse("application/json"));
|
||||
builder.post(bodyRequestBody);
|
||||
Request request = builder.build();
|
||||
|
||||
// 7. 创建事件监听器
|
||||
EventSourceListener listener = new EventSourceListener() {
|
||||
@Override
|
||||
public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
|
||||
log.info("调用接口 [{}] 接口开始监听", request.url());
|
||||
// 将EventSource存储到Map中,以便后续可以中断
|
||||
conversationEventSourceMap.put(conversationId, eventSource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClosed(@NotNull EventSource eventSource) {
|
||||
log.info("调用接口 [{}] 接口关闭", request.url());
|
||||
// 对话完成,保存到ES
|
||||
elasticSearchIndexService.createData(conversationData);
|
||||
// 从Map中移除已完成的会话
|
||||
conversationEventSourceMap.remove(conversationId);
|
||||
sseEmitter.complete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
|
||||
log.info("调用接口 [{}] 监听数据 id: [{}] type: [{}] data: [{}]", request.url(), id, type, data);
|
||||
|
||||
try {
|
||||
// 解析返回的数据
|
||||
JSONObject jsonData = JSONObject.parseObject(data);
|
||||
if (jsonData.getBooleanValue("success") && jsonData.getIntValue("code") == 0) {
|
||||
JSONObject responseData = jsonData.getJSONObject("data");
|
||||
Integer status = responseData.getInteger("status");
|
||||
|
||||
if (status != null) {
|
||||
CaseAiChatStatusEnum statusEnum = CaseAiChatStatusEnum.getByCode(status);
|
||||
if (statusEnum == CaseAiChatStatusEnum.REFERS) { // 返回引用文件
|
||||
// 处理文件引用并构建返给前端的数据
|
||||
JSONObject modifiedData = handleFileReferAndBuildResponse(responseData, conversationData);
|
||||
if (modifiedData != null) {
|
||||
// 发送修改后的数据给前端
|
||||
sseEmitter.send(modifiedData.toJSONString());
|
||||
return; // 早期返回,不发送原始数据
|
||||
}
|
||||
} else if (statusEnum == CaseAiChatStatusEnum.CHAT) { // 流式对话中
|
||||
String content = responseData.getString("content");
|
||||
if (content != null) {
|
||||
conversationData.appendAnswer(content);
|
||||
}
|
||||
} else if (statusEnum == CaseAiChatStatusEnum.SUGGESTIONS) { // 返回建议
|
||||
handleSuggestions(responseData, conversationData);
|
||||
} else if (statusEnum == CaseAiChatStatusEnum.CHAT_COMPLETED || statusEnum == CaseAiChatStatusEnum.API_COMPLETED) { // 接口交互完成
|
||||
// 不做特殊处理
|
||||
} else {
|
||||
// 异常问题,取message内容
|
||||
String message = jsonData.getString("message");
|
||||
errMessage(sseEmitter, conversationId, message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
sseEmitter.send(responseData.toJSONString());
|
||||
} else {
|
||||
sseEmitter.send(data);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("调用接口处理监听数据时发生异常", e);
|
||||
} catch (Exception e) {
|
||||
log.error("解析EventStream数据异常", e);
|
||||
try {
|
||||
sseEmitter.send(data); // 即使解析失败也要发送原始数据
|
||||
} catch (IOException ioException) {
|
||||
log.error("发送数据到前端失败", ioException);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable e, @Nullable Response response) {
|
||||
if (e == null) {
|
||||
sseEmitter.completeWithError(new RuntimeException("调用接口异常, 异常未捕获"));
|
||||
return;
|
||||
}
|
||||
log.error("调用接口 [{}] 接口异常", request.url(), e);
|
||||
if (isTimeoutException(e)) {
|
||||
log.warn("接口调用超时,conversationId: {}", conversationId);
|
||||
errMessage(sseEmitter, conversationId, SYS_ERR_MSG);
|
||||
sseEmitter.complete();
|
||||
// 从Map中移除失败的会话
|
||||
conversationEventSourceMap.remove(conversationId);
|
||||
|
||||
// 即使失败,也要将已有的对话数据保存到ES
|
||||
conversationData.appendAnswer(SYS_ERR_MSG);
|
||||
elasticSearchIndexService.createData(conversationData);
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果是 content-type 错误,尝试作为普通 HTTP 请求处理
|
||||
if (e instanceof IllegalStateException && e.getMessage() != null && e.getMessage().contains("Invalid content-type")) {
|
||||
log.warn("服务器返回的 Content-Type 不是 text/event-stream,尝试作为普通 HTTP 请求处理");
|
||||
handleAsRegularHttpRequest(request, sseEmitter, conversationData);
|
||||
// 从Map中移除失败的会话
|
||||
conversationEventSourceMap.remove(conversationId);
|
||||
// 即使失败,也要将已有的对话数据保存到ES
|
||||
conversationData.appendAnswer(SYS_ERR_MSG);
|
||||
elasticSearchIndexService.createData(conversationData);
|
||||
return;
|
||||
}
|
||||
|
||||
// 从Map中移除失败的会话
|
||||
conversationEventSourceMap.remove(conversationId);
|
||||
|
||||
// 即使失败,也要将已有的对话数据保存到ES
|
||||
elasticSearchIndexService.createData(conversationData);
|
||||
sseEmitter.completeWithError(e);
|
||||
}
|
||||
};
|
||||
|
||||
// 8. 执行HTTP请求
|
||||
OkHttpClient client = new OkHttpClient.Builder()
|
||||
.connectTimeout(60, TimeUnit.SECONDS)
|
||||
.writeTimeout(600, TimeUnit.SECONDS)
|
||||
.readTimeout(600, TimeUnit.SECONDS)
|
||||
.callTimeout(600, TimeUnit.SECONDS)
|
||||
.dispatcher(dispatcher)
|
||||
.build();
|
||||
EventSource.Factory factory = EventSources.createFactory(client);
|
||||
factory.newEventSource(request, listener);
|
||||
|
||||
return sseEmitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取或创建会话ID
|
||||
*/
|
||||
private String getOrCreateConversationId(CaseAiChatDto caseAiChatDto, CurrentUser currentUser) {
|
||||
String conversationId = caseAiChatDto.getConversationId();
|
||||
|
||||
if (StringUtils.isEmpty(conversationId)) {
|
||||
// 新会话,调用创建会话接口
|
||||
String conversationName = "AI案例咨询-" + LocalDateTime.now().toString();
|
||||
CaseAiConversations newConversation = createNewConversation(currentUser.getCode(), conversationName);
|
||||
return newConversation.getAiConversationId();
|
||||
} else {
|
||||
// 已存在会话,从数据库查询
|
||||
return caseAiConversationsDao.findAiConversationIdById(conversationId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public CaseAiConversations createNewConversation(String userId, String conversationName) {
|
||||
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||
String url = caseAiProperties.getBaseUrl() + "/apigateway/knowledge/v1/conversation";
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
|
||||
// 设置请求头
|
||||
String accessToken = aiAccessTokenService.getAccessToken();
|
||||
String apiCode = caseAiProperties.getChatApiCode();
|
||||
httpPost.setHeader("access_token", accessToken);
|
||||
httpPost.setHeader("X-AI-ApiCode", apiCode);
|
||||
httpPost.setHeader("Content-Type", "application/json");
|
||||
|
||||
// 设置请求体
|
||||
JSONObject requestBody = new JSONObject();
|
||||
requestBody.put("userId", userId);
|
||||
requestBody.put("name", conversationName);
|
||||
StringEntity entity = new StringEntity(requestBody.toJSONString(), StandardCharsets.UTF_8);
|
||||
httpPost.setEntity(entity);
|
||||
|
||||
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
|
||||
int statusCode = response.getStatusLine().getStatusCode();
|
||||
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
|
||||
|
||||
if (statusCode == 200) {
|
||||
JSONObject result = JSONObject.parseObject(responseBody);
|
||||
if (result.getIntValue("code") == 0 && result.getBooleanValue("success")) {
|
||||
JSONObject data = result.getJSONObject("data");
|
||||
String aiConversationId = data.getString("id");
|
||||
String name = data.getString("name");
|
||||
|
||||
// 保存到数据库
|
||||
CaseAiConversations conversation = new CaseAiConversations();
|
||||
conversation.setAiConversationId(aiConversationId);
|
||||
conversation.setConversationName(name);
|
||||
conversation.setConversationUser(userId);
|
||||
caseAiConversationsDao.save(conversation);
|
||||
|
||||
log.info("创建AI会话成功,aiConversationId: {}, name: {}", aiConversationId, name);
|
||||
return conversation;
|
||||
} else {
|
||||
log.error("创建AI会话失败,接口返回失败,response: {}", responseBody);
|
||||
throw new RuntimeException("创建AI会话失败: " + result.getString("message"));
|
||||
}
|
||||
} else {
|
||||
log.error("创建AI会话失败,HTTP请求失败,status: {}, response: {}", statusCode, responseBody);
|
||||
throw new RuntimeException("创建AI会话失败,HTTP状态码: " + statusCode);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("创建AI会话异常", e);
|
||||
throw new RuntimeException("创建AI会话异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CaseAiMessageVo> getConversationMessages(String conversationId) {
|
||||
if (StringUtils.isEmpty(conversationId)) {
|
||||
log.warn("conversationId 为空, 不查询");
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return elasticSearchIndexService.queryData(conversationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getConversationExcel(LocalDateTime startTime, LocalDateTime endTime, HttpServletResponse response) {
|
||||
Workbook workbook = getChatMessageExcel(startTime, endTime);
|
||||
// 写入response.getOutputStream()
|
||||
try (OutputStream out = response.getOutputStream()) {
|
||||
response.setContentType("application/octet-stream");
|
||||
response.setHeader("Content-Disposition", "attachment;filename=chat_message.xlsx");
|
||||
workbook.write(out);
|
||||
out.flush();
|
||||
} catch (Exception e) {
|
||||
log.error("导出Excel异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void downloadConversationExcel(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
Workbook workbook = getChatMessageExcel(startTime, endTime);
|
||||
// 创建Excel文件并保存
|
||||
if (caseAiProperties.isAiChatDataSendEmail()) {
|
||||
// TODO 发送邮件附件
|
||||
} else {
|
||||
// 保存文件
|
||||
String dirPath = caseAiProperties.getAiChatRootPath() + File.separator + startTime.format(DateTimeFormatter.ofPattern("yyyyMM"));
|
||||
Path dir = Paths.get(dirPath);
|
||||
if (!Files.exists(dir)) {
|
||||
try {
|
||||
Files.createDirectories(dir);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
String fileName = "AI会话数据-" + startTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "-" + System.currentTimeMillis() + ".xlsx";
|
||||
Path filePath = dir.resolve(fileName);
|
||||
try (OutputStream out = Files.newOutputStream(filePath)) {
|
||||
workbook.write(out);
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
log.error("保存文件错误", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 ES 数据中解析消息对象
|
||||
* @param sourceMap ES数据
|
||||
* @return 消息对象
|
||||
*/
|
||||
private CaseAiMessageVo parseMessageFromES(Map<String, Object> sourceMap) {
|
||||
try {
|
||||
CaseAiMessageVo messageVo = new CaseAiMessageVo();
|
||||
messageVo.setQuery((String) sourceMap.get("query"));
|
||||
messageVo.setAnswer((String) sourceMap.get("answer"));
|
||||
|
||||
// 解析 suggestions
|
||||
Object suggestionsObj = sourceMap.get("suggestions");
|
||||
if (suggestionsObj instanceof List) {
|
||||
messageVo.setSuggestions((List<String>) suggestionsObj);
|
||||
}
|
||||
|
||||
// 解析 caseRefer
|
||||
Object caseReferObj = sourceMap.get("caseRefer");
|
||||
if (caseReferObj instanceof List) {
|
||||
List<CaseReferVo> caseReferList = new ArrayList<>();
|
||||
List<Map<String, Object>> caseReferMaps = (List<Map<String, Object>>) caseReferObj;
|
||||
|
||||
for (Map<String, Object> caseReferMap : caseReferMaps) {
|
||||
CaseReferVo caseRefer = new CaseReferVo();
|
||||
caseRefer.setCaseId((String) caseReferMap.get("caseId"));
|
||||
caseRefer.setTitle((String) caseReferMap.get("title"));
|
||||
caseRefer.setAuthorName((String) caseReferMap.get("authorName"));
|
||||
caseRefer.setContent((String) caseReferMap.get("content"));
|
||||
|
||||
// 解析 keywords
|
||||
Object keywordsObj = caseReferMap.get("keywords");
|
||||
if (keywordsObj instanceof List) {
|
||||
caseRefer.setKeywords((List<String>) keywordsObj);
|
||||
}
|
||||
|
||||
caseReferList.add(caseRefer);
|
||||
}
|
||||
messageVo.setCaseRefer(caseReferList);
|
||||
}
|
||||
|
||||
return messageVo;
|
||||
} catch (Exception e) {
|
||||
log.error("解析ES消息数据异常", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理文件引用并构建返给前端的响应数据
|
||||
*/
|
||||
private JSONObject handleFileReferAndBuildResponse(JSONObject responseData, AiChatConversationData conversationData) {
|
||||
try {
|
||||
// 先处理文件引用,收集CaseReferVo数据
|
||||
List<CaseReferVo> currentCaseRefers = new ArrayList<>();
|
||||
Set<String> docIds = new HashSet<>();
|
||||
|
||||
JSONObject fileRefer = responseData.getJSONObject("fileRefer");
|
||||
if (fileRefer != null && fileRefer.containsKey("files")) {
|
||||
JSONArray files = fileRefer.getJSONArray("files");
|
||||
for (int i = 0; i < files.size(); i++) {
|
||||
JSONObject file = files.getJSONObject(i);
|
||||
String docId = file.getString("docId");
|
||||
if (docId != null) {
|
||||
// 根据docId从 case_document_log 表查询案例数据
|
||||
CaseReferVo caseRefer = getCaseReferByDocId(docId);
|
||||
if (caseRefer != null && !docIds.contains(docId)) {
|
||||
docIds.add(docId);
|
||||
currentCaseRefers.add(caseRefer);
|
||||
conversationData.addCaseRefer(caseRefer); // 也添加到总的收集器中
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 构建返给前端的数据结构
|
||||
JSONObject data = new JSONObject();
|
||||
data.put("status", 0);
|
||||
data.put("conversationId", conversationData.getConversationId());
|
||||
data.put("content", responseData.getString("content"));
|
||||
|
||||
// 添加处理后的案例引用数据
|
||||
JSONArray caseReferArray = new JSONArray();
|
||||
for (CaseReferVo caseRefer : currentCaseRefers) {
|
||||
JSONObject caseReferObj = new JSONObject();
|
||||
caseReferObj.put("caseId", caseRefer.getCaseId());
|
||||
caseReferObj.put("title", caseRefer.getTitle());
|
||||
caseReferObj.put("authorName", caseRefer.getAuthorName());
|
||||
caseReferObj.put("keywords", caseRefer.getKeywords());
|
||||
caseReferObj.put("content", caseRefer.getContent());
|
||||
// 使用指定的时间格式
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
caseReferObj.put("uploadTime", caseRefer.getUploadTime() != null ? caseRefer.getUploadTime().format(formatter) : null);
|
||||
|
||||
caseReferArray.add(caseReferObj);
|
||||
}
|
||||
|
||||
// 构建新的fileRefer结构,包含案例引用
|
||||
JSONObject newFileRefer = new JSONObject();
|
||||
newFileRefer.put("caseRefers", caseReferArray);
|
||||
|
||||
// 保留原始的docs和files信息(如果需要)
|
||||
if (fileRefer != null) {
|
||||
if (fileRefer.containsKey("docs")) {
|
||||
newFileRefer.put("docs", fileRefer.get("docs"));
|
||||
}
|
||||
if (fileRefer.containsKey("files")) {
|
||||
newFileRefer.put("files", fileRefer.get("files"));
|
||||
}
|
||||
}
|
||||
|
||||
data.put("fileRefer", newFileRefer);
|
||||
data.put("suggestions", responseData.get("suggestions"));
|
||||
|
||||
log.info("处理文件引用成功,返回 {} 个案例引用", currentCaseRefers.size());
|
||||
return data;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("处理文件引用并构建响应数据异常", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理文件引用(原方法,保留用于数据收集)
|
||||
*/
|
||||
private void handleFileRefer(JSONObject responseData, AiChatConversationData conversationData) {
|
||||
try {
|
||||
JSONObject fileRefer = responseData.getJSONObject("fileRefer");
|
||||
if (fileRefer != null && fileRefer.containsKey("files")) {
|
||||
JSONArray files = fileRefer.getJSONArray("files");
|
||||
for (int i = 0; i < files.size(); i++) {
|
||||
JSONObject file = files.getJSONObject(i);
|
||||
String docId = file.getString("docId");
|
||||
if (docId != null) {
|
||||
// 根据docId从 case_document_log 表查询案例数据
|
||||
CaseReferVo caseRefer = getCaseReferByDocId(docId);
|
||||
if (caseRefer != null) {
|
||||
conversationData.addCaseRefer(caseRefer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("处理文件引用异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理建议
|
||||
*/
|
||||
private void handleSuggestions(JSONObject responseData, AiChatConversationData conversationData) {
|
||||
try {
|
||||
JSONArray suggestions = responseData.getJSONArray("suggestions");
|
||||
if (suggestions != null) {
|
||||
for (int i = 0; i < suggestions.size(); i++) {
|
||||
String suggestion = suggestions.getString(i);
|
||||
if (suggestion != null) {
|
||||
conversationData.addSuggestion(suggestion);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("处理建议异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据docId查询案例引用信息
|
||||
*/
|
||||
private CaseReferVo getCaseReferByDocId(String docId) {
|
||||
try {
|
||||
// 从 case_document_log 表查询案例信息(docId对应task_id)
|
||||
CaseDocumentLog docLog = caseDocumentLogDao.findByTaskId(docId);
|
||||
if (docLog == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 根据 case_id 查询案例详情
|
||||
Cases caseEntity = casesDao.get(docLog.getCaseId());
|
||||
if (caseEntity == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String authorUserId = caseEntity.getAuthorId();
|
||||
OrgSimpleVo authorOrg = userService.findOrgByUserId(authorUserId);
|
||||
// 构建 CaseReferVo
|
||||
CaseReferVo caseRefer = new CaseReferVo();
|
||||
caseRefer.setCaseId(caseEntity.getId());
|
||||
caseRefer.setTitle(caseEntity.getTitle());
|
||||
caseRefer.setAuthorName(caseEntity.getAuthorName());
|
||||
caseRefer.setContent(caseEntity.getSummary());
|
||||
caseRefer.setUploadTime(caseEntity.getSysCreateTime());
|
||||
caseRefer.setOrgInfo(authorOrg.getName());
|
||||
|
||||
// 构建关键词列表
|
||||
List<String> keywords = new ArrayList<>();
|
||||
if (caseEntity.getKeyword1() != null) keywords.add(caseEntity.getKeyword1());
|
||||
if (caseEntity.getKeyword2() != null) keywords.add(caseEntity.getKeyword2());
|
||||
if (caseEntity.getKeyword3() != null) keywords.add(caseEntity.getKeyword3());
|
||||
if (caseEntity.getKeyword4() != null) keywords.add(caseEntity.getKeyword4());
|
||||
if (caseEntity.getKeyword5() != null) keywords.add(caseEntity.getKeyword5());
|
||||
caseRefer.setKeywords(keywords);
|
||||
|
||||
return caseRefer;
|
||||
} catch (Exception e) {
|
||||
log.error("根据docId查询案例引用信息异常", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当 SSE 失败时,作为普通 HTTP 请求处理
|
||||
*/
|
||||
private void handleAsRegularHttpRequest(Request request, SseEmitter sseEmitter, AiChatConversationData conversationData) {
|
||||
try {
|
||||
OkHttpClient client = new OkHttpClient.Builder()
|
||||
.connectTimeout(60, TimeUnit.SECONDS)
|
||||
.writeTimeout(60, TimeUnit.SECONDS)
|
||||
.readTimeout(60, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
Response response = client.newCall(request).execute();
|
||||
if (response.isSuccessful()) {
|
||||
String responseBody = response.body().string();
|
||||
log.info("作为普通 HTTP 请求处理成功,将响应原封不动推送给前端");
|
||||
|
||||
// 将响应内容原封不动地推送到 SseEmitter
|
||||
JSONObject responseData = JSONObject.parseObject(responseBody);
|
||||
if (responseBody.contains("message")) {
|
||||
errMessage(sseEmitter, conversationData.getConversationId(), responseData.getString("message"));
|
||||
sseEmitter.complete();
|
||||
return;
|
||||
}
|
||||
sseEmitter.send(responseBody);
|
||||
sseEmitter.complete();
|
||||
} else {
|
||||
log.error("普通 HTTP 请求失败,状态码: {}", response.code());
|
||||
sseEmitter.completeWithError(new RuntimeException("HTTP 请求失败,状态码: " + response.code()));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("处理普通 HTTP 请求异常", e);
|
||||
sseEmitter.completeWithError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void errMessage(SseEmitter sseEmitter, String conversationId, String message) {
|
||||
JSONObject conversationData = new JSONObject();
|
||||
conversationData.put("conversationId", conversationId);
|
||||
conversationData.put("content", "");
|
||||
conversationData.put("status", 0);
|
||||
|
||||
JSONObject jsonData = new JSONObject();
|
||||
jsonData.put("status", 1);
|
||||
jsonData.put("content", message);
|
||||
|
||||
JSONObject finishData = new JSONObject();
|
||||
jsonData.put("status", 4);
|
||||
jsonData.put("content", "");
|
||||
try {
|
||||
sseEmitter.send(conversationData.toJSONString());
|
||||
sseEmitter.send(jsonData.toJSONString());
|
||||
sseEmitter.send(finishData.toJSONString());
|
||||
} catch (IOException e) {
|
||||
log.error("发送错误信息异常", e);
|
||||
sseEmitter.completeWithError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean stopChatOutput(String conversationId) {
|
||||
EventSource eventSource = conversationEventSourceMap.get(conversationId);
|
||||
if (eventSource != null) {
|
||||
try {
|
||||
// 取消事件源,中断连接
|
||||
eventSource.cancel();
|
||||
// 注意:cancel()会触发onFailure回调,在onFailure中会清理资源
|
||||
log.info("成功发送停止会话 {} 的指令", conversationId);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("停止会话 {} 输出时发生异常", conversationId, e);
|
||||
// 即使出现异常,也从Map中移除,避免内存泄漏
|
||||
conversationEventSourceMap.remove(conversationId);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
log.warn("未找到会话 {} 对应的事件源,可能已经完成或不存在", conversationId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断Throwable是否为超时类异常
|
||||
* @param e
|
||||
* @return
|
||||
*/
|
||||
private boolean isTimeoutException(@Nullable Throwable e) {
|
||||
if (e == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// ConnectException SocketTimeoutException
|
||||
if (e instanceof java.net.ConnectException || e instanceof java.net.SocketTimeoutException) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 可能是包装后的异常,递归检查 cause
|
||||
Throwable cause = e.getCause();
|
||||
while (cause != null) {
|
||||
if (cause instanceof java.net.ConnectException || cause instanceof java.net.SocketTimeoutException) {
|
||||
return true;
|
||||
}
|
||||
cause = cause.getCause();
|
||||
}
|
||||
|
||||
// 有些情况下 OkHttp 会抛出 IOException 并包含 "timeout" 字样
|
||||
if (e instanceof java.io.IOException) {
|
||||
String msg = e.getMessage();
|
||||
if (msg != null && msg.toLowerCase().contains("timeout")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private Workbook getChatMessageExcel(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
// 1. 根据startTime和endTime,查询在这个时间区间内的CaseAiConversations数据
|
||||
List<CaseAiConversations> conversations = caseAiConversationsDao.getGenericDao().findList(
|
||||
CaseAiConversations.class,
|
||||
FieldFilters.ge("sysCreateTime", startTime),
|
||||
FieldFilters.le("sysCreateTime", endTime)
|
||||
);
|
||||
|
||||
// 准备Excel数据
|
||||
List<ConversationExcelVo> excelDataList = new ArrayList<>();
|
||||
|
||||
// 2. 遍历这组数据,根据aiConversationId从es中查询数据(可调用getConversationMessages()方法)
|
||||
for (CaseAiConversations conversation : conversations) {
|
||||
String aiConversationId = conversation.getAiConversationId();
|
||||
String conversationName = conversation.getConversationName();
|
||||
String conversationUser = conversation.getConversationUser();
|
||||
|
||||
List<CaseAiMessageVo> messages = getConversationMessages(aiConversationId);
|
||||
|
||||
// 计算会话时长
|
||||
long duration = 0; // 默认为0,如果需要精确计算,需要从消息中提取时间信息
|
||||
|
||||
// 3. 写入Excel,包括每个会话的用户,会话标题,会话内的问答记录,每次对话时长等
|
||||
ConversationExcelVo excelData = new ConversationExcelVo();
|
||||
excelData.setConversationId(aiConversationId);
|
||||
excelData.setConversationName(conversationName);
|
||||
excelData.setUser(conversationUser);
|
||||
excelData.setMessages(messages);
|
||||
|
||||
excelDataList.add(excelData);
|
||||
}
|
||||
|
||||
// 写入Excel文件
|
||||
Workbook workbook = new XSSFWorkbook();
|
||||
Sheet sheet = workbook.createSheet("AI会话数据");
|
||||
// 标题行
|
||||
Row headerRow = sheet.createRow(0);
|
||||
headerRow.createCell(0).setCellValue("会话ID");
|
||||
headerRow.createCell(1).setCellValue("会话名称");
|
||||
headerRow.createCell(2).setCellValue("用户");
|
||||
headerRow.createCell(3).setCellValue("提问");
|
||||
headerRow.createCell(4).setCellValue("回答");
|
||||
headerRow.createCell(5).setCellValue("开始时间");
|
||||
headerRow.createCell(6).setCellValue("问答时长(秒)");
|
||||
|
||||
// 内容行
|
||||
if (!excelDataList.isEmpty()) {
|
||||
int rowNum = 1; // 从第二行开始写入数据
|
||||
for (ConversationExcelVo excelData : excelDataList) {
|
||||
List<CaseAiMessageVo> messages = excelData.getMessages();
|
||||
|
||||
if (messages != null && !messages.isEmpty()) {
|
||||
// 记录起始行号,用于后续合并单元格
|
||||
int startRow = rowNum;
|
||||
|
||||
// 遍历每个消息
|
||||
for (CaseAiMessageVo message : messages) {
|
||||
Row row = sheet.createRow(rowNum++);
|
||||
// 填充每行数据
|
||||
row.createCell(0).setCellValue(excelData.getConversationId());
|
||||
row.createCell(1).setCellValue(excelData.getConversationName());
|
||||
row.createCell(2).setCellValue(excelData.getUser());
|
||||
row.createCell(3).setCellValue(message.getQuery() != null ? message.getQuery() : "");
|
||||
row.createCell(4).setCellValue(message.getAnswer() != null ? message.getAnswer() : "");
|
||||
row.createCell(5).setCellValue(""); // 开始时间字段暂留空
|
||||
row.createCell(6).setCellValue(message.getDurationSeconds() != null ? message.getDurationSeconds() : 0);
|
||||
}
|
||||
|
||||
// 合并单元格(会话ID、会话名称、用户三列)
|
||||
// 参数说明:起始行号,结束行号,起始列号,结束列号
|
||||
if (rowNum > startRow + 1) { // 只有当有多行时才合并
|
||||
sheet.addMergedRegion(new CellRangeAddress(startRow, rowNum - 1, 0, 0));
|
||||
sheet.addMergedRegion(new CellRangeAddress(startRow, rowNum - 1, 1, 1));
|
||||
sheet.addMergedRegion(new CellRangeAddress(startRow, rowNum - 1, 2, 2));
|
||||
}
|
||||
} else {
|
||||
// 如果没有消息,则仍然创建一行显示基本信息
|
||||
Row row = sheet.createRow(rowNum++);
|
||||
row.createCell(0).setCellValue(excelData.getConversationId());
|
||||
row.createCell(1).setCellValue(excelData.getConversationName());
|
||||
row.createCell(2).setCellValue(excelData.getUser());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return workbook;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.xboe.module.boecase.service.impl;
|
||||
|
||||
import com.xboe.module.boecase.properties.CaseAiProperties;
|
||||
import com.xboe.module.boecase.service.ICaseAiPermissionService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 案例AI权限服务实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@Transactional
|
||||
public class CaseAiPermissionServiceImpl implements ICaseAiPermissionService {
|
||||
|
||||
@Autowired
|
||||
private CaseAiProperties caseAiProperties;
|
||||
|
||||
/**
|
||||
* 判断指定用户是否显示"案例专家"功能入口
|
||||
* @param userCode 用户编码
|
||||
* @return 是否显示功能入口
|
||||
*/
|
||||
@Override
|
||||
public boolean shouldShowCaseAiEntrance(String userCode) {
|
||||
log.info("判断用户[{}]是否显示案例专家功能入口", userCode);
|
||||
|
||||
// 如果不启用白名单,直接返回true
|
||||
if (!caseAiProperties.isUseWhiteList()) {
|
||||
log.info("未启用白名单,所有用户都显示功能入口");
|
||||
return true;
|
||||
}
|
||||
|
||||
// 启用白名单时,判断当前用户是否在白名单中
|
||||
List<String> whiteUserCodeList = caseAiProperties.getWhiteUserCodeList();
|
||||
log.info("白名单列表:{}", whiteUserCodeList);
|
||||
boolean isInWhiteList = whiteUserCodeList != null
|
||||
&& whiteUserCodeList.stream().anyMatch(userCode::equals);
|
||||
|
||||
log.info("用户[{}]{}在白名单中", userCode, isInWhiteList ? "" : "不");
|
||||
return isInWhiteList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package com.xboe.module.boecase.service.impl;
|
||||
|
||||
import com.xboe.common.utils.StringUtil;
|
||||
import com.xboe.common.OrderCondition;
|
||||
import com.xboe.common.PageList;
|
||||
import com.xboe.core.orm.FieldFilters;
|
||||
import com.xboe.core.orm.IFieldFilter;
|
||||
import com.xboe.core.orm.LikeMatchMode;
|
||||
import com.xboe.enums.CaseDocumentLogRunStatusEnum;
|
||||
import com.xboe.module.boecase.dao.CaseDocumentLogDao;
|
||||
import com.xboe.module.boecase.dto.CaseDocumentLogQueryDto;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.module.boecase.service.ICaseDocumentLogService;
|
||||
import com.xboe.module.boecase.service.ICaseKnowledgeService;
|
||||
import com.xboe.module.boecase.vo.CaseDocumentLogVo;
|
||||
import com.xboe.enums.CaseDocumentLogOptTypeEnum;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* AI调用日志Service实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@Transactional
|
||||
public class CaseDocumentLogServiceImpl implements ICaseDocumentLogService {
|
||||
|
||||
@Resource
|
||||
private CaseDocumentLogDao caseDocumentLogDao;
|
||||
|
||||
@Resource
|
||||
private ICaseKnowledgeService caseKnowledgeService;
|
||||
|
||||
@Resource(name = "aiDocExecutor")
|
||||
private ThreadPoolTaskExecutor aiDocExecutor;
|
||||
|
||||
@Override
|
||||
public PageList<CaseDocumentLogVo> pageQuery(int pageIndex, int pageSize, CaseDocumentLogQueryDto queryDto) {
|
||||
// 构建查询条件
|
||||
List<IFieldFilter> filters = new ArrayList<>();
|
||||
|
||||
// 运行状态过滤
|
||||
filters.add(FieldFilters.eq("runStatus", CaseDocumentLogRunStatusEnum.COMPLETED.getCode()));
|
||||
|
||||
// 案例标题模糊查询
|
||||
if (StringUtil.isNotBlank(queryDto.getCaseTitle())) {
|
||||
filters.add(FieldFilters.like("caseTitle", LikeMatchMode.ANYWHERE, queryDto.getCaseTitle()));
|
||||
}
|
||||
|
||||
// 操作类型精确查询
|
||||
if (StringUtil.isNotBlank(queryDto.getOptType())) {
|
||||
filters.add(FieldFilters.eq("optType", queryDto.getOptType()));
|
||||
}
|
||||
|
||||
// 调用时间区间查询
|
||||
if (queryDto.getOptTimeStart() != null) {
|
||||
filters.add(FieldFilters.ge("optTime", queryDto.getOptTimeStart()));
|
||||
}
|
||||
if (queryDto.getOptTimeEnd() != null) {
|
||||
// 将结束时间调整为当天的23:59:59
|
||||
LocalDateTime optTimeEnd = queryDto.getOptTimeEnd().withHour(23).withMinute(59).withSecond(59);
|
||||
filters.add(FieldFilters.le("optTime", optTimeEnd));
|
||||
}
|
||||
|
||||
// 接口调用状态
|
||||
if (queryDto.getOptStatus() != null) {
|
||||
filters.add(FieldFilters.eq("optStatus", queryDto.getOptStatus()));
|
||||
}
|
||||
|
||||
// 业务处理状态
|
||||
if (queryDto.getCaseStatus() != null) {
|
||||
filters.add(FieldFilters.eq("caseStatus", queryDto.getCaseStatus()));
|
||||
}
|
||||
|
||||
// 删除标识过滤
|
||||
filters.add(FieldFilters.eq("deleted", false));
|
||||
|
||||
// 按创建时间降序排序
|
||||
OrderCondition order = OrderCondition.desc("sysCreateTime");
|
||||
|
||||
// 执行分页查询
|
||||
PageList<CaseDocumentLog> pageResult = caseDocumentLogDao.getGenericDao()
|
||||
.findPage(pageIndex, pageSize, CaseDocumentLog.class, filters, order);
|
||||
|
||||
// 转换为VO对象
|
||||
List<CaseDocumentLogVo> voList = pageResult.getList().stream()
|
||||
.map(this::convertToVo)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 构建返回结果
|
||||
PageList<CaseDocumentLogVo> result = new PageList<>();
|
||||
result.setList(voList);
|
||||
result.setCount(pageResult.getCount());
|
||||
result.setPageSize(pageResult.getPageSize());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int clearLogsByCondition(CaseDocumentLogQueryDto queryDto) {
|
||||
// 构建查询条件(与分页查询相同的逻辑)
|
||||
List<IFieldFilter> filters = new ArrayList<>();
|
||||
|
||||
// 运行状态过滤
|
||||
filters.add(FieldFilters.eq("runStatus", CaseDocumentLogRunStatusEnum.COMPLETED.getCode()));
|
||||
|
||||
// 案例标题模糊查询
|
||||
if (StringUtil.isNotBlank(queryDto.getCaseTitle())) {
|
||||
filters.add(FieldFilters.like("caseTitle", LikeMatchMode.ANYWHERE, queryDto.getCaseTitle()));
|
||||
}
|
||||
|
||||
// 操作类型精确查询
|
||||
if (StringUtil.isNotBlank(queryDto.getOptType())) {
|
||||
filters.add(FieldFilters.eq("optType", queryDto.getOptType()));
|
||||
}
|
||||
|
||||
// 调用时间区间查询
|
||||
if (queryDto.getOptTimeStart() != null) {
|
||||
filters.add(FieldFilters.ge("optTime", queryDto.getOptTimeStart()));
|
||||
}
|
||||
if (queryDto.getOptTimeEnd() != null) {
|
||||
// 将结束时间调整为当天的23:59:59
|
||||
LocalDateTime optTimeEnd = queryDto.getOptTimeEnd().withHour(23).withMinute(59).withSecond(59);
|
||||
filters.add(FieldFilters.le("optTime", optTimeEnd));
|
||||
}
|
||||
|
||||
// 接口调用状态
|
||||
if (queryDto.getOptStatus() != null) {
|
||||
filters.add(FieldFilters.eq("optStatus", queryDto.getOptStatus()));
|
||||
}
|
||||
|
||||
// 业务处理状态
|
||||
if (queryDto.getCaseStatus() != null) {
|
||||
filters.add(FieldFilters.eq("caseStatus", queryDto.getCaseStatus()));
|
||||
}
|
||||
|
||||
// 删除标识过滤
|
||||
filters.add(FieldFilters.eq("deleted", false));
|
||||
|
||||
// 查询符合条件的所有记录
|
||||
IFieldFilter[] filtersArray = filters.toArray(new IFieldFilter[0]);
|
||||
List<CaseDocumentLog> logsToDelete = caseDocumentLogDao.getGenericDao()
|
||||
.findList(CaseDocumentLog.class, filtersArray);
|
||||
|
||||
if (logsToDelete.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 批量设置删除标识为true(逻辑删除)
|
||||
int deletedCount = 0;
|
||||
for (CaseDocumentLog log : logsToDelete) {
|
||||
log.setDeleted(true);
|
||||
caseDocumentLogDao.update(log);
|
||||
deletedCount++;
|
||||
}
|
||||
|
||||
log.info("清空日志操作完成,共删除{}条记录", deletedCount);
|
||||
return deletedCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retryByLogId(String logId) {
|
||||
if (StringUtil.isBlank(logId)) {
|
||||
log.error("重试失败,logId不能为空");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 1. 根据logId查询原始日志数据
|
||||
CaseDocumentLog originalLog = caseDocumentLogDao.get(logId);
|
||||
if (originalLog == null || originalLog.getDeleted()) {
|
||||
log.error("重试失败,未找到有效的日志记录,logId: {}", logId);
|
||||
return false;
|
||||
}
|
||||
|
||||
log.info("开始异步重试AI调用,原始日志ID: {}, 案例标题: {}, 操作类型: {}",
|
||||
logId, originalLog.getCaseTitle(), originalLog.getOptType());
|
||||
|
||||
// 2. 使用线程池异步执行AI调用重试逻辑
|
||||
String optType = originalLog.getOptType();
|
||||
String caseId = originalLog.getCaseId();
|
||||
|
||||
aiDocExecutor.execute(() -> executeRetryLogic(optType, caseId, originalLog));
|
||||
|
||||
// 立即返回true表示重试请求已接受,具体结果通过日志异步处理
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行AI调用重试逻辑
|
||||
* @param optType 操作类型
|
||||
* @param caseId 案例ID
|
||||
*/
|
||||
private void executeRetryLogic(String optType, String caseId, CaseDocumentLog originalLog) {
|
||||
boolean retrySuccess = false;
|
||||
|
||||
try {
|
||||
if (StringUtil.isBlank(caseId)) {
|
||||
throw new IllegalArgumentException("案例ID不能为空");
|
||||
}
|
||||
|
||||
log.info("[异步任务] 正在执行AI调用重试,操作类型: {}, caseId: {}", optType, caseId);
|
||||
|
||||
// 根据操作类型执行对应的方法(这些方法内部会自动创建日志记录)
|
||||
if (CaseDocumentLogOptTypeEnum.CREATE.getCode().equals(optType)) {
|
||||
// 上传案例文档
|
||||
retrySuccess = caseKnowledgeService.uploadCaseDocument(caseId);
|
||||
log.info("[异步任务] 执行上传案例文档重试,caseId: {}, 结果: {}", caseId, retrySuccess);
|
||||
|
||||
} else if (CaseDocumentLogOptTypeEnum.DELETE.getCode().equals(optType)) {
|
||||
// 删除案例文档
|
||||
retrySuccess = caseKnowledgeService.deleteCaseDocument(caseId);
|
||||
log.info("[异步任务] 执行删除案例文档重试,caseId: {}, 结果: {}", caseId, retrySuccess);
|
||||
|
||||
} else if (CaseDocumentLogOptTypeEnum.UPDATE.getCode().equals(optType)) {
|
||||
// 更新案例文档
|
||||
retrySuccess = caseKnowledgeService.retryCaseDocument(caseId, originalLog);
|
||||
log.info("[异步任务] 执行更新案例文档重试,caseId: {}, 结果: {}", caseId, retrySuccess);
|
||||
|
||||
} else {
|
||||
throw new IllegalArgumentException("不支持的操作类型: " + optType);
|
||||
}
|
||||
|
||||
if (retrySuccess) {
|
||||
log.info("[异步任务] AI调用重试成功,操作类型: {}, caseId: {}", optType, caseId);
|
||||
} else {
|
||||
log.warn("[异步任务] AI调用重试失败,操作类型: {}, caseId: {}", optType, caseId);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("[异步任务] AI调用重试异常,操作类型: {}, caseId: {}",
|
||||
optType, caseId, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean save(CaseDocumentLog caseDocumentLog) {
|
||||
try {
|
||||
caseDocumentLogDao.save(caseDocumentLog);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("保存CaseDocumentLog失败", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 实体转换为VO
|
||||
*/
|
||||
private CaseDocumentLogVo convertToVo(CaseDocumentLog entity) {
|
||||
CaseDocumentLogVo vo = new CaseDocumentLogVo();
|
||||
BeanUtils.copyProperties(entity, vo);
|
||||
|
||||
// 操作类型转换为中文描述
|
||||
vo.setOptType(CaseDocumentLogOptTypeEnum.getDescByCode(entity.getOptType()));
|
||||
|
||||
// 接口调用状态转换
|
||||
vo.setOptStatusText(getOptStatusText(entity.getOptStatus()));
|
||||
|
||||
// 业务处理状态转换
|
||||
vo.setCaseStatusText(getCaseStatusText(entity.getCaseStatus()));
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取接口调用状态描述
|
||||
*/
|
||||
private String getOptStatusText(Integer optStatus) {
|
||||
if (optStatus == null) {
|
||||
return "";
|
||||
}
|
||||
switch (optStatus) {
|
||||
case 1:
|
||||
return "调用成功";
|
||||
case 2:
|
||||
return "调用失败";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取业务处理状态描述
|
||||
*/
|
||||
private String getCaseStatusText(Integer caseStatus) {
|
||||
if (caseStatus == null) {
|
||||
return "";
|
||||
}
|
||||
switch (caseStatus) {
|
||||
case 1:
|
||||
return "处理成功";
|
||||
case 2:
|
||||
return "处理失败";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -19,7 +19,9 @@ import com.xboe.common.utils.IDGenerator;
|
||||
import com.xboe.common.utils.StringUtil;
|
||||
import com.xboe.core.CurrentUser;
|
||||
import com.xboe.core.orm.*;
|
||||
import com.xboe.enums.CaseDocumentLogOptTypeEnum;
|
||||
import com.xboe.enums.CasesRankEnum;
|
||||
import com.xboe.module.boecase.async.CaseAiDocumentAsyncHandler;
|
||||
import com.xboe.module.boecase.dao.*;
|
||||
import com.xboe.module.boecase.dto.*;
|
||||
import com.xboe.module.boecase.entity.*;
|
||||
@@ -90,6 +92,9 @@ public class CasesServiceImpl implements ICasesService {
|
||||
@Resource
|
||||
private ThirdApi thirdApi;
|
||||
|
||||
@Autowired
|
||||
private CaseAiDocumentAsyncHandler caseAiDocumentAsyncHandler;
|
||||
|
||||
/**
|
||||
* 案例分页查询,用于门户的查询
|
||||
*/
|
||||
@@ -799,7 +804,11 @@ public class CasesServiceImpl implements ICasesService {
|
||||
*/
|
||||
@Override
|
||||
public void delete(String id) {
|
||||
Cases cases = casesDao.get(id);
|
||||
// 原删除
|
||||
casesDao.setDeleted(id);
|
||||
// 增加逻辑
|
||||
caseAiDocumentAsyncHandler.process(CaseDocumentLogOptTypeEnum.DELETE, cases);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -986,6 +995,8 @@ public class CasesServiceImpl implements ICasesService {
|
||||
cases.setMajorIds(majorIds);
|
||||
cases.setMajorType(stringBuffer.toString());
|
||||
casesDao.save(cases);
|
||||
// 增加逻辑
|
||||
caseAiDocumentAsyncHandler.process(CaseDocumentLogOptTypeEnum.CREATE, cases);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1009,6 +1020,8 @@ public class CasesServiceImpl implements ICasesService {
|
||||
cases.setMajorIds(majorIds);
|
||||
cases.setMajorType(stringBuffer.toString());
|
||||
casesDao.update(cases);
|
||||
// 增加逻辑
|
||||
caseAiDocumentAsyncHandler.process(CaseDocumentLogOptTypeEnum.UPDATE, cases);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
package com.xboe.module.boecase.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.xboe.constants.CaseAiConstants;
|
||||
import com.xboe.module.boecase.entity.AiChatConversationData;
|
||||
import com.xboe.module.boecase.service.IElasticSearchIndexService;
|
||||
import com.xboe.module.boecase.vo.CaseAiMessageVo;
|
||||
import com.xboe.module.boecase.vo.CaseReferVo;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
|
||||
import org.elasticsearch.action.index.IndexRequest;
|
||||
import org.elasticsearch.action.index.IndexResponse;
|
||||
import org.elasticsearch.action.search.SearchRequest;
|
||||
import org.elasticsearch.action.search.SearchResponse;
|
||||
import org.elasticsearch.action.support.master.AcknowledgedResponse;
|
||||
import org.elasticsearch.client.RequestOptions;
|
||||
import org.elasticsearch.client.RestHighLevelClient;
|
||||
import org.elasticsearch.client.indices.CreateIndexRequest;
|
||||
import org.elasticsearch.client.indices.CreateIndexResponse;
|
||||
import org.elasticsearch.client.indices.GetIndexRequest;
|
||||
import org.elasticsearch.common.settings.Settings;
|
||||
import org.elasticsearch.common.xcontent.XContentType;
|
||||
import org.elasticsearch.index.query.QueryBuilders;
|
||||
import org.elasticsearch.search.SearchHit;
|
||||
import org.elasticsearch.search.SearchHits;
|
||||
import org.elasticsearch.search.builder.SearchSourceBuilder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ElasticSearchIndexServiceImpl implements IElasticSearchIndexService {
|
||||
|
||||
@Autowired(required = false)
|
||||
private RestHighLevelClient elasticsearchClient;
|
||||
|
||||
@Override
|
||||
public boolean checkIndexExists() {
|
||||
if (elasticsearchClient == null) {
|
||||
log.error("ElasticSearch客户端未配置");
|
||||
return false;
|
||||
}
|
||||
// 检查索引是否存在
|
||||
GetIndexRequest getIndexRequest = new GetIndexRequest(CaseAiConstants.CASE_AI_INDEX_NAME);
|
||||
try {
|
||||
return elasticsearchClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
|
||||
} catch (IOException e) {
|
||||
log.error("查询ElasticSearch索引时发生异常", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean createIndex() {
|
||||
if (elasticsearchClient == null) {
|
||||
log.error("ElasticSearch客户端未配置");
|
||||
return false;
|
||||
}
|
||||
// 创建索引
|
||||
CreateIndexRequest createIndexRequest = new CreateIndexRequest(CaseAiConstants.CASE_AI_INDEX_NAME);
|
||||
|
||||
// 设置索引配置
|
||||
createIndexRequest.settings(Settings.builder()
|
||||
.put("index.number_of_shards", 1)
|
||||
.put("index.number_of_replicas", 0)
|
||||
.put("index.analysis.analyzer.ik_max_word.tokenizer", "ik_max_word")
|
||||
.put("index.analysis.analyzer.ik_smart.tokenizer", "ik_smart")
|
||||
);
|
||||
|
||||
// 设置字段映射
|
||||
String mapping = getAiChatMessagesMapping();
|
||||
createIndexRequest.mapping(mapping, XContentType.JSON);
|
||||
|
||||
// 执行创建索引请求
|
||||
CreateIndexResponse createIndexResponse = null;
|
||||
try {
|
||||
createIndexResponse = elasticsearchClient.indices()
|
||||
.create(createIndexRequest, RequestOptions.DEFAULT);
|
||||
} catch (IOException e) {
|
||||
log.error("创建ElasticSearch索引时发生异常", e);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (createIndexResponse.isAcknowledged()) {
|
||||
log.info("ElasticSearch索引 [{}] 创建成功", CaseAiConstants.CASE_AI_INDEX_NAME);
|
||||
return true;
|
||||
} else {
|
||||
log.error("ElasticSearch索引 [{}] 创建可能失败,响应未确认", CaseAiConstants.CASE_AI_INDEX_NAME);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteIndex() {
|
||||
if (elasticsearchClient == null) {
|
||||
log.error("ElasticSearch客户端未配置");
|
||||
return false;
|
||||
}
|
||||
// 执行删除索引请求
|
||||
DeleteIndexRequest deleteRequest = new DeleteIndexRequest(CaseAiConstants.CASE_AI_INDEX_NAME);
|
||||
try {
|
||||
AcknowledgedResponse deleteResponse = elasticsearchClient.indices().delete(deleteRequest, RequestOptions.DEFAULT);
|
||||
if (deleteResponse.isAcknowledged()) {
|
||||
log.info("成功删除Elasticsearch索引: {}", CaseAiConstants.CASE_AI_INDEX_NAME);
|
||||
return true;
|
||||
} else {
|
||||
log.error("删除索引 [{}] 未被确认(可能部分节点未响应)", CaseAiConstants.CASE_AI_INDEX_NAME);
|
||||
return false;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("删除ElasticSearch索引时发生异常", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean createData(AiChatConversationData conversationData) {
|
||||
if (elasticsearchClient == null) {
|
||||
log.error("未配置Elasticsearch客户端,无法保存对话记录");
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// 构建要保存的数据
|
||||
JSONObject esData = new JSONObject();
|
||||
esData.put("query", conversationData.getQuery());
|
||||
esData.put("answer", conversationData.getAnswerAsString());
|
||||
esData.put("conversationId", conversationData.getConversationId());
|
||||
esData.put("userId", conversationData.getUserId());
|
||||
// 持续时间
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
esData.put("startTime", conversationData.getStartTime().toString());
|
||||
esData.put("timestamp", now.toString());
|
||||
esData.put("durationSeconds", Duration.between(conversationData.getStartTime(), now).getSeconds());
|
||||
|
||||
// 构建 caseRefer 数据
|
||||
JSONArray caseReferArray = new JSONArray();
|
||||
for (CaseReferVo caseRefer : conversationData.getCaseRefers()) {
|
||||
JSONObject caseReferObj = new JSONObject();
|
||||
caseReferObj.put("caseId", caseRefer.getCaseId());
|
||||
caseReferObj.put("title", caseRefer.getTitle());
|
||||
caseReferObj.put("authorName", caseRefer.getAuthorName());
|
||||
caseReferObj.put("keywords", caseRefer.getKeywords());
|
||||
caseReferObj.put("content", caseRefer.getContent());
|
||||
caseReferArray.add(caseReferObj);
|
||||
}
|
||||
esData.put("caseRefer", caseReferArray);
|
||||
|
||||
// 添加建议
|
||||
esData.put("suggestions", conversationData.getSuggestions());
|
||||
|
||||
// 保存到ES
|
||||
IndexRequest indexRequest = new IndexRequest("ai_chat_messages");
|
||||
String dataStr = esData.toJSONString();
|
||||
log.info("保存对话记录到ES:{}", dataStr);
|
||||
indexRequest.source(dataStr, XContentType.JSON);
|
||||
|
||||
IndexResponse indexResponse = elasticsearchClient.index(indexRequest, RequestOptions.DEFAULT);
|
||||
log.info("保存对话记录到ES成功,文档ID: {}", indexResponse.getId());
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("保存对话记录到ES异常", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CaseAiMessageVo> queryData(String conversationId) {
|
||||
List<CaseAiMessageVo> list = new ArrayList<>();
|
||||
if (elasticsearchClient == null) {
|
||||
log.error("未配置Elasticsearch客户端,无法查询对话记录");
|
||||
return list;
|
||||
}
|
||||
try {
|
||||
// 从 ES 中查询消息记录
|
||||
SearchRequest searchRequest = new SearchRequest(CaseAiConstants.CASE_AI_INDEX_NAME); // ES索引名,可以根据实际情况调整
|
||||
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
|
||||
searchSourceBuilder.query(QueryBuilders.termQuery("conversationId", conversationId));
|
||||
searchSourceBuilder.size(1000); // 设置最大返回数量
|
||||
searchRequest.source(searchSourceBuilder);
|
||||
|
||||
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
|
||||
SearchHits hits = searchResponse.getHits();
|
||||
|
||||
for (SearchHit hit : hits) {
|
||||
Map<String, Object> sourceMap = hit.getSourceAsMap();
|
||||
CaseAiMessageVo data = parseMessageFromES(sourceMap);
|
||||
if (data != null) {
|
||||
list.add(data);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("从 ES 中查询到 {} 条消息记录", list.size());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("从 ES 查询会话消息记录异常", e);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private CaseAiMessageVo parseMessageFromES(Map<String, Object> sourceMap) {
|
||||
try {
|
||||
CaseAiMessageVo messageVo = new CaseAiMessageVo();
|
||||
messageVo.setQuery((String) sourceMap.get("query"));
|
||||
messageVo.setAnswer((String) sourceMap.get("answer"));
|
||||
if (sourceMap.containsKey("startTime")) {
|
||||
String startTimeStr = (String) sourceMap.get("startTime");
|
||||
messageVo.setStartTime(LocalDateTime.parse(startTimeStr));
|
||||
}
|
||||
if (sourceMap.containsKey("durationSeconds")) {
|
||||
messageVo.setDurationSeconds((Integer) sourceMap.get("durationSeconds"));
|
||||
}
|
||||
|
||||
// 解析 suggestions
|
||||
if (sourceMap.containsKey("suggestions")) {
|
||||
Object suggestionsObj = sourceMap.get("suggestions");
|
||||
if (suggestionsObj instanceof List) {
|
||||
messageVo.setSuggestions((List<String>) suggestionsObj);
|
||||
}
|
||||
}
|
||||
|
||||
// 解析 caseRefer
|
||||
if (sourceMap.containsKey("caseRefer")) {
|
||||
Object caseReferObj = sourceMap.get("caseRefer");
|
||||
if (caseReferObj instanceof List) {
|
||||
List<CaseReferVo> caseReferList = new ArrayList<>();
|
||||
List<Map<String, Object>> caseReferMaps = (List<Map<String, Object>>) caseReferObj;
|
||||
|
||||
for (Map<String, Object> caseReferMap : caseReferMaps) {
|
||||
CaseReferVo caseRefer = new CaseReferVo();
|
||||
caseRefer.setCaseId((String) caseReferMap.get("caseId"));
|
||||
caseRefer.setTitle((String) caseReferMap.get("title"));
|
||||
caseRefer.setAuthorName((String) caseReferMap.get("authorName"));
|
||||
caseRefer.setContent((String) caseReferMap.get("content"));
|
||||
|
||||
// 解析 keywords
|
||||
Object keywordsObj = caseReferMap.get("keywords");
|
||||
if (keywordsObj instanceof List) {
|
||||
caseRefer.setKeywords((List<String>) keywordsObj);
|
||||
}
|
||||
|
||||
caseReferList.add(caseRefer);
|
||||
}
|
||||
messageVo.setCaseRefer(caseReferList);
|
||||
}
|
||||
}
|
||||
|
||||
return messageVo;
|
||||
} catch (Exception e) {
|
||||
log.error("解析ES消息数据异常", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取ai_chat_messages索引的字段映射配置
|
||||
* 根据项目中的会话消息数据结构规范定义映射
|
||||
*
|
||||
* @return JSON格式的映射配置
|
||||
*/
|
||||
private String getAiChatMessagesMapping() {
|
||||
return "{\n" +
|
||||
" \"properties\": {\n" +
|
||||
" \"conversationId\": {\n" +
|
||||
" \"type\": \"keyword\",\n" +
|
||||
" \"index\": true\n" +
|
||||
" },\n" +
|
||||
" \"query\": {\n" +
|
||||
" \"type\": \"text\",\n" +
|
||||
" \"analyzer\": \"ik_max_word\",\n" +
|
||||
" \"search_analyzer\": \"ik_smart\",\n" +
|
||||
" \"fields\": {\n" +
|
||||
" \"keyword\": {\n" +
|
||||
" \"type\": \"keyword\",\n" +
|
||||
" \"ignore_above\": 256\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" },\n" +
|
||||
" \"answer\": {\n" +
|
||||
" \"type\": \"text\",\n" +
|
||||
" \"analyzer\": \"ik_max_word\",\n" +
|
||||
" \"search_analyzer\": \"ik_smart\"\n" +
|
||||
" },\n" +
|
||||
" \"caseRefer\": {\n" +
|
||||
" \"type\": \"nested\",\n" +
|
||||
" \"properties\": {\n" +
|
||||
" \"caseId\": {\n" +
|
||||
" \"type\": \"keyword\",\n" +
|
||||
" \"index\": true\n" +
|
||||
" },\n" +
|
||||
" \"title\": {\n" +
|
||||
" \"type\": \"text\",\n" +
|
||||
" \"analyzer\": \"ik_max_word\",\n" +
|
||||
" \"search_analyzer\": \"ik_smart\"\n" +
|
||||
" },\n" +
|
||||
" \"authorName\": {\n" +
|
||||
" \"type\": \"keyword\",\n" +
|
||||
" \"index\": true\n" +
|
||||
" },\n" +
|
||||
" \"keywords\": {\n" +
|
||||
" \"type\": \"text\",\n" +
|
||||
" \"analyzer\": \"ik_max_word\",\n" +
|
||||
" \"search_analyzer\": \"ik_smart\"\n" +
|
||||
" },\n" +
|
||||
" \"content\": {\n" +
|
||||
" \"type\": \"text\",\n" +
|
||||
" \"analyzer\": \"ik_max_word\",\n" +
|
||||
" \"search_analyzer\": \"ik_smart\"\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" },\n" +
|
||||
" \"suggestions\": {\n" +
|
||||
" \"type\": \"text\",\n" +
|
||||
" \"analyzer\": \"ik_max_word\",\n" +
|
||||
" \"search_analyzer\": \"ik_smart\"\n" +
|
||||
" },\n" +
|
||||
" \"userId\": {\n" +
|
||||
" \"type\": \"keyword\",\n" +
|
||||
" \"index\": true\n" +
|
||||
" },\n" +
|
||||
" \"timestamp\": {\n" +
|
||||
" \"type\": \"date\",\n" +
|
||||
" \"format\": \"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd'T'HH:mm:ss||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS'Z'||epoch_millis\"\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.xboe.module.boecase.task;
|
||||
|
||||
import com.xboe.module.boecase.service.ICaseAiChatService;
|
||||
import com.xxl.job.core.handler.annotation.XxlJob;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.YearMonth;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class CaseAiChatDataTask {
|
||||
|
||||
@Autowired
|
||||
private ICaseAiChatService caseAiChatService;
|
||||
|
||||
|
||||
/**
|
||||
* 查询上月聊天数据并下载
|
||||
* cron: 0/10 * * * * ?
|
||||
*/
|
||||
@XxlJob("chatDataExcelDownloadJob")
|
||||
public void chatDataExcelDownload(String param) {
|
||||
LocalDateTime startTime;
|
||||
LocalDateTime endTime;
|
||||
|
||||
if (param != null && !param.isEmpty()) {
|
||||
// 解析参数,格式应为 "startTime,endTime",例如 "2023-01-01T00:00:00,2023-01-31T23:59:59"
|
||||
String[] times = param.split(",");
|
||||
if (times.length == 2) {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
|
||||
try {
|
||||
startTime = LocalDateTime.parse(times[0], formatter);
|
||||
endTime = LocalDateTime.parse(times[1], formatter);
|
||||
log.info("使用参数指定的时间范围: {} 到 {}", startTime, endTime);
|
||||
} catch (Exception e) {
|
||||
log.error("解析时间参数失败,使用默认时间范围", e);
|
||||
// 使用默认逻辑
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
YearMonth lastMonth = YearMonth.from(now).minusMonths(1);
|
||||
startTime = now.minusMonths(1)
|
||||
.withDayOfMonth(1)
|
||||
.withHour(0)
|
||||
.withMinute(0)
|
||||
.withSecond(0);
|
||||
endTime = lastMonth.atEndOfMonth().atTime(23, 59, 59);
|
||||
}
|
||||
} else {
|
||||
// 使用默认逻辑
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
YearMonth lastMonth = YearMonth.from(now).minusMonths(1);
|
||||
startTime = now.minusMonths(1)
|
||||
.withDayOfMonth(1)
|
||||
.withHour(0)
|
||||
.withMinute(0)
|
||||
.withSecond(0);
|
||||
endTime = lastMonth.atEndOfMonth().atTime(23, 59, 59);
|
||||
}
|
||||
} else {
|
||||
// 使用默认逻辑
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
YearMonth lastMonth = YearMonth.from(now).minusMonths(1);
|
||||
startTime = now.minusMonths(1)
|
||||
.withDayOfMonth(1)
|
||||
.withHour(0)
|
||||
.withMinute(0)
|
||||
.withSecond(0);
|
||||
endTime = lastMonth.atEndOfMonth().atTime(23, 59, 59);
|
||||
}
|
||||
|
||||
// 执行
|
||||
caseAiChatService.downloadConversationExcel(startTime, endTime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.xboe.module.boecase.task;
|
||||
|
||||
import com.xboe.module.boecase.service.ICaseKnowledgeService;
|
||||
import com.xxl.job.core.handler.annotation.XxlJob;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class CaseDocumentLogTask {
|
||||
|
||||
@Autowired
|
||||
private ICaseKnowledgeService caseKnowledgeService;
|
||||
|
||||
/**
|
||||
* 批量查询文件状态并修改
|
||||
* 目前每次查看10条数据,批处理拟每10秒一次,每分钟可运行6次,60条数据
|
||||
* cron: 0/10 * * * * ?
|
||||
*/
|
||||
@XxlJob("batchCheckFileStatusJob")
|
||||
public void batchCheckFileStatusJob() {
|
||||
// log.info("开始批量查询文件状态");
|
||||
caseKnowledgeService.batchCheckFileStatus();
|
||||
// log.info("结束批量查询文件状态");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.xboe.module.boecase.task;
|
||||
|
||||
import com.xboe.constants.CaseAiConstants;
|
||||
import com.xboe.enums.CaseDocumentLogCaseStatusEnum;
|
||||
import com.xboe.enums.CaseDocumentLogOptStatusEnum;
|
||||
import com.xboe.enums.CaseDocumentLogOptTypeEnum;
|
||||
import com.xboe.enums.CaseDocumentLogRunStatusEnum;
|
||||
import com.xboe.module.boecase.async.CaseAiDocumentAsyncHandler;
|
||||
import com.xboe.module.boecase.dao.CaseDocumentLogDao;
|
||||
import com.xboe.module.boecase.dao.CasesDao;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.module.boecase.entity.Cases;
|
||||
import com.xxl.job.core.handler.annotation.XxlJob;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 旧案例上传
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class CaseUploadTask {
|
||||
|
||||
@Resource
|
||||
private CasesDao casesDao;
|
||||
|
||||
@Resource
|
||||
private CaseDocumentLogDao caseDocumentLogDao;
|
||||
|
||||
@Autowired
|
||||
private CaseAiDocumentAsyncHandler caseAiDocumentAsyncHandler;
|
||||
|
||||
@Autowired
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
private static final String CASE_UPLOAD_LAST_ID_KEY = "case:upload:last:id";
|
||||
|
||||
@XxlJob("oldDataUploadJob")
|
||||
public void oldDataUploadJob() {
|
||||
String currentLastId = null;
|
||||
try {
|
||||
// log.info("开始执行旧案例上传任务");
|
||||
|
||||
// 从Redis获取上次处理的最后一条记录ID
|
||||
String lastProcessedId = stringRedisTemplate.opsForValue().get(CASE_UPLOAD_LAST_ID_KEY);
|
||||
// log.info("上次处理的最后一条记录ID: {}", lastProcessedId);
|
||||
|
||||
// 查询符合条件的案例数据
|
||||
List<Cases> casesToProcess = findCasesToProcess(lastProcessedId);
|
||||
// log.info("查询到待处理案例数量: {}", casesToProcess.size());
|
||||
|
||||
if (casesToProcess.isEmpty()) {
|
||||
// log.info("没有需要处理的案例数据");
|
||||
return;
|
||||
}
|
||||
currentLastId = casesToProcess.get(casesToProcess.size() - 1).getId();
|
||||
|
||||
// 批量检查这些案例是否已在CaseDocumentLog中存在记录,提升性能
|
||||
List<String> caseIds = new ArrayList<>();
|
||||
for (Cases cases : casesToProcess) {
|
||||
caseIds.add(cases.getId());
|
||||
}
|
||||
|
||||
// 一次性查询所有相关案例的记录
|
||||
List<CaseDocumentLog> existingLogs = caseDocumentLogDao.getGenericDao()
|
||||
.findList(CaseDocumentLog.class,
|
||||
com.xboe.core.orm.FieldFilters.in("caseId", caseIds));
|
||||
|
||||
// 过滤出未在CaseDocumentLog中存在的案例
|
||||
List<Cases> casesList = new ArrayList<>();
|
||||
for (Cases cases : casesToProcess) {
|
||||
// boolean exists = false;
|
||||
// for (CaseDocumentLog log : existingLogs) {
|
||||
// if (cases.getId().equals(log.getCaseId())
|
||||
// && StringUtils.equals(log.getRequestUrl(), CaseAiConstants.CASE_DOC_UPLOAD_INTERFACE_NAME)
|
||||
// && Objects.equals(log.getRunStatus(), CaseDocumentLogRunStatusEnum.COMPLETED.getCode())
|
||||
// && Objects.equals(log.getOptStatus(), CaseDocumentLogOptStatusEnum.SUCCESS.getCode())
|
||||
// && Objects.equals(log.getRunStatus(), CaseDocumentLogCaseStatusEnum.SUCCESS.getCode())) {
|
||||
// exists = true;
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// if (!exists) {
|
||||
// casesList.add(cases);
|
||||
// }
|
||||
List<CaseDocumentLog> thisCaseLogs = existingLogs.stream()
|
||||
.filter(log -> cases.getId().equals(log.getCaseId()))
|
||||
.collect(Collectors.toList());
|
||||
if (thisCaseLogs == null || thisCaseLogs.isEmpty()) {
|
||||
casesList.add(cases);
|
||||
} else if (thisCaseLogs.stream()
|
||||
.noneMatch(caseLog -> {
|
||||
// 1. 是否存在已上传完成的案例
|
||||
boolean hasCompleted = StringUtils.equals(caseLog.getRequestUrl(), CaseAiConstants.CASE_DOC_UPLOAD_INTERFACE_NAME)
|
||||
&& Objects.equals(caseLog.getRunStatus(), CaseDocumentLogRunStatusEnum.COMPLETED.getCode())
|
||||
&& Objects.equals(caseLog.getOptStatus(), CaseDocumentLogOptStatusEnum.SUCCESS.getCode())
|
||||
&& Objects.equals(caseLog.getRunStatus(), CaseDocumentLogCaseStatusEnum.SUCCESS.getCode());
|
||||
// 2. 是否存在上传中的案例
|
||||
boolean hasUploading = StringUtils.equals(caseLog.getRequestUrl(), CaseAiConstants.CASE_DOC_UPLOAD_INTERFACE_NAME)
|
||||
&& Objects.equals(caseLog.getRunStatus(), CaseDocumentLogRunStatusEnum.RUNNING.getCode());
|
||||
return hasCompleted || hasUploading;
|
||||
})) {
|
||||
casesList.add(cases);
|
||||
}
|
||||
}
|
||||
|
||||
// log.info("过滤后需要处理的案例数量: {}", casesList.size());
|
||||
|
||||
if (!casesList.isEmpty()) {
|
||||
// 调用异步处理方法
|
||||
caseAiDocumentAsyncHandler.process(CaseDocumentLogOptTypeEnum.CREATE, casesList.toArray(new Cases[0]));
|
||||
|
||||
} else {
|
||||
log.info("没有新的案例需要处理");
|
||||
}
|
||||
// 将当前处理的最后一条数据ID存入Redis
|
||||
|
||||
// log.info("旧案例上传任务执行完成");
|
||||
} catch (Exception e) {
|
||||
log.error("执行旧案例上传任务时发生异常", e);
|
||||
} finally {
|
||||
if (currentLastId != null) {
|
||||
fixOnLastCase(currentLastId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询需要处理的案例数据
|
||||
*
|
||||
* @param lastProcessedId 上次处理的最后一条记录ID
|
||||
* @return 案例列表
|
||||
*/
|
||||
private List<Cases> findCasesToProcess(String lastProcessedId) {
|
||||
com.xboe.core.orm.QueryBuilder queryBuilder = com.xboe.core.orm.QueryBuilder.from(Cases.class);
|
||||
queryBuilder.addFilter(com.xboe.core.orm.FieldFilters.eq("deleted", false));
|
||||
// 只处理有文件路径的案例
|
||||
queryBuilder.addFilter(com.xboe.core.orm.FieldFilters.isNotNull("filePath"));
|
||||
queryBuilder.addFilter(com.xboe.core.orm.FieldFilters.ne("filePath", ""));
|
||||
|
||||
// 如果有上次处理的ID,则从该ID之后开始查询
|
||||
if (lastProcessedId != null && !lastProcessedId.isEmpty()) {
|
||||
queryBuilder.addFilter(com.xboe.core.orm.FieldFilters.gt("id", lastProcessedId));
|
||||
}
|
||||
|
||||
// 按创建时间升序排序
|
||||
queryBuilder.addOrder(com.xboe.common.OrderCondition.asc("id"));
|
||||
// 限制每次处理的数量,避免一次性处理太多数据
|
||||
queryBuilder.setPageSize(100);
|
||||
|
||||
return casesDao.findList(queryBuilder.builder());
|
||||
}
|
||||
|
||||
private void fixOnLastCase(String currentLastId) {
|
||||
stringRedisTemplate.opsForValue().set(CASE_UPLOAD_LAST_ID_KEY, currentLastId);
|
||||
log.info("已处理案例,最后一条记录ID已更新为: {}", currentLastId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.xboe.module.boecase.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* AI会话记录
|
||||
*/
|
||||
@Data
|
||||
public class CaseAiConversationVo {
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.xboe.module.boecase.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* AI会话消息记录VO
|
||||
*/
|
||||
@Data
|
||||
public class CaseAiMessageVo {
|
||||
|
||||
/**
|
||||
* 用户提问内容
|
||||
*/
|
||||
private String query;
|
||||
|
||||
/**
|
||||
* AI回答内容
|
||||
*/
|
||||
private String answer;
|
||||
|
||||
/**
|
||||
* 会话开始时间
|
||||
*/
|
||||
private LocalDateTime startTime;
|
||||
|
||||
/**
|
||||
* 会话时长(秒)
|
||||
*/
|
||||
private Integer durationSeconds;
|
||||
|
||||
/**
|
||||
* 案例引用列表
|
||||
*/
|
||||
private List<CaseReferVo> caseRefer;
|
||||
|
||||
/**
|
||||
* 建议列表
|
||||
*/
|
||||
private List<String> suggestions;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.xboe.module.boecase.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* AI调用日志列表展示VO
|
||||
*/
|
||||
@Data
|
||||
public class CaseDocumentLogVo {
|
||||
|
||||
/**
|
||||
* 日志ID
|
||||
*/
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 案例标题
|
||||
*/
|
||||
private String caseTitle;
|
||||
|
||||
/**
|
||||
* 操作类型
|
||||
*/
|
||||
private String optType;
|
||||
|
||||
/**
|
||||
* 调用接口名称
|
||||
*/
|
||||
private String requestUrl;
|
||||
|
||||
/**
|
||||
* 调用时间
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime optTime;
|
||||
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
private String requestBody;
|
||||
|
||||
/**
|
||||
* 响应参数
|
||||
*/
|
||||
private String responseBody;
|
||||
|
||||
/**
|
||||
* 接口调用结果
|
||||
* 0-调用中, 1-调用成功, 2-调用失败
|
||||
*/
|
||||
private Integer optStatus;
|
||||
|
||||
/**
|
||||
* 接口调用结果描述
|
||||
*/
|
||||
private String optStatusText;
|
||||
|
||||
/**
|
||||
* 业务处理结果
|
||||
* 1-处理成功, 2-处理失败
|
||||
*/
|
||||
private Integer caseStatus;
|
||||
|
||||
/**
|
||||
* 业务处理结果描述
|
||||
*/
|
||||
private String caseStatusText;
|
||||
|
||||
/**
|
||||
* 执行时间(ms)
|
||||
*/
|
||||
private Long executeDuration;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.xboe.module.boecase.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 案例引用信息VO
|
||||
*/
|
||||
@Data
|
||||
public class CaseReferVo {
|
||||
|
||||
/**
|
||||
* 案例ID
|
||||
*/
|
||||
private String caseId;
|
||||
|
||||
/**
|
||||
* 案例标题
|
||||
*/
|
||||
private String title;
|
||||
|
||||
/**
|
||||
* 作者姓名
|
||||
*/
|
||||
private String authorName;
|
||||
|
||||
/**
|
||||
* 组织信息
|
||||
*/
|
||||
private String orgInfo;
|
||||
|
||||
/**
|
||||
* 上传时间
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime uploadTime;
|
||||
|
||||
/**
|
||||
* 关键词列表
|
||||
*/
|
||||
private List<String> keywords;
|
||||
|
||||
/**
|
||||
* 案例内容
|
||||
*/
|
||||
private String content;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.xboe.module.boecase.vo;
|
||||
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 会话Excel导出VO
|
||||
*/
|
||||
@Data
|
||||
public class ConversationExcelVo {
|
||||
/**
|
||||
* 会话ID
|
||||
*/
|
||||
private String conversationId;
|
||||
|
||||
/**
|
||||
* 会话名称
|
||||
*/
|
||||
private String conversationName;
|
||||
|
||||
/**
|
||||
* 用户
|
||||
*/
|
||||
private String user;
|
||||
|
||||
/**
|
||||
* 问答记录
|
||||
*/
|
||||
private List<CaseAiMessageVo> messages;
|
||||
}
|
||||
@@ -2,11 +2,14 @@
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.boe.feign.api.infrastructure.entity.CommonSearchVo;
|
||||
import com.boe.feign.api.infrastructure.entity.Dict;
|
||||
import com.xboe.api.ThirdApi;
|
||||
import com.xboe.module.course.dto.*;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
@@ -169,19 +172,48 @@ public class CourseManageApi extends ApiBaseController{
|
||||
List<CourseSection> sectionlist=sectionService.getByCourseId(id);
|
||||
List<CourseTeacher> teachers=courseService.findTeachersByCourseId(id);
|
||||
List<CourseCrowd> crowds=courseService.findCrowdByCourseId(id);
|
||||
|
||||
//
|
||||
|
||||
CommonSearchVo searcher = new CommonSearchVo();
|
||||
searcher.setPid(637L);
|
||||
searcher.setType(1);
|
||||
List<Dict> dictList = thirdApi.getDictItems(searcher);
|
||||
boolean isPermission = false;
|
||||
if(dictList != null && dictList.size() > 0){
|
||||
List<String> dicts = dictList.stream().map(Dict::getValue).collect(Collectors.toList());
|
||||
isPermission = dicts.contains(course.getOrgId());
|
||||
rs.put("dicts",dicts);
|
||||
}
|
||||
log.error("-------是否仅内网查看 = " + isPermission);
|
||||
rs.put("course",course);
|
||||
rs.put("contents",cclist);
|
||||
rs.put("sections",sectionlist);
|
||||
rs.put("teachers",teachers);
|
||||
rs.put("crowds",crowds);
|
||||
|
||||
rs.put("isPermission",isPermission);
|
||||
|
||||
|
||||
|
||||
return success(rs);
|
||||
|
||||
}
|
||||
|
||||
@GetMapping("/getDictIds")
|
||||
public JsonResponse<Map<String,Object>> getDictIds(Long pid,Integer type){
|
||||
CommonSearchVo searcher = new CommonSearchVo();
|
||||
if(pid==null || type ==null){
|
||||
return badRequest("参数错误");
|
||||
}
|
||||
Map<String,Object> rs=new HashMap<String,Object>();
|
||||
searcher.setPid(pid);
|
||||
searcher.setType(type);
|
||||
List<Dict> dictList = thirdApi.getDictItems(searcher);
|
||||
rs.put("dicts",null);
|
||||
if(dictList != null && dictList.size() > 0){
|
||||
List<String> dicts = dictList.stream().map(Dict::getValue).collect(Collectors.toList());
|
||||
rs.put("dicts",dicts);
|
||||
}
|
||||
return success(rs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员审核列表,教师的审核不在这里,此审核也应该移动CourseAuditApi中去
|
||||
* @param pager
|
||||
@@ -886,7 +918,7 @@ public class CourseManageApi extends ApiBaseController{
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/delete")
|
||||
public JsonResponse<Boolean> delete(String id,Boolean erasable,String title,String remark){
|
||||
public JsonResponse<Boolean> delete(String id,Boolean erasable,String title,String remark, HttpServletRequest request){
|
||||
if(StringUtils.isBlank(id)){
|
||||
return badRequest("参数错误");
|
||||
}
|
||||
@@ -901,6 +933,11 @@ public class CourseManageApi extends ApiBaseController{
|
||||
try {
|
||||
CurrentUser cu=getCurrent();
|
||||
courseService.delete(id, erasable,cu.getAccountId(), cu.getName(), remark);
|
||||
|
||||
String token = request.getHeader("Xboe-Access-Token");
|
||||
CourseParam param = new CourseParam();
|
||||
param.setId(id);
|
||||
thirdApi.delOnLineById(param,token);
|
||||
return success(true);
|
||||
} catch (Exception e) {
|
||||
log.error("管理员删除课程错误",e);
|
||||
|
||||
@@ -33,7 +33,10 @@ public class Course extends BaseEntity {
|
||||
|
||||
/**所有的设备*/
|
||||
public static int DEVICE_ALL=3;
|
||||
|
||||
|
||||
/**仅内网*/
|
||||
public static int DEVICE_INTERNAL=4;
|
||||
|
||||
/**未提交,草稿*/
|
||||
public static final int STATUS_NONE=1;
|
||||
|
||||
|
||||
@@ -342,4 +342,5 @@ public interface ICourseService {
|
||||
|
||||
|
||||
List<Course> findByIds(List<String> courseIds);
|
||||
void deletedStudyResourceBatchByCourseIdAndType(String courseId,Integer courseType);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.xboe.module.course.service.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -20,6 +21,11 @@ import com.xboe.core.orm.*;
|
||||
import com.xboe.school.study.dao.StudyCourseDao;
|
||||
import com.xboe.school.study.entity.StudyCourse;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.elasticsearch.client.RequestOptions;
|
||||
import org.elasticsearch.client.RestHighLevelClient;
|
||||
import org.elasticsearch.index.query.BoolQueryBuilder;
|
||||
import org.elasticsearch.index.query.QueryBuilders;
|
||||
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
|
||||
import org.hibernate.mapping.IdGenerator;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
@@ -116,6 +122,9 @@ public class CourseServiceImpl implements ICourseService {
|
||||
@Autowired(required = false)
|
||||
private IEventDataSender eventSender;
|
||||
|
||||
@Resource
|
||||
RestHighLevelClient restHighLevelClient;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
@@ -174,6 +183,8 @@ public class CourseServiceImpl implements ICourseService {
|
||||
filters.add(FieldFilters.in("device", Course.DEVICE_MOBILE, Course.DEVICE_ALL));
|
||||
} else if (dto.getDevice() == Course.DEVICE_ALL) {
|
||||
filters.add(FieldFilters.eq("device", Course.DEVICE_ALL));
|
||||
}else if (dto.getDevice() == Course.DEVICE_INTERNAL) {
|
||||
filters.add(FieldFilters.eq("device", Course.DEVICE_INTERNAL));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -855,12 +866,14 @@ public class CourseServiceImpl implements ICourseService {
|
||||
log.error("未配置事件消息发送的实现");
|
||||
}
|
||||
}
|
||||
|
||||
// 删除ES数据
|
||||
deletedStudyResourceBatchByCourseIdAndType(id,c.getType());
|
||||
} else {
|
||||
//彻底删除,课件设置为无课程状态
|
||||
courseDao.setDeleted(id);
|
||||
}
|
||||
//记录删除日志信息
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1987,5 +2000,17 @@ public class CourseServiceImpl implements ICourseService {
|
||||
return courseDao.findListByHql("Select new Course(id,studys,score) from Course where id in(?1)", ids);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void deletedStudyResourceBatchByCourseIdAndType(String courseId, Integer courseType) {
|
||||
DeleteByQueryRequest request = new DeleteByQueryRequest("new_study_resource");
|
||||
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
|
||||
boolQueryBuilder.must(QueryBuilders.matchQuery("courseId", courseId));
|
||||
boolQueryBuilder.must(QueryBuilders.matchQuery("courseType", courseType));
|
||||
request.setQuery(boolQueryBuilder);
|
||||
try {
|
||||
restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.xboe.module.popup.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.xboe.core.SysConstant;
|
||||
import com.xboe.core.orm.IdEntity;
|
||||
import lombok.Data;
|
||||
@@ -24,12 +25,14 @@ public class Popup extends IdEntity {
|
||||
* 开始时间
|
||||
* */
|
||||
@Column(name = "start_time")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
/**
|
||||
* 结束时间
|
||||
* */
|
||||
@Column(name = "end_time")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime endTime;
|
||||
|
||||
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
package com.xboe.school.study.api;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.alibaba.nacos.shaded.com.google.common.util.concurrent.RateLimiter;
|
||||
import com.boe.feign.api.infrastructure.entity.CommonSearchVo;
|
||||
import com.boe.feign.api.infrastructure.entity.Dict;
|
||||
import com.xboe.api.ThirdApi;
|
||||
import com.xboe.constants.CacheName;
|
||||
import com.xboe.module.course.vo.TeacherVo;
|
||||
import com.xboe.module.usergroup.service.IUserGroupService;
|
||||
import com.xboe.school.study.dao.StudyCourseDao;
|
||||
import com.xboe.school.vo.StudyTimeVo;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -227,7 +235,30 @@ public class StudyCourseApi extends ApiBaseController{
|
||||
rs.put("contents",cclist);
|
||||
rs.put("sections",sectionlist);
|
||||
rs.put("teachers",teachers);
|
||||
|
||||
// 未选择仅内网时isPermission = false,不用区分内外网
|
||||
boolean isPermission = false;
|
||||
if(course.getDevice() ==4){
|
||||
CommonSearchVo searcher = new CommonSearchVo();
|
||||
searcher.setPid(637L);
|
||||
searcher.setType(1);
|
||||
List<Dict> dictList = thirdApi.getDictItems(searcher);
|
||||
if(dictList != null && dictList.size() > 0){
|
||||
List<String> dicts = dictList.stream().map(Dict::getValue).collect(Collectors.toList());
|
||||
// 选择仅内网 并且字典中配置了此课程资源归属,那么只能内网观看 返回 truw
|
||||
isPermission = dicts.contains(course.getOrgId());
|
||||
}
|
||||
}
|
||||
rs.put("isPermission",isPermission);
|
||||
|
||||
CommonSearchVo warn = new CommonSearchVo();
|
||||
warn.setCode("course_warn");
|
||||
warn.setType(1);
|
||||
List<Dict> warns = thirdApi.getDictItems(warn);
|
||||
if(warns != null && warns.size() > 0){
|
||||
rs.put("warn",warns.get(0).getValue());
|
||||
rs.put("warnTitle",warns.get(0).getName());
|
||||
}
|
||||
|
||||
//检查是否已报名
|
||||
StudyCourse sc=service.findByCourseIdAndAid(cid, aid);
|
||||
if(pass==true && sc==null) {
|
||||
@@ -253,6 +284,36 @@ public class StudyCourseApi extends ApiBaseController{
|
||||
rs.put("progress", sc.getProgress());
|
||||
//查询上次学习的是什么资源。查询用户的学习情况
|
||||
List<StudyCourseItem> items=studyService.findByStudyId(sc.getId());
|
||||
// 和内容匹配,根据内容的视频时长,计算学习进度
|
||||
if(CollectionUtil.isNotEmpty(items) && CollectionUtil.isNotEmpty(cclist)){
|
||||
// 根据ID转换map
|
||||
Map<String, CourseContent> contentMap = cclist.stream().collect(Collectors.toMap(CourseContent::getId, Function.identity()));
|
||||
for (StudyCourseItem item : items) {
|
||||
CourseContent content = contentMap.get(item.getContentId());
|
||||
if(null == content){
|
||||
continue;
|
||||
}
|
||||
|
||||
if(null==item.getLastStudyTime()
|
||||
|| item.getLastStudyTime()<=0
|
||||
|| null==content.getDuration()
|
||||
|| content.getDuration()<=0){
|
||||
continue;
|
||||
}
|
||||
|
||||
BigDecimal lastStudyTime = new BigDecimal(item.getLastStudyTime());
|
||||
BigDecimal duration = new BigDecimal(content.getDuration());
|
||||
BigDecimal progress = lastStudyTime.divide(duration, 10, RoundingMode.HALF_UP);
|
||||
if(progress.compareTo(BigDecimal.ZERO) < 0){
|
||||
progress = BigDecimal.ZERO;
|
||||
}else if(progress.compareTo(BigDecimal.ONE) > 0){
|
||||
progress = BigDecimal.ONE;
|
||||
}
|
||||
|
||||
item.setProgressVideo(progress);
|
||||
}
|
||||
}
|
||||
|
||||
rs.put("contentStudys",items);//学习的内容
|
||||
}
|
||||
|
||||
@@ -577,7 +638,7 @@ public class StudyCourseApi extends ApiBaseController{
|
||||
@Deprecated
|
||||
@RequestMapping(value="/appendtime",method = {RequestMethod.GET,RequestMethod.POST})
|
||||
public JsonResponse<String> appendTime(StudyTime studyTime, HttpServletRequest request){
|
||||
|
||||
|
||||
if(StringUtils.isBlank(studyTime.getStudyId())){
|
||||
return error("参数错误");
|
||||
}
|
||||
@@ -607,7 +668,91 @@ public class StudyCourseApi extends ApiBaseController{
|
||||
return error("记录学习时长错误",e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* appendtime 于 study-video-time 合并
|
||||
* */
|
||||
/*@RequestMapping(value="/updateStudyVideoTime1",method = {RequestMethod.GET,RequestMethod.POST})
|
||||
public JsonResponse<String> updateStudyVideoTime1(StudyTimeVo studyTime, HttpServletRequest request){
|
||||
|
||||
// 0 study-video-time , 1 appendtime
|
||||
if (studyTime.getType() == 0){
|
||||
if(StringUtils.isBlank(studyTime.getItemId())){
|
||||
return error("参数错误");
|
||||
}
|
||||
if(studyTime.getVideoTime()==null){
|
||||
return error("无时间点");
|
||||
}
|
||||
//检查是否已存在
|
||||
try {
|
||||
studyService.updateLastTime(studyTime.getItemId(),studyTime.getVideoTime(), getCurrent().getAccountId());
|
||||
if (studyTime.getContentId() != null && studyTime.getCourseId() != null && studyTime.getProgressVideo() != null){
|
||||
contentService.updateProcessVideo(studyTime.getContentId(), studyTime.getCourseId(), studyTime.getProgressVideo());
|
||||
}
|
||||
return success("true");
|
||||
}catch(Exception e) {
|
||||
log.error("updateStudyVideoTime type =0 记录最后学习时间错误",e);
|
||||
return error("updateStudyVideoTime type =0 记录最后学习时间失败 ",e.getMessage());
|
||||
}
|
||||
}else if(studyTime.getType() == 1){
|
||||
if(StringUtils.isBlank(studyTime.getStudyId())){
|
||||
return error("参数错误");
|
||||
}
|
||||
if(StringUtils.isBlank(studyTime.getCourseId())){
|
||||
return error("未指定课程");
|
||||
}
|
||||
if(StringUtils.isBlank(studyTime.getContentId())){
|
||||
return error("未指定资源内容");
|
||||
}
|
||||
|
||||
String token = request.getHeader("Xboe-Access-Token");
|
||||
if (StringUtils.isEmpty(token)) {
|
||||
token = request.getHeader("token");
|
||||
}
|
||||
try {
|
||||
studyService.updateStudyDuration(studyTime.getStudyId(),null,studyTime.getContentId(),studyTime.getVideoTime(),studyTime.getCourseId());
|
||||
List<StudyCourse> allUserList = thirdApi.getStudyCourseList(studyTime.getStudyId() ,studyTime.getCourseId(), token);
|
||||
log.info("updateStudyVideoTime type =1 在线课学习记录 = " + allUserList);
|
||||
return success(studyTime.getId());
|
||||
}catch(Exception e) {
|
||||
log.error("updateStudyVideoTime type =1 记录学习时长错误",e);
|
||||
return error("updateStudyVideoTime type =1 记录学习时长错误 ",e.getMessage());
|
||||
}
|
||||
}else{
|
||||
return error("type不能为空");
|
||||
}
|
||||
}*/
|
||||
|
||||
@RequestMapping(value="/updateStudyVideoTime",method = {RequestMethod.GET,RequestMethod.POST})
|
||||
public JsonResponse<String> updateStudyVideoTime(StudyTimeVo studyTime, HttpServletRequest request){
|
||||
try {
|
||||
if(StringUtils.isBlank(studyTime.getItemId())){
|
||||
return error("参数错误");
|
||||
}
|
||||
if(studyTime.getVideoTime()==null){
|
||||
return error("无时间点");
|
||||
}
|
||||
if(StringUtils.isBlank(studyTime.getStudyId())){
|
||||
return error("参数错误");
|
||||
}
|
||||
if(StringUtils.isBlank(studyTime.getCourseId())){
|
||||
return error("未指定课程");
|
||||
}
|
||||
if(StringUtils.isBlank(studyTime.getContentId())){
|
||||
return error("未指定资源内容");
|
||||
}
|
||||
studyService.updateStudyDuration(studyTime.getStudyId(),studyTime.getItemId(),studyTime.getContentId(),studyTime.getVideoTime(),studyTime.getCourseId());
|
||||
if (studyTime.getContentId() != null && studyTime.getCourseId() != null && studyTime.getProgressVideo() != null){
|
||||
contentService.updateProcessVideo(studyTime.getContentId(), studyTime.getCourseId(), studyTime.getProgressVideo());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("updateStudyVideoTime",e);
|
||||
return error("学习时长记录失败",e.getMessage(),null);
|
||||
}
|
||||
return success("true");
|
||||
}
|
||||
|
||||
/**获取最后一次的学习内容*/
|
||||
@GetMapping("/last-study")
|
||||
public JsonResponse<Map<String,Object>> lastStudy(){
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.xboe.school.study.api;
|
||||
|
||||
import com.xboe.api.ThirdApi;
|
||||
import com.xboe.school.study.entity.StudyCourse;
|
||||
import com.xboe.school.study.service.IStudyService;
|
||||
import com.xxl.job.core.handler.annotation.XxlJob;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -10,10 +12,13 @@ import org.springframework.data.redis.core.ScanOptions;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
/**
|
||||
* @author by lyc
|
||||
@@ -26,13 +31,15 @@ public class StudyCourseTask {
|
||||
|
||||
private final IStudyService studyService;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
@Resource
|
||||
private ThirdApi thirdApi;
|
||||
|
||||
/**
|
||||
* 定时任务
|
||||
* 获取redis 中学习结束的数据更新入库
|
||||
* */
|
||||
@XxlJob("saveStudyCourseItemLastTime")
|
||||
public void saveStudyCourseItemLastTime() {
|
||||
@XxlJob("saveStudyCourseItemLastTime2")
|
||||
public void saveStudyCourseItemLastTime2() {
|
||||
// 1. 定义匹配模式(匹配所有目标key)
|
||||
final String KEY_PATTERN = "studyContentId:*:last_active";
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
|
||||
@@ -59,7 +66,6 @@ public class StudyCourseTask {
|
||||
String[] parts = redisKey.split(":");
|
||||
if (parts.length < 2) continue;
|
||||
String studyContentId = parts[1];
|
||||
|
||||
// 7. 获取存储的时间点(示例逻辑)
|
||||
String redisValue = redisTemplate.opsForValue().get(redisKey);
|
||||
if (redisValue == null) continue;
|
||||
@@ -69,19 +75,15 @@ public class StudyCourseTask {
|
||||
if (partValues.length >= 2){
|
||||
timestamp = LocalDateTime.parse(partValues[1], formatter);
|
||||
}
|
||||
|
||||
// 8. 更新数据库(调用已有服务方法)
|
||||
studyService.updateStudyCourseItemLastTime(studyContentId, lastStudyTime, timestamp);
|
||||
|
||||
// 9. 删除Redis键(原子操作)
|
||||
redisTemplate.delete(redisKey);
|
||||
|
||||
log.info("处理成功 key: {}, lastStudyTime: {}", redisKey, lastStudyTime);
|
||||
} catch (Exception e) {
|
||||
log.error("处理失败 key: {}", redisKey, e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
cursor.close();
|
||||
} catch (Exception e) {
|
||||
@@ -102,5 +104,159 @@ public class StudyCourseTask {
|
||||
}
|
||||
|
||||
|
||||
@XxlJob("saveStudyCourseItemLastTime")
|
||||
public void saveStudyCourseItemLastTime() {
|
||||
// 1. 定义匹配模式(匹配所有目标key)
|
||||
final String KEY_PATTERN = "studyId:*:courseId:*:courseContentId:*:studyItemId:*";
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
|
||||
// 2. 使用SCAN安全遍历(避免阻塞)
|
||||
ScanOptions options = ScanOptions.scanOptions()
|
||||
.match(KEY_PATTERN)
|
||||
.count(100) // 分页大小
|
||||
.build();
|
||||
|
||||
try (RedisConnection connection = Objects.requireNonNull(redisTemplate.getConnectionFactory()).getConnection()) {
|
||||
Cursor<byte[]> cursor = connection.scan(options);
|
||||
// 3. 遍历处理符合条件的key
|
||||
while (cursor.hasNext()) {
|
||||
String redisKey = new String(cursor.next());
|
||||
log.info("-定时任务 saveStudyCourseItemLastTime ---redisKey = " + redisKey);
|
||||
// 4. 获取剩余TTL(秒)
|
||||
Long ttl = redisTemplate.getExpire(redisKey, TimeUnit.SECONDS);
|
||||
|
||||
// 5. 过滤条件:剩余时间 >= 29天23小时30分钟(转换为秒)
|
||||
// 总需时间 = (30天 - 30分钟) = 29天23小时30分钟 = 2590200秒
|
||||
// 5分钟 300秒 || 2592000 - 300 = 2591700
|
||||
if (ttl <= 2590200) {
|
||||
try {
|
||||
// 6. 提取studyContentId
|
||||
String[] parts = redisKey.split(":");
|
||||
if (parts.length < 7) continue;
|
||||
String studyId = parts[1];
|
||||
String courseId = parts[3];
|
||||
String courseContentId = parts[5];
|
||||
String studyItemId = parts[7];
|
||||
// 7. 获取存储的时间点(示例逻辑)
|
||||
String redisValue = redisTemplate.opsForValue().get(redisKey);
|
||||
log.info("-定时任务 saveStudyCourseItemLastTime ---redisValue = " + redisValue);
|
||||
if (redisValue == null) continue;
|
||||
String[] partValues = redisValue.split("&");
|
||||
int studyVideoTtime = Integer.parseInt(partValues[0]);
|
||||
int appendtime = Integer.parseInt(partValues[1]);
|
||||
LocalDateTime timestamp = null;
|
||||
if (partValues.length >= 2){
|
||||
timestamp = LocalDateTime.parse(partValues[2], formatter);
|
||||
}
|
||||
// 8. 更新数据库(调用已有服务方法)
|
||||
studyService.newAppendStudyDuration(studyId,null,courseContentId,appendtime,timestamp);
|
||||
log.info("-定时任务 saveStudyCourseItemLastTime ---studyItemId = " + studyItemId);
|
||||
if (studyItemId != null && !studyItemId.equals("null")){
|
||||
log.info("-定时任务 saveStudyCourseItemLastTime --- boolean studyItemId = " + (studyItemId != null));
|
||||
// 8. 更新数据库(调用已有服务方法)
|
||||
studyService.updateStudyCourseItemLastTime(studyItemId, studyVideoTtime, timestamp);
|
||||
}
|
||||
List<StudyCourse> allUserList = thirdApi.getStudyCourseList(studyId , courseId, null);
|
||||
log.info("处理成功 allUserList: {}", allUserList);
|
||||
// 9. 删除Redis键(原子操作)
|
||||
redisTemplate.delete(redisKey);
|
||||
log.info("处理成功 key: {}, lastStudyTime: {}", redisKey, appendtime);
|
||||
} catch (Exception e) {
|
||||
log.error("处理失败 key: {}", redisKey, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
cursor.close();
|
||||
} catch (Exception e) {
|
||||
log.error("定时任务执行异常", e);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@XxlJob("saveStudyCourseItemLastTime1")
|
||||
public void saveStudyCourseItemLastTime1() {
|
||||
// 定义需要处理的键模式集合
|
||||
processKeys("studyContentId:*:last_active", this::handleLastActiveKey);
|
||||
processKeys("studyId:*:courseId:*:courseContentId:*", this::handleDurationKey);
|
||||
}
|
||||
|
||||
private void processKeys(String keyPattern, BiConsumer<String, String> keyHandler) {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
|
||||
ScanOptions options = ScanOptions.scanOptions()
|
||||
.match(keyPattern)
|
||||
.count(100)
|
||||
.build();
|
||||
|
||||
try (RedisConnection connection = Objects.requireNonNull(redisTemplate.getConnectionFactory()).getConnection()) {
|
||||
Cursor<byte[]> cursor = connection.scan(options);
|
||||
while (cursor.hasNext()) {
|
||||
String redisKey = new String(cursor.next());
|
||||
Long ttl = redisTemplate.getExpire(redisKey, TimeUnit.SECONDS);
|
||||
|
||||
if (ttl != null && ttl <= 2590200) {
|
||||
try {
|
||||
String redisValue = redisTemplate.opsForValue().get(redisKey);
|
||||
if (redisValue != null) {
|
||||
// 调用对应的处理方法
|
||||
keyHandler.accept(redisKey, redisValue);
|
||||
}
|
||||
redisTemplate.delete(redisKey);
|
||||
log.info("Key processed: {}", redisKey);
|
||||
} catch (Exception e) {
|
||||
log.error("Process failed [{}]", redisKey, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
cursor.close();
|
||||
} catch (Exception e) {
|
||||
log.error("Key processing error: {}", keyPattern, e);
|
||||
}
|
||||
}
|
||||
|
||||
// 处理 last_active 类型键
|
||||
private void handleLastActiveKey(String redisKey, String redisValue) {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
|
||||
String[] parts = redisKey.split(":");
|
||||
String studyContentId = parts[1];
|
||||
|
||||
String[] values = redisValue.split("&");
|
||||
int lastStudyTime = Integer.parseInt(values[0]);
|
||||
LocalDateTime timestamp = values.length >= 2 ?
|
||||
LocalDateTime.parse(values[1], formatter) : null;
|
||||
|
||||
studyService.updateStudyCourseItemLastTime(studyContentId, lastStudyTime, timestamp);
|
||||
}
|
||||
|
||||
// 处理 duration 类型键
|
||||
private void handleDurationKey(String redisKey, String redisValue) {
|
||||
String[] parts = redisKey.split(":");
|
||||
String studyId = parts[1];
|
||||
String courseId = parts[3];
|
||||
String courseContentId = parts[5];
|
||||
|
||||
String[] values = redisValue.split("&");
|
||||
int duration = Integer.parseInt(values[0]);
|
||||
LocalDateTime timestamp = values.length >= 2 ?
|
||||
LocalDateTime.parse(values[1], DateTimeFormatter.ISO_LOCAL_DATE_TIME) : null;
|
||||
|
||||
studyService.newAppendStudyDuration(studyId, null, courseContentId, duration, timestamp);
|
||||
|
||||
// 保留第三方调用
|
||||
List<StudyCourse> allUserList = thirdApi.getStudyCourseList(studyId, courseId, null);
|
||||
log.info("Study records synced: {}", allUserList.size());
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.xboe.school.study.entity;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.Transient;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.xboe.core.SysConstant;
|
||||
@@ -128,5 +130,12 @@ public class StudyCourseItem extends IdEntity {
|
||||
*/
|
||||
@Column(name = "status",length=1)
|
||||
private Integer status;
|
||||
|
||||
|
||||
/**
|
||||
* 视频播放进度
|
||||
* */
|
||||
// @Column(name = "progress_video")
|
||||
@Transient
|
||||
private BigDecimal progressVideo;
|
||||
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import com.xboe.common.PageList;
|
||||
import com.xboe.school.study.dto.StudyContentDto;
|
||||
import com.xboe.school.study.entity.StudyCourseItem;
|
||||
import com.xboe.school.study.entity.StudyTime;
|
||||
import com.xboe.system.user.entity.User;
|
||||
|
||||
/**
|
||||
* 学习情况处理,比较综合一个处理类
|
||||
@@ -36,11 +35,12 @@ public interface IStudyService {
|
||||
|
||||
/**
|
||||
* 更新最后的学习时间,及学习时间点
|
||||
*
|
||||
* @param studyContentId
|
||||
* @param lastStudyTime
|
||||
* @param aid
|
||||
*/
|
||||
void updateLastTime(String studyContentId,int lastStudyTime,String aid);
|
||||
void updateLastTime(String studyContentId, int lastStudyTime, String aid);
|
||||
|
||||
/**
|
||||
* 资源学习记录
|
||||
@@ -101,4 +101,8 @@ public interface IStudyService {
|
||||
List<StudyCourseItem> getList(String courseId, String contentId, String name, Integer status);
|
||||
|
||||
void updateStudyCourseItemLastTime(String studyContentId, int lastStudyTime, LocalDateTime timestamp);
|
||||
|
||||
void updateStudyDuration(String studyId,String studyItemId, String contentId, Integer videoTime,String courseId);
|
||||
|
||||
void newAppendStudyDuration(String studyId, String studyItemId, String courseContentId, int duration, LocalDateTime timestamp);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.xboe.module.course.entity.CourseExam;
|
||||
import com.xboe.school.study.dao.StudyCourseDao;
|
||||
import com.xboe.school.study.dao.StudyCourseItemDao;
|
||||
import com.xboe.school.study.dao.StudyExamDao;
|
||||
import com.xboe.school.study.entity.StudyCourse;
|
||||
import com.xboe.school.study.entity.StudyCourseItem;
|
||||
import com.xboe.school.study.entity.StudyExam;
|
||||
import com.xboe.school.study.service.IStudyExamService;
|
||||
@@ -170,15 +171,32 @@ public class StudyExamServiceImpl implements IStudyExamService{
|
||||
}
|
||||
builder.addGroupBy("studyId");
|
||||
List<StudyExam> list1 = dao.findList(builder.builder());
|
||||
log.info("------------QueryBuilder list1.size = " + list1.size() + ",0 = " + list1.get(0));
|
||||
|
||||
for(StudyExam item : list1){
|
||||
log.info("-----------------CourseId = " + item.getCourseId() + " , StudyId = " + item.getStudyId() + " , StudentId = " + item.getStudentId());
|
||||
int totalContent = courseContentDao.getCount(item.getCourseId());
|
||||
log.info("----------准备判断进度-------totalContent = " + totalContent);
|
||||
scDao.finishCheck1(item.getStudyId(),item.getCourseId(),totalContent);
|
||||
log.info("----------判断进度完毕----------------------");
|
||||
if(list1 != null && list1.size() > 0){
|
||||
log.info("----------StudyExam--QueryBuilder list1.size = " + list1.size() + ",0 = " + list1.get(0));
|
||||
for(StudyExam item : list1){
|
||||
log.info("--------------StudyExam---CourseId = " + item.getCourseId() + " , StudyId = " + item.getStudyId() + " , StudentId = " + item.getStudentId());
|
||||
int totalContent = courseContentDao.getCount(item.getCourseId());
|
||||
log.info("--------StudyExam--准备判断进度-------totalContent = " + totalContent);
|
||||
scDao.finishCheck1(item.getStudyId(),item.getCourseId(),totalContent);
|
||||
log.info("--------StudyExam--判断进度完毕----------------------");
|
||||
}
|
||||
}else{
|
||||
QueryBuilder builder1 = QueryBuilder.from(StudyCourse.class);
|
||||
if (StringUtils.isEmpty(courseId)){
|
||||
return;
|
||||
}
|
||||
builder1.addFilter(FieldFilters.eq("courseId", courseId));
|
||||
List<StudyCourse> list2 = scDao.findList(builder1.builder());
|
||||
log.info("------------StudyCourse list2.size = " + list2.size() + ",0 = " + list2.get(0));
|
||||
for(StudyCourse item : list2){
|
||||
log.info("-------------StudyCourse----CourseId = " + item.getCourseId() + " , StudyId = " + item.getId() + " , StudentId = " + item.getAid());
|
||||
int totalContent = courseContentDao.getCount(item.getCourseId());
|
||||
log.info("--------StudyCourse--准备判断进度-------totalContent = " + totalContent);
|
||||
scDao.finishCheck1(item.getId(),item.getCourseId(),totalContent);
|
||||
log.info("--------StudyCourse--判断进度完毕----------------------");
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
log.info("------异常----------------------:" +exception.getMessage());
|
||||
|
||||
@@ -10,10 +10,6 @@ import java.util.Map;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import com.xboe.module.article.entity.Article;
|
||||
import com.xboe.module.interaction.entity.Shares;
|
||||
import com.xboe.school.study.entity.StudyCourse;
|
||||
import com.xboe.system.user.entity.User;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
@@ -120,34 +116,74 @@ public class StudyServiceImpl implements IStudyService{
|
||||
//增加内容的学习时长
|
||||
if(StringUtils.isNotBlank(studyItemId)) {
|
||||
//直接根据id更新
|
||||
// String hql="Update StudyCourseItem set studyDuration=studyDuration+"+duration+",status=(case when status<2 then 2 else status end) where id=?1";
|
||||
// scItemDao.update(hql,studyItemId);
|
||||
String sql="Update boe_study_course_item set study_duration=study_duration+"+duration+",status=(case when status<2 then 2 else status end) where id=?1";
|
||||
scItemDao.sqlUpdate(sql,studyItemId);
|
||||
//scItemDao.updateMultiFieldById(studyItemId, UpdateBuilder.create("studyDuration", "studyDuration+"+duration,FieldUpdateType.EXPRESSION));
|
||||
|
||||
|
||||
}else {
|
||||
//根据学习id和课程内容id更新
|
||||
// scItemDao.update(UpdateBuilder.from(StudyCourseItem.class)
|
||||
// .addUpdateField("studyDuration", "studyDuration+"+duration,FieldUpdateType.EXPRESSION)
|
||||
// .addFilter(FieldFilters.eq("studyId", studyId))
|
||||
// .addFilter(FieldFilters.eq("contentId", courseContentId))
|
||||
// .builder());
|
||||
//
|
||||
// String hql="Update StudyCourseItem set studyDuration=studyDuration+"+duration+",status=(case when status<2 then 2 else status end) where studyId=?1 and contentId=?2";
|
||||
// scItemDao.update(hql,studyId,courseContentId);
|
||||
String sql="Update boe_study_course_item set study_duration=study_duration+"+duration+",status=(case when status<2 then 2 else status end) where study_id=?1 and content_id=?2";
|
||||
scItemDao.sqlUpdate(sql,studyId,courseContentId);
|
||||
}
|
||||
|
||||
//追加课程的学习时长
|
||||
//scDao.updateMultiFieldById(studyId, UpdateBuilder.create("totalDuration", "totalDuration+"+duration,FieldUpdateType.EXPRESSION));
|
||||
|
||||
String sql="Update boe_study_course set total_duration=total_duration+"+duration+",status=(case when status<2 then 2 else status end),progress=(case when progress=0 then 1 else progress end),last_time = '"+LocalDateTime.now()+"' where id=?1";
|
||||
scDao.sqlUpdate(sql,studyId);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void newAppendStudyDuration(String studyId,String studyItemId,String courseContentId, int duration,LocalDateTime timestamp) {
|
||||
|
||||
//增加内容的学习时长
|
||||
if(StringUtils.isNotBlank(studyItemId)) {
|
||||
//直接根据id更新
|
||||
String sql="Update boe_study_course_item set study_duration=study_duration+"+duration+",status=(case when status<2 then 2 else status end) where id=?1";
|
||||
scItemDao.sqlUpdate(sql,studyItemId);
|
||||
|
||||
}else {
|
||||
String sql="Update boe_study_course_item set study_duration=study_duration+"+duration+",status=(case when status<2 then 2 else status end) where study_id=?1 and content_id=?2";
|
||||
scItemDao.sqlUpdate(sql,studyId,courseContentId);
|
||||
}
|
||||
|
||||
String sql="Update boe_study_course set total_duration=total_duration+"+duration+",status=(case when status<2 then 2 else status end),progress=(case when progress=0 then 1 else progress end),last_time = '"+timestamp+"' where id=?1";
|
||||
scDao.sqlUpdate(sql,studyId);
|
||||
}
|
||||
|
||||
// 更新 前端传输已学习时长
|
||||
@Override
|
||||
public void updateStudyDuration(String studyId,String studyItemId,String courseContentId, Integer videoTime,String courseId) {
|
||||
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
|
||||
|
||||
String key = "studyId:" + studyId + ":courseId:" + courseId + ":courseContentId:" + courseContentId + ":studyItemId:" + studyItemId;
|
||||
String currentValue = redisTemplate.opsForValue().get(key);
|
||||
Integer lastDuration = 0;
|
||||
Integer oldVideoTime = 0;
|
||||
Integer sum = 10; // 原appendtime改为固定10秒调用一次接口
|
||||
if (currentValue != null) {
|
||||
String[] partValues = currentValue.split("&");
|
||||
oldVideoTime = Integer.parseInt(partValues[0]);
|
||||
lastDuration = Integer.parseInt(partValues[1]);
|
||||
sum += lastDuration;
|
||||
if(oldVideoTime > videoTime){
|
||||
videoTime = oldVideoTime;// 取最大值最终入库
|
||||
}
|
||||
};
|
||||
|
||||
String value = videoTime + "&" + sum + "&" + now.format(formatter); // study_video_time & appendtime & time
|
||||
log.info("-study-video-time-----value = " + value);
|
||||
|
||||
// 20250303 优化 多次更新改一次更新
|
||||
// 更新Redis中的最后活跃时间(带30秒过期)
|
||||
redisTemplate.opsForValue().set(
|
||||
key,
|
||||
value,
|
||||
Duration.ofSeconds(2592000)
|
||||
);
|
||||
log.info("- 合并 updateStudyDuration -redis保存---value = " + value);
|
||||
// Duration.ofDays(30) 也就是 2592000秒
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void appendStudyDuration(StudyTime st) {
|
||||
@@ -170,7 +206,21 @@ public class StudyServiceImpl implements IStudyService{
|
||||
|
||||
@Override
|
||||
public List<StudyCourseItem> findByStudyId(String studyId) {
|
||||
return scItemDao.findList(OrderCondition.desc("lastTime"),FieldFilters.eq("studyId", studyId));
|
||||
List<StudyCourseItem> list = scItemDao.findList(OrderCondition.desc("lastTime"),FieldFilters.eq("studyId", studyId));
|
||||
for (StudyCourseItem item : list){
|
||||
log.info("-- studyIndex -查询上次学习的是什么资源。mysql查询---------------- item = " + item);
|
||||
String redisKey = "studyId:" + studyId + ":courseId:" + item.getCourseId() + ":courseContentId:" + item.getContentId() + ":studyItemId:" + item.getId();
|
||||
log.info("-- studyIndex -查询上次学习的是什么资源。查询用户的学习情况---------------- redisKey = " + redisKey);
|
||||
String redisValue = redisTemplate.opsForValue().get(redisKey);
|
||||
log.info("-- studyIndex -查询上次学习的是什么资源。查询用户的学习情况---------------- redisValue = " + redisValue);
|
||||
if (redisValue != null) {
|
||||
String[] values = redisValue.split("&");
|
||||
int duration = Integer.parseInt(values[0]);
|
||||
item.setLastStudyTime(duration);
|
||||
log.info("-- studyIndex -----set 结果---------------- LastStudyTime = " + item.getLastStudyTime());
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -232,11 +282,12 @@ public class StudyServiceImpl implements IStudyService{
|
||||
return pageList;
|
||||
}
|
||||
}
|
||||
|
||||
String sql = "select a.id, a.course_id, a.course_name, a.aname, " +
|
||||
"IFNULL(b.finish_time, '0') as finish_time, IFNULL(b.progress, 0) as progress, IFNULL(b.status, 1) as status " +
|
||||
"IFNULL(b.finish_time, '0') as finish_time, IFNULL(b.progress, 0) as progress, IFNULL(b.status, 1) as status,b.score " +
|
||||
"from (select id, course_id, course_name, aname, 0, 1 from boe_study_course where course_id = '" + courseId + "' and aname like '%"+name+"%') a " +
|
||||
"left join " +
|
||||
"(select bsc.id, bsc.course_id, bsc.course_name, bsc.aname, item.finish_time, item.progress, item.status " +
|
||||
"(select bsc.id, bsc.course_id, bsc.course_name, bsc.aname, item.finish_time, item.progress, item.status,MAX(item.score) score " +
|
||||
"from boe_study_course bsc left join boe_study_course_item item on item.course_id = bsc.course_id and item.study_id = bsc.id " +
|
||||
"where bsc.course_id = '" + courseId + "' and item.content_id = '" + contentId + "' and item.aname like '%"+name+"%' group by bsc.id) b " +
|
||||
"on a.course_id = b.course_id and a.id = b.id " +
|
||||
@@ -265,6 +316,9 @@ public class StudyServiceImpl implements IStudyService{
|
||||
sc.setProgress(Integer.valueOf(objs[5].toString()));
|
||||
sc.setStatus(Integer.valueOf(objs[6].toString()));
|
||||
sc.setAname(objs[3].toString());
|
||||
if(objs[7] != null){
|
||||
sc.setScore(Float.valueOf(objs[7].toString()));
|
||||
}
|
||||
item.add(sc);
|
||||
}
|
||||
log.info("资源完成情况人员"+item);
|
||||
@@ -361,6 +415,7 @@ public class StudyServiceImpl implements IStudyService{
|
||||
log.info("-study-video-time-mysql保存---studyContentId = " + studyContentId);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Map<String,Object> getLast(String aid) {
|
||||
//按lastTime排序,第一条,只是课件内容
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.xboe.school.vo;
|
||||
|
||||
import com.xboe.school.study.entity.StudyTime;
|
||||
import lombok.Data;
|
||||
|
||||
/** appendtime 于 study-video-time 合并
|
||||
* appendtime 参数 StudyTime
|
||||
* study-video-time 参数 是 StudyTimeVo
|
||||
*/
|
||||
@Data
|
||||
public class StudyTimeVo extends StudyTime {
|
||||
|
||||
private String itemId;
|
||||
private Integer videoTime;
|
||||
// private String contentId; // 已继承
|
||||
// private String courseId; // 已继承
|
||||
private Float progressVideo;
|
||||
private Integer type; // 0 study-video-time , 1 appendtime
|
||||
}
|
||||
@@ -79,6 +79,16 @@ xboe:
|
||||
image:
|
||||
course:
|
||||
default: http://192.168.0.253/pc/images/bgimg/course.png
|
||||
case:
|
||||
ai:
|
||||
base-url: http://10.10.181.114:30003
|
||||
app-key: 6e9be45319184ac793aa127c362b0f0b
|
||||
secret-key: db4d24279e3d6dbf1524af42cd0bedd2
|
||||
ai-api-code: 30800
|
||||
case-knowledge-id: de2e006e-82fb-4ace-8813-f25c316be4ff
|
||||
file-upload-callback-url: http://192.168.0.253:9090/xboe/m/boe/caseDocumentLog/uploadCallback
|
||||
alert-email-recipients:
|
||||
- liu.zixi@ebiz-digits.com
|
||||
xxl:
|
||||
job:
|
||||
accessToken: 65ddc683-22f5-83b4-de3a-3c97a0a29af0
|
||||
|
||||
@@ -111,6 +111,16 @@ xboe:
|
||||
image:
|
||||
course:
|
||||
default: http://10.251.132.75/pc/images/bgimg/course.png
|
||||
case:
|
||||
ai:
|
||||
base-url: http://10.10.181.114:30003
|
||||
app-key: 6e9be45319184ac793aa127c362b0f0b
|
||||
secret-key: db4d24279e3d6dbf1524af42cd0bedd2
|
||||
ai-api-code: 30800
|
||||
case-knowledge-id: de2e006e-82fb-4ace-8813-f25c316be4ff
|
||||
file-upload-callback-url: http://10.251.132.75:9090/xboe/m/boe/caseDocumentLog/uploadCallback
|
||||
alert-email-recipients:
|
||||
- liu.zixi@ebiz-digits.com
|
||||
jasypt:
|
||||
encryptor:
|
||||
algorithm: PBEWithMD5AndDES
|
||||
|
||||
@@ -77,6 +77,47 @@ xboe:
|
||||
image:
|
||||
course:
|
||||
default: https://u.boe.com/pc/images/bgimg/course.png
|
||||
case:
|
||||
ai:
|
||||
base-url: https://gateway-internal.boe.com
|
||||
# base-url: https://gateway-pro.boe.com
|
||||
app-key: 3edef300b25642da949ccddf58441a0f
|
||||
secret-key: 43bc8003a811a7f9c89cbecbfe4bbb22
|
||||
ai-api-code: 30800
|
||||
chat-api-code: 32065
|
||||
# case-knowledge-id: f062c9e4-c6ad-437b-b5ca-bbb9fed9b442
|
||||
# 20251117 张娟提供新版kId
|
||||
case-knowledge-id: 0a4d5d9e-0dae-456e-a342-3dfd2046b9e3
|
||||
caseDetailUrlBase: https://u.boe.com/pc/case/detail?id=
|
||||
file-upload-callback-url: https://u.boe.com/systemapi/xboe/m/boe/caseDocumentLog/uploadCallback
|
||||
use-white-list: true
|
||||
white-user-code-list:
|
||||
- "00004409"
|
||||
- "10361430"
|
||||
- "10867319"
|
||||
- "00004746"
|
||||
- "00004701"
|
||||
- "00004471"
|
||||
- "11311660"
|
||||
- "10157955"
|
||||
- "10726944"
|
||||
- "110408"
|
||||
- "10768019"
|
||||
- "137812"
|
||||
- "107863"
|
||||
- "10046607"
|
||||
- "110858"
|
||||
- "98000352"
|
||||
- "101215"
|
||||
- "00005011"
|
||||
- "10827857"
|
||||
- "11339772"
|
||||
- "pctest06"
|
||||
alert-email-recipients:
|
||||
- chengmeng@boe.com.cn
|
||||
- liyubing@boe.com.cn
|
||||
- lijian-hq@boe.com.cn
|
||||
ai-chat-root-path: /home/www/elearning/upload/ai/chat
|
||||
xxl:
|
||||
job:
|
||||
accessToken: 65ddc683-22f5-83b4-de3a-3c97a0a29af0
|
||||
|
||||
@@ -111,6 +111,41 @@ xboe:
|
||||
image:
|
||||
course:
|
||||
default: https://u-pre.boe.com/pc/images/bgimg/course.png
|
||||
case:
|
||||
ai:
|
||||
base-url: http://10.10.181.114:30003
|
||||
app-key: 6e9be45319184ac793aa127c362b0f0b
|
||||
secret-key: db4d24279e3d6dbf1524af42cd0bedd2
|
||||
ai-api-code: 30800
|
||||
chat-api-code: 32065
|
||||
case-knowledge-id: de2e006e-82fb-4ace-8813-f25c316be4ff
|
||||
caseDetailUrlBase: https://u-pre.boe.com/pc/case/detail?id=
|
||||
file-upload-callback-url: http://10.251.186.27:9090/xboe/m/boe/caseDocumentLog/uploadCallback
|
||||
use-white-list: true
|
||||
white-user-code-list:
|
||||
- "00004409"
|
||||
- "10361430"
|
||||
- "10867319"
|
||||
- "00004746"
|
||||
- "00004701"
|
||||
- "00004471"
|
||||
- "11311660"
|
||||
- "10157955"
|
||||
- "10726944"
|
||||
- "110408"
|
||||
- "10768019"
|
||||
- "137812"
|
||||
- "107863"
|
||||
- "10046607"
|
||||
- "110858"
|
||||
- "98000352"
|
||||
- "101215"
|
||||
- "00005011"
|
||||
- "10827857"
|
||||
- "11339772"
|
||||
alert-email-recipients:
|
||||
- chengmeng@boe.com.cn
|
||||
ai-chat-root-path: /home/www/elearning/upload/ai/chat
|
||||
jasypt:
|
||||
encryptor:
|
||||
algorithm: PBEWithMD5AndDES
|
||||
@@ -122,8 +157,8 @@ boe:
|
||||
ok:
|
||||
http:
|
||||
connect-timeout: 30
|
||||
read-timeout: 30
|
||||
write-timeout: 30
|
||||
read-timeout: 300
|
||||
write-timeout: 300
|
||||
max-idle-connections: 200
|
||||
keep-alive-duration: 300
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ spring:
|
||||
time-zone: GMT+8
|
||||
mvc:
|
||||
static-path-pattern: /cdn/**
|
||||
async:
|
||||
request-timeout: 600000
|
||||
jpa:
|
||||
database: MYSQL
|
||||
show-sql: false
|
||||
@@ -44,8 +46,8 @@ server:
|
||||
ok:
|
||||
http:
|
||||
connect-timeout: 30
|
||||
read-timeout: 30
|
||||
write-timeout: 30
|
||||
read-timeout: 300
|
||||
write-timeout: 300
|
||||
max-idle-connections: 200
|
||||
keep-alive-duration: 300
|
||||
boe:
|
||||
@@ -73,4 +75,5 @@ coursesuilt:
|
||||
updateOrSaveCourse: ${boe.domain}/manageApi/admin/teacherRecord/updateOrSaveCourse
|
||||
syncCourseStudent: ${boe.domain}/manageApi/admin/teacherRecord/syncCourseStudent
|
||||
syncOnLineScore: ${boe.domain}/manageApi/admin/teacherRecord/syncOnLineScore
|
||||
updateOnLineStatua: ${boe.domain}/manageApi/admin/teacherRecord/updateOnLineStatua
|
||||
updateOnLineStatua: ${boe.domain}/manageApi/admin/teacherRecord/updateOnLineStatua
|
||||
delOnLineById: ${boe.domain}/manageApi/admin/teacherRecord/delOnLineById
|
||||
@@ -31,11 +31,23 @@
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="caseAiChat"
|
||||
class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<encoder>
|
||||
<pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%n</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
<File>${log.path}/caseAiChat.log</File>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<FileNamePattern>${log.path}/caseAiChat.%d{yyyy-MM-dd}.log</FileNamePattern>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<!-- Log file error output -->
|
||||
<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${log.path}/error.log</file>
|
||||
<appender name="caseAiChat" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${log.path}/caseAiChat.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${log.path}/%d{yyyy-MM}/error.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
|
||||
<fileNamePattern>${log.path}/%d{yyyy-MM}/caseAiChat.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
|
||||
<maxFileSize>50MB</maxFileSize>
|
||||
<maxHistory>30</maxHistory>
|
||||
</rollingPolicy>
|
||||
@@ -53,4 +65,8 @@
|
||||
<!-- <appender-ref ref="console"/>-->
|
||||
<!-- <appender-ref ref="error"/> -->
|
||||
</root>
|
||||
|
||||
<logger name="caseAiChatLogger" additivity="false" level="INFO">
|
||||
<appender-ref ref="caseAiChat"/>
|
||||
</logger>
|
||||
</configuration>
|
||||
|
||||
@@ -47,10 +47,26 @@
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<appender name="caseAiChat"
|
||||
class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<encoder>
|
||||
<pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%n</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
<File>${log.path}/caseAiChat.log</File>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<FileNamePattern>${log.path}/caseAiChat.%d{yyyy-MM-dd}.log</FileNamePattern>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<!-- Level: FATAL 0 ERROR 3 WARN 4 INFO 6 DEBUG 7 -->
|
||||
<root level="INFO">
|
||||
<appender-ref ref="debug"/>
|
||||
<appender-ref ref="error"/>
|
||||
<appender-ref ref="console"/>
|
||||
</root>
|
||||
|
||||
<logger name="caseAiChatLogger" additivity="false" level="INFO">
|
||||
<appender-ref ref="caseAiChat"/>
|
||||
</logger>
|
||||
</configuration>
|
||||
|
||||
Reference in New Issue
Block a user