feat: 知识库按点é赞数倒序

This commit is contained in:
moyangzhan 2024-04-17 00:42:57 +08:00
parent 131e8e38a0
commit 6112361fba
22 changed files with 288 additions and 34 deletions

View File

@ -1,5 +1,6 @@
package com.moyz.adi.chat.controller; package com.moyz.adi.chat.controller;
import com.moyz.adi.common.dto.ConvAddReq;
import com.moyz.adi.common.dto.ConvDto; import com.moyz.adi.common.dto.ConvDto;
import com.moyz.adi.common.dto.ConvEditReq; import com.moyz.adi.common.dto.ConvEditReq;
import com.moyz.adi.common.service.ConversationService; import com.moyz.adi.common.service.ConversationService;
@ -11,6 +12,7 @@ import jakarta.annotation.Resource;
import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min; import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@ -42,6 +44,11 @@ public class ConversationController {
return conversationService.detail(uuid, maxMsgUuid, pageSize); return conversationService.detail(uuid, maxMsgUuid, pageSize);
} }
@PostMapping("/add")
public ConvDto add(@RequestBody @Validated ConvAddReq convAddReq) {
return conversationService.add(convAddReq.getTitle(), convAddReq.getAiSystemMessage());
}
@PostMapping("/edit/{uuid}") @PostMapping("/edit/{uuid}")
public boolean edit(@PathVariable String uuid, @RequestBody ConvEditReq convEditReq) { public boolean edit(@PathVariable String uuid, @RequestBody ConvEditReq convEditReq) {
return conversationService.edit(uuid, convEditReq); return conversationService.edit(uuid, convEditReq);

View File

@ -1,12 +1,15 @@
package com.moyz.adi.chat.controller; package com.moyz.adi.chat.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moyz.adi.common.base.ThreadContext;
import com.moyz.adi.common.dto.KbEditReq; import com.moyz.adi.common.dto.KbEditReq;
import com.moyz.adi.common.dto.KbInfoResp;
import com.moyz.adi.common.entity.AdiFile; import com.moyz.adi.common.entity.AdiFile;
import com.moyz.adi.common.entity.KnowledgeBase; import com.moyz.adi.common.entity.KnowledgeBase;
import com.moyz.adi.common.service.KnowledgeBaseService; import com.moyz.adi.common.service.KnowledgeBaseService;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import jakarta.validation.constraints.Min; import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
@ -38,12 +41,12 @@ public class KnowledgeBaseController {
} }
@GetMapping("/searchMine") @GetMapping("/searchMine")
public Page<KnowledgeBase> searchMine(@RequestParam(defaultValue = "") String keyword, @RequestParam(defaultValue = "false") Boolean includeOthersPublic, @NotNull @Min(1) Integer currentPage, @NotNull @Min(10) Integer pageSize) { public Page<KbInfoResp> searchMine(@RequestParam(defaultValue = "") String keyword, @RequestParam(defaultValue = "false") Boolean includeOthersPublic, @NotNull @Min(1) Integer currentPage, @NotNull @Min(10) Integer pageSize) {
return knowledgeBaseService.searchMine(keyword, includeOthersPublic, currentPage, pageSize); return knowledgeBaseService.searchMine(keyword, includeOthersPublic, currentPage, pageSize);
} }
@GetMapping("/searchPublic") @GetMapping("/searchPublic")
public Page<KnowledgeBase> searchPublic(@RequestParam(defaultValue = "") String keyword, @NotNull @Min(1) Integer currentPage, @NotNull @Min(10) Integer pageSize) { public Page<KbInfoResp> searchPublic(@RequestParam(defaultValue = "") String keyword, @NotNull @Min(1) Integer currentPage, @NotNull @Min(10) Integer pageSize) {
return knowledgeBaseService.searchPublic(keyword, currentPage, pageSize); return knowledgeBaseService.searchPublic(keyword, currentPage, pageSize);
} }
@ -70,8 +73,8 @@ public class KnowledgeBaseController {
* *
* @return * @return
*/ */
@PostMapping("/star/{kbUuid}") @PostMapping("/star/toggle")
public boolean star(@PathVariable String kbUuid) { public boolean star(@RequestParam @NotBlank String kbUuid) {
return knowledgeBaseService.star(kbUuid); return knowledgeBaseService.toggleStar(ThreadContext.getCurrentUser(), kbUuid);
} }
} }

