headteacher.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. const have_mobile = await this.umodel.count({ mobile, uid: { $ne: id } });
  28. if (have_mobile > 0) throw new BusinessError(ErrorCode.DATA_EXIST, '电话已经存在');
  29. const res = await this.model.update({ _id: ObjectId(id) }, data);
  30. if (res) {
  31. const _user = await this.umodel.findOne({ uid: id, type: '1' });
  32. if (_user) {
  33. _user.mobile = mobile;
  34. _user.name = name;
  35. if (openid) {
  36. _user.openid = openid;
  37. }
  38. _user.save();
  39. }
  40. }
  41. return res;
  42. }
  43. async delete({ id }) {
  44. const res = await this.model.findByIdAndDelete(id);
  45. const _user = await this.umodel.findOne({ uid: id, thpe: '1' });
  46. _user.delete();
  47. return res;
  48. }
  49. }
  50. module.exports = HeadteacherService;