Commit cd112ea9 authored by wujipeng's avatar wujipeng
Browse files

init

parents
Pipeline #346 canceled with stages
package com.platform.business.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.platform.business.mapper.TheoreticalPracticeStudentQuestionBankMapper;
import com.platform.business.model.dto.TheoreticalPracticeStudentQuestionBankDTO;
import com.platform.business.model.entity.TheoreticalPracticeStudentQuestionBankEntity;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TheoreticalPracticeStudentQuestionBankVO;
import com.platform.business.service.TheoreticalPracticeStudentQuestionBankService;
import com.platform.business.service.UserService;
import com.platform.business.utils.ChineseNumberUtils;
import com.platform.business.utils.JwtTokenUtil;
import com.platform.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class TheoreticalPracticeStudentQuestionBankServiceImpl extends ServiceImpl<TheoreticalPracticeStudentQuestionBankMapper,
TheoreticalPracticeStudentQuestionBankEntity> implements TheoreticalPracticeStudentQuestionBankService {
@Resource
private UserService userService;
@Resource
private JwtTokenUtil jwtTokenUtil;
@Resource
private HttpServletRequest request;
@Override
public List<String> groupByStudentId() {
return baseMapper.groupByStudentId();
}
@Override
public List<TheoreticalPracticeStudentQuestionBankVO> onePage(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO) {
List<TheoreticalPracticeStudentQuestionBankEntity> all = list(new LambdaQueryWrapper<TheoreticalPracticeStudentQuestionBankEntity>()
.eq(TheoreticalPracticeStudentQuestionBankEntity::getStudentId, theoreticalPracticeStudentQuestionBankDTO.getStudentId()));
//转换成以firstLevelName分组的map
Map<String, List<TheoreticalPracticeStudentQuestionBankEntity>> groupedMap = all.stream()
.collect(Collectors.groupingBy(TheoreticalPracticeStudentQuestionBankEntity::getFirstLevelName));
PageHelper.startPage(theoreticalPracticeStudentQuestionBankDTO.getPageNum(), theoreticalPracticeStudentQuestionBankDTO.getPageSize());
List<TheoreticalPracticeStudentQuestionBankVO> result = baseMapper.onePage(theoreticalPracticeStudentQuestionBankDTO);
PageHelper.clearPage();
for (TheoreticalPracticeStudentQuestionBankVO theoreticalPracticeStudentQuestionBankVO : result) {
theoreticalPracticeStudentQuestionBankVO.setChapter(ChineseNumberUtils.toChinese(Integer.parseInt(theoreticalPracticeStudentQuestionBankVO.getChapter())));
if (groupedMap.containsKey(theoreticalPracticeStudentQuestionBankVO.getFirstLevelName())) {
List<TheoreticalPracticeStudentQuestionBankVO> subset = new ArrayList<>();
analysisSubset(subset, groupedMap.get(theoreticalPracticeStudentQuestionBankVO.getFirstLevelName()));
theoreticalPracticeStudentQuestionBankVO.setSubset(subset);
}
}
return result;
}
private void analysisSubset(List<TheoreticalPracticeStudentQuestionBankVO> subset, List<TheoreticalPracticeStudentQuestionBankEntity> data) {
//判断题总数
int judgmentTotal = 0;
//判断题已完成数
int judgmentCompleted = 0;
//判断题正确数
int judgmentAccuracy = 0;
//单选题总数
int singleTotal = 0;
//单选题已完成数
int singleCompleted = 0;
//单选题正确数
int singleAccuracy = 0;
//多选题总数
int multipleTotal = 0;
//多选题已完成数
int multipleCompleted = 0;
//多选题正确数
int multipleAccuracy = 0;
for (TheoreticalPracticeStudentQuestionBankEntity entity : data) {
if ("判断题".equals(entity.getType())) {
judgmentTotal++;
if (!StringUtils.isEmpty(entity.getActualChoice())) {
judgmentCompleted++;
}
if (!ObjectUtils.isEmpty(entity.getResult()) && entity.getResult()) {
judgmentAccuracy++;
}
} else if ("单选题".equals(entity.getType())) {
singleTotal++;
if (!StringUtils.isEmpty(entity.getActualChoice())) {
singleCompleted++;
}
if (!ObjectUtils.isEmpty(entity.getResult()) && entity.getResult()) {
singleAccuracy++;
}
} else if ("多选题".equals(entity.getType())) {
multipleTotal++;
if (!StringUtils.isEmpty(entity.getActualChoice())) {
multipleCompleted++;
}
if (!ObjectUtils.isEmpty(entity.getResult()) && entity.getResult()) {
multipleAccuracy++;
}
}
}
subset.add(TheoreticalPracticeStudentQuestionBankVO.builder()
.name("判断题")
.total(judgmentTotal)
.completed(judgmentCompleted)
.accuracyRate(judgmentTotal == 0 ? 0 : 100 * judgmentAccuracy / judgmentTotal)
.build());
subset.add(TheoreticalPracticeStudentQuestionBankVO.builder()
.name("单选题")
.total(singleTotal)
.completed(singleCompleted)
.accuracyRate(singleTotal == 0 ? 0 : 100 * singleAccuracy / singleTotal)
.build());
subset.add(TheoreticalPracticeStudentQuestionBankVO.builder()
.name("多选题")
.total(multipleTotal)
.completed(multipleCompleted)
.accuracyRate(multipleTotal == 0 ? 0 : 100 * multipleAccuracy / multipleTotal)
.build());
}
@Override
public List<TheoreticalPracticeStudentQuestionBankVO> twoPage(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO) {
List<TheoreticalPracticeStudentQuestionBankEntity> all = list(new LambdaQueryWrapper<TheoreticalPracticeStudentQuestionBankEntity>()
.eq(TheoreticalPracticeStudentQuestionBankEntity::getStudentId, theoreticalPracticeStudentQuestionBankDTO.getStudentId())
.eq(TheoreticalPracticeStudentQuestionBankEntity::getFirstLevelName, theoreticalPracticeStudentQuestionBankDTO.getFirstLevelName()));
//转换成以secondLevelName分组的map
Map<String, List<TheoreticalPracticeStudentQuestionBankEntity>> groupedMap = all.stream()
.collect(Collectors.groupingBy(TheoreticalPracticeStudentQuestionBankEntity::getSecondLevelName));
PageHelper.startPage(theoreticalPracticeStudentQuestionBankDTO.getPageNum(), theoreticalPracticeStudentQuestionBankDTO.getPageSize());
List<TheoreticalPracticeStudentQuestionBankVO> result = baseMapper.twoPage(theoreticalPracticeStudentQuestionBankDTO);
PageHelper.clearPage();
for (TheoreticalPracticeStudentQuestionBankVO theoreticalPracticeStudentQuestionBankVO : result) {
theoreticalPracticeStudentQuestionBankVO.setSection(ChineseNumberUtils.toChinese(Integer.parseInt(theoreticalPracticeStudentQuestionBankVO.getSection())));
if (groupedMap.containsKey(theoreticalPracticeStudentQuestionBankVO.getSecondLevelName())) {
List<TheoreticalPracticeStudentQuestionBankVO> subset = new ArrayList<>();
analysisSubset(subset, groupedMap.get(theoreticalPracticeStudentQuestionBankVO.getSecondLevelName()));
theoreticalPracticeStudentQuestionBankVO.setSubset(subset);
}
}
return result;
}
@Override
public List<TheoreticalPracticeStudentQuestionBankVO> overview(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO) {
List<TheoreticalPracticeStudentQuestionBankVO> result = baseMapper.overview(theoreticalPracticeStudentQuestionBankDTO);
for (TheoreticalPracticeStudentQuestionBankVO theoreticalPracticeStudentQuestionBank : result) {
if (StringUtils.isNotEmpty(theoreticalPracticeStudentQuestionBank.getType())) {
List<TheoreticalPracticeStudentQuestionBankVO> data = baseMapper.paperOverview(theoreticalPracticeStudentQuestionBankDTO.getStudentId(),
theoreticalPracticeStudentQuestionBankDTO.getFirstLevelName(),
theoreticalPracticeStudentQuestionBankDTO.getSecondLevelName(),
theoreticalPracticeStudentQuestionBank.getType());
theoreticalPracticeStudentQuestionBank.setSubset(data);
}
}
return result;
}
@Override
public TheoreticalPracticeStudentQuestionBankVO detail(String id) {
TheoreticalPracticeStudentQuestionBankVO result = BeanUtil.copyProperties(getById(id), TheoreticalPracticeStudentQuestionBankVO.class);
long total = count(new LambdaQueryWrapper<TheoreticalPracticeStudentQuestionBankEntity>()
.eq(TheoreticalPracticeStudentQuestionBankEntity::getStudentId, result.getStudentId())
.eq(TheoreticalPracticeStudentQuestionBankEntity::getFirstLevelName, result.getFirstLevelName())
.eq(TheoreticalPracticeStudentQuestionBankEntity::getSecondLevelName, result.getSecondLevelName())
);
long completed = count(new LambdaQueryWrapper<TheoreticalPracticeStudentQuestionBankEntity>()
.eq(TheoreticalPracticeStudentQuestionBankEntity::getStudentId, result.getStudentId())
.isNotNull(TheoreticalPracticeStudentQuestionBankEntity::getActualChoice)
.eq(TheoreticalPracticeStudentQuestionBankEntity::getFirstLevelName, result.getFirstLevelName())
.eq(TheoreticalPracticeStudentQuestionBankEntity::getSecondLevelName, result.getSecondLevelName())
);
result.setTotal((int) total);
result.setCompleted((int) completed);
return result;
}
@Override
public Long countdown() {
String token = request.getHeader("Authorization");
UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getPhoneNumber, jwtTokenUtil.getUsernameFromToken(token)));
Date date = baseMapper.countdown(user.getId(),new Date());
if (ObjectUtils.isEmpty(date)) {
return -1L;
} else {
return date.getTime();
}
}
@Override
public Boolean reAnswer(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO) {
return baseMapper.reAnswer(theoreticalPracticeStudentQuestionBankDTO);
}
@Override
public Boolean edit(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO) {
TheoreticalPracticeStudentQuestionBankEntity theoreticalPracticeStudentQuestionBank = getById(theoreticalPracticeStudentQuestionBankDTO.getId());
//判断是否答对
theoreticalPracticeStudentQuestionBankDTO.setResult(theoreticalPracticeStudentQuestionBank.getAnswer().equals(theoreticalPracticeStudentQuestionBankDTO.getActualChoice()));
return updateById(theoreticalPracticeStudentQuestionBankDTO);
}
}
package com.platform.business.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.business.mapper.TheoreticalPracticeStudentMapper;
import com.platform.business.model.entity.TheoreticalPracticeStudentEntity;
import com.platform.business.model.vo.TheoreticalPracticeStudentVO;
import com.platform.business.service.TheoreticalPracticeStudentService;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TheoreticalPracticeStudentServiceImpl extends ServiceImpl<TheoreticalPracticeStudentMapper, TheoreticalPracticeStudentEntity> implements TheoreticalPracticeStudentService {
@Override
public List<TheoreticalPracticeStudentVO> selectStudentListByPracticeId(String id) {
return baseMapper.selectStudentListByPracticeId(id);
}
}
package com.platform.business.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.business.mapper.TheoreticalPracticeStudentSimulationDetailMapper;
import com.platform.business.model.entity.TheoreticalPracticeStudentSimulationDetailEntity;
import com.platform.business.model.vo.TheoreticalPracticeStudentSimulationDetailVO;
import com.platform.business.service.TheoreticalPracticeStudentSimulationDetailService;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TheoreticalPracticeStudentSimulationDetailServiceImpl extends
ServiceImpl<TheoreticalPracticeStudentSimulationDetailMapper, TheoreticalPracticeStudentSimulationDetailEntity> implements TheoreticalPracticeStudentSimulationDetailService {
@Override
public List<TheoreticalPracticeStudentSimulationDetailVO> numberAndScore(String id) {
return baseMapper.numberAndScore(id);
}
@Override
public List<TheoreticalPracticeStudentSimulationDetailVO> paperOverview(String id, String type) {
return baseMapper.paperOverview(id, type);
}
@Override
public void reAnswer(String id) {
baseMapper.reAnswer(id);
}
@Override
public TheoreticalPracticeStudentSimulationDetailVO questionDetail(String id) {
return baseMapper.questionDetail(id);
}
@Override
public TheoreticalPracticeStudentSimulationDetailVO gradesQuestionDetail(String id) {
return baseMapper.gradesQuestionDetail(id);
}
}
package com.platform.business.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.business.mapper.TheoreticalPracticeStudentSimulationMapper;
import com.platform.business.model.dto.CombinationDTO;
import com.platform.business.model.dto.TheoreticalPracticeStudentSimulationDTO;
import com.platform.business.model.dto.TheoreticalPracticeStudentSimulationDetailDTO;
import com.platform.business.model.entity.*;
import com.platform.business.model.vo.TheoreticalPracticeStudentSimulationDetailVO;
import com.platform.business.model.vo.TheoreticalPracticeStudentSimulationVO;
import com.platform.business.service.TheoreticalLibraryService;
import com.platform.business.service.TheoreticalPracticeStudentSimulationDetailService;
import com.platform.business.service.TheoreticalPracticeStudentSimulationService;
import com.platform.business.service.UserService;
import com.platform.exception.BusinessException;
import com.platform.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class TheoreticalPracticeStudentSimulationServiceImpl extends ServiceImpl<TheoreticalPracticeStudentSimulationMapper, TheoreticalPracticeStudentSimulationEntity> implements TheoreticalPracticeStudentSimulationService {
@Resource
private TheoreticalLibraryService theoreticalLibraryService;
@Resource
private TheoreticalPracticeStudentSimulationDetailService theoreticalPracticeStudentSimulationDetailService;
@Resource
private UserService userService;
@Override
public List<TheoreticalPracticeStudentSimulationVO> pageData(TheoreticalPracticeStudentSimulationDTO theoreticalPracticeStudentSimulationDTO) {
return baseMapper.pageData(theoreticalPracticeStudentSimulationDTO);
}
@Override
public Boolean create(CombinationDTO combinationDTO) {
//查询当前登陆人信息
UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getPhoneNumber, combinationDTO.getCreateUser()));
List<PaperRuleEntity> paperRuleList = combinationDTO.getPaperRuleList();
Map<String, Double> paperRuleMap = paperRuleList.stream().collect(Collectors.toMap(PaperRuleEntity::getType, PaperRuleEntity::getEachQuestion));
//保存理论考试
TheoreticalPracticeStudentSimulationEntity theoreticalPracticeStudentSimulation = new TheoreticalPracticeStudentSimulationEntity();
theoreticalPracticeStudentSimulation.setName(combinationDTO.getName());
theoreticalPracticeStudentSimulation.setStudentId(user.getId());
theoreticalPracticeStudentSimulation.setStudentName(user.getNickName());
theoreticalPracticeStudentSimulation.setCreateTime(new Date());
theoreticalPracticeStudentSimulation.setScore("待作答");
theoreticalPracticeStudentSimulation.setTotalScore(combinationDTO.getSum());
theoreticalPracticeStudentSimulation.setType(combinationDTO.getType());
theoreticalPracticeStudentSimulation.setDuration(combinationDTO.getDuration());
theoreticalPracticeStudentSimulation.setForbid(combinationDTO.getForbid());
save(theoreticalPracticeStudentSimulation);
//获取试题分布
List<PaperDistributionEntity> paperDistributionList = combinationDTO.getPaperDistributionList();
List<TheoreticalPracticeStudentSimulationDetailEntity> judgmentActual = randomQuestions(paperDistributionList, "判断题");
List<TheoreticalPracticeStudentSimulationDetailEntity> choiceActual = randomQuestions(paperDistributionList, "单选题");
List<TheoreticalPracticeStudentSimulationDetailEntity> moreActual = randomQuestions(paperDistributionList, "多选题");
judgmentActual.addAll(choiceActual);
judgmentActual.addAll(moreActual);
for (TheoreticalPracticeStudentSimulationDetailEntity theoreticalPaperDetailEntity : judgmentActual) {
theoreticalPaperDetailEntity.setSimulationId(theoreticalPracticeStudentSimulation.getId());
theoreticalPaperDetailEntity.setScore(paperRuleMap.get(theoreticalPaperDetailEntity.getType()));
}
theoreticalPracticeStudentSimulationDetailService.saveBatch(judgmentActual);
return true;
}
//生成随机题目
private List<TheoreticalPracticeStudentSimulationDetailEntity> randomQuestions(List<PaperDistributionEntity> paperRuleList, String type) {
List<TheoreticalPracticeStudentSimulationDetailEntity> resultList = new ArrayList<>();
for (PaperDistributionEntity paperDistributionEntity : paperRuleList) {
List<TheoreticalPracticeStudentSimulationDetailEntity> theoreticalLibraryList = new ArrayList<>();
if ("判断题".equals(type)) {
theoreticalLibraryList = theoreticalLibraryService
.randomQuestionsSimulation(paperDistributionEntity.getLev(), type, paperDistributionEntity.getJudgmentCount(), paperDistributionEntity.getChapter(), paperDistributionEntity.getSection());
} else if ("单选题".equals(type)) {
theoreticalLibraryList = theoreticalLibraryService
.randomQuestionsSimulation(paperDistributionEntity.getLev(), type, paperDistributionEntity.getSingleCount(), paperDistributionEntity.getChapter(), paperDistributionEntity.getSection());
} else if ("多选题".equals(type)) {
theoreticalLibraryList = theoreticalLibraryService
.randomQuestionsSimulation(paperDistributionEntity.getLev(), type, paperDistributionEntity.getMoreCount(), paperDistributionEntity.getChapter(), paperDistributionEntity.getSection());
}
resultList.addAll(theoreticalLibraryList);
}
return resultList;
}
@Override
@Transactional
public Boolean start(String id) {
TheoreticalPracticeStudentSimulationEntity theoreticalPracticeStudentSimulation = getById(id);
long now = System.currentTimeMillis();
theoreticalPracticeStudentSimulation.setStartTime(now);
theoreticalPracticeStudentSimulation.setEndTime(now + theoreticalPracticeStudentSimulation.getDuration() * 60 * 1000);
updateById(theoreticalPracticeStudentSimulation);
UserEntity user = userService.getById(theoreticalPracticeStudentSimulation.getStudentId());
user.setSimulationId(id);
user.setSimulationFlag(true);
return userService.updateById(user);
}
@Override
public Boolean updateDetail(TheoreticalPracticeStudentSimulationDetailDTO theoreticalPracticeStudentSimulationDetailDTO) {
return theoreticalPracticeStudentSimulationDetailService.updateById(theoreticalPracticeStudentSimulationDetailDTO);
}
@Override
public List<TheoreticalPracticeStudentSimulationDetailVO> overview(String id) {
//查询试题数量和分值
List<TheoreticalPracticeStudentSimulationDetailVO> result = theoreticalPracticeStudentSimulationDetailService.numberAndScore(id);
for (TheoreticalPracticeStudentSimulationDetailVO theoreticalPracticeStudentSimulationDetailVO : result) {
if (StringUtils.isNotEmpty(theoreticalPracticeStudentSimulationDetailVO.getType())) {
List<TheoreticalPracticeStudentSimulationDetailVO> data = theoreticalPracticeStudentSimulationDetailService.paperOverview(id, theoreticalPracticeStudentSimulationDetailVO.getType());
theoreticalPracticeStudentSimulationDetailVO.setData(data);
}
}
return result;
}
@Override
@Transactional
public Boolean reAnswer(String id) {
if (StringUtils.isEmpty(id)) {
throw new BusinessException("模拟考场id不能为空");
}
//清除时间
baseMapper.reAnswer(id);
//清除数据
theoreticalPracticeStudentSimulationDetailService.reAnswer(id);
TheoreticalPracticeStudentSimulationEntity theoreticalPracticeStudentSimulation = getById(id);
UserEntity user = userService.getById(theoreticalPracticeStudentSimulation.getStudentId());
user.setSimulationId(id);
user.setSimulationFlag(true);
return userService.updateById(user);
}
@Override
public Map<String, String> submitCheck(String id) {
Map<String, String> result = new HashMap<>();
//查询考试信息
TheoreticalPracticeStudentSimulationEntity theoreticalPracticeStudentSimulation = getById(id);
//判断是否在禁止交卷时间内
if (theoreticalPracticeStudentSimulation.getStartTime() + theoreticalPracticeStudentSimulation.getForbid() * 60 * 1000 > System.currentTimeMillis()) {
result.put("first", "暂不支持交卷,请继续作答");
result.put("second", "考试开始" + theoreticalPracticeStudentSimulation.getForbid() + "分钟内,禁止交卷。");
return result;
}
//判断题目是否都做完
long count = theoreticalPracticeStudentSimulationDetailService.count(new LambdaQueryWrapper<TheoreticalPracticeStudentSimulationDetailEntity>()
.eq(TheoreticalPracticeStudentSimulationDetailEntity::getSimulationId, id)
.isNull(TheoreticalPracticeStudentSimulationDetailEntity::getActualChoice));
if (count > 0) {
result.put("first", "您还有" + count + "道题目未答,是否交卷?");
result.put("second", "提示:倒计时结束后会自动保存答案并交卷");
} else {
result.put("first", "您已完成作答,是否交卷?");
result.put("second", "提示:倒计时结束后会自动保存答案并交卷");
}
return result;
}
@Override
@Transactional
public Boolean submit(String id) {
//总分
double score = 0;
//查询考生个人信息
TheoreticalPracticeStudentSimulationEntity theoreticalPracticeStudentSimulation = getById(id);
//修改登陆信息
userService.closeSimulation(theoreticalPracticeStudentSimulation.getStudentId());
//判题
List<TheoreticalPracticeStudentSimulationDetailEntity> theoreticalPaperStudentDetailList = theoreticalPracticeStudentSimulationDetailService.list(new LambdaQueryWrapper<TheoreticalPracticeStudentSimulationDetailEntity>()
.eq(TheoreticalPracticeStudentSimulationDetailEntity::getSimulationId, id));
for (TheoreticalPracticeStudentSimulationDetailEntity theoreticalPracticeStudentSimulationDetail : theoreticalPaperStudentDetailList) {
if (StringUtils.isNotEmpty(theoreticalPracticeStudentSimulationDetail.getActualChoice())) {
if (theoreticalPracticeStudentSimulationDetail.getActualChoice().equals(theoreticalPracticeStudentSimulationDetail.getAnswer())) {
theoreticalPracticeStudentSimulationDetail.setResult(true);
score += theoreticalPracticeStudentSimulationDetail.getScore();
} else {
theoreticalPracticeStudentSimulationDetail.setResult(false);
}
}
}
theoreticalPracticeStudentSimulationDetailService.updateBatchById(theoreticalPaperStudentDetailList);
theoreticalPracticeStudentSimulation.setScore(String.valueOf(score));
//计算答题时长
long time = System.currentTimeMillis() - theoreticalPracticeStudentSimulation.getStartTime();
theoreticalPracticeStudentSimulation.setAnswerDuration(time / 1000 / 60);
return updateById(theoreticalPracticeStudentSimulation);
}
@Override
public TheoreticalPracticeStudentSimulationDetailVO proceedTitleDetail(String id) {
TheoreticalPracticeStudentSimulationDetailVO result = theoreticalPracticeStudentSimulationDetailService.questionDetail(id);
//查询题数
long count = theoreticalPracticeStudentSimulationDetailService.count(new LambdaQueryWrapper<TheoreticalPracticeStudentSimulationDetailEntity>()
.eq(TheoreticalPracticeStudentSimulationDetailEntity::getSimulationId, result.getSimulationId())
.eq(TheoreticalPracticeStudentSimulationDetailEntity::getType, result.getType()));
result.setNum((int) count);
return result;
}
@Override
public TheoreticalPracticeStudentSimulationDetailVO analysisTitleDetail(String id) {
TheoreticalPracticeStudentSimulationDetailVO result = theoreticalPracticeStudentSimulationDetailService.gradesQuestionDetail(id);
//查询题数
long count = theoreticalPracticeStudentSimulationDetailService.count(new LambdaQueryWrapper<TheoreticalPracticeStudentSimulationDetailEntity>()
.eq(TheoreticalPracticeStudentSimulationDetailEntity::getSimulationId, result.getSimulationId())
.eq(TheoreticalPracticeStudentSimulationDetailEntity::getType, result.getType()));
result.setNum((int) count);
//查询同类型答对数量和得分
TheoreticalPracticeStudentSimulationDetailVO same = baseMapper.same(result.getSimulationId(), result.getType());
result.setSameRightNum(same.getSameRightNum());
result.setSameScore(same.getSameScore());
return result;
}
@Override
public Map<String, String> getPaperInformation(String userName) {
Map<String, String> result = new HashMap<>();
UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getPhoneNumber, userName));
long count = count(new LambdaQueryWrapper<TheoreticalPracticeStudentSimulationEntity>().eq(TheoreticalPracticeStudentSimulationEntity::getStudentId, user.getId()));
result.put("name", user.getLevel() + "模拟试卷" + (count + 1));
result.put("lev", user.getLevel());
return result;
}
}
package com.platform.business.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.platform.business.mapper.UserMapper;
import com.platform.business.model.dto.UserDTO;
import com.platform.business.model.entity.*;
import com.platform.business.model.vo.SysRoleAndMenuVO;
import com.platform.business.model.vo.UserVO;
import com.platform.business.service.*;
import com.platform.business.utils.ExcelUtil;
import com.platform.business.utils.PasswordUtil;
import com.platform.model.resp.Result;
import com.platform.utils.DozerUtils;
import com.platform.utils.StringUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.PicturesTable;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
@Resource
private StudentLevelCertService studentLevelCertService;
@Resource
private PasswordUtil passwordUtil;
@Resource
private SysUserAndRoleService sysUserAndRoleService;
@Resource
private SysRoleService sysRoleService;
@Resource
private TeacherWorkRecordService teacherWorkRecordService;
@Resource
private TeacherTeachRecordService teacherTeachRecordService;
@Resource
private BsFileService bsFileService;
@Resource
private SysRoleAndMenuService sysRoleAndMenuService;
@Resource
private SysPhoneRoleService sysPhoneRoleService;
@Override
public List<UserVO> queryList(UserDTO userDTO) {
return baseMapper.queryList(userDTO);
}
@Override
public UserVO detail(String id) {
UserVO user = DozerUtils.convertBean(getById(id), UserVO.class);
if (user == null) {
return null;
}
SysUserAndRoleEntity sysUserAndRole = sysUserAndRoleService.getOne(new LambdaQueryWrapper<SysUserAndRoleEntity>().eq(SysUserAndRoleEntity::getUserId, id), false);
if (!ObjectUtils.isEmpty(sysUserAndRole)) {
SysRoleEntity role = sysRoleService.getById(sysUserAndRole.getRoleId());
if (!ObjectUtils.isEmpty(role)) {
user.setRoleId(role.getId());
user.setRoleName(role.getName());
}
}
List<SysPhoneRoleEntity> sysPhoneRoleEntities = sysPhoneRoleService.queryByPhone(user.getUsername());
for (SysPhoneRoleEntity sysPhoneRoleEntity : sysPhoneRoleEntities) {
if ("教师".equals(sysPhoneRoleEntity.getRoleName())) {
List<TeacherWorkRecordEntity> teacherWorkRecordList = teacherWorkRecordService.list(new LambdaQueryWrapper<TeacherWorkRecordEntity>().eq(TeacherWorkRecordEntity::getUserId, id));
List<TeacherTeachRecordEntity> teacherTeachRecordList = teacherTeachRecordService.list(new LambdaQueryWrapper<TeacherTeachRecordEntity>().eq(TeacherTeachRecordEntity::getUserId, id));
user.setTeacherWorkRecordList(teacherWorkRecordList);
user.setTeacherTeachRecordList(teacherTeachRecordList);
} else {
//查看学员证书
List<StudentLevelCertEntity> studentLevelCertEntityList = studentLevelCertService.queryByIdCard(user.getCertNo());
user.setStudentLevelCertList(studentLevelCertEntityList);
}
}
return user;
}
@Override
@Transactional
public Object saveOrUpdateUser(UserDTO userDTO) {
// if (!ObjectUtils.isEmpty(userDTO.getTeacherTeachRecordList()) && !userDTO.getTeacherTeachRecordList().isEmpty()) {
// teacherTeachRecordService.saveOrUpdateBatch(userDTO.getTeacherTeachRecordList());
// }
if (!ObjectUtils.isEmpty(userDTO.getTeacherWorkRecordList()) && !userDTO.getTeacherWorkRecordList().isEmpty()) {
//删除旧数据
teacherWorkRecordService.remove(new LambdaQueryWrapper<TeacherWorkRecordEntity>().eq(TeacherWorkRecordEntity::getUserId, userDTO.getId()));
teacherWorkRecordService.saveBatch(userDTO.getTeacherWorkRecordList());
}
if (StringUtils.isEmpty(userDTO.getId())) {
String password = passwordUtil.encodePassword("123456");
userDTO.setPassword(password);
}
SysPhoneRoleEntity sysPhoneRoleEntity = new SysPhoneRoleEntity();
sysPhoneRoleEntity.setPhone(userDTO.getPhoneNumber());
sysPhoneRoleEntity.setRoleName("管理员");
sysPhoneRoleService.save(sysPhoneRoleEntity);
saveOrUpdate(userDTO);
SysUserAndRoleEntity sysUserAndRole = sysUserAndRoleService.getOne(new LambdaQueryWrapper<SysUserAndRoleEntity>().eq(SysUserAndRoleEntity::getUserId, userDTO.getId()));
if (ObjectUtils.isEmpty(sysUserAndRole) || !Objects.equals(userDTO.getRoleId(), sysUserAndRole.getRoleId())) {
sysUserAndRoleService.remove(new LambdaQueryWrapper<SysUserAndRoleEntity>().eq(SysUserAndRoleEntity::getUserId, userDTO.getId()));
SysUserAndRoleEntity sysUserAndRoleNew = new SysUserAndRoleEntity();
sysUserAndRoleNew.setUserId(userDTO.getId());
sysUserAndRoleNew.setRoleId(userDTO.getRoleId());
sysUserAndRoleService.save(sysUserAndRoleNew);
}
return true;
}
@Override
public Object resetPassword(String id) {
UserEntity user = getById(id);
if (user != null) {
// String password = passwordUtil.encodePassword(user.getUsername() + user.getPhoneNumber());
String password = passwordUtil.encodePassword("123456");
user.setPassword(password);
}
return updateById(user);
}
@Override
@Transactional
public Result studentImport(MultipartFile file) {
List<UserEntity> userList = Lists.newArrayList();
List<SysPhoneRoleEntity> phoneRoleList = Lists.newArrayList();
try (XSSFWorkbook sheets = new XSSFWorkbook(ExcelUtil.convertMultipartFileToFile(file))) {
XSSFSheet sheet = sheets.getSheetAt(0);
for (int i = 4; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
//判断是否有序号
String serialNumber = ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(0));
if (StringUtils.isEmpty(serialNumber) || !serialNumber.matches("-?\\d+(\\.\\d+)?")) {
break;
}
UserEntity user = new UserEntity();
//手机号和角色类(学生,老师) 注:不是系统角色
SysPhoneRoleEntity phoneRole = new SysPhoneRoleEntity();
//类型
user.setIdType("学生");
phoneRole.setRoleName("学生");
//密码
user.setPassword(passwordUtil.encodePassword("123456"));
//学员姓名
user.setNickName(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(1)));
//性别
user.setSex(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(2)));
//身份证号
user.setIdCard(convertScientificToNormal(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(3))));
//联系电话 + 账号
user.setPhoneNumber(convertScientificToNormal(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(4))));
phoneRole.setPhone(convertScientificToNormal(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(4))));
user.setUsername(convertScientificToNormal(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(4))));
//人员类别1
user.setUserType1(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(5)));
//人员类别2
user.setUserType2(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(6)));
//具有劳动关系单位(缴金单位)-单位名称
user.setCompanyName1(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(7)));
//具有劳动关系单位(缴金单位)-组织机构代码
user.setCompanyCode1(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(8)));
//实际用工单位-单位名称
user.setCompanyName2(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(9)));
//实际用工单位-组织机构代码
user.setCompanyCode2(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(10)));
//最高学历
user.setHighestEducation(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(11)));
//专业
user.setMajor(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(12)));
//社保缴金年限
user.setSocialSecurityYear(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(13)));
//从事本职业或相关职业工作年限
user.setWorkYear(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(14)));
//职业(工种)
user.setOccupation(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(15)));
//等级
user.setLevel(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(16)));
//证书编号
user.setCertNo(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(17)));
//发证日期
user.setIssueDate(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(18)));
//职称
user.setJobTitle(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(19)));
//获得职称时间
user.setJobTitleDate(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(20)));
//符合认定申报资质条款
user.setQualificationClause(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(21)));
//备注
user.setRemark(ExcelUtil.getCellValueAsString(sheet.getRow(i).getCell(22)));
userList.add(user);
phoneRoleList.add(phoneRole);
}
//保存手机号和角色绑定类
sysPhoneRoleService.saveBatch(phoneRoleList);
if (userList.isEmpty()) {
return Result.fail("导入数据为空");
}
return Result.data(saveBatch(userList));
} catch (Exception e) {
return Result.fail("导入失败");
}
}
/**
* 将科学计数法格式的字符串转换为普通数字格式的字符串
*
* @param scientificStr 科学计数法格式的字符串(例如 "1.23E+5")
* @return 普通数字格式的字符串(例如 "123000")。如果输入无效,返回null。
*/
public static String convertScientificToNormal(String scientificStr) {
if (scientificStr == null || scientificStr.trim().isEmpty()) {
return null;
}
try {
// 使用BigDecimal解析字符串
BigDecimal number = new BigDecimal(scientificStr.trim());
// 使用toPlainString方法获取非科学计数法的字符串表示
return number.toPlainString();
} catch (NumberFormatException e) {
return scientificStr;
}
}
@Override
@Transactional
public Object teacherImport(MultipartFile file) {
List<SysPhoneRoleEntity> phoneRoleList = Lists.newArrayList();
//判断文件后缀名是doc还是docx
if (Objects.requireNonNull(file.getOriginalFilename()).endsWith(".doc")) {
try (FileInputStream fis = new FileInputStream(ExcelUtil.convertMultipartFileToFile(file)); HWPFDocument hwpfDocument = new HWPFDocument(fis)) {
UserEntity user = new UserEntity();
//获取图片
PicturesTable picturesTable = hwpfDocument.getPicturesTable();
//获取所有图片
List<Picture> allPictures = picturesTable.getAllPictures();
for (Picture picture : allPictures) {
String fileName = System.currentTimeMillis() + "." + picture.suggestFullFileName().split("\\.")[1];
byte[] content = picture.getContent();
MultipartFile multipartFile = convertToMultipartFile(content, fileName);
BsFileEntity bsFile = bsFileService.uploadFile(multipartFile);
user.setAvatar(bsFile.getFileName());
}
//获取表格
Range range = hwpfDocument.getRange();
TableIterator tableIterator = new TableIterator(range);
while (tableIterator.hasNext()) {
Table table = tableIterator.next();
//手机号和角色类(学生,老师) 注:不是系统角色
SysPhoneRoleEntity phoneRole = new SysPhoneRoleEntity();
//从业经历
List<TeacherWorkRecordEntity> teacherWorkRecordList = Lists.newArrayList();
//任教经历
List<TeacherTeachRecordEntity> teacherTeachRecordList = Lists.newArrayList();
//个人信息
user.setIdType("教师");
phoneRole.setRoleName("教师");
user.setPassword(passwordUtil.encodePassword("123456"));
personalInformation(table, user);
phoneRole.setPhone(user.getPhoneNumber());
//添加关联信息到手机号和角色类
phoneRoleList.add(phoneRole);
//保存用户
save(user);
teacherExperience(teacherWorkRecordList, teacherTeachRecordList, user.getId(), table);
teacherWorkRecordService.saveBatch(teacherWorkRecordList);
teacherTeachRecordService.saveBatch(teacherTeachRecordList);
}
//批量保存手机号和角色类
sysPhoneRoleService.saveBatch(phoneRoleList);
return true;
} catch (IOException e) {
throw new RuntimeException(e);
}
} else if (Objects.requireNonNull(file.getOriginalFilename()).endsWith(".docx")) {
// try (FileInputStream fis = new FileInputStream(ExcelUtil.convertMultipartFileToFile(file));
// XWPFDocument xwpfDocument = new XWPFDocument(fis)) {
// //获取所有表格
// List<XWPFTable> tables = xwpfDocument.getTables();
// //获取所有图片
// List<XWPFPictureData> pictures = xwpfDocument.getAllPictures();
// for (XWPFPictureData picture : pictures) {
//
// }
// return true;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//TODO 处理docx类型
return false;
} else {
throw new RuntimeException("文件格式错误");
}
}
public static MultipartFile convertToMultipartFile(byte[] content, String fileName) throws IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
FileItem fileItem = factory.createItem("file", "application/octet-stream", false, fileName);
try (OutputStream os = fileItem.getOutputStream()) {
os.write(content);
}
return new CommonsMultipartFile(fileItem);
}
public MultipartFile convertXWPFPictureDataToMultipartFile(XWPFPictureData pictureData, String fileName) throws IOException {
// 1. 从 XWPFPictureData 获取图片的字节数组
byte[] imageData = pictureData.getData();
// 2. 获取建议的文件扩展名以确定内容类型,并构建完整文件名(如果未提供)
String fileExtension = pictureData.suggestFileExtension(); // 例如 "png", "jpeg"
String contentType = "image/" + fileExtension; // 简单映射,可根据需要细化
if (fileName == null || fileName.isEmpty()) {
fileName = "image." + fileExtension;
}
// 3. 使用 DiskFileItem 创建 FileItem
FileItem fileItem = new DiskFileItem("file", contentType, false, fileName, imageData.length, null);
try (InputStream inputStream = new ByteArrayInputStream(imageData); OutputStream outputStream = fileItem.getOutputStream()) {
IOUtils.copy(inputStream, outputStream);
} catch (IOException e) {
throw new IOException("Error creating FileItem from XWPFPictureData", e);
}
// 4. 使用 CommonsMultipartFile 包装 FileItem
return new CommonsMultipartFile(fileItem);
}
/**
* 处理教师经历
*/
private void teacherExperience(List<TeacherWorkRecordEntity> teacherWorkRecordList, List<TeacherTeachRecordEntity> teacherTeachRecordList, String userId, Table table) {
boolean tip = true;
for (int i = 10; i < table.numRows(); i++) {
TableRow row = table.getRow(i);
TableCell cell = row.getCell(0);
String text = cell.text().trim();
if (StringUtils.isEmpty(text)) {
continue;
} else if ("序号".equals(text) || "任教经历".equals(text)) {
tip = false;
continue;
}
if (tip) {
TeacherWorkRecordEntity teacherWorkRecord = new TeacherWorkRecordEntity();
teacherWorkRecord.setUserId(userId);
teacherWorkRecord.setStartDate(table.getRow(i).getCell(0).text().trim());
teacherWorkRecord.setWorkUnit(table.getRow(i).getCell(1).text().trim());
teacherWorkRecord.setDuty(table.getRow(i).getCell(2).text().trim());
teacherWorkRecordList.add(teacherWorkRecord);
} else {
TeacherTeachRecordEntity teacherTeachRecord = new TeacherTeachRecordEntity();
teacherTeachRecord.setUserId(userId);
teacherTeachRecord.setSerialNumber(table.getRow(i).getCell(0).text().trim());
teacherTeachRecord.setTeachDate(table.getRow(i).getCell(1).text().trim());
teacherTeachRecord.setTeachClassNum(table.getRow(i).getCell(2).text().trim());
teacherTeachRecord.setTeachCourse(table.getRow(i).getCell(3).text().trim());
teacherTeachRecord.setTeachHour(table.getRow(i).getCell(4).text().trim());
teacherTeachRecord.setRemark(table.getRow(i).getCell(5).text().trim());
teacherTeachRecordList.add(teacherTeachRecord);
}
}
}
/**
* 处理教师个人信息
*/
private static void personalInformation(Table table, UserEntity user) {
//姓名
user.setNickName(table.getRow(0).getCell(1).text().trim());
//性别
user.setSex(table.getRow(0).getCell(3).text().trim());
//出生年月
user.setBirthday(table.getRow(0).getCell(5).text().trim());
//身份证编号
user.setIdCard(table.getRow(1).getCell(1).text().trim() + table.getRow(1).getCell(2).text().trim() + table.getRow(1).getCell(3).text().trim() + table.getRow(1).getCell(4).text().trim() + table.getRow(1).getCell(5).text().trim() + table.getRow(1).getCell(6).text().trim() + table.getRow(1).getCell(7).text().trim() + table.getRow(1).getCell(8).text().trim() + table.getRow(1).getCell(9).text().trim() + table.getRow(1).getCell(10).text().trim() + table.getRow(1).getCell(11).text().trim() + table.getRow(1).getCell(12).text().trim() + table.getRow(1).getCell(13).text().trim() + table.getRow(1).getCell(14).text().trim() + table.getRow(1).getCell(15).text().trim() + table.getRow(1).getCell(16).text().trim() + table.getRow(1).getCell(17).text().trim() + table.getRow(1).getCell(18).text().trim());
//所学专业
user.setMajor(table.getRow(2).getCell(1).text().trim());
//学历/学位
user.setHighestEducation(table.getRow(2).getCell(3).text().trim());
//专业技术职务资格
user.setJobQualification(table.getRow(3).getCell(1).text().trim());
//教师资格(上岗)证编号
user.setCertNo(table.getRow(4).getCell(1).text().trim());
//发证部门
user.setIssueDept1(table.getRow(4).getCell(3).text().trim());
//技术等级
user.setLevel(table.getRow(5).getCell(1).text().trim());
//发证部门
user.setIssueDept2(table.getRow(5).getCell(3).text().trim());
//工作单位
user.setWorkUnit(table.getRow(6).getCell(1).text().trim());
//地址
user.setWorkUnitAddress(table.getRow(6).getCell(3).text().trim());
//家庭地址
user.setHomeAddress(table.getRow(7).getCell(1).text().trim());
//邮编
user.setZipCode(table.getRow(7).getCell(3).text().trim());
//联系方式 + 账号
user.setPhoneNumber(table.getRow(7).getCell(5).text().trim());
user.setUsername(table.getRow(7).getCell(5).text().trim());
}
@Override
public Result updatePassword(UserDTO userDTO) {
UserEntity user = getById(userDTO.getId());
boolean matches = passwordUtil.matches(userDTO.getOldPassword(), user.getPassword());
if (matches) {
user.setPassword(passwordUtil.encodePassword(userDTO.getNewPassword()));
return Result.data(updateById(user));
} else {
return Result.fail("旧密码错误");
}
}
@Override
public UserVO getUserMessage(String userName) {
UserVO userVO = baseMapper.queryByUserName(userName);
//获取用户角色 注:此处不是系统角色
//系统中账户就是为手机号
List<SysPhoneRoleEntity> sysPhoneRoleEntities = sysPhoneRoleService.queryByPhone(userName);
//查询系统角色
SysPhoneRoleEntity sysPhoneRoleEntity = null;
if (StringUtils.isNotEmpty(userVO.getRoleName())) {
sysPhoneRoleEntity = new SysPhoneRoleEntity();
sysPhoneRoleEntity.setRoleName(userVO.getRoleName());
sysPhoneRoleEntity.setPhone(userName);
}
//去重
if (sysPhoneRoleEntities.size() > 1) {
if (!ObjectUtils.isEmpty(sysPhoneRoleEntity)) {
sysPhoneRoleEntities.add(sysPhoneRoleEntity);
}
sysPhoneRoleEntities = sysPhoneRoleEntities.stream().distinct().collect(Collectors.toList());
userVO.setSysPhoneRoleEntities(sysPhoneRoleEntities);
} else {
if (!ObjectUtils.isEmpty(sysPhoneRoleEntity)) {
sysPhoneRoleEntities = new ArrayList<>();
sysPhoneRoleEntities.add(sysPhoneRoleEntity);
}
userVO.setSysPhoneRoleEntities(sysPhoneRoleEntities);
}
Integer roleId = userVO.getRoleId();
if (roleId != null) {
List<SysRoleAndMenuVO> sysRoleAndMenuVOList = sysRoleAndMenuService.queryByRoleId(roleId);
userVO.setSysMenuEntities(sysRoleAndMenuVOList);
}
return userVO;
}
// @Override
// public UserVO getUserMessage(String userName) {
// // 1. 获取基础用户信息
// UserVO userVO = baseMapper.queryByUserName(userName);
// if (userVO == null) {
// return null;
// }
// // 2. 获取用户所有角色
// List<SysPhoneRoleEntity> allRoles = new ArrayList<>();
// // 获取系统分配的角色
// List<SysPhoneRoleEntity> sysPhoneRoleEntities = sysPhoneRoleService.queryByPhone(userName);
// if (CollectionUtils.isNotEmpty(sysPhoneRoleEntities)) {
// allRoles.addAll(sysPhoneRoleEntities);
// }
// // 获取用户的固有角色(从userVO中)
// String roleName = userVO.getRoleName();
// if (StringUtils.isNotBlank(roleName)) {
// SysPhoneRoleEntity userRole = new SysPhoneRoleEntity();
// userRole.setRoleName(roleName);
// userRole.setPhone(userName);
// allRoles.add(userRole);
// }
// //去重
// allRoles = allRoles.stream().distinct().collect(Collectors.toList());
// // 3. 设置角色列表到userVO
// userVO.setSysPhoneRoleEntities(allRoles);
// // 4. 获取角色对应的菜单权限
// Integer roleId = userVO.getRoleId();
// if (roleId != null) {
// List<SysRoleAndMenuVO> menuList = sysRoleAndMenuService.queryByRoleId(roleId);
// userVO.setSysMenuEntities(menuList);
// }
// return userVO;
// }
@Override
public UserVO queryByUserName(String userName) {
return baseMapper.queryByUserName(userName);
}
@Override
public void closeExam(String id) {
baseMapper.closeExam(id);
}
@Override
public void closeSimulation(String studentId) {
baseMapper.closeSimulation(studentId);
}
}
package com.platform.business.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.business.mapper.UserTeacherMapper;
import com.platform.business.model.entity.TeacherWorkRecordEntity;
import com.platform.business.model.entity.UserTeacherEntity;
import com.platform.business.model.vo.ClassSubjectVO;
import com.platform.business.model.vo.UserTeacherVO;
import com.platform.business.service.ClassSubjectService;
import com.platform.business.service.TeacherWorkRecordService;
import com.platform.business.service.UserTeacherService;
import com.platform.utils.DozerUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserTeacherServiceImpl extends ServiceImpl<UserTeacherMapper, UserTeacherEntity> implements UserTeacherService {
@Resource
private ClassSubjectService classSubjectService;
@Resource
private TeacherWorkRecordService teacherWorkRecordService;
@Override
public UserTeacherVO getByUserId(String id) {
UserTeacherVO userTeacherVO = DozerUtils.convertBean(baseMapper.selectOne(new LambdaQueryWrapper<UserTeacherEntity>()
.eq(UserTeacherEntity::getUserId, id)), UserTeacherVO.class);
if (userTeacherVO != null) {
//查看从业经历
List<TeacherWorkRecordEntity> teacherWorkRecordEntityList = teacherWorkRecordService.queryByUserId(id);
userTeacherVO.setTeacherWorkRecord(teacherWorkRecordEntityList);
//查看任教经理
List<ClassSubjectVO> classSubjectVOList = classSubjectService.countByTeacherId(id);
userTeacherVO.setClassSubjectList(classSubjectVOList);
}
return userTeacherVO;
}
}
//package com.platform.business.strategy;
//
//import com.platform.business.model.req.ExamReq;
//import com.platform.business.model.resp.ExamResp;
//
//public interface WebSocketMsgStrategy {
//
// ExamResp execute(ExamReq examReq);
//}
//package com.platform.business.strategy.impl;
//
//import cn.hutool.core.collection.CollUtil;
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.google.common.collect.Lists;
//import com.platform.business.duplex.WebSocketServer;
//import com.platform.business.model.entity.ExamDetailEntity;
//import com.platform.business.model.entity.QuestionBankEntity;
//import com.platform.business.model.entity.QuestionThirdEntity;
//import com.platform.business.model.req.ExamQuestionReq;
//import com.platform.business.model.req.ExamReq;
//import com.platform.business.model.req.ExamResultReq;
//import com.platform.business.model.resp.ExamChildResp;
//import com.platform.business.model.resp.ExamResp;
//import com.platform.business.service.ExamDetailService;
//import com.platform.business.service.QuestionBankService;
//import com.platform.business.service.QuestionThirdService;
//import com.platform.business.strategy.WebSocketMsgStrategy;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.Resource;
//import java.io.IOException;
//import java.util.List;
//
//@Slf4j
//@Component
//public class ExamSubmitStrategyImpl implements WebSocketMsgStrategy {
//
// private static ExamSubmitStrategyImpl examSubmitStrategy;
//
// public static void setExamSubmitStrategy(ExamSubmitStrategyImpl examSubmitStrategy) {
// ExamSubmitStrategyImpl.examSubmitStrategy = examSubmitStrategy;
// }
//
// @PostConstruct
// public void init() {
// setExamSubmitStrategy(this);
// }
//
// @Resource
// private ExamDetailService examDetailService;
// @Resource
// private QuestionBankService questionBankService;
// @Resource
// private QuestionThirdService questionThirdService;
// @Resource
// private WebSocketServer webSocketServer;
//
//
// @Override
// public ExamResp execute(ExamReq examReq) {
//
// //查看一级课题信息
// QuestionBankEntity questionBankEntity = examSubmitStrategy.questionBankService.getByNoAndLevel(examReq.getId(), examReq.getLevel());
// if (questionBankEntity != null) {
// //查看三级题的信息
// List<QuestionThirdEntity> questionThirdEntityList = examSubmitStrategy.questionThirdService.queryByQuestionId(questionBankEntity.getId());
// if (CollUtil.isNotEmpty(questionThirdEntityList)) {
//
// //初始化得分明细集合
// List<ExamDetailEntity> examDetailEntityList = Lists.newArrayList();
// List<ExamResultReq> examResultReqList = examReq.getResult();
//
// double totalScore = 0.0;
// double score = 0.0;
// for (QuestionThirdEntity questionThirdEntity : questionThirdEntityList) {
// totalScore = totalScore + questionThirdEntity.getScore();
//
// for (ExamResultReq examResultReq : examResultReqList) {
// List<ExamQuestionReq> examQuestionReqList = examResultReq.getQuestions();
// for (ExamQuestionReq examQuestionReq : examQuestionReqList) {
// if (examQuestionReq.getId().equals(questionThirdEntity.getNo())) {
// if (examQuestionReq.getResult().equals("1")) {
// examDetailEntityList.add(ExamDetailEntity.builder()
// .questionNo(questionThirdEntity.getNo())
// .score(questionThirdEntity.getScore())
// .studentId(examReq.getUserId())
// .build());
// examQuestionReq.setScore(questionThirdEntity.getScore());
// score = score + questionThirdEntity.getScore();
// examResultReq.setScore(examResultReq.getScore() + questionThirdEntity.getScore());
// } else {
// examDetailEntityList.add(ExamDetailEntity.builder()
// .questionNo(questionThirdEntity.getNo())
// .studentId(examReq.getUserId())
// .score(0.0).build());
// }
// examResultReq.setTotalScore(examResultReq.getTotalScore() + questionThirdEntity.getScore());
// }
// }
// }
// }
//
// if (CollUtil.isNotEmpty(examDetailEntityList)) {
// examSubmitStrategy.examDetailService.remove(new LambdaQueryWrapper<>());
// examSubmitStrategy.examDetailService.saveBatch(examDetailEntityList);
// }
//
// //组装返回数据
// List<ExamChildResp> childList = Lists.newArrayList();
//
// for (ExamResultReq examResultReq : examResultReqList) {
// childList.add(ExamChildResp.builder().id(examResultReq.getId())
// .title(examResultReq.getTitle())
// .score(examResultReq.getScore())
// .totalScore(examResultReq.getTotalScore())
// .build());
// }
//
// ExamResp examResp = new ExamResp();
// examResp.setId(questionBankEntity.getNo());
// examResp.setTotalScore(totalScore);
// examResp.setScore(score);
// examResp.setTitle(questionBankEntity.getName());
// examResp.setChild(childList);
//
// try {
// examSubmitStrategy.webSocketServer.sendInfo(JSON.toJSONString(examResp), String.valueOf(examReq.getUserId()));
// } catch (IOException e) {
// log.info("发送考试结果信息失败");
// throw new RuntimeException(e);
// }
// return examResp;
// }
// }
// return null;
//
// }
//}
package com.platform.business.utils;
public class ChineseNumberUtils {
private static final String[] CN_NUM = {
"零", "一", "二", "三", "四",
"五", "六", "七", "八", "九"
};
private static final String[] CN_UNIT = {
"", "十", "百", "千"
};
/**
* 将阿拉伯数字转换为中文数字(支持 0 ~ 9999)
*
* @param num 阿拉伯数字
* @return 中文数字
*/
public static String toChinese(int num) {
if (num == 0) {
return CN_NUM[0];
}
if (num < 0 || num > 9999) {
throw new IllegalArgumentException("暂不支持的数字范围");
}
StringBuilder result = new StringBuilder();
int unitIndex = 0;
boolean needZero = false;
while (num > 0) {
int digit = num % 10;
if (digit != 0) {
if (needZero) {
result.insert(0, CN_NUM[0]);
}
result.insert(0, CN_NUM[digit] + CN_UNIT[unitIndex]);
needZero = false;
} else {
needZero = result.length() == 0;
}
unitIndex++;
num /= 10;
}
// 处理“一十”开头的特殊情况
String str = result.toString();
if (str.startsWith("一十")) {
str = str.substring(1);
}
return str;
}
}
\ No newline at end of file
package com.platform.business.utils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @author : wujipeng
* @date : 2025/9/4 11:17
* @Version: 1.0
* @Desc : 描述信息
*/
public class ExcelUtil {
// 获取单元格值作为字符串
public static String getCellValueAsString(Cell cell) {
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getLocalDateTimeCellValue().toString();
} else {
return String.valueOf(cell.getNumericCellValue());
}
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case FORMULA:
return cell.getCellFormula();
case BLANK:
return "";
default:
return cell.toString();
}
}
// 将MultipartFile转换为File
public static File convertMultipartFileToFile(MultipartFile file) throws IOException {
File convFile = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename());
file.transferTo(convFile);
return convFile;
}
}
package com.platform.business.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
public class JwtTokenUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
// 生成密钥
private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(secret.getBytes());
}
// 生成token
public String generateToken(String username) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, username);
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
.compact();
}
// 从token中获取用户名
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
// 从token中获取过期时间
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parserBuilder()
.setSigningKey(getSigningKey())
.build()
.parseClaimsJws(token)
.getBody();
}
// 验证token是否过期
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
// 验证token
public Boolean validateToken(String token, String username) {
final String tokenUsername = getUsernameFromToken(token);
return (tokenUsername.equals(username) && !isTokenExpired(token));
}
}
\ No newline at end of file
package com.platform.business.utils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class PasswordUtil {
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
public String encodePassword(String rawPassword) {
return passwordEncoder.encode(rawPassword);
}
public boolean matches(String rawPassword, String encodedPassword) {
return passwordEncoder.matches(rawPassword, encodedPassword);
}
}
\ No newline at end of file
spring:
application:
name: practical-train-business
# 配置中心
cloud:
nacos:
discovery:
server-addr: ${NACOS-HOST:192.168.10.3}:${NACOS-PORT:6001}
namespace: 272b9958-7a2d-41f8-ba0b-fdcb7ee8ead0
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
file-extension: yml
namespace: 272b9958-7a2d-41f8-ba0b-fdcb7ee8ead0
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
spring:
application:
name: practical-train-business
# 配置中心
cloud:
nacos:
discovery:
server-addr: ${NACOS-HOST:47.111.94.26}:${NACOS-PORT:8848}
namespace: 272b9958-7a2d-41f8-ba0b-fdcb7ee8ead0
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
file-extension: yml
namespace: 272b9958-7a2d-41f8-ba0b-fdcb7ee8ead0
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.CandidateMapper">
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.ClassMapper">
<select id="queryList" resultType="com.platform.business.model.vo.ClassVO">
SELECT
c.id AS id,
c.name name,
c.level level,
(select count(*) from class_student where class_id = c.id) studentNum,
CASE
WHEN MIN(cs.date) IS NULL THEN '时间待定'
ELSE CONCAT(MIN(cs.date), ' - ', MAX(cs.date))
END AS dateRange
FROM
class c
LEFT JOIN
class_subject cs ON c.id = cs.class_id
<where>
<if test="level != null and level != ''">
and c.level = #{level}
</if>
<if test="name != null and name != ''">
and c.name like concat('%',#{name},'%')
</if>
</where>
GROUP BY
c.id,
c.name,
c.level
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.ClassStudentMapper">
<select id="queryList" resultType="com.platform.business.model.vo.ClassStudentVO">
select
cs.id id,
u.nick_name name,
u.id_card idCard,
u.factory,
u.phone_number phone,
u.id userId,
u.sex sex
from
class_student cs
left join
user u
on cs.user_id = u.id
where
cs.class_id = #{id}
</select>
<select id="selectTraineesNumber" resultType="com.platform.business.model.vo.HomeVO">
select class_id as classId,
count(*) as traineesNumber
from
class_student
group by
class_id
</select>
<select id="todayCourse" resultType="com.platform.business.model.vo.HomeVO">
select
subject_name as name,
remark as content,
time_frame as timeFrame,
teacher_id as teacherId,
user.nick_name as teacherName
from
class_subject left join user on class_subject.teacher_id = user.id
where
date = current_date
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.ClassSubjectMapper">
<delete id="deleteByClassIdAndDate">
delete
from
class_subject cs
where
cs.class_id = #{classId}
and
cs.date = #{date};
</delete>
<select id="queryByClassAndMonth" resultType="com.platform.business.model.vo.ClassSubjectVO">
select
cs.id id,
cs.subject_name,
cs.time_frame,
cs.subject_hour,
cs.date,
cs.subject_times,
u.nick_name teacherName,
cs.teacher_id teacherId
from
class_subject cs
left join
user u
on
cs.teacher_id = u.id
where
cs.class_id = #{classId}
and
DATE_FORMAT(cs.date, '%Y-%m') = #{date};
</select>
<select id="countByTeacherId" resultType="com.platform.business.model.vo.ClassSubjectVO">
select
id ,
date,
class_id,
subject_name,
remark,
(select count(*) from class_subject where teacher_id = #{id}) classNum,
(select sum(subject_hour) from class_subject where teacher_id = #{id}) subjectHour
from
class_subject
where
teacher_id = #{id}
group by id
</select>
<select id="queryByTeacherId" resultType="com.platform.business.model.vo.ClassSubjectVO">
select
date,
class_id,
subject_name,
remark,
subject_hour
from
class_subject
where
teacher_id = #{id}
group by id
</select>
<select id="queryOneself" resultType="com.platform.business.model.vo.ClassSubjectVO">
select
class_subject.id,
class_subject.class_id,
class_subject.subject_times,
class_subject.date,
class_subject.week,
class_subject.time_frame,
class_subject.subject_hour,
class_subject.subject_name,
class_subject.teacher_id,
class_subject.remark,
class.name as className
from
class_subject
left join class
on class_subject.class_id = class.id
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.ExamDetailMapper">
<select id="queryQuestionList" resultType="com.platform.business.model.vo.ExamDetailVO">
select
ed.score as resultScore,
ed.question_no as questionNO,
qt.title as thirdTitle,
qs.title as secondTitle,
qt.score as score,
qb.level as level,
ed.read_teacher as readTeacher,
qt.answer as answer
from
exam_detail ed
left join
question_third qt
on
ed.question_no = qt.no
left join
question_second qs
on
qt.question_second_id = qs.id
left join
question_bank qb
on
qt.question_id = qb.id
<where>
<if test="examId != null">
ed.exam_id = #{examId}
</if>
<if test="studentId != null">
and ed.student_id = #{studentId}
</if>
</where>
</select>
</mapper>
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment