From 2c9157741923ac8a8d3196effcf3224c0609e31e Mon Sep 17 00:00:00 2001 From: Shivam Mishra Date: Wed, 26 Mar 2025 22:20:58 +0530 Subject: [PATCH] feat: start service --- .../remove_orphaned_contacts_service.rb | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 app/services/internal/remove_orphaned_contacts_service.rb diff --git a/app/services/internal/remove_orphaned_contacts_service.rb b/app/services/internal/remove_orphaned_contacts_service.rb new file mode 100644 index 000000000..793bfbb7b --- /dev/null +++ b/app/services/internal/remove_orphaned_contacts_service.rb @@ -0,0 +1,43 @@ +class Internal::RemoveOrphanedContactsService + # by default, purge contacts older than 6 months + attr_reader :account_id, :offset, :account, :deleted_count + + def initialize(account_id:, offset: 180.days) + @account_id = account_id + @account = Account.find(account_id) + raise ArgumentError, 'Account not found' if @account.nil? + + @offset = offset + @deleted_count = 0 + end + + def perform + Rails.logger.info "Starting contact purge for account #{account_id} for #{offset / 1.day} days" + + base_query.find_in_batches(batch_size: 100) do |contacts_batch| + process_batch(contacts_batch) + end + + Rails.logger.info "Completed contact purge for account #{account_id}. Total contacts deleted: #{deleted_count}" + end + + private + + def process_batch(contacts_batch) + batch_deleted = 0 + + contacts_batch.each do |contact| + next if contact.conversations.exists? + + contact.destroy! + batch_deleted += 1 + @deleted_count += 1 + end + + Rails.logger.info "Processed batch of #{contacts_batch.size} contacts, deleted #{batch_deleted} for account #{account_id}" + end + + def base_query + account.contacts.where('created_at < ?', Time.zone.now - offset) + end +end