Compare commits

...

101 Commits

Author SHA1 Message Date
liu.zixi
770f467523 [DAT] 配合业务处理挡板 2025-10-31 10:37:28 +08:00
liu.zixi
70a537781c [DAT] 对话接口加新的apiCode 2025-10-31 10:37:27 +08:00
liu.zixi
918d444f36 [DAT] 数据挡板:业务处理失败 2025-10-31 10:37:25 +08:00
liu.zixi
ef28650966 [DAT] 数据挡板:更新时,删除成功新增失败 2025-10-31 10:37:24 +08:00
liu.zixi
8188810f5d [DAT] 重试时根据上一次执行步骤来决定 2025-10-31 10:37:23 +08:00
liu.zixi
ad981eb49d [DAT] 数据挡板:接口调用失败挡板去除 2025-10-31 10:37:21 +08:00
liu.zixi
dae2e29b93 [DAT] 数据挡板:更改时新增失败 2025-10-31 10:37:20 +08:00
liu.zixi
6a73dc60dd [DAT] 数据挡板:新增、删除、更改全挡 2025-10-31 10:37:19 +08:00
liu.zixi
66cbf57387 [DAT] from改为带@的全称 2025-10-31 10:37:18 +08:00
liu.zixi
fafb584213 [DAT] 告警邮件配置 2025-10-31 10:37:17 +08:00
liu.zixi
50cf9fa4fb [DAT] 增加白名单配置 2025-10-31 10:37:15 +08:00
liu.zixi
e4ada3e3c5 [DAT] email更换 2025-10-31 10:37:14 +08:00
liu.zixi
7eb98eece4 [DAT] 去挡板 2025-10-31 10:37:13 +08:00
liu.zixi
c103ea2605 [DAT] 接口失败时,业务状态设为null 2025-10-31 10:37:12 +08:00
liu.zixi
9616c819b3 [DAT] upload时应当为接口失败 2025-10-31 10:37:11 +08:00
liu.zixi
93d5b30489 [DAT] upload加挡板 2025-10-31 10:37:09 +08:00
liu.zixi
cd3bb38390 [DAT] 文档去重 2025-10-31 10:37:08 +08:00
liu.zixi
dab0efb010 [DAT] 显示摘要 2025-10-31 10:37:07 +08:00
liu.zixi
d7acd100b5 [DAT] 去挡板 2025-10-31 10:37:06 +08:00
liu.zixi
abb6cf5516 [DAT] 修复时间错误的问题;尝试修复发邮件 2025-10-31 10:37:04 +08:00
liu.zixi
4fab87998d [DAT] 接口调用失败的数据挡板2 2025-10-31 10:37:03 +08:00
liu.zixi
ceaeda8614 [DAT] 接口调用失败的数据挡板 2025-10-31 10:37:02 +08:00
liu.zixi
636d67165d [DAT] 发邮件增加日志打印 2025-10-31 10:37:01 +08:00
liu.zixi
253eb4ee2e [DAT] 放开重试挡板 2025-10-31 10:36:59 +08:00
liu.zixi
a811b675e7 [DAT] 打日志查看 2025-10-31 10:36:58 +08:00
liu.zixi
1f28daedc5 [DAT] 新增失败时发邮件 2025-10-31 10:36:57 +08:00
liu.zixi
147b74d99c [DAT] 批处理更改responseBody 2025-10-31 10:36:56 +08:00
liu.zixi
4b0a5a8761 [DAT] 去掉com.sun.mail依赖 2025-10-31 10:36:54 +08:00
liu.zixi
b90da03486 [DAT] 发送邮件实现方式再次修改 2025-10-31 10:36:53 +08:00
liu.zixi
4c8e228fa2 [DAT] 发送邮件实现方式修改 2025-10-31 10:36:51 +08:00
liu.zixi
a0a22ead1b [DAT] 调用时间查询逻辑修改 2025-10-31 10:36:50 +08:00
liu.zixi
8a03b3a983 [DAT] 修改update方法调试 2025-10-31 10:36:49 +08:00
liu.zixi
f864e8ba66 [DAT] 删除时修改数据查询条件 2025-10-31 10:36:48 +08:00
liu.zixi
5c4234a3b7 [DAT] 修改update方法只删除不上传的错误 2025-10-31 10:36:46 +08:00
liu.zixi
27c84faa48 [DAT] 照原型数据更新 2025-10-31 10:36:45 +08:00
liu.zixi
0304fc10f1 DAT测试配合 2025-10-31 10:36:44 +08:00
liu.zixi
a12c1f410b 案例专家:增加部分情况下的日志记录 2025-10-31 10:36:42 +08:00
liu.zixi
7b08d26da6 案例专家:修正调用逻辑 2025-10-31 10:36:41 +08:00
liu.zixi
d143ceeb4c 案例专家:新数据处理 2025-10-31 10:36:40 +08:00
liu.zixi
45192a3140 换日志级别,调试 2025-10-31 10:36:38 +08:00
liu.zixi
98f4356a49 延长 Spring Boot 异步请求超时 2025-10-31 10:36:37 +08:00
liu.zixi
8f0b579f6b okhttp的超时时长调到300秒 2025-10-31 10:36:36 +08:00
liu.zixi
6a8a9e5c87 整理es相关代码;增加手动调试用接口 2025-10-31 10:36:34 +08:00
liu.zixi
1898252fc1 案例专家:是否深度思考做成入参,先关闭思考 2025-10-31 10:36:33 +08:00
liu.zixi
cb448a09a3 案例专家:es修改索引格式、添加event-stream专属线程池 2025-10-31 10:36:32 +08:00
liu.zixi
c48c0a0f86 案例专家:yml中的用户列表加双引号 2025-10-31 10:36:31 +08:00
liu.zixi
cb103442e7 案例专家:修改白名单校验逻辑 2025-10-31 10:36:29 +08:00
liu.zixi
24bc40b6ec 案例专家:修改yml文件一个配置的写法 2025-10-31 10:36:28 +08:00
liu.zixi
d75dc2b7b5 案例专家:日志等级修改 2025-10-31 10:36:26 +08:00
liu.zixi
75478cbda7 案例专家:增加手动刷新索引功能 2025-10-31 10:36:25 +08:00
liu.zixi
bf555b1070 案例专家:userId更换成code 2025-10-31 10:36:24 +08:00
liu.zixi
8ae8a650fd 案例专家:userId更换成code 2025-10-31 10:36:23 +08:00
liu.zixi
f7f7a928b2 案例专家:打印入参,调试用 2025-10-31 10:36:22 +08:00
liu.zixi
f465c39b83 案例专家:修改log等级,观察联调 2025-10-31 10:36:20 +08:00
liu.zixi
a2f65a8a29 案例专家:修改批处理问题 2025-10-31 10:36:18 +08:00
liu.zixi
28c3812260 案例专家:邮件告警逻辑 2025-10-31 10:36:17 +08:00
liu.zixi
fa125b29cc 批处理:JobHandler开发 2025-10-31 10:36:15 +08:00
liu.zixi
f35ab10bd2 批处理:JobHandler开发 2025-10-31 10:36:14 +08:00
liu.zixi
d0af06b572 案例助手:代码整理和部分问题修复 2025-10-31 10:36:12 +08:00
liu.zixi
5610289893 案例助手:修复找不到旧会话的bug 2025-10-31 10:36:11 +08:00
liu.zixi
b4103bd4e5 案例助手:聊天接口兼容application/json 2025-10-31 10:36:10 +08:00
liu.zixi
72399eff18 案例助手:增加@Transactional注解 2025-10-31 10:36:08 +08:00
liu.zixi
952301b095 案例助手:增加字段,增加白名单机制等 2025-10-31 10:36:07 +08:00
liu.zixi
0eff0123ca 案例助手:聊天增加上传时间和企业信息 2025-10-31 10:36:05 +08:00
liu.zixi
4d3d4978aa 修复清空日志的bug 2025-10-31 10:36:03 +08:00
liu.zixi
abb036d769 三方接口异步处理 2025-10-31 10:36:02 +08:00
liu.zixi
fe2422574c 返回conversationId 2025-10-31 10:36:00 +08:00
liu.zixi
efe17f3b72 文件读取逻辑纠正 2025-10-31 10:35:58 +08:00
liu.zixi
1aa804118e 修正AI接口的数据入库逻辑 2025-10-31 10:35:56 +08:00
liu.zixi
bd2b372333 修改不同环境回调地址 2025-10-31 10:35:54 +08:00
liu.zixi
8ba8651988 修正编译错误 2025-10-31 10:35:53 +08:00
liu.zixi
ece950fddc 修正编译错误;
增加临时接口
2025-10-31 10:35:52 +08:00
liu.zixi
622c3bdd5b AI调用日志 重试功能补完 2025-10-31 10:35:50 +08:00
liu.zixi
278336c9f7 案例专家功能提交 2025-10-31 10:35:49 +08:00
670788339
264a581df8 Merge branch 'master-20251023-tag' into test1031
# Conflicts:
#	servers/boe-server-all/src/main/java/com/xboe/module/course/api/CourseManageApi.java
#	servers/boe-server-all/src/main/java/com/xboe/module/course/service/impl/CourseServiceImpl.java
2025-10-31 10:20:09 +08:00
Caojr
20e3b001d5 szx-1277 增加boe_course_teacher删除记录逻辑 2025-10-30 14:37:40 +08:00
Caojr
a37f90aeaa szx-1277 增加参数 2025-10-30 12:08:59 +08:00
Caojr
e767345c1e szx-1277 hrbp审核接口修改course服务调用接 2025-10-30 11:45:21 +08:00
Caojr
6fe6f7c6e5 临时注释多余的completeStatus接口调用 2025-10-10 10:15:11 +08:00
670788339
249a8d81a6 JsonFormat 2025-08-28 10:32:53 +08:00
670788339
7abb00772b 显示考试成绩 2025-08-26 14:39:37 +08:00
670788339
04e11f2e71 还原 2025-08-22 14:18:35 +08:00
670788339
2feb149e92 在线课程管理不显示考试成绩 2025-08-22 14:11:34 +08:00
670788339
16fa9cb028 在线课程管理不显示考试成绩 2025-08-22 10:36:14 +08:00
670788339
cac466ba73 修复无考试在线进度 2025-08-19 16:15:34 +08:00
670788339
30d2a0cde2 Merge branch 'master-0720-lyc' into release-20250328-master 2025-07-23 17:04:29 +08:00
670788339
541e542d9b 仅内网只可看 调整 2025-07-23 16:08:59 +08:00
670788339
aa04e16209 仅内网只可看 调整 2025-07-23 16:03:03 +08:00
670788339
57e22492e5 仅内网只可PC看 2025-07-23 15:42:47 +08:00
670788339
1917647a99 仅内网只可PC看 2025-07-21 17:43:18 +08:00
670788339
f5f7ab3bc5 字典调整 2025-07-21 13:27:35 +08:00
670788339
413a2ebc33 字典调整 2025-07-21 09:57:33 +08:00
670788339
22db916abf 仅内网可见-学员端 2025-07-21 09:37:25 +08:00
670788339
8ce284ea7e 仅内网可见-学员端 2025-07-21 09:27:12 +08:00
670788339
c485757061 仅内网可见-学员端 2025-07-21 09:21:58 +08:00
670788339
9a00b41cde 仅内网可见-学员端 2025-07-21 09:17:13 +08:00
670788339
59beaa5b74 仅内网可见-学员端 2025-07-21 09:07:58 +08:00
670788339
9b9e97a8d4 仅内网可见-学员端 2025-07-21 08:44:16 +08:00
670788339
200ec38038 仅内网可见 2025-07-20 17:13:29 +08:00
670788339
7613f30ca7 仅内网可见 2025-07-20 15:22:36 +08:00
670788339
248e0799bd 仅内网可见 2025-07-20 13:48:21 +08:00
58 changed files with 5063 additions and 44 deletions

