用户发件箱 查询逻辑优化

master
Alan 3 months ago
parent 52398db536
commit b1ccfb1c3e
  1. 9
      src/main/java/com/teaching/backend/controller/courses/CoursesController.java
  2. 2
      src/main/java/com/teaching/backend/model/entity/courses/StudentCourses.java
  3. 20
      src/main/java/com/teaching/backend/model/vo/message/CourseUserInfVO.java
  4. 36
      src/main/java/com/teaching/backend/model/vo/message/UserCheckMessageVO.java
  5. 3
      src/main/java/com/teaching/backend/service/courses/ICoursesService.java
  6. 157
      src/main/java/com/teaching/backend/service/impl/courses/CoursesServiceImpl.java
  7. 2
      src/main/java/com/teaching/backend/service/impl/courses/StudentCoursesServiceImpl.java
  8. 14
      src/main/java/com/teaching/backend/service/impl/message/MessagesServiceImpl.java
  9. 131
      src/main/java/com/teaching/backend/service/impl/message/UserInboxServiceImpl.java

@ -12,6 +12,7 @@ import com.teaching.backend.model.entity.umsAdmin.UmsStudent;
import com.teaching.backend.model.query.CourseQuery;
import com.teaching.backend.model.vo.courses.CoursesVO;
import com.teaching.backend.model.vo.courses.PersonalCenterStudentListVO;
import com.teaching.backend.model.vo.message.CourseUserInfVO;
import com.teaching.backend.service.courses.ICoursesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -138,4 +139,12 @@ public class CoursesController {
return CommonResult.success(umsStudentList);
}
@ApiOperation("根据用户id,查询与用户有关的课程列表,并在课程列表显示所有用户信息")
// @ValidateParams({"userId"})
@GetMapping("/page/courseusers")
public BaseResponse<List<CourseUserInfVO>> getUserInfByCourse(@RequestParam Long userId){
List<CourseUserInfVO> courseUsersInfList = coursesService.getUserInfByCourse(userId);
return ResultUtils.success(courseUsersInfList);
}
}

