staff.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 StaffService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'staff');
  10. this.model = this.ctx.model.Staff;
  11. this.umodel = this.ctx.model.User;
  12. }
  13. async update({ id }, data) {
  14. const staff = await this.model.findById(id);
  15. const { name, gender, phone, address, birthday, id_number, dept_id, level_id, sort, type } = data;
  16. const user = (await this.umodel.find({ userid: id }))[0];
  17. if (name) {
  18. user.name = name;
  19. staff.name = name;
  20. await user.save();
  21. }
  22. if (gender) {
  23. staff.gender = gender;
  24. }
  25. if (phone) {
  26. const _user = await this.umodel.find({ phone });
  27. if (_.isEqual(_user.length, 0) || (_.isEqual(_user.length, 1) && _.isEqual(_user[0].id, user.id))) {
  28. user.phone = phone;
  29. staff.phone = phone;
  30. await user.save();
  31. } else {
  32. throw new BusinessError(ErrorCode.DATA_EXISTED);
  33. }
  34. }
  35. if (type) {
  36. const user = await this.umodel.findOne({ userid: id });
  37. user.type = type;
  38. await user.save();
  39. }
  40. if (address) {
  41. staff.address = address;
  42. }
  43. if (birthday) {
  44. staff.birthday = birthday;
  45. }
  46. if (id_number) {
  47. staff.id_number = id_number;
  48. }
  49. if (dept_id) {
  50. staff.dept_id = dept_id;
  51. }
  52. if (level_id) {
  53. staff.level_id = level_id;
  54. }
  55. if (sort) {
  56. staff.sort = sort;
  57. }
  58. const res = await staff.save();
  59. return res;
  60. }
  61. async delete({ id }) {
  62. await this.model.findByIdAndDelete(id);
  63. await this.umodel.findOneAndDelete({ userid: id });
  64. }
  65. async fetch({ id }) {
  66. let staff = await this.model.findById(id);
  67. staff = JSON.parse(JSON.stringify(staff));
  68. const user = await this.umodel.findOne({ userid: staff.id });
  69. staff.type = user.type;
  70. return staff;
  71. }
  72. }
  73. module.exports = StaffService;