mirror of
https://codeup.aliyun.com/67762337eccfc218f6110e0e/per-boe/java-servers.git
synced 2025-12-06 17:36:47 +08:00
Compare commits
104 Commits
SZX-1293-z
...
test1031
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
37d444800a | ||
|
|
8ff8703576 | ||
|
|
d5b774a9ad | ||
|
|
770f467523 | ||
|
|
70a537781c | ||
|
|
918d444f36 | ||
|
|
ef28650966 | ||
|
|
8188810f5d | ||
|
|
ad981eb49d | ||
|
|
dae2e29b93 | ||
|
|
6a73dc60dd | ||
|
|
66cbf57387 | ||
|
|
fafb584213 | ||
|
|
50cf9fa4fb | ||
|
|
e4ada3e3c5 | ||
|
|
7eb98eece4 | ||
|
|
c103ea2605 | ||
|
|
9616c819b3 | ||
|
|
93d5b30489 | ||
|
|
cd3bb38390 | ||
|
|
dab0efb010 | ||
|
|
d7acd100b5 | ||
|
|
abb6cf5516 | ||
|
|
4fab87998d | ||
|
|
ceaeda8614 | ||
|
|
636d67165d | ||
|
|
253eb4ee2e | ||
|
|
a811b675e7 | ||
|
|
1f28daedc5 | ||
|
|
147b74d99c | ||
|
|
4b0a5a8761 | ||
|
|
b90da03486 | ||
|
|
4c8e228fa2 | ||
|
|
a0a22ead1b | ||
|
|
8a03b3a983 | ||
|
|
f864e8ba66 | ||
|
|
5c4234a3b7 | ||
|
|
27c84faa48 | ||
|
|
0304fc10f1 | ||
|
|
a12c1f410b | ||
|
|
7b08d26da6 | ||
|
|
d143ceeb4c | ||
|
|
45192a3140 | ||
|
|
98f4356a49 | ||
|
|
8f0b579f6b | ||
|
|
6a8a9e5c87 | ||
|
|
1898252fc1 | ||
|
|
cb448a09a3 | ||
|
|
c48c0a0f86 | ||
|
|
cb103442e7 | ||
|
|
24bc40b6ec | ||
|
|
d75dc2b7b5 | ||
|
|
75478cbda7 | ||
|
|
bf555b1070 | ||
|
|
8ae8a650fd | ||
|
|
f7f7a928b2 | ||
|
|
f465c39b83 | ||
|
|
a2f65a8a29 | ||
|
|
28c3812260 | ||
|
|
fa125b29cc | ||
|
|
f35ab10bd2 | ||
|
|
d0af06b572 | ||
|
|
5610289893 | ||
|
|
b4103bd4e5 | ||
|
|
72399eff18 | ||
|
|
952301b095 | ||
|
|
0eff0123ca | ||
|
|
4d3d4978aa | ||
|
|
abb036d769 | ||
|
|
fe2422574c | ||
|
|
efe17f3b72 | ||
|
|
1aa804118e | ||
|
|
bd2b372333 | ||
|
|
8ba8651988 | ||
|
|
ece950fddc | ||
|
|
622c3bdd5b | ||
|
|
278336c9f7 | ||
|
|
264a581df8 | ||
|
|
20e3b001d5 | ||
|
|
a37f90aeaa | ||
|
|
e767345c1e | ||
|
|
6fe6f7c6e5 | ||
|
|
249a8d81a6 | ||
|
|
7abb00772b | ||
|
|
04e11f2e71 | ||
|
|
2feb149e92 | ||
|
|
16fa9cb028 | ||
|
|
cac466ba73 | ||
|
|
30d2a0cde2 | ||
|
|
541e542d9b | ||
|
|
aa04e16209 | ||
|
|
57e22492e5 | ||
|
|
1917647a99 | ||
|
|
f5f7ab3bc5 | ||
|
|
413a2ebc33 | ||
|
|
22db916abf | ||
|
|
8ce284ea7e | ||
|
|
c485757061 | ||
|
|
9a00b41cde | ||
|
|
59beaa5b74 | ||
|
|
9b9e97a8d4 | ||
|
|
200ec38038 | ||
|
|
7613f30ca7 | ||
|
|
248e0799bd |
@@ -161,11 +161,21 @@
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpmime</artifactId>
|
||||
<version>4.5.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.mail</groupId>
|
||||
<artifactId>javax.mail-api</artifactId>
|
||||
<version>1.5.6</version>
|
||||
</dependency>
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>com.sun.mail</groupId>-->
|
||||
<!-- <artifactId>javax.mail</artifactId>-->
|
||||
<!-- <version>1.5.6</version>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
@@ -227,6 +237,23 @@
|
||||
<artifactId>elasticsearch-rest-high-level-client</artifactId>
|
||||
<version>7.9.0</version> <!-- 请根据实际需求选择合适的版本 -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>4.2.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp-sse</artifactId>
|
||||
<version>4.2.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>2.0.31</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.xboe</groupId>
|
||||
|
||||
@@ -45,10 +45,7 @@ import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.xboe.config;
|
||||
|
||||
import com.xboe.module.boecase.service.IElasticSearchIndexService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* ElasticSearch索引初始化器
|
||||
* 在Spring Boot启动完成并监听到配置文件加载完毕后,检查并创建所需的ES索引
|
||||
*
|
||||
* @author AI Assistant
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class ElasticSearchIndexInitializer {
|
||||
|
||||
@Autowired
|
||||
private IElasticSearchIndexService elasticSearchIndexService;
|
||||
|
||||
/**
|
||||
* 监听Spring Boot应用启动完成事件
|
||||
* ApplicationReadyEvent在应用启动完成、所有配置加载完毕后触发
|
||||
*/
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void initializeElasticSearchIndices() {
|
||||
if (elasticSearchIndexService.checkIndexExists()) {
|
||||
log.info("ElasticSearch索引 ai_chat_messages 已存在");
|
||||
} else {
|
||||
log.info("ElasticSearch索引 ai_chat_messages 不存在,开始创建...");
|
||||
elasticSearchIndexService.createIndex();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.xboe.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import okhttp3.Dispatcher;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
/**
|
||||
* 线程池配置类
|
||||
*/
|
||||
@Configuration
|
||||
@Slf4j
|
||||
public class ThreadPoolConfig {
|
||||
|
||||
/**
|
||||
* 执行AI文档接口的的线程池
|
||||
* 策略:单线程等待队列
|
||||
*/
|
||||
@Bean(name = "aiDocExecutor")
|
||||
public ThreadPoolTaskExecutor aiDocExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
// 设置核心线程数
|
||||
int corePoolSize = Runtime.getRuntime().availableProcessors();
|
||||
executor.setCorePoolSize(Math.max(4, corePoolSize));
|
||||
// 设置最大线程数
|
||||
executor.setMaxPoolSize(Math.max(16, corePoolSize * 2));
|
||||
// 设置队列容量(确保任务排队)
|
||||
executor.setQueueCapacity(100);
|
||||
// keepalive
|
||||
executor.setKeepAliveSeconds(30);
|
||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||
executor.setAwaitTerminationSeconds(30);
|
||||
// 设置线程名称前缀
|
||||
executor.setThreadNamePrefix("ai_doc_task-");
|
||||
// 设置拒绝策略(当队列满时,由调用线程处理该任务)
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
// 初始化线程池
|
||||
executor.initialize();
|
||||
log.info("AI文档线程池初始化完成 - 核心线程: {}, 最大线程: {}, 队列容量: {}",
|
||||
executor.getCorePoolSize(),
|
||||
executor.getMaxPoolSize(),
|
||||
executor.getQueueCapacity());
|
||||
return executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* event-stream线程池
|
||||
* @return
|
||||
*/
|
||||
@Bean(name = "eventStreamExecutor")
|
||||
public ThreadPoolTaskExecutor eventStreamExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(10);
|
||||
executor.setMaxPoolSize(500);
|
||||
executor.setQueueCapacity(10);
|
||||
executor.setThreadNamePrefix("event-stream-");
|
||||
executor.setKeepAliveSeconds(300);
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
@Bean(name = "customDispatcher")
|
||||
public Dispatcher customDispatcher(@Qualifier("eventStreamExecutor") ThreadPoolTaskExecutor eventStreamExecutor) {
|
||||
return new Dispatcher(eventStreamExecutor.getThreadPoolExecutor());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.xboe.constants;
|
||||
|
||||
public class CaseAiConstants {
|
||||
|
||||
public static final String CASE_AI_INDEX_NAME = "ai_chat_messages";
|
||||
|
||||
public static final String CASE_DOC_UPLOAD_INTERFACE_NAME = "文档上传";
|
||||
|
||||
public static final String CASE_DOC_DELETE_INTERFACE_NAME = "文档删除";
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
public enum CaseAiChatStatusEnum {
|
||||
|
||||
REFERS(0, "引用文档"),
|
||||
|
||||
CHAT(1, "聊天中"),
|
||||
|
||||
CHAT_COMPLETED(2, "聊天完成"),
|
||||
|
||||
SUGGESTIONS(3, "建议"),
|
||||
|
||||
API_COMPLETED(4, "接口完成"),
|
||||
;
|
||||
|
||||
private final int code;
|
||||
|
||||
private final String label;
|
||||
|
||||
CaseAiChatStatusEnum(int code, String label) {
|
||||
this.code = code;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public static CaseAiChatStatusEnum getByCode(int code) {
|
||||
for (CaseAiChatStatusEnum value : values()) {
|
||||
if (value.code == code) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return API_COMPLETED;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
/**
|
||||
* AI调用日志业务处理状态枚举
|
||||
*/
|
||||
public enum CaseDocumentLogCaseStatusEnum {
|
||||
|
||||
SUCCESS(1, "处理成功"),
|
||||
FAILED(2, "处理失败");
|
||||
|
||||
private final Integer code;
|
||||
private final String desc;
|
||||
|
||||
CaseDocumentLogCaseStatusEnum(Integer code, String desc) {
|
||||
this.code = code;
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取描述
|
||||
*/
|
||||
public static String getDescByCode(Integer code) {
|
||||
for (CaseDocumentLogCaseStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum.getDesc();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取枚举
|
||||
*/
|
||||
public static CaseDocumentLogCaseStatusEnum getByCode(Integer code) {
|
||||
for (CaseDocumentLogCaseStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
/**
|
||||
* AI调用日志接口调用状态枚举
|
||||
*/
|
||||
public enum CaseDocumentLogOptStatusEnum {
|
||||
|
||||
CALLING(0, "调用中"),
|
||||
SUCCESS(1, "调用成功"),
|
||||
FAILED(2, "调用失败");
|
||||
|
||||
private final Integer code;
|
||||
private final String desc;
|
||||
|
||||
CaseDocumentLogOptStatusEnum(Integer code, String desc) {
|
||||
this.code = code;
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取描述
|
||||
*/
|
||||
public static String getDescByCode(Integer code) {
|
||||
for (CaseDocumentLogOptStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum.getDesc();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取枚举
|
||||
*/
|
||||
public static CaseDocumentLogOptStatusEnum getByCode(Integer code) {
|
||||
for (CaseDocumentLogOptStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
/**
|
||||
* AI调用日志操作类型枚举
|
||||
*/
|
||||
public enum CaseDocumentLogOptTypeEnum {
|
||||
|
||||
CREATE("create", "新增"),
|
||||
DELETE("delete", "删除"),
|
||||
UPDATE("update", "更改");
|
||||
|
||||
private final String code;
|
||||
private final String desc;
|
||||
|
||||
CaseDocumentLogOptTypeEnum(String code, String desc) {
|
||||
this.code = code;
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取描述
|
||||
*/
|
||||
public static String getDescByCode(String code) {
|
||||
for (CaseDocumentLogOptTypeEnum typeEnum : values()) {
|
||||
if (typeEnum.getCode().equals(code)) {
|
||||
return typeEnum.getDesc();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.xboe.enums;
|
||||
|
||||
/**
|
||||
* AI调用日志接口运行状态枚举
|
||||
*/
|
||||
public enum CaseDocumentLogRunStatusEnum {
|
||||
|
||||
RUNNING(0, "运行中"),
|
||||
COMPLETED(1, "运行完成");
|
||||
|
||||
private final Integer code;
|
||||
private final String desc;
|
||||
|
||||
CaseDocumentLogRunStatusEnum(Integer code, String desc) {
|
||||
this.code = code;
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取描述
|
||||
*/
|
||||
public static String getDescByCode(Integer code) {
|
||||
for (CaseDocumentLogRunStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum.getDesc();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据code获取枚举
|
||||
*/
|
||||
public static CaseDocumentLogRunStatusEnum getByCode(Integer code) {
|
||||
for (CaseDocumentLogRunStatusEnum statusEnum : values()) {
|
||||
if (statusEnum.getCode().equals(code)) {
|
||||
return statusEnum;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.xboe.module.assistance.service;
|
||||
|
||||
/**
|
||||
* SMTP邮件服务接口
|
||||
*/
|
||||
public interface ISmtpEmailService {
|
||||
|
||||
/**
|
||||
* 使用SMTP直接发送邮件
|
||||
* @param to 收件人邮箱
|
||||
* @param subject 邮件主题
|
||||
* @param htmlMsg 邮件内容(HTML格式)
|
||||
* @param from 发件人邮箱
|
||||
* @throws Exception 发送异常
|
||||
*/
|
||||
void sendMailBySmtp(String to, String subject, String htmlMsg, String from) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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("创建失败");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package com.xboe.module.boecase.api;
|
||||
|
||||
import com.xboe.common.PageList;
|
||||
import com.xboe.core.JsonResponse;
|
||||
import com.xboe.core.api.ApiBaseController;
|
||||
import com.xboe.core.log.AutoLog;
|
||||
import com.xboe.module.boecase.dto.CaseDocumentLogQueryDto;
|
||||
import com.xboe.module.boecase.service.ICaseDocumentLogService;
|
||||
import com.xboe.module.boecase.service.ICaseKnowledgeService;
|
||||
import com.xboe.module.boecase.service.ICasesService;
|
||||
import com.xboe.module.boecase.entity.Cases;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.common.utils.IDGenerator;
|
||||
import com.xboe.common.utils.StringUtil;
|
||||
import java.time.LocalDateTime;
|
||||
import com.xboe.module.boecase.vo.CaseDocumentLogVo;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* AI调用日志管理API
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping(value = "/xboe/m/boe/caseDocumentLog")
|
||||
public class CaseDocumentLogApi extends ApiBaseController {
|
||||
|
||||
@Resource
|
||||
private ICaseDocumentLogService caseDocumentLogService;
|
||||
|
||||
@Resource
|
||||
private ICaseKnowledgeService caseKnowledgeService;
|
||||
|
||||
@Resource
|
||||
private ICasesService casesService;
|
||||
|
||||
/**
|
||||
* AI调用日志分页查询
|
||||
*
|
||||
* @param queryDto 查询条件
|
||||
* @return 分页结果
|
||||
*/
|
||||
@PostMapping("/pageQuery")
|
||||
@AutoLog(module = "AI调用日志", action = "分页查询", info = "AI调用日志分页查询")
|
||||
public JsonResponse<PageList<CaseDocumentLogVo>> pageQuery(@RequestBody CaseDocumentLogQueryDto queryDto) {
|
||||
try {
|
||||
PageList<CaseDocumentLogVo> result = caseDocumentLogService.pageQuery(
|
||||
queryDto.getPageIndex(),
|
||||
queryDto.getPageSize(),
|
||||
queryDto
|
||||
);
|
||||
return success(result);
|
||||
} catch (Exception e) {
|
||||
log.error("AI调用日志分页查询失败", e);
|
||||
return error("查询失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空日志(根据筛选条件)
|
||||
*
|
||||
* @param queryDto 查询条件
|
||||
* @return 删除结果
|
||||
*/
|
||||
@PostMapping("/clearLogs")
|
||||
@AutoLog(module = "AI调用日志", action = "清空日志", info = "AI调用日志清空操作")
|
||||
public JsonResponse<Integer> clearLogs(@RequestBody CaseDocumentLogQueryDto queryDto) {
|
||||
try {
|
||||
int deletedCount = caseDocumentLogService.clearLogsByCondition(queryDto);
|
||||
return success(deletedCount);
|
||||
} catch (Exception e) {
|
||||
log.error("AI调用日志清空失败", e);
|
||||
return error("清空失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试AI调用
|
||||
*
|
||||
* @param request 重试请求参数
|
||||
* @return 重试结果
|
||||
*/
|
||||
@PostMapping("/retry")
|
||||
@AutoLog(module = "AI调用日志", action = "重试调用", info = "AI调用日志重试操作")
|
||||
public JsonResponse<Boolean> retry(@RequestBody RetryRequest request) {
|
||||
try {
|
||||
boolean result = caseDocumentLogService.retryByLogId(request.getLogId());
|
||||
return success(result);
|
||||
} catch (Exception e) {
|
||||
log.error("AI调用重试失败", e);
|
||||
return error("重试失败", e.getMessage());
|
||||
}
|
||||
// 先走挡板
|
||||
// return success(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据案例ID上传案例文档到知识库
|
||||
*
|
||||
* @param request 上传请求参数
|
||||
* @return 上传结果
|
||||
*/
|
||||
@PostMapping("/uploadCaseByID")
|
||||
@AutoLog(module = "案例文档管理", action = "根据案例ID上传文档", info = "根据案例ID查询案例信息并上传文档到知识库")
|
||||
public JsonResponse<Boolean> uploadCaseById(@RequestBody UploadCaseRequest request) {
|
||||
try {
|
||||
String caseId = request.getCaseId();
|
||||
if (StringUtil.isBlank(caseId)) {
|
||||
return badRequest("案例ID不能为空");
|
||||
}
|
||||
|
||||
// 查询案例信息
|
||||
Cases caseInfo = casesService.selectById(caseId, false);
|
||||
if (caseInfo == null || caseInfo.getDeleted()) {
|
||||
return badRequest("案例不存在或已删除");
|
||||
}
|
||||
|
||||
log.info("开始上传案例文档到知识库,案例ID: {}, 案例标题: {}", caseId, caseInfo.getTitle());
|
||||
|
||||
// 调用ICaseKnowledgeService的uploadCaseDocument方法
|
||||
boolean result = caseKnowledgeService.uploadCaseDocument(caseId);
|
||||
|
||||
if (result) {
|
||||
log.info("案例文档上传成功,案例ID: {}", caseId);
|
||||
return success(result, "案例文档上传成功");
|
||||
} else {
|
||||
log.warn("案例文档上传失败,案例ID: {}", caseId);
|
||||
return success(result, "案例文档上传失败");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("根据案例ID上传文档失败", e);
|
||||
return error("上传失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接创建CaseDocumentLog数据
|
||||
*
|
||||
* @param logData 日志数据
|
||||
* @return 创建结果
|
||||
*/
|
||||
@PostMapping("/createLog")
|
||||
@AutoLog(module = "案例文档日志", action = "创建日志记录", info = "直接创建一条CaseDocumentLog数据")
|
||||
public JsonResponse<String> createLog(@RequestBody CaseDocumentLog logData) {
|
||||
try {
|
||||
// 参数校验
|
||||
if (StringUtil.isBlank(logData.getCaseId())) {
|
||||
return badRequest("案例ID不能为空");
|
||||
}
|
||||
if (StringUtil.isBlank(logData.getOptType())) {
|
||||
return badRequest("操作类型不能为空");
|
||||
}
|
||||
|
||||
// 设置必要的默认值
|
||||
if (StringUtil.isBlank(logData.getId())) {
|
||||
logData.setId(IDGenerator.generate());
|
||||
}
|
||||
if (logData.getOptTime() == null) {
|
||||
logData.setOptTime(LocalDateTime.now());
|
||||
}
|
||||
if (logData.getOptStatus() == null) {
|
||||
logData.setOptStatus(0); // 默认为调用中
|
||||
}
|
||||
if (logData.getDeleted() == null) {
|
||||
logData.setDeleted(false);
|
||||
}
|
||||
|
||||
// 如果提供了案例ID但没有案例标题,尝试查询案例信息补充标题
|
||||
if (StringUtil.isBlank(logData.getCaseTitle()) && StringUtil.isNotBlank(logData.getCaseId())) {
|
||||
try {
|
||||
Cases caseInfo = casesService.selectById(logData.getCaseId(), false);
|
||||
if (caseInfo != null) {
|
||||
logData.setCaseTitle(caseInfo.getTitle());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("查询案例标题失败,案例ID: {}", logData.getCaseId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("创建CaseDocumentLog记录,案例ID: {}, 操作类型: {}",
|
||||
logData.getCaseId(), logData.getOptType());
|
||||
|
||||
// 保存日志记录
|
||||
caseDocumentLogService.save(logData);
|
||||
|
||||
log.info("CaseDocumentLog记录创建成功,日志ID: {}", logData.getId());
|
||||
return success(logData.getId(), "日志记录创建成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("创建CaseDocumentLog记录失败", e);
|
||||
return error("创建失败", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文档上传回调接口
|
||||
*
|
||||
* @param request 回调请求参数
|
||||
* @return 回调结果
|
||||
*/
|
||||
@PostMapping("/uploadCallback")
|
||||
@AutoLog(module = "AI调用日志", action = "文档上传回调", info = "文档上传回调接口")
|
||||
public CallbackResponse uploadCallback(@RequestBody CallbackRequest request) {
|
||||
try {
|
||||
log.info("收到文档上传回调,taskId: {}, fileStatus: {}, message: {}",
|
||||
request.getTaskId(), request.getFileStatus(), request.getMessage());
|
||||
|
||||
boolean result = caseKnowledgeService.handleUploadCallback(
|
||||
request.getTaskId(),
|
||||
request.getMessage(),
|
||||
request.getFileStatus()
|
||||
);
|
||||
|
||||
CallbackResponse response = new CallbackResponse();
|
||||
response.setSuccess(result);
|
||||
response.setCode(result ? 0 : -1);
|
||||
response.setMessage(result ? "回调处理成功" : "回调处理失败");
|
||||
|
||||
return response;
|
||||
} catch (Exception e) {
|
||||
log.error("文档上传回调处理失败", e);
|
||||
|
||||
CallbackResponse response = new CallbackResponse();
|
||||
response.setSuccess(false);
|
||||
response.setCode(-1);
|
||||
response.setMessage("回调处理异常: " + e.getMessage());
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回调请求参数
|
||||
*/
|
||||
public static class CallbackRequest {
|
||||
private String taskId;
|
||||
private String message;
|
||||
private String fileStatus;
|
||||
|
||||
public String getTaskId() {
|
||||
return taskId;
|
||||
}
|
||||
|
||||
public void setTaskId(String taskId) {
|
||||
this.taskId = taskId;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getFileStatus() {
|
||||
return fileStatus;
|
||||
}
|
||||
|
||||
public void setFileStatus(String fileStatus) {
|
||||
this.fileStatus = fileStatus;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回调响应参数
|
||||
*/
|
||||
public static class CallbackResponse {
|
||||
private boolean success;
|
||||
private int code;
|
||||
private String message;
|
||||
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传案例请求参数
|
||||
*/
|
||||
public static class UploadCaseRequest {
|
||||
private String caseId;
|
||||
|
||||
public String getCaseId() {
|
||||
return caseId;
|
||||
}
|
||||
|
||||
public void setCaseId(String caseId) {
|
||||
this.caseId = caseId;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试请求参数
|
||||
*/
|
||||
public static class RetryRequest {
|
||||
private String logId;
|
||||
|
||||
public String getLogId() {
|
||||
return logId;
|
||||
}
|
||||
|
||||
public void setLogId(String logId) {
|
||||
this.logId = logId;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.xboe.module.boecase.api;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* 案例上传任务API
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/xboe/m/boe/caseUpload")
|
||||
public class CaseUploadTaskApi {
|
||||
|
||||
@Autowired
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
private static final String CASE_UPLOAD_LAST_ID_KEY = "case:upload:last:id";
|
||||
|
||||
/**
|
||||
* 清除处理位置标记,使下次任务从头开始执行
|
||||
*/
|
||||
@PostMapping("/reset")
|
||||
public void resetLastProcessedId() {
|
||||
stringRedisTemplate.delete(CASE_UPLOAD_LAST_ID_KEY);
|
||||
log.info("已清除上次处理位置标记");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.xboe.module.boecase.dao;
|
||||
|
||||
import com.xboe.core.orm.BaseDao;
|
||||
import com.xboe.core.orm.FieldFilters;
|
||||
import com.xboe.module.boecase.entity.CaseAiConversations;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* 案例AI会话信息DAO
|
||||
*/
|
||||
@Repository
|
||||
public class CaseAiConversationsDao extends BaseDao<CaseAiConversations> {
|
||||
|
||||
/**
|
||||
* 根据主键ID查询AI会话ID
|
||||
* @param conversationId 主键ID
|
||||
* @return AI会话ID
|
||||
*/
|
||||
public String findAiConversationIdById(String conversationId) {
|
||||
CaseAiConversations conversation = this.getGenericDao().findOne(CaseAiConversations.class,
|
||||
FieldFilters.eq("ai_conversation_id", conversationId));
|
||||
return conversation != null ? conversation.getAiConversationId() : conversationId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.xboe.module.boecase.dao;
|
||||
|
||||
import com.xboe.core.orm.BaseDao;
|
||||
import com.xboe.core.orm.FieldFilters;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* AI调用日志DAO
|
||||
*/
|
||||
@Repository
|
||||
@Slf4j
|
||||
public class CaseDocumentLogDao extends BaseDao<CaseDocumentLog> {
|
||||
|
||||
/**
|
||||
* 根据taskId查询文档日志
|
||||
* @param taskId 任务ID
|
||||
* @return 文档日志
|
||||
*/
|
||||
public CaseDocumentLog findByTaskId(String taskId) {
|
||||
return this.getGenericDao().findOne(CaseDocumentLog.class,
|
||||
FieldFilters.eq("taskId", taskId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.xboe.module.boecase.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* AI对话入参
|
||||
*/
|
||||
@Data
|
||||
public class CaseAiChatDto {
|
||||
|
||||
/**
|
||||
* 对话id
|
||||
* 如果是新对话,传空
|
||||
*/
|
||||
private String conversationId;
|
||||
|
||||
/**
|
||||
* 提问内容
|
||||
*/
|
||||
private String query;
|
||||
|
||||
/**
|
||||
* 是否开启思考
|
||||
* 0-否 1-是
|
||||
*/
|
||||
private Integer enableThinking;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.xboe.module.boecase.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* AI调用日志查询条件DTO
|
||||
*/
|
||||
@Data
|
||||
public class CaseDocumentLogQueryDto extends PageDto {
|
||||
|
||||
/**
|
||||
* 案例标题(模糊查询)
|
||||
*/
|
||||
private String caseTitle;
|
||||
|
||||
/**
|
||||
* 操作类型(create-新增,delete-删除,update-更改)
|
||||
*/
|
||||
private String optType;
|
||||
|
||||
/**
|
||||
* 调用时间开始
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime optTimeStart;
|
||||
|
||||
/**
|
||||
* 调用时间结束
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime optTimeEnd;
|
||||
|
||||
/**
|
||||
* 接口调用状态
|
||||
* 0-调用中, 1-调用成功, 2-调用失败
|
||||
*/
|
||||
private Integer optStatus;
|
||||
|
||||
/**
|
||||
* 业务处理状态
|
||||
* 1-处理成功, 2-处理失败
|
||||
*/
|
||||
private Integer caseStatus;
|
||||
}
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.xboe.module.boecase.entity;
|
||||
|
||||
import com.xboe.core.SysConstant;
|
||||
import com.xboe.core.orm.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Table;
|
||||
|
||||
/**
|
||||
* 案例AI会话信息表
|
||||
*/
|
||||
@Data
|
||||
@Entity
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Table(name = SysConstant.TABLE_PRE + "case_ai_conversations")
|
||||
public class CaseAiConversations extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 会话ID(由AI平台提供)
|
||||
*/
|
||||
@Column(name = "ai_conversation_id", length = 100)
|
||||
private String aiConversationId;
|
||||
|
||||
/**
|
||||
* 会话名称
|
||||
*/
|
||||
@Column(name = "conversation_name", length = 200)
|
||||
private String conversationName;
|
||||
|
||||
/**
|
||||
* 会话对应用户ID
|
||||
*/
|
||||
@Column(name = "conversation_user", length = 50)
|
||||
private String conversationUser;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.xboe.module.boecase.entity;
|
||||
|
||||
import com.xboe.core.SysConstant;
|
||||
import com.xboe.core.orm.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 案例文档日志信息表
|
||||
*/
|
||||
@Data
|
||||
@Entity
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Table(name = SysConstant.TABLE_PRE + "case_document_log")
|
||||
public class CaseDocumentLog extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 任务ID
|
||||
*/
|
||||
@Column(name = "task_id", length = 20)
|
||||
private String taskId;
|
||||
|
||||
/**
|
||||
* 案例id
|
||||
*/
|
||||
@Column(name = "case_id", length = 20)
|
||||
private String caseId;
|
||||
|
||||
/**
|
||||
* 案例标题
|
||||
*/
|
||||
@Column(name = "case_title", length = 200)
|
||||
private String caseTitle;
|
||||
|
||||
/**
|
||||
* 操作类型
|
||||
*/
|
||||
@Column(name = "opt_type")
|
||||
private String optType;
|
||||
|
||||
/**
|
||||
* 请求地址
|
||||
*/
|
||||
@Column(name = "request_url", length = 500)
|
||||
private String requestUrl;
|
||||
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
@Column(name = "request_body", length = 4000)
|
||||
private String requestBody;
|
||||
|
||||
/**
|
||||
* 响应参数
|
||||
*/
|
||||
@Column(name = "response_body", length = 4000)
|
||||
private String responseBody;
|
||||
|
||||
/**
|
||||
* 调用时间
|
||||
*/
|
||||
@Column(name = "opt_time")
|
||||
private LocalDateTime optTime;
|
||||
|
||||
/**
|
||||
* 接口运行状态
|
||||
* 0-运行中, 1-运行完毕
|
||||
*/
|
||||
@Column(name = "run_status")
|
||||
private Integer runStatus;
|
||||
|
||||
/**
|
||||
* 接口调用状态
|
||||
* 0-调用中, 1-调用成功, 2-调用失败
|
||||
*/
|
||||
@Column(name = "opt_status")
|
||||
private Integer optStatus;
|
||||
|
||||
/**
|
||||
* 业务处理状态
|
||||
* 1-处理成功, 2-处理失败
|
||||
*/
|
||||
@Column(name = "case_status")
|
||||
private Integer caseStatus;
|
||||
|
||||
/**
|
||||
* 执行时间(ms)
|
||||
*/
|
||||
@Column(name = "execute_duration")
|
||||
private Long executeDuration;
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
/**
|
||||
* 获取accesstoken
|
||||
*/
|
||||
public interface IAiAccessTokenService {
|
||||
|
||||
/**
|
||||
* 获取accesstoken
|
||||
* @return
|
||||
*/
|
||||
String getAccessToken();
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
/**
|
||||
* 案例AI权限服务接口
|
||||
*/
|
||||
public interface ICaseAiPermissionService {
|
||||
|
||||
/**
|
||||
* 判断指定用户是否显示"案例专家"功能入口
|
||||
* @param userCode 用户编码
|
||||
* @return 是否显示功能入口
|
||||
*/
|
||||
boolean shouldShowCaseAiEntrance(String userCode);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
import com.xboe.common.PageList;
|
||||
import com.xboe.module.boecase.dto.CaseDocumentLogQueryDto;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.module.boecase.vo.CaseDocumentLogVo;
|
||||
|
||||
/**
|
||||
* AI调用日志Service接口
|
||||
*/
|
||||
public interface ICaseDocumentLogService {
|
||||
|
||||
/**
|
||||
* 分页查询AI调用日志
|
||||
*
|
||||
* @param pageIndex 页码
|
||||
* @param pageSize 每页大小
|
||||
* @param queryDto 查询条件
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageList<CaseDocumentLogVo> pageQuery(int pageIndex, int pageSize, CaseDocumentLogQueryDto queryDto);
|
||||
|
||||
/**
|
||||
* 根据查询条件清空日志
|
||||
* 仅删除当前筛选条件下的日志记录,非筛选范围内的日志不受影响
|
||||
*
|
||||
* @param queryDto 查询条件
|
||||
* @return 删除的记录数
|
||||
*/
|
||||
int clearLogsByCondition(CaseDocumentLogQueryDto queryDto);
|
||||
|
||||
/**
|
||||
* 根据logId重试AI调用
|
||||
* 查询原始日志数据,重试执行后添加新的日志记录
|
||||
*
|
||||
* @param logId 日志ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean retryByLogId(String logId);
|
||||
|
||||
/**
|
||||
* 保存日志记录
|
||||
*
|
||||
* @param log 日志对象
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean save(CaseDocumentLog log);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.xboe.module.boecase.service;
|
||||
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.module.boecase.entity.Cases;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* 案例-知识库
|
||||
*/
|
||||
public interface ICaseKnowledgeService {
|
||||
|
||||
/**
|
||||
* 上传案例文档
|
||||
*
|
||||
* @param caseId 案例ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean uploadCaseDocument(String caseId);
|
||||
|
||||
/**
|
||||
* 上传案例文档
|
||||
*
|
||||
* @param cases 案例
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean uploadCaseDocument(Cases cases);
|
||||
|
||||
/**
|
||||
* 删除案例文档
|
||||
*
|
||||
* @param caseId 案例ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean deleteCaseDocument(String caseId);
|
||||
|
||||
/**
|
||||
* 删除案例文档
|
||||
*
|
||||
* @param cases 案例
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean deleteCaseDocument(Cases cases);
|
||||
|
||||
/**
|
||||
* 更新案例文档
|
||||
*
|
||||
* @param caseId 案例ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean retryCaseDocument(String caseId, CaseDocumentLog originalLog);
|
||||
|
||||
/**
|
||||
* 更新案例文档
|
||||
*
|
||||
* @param cases 案例
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean updateCaseDocument(Cases cases);
|
||||
|
||||
/**
|
||||
* 处理文档上传回调
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
* @param message 回调信息
|
||||
* @param fileStatus 文件状态(vectored: 成功, failed: 失败)
|
||||
* @return 是否处理成功
|
||||
*/
|
||||
boolean handleUploadCallback(String taskId, String message, String fileStatus);
|
||||
|
||||
/**
|
||||
* 批量检查文件状态
|
||||
*/
|
||||
@Transactional(rollbackFor = Throwable.class)
|
||||
void batchCheckFileStatus();
|
||||
}
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.xboe.module.boecase.service.impl;
|
||||
|
||||
import com.xboe.module.boecase.properties.CaseAiProperties;
|
||||
import com.xboe.module.boecase.service.ICaseAiPermissionService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 案例AI权限服务实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@Transactional
|
||||
public class CaseAiPermissionServiceImpl implements ICaseAiPermissionService {
|
||||
|
||||
@Autowired
|
||||
private CaseAiProperties caseAiProperties;
|
||||
|
||||
/**
|
||||
* 判断指定用户是否显示"案例专家"功能入口
|
||||
* @param userCode 用户编码
|
||||
* @return 是否显示功能入口
|
||||
*/
|
||||
@Override
|
||||
public boolean shouldShowCaseAiEntrance(String userCode) {
|
||||
log.info("判断用户[{}]是否显示案例专家功能入口", userCode);
|
||||
|
||||
// 如果不启用白名单,直接返回true
|
||||
if (!caseAiProperties.isUseWhiteList()) {
|
||||
log.info("未启用白名单,所有用户都显示功能入口");
|
||||
return true;
|
||||
}
|
||||
|
||||
// 启用白名单时,判断当前用户是否在白名单中
|
||||
List<String> whiteUserCodeList = caseAiProperties.getWhiteUserCodeList();
|
||||
log.info("白名单列表:{}", whiteUserCodeList);
|
||||
boolean isInWhiteList = whiteUserCodeList != null
|
||||
&& whiteUserCodeList.stream().anyMatch(userCode::equals);
|
||||
|
||||
log.info("用户[{}]{}在白名单中", userCode, isInWhiteList ? "" : "不");
|
||||
return isInWhiteList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package com.xboe.module.boecase.service.impl;
|
||||
|
||||
import com.xboe.common.utils.StringUtil;
|
||||
import com.xboe.common.OrderCondition;
|
||||
import com.xboe.common.PageList;
|
||||
import com.xboe.core.orm.FieldFilters;
|
||||
import com.xboe.core.orm.IFieldFilter;
|
||||
import com.xboe.core.orm.LikeMatchMode;
|
||||
import com.xboe.enums.CaseDocumentLogRunStatusEnum;
|
||||
import com.xboe.module.boecase.dao.CaseDocumentLogDao;
|
||||
import com.xboe.module.boecase.dto.CaseDocumentLogQueryDto;
|
||||
import com.xboe.module.boecase.entity.CaseDocumentLog;
|
||||
import com.xboe.module.boecase.service.ICaseDocumentLogService;
|
||||
import com.xboe.module.boecase.service.ICaseKnowledgeService;
|
||||
import com.xboe.module.boecase.vo.CaseDocumentLogVo;
|
||||
import com.xboe.enums.CaseDocumentLogOptTypeEnum;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* AI调用日志Service实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@Transactional
|
||||
public class CaseDocumentLogServiceImpl implements ICaseDocumentLogService {
|
||||
|
||||
@Resource
|
||||
private CaseDocumentLogDao caseDocumentLogDao;
|
||||
|
||||
@Resource
|
||||
private ICaseKnowledgeService caseKnowledgeService;
|
||||
|
||||
@Resource(name = "aiDocExecutor")
|
||||
private ThreadPoolTaskExecutor aiDocExecutor;
|
||||
|
||||
@Override
|
||||
public PageList<CaseDocumentLogVo> pageQuery(int pageIndex, int pageSize, CaseDocumentLogQueryDto queryDto) {
|
||||
// 构建查询条件
|
||||
List<IFieldFilter> filters = new ArrayList<>();
|
||||
|
||||
// 运行状态过滤
|
||||
filters.add(FieldFilters.eq("runStatus", CaseDocumentLogRunStatusEnum.COMPLETED.getCode()));
|
||||
|
||||
// 案例标题模糊查询
|
||||
if (StringUtil.isNotBlank(queryDto.getCaseTitle())) {
|
||||
filters.add(FieldFilters.like("caseTitle", LikeMatchMode.ANYWHERE, queryDto.getCaseTitle()));
|
||||
}
|
||||
|
||||
// 操作类型精确查询
|
||||
if (StringUtil.isNotBlank(queryDto.getOptType())) {
|
||||
filters.add(FieldFilters.eq("optType", queryDto.getOptType()));
|
||||
}
|
||||
|
||||
// 调用时间区间查询
|
||||
if (queryDto.getOptTimeStart() != null) {
|
||||
filters.add(FieldFilters.ge("optTime", queryDto.getOptTimeStart()));
|
||||
}
|
||||
if (queryDto.getOptTimeEnd() != null) {
|
||||
// 将结束时间调整为当天的23:59:59
|
||||
LocalDateTime optTimeEnd = queryDto.getOptTimeEnd().withHour(23).withMinute(59).withSecond(59);
|
||||
filters.add(FieldFilters.le("optTime", optTimeEnd));
|
||||
}
|
||||
|
||||
// 接口调用状态
|
||||
if (queryDto.getOptStatus() != null) {
|
||||
filters.add(FieldFilters.eq("optStatus", queryDto.getOptStatus()));
|
||||
}
|
||||
|
||||
// 业务处理状态
|
||||
if (queryDto.getCaseStatus() != null) {
|
||||
filters.add(FieldFilters.eq("caseStatus", queryDto.getCaseStatus()));
|
||||
}
|
||||
|
||||
// 删除标识过滤
|
||||
filters.add(FieldFilters.eq("deleted", false));
|
||||
|
||||
// 按创建时间降序排序
|
||||
OrderCondition order = OrderCondition.desc("sysCreateTime");
|
||||
|
||||
// 执行分页查询
|
||||
PageList<CaseDocumentLog> pageResult = caseDocumentLogDao.getGenericDao()
|
||||
.findPage(pageIndex, pageSize, CaseDocumentLog.class, filters, order);
|
||||
|
||||
// 转换为VO对象
|
||||
List<CaseDocumentLogVo> voList = pageResult.getList().stream()
|
||||
.map(this::convertToVo)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 构建返回结果
|
||||
PageList<CaseDocumentLogVo> result = new PageList<>();
|
||||
result.setList(voList);
|
||||
result.setCount(pageResult.getCount());
|
||||
result.setPageSize(pageResult.getPageSize());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int clearLogsByCondition(CaseDocumentLogQueryDto queryDto) {
|
||||
// 构建查询条件(与分页查询相同的逻辑)
|
||||
List<IFieldFilter> filters = new ArrayList<>();
|
||||
|
||||
// 运行状态过滤
|
||||
filters.add(FieldFilters.eq("runStatus", CaseDocumentLogRunStatusEnum.COMPLETED.getCode()));
|
||||
|
||||
// 案例标题模糊查询
|
||||
if (StringUtil.isNotBlank(queryDto.getCaseTitle())) {
|
||||
filters.add(FieldFilters.like("caseTitle", LikeMatchMode.ANYWHERE, queryDto.getCaseTitle()));
|
||||
}
|
||||
|
||||
// 操作类型精确查询
|
||||
if (StringUtil.isNotBlank(queryDto.getOptType())) {
|
||||
filters.add(FieldFilters.eq("optType", queryDto.getOptType()));
|
||||
}
|
||||
|
||||
// 调用时间区间查询
|
||||
if (queryDto.getOptTimeStart() != null) {
|
||||
filters.add(FieldFilters.ge("optTime", queryDto.getOptTimeStart()));
|
||||
}
|
||||
if (queryDto.getOptTimeEnd() != null) {
|
||||
// 将结束时间调整为当天的23:59:59
|
||||
LocalDateTime optTimeEnd = queryDto.getOptTimeEnd().withHour(23).withMinute(59).withSecond(59);
|
||||
filters.add(FieldFilters.le("optTime", optTimeEnd));
|
||||
}
|
||||
|
||||
// 接口调用状态
|
||||
if (queryDto.getOptStatus() != null) {
|
||||
filters.add(FieldFilters.eq("optStatus", queryDto.getOptStatus()));
|
||||
}
|
||||
|
||||
// 业务处理状态
|
||||
if (queryDto.getCaseStatus() != null) {
|
||||
filters.add(FieldFilters.eq("caseStatus", queryDto.getCaseStatus()));
|
||||
}
|
||||
|
||||
// 删除标识过滤
|
||||
filters.add(FieldFilters.eq("deleted", false));
|
||||
|
||||
// 查询符合条件的所有记录
|
||||
IFieldFilter[] filtersArray = filters.toArray(new IFieldFilter[0]);
|
||||
List<CaseDocumentLog> logsToDelete = caseDocumentLogDao.getGenericDao()
|
||||
.findList(CaseDocumentLog.class, filtersArray);
|
||||
|
||||
if (logsToDelete.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 批量设置删除标识为true(逻辑删除)
|
||||
int deletedCount = 0;
|
||||
for (CaseDocumentLog log : logsToDelete) {
|
||||
log.setDeleted(true);
|
||||
caseDocumentLogDao.update(log);
|
||||
deletedCount++;
|
||||
}
|
||||
|
||||
log.info("清空日志操作完成,共删除{}条记录", deletedCount);
|
||||
return deletedCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retryByLogId(String logId) {
|
||||
if (StringUtil.isBlank(logId)) {
|
||||
log.error("重试失败,logId不能为空");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 1. 根据logId查询原始日志数据
|
||||
CaseDocumentLog originalLog = caseDocumentLogDao.get(logId);
|
||||
if (originalLog == null || originalLog.getDeleted()) {
|
||||
log.error("重试失败,未找到有效的日志记录,logId: {}", logId);
|
||||
return false;
|
||||
}
|
||||
|
||||
log.info("开始异步重试AI调用,原始日志ID: {}, 案例标题: {}, 操作类型: {}",
|
||||
logId, originalLog.getCaseTitle(), originalLog.getOptType());
|
||||
|
||||
// 2. 使用线程池异步执行AI调用重试逻辑
|
||||
String optType = originalLog.getOptType();
|
||||
String caseId = originalLog.getCaseId();
|
||||
|
||||
aiDocExecutor.execute(() -> executeRetryLogic(optType, caseId, originalLog));
|
||||
|
||||
// 立即返回true表示重试请求已接受,具体结果通过日志异步处理
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行AI调用重试逻辑
|
||||
* @param optType 操作类型
|
||||
* @param caseId 案例ID
|
||||
*/
|
||||
private void executeRetryLogic(String optType, String caseId, CaseDocumentLog originalLog) {
|
||||
boolean retrySuccess = false;
|
||||
|
||||
try {
|
||||
if (StringUtil.isBlank(caseId)) {
|
||||
throw new IllegalArgumentException("案例ID不能为空");
|
||||
}
|
||||
|
||||
log.info("[异步任务] 正在执行AI调用重试,操作类型: {}, caseId: {}", optType, caseId);
|
||||
|
||||
// 根据操作类型执行对应的方法(这些方法内部会自动创建日志记录)
|
||||
if (CaseDocumentLogOptTypeEnum.CREATE.getCode().equals(optType)) {
|
||||
// 上传案例文档
|
||||
retrySuccess = caseKnowledgeService.uploadCaseDocument(caseId);
|
||||
log.info("[异步任务] 执行上传案例文档重试,caseId: {}, 结果: {}", caseId, retrySuccess);
|
||||
|
||||
} else if (CaseDocumentLogOptTypeEnum.DELETE.getCode().equals(optType)) {
|
||||
// 删除案例文档
|
||||
retrySuccess = caseKnowledgeService.deleteCaseDocument(caseId);
|
||||
log.info("[异步任务] 执行删除案例文档重试,caseId: {}, 结果: {}", caseId, retrySuccess);
|
||||
|
||||
} else if (CaseDocumentLogOptTypeEnum.UPDATE.getCode().equals(optType)) {
|
||||
// 更新案例文档
|
||||
retrySuccess = caseKnowledgeService.retryCaseDocument(caseId, originalLog);
|
||||
log.info("[异步任务] 执行更新案例文档重试,caseId: {}, 结果: {}", caseId, retrySuccess);
|
||||
|
||||
} else {
|
||||
throw new IllegalArgumentException("不支持的操作类型: " + optType);
|
||||
}
|
||||
|
||||
if (retrySuccess) {
|
||||
log.info("[异步任务] AI调用重试成功,操作类型: {}, caseId: {}", optType, caseId);
|
||||
} else {
|
||||
log.warn("[异步任务] AI调用重试失败,操作类型: {}, caseId: {}", optType, caseId);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("[异步任务] AI调用重试异常,操作类型: {}, caseId: {}",
|
||||
optType, caseId, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean save(CaseDocumentLog caseDocumentLog) {
|
||||
try {
|
||||
caseDocumentLogDao.save(caseDocumentLog);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("保存CaseDocumentLog失败", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 实体转换为VO
|
||||
*/
|
||||
private CaseDocumentLogVo convertToVo(CaseDocumentLog entity) {
|
||||
CaseDocumentLogVo vo = new CaseDocumentLogVo();
|
||||
BeanUtils.copyProperties(entity, vo);
|
||||
|
||||
// 操作类型转换为中文描述
|
||||
vo.setOptType(CaseDocumentLogOptTypeEnum.getDescByCode(entity.getOptType()));
|
||||
|
||||
// 接口调用状态转换
|
||||
vo.setOptStatusText(getOptStatusText(entity.getOptStatus()));
|
||||
|
||||
// 业务处理状态转换
|
||||
vo.setCaseStatusText(getCaseStatusText(entity.getCaseStatus()));
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取接口调用状态描述
|
||||
*/
|
||||
private String getOptStatusText(Integer optStatus) {
|
||||
if (optStatus == null) {
|
||||
return "";
|
||||
}
|
||||
switch (optStatus) {
|
||||
case 1:
|
||||
return "调用成功";
|
||||
case 2:
|
||||
return "调用失败";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取业务处理状态描述
|
||||
*/
|
||||
private String getCaseStatusText(Integer caseStatus) {
|
||||
if (caseStatus == null) {
|
||||
return "";
|
||||
}
|
||||
switch (caseStatus) {
|
||||
case 1:
|
||||
return "处理成功";
|
||||
case 2:
|
||||
return "处理失败";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -19,7 +19,9 @@ import com.xboe.common.utils.IDGenerator;
|
||||
import com.xboe.common.utils.StringUtil;
|
||||
import com.xboe.core.CurrentUser;
|
||||
import com.xboe.core.orm.*;
|
||||
import com.xboe.enums.CaseDocumentLogOptTypeEnum;
|
||||
import com.xboe.enums.CasesRankEnum;
|
||||
import com.xboe.module.boecase.async.CaseAiDocumentAsyncHandler;
|
||||
import com.xboe.module.boecase.dao.*;
|
||||
import com.xboe.module.boecase.dto.*;
|
||||
import com.xboe.module.boecase.entity.*;
|
||||
@@ -90,6 +92,9 @@ public class CasesServiceImpl implements ICasesService {
|
||||
@Resource
|
||||
private ThirdApi thirdApi;
|
||||
|
||||
@Autowired
|
||||
private CaseAiDocumentAsyncHandler caseAiDocumentAsyncHandler;
|
||||
|
||||
/**
|
||||
* 案例分页查询,用于门户的查询
|
||||
*/
|
||||
@@ -799,7 +804,11 @@ public class CasesServiceImpl implements ICasesService {
|
||||
*/
|
||||
@Override
|
||||
public void delete(String id) {
|
||||
Cases cases = casesDao.get(id);
|
||||
// 原删除
|
||||
casesDao.setDeleted(id);
|
||||
// 增加逻辑
|
||||
caseAiDocumentAsyncHandler.process(CaseDocumentLogOptTypeEnum.DELETE, cases);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -986,6 +995,8 @@ public class CasesServiceImpl implements ICasesService {
|
||||
cases.setMajorIds(majorIds);
|
||||
cases.setMajorType(stringBuffer.toString());
|
||||
casesDao.save(cases);
|
||||
// 增加逻辑
|
||||
caseAiDocumentAsyncHandler.process(CaseDocumentLogOptTypeEnum.CREATE, cases);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1009,6 +1020,8 @@ public class CasesServiceImpl implements ICasesService {
|
||||
cases.setMajorIds(majorIds);
|
||||
cases.setMajorType(stringBuffer.toString());
|
||||
casesDao.update(cases);
|
||||
// 增加逻辑
|
||||
caseAiDocumentAsyncHandler.process(CaseDocumentLogOptTypeEnum.UPDATE, cases);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,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" +
|
||||
"}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.xboe.module.boecase.task;
|
||||
|
||||
import com.xboe.module.boecase.service.ICaseKnowledgeService;
|
||||
import com.xxl.job.core.handler.annotation.XxlJob;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class CaseDocumentLogTask {
|
||||
|
||||
@Autowired
|
||||
private ICaseKnowledgeService caseKnowledgeService;
|
||||
|
||||
/**
|
||||
* 批量查询文件状态并修改
|
||||
* 目前每次查看10条数据,批处理拟每10秒一次,每分钟可运行6次,60条数据
|
||||
* cron: 0/10 * * * * ?
|
||||
*/
|
||||
@XxlJob("batchCheckFileStatusJob")
|
||||
public void batchCheckFileStatusJob() {
|
||||
log.info("开始批量查询文件状态");
|
||||
caseKnowledgeService.batchCheckFileStatus();
|
||||
log.info("结束批量查询文件状态");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.xboe.module.boecase.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* AI会话记录
|
||||
*/
|
||||
@Data
|
||||
public class CaseAiConversationVo {
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.xboe.module.boecase.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* AI调用日志列表展示VO
|
||||
*/
|
||||
@Data
|
||||
public class CaseDocumentLogVo {
|
||||
|
||||
/**
|
||||
* 日志ID
|
||||
*/
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 案例标题
|
||||
*/
|
||||
private String caseTitle;
|
||||
|
||||
/**
|
||||
* 操作类型
|
||||
*/
|
||||
private String optType;
|
||||
|
||||
/**
|
||||
* 调用接口名称
|
||||
*/
|
||||
private String requestUrl;
|
||||
|
||||
/**
|
||||
* 调用时间
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime optTime;
|
||||
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
private String requestBody;
|
||||
|
||||
/**
|
||||
* 响应参数
|
||||
*/
|
||||
private String responseBody;
|
||||
|
||||
/**
|
||||
* 接口调用结果
|
||||
* 0-调用中, 1-调用成功, 2-调用失败
|
||||
*/
|
||||
private Integer optStatus;
|
||||
|
||||
/**
|
||||
* 接口调用结果描述
|
||||
*/
|
||||
private String optStatusText;
|
||||
|
||||
/**
|
||||
* 业务处理结果
|
||||
* 1-处理成功, 2-处理失败
|
||||
*/
|
||||
private Integer caseStatus;
|
||||
|
||||
/**
|
||||
* 业务处理结果描述
|
||||
*/
|
||||
private String caseStatusText;
|
||||
|
||||
/**
|
||||
* 执行时间(ms)
|
||||
*/
|
||||
private Long executeDuration;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.xboe.module.boecase.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 案例引用信息VO
|
||||
*/
|
||||
@Data
|
||||
public class CaseReferVo {
|
||||
|
||||
/**
|
||||
* 案例ID
|
||||
*/
|
||||
private String caseId;
|
||||
|
||||
/**
|
||||
* 案例标题
|
||||
*/
|
||||
private String title;
|
||||
|
||||
/**
|
||||
* 作者姓名
|
||||
*/
|
||||
private String authorName;
|
||||
|
||||
/**
|
||||
* 组织信息
|
||||
*/
|
||||
private String orgInfo;
|
||||
|
||||
/**
|
||||
* 上传时间
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private LocalDateTime uploadTime;
|
||||
|
||||
/**
|
||||
* 关键词列表
|
||||
*/
|
||||
private List<String> keywords;
|
||||
|
||||
/**
|
||||
* 案例内容
|
||||
*/
|
||||
private String content;
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
@@ -133,6 +150,22 @@ public class CourseManageApi extends ApiBaseController{
|
||||
dto.setOrgIds(ids);
|
||||
dto.setReadIds(userOrgIds.getReadIds());
|
||||
PageList<Course> coursePageList = courseService.findPage(pager.getPageIndex(), pager.getPageSize(),dto);
|
||||
// 补充审核人和审核时间(取最近一条审核记录)- 批量查询优化
|
||||
if (coursePageList != null && coursePageList.getList() != null && !coursePageList.getList().isEmpty()) {
|
||||
List<String> courseIds = coursePageList.getList().stream().map(Course::getId).collect(Collectors.toList());
|
||||
Map<String, CourseHRBPAudit> latestAuditMap = hrbpAuditService.findLatestByCourseIds(courseIds);
|
||||
for (Course c : coursePageList.getList()) {
|
||||
try {
|
||||
CourseHRBPAudit latest = latestAuditMap.get(c.getId());
|
||||
if (latest != null) {
|
||||
c.setAuditUser(latest.getAuditUser());
|
||||
c.setAuditTime(latest.getAuditTime());
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
// ignore single course enrich error
|
||||
}
|
||||
}
|
||||
}
|
||||
return success(coursePageList);
|
||||
}catch(Exception e) {
|
||||
log.error("管理课程列表查询错误",e);
|
||||
@@ -158,6 +191,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 +214,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 +347,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())) {
|
||||
//只有在第一次添加保存时才会这样
|
||||
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -397,6 +400,15 @@ public class Course extends BaseEntity {
|
||||
@Transient
|
||||
private String teacher;
|
||||
|
||||
/**审核人名称(列表展示用)*/
|
||||
@Transient
|
||||
private String auditUser;
|
||||
|
||||
/**审核时间(列表展示用)*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@Transient
|
||||
private LocalDateTime auditTime;
|
||||
|
||||
public Course(String id,String name,String summary,String coverImg,String sysCreateAid,String sysCreateBy,Integer type,LocalDateTime publishTime){
|
||||
super.setId(id);
|
||||
this.name=name;
|
||||
|
||||
@@ -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;
|
||||
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.xboe.module.course.service;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.xboe.common.PageList;
|
||||
import com.xboe.module.course.dto.CourseHRBPAuditDto;
|
||||
@@ -56,5 +57,10 @@ public interface ICourseHRBPAuditService {
|
||||
*/
|
||||
PageList<CourseHRBPAudit> pageList(Integer pageIndex, Integer pageSize,int userType, CourseHRBPAudit info);
|
||||
|
||||
/**
|
||||
* 查询一组课程的最近一次审核记录,返回键为courseId的映射。
|
||||
*/
|
||||
Map<String, CourseHRBPAudit> findLatestByCourseIds(List<String> courseIds);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.xboe.module.course.service.impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
@@ -263,4 +265,27 @@ public class CourseHRBPAuditServiceImpl implements ICourseHRBPAuditService {
|
||||
return courseHRBPAuditDao.get(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, CourseHRBPAudit> findLatestByCourseIds(List<String> courseIds) {
|
||||
Map<String, CourseHRBPAudit> result = new HashMap<String, CourseHRBPAudit>();
|
||||
if (courseIds == null || courseIds.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
// 按 addTime 倒序,使首次出现的courseId即为该课程的最近一条审核记录
|
||||
List<CourseHRBPAudit> audits = courseHRBPAuditDao.findList(
|
||||
OrderCondition.desc("addTime"),
|
||||
FieldFilters.in("courseId", courseIds)
|
||||
);
|
||||
for (CourseHRBPAudit a : audits) {
|
||||
if (!result.containsKey(a.getCourseId())) {
|
||||
result.put(a.getCourseId(), a);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("批量查询课程审核记录错误", e.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -79,6 +79,16 @@ xboe:
|
||||
image:
|
||||
course:
|
||||
default: http://192.168.0.253/pc/images/bgimg/course.png
|
||||
case:
|
||||
ai:
|
||||
base-url: http://10.10.181.114:30003
|
||||
app-key: 6e9be45319184ac793aa127c362b0f0b
|
||||
secret-key: db4d24279e3d6dbf1524af42cd0bedd2
|
||||
ai-api-code: 30800
|
||||
case-knowledge-id: de2e006e-82fb-4ace-8813-f25c316be4ff
|
||||
file-upload-callback-url: http://192.168.0.253:9090/xboe/m/boe/caseDocumentLog/uploadCallback
|
||||
alert-email-recipients:
|
||||
- liu.zixi@ebiz-digits.com
|
||||
xxl:
|
||||
job:
|
||||
accessToken: 65ddc683-22f5-83b4-de3a-3c97a0a29af0
|
||||
|
||||
@@ -111,6 +111,16 @@ xboe:
|
||||
image:
|
||||
course:
|
||||
default: http://10.251.132.75/pc/images/bgimg/course.png
|
||||
case:
|
||||
ai:
|
||||
base-url: http://10.10.181.114:30003
|
||||
app-key: 6e9be45319184ac793aa127c362b0f0b
|
||||
secret-key: db4d24279e3d6dbf1524af42cd0bedd2
|
||||
ai-api-code: 30800
|
||||
case-knowledge-id: de2e006e-82fb-4ace-8813-f25c316be4ff
|
||||
file-upload-callback-url: http://10.251.132.75:9090/xboe/m/boe/caseDocumentLog/uploadCallback
|
||||
alert-email-recipients:
|
||||
- liu.zixi@ebiz-digits.com
|
||||
jasypt:
|
||||
encryptor:
|
||||
algorithm: PBEWithMD5AndDES
|
||||
|
||||
@@ -77,6 +77,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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
215
sql/20251115/数据迁移SQL脚本.sql
Normal file
215
sql/20251115/数据迁移SQL脚本.sql
Normal file
@@ -0,0 +1,215 @@
|
||||
-- 数据迁移SQL(项目与报名)
|
||||
-- 执行顺序:
|
||||
-- 1.1 查看项目数据量
|
||||
-- 1.2 预览项目数据
|
||||
-- 1.3 迁移项目信息
|
||||
-- 1.4 验证项目迁移结果
|
||||
-- 2.1 查看报名数据量(按项目ID)
|
||||
-- 2.2 预览报名数据
|
||||
-- 2.3 获取新项目ID
|
||||
-- 2.4 写入报名数据(使用新项目ID)
|
||||
-- 2.5 验证报名迁移结果
|
||||
|
||||
-- 任务1:项目数据迁移(eln_boe_mixture_project -> boe_new.project_info),条件:is_deleted='0' AND program_name='社招新员工在线入职学习'
|
||||
-- 步骤1.1:查看符合条件的数据量(执行前验证)
|
||||
SELECT COUNT(*) AS data_count
|
||||
FROM elearninglms.eln_boe_mixture_project
|
||||
WHERE is_deleted = '0'
|
||||
AND program_name = '社招新员工在线入职学习';
|
||||
|
||||
-- 步骤1.2:查看要迁移的数据详情(执行前验证)
|
||||
SELECT *
|
||||
FROM elearninglms.eln_boe_mixture_project
|
||||
WHERE is_deleted = '0'
|
||||
AND program_name = '社招新员工在线入职学习';
|
||||
|
||||
-- 步骤1.3:执行数据迁移(INSERT INTO ... SELECT)
|
||||
INSERT INTO boe_new.project_info (
|
||||
name,
|
||||
pic_url,
|
||||
type,
|
||||
begin_time,
|
||||
end_time,
|
||||
manager_id,
|
||||
remark,
|
||||
status,
|
||||
num_value,
|
||||
introduction,
|
||||
new_type,
|
||||
deleted,
|
||||
unlock_mode,
|
||||
rank_flag,
|
||||
attach_switch,
|
||||
bpm_flag,
|
||||
load_flag,
|
||||
create_time,
|
||||
create_id,
|
||||
update_time,
|
||||
update_id
|
||||
)
|
||||
SELECT
|
||||
p.program_name AS name,
|
||||
p.theme_url AS pic_url,
|
||||
1 AS type, -- 项目类别固定为1
|
||||
CASE
|
||||
WHEN p.open_start_time IS NOT NULL AND p.open_start_time > 0
|
||||
THEN FROM_UNIXTIME(p.open_start_time)
|
||||
WHEN p.start_time IS NOT NULL AND p.start_time > 0
|
||||
THEN FROM_UNIXTIME(p.start_time)
|
||||
ELSE NULL
|
||||
END AS begin_time,
|
||||
CASE
|
||||
WHEN p.open_end_time IS NOT NULL AND p.open_end_time > 0
|
||||
THEN FROM_UNIXTIME(p.open_end_time)
|
||||
WHEN p.end_time IS NOT NULL AND p.end_time > 0
|
||||
THEN FROM_UNIXTIME(p.end_time)
|
||||
ELSE NULL
|
||||
END AS end_time,
|
||||
p.project_manager_id AS manager_id,
|
||||
COALESCE(p.program_desc, p.program_desc_nohtml, '') AS remark,
|
||||
CASE
|
||||
WHEN p.status = '0' THEN 0 -- 临时 → 草稿
|
||||
WHEN p.status = '1' THEN 1 -- 正常 → 已发布
|
||||
WHEN p.status = '2' THEN -1 -- 停用 → 已结束
|
||||
ELSE 0
|
||||
END AS status,
|
||||
p.program_code AS num_value,
|
||||
COALESCE(p.program_desc_nohtml, p.program_desc, '') AS introduction,
|
||||
2 AS new_type, -- 学习项目
|
||||
0 AS deleted, -- 未删除
|
||||
1 AS unlock_mode, -- 自由模式
|
||||
0 AS rank_flag, -- 不显示积分排行榜
|
||||
1 AS attach_switch, -- 共享文档开启
|
||||
0 AS bpm_flag, -- 报名审批关闭
|
||||
0 AS load_flag, -- 下载成绩关闭
|
||||
FROM_UNIXTIME(p.created_at) AS create_time,
|
||||
CAST(p.created_by AS UNSIGNED) AS create_id,
|
||||
FROM_UNIXTIME(COALESCE(p.updated_at, p.created_at)) AS update_time,
|
||||
CAST(COALESCE(p.updated_by, p.created_by) AS UNSIGNED) AS update_id
|
||||
FROM elearninglms.eln_boe_mixture_project p
|
||||
WHERE p.is_deleted = '0'
|
||||
AND p.program_name = '社招新员工在线入职学习'
|
||||
AND NOT EXISTS (
|
||||
-- 防止重复插入:如果项目名称已存在则跳过
|
||||
SELECT 1
|
||||
FROM boe_new.project_info pi
|
||||
WHERE pi.name = p.program_name
|
||||
AND pi.deleted = 0
|
||||
);
|
||||
|
||||
-- 步骤1.4:验证迁移结果
|
||||
SELECT
|
||||
COUNT(*) AS migrated_count,
|
||||
name,
|
||||
status,
|
||||
begin_time,
|
||||
end_time
|
||||
FROM boe_new.project_info
|
||||
WHERE name = '社招新员工在线入职学习'
|
||||
AND deleted = 0
|
||||
GROUP BY name, status, begin_time, end_time;
|
||||
|
||||
-- 任务2:项目报名数据迁移(eln_boe_mixture_project_enroll -> boe_base.boe_study_course)
|
||||
-- 迁移全部报名数据(包括已删除记录,按 is_deleted 映射状态)
|
||||
|
||||
-- 步骤2.1:查看符合条件的数据量(执行前验证)
|
||||
-- 注意:需要先将 '123xxx' 替换为实际的项目ID(kid)
|
||||
SELECT COUNT(*) AS enroll_count
|
||||
FROM elearninglms.eln_boe_mixture_project_enroll
|
||||
WHERE program_id = '123xxx'; -- 请替换为实际的项目ID(kid)
|
||||
|
||||
-- 步骤2.2:查看要迁移的数据详情(执行前验证)
|
||||
SELECT *
|
||||
FROM elearninglms.eln_boe_mixture_project_enroll
|
||||
WHERE program_id = '123xxx' -- 请替换为实际的项目ID(kid)
|
||||
LIMIT 100;
|
||||
|
||||
-- 步骤2.3:获取新项目ID
|
||||
SET @new_project_id = (
|
||||
SELECT id FROM boe_new.project_info
|
||||
WHERE name = '社招新员工在线入职学习' AND deleted = 0
|
||||
ORDER BY id DESC LIMIT 1
|
||||
);
|
||||
|
||||
-- 步骤2.4:写入报名数据(使用新项目ID)
|
||||
INSERT INTO boe_base.boe_study_course (
|
||||
course_id,
|
||||
course_type,
|
||||
course_name,
|
||||
aid,
|
||||
aname,
|
||||
source,
|
||||
add_time,
|
||||
start_time,
|
||||
last_score,
|
||||
status,
|
||||
progress,
|
||||
remark
|
||||
)
|
||||
SELECT
|
||||
pi.id AS course_id, -- 使用新项目表的自增ID
|
||||
90 AS course_type,
|
||||
COALESCE(pi.name, p.program_name, '') AS course_name,
|
||||
e.user_id AS aid,
|
||||
COALESCE(u.real_name, '') AS aname,
|
||||
CASE
|
||||
WHEN e.enroll_method = 'self' THEN 1
|
||||
WHEN e.enroll_method = 'admin' THEN 2
|
||||
WHEN e.enroll_method = 'manager' THEN 3
|
||||
ELSE 1
|
||||
END AS source,
|
||||
FROM_UNIXTIME(e.enroll_time) AS add_time,
|
||||
FROM_UNIXTIME(e.enroll_time) AS start_time,
|
||||
NULL AS last_score,
|
||||
CASE
|
||||
WHEN e.enroll_type = '1' AND e.approved_state = '1' AND e.is_deleted = '0' THEN 2
|
||||
WHEN e.enroll_type = '3' THEN 8
|
||||
WHEN e.cancel_state = '1' THEN 8
|
||||
WHEN e.is_deleted = '1' THEN 8
|
||||
ELSE 1
|
||||
END AS status,
|
||||
0 AS progress,
|
||||
CONCAT('迁移自项目报名表,报名ID:', e.kid) AS remark
|
||||
FROM elearninglms.eln_boe_mixture_project_enroll e
|
||||
LEFT JOIN elearninglms.eln_boe_mixture_project p
|
||||
ON e.program_id = p.kid
|
||||
LEFT JOIN boe_new.project_info pi
|
||||
ON p.program_name = pi.name AND pi.deleted = 0
|
||||
LEFT JOIN elearninglms.eln_fw_user u
|
||||
ON e.user_id = u.kid
|
||||
WHERE e.program_id = '123xxx' -- 请替换为实际的项目ID(kid)
|
||||
AND pi.id = @new_project_id -- 使用新项目ID
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM boe_base.boe_study_course sc
|
||||
WHERE sc.course_id = @new_project_id
|
||||
AND sc.aid = e.user_id
|
||||
);
|
||||
|
||||
-- 步骤2.5:验证迁移结果
|
||||
SELECT
|
||||
COUNT(*) AS migrated_count,
|
||||
status,
|
||||
COUNT(CASE WHEN last_score IS NOT NULL THEN 1 END) AS has_score_count
|
||||
FROM boe_base.boe_study_course
|
||||
WHERE course_id = @new_project_id
|
||||
GROUP BY status;
|
||||
|
||||
-- 回滚SQL
|
||||
-- 回滚步骤R1:确认新项目ID(如变量丢失可重新获取)
|
||||
--SET @new_project_id = (
|
||||
-- SELECT id FROM boe_new.project_info
|
||||
-- WHERE name = '社招新员工在线入职学习' AND deleted = 0
|
||||
-- ORDER BY id DESC LIMIT 1
|
||||
--);
|
||||
--
|
||||
---- 回滚步骤R2:回滚报名数据(按备注标记,仅删除本次迁移写入的数据)
|
||||
--DELETE FROM boe_base.boe_study_course
|
||||
--WHERE course_id = @new_project_id
|
||||
-- AND remark LIKE '迁移自项目报名表%';
|
||||
--
|
||||
---- 回滚步骤R3:回滚项目信息(谨慎执行,确认仅影响本次迁移记录)
|
||||
--DELETE FROM boe_new.project_info
|
||||
--WHERE id = @new_project_id
|
||||
-- AND name = '社招新员工在线入职学习'
|
||||
-- AND deleted = 0;
|
||||
187
sql/20251115/数据迁移方案文档.md
Normal file
187
sql/20251115/数据迁移方案文档.md
Normal file
@@ -0,0 +1,187 @@
|
||||
# 数据迁移方案文档
|
||||
|
||||
## 一、迁移概述
|
||||
|
||||
本次迁移涉及两个数据迁移任务:
|
||||
1. **项目数据迁移**:从 `elearninglms.eln_boe_mixture_project` 迁移到 `boe_new.project_info`
|
||||
2. **项目报名数据迁移**:从 `elearninglms.eln_boe_mixture_project_enroll` 迁移到 `boe_base.boe_study_course`
|
||||
|
||||
---
|
||||
|
||||
## 二、任务1:项目数据迁移
|
||||
|
||||
### 2.1 迁移信息
|
||||
|
||||
- **源表**:`elearninglms.eln_boe_mixture_project`
|
||||
- **目标表**:`boe_new.project_info`
|
||||
- **迁移条件**:`is_deleted='0'` AND `program_name='社招新员工在线入职学习'`
|
||||
|
||||
### 2.2 字段映射关系
|
||||
|
||||
| 源表字段 | 目标表字段 | 说明 | 转换规则 |
|
||||
|---------|-----------|------|---------|
|
||||
| `kid` | - | 项目ID(varchar) | 不直接映射,目标表id为自增 |
|
||||
| `program_name` | `name` | 项目名称 | 直接映射 |
|
||||
| `program_desc` | `remark` | 项目描述/说明 | 直接映射 |
|
||||
| `theme_url` | `pic_url` | 封面图地址 | 直接映射 |
|
||||
| `start_time` / `open_start_time` | `begin_time` | 开始时间 | 优先使用 `open_start_time`,空则用 `start_time`,需转换为 timestamp |
|
||||
| `end_time` / `open_end_time` | `end_time` | 结束时间 | 优先使用 `open_end_time`,空则用 `end_time`,需转换为 timestamp |
|
||||
| `project_manager_id` | `manager_id` | 项目经理ID | 直接映射 |
|
||||
| `status` | `status` | 状态 | 需要转换:'0'→0(草稿), '1'→1(已发布), '2'→-1(已结束) |
|
||||
| `created_at` | `create_time` | 创建时间 | 需转换为 timestamp |
|
||||
| `created_by` | `create_id` | 创建人ID | 需转换为 bigint |
|
||||
| `updated_at` | `update_time` | 更新时间 | 需转换为 timestamp |
|
||||
| `updated_by` | `update_id` | 更新人ID | 需转换为 bigint |
|
||||
| `program_code` | `num_value` | 项目编号 | 直接映射 |
|
||||
| `program_desc` / `program_desc_nohtml` | `introduction` | 项目介绍 | 优先使用 `program_desc_nohtml` |
|
||||
|
||||
### 2.3 默认值设置
|
||||
|
||||
- `type`: 1(项目类别)
|
||||
- `new_type`: 2(学习项目)
|
||||
- `deleted`: 0(未删除)
|
||||
- `unlock_mode`: 1(自由模式)
|
||||
- `rank_flag`: 0(不显示积分排行榜)
|
||||
- `attach_switch`: 1(共享文档开启)
|
||||
- `bpm_flag`: 0(报名审批关闭)
|
||||
- `load_flag`: 0(下载成绩关闭)
|
||||
|
||||
### 2.4 注意事项
|
||||
|
||||
1. 目标表的 `id` 字段为自增主键,无需手动设置
|
||||
2. 时间字段需要从 int(时间戳)转换为 timestamp
|
||||
3. 状态字段需要根据源表的值进行映射转换
|
||||
4. 如果源表中存在多条符合条件的记录,需要确认是否全部迁移或仅迁移最新的一条
|
||||
|
||||
---
|
||||
|
||||
## 三、任务2:项目报名数据迁移
|
||||
|
||||
### 3.1 迁移信息
|
||||
|
||||
- **源表**:`elearninglms.eln_boe_mixture_project_enroll`
|
||||
- **目标表**:`boe_base.boe_study_course`
|
||||
- **迁移条件**:`program_id='123xxx'`(注意:实际执行时需要替换为真实的项目ID)
|
||||
- **重要说明**:**迁移全部报名数据,包括已删除的记录(is_deleted='1')**。已删除的记录在状态映射时会被标记为"终止"状态(status=8)
|
||||
|
||||
### 3.2 字段映射关系
|
||||
|
||||
| 源表字段 | 目标表字段 | 说明 | 转换规则 |
|
||||
|---------|-----------|------|---------|
|
||||
| `program_id` | `course_id` | 项目ID(作为课程ID) | 直接映射 |
|
||||
| `user_id` | `aid` | 学员ID | 直接映射 |
|
||||
| - | `last_score` | 学习成绩 | 初始设置为 NULL,后续需要从成绩表关联更新 |
|
||||
| `enroll_type` + `approved_state` | `status` | 完成状态 | 根据业务规则映射(见下方) |
|
||||
| `enroll_time` | `add_time` | 加入时间(报名时间) | 需转换为 datetime |
|
||||
| `enroll_time` | `start_time` | 开始学习时间 | 需转换为 datetime |
|
||||
|
||||
### 3.3 状态映射规则
|
||||
|
||||
根据 `boe_study_course` 表的 status 定义:
|
||||
- `STATUS_NOSTUDY = 1`(未开始学习)
|
||||
- `STATUS_STUDYING = 2`(学习中)
|
||||
- `STATUS_ABORTED = 8`(终止)
|
||||
- `STATUS_FINISH = 9`(学习完成)
|
||||
|
||||
**状态映射逻辑**:
|
||||
```sql
|
||||
CASE
|
||||
WHEN enroll_type = '1' AND approved_state = '1' AND is_deleted = '0' THEN 2 -- 报名成功且审批同意 → 学习中
|
||||
WHEN enroll_type = '3' THEN 8 -- 拒绝报名 → 终止
|
||||
WHEN cancel_state = '1' THEN 8 -- 取消审批同意 → 终止
|
||||
WHEN is_deleted = '1' THEN 8 -- 已删除 → 终止
|
||||
ELSE 1 -- 其他情况 → 未开始
|
||||
END AS status
|
||||
```
|
||||
|
||||
### 3.4 其他字段设置
|
||||
|
||||
- `course_type`: 需要根据项目类型设置(默认为项目类型对应的课程类型)
|
||||
- `course_name`: 需要关联项目表获取项目名称
|
||||
- `aname`: 需要关联用户表获取学员姓名
|
||||
- `source`: 根据 `enroll_method` 映射('self'→1, 'admin'→2, 'manager'→3)
|
||||
- `progress`: 初始设置为 0 或 NULL
|
||||
- `last_score`: 初始设置为 NULL,需要后续从成绩表更新
|
||||
|
||||
### 3.5 注意事项
|
||||
|
||||
1. **学习成绩(last_score)**:源表中没有直接的成绩字段,需要:
|
||||
- 方案A:从其他成绩表(如 `eln_ln_examination_result_user`)关联获取
|
||||
- 方案B:先设置为 NULL,后续通过业务逻辑更新
|
||||
|
||||
2. **完成状态(status)**:需要根据业务逻辑判断,当前映射规则仅供参考,实际使用时需要根据业务需求调整
|
||||
|
||||
3. **项目ID替换**:SQL中的 `'123xxx'` 需要替换为实际的项目ID
|
||||
|
||||
4. **数据去重**:确保 `(course_id, aid)` 组合的唯一性,避免重复插入
|
||||
|
||||
5. **关联查询**:可能需要关联用户表获取学员姓名等信息
|
||||
|
||||
6. **全部数据迁移**:本次迁移会包含所有符合条件的报名记录,包括已删除的记录。已删除的记录会根据 `is_deleted='1'` 映射为终止状态(status=8)
|
||||
|
||||
---
|
||||
|
||||
## 四、执行步骤
|
||||
|
||||
### 4.1 执行前准备
|
||||
|
||||
1. **备份数据**:执行迁移前,务必备份源表和目标表
|
||||
2. **验证条件**:确认迁移条件是否正确(特别是项目名称和项目ID)
|
||||
3. **数据检查**:检查源表中符合条件的数据量
|
||||
4. **环境确认**:确认目标数据库连接和权限
|
||||
|
||||
### 4.2 执行顺序
|
||||
|
||||
1. **先执行任务1**:迁移项目数据
|
||||
2. **获取新项目ID**:记录迁移后的项目ID(如果需要)
|
||||
3. **更新任务2的SQL**:将项目ID替换为实际值
|
||||
4. **执行任务2**:迁移项目报名数据
|
||||
|
||||
### 4.3 执行后验证
|
||||
|
||||
1. **数据量核对**:对比源表和目标表的记录数
|
||||
2. **关键字段验证**:抽查关键字段是否正确迁移
|
||||
3. **业务功能验证**:在系统中验证迁移后的数据是否正常
|
||||
|
||||
---
|
||||
|
||||
## 五、风险评估与回滚方案
|
||||
|
||||
### 5.1 风险点
|
||||
|
||||
1. **数据量**:如果数据量较大,可能影响系统性能
|
||||
2. **字段类型不匹配**:时间戳转换、状态值转换可能出错
|
||||
3. **数据完整性**:关联字段可能缺失或无效
|
||||
4. **业务逻辑**:状态映射规则可能与实际业务不符
|
||||
|
||||
### 5.2 回滚方案
|
||||
|
||||
1. **备份恢复**:使用备份数据恢复目标表
|
||||
2. **删除迁移数据**:根据迁移条件删除已迁移的数据
|
||||
3. **数据修复**:手动修复错误的数据
|
||||
|
||||
---
|
||||
|
||||
## 六、附录
|
||||
|
||||
### 6.1 相关表结构
|
||||
|
||||
- `elearninglms.eln_boe_mixture_project`:源项目表
|
||||
- `boe_new.project_info`:目标项目表
|
||||
- `elearninglms.eln_boe_mixture_project_enroll`:源报名表
|
||||
- `boe_base.boe_study_course`:目标课程学习表
|
||||
|
||||
### 6.2 状态值对照表
|
||||
|
||||
**项目状态映射**:
|
||||
- '0'(临时)→ 0(草稿)
|
||||
- '1'(正常)→ 1(已发布)
|
||||
- '2'(停用)→ -1(已结束)
|
||||
|
||||
**学习状态映射**:
|
||||
- 1:未开始学习
|
||||
- 2:学习中
|
||||
- 8:终止
|
||||
- 9:学习完成
|
||||
|
||||
---
|
||||
Reference in New Issue
Block a user