@ -33,7 +33,7 @@ public class StudentCourses implements Serializable {
/**
* 学生的userId
*/
private String student;
private Long student;
/**
* 课程id

@ -0,0 +1,20 @@
package com.teaching.backend.model.vo.message;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class CourseUserInfVO {
@ApiModelProperty(value = "课程id")
private String courseId;
@ApiModelProperty(value = "课程name")
private String courseName;
@ApiModelProperty(value = "与课程有关的用户信息集合")
private List<UserReadMessageTimeVO> usersInf;
}

@ -1,36 +0,0 @@
package com.teaching.backend.model.vo.message;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class UserCheckMessageVO {
@ApiModelProperty("id")
private Long id;
@ApiModelProperty("课程id")
private String courseId;
@ApiModelProperty("课程名称")
private String courseName;
@ApiModelProperty(value = "发件人id")
private Long senderId;
@ApiModelProperty(value = "发件人name")
private String senderName;
@ApiModelProperty(value = "消息标题")
private String title;
@ApiModelProperty(value = "消息内容")
private String content;
@ApiModelProperty(value = "发送时间")
private LocalDateTime sendTime;
@ApiModelProperty(value = "是否已读(0没有,1有)")
private Boolean isRead;
}

@ -11,6 +11,7 @@ import com.teaching.backend.model.entity.umsAdmin.UmsUser;
import com.teaching.backend.model.query.CourseQuery;
import com.teaching.backend.model.vo.courses.CoursesVO;
import com.teaching.backend.model.vo.courses.PersonalCenterStudentListVO;
import com.teaching.backend.model.vo.message.CourseUserInfVO;
import com.teaching.backend.model.vo.umsAdmin.UmsStudentVO;
import javax.servlet.http.HttpServletResponse;
@ -51,4 +52,6 @@ public interface ICoursesService extends IService<Courses> {
List<PersonalCenterStudentListVO> queryStudentList(String userId);
LinkedHashSet<UmsStudentManage> queryTeacherByStudentList(String userId);
List<CourseUserInfVO> getUserInfByCourse(Long userId);
}

@ -32,9 +32,12 @@ import com.teaching.backend.model.query.CourseQuery;
import com.teaching.backend.model.vo.courses.CourseObjectivesTreeVO;
import com.teaching.backend.model.vo.courses.CoursesVO;
import com.teaching.backend.model.vo.courses.PersonalCenterStudentListVO;
import com.teaching.backend.model.vo.message.CourseUserInfVO;
import com.teaching.backend.model.vo.message.UserReadMessageTimeVO;
import com.teaching.backend.model.vo.umsAdmin.UmsStudentVO;
import com.teaching.backend.service.courses.ICoursesService;
import com.teaching.backend.utils.CourseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -62,6 +65,7 @@ import static com.teaching.backend.constant.RoleConstants.TEACHER_ROLE;
* @since 2024-05-30
*/
@Service
@Slf4j
public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses> implements ICoursesService {
@Autowired
@ -382,7 +386,7 @@ public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses> impl
List<StudentCourses> studentUsernames = studentCoursesMapper.selectBatchSomeStudent(courseId);
List<CourseLearningRecord> courseLearningRecordList = new ArrayList<>();
for (StudentCourses studentUsername : studentUsernames) {
CourseLearningRecord courseLearningRecord = courseLearningRecordMapper.selectNewRecord(studentUsername.getStudent());
CourseLearningRecord courseLearningRecord = courseLearningRecordMapper.selectNewRecord(String.valueOf(studentUsername.getStudent()));
courseLearningRecordList.add(courseLearningRecord);
}
courseLearningRecordList = courseLearningRecordList.stream().sorted(Comparator.comparing(CourseLearningRecord::getTimes).reversed()).collect(Collectors.toList());
@ -396,6 +400,8 @@ public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses> impl
throw new BusinessException(400,"只有老师才有此功能");
}
@Override
public List<CoursesVO> getPagePageSize(int page, int pageSize) {
int startIndex = (page-1) * pageSize;
@ -610,6 +616,155 @@ public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses> impl
document.write(outputStream);
}
@Override
public List<CourseUserInfVO> getUserInfByCourse(Long userId) {
UmsUser umsUser = umsUserMapper.selectById(userId);
if (umsUser == null){
throw new BusinessException(ErrorCode.PARAMS_USER_NOTEXISTS);
}
int roleId = Integer.parseInt(umsUser.getRoleId());
List<CourseUserInfVO> courseUserInfVO;
switch (roleId) {
//教师
case 1:
courseUserInfVO = queryCourseUserForTeacher(userId);
break;
//学生
case 2:
courseUserInfVO = queryCourseUserForStudent(userId);
break;
default:
throw new BusinessException(ErrorCode.INVALID_ROLE);
}
return courseUserInfVO;
}
private List<CourseUserInfVO> queryCourseUserForTeacher(Long userId) {
// 查询所有与该教师相关的课程
List<Courses> teacherCoursesInf = coursesMapper.selectList(
new LambdaQueryWrapper<Courses>()
.apply("FIND_IN_SET({0}, teacher)", userId)
.select(Courses::getId, Courses::getTeacher)
);
List<CourseUserInfVO> courseUserInfVOS = new ArrayList<>();
for (Courses courses : teacherCoursesInf) {
CourseUserInfVO courseUserInfVO = new CourseUserInfVO();
List<UserReadMessageTimeVO> userReadMessageTimeVOS = new ArrayList<>();
courseUserInfVO.setCourseId(courses.getId());
// 查询与课程相关的所有学生
List<Long> studentIds = studentCoursesMapper.selectList(
new LambdaQueryWrapper<>(StudentCourses.class)
.eq(StudentCourses::getCourse, courses.getId())
).stream().map(StudentCourses::getStudent).collect(Collectors.toList());
// 为每个学生创建一个新的 UserReadMessageTimeVO 对象
for (Long studentId : studentIds) {
UmsStudent umsStudent = umsStudentMapper.selectOne(
new LambdaQueryWrapper<>(UmsStudent.class)
.eq(UmsStudent::getUserId, studentId)
.select(UmsStudent::getName)
);
if (umsStudent == null) {
log.error("用户不存在: {}",studentId);
throw new BusinessException(ErrorCode.PARAMS_USER_NOTEXISTS);
}
UserReadMessageTimeVO userReadMessageTimeVO = new UserReadMessageTimeVO(); // 在循环中创建新对象
userReadMessageTimeVO.setId(studentId);
userReadMessageTimeVO.setReceiverName(umsStudent.getName());
userReadMessageTimeVOS.add(userReadMessageTimeVO);
}
// 为每个教师创建一个新的 UserReadMessageTimeVO 对象
String[] teacherUserIds = courses.getTeacher().split(",");
for (String teacherId : teacherUserIds) {
UmsTeacher umsTeacher = umsTeacherMapper.selectOne(
new LambdaQueryWrapper<UmsTeacher>()
.eq(UmsTeacher::getUserId, teacherId)
);
if (umsTeacher == null) {
log.error("教师不存在: {}",teacherId);
throw new BusinessException(ErrorCode.PARAMS_USER_NOTEXISTS);
}
UserReadMessageTimeVO userReadMessageTimeVO = new UserReadMessageTimeVO(); // 在循环中创建新对象
userReadMessageTimeVO.setId(umsTeacher.getUserId());
userReadMessageTimeVO.setReceiverName(umsTeacher.getName());
userReadMessageTimeVOS.add(userReadMessageTimeVO);
}
courseUserInfVO.setUsersInf(userReadMessageTimeVOS);
courseUserInfVOS.add(courseUserInfVO);
}
return courseUserInfVOS;
}
private List<CourseUserInfVO> queryCourseUserForStudent(Long userId) {
// 查询学生所参与的所有课程
List<StudentCourses> studentCoursesList = studentCoursesMapper.selectList(
new LambdaQueryWrapper<StudentCourses>()
.eq(StudentCourses::getStudent, userId)
.select(StudentCourses::getCourse)
);
List<CourseUserInfVO> courseUserInfVOS = new ArrayList<>();
for (StudentCourses studentCourse : studentCoursesList) {
CourseUserInfVO courseUserInfVO = new CourseUserInfVO();
List<UserReadMessageTimeVO> userReadMessageTimeVOS = new ArrayList<>();
courseUserInfVO.setCourseId(studentCourse.getCourse());
// 查询与课程相关的所有学生
List<Long> studentIds = studentCoursesMapper.selectList(
new LambdaQueryWrapper<>(StudentCourses.class)
.eq(StudentCourses::getCourse, studentCourse.getCourse())
).stream().map(StudentCourses::getStudent).collect(Collectors.toList());
// 为每个学生创建一个新的 UserReadMessageTimeVO 对象
for (Long studentId : studentIds) {
UmsStudent umsStudent = umsStudentMapper.selectOne(
new LambdaQueryWrapper<>(UmsStudent.class)
.eq(UmsStudent::getUserId, studentId)
.select(UmsStudent::getName)
);
if (umsStudent == null) {
log.error("用户不存在: {}", studentId);
throw new BusinessException(ErrorCode.PARAMS_USER_NOTEXISTS);
}
UserReadMessageTimeVO userReadMessageTimeVO = new UserReadMessageTimeVO(); // 在循环中创建新对象
userReadMessageTimeVO.setId(studentId);
userReadMessageTimeVO.setReceiverName(umsStudent.getName());
userReadMessageTimeVOS.add(userReadMessageTimeVO);
}
// 查询与课程相关的所有教师
Courses course = coursesMapper.selectById(studentCourse.getCourse());
if (course != null) {
String[] teacherUserIds = course.getTeacher().split(",");
for (String teacherId : teacherUserIds) {
UmsTeacher umsTeacher = umsTeacherMapper.selectOne(
new LambdaQueryWrapper<UmsTeacher>()
.eq(UmsTeacher::getUserId, teacherId)
);
if (umsTeacher == null) {
log.error("教师不存在: {}", teacherId);
throw new BusinessException(ErrorCode.PARAMS_USER_NOTEXISTS);
}
UserReadMessageTimeVO userReadMessageTimeVO = new UserReadMessageTimeVO(); // 在循环中创建新对象
userReadMessageTimeVO.setId(umsTeacher.getUserId());
userReadMessageTimeVO.setReceiverName(umsTeacher.getName());
userReadMessageTimeVOS.add(userReadMessageTimeVO);
}
} else {
log.error("课程不存在: {}", studentCourse.getCourse());
throw new BusinessException(ErrorCode.PARAMS_COURSE_NOTEXISTS);
}
courseUserInfVO.setUsersInf(userReadMessageTimeVOS);
courseUserInfVOS.add(courseUserInfVO);
}
return courseUserInfVOS;
}
}