View File

@@ -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>

View File

@@ -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;
@@ -407,4 +404,20 @@ public class ThirdApi {
.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;
}
}

View File

@@ -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();
}
}
}

View File

@@ -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());
}
}

View File

@@ -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 = "文档删除";
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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 "";
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}

View File

@@ -0,0 +1,98 @@
package com.xboe.module.assistance.service.impl;
import java.util.Date;
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 {
// 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 = "boeLms20250814Syse";
private static final String SMTP_PORT = "465";
private static final String SMTP_ENCRYPTION = "ssl";
@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);
}
}
}

View File

@@ -0,0 +1,126 @@
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.util.List;
/**
* AI对话管理API
*/
@Slf4j
@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());
}
/**
* 根据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());
}
}
/**
* 判断当前登录用户是否显示"案例专家"功能入口
* @return 是否显示功能入口
*/
@GetMapping("/show-entrance")
public JsonResponse<Boolean> showCaseAiEntrance() {
try {
String currentUserCode = getCurrent().getCode();
boolean shouldShow = caseAiPermissionService.shouldShowCaseAiEntrance(currentUserCode);
return success(shouldShow);
} 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("创建失败");
}
}

View File

@@ -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;
}
}
}

View File

@@ -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("已清除上次处理位置标记");
}
}

