Files
leadchat/lib/tasks/ops/cleanup_orphan_conversations.rake
Tanmay Deep Sharma 2b50909d9b fix: use last_activity_at for orphan conversation cleanup timeframe (#13859)
## Description

The RemoveOrphanConversationsService filters orphan conversations by a
time window before deleting them. Previously it used created_at, which
could miss old conversations that still had recent activity.
Switching to last_activity_at ensures the cleanup window reflects actual
conversation activity rather than creation time.

## Type of change

Please delete options that are not relevant.

- [ ] Bug fix (non-breaking change which fixes an issue)

## How Has This Been Tested?

- By running Rake task 
- Run the job from console 

## Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my code
- [ ] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream
modules
2026-03-20 16:28:05 +05:30

43 lines
1.4 KiB
Ruby

# frozen_string_literal: true
# Run with:
# bundle exec rake chatwoot:ops:cleanup_orphan_conversations
namespace :chatwoot do
namespace :ops do
desc 'Identify and delete conversations without a valid contact or inbox in a timeframe'
task cleanup_orphan_conversations: :environment do
print 'Enter Account ID: '
account_id = $stdin.gets.to_i
account = Account.find(account_id)
print 'Enter timeframe in days (default: 7): '
days_input = $stdin.gets.strip
days = days_input.empty? ? 7 : days_input.to_i
service = Internal::RemoveOrphanConversationsService.new(account: account, days: days)
# Preview count using the same query logic
base = account
.conversations
.where('conversations.last_activity_at > ?', days.days.ago)
.left_outer_joins(:contact, :inbox)
conversations = base.where(contacts: { id: nil }).or(base.where(inboxes: { id: nil }))
count = conversations.count
puts "Found #{count} conversations without a valid contact or inbox."
if count.positive?
print 'Do you want to delete these conversations? (y/N): '
confirm = $stdin.gets.strip.downcase
if %w[y yes].include?(confirm)
total_deleted = service.perform
puts "#{total_deleted} conversations deleted."
else
puts 'No conversations were deleted.'
end
end
end
end
end