@ -53,7 +53,7 @@ public class StudentCoursesServiceImpl extends ServiceImpl<StudentCoursesMapper,
@Override
public String saveCoursesToStudents(StudentCoursesDTO studentCoursesDTO) {
String studentId = studentCoursesDTO.getStudent();
Long studentId = studentCoursesDTO.getStudent();
if (studentId == null || studentId.equals("")) {
throw new BusinessException(ErrorCode.STUDENT_NOT_EXIT);
}

@ -65,7 +65,7 @@ public class MessagesServiceImpl extends ServiceImpl<MessagesMapper, SysMessages
// 执行批量插入操作,并判断是否成功
boolean inboxInsertSuccess = userInboxMapper.insertBatchInBox(userInboxes);
if (!inboxInsertSuccess) {
throw new BusinessException(ErrorCode.OPERATION_ERROR,"收件箱数据插入失败!");
throw new BusinessException(ErrorCode.OPERATION_ERROR, "收件箱数据插入失败!");
}
// 5.更新或保存消息数据
@ -75,14 +75,22 @@ public class MessagesServiceImpl extends ServiceImpl<MessagesMapper, SysMessages
sysMessages.setSendTime(LocalDateTime.now());
sysMessages.setIsSend(true);
boolean messageSaveSuccess = updateById(sysMessages);
boolean messageSaveSuccess;
if (sysMessageDTO.getId() != null) {
messageSaveSuccess = updateById(sysMessages);
} else {
messageSaveSuccess = save(sysMessages); // 使用 save 方法插入新的记录
}
if (!messageSaveSuccess) {
throw new BusinessException(ErrorCode.OPERATION_ERROR,"消息保存失败!");
throw new BusinessException(ErrorCode.OPERATION_ERROR, "消息保存失败!");
}
return "消息发送成功!";
}
/**
* 发件箱的删除
*

@ -29,10 +29,7 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
/**
@ -138,73 +135,82 @@ public class UserInboxServiceImpl extends ServiceImpl<UserInboxMapper, UserInbox
.eq(SysMessages::getSenderId, messagesQuery.getUserId())
.eq(SysMessages::getIsSend, messagesQuery.getIsSend())
.eq(SysMessages::getIsDelete, messagesQuery.getIsDelete())
.select(SysMessages::getId,SysMessages::getCourseId,SysMessages::getTitle,SysMessages::getSendTime));
.select(SysMessages::getId, SysMessages::getCourseId, SysMessages::getTitle, SysMessages::getSendTime)
);
// 将Page<SysMessages>转换为PageDTO<SysMessageVO>
// PageDTO<SysMessageVO> messages = PageDTO.of(p, sysMessages -> {
// SysMessageVO vo = new SysMessageVO();
// BeanUtil.copyProperties(sysMessages, vo, CopyOptions.create().setIgnoreProperties(SysMessageVO::getSenderId));
// return vo;
// });
PageDTO<SysMessageVO> messages = PageDTO.of(p, SysMessageVO.class);
// 获取PageDTO中的SysMessageVO列表
List<SysMessageVO> messagesList = messages.getList();
if (messagesList.isEmpty()) {
throw new BusinessException(ErrorCode.MESSAGE_NO_EXIT);
}
// 遍历每个消息以填充附加数据
for (SysMessageVO sysMessageVO : messagesList) {
// 设置课程名称
if (!StringUtils.isEmpty(sysMessageVO.getCourseId())) {
Courses courses = coursesMapper.selectById(sysMessageVO.getCourseId());
if (courses != null) {
sysMessageVO.setCourseName(courses.getName());
}
}
// 批量查询课程名称
Set<String> courseIds = messagesList.stream()
.map(SysMessageVO::getCourseId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
// 查询UserInbox以获取当前消息的所有收件人数量
Long totalReceiverCount = userInboxMapper.selectCount(
new LambdaQueryWrapper<UserInbox>()
.eq(UserInbox::getMessageId, sysMessageVO.getId())
);
Map<String, String> courseNames = coursesMapper.selectBatchIds(courseIds).stream()
.collect(Collectors.toMap(Courses::getId, Courses::getName));
sysMessageVO.setUserNum(totalReceiverCount); // 设置收信总人数
// 批量查询所有用户收件箱数据
Set<Long> messageIds = messagesList.stream()
.map(SysMessageVO::getId)
.collect(Collectors.toSet());
// 查询前5个UserInbox以获取当前消息的收件人列表
List<UserInbox> userInboxes = userInboxMapper.selectList(
new LambdaQueryWrapper<UserInbox>()
.eq(UserInbox::getMessageId, sysMessageVO.getId())
.select(UserInbox::getReceiverId, UserInbox::getIsRead)
.last("LIMIT 5")
);
List<UserInbox> allUserInboxes = userInboxMapper.selectList(
new LambdaQueryWrapper<UserInbox>()
.in(UserInbox::getMessageId, messageIds)
.select(UserInbox::getMessageId, UserInbox::getReceiverId, UserInbox::getIsRead)
);
// 设置收件用户集合
List<UserReadMessageTimeVO> receiveUsers = userInboxes.stream().map(userInbox -> {
UserReadMessageTimeVO vo = new UserReadMessageTimeVO();
vo.setId(userInbox.getReceiverId());
// 将UserInbox数据按消息ID进行分组
Map<Long, List<UserInbox>> userInboxesByMessageId = allUserInboxes.stream()
.collect(Collectors.groupingBy(UserInbox::getMessageId));
UmsStudent umsStudent = umsStudentMapper.selectOne(
new LambdaQueryWrapper<UmsStudent>()
.eq(UmsStudent::getUserId, userInbox.getReceiverId()));
if (umsStudent == null) {
vo.setReceiverName(umsTeacherMapper.selectOne(
new LambdaQueryWrapper<UmsTeacher>()
.eq(UmsTeacher::getUserId, userInbox.getReceiverId())
).getName());
} else {
vo.setReceiverName(umsStudent.getName());
}
return vo;
}).collect(Collectors.toList());
sysMessageVO.setReceiveUsers(receiveUsers); // 设置收件人信息
// 缓存用户名称以避免重复查询
Map<Long, String> userNamesCache = new HashMap<>();
// 计算已读用户人数
long readUserCount = userInboxes.stream()
.filter(UserInbox::getIsRead)
.count();
sysMessageVO.setReadUserNum(readUserCount);
for (SysMessageVO sysMessageVO : messagesList) {
String courseId = sysMessageVO.getCourseId();
if (courseId != null) {
sysMessageVO.setCourseName(courseNames.get(courseId));
}
List<UserInbox> userInboxes = userInboxesByMessageId.get(sysMessageVO.getId());
if (userInboxes != null) {
sysMessageVO.setUserNum((long) userInboxes.size());
sysMessageVO.setReadUserNum(userInboxes.stream().filter(UserInbox::getIsRead).count());
List<UserReadMessageTimeVO> receiveUsers = userInboxes.stream().limit(5)
.map(userInbox -> {
UserReadMessageTimeVO vo = new UserReadMessageTimeVO();
Long receiverId = userInbox.getReceiverId();
vo.setId(receiverId);
// 获取或缓存接收者名称
String receiverName = userNamesCache.computeIfAbsent(receiverId, id -> {
UmsStudent umsStudent = umsStudentMapper.selectOne(
new LambdaQueryWrapper<UmsStudent>().eq(UmsStudent::getUserId, id)
);
if (umsStudent != null) {
return umsStudent.getName();
} else {
UmsTeacher umsTeacher = umsTeacherMapper.selectOne(
new LambdaQueryWrapper<UmsTeacher>().eq(UmsTeacher::getUserId, id)
);
return umsTeacher != null ? umsTeacher.getName() : null;
}
});
vo.setReceiverName(receiverName);
return vo;
}).collect(Collectors.toList());
sysMessageVO.setReceiveUsers(receiveUsers);
}
}
// 更新PageDTO中的消息列表并返回
@ -213,25 +219,12 @@ public class UserInboxServiceImpl extends ServiceImpl<UserInboxMapper, UserInbox
}
@Override
public SysMessageVO getMessageDetail(MessagesQuery messagesQuery) {
SysMessages sysMessage = messagesService.getById(messagesQuery.getMessageId());
SysMessageVO sysMessageVO = new SysMessageVO();
// BeanUtil.copyProperties(sysMessage, sysMessageVO);
sysMessageVO.setId(messagesQuery.getMessageId());
sysMessageVO.setContent(sysMessage.getContent());
// 设置课程名称 列表已查 前端自己去拿
// if (!StringUtils.isEmpty(sysMessage.getCourseId())) {
// Courses courses = coursesMapper.selectById(sysMessage.getCourseId());
// if (courses != null) {
// sysMessageVO.setCourseName(courses.getName());
// }
// }
sysMessageVO.setSenderId(messagesQuery.getUserId());
// 获取发件人信息
UmsTeacher umsTeacher = umsTeacherMapper.selectOne(

Loading…
Cancel
Save