View File

@@ -0,0 +1,67 @@
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);
@Autowired
@Qualifier("aiDocExecutor")
private ThreadPoolTaskExecutor aiDocExecutor;
@Autowired
private ICaseKnowledgeService caseKnowledgeService;
public void process(CaseDocumentLogOptTypeEnum optTypeEnum, Cases... caseList) {
for (Cases cases : caseList) {
// 控制并发数量
while (currentTaskCount.get() >= 15) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
currentTaskCount.incrementAndGet();
aiDocExecutor.submit(() -> {
processCases(cases, optTypeEnum);
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);
}
}
}

View File

@@ -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;
}
}

View File

@@ -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));
}
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -0,0 +1,116 @@
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 timestamp;
// ================== 构造函数 ==================
public AiChatConversationData() {
this.timestamp = LocalDateTime.now();
}
public AiChatConversationData(String conversationId, String query, String answer,
List<CaseReferVo> caseRefers, List<String> suggestions,
String userId) {
this.conversationId = conversationId;
this.query = query;
this.answer = new StringBuilder(answer != null ? answer : "");
this.caseRefers = caseRefers != null ? caseRefers : new ArrayList<>();
this.suggestions = suggestions != null ? suggestions : new ArrayList<>();
this.userId = userId;
this.timestamp = 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);
}
}
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -0,0 +1,75 @@
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 boolean fileUploadUseCallback;
/**
* 文档上传回调接口地址
*/
private String fileUploadCallbackUrl;
/**
* 是否启用白名单
*/
private boolean useWhiteList;
/**
* 白名单用户列表
*/
private List<String> whiteUserCodeList;
/**
* AI处理失败告警邮件收件人列表
*/
private List<String> alertEmailRecipients;
}

