Last active
December 15, 2021 21:50
-
-
Save shannondoah/37c99795099ad8a0f4beae44240d1642 to your computer and use it in GitHub Desktop.
Script to merge contacts by phone and name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NameAndPhoneAutoMerge | |
attr_reader :company | |
def initialize(company) | |
@company = company | |
end | |
def self.process(company) | |
new(company).process | |
end | |
def process | |
merge_duplicates | |
company.reset_counts | |
end | |
def contacts | |
@contacts ||= company.contacts.where(email: nil) | |
end | |
def duplicates | |
@duplicates ||= contacts.group(:phone, :first_name, :last_name).having("count(*) > 1").count | |
end | |
def merge_duplicates | |
total_slices = (duplicates.size / 250.0).round | |
duplicates.each_slice(250).with_index do |slice, index| | |
slice.each do |params, count| | |
contact_params = %i[phone first_name last_name].zip(params).to_h | |
dupes = contacts.where(contact_params).order(updated_at: :desc) | |
contact_id = dupes.first.id # most recently updated as root contact | |
ContactMergeWorker.perform_async(contact_id, dupes.pluck(:id), true) | |
end | |
puts "Completed batch #{index + 1} of #{total_slices}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment