Skip to content

Instantly share code, notes, and snippets.

@misteral
Created March 11, 2016 07:16
Show Gist options
  • Save misteral/e798e944b4c2e12b4702 to your computer and use it in GitHub Desktop.
Save misteral/e798e944b4c2e12b4702 to your computer and use it in GitHub Desktop.
Service class
module Services
class UserContactsImport
attr_reader :unparsed_phones
def initialize(user, contacts_list, rewrite)
@user = user
@contact_phones = flat_and_remove_self(contacts_list)
@rewrite = rewrite
@unparsed_phones = []
end
def process!
convert_to_international!
update_contacts(phones_to_insert)
end
private
def flat_and_remove_self(contacts_list)
contacts_list.map { |list| list['phones'] }
.flatten.uniq
.delete_if { |phone| phone.include?(@user.national_number) }
end
def convert_to_international!
@phones_hash = {}
@contact_phones.each do |phone|
int_phone = to_e164(phone)
@phones_hash[int_phone] = phone if int_phone
end
end
def to_e164(phone)
country_code = Phonelib.parse(phone).valid_country || @user.country_code
e164_number = Phonelib.parse(phone, country_code).e164
return e164_number[1..-1] if e164_number
@unparsed_phones << phone
nil
end
def update_contacts(insert_phones)
return if insert_phones.blank?
Contact.import [:international_phone, :phone],
insert_phones.to_a,
validate: false
link_contacts_to_user(insert_phones)
Contact.fill_registered
end
def phones_to_insert
diff = @phones_hash.keys - @user.phonebook_contacts
.pluck(:international_phone)
@phones_hash.clone.keep_if { |k, _| diff.include? k }
end
def link_contacts_to_user(phones)
values = []
Contact.get_ids_with(phones.keys).each do |contact_id|
values.push [contact_id, @user.id, 'PhonebookContactsUser']
end
ContactsUser.import [:contact_id, :user_id, :type],
values,
validate: false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment