Skip to content

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

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.rb
index 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 job
def 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]))
end
diff --git a/app/workers/copy_project_job.rb b/app/workers/copy_project_job.rb
index 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_normal
include OpenProject::LocaleHelper
include GoodJob::ActiveJobExtensions::Batches
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_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)
end
rescue StandardError => e
logger.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? = true
protected
- 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 < ApplicationJob
payload:
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
+ else
logger.error("Copying project fails with validation errors: #{errors.join("\n")}")
+ return nil, errors
end
-
- return target_project, errors
end
rescue ActiveRecord::RecordNotFound => e
logger.error("Entity missing: #{e.message} #{e.backtrace.join("\n")}")
raise e
rescue StandardError => e
logger.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 e
ensure
- 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}")
end
end
+ # 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.new
end
diff --git a/app/workers/notifications/schedule_date_alerts_notifications_job.rb b/app/workers/notifications/schedule_date_alerts_notifications_job.rb
index 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 Notifications
diff --git a/app/workers/notifications/schedule_reminder_mails_job.rb b/app/workers/notifications/schedule_reminder_mails_job.rb
index 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 Notifications
diff --git a/app/workers/send_copy_project_status_email_job.rb b/app/workers/send_copy_project_status_email_job.rb
new file mode 100644
index 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
+end
diff --git a/spec/features/projects/copy_spec.rb b/spec/features/projects/copy_spec.rb
index 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] do
describe "with a full copy example" do
let!(:project) do
create(:project,
@@ -369,7 +369,7 @@ RSpec.describe "Projects copy", :js, :with_cuprite do
editor = 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 do
fill_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_inline
perform_enqueued_jobs
expect(copied_project)
@@ -513,6 +514,7 @@ RSpec.describe "Projects copy", :js, :with_cuprite do
expect(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_inline
while perform_enqueued_jobs > 0
end
end
diff --git a/spec/features/projects/template_spec.rb b/spec/features/projects/template_spec.rb
index 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] do
describe "making project a template" do
let(:project) { create(:project) }
@@ -134,6 +135,7 @@ RSpec.describe "Project templates", :js, :with_cuprite do
expect(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_inline
2.times { perform_enqueued_jobs }
mail = ActionMailer::Base
diff --git a/spec/workers/copy_project_job_spec.rb b/spec/workers/copy_project_job_spec.rb
index 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] do
let(: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: [CopyProject
let(: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: [CopyProject
it "copies the project", :aggregate_failures do
copy_job = nil
- batch = GoodJob::Batch.enqueue(user: admin) do
+ batch = GoodJob::Batch.enqueue(user: admin, source_project:) do
copy_job = described_class.perform_later(**job_args)
end
GoodJob.perform_inline
@@ -88,7 +88,7 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProject
end
it "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:) do
described_class.perform_later(**job_args)
end
GoodJob.perform_inline
@@ -111,15 +111,6 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProject
project
end
- 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 do
allow(User).to receive(:current).and_return(admin)
end
@@ -127,11 +118,8 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProject
it "saves without the repository" do
expect(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])
end
GoodJob.perform_inline
@@ -154,22 +142,19 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProject
before do
allow(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!" })
end
it "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])
+ 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: [CopyProject
allow(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])
end
GoodJob.perform_inline
batch.reload
@@ -230,12 +212,10 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProject
shared_context "on copy project" do
before 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_inline
end
end
@@ -249,14 +229,11 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProject
let(:params) { { name: "Copy", identifier: "copy" } }
let(:subproject) do
create(:project, parent: project).tap do |p|
- create(:member,
- principal: user,
- roles: [role],
- project: p)
+ create(:member, principal: user, roles: [role], project: p)
end
end
- subject { Project.find_by(identifier: "copy") }
+ subject(:copied_project) { Project.find_by(identifier: "copy") }
describe "user without add_subprojects permission in parent" do
include_context "on copy project" do
@@ -264,17 +241,17 @@ RSpec.describe CopyProjectJob, type: :model, with_good_job_batches: [CopyProject
end
it "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_nil
expect(subproject.reload.enabled_module_names).not_to be_empty
end
it "notifies the user of the success" do
- perform_enqueued_jobs
+ perform_enqueued_jobs # needed for the deliveries
mail = 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_present
expect(mail.subject).to eq "Created project #{subject.name}"