View File

@@ -0,0 +1,13 @@
package com.xboe.module.boecase.service;
/**
* 获取accesstoken
*/
public interface IAiAccessTokenService {
/**
* 获取accesstoken
* @return
*/
String getAccessToken();
}

View File

@@ -0,0 +1,38 @@
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 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);
}

View File

@@ -0,0 +1,14 @@
package com.xboe.module.boecase.service;
/**
* 案例AI权限服务接口
*/
public interface ICaseAiPermissionService {
/**
* 判断指定用户是否显示"案例专家"功能入口
* @param userCode 用户编码
* @return 是否显示功能入口
*/
boolean shouldShowCaseAiEntrance(String userCode);
}

View File

@@ -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);
}

View File

@@ -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();
}

View File

@@ -0,0 +1,46 @@
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 {
/**
* 查看索引是否存在
* @param indexName
* @return
*/
boolean checkIndexExists();
/**
* 创建索引
* @param indexName
*/
boolean createIndex();
/**
* 删除索引
* @param indexName
* @return
*/
boolean deleteIndex();
/**
* 新增数据
* @param data
* @return
*/
boolean createData(AiChatConversationData data);
/**
* 查询数据
* @param conversationId
* @return
*/
List<CaseAiMessageVo> queryData(String conversationId);
}

View File

@@ -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
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;
}
}
}

View File

