group.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 GroupService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'group');
  10. this.model = this.ctx.model.Group;
  11. this.smodel = this.ctx.model.Student;
  12. }
  13. async insert(data) {
  14. const { groupid, stuid, stuname } = data;
  15. const group = await this.model.findById(groupid);
  16. const stuids = [];
  17. for (const student of group.students) {
  18. stuids.push(student.stuid);
  19. }
  20. if (stuids.includes(stuid)) {
  21. throw new BusinessError(
  22. ErrorCode.DATA_EXIST,
  23. '您已加入该组,请勿重复操作'
  24. );
  25. } else {
  26. group.students.push({ stuid, stuname });
  27. await group.save();
  28. }
  29. }
  30. async exit(data) {
  31. const { groupid, stuid } = data;
  32. const group = await this.model.findById(groupid);
  33. const students = group.students;
  34. for (const student of students) {
  35. if (student.stuid === stuid) {
  36. students.remove(student);
  37. }
  38. }
  39. await group.save();
  40. }
  41. // 设置学生为组长或组员
  42. async sethead(data) {
  43. const { groupid, stuid, type } = data;
  44. const group = await this.model.findById(groupid);
  45. const students = group.students;
  46. for (const student of students) {
  47. if (student.stuid === stuid) {
  48. student.type = type;
  49. }
  50. }
  51. await group.save();
  52. const student = await this.smodel.findById(stuid);
  53. if (type === '1') {
  54. student.jod = '组长';
  55. }
  56. if (type === '0') {
  57. student.jod = '普通学生';
  58. }
  59. await student.save();
  60. }
  61. async findbystuid(data) {
  62. const { stuid } = data;
  63. const _student = await this.smodel.findById(stuid);
  64. const groups = await this.model.find({ classid: _student.classid });
  65. let result;
  66. for (const group of groups) {
  67. const students = group.students;
  68. for (const student of students) {
  69. if (student.stuid === stuid) {
  70. result = group;
  71. }
  72. }
  73. }
  74. if (!result) {
  75. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '该学生尚未进组');
  76. }
  77. return result;
  78. }
  79. }
  80. module.exports = GroupService;