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
Updates the CopyJob and tests to rely on GoodJob::Batch
Marcello Rocha3e32aa880e7e
diff --git a/app/services/projects/enqueue_copy_service.rb b/app/services/projects/enqueue_copy_service.rbindex 7fc088d4027..705e0c7f724 100644--- a/app/services/projects/enqueue_copy_service.rb+++ b/app/services/projects/enqueue_copy_service.rb@@ -60,11 +60,15 @@ module Projects### Schedule the project copy jobdef schedule_copy_job(params)- CopyProjectJob.perform_later(user_id: user.id,- source_project_id: source.id,- target_project_params: params[:target_project_params],- associations_to_copy: params[:only].to_a,- send_mails: ActiveRecord::Type::Boolean.new.cast(params[:send_notifications]))+ job = nil+ GoodJob::Batch.enqueue(user:) do+ job = CopyProjectJob.perform_later(user_id: user.id,+ source_project_id: source.id,+ target_project_params: params[:target_project_params],+ associations_to_copy: params[:only].to_a,+ send_mails: ActiveRecord::Type::Boolean.new.cast(params[:send_notifications]))+ end+ jobendendenddiff --git a/app/workers/copy_project_job.rb b/app/workers/copy_project_job.rbindex b983393537d..cefe8158fab 100644--- a/app/workers/copy_project_job.rb+++ b/app/workers/copy_project_job.rb@@ -29,15 +29,19 @@class CopyProjectJob < ApplicationJobqueue_with_priority :above_normalinclude OpenProject::LocaleHelper+ include GoodJob::ActiveJobExtensions::Batches- attr_reader :user_id,- :source_project_id,- :target_project_params,- :target_project_name,- :target_project,- :errors,- :associations_to_copy,- :send_mails+ queue_with_priority :above_normal++ attr_reader :errors, :target_project, :target_project_params++ # attr_reader :source_project_id,+ # :target_project_params,+ # :target_project_name,+ # :target_project,+ # :errors,+ # :associations_to_copy,+ # :send_mailsdef perform(user_id:,source_project_id:,@@ -46,11 +50,10 @@ class CopyProjectJob < ApplicationJobsend_mails: false)# Needs refactoring after moving to activejob- @user_id = user_id- @source_project_id = source_project_id+ @source_project_id = source_project_id@target_project_params = target_project_params.with_indifferent_access- @associations_to_copy = associations_to_copy- @send_mails = send_mails+ @associations_to_copy = associations_to_copy+ @send_mails = send_mailsUser.current = user@target_project_name = target_project_params[:name]@@ -59,18 +62,21 @@ class CopyProjectJob < ApplicationJobcreate_project_copyend+ batch.properties.merge!(target_project:, errors:)+ batch.save+if target_projectsuccessful_status_updateProjectMailer.copy_project_succeeded(user, source_project, target_project, errors).deliver_laterelsefailure_status_update- ProjectMailer.copy_project_failed(user, source_project, target_project_name, errors).deliver_later+ ProjectMailer.copy_project_failed(user, source_project, @target_project_name, errors).deliver_laterendrescue StandardError => elogger.error { "Failed to finish copy project job: #{e} #{e.message}" }errors = [I18n.t("copy_project.failed_internal")]failure_status_update- ProjectMailer.copy_project_failed(user, source_project, target_project_name, errors).deliver_later+ ProjectMailer.copy_project_failed(user, source_project, @target_project_name, errors).deliver_laterenddef store_status?@@ -124,17 +130,17 @@ class CopyProjectJob < ApplicationJobenddef user- @user ||= User.find user_id+ @user ||= batch.properties[:user]enddef source_project- @source_project ||= Project.find source_project_id+ @source_project ||= Project.find @source_project_idenddef create_project_copyerrors = []- ProjectMailer.with_deliveries(send_mails) do+ ProjectMailer.with_deliveries(@send_mails) doservice_call = copy_projecttarget_project = service_call.resulterrors = service_call.errors.full_messages@@ -149,13 +155,15 @@ class CopyProjectJob < ApplicationJobendrescue ActiveRecord::RecordNotFound => elogger.error("Entity missing: #{e.message} #{e.backtrace.join("\n")}")+ raise erescue StandardError => elogger.error("Encountered an error when trying to copy project " \- "'#{source_project_id}' : #{e.message} #{e.backtrace.join("\n")}")+ "'#{@source_project_id}' : #{e.message} #{e.backtrace.join("\n")}")+ raise eensureunless errors.empty?logger.error("Encountered an errors while trying to copy related objects for " \- "project '#{source_project_id}': #{errors.inspect}")+ "project '#{@source_project_id}': #{errors.inspect}")endend@@ -166,8 +174,8 @@ class CopyProjectJob < ApplicationJobenddef copy_project_params- params = { target_project_params:, send_notifications: send_mails }- params[:only] = associations_to_copy if associations_to_copy.present?+ params = { target_project_params:, send_notifications: @send_mails }+ params[:only] = @associations_to_copy if @associations_to_copy.present?paramsenddiff --git a/spec/requests/api/v3/projects/copy/copy_resource_spec.rb b/spec/requests/api/v3/projects/copy/copy_resource_spec.rbindex 388df496080..37ab48d5b10 100644--- a/spec/requests/api/v3/projects/copy/copy_resource_spec.rb+++ b/spec/requests/api/v3/projects/copy/copy_resource_spec.rb@@ -1,3 +1,5 @@+# frozen_string_literal: true+#-- copyright# OpenProject is an open source project management software.# Copyright (C) 2012-2024 the OpenProject GmbH@@ -28,7 +30,7 @@require "spec_helper"require "rack/test"-RSpec.describe API::V3::Projects::Copy::CopyAPI, content_type: :json do+RSpec.describe "API::V3::Projects::Copy::CopyAPI", content_type: :json, with_good_job_batches: [CopyProjectJob] doinclude Rack::Test::Methodsinclude API::V3::Utilities::PathHelper@@ -69,6 +71,8 @@ RSpec.describe API::V3::Projects::Copy::CopyAPI, content_type: :json dosubject(:response) { last_response }+ # rubocop:disable RSpec/Rails/HaveHttpStatus+ # those are mock responses that don't deal well with the rails helpersdescribe "#POST /api/v3/projects/:id/copy" dodescribe "with empty params" doit "returns 422", :aggregate_failures do@@ -104,17 +108,17 @@ RSpec.describe API::V3::Projects::Copy::CopyAPI, content_type: :json doget response.location- expect(last_response.status).to eq 200+ expect(last_response.status).to eq(200)expect(last_response.body).to be_json_eql("in_queue".to_json).at_path("status")- perform_enqueued_jobs+ GoodJob.perform_inlineget response.location- expect(last_response.status).to eq 200+ expect(last_response.status).to eq(200)expect(last_response.body).to be_json_eql("success".to_json)@@ -143,7 +147,7 @@ RSpec.describe API::V3::Projects::Copy::CopyAPI, content_type: :json doendit "does not copy the wiki" do- perform_enqueued_jobs+ GoodJob.perform_inlineproject = Project.find_by(identifier: "my-copied-project")expect(project).to be_present@@ -169,10 +173,10 @@ RSpec.describe API::V3::Projects::Copy::CopyAPI, content_type: :json dolet(:sendNotifications) { false }it "queues the job without notifications" do- expect(CopyProjectJob)- .to have_been_enqueued.with do |args|- expect(args[:send_mails]).to be false- end+ job = GoodJob::Job.where(job_class: "CopyProjectJob").last+ enqueue_params = job.serialized_params["arguments"][0]++ expect(enqueue_params["send_mails"]).to be_falseyendend@@ -180,10 +184,10 @@ RSpec.describe API::V3::Projects::Copy::CopyAPI, content_type: :json dolet(:sendNotifications) { true }it "queues the job with notifications" do- expect(CopyProjectJob)- .to have_been_enqueued.with do |args|- expect(args[:send_mails]).to be true- end+ job = GoodJob::Job.where(job_class: "CopyProjectJob").last+ enqueue_params = job.serialized_params["arguments"][0]++ expect(enqueue_params["send_mails"]).to be_truthyendendend@@ -199,4 +203,5 @@ RSpec.describe API::V3::Projects::Copy::CopyAPI, content_type: :json doendendend+ # rubocop:enable RSpec/Rails/HaveHttpStatusenddiff --git a/spec/workers/copy_project_job_spec.rb b/spec/workers/copy_project_job_spec.rbindex 16673761b35..1f2308e4e27 100644--- a/spec/workers/copy_project_job_spec.rb+++ b/spec/workers/copy_project_job_spec.rb@@ -28,50 +28,24 @@require "spec_helper"-RSpec.describe CopyProjectJob, type: :model do+RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectJob] dolet(:params) { { name: "Copy", identifier: "copy" } }- let(:maildouble) { double("Mail::Message", deliver: true) }+ let(:user_de) { create(:admin, language: :de) }+ let(:mail_double) { double("Mail::Message", deliver: true) } # rubocop:disable RSpec/VerifiedDoubles- before do- allow(maildouble).to receive(:deliver_later)- end-- describe "copy localizes error message" do- let(:user_de) { create(:admin, language: :de) }- let(:source_project) { create(:project) }- let(:target_project) { create(:project) }-- let(:copy_job) do- described_class.new- end-- it "sets locale correctly" do- expect(copy_job)- .to receive(:create_project_copy)- .and_wrap_original do |m, *args, &block|- expect(I18n.locale).to eq(:de)- m.call(*args, &block)- end-- copy_job.perform user_id: user_de.id,- source_project_id: source_project.id,- target_project_params: {},- associations_to_copy: []- end- end+ before { allow(mail_double).to receive(:deliver_later) }describe "copy project succeeds with errors" dolet(:admin) { create(:admin) }let(:source_project) { create(:project, types: [type]) }+let!(:work_package) { create(:work_package, project: source_project, type:) }+let(:type) { create(:type_bug) }let(:custom_field) do- create(:work_package_custom_field,- name: "required_field",- field_format: "text",- is_required: true,- is_for_all: true)+ create(:work_package_custom_field, name: "required_field", field_format: "text", is_required: true, is_for_all: true)end+let(:job_args) do{user_id: admin.id,@@ -80,40 +54,50 @@ RSpec.describe CopyProjectJob, type: :model doassociations_to_copy: [:work_packages]}end- let(:copy_job) do- described_class.new(**job_args).tap(&:perform_now)- endlet(:params) { { name: "Copy", identifier: "copy", type_ids: [type.id], work_package_custom_field_ids: [custom_field.id] } }let(:expected_error_message) do"#{WorkPackage.model_name.human} '#{work_package.type.name} ##{work_package.id}: #{work_package.subject}': #{custom_field.name} #{I18n.t('errors.messages.blank')}."end- # rubocop:disable RSpec/InstanceVariablebefore dosource_project.work_package_custom_fields << custom_fieldtype.custom_fields << custom_field-- allow(User).to receive(:current).and_return(admin)-- @copied_project = copy_job.target_project- @errors = copy_job.errorsendit "copies the project", :aggregate_failures do- expect(Project.find_by(identifier: params[:identifier])).to eq(@copied_project)- expect(@errors.first).to eq(expected_error_message)+ copy_job = nil+ batch = GoodJob::Batch.enqueue(user: admin) do+ copy_job = described_class.perform_later(**job_args)+ end+ GoodJob.perform_inline+ batch.reload++ copied_project = Project.find_by(identifier: params[:identifier])++ expect(copied_project).to eq(batch.properties[:target_project])+ expect(batch.properties[:errors].first).to eq(expected_error_message)# expect to create a statusexpect(copy_job.job_status).to be_presentexpect(copy_job.job_status[:status]).to eq "success"expect(copy_job.job_status[:payload]["redirect"]).to include "/projects/copy"- expected_link = { "href" => "/api/v3/projects/#{@copied_project.id}", "title" => @copied_project.name }+ expected_link = { "href" => "/api/v3/projects/#{copied_project.id}", "title" => copied_project.name }expect(copy_job.job_status[:payload]["_links"]["project"]).to eq(expected_link)end++ it "ensures that error messages are correctly localized" do+ batch = GoodJob::Batch.enqueue(user: user_de) do+ described_class.perform_later(**job_args)+ end+ GoodJob.perform_inline+ batch.reload++ msg = /Arbeitspaket 'Bug #\d+: WorkPackage No. \d+': required_field muss ausgefüllt werden\./+ expect(batch.properties[:errors].first).to match(msg)+ endend- # rubocop:enable RSpec/InstanceVariabledescribe "project has an invalid repository" dolet(:admin) { create(:admin) }@@ -143,8 +127,18 @@ RSpec.describe CopyProjectJob, type: :model doit "saves without the repository" doexpect(source_project).not_to be_valid- copied_project = copy_job.target_project- errors = copy_job.errors+ batch = GoodJob::Batch.enqueue(user: admin) do+ described_class.perform_later(user_id: nil,+ source_project_id: source_project.id,+ target_project_params: params,+ associations_to_copy: [:work_packages])+ end++ GoodJob.perform_inline+ batch.reload++ copied_project = batch.properties[:target_project]+ errors = batch.properties[:errors]expect(errors).to be_emptyexpect(copied_project).to be_valid@@ -156,15 +150,6 @@ RSpec.describe CopyProjectJob, type: :model dodescribe "copy project fails with internal error" dolet(:admin) { create(:admin) }let(:source_project) { create(:project) }- let(:copy_job) do- described_class.new.tap do |job|- job.perform user_id: admin.id,- source_project_id: source_project.id,- target_project_params: params,- associations_to_copy: [:work_packages]- end- end-let(:params) { { name: "Copy", identifier: "copy" } }before do@@ -173,12 +158,20 @@ RSpec.describe CopyProjectJob, type: :model doendit "renders a error when unexpected errors occur" do+ copy_job = nil+ GoodJob::Batch.enqueue(user: admin) do+ copy_job = described_class.perform_later(user_id: admin.id,+ source_project_id: source_project.id,+ target_project_params: params,+ associations_to_copy: [:work_packages])+ end+expect(ProjectMailer).to receive(:copy_project_failed).with(admin, source_project, "Copy", [I18n.t("copy_project.failed_internal")])- .and_return maildouble+ .and_return mail_double- expect { copy_job }.not_to raise_error+ GoodJob.perform_inline# expect to create a statusexpect(copy_job.job_status).to be_present@@ -211,34 +204,39 @@ RSpec.describe CopyProjectJob, type: :model do.call(%i[estimated_hours remaining_hours ignore_non_working_days])end- it "copies the project without any errord (Bug #52384)" do+ it "copies the project without any errors (Bug #52384)" doallow(OpenProject.logger).to receive(:error)- copy_job = described_class.new- copy_job.perform user_id: admin.id,- source_project_id: source_project.id,- target_project_params: params,- associations_to_copy: [:work_packages]+ copy_job = nil+ batch = GoodJob::Batch.enqueue(user: admin) do+ copy_job = described_class.perform_later(user_id: nil,+ source_project_id: source_project.id,+ target_project_params: params,+ associations_to_copy: [:work_packages])+ end+ GoodJob.perform_inline+ batch.reloadexpect(copy_job.job_status.status).to eq "success"- expect(copy_job.errors).to be_empty+ expect(batch.properties[:errors]).to be_emptyexpect(OpenProject.logger).not_to have_received(:error)endend- describe "perform" do+ describe "#perform" dolet(:project) { create(:project, public: false) }let(:user) { create(:user) }let(:role) { create(:project_role, permissions: [:copy_projects]) }- shared_context "copy project" do+ shared_context "on copy project" dobefore do- described_class.new.tap do |job|- job.perform user_id: user.id,- source_project_id: project_to_copy.id,- target_project_params: params,- associations_to_copy: [:members]+ GoodJob::Batch.enqueue(user:) do+ described_class.perform_later user_id: user.id,+ source_project_id: project_to_copy.id,+ target_project_params: params,+ associations_to_copy: [:members]end+ GoodJob.perform_inlineendend@@ -261,7 +259,7 @@ RSpec.describe CopyProjectJob, type: :model dosubject { Project.find_by(identifier: "copy") }describe "user without add_subprojects permission in parent" do- include_context "copy project" do+ include_context "on copy project" dolet(:project_to_copy) { subproject }end@@ -287,7 +285,7 @@ RSpec.describe CopyProjectJob, type: :model dodescribe "user without add_subprojects permission in parent and when explicitly setting that parent" dolet(:params) { { name: "Copy", identifier: "copy", parent_id: project.id } }- include_context "copy project" do+ include_context "on copy project" dolet(:project_to_copy) { subproject }end@@ -318,7 +316,7 @@ RSpec.describe CopyProjectJob, type: :model domember_add_subprojectend- include_context "copy project" do+ include_context "on copy project" dolet(:project_to_copy) { subproject }end