staff.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 query({ skip, limit, ...info }) {
  66. const total = await (await this.model.find(info)).length;
  67. const staffs = await this.model
  68. .find(info)
  69. .skip(Number(skip))
  70. .limit(Number(limit));
  71. const newdata = [];
  72. for (let staff of staffs) {
  73. staff = JSON.parse(JSON.stringify(staff));
  74. const user = await this.umodel.findOne({ userid: staff.id });
  75. staff.type = user.type;
  76. newdata.push(staff);
  77. }
  78. return { data: newdata, total };
  79. }
  80. async fetch({ id }) {
  81. let staff = await this.model.findById(id);
  82. staff = JSON.parse(JSON.stringify(staff));
  83. const user = await this.umodel.findOne({ userid: staff.id });
  84. staff.type = user.type;
  85. return staff;
  86. }
  87. }
  88. module.exports = StaffService;