فهرست منبع

# Feature/196, 198, 199 Grouping users
* Refactor UserGroupRelation model and related logics.

Tatsuya Ise 8 سال پیش
والد
کامیت
074fda11d6
3فایلهای تغییر یافته به همراه247 افزوده شده و 204 حذف شده
  1. 1 1
      lib/models/page.js
  2. 217 175
      lib/models/user-group-relation.js
  3. 29 28
      lib/routes/admin.js

+ 1 - 1
lib/models/page.js

@@ -1245,7 +1245,7 @@ module.exports = function(crowi) {
           debug('isExistsGrantedGroupFor is return resolve(false);');
           return resolve(false);
         }
-        return pageRelations.map(pageRelation => UserGroupRelation.checkIsRelatedUserForGroup(userData, pageRelation.relatedGroup)
+        return pageRelations.map(pageRelation => UserGroupRelation.isRelatedUserForGroup(userData, pageRelation.relatedGroup)
         .then(function (checkResult) {
           return resolve(checkResult);
         })

+ 217 - 175
lib/models/user-group-relation.js

@@ -1,207 +1,249 @@
-module.exports = function(crowi) {
-  var debug = require('debug')('crowi:models:userGroupRelation')
-    , mongoose = require('mongoose')
-    , mongoosePaginate = require('mongoose-paginate')
-    , ObjectId = mongoose.Schema.Types.ObjectId
-
-    , PAGE_ITEMS = 50
-
-    , userGroupRelationSchema;
-
-  userGroupRelationSchema = new mongoose.Schema({
-    userGroupRelationId: String,
-    relatedGroup: { type: ObjectId, ref: 'UserGroup', required: true },
-    relatedUser: { type: ObjectId, ref: 'User', required: true },
-    createdAt: { type: Date, default: Date.now },
-  },{
-    toJSON: { getters: true },
-    toObject: { getters: true }
-  });
-  userGroupRelationSchema.plugin(mongoosePaginate);
-
-  // すべてのグループ所属関係を取得
-  userGroupRelationSchema.statics.findAllRelation = function() {
-    debug('findAllRelations is called');
-    var UserGroupRelation = this;
+const debug = require('debug')('crowi:models:userGroupRelation');
+const mongoose = require('mongoose');
+const mongoosePaginate = require('mongoose-paginate');
+const ObjectId = mongoose.Schema.Types.ObjectId;
+
+
+/*
+ * define schema
+ */
+const schema = new mongoose.Schema({
+  relatedGroup: { type: ObjectId, ref: 'UserGroup', required: true },
+  relatedUser: { type: ObjectId, ref: 'User', required: true },
+  createdAt: { type: Date, default: Date.now, required: true },
+});
+schema.plugin(mongoosePaginate);
+
+/**
+ * UserGroupRelation Class
+ *
+ * @class UserGroupRelation
+ */
+class UserGroupRelation {
+
+  /**
+   * limit items num for pagination
+   *
+   * @readonly
+   * @static
+   * @memberof UserGroupRelation
+   */
+  static get PAGE_ITEMS() {
+    return 50;
+  }
 
-    return new Promise(function(resolve, reject) {
-      UserGroupRelation
-        .find({ relatedGroup: group} )
-        .populate('relatedUser')
-        .exec(function (err, userGroupRelationData) {
-          if (err) {
-            return reject(err);
-          }
+  static set crowi(crowi) {
+    this._crowi = crowi;
+  }
 
-          return resolve(userGroupRelationData);
-        });
-    });
+  static get crowi() {
+    return this._crowi;
+  }
+
+  /**
+   * find all user and group relation
+   *
+   * @static
+   * @returns {Promise<UserGroupRelation[]>}
+   * @memberof UserGroupRelation
+   */
+  static findAllRelation() {
+
+    return this
+      .find()
+      .populate('relatedUser')
+      .populate('relatedGroup')
+      .exec();
   };
 
-  // 指定グループに対するすべてのグループ所属関係を取得
-  userGroupRelationSchema.statics.findAllRelationForUserGroup = function (userGroup) {
+  /**
+   * find all user and group relation of UserGroup
+   *
+   * @static
+   * @param {UserGroup} userGroup
+   * @returns {Promise<UserGroupRelation[]>}
+   * @memberof UserGroupRelation
+   */
+  static findAllRelationForUserGroup(userGroup) {
     debug('findAllRelationForUserGroup is called', userGroup);
     var UserGroupRelation = this;
 
-    return new Promise(function (resolve, reject) {
-      UserGroupRelation
-        .find({ relatedGroup: userGroup })
-        .populate('relatedUser')
-        .exec(function (err, userGroupRelationData) {
-          if (err) {
-            return reject(err);
-          }
-          return resolve(userGroupRelationData);
-        });
-    });
-  };
-
-  // 指定ユーザが所属するすべてのグループ所属関係を取得
-  userGroupRelationSchema.statics.findAllRelationForUser = function (user) {
-    debug('findAllRelationForUser is called');
-    var UserGroupRelation = this;
+    return this
+      .find({ relatedGroup: userGroup })
+      .populate('relatedUser')
+      .exec();
+  }
 
-    return new Promise(function (resolve, reject) {
-      UserGroupRelation
-        .find({ relatedUser: user.id })
-        .populate('relatedGroup')
-        .exec(function (err, userGroupRelationData) {
-          if (err) {
-            return reject(err);
-          }
-          return resolve(userGroupRelationData);
-        });
-    });
-  };
+  /**
+   * find all user and group relation of UserGroups
+   *
+   * @static
+   * @param {UserGroup[]} userGroups
+   * @returns {Promise<UserGroupRelation[]>}
+   * @memberof UserGroupRelation
+   */
+  static findAllRelationForUserGroups(userGroups) {
+
+    return this
+      .find({ relatedGroup: { $in: userGroups } })
+      .populate('relatedUser')
+      .exec();
+  }
 
-  // 指定グループリストに対するすべてのグループ所属関係を取得
-  userGroupRelationSchema.statics.findAllRelationForUserGroups = function (userGroups, callback) {
-    debug('findAllRelations is called', userGroups);
-    var UserGroupRelation = this;
-    var groupRelations = new Map();
-
-    return new Promise(function (resolve, reject) {
-      UserGroupRelation
-        .find({ relatedGroup: { $in: userGroups} })
-        .populate('relatedUser')
-        .exec(function (err, userGroupRelationData) {
-          if (err) {
-            return reject(err);
-          }
-          debug(userGroupRelationData);
-          return resolve(userGroupRelationData);
-        });
-    });
-  };
+  /**
+   * find all user and group relation of User
+   *
+   * @static
+   * @param {User} user
+   * @returns {Promise<UserGroupRelation[]>}
+   * @memberof UserGroupRelation
+   */
+  static findAllRelationForUser(user) {
+
+    return this
+      .find({ relatedUser: user.id })
+      .populate('relatedGroup')
+      .exec();
+  }
 
-  // ページネーション利用の検索
-  userGroupRelationSchema.statics.findUserGroupRelationsWithPagination = function (userGroup, options, callback) {
+  /**
+   * find all entities with pagination
+   *
+   * @see https://github.com/edwardhotchkiss/mongoose-paginate
+   *
+   * @static
+   * @param {UserGroup} userGroup
+   * @param {any} opts mongoose-paginate options object
+   * @returns {Promise<any>} mongoose-paginate result object
+   * @memberof UserGroupRelation
+   */
+  static findUserGroupRelationsWithPagination(userGroup, opts) {
+    const query = { relatedGroup: userGroup };
+    const options = Object.assign({}, opts);
+    if (options.page == null) {
+      options.page = 1;
+    }
+    if (options.limit == null) {
+      options.limit = UserGroupRelation.PAGE_ITEMS;
+    }
 
-    this.paginate({ relatedGroup: userGroup }, { page: options.page || 1, limit: options.limit || PAGE_ITEMS }, function(err, result) {
-      if (err) {
+    return this.paginate(query, options)
+      .catch((err) => {
         debug('Error on pagination:', err);
-        return callback(err, null);
-      }
-
-      return callback(err, result);
-    });
-  };
+      });
+  }
 
-  // グループのIDとユーザのIDから関係性を取得
-  userGroupRelationSchema.statics.findByGroupIdAndUser = function (userGroupId, userData, callback) {
-    var UserGroupRelation = this;
+  /**
+   * find one result by related group id and related user
+   *
+   * @static
+   * @param {string} userGroupId find query param for relatedGroup
+   * @param {User} userData find query param for relatedUser
+   * @returns {Promise<UserGroupRelation>}
+   * @memberof UserGroupRelation
+   */
+  static findByGroupIdAndUser(userGroupId, userData) {
+    const query = {
+      relatedGroup: userGroupId,
+      relatedUser: userData.id
+    }
 
-    return new Promise(function (resolve, reject) {
-      UserGroupRelation
-        .findOne({ relatedGroup: userGroupId, relatedUser: userData.id })
-        .populate('relatedUser')
-        .populate('relatedGroup')
-        .exec(function (err, userGroupRelationData) {
-          if (err) {
-            return reject(err);
-          }
-          debug(userGroupRelationData);
-          return resolve(userGroupRelationData);
-        });
-    });
+    return this
+      .findOne(query)
+      .populate('relatedUser')
+      .populate('relatedGroup')
+      .exec();
   }
 
-  // グループとユーザを指定し、関係性が存在するかチェック
-  userGroupRelationSchema.statics.checkIsRelatedUserForGroup = function (userData, userGroup) {
-    var UserGroupRelation = this;
-
-    debug('checkIsRelatedUserForGroup is called.', userData, userGroup);
+  /**
+   * get if the user has relation for group
+   *
+   * @param {User} userData
+   * @param {UserGroup} userGroup
+   * @returns {Promise<boolean>} is user related for group(or not)
+   * @memberof UserGroupRelation
+   */
+  static isRelatedUserForGroup(userData, userGroup) {
+    const query = {
+      relatedGroup: userGroup.id,
+      relatedUser: userData.id
+    }
 
-    return new Promise(function (resolve, reject) {
-      UserGroupRelation.count( {relatedGroup: userGroup.id, relatedUser: userData.id}, function (err, count) {
-      if (err) {
+    return this
+      .count(query)
+      .then((count) => {
+        // return true or false of the relation is exists(not count)
+        return resolve(0 < count);
+      })
+      .catch((err) => {
         debug('An Error occured.', err);
         return reject(err);
-      }
-      debug('checkIsRelatedUserForGroup count : ', count);
-      return resolve((0 < count));
       });
-    });
-  };
-
-  // 関係性の生成
-  userGroupRelationSchema.statics.createRelation = function(userGroup, user, callback) {
-    var UserGroupRelation = this
-      , newUserGroupRelation = new UserGroupRelation();
-
-    if (userGroup == null || user == null) {
-      return callback(new Error('userGroup or user is null'));
-    }
-    newUserGroupRelation.relatedGroup = userGroup;
-    newUserGroupRelation.relatedUser = user;
-    newUserGroupRelation.createdAt = Date.now();
+  }
 
-    debug('create new user-group-relation ', newUserGroupRelation);
-    newUserGroupRelation.save(function(err, userGroupRelationData) {
-      return callback(err, userGroupRelationData);
+  /**
+   * create user and group relation
+   *
+   * @param {UserGroup} userGroup
+   * @param {User} user
+   * @returns {Promise<UserGroupRelation>} created relation
+   * @memberof UserGroupRelation
+   */
+  static createRelation(userGroup, user) {
+    return this.create({
+      relatedGroup: userGroup.id,
+      relatedUser: user.id
     });
-  };
-
-  // グループに紐づく関係性の全削除
-  userGroupRelationSchema.statics.removeAllByUserGroup = function (userGroup, callback) {
-
-    if (userGroup === null || userGroup === undefined) { return callback(null); }
-    var UserGroupRelation = this
-    var relations = UserGroupRelation.findAllRelation(userGroup);
+  }
 
-    // 関係性削除の実装
-    relations.array.forEach(relation => {
-      UserGroupRelation.removeById(relation.id, function(err) {
-        if (err) { return callback(err); }
-      });
+  /**
+   * remove all relation for group
+   * @param {UserGroup} userGroup
+   * @returns {Promise<any>}
+   * @memberof UserGroupRelation
+   */
+  static removeAllByUserGroup(userGroup) {
+
+    return this.findAllRelationForUserGroup(userGroup)
+    .then((relations) => {
+      if (relations == null) {
+        return;
+      }
+      else {
+        relations.map((relation) => {
+          relation.remove();
+        });
+      }
     });
-    return callback(null);
   }
 
-  // ユーザグループの関係性を削除
-  userGroupRelationSchema.statics.removeById = function (id, callback) {
-    var UserGroupRelation = this
-    UserGroupRelation.findById(id, function (err, relationData) {
-      if (err) {
-        debug('Error on find a removing user-group-relation', err);
-        return callback(err);
+  /**
+   * remove relation by id
+   * @param {ObjectId} id
+   * @returns {Promise<any>}
+   * @memberof UserGroupRelation
+   */
+  static removeById(id) {
+
+    return this.findById(id)
+    .then((relationData) => {
+      if (relationData == null) {
+        throw new Exception('UserGroupRelation data is not exists. id:', id);
       }
-      debug('relationData is ', relationData);
-      if (relationData == null || relationData == undefined) {
-        debug('Cannot find user group relation by id', id);
-        return callback(new Error('Cannot find user group relation by id'));
+      else {
+        relationData.remove();
       }
-
-      relationData.remove(function(err) {
-        if (err) {
-          return callback(err);
-        }
-        return callback(null);
-      });
+    })
+    .catch((err) => {
+      debug('Error on find a removing user-group-relation', err);
+      reject(err);
     });
   }
 
-  userGroupRelationSchema.statics.PAGE_ITEMS         = PAGE_ITEMS;
+}
 
-  return mongoose.model('UserGroupRelation', userGroupRelationSchema);
-};
+module.exports = function (crowi) {
+  UserGroupRelation.crowi = crowi;
+  schema.loadClass(UserGroupRelation);
+  return mongoose.model('UserGroupRelation', schema);
+}

+ 29 - 28
lib/routes/admin.js

@@ -735,32 +735,32 @@ module.exports = function(crowi, app) {
     const UserGroup = crowi.model('UserGroup');
     const UserGroupRelation = crowi.model('UserGroupRelation');
 
-    // ユーザを名前で検索
-    User.findUserByUsername(req.body.user_name)
-      .then((user) => {
+    // req params
+    const userName = req.body.user_name;
+    const userGroupId = req.body.user_group_id;
+
+    let user = null;
+    let userGroup = null;
+
+    User.findUserByUsername(userName)
+      .then((result) => {
+        user = result;
         // ユーザグループをIDで検索
-        UserGroup.findById(req.body.user_group_id, function(err, userGroup) {
-          if (err) {
-            debug('Error on create user-group relation', err);
-            req.flash('errorMessage', 'グループの取得に失敗しました');
-            return res.redirect('/admin/user-group-detail/' + userGroup.name);
-          }
-          // Relation を作成
-          UserGroupRelation.createRelation(userGroup, user, function (err, data) {
-            if (err) {
-              debug('Error on create user-group relation', err);
-              req.flash('errorMessage', 'ユーザの追加に失敗しました');
-              return res.redirect('/admin/user-group-detail/' + userGroup.name);
-            }
-            return res.redirect('/admin/user-group-detail/' + userGroup.name);
-          });
-        });
+        return UserGroup.findById(userGroupId)
+      })
+      .then((result) => {
+        userGroup = result
+        // Relation を作成
+        return UserGroupRelation.createRelation(userGroup, user)
+      })
+      .then((result) => {
+          return res.redirect('/admin/user-group-detail/' + userGroup.name);
       }).catch((err) => {
-        debug('Error on create user-group relation', err);
-        req.flash('errorMessage', 'ユーザの取得に失敗しました');
-        return res.redirect('/admin/user-group-detail/' + userGroup.name);
+      debug('Error on create user-group relation', err);
+      req.flash('errorMessage', 'Error on create user-group relation');
+          return res.redirect('/admin/user-group-detail/' + userGroup.name);
       });
-  }
+    }
 
   actions.userGroupRelation.remove = function (req, res) {
     const UserGroupRelation = crowi.model('UserGroupRelation');
@@ -768,12 +768,13 @@ module.exports = function(crowi, app) {
     var relationId = req.params.relationId;
 
     debug(name, relationId);
-    UserGroupRelation.removeById(relationId, function(err) {
-      if (err) {
-        debug('Error on remove user-group-relation', err);
-        req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
-      }
+    UserGroupRelation.removeById(relationId)
+    .then(() =>{
       return res.redirect('/admin/user-group-detail/' + name);
+    })
+    .catch((err) => {
+      debug('Error on remove user-group-relation', err);
+      req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
     });
 
   }