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
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
add projects delete end point to api
ulferts05ac3af1ee90
diff --git a/app/contracts/projects/archive_contract.rb b/app/contracts/projects/archive_contract.rbnew file mode 100644index 00000000000..a5c1605d8b8--- /dev/null+++ b/app/contracts/projects/archive_contract.rb@@ -0,0 +1,67 @@+#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)+#+# 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-2017 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 Projects+ class ArchiveContract < ModelContract+ def validate+ user_allowed+ validate_no_foreign_wp_references++ super+ end++ protected++ def user_allowed+ unless authorized?+ errors.add :base, :error_unauthorized+ end+ end++ # Check that there is no wp of a non descendant project that is assigned+ # to one of the project or descendant versions+ def validate_no_foreign_wp_references+ version_ids = model.rolled_up_versions.select(:id)++ exists = WorkPackage+ .where.not(project_id: model.self_and_descendants.select(:id))+ .where(fixed_version_id: version_ids)+ .exists?++ errors.add :base, :foreign_wps_reference_version if exists+ end++ def validate_model?+ false+ end++ def authorized?+ user.admin?+ end+ end+enddiff --git a/app/contracts/projects/unarchive_contract.rb b/app/contracts/projects/unarchive_contract.rbnew file mode 100644index 00000000000..c6461f6a0e2--- /dev/null+++ b/app/contracts/projects/unarchive_contract.rb@@ -0,0 +1,60 @@+#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)+#+# 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-2017 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 Projects+ class UnarchiveContract < ModelContract+ def validate+ user_allowed+ validate_all_ancestors_active++ super+ end++ protected++ def user_allowed+ unless authorized?+ errors.add :base, :error_unauthorized+ end+ end++ def validate_all_ancestors_active+ if model.ancestors.any?(&:archived?)+ errors.add :base, :archived_ancestor+ end+ end++ def validate_model?+ false+ end++ def authorized?+ user.admin?+ end+ end+enddiff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rbindex c3b332c6126..d360e5399f8 100644--- a/app/controllers/projects_controller.rb+++ b/app/controllers/projects_controller.rb@@ -107,7 +107,7 @@ class ProjectsController < ApplicationController@errors = service_call.errors- flash[:notice] = l(:notice_successful_update) if service_call.success?+ flash[:notice] = t(:notice_successful_update) if service_call.success?redirect_to settings_project_path(@altered_project)end@@ -158,35 +158,26 @@ class ProjectsController < ApplicationControllerenddef archive- projects_url = url_for(controller: '/projects', action: 'index', status: params[:status])- if @project.archive- redirect_to projects_url- else- flash[:error] = I18n.t(:error_can_not_archive_project)- redirect_back fallback_location: projects_url- end-- update_demo_project_settings @project, false+ change_status_action(:archive)enddef unarchive- @project.unarchive if [email protected]?- redirect_to(url_for(controller: '/projects', action: 'index', status: params[:status]))- update_demo_project_settings @project, true+ change_status_action(:unarchive)end# Delete @projectdef destroy- service = ::Projects::DeleteProjectService.new(user: current_user, project: @project)- call = service.call(delayed: true)+ service_call = ::Projects::ScheduleDeletionService+ .new(user: current_user, model: @project)+ .call- if call.success?+ if service_call.success?flash[:notice] = I18n.t('projects.delete.scheduled')else- flash[:error] = I18n.t('projects.delete.schedule_failed', errors: call.errors.full_messages.join("\n"))+ flash[:error] = I18n.t('projects.delete.schedule_failed', errors: service_call.errors.full_messages.join("\n"))end- redirect_to controller: 'projects', action: 'index'+ redirect_to project_path_with_statusupdate_demo_project_settings @project, falseend@@ -215,6 +206,26 @@ class ProjectsController < ApplicationControllerrender_404end+ def change_status_action(status)+ service_call = change_status(status)++ if service_call.success?+ update_demo_project_settings @project, status == :archive+ redirect_to(project_path_with_status)+ else+ flash[:error] = t(:"error_can_not_#{status}_project",+ errors: service_call.errors.full_messages.join(', '))+ redirect_back fallback_location: project_path_with_status+ end+ end++ def change_status(status)+ "Projects::#{status.to_s.camelcase}Service"+ .constantize+ .new(user: current_user, model: @project)+ .call+ end+def redirect_work_packages_or_overviewreturn if redirect_to_project_menu_item(@project, :work_packages)@@ -225,6 +236,12 @@ class ProjectsController < ApplicationController@project = nilend+ def project_path_with_status+ acceptable_params = params.permit(:status).to_h.compact.select { |_, v| v.present? }++ projects_path(acceptable_params)+ end+def load_query@query = ParamsToQueryService.new(Project, current_user).call(params)diff --git a/app/models/project.rb b/app/models/project.rbindex ee819cab06d..017dcb1895d 100644--- a/app/models/project.rb+++ b/app/models/project.rb@@ -172,9 +172,6 @@ class Project < ActiveRecord::Basefriendly_id :identifier, use: :finders- before_destroy :delete_all_members- before_destroy :destroy_all_work_packages-scope :has_module, ->(mod) {where(["#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s])}@@ -294,48 +291,19 @@ class Project < ActiveRecord::Basecondend- # TODO: Move into ArchiveService- # Archives the project and its descendants- def archive- # Check that there is no issue of a non descendant project that is assigned- # to one of the project or descendant versions- v_ids = self_and_descendants.map(&:version_ids).flatten- if v_ids.any? && WorkPackage.includes(:project)- .where(["(#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?)" +- " AND #{WorkPackage.table_name}.fixed_version_id IN (?)", lft, rgt, v_ids])- .references(:projects)- .first- return false- end-- Project.transaction do- archive!- end-- true- end-- # TODO: Move into UnarchiveService- # Unarchives the project- # All its ancestors must be active- def unarchive- return false if ancestors.detect { |a| !a.active? }-- update_attribute :status, STATUS_ACTIVE- end-def types_used_by_work_packages::Type.where(id: WorkPackage.where(project_id: project.id).select(:type_id).distinct)end- # Returns an array of the types used by the project and its active sub projects+ # Returns a scope of the types used by the project and its active sub projectsdef rolled_up_types- @rolled_up_types ||=- ::Type.joins(:projects)+ ::Type+ .joins(:projects).select("DISTINCT #{::Type.table_name}.*")- .where(["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt])+ .where(projects: { id: self_and_descendants.select(:id) })+ .merge(Project.active).order("#{::Type.table_name}.position")end@@ -392,25 +360,6 @@ class Project < ActiveRecord::Baseendend- # TODO: Move into DeleteService- # Deletes all project's members- def delete_all_members- me = Member.table_name- mr = MemberRole.table_name- self.class.connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")- Member.where(project_id: id).destroy_all- end-- def destroy_all_work_packages- work_packages.each do |wp|- begin- wp.reload- wp.destroy- rescue ActiveRecord::RecordNotFound => e- end- end- end-# Returns users that should be always notified on project eventsdef recipientsnotified_users@@ -627,14 +576,6 @@ class Project < ActiveRecord::Baseendend- # Archives subprojects recursively- def archive!- children.each do |subproject|- subproject.send :archive!- end- update_attribute :status, STATUS_ARCHIVED- end-def self.possible_principles_conditioncondition = if Setting.work_package_group_assignment?["(#{Principal.table_name}.type=? OR #{Principal.table_name}.type=?)", 'User', 'Group']@@ -652,19 +593,6 @@ class Project < ActiveRecord::Baseprotected- def guarantee_project_or_nil_or_false(p)- if p.is_a?(Project)- p- elsif p.to_s.blank?- nil- else- p = Project.find_by(id: p)- return false unless p-- p- end- end-def shared_versions_on_persistedshared_versions_base_scope.where(projects: { id: id })diff --git a/app/services/base_services/base_contracted.rb b/app/services/base_services/base_contracted.rbnew file mode 100644index 00000000000..037bcbe0aef--- /dev/null+++ b/app/services/base_services/base_contracted.rb@@ -0,0 +1,91 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2019 the OpenProject Foundation (OPF)+#+# 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-2017 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 doc/COPYRIGHT.rdoc for more details.+#++++module BaseServices+ class BaseContracted+ include Concerns::Contracted+ include Shared::ServiceContext++ attr_reader :user++ def initialize(user:, contract_class: nil)+ @user = user+ self.contract_class = contract_class || default_contract_class+ end++ def call(params = nil)+ in_context(false) do+ perform(params)+ end+ end++ private++ def perform(params)+ service_call = before_perform(params)++ service_call = validate_contract(service_call) if service_call.success?+ service_call = persist(service_call) if service_call.success?+ service_call = after_perform(service_call) if service_call.success?++ service_call+ end++ def before_perform(_params)+ ServiceResult.new(success: true, result: model)+ end++ def validate_contract(call)+ success, errors = validate(model, user)++ unless success+ call.success = false+ call.errors = errors+ end++ call+ end++ def after_perform(call)+ # nothing for now but subclasses can override+ call+ end+ alias_method :after_save, :after_perform++ def persist(call)+ # nothing for now but subclasses can override+ call+ end++ def default_contract_class+ raise NotImplementedError+ end+ end+enddiff --git a/app/services/base_services/delete.rb b/app/services/base_services/delete.rbindex a4a0dbad1d5..c574ca62135 100644--- a/app/services/base_services/delete.rb+++ b/app/services/base_services/delete.rb@@ -27,38 +27,29 @@#++module BaseServices- class Delete- include ::Shared::ServiceContext- include ::Concerns::Contracted-- attr_accessor :user,- :model,- :contract_class+ class Delete < BaseContracted+ attr_accessor :modeldef initialize(user:, model:, contract_class: nil)- self.user = userself.model = model- self.contract_class = contract_class || default_contract+ super(user: user, contract_class: contract_class)end- def call- in_context(false) do- delete+ def persist(service_result)+ service_result = super(service_result)++ unless service_result.result.destroy+ service_result.errors = service_result.result.errors+ service_result.success = falseend- end- def default_contract- "#{model.class.name.demodulize.pluralize}::DeleteContract".constantize+ service_resultendprotected- def delete- result, errors = validate_and_yield(model, user) do- model.destroy- end-- ServiceResult.new(success: result, result: model, errors: errors)+ def default_contract_class+ "#{model.class.name.demodulize.pluralize}::DeleteContract".constantizeendendenddiff --git a/app/services/base_services/write.rb b/app/services/base_services/write.rbindex 4bca6c37758..03be3b55eca 100644--- a/app/services/base_services/write.rb+++ b/app/services/base_services/write.rb@@ -29,38 +29,28 @@#++module BaseServices- class Write- include Concerns::Contracted- include Shared::ServiceContext-- attr_reader :user+ class Write < BaseContracted+ private- def initialize(user:, contract_class: nil)- @user = user- self.contract_class = contract_class || default_contract_class- end+ def persist(service_result)+ service_result = super(service_result)- def call(params)- in_context(false) do- write(params)+ unless service_result.result.save+ service_result.errors = service_result.result.errors+ service_result.success = falseend- end-- private- def write(params)- attributes_call = set_attributes(params)+ service_result+ end- if attributes_call.failure?- # nothing to do- elsif !attributes_call.result.save- attributes_call.errors = attributes_call.result.errors- attributes_call.success = false- else- after_save(attributes_call)- end+ # Validations are already handled in the SetAttributesService+ # and thus we do not have to validate again.+ def validate_contract(service_result)+ service_result+ end- attributes_call+ def before_perform(params)+ set_attributes(params)enddef set_attributes(params)@@ -71,8 +61,8 @@ module BaseServices.call(params)end- def after_save(_attributes_call)- # nothing for now but subclasses can override+ def attributes_service_class+ "#{namespace}::SetAttributesService".constantizeenddef instance(_params)@@ -83,16 +73,12 @@ module BaseServicesraise NotImplementedErrorend- def attributes_service_class- "#{namespace}::SetAttributesService".constantize+ def namespace+ self.class.name.deconstantizeenddef instance_classnamespace.singularize.constantizeend-- def namespace- self.class.name.deconstantize- endendenddiff --git a/app/services/projects/archive_service.rb b/app/services/projects/archive_service.rbnew file mode 100644index 00000000000..2ca35f6c6b2--- /dev/null+++ b/app/services/projects/archive_service.rb@@ -0,0 +1,57 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2019 the OpenProject Foundation (OPF)+#+# 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-2017 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 doc/COPYRIGHT.rdoc for more details.+#++++module Projects+ class ArchiveService < ::BaseServices::BaseContracted+ include Concerns::Contracted++ def initialize(user:, model:, contract_class: Projects::ArchiveContract)+ super(user: user, contract_class: contract_class)+ self.model = model+ end++ private++ attr_accessor :model++ def persist(service_call)+ archive_project(model) and model.children.each do |child|+ archive_project(child)+ end++ service_call+ end++ def archive_project(project)+ # we do not care for validations+ project.update_column(:status, Project::STATUS_ARCHIVED)+ end+ end+enddiff --git a/app/services/projects/create_service.rb b/app/services/projects/create_service.rbindex d174945104e..fef49400149 100644--- a/app/services/projects/create_service.rb+++ b/app/services/projects/create_service.rb@@ -30,8 +30,10 @@module Projectsclass CreateService < ::BaseServices::Create- def after_save(attributes_call)+ def after_perform(attributes_call)attributes_call.result.add_member!(user, Role.in_new_project) unless user.admin?++ superendendenddiff --git a/app/services/projects/delete_project_service.rb b/app/services/projects/delete_service.rbsimilarity index 55%rename from app/services/projects/delete_project_service.rbrename to app/services/projects/delete_service.rbindex fa623e2258b..064928f020b 100644--- a/app/services/projects/delete_project_service.rb+++ b/app/services/projects/delete_service.rb@@ -29,48 +29,48 @@#++module Projects- class DeleteProjectService- attr_accessor :user, :project- include Concerns::Contracted-- def initialize(user:, project:)- self.user = user- self.project = project- self.contract_class = ::Projects::DeleteContract+ class DeleteService < ::BaseServices::Delete+ def call(*)+ super.tap do |service_call|+ notify(service_call.success?)+ endend- ##- # Deletes the given user if allowed.- #- # @return True if the project deletion has been initiated, false otherwise.- def call(delayed: true)- result, errors = validate_and_yield(project, user) { delete_or_schedule_deletion(delayed) }- ServiceResult.new(success: result, errors: errors)+ private++ def before_perform(*)+ OpenProject::Notifications.send('project_deletion_imminent', project: @project_to_destroy)++ delete_all_members+ destroy_all_work_packages++ superend- private+ # Deletes all project's members+ def delete_all_members+ MemberRole+ .includes(:member)+ .where(members: { project_id: model.id })+ .delete_all- def delete_or_schedule_deletion(delayed)- if delayed- # Archive the project- project.archive- Delayed::Job.enqueue DeleteProjectJob.new(user_id: user.id, project_id: project.id),- priority: ::ApplicationJob.priority_number(:low)- true- else- delete_project!- end+ Member.where(project_id: model.id).destroy_allend- def delete_project!- OpenProject::Notifications.send('project_deletion_imminent', project: @project_to_destroy)+ def destroy_all_work_packages+ model.work_packages.each do |wp|+ wp.reload+ wp.destroy+ rescue ActiveRecord::RecordNotFound+ # Everything fine, we wanted to delete it anyway+ end+ end- if project.destroy- ProjectMailer.delete_project_completed(project, user: user).deliver_now- true+ def notify(success)+ if success+ ProjectMailer.delete_project_completed(model, user: user).deliver_nowelse- ProjectMailer.delete_project_failed(project, user: user).deliver_now- false+ ProjectMailer.delete_project_failed(model, user: user).deliver_nowendendenddiff --git a/app/services/projects/schedule_deletion_service.rb b/app/services/projects/schedule_deletion_service.rbnew file mode 100644index 00000000000..a26a848cd7e--- /dev/null+++ b/app/services/projects/schedule_deletion_service.rb@@ -0,0 +1,58 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)+#+# 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-2017 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.+#++++##+# Schedules the deletion of a project if allowed. As the deletion can be+# a lengthy process, the project is archived first+#+module Projects+ class ScheduleDeletionService < ::BaseServices::BaseContracted+ attr_accessor :model++ def initialize(user:, model:, contract_class: ::Projects::DeleteContract)+ super(user: user, contract_class: contract_class)+ self.model = model+ end++ private++ def before_perform(_params)+ Projects::ArchiveService+ .new(user: user, model: model)+ .call+ end++ def persist(call)+ Delayed::Job.enqueue DeleteProjectJob.new(user_id: user.id, project_id: model.id),+ priority: ::ApplicationJob.priority_number(:low)+ call+ end+ end+enddiff --git a/app/services/projects/unarchive_service.rb b/app/services/projects/unarchive_service.rbnew file mode 100644index 00000000000..7edd0b0265b--- /dev/null+++ b/app/services/projects/unarchive_service.rb@@ -0,0 +1,55 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2019 the OpenProject Foundation (OPF)+#+# 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-2017 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 doc/COPYRIGHT.rdoc for more details.+#++++module Projects+ class UnarchiveService < ::BaseServices::BaseContracted+ include Concerns::Contracted++ def initialize(user:, model:, contract_class: Projects::UnarchiveContract)+ super(user: user, contract_class: contract_class)+ self.model = model+ end++ private++ attr_accessor :model++ def persist(service_call)+ activate_project(model)++ service_call+ end++ def activate_project(project)+ # we do not care for validations+ project.update_column(:status, Project::STATUS_ACTIVE)+ end+ end+enddiff --git a/app/services/projects/update_service.rb b/app/services/projects/update_service.rbindex 67b05ca63c7..ac4afbd4574 100644--- a/app/services/projects/update_service.rb+++ b/app/services/projects/update_service.rb@@ -44,11 +44,13 @@ module Projectsretend- def after_save(*)+ def after_perform(service_call)touch_on_custom_values_updatenotify_on_identifier_renamedsend_update_notificationupdate_wp_versions_on_parent_change++ service_callenddef touch_on_custom_values_updatediff --git a/app/services/roles/create_service.rb b/app/services/roles/create_service.rbindex b26ee135825..cf148429d77 100644--- a/app/services/roles/create_service.rb+++ b/app/services/roles/create_service.rb@@ -33,7 +33,7 @@ class Roles::CreateService < ::BaseServices::Createprivate- def write(params)+ def perform(params)copy_workflow_id = params.delete(:copy_workflow_from)super_call = superdiff --git a/app/services/versions/update_service.rb b/app/services/versions/update_service.rbindex 81be79cfcc4..2cf359999d6 100644--- a/app/services/versions/update_service.rb+++ b/app/services/versions/update_service.rb@@ -32,9 +32,10 @@ module Versionsclass UpdateService < ::BaseServices::Updateprivate- def after_save(*)+ def after_perform(service_call)model.touch if only_custom_values_updated?update_wps_from_sharing_change if model.saved_change_to_sharing?+ service_callend# Update the issue's fixed versions. Used if a version's sharing changes.diff --git a/app/services/work_packages/delete_service.rb b/app/services/work_packages/delete_service.rbindex 845e6cccfe6..75eb871a3d8 100644--- a/app/services/work_packages/delete_service.rb+++ b/app/services/work_packages/delete_service.rb@@ -31,32 +31,19 @@class WorkPackages::DeleteService < ::BaseServices::Deleteinclude ::WorkPackages::Shared::UpdateAncestors- def call- in_context(true) do- delete- end- end-private- def delete- result = ServiceResult.new success: false,- result: model-- WorkPackage.transaction do- descendants = model.descendants.to_a-- result = super+ def persist(service_result)+ descendants = model.descendants.to_a- if result.success?- update_ancestors_all_attributes(result.all_results).each do |ancestor_result|- result.merge!(ancestor_result)- end+ result = super- destroy_descendants(descendants, result)+ if result.success?+ update_ancestors_all_attributes(result.all_results).each do |ancestor_result|+ result.merge!(ancestor_result)end- result+ destroy_descendants(descendants, result)endresultdiff --git a/app/workers/projects/delete_project_job.rb b/app/workers/projects/delete_project_job.rbindex e79750a2d20..c4f96834c44 100644--- a/app/workers/projects/delete_project_job.rb+++ b/app/workers/projects/delete_project_job.rb@@ -41,18 +41,31 @@ module Projectsenddef perform- service = ::Projects::DeleteProjectService.new(user: user, project: project)- call = service.call(delayed: false)+ service_call = delete_project- if call.failure?- logger.error("Failed to delete project #{project} in background job: #{call.errors.join("\n")}")+ if service_call.failure?+ log_service_failure(service_call)endrescue StandardError => e+ log_standard_error(e)+ end++ private++ def delete_project+ ::Projects::DeleteService+ .new(user: user, model: project)+ .call+ end++ def log_standard_error(e)logger.error('Encountered an error when trying to delete project '\"'#{project_id}' : #{e.message} #{e.backtrace.join("\n")}")end- private+ def log_service_failure(service_call)+ logger.error("Failed to delete project #{project} in background job: #{service_call.errors.join("\n")}")+ enddef user@user ||= User.find user_iddiff --git a/config/locales/en.yml b/config/locales/en.ymlindex 38c3cec40c7..927eaf6f9e0 100644--- a/config/locales/en.yml+++ b/config/locales/en.yml@@ -552,6 +552,8 @@ en:invalid_values: "A value is invalid."id_filter_required: "An 'id' filter is required."project:+ archived_ancestor: 'The project has an archived ancestor.'+ foreign_wps_reference_version: 'Work packages in non descendant projects reference versions of the project or its descendants.'attributes:types:in_use_by_work_packages: "still in use by work packages: %{types}"@@ -1003,7 +1005,7 @@ en:enumeration_reported_project_statuses: "Reported project status"error_auth_source_sso_failed: "Single Sign-On (SSO) for user '%{value}' failed"- error_can_not_archive_project: "This project cannot be archived: There is at least one work package assigned to a version defined in this project."+ error_can_not_archive_project: "This project cannot be archived: %{errors}"error_can_not_delete_entry: "Unable to delete entry"error_can_not_delete_custom_field: "Unable to delete custom field"error_can_not_delete_type: "This type contains work packages and cannot be deleted."@@ -1012,6 +1014,7 @@ en:error_can_not_remove_role: "This role is in use and cannot be deleted."error_can_not_reopen_work_package_on_closed_version: "A work package assigned to a closed version cannot be reopened"error_can_not_find_all_resources: "Could not find all related resources to this request."+ error_can_not_unarchive_project: "This project cannot be unarchived: %{errors}"error_check_user_and_role: "Please choose a user and a role."error_code: "Error %{code}"error_cookie_missing: 'The OpenProject cookie is missing. Please ensure that cookies are enabled, as this application will not properly function without.'diff --git a/docs/api/apiv3/endpoints/projects.apib b/docs/api/apiv3/endpoints/projects.apibindex 9c00f13df4e..ac0091b9b1b 100644--- a/docs/api/apiv3/endpoints/projects.apib+++ b/docs/api/apiv3/endpoints/projects.apib@@ -2,10 +2,13 @@## Actions-| Link | Description | Condition |-|:--------------------------:|----------------------------------------------------------------------| --------------------------------- |-| createWorkPackage | Form endpoint that aids in preparing and creating a work package | **Permission**: add work packages |-| createWorkPackageImmediate | Directly creates a work package in the project | **Permission**: add work packages |+| Link | Description | Condition |+|:--------------------------: |----------------------------------------------------------------------| --------------------------------- |+| update | Form endpoint that aids in updating this projet | **Permission**: edit project |+| updateImmediately | Directly update this project | **Permission**: edit project |+| delete | Delete this project | **Permission**: admin |+| createWorkPackage | Form endpoint that aids in preparing and creating a work package | **Permission**: add work packages |+| createWorkPackageImmediately | Directly creates a work package in the project | **Permission**: add work packages |## Linked Properties@@ -17,7 +20,7 @@| versions | Versions available in this project | Collection | not null | READ | **Permission**: view work packages or manage versions || memberships | Memberships in the project | Collection | not null | READ | **Permission**: view members || workPackages | Work Packages of this project | Collection | not null | READ | |-| parent | Parent project of the project | Project | | READ/WRITE | **Permission** edit project+| parent | Parent project of the project | Project | | READ/WRITE | **Permission** edit project |Depending on custom fields defined for projects, additional links might exist.@@ -208,6 +211,68 @@ Updates the given project by applying the attributes provided in the body.}}+## Delete Project [DELETE]++Deletes the project permanently. As this is a lengthy process, the actual deletion is carried out asynchronously.+So the project might exist well after the request has returned successfully. To prevent unwanted changes to+the project scheduled for deletion, it is archived at once.+++ Parameters+ + id (required, integer, `1`) ... Project id+++ Response 204 (application/hal+json)++ Returned if the project was successfully deleted. There is currently no end point to query for the actual deletion status.+ Such an end point _might_ be added in the future.++ + Body+++ Response 403 (application/hal+json)++ Returned if the client does not have sufficient permissions.++ **Required permission:** admin++ + 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 project does not exist or the client does not have sufficient permissions+ to see it.++ **Required permission:** view project++ *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 the project cannot be deleted. This can happen when there are still references to the project in other projects+ that need to be severed at first.++ + Body++ {+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:PropertyConstraintViolation",+ "message": "Work packages in non descendant projects reference versions of the project or its descendants.",+ "_embedded": { "details": { "attribute": "base" } }+ }+## Projects [/api/v3/projects{?filters,sortBy}]+ Modeldiff --git a/lib/api/v3/projects/project_representer.rb b/lib/api/v3/projects/project_representer.rbindex d6b757c6deb..d3a9efe26ee 100644--- a/lib/api/v3/projects/project_representer.rb+++ b/lib/api/v3/projects/project_representer.rb@@ -50,7 +50,7 @@ module API}end- link :createWorkPackageImmediate,+ link :createWorkPackageImmediately,cache_if: -> { current_user_allowed_to(:add_work_packages, context: represented) } do{href: api_v3_paths.work_packages_by_project(represented.id),@@ -94,6 +94,34 @@ module API{ href: api_v3_paths.types_by_project(represented.id) }end+ link :update,+ cache_if: -> {+ current_user_allowed_to(:edit_project, context: represented)+ } do+ {+ href: api_v3_paths.project_form(represented.id),+ method: :post+ }+ end++ link :updateImmediately,+ cache_if: -> {+ current_user_allowed_to(:edit_project, context: represented)+ } do+ {+ href: api_v3_paths.project(represented.id),+ method: :patch+ }+ end++ link :delete,+ cache_if: -> { current_user.admin? } do+ {+ href: api_v3_paths.project(represented.id),+ method: :delete+ }+ end+associated_resource :parent,v3_path: :project,representer: ::API::V3::Projects::ProjectRepresenter,diff --git a/lib/api/v3/projects/projects_api.rb b/lib/api/v3/projects/projects_api.rbindex e3518f10049..55128ddfac2 100644--- a/lib/api/v3/projects/projects_api.rb+++ b/lib/api/v3/projects/projects_api.rb@@ -26,8 +26,6 @@# See docs/COPYRIGHT.rdoc for more details.#++-require 'api/v3/projects/project_representer'-module APImodule V3module Projects@@ -59,6 +57,9 @@ module APIget &::API::V3::Utilities::Endpoints::Show.new(model: Project).mountpatch &::API::V3::Utilities::Endpoints::Update.new(model: Project).mount+ delete &::API::V3::Utilities::Endpoints::Delete.new(model: Project,+ process_service: ::Projects::ScheduleDeletionService)+ .mountmount ::API::V3::Projects::UpdateFormAPIdiff --git a/modules/grids/app/services/grids/update_service.rb b/modules/grids/app/services/grids/update_service.rbindex b82d256c3f6..a62e5991f5d 100644--- a/modules/grids/app/services/grids/update_service.rb+++ b/modules/grids/app/services/grids/update_service.rb@@ -31,14 +31,16 @@class Grids::UpdateService < ::BaseServices::Updateprotected- def write(attributes)+ def perform(attributes)set_type_for_error_message(attributes.delete(:scope))superend- def after_save(*)+ def after_perform(service_call)model.touch if only_widgets_updated?++ superenddef only_widgets_updated?diff --git a/spec/contracts/projects/archive_contract_spec.rb b/spec/contracts/projects/archive_contract_spec.rbnew file mode 100644index 00000000000..2d06a4a4e7c--- /dev/null+++ b/spec/contracts/projects/archive_contract_spec.rb@@ -0,0 +1,62 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)+#+# 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-2017 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 Projects::ArchiveContract do+ let(:project) { FactoryBot.build_stubbed(:project) }++ subject(:contract) { described_class.new(project, current_user) }++ def expect_valid(valid, symbols = {})+ expect(contract.validate).to eq(valid)++ symbols.each do |key, arr|+ expect(contract.errors.symbols_for(key)).to match_array arr+ end+ end++ context 'when user is admin' do+ let(:current_user) { FactoryBot.build_stubbed :admin }++ it 'is valid' do+ expect_valid(true)+ end+ end++ context 'when user is not admin' do+ let(:current_user) { FactoryBot.build_stubbed :user }+ let(:permissions) { [] }++ it 'is invalid' do+ expect_valid(false, base: %i(error_unauthorized))+ end+ end+enddiff --git a/spec/contracts/projects/unarchive_contract_spec.rb b/spec/contracts/projects/unarchive_contract_spec.rbnew file mode 100644index 00000000000..eb57bfc439a--- /dev/null+++ b/spec/contracts/projects/unarchive_contract_spec.rb@@ -0,0 +1,62 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)+#+# 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-2017 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 Projects::UnarchiveContract do+ let(:project) { FactoryBot.build_stubbed(:project) }++ subject(:contract) { described_class.new(project, current_user) }++ def expect_valid(valid, symbols = {})+ expect(contract.validate).to eq(valid)++ symbols.each do |key, arr|+ expect(contract.errors.symbols_for(key)).to match_array arr+ end+ end++ context 'when user is admin' do+ let(:current_user) { FactoryBot.build_stubbed :admin }++ it 'is valid' do+ expect_valid(true)+ end+ end++ context 'when user is not admin' do+ let(:current_user) { FactoryBot.build_stubbed :user }+ let(:permissions) { [] }++ it 'is invalid' do+ expect_valid(false, base: %i(error_unauthorized))+ end+ end+enddiff --git a/spec/controllers/projects_controller_spec.rb b/spec/controllers/projects_controller_spec.rbindex 6bb74238cf4..a554b192bf1 100644--- a/spec/controllers/projects_controller_spec.rb+++ b/spec/controllers/projects_controller_spec.rb@@ -181,9 +181,8 @@ describe ProjectsController, type: :controller dobefore doallow(Project).to receive(:find).and_return(project)- expect_any_instance_of(::Projects::DeleteProjectService)+ expect_any_instance_of(::Projects::ScheduleDeletionService).to receive(:call)- .with(delayed: true).and_return service_resultenddiff --git a/spec/lib/api/v3/projects/project_representer_spec.rb b/spec/lib/api/v3/projects/project_representer_spec.rbindex 8a070aaa5f2..b087e0e0bbe 100644--- a/spec/lib/api/v3/projects/project_representer_spec.rb+++ b/spec/lib/api/v3/projects/project_representer_spec.rb@@ -169,7 +169,7 @@ describe ::API::V3::Projects::ProjectRepresenter doit 'has the correct path to create a work package' dois_expected.to be_json_eql(api_v3_paths.work_packages_by_project(project.id).to_json)- .at_path('_links/createWorkPackageImmediate/href')+ .at_path('_links/createWorkPackageImmediately/href')endend@@ -181,7 +181,7 @@ describe ::API::V3::Projects::ProjectRepresenter doendit_behaves_like 'has no link' do- let(:link) { 'createWorkPackageImmediate' }+ let(:link) { 'createWorkPackageImmediately' }endendend@@ -334,6 +334,67 @@ describe ::API::V3::Projects::ProjectRepresenter doendendend++ describe 'update' do+ context 'for a user having the edit_project permission' do+ let(:permissions) { [:edit_project] }++ it_behaves_like 'has an untitled link' do+ let(:link) { 'update' }+ let(:href) { api_v3_paths.project_form project.id }+ end+ end++ context 'for a user lacking the edit_project permission' do+ let(:permissions) { [] }++ it_behaves_like 'has no link' do+ let(:link) { 'update' }+ end+ end+ end++ describe 'updateImmediately' do+ context 'for a user having the edit_project permission' do+ let(:permissions) { [:edit_project] }++ it_behaves_like 'has an untitled link' do+ let(:link) { 'updateImmediately' }+ let(:href) { api_v3_paths.project project.id }+ end+ end++ context 'for a user lacking the edit_project permission' do+ let(:permissions) { [] }++ it_behaves_like 'has no link' do+ let(:link) { 'updateImmediately' }+ end+ end+ end++ describe 'delete' do+ context 'for a user being admin' do+ before do+ allow(user)+ .to receive(:admin?)+ .and_return(true)+ end++ it_behaves_like 'has an untitled link' do+ let(:link) { 'delete' }+ let(:href) { api_v3_paths.project project.id }+ end+ end++ context 'for a non admin user' do+ let(:permissions) { [] }++ it_behaves_like 'has no link' do+ let(:link) { 'delete' }+ end+ end+ endenddescribe 'caching' dodiff --git a/spec/models/project_spec.rb b/spec/models/project_spec.rbindex 8cd441d754a..589ca4a4e0f 100644--- a/spec/models/project_spec.rb+++ b/spec/models/project_spec.rb@@ -204,7 +204,7 @@ describe Project, type: :model doit 'should only check active projects' dosubproject = FactoryBot.create(:project, parent: project)FactoryBot.create(:version, project: subproject)- subproject.archive+ subproject.archived!project.reloaddiff --git a/spec/requests/api/v3/project_resource_spec.rb b/spec/requests/api/v3/project_resource_spec.rbindex 205a1d58767..4bf3e67ad70 100644--- a/spec/requests/api/v3/project_resource_spec.rb+++ b/spec/requests/api/v3/project_resource_spec.rb@@ -447,4 +447,108 @@ describe 'API v3 Project resource', type: :request, content_type: :json doendendend++ describe '#delete /api/v3/projects/:id' do+ let(:path) { api_v3_paths.project(project.id) }+ let(:setup) { }++ before do+ login_as current_user++ setup++ delete path+ end++ subject { last_response }++ context 'with required permissions (admin)' do+ let(:current_user) { FactoryBot.create(:admin) }++ it 'responds with HTTP No Content' do+ expect(subject.status).to eq 204+ end++ it 'deletes the project' do+ expect(Project.exists?(project.id)).to be_falsey+ end++ context 'for a project with work packages' do+ let(:work_package) { FactoryBot.create(:work_package, project: project) }+ let(:setup) { work_package }++ it 'deletes the work packages' do+ expect(WorkPackage.exists?(work_package.id)).to be_falsey+ end+ end++ context 'for a project with members' do+ let(:member) do+ FactoryBot.create(:member,+ project: project,+ principal: current_user,+ roles: [FactoryBot.create(:role)])+ end+ let(:member_role) { member.member_roles.first }+ let(:setup) do+ member+ member_role+ end++ it 'deletes the member' do+ expect(Member.exists?(member.id)).to be_falsey+ end++ it 'deletes the MemberRole' do+ expect(MemberRole.exists?(member_role.id)).to be_falsey+ end+ end++ context 'for a project with a forum' do+ let(:forum) do+ FactoryBot.create(:forum,+ project: project)+ end+ let(:setup) do+ forum+ end++ it 'deletes the forum' do+ expect(Forum.exists?(forum.id)).to be_falsey+ end+ end++ context 'for a non-existent project' do+ let(:path) { api_v3_paths.project 0 }++ it_behaves_like 'not found' do+ let(:id) { 0 }+ let(:type) { 'Project' }+ end+ end++ context 'for a project which has a version foreign work packages refer to' do+ let(:version) { FactoryBot.create(:version, project: project) }+ let(:work_package) { FactoryBot.create(:work_package, fixed_version: version) }++ let(:setup) { work_package }++ it 'responds with 422' do+ expect(subject.status).to eq 422+ end++ it 'explains the error' do+ expect(subject.body)+ .to be_json_eql(I18n.t(:'activerecord.errors.models.project.foreign_wps_reference_version').to_json)+ .at_path('message')+ end+ end+ end++ context 'without required permissions' do+ it 'responds with 403' do+ expect(subject.status).to eq 403+ end+ end+ endenddiff --git a/spec/services/projects/delete_service_spec.rb b/spec/services/projects/delete_service_spec.rbindex 07312de1efa..eb4f731ed92 100644--- a/spec/services/projects/delete_service_spec.rb+++ b/spec/services/projects/delete_service_spec.rb@@ -28,82 +28,49 @@require 'spec_helper'-describe ::Projects::DeleteProjectService, type: :model do+describe ::Projects::DeleteService, type: :model dolet(:user) { FactoryBot.build_stubbed(:admin) }let(:project) { FactoryBot.build_stubbed(:project) }- let(:instance) { described_class.new(user: user, project: project) }- let(:params) { }+ let(:instance) { described_class.new(user: user, model: project) }- subject { instance.call(params) }+ subject { instance.call }- context 'when delayed' do- let(:params) { { delayed: true } }+ context 'if authorized' do+ it 'destroys the project and sends a success mail' do+ expect(project).not_to receive(:archive)+ expect(project).to receive(:destroy).and_return true- context 'when authorized' do- it 'archives the project and creates a delayed job' do- expect(project).to receive(:archive)-- expect(::Projects::DeleteProjectJob)- .to receive(:new)- .with(user_id: user.id, project_id: project.id)- .and_call_original+ expect(ProjectMailer)+ .to receive_message_chain(:delete_project_completed, :deliver_now)- expect(subject).to be_success- end- end-- context 'when not authorized' do- let(:user) { FactoryBot.build_stubbed(:user) }-- it 'returns an error' do- expect(::Projects::DeleteProjectJob)- .not_to receive(:new)+ expect(::Projects::DeleteProjectJob)+ .not_to receive(:new)- expect(subject).to be_failure- end+ expect(subject).to be_successend- end-- context 'when not delayed' do- let(:params) { { delayed: false } }- context 'when authorized' do- it 'destroys the project and sends a success mail' do- expect(project).not_to receive(:archive)- expect(project).to receive(:destroy).and_return true+ it 'sends a message on destroy failure' do+ expect(project).to receive(:destroy).and_return false- expect(ProjectMailer)- .to receive_message_chain(:delete_project_completed, :deliver_now)+ expect(ProjectMailer)+ .to receive_message_chain(:delete_project_failed, :deliver_now)- expect(::Projects::DeleteProjectJob)- .not_to receive(:new)+ expect(::Projects::DeleteProjectJob)+ .not_to receive(:new)- expect(subject).to be_success- end-- it 'sends a message on destroy failure' do- expect(project).to receive(:destroy).and_return false-- expect(ProjectMailer)- .to receive_message_chain(:delete_project_failed, :deliver_now)-- expect(::Projects::DeleteProjectJob)- .not_to receive(:new)-- expect(subject).to be_failure- end+ expect(subject).to be_failureend+ end- context 'when not authorized' do- let(:user) { FactoryBot.build_stubbed(:user) }+ context 'if not authorized' do+ let(:user) { FactoryBot.build_stubbed(:user) }- it 'returns an error' do- expect(::Projects::DeleteProjectJob)- .not_to receive(:new)+ it 'returns an error' do+ expect(::Projects::DeleteProjectJob)+ .not_to receive(:new)- expect(subject).to be_failure- end+ expect(subject).to be_failureendendenddiff --git a/spec/services/projects/schedule_deletion_service_spec.rb b/spec/services/projects/schedule_deletion_service_spec.rbnew file mode 100644index 00000000000..eacc00ecc99--- /dev/null+++ b/spec/services/projects/schedule_deletion_service_spec.rb@@ -0,0 +1,146 @@+#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2017 the OpenProject Foundation (OPF)+#+# 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-2017 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 doc/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'++describe ::Projects::ScheduleDeletionService, type: :model do+ let(:contract_class) do+ contract = double('contract_class', '<=': true)++ allow(contract)+ .to receive(:new)+ .with(project, user)+ .and_return(contract_instance)++ contract+ end+ let(:contract_instance) do+ double('contract_instance', validate: contract_valid, errors: contract_errors)+ end+ let(:contract_valid) { true }+ let(:contract_errors) do+ double('contract_errors')+ end+ let(:project_valid) { true }+ let(:project) { FactoryBot.build_stubbed(:project) }+ let(:instance) do+ described_class.new(user: user,+ model: project,+ contract_class: contract_class)+ end+ let(:archive_success) do+ true+ end+ let(:archive_errors) do+ double('archive_errors')+ end+ let(:archive_result) do+ ServiceResult.new result: project,+ success: archive_success,+ errors: archive_errors+ end+ let!(:archive_service) do+ service = double('archive_service_instance')++ allow(Projects::ArchiveService)+ .to receive(:new)+ .with(user: user,+ model: project)+ .and_return(service)++ allow(service)+ .to receive(:call)+ .and_return(archive_result)++ service+ end+ let(:user) { FactoryBot.build_stubbed(:admin) }++ subject { instance.call }++ context 'if contract and archiving are successful' do+ it 'archives the project and creates a delayed job' do+ expect(archive_service)+ .to receive(:call)+ .and_return(archive_result)++ job = double 'job'++ expect(::Projects::DeleteProjectJob)+ .to receive(:new)+ .with(user_id: user.id, project_id: project.id)+ .and_return(job)++ expect(Delayed::Job)+ .to receive(:enqueue)+ .with(job, anything)++ expect(subject).to be_success+ end+ end++ context 'if contract fails' do+ let(:contract_valid) { false }++ it 'is failure' do+ expect(subject).to be_failure+ end++ it 'returns the contract errors' do+ expect(subject.errors)+ .to eql contract_errors+ end++ it 'does not schedule a job' do+ expect(::Projects::DeleteProjectJob)+ .not_to receive(:new)++ subject+ end+ end++ context 'if archiving fails' do+ let(:archive_success) { false }++ it 'is failure' do+ expect(subject).to be_failure+ end++ it 'returns the contract errors' do+ expect(subject.errors)+ .to eql archive_errors+ end++ it 'does not schedule a job' do+ expect(::Projects::DeleteProjectJob)+ .not_to receive(:new)++ subject+ end+ end+enddiff --git a/spec_legacy/functional/projects_controller_spec.rb b/spec_legacy/functional/projects_controller_spec.rbindex 9003a940cf1..3c2daadf979 100644--- a/spec_legacy/functional/projects_controller_spec.rb+++ b/spec_legacy/functional/projects_controller_spec.rb@@ -372,7 +372,7 @@ describe ProjectsController, type: :controller doit 'should unarchive' dosession[:user_id] = 1 # admin- Project.find(1).archive+ Project.find(1).archived!put :unarchive, params: { id: 1 }assert_redirected_to '/projects'assert Project.find(1).active?diff --git a/spec_legacy/unit/project_spec.rb b/spec_legacy/unit/project_spec.rbindex 4b9f4ddbfb8..0902204ffed 100644--- a/spec_legacy/unit/project_spec.rb+++ b/spec_legacy/unit/project_spec.rb@@ -98,7 +98,7 @@ describe Project, type: :model doit 'should members should be active users' doProject.all.each do |project|- assert_nil project.members.detect { |m| !(m.user.is_a?(User) && m.user.active?) }+ assert_nil project.members.detect { |m| !(m.principal.is_a?(User) && m.principal.active?) }endend@@ -108,98 +108,6 @@ describe Project, type: :model doendend- it 'should archive' do- user = @ecookbook.members.first.user- @ecookbook.archive- @ecookbook.reload-- assert [email protected]?- assert @ecookbook.archived?- assert !user.projects.include?(@ecookbook)- # Subproject are also archived- assert [email protected]?- assert @ecookbook.descendants.active.empty?- end-- it 'should archive should fail if versions are used by non descendant projects' do- # Assign an issue of a project to a version of a child project- WorkPackage.find(4).update_attribute :fixed_version_id, 4-- assert_no_difference "Project.where('status = #{Project::STATUS_ARCHIVED}').count" do- assert_equal false, @ecookbook.archive- end- @ecookbook.reload- assert @ecookbook.active?- end-- it 'should unarchive' do- user = @ecookbook.members.first.user- @ecookbook.archive- # A subproject of an archived project can not be unarchived- assert !@ecookbook_sub1.unarchive-- # Unarchive project- assert @ecookbook.unarchive- @ecookbook.reload- assert @ecookbook.active?- assert [email protected]?- assert user.projects.include?(@ecookbook)- # Subproject can now be unarchived- @ecookbook_sub1.reload- assert @ecookbook_sub1.unarchive- end-- # fails because @ecookbook.issues[5 und 6].destroy fails- # because ActiveRecord::StaleObjectError- it 'should destroy' do- # 2 active members- assert_equal 2, @ecookbook.members.size- # and 1 is locked- assert_equal 3, Member.where(['project_id = ?', @ecookbook.id]).size- # some forums- assert @ecookbook.forums.any?-- @ecookbook.destroy- # make sure that the project non longer exists- assert_raises(ActiveRecord::RecordNotFound) do Project.find(@ecookbook.id) end- # make sure related data was removed- assert_equal 0, Member.where(project_id: @ecookbook.id).count- assert_equal 0, Forum.where(project_id: @ecookbook.id).count- assert_equal 0, WorkPackage.where(project_id: @ecookbook.id).count- end-- it 'should destroying root projects should clear data' do- Journal.destroy_all- WorkPackage.all.each(&:recreate_initial_journal!)-- Project.roots.each(&:destroy)-- assert_equal 0, Project.count, "Projects were not deleted: #{Project.all.inspect}"- assert_equal 0, Member.count, "Members were not deleted: #{Member.all.inspect}"- assert_equal 0, MemberRole.count- assert_equal 0, WorkPackage.count- assert_equal 0, Journal.count, "Journals were not deleted: #{Journal.all.inspect}"- assert_equal 0, EnabledModule.count- assert_equal 0, Category.count- assert_equal 0, Relation.count- assert_equal 0, Forum.count- assert_equal 0, Message.count- assert_equal 0, News.count- assert_equal 0, Query.where('project_id IS NOT NULL').count- assert_equal 0, Repository.count- assert_equal 0, Changeset.count- assert_equal 0, Change.count- assert_equal 0, Comment.count- assert_equal 0, TimeEntry.count- assert_equal 0, Version.count- assert_equal 0, Watcher.count- assert_equal 0, Wiki.count- assert_equal 0, WikiPage.count- assert_equal 0, WikiContent.count- assert_equal 0, Project.connection.select_all('SELECT * FROM custom_fields_projects').to_a.size- assert_equal 0, CustomValue.where(customized_type: ['Project', 'Issue', 'TimeEntry', 'Version']).count- end-it 'should parent' dop = Project.find(6).parentassert p.is_a?(Project)@@ -258,7 +166,10 @@ describe Project, type: :model doparent.types = ::Type.find([1, 2])child = parent.children.find(3)child.types = ::Type.find([1, 3])- parent.children.each(&:archive)+ parent.children.each do |child|+ child.archived!+ child.children.each(&:archived!)+ endassert_equal [1, 2], parent.rolled_up_types.map(&:id)end@@ -334,7 +245,7 @@ describe Project, type: :model doit 'should shared versions should ignore archived subprojects' doparent = Project.find(1)child = parent.children.find(3)- child.archive+ child.archived!parent.reloadassert_equal [1, 2, 3], parent.version_ids.sort