Merge branch 'test'

This commit is contained in:
tiger_zhou 2023-05-26 15:33:47 +08:00
commit 36a3609164
8 changed files with 683 additions and 626 deletions

View File

@ -0,0 +1,9 @@
INSERT INTO rts_user_simulation_record (map_id, user_id, type, duration, start_time, end_time)
SELECT map_id,
user_id,
'SIM',
duration,
start_time,
end_time
FROM user_simulation_stats
WHERE end_time > '2000-01-01 00:00:00';

View File

@ -18,112 +18,119 @@ import java.util.List;
@RestController
@RequestMapping("/api/v2/paper")
public class PaperUserController {
@Autowired
private PaperUserService paperUserService;
@Autowired
private PaperUserCreateService paperUserCreateService;
@Autowired
private PaperUserLoadQuestionService paperUserLoadQuestionService;
@Autowired
private PaperUserSubmitAnswerService paperUserSubmitAnswerService;
@Autowired
private PaperUserFindPageService paperUserFindPageService;
/**
* 根据试卷蓝图生成用户的试卷
*
* @param pcId 试卷蓝图id
*/
@PostMapping("/{pcId}")
public CreatePaperRspVo createPaper(@PathVariable("pcId") Long pcId, @RequestAttribute AccountVO user) {
return this.paperUserCreateService.createPaper(pcId, user);
}
@Autowired
private PaperUserService paperUserService;
@Autowired
private PaperUserCreateService paperUserCreateService;
@Autowired
private PaperUserLoadQuestionService paperUserLoadQuestionService;
@Autowired
private PaperUserSubmitAnswerService paperUserSubmitAnswerService;
@Autowired
private PaperUserFindPageService paperUserFindPageService;
/**
* 获取用户试卷完整信息
*
* @param puId 用户试卷id
*/
@GetMapping("/user/{puId}")
public PaperUserWholeVo findPaperUser(@PathVariable("puId") Long puId, @RequestAttribute AccountVO user) {
return this.paperUserService.findPaperUser(puId);
}
/**
* 根据试卷蓝图生成用户的试卷
*
* @param pcId 试卷蓝图id
*/
@PostMapping("/{pcId}")
public CreatePaperRspVo createPaper(@PathVariable("pcId") Long pcId,
@RequestAttribute AccountVO user) {
return this.paperUserCreateService.createPaper(pcId, user);
}
/**
* 获取用户试卷完整信息
*
* @param puId 用户试卷id
*/
@GetMapping("/user/{puId}")
public PaperUserWholeVo findPaperUser(@PathVariable("puId") Long puId,
@RequestAttribute AccountVO user) {
return this.paperUserService.findPaperUser(puId);
}
/**
* 用户交卷
*
* @param puId 用户试卷id
*/
@PostMapping("/user/{puId}/submit")
public PaperSubmitRspVo paperSubmit(@PathVariable("puId") Long puId,
@RequestAttribute AccountVO user) {
return this.paperUserService.paperSubmit(puId, user);
}
/**
* 用户交卷
*
* @param puId 用户试卷id
*/
@PostMapping("/user/{puId}/submit")
public PaperSubmitRspVo paperSubmit(@PathVariable("puId") Long puId,@RequestAttribute AccountVO user) {
return this.paperUserService.paperSubmit(puId);
}
/**
* 加载用户试卷试题
*
* @param groupType 试卷试题大类型:1-理论题2-实训题
* @param qId 试题id
* @param puId 试卷id
* @return
*/
@GetMapping("/user/question/{groupType}/{qId}/{puId}")
public PaperQuestionLoadRspVo loadQuestion(@PathVariable("groupType") Integer groupType,
@PathVariable("qId") Long qId, @PathVariable("puId") Long puId,
@RequestAttribute AccountVO user) {
PaperQType.GroupType pgType = PaperQType.GroupType.getItem(groupType);
return this.paperUserLoadQuestionService.loadQuestion(pgType, qId, puId, user);
}
/**
* 加载用户试卷试题
* @param groupType 试卷试题大类型:1-理论题2-实训题
* @param qId 试题id
* @param puId 试卷id
* @return
*/
@GetMapping("/user/question/{groupType}/{qId}/{puId}")
public PaperQuestionLoadRspVo loadQuestion(@PathVariable("groupType") Integer groupType, @PathVariable("qId") Long qId,@PathVariable("puId") Long puId, @RequestAttribute AccountVO user) {
PaperQType.GroupType pgType = PaperQType.GroupType.getItem(groupType);
return this.paperUserLoadQuestionService.loadQuestion(pgType, qId,puId, user);
}
/**
* 用户提交答案
* <p>
* 对于理论题用户完成一道题提交一道题的答案<br> 对于实训题用户完成实训操作后由实训系统自己评判实训是否成功完成前端提交实训是否成功完成的结果即可
*/
@PostMapping("/user/question/answer")
public PaperSubmitAnswerRspVo submitAnswer(@RequestBody PaperSubmitAnswerReqVo req,
@RequestAttribute AccountVO user) {
return this.paperUserSubmitAnswerService.submitAnswer(req, user);
}
/**
* 用户提交答案
* <p>
* 对于理论题用户完成一道题提交一道题的答案<br>
* 对于实训题用户完成实训操作后由实训系统自己评判实训是否成功完成前端提交实训是否成功完成的结果即可
*/
@PostMapping("/user/question/answer")
public PaperSubmitAnswerRspVo submitAnswer(@RequestBody PaperSubmitAnswerReqVo req, @RequestAttribute AccountVO user) {
return this.paperUserSubmitAnswerService.submitAnswer(req, user);
}
/**
* 分页查询某个试卷蓝图的所有用户试卷基本信息
*/
/**
* 分页查询某个试卷蓝图的所有用户试卷基本信息
*/
/* @PostMapping("/user/page/composition")
public PageVO<PaperUserInfoVo> findPaperUserByPage(@RequestBody FindPaperUserForCompositionReqVo req, @RequestAttribute AccountVO user) {
return this.paperUserFindPageService.findPaperUserByPage(req);
}*/
/**
* 查看某个班级的某个试卷蓝图的所有学生试卷
*/
@GetMapping("/user/page")
public PageVO<PageUserDetailVO> findPaperUserByPageForClass(@ModelAttribute PageUserDetailQuery req) {
return this.paperUserFindPageService.findPaperUserByPageForClass(req);
}
/**
* 查看某个班级的某个试卷蓝图的所有学生试卷
*/
@GetMapping("/user/page")
public PageVO<PageUserDetailVO> findPaperUserByPageForClass(
@ModelAttribute PageUserDetailQuery req) {
return this.paperUserFindPageService.findPaperUserByPageForClass(req);
}
/**
* 查看某个班级的某个试卷蓝图的所有学生试卷 (柱状图)
* @param req
* @return
*/
@GetMapping("/user/curve")
public CurveForClassVO curveForClass(@ModelAttribute PageUserDetailQuery req) {
return this.paperUserFindPageService.curveForClass(req);
}
/**
* 查看某个班级的某个试卷蓝图的所有学生试卷 (柱状图)
*
* @param req
* @return
*/
@GetMapping("/user/curve")
public CurveForClassVO curveForClass(@ModelAttribute PageUserDetailQuery req) {
return this.paperUserFindPageService.curveForClass(req);
}
@PostMapping("/question/label")
public Collection<String> paperAllLabel(@RequestBody FindCountForQuestionReqVo req){
return this.paperUserService.findAllLabel(req);
}
@PostMapping("/question/label")
public Collection<String> paperAllLabel(@RequestBody FindCountForQuestionReqVo req) {
return this.paperUserService.findAllLabel(req);
}
/**
* 查看组织下某个类型题的数量
* 参数 tags 目前只支持单个
*/
@PostMapping("/question/count")
public Long findCountForQuestion( @RequestBody FindCountForQuestionReqVo req) {
/**
* 查看组织下某个类型题的数量 参数 tags 目前只支持单个
*/
@PostMapping("/question/count")
public Long findCountForQuestion(@RequestBody FindCountForQuestionReqVo req) {
// req.setOrgId(orgId);
return this.paperUserService.findCountForQuestion(req);
}
return this.paperUserService.findCountForQuestion(req);
}
}