@@ -0,0 +1,562 @@
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.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.system.organization.vo.OrgSimpleVo;
import com.xboe.system.user.service.IUserService;
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.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 java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
@EnableConfigurationProperties({CaseAiProperties.class})
@Service
@Slf4j
public class CaseAiChatServiceImpl implements ICaseAiChatService {
@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;
@Override
@Transactional
public SseEmitter chat(CaseAiChatDto caseAiChatDto, CurrentUser currentUser) {
// 1. 获取conversationId
String conversationId = getOrCreateConversationId(caseAiChatDto, currentUser);
// 3. 构建请求参数
String userId = currentUser.getCode();
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));
String chatParamStr = chatParam.toJSONString();
log.info("案例问答接口请求参数: [{}]", chatParamStr);
// 4. 设置请求头
String accessToken = aiAccessTokenService.getAccessToken();
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();
// 5. 创建SSE响应器
SseEmitter sseEmitter = new SseEmitter();
// 6. 用于收集对话数据的容器
AiChatConversationData conversationData = new AiChatConversationData();
conversationData.setQuery(caseAiChatDto.getQuery());
conversationData.setConversationId(conversationId);
conversationData.setUserId(userId);
// 7. 创建事件监听器
EventSourceListener listener = new EventSourceListener() {
@Override
public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
log.info("调用接口 [{}] 接口开始监听", request.url());
}
@Override
public void onClosed(@NotNull EventSource eventSource) {
log.info("调用接口 [{}] 接口关闭", request.url());
// 对话完成保存到ES
elasticSearchIndexService.createData(conversationData);
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);
switch (statusEnum) {
case REFERS: // 返回引用文件
// 处理文件引用并构建返给前端的数据
JSONObject modifiedData = handleFileReferAndBuildResponse(responseData, conversationData);
if (modifiedData != null) {
// 发送修改后的数据给前端
sseEmitter.send(modifiedData.toJSONString());
return; // 早期返回,不发送原始数据
}
break;
case CHAT: // 流式对话中
String content = responseData.getString("content");
if (content != null) {
conversationData.appendAnswer(content);
}
break;
case SUGGESTIONS: // 返回建议
handleSuggestions(responseData, conversationData);
break;
case CHAT_COMPLETED:
case API_COMPLETED: // 接口交互完成
default:
// 不做特殊处理
break;
}
}
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) {
log.error("调用接口 [{}] 接口异常", request.url(), e);
// 如果是 content-type 错误,尝试作为普通 HTTP 请求处理
if (e instanceof IllegalStateException && e.getMessage() != null && e.getMessage().contains("Invalid content-type")) {
log.warn("服务器返回的 Content-Type 不是 text/event-stream尝试作为普通 HTTP 请求处理");
CaseAiChatServiceImpl.this.handleAsRegularHttpRequest(request, sseEmitter, conversationData);
return;
}
if (e != null) {
sseEmitter.completeWithError(e);
} else {
sseEmitter.completeWithError(new RuntimeException("调用接口异常, 异常未捕获"));
}
}
};
// 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);
}
/**
* 从 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
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);
}
}
/**
* 对话数据容器
*/
// ConversationData 已移动到独立的Entity类AiChatConversationData
}

View File

@@ -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;
}
}

View File

@@ -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 "";
}
}
}

View File

@@ -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

View File

@@ -0,0 +1,320 @@
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.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());
esData.put("timestamp", LocalDateTime.now().toString());
// 构建 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"));
// 解析 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;
}
}
/**
* 获取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" +
"}";
}
}

View File

@@ -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("结束批量查询文件状态");
}
}

View File

@@ -0,0 +1,130 @@
package com.xboe.module.boecase.task;
import com.xboe.enums.CaseDocumentLogOptTypeEnum;
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.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;
/**
* 旧案例上传
*/
@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() {
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;
}
// 批量检查这些案例是否已在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())) {
exists = true;
break;
}
}
if (!exists) {
casesList.add(cases);
}
}
log.info("过滤后需要处理的案例数量: {}", casesList.size());
if (!casesList.isEmpty()) {
// 调用异步处理方法
caseAiDocumentAsyncHandler.process(CaseDocumentLogOptTypeEnum.CREATE, casesList.toArray(new Cases[0]));
// 将当前处理的最后一条数据ID存入Redis
String currentLastId = casesList.get(casesList.size() - 1).getId();
stringRedisTemplate.opsForValue().set(CASE_UPLOAD_LAST_ID_KEY, currentLastId);
log.info("已处理案例最后一条记录ID已更新为: {}", currentLastId);
} else {
log.info("没有新的案例需要处理");
}
log.info("旧案例上传任务执行完成");
} catch (Exception e) {
log.error("执行旧案例上传任务时发生异常", e);
}
}
/**
* 查询需要处理的案例数据
*
* @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());
}
}

View File

@@ -0,0 +1,10 @@
package com.xboe.module.boecase.vo;
import lombok.Data;
/**
* AI会话记录
*/
@Data
public class CaseAiConversationVo {
}

View File

