Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Group API (#9034)

ulfertsb8ca382d343a
diff --git a/app/contracts/groups/add_users_contract.rb b/app/contracts/groups/add_users_contract.rb
index 05213b08982..872c67c0f31 100644
--- a/app/contracts/groups/add_users_contract.rb
+++ b/app/contracts/groups/add_users_contract.rb
@@ -27,11 +27,12 @@
#++
module Groups
- class AddUsersContract < Groups::BaseContract
+ class AddUsersContract < ::ModelContract
+ include RequiresAdminGuard
+
protected
# No need to validate the whole of the group when we only want to ensure that the user is an admin.
- # In case more conditions are added to the BaseContract, we might need an extra AdminOnlyContract
def validate_model?
false
end
diff --git a/app/contracts/groups/base_contract.rb b/app/contracts/groups/base_contract.rb
index 38e6a06415b..31650297cac 100644
--- a/app/contracts/groups/base_contract.rb
+++ b/app/contracts/groups/base_contract.rb
@@ -28,11 +28,25 @@
module Groups
class BaseContract < ::ModelContract
- validate :user_allowed_to_manage
+ include RequiresAdminGuard
- def user_allowed_to_manage
- unless user.admin?
- errors.add :base, :error_unauthorized
+ # attribute_alias is broken in the sense
+ # that `model#changed` includes only the non-aliased name
+ # hence we need to put "lastname" as an attribute here
+ attribute :name
+ attribute :lastname
+
+ validate :validate_unique_users
+
+ private
+
+ # Validating on the group_users since those are dealt with in the
+ # corresponding services.
+ def validate_unique_users
+ user_ids = model.group_users.map(&:user_id)
+
+ if user_ids.uniq.length < user_ids.length
+ errors.add(:group_users, :taken)
end
end
end
diff --git a/app/contracts/groups/create_contract.rb b/app/contracts/groups/create_contract.rb
new file mode 100644
index 00000000000..e8d39144954
--- /dev/null
+++ b/app/contracts/groups/create_contract.rb
@@ -0,0 +1,45 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Groups
+ class CreateContract < BaseContract
+ attribute :type
+
+ validate :type_is_group
+
+ private
+
+ def type_is_group
+ unless model.type == Group.name
+ errors.add(:type, 'Type and class mismatch')
+ end
+ end
+ end
+end
diff --git a/app/contracts/groups/delete_contract.rb b/app/contracts/groups/delete_contract.rb
new file mode 100644
index 00000000000..e213800cb7e
--- /dev/null
+++ b/app/contracts/groups/delete_contract.rb
@@ -0,0 +1,35 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Groups
+ class DeleteContract < ::DeleteContract
+ delete_permission -> { user.active? && user.admin? }
+ end
+end
diff --git a/app/contracts/groups/update_contract.rb b/app/contracts/groups/update_contract.rb
new file mode 100644
index 00000000000..252320609ee
--- /dev/null
+++ b/app/contracts/groups/update_contract.rb
@@ -0,0 +1,34 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Groups
+ class UpdateContract < BaseContract
+ end
+end
diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb
index fef4f26d0b1..2fb03d7c122 100644
--- a/app/controllers/groups_controller.rb
+++ b/app/controllers/groups_controller.rb
@@ -141,8 +141,8 @@ class GroupsController < ApplicationController
end
def remove_user
- @group = Group.includes(:users).find(params[:id])
- @group.users.delete(User.includes(:memberships).find(params[:user_id]))
+ @group = Group.includes(:group_users).find(params[:id])
+ @group.group_users.destroy(GroupUser.find_by(user_id: params[:user_id], group_id: @group.id))
I18n.t :notice_successful_update
redirect_to controller: '/groups', action: 'edit', id: @group, tab: 'users'
diff --git a/app/mailers/user_mailer.rb b/app/mailers/user_mailer.rb
index 4ee2055b368..53e55109a3b 100644
--- a/app/mailers/user_mailer.rb
+++ b/app/mailers/user_mailer.rb
@@ -300,7 +300,7 @@ class UserMailer < BaseMailer
with_locale_for(user) do
subject = if @group
- t(:mail_subject_group_reminder, count: @issues.size, days: @days, group: @group.groupname)
+ t(:mail_subject_group_reminder, count: @issues.size, days: @days, group: @group.name)
else
t(:mail_subject_reminder, count: @issues.size, days: @days)
end
diff --git a/app/models/group.rb b/app/models/group.rb
index 5381cfbc86d..c61a040928f 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -29,17 +29,23 @@
#++
class Group < Principal
- has_and_belongs_to_many :users,
- join_table: "#{table_name_prefix}group_users#{table_name_suffix}",
- before_add: :fail_add,
- after_remove: :user_removed
+ include ::Scopes::Scoped
+
+ has_many :group_users,
+ autosave: true,
+ dependent: :destroy,
+ after_remove: :user_removed
+
+ has_many :users,
+ through: :group_users,
+ before_add: :fail_add
acts_as_customizable
- alias_attribute(:groupname, :lastname)
- validates_presence_of :groupname
- validate :uniqueness_of_groupname
- validates_length_of :groupname, maximum: 256
+ alias_attribute(:name, :lastname)
+ validates_presence_of :name
+ validate :uniqueness_of_name
+ validates_length_of :name, maximum: 256
# HACK: We want to have the :preference association on the Principal to allow
# for eager loading preferences.
@@ -55,13 +61,15 @@ class Group < Principal
include Destroy
+ scopes :visible
+
def to_s
- lastname.to_s
+ lastname
end
- alias :name :to_s
+ def user_removed(group_user)
+ user = group_user.user
- def user_removed(user)
member_roles = MemberRole
.includes(member: :member_roles)
.where(inherited_from: members.joins(:member_roles).select('member_roles.id'))
@@ -92,10 +100,10 @@ class Group < Principal
private
- def uniqueness_of_groupname
- groups_with_name = Group.where('lastname = ? AND id <> ?', groupname, id || 0).count
+ def uniqueness_of_name
+ groups_with_name = Group.where('lastname = ? AND id <> ?', name, id || 0).count
if groups_with_name > 0
- errors.add :groupname, :taken
+ errors.add :name, :taken
end
end
diff --git a/app/models/group_user.rb b/app/models/group_user.rb
index 80f6d55aff3..86ab4af65b7 100644
--- a/app/models/group_user.rb
+++ b/app/models/group_user.rb
@@ -29,5 +29,7 @@
#++
class GroupUser < ApplicationRecord
- self.table_name = "#{table_name_prefix}group_users#{table_name_suffix}"
+ belongs_to :group,
+ touch: true
+ belongs_to :user
end
diff --git a/app/models/groups/scopes/visible.rb b/app/models/groups/scopes/visible.rb
new file mode 100644
index 00000000000..256cf6cda7b
--- /dev/null
+++ b/app/models/groups/scopes/visible.rb
@@ -0,0 +1,46 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Groups::Scopes
+ module Visible
+ extend ActiveSupport::Concern
+
+ class_methods do
+ def visible(current_user = User.current)
+ if current_user.allowed_to_globally?(:manage_members)
+ Group.all
+ else
+ Group
+ .in_project(Project.allowed_to(current_user, :view_members))
+ end
+ end
+ end
+ end
+end
diff --git a/app/models/queries/groups.rb b/app/models/queries/groups.rb
new file mode 100644
index 00000000000..0707a0b48bb
--- /dev/null
+++ b/app/models/queries/groups.rb
@@ -0,0 +1,36 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Queries::Groups
+ order_ns = Queries::Members::Orders
+ query = Queries::Members::MemberQuery
+
+ Queries::Register.order query, order_ns::DefaultOrder
+end
diff --git a/app/models/queries/groups/group_query.rb b/app/models/queries/groups/group_query.rb
new file mode 100644
index 00000000000..da88c43ba81
--- /dev/null
+++ b/app/models/queries/groups/group_query.rb
@@ -0,0 +1,37 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+class Queries::Groups::GroupQuery < Queries::BaseQuery
+ def self.model
+ Group
+ end
+
+ def default_scope
+ Group.visible(User.current)
+ end
+end
diff --git a/app/models/queries/groups/orders/default_order.rb b/app/models/queries/groups/orders/default_order.rb
new file mode 100644
index 00000000000..18b80ebd71b
--- /dev/null
+++ b/app/models/queries/groups/orders/default_order.rb
@@ -0,0 +1,37 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+class Queries::Groups::Orders::DefaultOrder < Queries::BaseOrder
+ self.model = Group
+
+ def self.key
+ /\A(id|created_at|updated_at)\z/
+ end
+end
diff --git a/app/services/groups/create_service.rb b/app/services/groups/create_service.rb
new file mode 100644
index 00000000000..4949ee3275f
--- /dev/null
+++ b/app/services/groups/create_service.rb
@@ -0,0 +1,31 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+class Groups::CreateService < ::BaseServices::Create; end
diff --git a/app/services/groups/delete_service.rb b/app/services/groups/delete_service.rb
new file mode 100644
index 00000000000..b7b889a1a1f
--- /dev/null
+++ b/app/services/groups/delete_service.rb
@@ -0,0 +1,29 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+class Groups::DeleteService < ::BaseServices::Delete; end
diff --git a/app/services/groups/set_attributes_service.rb b/app/services/groups/set_attributes_service.rb
new file mode 100644
index 00000000000..b3edb371ad8
--- /dev/null
+++ b/app/services/groups/set_attributes_service.rb
@@ -0,0 +1,65 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Groups
+ class SetAttributesService < ::BaseServices::SetAttributes
+ private
+
+ def set_attributes(params)
+ set_users(params)
+ super
+ end
+
+ # We do not want to persist the associated users (members) in a
+ # SetAttributesService. Therefore we are building the association here.
+ #
+ # Note that due to the way we handle members, via a specific AddUsersService
+ # the group should no longer simply be saved after group_users have been added.
+ def set_users(params)
+ user_ids = (params.delete(:user_ids) || []).map(&:to_i)
+
+ existing_user_ids = model.group_users.map(&:user_id)
+ build_new_users user_ids - existing_user_ids
+ mark_outdated_users existing_user_ids - user_ids
+ end
+
+ def build_new_users(new_user_ids)
+ new_user_ids.each do |id|
+ model.group_users.build(user_id: id)
+ end
+ end
+
+ def mark_outdated_users(removed_user_ids)
+ removed_user_ids.each do |id|
+ model.group_users.find { |gu| gu.user_id == id }.mark_for_destruction
+ end
+ end
+ end
+end
diff --git a/app/services/groups/update_service.rb b/app/services/groups/update_service.rb
new file mode 100644
index 00000000000..5e7990c71de
--- /dev/null
+++ b/app/services/groups/update_service.rb
@@ -0,0 +1,47 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+class Groups::UpdateService < ::BaseServices::Update
+ protected
+
+ def after_perform(call)
+ new_user_ids = call.result.group_users.select(&:saved_changes?).map(&:user_id)
+
+ if new_user_ids.any?
+ db_call = ::Groups::AddUsersService
+ .new(call.result, current_user: user)
+ .call(ids: new_user_ids)
+
+ call.add_dependent!(db_call)
+ end
+
+ call
+ end
+end
diff --git a/app/views/user_mailer/reminder_mail.html.erb b/app/views/user_mailer/reminder_mail.html.erb
index 3bb0f398c26..d3c1b494fac 100644
--- a/app/views/user_mailer/reminder_mail.html.erb
+++ b/app/views/user_mailer/reminder_mail.html.erb
@@ -26,7 +26,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
See docs/COPYRIGHT.rdoc for more details.
++#%>
-<p><%= @group.nil? ? t(:mail_body_reminder, count: @issues.size, days: @days) : t(:mail_body_group_reminder, count: @issues.size, days: @days, group: @group.groupname) %></p>
+<p><%= @group.nil? ? t(:mail_body_reminder, count: @issues.size, days: @days) : t(:mail_body_group_reminder, count: @issues.size, days: @days, group: @group.name) %></p>
<ul>
<% @issues.each do |issue| -%>
<li><%= issue.project %> - <%= link_to "#{issue.type} ##{issue.id}", work_package_url(issue) %>: <%= issue.subject %></li>
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 765c2909ebe..3f0c3af3bfe 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -833,7 +833,7 @@ en:
firstname: "First name"
group: "Group"
groups: "Groups"
- groupname: "Group name"
+ name: "Group name"
id: "ID"
is_default: "Default value"
is_for_all: "For all projects"
diff --git a/db/migrate/20210221230446_add_group_user_primary_key.rb b/db/migrate/20210221230446_add_group_user_primary_key.rb
new file mode 100644
index 00000000000..93eccabf6c8
--- /dev/null
+++ b/db/migrate/20210221230446_add_group_user_primary_key.rb
@@ -0,0 +1,9 @@
+class AddGroupUserPrimaryKey < ActiveRecord::Migration[6.1]
+ def change
+ # Adding a primary key will automatically fill that column with values.
+ # Therefore, there is no need to assign it manually.
+ add_column :group_users, :id, :primary_key
+
+ add_index :group_users, %i[user_id group_id], unique: true
+ end
+end
diff --git a/docs/api/apiv3/endpoints/groups.apib b/docs/api/apiv3/endpoints/groups.apib
index 7577bc3e137..2fdc2dea71e 100644
--- a/docs/api/apiv3/endpoints/groups.apib
+++ b/docs/api/apiv3/endpoints/groups.apib
@@ -2,27 +2,33 @@
Groups are collections of users. They support assigning/unassigning multiple users to/from a project in one operation.
-This resource is currently a stub.
+This resource does not yet have the form and schema endpoints. But as all properties are static, clients should still be able
+to work with this resource.
## Actions
-None
+## Actions
+| Link | Description | Condition |
+|:-------------------:| -------------------------------------------------------------------- | ---------------------------------------------------------------- |
+| delete | Deletes the group. | **Permission**: Administrator |
+| updateImmediately | Updates the group's attributes. | **Permission**: Administrator |
## Linked Properties
-| Link | Description | Type | Constraints | Supported operations | Condition |
-|:-----------:|-------------------------------------------------------------- | ------------- | --------------------- | -------------------- | ----------------------------------------- |
-| self | This group | Group | not null | READ | |
-| members | Link to collection of all the group's memberships. The list will only include the memberships in projects in which the requesting user has the necessary permissions. | MemberCollection | | READ | **Permission**: view members or manage members in any project |
+| Link | Description | Type | Constraints | Supported operations | Condition |
+|:-----------: |-------------------------------------------------------------- | ------------- | --------------------- | -------------------- | ----------------------------------------- |
+| self | This group | Group | not null | READ | |
+| memberships | Link to collection of all the group's memberships. The list will only include the memberships in projects in which the requesting user has the necessary permissions. | MemberCollection | | READ | **Permission**: view members or manage members in any project |
+| members | The list all all the users that are members of the group | UserCollection | | READ/WRITE | **Permission**: manage members in any project to read & admin to write |
## Local Properties
-| Property | Description | Type | Constraints | Supported operations | Condition |
-| :----------: | --------------------------------------------------------- | -------- | ---------------------------------------------------- | -------------------- | ----------------------------------------------------------- |
-| id | Group's id | Integer | x > 0 | READ | |
-| name | Group's full name, formatting depends on instance settings | String | | READ | |
-| createdAt | Time of creation | DateTime | | READ | |
-| updatedAt | Time of the most recent change to the user | DateTime | | READ | |
+| Property | Description | Type | Constraints | Supported operations | Condition |
+| :----------: | --------------------------------------------------------- | -------- | ---------------------------------------------------- | -------------------- | ----------------------------------------------------------- |
+| id | Group's id | Integer | x > 0 | READ | |
+| name | Group's full name, formatting depends on instance settings | String | | READ/WRITE | Admin to write |
+| createdAt | Time of creation | DateTime | | READ | Only visible by admins |
+| updatedAt | Time of the most recent change to the user | DateTime | | READ | Only visible by admins |
-## Group [/api/v3/groups/{id}]
+## View group [/api/v3/groups/{id}]
+ Model
+ Body
@@ -37,7 +43,29 @@ None
"self": {
"href": "/api/v3/groups/9",
"title": "The group"
- }
+ },
+ "delete": {
+ "href": "/api/v3/group/9",
+ "method": "delete"
+ },
+ "memberships": {
+ "href": "/api/v3/memberships?filters=[{"principal":{"operator":"=","values":["9"]}}]",
+ "title": "Memberships"
+ },
+ "updateImmediately": {
+ "href": "/api/v3/group/9",
+ "method": "patch"
+ },
+ "members": [
+ {
+ "href": "/api/v3/users/363",
+ "title": "First user"
+ },
+ {
+ "href": "/api/v3/users/60",
+ "title": "Second user"
+ }
+ ]
}
}
@@ -48,7 +76,7 @@ None
+ Response 200 (application/hal+json)
- [Group][]
+ [View group][]
+ Response 404 (application/hal+json)
@@ -65,3 +93,319 @@ None
"message": "The requested resource could not be found."
}
+## Create group [/api/v3/groups]
+
+## Create group [POST]
+
+Creates a new group applying the attributes provided in the body.
+
++ Request Create group
+
+ + Body
+
+ {
+ "name": "The group",
+ "_links": {
+ "members": [
+ {
+ "href": "/api/v3/users/363"
+ },
+ {
+ "href": "/api/v3/users/60"
+ }
+ ]
+ }
+ }
+
++ Response 201
+
+ [View group][]
+
++ Response 400 (application/hal+json)
+
+ Occurs when the client did not send a valid JSON object in the request body.
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:InvalidRequestBody",
+ "message": "The request body was not a single JSON object."
+ }
+
++ Response 403 (application/hal+json)
+
+ Returned if the client does not have sufficient permissions.
+
+ **Required permission:** Administrator
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:MissingPermission",
+ "message": "You are not authorized to access this resource."
+ }
+
++ Response 422 (application/hal+json)
+
+ Returned if:
+
+ * a constraint for a property was violated (`PropertyConstraintViolation`)
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:PropertyConstraintViolation",
+ "message": "Name can't be blank.",
+ "_embedded": {
+ "details": {
+ "attribute": "name"
+ }
+ }
+ }
+
+## Update group [/api/v3/groups/{id}]
+
+## Update group [PATCH]
+
+Updates the given group by applying the attributes provided in the body.
+
++ Parameters
+ + id (required, integer, `1`) ... Group id
+
++ Request Update membership
+
+ + Body
+
+ {
+ "_links": {
+ "members": [
+ {
+ "href": "/api/v3/users/363"
+ },
+ {
+ "href": "/api/v3/users/60"
+ }
+ ]
+ }
+ }
+
++ Response 200
+
+ [View group][]
+
++ Response 400 (application/hal+json)
+
+ Occurs when the client did not send a valid JSON object in the request body.
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:InvalidRequestBody",
+ "message": "The request body was not a single JSON object."
+ }
+
++ Response 403 (application/hal+json)
+
+ Returned if the client does not have sufficient permissions.
+
+ **Required permission:** Administrator
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:MissingPermission",
+ "message": "You are not authorized to access this resource."
+ }
+
++ Response 404 (application/hal+json)
+
+ Returned if the membership does not exist or the client does not have sufficient permissions
+ to see it.
+
+ **Required permission** If the user has the *manage members* permission in at least one project the user will be able to query all groups. If not, the user
+ will be able to query all groups which are members in projects, he has the *view members* permission in.
+
+ *Note: A client without sufficient permissions shall not be able to test for the existence of
+ a version. That's why a 404 is returned here, even if a 403 might be more appropriate.*
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:NotFound",
+ "message": "The requested resource could not be found."
+ }
+
++ Response 422 (application/hal+json)
+
+ Returned if:
+
+ * a constraint for a property was violated (`PropertyConstraintViolation`)
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:PropertyConstraintViolation",
+ "message": "Member is already taken.",
+ "_embedded": {
+ "details": {
+ "attribute": "members"
+ }
+ }
+ }
+
+## Delete group [/api/v3/group/{id}]
+
+## Delete group [DELETE]
+
+Deletes the group.
+
++ Parameters
+ + id (required, integer, `1`) ... Group id
+
++ Response 204 (application/hal+json)
+
+ Returned if the group was successfully deleted
+
+ + Body
+
++ Response 403 (application/hal+json)
+
+ Returned if the client does not have sufficient permissions.
+
+ **Required permission:** Administrator
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:MissingPermission",
+ "message": "You are not authorized to access this resource."
+ }
+
++ Response 404 (application/hal+json)
+
+ Returned if the group does not exist or the client does not have sufficient permissions
+ to see it.
+
+ **Required permission:** Administrator
+
+ *Note: A client without sufficient permissions shall not be able to test for the existence of
+ a version. That's why a 404 is returned here, even if a 403 might be more appropriate.*
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:NotFound",
+ "message": "The requested resource could not be found."
+ }
+
+
+## List groups [/api/v3/groups{?sortBy}]
+
++ Model
+ + Body
+
+ {
+ "_links": {
+ "self": { "href": "/api/v3/groups" }
+ },
+ "total": 2,
+ "count": 2,
+ "_type": "Collection",
+ "_embedded":
+ {
+ "elements": [
+ {
+ "_type": "Group",
+ "id": 9,
+ "name": "The group",
+ "createdAt": "2015-09-23T11:06:36Z",
+ "updatedAt": "2015-09-23T11:06:36Z",
+ "_links": {
+ "self": {
+ "href": "/api/v3/groups/9",
+ "title": "The group"
+ },
+ "memberships": {
+ "href": "/api/v3/memberships?filters=[{"principal":{"operator":"=","values":["9"]}}]",
+ "title": "Memberships"
+ },
+ "members": [
+ {
+ "href": "/api/v3/users/363",
+ "title": "First user"
+ },
+ {
+ "href": "/api/v3/users/60",
+ "title": "Second user"
+ }
+ ]
+ }
+ },
+ {
+ "_type": "Group",
+ "id": 123,
+ "name": "Another group",
+ "createdAt": "2018-09-23T11:06:36Z",
+ "updatedAt": "2019-09-23T11:06:36Z",
+ "_links": {
+ "self": {
+ "href": "/api/v3/groups/123",
+ "title": "Another group"
+ },
+ "memberships": {
+ "href": "/api/v3/memberships?filters=[{"principal":{"operator":"=","values":["123"]}}]",
+ "title": "Memberships"
+ },
+ "members": [
+ {
+ "href": "/api/v3/users/343",
+ "title": "Third user"
+ },
+ {
+ "href": "/api/v3/users/60",
+ "title": "Second user"
+ }
+ ]
+ }
+ }
+ ]
+ }
+ }
+
+## List groups [GET]
+
+Returns a collection of groups. The client can choose to filter the groups similar to how work packages are filtered. In addition to the provided filters, the server will reduce the result set to only contain groups, for which the requesting client has sufficient permissions (*view_members*, *manage_members*).
+
++ Parameters
+ + sortBy = ["id", "asc"] (optional, string, `[["id", "asc"]]`) ... JSON specifying sort criteria.
+ Accepts the same format as returned by the [queries](#queries) endpoint. Currently supported sorts are:
+ + id: Sort by primary key
+ + created_at: Sort by group creation datetime
+ + updated_at: Sort by the time the group was updated last
+
++ Response 200 (application/hal+json)
+
+ [List groups][]
+
++ Response 403 (application/hal+json)
+
+ Returned if the client does not have sufficient permissions.
+
+ **Required permission:** View members or manage members in any project
+
+ + Body
+
+ {
+ "_type": "Error",
+ "errorIdentifier": "urn:openproject-org:api:v3:errors:MissingPermission",
+ "message": "You are not authorized to access this resource."
+ }
diff --git a/docs/api/apiv3/endpoints/members.apib b/docs/api/apiv3/endpoints/members.apib
index f8bf53e19c6..f78cead2a25 100644
--- a/docs/api/apiv3/endpoints/members.apib
+++ b/docs/api/apiv3/endpoints/members.apib
@@ -320,7 +320,7 @@ Deletes the membership.
"message": "The requested resource could not be found."
}
-## List memberships [/api/v3/memberships{?filters}]
+## List memberships [/api/v3/memberships{?filters,sortBy}]
+ Model
+ Body
@@ -414,6 +414,15 @@ Returns a collection of memberships. The client can choose to filter the members
+ created_at: filters memberships based on the time the membership was created.
+ updated_at: filters memberships based on the time the membership was updated last.
+ + sortBy = ["id", "asc"] (optional, string, `[["id", "asc"]]`) ... JSON specifying sort criteria.
+ Accepts the same format as returned by the [queries](#queries) endpoint. Currently supported sorts are:
+ + id: Sort by primary key
+ + name: Sort by the name of the principal. Note that this depends on the setting for how the name is to be displayed at least for users.
+ + email: Sort by the email address of the principal. Groups and principal users, which do not have an email, are sorted last.
+ + status: Sort by the status of the principal. Groups and principal users, which do not have a status, are sorted together with the active users.
+ + created_at: Sort by membership creation datetime
+ + updated_at: Sort by the time the membership was updated last
+
+ Response 200 (application/hal+json)
[List memberships][]
diff --git a/lib/api/v3/groups/group_collection_representer.rb b/lib/api/v3/groups/group_collection_representer.rb
new file mode 100644
index 00000000000..ae008c8660e
--- /dev/null
+++ b/lib/api/v3/groups/group_collection_representer.rb
@@ -0,0 +1,39 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module API
+ module V3
+ module Groups
+ class GroupCollectionRepresenter < ::API::Decorators::OffsetPaginatedCollection
+ element_decorator ::API::V3::Groups::GroupRepresenter
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/groups/group_payload_representer.rb b/lib/api/v3/groups/group_payload_representer.rb
new file mode 100644
index 00000000000..d7090022ec0
--- /dev/null
+++ b/lib/api/v3/groups/group_payload_representer.rb
@@ -0,0 +1,39 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module API
+ module V3
+ module Groups
+ class GroupPayloadRepresenter < GroupRepresenter
+ include ::API::Utilities::PayloadRepresenter
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/groups/group_representer.rb b/lib/api/v3/groups/group_representer.rb
index d0231e9a92c..65d60c1a3ce 100644
--- a/lib/api/v3/groups/group_representer.rb
+++ b/lib/api/v3/groups/group_representer.rb
@@ -32,9 +32,31 @@ module API
module V3
module Groups
class GroupRepresenter < ::API::V3::Principals::PrincipalRepresenter
+ include API::Decorators::LinkedResource
+
def _type
'Group'
end
+
+ link :delete,
+ cache_if: -> { current_user.admin? } do
+ {
+ href: api_v3_paths.group(represented.id),
+ method: :delete
+ }
+ end
+
+ link :updateImmediately,
+ cache_if: -> { current_user.admin? } do
+ {
+ href: api_v3_paths.group(represented.id),
+ method: :patch
+ }
+ end
+
+ associated_resources :users,
+ as: :members,
+ skip_render: -> { !current_user.allowed_to_globally?(:manage_members) }
end
end
end
diff --git a/lib/api/v3/groups/groups_api.rb b/lib/api/v3/groups/groups_api.rb
index 6258ca0feac..a0e119800c3 100644
--- a/lib/api/v3/groups/groups_api.rb
+++ b/lib/api/v3/groups/groups_api.rb
@@ -30,29 +30,32 @@ module API
module V3
module Groups
class GroupsAPI < ::API::OpenProjectAPI
- helpers ::API::Utilities::PageSizeHelper
-
resources :groups do
- route_param :id, type: Integer, desc: 'Group ID' do
- helpers do
- def group_scope
- if current_user.allowed_to_globally?(:manage_members)
- Group.all
- else
- Group
- .in_project(Project.allowed_to(current_user, :view_members))
- end
- end
+ after_validation do
+ authorize_any %i[view_members manage_members], global: true
+ end
- def requested_user
- group_scope.find(params[:id])
- end
- end
+ get &::API::V3::Utilities::Endpoints::Index
+ .new(model: Group)
+ .mount
+ post &::API::V3::Utilities::Endpoints::Create
+ .new(model: Group)
+ .mount
- get do
- GroupRepresenter
- .new(requested_user, current_user: current_user)
+ route_param :id, type: Integer, desc: 'Group ID' do
+ after_validation do
+ @group = Group.visible(current_user).find(params[:id])
end
+
+ get &::API::V3::Utilities::Endpoints::Show
+ .new(model: Group)
+ .mount
+ patch &::API::V3::Utilities::Endpoints::Update
+ .new(model: Group)
+ .mount
+ delete &::API::V3::Utilities::Endpoints::Delete
+ .new(model: Group)
+ .mount
end
end
end
diff --git a/lib/api/v3/utilities/path_helper.rb b/lib/api/v3/utilities/path_helper.rb
index 3b4e773533c..fb3e9debdd8 100644
--- a/lib/api/v3/utilities/path_helper.rb
+++ b/lib/api/v3/utilities/path_helper.rb
@@ -370,17 +370,12 @@ module API
index :user
show :user
- class << self
- alias :groups :users
- end
-
def self.user_lock(id)
"#{user(id)}/lock"
end
- def self.group(id)
- "#{root}/groups/#{id}"
- end
+ index :group
+ show :group
resources :version
diff --git a/modules/boards/spec/features/action_boards/assignee_board_spec.rb b/modules/boards/spec/features/action_boards/assignee_board_spec.rb
index 604a88a660b..3423607f534 100644
--- a/modules/boards/spec/features/action_boards/assignee_board_spec.rb
+++ b/modules/boards/spec/features/action_boards/assignee_board_spec.rb
@@ -67,7 +67,7 @@ describe 'Assignee action board',
end
let!(:group) do
- FactoryBot.create(:group, groupname: 'Grouped').tap do |group|
+ FactoryBot.create(:group, name: 'Grouped').tap do |group|
FactoryBot.create(:member,
principal: group,
project: project,
diff --git a/modules/dashboards/spec/features/members_principals_spec.rb b/modules/dashboards/spec/features/members_principals_spec.rb
index b8e48737d8d..66b39821bc6 100644
--- a/modules/dashboards/spec/features/members_principals_spec.rb
+++ b/modules/dashboards/spec/features/members_principals_spec.rb
@@ -51,7 +51,7 @@ describe 'Dashboard page members', type: :feature, js: true, with_mail: false do
shared_let(:group) do
FactoryBot.create(:group,
- groupname: 'DEV Team',
+ name: 'DEV Team',
member_in_project: project,
member_with_permissions: permissions)
end
diff --git a/modules/ldap_groups/lib/open_project/ldap_groups/synchronize_filter.rb b/modules/ldap_groups/lib/open_project/ldap_groups/synchronize_filter.rb
index db47797f036..c3a5381396e 100644
--- a/modules/ldap_groups/lib/open_project/ldap_groups/synchronize_filter.rb
+++ b/modules/ldap_groups/lib/open_project/ldap_groups/synchronize_filter.rb
@@ -76,7 +76,7 @@ module OpenProject::LdapGroups
Group.where(id: sync.group_id).update_all(lastname: name)
else
# Create an OpenProject group
- sync.group = Group.find_or_create_by!(groupname: name)
+ sync.group = Group.find_or_create_by!(name: name)
end
end
end
diff --git a/spec/contracts/groups/create_contract_spec.rb b/spec/contracts/groups/create_contract_spec.rb
new file mode 100644
index 00000000000..e5126042b62
--- /dev/null
+++ b/spec/contracts/groups/create_contract_spec.rb
@@ -0,0 +1,60 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+require 'contracts/shared/model_contract_shared_context'
+require_relative 'shared_contract_examples'
+
+describe Groups::CreateContract do
+ include_context 'ModelContract shared context'
+
+ it_behaves_like 'group contract' do
+ let(:group) do
+ Group.new(name: group_name,
+ group_users: group_users)
+ end
+
+ let(:contract) { described_class.new(group, current_user) }
+
+ describe 'validations' do
+ let(:current_user) { FactoryBot.build_stubbed :admin }
+
+ describe 'type' do
+ context 'type and class mismatch' do
+ before do
+ group.type = User.name
+ end
+
+ it_behaves_like 'contract is invalid', type: 'Type and class mismatch'
+ end
+ end
+ end
+ end
+end
diff --git a/spec/contracts/groups/shared_contract_examples.rb b/spec/contracts/groups/shared_contract_examples.rb
new file mode 100644
index 00000000000..e4e4620e41a
--- /dev/null
+++ b/spec/contracts/groups/shared_contract_examples.rb
@@ -0,0 +1,80 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+
+shared_examples_for 'group contract' do
+ let(:group_name) { 'The group' }
+ let(:group_users) do
+ [FactoryBot.build_stubbed(:group_user, user_id: 1),
+ FactoryBot.build_stubbed(:group_user, user_id: 2)]
+ end
+
+ it_behaves_like 'contract is valid for active admins and invalid for regular users'
+
+ describe 'validations' do
+ let(:current_user) { FactoryBot.build_stubbed :admin }
+
+ context 'name' do
+ context 'is valid' do
+ it_behaves_like 'contract is valid'
+ end
+
+ context 'is too long' do
+ let(:group_name) { 'X' * 257 }
+
+ it_behaves_like 'contract is invalid', name: :too_long
+ end
+
+ context 'is not empty' do
+ let(:group_name) { '' }
+
+ it_behaves_like 'contract is invalid', name: :blank
+ end
+
+ context 'is unique' do
+ before do
+ Group.create(name: group_name)
+ end
+
+ it_behaves_like 'contract is invalid', name: :taken
+ end
+ end
+
+ context 'groups_users' do
+ let(:group_users) do
+ [FactoryBot.build_stubbed(:group_user, user_id: 1),
+ FactoryBot.build_stubbed(:group_user, user_id: 1)]
+ end
+
+ it_behaves_like 'contract is invalid', group_users: :taken
+ end
+ end
+end
diff --git a/spec/contracts/groups/update_contract_spec.rb b/spec/contracts/groups/update_contract_spec.rb
new file mode 100644
index 00000000000..9a8ca12e169
--- /dev/null
+++ b/spec/contracts/groups/update_contract_spec.rb
@@ -0,0 +1,59 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+require 'contracts/shared/model_contract_shared_context'
+require_relative 'shared_contract_examples'
+
+describe Groups::UpdateContract do
+ include_context 'ModelContract shared context'
+
+ it_behaves_like 'group contract' do
+ let(:group) do
+ FactoryBot.build_stubbed(:group,
+ name: group_name,
+ group_users: group_users)
+ end
+
+ let(:contract) { described_class.new(group, current_user) }
+
+ describe 'validations' do
+ let(:current_user) { FactoryBot.build_stubbed :admin }
+
+ describe 'type' do
+ before do
+ group.type = 'A new type'
+ end
+
+ it_behaves_like 'contract is invalid', type: :error_readonly
+ end
+ end
+ end
+end
diff --git a/spec/contracts/placeholder_users/create_contract_spec.rb b/spec/contracts/placeholder_users/create_contract_spec.rb
index d48992c56b8..685577c264c 100644
--- a/spec/contracts/placeholder_users/create_contract_spec.rb
+++ b/spec/contracts/placeholder_users/create_contract_spec.rb
@@ -1,4 +1,5 @@
#-- encoding: UTF-8
+
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
diff --git a/spec/factories/group_user_factory.rb b/spec/factories/group_user_factory.rb
new file mode 100644
index 00000000000..d8a90ba6204
--- /dev/null
+++ b/spec/factories/group_user_factory.rb
@@ -0,0 +1,32 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+FactoryBot.define do
+ factory :group_user do
+ end
+end
diff --git a/spec/features/custom_fields/multi_user_custom_field_spec.rb b/spec/features/custom_fields/multi_user_custom_field_spec.rb
index 3d13bba28a3..587115954d7 100644
--- a/spec/features/custom_fields/multi_user_custom_field_spec.rb
+++ b/spec/features/custom_fields/multi_user_custom_field_spec.rb
@@ -46,7 +46,7 @@ describe "multi select custom values", js: true do
let!(:group) do
FactoryBot.create :group,
- groupname: 'groupfoo',
+ name: 'groupfoo',
member_in_project: project,
member_through_role: role
end
diff --git a/spec/lib/api/v3/groups/group_collection_representer_spec.rb b/spec/lib/api/v3/groups/group_collection_representer_spec.rb
new file mode 100644
index 00000000000..87f0ff6a8e2
--- /dev/null
+++ b/spec/lib/api/v3/groups/group_collection_representer_spec.rb
@@ -0,0 +1,67 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+
+describe ::API::V3::Groups::GroupCollectionRepresenter do
+ let(:self_base_link) { '/api/v3/groups' }
+ let(:groups) do
+ FactoryBot.build_stubbed_list(:group, 3).tap do |groups|
+ allow(groups)
+ .to receive(:per_page)
+ .with(page_size)
+ .and_return(groups)
+
+ allow(groups)
+ .to receive(:page)
+ .with(page)
+ .and_return(groups)
+ end
+ end
+ let(:current_user) { FactoryBot.build_stubbed(:user) }
+ let(:representer) do
+ described_class.new(groups,
+ self_link: self_base_link,
+ per_page: page_size,
+ page: page,
+ current_user: current_user)
+ end
+ let(:total) { 3 }
+ let(:page) { 1 }
+ let(:page_size) { 2 }
+ let(:actual_count) { 3 }
+ let(:collection_inner_type) { 'Group' }
+
+ include API::V3::Utilities::PathHelper
+
+ context 'generation' do
+ subject(:collection) { representer.to_json }
+
+ it_behaves_like 'offset-paginated APIv3 collection', 3, 'groups', 'Group'
+ end
+end
diff --git a/spec/lib/api/v3/groups/group_representer_spec.rb b/spec/lib/api/v3/groups/group_representer_spec.rb
index f3333fdc8d8..8cf276f547f 100644
--- a/spec/lib/api/v3/groups/group_representer_spec.rb
+++ b/spec/lib/api/v3/groups/group_representer_spec.rb
@@ -28,102 +28,211 @@
require 'spec_helper'
-describe ::API::V3::Groups::GroupRepresenter do
- let(:group) { FactoryBot.build_stubbed(:group) }
- let(:current_user) { FactoryBot.build_stubbed(:user) }
- let(:representer) { described_class.new(group, current_user: current_user) }
+describe ::API::V3::Groups::GroupRepresenter, 'rendering' do
+ include ::API::V3::Utilities::PathHelper
- context 'generation' do
- subject(:generated) { representer.to_json }
+ subject(:generated) { representer.to_json }
- it do is_expected.to include_json('Group'.to_json).at_path('_type') end
+ let(:group) do
+ FactoryBot.build_stubbed(:group).tap do |g|
+ allow(g)
+ .to receive(:users)
+ .and_return(members)
+ end
+ end
+ let(:current_user_admin) { false }
+ let(:current_user) { FactoryBot.build_stubbed(:user, admin: current_user_admin) }
+ let(:representer) { described_class.new(group, current_user: current_user, embed_links: embed_links) }
+ let(:members) { 2.times.map { FactoryBot.build_stubbed(:user) } }
+ let(:permissions) { [:manage_members] }
+ let(:embed_links) { true }
+
+ before do
+ allow(current_user)
+ .to receive(:allowed_to_globally?) do |permission|
+ permissions.include?(permission)
+ end
+ end
- context 'as regular user' do
- it 'has an id property' do
- is_expected
- .to be_json_eql(group.id.to_json)
- .at_path('id')
+ describe '_links' do
+ describe 'self' do
+ it_behaves_like 'has a titled link' do
+ let(:link) { 'self' }
+ let(:href) { api_v3_paths.group group.id }
+ let(:title) { group.name }
end
+ end
- it 'has a name property' do
- is_expected
- .to be_json_eql(group.name.to_json)
- .at_path('name')
+ describe 'members' do
+ let(:link) { 'members' }
+
+ context 'with the necessary permissions' do
+ it_behaves_like 'has a link collection' do
+ let(:hrefs) do
+ members.map do |member|
+ {
+ href: api_v3_paths.user(member.id),
+ title: member.name
+ }
+ end
+ end
+ end
end
- it 'hides the updatedAt property' do
- is_expected.not_to have_json_path('updatedAt')
- end
+ context 'without the necessary permissions' do
+ let(:permissions) { [] }
- it 'hides the createdAt property' do
- is_expected.not_to have_json_path('createdAt')
+ it_behaves_like 'has no link'
end
end
- context 'as admin' do
- let(:current_user) { FactoryBot.build_stubbed(:admin) }
+ describe 'updateImmediately' do
+ let(:link) { 'updateImmediately' }
+
+ context 'with the necessary permissions' do
+ let(:current_user_admin) { true }
- it 'has an id property' do
- is_expected
- .to be_json_eql(group.id.to_json)
- .at_path('id')
+ it_behaves_like 'has an untitled link' do
+ let(:href) { api_v3_paths.group group.id }
+ end
end
- it 'has a name property' do
- is_expected
- .to be_json_eql(group.name.to_json)
- .at_path('name')
+ context 'without the necessary permissions' do
+ let(:current_user_admin) { false }
+
+ it_behaves_like 'has no link'
end
+ end
+
+ describe 'delete' do
+ let(:link) { 'delete' }
- it_behaves_like 'has UTC ISO 8601 date and time' do
- let(:date) { group.created_at }
- let(:json_path) { 'createdAt' }
+ context 'with the necessary permissions' do
+ let(:current_user_admin) { true }
+
+ it_behaves_like 'has an untitled link' do
+ let(:href) { api_v3_paths.group group.id }
+ end
end
- it_behaves_like 'has UTC ISO 8601 date and time' do
- let(:date) { group.updated_at }
- let(:json_path) { 'updatedAt' }
+ context 'without the necessary permissions' do
+ let(:current_user_admin) { false }
+
+ it_behaves_like 'has no link'
end
end
+ end
- describe '_links' do
- it 'should link to self' do
- expect(subject).to have_json_path('_links/self/href')
- end
+ describe 'properties' do
+ it_behaves_like 'property', :_type do
+ let(:value) { 'Group' }
end
- describe 'caching' do
- it 'is based on the representer\'s cache_key' do
- expect(OpenProject::Cache)
- .to receive(:fetch)
- .with(representer.json_cache_key)
- .and_call_original
+ it_behaves_like 'property', :id do
+ let(:value) { group.id }
+ end
- representer.to_json
+ it_behaves_like 'property', :name do
+ let(:value) { group.name }
+ end
+
+ describe 'createdAt' do
+ context 'without admin' do
+ it 'hides the createdAt property' do
+ is_expected.not_to have_json_path('createdAt')
+ end
end
- describe '#json_cache_key' do
- let!(:former_cache_key) { representer.json_cache_key }
+ context 'with an admin' do
+ let(:current_user) { FactoryBot.build_stubbed(:admin) }
- it 'includes the name of the representer class' do
- expect(representer.json_cache_key)
- .to include('API', 'V3', 'Groups', 'GroupRepresenter')
+ it_behaves_like 'has UTC ISO 8601 date and time' do
+ let(:date) { group.created_at }
+ let(:json_path) { 'createdAt' }
+ end
+ end
+ end
+
+ describe 'updatedAt' do
+ context 'without admin' do
+ it 'hides the updatedAt property' do
+ is_expected.not_to have_json_path('updatedAt')
end
+ end
- it 'changes when the locale changes' do
- I18n.with_locale(:fr) do
- expect(representer.json_cache_key)
- .not_to eql former_cache_key
+ context 'with an admin' do
+ let(:current_user) { FactoryBot.build_stubbed(:admin) }
+
+ it_behaves_like 'has UTC ISO 8601 date and time' do
+ let(:date) { group.updated_at }
+ let(:json_path) { 'updatedAt' }
+ end
+ end
+ end
+ end
+
+ describe '_embedded' do
+ describe 'members' do
+ let(:embedded_path) { '_embedded/members' }
+
+ context 'with the necessary permissions' do
+ it 'has an array of users embedded' do
+ members.each_with_index do |user, index|
+ is_expected
+ .to be_json_eql('User'.to_json)
+ .at_path("#{embedded_path}/#{index}/_type")
+
+ is_expected
+ .to be_json_eql(user.name.to_json)
+ .at_path("#{embedded_path}/#{index}/name")
end
end
+ end
+
+ context 'without the necessary permissions' do
+ let(:permissions) { [] }
+
+ it 'has no members embedded' do
+ expect(subject)
+ .not_to have_json_path embedded_path
+ end
+ end
+ end
+ end
- it 'changes when the group is updated' do
- group.updated_at = Time.now + 20.seconds
+ describe 'caching' do
+ let(:embed_links) { false }
+
+ it 'is based on the representer\'s cache_key' do
+ expect(OpenProject::Cache)
+ .to receive(:fetch)
+ .with(representer.json_cache_key)
+ .and_call_original
+
+ representer.to_json
+ end
+ describe '#json_cache_key' do
+ let!(:former_cache_key) { representer.json_cache_key }
+
+ it 'includes the name of the representer class' do
+ expect(representer.json_cache_key)
+ .to include('API', 'V3', 'Groups', 'GroupRepresenter')
+ end
+
+ it 'changes when the locale changes' do
+ I18n.with_locale(:fr) do
expect(representer.json_cache_key)
.not_to eql former_cache_key
end
end
+
+ it 'changes when the group is updated' do
+ group.updated_at = Time.now + 20.seconds
+
+ expect(representer.json_cache_key)
+ .not_to eql former_cache_key
+ end
end
end
end
diff --git a/spec/lib/api/v3/utilities/path_helper_spec.rb b/spec/lib/api/v3/utilities/path_helper_spec.rb
index b1d5cc9b88d..0821e90eb9b 100644
--- a/spec/lib/api/v3/utilities/path_helper_spec.rb
+++ b/spec/lib/api/v3/utilities/path_helper_spec.rb
@@ -425,11 +425,8 @@ describe ::API::V3::Utilities::PathHelper do
end
describe 'group paths' do
- describe '#group' do
- subject { helper.group 1 }
-
- it_behaves_like 'api v3 path', '/groups/1'
- end
+ it_behaves_like 'index', :group
+ it_behaves_like 'show', :group
end
describe 'version paths' do
diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb
index d514e3f6e19..47b4f565112 100644
--- a/spec/models/group_spec.rb
+++ b/spec/models/group_spec.rb
@@ -49,7 +49,7 @@ describe Group, type: :model do
describe 'with long but allowed attributes' do
it 'is valid' do
- group.groupname = 'a' * 256
+ group.name = 'a' * 256
expect(group).to be_valid
expect(group.save).to be_truthy
end
@@ -57,7 +57,7 @@ describe Group, type: :model do
describe 'with a name too long' do
it 'is invalid' do
- group.groupname = 'a' * 257
+ group.name = 'a' * 257
expect(group).not_to be_valid
expect(group.save).to be_falsey
end
@@ -71,6 +71,30 @@ describe Group, type: :model do
end
end
+ describe '#group_users' do
+ context 'when adding a user' do
+ it 'updates the timestamp' do
+ updated_at = group.updated_at
+ group.group_users.create(user: user)
+
+ expect(updated_at < group.reload.updated_at)
+ .to be_truthy
+ end
+ end
+
+ context 'when removing a user' do
+ it 'updates the timestamp' do
+ group.group_users.create(user: user)
+ updated_at = group.reload.updated_at
+
+ group.group_users.destroy_all
+
+ expect(updated_at < group.reload.updated_at)
+ .to be_truthy
+ end
+ end
+ end
+
describe 'from legacy specs' do
let!(:roles) { FactoryBot.create_list :role, 2 }
let!(:role_ids) { roles.map(&:id).sort }
@@ -118,7 +142,7 @@ describe Group, type: :model do
group.valid?
end
- it { expect(group.errors.full_messages[0]).to include I18n.t('attributes.groupname') }
+ it { expect(group.errors.full_messages[0]).to include I18n.t('attributes.name') }
end
end
end
@@ -135,8 +159,8 @@ describe Group, type: :model do
end
end
- describe '#groupname' do
- it { expect(group).to validate_presence_of :groupname }
- it { expect(group).to validate_uniqueness_of :groupname }
+ describe '#name' do
+ it { expect(group).to validate_presence_of :name }
+ it { expect(group).to validate_uniqueness_of :name }
end
end
diff --git a/spec/models/principals/scopes/ordered_by_name_spec.rb b/spec/models/principals/scopes/ordered_by_name_spec.rb
index 490207d7d98..6006ddd5b70 100644
--- a/spec/models/principals/scopes/ordered_by_name_spec.rb
+++ b/spec/models/principals/scopes/ordered_by_name_spec.rb
@@ -35,7 +35,7 @@ describe Principals::Scopes::OrderedByName, type: :model do
shared_let(:alice) { FactoryBot.create(:user, login: 'alice', firstname: 'Alice', lastname: 'Zetop') }
shared_let(:eve) { FactoryBot.create(:user, login: 'eve', firstname: 'Eve', lastname: 'Baddie') }
- shared_let(:group) { FactoryBot.create(:group, groupname: 'Core Team') }
+ shared_let(:group) { FactoryBot.create(:group, name: 'Core Team') }
shared_let(:placeholder_user) { FactoryBot.create(:placeholder_user, name: 'Developers') }
subject { Principal.ordered_by_name(desc: descending).pluck(:id) }
diff --git a/spec/requests/api/v3/groups/group_resource_spec.rb b/spec/requests/api/v3/groups/group_resource_spec.rb
index a1c0c17e2d7..b03eb6d57fd 100644
--- a/spec/requests/api/v3/groups/group_resource_spec.rb
+++ b/spec/requests/api/v3/groups/group_resource_spec.rb
@@ -33,54 +33,59 @@ describe 'API v3 Group resource', type: :request, content_type: :json do
include Rack::Test::Methods
include API::V3::Utilities::PathHelper
- let(:project) { FactoryBot.create(:project) }
+ subject(:response) { last_response }
+
+ shared_let(:project) { FactoryBot.create(:project) }
let(:group) do
FactoryBot.create(:group,
member_in_project: project,
- member_through_role: role)
+ member_through_role: role).tap do |g|
+ members.each do |members|
+ GroupUser.create group_id: g.id, user_id: members.id
+ end
+ end
end
- let(:group_project) { project }
let(:role) { FactoryBot.create(:role, permissions: permissions) }
- let(:permissions) { [:view_members] }
- let(:current_user) do
+ let(:permissions) { %i[view_members manage_members] }
+ let(:members) do
+ FactoryBot.create_list(:user, 2)
+ end
+ let(:admin) { FactoryBot.create(:admin) }
+
+ current_user do
FactoryBot.create(:user,
member_in_project: project,
member_through_role: role)
end
- subject(:response) { last_response }
-
- before do
- login_as(current_user)
- end
+ describe 'GET api/v3/groups/:id' do
+ let(:get_path) { api_v3_paths.group group.id }
- describe '#get' do
before do
get get_path
end
context 'having the necessary permission' do
- let(:get_path) { api_v3_paths.group group.id }
-
it 'responds with 200 OK' do
expect(subject.status)
.to eq(200)
end
- it 'responds with a group resource' do
+ it 'responds with the correct group resource including the members' do
expect(subject.body)
.to be_json_eql('Group'.to_json)
.at_path('_type')
- end
- it 'responds with the correct group' do
expect(subject.body)
.to be_json_eql(group.name.to_json)
.at_path('name')
+
+ expect(JSON::parse(subject.body).dig('_links', 'members').map { |link| link['href'] })
+ .to match_array members.map { |m| api_v3_paths.user(m.id) }
end
end
- context 'requesting nonexistent user' do
+ context 'requesting nonexistent group' do
let(:get_path) { api_v3_paths.group 9999 }
it_behaves_like 'not found' do
@@ -89,14 +94,322 @@ describe 'API v3 Group resource', type: :request, content_type: :json do
end
end
+ context 'not having the necessary permission to see any group' do
+ let(:permissions) { [] }
+
+ it_behaves_like 'unauthorized access'
+ end
+
+ context 'not having the necessary permission to see the specific group' do
+ let(:permissions) { %i[view_members] }
+ let(:group) { FactoryBot.create(:group) }
+
+ it_behaves_like 'not found'
+ end
+ end
+
+ describe 'POST api/v3/groups' do
+ let(:path) { api_v3_paths.groups }
+ let(:body) do
+ {
+ name: 'The new group',
+ members: [
+ {
+ href: api_v3_paths.user(members.first.id)
+ },
+ {
+ href: api_v3_paths.user(members.last.id)
+ }
+ ]
+ }.to_json
+ end
+
+ before do
+ post path, body
+ end
+
+ context 'when the user is allowed and the input is valid' do
+ current_user { FactoryBot.create(:admin) }
+
+ it 'responds with 201' do
+ expect(last_response.status).to eq(201)
+ end
+
+ it 'creates the group and sets the members' do
+ group = Group.find_by(name: 'The new group')
+ expect(group)
+ .to be_present
+
+ expect(group.users)
+ .to match_array members
+ end
+
+ it 'returns the newly created group' do
+ expect(last_response.body)
+ .to be_json_eql('Group'.to_json)
+ .at_path('_type')
+
+ expect(last_response.body)
+ .to be_json_eql('The new group'.to_json)
+ .at_path('name')
+ end
+ end
+
+ context 'when the user is allowed and the input is invalid' do
+ current_user { FactoryBot.create(:admin) }
+
+ let(:body) do
+ {
+ name: ''
+ }.to_json
+ end
+
+ it 'responds with 422 and explains the error' do
+ expect(last_response.status).to eq(422)
+
+ expect(last_response.body)
+ .to be_json_eql("Name can't be blank.".to_json)
+ .at_path('message')
+ end
+ end
+
context 'not having the necessary permission' do
+ it_behaves_like 'unauthorized access'
+ end
+ end
+
+ describe 'PATCH api/v3/groups/:id' do
+ let(:path) { api_v3_paths.group(group.id) }
+ let(:another_user) { FactoryBot.create(:user) }
+ let(:body) do
+ {
+ _links: {
+ "members": [
+ {
+ href: api_v3_paths.user(members.last.id)
+ },
+ {
+ href: api_v3_paths.user(another_user.id)
+ }
+ ]
+ }
+ }.to_json
+ end
+ let(:group_updated_at) { group.reload.updated_at }
+ let(:other_project) { FactoryBot.create(:project) }
+ let!(:membership) do
+ FactoryBot.create(:member,
+ principal: group,
+ project: other_project,
+ roles: [FactoryBot.create(:role)])
+ end
+
+ before do
+ # Setup the memberships in the group has
+ ::Groups::AddUsersService
+ .new(group, current_user: admin)
+ .call(ids: members.map(&:id))
+
+ group_updated_at
+
+ login_as current_user
+
+ patch path, body
+ end
+
+ context 'when the user is allowed and the input is valid' do
+ current_user { admin }
+
+ it 'responds with 200' do
+ expect(last_response.status).to eq(200)
+ end
+
+ it 'updates the group' do
+ group.reload
+
+ expect(group.users)
+ .to match_array [members.last, another_user]
+
+ # Altering only the members still updates the group's timestamp
+ expect(group.updated_at > group_updated_at)
+ .to be_truthy
+ end
+
+ it 'returns the updated group' do
+ expect(last_response.body)
+ .to be_json_eql('Group'.to_json)
+ .at_path('_type')
+
+ expect(last_response.body)
+ .to be_json_eql([{ href: api_v3_paths.user(members.last.id), title: members.last.name },
+ { href: api_v3_paths.user(another_user.id), title: another_user.name }].to_json)
+ .at_path('_links/members')
+
+ # unchanged
+ expect(last_response.body)
+ .to be_json_eql(group.name.to_json)
+ .at_path('name')
+
+ # includes the memberships the group has applied to the added user
+ expect(other_project.reload.users)
+ .to match_array [members.last, another_user]
+ end
+ end
+
+ context 'if attempting to set an empty name' do
+ current_user { admin }
+
+ let(:body) do
+ {
+ _links: {
+ "members": [
+ {
+ href: api_v3_paths.user(members.last.id)
+ },
+ {
+ href: api_v3_paths.user(another_user.id)
+ }
+ ]
+ },
+ name: ''
+ }.to_json
+ end
+
+ it 'returns 422' do
+ expect(last_response.status)
+ .to eql(422)
+
+ expect(last_response.body)
+ .to be_json_eql("Name can't be blank.".to_json)
+ .at_path('message')
+ end
+
+ it 'does not alter the group' do
+ group.reload
+
+ expect(group.users)
+ .to match_array members
+
+ expect(group.updated_at)
+ .to eql group_updated_at
+ end
+ end
+
+ context 'when not being an admin' do
+ let(:permissions) { [:manage_members] }
+
+ it_behaves_like 'unauthorized access'
+ end
+
+ context 'when lacking the view permissions' do
let(:permissions) { [] }
- let(:get_path) { api_v3_paths.group group.id }
- it_behaves_like 'not found' do
- let(:id) { group.id }
- let(:type) { 'Group' }
+ it_behaves_like 'unauthorized access'
+ end
+ end
+
+ describe 'DELETE /api/v3/groups/:id' do
+ let(:path) { api_v3_paths.group(group.id) }
+ let(:other_project) { FactoryBot.create(:project) }
+ let!(:membership) do
+ FactoryBot.create(:member,
+ principal: group,
+ project: other_project,
+ roles: [FactoryBot.create(:role)])
+ end
+
+ before do
+ # Setup the memberships in the group has
+ ::Groups::AddUsersService
+ .new(group, current_user: admin)
+ .call(ids: members.map(&:id))
+
+ login_as current_user
+
+ delete path
+ end
+
+ subject(:response) { last_response }
+
+ context 'with required permissions' do
+ current_user { admin }
+
+ it 'responds with HTTP No Content' do
+ expect(response.status).to eq 204
+ end
+
+ it 'deletes the group' do
+ expect(Group)
+ .not_to exist(group.id)
+ end
+
+ it 'deletes the memberships of the members' do
+ expect(other_project.users)
+ .to be_empty
+ end
+
+ context 'for a non-existent group' do
+ let(:path) { api_v3_paths.group 11111337 }
+
+ it_behaves_like 'not found' do
+ let(:id) { 11111337 }
+ let(:type) { 'Group' }
+ end
+ end
+ end
+
+ context 'without permission to delete groups' do
+ it_behaves_like 'unauthorized access'
+
+ it 'does not delete the member' do
+ expect(Group)
+ .to exist(group.id)
+ end
+ end
+ end
+
+ describe 'GET api/v3/groups' do
+ let(:get_path) { api_v3_paths.groups }
+ let(:other_group) do
+ FactoryBot.create(:group)
+ end
+
+ before do
+ group
+ other_group
+
+ get get_path
+ end
+
+ context 'having the necessary permission' do
+ it 'responds with 200 OK' do
+ expect(subject.status)
+ .to eq(200)
+ end
+
+ it 'responds with a collection of groups' do
+ expect(subject.body)
+ .to be_json_eql('Collection'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql('2')
+ .at_path('total')
+
+ expect(subject.body)
+ .to be_json_eql(other_group.id.to_json)
+ .at_path('_embedded/elements/0/id')
+
+ expect(subject.body)
+ .to be_json_eql(group.id.to_json)
+ .at_path('_embedded/elements/1/id')
end
end
+
+ context 'not having the necessary permission' do
+ let(:permissions) { [] }
+
+ it_behaves_like 'unauthorized access'
+ end
end
end
diff --git a/spec/services/base_services/behaves_like_update_service.rb b/spec/services/base_services/behaves_like_update_service.rb
index 215d873762f..3e4c3879a1b 100644
--- a/spec/services/base_services/behaves_like_update_service.rb
+++ b/spec/services/base_services/behaves_like_update_service.rb
@@ -66,22 +66,22 @@ shared_examples 'BaseServices update service' do
allow(set_attributes_class)
.to receive(:new)
- .with(user: user,
- model: model_instance,
- contract_class: contract_class,
- contract_options: {})
- .and_return(service)
+ .with(user: user,
+ model: model_instance,
+ contract_class: contract_class,
+ contract_options: {})
+ .and_return(service)
allow(service)
.to receive(:call)
- .and_return(set_attributes_result)
+ .and_return(set_attributes_result)
end
before do
allow(model_instance).to receive(:save).and_return(true)
end
- subject { instance.call(call_attributes) }
+ subject(:instance_call) { instance.call(call_attributes) }
describe '#user' do
it 'exposes a user which is available as a getter' do
@@ -98,7 +98,7 @@ shared_examples 'BaseServices update service' do
describe "#call" do
context 'when the model instance is valid' do
it 'is a successful call', :aggregate_failures do
- expect(subject.success?).to be_truthy
+ expect(subject).to be_success
expect(subject).to eql set_attributes_result
expect(subject.result).to eql model_instance
end
@@ -110,7 +110,7 @@ shared_examples 'BaseServices update service' do
it 'is unsuccessful', :aggregate_failures do
expect(model_instance).not_to receive(:save)
- expect(subject.success?).to be_falsey
+ expect(subject).to be_failure
expect(subject).to eql set_attributes_result
expect(model_instance).to_not receive(:save)
@@ -127,7 +127,7 @@ shared_examples 'BaseServices update service' do
end
it 'is unsuccessful and returns the errors', :aggregate_failures do
- expect(subject.success?).to be_falsey
+ expect(subject).to be_failure
expect(subject.errors).to eql model_instance.errors
end
end
diff --git a/spec/services/groups/set_attributes_service_spec.rb b/spec/services/groups/set_attributes_service_spec.rb
new file mode 100644
index 00000000000..d51ddb537bf
--- /dev/null
+++ b/spec/services/groups/set_attributes_service_spec.rb
@@ -0,0 +1,182 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+
+describe Groups::SetAttributesService, type: :model do
+ subject(:service_call) { instance.call(call_attributes) }
+
+ let(:user) { FactoryBot.build_stubbed(:user) }
+ let(:contract_class) do
+ contract = double('contract_class')
+
+ allow(contract)
+ .to receive(:new)
+ .with(group, user, options: { changed_by_system: [] })
+ .and_return(contract_instance)
+
+ contract
+ end
+ let(:contract_instance) do
+ instance_double(ModelContract, validate: contract_valid, errors: contract_errors)
+ end
+ let(:contract_valid) { true }
+ let(:contract_errors) do
+ instance_double(ActiveRecord::ActiveRecordError)
+ end
+ let(:group_valid) { true }
+ let(:instance) do
+ described_class.new(user: user,
+ model: group,
+ contract_class: contract_class)
+ end
+ let(:call_attributes) { {} }
+ let(:group) do
+ FactoryBot.build_stubbed(:group) do |g|
+ # To later check that it has not been called
+ allow(g)
+ .to receive(:save)
+ end
+ end
+
+ describe 'call' do
+ let(:call_attributes) do
+ {
+ name: 'The name'
+ }
+ end
+
+ before do
+ allow(group)
+ .to receive(:valid?)
+ .and_return(group_valid)
+
+ allow(contract_instance)
+ .to receive(:validate)
+ .and_return(contract_valid)
+ end
+
+ it 'is successful' do
+ expect(service_call)
+ .to be_success
+ end
+
+ it 'sets the attributes' do
+ service_call
+
+ expect(group.lastname)
+ .to eql call_attributes[:name]
+ end
+
+ it 'does not persist the group' do
+ service_call
+
+ expect(group)
+ .not_to have_received(:save)
+ end
+
+ context 'with changes to the users do' do
+ let(:first_user) { FactoryBot.build_stubbed(:user) }
+ let(:second_user) { FactoryBot.build_stubbed(:user) }
+ let(:third_user) { FactoryBot.build_stubbed(:user) }
+
+ let(:call_attributes) do
+ {
+ user_ids: [second_user.id, third_user.id]
+ }
+ end
+
+ shared_examples_for 'updates the users' do
+ let(:first_group_user) { FactoryBot.build_stubbed(:group_user, user: first_user) }
+ let(:second_group_user) { FactoryBot.build_stubbed(:group_user, user: second_user) }
+
+ let(:group) do
+ FactoryBot.build_stubbed(:group, group_users: [first_group_user, second_group_user])
+ end
+
+ it 'adds the new users' do
+ expect(service_call.result.group_users.map(&:user_id))
+ .to eql [first_user.id, second_user.id, third_user.id]
+ end
+
+ it 'does not persist the new association' do
+ expect(service_call.result.group_users.find { |gu| gu.user_id == third_user.id })
+ .to be_new_record
+ end
+
+ it 'keeps the association already existing before' do
+ expect(service_call.result.group_users.find { |gu| gu.user_id == second_user.id })
+ .not_to be_marked_for_destruction
+ end
+
+ it 'marks not mentioned users to be removed' do
+ expect(service_call.result.group_users.find { |gu| gu.user_id == first_user.id })
+ .to be_marked_for_destruction
+ end
+ end
+
+ context 'with a persisted record and integer values' do
+ let(:call_attributes) do
+ {
+ user_ids: [second_user.id, third_user.id]
+ }
+ end
+
+ it_behaves_like 'updates the users'
+ end
+
+ context 'with a persisted record and string values' do
+ let(:call_attributes) do
+ {
+ user_ids: [second_user.id.to_s, third_user.id.to_s]
+ }
+ end
+
+ it_behaves_like 'updates the users'
+ end
+
+ context 'with a new record' do
+ let(:group) do
+ Group.new
+ end
+
+ it 'sets the user' do
+ expect(service_call.result.group_users.map(&:user_id))
+ .to eql [second_user.id, third_user.id]
+ end
+
+ it 'does not persist the association' do
+ expect(service_call.result.group_users.all(&:new_record?))
+ .to be_truthy
+ end
+ end
+ end
+ end
+end
diff --git a/spec/services/groups/update_service_spec.rb b/spec/services/groups/update_service_spec.rb
new file mode 100644
index 00000000000..883f9b3109f
--- /dev/null
+++ b/spec/services/groups/update_service_spec.rb
@@ -0,0 +1,119 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+require 'services/base_services/behaves_like_update_service'
+
+describe Groups::UpdateService, type: :model do
+ it_behaves_like 'BaseServices update service' do
+ let(:add_service_result) do
+ ServiceResult.new success: true
+ end
+ let!(:add_users_service) do
+ add_service = instance_double(Groups::AddUsersService)
+
+ allow(Groups::AddUsersService)
+ .to receive(:new)
+ .with(model_instance, current_user: user)
+ .and_return(add_service)
+
+ allow(add_service)
+ .to receive(:call)
+ .and_return(add_service_result)
+
+ add_service
+ end
+
+ context 'with newly created group_users' do
+ let(:old_group_user) { FactoryBot.build_stubbed(:group_user, user_id: 3) }
+ let(:new_group_user) do
+ FactoryBot.build_stubbed(:group_user, user_id: 5).tap do |gu|
+ allow(gu)
+ .to receive(:saved_changes?)
+ .and_return(true)
+ end
+ end
+ let(:group_users) { [old_group_user, new_group_user] }
+
+ before do
+ allow(model_instance)
+ .to receive(:group_users)
+ .and_return(group_users)
+ end
+
+ context 'with the AddUsersService being successful' do
+ it 'is successful' do
+ expect(instance_call).to be_success
+ end
+
+ it 'calls the AddUsersService' do
+ instance_call
+
+ expect(add_users_service)
+ .to have_received(:call)
+ .with(ids: [new_group_user.user_id])
+ end
+ end
+
+ context 'with the AddUsersService being unsuccessful' do
+ let(:add_service_result) do
+ ServiceResult.new success: false
+ end
+
+ it 'is failure' do
+ expect(instance_call).to be_failure
+ end
+
+ it 'calls the AddUsersService' do
+ instance_call
+
+ expect(add_users_service)
+ .to have_received(:call)
+ .with(ids: [new_group_user.user_id])
+ end
+ end
+
+ context 'without any new group_users' do
+ let(:group_users) { [old_group_user] }
+
+ it 'is successful' do
+ expect(instance_call).to be_success
+ end
+
+ it 'does not call the AddUsersService' do
+ instance_call
+
+ expect(add_users_service)
+ .not_to have_received(:call)
+ end
+ end
+ end
+ end
+end