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
Moves the email sending to a Batch callback job
Marcello Rochaeb8d03287f05
diff --git a/app/services/projects/enqueue_copy_service.rb b/app/services/projects/enqueue_copy_service.rbindex 705e0c7f724..5102685fa46 100644--- a/app/services/projects/enqueue_copy_service.rb+++ b/app/services/projects/enqueue_copy_service.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@@ -61,10 +63,8 @@ module Projects# Schedule the project copy jobdef schedule_copy_job(params)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],+ GoodJob::Batch.enqueue(on_finish: SendCopyProjectStatusEmailJob, user:, source_project: source) do+ job = CopyProjectJob.perform_later(target_project_params: params[:target_project_params],associations_to_copy: params[:only].to_a,send_mails: ActiveRecord::Type::Boolean.new.cast(params[:send_notifications]))enddiff --git a/app/workers/copy_project_job.rb b/app/workers/copy_project_job.rbindex cefe8158fab..4fe7b3aa391 100644--- a/app/workers/copy_project_job.rb+++ b/app/workers/copy_project_job.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@@ -27,77 +29,53 @@#++class CopyProjectJob < ApplicationJob- queue_with_priority :above_normalinclude OpenProject::LocaleHelperinclude GoodJob::ActiveJobExtensions::Batchesqueue_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_mails-- def perform(user_id:,- source_project_id:,- target_project_params:,- associations_to_copy:,- send_mails: false)- # Needs refactoring after moving to activejob-- @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-+ # rubocop:disable Metrics/AbcSize+ # Again error handling pushing the branch costs up+ def perform(target_project_params:, associations_to_copy:, send_mails: false)User.current = user- @target_project_name = target_project_params[:name]+ target_project_params = target_project_params.with_indifferent_access- @target_project, @errors = with_locale_for(user) do- create_project_copy+ target_project, errors = with_locale_for(user) do+ create_project_copy(target_project_params, associations_to_copy, send_mails)end- batch.properties.merge!(target_project:, errors:)- batch.save+ update_batch(target_project:, errors:, target_project_name: target_project_params[:name])if target_project- successful_status_update- ProjectMailer.copy_project_succeeded(user, source_project, target_project, errors).deliver_later+ successful_status_update(target_project, errors)else- failure_status_update- ProjectMailer.copy_project_failed(user, source_project, @target_project_name, errors).deliver_later+ failure_status_update(errors)endrescue 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+ update_batch(errors:)+ failure_status_update(errors)end+ # rubocop:enable Metrics/AbcSize- def store_status?- true- end+ def store_status? = true- def updates_own_status?- true- end+ def updates_own_status? = trueprotected- def title- I18n.t(:label_copy_project)- end+ def title = I18n.t(:label_copy_project)private- def successful_status_update- payload = redirect_payload(url_helpers.project_url(target_project))- .merge(hal_links(target_project))+ def update_batch(hash)+ batch.properties.merge!(hash)+ batch.save+ end++ def successful_status_update(target_project, errors)+ payload = redirect_payload(url_helpers.project_url(target_project)).merge(hal_links(target_project))if errors.any?payload[:errors] = errors@@ -108,7 +86,7 @@ class CopyProjectJob < ApplicationJobpayload:end- def failure_status_update+ def failure_status_update(errors)message = I18n.t("copy_project.failed", source_project_name: source_project.name)if errors@@ -129,62 +107,50 @@ class CopyProjectJob < ApplicationJob}end- def user- @user ||= batch.properties[:user]- end+ def user = batch.properties[:user]- def source_project- @source_project ||= Project.find @source_project_id- end+ def source_project = batch.properties[:source_project]- def create_project_copy+ # rubocop:disable Metrics/AbcSize+ # Most of the cost is from handling errors, we need to check what can be moved around / removed+ def create_project_copy(target_project_params, associations_to_copy, send_mails)errors = []- ProjectMailer.with_deliveries(@send_mails) do- service_call = copy_project- target_project = service_call.result- errors = service_call.errors.full_messages+ ProjectMailer.with_deliveries(send_mails) do+ service_result = copy_project(target_project_params, associations_to_copy, send_mails)+ target_project = service_result.result+ errors = service_result.errors.full_messages# We assume the copying worked "successfully" if the project was saved- unless target_project&.persisted?- target_project = nil+ if target_project&.persisted?+ return target_project, errors+ elselogger.error("Copying project fails with validation errors: #{errors.join("\n")}")+ return nil, errorsend-- return target_project, errorsendrescue 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 eensure- unless errors.empty?+ if errors.any?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+ # rubocop:enable Metrics/AbcSize- def copy_project+ def copy_project(target_project_params, associations_to_copy, send_notifications)::Projects::CopyService.new(source: source_project, user:)- .call(copy_project_params)+ .call({ target_project_params:, send_notifications:, only: Array(associations_to_copy) })end- def copy_project_params- params = { target_project_params:, send_notifications: @send_mails }- params[:only] = @associations_to_copy if @associations_to_copy.present?+ def logger = OpenProject.logger- params- end-- def logger- Rails.logger- end-- def url_helpers- @url_helpers ||= OpenProject::StaticRouting::StaticUrlHelpers.new- end+ def url_helpers = OpenProject::StaticRouting::StaticUrlHelpers.newenddiff --git a/app/workers/notifications/schedule_date_alerts_notifications_job.rb b/app/workers/notifications/schedule_date_alerts_notifications_job.rbindex 525a0473bdd..24230fe1d4d 100644--- a/app/workers/notifications/schedule_date_alerts_notifications_job.rb+++ b/app/workers/notifications/schedule_date_alerts_notifications_job.rb@@ -23,7 +23,7 @@# 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.+# See COPYRIGHT and LICENSE files for more details.#++module Notificationsdiff --git a/app/workers/notifications/schedule_reminder_mails_job.rb b/app/workers/notifications/schedule_reminder_mails_job.rbindex 0c17199d1c7..969f04c1551 100644--- a/app/workers/notifications/schedule_reminder_mails_job.rb+++ b/app/workers/notifications/schedule_reminder_mails_job.rb@@ -23,7 +23,7 @@# 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.+# See COPYRIGHT and LICENSE files for more details.#++module Notificationsdiff --git a/app/workers/send_copy_project_status_email_job.rb b/app/workers/send_copy_project_status_email_job.rbnew file mode 100644index 00000000000..1e04eb64ae0--- /dev/null+++ b/app/workers/send_copy_project_status_email_job.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2024 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 COPYRIGHT and LICENSE files for more details.+#++++class SendCopyProjectStatusEmailJob < ApplicationJob+ # Job is to be used as a callback to the CopyProjectJob batch++ def perform(batch, _args)+ if copy_job_succeeded?(batch) && batch.properties[:target_project]+ send_success_email(batch)+ else+ send_failure_email(batch)+ end+ end++ private++ def copy_job_succeeded?(batch)+ job = batch.active_jobs.find { |batch_job| batch_job.instance_of?(CopyProjectJob) }++ job.job_status.success?+ end++ def send_failure_email(batch)+ ProjectMailer.copy_project_failed(+ batch.properties[:user],+ batch.properties[:source_project],+ batch.properties[:target_project_name],+ batch.properties[:errors]+ ).deliver_later+ end++ def send_success_email(batch)+ ProjectMailer.copy_project_succeeded(+ batch.properties[:user],+ batch.properties[:source_project],+ batch.properties[:target_project],+ batch.properties[:errors]+ ).deliver_later+ end+enddiff --git a/spec/features/projects/copy_spec.rb b/spec/features/projects/copy_spec.rbindex 3ecd33e6a01..bd865e4b25f 100644--- a/spec/features/projects/copy_spec.rb+++ b/spec/features/projects/copy_spec.rb@@ -28,7 +28,7 @@require "spec_helper"-RSpec.describe "Projects copy", :js, :with_cuprite do+RSpec.describe "Projects copy", :js, :with_cuprite, with_good_job_batches: [CopyProjectJob, SendCopyProjectStatusEmailJob] dodescribe "with a full copy example" dolet!(:project) docreate(:project,@@ -369,7 +369,7 @@ RSpec.describe "Projects copy", :js, :with_cuprite doeditor = Components::WysiwygEditor.new "[data-qa-field-name='customField#{project_custom_field.id}']"editor.expect_value "some text cf"- click_button "Save"+ click_on "Save"wait_for_copy_to_finish@@ -494,10 +494,11 @@ RSpec.describe "Projects copy", :js, :with_cuprite dofill_in "Name", with: "Copied project"- click_button "Save"+ click_on "Save"expect(page).to have_text "The job has been queued and will be processed shortly."+ GoodJob.perform_inlineperform_enqueued_jobsexpect(copied_project)@@ -513,6 +514,7 @@ RSpec.describe "Projects copy", :js, :with_cuprite doexpect(page).to have_text "The job has been queued and will be processed shortly."# ensure all jobs are run especially emails which might be sent later on+ GoodJob.perform_inlinewhile perform_enqueued_jobs > 0endenddiff --git a/spec/features/projects/template_spec.rb b/spec/features/projects/template_spec.rbindex 3cddab88a12..3bbadcdcc77 100644--- a/spec/features/projects/template_spec.rb+++ b/spec/features/projects/template_spec.rb@@ -28,7 +28,8 @@require "spec_helper"-RSpec.describe "Project templates", :js, :with_cuprite do+RSpec.describe "Project templates", :js, :with_cuprite,+ with_good_job_batches: [CopyProjectJob, SendCopyProjectStatusEmailJob] dodescribe "making project a template" dolet(:project) { create(:project) }@@ -134,6 +135,7 @@ RSpec.describe "Project templates", :js, :with_cuprite doexpect(page).to have_content I18n.t("js.job_status.generic_messages.in_queue")# Run background jobs twice: the background job which itself enqueues the mailer job+ GoodJob.perform_inline2.times { perform_enqueued_jobs }mail = ActionMailer::Basediff --git a/spec/workers/copy_project_job_spec.rb b/spec/workers/copy_project_job_spec.rbindex 1f2308e4e27..78ee6a18bd6 100644--- a/spec/workers/copy_project_job_spec.rb+++ b/spec/workers/copy_project_job_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"-RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectJob] do+RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectJob, SendCopyProjectStatusEmailJob] dolet(:params) { { name: "Copy", identifier: "copy" } }let(:user_de) { create(:admin, language: :de) }let(:mail_double) { double("Mail::Message", deliver: true) } # rubocop:disable RSpec/VerifiedDoubles@@ -48,8 +50,6 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectlet(:job_args) do{- user_id: admin.id,- source_project_id: source_project.id,target_project_params: params,associations_to_copy: [:work_packages]}@@ -67,7 +67,7 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectit "copies the project", :aggregate_failures docopy_job = nil- batch = GoodJob::Batch.enqueue(user: admin) do+ batch = GoodJob::Batch.enqueue(user: admin, source_project:) docopy_job = described_class.perform_later(**job_args)endGoodJob.perform_inline@@ -88,7 +88,7 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectendit "ensures that error messages are correctly localized" do- batch = GoodJob::Batch.enqueue(user: user_de) do+ batch = GoodJob::Batch.enqueue(user: user_de, source_project:) dodescribed_class.perform_later(**job_args)endGoodJob.perform_inline@@ -111,15 +111,6 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectprojectend- 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-before doallow(User).to receive(:current).and_return(admin)end@@ -127,11 +118,8 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectit "saves without the repository" doexpect(source_project).not_to be_valid- 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])+ batch = GoodJob::Batch.enqueue(user: admin, source_project:) do+ described_class.perform_later(target_project_params: params, associations_to_copy: [:work_packages])endGoodJob.perform_inline@@ -154,22 +142,19 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectbefore doallow(User).to receive(:current).and_return(admin)- allow(ProjectMailer).to receive(:copy_project_succeeded).and_raise "error message not meant for user"+ allow(Projects::CopyService).to receive(:new).and_return(->(*) { raise "Gen. Failure reporting for duty!" })endit "renders a error when unexpected errors occur" docopy_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])+ GoodJob::Batch.enqueue(user: admin, source_project:) do+ copy_job = described_class.perform_later(target_project_params: params, associations_to_copy: [:work_packages])end- expect(ProjectMailer)+ allow(ProjectMailer).to receive(:copy_project_failed).with(admin, source_project, "Copy", [I18n.t("copy_project.failed_internal")])- .and_return mail_double+ .and_return(mail_double)GoodJob.perform_inline@@ -208,11 +193,8 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectallow(OpenProject.logger).to receive(:error)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])+ batch = GoodJob::Batch.enqueue(user: admin, source_project:) do+ copy_job = described_class.perform_later(target_project_params: params, associations_to_copy: [:work_packages])endGoodJob.perform_inlinebatch.reload@@ -230,12 +212,10 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectshared_context "on copy project" dobefore do- 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]+ GoodJob::Batch.enqueue(on_finish: SendCopyProjectStatusEmailJob, user:, source_project: project_to_copy) do+ described_class.perform_later(target_project_params: params, associations_to_copy: [:members])end+GoodJob.perform_inlineendend@@ -249,14 +229,11 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectlet(:params) { { name: "Copy", identifier: "copy" } }let(:subproject) docreate(:project, parent: project).tap do |p|- create(:member,- principal: user,- roles: [role],- project: p)+ create(:member, principal: user, roles: [role], project: p)endend- subject { Project.find_by(identifier: "copy") }+ subject(:copied_project) { Project.find_by(identifier: "copy") }describe "user without add_subprojects permission in parent" doinclude_context "on copy project" do@@ -264,17 +241,17 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProjectendit "copies the project without the parent being set" do- expect(subject).not_to be_nil- expect(subject.parent).to be_nil+ expect(copied_project).not_to be_nil+ expect(copied_project.parent).to be_nilexpect(subproject.reload.enabled_module_names).not_to be_emptyendit "notifies the user of the success" do- perform_enqueued_jobs+ perform_enqueued_jobs # needed for the deliveriesmail = ActionMailer::Base.deliveries- .find { |m| m.message_id.start_with? "op.project-#{subject.id}" }+ .find { |m| m.message_id.start_with? "op.project-#{copied_project.id}" }expect(mail).to be_presentexpect(mail.subject).to eq "Created project #{subject.name}"