headteacher.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 HeadteacherService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'headteacher');
  10. this.model = this.ctx.model.Headteacher;
  11. this.umodel = this.ctx.model.User;
  12. }
  13. async create(data) {
  14. const { name, mobile } = data;
  15. const user = await this.umodel.findOne({ mobile });
  16. if (user) {
  17. throw new BusinessError(ErrorCode.DATA_EXIST, '电话已经存在');
  18. }
  19. const res = await this.model.create(data);
  20. const newdata = { name, mobile, type: '1', uid: res.id };
  21. newdata.passwd = { secret: '12345678' };
  22. await this.umodel.create(newdata);
  23. }
  24. async update({ id }, data) {
  25. const { name, mobile, openid } = data;
  26. // 修改后的手机号查找是否已存在
  27. console.log(mobile);
  28. const have_mobile = await this.umodel.count({ mobile, uid: { $ne: id } });
  29. if (have_mobile > 0) throw new BusinessError(ErrorCode.DATA_EXIST, '电话已经存在');
  30. const res = await this.model.update({ _id: ObjectId(id) }, data);
  31. if (res) {
  32. const _user = await this.umodel.findOne({ uid: id, type: '1' });
  33. if (_user) {
  34. _user.mobile = mobile;
  35. _user.name = name;
  36. if (openid) {
  37. _user.openid = openid;
  38. }
  39. _user.save();
  40. }
  41. }
  42. return res;
  43. }
  44. async delete({ id }) {
  45. const res = await this.model.findByIdAndDelete(id);
  46. const _user = await this.umodel.findOne({ uid: id, thpe: '1' });
  47. _user.delete();
  48. return res;
  49. }
  50. }
  51. module.exports = HeadteacherService;