score.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. class ScoreService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'score');
  10. this.model = this.ctx.model.Score;
  11. this.tmodel = this.ctx.model.Teacher;
  12. }
  13. async create(data) {
  14. const { lessonid, stuid, teacherid, score, remark } = data;
  15. let res = await this.model.findOne({ stuid, lessonid, teacherid });
  16. if (res) {
  17. if (score) res.score = score;
  18. if (remark)res.remark = remark;
  19. res = await res.save();
  20. } else {
  21. res = await this.model.create(data);
  22. }
  23. // const res = await this.model.create(data);
  24. this.computedScore({ teacherid });
  25. return res;
  26. }
  27. async update({ id, score, remark }) {
  28. const r = await this.model.findById(id);
  29. if (r) {
  30. // 修改分数,重置状态,下面重新计算
  31. r.score = score;
  32. r.remark = remark;
  33. await r.save();
  34. }
  35. this.computedScore({ teacherid: r.teacherid });
  36. }
  37. // 根据教师id计算教师分数
  38. async computedScore({ teacherid }) {
  39. assert(teacherid, '没有教师信息,无法计算分数');
  40. const teacher = await this.tmodel.findById(teacherid);
  41. if (!teacher) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '没有找到教师信息');
  42. const { beforescore } = teacher;
  43. let teaScoreList = await this.model.find({ teacherid });
  44. // 判断有没有学生给评分
  45. if (teaScoreList.length <= 0) return;
  46. teaScoreList = teaScoreList.map(i => {
  47. i.score = i.score * 1;
  48. return i;
  49. });
  50. // 2021-06-04修改:过滤6分以下的恶意评分
  51. teaScoreList = teaScoreList.filter(f => f.score > 6);
  52. teaScoreList = _.uniqBy(teaScoreList, 'stuid');
  53. teaScoreList = _.orderBy(teaScoreList, [ 'score' ], [ 'desc' ]);
  54. teaScoreList = _.drop(teaScoreList);
  55. teaScoreList = _.dropRight(teaScoreList);
  56. const stuScoreTotal = teaScoreList.reduce((p, n) => p + (n.score * 1 || 0), 0);
  57. let score = 0;
  58. if (beforescore) {
  59. score = _.round(_.divide(beforescore * 1 + stuScoreTotal * 1, (teaScoreList.length || 0) + 1), 2);
  60. } else {
  61. score = _.round(_.divide(stuScoreTotal * 1, teaScoreList.length), 2);
  62. }
  63. teacher.xsscore = score;
  64. await teacher.save();
  65. }
  66. // 手动触发,重新计算所有的教师的分数
  67. async computedAllTeacherScore() {
  68. const teacherList = await this.tmodel.find();
  69. for (const t of teacherList) {
  70. const { _id } = t;
  71. await this.computedScore({ teacherid: _id });
  72. }
  73. }
  74. }
  75. module.exports = ScoreService;