From e3e94aec95c0179a158aa21416fe4c496227269d Mon Sep 17 00:00:00 2001 From: Joffrey JAFFEUX Date: Tue, 26 Sep 2023 10:15:16 +0200 Subject: [PATCH] FIX: ensures we reuse existing thread if existing (#23618) This is a special case to ensure that if two users start a thread at the same time, we won't attempt to create a second thread. --- plugins/chat/app/services/chat/create_thread.rb | 8 ++++++-- .../chat/spec/services/chat/create_thread_spec.rb | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/plugins/chat/app/services/chat/create_thread.rb b/plugins/chat/app/services/chat/create_thread.rb index 3b83352ac37..9895d0dc85d 100644 --- a/plugins/chat/app/services/chat/create_thread.rb +++ b/plugins/chat/app/services/chat/create_thread.rb @@ -22,7 +22,7 @@ module Chat policy :threading_enabled_for_channel model :original_message transaction do - step :create_thread + step :find_or_create_thread step :associate_thread_to_message step :fetch_membership step :publish_new_thread @@ -59,7 +59,11 @@ module Chat channel.threading_enabled end - def create_thread(channel:, original_message:, contract:, **) + def find_or_create_thread(channel:, original_message:, contract:, **) + if original_message.thread_id.present? + return context.thread = ::Chat::Thread.find_by(id: original_message.thread_id) + end + context.thread = channel.threads.create( title: contract.title, diff --git a/plugins/chat/spec/services/chat/create_thread_spec.rb b/plugins/chat/spec/services/chat/create_thread_spec.rb index f687c67e5b8..c73a202fa89 100644 --- a/plugins/chat/spec/services/chat/create_thread_spec.rb +++ b/plugins/chat/spec/services/chat/create_thread_spec.rb @@ -97,5 +97,19 @@ RSpec.describe Chat::CreateThread do it { is_expected.to fail_a_policy(:threading_enabled_for_channel) } end + + context "when a thread is already present" do + before do + Chat::CreateThread.call( + guardian: current_user.guardian, + original_message_id: message_1.id, + channel_id: channel_1.id, + ) + end + + it "uses the existing thread" do + expect { result }.not_to change { Chat::Thread.count } + end + end end end