View File

@ -0,0 +1,27 @@
package com.moyz.adi.chat.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moyz.adi.common.base.ThreadContext;
import com.moyz.adi.common.dto.KbStarInfoResp;
import com.moyz.adi.common.service.KnowledgeBaseStarRecordService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "知识库点赞controller")
@Validated
@RequestMapping("/knowledge-base/star")
@RestController
public class KnowledgeBaseStarController {
@Resource
private KnowledgeBaseStarRecordService knowledgeBaseStarRecordService;
@GetMapping("/mine")
public Page<KbStarInfoResp> stars(int currentPage, int pageSize) {
return knowledgeBaseStarRecordService.listStarInfo(ThreadContext.getCurrentUser(), currentPage, pageSize);
}
}

View File

@ -61,9 +61,9 @@ public class UserController {
userService.logout(); userService.logout();
} }
@Operation(summary = "头像") @Operation(summary = "当前用户头像")
@GetMapping(value = "/avatar", produces = MediaType.IMAGE_JPEG_VALUE) @GetMapping(value = "/myAvatar", produces = MediaType.IMAGE_JPEG_VALUE)
public void avatar(HttpServletResponse response) { public void myAvatar(HttpServletResponse response) {
User user = ThreadContext.getCurrentUser(); User user = ThreadContext.getCurrentUser();
Avatar avatar = CatAvatar.newAvatarBuilder().build(); Avatar avatar = CatAvatar.newAvatarBuilder().build();
BufferedImage bufferedImage = avatar.create(user.getId()); BufferedImage bufferedImage = avatar.create(user.getId());
@ -74,4 +74,22 @@ public class UserController {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@Operation(summary = "用户头像")
@GetMapping(value = "/avatar/{uuid}", produces = MediaType.IMAGE_JPEG_VALUE)
public void avatar(@Validated @PathVariable String uuid, HttpServletResponse response){
User user = userService.getByUuid(uuid);
long userId = 0;
if(null != user){
userId = user.getId();
}
Avatar avatar = CatAvatar.newAvatarBuilder().build();
BufferedImage bufferedImage = avatar.create(userId);
//把图片写给浏览器
try {
ImageIO.write(bufferedImage, "png", response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} }

View File

@ -0,0 +1,14 @@
package com.moyz.adi.common.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import org.springframework.validation.annotation.Validated;
@Data
@Validated
public class ConvAddReq {
@NotBlank
private String title;
private String aiSystemMessage;
}

View File

@ -0,0 +1,14 @@
package com.moyz.adi.common.dto;
import lombok.Data;
@Data
public class KbInfoResp {
private String uuid;
private String title;
private String remark;
private Boolean isPublic;
private Integer starCount;
private String ownerUuid;
private String ownerName;
}

View File

@ -0,0 +1,9 @@
package com.moyz.adi.common.dto;
import lombok.Data;
@Data
public class KbStarInfoResp {
private String kbUuid;
private String kbTitle;
}

View File

@ -57,4 +57,8 @@ public class ConversationMessage extends BaseEntity {
@Schema(name = "上下文理解中携带的消息对数量(提示词及回复)") @Schema(name = "上下文理解中携带的消息对数量(提示词及回复)")
@TableField("understand_context_msg_pair_num") @TableField("understand_context_msg_pair_num")
private Integer understandContextMsgPairNum; private Integer understandContextMsgPairNum;
@Schema(name = "LLM name")
@TableField("language_model_name")
private String languageModelName;
} }

View File

@ -28,7 +28,11 @@ public class KnowledgeBase extends BaseEntity {
@Schema(title = "点赞数") @Schema(title = "点赞数")
@TableField("star_count") @TableField("star_count")
private Long starCount; private Integer starCount;
@Schema(title = "所属人uuid")
@TableField("owner_uuid")
private String ownerUuid;
@Schema(title = "所属人id") @Schema(title = "所属人id")
@TableField("owner_id") @TableField("owner_id")

View File

@ -0,0 +1,29 @@
package com.moyz.adi.common.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@TableName("adi_knowledge_base_star_record")
@Schema(title = "知识库点赞记录实体", description = "知识库点赞记录表")
public class KnowledgeBaseStarRecord extends BaseEntity {
@Schema(title = "Knowledge base id")
@TableField("kb_id")
private Long kbId;
@Schema(title = "Knowledge base uuid")
@TableField("kb_uuid")
private String kbUuid;
@Schema(title = "User id")
@TableField("user_id")
private Long userId;
@Schema(title = "User uuid")
@TableField("user_uuid")
private String userUuid;
}

View File

@ -22,6 +22,7 @@ public enum ErrorEnum {
A_UPLOAD_FAIL("A0018", "上传失败"), A_UPLOAD_FAIL("A0018", "上传失败"),
A_QA_ASK_LIMIT("A0019", "请求次数太多"), A_QA_ASK_LIMIT("A0019", "请求次数太多"),
A_QA_ITEM_LIMIT("A0020", "知识点生成已超额度"), A_QA_ITEM_LIMIT("A0020", "知识点生成已超额度"),
A_CONVERSATION_EXIST("A0021", "对话已存在"),
B_UNCAUGHT_ERROR("B0001", "未捕捉异常"), B_UNCAUGHT_ERROR("B0001", "未捕捉异常"),
B_COMMON_ERROR("B0002", "业务出错"), B_COMMON_ERROR("B0002", "业务出错"),
B_GLOBAL_ERROR("B0003", "全局异常"), B_GLOBAL_ERROR("B0003", "全局异常"),

View File

@ -0,0 +1,9 @@
package com.moyz.adi.common.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.moyz.adi.common.entity.KnowledgeBaseStarRecord;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface KnowledgeBaseStarRecordMapper extends BaseMapper<KnowledgeBaseStarRecord> {
}

View File

@ -43,7 +43,7 @@ public class GoogleSearchEngine extends AbstractSearchEngine<GoogleSetting> {
result.setErrorMessage(googleSearchResp.getError().getMessage()); result.setErrorMessage(googleSearchResp.getError().getMessage());
} else { } else {
log.info("google response:{}", resp); log.info("google response:{}", resp);
items = MPPageUtil.convertTo(googleSearchResp.getItems(), SearchResultItem.class); items = MPPageUtil.convertToList(googleSearchResp.getItems(), SearchResultItem.class);
} }
} }
} catch (Exception e) { } catch (Exception e) {

View File

@ -14,7 +14,6 @@ import com.moyz.adi.common.util.BizPager;
import com.moyz.adi.common.util.MPPageUtil; import com.moyz.adi.common.util.MPPageUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
@ -45,7 +44,7 @@ public class AiSearchRecordService extends ServiceImpl<AiSearchRecordMapper, AiS
} }
AiSearchResp result = new AiSearchResp(); AiSearchResp result = new AiSearchResp();
BizPager.listByMaxId(maxId, wrapper, this, AiSearchRecord::getId, (recordList, minId) -> { BizPager.listByMaxId(maxId, wrapper, this, AiSearchRecord::getId, (recordList, minId) -> {
List<AiSearchRecordResp> list = MPPageUtil.convertTo(recordList, AiSearchRecordResp.class); List<AiSearchRecordResp> list = MPPageUtil.convertToList(recordList, AiSearchRecordResp.class);
list.forEach(item -> { list.forEach(item -> {
if(null == item.getSearchEngineResp()){ if(null == item.getSearchEngineResp()){
SearchEngineResp searchEngineResp = new SearchEngineResp(); SearchEngineResp searchEngineResp = new SearchEngineResp();

View File

@ -228,6 +228,7 @@ public class ConversationMessageService extends ServiceImpl<ConversationMessageM
aiAnswer.setTokens(answerMeta.getTokens()); aiAnswer.setTokens(answerMeta.getTokens());
aiAnswer.setParentMessageId(promptMsg.getId()); aiAnswer.setParentMessageId(promptMsg.getId());
aiAnswer.setSecretKeyType(secretKeyType); aiAnswer.setSecretKeyType(secretKeyType);
aiAnswer.setLanguageModelName(askReq.getModelName());
baseMapper.insert(aiAnswer); baseMapper.insert(aiAnswer);
calcTodayCost(user, conversation, questionMeta, answerMeta); calcTodayCost(user, conversation, questionMeta, answerMeta);

View File

@ -20,6 +20,7 @@ import org.springframework.stereotype.Service;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.moyz.adi.common.enums.ErrorEnum.A_CONVERSATION_EXIST;
import static com.moyz.adi.common.enums.ErrorEnum.A_CONVERSATION_NOT_EXIST; import static com.moyz.adi.common.enums.ErrorEnum.A_CONVERSATION_NOT_EXIST;
@Slf4j @Slf4j
@ -39,7 +40,7 @@ public class ConversationService extends ServiceImpl<ConversationMapper, Convers
.orderByDesc(Conversation::getId) .orderByDesc(Conversation::getId)
.last("limit " + sysConfigService.getConversationMaxNum()) .last("limit " + sysConfigService.getConversationMaxNum())
.list(); .list();
return MPPageUtil.convertTo(list, ConvDto.class); return MPPageUtil.convertToList(list, ConvDto.class);
} }
/** /**
@ -80,7 +81,7 @@ public class ConversationService extends ServiceImpl<ConversationMapper, Convers
return b; return b;
}).getUuid(); }).getUuid();
//Wrap question content //Wrap question content
List<ConvMsgResp> userMessages = MPPageUtil.convertTo(questions, ConvMsgResp.class); List<ConvMsgResp> userMessages = MPPageUtil.convertToList(questions, ConvMsgResp.class);
ConvMsgListResp result = new ConvMsgListResp(minUuid, userMessages); ConvMsgListResp result = new ConvMsgListResp(minUuid, userMessages);
//Wrap answer content //Wrap answer content
@ -94,7 +95,7 @@ public class ConversationService extends ServiceImpl<ConversationMapper, Convers
//Fill AI answer to the request of user //Fill AI answer to the request of user
result.getMsgList().forEach(item -> { result.getMsgList().forEach(item -> {
List<ConvMsgResp> children = MPPageUtil.convertTo(idToMessages.get(item.getId()), ConvMsgResp.class); List<ConvMsgResp> children = MPPageUtil.convertToList(idToMessages.get(item.getId()), ConvMsgResp.class);
if (children.size() > 1) { if (children.size() > 1) {
children = children.stream().sorted(Comparator.comparing(ConvMsgResp::getCreateTime).reversed()).collect(Collectors.toList()); children = children.stream().sorted(Comparator.comparing(ConvMsgResp::getCreateTime).reversed()).collect(Collectors.toList());
} }
@ -122,6 +123,27 @@ public class ConversationService extends ServiceImpl<ConversationMapper, Convers
return this.lambdaQuery().eq(Conversation::getUuid, uuid).oneOpt().orElse(null); return this.lambdaQuery().eq(Conversation::getUuid, uuid).oneOpt().orElse(null);
} }
public ConvDto add(String title, String systemMessage) {
Conversation conversation = this.lambdaQuery()
.eq(Conversation::getUserId, ThreadContext.getCurrentUserId())
.eq(Conversation::getTitle, title)
.eq(Conversation::getIsDeleted, false)
.one();
if (null != conversation) {
throw new BaseException(A_CONVERSATION_EXIST);
}
String uuid = UUID.randomUUID().toString().replace("-", "");
Conversation one = new Conversation();
one.setUuid(uuid);
one.setTitle(title);
one.setAiSystemMessage(systemMessage);
one.setUserId(ThreadContext.getCurrentUserId());
baseMapper.insert(one);
Conversation conv = this.lambdaQuery().eq(Conversation::getUuid, uuid).one();
return MPPageUtil.convertTo(conv, ConvDto.class);
}
public boolean edit(String uuid, ConvEditReq convEditReq) { public boolean edit(String uuid, ConvEditReq convEditReq) {
Conversation conversation = this.lambdaQuery() Conversation conversation = this.lambdaQuery()
.eq(Conversation::getUuid, uuid) .eq(Conversation::getUuid, uuid)

View File

@ -16,7 +16,7 @@ public class KnowledgeBaseEmbeddingService extends ServiceImpl<KnowledgeBaseEmbe
public Page<KbItemEmbeddingDto> listByItemUuid(String kbItemUuid, int currentPage, int pageSize) { public Page<KbItemEmbeddingDto> listByItemUuid(String kbItemUuid, int currentPage, int pageSize) {
Page<KnowledgeBaseEmbedding> sourcePage = baseMapper.selectByItemUuid(new Page<>(currentPage, pageSize), kbItemUuid); Page<KnowledgeBaseEmbedding> sourcePage = baseMapper.selectByItemUuid(new Page<>(currentPage, pageSize), kbItemUuid);
Page<KbItemEmbeddingDto> result = new Page<>(); Page<KbItemEmbeddingDto> result = new Page<>();
MPPageUtil.convertTo(sourcePage, result, KbItemEmbeddingDto.class, (source, target) -> { MPPageUtil.convertToPage(sourcePage, result, KbItemEmbeddingDto.class, (source, target) -> {
target.setEmbedding(source.getEmbedding().toArray()); target.setEmbedding(source.getEmbedding().toArray());
return target; return target;
}); });

View File

@ -9,6 +9,7 @@ import com.moyz.adi.common.base.ThreadContext;
import com.moyz.adi.common.cosntant.AdiConstant; import com.moyz.adi.common.cosntant.AdiConstant;
import com.moyz.adi.common.cosntant.RedisKeyConstant; import com.moyz.adi.common.cosntant.RedisKeyConstant;
import com.moyz.adi.common.dto.KbEditReq; import com.moyz.adi.common.dto.KbEditReq;
import com.moyz.adi.common.dto.KbInfoResp;
import com.moyz.adi.common.dto.QAReq; import com.moyz.adi.common.dto.QAReq;
import com.moyz.adi.common.entity.*; import com.moyz.adi.common.entity.*;
import com.moyz.adi.common.exception.BaseException; import com.moyz.adi.common.exception.BaseException;
@ -16,6 +17,7 @@ import com.moyz.adi.common.helper.SSEEmitterHelper;
import com.moyz.adi.common.mapper.KnowledgeBaseMapper; import com.moyz.adi.common.mapper.KnowledgeBaseMapper;
import com.moyz.adi.common.util.BizPager; import com.moyz.adi.common.util.BizPager;
import com.moyz.adi.common.util.LocalDateTimeUtil; import com.moyz.adi.common.util.LocalDateTimeUtil;
import com.moyz.adi.common.util.MPPageUtil;
import com.moyz.adi.common.vo.SseAskParams; import com.moyz.adi.common.vo.SseAskParams;
import dev.langchain4j.data.document.Document; import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.parser.TextDocumentParser; import dev.langchain4j.data.document.parser.TextDocumentParser;
@ -33,6 +35,7 @@ import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@ -65,6 +68,9 @@ public class KnowledgeBaseService extends ServiceImpl<KnowledgeBaseMapper, Knowl
@Resource @Resource
private KnowledgeBaseQaRecordService knowledgeBaseQaRecordService; private KnowledgeBaseQaRecordService knowledgeBaseQaRecordService;
@Resource
private KnowledgeBaseStarRecordService knowledgeBaseStarRecordService;
@Resource @Resource
private FileService fileService; private FileService fileService;
@ -194,16 +200,20 @@ public class KnowledgeBaseService extends ServiceImpl<KnowledgeBaseMapper, Knowl
return true; return true;
} }
public Page<KnowledgeBase> searchMine(String keyword, Boolean includeOthersPublic, Integer currentPage, Integer pageSize) { public Page<KbInfoResp> searchMine(String keyword, Boolean includeOthersPublic, Integer currentPage, Integer pageSize) {
Page<KbInfoResp> result = new Page<>();
User user = ThreadContext.getCurrentUser(); User user = ThreadContext.getCurrentUser();
Page<KnowledgeBase> knowledgeBasePage;
if (user.getIsAdmin()) { if (user.getIsAdmin()) {
return baseMapper.searchByAdmin(new Page<>(currentPage, pageSize), keyword); knowledgeBasePage = baseMapper.searchByAdmin(new Page<>(currentPage, pageSize), keyword);
} else { } else {
return baseMapper.searchByUser(new Page<>(currentPage, pageSize), user.getId(), keyword, includeOthersPublic); knowledgeBasePage = baseMapper.searchByUser(new Page<>(currentPage, pageSize), user.getId(), keyword, includeOthersPublic);
} }
return MPPageUtil.convertToPage(knowledgeBasePage, result, KbInfoResp.class, null);
} }
public Page<KnowledgeBase> searchPublic(String keyword, Integer currentPage, Integer pageSize) { public Page<KbInfoResp> searchPublic(String keyword, Integer currentPage, Integer pageSize) {
Page<KbInfoResp> result = new Page<>();
LambdaQueryWrapper<KnowledgeBase> wrapper = new LambdaQueryWrapper(); LambdaQueryWrapper<KnowledgeBase> wrapper = new LambdaQueryWrapper();
wrapper.eq(KnowledgeBase::getIsPublic, true); wrapper.eq(KnowledgeBase::getIsPublic, true);
wrapper.eq(KnowledgeBase::getIsDeleted, false); wrapper.eq(KnowledgeBase::getIsDeleted, false);
@ -211,7 +221,8 @@ public class KnowledgeBaseService extends ServiceImpl<KnowledgeBaseMapper, Knowl
wrapper.like(KnowledgeBase::getTitle, keyword); wrapper.like(KnowledgeBase::getTitle, keyword);
} }
wrapper.orderByDesc(KnowledgeBase::getStarCount, KnowledgeBase::getUpdateTime); wrapper.orderByDesc(KnowledgeBase::getStarCount, KnowledgeBase::getUpdateTime);
return baseMapper.selectPage(new Page<>(currentPage, pageSize), wrapper); Page<KnowledgeBase> knowledgeBasePage = baseMapper.selectPage(new Page<>(currentPage, pageSize), wrapper);
return MPPageUtil.convertToPage(knowledgeBasePage, result, KbInfoResp.class, null);
} }
public boolean softDelete(String uuid) { public boolean softDelete(String uuid) {
@ -247,12 +258,42 @@ public class KnowledgeBaseService extends ServiceImpl<KnowledgeBaseMapper, Knowl
return sseEmitter; return sseEmitter;
} }
public boolean star(String kbUuid) { /**
KnowledgeBase knowledgeBase = getOrThrow(kbUuid); * Star or unstar
return ChainWrappers.lambdaUpdateChain(baseMapper) *
* @param user
* @param kbUuid
* @return true:star;false:unstar
*/
@Transactional
public boolean toggleStar(User user, String kbUuid) {
KnowledgeBase knowledgeBase = _this.getOrThrow(kbUuid);
boolean star;
KnowledgeBaseStarRecord oldRecord = knowledgeBaseStarRecordService.getRecord(user.getId(), kbUuid);
if (null == oldRecord) {
KnowledgeBaseStarRecord starRecord = new KnowledgeBaseStarRecord();
starRecord.setUserId(user.getId());
starRecord.setUserUuid(user.getUuid());
starRecord.setKbId(knowledgeBase.getId());
starRecord.setKbUuid(kbUuid);
knowledgeBaseStarRecordService.save(starRecord);
star = true;
} else {
//Deleted means unstar
knowledgeBaseStarRecordService.lambdaUpdate()
.eq(KnowledgeBaseStarRecord::getId, oldRecord.getId())
.set(KnowledgeBaseStarRecord::getIsDeleted, !oldRecord.getIsDeleted())
.update();
star = oldRecord.getIsDeleted();
}
int starCount = star ? knowledgeBase.getStarCount() + 1 : knowledgeBase.getStarCount() - 1;
ChainWrappers.lambdaUpdateChain(baseMapper)
.eq(KnowledgeBase::getId, knowledgeBase.getId()) .eq(KnowledgeBase::getId, knowledgeBase.getId())
.set(KnowledgeBase::getStarCount, knowledgeBase.getStarCount() + 1) .set(KnowledgeBase::getStarCount, starCount)
.update(); .update();
return star;
} }
/** /**

View File

@ -0,0 +1,46 @@
package com.moyz.adi.common.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.moyz.adi.common.dto.KbStarInfoResp;
import com.moyz.adi.common.entity.KnowledgeBaseStarRecord;
import com.moyz.adi.common.entity.User;
import com.moyz.adi.common.mapper.KnowledgeBaseStarRecordMapper;
import com.moyz.adi.common.util.MPPageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class KnowledgeBaseStarRecordService extends ServiceImpl<KnowledgeBaseStarRecordMapper, KnowledgeBaseStarRecord> {
public boolean isStarred(Long userId, String kbUuid) {
return ChainWrappers.lambdaQueryChain(baseMapper)
.eq(KnowledgeBaseStarRecord::getUserId, userId)
.eq(KnowledgeBaseStarRecord::getKbUuid, kbUuid)
.eq(KnowledgeBaseStarRecord::getIsDeleted, false)
.exists();
}
public KnowledgeBaseStarRecord getRecord(long userId, String kbUuid){
return ChainWrappers.lambdaQueryChain(baseMapper)
.eq(KnowledgeBaseStarRecord::getUserId, userId)
.eq(KnowledgeBaseStarRecord::getKbUuid, kbUuid)
.oneOpt()
.orElse(null);
}
public Page<KbStarInfoResp> listStarInfo(User user, int currentPage, int pageSize) {
LambdaQueryWrapper<KnowledgeBaseStarRecord> wrapper = new LambdaQueryWrapper();
wrapper.eq(KnowledgeBaseStarRecord::getIsDeleted, false);
wrapper.eq(KnowledgeBaseStarRecord::getUserId, user.getId());
wrapper.orderByDesc(KnowledgeBaseStarRecord::getId);
Page<KnowledgeBaseStarRecord> list = baseMapper.selectPage(new Page<>(currentPage, pageSize), wrapper);
Page<KbStarInfoResp> result = new Page<>();
return MPPageUtil.convertToPage(list, result, KbStarInfoResp.class);
}
}

View File

@ -26,7 +26,7 @@ public class PromptService extends ServiceImpl<PromptMapper, Prompt> {
public List<PromptDto> getAll(long userId) { public List<PromptDto> getAll(long userId) {
List<Prompt> prompts = this.lambdaQuery().eq(Prompt::getUserId, userId).eq(Prompt::getIsDeleted, false).list(); List<Prompt> prompts = this.lambdaQuery().eq(Prompt::getUserId, userId).eq(Prompt::getIsDeleted, false).list();
return MPPageUtil.convertTo(prompts, PromptDto.class); return MPPageUtil.convertToList(prompts, PromptDto.class);
} }
public Page<PromptDto> search(String keyword, int currentPage, int pageSize) { public Page<PromptDto> search(String keyword, int currentPage, int pageSize) {
@ -43,7 +43,7 @@ public class PromptService extends ServiceImpl<PromptMapper, Prompt> {
.eq(Prompt::getIsDeleted, false) .eq(Prompt::getIsDeleted, false)
.page(new Page<>(currentPage, pageSize)); .page(new Page<>(currentPage, pageSize));
} }
return MPPageUtil.convertTo(promptPage, new Page<>(), PromptDto.class); return MPPageUtil.convertToPage(promptPage, new Page<>(), PromptDto.class);
} }
public List<PromptDto> autocomplete(String keyword) { public List<PromptDto> autocomplete(String keyword) {
@ -62,7 +62,7 @@ public class PromptService extends ServiceImpl<PromptMapper, Prompt> {
.last("limit 10") .last("limit 10")
.list(); .list();
} }
return MPPageUtil.convertTo(promptPage, PromptDto.class); return MPPageUtil.convertToList(promptPage, PromptDto.class);
} }
public PromptListResp listByMinUpdateTime(LocalDateTime minUpdateTime) { public PromptListResp listByMinUpdateTime(LocalDateTime minUpdateTime) {
@ -88,7 +88,7 @@ public class PromptService extends ServiceImpl<PromptMapper, Prompt> {
} }
return b; return b;
}).get().getUpdateTime(); }).get().getUpdateTime();
List<PromptDto> promptDtos = MPPageUtil.convertTo(list, PromptDto.class); List<PromptDto> promptDtos = MPPageUtil.convertToList(list, PromptDto.class);
resp.setMaxUpdateTime(LocalDateTimeUtil.format(maxUpdateTime)); resp.setMaxUpdateTime(LocalDateTimeUtil.format(maxUpdateTime));
resp.setPrompts(promptDtos); resp.setPrompts(promptDtos);
return resp; return resp;
@ -170,6 +170,6 @@ public class PromptService extends ServiceImpl<PromptMapper, Prompt> {
.like(Prompt::getAct, keyword) .like(Prompt::getAct, keyword)
.last("limit 10") .last("limit 10")
.list(); .list();
return MPPageUtil.convertTo(prompts, PromptDto.class); return MPPageUtil.convertToList(prompts, PromptDto.class);
} }
} }

View File

@ -314,4 +314,10 @@ public class UserService extends ServiceImpl<UserMapper, User> {
adiMailSender.send("欢迎注册AIDeepIn", "激活链接(" + AdiConstant.AUTH_ACTIVE_CODE_EXPIRE + "小时内有效):" + backendUrl + "/auth/active?code=" + activeCode, email); adiMailSender.send("欢迎注册AIDeepIn", "激活链接(" + AdiConstant.AUTH_ACTIVE_CODE_EXPIRE + "小时内有效):" + backendUrl + "/auth/active?code=" + activeCode, email);
} }
public User getByUuid(String uuid){
return ChainWrappers.lambdaQueryChain(baseMapper)
.eq(User::getUuid, uuid)
.one();
}
} }

View File

@ -14,11 +14,11 @@ import java.util.function.BiFunction;
@Slf4j @Slf4j
public class MPPageUtil { public class MPPageUtil {
public static <T, U> Page<U> convertTo(Page<T> source, Page<U> target, Class<U> targetRecordClass) { public static <T, U> Page<U> convertToPage(Page<T> source, Page<U> target, Class<U> targetRecordClass) {
return MPPageUtil.convertTo(source, target, targetRecordClass, null); return MPPageUtil.convertToPage(source, target, targetRecordClass, null);
} }
public static <T, U> Page<U> convertTo(Page<T> source, Page<U> target, Class<U> targetRecordClass, BiFunction<T, U, U> biFunction) { public static <T, U> Page<U> convertToPage(Page<T> source, Page<U> target, Class<U> targetRecordClass, BiFunction<T, U, U> biFunction) {
BeanUtils.copyProperties(source, target); BeanUtils.copyProperties(source, target);
List<U> records = new ArrayList<>(); List<U> records = new ArrayList<>();
target.setRecords(records); target.setRecords(records);
@ -40,7 +40,7 @@ public class MPPageUtil {
return target; return target;
} }
public static <T, U> List<U> convertTo(List<T> source, Class<U> targetRecordClass) { public static <T, U> List<U> convertToList(List<T> source, Class<U> targetRecordClass) {
if (CollectionUtils.isEmpty(source)) { if (CollectionUtils.isEmpty(source)) {
return Collections.emptyList(); return Collections.emptyList();
} }