namespace :zammad do desc "Purge inactive users" task purge_inactive_users: :environment do User.joins('LEFT JOIN tickets ON tickets.customer_id = users.id') .joins(:roles) .where('roles.name = \'Customer\' AND tickets.state_id NOT IN (?) AND tickets.updated_at < ?', Ticket::State.where(name: ['new', 'open']).pluck(:id), 30.days.ago) .distinct .find_each do |user| if Ticket.where(customer_id: user.id) .where('state_id IN (?) AND updated_at >= ?', Ticket::State.where(name: ['new', 'open']).pluck(:id), 30.days.ago) .empty? user.destroy end end puts "Purge complete." end end