From 2d782c7b00b6fb82d1e34481f2923aa07347d0c1 Mon Sep 17 00:00:00 2001 From: Joffrey JAFFEUX Date: Tue, 15 Aug 2023 15:36:00 +0200 Subject: [PATCH] FIX: correctly deletes webhook_events with webhook (#23097) Each time a message is created through a webhook, we create we webhook_event associated to this webhook. When destroying a webhook, we were not destroying the webhook_events which was causing orphans records and more importantly errors in the app expecting to find and associated webhook. --- plugins/chat/app/models/chat/incoming_webhook.rb | 5 ++++- .../spec/models/chat/incoming_webhook_spec.rb | 10 ++++++++++ .../admin/incoming_webhooks_controller_spec.rb | 15 +++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 plugins/chat/spec/models/chat/incoming_webhook_spec.rb diff --git a/plugins/chat/app/models/chat/incoming_webhook.rb b/plugins/chat/app/models/chat/incoming_webhook.rb index cb76ffebc66..a7f447fbd68 100644 --- a/plugins/chat/app/models/chat/incoming_webhook.rb +++ b/plugins/chat/app/models/chat/incoming_webhook.rb @@ -5,7 +5,10 @@ module Chat self.table_name = "incoming_chat_webhooks" belongs_to :chat_channel, class_name: "Chat::Channel" - has_many :chat_webhook_events, class_name: "Chat::WebhookEvent" + has_many :chat_webhook_events, + foreign_key: "incoming_chat_webhook_id", + class_name: "Chat::WebhookEvent", + dependent: :delete_all before_create { self.key = SecureRandom.hex(12) } diff --git a/plugins/chat/spec/models/chat/incoming_webhook_spec.rb b/plugins/chat/spec/models/chat/incoming_webhook_spec.rb new file mode 100644 index 00000000000..197d0b1ccd6 --- /dev/null +++ b/plugins/chat/spec/models/chat/incoming_webhook_spec.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +RSpec.describe Chat::IncomingWebhook do + it do + is_expected.to have_many(:chat_webhook_events) + .with_foreign_key("incoming_chat_webhook_id") + .class_name("Chat::WebhookEvent") + .dependent(:delete_all) + end +end diff --git a/plugins/chat/spec/requests/chat/admin/incoming_webhooks_controller_spec.rb b/plugins/chat/spec/requests/chat/admin/incoming_webhooks_controller_spec.rb index 8a20809b773..a67d99a77bc 100644 --- a/plugins/chat/spec/requests/chat/admin/incoming_webhooks_controller_spec.rb +++ b/plugins/chat/spec/requests/chat/admin/incoming_webhooks_controller_spec.rb @@ -132,5 +132,20 @@ RSpec.describe Chat::Admin::IncomingWebhooksController do Chat::IncomingWebhook.count }.by(-1) end + + it "destroys webhook events records" do + sign_in(admin) + + Chat::MessageCreator.create( + chat_channel: existing.chat_channel, + user: Discourse.system_user, + content: "foo", + incoming_chat_webhook: existing, + ) + + expect { delete "/admin/plugins/chat/hooks/#{existing.id}.json" }.to change { + Chat::WebhookEvent.count + }.by(-1) + end end end