tempLessonApply.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. const moment = require('moment');
  7. //
  8. class TempLessonApplyService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'templessonapply');
  11. this.model = this.ctx.model.Apply.TempLessonApply;
  12. this.payOrderService = this.ctx.service.business.payOrder;
  13. this.lessonStudentService = this.ctx.service.business.lessonStudent;
  14. }
  15. async beforeCreate(data) {
  16. const query = _.pick(data, [ 'school_id', 'lesson_id', 'student_id', 'coach_id' ]);
  17. const num = await this.model.count(query);
  18. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '学生已申请临时参加课程');
  19. return data;
  20. }
  21. // 去支付,生成支付单
  22. async toPay({ id, payer_id }) {
  23. const data = await this.model.findById(id);
  24. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到临时上课的申请,无法进行支付');
  25. const { student_id, coach_id, lesson_id, school_id, money } = data;
  26. const payer_role = payer_id === student_id ? 'Student' : payer_id === coach_id ? 'Coach' : null;
  27. if (!payer_role) throw new BusinessError(ErrorCode.DATA_INVALID, '该支付用户不是学生也不是教练');
  28. const obj = { payer_id, payer_role, pay_for: 'Lesson', from_id: lesson_id, school_id, money, time: moment().format('YYYY-MM-DD HH:mm:ss'), desc: '私教课' };
  29. // 找openid
  30. const user = await this.ctx.model.User[payer_role].findById(payer_id).populate('user_id');
  31. if (!user) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户信息');
  32. const openid = _.get(user, 'user_id.openid');
  33. if (!openid) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户微信信息');
  34. obj.openid = openid;
  35. const res = await this.payOrderService.create(obj);
  36. return res;
  37. }
  38. // 处理审核成功的情况
  39. async afterUpdate(filter, body, data) {
  40. const { pay_id } = data;
  41. if (pay_id.status !== '1') return data;
  42. // 付款成功,去添加课程与学生关联
  43. const obj = _.pick(data, [ 'school_id', 'lesson_id', 'student_id', 'money', 'is_pay', 'pay_id' ]);
  44. obj.is_pay = '1';
  45. await this.lessonStudentService.create(obj);
  46. return data;
  47. }
  48. }
  49. module.exports = TempLessonApplyService;