View File

@ -1,13 +1,14 @@
package club.joylink.rtss.event;
import club.joylink.rtss.entity.UserSimulationStats;
import club.joylink.rtss.entity.UserSimulationRecord;
import lombok.Getter;
@Getter
public class UserSimulationRecordEvent {
UserSimulationStats record;
public UserSimulationRecordEvent(UserSimulationStats record) {
this.record = record;
}
UserSimulationRecord record;
public UserSimulationRecordEvent(UserSimulationRecord record) {
this.record = record;
}
}

View File

@ -3,11 +3,13 @@ package club.joylink.rtss.services.paper;
import club.joylink.rtss.constants.BusinessConsts;
import club.joylink.rtss.dao.PublishedTraining2DAO;
import club.joylink.rtss.dao.paper.*;
import club.joylink.rtss.entity.UserExam;
import club.joylink.rtss.entity.paper.*;
import club.joylink.rtss.entity.paper.question.PaperQuestion;
import club.joylink.rtss.entity.paper.question.PaperQuestionExample;
import club.joylink.rtss.entity.training2.PublishedTraining2;
import club.joylink.rtss.entity.training2.PublishedTraining2Example;
import club.joylink.rtss.event.UserExamRecordEvent;
import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
import club.joylink.rtss.exception.PaperExceptionAssert;
import club.joylink.rtss.services.training2.Training2PublishService;
@ -43,101 +45,109 @@ import java.util.stream.Collectors;
@Service
@Slf4j
public class PaperUserService {
@Autowired
private PaperCompositionDAO compositionDAO;
@Autowired
private PaperRuleDAO ruleDAO;
@Autowired
private PaperUserDAO paperUserDAO;
@Autowired
private PaperUserQuestionDAO paperUserQuestionDAO;
@Autowired
private PaperCompositionService compositionService;
@Autowired
private PaperQuestionDAO pagerQuestionDAO;
@Autowired
private PublishedTraining2DAO trainingDAO;
@Autowired
private PagerQuestionService paperQuestionService;
@Autowired
private Training2PublishService training2PublishService;
/**
* 获取理论或实操的所有标签
* @param req
* @return
*/
public Collection<String> findAllLabel(FindCountForQuestionReqVo req){
if(req.getGroupType() == PaperQType.GroupType.Common){
return paperQuestionService.findAllLable(req.getOrgId(),req.getSubType().name().toLowerCase());
}else if(PaperQType.GroupType.Training.equals(req.getGroupType())){
@Autowired
private PaperCompositionDAO compositionDAO;
@Autowired
private PaperRuleDAO ruleDAO;
@Autowired
private PaperUserDAO paperUserDAO;
@Autowired
private PaperUserQuestionDAO paperUserQuestionDAO;
@Autowired
private PaperCompositionService compositionService;
@Autowired
private PaperQuestionDAO pagerQuestionDAO;
@Autowired
private PublishedTraining2DAO trainingDAO;
@Autowired
private PagerQuestionService paperQuestionService;
@Autowired
private Training2PublishService training2PublishService;
/**
* 获取理论或实操的所有标签
*
* @param req
* @return
*/
public Collection<String> findAllLabel(FindCountForQuestionReqVo req) {
if (req.getGroupType() == PaperQType.GroupType.Common) {
return paperQuestionService.findAllLable(req.getOrgId(),
req.getSubType().name().toLowerCase());
} else if (PaperQType.GroupType.Training.equals(req.getGroupType())) {
// BusinessExceptionAssertEnum.OPERATION_NOT_SUPPORTED.assertNotTrue(req.getSubType() == PaperQType.SubType.Scene,"不支持此操作");
return this.training2PublishService.findAllLabel(req.getMapId(),req.getOrgId(),req.getSubType().name().toUpperCase(),req.getTrainingClient());
}
return Collections.emptyList();
return this.training2PublishService.findAllLabel(req.getMapId(), req.getOrgId(),
req.getSubType().name().toUpperCase(), req.getTrainingClient());
}
/**
* 获取组织某个类型题的数量
*/
@Transactional(readOnly = true)
public Long findCountForQuestion(FindCountForQuestionReqVo req){
if(PaperQType.GroupType.Common.equals(req.getGroupType())){
String tagStr=req.getTags();
BusinessConsts.TheoryType theoryType = this.getPaperQuestionType(req.getSubType());
return paperQuestionService.queryCount(req.getOrgId(),theoryType,tagStr);
}else if(PaperQType.GroupType.Training.equals(req.getGroupType())){
return Collections.emptyList();
}
/**
* 获取组织某个类型题的数量
*/
@Transactional(readOnly = true)
public Long findCountForQuestion(FindCountForQuestionReqVo req) {
if (PaperQType.GroupType.Common.equals(req.getGroupType())) {
String tagStr = req.getTags();
BusinessConsts.TheoryType theoryType = this.getPaperQuestionType(req.getSubType());
return paperQuestionService.queryCount(req.getOrgId(), theoryType, tagStr);
} else if (PaperQType.GroupType.Training.equals(req.getGroupType())) {
// PaperExceptionAssert.PdValid.assertTrue(!PaperQType.GroupType.Training.equals(groupType),"不支持查询实训题数量");
BusinessExceptionAssertEnum.OPERATION_NOT_SUPPORTED.assertNotTrue(req.getSubType() == PaperQType.SubType.Scene,"不支持此操作");
return training2PublishService.queryCountForLabel(req);
}
return 0L;
}
/**
* 获取用户试卷完整信息
*
* @param puId 用户试卷id
*/
@Transactional(readOnly = true)
public PaperUserWholeVo findPaperUser(Long puId) {
PaperUser paper = paperUserDAO.selectByPrimaryKey(puId);
PaperExceptionAssert.PuExisted.assertNotNull(paper, "用户试卷不存在");
//
PaperComposition composition = compositionDAO.selectByPrimaryKey(paper.getPcId());
List<PaperRule> ruleList = compositionService.findRuleByPcId(composition.getId());
List<PaperUserQuestion> userQuestionList = this.findUserSortedQuestions(puId);
//
PaperUserWholeVo rsp = new PaperUserWholeVo();
rsp.setComposition(PaperCompositionConvertor.convert(composition, ruleList));
rsp.setPaper(PaperUserConvertor.convert(paper));
rsp.setQuestionList(userQuestionList.stream().map(PaperUserQuestionConvertor::convert).collect(Collectors.toList()));
rsp.setSystemTime(System.currentTimeMillis());
return rsp;
BusinessExceptionAssertEnum.OPERATION_NOT_SUPPORTED.assertNotTrue(
req.getSubType() == PaperQType.SubType.Scene, "不支持此操作");
return training2PublishService.queryCountForLabel(req);
}
return 0L;
}
/**
* 删除用户试卷
*
* @param puId 用户试卷id
*/
@Transactional(rollbackFor = Exception.class)
public void deletePaperUser(Long puId) {
this.deletePaperQuestion(puId);
//删除试卷
paperUserDAO.deleteByPrimaryKey(puId);
}
/**
* 获取用户试卷完整信息
*
* @param puId 用户试卷id
*/
@Transactional(readOnly = true)
public PaperUserWholeVo findPaperUser(Long puId) {
PaperUser paper = paperUserDAO.selectByPrimaryKey(puId);
PaperExceptionAssert.PuExisted.assertNotNull(paper, "用户试卷不存在");
//
PaperComposition composition = compositionDAO.selectByPrimaryKey(paper.getPcId());
List<PaperRule> ruleList = compositionService.findRuleByPcId(composition.getId());
List<PaperUserQuestion> userQuestionList = this.findUserSortedQuestions(puId);
//
PaperUserWholeVo rsp = new PaperUserWholeVo();
rsp.setComposition(PaperCompositionConvertor.convert(composition, ruleList));
rsp.setPaper(PaperUserConvertor.convert(paper));
rsp.setQuestionList(userQuestionList.stream().map(PaperUserQuestionConvertor::convert)
.collect(Collectors.toList()));
rsp.setSystemTime(System.currentTimeMillis());
return rsp;
}
private void deletePaperQuestion(Long puId){
//删除试卷试题关联表
PaperUserQuestionExample puqExample = new PaperUserQuestionExample();
puqExample.createCriteria().andPuIdEqualTo(puId);
paperUserQuestionDAO.deleteByExample(puqExample);
}
/**
* 删除用户试卷
*
* @param puId 用户试卷id
*/
@Transactional(rollbackFor = Exception.class)
public void deletePaperUser(Long puId) {
this.deletePaperQuestion(puId);
//删除试卷
paperUserDAO.deleteByPrimaryKey(puId);
}
/**
* 开始答题
*
* @param puId 用户试卷id
*/
private void deletePaperQuestion(Long puId) {
//删除试卷试题关联表
PaperUserQuestionExample puqExample = new PaperUserQuestionExample();
puqExample.createCriteria().andPuIdEqualTo(puId);
paperUserQuestionDAO.deleteByExample(puqExample);
}
/**
* 开始答题
*
* @param puId 用户试卷id
*/
/*
@Transactional(rollbackFor = Exception.class)
public void paperStart(Long puId) {
@ -151,182 +161,193 @@ public class PaperUserService {
}
*/
/**
* 用户交卷
*
* @param puId 用户试卷id
*/
@Transactional(rollbackFor = Exception.class)
public PaperSubmitRspVo paperSubmit(Long puId) {
PaperUser paper = paperUserDAO.selectByPrimaryKey(puId);
PaperExceptionAssert.PuExisted.assertNotNull(paper, "该用户的试卷不存在puId = " + puId);
PaperExceptionAssert.PuStart.assertNotNull(paper.getStartTime(), "用户未开始答题");
PaperExceptionAssert.PuNotSubmit.assertNull(paper.getEndTime(), "用户已经交卷");
LocalDateTime now = LocalDateTime.now();
/**
* 用户交卷
*
* @param puId 用户试卷id
*/
@Transactional(rollbackFor = Exception.class)
public PaperSubmitRspVo paperSubmit(Long puId, AccountVO user) {
PaperUser paper = paperUserDAO.selectByPrimaryKey(puId);
PaperExceptionAssert.PuExisted.assertNotNull(paper, "该用户的试卷不存在puId = " + puId);
PaperExceptionAssert.PuStart.assertNotNull(paper.getStartTime(), "用户未开始答题");
PaperExceptionAssert.PuNotSubmit.assertNull(paper.getEndTime(), "用户已经交卷");
LocalDateTime now = LocalDateTime.now();
//统计最终结果
PaperComposition composition = compositionDAO.selectByPrimaryKey(paper.getPcId());
List<PaperRule> ruleList = compositionService.findRuleByPcId(paper.getPcId());
Map<Long, PaperRule> ruleIdMap = ruleList.stream().collect(Collectors.toMap(PaperRule::getId,Function.identity()));
//统计最终结果
PaperComposition composition = compositionDAO.selectByPrimaryKey(paper.getPcId());
List<PaperRule> ruleList = compositionService.findRuleByPcId(paper.getPcId());
Map<Long, PaperRule> ruleIdMap = ruleList.stream()
.collect(Collectors.toMap(PaperRule::getId, Function.identity()));
List<PaperUserQuestion> userQuestionList = findUserSortedQuestions(puId);
int scoreCommon = 0;
int scoreTraining = 0;
long paperTime = Duration.between(paper.getStartTime(), now).toMinutes();//实际做题时长min
for (PaperUserQuestion uq : userQuestionList) {
PaperRule rule = ruleIdMap.get(uq.getRuleId());
List<PaperUserQuestion> userQuestionList = findUserSortedQuestions(puId);
int scoreCommon = 0;
int scoreTraining = 0;
long paperTime = Duration.between(paper.getStartTime(), now).toMinutes();//实际做题时长min
for (PaperUserQuestion uq : userQuestionList) {
PaperRule rule = ruleIdMap.get(uq.getRuleId());
switch (PaperQType.GroupType.getItem(uq.getType())) {
case Common:
scoreCommon += calculateCommonScore(uq, rule);break;
case Training:
scoreTraining += calculateTrainingScore(uq, rule);break;
}
}
switch (PaperQType.GroupType.getItem(uq.getType())) {
case Common:
scoreCommon += calculateCommonScore(uq, rule);
break;
case Training:
scoreTraining += calculateTrainingScore(uq, rule);
break;
}
}
//记录交卷时间
PaperUser endPaper = new PaperUser();
endPaper.setId(puId);
endPaper.setEndTime(now);
endPaper.setScore(scoreCommon + scoreTraining);
paperUserDAO.updateByPrimaryKeySelective(endPaper);
//记录交卷时间
PaperUser endPaper = new PaperUser();
endPaper.setId(puId);
endPaper.setEndTime(now);
endPaper.setScore(scoreCommon + scoreTraining);
paperUserDAO.updateByPrimaryKeySelective(endPaper);
// this.deletePaperQuestion(puId);
//
PaperSubmitRspVo rsp = new PaperSubmitRspVo();
rsp.setPuId(puId);
rsp.setName(composition.getName());
rsp.setOrgId(composition.getOrgId());
rsp.setDuration(paperTime);
rsp.setScore(scoreCommon + scoreTraining);
rsp.setCommonScore(scoreCommon);
rsp.setTrainingScore(scoreTraining);
rsp.setPassScore(composition.getPassScore());
return rsp;
}
//
PaperSubmitRspVo rsp = new PaperSubmitRspVo();
rsp.setPuId(puId);
rsp.setName(composition.getName());
rsp.setOrgId(composition.getOrgId());
rsp.setDuration(paperTime);
rsp.setScore(scoreCommon + scoreTraining);
rsp.setCommonScore(scoreCommon);
rsp.setTrainingScore(scoreTraining);
rsp.setPassScore(composition.getPassScore());
// UserExam ue = new UserExam();
// ue.setExamId();
// ue.setUserId(user.getAccount());
//TODO 需要将 UserExam 发送 {@link UserExamService.submit 方法}
// this.applicationContext.publishEvent(new UserExamRecordEvent(userExam));
return rsp;
}
/**
* 获取题的最终得分
*/
private int calculateCommonScore(PaperUserQuestion puq, PaperRule rule) {
if (PaperQuestionState.Right.equals(PaperQuestionState.getItem(puq.getState()))) {//题答对时
return rule.getScore();
}
return 0;
/**
* 获取题的最终得分
*/
private int calculateCommonScore(PaperUserQuestion puq, PaperRule rule) {
if (PaperQuestionState.Right.equals(PaperQuestionState.getItem(puq.getState()))) {//题答对时
return rule.getScore();
}
return 0;
}
public static int getPercentage(double score,int sumScore,int ruleScore) {
if(score >= sumScore){
return ruleScore;
}
return new BigDecimal((score / sumScore) * ruleScore).setScale(0,RoundingMode.HALF_UP).intValue();
public static int getPercentage(double score, int sumScore, int ruleScore) {
if (score >= sumScore) {
return ruleScore;
}
return new BigDecimal((score / sumScore) * ruleScore).setScale(0, RoundingMode.HALF_UP)
.intValue();
/*double t = score / sumScore;
if(t <=0.5){
return (int)Math.round(t * ruleScore);
}
return (int)Math.floor(t * ruleScore);*/
}
}
/**
* 获取题的最终得分
*/
private int calculateTrainingScore(PaperUserQuestion puq,PaperRule rule) {
if(Objects.equals(puq.getSubType(), PaperQType.SubType.Single.getValue()) && PaperQuestionState.Right.equals(PaperQuestionState.getItem(puq.getState()))){
return rule.getScore();
}else if(Objects.equals(puq.getSubType(), PaperQType.SubType.Scene.getValue())){
if(Strings.isNullOrEmpty(puq.getTmpAnswer())){
return 0;
}
PaperSubmitAnswerReqVo.AnswerDetail answerDetail = JsonUtils.read(puq.getTmpAnswer(),PaperSubmitAnswerReqVo.AnswerDetail.class);
int sumScore = answerDetail.getSumScore();
double totalScore = answerDetail.getTrainDetail().stream().mapToDouble(PaperTrainAnswerDetail::getScore).sum();
return getPercentage(totalScore,sumScore,rule.getScore());
}
/**
* 获取题的最终得分
*/
private int calculateTrainingScore(PaperUserQuestion puq, PaperRule rule) {
if (Objects.equals(puq.getSubType(), PaperQType.SubType.Single.getValue())
&& PaperQuestionState.Right.equals(PaperQuestionState.getItem(puq.getState()))) {
return rule.getScore();
} else if (Objects.equals(puq.getSubType(), PaperQType.SubType.Scene.getValue())) {
if (Strings.isNullOrEmpty(puq.getTmpAnswer())) {
return 0;
}
PaperSubmitAnswerReqVo.AnswerDetail answerDetail = JsonUtils.read(puq.getTmpAnswer(),
PaperSubmitAnswerReqVo.AnswerDetail.class);
int sumScore = answerDetail.getSumScore();
double totalScore = answerDetail.getTrainDetail().stream()
.mapToDouble(PaperTrainAnswerDetail::getScore).sum();
return getPercentage(totalScore, sumScore, rule.getScore());
}
return 0;
}
/**
* 获取用户试卷试题(已排序)
*
* @param puId 用户试卷id
*/
@Transactional(readOnly = true)
public List<PaperUserQuestion> findUserSortedQuestions(Long puId) {
PaperUserQuestionExample example = new PaperUserQuestionExample();
example.createCriteria().andPuIdEqualTo(puId);
example.setOrderByClause(" id asc ");
List<PaperUserQuestion> findList = paperUserQuestionDAO.selectByExample(example);
findList.sort(Comparator.comparing(PaperUserQuestion::getId));
return findList;
}
/**
* 获取用户试卷试题(已排序)
*
* @param puId 用户试卷id
*/
@Transactional(readOnly = true)
public List<PaperUserQuestion> findUserSortedQuestions(Long puId) {
PaperUserQuestionExample example = new PaperUserQuestionExample();
example.createCriteria().andPuIdEqualTo(puId);
example.setOrderByClause(" id asc ");
List<PaperUserQuestion> findList = paperUserQuestionDAO.selectByExample(example);
findList.sort(Comparator.comparing(PaperUserQuestion::getId));
return findList;
/**
* @param pcId 试卷蓝图id
* @param userId 用户id
*/
@Transactional(readOnly = true)
public PaperUser findByUserIdAndPcId(Long userId, Long pcId) {
PaperUserExample example = new PaperUserExample();
example.createCriteria().andPcIdEqualTo(pcId).andUserIdEqualTo(userId);
List<PaperUser> list = paperUserDAO.selectByExample(example);
if (CollectionUtils.isEmpty(list)) {
return null;
} else {
return list.get(0);
}
}
/**
* @param pcId 试卷蓝图id
* @param userId 用户id
*/
@Transactional(readOnly = true)
public PaperUser findByUserIdAndPcId(Long userId, Long pcId) {
PaperUserExample example = new PaperUserExample();
example.createCriteria().andPcIdEqualTo(pcId).andUserIdEqualTo(userId);
List<PaperUser> list = paperUserDAO.selectByExample(example);
if (CollectionUtils.isEmpty(list)) {
return null;
} else {
return list.get(0);
}
public PaperQType.SubType getPaperQuestionType(PaperQuestion question) {
BusinessConsts.TheoryType theoryType = BusinessConsts.TheoryType.valueOf(question.getType());
switch (theoryType) {
case select:
return PaperQType.SubType.Select;
case judge:
return PaperQType.SubType.Judge;
case multi:
return PaperQType.SubType.Multi;
}
return null;
}
public PaperQType.SubType getPaperQuestionType(PaperQuestion question) {
BusinessConsts.TheoryType theoryType = BusinessConsts.TheoryType.valueOf(question.getType());
switch (theoryType) {
case select:
return PaperQType.SubType.Select;
case judge:
return PaperQType.SubType.Judge;
case multi:
return PaperQType.SubType.Multi;
}
return null;
public BusinessConsts.TheoryType getPaperQuestionType(PaperQType.SubType qt) {
switch (qt) {
case Judge:
return BusinessConsts.TheoryType.judge;
case Select:
return BusinessConsts.TheoryType.select;
case Multi:
return BusinessConsts.TheoryType.multi;
}
return null;
}
public BusinessConsts.TheoryType getPaperQuestionType(PaperQType.SubType qt) {
switch (qt) {
case Judge:
return BusinessConsts.TheoryType.judge;
case Select:
return BusinessConsts.TheoryType.select;
case Multi:
return BusinessConsts.TheoryType.multi;
}
return null;
/**
* 实训类型单操 single场景scene
*/
public PaperQType.SubType getTrainingType(PublishedTraining2 training) {
if (!StringUtils.hasText(training.getType())) {
log.error("发布列车类型为空 实训id[{}],实训名称[{}]", training.getId(), training.getName());
return null;
}
switch (training.getType().toLowerCase()) {
case "single":
return PaperQType.SubType.Single;
case "scene":
return PaperQType.SubType.Scene;
}
return null;
}
/**
* 实训类型单操 single场景scene
*/
public PaperQType.SubType getTrainingType(PublishedTraining2 training) {
if(!StringUtils.hasText(training.getType())){
log.error("发布列车类型为空 实训id[{}],实训名称[{}]",training.getId(),training.getName());
return null;
}
switch (training.getType().toLowerCase()) {
case "single":
return PaperQType.SubType.Single;
case "scene":
return PaperQType.SubType.Scene;
}
return null;
}
public String getTrainingType(PaperQType.SubType training) {
switch (training) {
case Single:
return "single";
case Scene:
return "scene";
}
return null;
public String getTrainingType(PaperQType.SubType training) {
switch (training) {
case Single:
return "single";
case Scene:
return "scene";
}
return null;
}
}

View File

@ -1,7 +1,7 @@
package club.joylink.rtss.services.thridAccount;
import club.joylink.rtss.entity.UserExam;
import club.joylink.rtss.entity.UserSimulationStats;
import club.joylink.rtss.entity.UserSimulationRecord;
import club.joylink.rtss.event.UserExamRecordEvent;
import club.joylink.rtss.event.UserSimulationRecordEvent;
import club.joylink.rtss.services.ISysUserService;
@ -10,6 +10,10 @@ import club.joylink.rtss.util.JsonUtils;
import club.joylink.rtss.vo.AccountVO;
import club.joylink.rtss.vo.LoginUserInfoVO;
import club.joylink.rtss.vo.thirdAccount.ThirdInterfaceConfig;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
@ -22,111 +26,112 @@ import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class ThirdAccountDataSyncService {
@Autowired
private ISysUserService iSysUserService;
@Autowired
private LoginSessionManager loginSessionManager;
@Autowired
private ThirdAccountConfigService thirdAccountConfigService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private ISysUserService iSysUserService;
@Autowired
private LoginSessionManager loginSessionManager;
@Autowired
private ThirdAccountConfigService thirdAccountConfigService;
@Autowired
private RestTemplate restTemplate;
@Async("thirdAccountDataSyncExecutor")
@EventListener
public void syncUserSimulationUsing(UserSimulationRecordEvent event) {
UserSimulationStats record = event.getRecord();
AccountVO accountVO = this.queryAccountVO(record.getUserId());
if (accountVO == null) { // 不是第三方账号,返回
return;
}
String parentAccount = accountVO.getParentAccount();
ThirdInterfaceConfig config = this.thirdAccountConfigService.getInterfaceConfigByAccountId(parentAccount);
Map<String, Object> syncRecordData = this.buildSyncUserSimulationRecordData(accountVO, record);
this.postToThird(config.getUserSimulationRecordSyncUrl(), syncRecordData);
@Async("thirdAccountDataSyncExecutor")
@EventListener
public void syncUserSimulationUsing(UserSimulationRecordEvent event) {
UserSimulationRecord record = event.getRecord();
AccountVO accountVO = this.queryAccountVO(record.getUserId());
if (accountVO == null) { // 不是第三方账号,返回
return;
}
String parentAccount = accountVO.getParentAccount();
ThirdInterfaceConfig config = this.thirdAccountConfigService.getInterfaceConfigByAccountId(
parentAccount);
Map<String, Object> syncRecordData = this.buildSyncUserSimulationRecordData(accountVO, record);
this.postToThird(config.getUserSimulationRecordSyncUrl(), syncRecordData);
}
@Async("thirdAccountDataSyncExecutor")
@EventListener
public void syncUserExamResult(UserExamRecordEvent event) {
UserExam record = event.getRecord();
AccountVO accountVO = this.queryAccountVO(record.getUserId());
if (accountVO == null) { // 不是第三方账号,返回
return;
}
String parentAccount = accountVO.getParentAccount();
ThirdInterfaceConfig config = this.thirdAccountConfigService.getInterfaceConfigByAccountId(parentAccount);
Map<String, Object> syncRecordData = this.buildSyncUserExamRecordData(accountVO, record);
this.postToThird(config.getUserExamRecordSyncUrl(), syncRecordData);
@Async("thirdAccountDataSyncExecutor")
@EventListener
public void syncUserExamResult(UserExamRecordEvent event) {
UserExam record = event.getRecord();
AccountVO accountVO = this.queryAccountVO(record.getUserId());
if (accountVO == null) { // 不是第三方账号,返回
return;
}
String parentAccount = accountVO.getParentAccount();
ThirdInterfaceConfig config = this.thirdAccountConfigService.getInterfaceConfigByAccountId(
parentAccount);
Map<String, Object> syncRecordData = this.buildSyncUserExamRecordData(accountVO, record);
this.postToThird(config.getUserExamRecordSyncUrl(), syncRecordData);
}
private AccountVO queryAccountVO(Long userId) {
AccountVO accountVO = null;
List<LoginUserInfoVO> loginInfoList = this.loginSessionManager.queryLoginInfoByUserId(userId);
if (!CollectionUtils.isEmpty(loginInfoList)) { // 用户在线
if (loginInfoList.get(0).getAccountVO().isThirdChildAccount()) {
accountVO = loginInfoList.get(0).getAccountVO();
}
} else {
AccountVO vo = this.iSysUserService.findUserById(userId);
if (vo != null && vo.isThirdChildAccount()) {
accountVO = vo;
}
}
return accountVO;
private AccountVO queryAccountVO(Long userId) {
AccountVO accountVO = null;
List<LoginUserInfoVO> loginInfoList = this.loginSessionManager.queryLoginInfoByUserId(userId);
if (!CollectionUtils.isEmpty(loginInfoList)) { // 用户在线
if (loginInfoList.get(0).getAccountVO().isThirdChildAccount()) {
accountVO = loginInfoList.get(0).getAccountVO();
}
} else {
AccountVO vo = this.iSysUserService.findUserById(userId);
if (vo != null && vo.isThirdChildAccount()) {
accountVO = vo;
}
}
return accountVO;
}
private void postToThird(String url, Map<String, Object> syncRecordData) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String body = JsonUtils.writeValueAsString(syncRecordData);
HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, httpEntity, String.class);
log.info("向第三方发送数据:" + body);
log.info("第三方同步数据接口Response" + responseEntity);
}
private void postToThird(String url, Map<String, Object> syncRecordData) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String body = JsonUtils.writeValueAsString(syncRecordData);
HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, httpEntity,
String.class);
log.info("向第三方发送数据:" + body);
log.info("第三方同步数据接口Response" + responseEntity);
}
private Map<String, Object> buildSyncUserSimulationRecordData(AccountVO accountVO, UserSimulationStats record) {
Map<String, Object> map = new HashMap<>();
map.put("userId", accountVO.getAccount());
map.put("type", record.getPrdType());
map.put("startTime", record.getStartTime());
map.put("endTime", record.getEndTime());
map.put("duration", record.getDuration());
return map;
}
private Map<String, Object> buildSyncUserSimulationRecordData(AccountVO accountVO,
UserSimulationRecord record) {
Map<String, Object> map = new HashMap<>();
map.put("userId", accountVO.getAccount());
map.put("type", String.valueOf(record.getFunctionId()));
map.put("startTime", record.getStartTime());
map.put("endTime", record.getEndTime());
map.put("duration", record.getDuration());
return map;
}
private Map<String, Object> buildSyncUserExamRecordData(AccountVO accountVO, UserExam record) {
Map<String, Object> map = new HashMap<>();
map.put("userId", accountVO.getAccount());
map.put("examName", record.getExamName());
map.put("usedTime", record.getUsedTime());
map.put("score", record.getScore());
return map;
}
private static class SyncUserSimulationRecord {
String userId;
/**
* 开始时间
*/
private LocalDateTime startTime;
private Map<String, Object> buildSyncUserExamRecordData(AccountVO accountVO, UserExam record) {
Map<String, Object> map = new HashMap<>();
map.put("userId", accountVO.getAccount());
map.put("examName", record.getExamName());
map.put("usedTime", record.getUsedTime());
map.put("score", record.getScore());
return map;
}
/**
* 结束时间
*/
private LocalDateTime endTime;
private static class SyncUserSimulationRecord {
/**
* 有效时长
*/
private Integer duration;
}
String userId;
/**
* 开始时间
*/
private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime;
/**
* 有效时长
*/
private Integer duration;
}
}

View File

@ -5,6 +5,7 @@ import club.joylink.rtss.entity.RtsMapFunction;
import club.joylink.rtss.entity.SysAccount;
import club.joylink.rtss.entity.UserSimulationRecord;
import club.joylink.rtss.entity.UserSimulationRecordExample;
import club.joylink.rtss.event.UserSimulationRecordEvent;
import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
import club.joylink.rtss.services.IMapService;
import club.joylink.rtss.services.ISysUserService;
@ -18,12 +19,6 @@ import club.joylink.rtss.vo.client.simulationUsage.UserSimulationStatsVO;
import club.joylink.rtss.vo.map.MapVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
@ -33,186 +28,205 @@ import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
@Service
public class UserSimulationRecordService {
@Autowired
private UserSimulationRecordDAO userSimulationRecordDAO;
@Autowired
private ISysUserService iSysUserService;
@Autowired
private RtsMapFunctionService rtsMapFunctionService;
@Autowired
private IMapService iMapService;
/**
* 添加记录
*/
public void addRecord(UserSimulationRecordManager.SimulationUseInfo simulationUseInfo) {
UserSimulationRecord record = new UserSimulationRecord();
record.setMapId(simulationUseInfo.getMapId());
record.setUserId(simulationUseInfo.getUserId());
record.setType(simulationUseInfo.getType());
record.setFunctionId(simulationUseInfo.getFunctionId());
record.setDuration(simulationUseInfo.getDuration());
record.setStartTime(simulationUseInfo.getStartTime());
record.setEndTime(LocalDateTime.now());
userSimulationRecordDAO.insert(record);
@Autowired
private UserSimulationRecordDAO userSimulationRecordDAO;
@Autowired
private ISysUserService iSysUserService;
@Autowired
private RtsMapFunctionService rtsMapFunctionService;
@Autowired
private IMapService iMapService;
@Autowired
private ApplicationContext applicationContext;
/**
* 添加记录
*/
public void addRecord(UserSimulationRecordManager.SimulationUseInfo simulationUseInfo) {
UserSimulationRecord record = new UserSimulationRecord();
record.setMapId(simulationUseInfo.getMapId());
record.setUserId(simulationUseInfo.getUserId());
record.setType(simulationUseInfo.getType());
record.setFunctionId(simulationUseInfo.getFunctionId());
record.setDuration(simulationUseInfo.getDuration());
record.setStartTime(simulationUseInfo.getStartTime());
record.setEndTime(LocalDateTime.now());
userSimulationRecordDAO.insert(record);
applicationContext.publishEvent(new UserSimulationRecordEvent(record));
}
public List<UserSimulationRecord> queryByMapAndUserIds(Long mapId, List<Long> userIds) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertCollectionNotEmpty(userIds, "用户列表不能为空");
UserSimulationRecordExample example = new UserSimulationRecordExample();
example.createCriteria().andMapIdEqualTo(mapId).andUserIdIn(userIds);
return userSimulationRecordDAO.selectByExample(example);
}
public PageVO<UserSimulationRecordVO> pagedQueryUserSimulationRecord(String accountSource,
UserSimulationQueryVO queryVO) {
List<SysAccount> accounts = iSysUserService.findEntitiesBySource(accountSource);
List<Long> accountIds = accounts.stream().map(SysAccount::getId).collect(Collectors.toList());
if (CollectionUtils.isEmpty(accounts)) {
return new PageVO<>(queryVO.getPageNum(), queryVO.getPageSize(), 0, null);
}
public List<UserSimulationRecord> queryByMapAndUserIds(Long mapId, List<Long> userIds) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertCollectionNotEmpty(userIds, "用户列表不能为空");
UserSimulationRecordExample example = new UserSimulationRecordExample();
example.createCriteria().andMapIdEqualTo(mapId).andUserIdIn(userIds);
return userSimulationRecordDAO.selectByExample(example);
UserSimulationRecordExample example = new UserSimulationRecordExample();
example.setOrderByClause("end_time desc");
UserSimulationRecordExample.Criteria criteria = example.createCriteria()
.andUserIdIn(accountIds);
if (StringUtils.hasText(queryVO.getType())) {
criteria.andTypeEqualTo(queryVO.getType());
}
if (queryVO.getStartTime() != null) {
criteria.andEndTimeGreaterThanOrEqualTo(queryVO.getStartTime());
}
if (queryVO.getEndTime() != null) {
criteria.andEndTimeLessThanOrEqualTo(queryVO.getEndTime());
}
public PageVO<UserSimulationRecordVO> pagedQueryUserSimulationRecord(String accountSource, UserSimulationQueryVO queryVO) {
List<SysAccount> accounts = iSysUserService.findEntitiesBySource(accountSource);
List<Long> accountIds = accounts.stream().map(SysAccount::getId).collect(Collectors.toList());
if (CollectionUtils.isEmpty(accounts)) {
return new PageVO<>(queryVO.getPageNum(), queryVO.getPageSize(), 0, null);
}
UserSimulationRecordExample example = new UserSimulationRecordExample();
example.setOrderByClause("end_time desc");
UserSimulationRecordExample.Criteria criteria = example.createCriteria().andUserIdIn(accountIds);
if (StringUtils.hasText(queryVO.getType())) {
criteria.andTypeEqualTo(queryVO.getType());
}
if (queryVO.getStartTime() != null) {
criteria.andEndTimeGreaterThanOrEqualTo(queryVO.getStartTime());
}
if (queryVO.getEndTime() != null) {
criteria.andEndTimeLessThanOrEqualTo(queryVO.getEndTime());
}
Page<UserSimulationRecord> page = PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize());
List<UserSimulationRecord> entities = userSimulationRecordDAO.selectByExample(example);
List<Long> functionIds = entities.stream()
.filter(record -> record.getFunctionId() != null)
.distinct()
.map(UserSimulationRecord::getFunctionId)
.collect(Collectors.toList());
Map<Long, String> functionIdNameMap = rtsMapFunctionService.listByIds(functionIds)
.stream().collect(Collectors.toMap(RtsMapFunction::getId, RtsMapFunction::getName));
Map<Long, SysAccount> accountMap = accounts.stream().collect(Collectors.toMap(SysAccount::getId, Function.identity()));
List<UserSimulationRecordVO> vos = UserSimulationRecordVO.convert(entities);
for (UserSimulationRecordVO vo : vos) {
SysAccount account = accountMap.get(vo.getUserId());
if (account != null) {
vo.setUserName(account.getName());
vo.setUserNickName(account.getNickname());
vo.setFunctionName(functionIdNameMap.get(vo.getFunctionId()));
}
}
return PageVO.convert(page, vos);
Page<UserSimulationRecord> page = PageHelper.startPage(queryVO.getPageNum(),
queryVO.getPageSize());
List<UserSimulationRecord> entities = userSimulationRecordDAO.selectByExample(example);
List<Long> functionIds = entities.stream()
.filter(record -> record.getFunctionId() != null)
.distinct()
.map(UserSimulationRecord::getFunctionId)
.collect(Collectors.toList());
Map<Long, String> functionIdNameMap = rtsMapFunctionService.listByIds(functionIds)
.stream().collect(Collectors.toMap(RtsMapFunction::getId, RtsMapFunction::getName));
Map<Long, SysAccount> accountMap = accounts.stream()
.collect(Collectors.toMap(SysAccount::getId, Function.identity()));
List<UserSimulationRecordVO> vos = UserSimulationRecordVO.convert(entities);
for (UserSimulationRecordVO vo : vos) {
SysAccount account = accountMap.get(vo.getUserId());
if (account != null) {
vo.setUserName(account.getName());
vo.setUserNickName(account.getNickname());
vo.setFunctionName(functionIdNameMap.get(vo.getFunctionId()));
}
}
return PageVO.convert(page, vos);
}
public List<UserSimulationStatsVO> listSimulationUsageStats(long userId, UserSimulationQueryVO queryVO) {
checkParam(queryVO);
// 根据时间单位获取区间内所有数据
LocalDateTime startTime = queryVO.getStartTime();
LocalDateTime endTime = queryVO.getEndTime();
TimeUnit timeUnit = queryVO.getTimeUnit();
UserSimulationRecordExample example = new UserSimulationRecordExample();
UserSimulationRecordExample.Criteria criteria = example.createCriteria()
.andUserIdEqualTo(userId)
.andStartTimeBetween(startTime, endTime);
if (StringUtils.hasText(queryVO.getType())) {
criteria.andTypeEqualTo(queryVO.getType());
public List<UserSimulationStatsVO> listSimulationUsageStats(long userId,
UserSimulationQueryVO queryVO) {
checkParam(queryVO);
// 根据时间单位获取区间内所有数据
LocalDateTime startTime = queryVO.getStartTime();
LocalDateTime endTime = queryVO.getEndTime();
TimeUnit timeUnit = queryVO.getTimeUnit();
UserSimulationRecordExample example = new UserSimulationRecordExample();
UserSimulationRecordExample.Criteria criteria = example.createCriteria()
.andUserIdEqualTo(userId)
.andStartTimeBetween(startTime, endTime);
if (StringUtils.hasText(queryVO.getType())) {
criteria.andTypeEqualTo(queryVO.getType());
}
List<UserSimulationRecord> list = userSimulationRecordDAO.selectByExample(example);
return statistic(startTime, endTime, timeUnit, list);
}
/**
* 查询指定来源的用户的使用记录统计
*
* @param projectCode 账号来源
*/
public List<UserSimulationStatsVO> listSimulationUsageStats(String projectCode,
UserSimulationQueryVO queryVO) {
List<Long> mapIds = iMapService.listByProjectCode(projectCode).stream().map(MapVO::getId)
.collect(Collectors.toList());
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertCollectionNotEmpty(mapIds, "该项目下无地图");
checkParam(queryVO);
LocalDateTime startTime = queryVO.getStartTime();
LocalDateTime endTime = queryVO.getEndTime();
TimeUnit timeUnit = queryVO.getTimeUnit();
List<UserSimulationRecord> list;
UserSimulationRecordExample example = new UserSimulationRecordExample();
UserSimulationRecordExample.Criteria criteria = example.createCriteria()
.andMapIdIn(mapIds)
.andStartTimeBetween(startTime, endTime);
if (StringUtils.hasText(queryVO.getType())) {
criteria.andTypeEqualTo(queryVO.getType());
}
list = userSimulationRecordDAO.selectByExample(example);
return statistic(startTime, endTime, timeUnit, list);
}
/**
* 对使用记录按照时间单位开始结束时间分段统计
*/
@NotNull
private List<UserSimulationStatsVO> statistic(LocalDateTime startTime, LocalDateTime endTime,
TimeUnit timeUnit, List<UserSimulationRecord> list) {
List<String> timeSegmentList = new ArrayList<>();
// 将数据按时间单位分段统计
Map<String, Integer> timeSegmentDurationMap;
switch (timeUnit) {
case YEAR:
for (int from = startTime.getYear(), to = endTime.getYear(); from <= to; from++) {
timeSegmentList.add(String.valueOf(from));
}
List<UserSimulationRecord> list = userSimulationRecordDAO.selectByExample(example);
return statistic(startTime, endTime, timeUnit, list);
}
/**
* 查询指定来源的用户的使用记录统计
*
* @param projectCode 账号来源
*/
public List<UserSimulationStatsVO> listSimulationUsageStats(String projectCode, UserSimulationQueryVO queryVO) {
List<Long> mapIds = iMapService.listByProjectCode(projectCode).stream().map(MapVO::getId).collect(Collectors.toList());
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertCollectionNotEmpty(mapIds, "该项目下无地图");
checkParam(queryVO);
LocalDateTime startTime = queryVO.getStartTime();
LocalDateTime endTime = queryVO.getEndTime();
TimeUnit timeUnit = queryVO.getTimeUnit();
List<UserSimulationRecord> list;
UserSimulationRecordExample example = new UserSimulationRecordExample();
UserSimulationRecordExample.Criteria criteria = example.createCriteria()
.andMapIdIn(mapIds)
.andStartTimeBetween(startTime, endTime);
if (StringUtils.hasText(queryVO.getType())) {
criteria.andTypeEqualTo(queryVO.getType());
timeSegmentDurationMap = list.stream().collect(Collectors.groupingBy(
record -> String.valueOf(record.getStartTime().getYear()),
LinkedHashMap::new,
Collectors.summingInt(UserSimulationRecord::getDuration)
));
break;
case MONTH: {
YearMonth from = YearMonth.from(startTime);
YearMonth to = YearMonth.from(endTime);
while (!from.isAfter(to)) {
timeSegmentList.add(from.toString());
from = from.plusMonths(1);
}
list = userSimulationRecordDAO.selectByExample(example);
return statistic(startTime, endTime, timeUnit, list);
}
/**
* 对使用记录按照时间单位开始结束时间分段统计
*/
@NotNull
private List<UserSimulationStatsVO> statistic(LocalDateTime startTime, LocalDateTime endTime, TimeUnit timeUnit, List<UserSimulationRecord> list) {
List<String> timeSegmentList = new ArrayList<>();
// 将数据按时间单位分段统计
Map<String, Integer> timeSegmentDurationMap;
switch (timeUnit) {
case YEAR:
for (int from = startTime.getYear(), to = endTime.getYear(); from <= to; from++) {
timeSegmentList.add(String.valueOf(from));
}
timeSegmentDurationMap = list.stream().collect(Collectors.groupingBy(
record -> String.valueOf(record.getStartTime().getYear()),
LinkedHashMap::new,
Collectors.summingInt(UserSimulationRecord::getDuration)
));
break;
case MONTH: {
YearMonth from = YearMonth.from(startTime);
YearMonth to = YearMonth.from(endTime);
while (!from.isAfter(to)) {
timeSegmentList.add(from.toString());
from = from.plusMonths(1);
}
timeSegmentDurationMap = list.stream().collect(Collectors.groupingBy(
record -> YearMonth.from(record.getStartTime().toLocalDate()).toString(),
LinkedHashMap::new,
Collectors.summingInt(UserSimulationRecord::getDuration)
));
break;
}
case DAY: {
LocalDate from = startTime.toLocalDate();
LocalDate to = endTime.toLocalDate();
while (!from.isAfter(to)) {
timeSegmentList.add(from.toString());
from = from.plusDays(1);
}
timeSegmentDurationMap = list.stream().collect(Collectors.groupingBy(
record -> record.getStartTime().toLocalDate().toString(),
LinkedHashMap::new,
Collectors.summingInt(UserSimulationRecord::getDuration)
));
break;
}
default:
throw new IllegalStateException("Unexpected value: " + timeUnit);
timeSegmentDurationMap = list.stream().collect(Collectors.groupingBy(
record -> YearMonth.from(record.getStartTime().toLocalDate()).toString(),
LinkedHashMap::new,
Collectors.summingInt(UserSimulationRecord::getDuration)
));
break;
}
case DAY: {
LocalDate from = startTime.toLocalDate();
LocalDate to = endTime.toLocalDate();
while (!from.isAfter(to)) {
timeSegmentList.add(from.toString());
from = from.plusDays(1);
}
return timeSegmentList.stream().map(ts -> {
Integer duration = timeSegmentDurationMap.getOrDefault(ts, 0);
return new UserSimulationStatsVO(duration, ts);
}).collect(Collectors.toList());
timeSegmentDurationMap = list.stream().collect(Collectors.groupingBy(
record -> record.getStartTime().toLocalDate().toString(),
LinkedHashMap::new,
Collectors.summingInt(UserSimulationRecord::getDuration)
));
break;
}
default:
throw new IllegalStateException("Unexpected value: " + timeUnit);
}
return timeSegmentList.stream().map(ts -> {
Integer duration = timeSegmentDurationMap.getOrDefault(ts, 0);
return new UserSimulationStatsVO(duration, ts);
}).collect(Collectors.toList());
}
private void checkParam(UserSimulationQueryVO queryVO) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getTimeUnit(), "缺少时间单位");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getStartTime(), "缺少开始时间");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getEndTime(), "缺少结束时间");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(!queryVO.getStartTime().isAfter(queryVO.getEndTime()), "开始时间不能晚于结束时间");
}
private void checkParam(UserSimulationQueryVO queryVO) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getTimeUnit(), "缺少时间单位");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getStartTime(), "缺少开始时间");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getEndTime(), "缺少结束时间");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(
!queryVO.getStartTime().isAfter(queryVO.getEndTime()), "开始时间不能晚于结束时间");
}
}

View File

@ -3,7 +3,9 @@ package club.joylink.rtss.simulation.cbtc.ATS.service.alarm;
import club.joylink.rtss.simulation.cbtc.ATS.data.AtsAlarm;
import club.joylink.rtss.simulation.cbtc.Simulation;
import club.joylink.rtss.simulation.cbtc.data.SimulationDataRepository;
import club.joylink.rtss.simulation.cbtc.data.map.MapElement;
import club.joylink.rtss.simulation.cbtc.data.map.MayOutOfOrderDevice;
import club.joylink.rtss.simulation.cbtc.data.map.MayOutOfOrderDevice.DeviceFault;
import club.joylink.rtss.simulation.cbtc.data.map.Section;
import club.joylink.rtss.simulation.cbtc.data.map.Station;
import club.joylink.rtss.simulation.cbtc.data.map.Switch.SwitchFault;
@ -123,23 +125,32 @@ public class NccAlarmService {
private String analyzeReason(SimulationDataRepository repository, TrainInfo trainInfo) {
List<AtsAlarm> alarmList = repository.getAlarmList();
if (!CollectionUtils.isEmpty(alarmList)) {
Optional<AtsAlarm> deviceFaultAlarm = alarmList.stream()
.filter(alarm -> AtsAlarm.HandleMethod.ATS.equals(alarm.getHandleMethod()))
.findFirst();
if (deviceFaultAlarm.isPresent()) {
AtsAlarm atsAlarm = deviceFaultAlarm.get();
MayOutOfOrderDevice device = repository.getByCode(atsAlarm.getDeviceCode(),
MayOutOfOrderDevice.class);
String fault = device.getFault().toString();
if (SwitchFault.SPLIT.name().equals(fault)) {
fault = "失表";
}
return String.format("%s(%s)%s", device.getDeviceType().getName(), device.getCode(),
fault);
}
String defaultReason = "其它原因";
if (CollectionUtils.isEmpty(alarmList)) {
return defaultReason;
}
return "其它原因";
Optional<AtsAlarm> deviceFaultAlarm = alarmList.stream()
.filter(alarm -> AtsAlarm.HandleMethod.ATS.equals(alarm.getHandleMethod()))
.findFirst();
if (deviceFaultAlarm.isEmpty()) {
return defaultReason;
}
AtsAlarm atsAlarm = deviceFaultAlarm.get();
MapElement element = repository.getByCode(atsAlarm.getCode());
if (!(element instanceof MayOutOfOrderDevice)) {
return defaultReason;
}
MayOutOfOrderDevice device = repository.getByCode(atsAlarm.getDeviceCode(),
MayOutOfOrderDevice.class);
DeviceFault deviceFault = device.getFault();
if (deviceFault == null) {
return defaultReason;
}
String fault = deviceFault.toString();
if (SwitchFault.SPLIT.name().equals(fault)) {
fault = "失表";
}
return String.format("%s(%s)%s", device.getDeviceType().getName(), device.getName(), fault);
// //列车故障
// VirtualRealityTrain train = repository.queryOnlineTrainBy(trainInfo.getGroupNumber());

View File

@ -67,13 +67,9 @@ public class ConversationGroupHandlerService {
* @param memberIds 群组成员
*/
public ConversationGroupVO createConversationGroup(Simulation simulation, SimulationMember member, String imageUrl, String name, List<String> memberIds) {
ConversationGroup conversationGroup = simulation.getConversationGroupByName(name);
if (conversationGroup != null) {
throw new SimulationException(SimulationExceptionType.Illegal_Argument, "" + name + "】已存在");
}
List<SimulationMember> simulationMembers = memberIds.stream().map(simulation::getSimulationMemberById).collect(Collectors.toList());
Long groupId = simulation.getMaxConversationGroupId();
conversationGroup = new ConversationGroup(groupId, imageUrl, name, simulation.getCorrectSystemTime(), member, simulationMembers);
ConversationGroup conversationGroup = new ConversationGroup(groupId, imageUrl, name, simulation.getCorrectSystemTime(), member, simulationMembers);
conversationGroup.initGroupType();
simulation.addConversationGroup(conversationGroup);
// 通知用户消息
@ -91,13 +87,6 @@ public class ConversationGroupHandlerService {
*/
public void updateConversationGroupName(Simulation simulation, SimulationMember member, Long id, String name) {
ConversationGroup conversationGroup = checkGroupIdAndReturn(simulation, member, id);
// 查找名称是否已存在
ConversationGroup nameConversationGroup = simulation.getConversationGroupByName(name);
if (nameConversationGroup != null && !Objects.equals(id, nameConversationGroup.getId())) {
throw new SimulationException(SimulationExceptionType.Illegal_Argument, "" + name + "】已存在");
} else if (nameConversationGroup != null && Objects.equals(id, nameConversationGroup.getId())) {
return;
}
conversationGroup.setName(name);
// 通知其他用户群名变更
applicationEventPublisher.publishEvent(new SimulationConversationGroupUpdateEvent(this, simulation, conversationGroup, ConversationGroupSocketMessageVO.MessageType.UPDATE_NAME));