tryLessonApply.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. //
  7. class TryLessonApplyService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'trylessonapply');
  10. this.model = this.ctx.model.Apply.TryLessonApply;
  11. this.lessonStudentService = this.ctx.service.business.lessonStudent;
  12. }
  13. async beforeCreate(body) {
  14. const { school_id, lesson_id, student_id } = body;
  15. // 该学校,该节课,这名学员. 申请试听的申请状态为 未审核或审核通过时
  16. let num = await this.model.count({ school_id, lesson_id, student_id, result: '0' });
  17. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '本节课的试听申请在审核中,无法重复申请');
  18. num = await this.model.count({ school_id, lesson_id, student_id, result: '1' });
  19. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '本节课的试听申请已通过,无法重复申请');
  20. // 查询这个学员在该学校是否使用过试听
  21. num = await this.model.count({ school_id, student_id, result: '1' });
  22. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该学员已经在本校试听过课程,无法重复申请');
  23. return body;
  24. }
  25. async beforeUpdate(filter, update) {
  26. // 不是 审核通过的情况就不需要继续检查是否使用过试听名额了
  27. if (update.result !== '1') return { filter, update };
  28. const data = await this.model.findById(filter.id);
  29. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到数据');
  30. const { school_id, student_id } = data;
  31. const num = await this.model.count({ school_id, student_id, result: '1' });
  32. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该学员已经在本校试听过课程,无法重复申请');
  33. return { filter, update };
  34. }
  35. // 处理审核成功的情况
  36. async afterUpdate(filter, body, data) {
  37. const { result } = data;
  38. // 审核不通过, 不处理
  39. if (result !== '1') return data;
  40. // 通过,则需要在 lessonStudent中添加数据
  41. const obj = _.pick(data, [ 'school_id', 'lesson_id', 'student_id' ]);
  42. obj.is_try = '1';
  43. await this.lessonStudentService.create(obj);
  44. return data;
  45. }
  46. }
  47. module.exports = TryLessonApplyService;