12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- 'use strict';
- const assert = require('assert');
- const _ = require('lodash');
- const { ObjectId } = require('mongoose').Types;
- const { CrudService } = require('naf-framework-mongoose/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- class StaffService extends CrudService {
- constructor(ctx) {
- super(ctx, 'staff');
- this.model = this.ctx.model.Staff;
- this.umodel = this.ctx.model.User;
- }
- async update({ id }, data) {
- const staff = await this.model.findById(id);
- const { name, gender, phone, address, birthday, id_number, dept_id, level_id, sort, type } = data;
- const user = (await this.umodel.find({ userid: id }))[0];
- if (name) {
- user.name = name;
- staff.name = name;
- await user.save();
- }
- if (gender) {
- staff.gender = gender;
- }
- if (phone) {
- const _user = await this.umodel.find({ phone });
- if (_.isEqual(_user.length, 0) || (_.isEqual(_user.length, 1) && _.isEqual(_user[0].id, user.id))) {
- user.phone = phone;
- staff.phone = phone;
- await user.save();
- } else {
- throw new BusinessError(ErrorCode.DATA_EXISTED);
- }
- }
- if (type) {
- const user = await this.umodel.findOne({ userid: id });
- user.type = type;
- await user.save();
- }
- if (address) {
- staff.address = address;
- }
- if (birthday) {
- staff.birthday = birthday;
- }
- if (id_number) {
- staff.id_number = id_number;
- }
- if (dept_id) {
- staff.dept_id = dept_id;
- }
- if (level_id) {
- staff.level_id = level_id;
- }
- if (sort) {
- staff.sort = sort;
- }
- const res = await staff.save();
- return res;
- }
- async delete({ id }) {
- await this.model.findByIdAndDelete(id);
- await this.umodel.findOneAndDelete({ userid: id });
- }
- async query({ skip, limit, ...info }) {
- const total = await (await this.model.find(info)).length;
- const staffs = await this.model
- .find(info)
- .skip(Number(skip))
- .limit(Number(limit));
- const newdata = [];
- for (let staff of staffs) {
- staff = JSON.parse(JSON.stringify(staff));
- const user = await this.umodel.findOne({ userid: staff.id });
- staff.type = user.type;
- newdata.push(staff);
- }
- return { data: newdata, total };
- }
- async fetch({ id }) {
- let staff = await this.model.findById(id);
- staff = JSON.parse(JSON.stringify(staff));
- const user = await this.umodel.findOne({ userid: staff.id });
- staff.type = user.type;
- return staff;
- }
- }
- module.exports = StaffService;
|