diff --git a/app/jobs/notification/remove_old_notification_job.rb b/app/jobs/notification/remove_old_notification_job.rb new file mode 100644 index 000000000..770461744 --- /dev/null +++ b/app/jobs/notification/remove_old_notification_job.rb @@ -0,0 +1,8 @@ +class Notification::RemoveOldNotificationJob < ApplicationJob + queue_as :low + + def perform + Notification.where('created_at < ?', 1.month.ago) + .find_each(batch_size: 1000, &:delete) + end +end diff --git a/app/jobs/trigger_scheduled_items_job.rb b/app/jobs/trigger_scheduled_items_job.rb index 9fc7a6491..82634e4d5 100644 --- a/app/jobs/trigger_scheduled_items_job.rb +++ b/app/jobs/trigger_scheduled_items_job.rb @@ -19,5 +19,8 @@ class TriggerScheduledItemsJob < ApplicationJob # Job to sync whatsapp templates Channels::Whatsapp::TemplatesSyncSchedulerJob.perform_later + + # Job to clear notifications which are older than 1 month + Notification::RemoveOldNotificationJob.perform_later end end diff --git a/spec/jobs/notification/remove_old_notification_job_spec.rb b/spec/jobs/notification/remove_old_notification_job_spec.rb new file mode 100644 index 000000000..efc6616eb --- /dev/null +++ b/spec/jobs/notification/remove_old_notification_job_spec.rb @@ -0,0 +1,24 @@ +require 'rails_helper' + +RSpec.describe Notification::RemoveOldNotificationJob do + let(:user) { create(:user) } + let(:conversation) { create(:conversation) } + + it 'enqueues the job' do + notification = create(:notification, user: user, notification_type: 'conversation_creation', primary_actor: conversation) + expect do + described_class.perform_later(notification) + end.to have_enqueued_job(described_class) + .on_queue('low') + end + + it 'removes old notifications which are older than 1 month' do + create(:notification, user: user, notification_type: 'conversation_creation', primary_actor: conversation, created_at: 2.months.ago) + create(:notification, user: user, notification_type: 'conversation_creation', primary_actor: conversation, created_at: 1.month.ago) + create(:notification, user: user, notification_type: 'conversation_creation', primary_actor: conversation, created_at: 1.day.ago) + create(:notification, user: user, notification_type: 'conversation_creation', primary_actor: conversation, created_at: 1.hour.ago) + + described_class.perform_now + expect(Notification.count).to eq(2) + end +end diff --git a/spec/jobs/trigger_scheduled_items_job_spec.rb b/spec/jobs/trigger_scheduled_items_job_spec.rb index 9fd846c2d..c3f34dfeb 100644 --- a/spec/jobs/trigger_scheduled_items_job_spec.rb +++ b/spec/jobs/trigger_scheduled_items_job_spec.rb @@ -40,5 +40,10 @@ RSpec.describe TriggerScheduledItemsJob do expect(Channels::Whatsapp::TemplatesSyncSchedulerJob).to receive(:perform_later).once described_class.perform_now end + + it 'triggers Notification::RemoveOldNotificationJob' do + expect(Notification::RemoveOldNotificationJob).to receive(:perform_later).once + described_class.perform_now + end end end