lesson.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 LessonService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'lesson');
  10. this.model = this.ctx.model.Business.Lesson;
  11. this.lessonCoachModel = this.ctx.model.Business.LessonCoach;
  12. this.lessonStudentModel = this.ctx.model.Business.LessonStudent;
  13. this.coachInBillService = this.ctx.service.business.coachInBill;
  14. }
  15. /**
  16. * 处理下课的课程进行结算
  17. * @param {Object} filter 修改条件
  18. * @param {Object} body 修改内容
  19. * @param {Object} data 修改后的结果
  20. * @return {Object} 返回整理后的内容
  21. */
  22. async afterUpdate(filter, body, data) {
  23. const { _id: lesson_id, type, status, school_id } = data;
  24. if (status !== '4') return data;
  25. const arr = [];
  26. if (type === '0') {
  27. // 公开课,每个教师都带着自己的金额. 按 人头数 * 单价 算钱
  28. const lessonCoachList = await this.lessonCoachModel.find({ lesson_id });
  29. // 这节课付了款的学生总数
  30. const studentNum = await this.lessonStudentModel.count({ lesson_id, is_pay: '1' });
  31. const obj = { lesson_id, type, school_id };
  32. for (const c of lessonCoachList) {
  33. const { coach_id, money } = c;
  34. const total = money * studentNum;
  35. arr.push({ ...obj, coach_id, money: total });
  36. }
  37. } else {
  38. // 私教课, 按学生实际缴费
  39. const lessonCoach = await this.lessonCoachModel.findOne({ lesson_id });
  40. const studentList = await this.lessonStudentModel.find({ lesson_id });
  41. const obj = { lesson_id, type, school_id };
  42. obj.coach_id = lessonCoach.coach_id;
  43. const total = studentList.reduce((p, n) => p + (n.money || 0), 0);
  44. obj.money = total;
  45. arr.push(obj);
  46. }
  47. // 创建,如果有该学校,这节课的这个教练已经有数据了,就不需要生成了
  48. for (const i of arr) {
  49. try {
  50. await this.coachInBillService.create(i);
  51. } catch (error) {
  52. // 不是数据有问题,就是有数据了,要不一般不会出错
  53. }
  54. }
  55. return data;
  56. }
  57. }
  58. module.exports = LessonService;