@@ -0,0 +1,32 @@
package com.xboe.module.boecase.vo;
import lombok.Data;
import java.util.List;
/**
* AI会话消息记录VO
*/
@Data
public class CaseAiMessageVo {
/**
* 用户提问内容
*/
private String query;
/**
* AI回答内容
*/
private String answer;
/**
* 案例引用列表
*/
private List<CaseReferVo> caseRefer;
/**
* 建议列表
*/
private List<String> suggestions;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -356,8 +356,10 @@ public class CourseAuditApi extends ApiBaseController{
//修改在线课开课状态=已开课
String token = request.getHeader("Xboe-Access-Token");
CourseParam param = new CourseParam();
param.setId(courseId);
thirdApi.updateOnLineStatua(param,token);
param.setId(c.getId());
param.setOrgId(c.getOrgId());
param.setOrgName(c.getOrgName());
thirdApi.updateOrSaveCourse(param,token);
}
return success(true);
} catch (Exception e) {

View File

@@ -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 com.xboe.module.course.entity.*;
@@ -30,6 +33,19 @@ import com.xboe.data.dto.UserOrgIds;
import com.xboe.data.outside.IOutSideDataService;
import com.xboe.data.service.IDataUserSyncService;
import com.xboe.module.assistance.service.IEmailService;
import com.xboe.module.course.entity.Course;
import com.xboe.module.course.entity.CourseContent;
import com.xboe.module.course.entity.CourseCrowd;
import com.xboe.module.course.entity.CourseHRBPAudit;
import com.xboe.module.course.entity.CourseSection;
import com.xboe.module.course.entity.CourseTeacher;
import com.xboe.module.course.entity.CourseUpdateLog;
import com.xboe.module.course.service.ICourseContentService;
import com.xboe.module.course.service.ICourseCrowdService;
import com.xboe.module.course.service.ICourseHRBPAuditService;
import com.xboe.module.course.service.ICourseSectionService;
import com.xboe.module.course.service.ICourseService;
import com.xboe.module.course.service.ICourseTeacherService;
import com.xboe.module.excel.ExportsExcelSenderUtil;
import com.xboe.standard.enums.BoedxContentType;
import com.xboe.standard.enums.BoedxCourseType;
@@ -84,6 +100,7 @@ public class CourseManageApi extends ApiBaseController{
private ICourseTagService tagService;
@Resource
IOutSideDataService outSideDataService;
@Autowired
IDataUserSyncService userSyncService;
@Resource
@@ -158,6 +175,18 @@ 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);
if (StringUtils.isNotBlank(course.getTags())){
List<CourseTag> tagList = tagService.getTagsByIds(course.getTags());
rs.put("tagList", tagList);
@@ -169,11 +198,30 @@ public class CourseManageApi extends ApiBaseController{
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中去
@@ -283,11 +331,11 @@ public class CourseManageApi extends ApiBaseController{
//填充必要的信息
try {
log.info("-------- 标签相关开始 ------- 课程ID = {} " , dto.getCourse().getId());
CurrentUser userInfo = getCurrent();
Course oldCourse = StringUtils.isBlank(dto.getCourse().getId()) ? null : courseService.get(dto.getCourse().getId());
tagService.updateTags(oldCourse,dto.getCourse(),userInfo);
log.info("-------- 标签相关结束 -------");
// log.info("-------- 标签相关开始 ------- 课程ID = {} " , dto.getCourse().getId());
// CurrentUser userInfo = getCurrent();
// Course oldCourse = StringUtils.isBlank(dto.getCourse().getId()) ? null : courseService.get(dto.getCourse().getId());
// tagService.updateTags(oldCourse,dto.getCourse(),userInfo);
// log.info("-------- 标签相关结束 -------");
if(StringUtils.isBlank(dto.getCourse().getId())) {
//只有在第一次添加保存时才会这样

View File

@@ -0,0 +1,9 @@
package com.xboe.module.course.dao;
import com.xboe.core.orm.BaseDao;
import com.xboe.module.course.entity.CourseTeacherDeletedRecord;
import org.springframework.stereotype.Repository;
@Repository
public class CourseTeacherDeletedRecordDao extends BaseDao<CourseTeacherDeletedRecord> {
}

View File

@@ -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;

View File

@@ -0,0 +1,43 @@
package com.xboe.module.course.entity;
import com.xboe.core.SysConstant;
import com.xboe.core.orm.IdBaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 课程任课教师删除记录
*/
@Data
@Entity
@EqualsAndHashCode(callSuper = false)
@Table(name = SysConstant.TABLE_PRE + "course_teacher_deleted_record")
public class CourseTeacherDeletedRecord extends IdBaseEntity {
private static final long serialVersionUID = 1L;
/**
* 课程id
*/
@Column(name = "course_id", nullable = false, length = 20)
private String courseId;
/**
* 教师id实际上就是aid
*
*/
@Column(name = "teacher_id", nullable = false, length = 20)
private String teacherId;
/**
* 教师姓名
*
*/
@Column(name = "teacher_name", length = 30)
private String teacherName;
}

View File

@@ -15,6 +15,7 @@ import java.util.stream.Stream;
import javax.annotation.Resource;
import javax.management.Query;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
@@ -24,6 +25,8 @@ import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.xboe.api.ThirdApi;
import com.xboe.core.orm.*;
import com.xboe.module.course.dao.*;
import com.xboe.module.course.entity.*;
import com.xboe.module.course.dto.CourseTagRelationDto;
import com.xboe.module.course.entity.*;
import com.xboe.module.course.service.ICourseTagService;
@@ -51,15 +54,6 @@ import com.xboe.common.beans.KeyValue;
import com.xboe.common.utils.IDGenerator;
import com.xboe.common.utils.StringUtil;
import com.xboe.core.event.IEventDataSender;
import com.xboe.module.course.dao.CourseContentDao;
import com.xboe.module.course.dao.CourseCrowdDao;
import com.xboe.module.course.dao.CourseDao;
import com.xboe.module.course.dao.CourseExamDao;
import com.xboe.module.course.dao.CourseHRBPAuditDao;
import com.xboe.module.course.dao.CourseHomeWorkDao;
import com.xboe.module.course.dao.CourseSectionDao;
import com.xboe.module.course.dao.CourseTeacherDao;
import com.xboe.module.course.dao.CourseUpdateLogDao;
import com.xboe.module.course.dto.CourseFullDto;
import com.xboe.module.course.dto.CourseQueryDto;
import com.xboe.module.course.dto.RankingDto;
@@ -129,7 +123,10 @@ public class CourseServiceImpl implements ICourseService {
@Resource
RestHighLevelClient restHighLevelClient;
@Resource
private CourseTeacherDeletedRecordDao courseTeacherDeletedRecordDao;
/**
* 生成过滤条件
*
@@ -186,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));
}
}
@@ -426,15 +425,15 @@ public class CourseServiceImpl implements ICourseService {
if (TempFilterConfig.Manager_CourseFile_ByOrgIds) {
if (dto.getIsSystemAdmin() == null || !dto.getIsSystemAdmin()) {
List<String> finalStrings = strings;
log.info("dto为"+dto);
if(dto.getIsCreateCourse()!=null&&dto.getIsCreateCourse()){
log.info("dto为" + dto);
if (dto.getIsCreateCourse() != null && dto.getIsCreateCourse()) {
listByFilters2.removeIf(e -> {
//去掉未发布的课程
if (!e.getPublished() && seache.contains(e.getId()) && !finalStrings.contains(e.getOrgId()) && !dto.getOrgAid().equals(e.getSysCreateAid())) {
return true;
}
//去掉所有条件都不符合的课程
if(!seache.contains(e.getId())&&!dto.getReadIds().contains(e.getId())&& !finalStrings.contains(e.getOrgId()) && !dto.getOrgAid().equals(e.getSysCreateAid())){
if (!seache.contains(e.getId()) && !dto.getReadIds().contains(e.getId()) && !finalStrings.contains(e.getOrgId()) && !dto.getOrgAid().equals(e.getSysCreateAid())) {
return true;
}
return false;
@@ -869,7 +868,7 @@ public class CourseServiceImpl implements ICourseService {
}
// 删除ES数据
deletedStudyResourceBatchByCourseIdAndType(id,c.getType());
deletedStudyResourceBatchByCourseIdAndType(id, c.getType());
} else {
//彻底删除,课件设置为无课程状态
courseDao.setDeleted(id);
@@ -981,6 +980,7 @@ public class CourseServiceImpl implements ICourseService {
Course c = full.getCourse();//当前的课程信息
Course nowCourse = courseDao.get(c.getId());//修改之前的课程信息
StringBuffer stringBuffer = new StringBuffer("[");
//追加日志内容
appendUpdateLog(stringBuffer, nowCourse, c);
@@ -1017,6 +1017,8 @@ public class CourseServiceImpl implements ICourseService {
c.setSysVersion(courseDao.getVersion(c.getId()));
full.getCourse().setSysVersion(c.getSysVersion());
// 兼容处理,记录下删除的关联数据
createCourseTeacherDeletedRecord(c.getId());
//先清空教师信息, 教师信息如果不一样了,也要加入到日志中
courseTeacherDao.deleteByField("courseId", c.getId());
if (full.getTeachers() != null && !full.getTeachers().isEmpty()) {
@@ -1071,6 +1073,8 @@ public class CourseServiceImpl implements ICourseService {
c.setSysVersion(courseDao.getVersion(c.getId()));
full.getCourse().setSysVersion(c.getSysVersion());
// 兼容处理,记录下删除的关联数据
createCourseTeacherDeletedRecord(c.getId());
//先清空教师信息, 教师信息如果不一样了,也要加入到日志中
courseTeacherDao.deleteByField("courseId", c.getId());
if (full.getTeachers() != null && !full.getTeachers().isEmpty()) {
@@ -1100,6 +1104,7 @@ public class CourseServiceImpl implements ICourseService {
@Override
public void submitAndPublish(CourseFullDto full, String aid, String aname) throws Exception {
Course c = full.getCourse();//当前的课程信息
log.info(" 课程 c = " + c.getId());
log.info(" 课程 c = " + c);
@@ -1107,6 +1112,9 @@ public class CourseServiceImpl implements ICourseService {
c.setPublishTime(LocalDateTime.now());
courseDao.update(c);
log.info(" 课程 c = " + c.getId());
// 兼容处理,记录下删除的关联数据
createCourseTeacherDeletedRecord(c.getId());
//先清空教师信息, 教师信息如果不一样了,也要加入到日志中
courseTeacherDao.deleteByField("courseId", c.getId());
if (full.getTeachers() != null && !full.getTeachers().isEmpty()) {
@@ -1172,7 +1180,7 @@ public class CourseServiceImpl implements ICourseService {
/***
* 发布全文索引
* @param
* @param c
*/
// private void fullTextPublish(Course c) {
// if(fullTextSearch==null) {
@@ -2130,4 +2138,25 @@ public class CourseServiceImpl implements ICourseService {
e.printStackTrace();
}
}
/**
* 删除boe_course_teacher数据时把删除的数据储存到boe_course_teacher_deleted_record表
* boe_course_teacher表没有deleted字段兼容处理
*
* @param courseId 课程ID
*/
private void createCourseTeacherDeletedRecord(String courseId) {
List<CourseTeacherDeletedRecord> courseTeacherList = courseTeacherDao.findList(FieldFilters.eq("courseId", courseId)).stream().map(ct -> {
CourseTeacherDeletedRecord courseTeacherDeletedRecord = new CourseTeacherDeletedRecord();
courseTeacherDeletedRecord.setCourseId(ct.getCourseId());
courseTeacherDeletedRecord.setTeacherId(ct.getTeacherId());
courseTeacherDeletedRecord.setTeacherName(ct.getTeacherName());
return courseTeacherDeletedRecord;
}).collect(Collectors.toList());
if (CollUtil.isNotEmpty(courseTeacherList)) {
courseTeacherDeletedRecordDao.saveList(courseTeacherList);
}
}
}

View File

@@ -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;

View File

@@ -10,6 +10,8 @@ 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;
@@ -233,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) {
@@ -567,8 +592,8 @@ public class StudyCourseApi extends ApiBaseController{
}
try {
studyService.finishVideoStudyItem(itemId, studyId,courseId,cnum,token);
List<StudyCourse> allUserList = thirdApi.getStudyCourseList(studyId ,courseId, token);
log.info("在线课学习记录"+allUserList);
// List<StudyCourse> allUserList = thirdApi.getStudyCourseList(studyId ,courseId, token);
// log.info("在线课学习记录"+allUserList);
return success(true);
}catch(Exception e) {
log.error("记录内容学习完成错误",e);

View File

@@ -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());

View File

@@ -282,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 " +
@@ -315,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);

View File

@@ -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

View File

@@ -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

View File

@@ -77,6 +77,41 @@ xboe:
image:
course:
default: https://u.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
file-upload-callback-url: http://10.251.113.95: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
- liyubing@boe.com.cn
- lijian-hq@boe.com.cn
xxl:
job:
accessToken: 65ddc683-22f5-83b4-de3a-3c97a0a29af0

View File

@@ -111,6 +111,39 @@ 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
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
jasypt:
encryptor:
algorithm: PBEWithMD5AndDES
@@ -122,8 +155,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

View File

@@ -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: