'use strict'; const { CrudService } = require('naf-framework-mongoose-free/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const _ = require('lodash'); const assert = require('assert'); // class LessonService extends CrudService { constructor(ctx) { super(ctx, 'lesson'); this.model = this.ctx.model.Business.Lesson; this.lessonCoachModel = this.ctx.model.Business.LessonCoach; this.lessonStudentModel = this.ctx.model.Business.LessonStudent; this.coachInBillService = this.ctx.service.business.coachInBill; } /** * 处理下课的课程进行结算 * @param {Object} filter 修改条件 * @param {Object} body 修改内容 * @param {Object} data 修改后的结果 * @return {Object} 返回整理后的内容 */ async afterUpdate(filter, body, data) { const { _id: lesson_id, type, status, school_id } = data; if (status !== '4') return data; const arr = []; if (type === '0') { // 公开课,每个教师都带着自己的金额. 按 人头数 * 单价 算钱 const lessonCoachList = await this.lessonCoachModel.find({ lesson_id }); // 这节课付了款的学生总数 const studentNum = await this.lessonStudentModel.count({ lesson_id, is_pay: '1' }); const obj = { lesson_id, type, school_id }; for (const c of lessonCoachList) { const { coach_id, money } = c; const total = money * studentNum; arr.push({ ...obj, coach_id, money: total }); } } else { // 私教课, 按学生实际缴费 const lessonCoach = await this.lessonCoachModel.findOne({ lesson_id }); const studentList = await this.lessonStudentModel.find({ lesson_id }); const obj = { lesson_id, type, school_id }; obj.coach_id = lessonCoach.coach_id; const total = studentList.reduce((p, n) => p + (n.money || 0), 0); obj.money = total; arr.push(obj); } // 创建,如果有该学校,这节课的这个教练已经有数据了,就不需要生成了 for (const i of arr) { try { await this.coachInBillService.create(i); } catch (error) { // 不是数据有问题,就是有数据了,要不一般不会出错 } } return data; } } module.exports = LessonService;