From 1b390b1204bcd66b715cc1edaff73b11f4d90e06 Mon Sep 17 00:00:00 2001 From: Vishnu Narayanan Date: Sat, 5 Apr 2025 12:23:46 +0530 Subject: [PATCH] feat: add global method without account scope --- app/models/contact.rb | 2 +- .../internal/remove_stale_contacts_service.rb | 28 +++++++++++++++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/app/models/contact.rb b/app/models/contact.rb index 62bdb96b5..83920d9fc 100644 --- a/app/models/contact.rb +++ b/app/models/contact.rb @@ -137,7 +137,7 @@ class Contact < ApplicationRecord .where('contacts.phone_number IS NULL OR contacts.phone_number = ?', '') .where('contacts.identifier IS NULL OR contacts.identifier = ?', '') .where('contacts.created_at < ?', time_period) - .where('NOT EXISTS (SELECT 1 FROM conversations WHERE conversations.contact_id = contacts.id)') + .where.missing(:conversations) } def get_source_id(inbox_id) diff --git a/app/services/internal/remove_stale_contacts_service.rb b/app/services/internal/remove_stale_contacts_service.rb index 31de9c5cb..34e4d9c2e 100644 --- a/app/services/internal/remove_stale_contacts_service.rb +++ b/app/services/internal/remove_stale_contacts_service.rb @@ -4,21 +4,15 @@ class Internal::RemoveStaleContactsService def perform(batch_size = 1000) Rails.logger.info "[Internal::RemoveStaleContactsService] Starting removal of stale contacts for account #{@account.id}" - # Get the stale contacts query stale_contacts = @account.contacts.stale_without_conversations(30.days.ago) - total_deleted = 0 # Get only IDs in batches without loading full records stale_contacts.select(:id).in_batches(of: batch_size) do |relation| - # Use pluck to get only the IDs contact_ids = relation.pluck(:id) next if contact_ids.empty? - # Delete associated contact_inboxes first ContactInbox.where(contact_id: contact_ids).delete_all - - # Then delete the contacts Contact.where(id: contact_ids).delete_all total_deleted += contact_ids.size @@ -29,4 +23,26 @@ class Internal::RemoveStaleContactsService Rails.logger.info "[Internal::RemoveStaleContactsService] Completed removal of #{total_deleted} stale contacts " \ "for account #{@account.id}" end + + # Process stale contacts across all accounts + def perform_global(batch_size = 1000) + Rails.logger.info '[Internal::RemoveStaleContactsService] Starting global removal of stale contacts' + + stale_contacts = Contact.stale_without_conversations(30.days.ago) + total_deleted = 0 + + stale_contacts.select(:id).in_batches(of: batch_size) do |relation| + contact_ids = relation.pluck(:id) + next if contact_ids.empty? + + ContactInbox.where(contact_id: contact_ids).delete_all + Contact.where(id: contact_ids).delete_all + + total_deleted += contact_ids.size + Rails.logger.info "[Internal::RemoveStaleContactsService] Deleted #{contact_ids.size} contacts " \ + "(#{total_deleted} total)" + end + + Rails.logger.info "[Internal::RemoveStaleContactsService] Completed global removal of #{total_deleted} stale contacts" + end end