ZAMMAD | delete customers without related tickets

deletecandidates = User.where(protected: false).where.not(id: 1)
deletecandidates.find_each do |user|
	next if Ticket.where(customer_id: user.id).count > 0
        puts %{ "#{user.fullname}" #{user.id} #{Ticket.where(customer_id: user.id).count}}

        Ticket.where(customer: user).find_each do |ticket|
    	    puts "  Deleting ticket ##{ticket.number}..."
    	    ticket.destroy
        end

        puts "  Removing references for user with email #{user.email}..."
    	ActivityStream.where(created_by_id: user.id).update_all(created_by_id: 1)
        History.where(created_by_id: user.id).update_all(created_by_id: 1)
        Ticket::Article.where(created_by_id: user.id).update_all(created_by_id: 1)
        Ticket::Article.where(updated_by_id: user.id).update_all(updated_by_id: 1)
        Store.where(created_by_id: user.id).update_all(created_by_id: 1)
        StatsStore.where(created_by_id: user.id).update_all(created_by_id: 1)
        Tag.where(created_by_id: user.id).update_all(created_by_id: 1)
        OnlineNotification.find_by(user_id: user.id)&.destroy!

        puts "  Deleting #{user.fullname}..."
        user.destroy
end

‘protected’ is a custom user object attribute i did add.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.