user-group.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. const debug = require('debug')('growi:models:userGroup');
  2. const mongoose = require('mongoose');
  3. const mongoosePaginate = require('mongoose-paginate-v2');
  4. /*
  5. * define schema
  6. */
  7. const ObjectId = mongoose.Schema.Types.ObjectId;
  8. const schema = new mongoose.Schema({
  9. userGroupId: String,
  10. name: { type: String, required: true, unique: true },
  11. createdAt: { type: Date, default: Date.now },
  12. parent: { type: ObjectId, ref: 'UserGroup', index: true },
  13. description: { type: String, default: '' },
  14. });
  15. schema.plugin(mongoosePaginate);
  16. class UserGroup {
  17. /**
  18. * public fields for UserGroup model
  19. *
  20. * @readonly
  21. * @static
  22. * @memberof UserGroup
  23. */
  24. static get USER_GROUP_PUBLIC_FIELDS() {
  25. return '_id name createdAt parent description';
  26. }
  27. /**
  28. * limit items num for pagination
  29. *
  30. * @readonly
  31. * @static
  32. * @memberof UserGroup
  33. */
  34. static get PAGE_ITEMS() {
  35. return 10;
  36. }
  37. /*
  38. * model static methods
  39. */
  40. // Generate image path
  41. static createUserGroupPictureFilePath(userGroup, name) {
  42. const ext = `.${name.match(/(.*)(?:\.([^.]+$))/)[2]}`;
  43. return `userGroup/${userGroup._id}${ext}`;
  44. }
  45. /**
  46. * find all entities with pagination
  47. *
  48. * @see https://github.com/edwardhotchkiss/mongoose-paginate
  49. *
  50. * @static
  51. * @param {any} opts mongoose-paginate options object
  52. * @returns {Promise<any>} mongoose-paginate result object
  53. * @memberof UserGroup
  54. */
  55. static findUserGroupsWithPagination(opts) {
  56. const query = { parent: null };
  57. const options = Object.assign({}, opts);
  58. if (options.page == null) {
  59. options.page = 1;
  60. }
  61. if (options.limit == null) {
  62. options.limit = UserGroup.PAGE_ITEMS;
  63. }
  64. return this.paginate(query, options)
  65. .catch((err) => {
  66. debug('Error on pagination:', err);
  67. });
  68. }
  69. static async findChildUserGroupsByParentIds(parentIds, includeGrandChildren = false) {
  70. if (parentIds == null) {
  71. throw Error('parentIds must not be null.');
  72. }
  73. const childUserGroups = await this.find({ parent: { $in: parentIds } });
  74. let grandChildUserGroups = null;
  75. if (includeGrandChildren) {
  76. const childUserGroupIds = childUserGroups.map(group => group._id);
  77. grandChildUserGroups = await this.find({ parent: { $in: childUserGroupIds } });
  78. }
  79. return {
  80. childUserGroups,
  81. grandChildUserGroups,
  82. };
  83. }
  84. // Delete completely
  85. static async removeCompletelyById(deleteGroupId, action, transferToUserGroupId, user) {
  86. const UserGroupRelation = mongoose.model('UserGroupRelation');
  87. const groupToDelete = await this.findById(deleteGroupId);
  88. if (groupToDelete == null) {
  89. throw new Error('UserGroup data is not exists. id:', deleteGroupId);
  90. }
  91. const deletedGroup = await groupToDelete.remove();
  92. await Promise.all([
  93. UserGroupRelation.removeAllByUserGroup(deletedGroup),
  94. UserGroup.crowi.pageService.handlePrivatePagesForDeletedGroup(deletedGroup, action, transferToUserGroupId, user),
  95. ]);
  96. return deletedGroup;
  97. }
  98. static countUserGroups() {
  99. return this.estimatedDocumentCount();
  100. }
  101. static async createGroup(name, description, parentId) {
  102. // create without parent
  103. if (parentId == null) {
  104. return this.create({ name, description });
  105. }
  106. // create with parent
  107. const parent = await this.findOne({ _id: parentId });
  108. if (parent == null) {
  109. throw Error('Parent does not exist.');
  110. }
  111. return this.create({ name, description, parent });
  112. }
  113. static async findAllAncestorGroups(parent, ancestors = [parent]) {
  114. if (parent == null) {
  115. return ancestors;
  116. }
  117. const nextParent = await this.findOne({ _id: parent.parent });
  118. if (nextParent == null) {
  119. return ancestors;
  120. }
  121. ancestors.push(nextParent);
  122. return this.findAllAncestorGroups(nextParent, ancestors);
  123. }
  124. // TODO 85062: write test code
  125. static async updateGroup(id, name, description, parentId, forceUpdateParents = false) {
  126. const userGroup = await this.findById(id);
  127. if (userGroup == null) {
  128. throw new Error('The group does not exist');
  129. }
  130. // check if the new group name is available
  131. const isExist = (await this.countDocuments({ name })) > 0;
  132. if (userGroup.name !== name && isExist) {
  133. throw new Error('The group name is already taken');
  134. }
  135. userGroup.name = name;
  136. userGroup.description = description;
  137. // return when not update parent
  138. if (userGroup.parent === parentId) {
  139. return userGroup.save();
  140. }
  141. const parent = await this.findById(parentId);
  142. // find users for comparison
  143. const UserGroupRelation = mongoose.model('UserGroupRelation');
  144. const [targetGroupUsers, parentGroupUsers] = await Promise.all(
  145. [UserGroupRelation.findUserIdsByGroupId(userGroup._id), UserGroupRelation.findUserIdsByGroupId(parent._id)],
  146. );
  147. const usersBelongsToTargetButNotParent = targetGroupUsers.filter(user => !parentGroupUsers.includes(user));
  148. // add the target group's users to all ancestors
  149. if (forceUpdateParents) {
  150. const ancestorGroups = await this.findAllAncestorGroups(parent);
  151. const ancestorGroupIds = ancestorGroups.map(group => group._id);
  152. await UserGroupRelation.createByGroupIdsAndUserIds(ancestorGroupIds, usersBelongsToTargetButNotParent);
  153. userGroup.parent = parent._id;
  154. }
  155. // validate related users
  156. else {
  157. const isUpdatable = usersBelongsToTargetButNotParent.length === 0;
  158. if (!isUpdatable) {
  159. throw Error('The parent group does not contain the users in this group.');
  160. }
  161. }
  162. return userGroup.save();
  163. }
  164. }
  165. module.exports = function(crowi) {
  166. UserGroup.crowi = crowi;
  167. schema.loadClass(UserGroup);
  168. return mongoose.model('UserGroup', schema);
  169. };