diff --git a/purge_inactive_users.rake b/purge_inactive_users.rake new file mode 100644 index 0000000..f3e6130 --- /dev/null +++ b/purge_inactive_users.rake @@ -0,0 +1,17 @@ +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