repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
chuckmersereau/api_practice
app/controllers/api/v2/contacts/tags/bulk_controller.rb
class Api::V2::Contacts::Tags::BulkController < Api::V2::BulkController include BulkTaggable resource_type :tags def create load_contacts authorize_contacts add_tags_to_contacts render_contacts end def destroy load_tags authorize_tags destroy_tags end private def add_tags_to_contacts @contacts.each do |contact| contact.tag_list.add(*tag_names) contact.save! end end def authorize_tags account_lists.each { |account_list| authorize(account_list, :show?) } end def authorize_contacts @contacts.each do |contact| authorize(contact, :update?) end end def contact_ids filter_params[:contact_ids].to_s.split(',').map(&:strip) end def contacts_query { account_list: account_lists }.tap do |query| query[:id] = contact_ids if contact_ids.present? end end def contacts_scope @contacts_scope ||= scope_exists!(Contact.where(contacts_query)) end alias tags_scope contacts_scope def destroy_tags # We are removing tags from each contact individually here to trigger the MC export # on contact update. Do not change this unless you have another solution in mind to trigger that callback. contacts_scope.joins(:taggings).where(taggings: { id: @tags }).each do |contact| contact.tag_list.remove(*tag_names) contact.save! end @tags.destroy_all head :no_content end def load_contacts @contacts ||= contacts_scope end def load_tags @tags ||= ActsAsTaggableOn::Tagging.joins(:tag) .where(taggable_type: 'Contact', taggable_id: taggable_ids, tags: { name: tag_names }) end def permitted_filters [:account_list_id, :contact_ids] end def pundit_user PunditContext.new(current_user) end def render_contacts render json: BulkResourceSerializer.new(resources: @contacts), include: include_params, fields: field_params end end
chuckmersereau/api_practice
app/workers/queue_contact_dup_merge_batch_worker.rb
<gh_stars>0 class QueueContactDupMergeBatchWorker include Sidekiq::Worker sidekiq_options queue: :api_contact_dup_contacts_merge_worker def perform(account_list_id, since_unix_time) @account_list = AccountList.find_by_id(account_list_id) return true unless @account_list @since_time = Time.at(since_unix_time) queue_batch_jobs batch.bid end private attr_reader :account_list, :since_time def batch return @batch if @batch @batch = Sidekiq::Batch.new @batch.description = "Merge duplicate Contacts for AccountList #{account_list.id} since #{since_time.utc}" @batch end # If we run a merge on two duplicate contacts at the same time in parallel then it can result in both contacts being deleted. # To avoid that we check for duplicates here and avoid queuing merge jobs for them. def queue_batch_jobs batch.jobs do queued_ids = [] contacts.each do |contact| contact_ids_to_merge = duplicates_ids_for_contact(contact) << contact.id next if (queued_ids & contact_ids_to_merge).present? queued_ids += contact_ids_to_merge ContactDupMergeWorker.perform_async(account_list.id, contact.id) end end end def contacts account_list.contacts.where('updated_at >= ?', since_time) end def duplicates_ids_for_contact(contact) Contact::DupContactsMerge.new(account_list: account_list, contact: contact).find_duplicates.collect(&:id) end end
chuckmersereau/api_practice
spec/mailers/previews/import_mailer_preview.rb
class ImportMailerPreview < ActionMailer::Preview def success import = Import.first ImportMailer.success(import) end def failed import = Import.first ImportMailer.failed(import) end def credentials_error account = Person::OrganizationAccount.first ImportMailer.credentials_error(account) end end
chuckmersereau/api_practice
spec/services/reports/appointment_results_period_spec.rb
require 'rails_helper' RSpec.describe Reports::AppointmentResultsPeriod, type: :model do let(:account_list) { create(:account_list) } let(:primary_appeal) do appeal = create(:appeal, account_list: account_list) account_list.update(primary_appeal: appeal) appeal end let(:second_appeal) { create(:appeal, account_list: account_list) } let(:end_date) { Date.new(2018, 4, 30).end_of_day } let(:params) { { account_list: account_list, start_date: Date.new(2018, 4, 1).beginning_of_day, end_date: end_date } } # use method to bust caching inside of the report def report described_class.new(params) end let!(:new_partner_contact) do create(:contact, account_list: account_list, status: 'Appointment Scheduled', created_at: '2018-03-04 13:00:00') end let!(:awaiting_decision_contact) do create(:contact, account_list: account_list, status: 'Call for Decision', created_at: '2018-03-04 13:00:00') end let!(:existing_partner_contact) do create(:contact, name: '<NAME>', account_list: account_list, status: 'Partner - Financial', pledge_amount: 10, created_at: '2018-03-04 13:00:00') end # this contact covers the use-case that the contact is created with a financial status let!(:new_financial_partner) do create(:contact, account_list: account_list, status: 'Partner - Financial', pledge_amount: 10, created_at: '2018-04-07 12:00:00') end describe '#individual_appointments' do let!(:appointment1) do create(:task, activity_type: 'Appointment', start_at: '2018-04-04 12:00:00', completed_at: '2018-04-04 13:00:00', account_list: account_list, completed: true, contacts: [new_partner_contact]) end let!(:appointment2) do create(:task, activity_type: 'Appointment', start_at: '2018-04-05 12:00:00', completed_at: '2018-04-05 13:00:00', account_list: account_list, completed: true, contacts: [awaiting_decision_contact]) end let!(:appointment3) do create(:task, activity_type: 'Appointment', start_at: '2018-04-06 12:00:00', completed_at: '2018-04-06 13:00:00', account_list: account_list, completed: true, contacts: [existing_partner_contact]) end let!(:appointment4) do create(:task, activity_type: 'Appointment', start_at: '2018-04-07 13:00:00', completed_at: '2018-04-07 13:00:00', account_list: account_list, completed: true, contacts: [new_financial_partner]) end it 'counts appointments on account list' do expect(report.individual_appointments).to eq 4 end it 'does not count appointments outside time window' do appointment1.update(start_at: '2018-05-01 00:00:00') expect(report.individual_appointments).to eq 3 end it 'does not count attempted appointments' do appointment1.update(result: 'Attempted') expect(report.individual_appointments).to eq 3 end end describe '#group_appointments' do it 'counts group_appointments on account list' end describe '#new_monthly_partners' do it 'counts contacts changing to financial partners' do travel_to '2018-04-11 18:30' do new_partner_contact.update(status: 'Partner - Financial') end travel_to '2018-04-11 18:31' do new_partner_contact.update(pledge_amount: 100) existing_partner_contact.update(pledge_amount: 15) end expect(report.new_monthly_partners).to eq 2 end it 'does not count if the partner did not set a pledge_amount' do travel_to('2018-03-11') { new_partner_contact.update(pledge_amount: nil) } expect do travel_to('2018-04-11') { new_partner_contact.update(status: 'Partner - Financial') } end.to_not change { report.new_monthly_partners } end it 'does counts if the partner set a pledge_amount' do expect do travel_to('2018-03-11') { new_partner_contact.update(status: 'Partner - Financial', pledge_amount: nil) } travel_to('2018-04-11') { new_partner_contact.update(pledge_amount: 100) } end.to change { report.new_monthly_partners }.by(1) end it 'does not count changes before the window' do expect do travel_to('2018-03-15') { new_partner_contact.update(status: 'Partner - Financial', pledge_amount: 100) } end.to_not change { report.new_monthly_partners } end it 'does not count changes after the window' do expect do travel_to('2018-05-01 18:30') { new_partner_contact.update(status: 'Partner - Financial', pledge_amount: 100) } end.to_not change { report.new_monthly_partners } end it 'counts contacts who later changed away from Partner - Financial' do travel_to('2018-04-11') { new_partner_contact.update(status: 'Partner - Financial', pledge_amount: 100) } travel_to('2018-06-11') { new_partner_contact.update(status: 'Partner - Special') } expect(report.new_monthly_partners).to eq 2 end end describe '#new_special_pledges' do it 'counts appointments resulting in pledges to primary appeal' do expect do travel_to '2018-04-11 18:30' do create(:pledge, contact: awaiting_decision_contact, appeal: primary_appeal) end end.to change { report.new_special_pledges }.by 1 end it 'does not count appointments resulting in pledges to non-primary appeal' do expect do travel_to '2018-04-11 18:30' do create(:pledge, contact: awaiting_decision_contact, appeal: second_appeal) end end.to_not change { report.new_special_pledges } end it 'does not count pledges made before period' do expect do travel_to '2018-03-30 18:30' do create(:pledge, contact: awaiting_decision_contact, appeal: primary_appeal) end end.to_not change { report.new_special_pledges } end end describe '#monthly_increase' do it 'counts the change in monthly support' do travel_to '2018-04-11 18:30' do new_partner_contact.update(status: 'Partner - Financial') end travel_to '2018-04-11 18:31' do new_partner_contact.update(pledge_amount: 100) existing_partner_contact.update(pledge_amount: 15) end # 100 for new_partner_contact, 10 for new_financial_partner, and 5 for existing_partner_contact expect(report.monthly_increase).to eq 115 end it 'does not count changes after period' do travel_to '2018-04-11 18:30' do new_partner_contact.update(status: 'Call for Decision') end travel_to(end_date + 1.day) do new_partner_contact.update(status: 'Partner - Financial', pledge_amount: 100) existing_partner_contact.update(pledge_amount: 15) end # 10 for new_financial_partner expect(report.monthly_increase).to eq 10 end it 'converts the changed amount into account currency' do allow(CurrencyRate).to receive(:latest_for).with('DBL').and_return(0.5) allow(CurrencyRate).to receive(:latest_for).with('USD').and_return(1) travel_to '2018-04-11 18:31' do new_partner_contact.update(status: 'Partner - Financial', pledge_amount: 100, pledge_currency: 'DBL') existing_partner_contact.update(pledge_amount: 15) end # 200 for new_partner_contact, 10 for new_financial_partner, and 5 for existing_partner_contact expect(report.monthly_increase).to eq 215 end it 'counts change in currency as increase' do allow(CurrencyRate).to receive(:latest_for).with('DBL').and_return(0.5) allow(CurrencyRate).to receive(:latest_for).with('USD').and_return(1) new_financial_partner.delete travel_to '2018-04-11 18:31' do existing_partner_contact.update(pledge_currency: 'DBL') end # 10 for existing_partner_contact support doubling through conversion rate expect(report.monthly_increase).to eq 10 end it 'knows if it should count only positive or negative too' do travel_to '2018-03-19 18:30' do new_partner_contact.update(pledge_amount: 100, status: 'Partner - Financial') end travel_to '2018-04-11 18:31' do new_partner_contact.update(pledge_amount: 90) existing_partner_contact.update(pledge_amount: 0) end # 10 for new_financial_partner expect(report.monthly_increase).to eq 10 end end describe '#pledge_increase' do it 'counts the new pledges to primary appeal' do travel_to end_date.to_datetime.end_of_day do create(:pledge, contact: awaiting_decision_contact, appeal: primary_appeal, amount: 50) end expect(report.pledge_increase).to eq 50 end it 'does not count appointments resulting in pledges to non-primary appeal' do travel_to '2018-04-11 18:30' do create(:pledge, contact: awaiting_decision_contact, appeal: second_appeal) end expect(report.pledge_increase).to eq 0 end it 'does not count pledges made before and after period' do travel_to '2018-03-30 18:30' do create(:pledge, contact: awaiting_decision_contact, appeal: primary_appeal) end travel_to '2018-05-11 18:30' do create(:pledge, contact: new_partner_contact, appeal: primary_appeal) end expect(report.pledge_increase).to eq 0 end end end
chuckmersereau/api_practice
spec/validators/class_validator_spec.rb
require 'rails_helper' describe ClassValidator do subject do ClassValidator.new(attributes: [:tester], is_a: String).validate_each(record_double, :tester, record_double.tester) end context 'valid' do let(:record_double) { double(errors: { tester: [] }, tester: 'A String') } it 'does not add any errors' do subject expect(record_double.errors[:tester]).to eq [] end end context 'invalid' do let(:record_double) { double(errors: { tester: [] }, tester: ['A String inside an Array']) } it 'adds errors' do subject expect(record_double.errors[:tester]).to eq ['should be a String'] end end context 'allow_nil is unspecified' do let(:record_double) { double(errors: { tester: [] }, tester: nil) } it 'adds errors' do subject expect(record_double.errors[:tester]).to eq ['should be a String'] end end context 'allow_nil is false' do subject do ClassValidator.new(attributes: [:tester], is_a: String, allow_nil: false) .validate_each(record_double, :tester, record_double.tester) end let(:record_double) { double(errors: { tester: [] }, tester: nil) } it 'adds errors if attribute is nil' do subject expect(record_double.errors[:tester]).to eq ['should be a String'] end end context 'allow_nil is true' do subject do ClassValidator.new(attributes: [:tester], is_a: String, allow_nil: true) .validate_each(record_double, :tester, record_double.tester) end let(:record_double) { double(errors: { tester: [] }, tester: nil) } it 'does not add any errors if attributes is nil' do subject expect(record_double.errors[:tester]).to eq [] end end end
chuckmersereau/api_practice
app/policies/account_list_invite_policy.rb
<gh_stars>0 class AccountListInvitePolicy < AccountListChildrenPolicy private def resource_owner? resource.account_list == current_account_list && user.account_lists.exists?(id: current_account_list.id) end end
chuckmersereau/api_practice
spec/models/contact_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/models/contact_spec.rb require 'rails_helper' describe Contact do before { stub_smarty_streets } describe 'Validations' do subject { build(:contact) } it { is_expected.to be_valid } it { is_expected.to validate_presence_of(:account_list_id) } it { is_expected.to validate_presence_of(:name) } end let(:account_list) { create(:account_list) } let(:contact) { create(:contact, account_list: account_list) } let(:person) { create(:person) } let(:email) { create(:email_address, primary: true, person: person) } let(:person_and_email_address) do email contact.people << person end let(:mail_chimp_account) do create(:mail_chimp_account, account_list: account_list) end describe '#deletable' do let(:delete_contact) { contact.destroy } it 'should save a reference to the contact that was deleted' do expect { delete_contact }.to change { DeletedRecord.count }.by(1) end it 'should record the deleted objects details' do delete_contact record = DeletedRecord.find_by(deletable_type: 'Contact', deletable_id: contact.id) expect(record.deletable_type).to eq('Contact') expect(record.deletable_id).to eq(contact.id) expect(record.deleted_from_id).to eq(contact.account_list_id) expect(record.deleted_by_id).to eq(contact.account_list.creator_id) end end describe 'scopes' do let!(:contact_one) { create(:contact, account_list: account_list, church_name: 'Cross of Christ') } let!(:contact_two) { create(:contact, account_list: account_list, church_name: 'Calvary Chapel') } let!(:contact_three) { create(:contact, account_list: account_list, church_name: 'Harvest') } let!(:contact_four) { create(:contact, account_list: account_list, church_name: '<NAME>') } let!(:primary) { create(:address, country: 'United States', primary_mailing_address: true, addressable: contact_one) } let!(:non_primary) { create(:address, country: 'United States', primary_mailing_address: false, addressable: contact_two) } let!(:historical) { create(:address, country: 'United States', historic: true, addressable: contact_three) } let!(:non_historical) { create(:address, country: 'United States', historic: false, addressable: contact_four) } context 'primary addresses' do it 'should return only the contacts that have a primary address' do expect(Contact.primary_addresses).to include(contact_one) end it 'should not return non primary addresses' do expect(Contact.non_primary_addresses).to_not include(contact_one) end it 'should return only non primary addresses' do expect(Contact.non_primary_addresses).to include(contact_two) end end context 'historical addresses' do it 'should return only the contacts that have a historical address' do expect(Contact.historical_addresses).to include(contact_three) end it 'should not return non historical addresses' do expect(Contact.non_historical_addresses).to_not include(contact_three) end it 'should return only non historical addresses' do expect(Contact.non_historical_addresses).to include(contact_four) end end context 'church names' do it 'should return only church names and ids' do expect(Contact.list_church_names.map(&:church_name)).to eq(['Calvary Chapel', 'Cross of Christ', 'Harvest']) end it 'should search by church name' do expect(Contact.search_church_names('cross').first.church_name).to eq('Cross of Christ') end end end describe 'saving addresses' do it 'should create an address' do address = build(:address, addressable: nil) address_attributes = address.attributes.with_indifferent_access .except(:id, :addressable_id, :addressable_type, :updated_at, :created_at) expect do contact.addresses_attributes = [address_attributes] contact.save! end.to change(Address, :count).by(1) end it 'should mark an address deleted' do address = create(:address, addressable: contact) contact.addresses_attributes = [{ id: address.id, _destroy: '1' }] contact.save! expect { address.reload }.to raise_error(ActiveRecord::RecordNotFound) end it 'should update an address' do stub_request(:get, %r{https:\/\/api\.smartystreets\.com\/street-address}) .with(headers: { 'Accept' => 'application/json', 'Accept-Encoding' => 'gzip, deflate', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby' }) .to_return(status: 200, body: '[]', headers: {}) address = create(:address, addressable: contact) address_attributes = address.attributes .merge!(street: address.street + 'boo') .with_indifferent_access .except(:addressable_id, :addressable_type, :updated_at, :created_at) contact.addresses_attributes = [address_attributes] contact.save! expect(contact.addresses.first.street).to eq(address.street + 'boo') end end describe 'add_to_notes' do before do @contact = Contact.new(notes: 'Old notes') end it 'should append notes' do @contact.add_to_notes('New notes') expect(@contact.notes).to eq("Old notes \n \nNew notes") end it 'should not append notes a second time' do @contact.add_to_notes('New notes') expect(@contact.notes).to eq("Old notes \n \nNew notes") end end describe 'saving email addresses' do let!(:person) { create(:person) } let!(:email_1) { create(:email_address, primary: true, person: person) } let!(:email_2) { create(:email_address, primary: false, person: person) } before do contact.people << person end it 'should change which email address is primary' do contact_attributes = { 'people_attributes' => { '0' => { 'email_addresses_attributes' => { '0' => { 'email' => email_1.email, 'primary' => '0', '_destroy' => 'false', 'id' => email_1.id }, '1' => { 'email' => email_2.email, 'primary' => '1', '_destroy' => 'false', 'id' => email_2.id } }, 'id' => person.id } } } contact.update_attributes(contact_attributes) expect(email_1.reload.primary?).to be false expect(email_2.reload.primary?).to be true end end describe 'saving donor accounts' do it 'links to an existing donor account if one matches' do donor_account = create(:donor_account) account_list.designation_accounts << create(:designation_account, organization: donor_account.organization) donor_account_attributes = { account_number: donor_account.account_number, organization_id: donor_account.organization_id } contact.donor_accounts_attributes = { '0' => donor_account_attributes } contact.save! expect(contact.donor_accounts).to include(donor_account) end it 'creates a new donor account' do expect do contact.donor_accounts_attributes = { '0' => { account_number: 'asdf', organization_id: create(:organization).id } } contact.save! end.to change(DonorAccount, :count).by(1) end it 'updates an existing donor account' do donor_account = create(:donor_account) donor_account.contacts << contact contact.donor_accounts_attributes = { '0' => { id: donor_account.id, account_number: 'asdf' } } contact.save! expect(donor_account.reload.account_number).to eq('asdf') end it 'deletes an existing donor account' do donor_account = create(:donor_account) donor_account.contacts << contact expect do contact.donor_accounts_attributes = { '0' => { id: donor_account.id, account_number: 'asdf', _destroy: '1' } } contact.save! end.to change(ContactDonorAccount, :count).by(-1) end it 'deletes an existing donor account when posting a blank account number' do donor_account = create(:donor_account) donor_account.contacts << contact expect do contact.donor_accounts_attributes = { '0' => { id: donor_account.id, account_number: '' } } contact.save! end.to change(ContactDonorAccount, :count).by(-1) end it 'saves a contact when posting a blank donor account number' do contact.donor_accounts_attributes = { '0' => { account_number: '', organization_id: 1 } } expect(contact.save).to eq(true) end it "won't let you assign the same donor account number to two contacts" do donor_account = create(:donor_account) donor_account.contacts << contact contact2 = create(:contact, account_list: contact.account_list) expect( contact2.update(donor_accounts_attributes: { '0' => { account_number: donor_account.account_number, organization_id: donor_account.organization_id } }) ).to eq(false) end end describe 'create_from_donor_account' do before do @account_list = create(:account_list) @donor_account = create(:donor_account) end it "copies the donor account's addresses" do create(:address, addressable: @donor_account, remote_id: '1') expect do @contact = Contact.create_from_donor_account(@donor_account, @account_list) end.to change(Address, :count) expect(@contact.addresses.first.equal_to?(@donor_account.addresses.first)).to be true expect(@contact.addresses.first.source_donor_account).to eq(@donor_account) expect(@contact.addresses.first.remote_id).to eq('1') end it 'defaults the contact locale from organization locale' do @donor_account.organization.update(locale: 'fr') contact = Contact.create_from_donor_account(@donor_account, @account_list) expect(contact.locale).to eq 'fr' end end it 'should have a primary person' do person = create(:person) contact.people << person expect(contact.primary_or_first_person).to eq(person) end describe 'when being deleted' do it 'should delete people not linked to another contact' do contact.people << create(:person) expect do contact.destroy end.to change(Person, :count) end it 'should NOT delete people linked to another contact' do person = create(:person) contact.people << person contact2 = create(:contact, account_list: contact.account_list) contact2.people << person expect do contact.destroy end.to_not change(Person, :count) end it 'deletes associated addresses' do create(:address, addressable: contact) expect { contact.destroy } .to change(Address, :count).by(-1) end end describe '#update_late_at' do before do contact.late_at = 2.weeks.ago contact.pledge_start_date = Time.now.utc end context 'set to nil when' do it 'is not financial' do contact.update(status: 'Partner - Special') expect(contact.late_at).to be_nil end it 'does not have a pledge_frequency' do contact.update(pledge_frequency: nil) expect(contact.late_at).to be_nil end it 'does not have an initial date' do contact.update(last_donation_date: nil, pledge_start_date: nil) expect(contact.late_at).to be_nil end end context 'sets to appropriate late_at date when' do it 'has a pledge freqency of 0.2' do contact.update(pledge_frequency: 0.2) expect(contact.late_at).to eq contact.pledge_start_date + 1.week end it 'has a pledge freqency of 0.5' do contact.update(pledge_frequency: 0.5) expect(contact.late_at).to eq contact.pledge_start_date + 2.weeks end it 'has a pledge freqency of 2.0' do contact.update(pledge_frequency: 2.0) expect(contact.late_at).to eq contact.pledge_start_date + 2.months end end end describe '#late_by?' do it 'should tell if a monthly donor is late on their donation' do expect(contact.late_by?(2.days, 30.days)).to be true expect(contact.late_by?(30.days, 60.days)).to be false expect(contact.late_by?(60.days)).to be false end it 'should tell if an annual donor is late on their donation' do contact = create(:contact, pledge_frequency: 12.0, last_donation_date: 14.months.ago) expect(contact.late_by?(30.days, 45.days)).to be false expect(contact.late_by?(45.days)).to be true end end context '#primary_person_id=' do it 'should not fail if an invalid id is passed in' do expect do contact.primary_person_id = 0 end.not_to raise_exception end end describe '#merge' do let(:loser_contact) { create(:contact, account_list: account_list) } it 'should move all people' do contact.people << create(:person) contact.people << create(:person, first_name: 'Jill') loser_contact.people << create(:person, first_name: 'Bob') contact.merge(loser_contact) expect(contact.contact_people.size).to eq(3) end it 'should not remove the loser from prayer letters service' do pla = create(:prayer_letters_account, account_list: account_list) expect(pla).to_not receive(:delete_contact) loser_contact.addresses << create(:address, primary_mailing_address: true) loser_contact.update_columns(prayer_letters_id: 'foo', send_newsletter: 'Both') contact.merge(loser_contact) end it "should move loser's tasks" do task = create(:task, account_list: contact.account_list, subject: 'Loser task') loser_contact.tasks << task contact.tasks << create(:task, account_list: contact.account_list, subject: 'Winner task') shared_task = create(:task, account_list: contact.account_list, subject: 'Shared Task') contact.tasks << shared_task loser_contact.tasks << shared_task contact.update_uncompleted_tasks_count expect { contact.merge(loser_contact) } .to change(contact, :uncompleted_tasks_count).by(1) expect(contact.tasks).to include(task, shared_task) expect(shared_task.contacts.reload).to match_array [contact] end it "should move loser's notifications" do notification = create(:notification, contact: loser_contact) contact.merge(loser_contact) expect(contact.notifications).to include(notification) end it 'should not duplicate referrals' do referrer = create(:contact) loser_contact.contacts_that_referred_me << referrer contact.contacts_that_referred_me << referrer contact.merge(loser_contact) expect(contact.contacts_that_referred_me.length).to eq(1) end it 'should not remove the facebook account of a person on the merged contact' do loser_person = create(:person) loser_contact.people << loser_person fb = create(:facebook_account, person: loser_person) winner_person = create(:person, first_name: loser_person.first_name, last_name: loser_person.last_name) contact.people << winner_person contact.merge(loser_contact) expect(contact.people.length).to eq(1) expect(contact.people.first.facebook_accounts).to eq([fb]) end it 'should never delete a task' do task = create(:task, account_list: account_list) loser_contact.tasks << task contact.tasks << task expect do expect do contact.merge(loser_contact) end.not_to change(Task, :count) end.to change(ActivityContact, :count).by(-1) end it 'prepend notes from loser to winner' do loser_contact.notes = 'asdf' contact.notes = 'fdsa' contact.merge(loser_contact) expect(contact.notes).to eq("fdsa\nasdf") end it 'keeps winner notes if loser has none' do loser_contact.notes = nil contact.notes = 'fdsa' contact.merge(loser_contact) expect(contact.notes).to eq('fdsa') end it 'keeps loser notes if winner has none' do loser_contact.notes = 'fdsa' contact.notes = '' contact.merge(loser_contact) expect(contact.notes).to eq('fdsa') end it 'should total the donations of the contacts' do designation_account = create(:designation_account) account_list.designation_accounts << designation_account loser_contact.donor_accounts << create(:donor_account, account_number: '1') create(:donation, amount: 500.00, donor_account: loser_contact.donor_accounts.first, designation_account: designation_account) contact.donor_accounts << create(:donor_account, account_number: '2') create(:donation, amount: 300.00, donor_account: contact.donor_accounts.first, designation_account: designation_account) # Test that donation in same donor account but different designation # account not counted toward contact total. create(:donation, amount: 200.00, donor_account: contact.donor_accounts.first, designation_account: create(:designation_account)) contact.merge(loser_contact) expect(contact.total_donations).to eq(800.00) end it 'should keep the least recent first donation date' do loser_contact.first_donation_date = '2009-01-01' contact.first_donation_date = '2010-01-01' contact.merge(loser_contact) expect(contact.first_donation_date).to eq(Date.parse('2009-01-01')) end it 'should keep the most recent last donation date' do loser_contact.last_donation_date = '2010-01-01' contact.last_donation_date = '2009-01-01' contact.merge(loser_contact) expect(contact.last_donation_date).to eq(Date.parse('2010-01-01')) end it 'calls merge_people for the winner' do expect(contact).to receive(:merge_people) contact.merge(loser_contact) end end context '#destroy' do before do create(:prayer_letters_account, account_list: account_list) end it 'deletes this person from prayerletters.com if no other contact has the prayer_letters_id' do stub_request(:delete, %r{www.prayerletters.com/.*}) .to_return(status: 200, body: '', headers: {}) prayer_letters_id = 'foo' contact.prayer_letters_id = prayer_letters_id contact.send(:delete_from_letter_services) end it "DOESN'T delete this person from prayerletters.com if another contact has the prayer_letters_id" do # This spec passes because no external web call is made prayer_letters_id = 'foo' contact.update_column(:prayer_letters_id, prayer_letters_id) create(:contact, account_list: account_list, prayer_letters_id: prayer_letters_id) contact.send(:delete_from_letter_services) end end context 'without set greeting or envelope_greeting' do let(:person) { create(:person, last_name: 'Craig') } let(:spouse) { create(:person, first_name: 'Jill', last_name: 'Craig') } before do contact.people << person contact.people << spouse contact.name = "#{person.last_name}, #{person.first_name} and #{spouse.first_name}" contact.save person.save spouse.save end it 'generates a greeting' do contact.reload expect(contact['greeting']).to be_nil expect(contact.greeting).to eq(person.first_name + ' and ' + spouse.first_name) end it 'excludes deceased person from greetings' do person.reload person.deceased = true person.deceased_check person.save contact.reload expect(contact.greeting).to eq spouse.first_name expect(contact.envelope_greeting).to eq(spouse.first_name + ' ' + spouse.last_name) end it 'excludes deceased spouse from greetings' do spouse.reload spouse.deceased = true spouse.deceased_check spouse.save contact.reload expect(contact.greeting).to eq person.first_name expect(contact.envelope_greeting).to eq(person.first_name + ' ' + person.last_name) end it 'still gives name with single deceased' do spouse.destroy contact.reload expect(contact.people.count).to be 1 expect(contact.greeting).to eq person.first_name end it 'considers the spouse to be the contact with primary nil or false' do spouse.contact_people.first.update(primary: false) expect(contact.reload.spouse).to eq(spouse) spouse.contact_people.first.update(primary: nil) expect(contact.reload.spouse).to eq(spouse) spouse.contact_people.first.update(primary: true) person.contact_people.first.update(primary: false) expect(contact.reload.spouse).to eq(person) end end context '#envelope_greeting' do let(:primary) { create(:person, first_name: 'Bob', last_name: 'Jones', legal_first_name: 'Robert') } before do contact.update_attributes(greeting: 'Fred and Lori Doe', name: 'Fredrick & <NAME>') contact.people << primary end it 'uses contact name' do contact.name = '<NAME>' expect(contact.envelope_greeting).to eq 'John & <NAME>' contact.name = 'John & <NAME>' expect(contact.envelope_greeting).to eq 'John & <NAME>' contact.name = 'Smith,' expect(contact.envelope_greeting).to eq 'Smith' contact.name = 'Smith, <NAME> and <NAME>' expect(contact.envelope_greeting).to eq '<NAME> and <NAME>' contact.name = '<NAME> and Jane (Smith)' expect(contact.envelope_greeting).to eq '<NAME> and <NAME>' contact.name = '<NAME> (Jonny) and Jane' expect(contact.envelope_greeting).to eq 'John and <NAME>' contact.name = 'New Life Church' expect(contact.envelope_greeting).to eq 'New Life Church' contact.name = '<NAME> (G)' expect(contact.envelope_greeting).to eq '<NAME>' contact.name = '<NAME> (Johnny) and Janet (Jane)' expect(contact.envelope_greeting).to eq 'John and <NAME>' contact.name = '<NAME> (Johnny)' expect(contact.envelope_greeting).to eq '<NAME>' end it 'treats parens after a spouse as nickname if also in donor account name' do contact.donor_accounts << create(:donor_account, name: 'Doe, John and Janet (Jane)') contact.name = 'Doe, John and Janet (Jane)' expect(contact.envelope_greeting).to eq 'John and <NAME>' end it 'can be overwriten' do spouse = create(:person, first_name: 'Jen', last_name: 'Jones') contact.people << spouse contact.reload expect(contact.envelope_greeting).to eq('Fredrick & <NAME>') contact.update_attributes(envelope_greeting: 'Mr and Mrs Jones') contact.reload expect(contact.envelope_greeting).to eq('Mr and Mrs Jones') end it "will add last name if person doesn't have it set" do primary.update_attributes(last_name: '') contact.reload expect(contact.envelope_greeting).to eq('Fredrick & <NAME>') end end context '#merge_people' do it 'merges people with the same trimmed first and last name case insensitive' do matches = { { first_name: 'John', last_name: 'Doe' } => { first_name: 'John', last_name: 'Doe' }, { first_name: 'John ', last_name: 'Doe ' } => { first_name: 'John', last_name: 'Doe' }, { first_name: 'john', last_name: 'doe' } => { first_name: 'JOHN', last_name: 'Doe' }, { first_name: 'joHn ', last_name: 'dOe' } => { first_name: ' JOHN', last_name: ' Doe' } } matches.each do |person_attrs1, person_attrs2| Person.destroy_all contact.people << create(:person, person_attrs1) contact.people << create(:person, person_attrs2) expect do contact.merge_people end.to change(Person, :count).from(2).to(1) end non_matches = { { first_name: 'Jane', last_name: 'Doe' } => { first_name: 'John', last_name: 'Doe' } } non_matches.each do |person_attrs1, person_attrs2| Person.destroy_all contact.people << create(:person, person_attrs1) contact.people << create(:person, person_attrs2) expect do contact.merge_people end.to_not change(Person, :count).from(2) end end it 'does not error but merges if last name is nil (first name cannot be blank)' do contact.people << create(:person, first_name: 'John', last_name: nil) contact.people << create(:person, first_name: 'John', last_name: nil) expect do contact.merge_people end.to change(Person, :count).by(-1) end it 'does not error on second merge if their master person has been merged by first merge' do person1 = create(:person) person2 = create(:person) person3 = create(:person, master_person: person2.master_person) contact.people << person1 contact.people << person2 contact.people << person3 expect { contact.merge_people }.to_not raise_error end end context '#sync_with_google_contacts' do it 'calls sync contacts on the google integration' do contact # create test record so the commit callbacks aren't triggered below create(:google_integration, contacts_integration: true, calendar_integration: false, account_list: account_list, google_account: create(:google_account)) expect_any_instance_of(GoogleIntegration).to receive(:sync_data) Sidekiq::Testing.inline! { contact.send(:sync_with_google_contacts) } end end context '#sync_with_prayer_letters' do let(:pl) { create(:prayer_letters_account, account_list: account_list) } let(:address) { create(:address, primary_mailing_address: true) } before do stub_request(:get, %r{https://api\.smartystreets\.com/street-address/.*}) .to_return(body: '[]') contact.account_list.prayer_letters_account = pl contact.send_newsletter = 'Physical' contact.prayer_letters_params = pl.contact_params(contact) contact.save contact.addresses << address end it 'does not queue the update if not set to receive newsletter, but deletes' do expect(contact) .to receive(:delete_from_letter_service) .with(:prayer_letters) expect_update_queued(false) { contact.update(send_newsletter: nil) } end it 'does not queue if address missing, but deletes' do expect_any_instance_of(Contact) .to receive(:delete_from_letter_service) .with(:prayer_letters) expect_update_queued(false) { address.update(street: nil) } end it 'queues update if relevant info changed' do expect(contact.prayer_letters_params).to_not eq({}) expect_update_queued { contact.update(name: 'Not-John', greeting: 'New greeting') } end it 'queues update if queried address changed' do expect_update_queued { Address.first.update(street: 'changed') } end it 'queues update if address changed' do expect_update_queued { address.update(street: 'changed') } end xit 'does not queue update if data not changed or unrelated data changed' do # this is being skipped because it was never truly passing # we need to loop back around to see if the intended functionality is still needed expect_update_queued(false) { contact.touch } expect_update_queued(false) { contact.update(notes: 'Unrelated info') } end def expect_update_queued(queued = true) if queued expect_any_instance_of(PrayerLettersAccount).to receive(:add_or_update_contact).with(contact) else expect_any_instance_of(PrayerLettersAccount).to_not receive(:add_or_update_contact).with(contact) end yield end end context '#sync_with_mail_chimp' do context 'with mail_chimp account' do let(:contact) { create(:contact, account_list: account_list, send_newsletter: 'Email') } let!(:mail_chimp_account) do create(:mail_chimp_account, account_list: account_list, primary_list_id: 'primary_list_id') end before do person_and_email_address contact.tag_list.add('example_tag') contact.save end it 'notifies the mail chimp account of changes on certain fields' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [contact.id] ) contact.locale = 'en-US' contact.save! end it 'notifies the mail chimp account of changes on certain nested fields' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [contact.id] ) contact.people.first.primary_email_address.email = '<EMAIL>' contact.save! end it 'notifies the mail chimp account of changes when tags are added' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [contact.id] ) contact.tag_list.add('second_example_tag') contact.save! end it 'notifies the mail chimp account of changes when tags are removed' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [contact.id] ) contact.tag_list.remove('example_tag') contact.save! end it 'notifies the mail chimp account when a person is opted out' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [] ) contact.people.first.optout_enewsletter = true contact.save! end it 'does not notify the mail chimp account of changes on certain fields' do expect(MailChimp::ExportContactsWorker).not_to receive(:perform_async) contact.timezone = 'PST' contact.save! end it 'does not notify the mail chimp account if contact is not in scope' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [] ) contact.update(send_newsletter: 'None', status: 'Never Ask') end end context 'without mail_chimp_account' do it 'does not error if there is no mail chimp account' do expect { contact.send(:sync_with_mail_chimp) }.to_not raise_error end end end describe 'donation methods' do let!(:da) { create(:designation_account) } let!(:account_list) { create(:account_list) } let!(:organization) { create(:organization, gift_aid_percentage: 25) } let!(:donor_account) { create(:donor_account, organization: organization) } let!(:contact) { create(:contact, account_list: account_list) } let!(:donation) { create(:donation, donor_account: donor_account, designation_account: da) } let(:old_donation) do create(:donation, donor_account: donor_account, designation_account: da, donation_date: Date.today << 3) end let(:gift_aid_donation) do create(:donation, donor_account: donor_account, designation_account: da, payment_method: 'Gift Aid', amount: 2.50) end before do account_list.account_list_entries.create!(designation_account: da) contact.donor_accounts << donor_account contact.update_donation_totals(donation) contact.update_donation_totals(old_donation) end context '#designated_donations' do it 'gives donations whose designation is connected to the contact account list' do expect(contact.donations.to_a).to eq([donation, old_donation]) donation.update(designation_account: nil) old_donation.update(donor_account: nil) expect(contact.donations).to be_empty end end context '#last_donation' do it 'returns the latest designated donation' do old_donation expect(contact.last_donation).to eq(donation) donation.update(designation_account: nil) expect(contact.last_donation).to eq(old_donation) end end context '#last_six_donations' do it 'returns the lastest six donations' do create_list(:donation, 7, donor_account: donor_account, designation_account: da) expect(contact.last_six_donations).to eq(contact.donations.first(6)) end end context '#last_monthly_total' do it 'returns zero with no error if there are no donations' do Donation.destroy_all contact.update(last_donation_date: nil) expect(contact.last_monthly_total).to eq(0) end it 'returns the total of the current month if it has a donation' do expect(contact.last_monthly_total).to eq(9.99.round(2)) end it 'returns the total of the previous month if current month has no donations' do contact.update(last_donation_date: nil) donation.update(donation_date: Date.today << 1) old_donation.update(donation_date: Date.today << 1) contact.update_donation_totals(donation) contact.update_donation_totals(old_donation) expect(contact.last_monthly_total).to eq((9.99 * 2).round(2)) end it 'returns zero if the previous and current months have no donations' do contact.update(last_donation_date: nil) donation.update(donation_date: Date.today << 2) old_donation.update(donation_date: Date.today << 2) contact.update_donation_totals(donation) contact.update_donation_totals(old_donation) expect(contact.last_monthly_total).to eq(0) end end context '#prev_month_donation_date' do it 'returns nil if there are no donations' do Donation.destroy_all expect(contact.prev_month_donation_date).to be_nil contact.update(last_donation_date: nil) expect(contact.prev_month_donation_date).to be_nil end it 'returns the donation date of the donation before this month if this month has donations' do expect(contact.prev_month_donation_date).to eq(old_donation.donation_date) end it 'returns the donation date of the donation before last month if this month has no donations' do contact.update(last_donation_date: nil) donation.update(donation_date: Date.today << 1) contact.update_donation_totals(donation) expect(contact.prev_month_donation_date).to eq(old_donation.donation_date) end end context '#current_monthly_avg' do it 'looks at the current donation only including the previous gift' do old_donation.update(amount: 3) expect(contact.monthly_avg_current).to eq(9.99) end end context '#recent_monthly_avg' do it 'uses time between donations to calculate average' do expect(contact.monthly_avg_with_prev_gift).to eq(9.99 / 2) end it 'considers pledge frequency in the average' do contact.update(pledge_frequency: 12) expect(contact.monthly_avg_with_prev_gift).to eq(9.99 * 2 / 12) end it 'averages correctly even if there are multiple contact donor account records' do create(:contact_donor_account, contact: contact, donor_account: donor_account) expect(contact.monthly_avg_with_prev_gift).to eq(9.99 / 2) end it 'averages including all donations in the previous donation month' do old_donation.update(donation_date: old_donation.donation_date.end_of_month) create(:donation, donor_account: donor_account, designation_account: da, donation_date: old_donation.donation_date.beginning_of_month) expect(contact.monthly_avg_with_prev_gift).to eq(9.99 * 3 / 4) end end context '#monthly_avg_from' do it 'sums donations from date to current (or previous) month, goes back by pledge frequency multiple' do expect(contact.monthly_avg_from(Date.today)).to eq(9.99) expect(contact.monthly_avg_from(Date.today << 2)).to eq(9.99 / 3) expect(contact.monthly_avg_from(Date.today << 3)).to eq(9.99 / 2) contact.update(pledge_frequency: 3) expect(contact.monthly_avg_from(Date.today)).to eq(9.99 / 3) expect(contact.monthly_avg_from(Date.today << 2)).to eq(9.99 / 3) expect(contact.monthly_avg_from(Date.today << 3)).to eq(9.99 * 2 / 6) end it 'sums donations correctly when given a except_payment_method argument' do gift_aid_donation expect(contact.monthly_avg_from(Date.today)).to eq(12.49) expect(contact.monthly_avg_from(Date.today, except_payment_method: 'Gift Aid')).to eq(9.99) end end context '#months_from_prev_to_last_donation' do it 'gives the months elapsed between the last donation and the last donation in a previous month' do expect(contact.months_from_prev_to_last_donation).to eq(3) end end end context '#find_timezone' do it 'returns nil if the contact has no primary address' do expect(contact.find_timezone).to be_nil end it 'retrieves the master address timezone if there is a primary address' do address = build(:address) allow(contact).to receive(:primary_or_first_address) { address } expect(address.master_address).to receive(:find_timezone).and_return('EST') expect(contact.find_timezone).to eq 'EST' end end context '#update_all_donation_totals' do it 'sets the total_donations field to its query result' do expect(contact).to receive(:total_donations_query) { 5 } contact.update_all_donation_totals expect(contact.reload.total_donations).to eq 5 end end context '#total_donations_query' do it 'sums the donations for the contact' do designation_account = create(:designation_account) account_list.designation_accounts << designation_account donor_account = create(:donor_account) contact.donor_accounts << donor_account create(:donation, amount: 5, donor_account: donor_account, designation_account: designation_account) # It shouldn't count this donation since it has no designation create(:donation, amount: 10, donor_account: donor_account) expect(contact.total_donations_query).to eq 5 end end context '#mailing_address' do it 'gives a new address if contact only has a historic address' do contact.addresses << create(:address, street: '1', historic: true) expect(contact.mailing_address.street).to be_nil end end context '#reload_mailing_address' do it 'does not error if contact has no addresses' do expect { create(:contact).reload_mailing_address }.to_not raise_error end it 'returns the reloaded mailing address' do contact = build(:contact) address = build(:address) contact.addresses << address expect(contact.reload_mailing_address).to eq address end end context '#pledge_currency_symbol' do context 'with account_list#currency ""' do it 'returns default currency' do account_list.update(currency: '') expect(contact.pledge_currency_symbol).to eq '$' end end context 'with account list currency not in twitter list' do it 'returns currency string' do # Some currencies come in from data server with their # non-official labels, e.g. Kenyan shillings are officially KES, but # may come in as KSH (which doesn't exist in the Twitter list) account_list.update(currency: 'KSH') allow(TwitterCldr::Shared::Currencies) .to receive(:for_code).with('KSH') { nil } expect(contact.pledge_currency_symbol).to eq 'KSH' end end end context '#pledge_amount=' do it 'stores the right value even with a comma' do contact.update(pledge_amount: '100,000.00') expect(contact.pledge_amount).to eq(100_000.0) contact.update(pledge_amount: '100.00') expect(contact.pledge_amount).to eq(100.0) end it 'stores the right value even with a comma when written in a spanish way' do contact.update(pledge_amount: '100.000,00') expect(contact.pledge_amount).to eq(100_000.0) contact.update(pledge_amount: '100,00') expect(contact.pledge_amount).to eq(100.0) end end context '#mail_chimp_open_rate' do before do stub_request(:get, 'https://us4.api.mailchimp.com/3.0/') .to_return(status: 200, body: '', headers: {}) email_hash = Digest::MD5.hexdigest(email.email.downcase) member_url = "https://us4.api.mailchimp.com/3.0/lists/MyString/members/#{email_hash}" stub_request(:get, member_url) .to_return(status: 200, body: { 'stats' => { 'avg_open_rate' => 89 } }.to_json, headers: {}) end it 'returns the open rate of the contact retrieved from Mail Chimp' do mail_chimp_account person_and_email_address expect(contact.mail_chimp_open_rate).to eq(89) end end describe 'accepts nested attributes for contact referrals' do let!(:attributes) do { contacts_referred_by_me_attributes: [ { account_list_id: contact.account_list_id, name: 'First Referral Name', primary_person_first_name: 'Primary Person First Name', primary_person_last_name: 'Primary Person Last Name', spouse_first_name: 'Spouse First Name', spouse_last_name: 'Spouse Last Name', primary_address_street: 'Primary Address Street' }, { account_list_id: contact.account_list_id, name: 'Second Referral Name', primary_person_first_name: 'Second Referral Primary Person First Name', primary_person_last_name: 'Second Referral Primary Person Last Name', spouse_first_name: 'Second Referral Spouse First Name', spouse_last_name: 'Second Referral Spouse Last Name', primary_address_street: 'Second Referral Primary Address Street' } ] } end it 'does not save an invalid contact' do contact.assign_attributes(contacts_referred_by_me_attributes: [{ name: '' }]) expect { contact.save! && contact.reload }.to_not change { Contact.count + Person.count + Address.count } end it 'creates new contacts' do contact.assign_attributes( contacts_referred_by_me_attributes: [ { name: 'A Contact', account_list_id: contact.account_list_id }, { name: 'Another Contact', account_list_id: contact.account_list_id } ] ) expect { contact.save! && contact.reload }.to change { contact.contacts_referred_by_me.count }.from(0).to(2) .and change { Contact.count }.by(2) .and change { Person.count }.by(0) .and change { Address.count }.by(0) end it 'creates new contacts, with people and address' do contact.assign_attributes(attributes) expect { contact.save! && contact.reload }.to change { contact.contacts_referred_by_me.count }.from(0).to(2) .and change { Contact.count }.by(2) .and change { Person.count }.by(4) .and change { Address.count }.by(2) referred_contact = Contact.find(contact.id).contacts_referred_by_me.order(:created_at).first expect(referred_contact.name).to eq 'First Referral Name' expect(referred_contact.primary_person.first_name).to eq 'Primary Person First Name' expect(referred_contact.primary_person.last_name).to eq 'Primary Person Last Name' expect(referred_contact.spouse.first_name).to eq 'Spouse First Name' expect(referred_contact.spouse.last_name).to eq 'Spouse Last Name' expect(referred_contact.primary_address.street).to eq 'Primary Address Street' end it 'updates existing contacts, and their people and address' do contact.update!(attributes) && contact.reload referred_contact_id = contact.contacts_referred_by_me.first.id contact.update!(contacts_referred_by_me_attributes: [{ id: referred_contact_id, account_list_id: contact.account_list_id, name: '<NAME>', primary_person_first_name: 'My New First Name', spouse_first_name: '<NAME>', primary_address_street: 'My New Street' }]) referred_contact = Contact.find(referred_contact_id) expect(referred_contact.name).to eq 'New Contact Name' expect(referred_contact.primary_person.first_name).to eq '<NAME>' expect(referred_contact.spouse.first_name).to eq '<NAME> First Name' expect(referred_contact.primary_address.street).to eq 'My New Street' end it 'does not allow destroy' do contact.update!(attributes) && contact.reload referred_contact_id = contact.contacts_referred_by_me.first.id expect do contact.update!(contacts_referred_by_me_attributes: [{ id: referred_contact_id, account_list_id: contact.account_list_id, _destroy: '1' }]) end.to_not change { contact.reload && contact.contacts_referred_by_me.count } end end it 'delegated readers should not cause new associated records to be created' do contact = Contact.create!(name: 'Tester', account_list_id: create(:account_list).id) expect(ContactPerson.where(contact_id: contact.id).count).to eq 0 expect(Address.where(addressable_type: 'Contact', addressable_id: contact.id).count).to eq 0 contact.spouse_first_name contact.primary_person_first_name contact.primary_address_street contact.save! expect(ContactPerson.where(contact_id: contact.id).count).to eq 0 expect(Address.where(addressable_type: 'Contact', addressable_id: contact.id).count).to eq 0 end describe '#monthly_pledge' do let(:contact) { build(:contact) } context 'with a positive pledge_frequency' do before { contact.pledge_frequency = 10 } context 'when pledge_amount is nil or negative' do it 'is 0' do contact.pledge_amount = nil expect(contact.monthly_pledge).to eq 0 contact.pledge_amount = 0 expect(contact.monthly_pledge).to eq 0 contact.pledge_amount = -1 expect(contact.monthly_pledge).to eq 0 end end context 'when pledge_amount is positive' do it 'is the correct value' do contact.pledge_amount = 100 expect(contact.monthly_pledge).to eq 10.00 end end end context 'with a positive pledge_amount' do before { contact.pledge_amount = 10 } context 'when pledge_frequency is nil or negative' do it 'is defaults to monthly, ie: (pledge_amount / 1)' do contact.pledge_frequency = nil expect(contact.monthly_pledge).to eq 10.0 contact.pledge_frequency = 0 expect(contact.monthly_pledge).to eq 10.0 contact.pledge_frequency = -1 expect(contact.monthly_pledge).to eq 10.0 end end context 'when pledge_frequency is positive' do it 'is the correct value' do contact.pledge_frequency = 2 # every 2 months expect(contact.monthly_pledge).to eq 5.00 end end end context '#create_people_from_contact' do it 'seperates contact name into primary person and spouse when applicable' do expect do contact.name = '<NAME> Mary' contact.send(:create_people_from_contact) end.to change { Person.count }.by(2) end it 'does not separate a contact name when "and" is part of a word' do expect do contact.name = '<NAME>' contact.send(:create_people_from_contact) end.to change { Person.count }.by(1) end end context '#pledge_currency_symbol' do it 'returns the currency symbol regardless of if the pledge currency is upcased or not' do contact.pledge_currency = 'USD' expect(contact.pledge_currency_symbol).to eq '$' contact.pledge_currency = 'usd' expect(contact.pledge_currency_symbol).to eq '$' end end end context '#amount_with_gift_aid' do let!(:contact_with_gift_aid_organization) { create(:contact) } let!(:organization) { create(:organization, gift_aid_percentage: 25) } let!(:donor_account) do create(:donor_account, account_number: 'unique_number', organization: organization, contacts: [contact_with_gift_aid_organization]) end it 'returns the amount with gift aid added when applicable' do contact_with_gift_aid_organization.no_gift_aid = true expect(contact_with_gift_aid_organization.amount_with_gift_aid(100.00)).to eq(100.00) end it 'does not returns the amount with gift aid added when no_gift_aid is set to true' do expect(contact_with_gift_aid_organization.amount_with_gift_aid(100.00)).to eq(125.00) end end describe '#set_status_confirmed_at' do let!(:contact) { create(:contact) } it 'changes status_confirmed_at to the current time if it changed from false to true' do contact.update!(status_valid: false) contact.reload travel_to Time.current do expect do contact.status_valid = true contact.save! end.to change { contact.reload.status_confirmed_at }.from(nil).to(Time.current) end end it 'does not change status_confirmed_at if status_valid was not changed' do expect do contact.name = 'Testing' contact.save end.to_not change { contact.reload.status_confirmed_at }.from(nil) end it 'does not change status_confirmed_at if status_valid was previously true' do contact = create(:contact, status_valid: true) expect(contact.status_valid).to eq(true) expect do contact.status_valid = nil contact.save end.to_not change { contact.reload.status_confirmed_at }.from(nil) contact = create(:contact, status_valid: true) expect(contact.status_valid).to eq(true) expect do contact.status_valid = false contact.save end.to_not change { contact.reload.status_confirmed_at }.from(nil) end it 'does not change status_confirmed_at if status_valid was previously nil' do contact = create(:contact) expect(contact.status_valid).to eq(nil) expect do contact.status_valid = false contact.save end.to_not change { contact.reload.status_confirmed_at }.from(nil) contact = create(:contact) expect(contact.status_valid).to eq(nil) expect do contact.status_valid = true contact.save end.to_not change { contact.reload.status_confirmed_at }.from(nil) end it 'does not change status_confirmed_at if not changing to true' do contact = create(:contact, status_valid: false) expect(contact.status_valid).to eq(false) expect do contact.status_valid = nil contact.save end.to_not change { contact.reload.status_confirmed_at }.from(nil) contact = create(:contact, status_valid: false) expect(contact.status_valid).to eq(false) expect do contact.status_valid = false contact.save end.to_not change { contact.reload.status_confirmed_at }.from(nil) end end end
chuckmersereau/api_practice
lib/google_contact_sync.rb
module GoogleContactSync MAX_SYNCED_ADDRESSES = 10 module_function def sync_contact(contact, g_contacts_and_links) g_contacts = g_contacts_and_links.map(&:first) g_contact_links = g_contacts_and_links.map(&:second) contact.people.each do |person| index = g_contact_links.find_index { |link| link.person_id == person.id } g_contact_link = g_contact_links[index] g_contact = g_contacts[index] g_contact_link.last_data[:emails] ||= [] g_contact_link.last_data[:addresses] ||= [] g_contact_link.last_data[:phone_numbers] ||= [] g_contact_link.last_data[:websites] ||= [] sync_with_g_contact(person, g_contact, g_contact_link) end sync_addresses(g_contacts, contact, g_contact_links) g_contacts_and_links.each do |g_contact_and_link| g_contact, g_contact_link = g_contact_and_link sync_notes(contact, g_contact, g_contact_link) end end def sync_with_g_contact(person, g_contact, g_contact_link) sync_basic_person_fields(person, g_contact, g_contact_link) sync_employer_and_title(person, g_contact, g_contact_link) sync_emails(g_contact, person, g_contact_link) sync_numbers(g_contact, person, g_contact_link) sync_websites(g_contact, person, g_contact_link) end def sync_notes(contact, g_contact, g_contact_link) sync_g_contact_and_record(contact, g_contact, g_contact_link, notes: :content) end def sync_basic_person_fields(person, g_contact, g_contact_link) sync_g_contact_and_record(person, g_contact, g_contact_link, first_name: :given_name, last_name: :family_name) end def sync_g_contact_and_record(record, g_contact, g_contact_link, field_map) field_map.each do |field, g_contact_field| synced_value = compare_field_for_sync(record[field], g_contact.send(g_contact_field), g_contact_link.last_data[g_contact_field]) # Replace vertical tabs with newlines in both MPDX and Google Contact as vertical tabs are invalid XML and # will get escaped to newlines by the google_contacts_api gem. # By fixing them in MPDX as well, we make the values the same to simplify future syncs. synced_value&.tr!("\v", "\n") g_contact.prep_changes(g_contact_field => synced_value) if synced_value != g_contact.send(g_contact_field) record[field] = synced_value if field == :first_name && record[field].nil? record[field] = 'Unknown' # MPDX doesn't allow blank first names log_missing_name_info(record, g_contact, g_contact_link, field_map) end end end def log_missing_name_info(record, g_contact, g_contact_link, field_map) Rails.logger.error("Google sync missing first name:\n"\ " record.attributes: #{record.attributes}\n "\ " google_contact: #{g_contact.to_hash}\n "\ " last_data: #{g_contact_link.last_data}\n "\ " field_map: #{field_map}") end def sync_employer_and_title(person, g_contact, g_contact_link) g_contact_orgs = g_contact.organizations last_orgs = g_contact_link.last_data[:organizations] || [] # Since in the Google Contacts user interface you can only set the title and org name for a # single organization it's a reasonable assumption to just look at the first organization employer = compare_field_for_sync(person.employer, field_of_first(g_contact_orgs, :org_name), field_of_first(last_orgs, :org_name)) occupation = compare_field_for_sync(person.occupation, field_of_first(g_contact_orgs, :org_title), field_of_first(last_orgs, :org_title)) person.employer = employer person.occupation = occupation if field_of_first(g_contact_orgs, :org_name) != employer || field_of_first(g_contact_orgs, :org_title) != occupation g_contact.prep_changes(organizations: g_contact_organizations_for(employer, occupation)) end end def compare_field_for_sync(mpdx_val, g_contact_val, last_val) mpdx_changed = mpdx_val != last_val && (mpdx_val.present? || last_val.present?) if mpdx_changed # If MPDX changed, the synced value is the MPDX "wins" if both MPDX and Google were changed mpdx_val else # Otherwise the synced value should be the Google value in case it changed. g_contact_val end end def field_of_first(hashes, field) hashes.empty? ? nil : hashes.first[field] end def sync_emails(g_contact, person, g_contact_link) sync_items(g_contact, person, g_contact_link, compare_fn: :compare_emails_for_sync, mpdx_add_fn: :add_emails_from_g_contact, google_format_fn: :format_email_for_google, normalize_fn: :normalize_email, person_items: :email_addresses, person_item_key: :email, g_contact_items: :emails_full, g_contact_item_key: :address, g_contact_assign: :emails) end def sync_numbers(g_contact, person, g_contact_link) sync_items(g_contact, person, g_contact_link, compare_fn: :compare_numbers_for_sync, mpdx_add_fn: :add_numbers_from_g_contact, google_format_fn: :format_phone_for_google, normalize_fn: :normalize_number, person_items: :phone_numbers, person_item_key: :number, g_contact_items: :phone_numbers_full, g_contact_item_key: :number, g_contact_assign: :phone_numbers) end def sync_websites(g_contact, person, g_contact_link) sync_items(g_contact, person, g_contact_link, compare_fn: :compare_websites_for_sync, mpdx_add_fn: :add_websites_from_g_contact, google_format_fn: :format_website_for_google, normalize_fn: :normalize_website, person_items: :websites, person_item_key: :url, g_contact_items: :websites, g_contact_item_key: :href, g_contact_assign: :websites) end def normalize_website(website) website.strip.downcase end def normalize_email(email) email.strip.downcase end def sync_items(g_contact, person, g_contact_link, opts) # Compare the items for sync mpdx_adds, mpdx_dels, g_contact_adds, g_contact_dels = send(opts[:compare_fn], g_contact, person, g_contact_link) # Add and delete the MPDX items send(opts[:mpdx_add_fn], mpdx_adds, g_contact, person) person_items = person.send(opts[:person_items]).to_a person_items.each do |item| item.mark_for_destruction if mpdx_dels.include?(send(opts[:normalize_fn], item.send(opts[:person_item_key]))) end update_g_contact_items(g_contact, g_contact_adds, g_contact_dels, opts, person_items) end def update_g_contact_items(g_contact, g_contact_adds, g_contact_dels, opts, person_items) g_contact_items = g_contact.send(opts[:g_contact_items]) g_contact_items += g_contact_adds.map do |item_key| person_item = person_items.find { |p_i| send(opts[:normalize_fn], p_i.send(opts[:person_item_key])) == item_key } send(opts[:google_format_fn], person_item) end g_contact_items.delete_if do |item| item_key = send(opts[:normalize_fn], item[opts[:g_contact_item_key]]) g_contact_dels.include?(item_key) end g_contact.prep_changes(opts[:g_contact_assign] => ensure_single_primary(g_contact_items)) end def ensure_single_primary(items) found_primary = false items.each do |item| if found_primary item[:primary] = false else found_primary = item[:primary] end end end def sync_addresses(g_contacts, contact, g_contact_links) g_contact_addresses = g_contacts.flat_map(&:addresses).to_set last_addresses = g_contact_links.flat_map { |g_contact_link| g_contact_link.last_data[:addresses] }.to_set mpdx_adds, mpdx_dels, g_contact_adds, g_contact_dels, g_contact_address_records = compare_addresses_for_sync(g_contact_addresses, contact, last_addresses) # Add and delete MPDX address records add_addresses_from_g_contact(mpdx_adds, contact) contact.addresses.each { |a| a.mark_for_destruction if mpdx_dels.include?(a.master_address_id) } # Build the Google Contact address list and assign it to all Google contacts g_contact_address_records = remove_duplicate_addresses(g_contact_address_records) + g_contact_adds g_contact_address_records.delete_if { |address| g_contact_dels.include?(address.master_address_id) } ensure_single_primary_address(g_contact_address_records) g_contact_addresses = g_contact_address_records.map { |address| format_address_for_google(address) } g_contacts.each { |g_contact| g_contact.prep_changes(addresses: g_contact_addresses.to_a) } end def remove_duplicate_addresses(addresses) addresses.map(&:master_address_id).to_set.map do |master_address_id| lookup_by_key(addresses, master_address_id: master_address_id) end end def ensure_single_primary_address(addresses) found_primary = false addresses.each do |address| next unless address.primary_mailing_address if found_primary address.primary_mailing_address = false else found_primary = true end end end def add_addresses_from_g_contact(addresses, contact) contact_primary = contact.addresses.where(primary_mailing_address: true) addresses.each do |address| address.primary_mailing_address = false if contact_primary next if empty_address?(address) contact.addresses << address end end def empty_address?(address) address.attributes.slice('street', 'city', 'state', 'postal_code') == { 'street' => nil, 'city' => nil, 'state' => nil, 'postal_code' => nil } end def add_emails_from_g_contact(emails_to_add, g_contact, person) had_primary = person.primary_email_address.present? g_contact_emails_normalized_map = Hash[g_contact.emails_full.map do |email| [normalize_email(email[:address]), email] end] emails_to_add.each do |email| email_attrs = format_email_for_mpdx(g_contact_emails_normalized_map[email]) email_attrs[:primary] = false if had_primary person.email_address = email_attrs end end def add_numbers_from_g_contact(numbers_to_add, g_contact, person) g_contact_numbers_normalized_map = Hash[g_contact.phone_numbers_full.map do |number| [normalize_number(number[:number]), number] end] had_primary = person.primary_phone_number.present? numbers_to_add.each do |number| number_attrs = format_phone_for_mpdx(g_contact_numbers_normalized_map[number]) if had_primary number_attrs[:primary] = false else had_primary = number_attrs[:primary] end person.phone_number = number_attrs end end def add_websites_from_g_contact(urls_to_add, g_contact, person) had_primary = person.websites.where(primary: true).first g_contact_websites_normalized_map = Hash[g_contact.websites.map do |website| [normalize_website(website[:href]), website] end] urls_to_add.each do |url| g_contact_website = g_contact_websites_normalized_map[url] website = Person::Website.new(url: g_contact_website[:href], primary: g_contact_website[:primary]) if had_primary website[:primary] = false else had_primary = website[:primary] end person.websites << website end end def compare_websites_for_sync(g_contact, person, g_contact_link) last_sync_websites = g_contact_link.last_data[:websites].map { |websites| websites[:href] } compare_normalized_for_sync(last_sync_websites, person.websites.pluck(:url), g_contact.websites.map { |w| w[:href] }, method(:normalize_website)) end def compare_emails_for_sync(g_contact, person, g_contact_link) last_sync_emails = g_contact_link.last_data[:emails].map { |email| email[:address] } compare_normalized_for_sync(last_sync_emails, person.email_addresses.where(historic: false).pluck(:email), g_contact.emails, method(:normalize_email), person.email_addresses.where(historic: true).pluck(:email)) end def compare_numbers_for_sync(g_contact, person, g_contact_link) last_sync_numbers = g_contact_link.last_data[:phone_numbers].map { |p| p[:number] } current_numbers = person.phone_numbers.where(historic: false).pluck(:number) historic_numbers = person.phone_numbers.where(historic: true).pluck(:number) compare_normalized_for_sync(last_sync_numbers, current_numbers, g_contact.phone_numbers, method(:normalize_number), historic_numbers) end def compare_addresses_for_sync(g_contact_addresses, contact, last_addresses) compare_address_records(g_contact_addresses.map(&method(:new_address_for_g_address)), contact, last_addresses.map(&method(:new_address_for_g_address))) end def compare_address_records(g_contact_address_records, contact, last_address_records) # Compare normalized addresses (by master_address_id) mpdx_adds, mpdx_dels, g_contact_adds, g_contact_dels = compare_normalized_for_sync(last_address_records, contact.addresses.where(historic: false), g_contact_address_records, method(:normalize_address), contact.addresses.where(historic: true)) # Convert from the master_address_id back to entries in addresses lists (except for g_contact_dels) [ mpdx_adds.map { |master_id| lookup_by_key(g_contact_address_records, master_address_id: master_id) }, mpdx_dels, contact.addresses.where(master_address_id: g_contact_adds.to_a).limit(MAX_SYNCED_ADDRESSES), g_contact_dels, g_contact_address_records ] end def normalize_number(number) phonelib = Phonelib.parse(number) phonelib ? phonelib.e164 : number end def new_address_for_g_address(g_addr) Address.new(street: g_addr[:street], city: g_addr[:city], state: g_addr[:region], postal_code: g_addr[:postcode], country: g_addr[:country] == 'United States of America' ? 'United States' : g_addr[:country], location: address_rel_to_location(g_addr[:rel]), primary_mailing_address: g_addr[:primary]) end def normalize_address(address) address.find_or_create_master_address unless address.master_address_id raise "No master_address_id for address: #{address}" unless address.master_address_id address.master_address_id end def compare_normalized_for_sync(last_sync_list, mpdx_list, g_contact_list, normalize_fn, historic_list = []) compare_considering_historic( last_sync_list.map(&normalize_fn).select(&:present?), mpdx_list.map(&normalize_fn).select(&:present?), g_contact_list.map(&normalize_fn).select(&:present?), historic_list.map(&normalize_fn).select(&:present?) ) end def compare_considering_historic(last_sync_list, mpdx_list, g_contact_list, historic_list) historic = historic_list.to_set mpdx_adds, mpdx_dels, g_contact_adds, g_contact_dels = compare_for_sync(last_sync_list, mpdx_list, g_contact_list) # Don't add/delete MPDX's historic items, don't add them to Google, # but do delete them from Google [mpdx_adds - historic, mpdx_dels - historic, g_contact_adds - historic, g_contact_dels + historic] end def compare_for_sync(last_sync_list, mpdx_list, g_contact_list) last_sync_set = last_sync_list.to_set mpdx_set = mpdx_list.to_set g_contact_set = g_contact_list.to_set # These sets represent what MPDX and Google Contacts added or deleted since the last sync mpdx_added = mpdx_set - last_sync_set g_contact_added = g_contact_set - last_sync_set mpdx_deleleted = last_sync_set - mpdx_set g_contact_deleleted = last_sync_set - g_contact_set # These sets represent what MPDX and Google Contacts need to add or delete to get in sync again # Basically, you just propgate the added/deleted entries from one to the other, but we also # subtract out the entries that system already added or deleted on its own. # # An update simply becomes an add and a delete and both are propagated. # Thus a conflicting update will result in both systems preserving the two new values and # deleting the old value. This preserves the user's intention across systems and allows them to # then delete the incorrect conflicted value (or just keep both if they're both correct). mpdx_to_add = g_contact_added - mpdx_added g_contact_to_add = mpdx_added - g_contact_added mpdx_to_delete = g_contact_deleleted - mpdx_deleleted g_contact_to_delete = mpdx_deleleted - g_contact_deleleted [mpdx_to_add, mpdx_to_delete, g_contact_to_add, g_contact_to_delete] end def lookup_by_key(hashes_list, search_key_value) key = search_key_value.keys[0] value = search_key_value.values[0] hashes_list.find { |hash| hash[key] == value } end def g_contact_organizations_for(employer, occupation) if employer.present? || occupation.present? [{ org_name: employer, org_title: occupation, primary: true, rel: 'work' }] else [] end end def format_email_for_mpdx(email) { email: email[:address], primary: email[:primary], location: email[:rel] } end def format_email_for_google(email) { primary: email.primary, rel: email.location.in?(%w(work home)) ? email.location : 'other', address: email.email } end def format_phone_for_mpdx(phone) { number: phone[:number], location: phone[:rel] } end def format_phone_for_google(phone) number = phone.number phonelib = Phonelib.parse(number) if phonelib number = phonelib.country_code == '1' ? phonelib.local_number : phonelib.e164 end # From https://developers.google.com/gdata/docs/2.0/elements#gdPhoneNumber allowed_rels = %w(assistant callback car company_main fax home home_fax isdn main mobile other other_fax pager radio telex tty_tdd work work_fax work_mobile work_pager) { number: number, primary: phone.primary, rel: phone.location.in?(allowed_rels) ? phone.location : 'other' } end def format_website_for_google(website) { href: website.url, primary: website.primary, rel: 'other' } end def format_address_for_google(address) { rel: address_location_to_rel(address.location), primary: address.primary_mailing_address, street: address.street, city: address.city, region: address.state, postcode: address.postal_code, country: address.country == 'United States' ? 'United States of America' : address.country } end def address_location_to_rel(location) if location == 'Business' 'work' elsif location == 'Home' 'home' else 'other' end end def address_rel_to_location(rel) if rel == 'work' 'Business' elsif rel == 'home' 'Home' else 'Other' end end end
chuckmersereau/api_practice
db/migrate/20170918022824_create_background_batch_requests.rb
<filename>db/migrate/20170918022824_create_background_batch_requests.rb class CreateBackgroundBatchRequests < ActiveRecord::Migration def change create_table :background_batch_requests do |t| t.belongs_to :background_batch, index: true, foreign_key: true t.string :path t.string :request_params t.string :request_body t.string :request_headers t.string :request_method, default: 'GET' t.string :response_headers t.string :response_body t.string :response_status t.integer :status, default: 0 t.boolean :default_account_list, default: false t.uuid :uuid, null: false, index: true, default: 'uuid_generate_v4()' t.timestamps null: false end end end
chuckmersereau/api_practice
spec/factories/deleted_records.rb
FactoryBot.define do factory :deleted_record do deleted_at Date.current - 1.day deleted_from { |a| a.association(:account_list) } deleted_by { |a| a.association(:person) } deletable { |a| a.association(:contact) } end factory :deleted_task_record, parent: :deleted_record do deleted_at Date.current - 1.day deleted_from { |a| a.association(:account_list) } deleted_by { |a| a.association(:person) } deletable { |a| a.association(:task) } end factory :deleted_donation_record, parent: :deleted_record do deleted_at Date.current deleted_from { |a| a.association(:designation_account) } deleted_by { |a| a.association(:person) } deletable { |a| a.association(:donation) } end end
chuckmersereau/api_practice
config/initializers/json_api_service.rb
<filename>config/initializers/json_api_service.rb require 'json_api_service' JsonApiService.configure do |config| config.custom_references = { background_batch_requests: 'BackgroundBatch::Request', comments: 'ActivityComment', facebook_accounts: 'Person::FacebookAccount', google_accounts: 'Person::GoogleAccount', key_accounts: 'Person::KeyAccount', linkedin_accounts: 'Person::LinkedinAccount', organization_accounts: 'Person::OrganizationAccount', primary_appeals: 'Appeal', salary_organization_id: 'Organization', twitter_accounts: 'Person::TwitterAccount', user_options: 'User::Option', websites: 'Person::Website' } config.ignored_foreign_keys = { account_lists: [ :default_organization_id ], background_batches: [ :batch_id ], donations: [ :remote_id ], exports_to_mail_chimp: [ :mail_chimp_list_id ], facebook_accounts: [ :remote_id ], google_accounts: [ :remote_id ], google_integrations: [ :calendar_id ], key_accounts: [ :remote_id ], linkedin_accounts: [ :remote_id ], mail_chimp_accounts: [ :primary_list_id ], organization_accounts: [ :remote_id ], twitter_accounts: [ :remote_id ] } end
chuckmersereau/api_practice
spec/factories/account_lists.rb
FactoryBot.define do factory :account_list do name { Faker::Company.name } currency 'USD' home_country 'United States' monthly_goal { rand(10_000) } tester false end end
chuckmersereau/api_practice
app/serializers/donation_reports/donor_info_serializer.rb
<reponame>chuckmersereau/api_practice class DonationReports::DonorInfoSerializer < ServiceSerializer attributes :contact_id, :contact_name, :late_by_30_days, :late_by_60_days, :pledge_amount, :pledge_currency, :pledge_frequency, :status delegate :contact_id, :contact_name, :late_by_30_days, :late_by_60_days, :pledge_currency, to: :object def status _(object.status) end def pledge_frequency _(Contact.pledge_frequencies[object.pledge_frequency]) end def pledge_amount object.pledge_amount.to_f end end
chuckmersereau/api_practice
spec/controllers/api/v2/admin/impersonation_controller_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe Api::V2::Admin::ImpersonationController do let!(:user) { create(:user_with_account, admin: true) } let(:email) { '<EMAIL>' } let!(:user_to_impersonate) { create(:user, email: email) } let!(:key_account) { create(:key_account, user: user_to_impersonate, email: email) } let(:account_list) { user.account_lists.order(:created_at).first } let(:given_resource_type) { :impersonation } let(:correct_attributes) { { reason: 'Reason' } } let(:response_data) { JSON.parse(response.body)['data'] } include_context 'common_variables' context 'create' do it 'returns a 401 when someone is not logged in' do post :create, full_correct_attributes expect(response.status).to eq(401) end it 'returns a 403 when someone that is not an admin tries to impersonate' do api_login(create(:user)) post :create, full_correct_attributes expect(response.status).to eq(403) end it 'returns a 404 when the user id does not exist' do full_correct_attributes[:data][:attributes][:user] = SecureRandom.uuid api_login(user) post :create, full_correct_attributes expect(response.status).to eq(404) end it 'returns a 404 when the user email does not exist' do full_correct_attributes[:data][:attributes][:user] = '<EMAIL>' api_login(user) post :create, full_correct_attributes expect(response.status).to eq(404) end it 'returns a 200 when an admin is logged in and searches the user by ID' do expect_admin_user_to_be_able_to_impersonate_with_id(user_to_impersonate.id) end it 'returns a 200 when an admin is logged in and searches the user by email' do expect_admin_user_to_be_able_to_impersonate_with_id(email) end def expect_admin_user_to_be_able_to_impersonate_with_id(user_key) travel_to(Time.now.getlocal) api_login(user) expect do full_correct_attributes[:data][:attributes][:user] = user_key post :create, full_correct_attributes end.to change { Admin::ImpersonationLog.count }.by(1) expect(response.status).to eq(200) expect(response_data['attributes']['json_web_token']).to eq( JsonWebToken.encode( user_id: user_to_impersonate.id, exp: 1.hour.from_now.utc.to_i ) ) travel_back end end end
chuckmersereau/api_practice
spec/controllers/api/v2/coaching/contacts_controller_spec.rb
require 'rails_helper' describe Api::V2::Coaching::ContactsController, type: :controller do let(:given_serializer_class) { Coaching::ContactSerializer } let(:resource_type) { 'contacts' } let(:factory_type) { :contact } let!(:user) { create(:user, locale: :en) } let!(:owner) { create(:user_with_account) } let!(:account_list) { owner.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:contact_1) { create :contact, account_list_id: account_list.id } let!(:contact_2) { create :contact, account_list_id: account_list.id, created_at: 1.week.from_now } let!(:contact_3) { create :contact, created_at: 2.weeks.from_now } let(:id) { contact_1.id } let!(:coaches) { create_list(:user_coach, 2) } before do account_list.coaches += coaches account_list.coaches << user.becomes(User::Coach) end let(:resource) { contact_1 } let(:correct_attributes) { attributes_for(:contact) } include_examples 'index_examples' include_examples 'show_examples' describe 'hash[total_pledge]' do before do contact_1.update(pledge_amount: 100, pledge_frequency: 4) contact_2.update(pledge_amount: 200, pledge_frequency: 1) contact_3.update(pledge_amount: 999, pledge_frequency: 1) end it 'totals the contacts\' commitment in the "meta" object' do api_login(user) get :index, parent_param_if_needed expect(response.status).to eq(200), invalid_status_detail meta = JSON.parse(response.body)['meta'] expect(meta['total_pledge']['amount']).to eq(100 / 4 + 200 / 1) expect(meta['total_pledge']['currency']).to eq('USD') end end end
chuckmersereau/api_practice
app/services/coaching/contact/total_monthly_pledge.rb
class Coaching::Contact::TotalMonthlyPledge DEFAULT_CURRENCY = 'USD'.freeze attr_accessor :contacts_scope, :currency def initialize(contacts_scope, currency) @contacts_scope = contacts_scope @currency = currency || DEFAULT_CURRENCY end def total contacts_scope.map(&method(:convert_pledge)) .inject(0.0, :+) .round(2) end private def convert_pledge(contact) CurrencyRate.convert_with_latest(amount: contact.monthly_pledge, from: contact.pledge_currency, to: currency) end end
chuckmersereau/api_practice
app/services/mail_chimp/webhook/base.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 # Webhooks are calls to the MPDX API made by Mail Chimp following certain events. # These calls are received by the mail_chimp_webhook_controller and handled by # different classes in the mail_chimp/webhook folder. # This class is inherited by all webhook service classes and therefore implements # methods that every single webhook class should implement. module MailChimp::Webhook class Base attr_reader :mail_chimp_account, :account_list def initialize(mail_chimp_account) @mail_chimp_account = mail_chimp_account @account_list = mail_chimp_account.account_list end def campaign_status_hook(campaign_id, status, subject) return unless status == 'sent' MailChimp::CampaignLoggerWorker.perform_async(mail_chimp_account.id, campaign_id, subject) end end end
chuckmersereau/api_practice
db/migrate/20170801182230_add_index_on_donor_accounts_acct_number.rb
<gh_stars>0 class AddIndexOnDonorAccountsAcctNumber < ActiveRecord::Migration disable_ddl_transaction! def self.up execute 'CREATE EXTENSION IF NOT EXISTS pg_trgm;' execute 'CREATE INDEX concurrently index_donor_accounts_on_acct_num_trig ON donor_accounts USING GIN (account_number gin_trgm_ops);' end def self.down remove_index :donor_accounts, name: :index_donor_accounts_on_acct_num_trig, algorithm: :concurrently execute 'DROP EXTENSION IF EXISTS pg_trgm;' end end
chuckmersereau/api_practice
spec/controllers/api/v2/contacts/exports/mailing_controller_spec.rb
require 'rails_helper' require 'tempfile' require 'roo' describe Api::V2::Contacts::Exports::MailingController, type: :controller do let(:factory_type) { :contact } let!(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let(:second_account_list) { create(:account_list, users: [user]) } let(:resource) { create(:export_log, user: user) } let(:id) { resource.id } let(:incorrect_attributes) { nil } let(:correct_attributes) do { params: { filter: { status: 'active' } } } end let!(:contact) { create(:contact, account_list: account_list, name: 'Last Contact', addresses: [build(:address)]) } let!(:second_contact) do create(:contact, account_list: account_list, name: 'First Contact', addresses: [build(:address, street: '123 another street')]) end let!(:third_contact) { create(:contact, account_list: second_account_list, name: 'Missing Contact') } include_examples 'show_examples' include_examples 'create_examples' describe '#show' do it 'only allows export display to occur once' do api_login(user) get :show, id: resource.id expect(response.status).to eq(200) get :show, id: resource.id expect(response.status).to eq(403) end it 'sets active to false' do api_login(user) get :show, id: resource.id expect(resource.reload.active).to eq(false) end end render_views context 'Mailing CSV export' do let(:contact_index) { response.body.index(contact.name) } let(:second_contact_index) { response.body.index(contact.name) } it 'does not shows resources to users that are not signed in' do get :index, format: :csv expect(response.status).to eq(401) end it 'logs the export if successful' do api_login(user) expect do get :index, format: :csv end.to change { ExportLog.count }.from(0).to(1) expect(response.status).to eq(200) expect(ExportLog.first.active).to eq(false) expect(ExportLog.first.type).to eq('Contacts Mailing') end it 'renders the export alphabetically for users that are signed in' do api_login(user) get :index, format: :csv expect(response.status).to eq(200) expect(contact_index).to be_present expect(response.body).to be_present expect(contact_index).to be > response.body.index(second_contact.name) expect(response.body).to include(contact.csv_street) expect(response.body).to include(second_contact.csv_street) end it 'renders the export with right contacts when contact_ids is provided' do api_login(user) get :index, format: :csv, filter: { ids: contact.id } expect(response.status).to eq(200) expect(contact_index).to be_present expect(response.body).to be_present expect(response.body).to include(contact.csv_street) expect(response.body).to_not include(second_contact.csv_street) end it 'allows filtering by account_list_id' do api_login(user) get :index, format: :csv, filter: { account_list_id: second_account_list.id } expect(response.status).to eq(200) expect(response.body).to include(third_contact.name) expect(response.body).to_not include(contact.name) end it 'allows filtering by status' do filters = { status: 'Call for Decision' } api_login(user) get :index, format: :csv, filter: filters expect(response.status).to eq(200) end end end
chuckmersereau/api_practice
app/services/row_transfer_request.rb
<gh_stars>0 class RowTransferRequest class << self # clone: sets if Kirby will leave the rows in the master DB. # if false, the rows will be deleted from master after the copy # # safe: sets if Kirby will fail if some of id's exist in the slave table # if false, the ids that are already in the slave db will be ignored def transfer(table_name, ids, clone: true, safe: false) RestClient.post ENV.fetch('KIRBY_URL'), payload(table_name, Array.wrap(ids), clone, safe), headers Rails.logger.debug "#{ids.size} record(s) on #{table_name} transferred" end private def payload(table, ids, clone, safe) { table: table, uuids: ids.join(','), clone: clone, safe: safe }.to_json end def headers { content_type: :json, 'x-api-key' => ENV.fetch('AWS_API_GATEWAY_KEY') } end end end
chuckmersereau/api_practice
db/migrate/20130110204055_add_donation_id_to_notification.rb
class AddDonationIdToNotification < ActiveRecord::Migration def change add_column :notifications, :donation_id, :integer add_index :notifications, [:contact_id, :notification_type_id, :donation_id], name: 'notification_index' end end
chuckmersereau/api_practice
spec/models/designation_account_spec.rb
<gh_stars>0 require 'rails_helper' describe DesignationAccount do it 'should return designation_number for to_s' do expect(build(:designation_account, designation_number: 'foo').to_s).to eq('foo') end it "should return a user's first account list" do account_list = double('account_list') user = double('user', account_lists: [account_list]) da = DesignationAccount.new allow(da).to receive(:account_lists).and_return([account_list]) expect(da.account_list(user)).to eq(account_list) end context '#currency' do let(:organization) { build(:fake_org, default_currency_code: 'GBP') } let(:designation_account) { build(:designation_account, organization: organization) } it 'returns the org default currency code' do expect(designation_account.currency).to eq 'GBP' end context 'organization has no default_currency_code' do before do organization.default_currency_code = nil end it 'returns USD if org has no default currency code' do expect(designation_account.currency).to eq 'USD' end end end context '#converted_balance' do let(:organization) { build(:fake_org, default_currency_code: 'GBP') } let(:designation_account) { build(:designation_account, organization: organization, balance: 100.0) } it 'converts balance to specified currency' do allow(CurrencyRate).to receive(:convert_with_latest!).with(amount: 100.0, from: 'GBP', to: 'EUR') { 124.8 } expect(designation_account.converted_balance('EUR')).to eq 124.8 end it 'returns zero but logs error to rollbar if currency rate missing' do allow(Rollbar).to receive(:error) allow(CurrencyRate).to receive(:convert_with_latest!).and_raise(CurrencyRate::RateNotFoundError) expect(designation_account.converted_balance('EUR')).to eq 0.0 expect(Rollbar).to have_received(:error) end end describe '.filter' do context 'wildcard_search' do context 'designation_number' do let!(:designation_account) { create(:designation_account, designation_number: '1234') } context 'designation_number starts with' do it 'returns designation_account' do expect(described_class.filter(wildcard_search: '12')).to eq([designation_account]) end end context 'designation_number does not start with' do it 'returns no designation_accounts' do expect(described_class.filter(wildcard_search: '34')).to be_empty end end end context 'name' do let!(:designation_account) { create(:designation_account, name: 'abcd') } context 'name contains' do it 'returns dnor_account' do expect(described_class.filter(wildcard_search: 'bc')).to eq([designation_account]) end end context 'name does not contain' do it 'returns no designation_accounts' do expect(described_class.filter(wildcard_search: 'def')).to be_empty end end end end context 'not wildcard_search' do let!(:designation_account) { create(:designation_account, designation_number: '1234') } it 'returns designation_account' do expect(described_class.filter(designation_number: designation_account.designation_number)).to eq([designation_account]) end end end describe '.balances' do let!(:designation_account) { create(:designation_account) } it 'should create associated balance record when balance is updated' do expect { create(:designation_account, balance: 10.0) }.to change { Balance.count }.by(1) expect { designation_account.update(balance: 20.0) }.to change { Balance.count }.by(1) expect { designation_account.update(balance: 20.0) }.to change { Balance.count }.by(0) end it 'should not create associated balance record when balance is updated to nil' do expect { designation_account.update(balance: nil) }.to change { Balance.count }.by(0) end end end
chuckmersereau/api_practice
app/controllers/api/v2/account_lists/users_controller.rb
class Api::V2::AccountLists::UsersController < Api::V2Controller def index authorize load_account_list, :show? load_users render json: @users.preload_valid_associations(include_associations), meta: meta_hash(@users), include: include_params, fields: field_params, each_serializer: AccountListUserSerializer end def show load_user authorize_user render_user end def destroy load_user authorize_user destroy_user end private def destroy_user @user.remove_user_access(load_account_list) head :no_content end def load_users @users = user_scope.where(filter_params) .reorder(sorting_param) .order(default_sort_param) .page(page_number_param) .per(per_page_param) end def load_user @user ||= User.find(params[:id]) end def render_user render json: @user, status: success_status, include: include_params, fields: field_params, serializer: AccountListUserSerializer end def authorize_user authorize @user end def user_scope load_account_list.users end def load_account_list @account_list ||= AccountList.find(params[:account_list_id]) end def pundit_user if action_name == 'index' PunditContext.new(current_user, account_list: load_account_list) else current_user end end def default_sort_param User.arel_table[:created_at].asc end end
chuckmersereau/api_practice
spec/serializers/constant_list_serializer_spec.rb
require 'rails_helper' describe ConstantListSerializer do let(:serializer) { ConstantListSerializer.new(constant_list) } subject { serializer } let(:constant_list) { ConstantList.new } context '#activities' do it { expect(subject.activities).to be_an Array } it 'all elements should be strings' do subject.activities.each do |activity| expect(activity).to be_a(String) end end end context '#organizations' do before { 5.times { create(:organization) } } it { expect(subject.organizations).to be_a_hash_with_types String, String } end context '#organizations_attributes' do before { 5.times { create(:organization) } } it { expect(subject.organizations_attributes).to be_a_hash_with_types String, Hash } end context '#notifications' do before { 5.times { create(:notification) } } it { expect(subject.notifications).to be_a_hash_with_types String, String } end context '#locales' do it 'should have the correct data structure' do subject.locales.each do |_code, locale| expect(locale).to be_a_hash_with_types Symbol, String end expect(subject.locales).to be_a_hash_with_types Symbol, Hash end it 'should have an english name with the locale code in parentheses' do subject.locales.each do |_code, locale| expect(locale[:english_name]).to match(/\A[^\(]+\(\w+(?:-\w+)?\)\z/) end end it 'should have ISO 3166-1 alpha-2 codes' do subject.locales.each do |code, _locale| expect(code).to match(/\w\w/) end end end context '#pledge_frequencies' do it { expect(subject.pledge_frequencies).to be_a_hash_with_types Numeric, String } it 'ideally would underscore keys but it should not underscore the frequencies to support clients that are still depending on it' do subject.pledge_frequencies.keys.each do |key| expect(key).to be_a(BigDecimal) expect(key.to_s).to include('.') expect(key.to_s).to_not include('_') end end end context '#send_appeals_hashes' do it { expect(subject.send_appeals_hashes).to be_a(Array) } it { subject.send_appeals_hashes.each { |hash| expect(hash).to be_a(Hash) } } end context '#dates' do it { expect(subject.dates).to be_a_hash_with_types String, String } end context '#languages' do it { expect(subject.languages).to be_a_hash_with_types String, String } end context '#activity_hashes' do it { expect(subject.activity_hashes.first).to be_a_hash_with_types Symbol, String } end context '#assignable_location_hashes' do it { expect(subject.assignable_location_hashes.first).to be_a_hash_with_types Symbol, String } end context '#assignable_likely_to_give_hashes' do it { expect(subject.assignable_likely_to_give_hashes.first).to be_a_hash_with_types Symbol, String } end context '#assignable_send_newsletter_hashes' do it { expect(subject.assignable_send_newsletter_hashes.first).to be_a_hash_with_types Symbol, String } end context '#status_hashes' do it { expect(subject.status_hashes.first).to be_a_hash_with_types Symbol, String } end context '#pledge_frequency_hashes' do let(:first_pledge_frequency_hash) { subject.pledge_frequency_hashes.first } it do expect(first_pledge_frequency_hash[:id]).to be_a String expect(first_pledge_frequency_hash[:key]).to be_a BigDecimal end end context '#notification_hashes' do let!(:notification_type) { create(:notification_type) } it { expect(subject.notification_hashes.first).to be_a_hash_with_types Symbol, String } end %w( assignable_likely_to_give assignable_send_newsletter statuses ).each do |attribute| context "##{attribute}" do it 'should consist of string/symbol pairs' do subject.send(attribute.to_sym).each do |contact| expect(contact).to be_a(String) end end end end end
chuckmersereau/api_practice
app/controllers/api/v2/contacts/referrals_controller.rb
class Api::V2::Contacts::ReferralsController < Api::V2Controller resource_type :contact_referrals def index authorize current_contact, :show? load_referrals render json: @referrals.preload_valid_associations(include_associations), meta: meta_hash(@referrals), include: include_params, fields: field_params end def show load_referral authorize_referral render_referral end def create persist_referral end def update load_referral authorize_referral persist_referral end def destroy load_referral authorize_referral destroy_referral end private def current_contact @current_contact ||= Contact.find(params[:contact_id]) end def referral_params params .require(:contact_referral) .permit(referral_attributes) end def referral_attributes ContactReferral::PERMITTED_ATTRIBUTES end def referral_scope current_contact.contact_referrals_by_me end def authorize_referral authorize @referral end def build_referral @referral ||= referral_scope.build @referral.assign_attributes(referral_params) end def destroy_referral @referral.destroy head :no_content end def load_referral @referral ||= referral_scope.find(params[:id]) end def load_referrals @referrals = referral_scope.where(filter_params) .reorder(sorting_param) .page(page_number_param) .per(per_page_param) end def persist_referral build_referral authorize_referral if save_referral render_referral else render_with_resource_errors(@referral) end end def render_referral render json: @referral, status: success_status, include: include_params, fields: field_params end def save_referral @referral.save(context: persistence_context) end def pundit_user PunditContext.new(current_user, contact: current_contact) end end
chuckmersereau/api_practice
app/serializers/coaching/person_serializer.rb
<reponame>chuckmersereau/api_practice class Coaching::PersonSerializer < PersonSerializer def person_exhibit @exhibit ||= Coaching::PersonExhibit.new(object, nil) end end
chuckmersereau/api_practice
spec/models/name_male_ratio_spec.rb
require 'rails_helper' describe NameMaleRatio do end
chuckmersereau/api_practice
app/controllers/api/v2/contacts/people/email_addresses_controller.rb
class Api::V2::Contacts::People::EmailAddressesController < Api::V2Controller def index load_email_addresses authorize current_contact, :show? render_email_addresses end def show load_email_address authorize_email_address render_email_address end def create persist_email_address end def update load_email_address persist_email_address end def destroy load_email_address authorize_email_address destroy_email_address end private def destroy_email_address @email_address.destroy head :no_content end def persist_email_address build_email_address authorize_email_address if save_email_address render_email_address else render_with_resource_errors(@email_address) end end def email_address_params params .require(:email_address) .permit(email_address_attributes) end def email_address_attributes EmailAddress::PERMITTED_ATTRIBUTES end def email_address_scope current_person.email_addresses end def authorize_email_address authorize @email_address end def build_email_address @email_address ||= email_address_scope.build @email_address.assign_attributes(email_address_params) end def load_email_address @email_address ||= email_address_scope.find(params[:id]) end def load_email_addresses @email_addresses = email_address_scope.where(filter_params) .reorder(sorting_param) .order(default_sort_param) .page(page_number_param) .per(per_page_param) end def render_email_address render json: @email_address, status: success_status, include: include_params, fields: field_params end def render_email_addresses render json: @email_addresses.preload_valid_associations(include_associations), meta: meta_hash(@email_addresses), include: include_params, fields: field_params end def save_email_address @email_address.save(context: persistence_context) end def current_contact @current_contact ||= Contact.find(params[:contact_id]) end def current_person @current_person ||= current_contact.people.find(params[:person_id]) end def pundit_user PunditContext.new(current_user, contact: current_contact, person: current_person) end def default_sort_param EmailAddress.arel_table[:created_at].asc end end
chuckmersereau/api_practice
app/helpers/gmail_compose_link_helper.rb
<reponame>chuckmersereau/api_practice module GmailComposeLinkHelper def link_to_gmail_compose(name, opts = {}) gmail_opts = [:to, :subject, :body, :cc, :bcc] link_to(name, gmail_compose_url(opts.slice(*gmail_opts)), opts.except(*gmail_opts)) end private # See: https://stackoverflow.com/q/6548570/879524 def gmail_compose_url(opts = {}) options = { view: 'cm', fs: 1, to: opts[:to], su: opts[:subject], body: opts[:body], bcc: opts[:bcc], cc: opts[:cc] } params = options.select { |_, v| v.present? }.to_param "https://mail.google.com/mail/?#{params}" end end
chuckmersereau/api_practice
app/models/phone_number.rb
<filename>app/models/phone_number.rb class PhoneNumber < ApplicationRecord include Concerns::AfterValidationSetSourceToMPDX include HasPrimary @@primary_scope = :person audited associated_with: :person, except: [:updated_at, :global_registry_id] LOCATIONS = [_('Mobile'), _('Home'), _('Work')].freeze PERMITTED_ATTRIBUTES = [:created_at, :country_code, :location, :number, :overwrite, :primary, :remote_id, :source, :updated_at, :updated_in_db_at, :id, :valid_values].freeze belongs_to :person, touch: true before_save :clean_up_number before_create :set_valid_values validates :number, presence: true validates :number, :country_code, :location, :remote_id, updatable_only_when_source_is_mpdx: true global_registry_bindings parent: :person, fields: { number: :string, primary: :boolean, location: :string } def self.add_for_person(person, attributes) attributes = attributes.with_indifferent_access.except(:_destroy) normalized_number = PhoneNumber.new(attributes.merge(person: person)) normalized_number.clean_up_number normalized_or_not = [normalized_number.number, attributes[:number]] number = person.phone_numbers.find_by(number: normalized_or_not) if number && (attributes[:source] != TntImport::SOURCE || number.source == attributes[:source]) number.update_attributes(attributes) else attributes['primary'] = person.phone_numbers.empty? if attributes['primary'].nil? new_or_create = person.new_record? ? :new : :create number = person.phone_numbers.send(new_or_create, attributes) end number end def clean_up_number # Default country to United States to help prevent duplicate numbers from # being created when the user has not selected a home country. country = user_country || 'US' # Use PhoneLib for parsing because PhoneLib supports extensions phone = Phonelib.parse(number, country) return if phone.e164.blank? self.number = phone.extension.present? ? "#{phone.e164};#{phone.extension}" : phone.e164 self.country_code = phone.country_code end def ==(other) return false unless other.is_a?(PhoneNumber) number.to_s.gsub(/\D/, '') == other.number.to_s.gsub(/\D/, '') end def merge(other) self.primary = (primary? || other.primary?) self.country_code = other.country_code if country_code.blank? self.location = other.location if location.blank? self.remote_id = other.remote_id if remote_id.blank? save(validate: false) other.destroy end def user_country return @user_country if @user_country return nil unless person&.contacts&.first && person.contacts.first.account_list && person.contacts.first.account_list.home_country code = Address.find_country_iso(person.contacts.first.account_list.home_country) return nil unless code @user_country = code.downcase.to_sym end def set_valid_values self.valid_values = (source == MANUAL_SOURCE) || !self.class.where(person: person).exists? true end end
chuckmersereau/api_practice
app/workers/mail_chimp/campaign_logger_worker.rb
<filename>app/workers/mail_chimp/campaign_logger_worker.rb class MailChimp::CampaignLoggerWorker include Sidekiq::Worker sidekiq_options queue: :api_mail_chimp_sync_worker, unique: :until_executed def perform(mail_chimp_account_id, campaign_id, subject) mail_chimp_account = MailChimpAccount.find_by(id: mail_chimp_account_id) return unless mail_chimp_account MailChimp::CampaignLogger.new(mail_chimp_account) .log_sent_campaign(campaign_id, subject) end end
chuckmersereau/api_practice
spec/support/json_api_helper.rb
<gh_stars>0 module JsonApiHelper def json_response @json_response ||= parse_response_body end def check_collection_resource(total_items, additional_keys = []) expect(json_response.keys).to eq %w(data meta) expect(resource_data.count).to eq total_items expect(first_or_only_item.keys).to eq item_keys(additional_keys) expect(first_or_only_item['type']).to eq resource_type.to_s expect(resource_object.keys).to match_array(resource_attributes) if defined?(resource_attributes) end def check_resource(additional_keys = [], additional_attributes = [], additional_relationships = []) expect(json_response.keys).to eq %w(data) expect(first_or_only_item.keys).to eq item_keys(additional_keys) expect(first_or_only_item['type']).to eq resource_type.to_s check_resource_attributes(additional_attributes) check_resource_relationships(additional_relationships) end def check_resource_attributes(additional_attributes) return unless defined?(resource_attributes) expect(resource_object.keys).to match_array(resource_attributes + additional_attributes) end def check_resource_relationships(additional_relationships) return unless defined?(resource_associations) expect(first_or_only_item['relationships'].keys).to match_array(resource_associations + additional_relationships) end def item_keys(additional_keys) (resource_object.empty? ? %w(id type) : %w(id type attributes)) + additional_keys end def invalid_status_detail body = json_response.is_a?(String) ? '' : JSON.pretty_generate(json_response) "\n\nResponse Status: #{returned_status}\nResponse Body: #{body}" end def first_or_only_item resource_data.is_a?(Array) ? resource_data.first : resource_data end def resource_object first_or_only_item.fetch('attributes', {}) end def resource_data json_response['data'] end def build_data(params, account_list_id: nil, relationships: {}) attributes = params.deep_symbolize_keys .except(:id, :id) .sort .each_with_object({}) { |(key, value), hash| hash[key] = value } params = { type: (defined?(request_type) ? request_type : resource_type), attributes: attributes } if account_list_id params.merge!( relationships: { account_list: { data: { type: 'account_lists', id: account_list_id } } } ) elsif relationships.present? params.merge(relationships: relationships) else params end end def returned_status if defined?(response_status) response_status else response.status end end private def parse_response_body if defined?(response_body) return '' if response_body.blank? JSON.parse(response_body) else return '' if response.body.blank? JSON.parse(response.body) end end end
chuckmersereau/api_practice
app/serializers/user/option_serializer.rb
class User::OptionSerializer < ApplicationSerializer attributes :created_at, :key, :value, :updated_at end
chuckmersereau/api_practice
spec/services/human_name_parser_spec.rb
<filename>spec/services/human_name_parser_spec.rb require 'rails_helper' describe HumanNameParser do it 'initializes' do expect(HumanNameParser.new('Tester')).to be_a HumanNameParser end describe '#parse' do it 'parses a name like "<NAME>"' do expect(HumanNameParser.new('<NAME>').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: nil, spouse_middle_name: nil, spouse_last_name: nil) end it 'parses a name like "<NAME>"' do expect(HumanNameParser.new('<NAME>').parse).to eq(first_name: 'Bob', middle_name: 'L.', last_name: 'Jones', spouse_first_name: nil, spouse_middle_name: nil, spouse_last_name: nil) end it 'parses a name like "<NAME>"' do expect(HumanNameParser.new('<NAME>').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: '<NAME>', spouse_first_name: nil, spouse_middle_name: nil, spouse_last_name: nil) end it 'parses a name like "<NAME>"' do expect(HumanNameParser.new('<NAME>').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: nil, spouse_middle_name: nil, spouse_last_name: nil) end it 'parses a name like "Mr. <NAME> Sr."' do expect(HumanNameParser.new('Mr. <NAME> Sr.').parse).to eq(first_name: 'Bob', middle_name: 'Billy', last_name: 'Jones', spouse_first_name: nil, spouse_middle_name: nil, spouse_last_name: nil) end it 'parses names like "Jones, Bob and Sara"' do expect(HumanNameParser.new('Jones, Bob and Sara').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: 'Jones') end it 'parses names like "Jones, Bob and ."' do expect(Rollbar).to_not receive(:info) expect(HumanNameParser.new('Jones, Bob and .').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: '.', spouse_middle_name: nil, spouse_last_name: 'Jones') end it 'parses names like "Jones, Bob and ???"' do expect(Rollbar).to_not receive(:info) expect(HumanNameParser.new('Jones, Bob and ???').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: '???', spouse_middle_name: nil, spouse_last_name: 'Jones') end it 'parses names like "Bob and Sara Jones"' do expect(HumanNameParser.new('Bob and <NAME>').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: 'Jones') end it 'parses names like "Bob and <NAME>"' do expect(HumanNameParser.new('Bob and <NAME>').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: '<NAME>', spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: '<NAME>') end it 'parses names like "<NAME> and Sara (Nickname)"' do expect(HumanNameParser.new('<NAME> and Sara (Nickname)').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: 'Jones') end it 'parses names like "<NAME> (Nickname) and Sara"' do expect(HumanNameParser.new('<NAME> (Nickname) and Sara').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: 'Jones') end it 'parses names like "<NAME> (Nickname) and Sara (Nickname)"' do expect(HumanNameParser.new('<NAME> (Nickname) and Sara (Nickname)').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: 'Jones') end it 'parses names like "Bob (Nickname) Jones"' do expect(HumanNameParser.new('Bob (Nickname) Jones').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: nil, spouse_middle_name: nil, spouse_last_name: nil) end it 'parses names like "<NAME> (Nickname)"' do expect(HumanNameParser.new('<NAME> (Nickname)').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: nil, spouse_middle_name: nil, spouse_last_name: nil) end it 'parses names like "<NAME> and <NAME>"' do expect(HumanNameParser.new('Yo<NAME> and Kyung Soon Kim').parse).to eq(first_name: 'Young', middle_name: 'Jae', last_name: 'Lee', spouse_first_name: 'Kyung', spouse_middle_name: 'Soon', spouse_last_name: 'Kim') end it 'parses names like "<NAME> and <NAME>"' do expect(HumanNameParser.new('Young Jae Kim and Kyung Soon').parse).to eq(first_name: 'Young', middle_name: 'Jae', last_name: 'Kim', spouse_first_name: 'Kyung', spouse_middle_name: 'Soon', spouse_last_name: 'Kim') end it 'parses names like "<NAME> and Kyung Soon Kim"' do expect(HumanNameParser.new('Young Jae and Kyung Soon Kim').parse).to eq(first_name: 'Young', middle_name: 'Jae', last_name: 'Kim', spouse_first_name: 'Kyung', spouse_middle_name: 'Soon', spouse_last_name: 'Kim') end it 'parses names like "Kim, <NAME> and Kyung Soon"' do expect(HumanNameParser.new('Kim, Young Jae and Kyung Soon').parse).to eq(first_name: 'Young', middle_name: 'Jae', last_name: 'Kim', spouse_first_name: 'Kyung', spouse_middle_name: 'Soon', spouse_last_name: 'Kim') end it 'parses names like "Jones, <NAME> and <NAME>"' do expect(HumanNameParser.new('Jones, <NAME> and <NAME>').parse).to eq(first_name: 'Bobby', middle_name: 'Bob', last_name: 'Jones', spouse_first_name: 'Sarah', spouse_middle_name: 'Sary', spouse_last_name: 'Jones') end it %(parses names like "Bob and <NAME>") do expect(HumanNameParser.new('Bob and <NAME>').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: 'Jones') end it %(parses names like "Mr. <NAME> and Mrs. <NAME>") do expect(HumanNameParser.new('Mr. <NAME> and Mrs. <NAME>').parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: 'Sara', spouse_middle_name: 'Janes', spouse_last_name: 'Jones') end ['Mr. and Mrs.', 'Mr and Mrs', 'Mr. & Mrs.', 'Mrs. and Mr.', 'Miss & Mr'].each do |titles| it %(parses names like "#{titles} Bob and Sara") do expect(HumanNameParser.new("#{titles} Bob and Sara").parse).to eq(first_name: 'Bob', middle_name: nil, last_name: nil, spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: nil) end it %(parses names like "#{titles} Bob and <NAME>") do expect(HumanNameParser.new("#{titles} Bob and <NAME>").parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: 'Jones') end it %(parses names like "#{titles} Jones, Bob and Sara") do expect(HumanNameParser.new("#{titles} Jones, Bob and Sara").parse).to eq(first_name: 'Bob', middle_name: nil, last_name: 'Jones', spouse_first_name: 'Sara', spouse_middle_name: nil, spouse_last_name: 'Jones') end end it 'handles unparsable names' do expect(Nameable).to receive(:parse).and_raise(Nameable::InvalidNameError) expect(HumanNameParser.new('Unparsable Name').parse).to eq(first_name: nil, middle_name: nil, last_name: nil, spouse_first_name: nil, spouse_middle_name: nil, spouse_last_name: nil) end it 'notifies Rollbar if unparsable' do expect(Nameable).to receive(:parse).and_raise(Nameable::InvalidNameError) expect(Rollbar).to receive(:info) HumanNameParser.new('🎂').parse end end end
chuckmersereau/api_practice
spec/workers/csv_import_contact_worker_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/workers/csv_import_contact_worker_spec.rb require 'rails_helper' describe CsvImportContactWorker do let!(:import) { create(:csv_import_with_mappings) } let!(:csv_import) { CsvImport.new(import) } let(:csv_rows) do csv_rows = [] csv_import.each_row { |csv_row| csv_rows << csv_row } csv_rows end before do Sidekiq::Testing.inline! stub_smarty_streets end it 'creates a contact' do csv_row = csv_rows.first expect do CsvImportContactWorker.new.perform(import.id, csv_row.headers, csv_row.fields) end.to change { Contact.count }.from(0).to(1) end context 'ActiveRecord::RecordInvalid exception raised when saving contact' do let(:csv_row) do csv_row = csv_rows.first.to_h csv_row['fullname'] = nil csv_row['fname'] = nil csv_row['lname'] = nil CSV::Row.new(csv_row.keys, csv_row.values) end it 'adds failed line to file_row_failures' do expect(import.reload.file_row_failures).to eq([]) expect do CsvImportContactWorker.new.perform(import.id, csv_row.headers, csv_row.fields) end.to_not change { Contact.count }.from(0) failing_row = ["Validation failed: First name can't be blank", nil, nil, nil, 'Jane ', 'Doe', 'Hi John and Jane', 'Doe family', 'Westside Baptist Church', '1 Example Ave, Apt 6', 'Sample City', 'IL', '60201', 'USA', 'Praying', '50', 'Monthly', 'CAD', 'Both', 'christmas-card, family', ' <EMAIL> ', ' <EMAIL> ', '(213) 222-3333', '(407) 555-6666', 'test notes', 'No', 'Yes', 'metro', 'region', 'Yes', 'http://www.john.doe', '<NAME>'] expect(import.reload.file_row_failures).to eq([failing_row]) end it 'does not report to Rollbar' do expect(Rollbar).to_not receive(:error) CsvImportContactWorker.new.perform(import.id, csv_row.headers, csv_row.fields) end end context 'ActiveRecord::RecordNotUnique exception raised when saving contact' do let(:csv_row) { csv_rows.first } before do expect(CsvRowContactBuilder).to receive(:new).exactly(1).times .and_raise(ActiveRecord::RecordNotUnique, 'just testing') end it 'adds failed line to file_row_failures' do expect(import.reload.file_row_failures).to eq([]) expect do CsvImportContactWorker.new.perform(import.id, csv_row.headers, csv_row.fields) end.to_not change { Contact.count }.from(0) failing_row = ['Record not unique error: Please ensure you are not importing duplicate '\ 'data (such as duplicate email addresses, which must be unique)', 'Johnny and <NAME>', ' John', 'Doe', 'Jane ', 'Doe', 'Hi John and Jane', 'Doe family', 'Westside Baptist Church', '1 Example Ave, Apt 6', 'Sample City', 'IL', '60201', 'USA', 'Praying', '50', 'Monthly', 'CAD', 'Both', 'christmas-card, family', ' <EMAIL> ', ' <EMAIL> ', '(213) 222-3333', '(407) 555-6666', 'test notes', 'No', 'Yes', 'metro', 'region', 'Yes', 'http://www.john.doe', '<NAME>'] expect(import.reload.file_row_failures).to eq([failing_row]) end it 'does not report to Rollbar' do expect(Rollbar).to_not receive(:error) CsvImportContactWorker.new.perform(import.id, csv_row.headers, csv_row.fields) end end context 'unknown exception raised when saving contact' do let(:csv_row) { csv_rows.first } before do expect(CsvRowContactBuilder).to receive(:new).exactly(4).times.and_raise(StandardError) expect(Rollbar).to receive(:error).exactly(4).times end it 'adds failed line to file_row_failures' do expect(import.reload.file_row_failures).to eq([]) expect do CsvImportContactWorker.new.perform(import.id, csv_row.headers, csv_row.fields) end.to_not change { Contact.count }.from(0) failing_row = ['StandardError', 'Johnny and <NAME>', ' John', 'Doe', 'Jane ', 'Doe', 'Hi John and Jane', 'Doe family', 'Westside Baptist Church', '1 Example Ave, Apt 6', 'Sample City', 'IL', '60201', 'USA', 'Praying', '50', 'Monthly', 'CAD', 'Both', 'christmas-card, family', ' <EMAIL> ', ' <EMAIL> ', '(213) 222-3333', '(407) 555-6666', 'test notes', 'No', 'Yes', 'metro', 'region', 'Yes', 'http://www.john.doe', '<NAME>'] expect(import.reload.file_row_failures).to eq([failing_row]) end end end
chuckmersereau/api_practice
spec/models/audited/audit_elastic_spec.rb
<filename>spec/models/audited/audit_elastic_spec.rb require 'rails_helper' RSpec.describe Audited::AuditElastic, type: :model do let(:audited) { create(:person, first_name: 'Stephan') } let(:user) { create(:user) } let(:audit_attributes) do { action: 'update', audited_changes: { first_name: %w(<NAME>) }.to_json, user_id: user.id, user_type: 'User', auditable_id: audited.id, auditable_type: audited.class.to_s } end subject { Audited::AuditElastic.new(audit_attributes) } describe '#user' do it 'returns user model' do expect(subject.user).to eq user end end describe '#undo' do it 'changes back a value' do expect { subject.undo }.to change { audited.reload.first_name }.to('Steve') end it 'saves an audit with comment' do allow_any_instance_of(audited.class).to receive(:system_auditing_enabled).and_return(true) subject comment = 'Test' expect { subject.undo(comment) }.to change(AuditChangeWorker.jobs, :size).by(1) expect(AuditChangeWorker.jobs.dig(-1, 'args', 0, 'comment')).to eq comment end end end
chuckmersereau/api_practice
app/services/reports/base.rb
class Reports::Base < ActiveModelSerializers::Model attr_accessor :account_list attr_writer :filter_params def periods_data @periods_data ||= periods.map do |period| generate_report_for_period(period) end end def filter_params @filter_params || {} end def end_date filter_params[:end_date].presence || Date.today end def range filter_params[:range].presence || default_range end protected def default_range '4w' end def generate_report_for_period(*) raise NotImplementedError, 'Report must extend generate_report_for_period' end private def periods Array.new(times) do |i| period_end_date = end_date - i.send(time_unit) { start_date: period_end_date.send("beginning_of_#{time_unit}").beginning_of_day, end_date: period_end_date.send("end_of_#{time_unit}").end_of_day } end end def times range.to_i end def time_unit case range[-1] when 'd' :day when 'w' :week when 'm' :month when 'y' :year end end def valid_range range =~ /^\d+[dwmy]$/ end end
chuckmersereau/api_practice
db/migrate/20170418040030_add_index_on_donations_on_desig_date_remote.rb
<filename>db/migrate/20170418040030_add_index_on_donations_on_desig_date_remote.rb<gh_stars>0 class AddIndexOnDonationsOnDesigDateRemote < ActiveRecord::Migration disable_ddl_transaction! def change add_index :donations, [:designation_account_id, :donation_date, :remote_id], name: 'index_donations_on_des_acc_id_and_don_date_and_rem_id', order: { donation_date: :desc }, algorithm: :concurrently end end
chuckmersereau/api_practice
app/services/contact_multi_add.rb
<reponame>chuckmersereau/api_practice<filename>app/services/contact_multi_add.rb<gh_stars>0 class ContactMultiAdd def initialize(account_list, referring_contact = nil) @account_list = account_list @referring_contact = referring_contact end def add_contacts(contacts_attributes) contacts = Contact.transaction do contacts_attributes.values .select { |attrs| attrs.values.any?(&:present?) } .map(&method(:create_contact_and_people)) end [contacts.compact, contacts.count(&:nil?)] end private def create_contact_and_people(attrs) return unless attrs[:first_name].present? || attrs[:last_name].present? contact = create_contact(attrs) add_primary_person(contact, attrs) add_spouse(contact, attrs) if attrs[:spouse_first_name].present? add_address(contact, attrs) @referring_contact&.contact_referrals_by_me&.create(referred_to_id: contact.id) contact rescue ActiveRecord::RecordInvalid end def create_contact(attrs) attrs[:first_name] = _('Unknown') if attrs[:first_name].blank? attrs[:last_name] = _('Unknown') if attrs[:last_name].blank? contact_name = "#{attrs[:last_name]}, #{attrs[:first_name]}" contact_name += " & #{attrs[:spouse_first_name]}" if attrs[:spouse_first_name].present? contact_greeting = (attrs[:first_name]).to_s contact_greeting += " & #{attrs[:spouse_first_name]}" if attrs[:spouse_first_name].present? contact = @account_list.contacts.create(name: contact_name, greeting: contact_greeting, notes: attrs[:notes]) contact end def add_primary_person(contact, attrs) person = Person.create(attrs.slice(:first_name, :last_name, :email, :phone)) contact.people << person end def add_spouse(contact, attrs) spouse = Person.create(first_name: attrs[:spouse_first_name], last_name: attrs[:last_name], phone: attrs[:spouse_phone], email: attrs[:spouse_email]) contact.people << spouse end def add_address(contact, attrs) contact.addresses_attributes = [ attrs.slice(:street, :city, :state, :postal_code).merge(primary_mailing_address: true) ] contact.save end end
chuckmersereau/api_practice
db/migrate/20170404211527_remove_donation_id_from_pledges.rb
class RemoveDonationIdFromPledges < ActiveRecord::Migration def change remove_column :pledges, :donation_id, :integer end end
chuckmersereau/api_practice
db/migrate/20170921213101_create_google_plus_accounts.rb
<reponame>chuckmersereau/api_practice<filename>db/migrate/20170921213101_create_google_plus_accounts.rb<gh_stars>0 class CreateGooglePlusAccounts < ActiveRecord::Migration def change create_table :google_plus_accounts do |t| t.string :account_id t.string :profile_picture_link t.uuid :uuid, default: 'uuid_generate_v4()' t.belongs_to :email_address, index: true t.timestamps null: false end end end
chuckmersereau/api_practice
app/services/reports/goal_progress.rb
class Reports::GoalProgress < ActiveModelSerializers::Model attr_accessor :account_list delegate :designation_accounts, :in_hand_percent, :monthly_goal, :pledged_percent, :received_pledges, :salary_currency_or_default, :salary_organization_id, :total_pledges, to: :account_list def salary_balance designation_accounts.where(organization_id: salary_organization_id).where(active: true).to_a.sum do |designation_account| designation_account.converted_balance(salary_currency_or_default) end end end
chuckmersereau/api_practice
spec/services/account_list/restorer_spec.rb
require 'rails_helper' RSpec.describe AccountList::Restorer do describe 'initialize' do context 'account_list cannot be found' do it 'raises an error' do expect { described_class.new(SecureRandom.uuid) }.to raise_error(ActiveRecord::RecordNotFound) end end end describe '.restore' do let(:account_list_id) { SecureRandom.uuid } it 'calls RowTransferRequest' do expect(AccountList::Restorer).to receive(:new).with(account_list_id).and_return( OpenStruct.new( store: { 'people' => %w(123 456) } ) ) expect(RowTransferRequest).to receive(:transfer).with('people', %w(123 456)) described_class.restore(account_list_id) end end describe '#store' do before do 2.times { ApplicationSeeder.new.seed } end let(:user) { User.order(:created_at).first } let(:account_list) { user.account_lists.order(:created_at).first } subject { described_class.new(account_list.id).store } let!(:records_to_copy) do records_to_copy = {} [ account_list, account_list.account_list_coaches, account_list.account_list_entries, account_list.account_list_invites, account_list.account_list_users, account_list.activities, account_list.activities.collect(&:activity_contacts).flatten, account_list.activities.collect(&:comments).flatten, account_list.activities.collect(&:google_emails).flatten, account_list.activities.collect(&:google_email_activities).flatten, account_list.activities.collect(&:google_events).flatten, account_list.appeals, account_list.appeals.collect(&:appeal_contacts).flatten, account_list.appeals.collect(&:excluded_appeal_contacts).flatten, account_list.companies, account_list.company_partnerships, account_list.contacts, account_list.contacts.collect(&:addresses).flatten, account_list.contacts.collect(&:contact_donor_accounts).flatten, account_list.contacts.collect(&:contact_notes_logs).flatten, account_list.contacts.collect(&:contact_people).flatten, account_list.contacts.collect(&:contact_referrals_by_me).flatten, account_list.contacts.collect(&:donor_accounts).flatten, account_list.contacts.collect(&:partner_status_logs).flatten, account_list.designation_accounts, account_list.designation_accounts.collect(&:account_list_entries).flatten, account_list.designation_accounts.collect(&:balances).flatten, account_list.designation_accounts.collect(&:designation_profile_accounts).flatten, account_list.designation_accounts.collect(&:donations).flatten, account_list.designation_profiles, account_list.donations, account_list.pledges, account_list.pledges.collect(&:pledge_donations).flatten, account_list.google_integrations, account_list.imports, account_list.mail_chimp_account, account_list.mail_chimp_account.mail_chimp_appeal_list, account_list.mail_chimp_account.mail_chimp_members, account_list.notification_preferences, account_list.notifications, account_list.people, account_list.people.collect(&:companies).flatten, account_list.people.collect(&:company_positions).flatten, account_list.people.collect(&:donor_account_people).flatten, account_list.people.collect(&:donor_accounts).flatten, account_list.people.collect(&:facebook_accounts).flatten, account_list.people.collect(&:family_relationships).flatten, account_list.people.collect(&:google_accounts).flatten, account_list.people.collect(&:google_contacts).flatten, account_list.people.collect(&:key_accounts).flatten, account_list.people.collect(&:linkedin_accounts).flatten, account_list.people.collect(&:phone_numbers).flatten, account_list.people.collect(&:pictures).flatten, account_list.people.collect(&:twitter_accounts).flatten, account_list.people.collect(&:websites).flatten, account_list.people.collect(&:email_addresses).flatten, account_list.pls_account, account_list.prayer_letters_account, account_list.duplicate_record_pairs, GooglePlusAccount.where( id: account_list.people.joins(email_addresses: [:google_plus_account]).pluck('google_plus_accounts.id') ), MasterAddress.where( id: account_list.contacts.joins(addresses: [:master_address]).pluck('master_addresses.id') ), MasterCompany.where( id: account_list.people.joins(donor_accounts: [:master_company]).pluck('master_companies.id') + account_list.contacts.joins(donor_accounts: [:master_company]).pluck('master_companies.id') + account_list.companies.joins(:master_company).pluck('master_companies.id') ), MasterPerson.where( id: account_list.people.joins(:master_person).pluck('master_people.id') ), MasterPersonDonorAccount.where( id: account_list.people .joins(donor_accounts: [:master_person_donor_accounts]) .pluck('master_person_donor_accounts.id') + account_list.contacts .joins(donor_accounts: [:master_person_donor_accounts]) .pluck('master_person_donor_accounts.id') + account_list.contacts .joins(addresses: [source_donor_account: [:master_person_donor_accounts]]) .pluck('master_person_donor_accounts.id') ), MasterPersonSource.where( id: account_list.people .joins(master_person: [:master_person_sources]) .pluck('master_person_sources.id') ), ActsAsTaggableOn::Tag.where( id: account_list.contacts.joins(taggings: [:tag]).pluck('tags.id') + account_list.activities.joins(taggings: [:tag]).pluck('tags.id') ), ActsAsTaggableOn::Tagging.where( id: account_list.contacts.joins(:taggings).pluck('taggings.id') + account_list.activities.joins(:taggings).pluck('taggings.id') ) ].each do |record| if record.is_a?(ActiveRecord::Associations::CollectionProxy) || record.is_a?(ActiveRecord::Relation) || record.is_a?(Array) next if record.empty? table_name = record.first.class.table_name ids = record.collect(&:id) else table_name = record.class.table_name ids = [record.id] end records_to_copy[table_name] ||= [] records_to_copy[table_name] = (records_to_copy[table_name] + ids).uniq end records_to_copy end it 'store includes records associated to the account_list' do subject.each do |table_name, ids| expect(records_to_copy[table_name]).to match_array ids end end end end
chuckmersereau/api_practice
app/models/person/twitter_account.rb
<gh_stars>0 class Person::TwitterAccount < ApplicationRecord include Person::Account after_save :ensure_only_one_primary PERMITTED_ATTRIBUTES = [:created_at, :overwrite, :primary, :remote_id, :screen_name, :updated_at, :updated_in_db_at, :id].freeze validates :screen_name, presence: true def self.find_or_create_from_auth(auth_hash, person) relation_scope = person.twitter_accounts params = auth_hash.extra.access_token.params primary = person.twitter_accounts.empty? attributes = { remote_id: params[:screen_name], screen_name: params[:screen_name], token: params[:oauth_token], secret: params[:oauth_token_secret], valid_token: true, primary: primary } find_or_create_person_account( person: person, attributes: attributes, relation_scope: relation_scope ) end def to_s screen_name end def self.one_per_user? false end def queue_import_data end def url "http://twitter.com/#{screen_name}" if screen_name end private def ensure_only_one_primary primaries = person.twitter_accounts.where(primary: true) primaries[0..-2].map { |p| p.update_column(:primary, false) } if primaries.length > 1 end end
chuckmersereau/api_practice
app/models/notification_type/remind_partner_in_advance.rb
class NotificationType::RemindPartnerInAdvance < NotificationType def check_contacts_filter(contacts) contacts.financial_partners.where(['pledge_start_date is NULL OR pledge_start_date < ?', 30.days.ago]) .where(direct_deposit: false) .where('pledge_frequency >= ?', 3.0) end def check(account_list) notifications = [] check_contacts_filter(account_list.contacts).each do |contact| next unless contact.pledge_received? next unless early_by?(1.month, contact) prior_notification = Notification.active .where(contact_id: contact.id, notification_type_id: id) .where('event_date > ?', 2.months.ago) .exists? next if prior_notification next unless contact.donations.any? notification = contact.notifications.create!(notification_type_id: id, event_date: Time.zone.today) notifications << notification end notifications end def early_by?(days, contact) date_to_check = contact.last_donation_date || contact.pledge_start_date return false unless date_to_check.present? next_gift_date = date_to_check + contact.pledge_frequency.to_i.months next_gift_date > Time.zone.today && next_gift_date <= Time.zone.today + days + 1.day end def task_description_template(_notification = nil) _('%{contact_name} have an expected gift in one month. Contact to follow up.') end protected def task_activity_type _('To Do') end end
chuckmersereau/api_practice
app/models/contact_referral.rb
<reponame>chuckmersereau/api_practice class ContactReferral < ApplicationRecord PERMITTED_ATTRIBUTES = [:created_at, :overwrite, :referred_by_id, :referred_to_id, :updated_at, :updated_in_db_at, :id].freeze belongs_to :referred_by, class_name: 'Contact', foreign_key: :referred_by_id belongs_to :referred_to, class_name: 'Contact', foreign_key: :referred_to_id validates :referred_by_id, presence: true validates :referred_to_id, presence: true end
chuckmersereau/api_practice
app/services/contact/filter/city.rb
class Contact::Filter::City < Contact::Filter::Base def execute_query(contacts, filters) city_filters = parse_list(filters[:city]) city_filters << nil if city_filters.delete('none') contacts.where('addresses.city' => city_filters, 'addresses.historic' => filters[:address_historic] == 'true') .joins(:addresses) end def title _('City') end def parent _('Contact Location') end def type 'multiselect' end def custom_options account_list_cities = account_lists.map(&:cities) .flatten .uniq .select(&:present?) .map { |city| { name: city, id: city } } [{ name: _('-- None --'), id: 'none' }] + account_list_cities end end
chuckmersereau/api_practice
lib/json_api_service.rb
require 'json_api_service/configuration' require 'json_api_service/errors' require 'json_api_service/validator' require 'json_api_service/transformer' require 'json_api_service/params_object' module JsonApiService class << self attr_writer :configuration end def self.consume(params:, context:) Validator.validate!( params: params, context: context, configuration: configuration ) Transformer.transform( params: params, configuration: configuration ) end def self.configuration @configuration ||= Configuration.new end def self.configuration=(value) @configuration = value end def self.configure yield(configuration) end end
chuckmersereau/api_practice
spec/controllers/api/v2/deleted_records_controller_spec.rb
<filename>spec/controllers/api/v2/deleted_records_controller_spec.rb<gh_stars>0 require 'rails_helper' describe Api::V2::DeletedRecordsController, type: :controller do let(:factory_type) { :deleted_record } # first user let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:designation_account) { create(:designation_account) } let!(:account_list_entry) { create(:account_list_entry, account_list: account_list, designation_account: designation_account) } let!(:second_user) { create(:user_with_account) } let!(:second_account_list) { second_user.account_lists.order(:created_at).first } before(:each) do 3.times do |number| create(:deleted_record, deleted_from: account_list, deleted_by: user, deleted_at: Date.current - number.day) end create(:deleted_record, deleted_from: account_list, deleted_by: user, deleted_at: Date.current - 2.years) create(:deleted_task_record, deleted_from: account_list, deleted_by: user, deleted_at: Date.current - 2.years) create(:deleted_donation_record, deleted_from_id: designation_account.id, deleted_from_type: designation_account.class.name, deleted_by: user, deleted_at: Date.current) create(:deleted_task_record, deleted_from: second_account_list, deleted_by: user, deleted_at: Date.current - 1.day) end let(:unpermitted_attributes) { nil } let(:correct_attributes) { attributes_for(:deleted_record, deleted_from: account_list, deleted_by: user) } let(:incorrect_attributes) { attributes_for(:deleted_record, deleted_from: nil) } describe 'get all deleted records' do it 'that have been created by a specific time' do api_login(user) get :index, filter: { since_date: Date.current.beginning_of_year.iso8601 } data = JSON.parse(response.body)['data'] expect(data.size).to eq(4) end it 'that have been created by a specific DateTime' do api_login(user) get :index, filter: { since_date: Time.current.beginning_of_year.utc.iso8601 } data = JSON.parse(response.body)['data'] expect(data.size).to eq(4) end it 'should only get deleted records that are Contacts' do api_login(user) get :index, filter: { types: 'Contact' } data = JSON.parse(response.body)['data'] expect(data.size).to eq(4) data.each do |hash| expect(hash['attributes']['deletable_type']).to eq('Contact') end end it 'should only get deleted records that are Tasks' do api_login(user) get :index, filter: { types: 'Activity' } data = JSON.parse(response.body)['data'] expect(data.size).to eq(1) data.each do |hash| expect(hash['attributes']['deletable_type']).to eq('Activity') end end it 'should only get deleted records that are Donations' do api_login(user) get :index, filter: { types: 'Donation' } data = JSON.parse(response.body)['data'] expect(data.size).to eq(1) data.each do |hash| expect(hash['attributes']['deletable_type']).to eq('Donation') end end it 'should get all Task and Contact records' do api_login(user) get :index, filter: { types: 'Activity, Contact' } data = JSON.parse(response.body)['data'] expect(data.size).to eq(5) data.each do |hash| expect(hash['attributes']['deletable_type']).to be_in(%w(Contact Activity)) end end it 'should get Task records for a specific period' do api_login(user) start_date = Date.current.beginning_of_year - 2.years get :index, filter: { types: 'Activity', since_date: "#{start_date.iso8601}..#{Date.current.iso8601}" } data = JSON.parse(response.body)['data'] expect(data.size).to eq(1) end it 'should get all records for an account list id' do api_login(user) get :index data = JSON.parse(response.body)['data'] expect(data.size).to eq(6) end end end
chuckmersereau/api_practice
app/mailers/chalkline_mailer.rb
class ChalklineMailer < ApplicationMailer TIME_ZONE = 'Central Time (US & Canada)'.freeze default to: ENV.fetch('CHALKLINE_NEWSLETTER_EMAIL') def mailing_list(account_list) @name = account_list.users_combined_name user_emails = account_list.user_emails_with_names time_formatted = Time.now.in_time_zone(TIME_ZONE).strftime('%Y%m%d %l%M%P') filename = "#{@name} #{time_formatted}.csv".gsub(/\s+/, '_').downcase attachments[filename] = { mime_type: 'text/csv', content: CsvExport.mailing_addresses( ContactFilter.new(newsletter: 'address').filter(account_list.contacts, account_list) ) } mail subject: format(_('MPDX List: %{name}'), name: @name), cc: user_emails, reply_to: user_emails end end
chuckmersereau/api_practice
spec/services/reports/activity_results_period_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe Reports::ActivityResultsPeriod, type: :model do let(:account_list) { create(:account_list) } let(:start_date) { Date.current.beginning_of_year } let(:end_date) { Date.current.end_of_day } let(:params) { { account_list: account_list, start_date: start_date, end_date: end_date } } # use method to bust caching inside of the report def report described_class.new(params) end def activity_state ::Task::TASK_ACTIVITIES.each do |activity_type| ::Task::REPORT_STATES.each do |state| yield(activity_type, state) end end end def create_activity(type:, completed:) completed_state = completed == 'completed' account_list.activities.create!( activity_type: type, completed: completed_state, subject: "Testing #{type} that is #{completed_state}" ) end def create_numerous_activities(number, activity_type, completed) number.times do create_activity(type: activity_type, completed: completed) end end # This is not an optimal way of testing. Ideally, RSpec's describe/it block's # scoping would allow us to use the +activity_state+ block method to create # an +it+ spec for each +activity_type+ and it's +state+. describe 'activity counts' do it 'have correct counts' do activity_state do |activity_type, state| rand_number = rand(1..5) method_name = "#{state}_#{activity_type.parameterize.underscore.to_sym}" create_numerous_activities(rand_number, activity_type, state) expect(report.send(method_name)).to eq rand_number end end end end
chuckmersereau/api_practice
app/models/notification_type/recontinuing_gift.rb
<gh_stars>0 class NotificationType::RecontinuingGift < NotificationType MONTHS_LATE_WHEN_RECONTINUED = 2 def check_contacts_filter(contacts) contacts.financial_partners.where.not(pledge_frequency: nil) .where('pledge_frequency < ?', LongTimeFrameGift::LONG_TIME_FRAME_PLEDGE_FREQUENCY) .where(pledge_received: true) end def check_for_donation_to_notify(contact) contact.last_donation if self.class.had_recontinuing_gift?(contact) end def self.had_recontinuing_gift?(contact) return unless contact.pledge_amount && contact.pledge_frequency # A gift is only "recontiuing" if the prior gift was given when the contact # was a financial partner. return unless contact.prev_month_donation_date.present? && contact.status_on_date(contact.prev_month_donation_date) == 'Partner - Financial' contact.last_monthly_total >= contact.pledge_amount && contact.months_from_prev_to_last_donation.present? && contact.months_from_prev_to_last_donation >= (contact.pledge_frequency + MONTHS_LATE_WHEN_RECONTINUED) end def task_description_template(notification = nil) if notification&.account_list&.designation_accounts&.many? _('%{contact_name} recontinued their giving with a gift of %{amount} '\ 'on %{date} to %{designation}. Send them a Thank You.') else _('%{contact_name} recontinued their giving with a gift of %{amount} on %{date}. Send them a Thank You.') end end end
chuckmersereau/api_practice
spec/services/csv_import_spec.rb
<filename>spec/services/csv_import_spec.rb require 'rails_helper' describe CsvImport do let!(:csv_import) { build(:csv_import, tags: 'csv, test') } let!(:import) { CsvImport.new(csv_import) } before do Sidekiq::Testing.inline! stub_smarty_streets end it 'defines constants that are consistent with the supported headers' do expect(CsvImport.supported_headers.keys & CsvImport.constants.keys).to eq CsvImport.constants.keys end it 'defines required headers that are consistent with the supported headers' do expect(CsvImport.supported_headers.keys & CsvImport.required_headers.keys).to eq CsvImport.required_headers.keys end describe '.supported_headers' do it 'returns a Hash of Strings' do expect(CsvImport.supported_headers).to be_a_hash_with_types(Symbol, String) end end describe '.required_headers' do it 'returns a Hash of Strings' do expect(CsvImport.required_headers).to be_a_hash_with_types(Symbol, String) end end describe '.constants' do it 'returns a Hash of Hashes' do expect(CsvImport.constants).to be_a_hash_with_types(Symbol, Array) end end describe '#each_row' do let!(:csv_import) { build(:csv_import_custom_headers) } let!(:import) { CsvImport.new(csv_import) } it 'enumerates through the csv rows' do rows = [] import.each_row do |csv_row| expect(csv_row).to be_a(CSV::Row) expect(csv_row.headers).to be_present expect(csv_row.fields).to be_present rows << csv_row end expect(rows.size).to eq(3) end end context 'csv file quirks' do before do csv_import.update(in_preview: true) csv_import.file_headers_mappings = { 'church' => 'church', 'city' => 'mailing_city', 'pledge_amount' => 'commitment_amount', 'pledge_currency' => 'commitment_currency', 'pledge_frequency' => 'commitment_frequency', 'country' => 'mailing_country', 'email_1' => 'primary_email', 'envelope_greeting' => 'envelope_greeting', 'first_name' => 'first_name', 'greeting' => 'greeting', 'last_name' => 'last_name', 'newsletter' => 'newsletter', 'notes' => 'notes', 'phone_1' => 'primary_phone', 'spouse_email' => 'spouse_email', 'spouse_first_name' => 'spouse_first_name', 'spouse_phone' => 'spouse_phone', 'state' => 'mailing_state', 'status' => 'status', 'street' => 'mailing_street_address', 'tags' => 'tags', 'zip' => 'mailing_postal_code' } csv_import.file_constants_mappings = { 'pledge_currency' => [ { id: 'CAD', values: ['CAD'] } ], 'pledge_frequency' => [ { id: 'Monthly', values: ['Monthly'] } ], 'newsletter' => [ { id: 'Both', values: ['Both'] } ], 'status' => [ { id: 'Partner - Pray', values: ['Partner - Pray'] } ] } end it 'does not error if the csv file has a byte order mark' do csv_import.update(file: File.new(Rails.root.join('spec/fixtures/sample_csv_with_bom.csv'))) import.update_cached_file_data csv_import.update(in_preview: false) expect { import.import }.to change { Contact.count }.from(1).to(2) contact = Contact.first expect(contact.account_list).to eq(csv_import.account_list) expect(contact.to_s).to eq('Doe, John and Jane') end it 'does not error if the csv file has a non-utf-8 encoding' do csv_import.update(file: File.new(Rails.root.join('spec/fixtures/sample_csv_iso_8950_1.csv'))) import.update_cached_file_data csv_import.file_constants_mappings = { 'pledge_currency' => [ { id: 'CAD', values: [''] } ], 'pledge_frequency' => [ { id: '', values: [''] } ], 'newsletter' => [ { id: '', values: [''] } ], 'status' => [ { id: 'Partner - Pray', values: [''] } ] } csv_import.update(in_preview: false) expect { import.import }.to change { Contact.count }.from(1).to(2) expect(Contact.first.name).to eq('<NAME>') end it 'changes None to an empty string in the send newsletter field' do csv_import.update(file: File.new(Rails.root.join('spec/fixtures/sample_csv_with_none.csv'))) import.update_cached_file_data csv_import.file_constants_mappings['newsletter'] = [ { id: '', values: ['None'] } ] csv_import.update(in_preview: false) expect { import.import }.to change { Contact.count }.from(1).to(2) expect(Contact.first.send_newsletter).to eq(nil) end it 'does not error if csv file uses inconsistent newlines like \n then later \r\n' do csv_import.update(file: File.new(Rails.root.join('spec/fixtures/sample_csv_inconsistent_newlines.csv'))) import.update_cached_file_data csv_import.update(in_preview: false) expect { import.import }.to change { Contact.count }.from(1).to(2) expect(Contact.first.name).to eq('<NAME> and Jane') end end context 'with mappings' do let!(:csv_import) { create(:csv_import_custom_headers, tags: 'csv, test', in_preview: true) } let!(:import) { CsvImport.new(csv_import) } before do csv_import.file_headers_mappings = { 'church' => 'church', 'city' => 'city', 'pledge_amount' => 'amount', 'pledge_currency' => 'currency', 'pledge_frequency' => 'frequency', 'country' => 'country', 'email_1' => 'email_address', 'first_name' => 'fname', 'greeting' => 'greeting', 'envelope_greeting' => 'mailing_greeting', 'last_name' => 'lname', 'likely_to_give' => 'likely_giver', 'metro_area' => 'metro', 'newsletter' => 'newsletter', 'notes' => 'extra_notes', 'phone_1' => 'phone', 'region' => 'region', 'send_appeals' => 'appeals', 'spouse_email' => 'spouse_email_address', 'spouse_first_name' => 'spouse_fname', 'spouse_last_name' => 'spouse_lname', 'spouse_phone' => 'spouse_phone_number', 'state' => 'province', 'status' => 'status', 'street' => 'street', 'tags' => 'tags', 'website' => 'website', 'zip' => 'zip_code' } csv_import.file_constants_mappings = { 'pledge_currency' => [ { id: 'CAD', values: ['CAD'] }, { id: 'USD', values: [''] } ], 'pledge_frequency' => [ { id: 'Monthly', values: ['Monthly'] }, { id: '', values: [''] } ], 'likely_to_give' => [ { id: 'Most Likely', values: ['Yes'] }, { id: 'Least Likely', values: ['No'] } ], 'newsletter' => [ { id: 'Both', values: ['Both'] } ], 'send_appeals' => [ { id: true, values: ['Yes'] }, { id: false, values: ['No'] } ], 'status' => [ { id: 'Partner - Financial', values: ['Praying and giving'] }, { id: 'Partner - Pray', values: ['Praying'] } ] } import.update_cached_file_data end describe '#import' do it 'parses the csv and saves the contacts' do csv_import.in_preview = false expect(csv_import).to be_valid expect { import.import }.to change(Contact, :count).from(0).to(3) expect(csv_import.account_list.contacts.reload.where(name: '<NAME> and Jane')).to be_present end it 'aborts if the import is invalid' do csv_import.in_preview = false csv_import.file_constants_mappings = nil csv_import.file_headers_mappings = nil expect(csv_import).to be_invalid expect do expect { import.import }.to raise_error RuntimeError end.not_to change { Contact.count } end it 'aborts if the import is in preview' do csv_import.in_preview = true expect(csv_import).to be_valid expect do expect { import.import }.to raise_error RuntimeError end.not_to change { Contact.count } end it 'returns true when queueing jobs' do csv_import.in_preview = false expect(import.import).to eq(true) end it 'returns false if no jobs were queued' do allow_any_instance_of(ImportUploader).to receive(:path).and_return( Rails.root.join('spec/fixtures/sample_csv_blank.csv').to_s ) csv_import.in_preview = false expect(import.import).to eq(false) end it 'queues a sidekiq batch' do csv_import.in_preview = false expect { import.import }.to change { Sidekiq::BatchSet.new.count }.by(1) end it 'imports valid contacts successfully and stores invalid contacts in the file_row_failures' do allow_any_instance_of(ImportUploader).to receive(:path).and_return( Rails.root.join('spec/fixtures/sample_csv_with_some_invalid_rows.csv').to_s ) csv_import.in_preview = false expect do expect(import.import).to eq(true) end.to change { Contact.count }.by(1) expect(csv_import.reload.file_row_failures.size).to eq(2) end it 'imports if file_constants is blank' do csv_import.file_headers = { 'first_name' => 'first_name', 'church' => 'church' } csv_import.file_headers_mappings = { 'first_name' => 'first_name', 'church' => 'church' } csv_import.file_constants_mappings = {} csv_import.file_constants = {} csv_import.in_preview = false expect(csv_import).to be_valid expect { import.import }.to change(Contact, :count).from(0).to(3) expect(csv_import.account_list.contacts.reload.where(name: '<NAME>')).to be_present end end describe '#sample_contacts' do it 'returns sample contacts' do expect(import.sample_contacts).to be_a Array expect(import.sample_contacts.size).to eq 3 expect(import.sample_contacts.first.name).to eq '<NAME> and Jane' expect(import.sample_contacts.second.name).to eq 'Park and Kim, Bob and Sara' expect(import.sample_contacts.third.name).to eq '<NAME>' import.sample_contacts.each do |sample_contact| expect(sample_contact).to be_a Contact expect(sample_contact.id).to be_present expect(Contact.find_by(id: sample_contact.id)).to be_blank end end it 'generates ids for all of the objects' do import.sample_contacts.each do |contact| expect(contact.id).to be_present expect(contact.primary_person.id).to be_present expect(contact.spouse.id).to be_present if contact.spouse contact.addresses.each { |address| expect(address.id).to be_present } contact.primary_person.email_addresses.each { |email_address| expect(email_address.id).to be_present } contact.primary_person.phone_numbers.each { |phone_number| expect(phone_number.id).to be_present } if contact.spouse contact.spouse.email_addresses.each { |email_address| expect(email_address.id).to be_present } contact.spouse.phone_numbers.each { |phone_number| expect(phone_number.id).to be_present } end end end end end describe '#update_cached_file_data' do it 'assigns file_headers when setting file' do import = create(:csv_import_custom_headers, in_preview: true) csv_import = CsvImport.new(import) expect { csv_import.update_cached_file_data }.to change { import.reload.file_headers }.from({}).to( 'fullname' => 'fullname', 'fname' => 'fname', 'lname' => 'lname', 'spouse_fname' => 'Spouse-fname', 'spouse_lname' => 'Spouse-lname', 'greeting' => 'greeting', 'mailing_greeting' => 'mailing-greeting', 'church' => 'church', 'street' => 'street', 'city' => 'city', 'province' => 'province', 'zip_code' => 'zip-code', 'country' => 'country', 'status' => 'status', 'amount' => 'amount', 'frequency' => 'frequency', 'currency' => 'currency', 'newsletter' => 'newsletter', 'tags' => 'tags', 'email_address' => 'email-address', 'spouse_email_address' => 'Spouse-email-address', 'phone' => 'phone', 'spouse_phone_number' => 'Spouse-phone-number', 'extra_notes' => 'extra-notes', 'skip' => 'skip', 'likely_giver' => 'likely-giver', 'metro' => 'metro', 'region' => 'region', 'appeals' => 'appeals', 'website' => 'website', 'referred_by' => 'referred_by' ) end it 'assigns file_constants when setting file' do import = create(:csv_import_custom_headers, in_preview: true) csv_import = CsvImport.new(import) expect { csv_import.update_cached_file_data }.to change { import.reload.file_constants }.from({}).to( 'greeting' => Set.new(['Hi John and Jane', 'Hello!', '']), 'status' => Set.new(['Praying', 'Praying and giving']), 'amount' => Set.new(['50', '10', '']), 'frequency' => Set.new(['Monthly', '']), 'newsletter' => Set.new(['Both']), 'currency' => Set.new(['CAD', '']), 'skip' => Set.new(['No', 'Yes', '']), 'likely_giver' => Set.new(%w(Yes No)), 'appeals' => Set.new(%w(Yes No)) ) end it 'assigns file_row_samples when setting file' do import = create(:csv_import_custom_headers, in_preview: true) csv_import = CsvImport.new(import) expect { csv_import.update_cached_file_data }.to change { import.reload.file_row_samples }.from([]).to( [ [ 'Johnny and <NAME>', ' John', 'Doe', 'Jane ', 'Doe', 'Hi John and Jane', 'Doe family', 'Westside Baptist Church', '1 Example Ave, Apt 6', 'Sample City', 'IL', '60201', 'USA', 'Praying', '50', 'Monthly', 'CAD', 'Both', 'christmas-card, family', ' <EMAIL> ', ' <EMAIL> ', '(213) 222-3333', '(407) 555-6666', 'test notes', 'No', 'Yes', 'metro', 'region', 'Yes', 'http://www.john.doe', '<NAME>' ], [ 'Bobby & <NAME>', 'Bob', 'Park', 'Sara', 'Kim', 'Hello!', nil, nil, '123 Street West ', 'A Small Town', 'Quebec', 'L8D 3B9 ', 'Canada', 'Praying and giving', '10', 'Monthly', nil, 'Both', 'bob', '<EMAIL>', '<EMAIL>', '+12345678901', '+10987654321', nil, 'Yes', 'No', 'metro', 'region', 'No', 'website', nil ], [ '<NAME>', 'Joe', 'Man', nil, nil, nil, nil, nil, 'Apartment, Unit 123', 'Big City', 'BC', nil, 'CA', 'Praying', nil, nil, nil, 'Both', nil, '<EMAIL>', nil, '123.456.7890', nil, 'notes', nil, 'Yes', 'metro', 'region', 'Yes', 'website', nil ] ] ) end end describe '#generate_csv_from_file_row_failures' do let(:import) { create(:csv_import_with_mappings) } let(:csv_import) { CsvImport.new(import) } before do import.in_preview = false allow_any_instance_of(ImportUploader).to receive(:path).and_return( Rails.root.join('spec/fixtures/sample_csv_with_some_invalid_rows.csv').to_s ) csv_import.import import.reload end it 'generates a csv file as a string that contains the failed rows' do expect(csv_import.generate_csv_from_file_row_failures).to eq( 'Error Message,fullname,fname,lname,Spouse-fname,Spouse-lname,greeting,mailing-greeting,church,' \ 'street,city,province,zip-code,country,status,amount,frequency,currency,newsletter,tags,' \ 'email-address,Spouse-email-address,phone,Spouse-phone-number,extra-notes,skip,likely-giver' \ ",metro,region,appeals,website,referred_by\n\"Validation failed: Email is invalid, Email is invalid\",Bob" \ ',Park,Sara,Kim,Hello!,,,123 Street West,A Small Town,Quebec,L8D 3B9,Canada,Praying and giving' \ ',10,Monthly,,Both,bob,this is not a valid email,this is also not a valid email,+12345678901' \ ",+10987654321,,Yes,No,metro,region,No,website\n\"Validation failed: First name can't be blank, " \ "Name can't be blank\",,,,,,,,\"Apartment, Unit 123\",Big City,BC,,CA,Praying,,,,Both,,<EMAIL>" \ ",,123.456.7890,,notes,,Yes,metro,region,Yes,website\n" ) end end context 'with full name' do let!(:csv_import) { build(:csv_import_fullname, tags: 'csv, test') } let!(:import) { CsvImport.new(csv_import) } before do csv_import.update(in_preview: true) csv_import.file_headers_mappings = { 'full_name' => 'full_name', 'city' => 'mailing_city', 'pledge_amount' => 'commitment_amount', 'pledge_frequency' => 'commitment_frequency', 'country' => 'mailing_country', 'email_1' => 'primary_email', 'envelope_greeting' => 'envelope_greeting', 'greeting' => 'greeting', 'newsletter' => 'newsletter', 'notes' => 'notes', 'phone_1' => 'primary_phone', 'spouse_email' => 'spouse_email', 'spouse_first_name' => 'spouse_first_name', 'spouse_phone' => 'spouse_phone', 'state' => 'mailing_state', 'status' => 'status', 'street' => 'mailing_street_address', 'tags' => 'tags', 'zip' => 'mailing_postal_code' } csv_import.file_constants_mappings = { 'pledge_frequency' => [ { id: 'Monthly', values: ['Monthly'] } ], 'newsletter' => [ { id: 'Both', values: ['Both'] } ], 'status' => [ { id: 'Partner - Pray', values: ['Partner - Pray'] } ] } import.update_cached_file_data end it 'returns contact with full name' do csv_import.update(in_preview: false) expect { import.import }.to change { Contact.count }.from(1).to(2) expect(Contact.first.name).to eq('<NAME>') end end end
chuckmersereau/api_practice
db/migrate/20141230003854_make_name_male_ratios_name_unique.rb
class MakeNameMaleRatiosNameUnique < ActiveRecord::Migration def change remove_index :name_male_ratios, :name add_index :name_male_ratios, :name, unique: true end end
chuckmersereau/api_practice
spec/support/shared_controller_examples/bulk_update_examples.rb
<reponame>chuckmersereau/api_practice RSpec.shared_examples 'bulk_update_examples' do |options = {}| options[:except] ||= [] include_context 'common_variables' describe '#update' do let(:unauthorized_resource) { create(factory_type) } let(:bulk_update_attributes) do { data: [ { data: { type: resource_type, id: resource.id, attributes: correct_attributes.merge(updated_in_db_at: resource.updated_at) }.merge!(relationships: relationships) }, { data: { type: resource_type, id: second_resource.id, attributes: incorrect_attributes }.merge!(relationships: relationships) }, { data: { type: resource_type, id: third_resource.id, attributes: correct_attributes.merge(updated_in_db_at: third_resource.updated_at) }.merge!(relationships: relationships) } ] } end let(:response_body) { JSON.parse(response.body) } let(:response_errors) { response_body['errors'] } before do api_login(user) end it 'returns a 200 and the list of updated resources' do put :update, bulk_update_attributes expect(response.status).to eq(200), invalid_status_detail expect(response_body.length).to eq(3) end it 'updates the resources which belong to user and do not have errors' do expect do expect do put :update, bulk_update_attributes end.to change { resource.reload.updated_at }.and change { third_resource.reload.updated_at } end.to_not change { second_resource.updated_at } expect(response_body.detect { |hash| hash.dig('data', 'id') == resource.id }['errors']).to be_blank expect(response_body.detect { |hash| hash.dig('id') == second_resource.id }['errors']).to be_present expect(response_body.detect { |hash| hash.dig('data', 'id') == third_resource.id }['errors']).to be_blank end it 'returns error objects for resources that were not updated, but belonged to user' do expect do put :update, bulk_update_attributes end.to_not change { second_resource.reload.send(reference_key) } response_with_errors = response_body.detect { |hash| hash.dig('id') == second_resource.id } expect(response_with_errors['errors']).to be_present expected_error = response_with_errors['errors'].detect do |hash| hash.dig('source', 'pointer') == "/data/attributes/#{reference_key}" end expect(expected_error).to be_present end context 'resources not found' do it 'responds correctly if all resources are not found' do put :update, data: [{ data: { type: resource_type, id: SecureRandom.uuid } }] expect(response.status).to eq(404), invalid_status_detail expect(response_body['errors']).to be_present expect(response_body['data']).to be_blank end it 'responds correctly if only some resources are not found' do bulk_update_attributes[:data] << { data: { type: resource_type, id: SecureRandom.uuid } } put :update, data: bulk_update_attributes[:data] expect(response.status).to eq(200), invalid_status_detail expect(response_body.size).to eq(3) end end context 'request mixes resources that do belong to and do not belong to the current user' do let!(:bulk_update_attributes) do { data: [ { data: { type: resource_type, id: resource.id, attributes: correct_attributes.merge(overwrite: true) } }, { data: { type: resource_type, id: second_resource.id, attributes: incorrect_attributes } }, { data: { type: resource_type, id: unauthorized_resource.id, attributes: correct_attributes.merge(overwrite: true) } } ] } end it 'still updates some resources' do expect do put :update, bulk_update_attributes end.to change { resource.class.order(:updated_at).last.updated_at } expect(response.status).to eq(200), invalid_status_detail end end context 'resources forbidden' do let!(:bulk_update_attributes_with_forbidden_resource) do { data: [ { data: { type: resource_type, id: resource.id, attributes: correct_attributes.merge(overwrite: true) } }, { data: { type: resource_type, id: second_resource.id, attributes: correct_attributes.merge(overwrite: true), relationships: { account_list: { data: { id: create(:account_list).id, type: 'account_lists' } } } } }, { data: { type: resource_type, id: third_resource.id, attributes: correct_attributes.merge(overwrite: true) } } ] } end it 'does not update resources that do not belong to current user' do data_hash = { type: resource_type, id: unauthorized_resource.id, attributes: { reference_key => reference_value } } put :update, data: [{ data: data_hash }] expect(unauthorized_resource.reload.send(reference_key)).to_not eq(reference_value) expect(response.status).to eq(404), invalid_status_detail expect(response_errors.size).to eq(1) end it 'does not update resources for users that are not signed in' do api_logout expect do put :update end.not_to change { resource.class.order(:updated_at).last.updated_at } expect(response.status).to eq(401), invalid_status_detail end unless options[:except].include?(:forbidden_resources) it "returns a 403 when user tries to associate resource to an account list that doesn't belong to him" do expect do put :update, bulk_update_attributes_with_forbidden_resource end.not_to change { resource.class.order(:updated_at).last.updated_at } expect(response.status).to eq(403), invalid_status_detail end end end end end
chuckmersereau/api_practice
spec/services/mail_chimp/importer/matcher_spec.rb
require 'rails_helper' RSpec.describe MailChimp::Importer::Matcher do let(:mail_chimp_account) { build(:mail_chimp_account) } let(:account_list) { mail_chimp_account.account_list } subject { described_class.new(mail_chimp_account) } context '#find_matching_people' do let(:first_email) { '<EMAIL>' } let(:formatted_member_infos) do [ { email: first_email, first_name: '<NAME>', last_name: '<NAME>', greeting: 'Greeting', groupings: 'Random Grouping', status: 'subscribed' }, { email: '<EMAIL>', first_name: '<NAME>', last_name: '<NAME>', greeting: 'Second Greeting', groupings: 'Second Random Grouping', status: 'subscribed' } ] end let(:contact) { create(:contact, account_list: account_list) } let!(:person) do create(:person, contacts: [contact], primary_email_address: build(:email_address, email: first_email.downcase)) end it 'returns a hash of people matching mail chimp member_infos' do expect(subject.find_matching_people(formatted_member_infos)).to eq( person.id => { 'email' => '<EMAIL>', 'first_name' => '<NAME>', 'last_name' => '<NAME>', 'greeting' => 'Greeting', 'groupings' => 'Random Grouping', 'status' => 'subscribed' } ) end end end
chuckmersereau/api_practice
app/serializers/reports/goal_progress_serializer.rb
<reponame>chuckmersereau/api_practice class Reports::GoalProgressSerializer < ServiceSerializer delegate :account_list, :in_hand_percent, :monthly_goal, :pledged_percent, :received_pledges, :salary_balance, :salary_currency_or_default, :total_pledges, to: :object belongs_to :account_list attributes :in_hand_percent, :monthly_goal, :pledged_percent, :received_pledges, :salary_balance, :salary_currency_or_default, :salary_organization_id, :total_pledges def salary_organization_id Organization.where(id: account_list.salary_organization_id) .limit(1) .pluck(:id) .first end end
chuckmersereau/api_practice
app/models/background_batch.rb
class BackgroundBatch < ApplicationRecord belongs_to :user validates :user, presence: true has_many :requests, class_name: 'BackgroundBatch::Request', dependent: :destroy validates :requests, length: { minimum: 1 } validates_associated :requests accepts_nested_attributes_for :requests after_validation :create_batch, on: :create after_commit :create_workers, on: :create PERMITTED_ATTRIBUTES = [ :id, requests_attributes: [ :default_account_list, :path, :request_params, :request_body, :request_headers, :request_method, :id ] ].freeze def status @status ||= Sidekiq::Batch::Status.new(batch_id) end protected def create_batch @batch = Sidekiq::Batch.new self.batch_id = @batch.bid end def create_workers @batch.jobs do requests.each { |request| BackgroundBatch::RequestWorker.perform_async(request.id) } end end end
chuckmersereau/api_practice
app/services/reports/pledge_increase_contact.rb
class Reports::PledgeIncreaseContact < ActiveModelSerializers::Model attr_accessor :contact, :beginning, :end_status def beginning_converted convert(beginning_monthly, beginning_currency) end def beginning_monthly pledge_from_status(beginning) end def beginning_currency beginning.try(:[], 'pledge_currency') || default_currency end def end_converted convert(end_monthly, end_currency) end def end_monthly # use current contact values if there have been no changes since the end of the window pledge_from_status(end_status || contact) end def end_currency (end_status || contact).pledge_currency end def increase_amount @increase_amount ||= (end_converted - beginning_converted) end private def convert(amount, currency) CurrencyRate.convert_with_latest(amount: amount, from: currency, to: default_currency) end def default_currency @default_currency = contact.account_list.salary_currency_or_default end def pledge_from_status(status) return 0 unless status&.status == 'Partner - Financial' status.pledge_amount.to_i / (status.pledge_frequency || 1) end end
chuckmersereau/api_practice
db/migrate/20181001171217_create_sessions.rb
<gh_stars>0 class CreateSessions < ActiveRecord::Migration def change create_table :sessions, id: :uuid do |t| t.uuid :user t.integer :sid t.timestamps null: false end end end
chuckmersereau/api_practice
app/services/account_list/readable_finder.rb
# Finds [AccountList] records which a given user either has access to, or is a # [User::Coach] of. class AccountList::ReadableFinder delegate :to_sql, to: :query def initialize(user_or_id) @user_or_id = user_or_id end def user @user ||= @user_or_id.is_a?(User) ? @user_or_id : User.find(@user_or_id) end def relation AccountList.where(to_sql) end private def query arel_account_lists[:id].in(subquery) end def subquery join_tables(arel_account_lists).where(where_clause).project(projection) end def join_tables(arel) arel.join(arel_coaches, Arel::Nodes::OuterJoin) .on(arel[:id].eq(arel_coaches[:account_list_id])) .join(arel_users, Arel::Nodes::OuterJoin) .on(arel[:id].eq(arel_users[:account_list_id])) end def where_clause arel_users[:user_id].eq(user.id).or(arel_coaches[:coach_id].eq(user.id)) end def projection arel_account_lists[:id] end def arel_account_lists @arel_account_lists ||= AccountList.arel_table end def arel_coaches @arel_coaches ||= AccountListCoach.arel_table end def arel_users @arel_users ||= AccountListUser.arel_table end end
chuckmersereau/api_practice
spec/services/google_contacts_integrator_spec.rb
require 'rails_helper' describe GoogleContactsIntegrator do let(:now) { Time.now.utc } before do stub_request(:get, %r{https://api\.smartystreets\.com/street-address/.*}).to_return(body: '[]') @user = create(:user) @account = create(:google_account, person_id: @user.id) @account_list = create(:account_list, creator: @user, log_debug_info: true) @integration = create(:google_integration, google_account: @account, account_list: @account_list, contacts_integration: true, calendar_integration: false) @integrator = GoogleContactsIntegrator.new(@integration) @contact = create(:contact, account_list: @account_list, status: 'Partner - Pray', notes: 'about') @person = create(:person, first_name: 'John', last_name: 'Google', occupation: 'Worker', employer: 'Company, Inc') @contact.people << @person @g_contact = GoogleContactsApi::Contact.new( 'gd$etag' => 'a', 'id' => { '$t' => '1' }, 'gd$name' => { 'gd$givenName' => { '$t' => 'John' }, 'gd$familyName' => { '$t' => 'Google' } } ) @api_url = 'https://www.google.com/m8/feeds/contacts' end describe 'sync_contacts basic function' do it 'syncs contacts and records last synced time' do expect(@integrator).to receive(:setup_assigned_remote_ids) expect(@integrator).to receive(:contacts_to_sync) .and_return(Contact.where(id: @contact.id)) expect(@integrator).to receive(:sync_contact).with(@contact) expect(Time).to receive(:now).at_least(:once).and_return(now) @integrator.sync_contacts expect(@integration.contacts_last_synced).to eq(now) end it 'does not re-raise a missing refresh token error' do expect_any_instance_of(Person::GoogleAccount).to receive(:contacts_api_user) .and_raise(Person::GoogleAccount::MissingRefreshToken) expect { @integrator.sync_contacts }.not_to raise_error end end describe 'contacts_to_sync' do before do @integrator.cache = GoogleContactsCache.new(@account) end it 'returns all active contacts if not synced yet' do expect(@integration.account_list).to receive(:active_contacts).and_return([@contact]) expect(@account.contacts_api_user).to receive(:contacts).and_return([@g_contact]) expect(@integrator.contacts_to_sync).to eq([@contact]) end it 'returns queried contacts for subsequent sync' do @integration.update_column(:contacts_last_synced, now) g_contact = double(id: 'id_1', given_name: 'John', family_name: 'Google') expect(@account.contacts_api_user).to receive(:contacts_updated_min) .with(now, showdeleted: false).and_return([g_contact]) expect(@integrator).to receive(:contacts_to_sync_query).with([g_contact]).and_return([@contact]) expect(@integrator.contacts_to_sync).to eq([@contact]) end end describe 'mpdx_group' do it 'searches for an existing group which matches the goal title, and caches it' do mpdx_group = double(title: GoogleContactsIntegrator::CONTACTS_GROUP_TITLE) expect(@integrator.api_user).to receive(:groups).exactly(:once).and_return([mpdx_group]) expect(@integrator.mpdx_group).to eq(mpdx_group) # Test a second time to check that it caches it rather than calling the API again expect(@integrator.mpdx_group).to eq(mpdx_group) end it 'creates a group if none match its title do' do not_mpdx_group = double(title: 'not-mpdx-group-title') mpdx_group = double expect(@integrator.api_user).to receive(:groups).exactly(:once).and_return([not_mpdx_group]) expect(GoogleContactsApi::Group).to receive(:create).exactly(:once) .with({ title: GoogleContactsIntegrator::CONTACTS_GROUP_TITLE }, @integrator.api_user.api) .and_return(mpdx_group) expect(@integrator.mpdx_group).to eq(mpdx_group) # Test a second time to check that it caches it rather than calling the API again expect(@integrator.mpdx_group).to eq(mpdx_group) end end describe 'my_contacts_group' do it 'searches for the system group with id of Contacts' do my_contacts = double(system_group_id: 'Contacts', id: 1) expect(@integrator).to receive(:groups).and_return([double(system_group_id: nil), my_contacts]) expect(@integrator.my_contacts_group).to eq(my_contacts) end end describe 'contacts_to_sync_query' do before do @g_contact = create(:google_contact, google_account: @account, person: @person, contact: @contact) end def contacts_to_sync_query(updated_remote_ids = []) @integrator.contacts_to_sync_query(updated_remote_ids).reload.to_a end def expect_contact_sync_query(result) expect(contacts_to_sync_query).to eq(result) end it 'returns active contacts and not inactive' do expect_contact_sync_query([@contact]) @contact.update_column(:status, 'Not Interested') expect_contact_sync_query([]) end it 'only returns contacts that have been modified since last sync' do @g_contact.update_column(:last_synced, 1.hour.since) expect_contact_sync_query([]) @g_contact.update_column(:last_synced, 1.year.ago) expect_contact_sync_query([@contact]) end it 'detects modification of addresses, people, emails, phone numbers and websites' do @g_contact.update_column(:last_synced, 1.hour.since) expect_contact_sync_query([]) # Addresses @contact.addresses_attributes = [{ street: '1 Way' }] @contact.save expect_contact_sync_query([]) @contact.addresses.first.update_column(:updated_at, 2.hours.since) expect_contact_sync_query([@contact]) @contact.addresses.first.update_column(:updated_at, now) expect_contact_sync_query([]) # People @person.update_column(:updated_at, 2.hours.since) expect_contact_sync_query([@contact]) @person.update_column(:updated_at, now) expect_contact_sync_query([]) # Email @person.email = '<EMAIL>' @person.save expect_contact_sync_query([]) @person.email_addresses.first.update_column(:updated_at, 2.hours.since) expect_contact_sync_query([@contact]) @person.email_addresses.first.update_column(:updated_at, now) expect_contact_sync_query([]) # Phone @person.phone = '213-456-7890' @person.save expect(contacts_to_sync_query).to eq([]) @person.phone_numbers.first.update_column(:updated_at, 2.hours.since) expect(contacts_to_sync_query).to eq([@contact]) @person.phone_numbers.first.update_column(:updated_at, now) expect(contacts_to_sync_query).to eq([]) # Website @person.websites << Person::Website.new(url: 'example.com') @person.save expect(contacts_to_sync_query).to eq([]) @person.websites.first.update_column(:updated_at, 2.hours.since) expect(contacts_to_sync_query).to eq([@contact]) @person.websites.first.update_column(:updated_at, now) expect(contacts_to_sync_query).to eq([]) end it 'finds contacts whose remote g_contacts have been updated since the matching google_contacts records' do @g_contact.update_column(:last_synced, 1.hour.since) @g_contact.update_column(:remote_id, 'a') expect(contacts_to_sync_query([])).to eq([]) previously_updated_g_contact = double(id: 'a', updated: 2.hours.ago) expect(contacts_to_sync_query([previously_updated_g_contact])).to eq([]) since_sync_updated_g_contact = double(id: 'a', updated: 2.hours.since) expect(contacts_to_sync_query([since_sync_updated_g_contact])).to eq([@contact]) end it 'finds a contact to sync if there is a Google contact record in a different account and none for its account' do other_account = create(:google_account) create(:google_contact, google_account: other_account, person: @person, contact: nil) @g_contact.destroy expect_contact_sync_query([@contact]) end end describe 'logic for assigning each MPDX contact to a single Google contact' do describe 'setup_assigned_remote_ids' do it 'queries remote ids for the specific google account and account list' do create(:google_contact, remote_id: 'not in account list or google account') create(:google_contact, remote_id: 'id', person: @person, contact: @contact, google_account: @account) @integrator.setup_assigned_remote_ids expect(@integrator.assigned_remote_ids).to eq(['id'].to_set) end end describe 'get_or_query_g_contact' do it 'returns nil if a remote id is already assigned' do g_contact_link = double(remote_id: nil) g_contact = double(id: 'id', given_name: 'John', family_name: 'Google') @integrator.cache = double expect(@integrator.cache).to receive(:select_by_name).with('John', 'Google').exactly(:twice).and_return([g_contact]) @integrator.assigned_remote_ids = [].to_set expect(@integrator.get_or_query_g_contact(g_contact_link, @person)).to eq(g_contact) # Return nil if the id is already taken @integrator.assigned_remote_ids = ['id'].to_set expect(@integrator.get_or_query_g_contact(g_contact_link, @person)).to be_nil end end describe 'get_g_contact_and_link' do it 'marks the remote id of a queried g_contact as assigned and adds the g_contact to the mpdx group' do g_contact_link = create(:google_contact, remote_id: 'id', person: @person, contact: @contact, google_account: @account) g_contact = double(id: 'id', given_name: 'John', family_name: 'Google') expect(@integrator).to receive(:get_or_query_g_contact).with(g_contact_link, @person).and_return(g_contact) mpdx_group = double my_contacts_group = double expect(@integrator).to receive(:mpdx_group).and_return(mpdx_group) expect(@integrator).to receive(:my_contacts_group).and_return(my_contacts_group) expect(g_contact).to receive(:prep_add_to_group).once.with(mpdx_group) expect(g_contact).to receive(:prep_add_to_group).once.with(my_contacts_group) contact_person = @contact.contact_people.first @integrator.assigned_remote_ids = [].to_set expect(@integrator.get_g_contact_and_link(contact_person)).to eq([g_contact, g_contact_link]) expect(@integrator.assigned_remote_ids).to eq(['id'].to_set) end describe 'save_g_contact_links' do it 'marks the remote id of a saved g_contact as assigned' do g_contact_link = build(:google_contact, remote_id: 'id', person: @person, contact: @contact, google_account: @account) g_contact = double(id: 'id', formatted_attrs: {}, etag: '') @integrator.assigned_remote_ids = [].to_set @integrator.save_g_contact_links([[g_contact, g_contact_link]]) expect(@integrator.assigned_remote_ids).to eq(['id'].to_set) end end end end describe 'sync_contact' do let(:g_contact_link) { double(last_data: { given_name: 'John' }) } it 'does not save a g_contact if it has not changed since the last sync' do g_contact = double(attrs_with_changes: { given_name: 'John' }) contact_person = @contact.contact_people.first expect(@integrator).to receive(:get_g_contact_and_link).with(contact_person).and_return([g_contact, g_contact_link]) expect(GoogleContactSync).to receive(:sync_contact).with(@contact, [[g_contact, g_contact_link]]) expect(@integrator).to receive(:save_g_contact_links).with([[g_contact, g_contact_link]]) expect(@integrator).to receive(:save_g_contacts_then_links).exactly(0).times @integrator.sync_contact(@contact) end it 'saves the g_contacts if they were modified' do g_contact = double(attrs_with_changes: { given_name: 'MODIFIED-John' }) contact_person = @contact.contact_people.first expect(@integrator).to receive(:get_g_contact_and_link).with(contact_person).and_return([g_contact, g_contact_link]) expect(GoogleContactSync).to receive(:sync_contact).with(@contact, [[g_contact, g_contact_link]]) expect(@integrator).to receive(:save_g_contacts_then_links).with(@contact, [g_contact], [[g_contact, g_contact_link]]) @integrator.sync_contact(@contact) end it 'does not attempt to sync a ContactPerson that points to a non-exist Person' do g_contact = double(attrs_with_changes: { given_name: 'John' }) expect(@integrator).to receive(:get_g_contact_and_link) .with(@contact.contact_people.first) { [g_contact, g_contact_link] } contact_person_no_person = create(:contact_person, person: create(:person)) contact_person_no_person.update_column(:person_id, 0) @contact.contact_people << contact_person_no_person expect(@integrator).to_not receive(:get_g_contact_and_link) .with(contact_person_no_person) expect(GoogleContactSync).to receive(:sync_contact) expect(@integrator).to receive(:save_g_contact_links) @integrator.sync_contact(@contact) end it "does not try to sync if all a contact's contact-people have non-existent people" do @contact.contact_people.first.update_column(:person_id, 0) expect(GoogleContactSync).to_not receive(:sync_contact) @integrator.sync_contact(@contact) end end def stub_groups_request(body = nil, status = 200) groups_body = { 'feed' => { 'entry' => [ { 'id' => { '$t' => 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/mpdxgroupid' }, 'title' => { '$t' => GoogleContactsIntegrator::CONTACTS_GROUP_TITLE } }, { 'id' => { '$t' => 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/inactivegroupid' }, 'title' => { '$t' => GoogleContactsIntegrator::INACTIVE_GROUP_TITLE } }, { 'id' => { '$t' => 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/6' }, 'gContact$systemGroup' => { 'id' => 'Contacts' } } ], 'openSearch$totalResults' => { '$t' => '3' }, 'openSearch$startIndex' => { '$t' => '0' }, 'openSearch$itemsPerPage' => { '$t' => '3' } } } stub_request(:get, 'https://www.google.com/m8/feeds/groups/default/full?alt=json&max-results=100000&v=3') .with(headers: { 'Authorization' => "Bearer #{@account.token}" }) .to_return(body: body || groups_body.to_json, status: status) end def empty_feed_json { 'feed' => { 'entry' => [], 'openSearch$totalResults' => { '$t' => '0' }, 'openSearch$startIndex' => { '$t' => '0' }, 'openSearch$itemsPerPage' => { '$t' => '0' } } }.to_json end def stub_empty_g_contacts stub_request(:get, "#{@api_url}/default/full?alt=json&max-results=100000&showdeleted=false&v=3") .with(headers: { 'Authorization' => "Bearer #{@account.token}" }) .to_return(body: empty_feed_json) end def stub_empty_updated_g_contacts stub_request(:get, %r{#{@api_url}/default/full\?alt=json&max-results=100000&showdeleted=false&updated-min=.*&v=3}) .to_return(body: empty_feed_json) end def g_contact_fixture_json @g_contact_fixture_json ||= File.new(Rails.root.join('spec/fixtures/google_contacts.json')).read end def stub_g_contact_from_fixture stub_request(:get, "#{@api_url}/default/full?alt=json&max-results=100000&showdeleted=false&v=3") .with(headers: { 'Authorization' => "Bearer #{@account.token}" }) .to_return(body: g_contact_fixture_json) end describe 'overall sync for creating a new google contact' do it 'creates a new google contact and association for a contact to sync' do stub_empty_g_contacts stub_empty_updated_g_contacts stub_groups_request contact_name_info = <<-EOS <gd:name> <gd:givenName>John</gd:givenName> <gd:familyName>Google</gd:familyName> </gd:name> EOS contact_org_and_group_info = <<-EOS <gd:organization rel="http://schemas.google.com/g/2005#work" primary="true"> <gd:orgName>Company, Inc</gd:orgName> <gd:orgTitle>Worker</gd:orgTitle> </gd:organization> <gContact:groupMembershipInfo deleted="false" href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/mpdxgroupid"/> <gContact:groupMembershipInfo deleted="false" href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/6"/> EOS create_contact_request_xml = <<-EOS <feed xmlns='http://www.w3.org/2005/Atom' xmlns:gContact='http://schemas.google.com/contact/2008' xmlns:gd='http://schemas.google.com/g/2005' xmlns:batch='http://schemas.google.com/gdata/batch'> <atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005" xmlns:gContact="http://schemas.google.com/contact/2008"> <atom:category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact"/> <batch:id>0</batch:id> <batch:operation type="insert"/> #{contact_name_info} <atom:content>about</atom:content> #{contact_org_and_group_info} </atom:entry> </feed> EOS create_contact_response_xml = <<-EOS <feed gd:etag="&quot;QHg9eDVSLyt7I2A9XRdQE0QORQY.&quot;" xmlns="http://www.w3.org/2005/Atom" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:gContact="http://schemas.google.com/contact/2008" xmlns:gd="http://schemas.google.com/g/2005" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/"> <entry> <batch:id>0</batch:id> <batch:operation type='insert'/> <batch:status code='201' reason='Created'/> #{contact_name_info} <content>about</content> #{contact_org_and_group_info} </entry> </feed> EOS stub_request(:post, 'https://www.google.com/m8/feeds/contacts/default/full/batch?alt=&v=3').to_return do |request| expect(EquivalentXml.equivalent?(request.body, create_contact_request_xml)).to be true { body: create_contact_response_xml } end @integrator.sync_contacts @person.reload expect(@person.google_contacts.count).to eq(1) last_data = { name_prefix: nil, given_name: 'John', additional_name: nil, family_name: 'Google', name_suffix: nil, content: 'about', emails: [], phone_numbers: [], addresses: [], organizations: [{ rel: 'work', primary: true, org_name: 'Company, Inc', org_title: 'Worker' }], websites: [], group_memberships: ['http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/mpdxgroupid', 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/6'], deleted_group_memberships: [] } expect(@person.google_contacts.first.last_data).to eq(last_data) expect(@person.google_contacts.first.last_synced.nil?).to be false end end describe 'sync behavior for person in multiple contacts' do before do @contact2 = create(:contact, name: '<NAME>', account_list: @account_list, status: 'Partner - Pray', notes: 'about') @contact2.people << @person stub_empty_g_contacts stub_empty_updated_g_contacts stub_groups_request end it 'syncs each person-contact with its own Google contact' do times_batch_create_or_update_called = 0 batch_time3_g_contact_id = '' expect(@account.contacts_api_user).to receive(:batch_create_or_update) .exactly(4).times do |g_contact, &block| times_batch_create_or_update_called += 1 case times_batch_create_or_update_called when 1 g_contact['id'] = { '$t' => '1' } block.call(code: 201) when 2 g_contact['id'] = { '$t' => '2' } block.call(code: 201) when 3 batch_time3_g_contact_id = g_contact.id block.call(code: 200) when 4 # On the second sync, expect different ids for the different person-contacts expect([g_contact.id, batch_time3_g_contact_id].to_set).to eq(%w(1 2).to_set) block.call(code: 200) end end # First sync will have it do creates expect(times_batch_create_or_update_called).to eq(0) @integrator.sync_contacts expect(times_batch_create_or_update_called).to eq(2) # Second sync have it do an update @person.touch g_contact1 = GoogleContactsApi::Contact.new('id' => { '$t' => '1' }) g_contact2 = GoogleContactsApi::Contact.new('id' => { '$t' => '2' }) expect(@account.contacts_api_user).to receive(:get_contact).with('1').and_return(g_contact1) expect(@account.contacts_api_user).to receive(:get_contact).with('2').and_return(g_contact2) @integrator.sync_contacts expect(times_batch_create_or_update_called).to eq(4) end end it 'does nothing when an organization account is downloading' do @account_list.users << create(:user) create(:organization_account, downloading: true, person: @account_list.users.first) expect(@integrator).to_not receive(:sync_and_return_num_synced) @integrator.sync_contacts end it 'does nothing when an import is running' do @account_list.imports << create(:import, importing: true, source: 'google') expect(@integrator).to_not receive(:sync_and_return_num_synced) @integrator.sync_contacts end it 'does nothing when the mail chimp account is importing' do create(:mail_chimp_account, account_list: @account_list, importing: true) expect(@integrator).to_not receive(:sync_and_return_num_synced) @integrator.sync_contacts end describe 'compatibility with previous import code' do it 'does consider old google contacts associated by previously implemented Google contacts import' do # The Google contacts import code would only associate a google_contact link record with the person, so just leave # those old format records alone; they aren't person/contact merge losers. Those would have both a contact_id and # person_id associated with it (but which no longer exists in the database due to the merge). create(:google_contact, google_account: @account, person: @person) expect(@integrator.g_contact_merge_losers).to be_empty end end context '#delete_g_contact_merge_loser' do it 'does not cause an error if the remote_id of the merge loser is nil' do g_contact_link = create(:google_contact, remote_id: nil) expect do @integrator.delete_g_contact_merge_loser(g_contact_link) end.to_not raise_error expect(GoogleContact.count).to eq(0) end end describe 'sync behavior for merged MPDX contacts/people' do before do @contact.update_column(:notes, 'contact') @contact2 = create(:contact, name: '<NAME>', account_list: @account_list, status: 'Partner - Pray', notes: 'contact2') @contact2.people << @person @person2 = create(:person, first_name: 'Jane', last_name: 'Doe') @contact.people << @person2 @contact2.people << @person2 stub_empty_g_contacts stub_empty_updated_g_contacts stub_groups_request end it 'deletes Google contacts for losing merged contacts/people' do g_contact_ids = {} g_contacts_for_ids = {} batch_create_or_update_calls = 0 expect(@account.contacts_api_user).to receive(:batch_create_or_update) .exactly(7).times do |g_contact, &block| batch_create_or_update_calls += 1 case batch_create_or_update_calls when 1..4 g_contact_id = batch_create_or_update_calls.to_s g_contact['id'] = { '$t' => g_contact_id } g_contact['gd$etag'] = 'etag:' + g_contact_id g_contact['content'] = { '$t' => g_contact.prepped_changes[:content] } g_contact['gd$name'] = { 'gd$givenName' => { '$t' => g_contact.prepped_changes[:given_name] } } notes_and_first_name = g_contact.content + ':' + g_contact.given_name g_contact_ids[notes_and_first_name] = g_contact_id g_contacts_for_ids[g_contact_id] = g_contact block.call(code: 201) else block.call(code: 200) end end expect(@account.contacts_api_user).to receive(:get_contact) .at_least(:once) { |id| g_contacts_for_ids[id] } # The first sync should create four Google contacts for @contact-@person, @contact-@person2, # @contact2-@person, and @contact2-@person2 @integrator.sync_contacts expect(batch_create_or_update_calls).to eq(4) expect(GoogleContact.all.count).to eq(4) expect(GoogleContact.find_by(contact: @contact, person: @person).remote_id).to eq(g_contact_ids['contact:John']) expect(GoogleContact.find_by(contact: @contact, person: @person2).remote_id).to eq(g_contact_ids['contact:Jane']) expect(GoogleContact.find_by(contact: @contact2, person: @person).remote_id).to eq(g_contact_ids['contact2:John']) expect(GoogleContact.find_by(contact: @contact2, person: @person2).remote_id).to eq(g_contact_ids['contact2:Jane']) # Then we merge @contact with @contact2 (@contact wins), so we should delete the @contact2 g_contacts @contact.merge(@contact2) expect(@account.contacts_api_user).to_not receive(:delete_contact) @integrator.sync_contacts expect(GoogleContact.all.count).to eq(2) expect(GoogleContact.find_by(contact: @contact, person: @person).remote_id).to eq(g_contact_ids['contact:John']) expect(GoogleContact.find_by(contact: @contact, person: @person2).remote_id).to eq(g_contact_ids['contact:Jane']) # Then we merge @person with @person2 (@person wins), so we should delete @person2 g_contact @person.merge(@person2) expect(@account.contacts_api_user).to_not receive(:delete_contact) @integrator.sync_contacts expect(GoogleContact.all.count).to eq(1) expect(GoogleContact.find_by(contact: @contact, person: @person).remote_id).to eq(g_contact_ids['contact:John']) end end describe 'sync behavior for HTTP errors' do before do stub_groups_request @integration.update_column(:contacts_last_synced, 1.hour.ago) create(:google_contact, google_account: @account, contact: @contact, person: @person, remote_id: '1', last_data: { given_name: 'John', family_name: 'Doe' }, last_synced: 1.hour.ago) expect(@account.contacts_api_user).to receive(:contacts_updated_min).at_least(:once).and_return([]) end it 'retries the sync and creates a new contact on a 404 error' do expect(@account.contacts_api_user).to receive(:get_contact).with('1').and_return(@g_contact) expect(@account.contacts_api_user).to receive(:query_contacts).with('John Google', showdeleted: false).and_return([]) new_g_contact = GoogleContactsApi::Contact.new expect(GoogleContactsApi::Contact).to receive(:new).and_return(new_g_contact) times_batch_create_or_update_called = 0 expect(@account.contacts_api_user).to receive(:batch_create_or_update) .exactly(2).times do |g_contact, &block| times_batch_create_or_update_called += 1 case times_batch_create_or_update_called when 1 expect(g_contact).to eq(@g_contact) block.call(code: 404) when 2 expect(g_contact).to eq(new_g_contact) block.call(code: 201) end end expect(times_batch_create_or_update_called).to eq(0) @integrator.sync_contacts expect(times_batch_create_or_update_called).to eq(2) end it 'retries the sync and reloads a contact on a 412 error' do g_contact_reloaded = GoogleContactsApi::Contact.new('gd$etag' => 'a', 'id' => { '$t' => '2' }, 'gd$name' => { 'gd$givenName' => { '$t' => 'MODIFIED-Jane' }, 'gd$familyName' => { '$t' => 'Doe' } }) expect(@account.contacts_api_user).to receive(:get_contact).with('1').exactly(:twice) .and_return(@g_contact, g_contact_reloaded) times_batch_create_or_update_called = 0 expect(@account.contacts_api_user).to receive(:batch_create_or_update) .exactly(2).times do |g_contact, &block| times_batch_create_or_update_called += 1 case times_batch_create_or_update_called when 1 expect(g_contact).to eq(@g_contact) block.call(code: 412) when 2 expect(g_contact).to eq(g_contact_reloaded) block.call(code: 200) end end expect(@account.contacts_api_user).to receive(:send_batched_requests).exactly(:twice) expect(times_batch_create_or_update_called).to eq(0) @integrator.sync_and_return_num_synced expect(times_batch_create_or_update_called).to eq(2) end it 'raises an error for 500 errors returned on individual sync' do expect(@account.contacts_api_user).to receive(:get_contact).with('1').and_return(@g_contact) times_batch_create_or_update_called = 0 expect(@account.contacts_api_user).to receive(:batch_create_or_update) .exactly(:once) do |g_contact, &block| times_batch_create_or_update_called += 1 case times_batch_create_or_update_called when 1 expect(g_contact).to eq(@g_contact) block.call(code: 500) end end expect(times_batch_create_or_update_called).to eq(0) expect { @integrator.sync_contacts }.to raise_error(/500/) expect(times_batch_create_or_update_called).to eq(1) end end describe 'when a contact was synced but then made inactive' do it 'deletes the link and puts the google contact in the group "Inactive"' do stub_groups_request contact_feed = { 'feed' => { 'entry' => [ { 'id' => { '$t' => 'http://www.google.com/m8/feeds/contacts/test.user%40cru.org/base/test' } } ], 'openSearch$totalResults' => { '$t' => '1' }, 'openSearch$startIndex' => { '$t' => '0' }, 'openSearch$itemsPerPage' => { '$t' => '1' } } } stub_request(:get, "#{@api_url}/default/full?alt=json&max-results=100000&showdeleted=false&v=3") .with(headers: { 'Authorization' => "Bearer #{@account.token}" }) .to_return(body: contact_feed.to_json) expect(Time).to receive(:now).at_least(:once).and_return(now) update_request_xml = <<-EOS <feed xmlns='http://www.w3.org/2005/Atom' xmlns:gContact='http://schemas.google.com/contact/2008' xmlns:gd='http://schemas.google.com/g/2005' xmlns:batch='http://schemas.google.com/gdata/batch'> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005" gd:etag=""> <id>http://www.google.com/m8/feeds/contacts/test.user%40cru.org/base/test</id> <updated>#{GoogleContactsApi::Api.format_time_for_xml(now)}</updated> <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact"/> <batch:id>0</batch:id> <batch:operation type="update"/> <gd:name></gd:name> <gContact:groupMembershipInfo deleted="false" href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/inactivegroupid"/> </entry> </feed> EOS update_response_xml = <<-EOS <feed gd:etag="&quot;QHg9eDVSLyt7I2A9XRdQE0QORQY.&quot;" xmlns="http://www.w3.org/2005/Atom" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:gContact="http://schemas.google.com/contact/2008" xmlns:gd="http://schemas.google.com/g/2005" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/"> <entry> <batch:id>0</batch:id> <batch:operation type='update'/> <batch:status code='200' reason='Success'/> </entry> </feed> EOS update_stub = stub_request(:post, 'https://www.google.com/m8/feeds/contacts/default/full/batch?alt=&v=3').to_return do |request| expect(EquivalentXml.equivalent?(request.body, update_request_xml)).to be true { body: update_response_xml } end create(:google_contact, google_account: @account, person: @person, contact: @contact, remote_id: 'http://www.google.com/m8/feeds/contacts/test.user%40cru.org/base/test') @contact.update_column :status, 'Not Interested' @integrator.sync_contacts expect(update_stub).to have_been_requested expect(GoogleContact.count).to eq(0) end end describe 'cleanup inactive contacts errors' do before do stub_groups_request @remote_id = 'http://www.google.com/m8/feeds/contacts/test.user%40cru.org/base/test' @g_contact_link = create(:google_contact, google_account: @account, person: @person, contact: @contact, remote_id: @remote_id) @contact.update_column :status, 'Not Interested' @cache = GoogleContactsCache.new(@account) @cache.cache_g_contacts([]) @integrator.cache = @cache end it 'deletes the associated link record in the case of a 404 error' do expect(@cache).to receive(:find_by_id).with(@remote_id).and_return(@g_contact) expect(@account.contacts_api_user).to receive(:batch_create_or_update) .exactly(:once) { |_g_contact, &block| block.call(code: 404) } @integrator.cleanup_inactive_g_contacts expect(GoogleContact.all.count).to eq(0) end it 'reloads the g_contact then retries the update in the case of a 412 error' do expect(@cache).to receive(:remove_g_contact).with(@g_contact) expect(@cache).to receive(:find_by_id).exactly(:twice).with(@remote_id).and_return(@g_contact) times_batch_create_or_update_called = 0 expect(@account.contacts_api_user).to receive(:batch_create_or_update) .exactly(:twice) do |_g_contact, &block| times_batch_create_or_update_called += 1 case times_batch_create_or_update_called when 1 block.call(code: 412) when 2 block.call(code: 200) end end @integrator.cleanup_inactive_g_contacts expect(GoogleContact.all.count).to eq(0) end end describe 'delete merge loser 404 contact not found error (already deleted)' do it 'destroys the local g_contact_link anyway' do create(:google_contact, google_account: @account, person: @person, contact: @contact, remote_id: 'http://www.google.com/m8/feeds/contacts/test.user%40cru.org/base/test') ContactPerson.all.destroy_all stub_request(:delete, 'https://www.google.com/m8/feeds/contacts/test.user@cru.org/base/test?alt=json&v=3') .to_return(status: 404) @integrator.delete_g_contact_merge_losers expect(GoogleContact.all.count).to eq(0) end end context '#retry_on_api_errs' do def expect_err_for_response_code(code, expected_err) if code == 200 stub_groups_request else body = <<-EOS error: { errors: [ { "domain": "d", "reason": "r", "message": "m" } ], "code": #{code}, "message": "m" } EOS stub_groups_request(body, code) end expectation = expect { GoogleContactsIntegrator.retry_on_api_errs { @integrator.api_user.groups } } if expected_err expectation.to raise_error(expected_err) else expectation.to_not raise_error end end it 'raises a LowerRetryWorker::RetryJobButNoRollbarError error on 500s, 403 errs' do expect_err_for_response_code(500, LowerRetryWorker::RetryJobButNoRollbarError) expect_err_for_response_code(503, LowerRetryWorker::RetryJobButNoRollbarError) expect_err_for_response_code(403, LowerRetryWorker::RetryJobButNoRollbarError) end it 'raise an OAuth2 error for other error codes' do expect_err_for_response_code(400, OAuth2::Error) expect_err_for_response_code(404, OAuth2::Error) end it 'does not raise an error for success code' do expect_err_for_response_code(200, nil) end end describe 'overall first and subsequent sync for modifed contact info' do it 'combines MPDX & Google data on first sync then propagates updates of email/phone/address on subsequent syncs' do setup_first_sync_data expect_first_sync_api_put @integrator.sync_contacts first_sync_expectations modify_data expect_second_sync_api_put @integrator.sync_contacts second_sync_expectations end def setup_first_sync_data stub_g_contact_from_fixture @updated_g_contact_obj = JSON.parse(g_contact_fixture_json)['feed']['entry'][0] @updated_g_contact_obj['gd$email'] = [ { primary: true, rel: 'http://schemas.google.com/g/2005#other', address: '<EMAIL>' }, { primary: false, rel: 'http://schemas.google.com/g/2005#home', address: '<EMAIL>' } ] @updated_g_contact_obj['gd$phoneNumber'] = [ { '$t' => '(213) 334-5158', 'rel' => 'http://schemas.google.com/g/2005#mobile', 'primary' => 'true' }, { '$t' => '(407) 789-0123', 'rel' => 'http://schemas.google.com/g/2005#home', 'primary' => 'false' } ] @updated_g_contact_obj['gd$structuredPostalAddress'] = [ { 'rel' => 'http://schemas.google.com/g/2005#home', 'primary' => 'false', 'gd$street' => { '$t' => '2345 Long Dr. #232' }, 'gd$city' => { '$t' => 'Somewhere' }, 'gd$region' => { '$t' => 'IL' }, 'gd$postcode' => { '$t' => '12345' }, 'gd$country' => { '$t' => 'United States of America' } }, { 'gd$country' => { '$t' => 'United States of America' }, 'gd$street' => { '$t' => '123 Big Rd' }, 'gd$city' => { '$t' => 'Anywhere' }, 'gd$region' => { '$t' => 'MO' }, 'gd$postcode' => { '$t' => '56789' } }, { 'rel' => 'http://schemas.google.com/g/2005#work', 'primary' => 'true', 'gd$street' => { '$t' => '100 Lake Hart Dr.' }, 'gd$city' => { '$t' => 'Orlando' }, 'gd$region' => { '$t' => 'FL' }, 'gd$postcode' => { '$t' => '32832' }, 'gd$country' => { '$t' => 'United States of America' } } ] @updated_g_contact_obj['gContact$groupMembershipInfo'] = [ { 'deleted' => 'false', 'href' => 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/1b9d086d0a95e81a' }, { 'deleted' => 'false', 'href' => 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/6' }, { 'deleted' => 'false', 'href' => 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/33bfe364885eed6f' }, { 'deleted' => 'false', 'href' => 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/mpdxgroupid' } ] @person.email_address = { email: '<EMAIL>', location: 'home', primary: true } @person.phone_number = { number: '+14077890123', primary: true, location: 'home' } @person.websites << Person::Website.create(url: 'mpdx.example.com', primary: false) @contact.addresses_attributes = [ { street: '100 Lake Hart Dr.', city: 'Orlando', state: 'FL', postal_code: '32832', country: 'United States', location: 'Business', primary_mailing_address: true } ] @contact.save stub_empty_updated_g_contacts stub_groups_request create_group_request_regex_str = '<atom:entry xmlns:gd="http://schemas.google.com/g/2005" xmlns:atom="http://www.w3.org/2005/Atom">\s*'\ '<atom:category scheme="http://schemas.google.com/g/2005#kind"\s+term="http://schemas.google.com/contact/2008#group"/>\s*'\ "<atom:title type=\"text\">#{GoogleContactsIntegrator::CONTACTS_GROUP_TITLE}</atom:title>\s*"\ '</atom:entry>' create_group_response = { 'entry' => { 'id' => { '$t' => 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/mpdxgroupid' } } } stub_request(:post, 'https://www.google.com/m8/feeds/groups/default/full?alt=json&v=3') .with(body: /#{create_group_request_regex_str}/m, headers: { 'Authorization' => "Bearer #{@account.token}" }) .to_return(body: create_group_response.to_json) end def expect_first_sync_api_put xml_regex_str = '<gd:name>\s*'\ '<gd:namePrefix>Mr</gd:namePrefix>\s*'\ '<gd:givenName>John</gd:givenName>\s*'\ '<gd:additionalName>Henry</gd:additionalName>\s*'\ '<gd:familyName>Google</gd:familyName>\s*'\ '<gd:nameSuffix>III</gd:nameSuffix>\s*'\ '</gd:name>\s*'\ '<atom:content>about</atom:content>\s*'\ '<gd:email\s+rel="http://schemas.google.com/g/2005#other"\s+primary="true"\s+address="<EMAIL>"/>\s+'\ '<gd:email\s+rel="http://schemas.google.com/g/2005#home"\s+address="<EMAIL>"/>\s+'\ '<gd:phoneNumber\s+rel="http://schemas.google.com/g/2005#mobile"\s+primary="true"\s+>\(213\) 334-5158</gd:phoneNumber>\s+'\ '<gd:phoneNumber\s+rel="http://schemas.google.com/g/2005#home"\s+>\(407\) 789-0123</gd:phoneNumber>\s+'\ '<gd:structuredPostalAddress\s+rel="http://schemas.google.com/g/2005#home"\s+>\s+'\ '<gd:city>Somewhere</gd:city>\s+'\ '<gd:street>2345 Long Dr. #232</gd:street>\s+'\ '<gd:region>IL</gd:region>\s+'\ '<gd:postcode>12345</gd:postcode>\s+'\ '<gd:country>United States of America</gd:country>\s+'\ '</gd:structuredPostalAddress>\s+'\ '<gd:structuredPostalAddress\s+rel="http://schemas.google.com/g/2005#work"\s+>\s+'\ '<gd:city>Anywhere</gd:city>\s+'\ '<gd:street>123 Big Rd</gd:street>\s+'\ '<gd:region>MO</gd:region>\s+'\ '<gd:postcode>56789</gd:postcode>\s+'\ '<gd:country>United States of America</gd:country>\s+'\ '</gd:structuredPostalAddress>\s+'\ '<gd:structuredPostalAddress\s+rel="http://schemas.google.com/g/2005#work"\s+primary="true">\s+'\ '<gd:city>Orlando</gd:city>\s+'\ '<gd:street>100 Lake Hart Dr.</gd:street>\s+'\ '<gd:region>FL</gd:region>\s+'\ '<gd:postcode>32832</gd:postcode>\s+'\ '<gd:country>United States of America</gd:country>\s+'\ '</gd:structuredPostalAddress>\s+'\ '<gd:organization\s+rel="http://schemas.google.com/g/2005#work"\s+primary="true">\s+'\ '<gd:orgName>Company, Inc</gd:orgName>\s+'\ '<gd:orgTitle>Worker</gd:orgTitle>\s+'\ '</gd:organization>\s+'\ '<gContact:website\s+href="blog.example.com"\s+rel="blog"\s+/>\s+'\ '<gContact:website\s+href="www.example.com"\s+rel="profile"\s+primary="true"\s+/>\s+'\ '<gContact:website\s+href="mpdx.example.com"\s+rel="other"\s+/>\s+'\ '<gContact:groupMembershipInfo\s+deleted="false"\s+'\ 'href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/1b9d086d0a95e81a"/>\s+'\ '<gContact:groupMembershipInfo\s+deleted="false"\s+'\ 'href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/6"/>\s+'\ '<gContact:groupMembershipInfo\s+deleted="false"\s+'\ 'href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/33bfe364885eed6f"/>\s+'\ '<gContact:groupMembershipInfo\s+deleted="false"\s+'\ 'href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/mpdxgroupid"/>\s+' stub_request(:post, 'https://www.google.com/m8/feeds/contacts/default/full/batch?alt=&v=3') .with(body: /#{xml_regex_str}/m, headers: { 'Authorization' => "Bearer #{@account.token}" }) .to_return(body: File.new(Rails.root.join('spec/fixtures/google_contacts.xml')).read) end def first_sync_expectations @person.reload expect(@person.email_addresses.count).to eq(2) email1 = @person.email_addresses.first expect(email1.email).to eq('<EMAIL>') expect(email1.location).to eq('home') expect(email1.primary).to be true email2 = @person.email_addresses.last expect(email2.email).to eq('<EMAIL>') expect(email2.location).to eq('other') expect(email2.primary).to be false expect(@person.phone_numbers.count).to eq(2) number1 = @person.phone_numbers.first expect(number1.number).to eq('+14077890123') expect(number1.location).to eq('home') expect(number1.primary).to be true number2 = @person.phone_numbers.last expect(number2.number).to eq('+12133345158') expect(number2.location).to eq('mobile') expect(number2.primary).to be false expect(@person.websites.count).to eq(3) websites = @person.websites.order(:url).to_a expect(websites[0].url).to eq('blog.example.com') expect(websites[0].primary).to be false expect(websites[1].url).to eq('mpdx.example.com') expect(websites[1].primary).to be false expect(websites[2].url).to eq('www.example.com') expect(websites[2].primary).to be true g_contact_link = @person.google_contacts.first expect(g_contact_link.remote_id).to eq('http://www.google.com/m8/feeds/contacts/test.user%40cru.org/base/6b70f8bb0372c') expect(g_contact_link.last_etag).to eq('"SXk6cDdXKit7I2A9Wh9VFUgORgE."') addresses = @contact.addresses.order(:state).map do |address| address.attributes.symbolize_keys.slice(:street, :city, :state, :postal_code, :country, :location, :primary_mailing_address) end expect(addresses).to contain_exactly( { street: '100 Lake Hart Dr.', city: 'Orlando', state: 'FL', postal_code: '32832', country: 'United States', location: 'Business', primary_mailing_address: true }, { street: '2345 Long Dr. #232', city: 'Somewhere', state: 'IL', postal_code: '12345', country: 'United States', location: 'Home', primary_mailing_address: false }, street: '123 Big Rd', city: 'Anywhere', state: 'MO', postal_code: '56789', country: 'United States', location: 'Business', primary_mailing_address: false ) last_data = { name_prefix: 'Mr', given_name: 'John', additional_name: 'Henry', family_name: 'Google', name_suffix: 'III', content: 'Notes here', emails: [{ primary: true, rel: 'other', address: '<EMAIL>' }, { primary: false, rel: 'home', address: '<EMAIL>' }], phone_numbers: [ { number: '(213) 334-5158', rel: 'mobile', primary: true }, { number: '(407) 789-0123', rel: 'home', primary: false } ], addresses: [ { rel: 'home', primary: false, country: 'United States of America', city: 'Somewhere', street: '2345 Long Dr. #232', region: 'IL', postcode: '12345' }, { country: 'United States of America', city: 'Anywhere', street: '123 Big Rd', region: 'MO', postcode: '56789', rel: 'work', primary: false }, { rel: 'work', primary: true, street: '100 Lake Hart Dr.', city: 'Orlando', region: 'FL', postcode: '32832', country: 'United States of America' } ], organizations: [{ org_title: 'Worker Person', org_name: 'Example, Inc', rel: 'other', primary: false }], websites: [{ href: 'blog.example.com', rel: 'blog', primary: false }, { href: 'www.example.com', rel: 'profile', primary: true }], group_memberships: [ 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/1b9d086d0a95e81a', 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/6', 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/33bfe364885eed6f', 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/mpdxgroupid' ], deleted_group_memberships: [] } expect(g_contact_link.last_data).to eq(last_data) end def modify_data old_email = @person.email_addresses.first @person.email_address = { email: '<EMAIL>', primary: true, _destroy: 1, id: old_email.id } first_number = @person.phone_numbers.first first_number.number = '+14077894444' first_number.save first_address = @contact.addresses.first first_address.street = 'MODIFIED 100 Lake Hart Dr.' first_address.save website = @person.websites.where(url: 'mpdx.example.com').first website.url = 'MODIFIED_mpdx.example.com' website.save @account_list.reload WebMock.reset! stub_google_geocoder stub_request(:get, %r{https://api\.smartystreets\.com/street-address/.*}).to_return(body: '[]') @updated_g_contact_obj = JSON.parse(g_contact_fixture_json)['feed']['entry'][0] @updated_g_contact_obj['gd$email'] = [ { primary: true, rel: 'http://schemas.google.com/g/2005#other', address: '<EMAIL>' }, { primary: false, rel: 'http://schemas.google.com/g/2005#home', address: '<EMAIL>' } ] @updated_g_contact_obj['gd$phoneNumber'] = [ { '$t' => '(213) 334-5555', 'rel' => 'http://schemas.google.com/g/2005#mobile', 'primary' => 'true' }, { '$t' => '(407) 789-0123', 'rel' => 'http://schemas.google.com/g/2005#home', 'primary' => 'false' } ] @updated_g_contact_obj['gd$structuredPostalAddress'] = [ { 'rel' => 'http://schemas.google.com/g/2005#home', 'primary' => 'false', 'gd$street' => { '$t' => '2345 Long Dr. #232' }, 'gd$city' => { '$t' => 'Somewhere' }, 'gd$region' => { '$t' => 'IL' }, 'gd$postcode' => { '$t' => '12345' }, 'gd$country' => { '$t' => 'United States of America' } }, { 'gd$street' => { '$t' => 'MODIFIED 123 Big Rd' }, 'gd$city' => { '$t' => 'Anywhere' }, 'gd$region' => { '$t' => 'MO' }, 'gd$postcode' => { '$t' => '56789' }, 'gd$country' => { '$t' => 'United States of America' } }, { 'rel' => 'http://schemas.google.com/g/2005#work', 'primary' => 'true', 'gd$street' => { '$t' => '100 Lake Hart Dr.' }, 'gd$city' => { '$t' => 'Orlando' }, 'gd$region' => { '$t' => 'FL' }, 'gd$postcode' => { '$t' => '32832' }, 'gd$country' => { '$t' => 'United States of America' } } ] @updated_g_contact_obj['gContact$website'] = [ { 'href' => 'MODIFIED_blog.example.com', 'rel' => 'blog' }, { 'href' => 'www.example.com', 'rel' => 'profile', 'primary' => 'true' } ] updated_contacts_body = { 'feed' => { 'entry' => [@updated_g_contact_obj], 'openSearch$totalResults' => { '$t' => '1' }, 'openSearch$startIndex' => { '$t' => '0' }, 'openSearch$itemsPerPage' => { '$t' => '1' } } } stub_request(:get, %r{#{@api_url}/default/full\?alt=json&max-results=100000&showdeleted=false&updated-min=.*&v=3}) .to_return(body: updated_contacts_body.to_json).then.to_return(body: empty_feed_json) groups_body = { 'feed' => { 'entry' => [ { 'id' => { '$t' => 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/mpdxgroupid' }, 'title' => { '$t' => GoogleContactsIntegrator::CONTACTS_GROUP_TITLE } } ], 'openSearch$totalResults' => { '$t' => '1' }, 'openSearch$startIndex' => { '$t' => '0' }, 'openSearch$itemsPerPage' => { '$t' => '1' } } } stub_request(:get, 'https://www.google.com/m8/feeds/groups/default/full?alt=json&max-results=100000&v=3') .with(headers: { 'Authorization' => "Bearer #{@account.token}" }) .to_return(body: groups_body.to_json) end def expect_second_sync_api_put xml_regex_str = '</atom:content>\s+'\ '<gd:email\s+rel="http://schemas.google.com/g/2005#other"\s+primary="true"\s+address="<EMAIL>"/>\s+'\ '<gd:phoneNumber\s+rel="http://schemas.google.com/g/2005#mobile"\s+primary="true"\s+>\(213\) 334-5555</gd:phoneNumber>\s+'\ '<gd:phoneNumber\s+rel="http://schemas.google.com/g/2005#home"\s+>\(407\) 789-4444</gd:phoneNumber>\s+'\ '<gd:structuredPostalAddress\s+rel="http://schemas.google.com/g/2005#home"\s+>\s+'\ '<gd:city>Somewhere</gd:city>\s+'\ '<gd:street>2345 Long Dr. #232</gd:street>\s+'\ '<gd:region>IL</gd:region>\s+'\ '<gd:postcode>12345</gd:postcode>\s+'\ '<gd:country>United States of America</gd:country>\s+'\ '</gd:structuredPostalAddress>\s+'\ '<gd:structuredPostalAddress\s+rel="http://schemas.google.com/g/2005#work"\s+>\s+'\ '<gd:city>Anywhere</gd:city>\s+'\ '<gd:street>MODIFIED 123 Big Rd</gd:street>\s+'\ '<gd:region>MO</gd:region>\s+'\ '<gd:postcode>56789</gd:postcode>\s+'\ '<gd:country>United States of America</gd:country>\s+'\ '</gd:structuredPostalAddress>\s+'\ '<gd:structuredPostalAddress\s+rel="http://schemas.google.com/g/2005#work"\s+primary="true">\s+'\ '<gd:city>Orlando</gd:city>\s+'\ '<gd:street>MODIFIED 100 Lake Hart Dr.</gd:street>\s+'\ '<gd:region>FL</gd:region>\s+'\ '<gd:postcode>32832</gd:postcode>\s+'\ '<gd:country>United States of America</gd:country>\s+'\ '</gd:structuredPostalAddress>\s+'\ '<gd:organization\s+rel="http://schemas.google.com/g/2005#work"\s+primary="true">\s+'\ '<gd:orgName>Company, Inc</gd:orgName>\s+'\ '<gd:orgTitle>Worker</gd:orgTitle>\s+'\ '</gd:organization>\s+'\ '<gContact:website\s+href="MODIFIED_blog.example.com"\s+rel="blog"\s+/>\s+'\ '<gContact:website\s+href="www.example.com"\s+rel="profile"\s+primary="true"\s+/>\s+'\ '<gContact:website\s+href="MODIFIED_mpdx.example.com"\s+rel="other"\s+/>\s+'\ '<gContact:groupMembershipInfo\s+deleted="false"\s+'\ 'href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/1b9d086d0a95e81a"/>\s+'\ '<gContact:groupMembershipInfo\s+deleted="false"\s+'\ 'href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/6"/>\s+'\ '<gContact:groupMembershipInfo\s+deleted="false"\s+'\ 'href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/33bfe364885eed6f"/>\s+'\ '<gContact:groupMembershipInfo\s+deleted="false"\s+'\ 'href="http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/mpdxgroupid"/>\s+'\ '</entry>' stub_request(:post, 'https://www.google.com/m8/feeds/contacts/default/full/batch?alt=&v=3') .with(body: /#{xml_regex_str}/m, headers: { 'Authorization' => "Bearer #{@account.token}" }) .to_return(body: File.new(Rails.root.join('spec/fixtures/google_contacts.xml')).read) end def second_sync_expectations @person.reload expect(@person.email_addresses.count).to eq(1) expect(@person.email_addresses.last.email).to eq('<EMAIL>') expect(@person.phone_numbers.count).to eq(2) expect(@person.phone_numbers.first.number).to eq('+14077894444') expect(@person.phone_numbers.last.number).to eq('+12133345555') @contact.reload addresses = @contact.addresses.order(:state).map do |address| address.attributes.symbolize_keys.slice(:street, :city, :state, :postal_code, :country, :location, :primary_mailing_address) end expect(addresses).to contain_exactly( { street: 'MODIFIED 100 Lake Hart Dr.', city: 'Orlando', state: 'FL', postal_code: '32832', country: 'United States', location: 'Business', primary_mailing_address: true }, { street: '2345 Long Dr. #232', city: 'Somewhere', state: 'IL', postal_code: '12345', country: 'United States', location: 'Home', primary_mailing_address: false }, street: 'MODIFIED 123 Big Rd', city: 'Anywhere', state: 'MO', postal_code: '56789', country: 'United States', location: 'Business', primary_mailing_address: false ) expect(@person.websites.count).to eq(3) websites = @person.websites.order(:url).to_a expect(websites[0].url).to eq('MODIFIED_blog.example.com') expect(websites[0].primary).to be false expect(websites[1].url).to eq('MODIFIED_mpdx.example.com') expect(websites[1].primary).to be false expect(websites[2].url).to eq('www.example.com') expect(websites[2].primary).to be true end end end
chuckmersereau/api_practice
spec/factories/account_list_coaches.rb
<filename>spec/factories/account_list_coaches.rb<gh_stars>0 FactoryBot.define do factory :account_list_coach do association :coach, factory: :user_coach account_list end end
chuckmersereau/api_practice
app/services/task/filter/date_range.rb
<gh_stars>0 class Task::Filter::DateRange < Task::Filter::Base def execute_query(tasks, filters) case filters[:date_range] when 'last_week' tasks.where('completed_at <= ? and completed_at > ?', 1.week.ago, 2.weeks.ago) when 'last_month' tasks.where('completed_at <= ? AND completed_at > ?', 1.month.ago, 2.months.ago) when 'last_year' tasks.where('completed_at <= ? AND completed_at > ?', 1.year.ago, 2.years.ago) when 'last_two_years' tasks.where('completed_at <= ? AND completed_at > ?', 2.years.ago, 3.years.ago) when 'overdue' tasks.overdue when 'today' tasks.today when 'tomorrow' tasks.tomorrow when 'future' tasks.future when 'upcoming' tasks.upcoming when 'no_date' tasks.no_date end end def title _('Date Range') end def type 'radio' end def custom_options %w(last_week last_month last_year last_two_years overdue today tomorrow future upcoming).map do |range| { name: _(range.humanize.titleize), id: range } end end end
chuckmersereau/api_practice
app/controllers/api/v2/account_lists/merge_controller.rb
<reponame>chuckmersereau/api_practice<filename>app/controllers/api/v2/account_lists/merge_controller.rb class Api::V2::AccountLists::MergeController < Api::V2Controller def create load_merge_account_list authorize_merge_account_list if @merge_account_list != load_account_list load_account_list.merge(@merge_account_list) render json: load_account_list, status: :created else render_400(detail: create_error_message) end end private def load_merge_account_list @merge_account_list ||= merge_account_list_scope.find(merge_account_list_params[:account_list_to_merge_id]) end def authorize_merge_account_list authorize @merge_account_list end def merge_account_list_params params .require(:merge) .permit(:account_list_to_merge_id) end def merge_account_list_scope current_user.account_lists end def load_account_list @account_list ||= AccountList.find(params[:account_list_id]) end def pundit_user PunditContext.new(current_user, account_list: load_account_list) end def create_error_message "Account List to be merged can't be the same as the Account List being merged into" end end
chuckmersereau/api_practice
db/migrate/20140707103152_add_region_to_address.rb
class AddRegionToAddress < ActiveRecord::Migration def change add_column :addresses, :region, :string add_column :addresses, :metro_area, :string end end
chuckmersereau/api_practice
app/models/notification_type/task_if_period_past.rb
class NotificationType::TaskIfPeriodPast < NotificationType def check_contacts_filter(contacts) contacts.financial_partners end # Check to see if this designation_account has no actitivities that should trigger a notification def check(account_list) notifications = [] check_contacts_filter(account_list.contacts).each do |contact| next unless contact.created_at < 1.year.ago || contact.activities.where('start_at < ?', 1.year.ago).any? prior_notification = Notification.active .where(contact_id: contact.id, notification_type_id: id) .where('event_date > ?', 1.year.ago) .exists? next if prior_notification next unless notify_for_contact?(contact) notification = contact.notifications.create!(notification_type_id: id, event_date: Date.today) notifications << notification end notifications end def notify_for_contact?(contact) contact.tasks.where('start_at > ? OR completed_at > ?', past_period_to_check, past_period_to_check) .where(activity_type: task_type_to_check).empty? end def past_period_to_check 1.year.ago end def task_type_to_check task_activity_type end def task_description_template(_notification = nil) raise 'This method must be implemented in a subclass' end end
chuckmersereau/api_practice
db/migrate/20120309171322_create_designation_profiles.rb
<gh_stars>0 class CreateDesignationProfiles < ActiveRecord::Migration def change create_table :designation_profiles do |t| t.integer :remote_id t.belongs_to :user, null: false t.belongs_to :organization, null: false t.string :name t.timestamps null: false end DesignationAccount.destroy_all add_column :designation_accounts, :designation_profile_id, :integer, null: false remove_column :designation_accounts, :profile add_index :designation_profiles, [:user_id, :organization_id, :name], unique: true, name: 'unique_name' add_index :designation_profiles, :organization_id add_index :designation_accounts, :designation_profile_id end end
chuckmersereau/api_practice
app/services/contact/filter/status.rb
class Contact::Filter::Status < Contact::Filter::Base def execute_query(contacts, filters) status_filters = parse_list(filters[:status]) status_filters << 'null' if (status_filters.include? '') && !status_filters.include?('null') status_filters << '' if (status_filters.include? 'null') && !status_filters.include?('') status_filters += Contact.active_statuses + ['null'] if status_filters.include?('active') status_filters += Contact.inactive_statuses if status_filters.include?('hidden') return contacts.where(status: status_filters + [nil]) if status_filters.include? 'null' contacts.where(status: status_filters) end def execute_reverse_query(contacts, filters) status_filters = parse_list(filters[:status]) if (%w(active null) & status_filters).any? status_filters -= %w(active null) status_filters << 'hidden' elsif status_filters.delete('hidden') status_filters << 'null' else return nil end filters[:status] = status_filters.join(',') execute_query(contacts, filters) end def title _('Status') end def type 'multiselect' end def default_options [] end def default_selection 'active, null' end def custom_options [{ name: _('-- All Active --'), id: 'active' }, { name: _('-- All Hidden --'), id: 'hidden' }, { name: _('-- None --'), id: 'null' }] + contact_instance.assignable_statuses.map { |state| { name: _(state), id: state } } end end
chuckmersereau/api_practice
spec/services/siebel_spec.rb
<filename>spec/services/siebel_spec.rb # rubocop:disable Metrics/LineLength require 'rails_helper' describe Siebel do let(:wsapi) { 'https://wsapi.cru.org/wsapi/rest' } let(:org) { create(:organization) } let(:person) { create(:person) } let(:org_account) { build(:organization_account, person: person, organization: org) } let(:account_list) { create(:account_list) } let(:designation_profile) { create(:designation_profile, user: person.to_user, organization: org, account_list: account_list) } let!(:siebel) { Siebel.new(org_account) } let(:designation_account_one) { build(:designation_account, staff_account_id: 1, organization: org) } let(:designation_account_two) { build(:designation_account, staff_account_id: 2, organization: org) } let(:donor_account) { create(:donor_account, organization: org) } let(:contact) { create(:contact) } let(:siebel_donor) do SiebelDonations::Donor.new(Oj.load('{ "id": "602506447", "accountName": "<NAME>angelic<NAME>", "contacts": [ { "updatedAt":"' + 1.day.ago.to_s(:db) + '","id": "1-2XH-663", "primary": true, "firstName": "Friend", "lastName": "<NAME>", "sex": "Unspecified", "phoneNumbers": [ { "updatedAt":"' + 1.day.ago.to_s(:db) + '","id": "1-CI7-4832", "type": "Work", "primary": true, "phone": "408/269-4782" } ] } ], "addresses": [ { "updatedAt":"' + 1.day.ago.to_s(:db) + '","id": "1-HS7-779", "type": "Mailing", "primary": true, "seasonal": false, "address1": "545 Hillsdale Ave", "city": "San Jose", "state": "CA", "zip": "95136-1202" } ], "type": "Business" }')) end before do account_list.users << person.to_user stub_smarty_streets end context '#import_profiles' do let!(:relay) { create(:key_account, person: person) } it 'imports profiles for a relay guid' do stub_request(:get, "#{wsapi}/profiles?response_timeout=600&ssoGuid=#{org_account.remote_id}") .to_return(body: '[ { "name": "Staff Account (0559826)", "designations": [ { "number": "0559826", "description": "Joshua and <NAME> (0559826)", "staffAccountId": "000559826" } ] }]') expect(siebel).to receive(:find_or_create_designation_account) expect do siebel.import_profiles end.to change { DesignationProfile.count }.by(1) end end context '#import_profile_balance' do it 'sets the profile balance to the sum of designation account balances in this profile' do stub_request(:get, "#{wsapi}/staffAccount/balances?employee_ids=1&response_timeout=600") .to_return(body: '{ "1": { "primary": 1 }}') stub_request(:get, "#{wsapi}/staffAccount/balances?employee_ids=2&response_timeout=600") .to_return(body: '{ "2": { "primary": 2 }}') designation_profile.designation_accounts << designation_account_one designation_profile.designation_accounts << designation_account_two siebel.import_profile_balance(designation_profile) expect(designation_profile.balance).to eq(3) end it 'updates the balance of a designation account on that profile' do stub_request(:get, "#{wsapi}/staffAccount/balances?employee_ids=1&response_timeout=600") .to_return(body: '{ "1": { "primary": 1 }}') designation_profile.designation_accounts << designation_account_one siebel.import_profile_balance(designation_profile) expect(designation_account_one.balance).to eq(1) end it 'sets inactive designation accounts to a zero balance thus excluding their amount from the profile total' do stub_request(:get, "#{wsapi}/staffAccount/balances?employee_ids=1&response_timeout=600") .to_return(body: '{ "1": { "primary": 1 }}') stub_request(:get, "#{wsapi}/staffAccount/balances?employee_ids=2&response_timeout=600") .to_return(body: '{ "2": { "primary": 2 }}') designation_profile.designation_accounts << designation_account_one designation_profile.designation_accounts << designation_account_two designation_account_one.update(active: false) siebel.import_profile_balance(designation_profile) expect(designation_profile.balance).to eq(2) expect(designation_account_one.balance).to eq(0) end end context '#import_donations' do it 'imports a new donation from the donor system' do stub_one_donation designation_profile.designation_accounts << designation_account_one expect(siebel).to receive(:add_or_update_donation) siebel.import_donations(designation_profile) end it 'removes a donation not in the downloaded list if list is non-empty' do designation_profile.designation_accounts << designation_account_one create(:donation, remote_id: '1-IGQAP', donor_account: donor_account, designation_account: designation_account_one, donation_date: Date.new(2012, 12, 17)) create(:donation, remote_id: '1-IGQAM', donor_account: donor_account, designation_account: designation_account_one, donation_date: Date.new(2012, 12, 18)) stub_one_donation stub_no_donations_on_date(Date.new(2012, 12, 17)) expect do siebel.send(:import_donations, designation_profile) end.to change { designation_account_one.donations.count }.by(-1) end it 'removes at most 3 donations per import' do designation_profile.designation_accounts << designation_account_one 4.times do |i| create(:donation, remote_id: "#{i}-IGQAP", donor_account: donor_account, designation_account: designation_account_one, donation_date: Date.new(2012, 12, 17)) end create(:donation, remote_id: '1-IGQAM', donor_account: donor_account, designation_account: designation_account_one, donation_date: Date.new(2012, 12, 18)) stub_one_donation stub_no_donations_on_date(Date.new(2012, 12, 17)) expect do siebel.send(:import_donations, designation_profile) end.to change { designation_account_one.donations.count }.by(-3) end it 'does not remove donations if the result from Siebel is empty' do create(:donation, remote_id: '1-IGQAP', donor_account: donor_account, designation_account: designation_account_one, donation_date: Date.new(2012, 12, 18)) stub_donations('[]') stub_no_donations_on_date(Date.new(2012, 12, 18)) designation_profile.designation_accounts << designation_account_one expect do siebel.send(:import_donations, designation_profile) end.to_not change(Donation, :count) end it 'does not remove a donation if it has appeal info' do designation_profile.designation_accounts << designation_account_one appeal = create(:appeal) create(:donation, remote_id: '1-IGQAP', donor_account: donor_account, designation_account: designation_account_one, donation_date: Date.new(2012, 12, 17), appeal: appeal) create(:donation, remote_id: '1-IGQAM', donor_account: donor_account, designation_account: designation_account_one, donation_date: Date.new(2012, 12, 18), appeal: appeal) stub_one_donation stub_no_donations_on_date(Date.new(2012, 12, 17)) expect do siebel.send(:import_donations, designation_profile) end.to_not change(Donation, :count) end it 'does not remove a manually entered donation if it is not in the download list' do designation_profile.designation_accounts << designation_account_one appeal = create(:appeal) create(:donation, remote_id: nil, donor_account: donor_account, designation_account: designation_account_one, donation_date: Date.new(2012, 12, 17), appeal: appeal) create(:donation, remote_id: '1-IGQAM', donor_account: donor_account, designation_account: designation_account_one, donation_date: Date.new(2012, 12, 18), appeal: appeal) stub_one_donation stub_no_donations_on_date(Date.new(2012, 12, 17)) expect do siebel.send(:import_donations, designation_profile) end.to_not change(Donation, :count) end def stub_one_donation donations_json = [ { id: '1-IGQAM', amount: '100.00', designation: designation_account_one.designation_number, donorId: donor_account.account_number, donationDate: '2012-12-18', postedDate: '2012-12-21', paymentMethod: 'Check', channel: 'Mail', campaignCode: '000000' } ].to_json stub_donations(donations_json) end def stub_donations(donations_json) today = Date.today.strftime('%Y-%m-%d') stub_request(:get, "#{wsapi}/donations?designations=#{designation_account_one.designation_number}&"\ "posted_date_end=#{today}&response_timeout=600&posted_date_start=2004-01-01") .to_return(body: donations_json) stub_request(:get, "#{wsapi}/donations?designations=#{designation_account_one.designation_number}&"\ "donation_date_end=#{today}&response_timeout=600&donation_date_start=2004-01-01") .to_return(body: donations_json) end def stub_no_donations_on_date(date) date_str = date.strftime('%Y-%m-%d') stub_request(:get, "#{wsapi}/donations?designations=#{designation_account_one.designation_number}&"\ "donors=#{donor_account.account_number}&end_date=#{date_str}&"\ "response_timeout=600&start_date=#{date_str}") .to_return(body: '[]') end end context '#find_or_create_designation_account' do it "creates a designation account when it can't find one" do expect do siebel.send(:find_or_create_designation_account, '1', designation_profile, name: 'foo') end.to change { DesignationAccount.count }.by(1) end it 'updates an existing designation account' do designation_account_one.save expect do siebel.send(:find_or_create_designation_account, designation_account_one.designation_number, designation_profile, name: 'foo') end.not_to change { DesignationAccount.count } expect(designation_account_one.reload.name).to eq('foo') end end context '#add_or_update_donation' do let(:siebel_donation) { SiebelDonations::Donation.new(Oj.load('{ "id": "1-IGQAM", "amount": "100.00", "designation": "' + designation_account_one.designation_number + '", "donorId": "' + donor_account.account_number + '", "donationDate": "2012-12-18", "postedDate": "2012-12-21", "paymentMethod": "Check", "channel": "Mail", "campaignCode": "000000" }')) } before do designation_account_one.save designation_profile.designation_accounts << designation_account_one end it 'creates a new donation' do expect do siebel.send(:add_or_update_donation, siebel_donation, designation_account_one, designation_profile) end.to change { Donation.count }.by(1) end it 'updates an existing donation with a remote_id' do donation = create(:donation, remote_id: '1-IGQAM', tnt_id: nil, donor_account: donor_account, amount: 5, designation_account: designation_account_one) expect do siebel.send(:add_or_update_donation, siebel_donation, designation_account_one, designation_profile) end.not_to change { Donation.count } expect(donation.reload.amount).to eq(100.00) end it 'updates an existing donation with a tnt_id' do donation = create(:donation, remote_id: nil, tnt_id: '1-IGQAM', donor_account: donor_account, amount: 5, designation_account: designation_account_one) expect do siebel.send(:add_or_update_donation, siebel_donation, designation_account_one, designation_profile) end.not_to change { Donation.count } expect(donation.reload.amount).to eq(100.00) end it 'updates an existing donation that does not have a remote_id or tnt_id' do donation = create(:donation, remote_id: nil, tnt_id: nil, donor_account: donor_account, amount: 100.00, donation_date: Date.parse('2012-12-18'), designation_account: designation_account_one) expect do siebel.send(:add_or_update_donation, siebel_donation, designation_account_one, designation_profile) end.not_to change { Donation.count } expect(donation.reload.remote_id).to eq('1-IGQAM') end it 'imports multiple donations that were made on the same day, by the same donor, and of the same amount' do siebel_donation_one = SiebelDonations::Donation.new(Oj.load(%({ "id": "1-IGQAM", "amount": "100.00", "designation": "#{designation_account_one.designation_number}", "donorId": "#{donor_account.account_number}", "donationDate": "2012-12-18", "postedDate": "2012-12-21", "paymentMethod": "Check", "channel": "Mail", "campaignCode": "000000" }))) siebel_donation_two = SiebelDonations::Donation.new(Oj.load(%({ "id": "1-MHEBN", "amount": "100.00", "designation": "#{designation_account_one.designation_number}", "donorId": "#{donor_account.account_number}", "donationDate": "2012-12-18", "postedDate": "2012-12-21", "paymentMethod": "Check", "channel": "Mail", "campaignCode": "000000" }))) expect { siebel.send(:add_or_update_donation, siebel_donation_one, designation_account_one, designation_profile) }.to change { Donation.count }.from(0).to(1) expect { siebel.send(:add_or_update_donation, siebel_donation_two, designation_account_one, designation_profile) }.to change { Donation.count }.from(1).to(2) end it "fetches the donor from siebel if the donor isn't already on this account list" do donor_account.destroy stub_request(:get, "#{wsapi}/donors?ids=MyString&response_timeout=600") .to_return(body: '[{ "id": "602506447", "accountName": "<NAME>"}]', headers: {}) expect do siebel.send(:add_or_update_donation, siebel_donation, designation_account_one, designation_profile) end.to change { DonorAccount.count }.by(1) end it 'uses the find donation service' do donation = create(:donation, remote_id: nil, tnt_id: nil, donor_account: donor_account, amount: 100.00, donation_date: Date.parse('2012-12-18'), designation_account: designation_account_one) expect_any_instance_of(DonationImports::Base::FindDonation).to receive(:find_and_merge).and_return(donation) expect do siebel.send(:add_or_update_donation, siebel_donation, designation_account_one, designation_profile) end.to_not change { Donation.count } end end context '#import_donors' do before do designation_profile.designation_accounts << designation_account_one stub_request(:get, "#{wsapi}/donors?account_address_filter=primary&contact_email_filter=all&contact_filter=all&contact_phone_filter=all&having_given_to_designations=#{designation_account_one.designation_number}&response_timeout=600") .to_return(body: '[{"id":"602506447","accountName":"HillsideEvangelicalFreeChurch","type":"Business","updatedAt":"' + Date.today.to_s(:db) + '"}]') end it 'imports a new donor from the donor system' do expect(siebel).to receive(:add_or_update_donor_account) expect(siebel).to receive(:add_or_update_company) siebel.import_donors(designation_profile, Date.today) end it 'does not error if donor account has multiple primary addresses' do donor_account.update_column(:account_number, '602506447') address1 = create(:address, primary_mailing_address: true) address2 = create(:address) donor_account.addresses << address1 donor_account.addresses << address2 address2.update_column(:primary_mailing_address, true) siebel.import_donors(designation_profile, Date.today) end end context '#add_or_update_donor_account' do it 'adds a new donor account' do expect(siebel).to receive(:add_or_update_person) expect(siebel).to receive(:add_or_update_address).twice expect do siebel.send(:add_or_update_donor_account, account_list, siebel_donor, designation_profile) end.to change { DonorAccount.count }.by(1) end it 'updates an existing donor account' do donor_account = create(:donor_account, organization: org, account_number: siebel_donor.id) expect(siebel).to receive(:add_or_update_person) expect(siebel).to receive(:add_or_update_address).once.with(anything, donor_account, donor_account) expect(siebel).to receive(:add_or_update_address).once.with(anything, anything, donor_account) expect do siebel.send(:add_or_update_donor_account, account_list, siebel_donor, designation_profile) end.not_to change { DonorAccount.count } expect(donor_account.reload.name).to eq(siebel_donor.account_name) end it "doesn't create a new contact if one already exists with this account number" do donor_account = create(:donor_account, organization: org, account_number: siebel_donor.id) contact = create(:contact, account_list: account_list) donor_account.contacts << contact expect do siebel.send(:add_or_update_donor_account, account_list, siebel_donor, designation_profile) end.not_to change { Contact.count } end it "skips people who haven't been updated since the last download" do donor_account = create(:donor_account, organization: org, account_number: siebel_donor.id) expect(donor_account).to receive(:link_to_contact_for).and_return(contact) allow(org).to receive_message_chain(:donor_accounts, :where, :first_or_initialize) .and_return(donor_account) allow(contact).to receive_message_chain(:people, :present?).and_return(true) expect(siebel).to_not receive(:add_or_update_person) expect do siebel.send(:add_or_update_donor_account, account_list, siebel_donor, designation_profile, Time.zone.now) end.not_to change { Person.count } expect(donor_account.reload.name).to eq(siebel_donor.account_name) end end context '#add_or_update_person' do let(:siebel_person) { SiebelDonations::Contact.new(Oj.load('{"id":"1-3GJ-2744","primary":true,"firstName":"Jean","preferredName":"Jean","lastName":"Spansel","title":"Mrs","sex":"F"}')) } it 'adds a new person' do siebel_person_with_rels = SiebelDonations::Contact.new(Oj.load('{"id":"1-3GJ-2744","primary":true,"firstName":"Jean","preferredName":"Jean","lastName":"Spansel","title":"Mrs","sex":"F","emailAddresses":[{"updatedAt":"' + 1.day.ago.to_s(:db) + '","id":"1-CEX-8425","type":"Home","primary":true,"email":"<EMAIL>"}],"phoneNumbers":[{"id":"1-BTE-2524","type":"Work","primary":true,"phone":"510/656-7873"}]}')) expect(siebel).to receive(:add_or_update_email_address).twice expect(siebel).to receive(:add_or_update_phone_number).twice expect do siebel.send(:add_or_update_person, siebel_person_with_rels, donor_account, contact) end.to change { Person.count }.by(2) end it 'skips phone numbers and emails that have not been updated' do siebel_person_with_rels = SiebelDonations::Contact.new( Oj.load('{"id":"1-3GJ-2744","primary":true,"firstName":"Jean","preferredName":"Jean","lastName":"Spansel", "title":"Mrs","sex":"F","emailAddresses":[ {"updatedAt":"' + 1.day.ago.to_s(:db) + '","id":"1-CEX-8425","type":"Home","primary":true, "email":"<EMAIL>"}], "phoneNumbers":[{"updatedAt":"' + 1.day.ago.to_s(:db) + '","id":"1-BTE-2524","type":"Work", "primary":true,"phone":"510/656-7873"}]}') ) expect(contact).to receive(:add_person).and_return(person) allow(person).to receive_message_chain(:phone_numbers, :present?).and_return(true) allow(person).to receive_message_chain(:email_addresses, :present?).and_return(true) expect(siebel).to_not receive(:add_or_update_email_address) expect(siebel).to_not receive(:add_or_update_phone_number) siebel.send(:add_or_update_person, siebel_person_with_rels, donor_account, contact, Time.zone.now) end it 'leaves the user modified name fields alone when it updates a person' do mp = MasterPerson.create MasterPersonSource.create(master_person_id: mp.id, organization_id: org.id, remote_id: siebel_person.id) p = create(:person, master_person_id: mp.id) donor_account.people << p contact.people << p expect do siebel.send(:add_or_update_person, siebel_person, donor_account, contact) end.not_to change { Person.count } expect(p.reload.legal_first_name).to_not eq(siebel_person.first_name) end it 'find and updates an old-style remote_id' do # Set up a person with the old style remote id mp = MasterPerson.create mps = MasterPersonSource.create(master_person_id: mp.id, organization_id: org.id, remote_id: donor_account.account_number + '-1') expect do siebel.send(:add_or_update_person, siebel_person, donor_account, contact) end.not_to change { MasterPersonSource.count } expect(mps.reload.remote_id).to eq(siebel_person.id) end it 'maps sex=M to gender=male' do siebel_person = SiebelDonations::Contact.new(Oj.load('{"id":"1-3GJ-2744","primary":true,"firstName":"Jean","preferredName":"Jean","lastName":"Spansel","title":"Mrs","sex":"M"}')) p = siebel.send(:add_or_update_person, siebel_person, donor_account, contact).first expect(p.gender).to eq('male') end it 'maps sex=Undetermined to gender=nil' do siebel_person = SiebelDonations::Contact.new(Oj.load('{"id":"1-3GJ-2744","primary":true,"firstName":"Jean","preferredName":"Jean","lastName":"Spansel","title":"Mrs","sex":"Undetermined"}')) p = siebel.send(:add_or_update_person, siebel_person, donor_account, contact).first expect(p.gender).to be_nil end end context '#add_or_update_address' do let(:siebel_address) { SiebelDonations::Address.new(Oj.load('{"id":"1-IQ5-1006","type":"Mailing","primary":true,"seasonal":false,"address1":"1697 Marabu Way","city":"Fremont","state":"CA","zip":"94539-3683","updated_at":"2014-02-14"}')) } let(:source_donor_account) { create(:donor_account) } it 'adds a new address' do expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to change { Address.count }.by(1) expect(contact.addresses.count).to eq(1) address = contact.addresses.first attrs = { street: '1697 Marab<NAME>', city: 'Fremont', state: 'CA', country: nil, postal_code: '94539-3683', start_date: Date.new(2014, 2, 14), source: 'Siebel' } expect(address.attributes.symbolize_keys.slice(*attrs.keys)).to eq(attrs) end it 'updates an existing address' do address = create(:address, addressable: contact, remote_id: siebel_address.id) expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.not_to change { Address.count } expect(address.reload.postal_code).to eq(siebel_address.zip) end it 'raises an error if the address is invalid' do siebel_address = SiebelDonations::Address.new(Oj.load('{"id":"1-IQ5-1006","type":"BAD_TYPE"}')) expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to raise_error(/Validation failed/) end it "doesn't add a new address when there is a matching deleted address" do create(:address, addressable: contact, street: siebel_address.address1, city: siebel_address.city, state: siebel_address.state, postal_code: siebel_address.zip, deleted: true) expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.not_to change { Address.count } end it 'sets the source donor account' do source_donor_account = create(:donor_account) siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) expect(contact.addresses.first.source_donor_account).to eq(source_donor_account) end it 'sets the address as primary if none are marked primary' do contact.addresses << create(:address, historic: true, primary_mailing_address: false) expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to change(Address, :count).from(1).to(2) expect(contact.addresses.where(primary_mailing_address: true).count).to eq(1) expect(contact.addresses.where.not(remote_id: nil).first.primary_mailing_address).to be true # survives a second import contact.reload expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to_not change(Address, :count) expect(contact.addresses.reload.where(primary_mailing_address: true).count).to eq(1) end it 'does not set the address as primary if a non-matching non-Siebel address is primary' do manual_address = create(:address, primary_mailing_address: true, source: Address::MANUAL_SOURCE) contact.addresses << manual_address expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to change(Address, :count).from(1).to(2) expect(manual_address.primary_mailing_address).to be true expect(contact.addresses.where.not(remote_id: nil).first.primary_mailing_address).to be false # survives a second import contact.reload expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to_not change(Address, :count) expect(manual_address.primary_mailing_address).to be true expect(contact.addresses.where.not(remote_id: nil).first.primary_mailing_address).to be false end it 'sets the address as primary if a Siebel address from the same donor account is primary' do donor_account = create(:donor_account) contact.addresses << create(:address, primary_mailing_address: true, source: 'Siebel', source_donor_account: donor_account) expect do siebel.send(:add_or_update_address, siebel_address, contact, donor_account) end.to change(Address, :count).from(1).to(2) expect(contact.addresses.where(primary_mailing_address: true).count).to eq(1) expect(contact.addresses.where.not(remote_id: nil).first.primary_mailing_address).to be true # survives a second import contact.reload expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to_not change(Address, :count) expect(contact.addresses.where(primary_mailing_address: true).count).to eq(1) expect(contact.addresses.where.not(remote_id: nil).first.primary_mailing_address).to be true end it 'does not make address primary if a non-matching Siebel address from a different donor account is primary' do donor_account1 = create(:donor_account) donor_account2 = create(:donor_account) contact.addresses << create(:address, primary_mailing_address: true, source: 'Siebel', source_donor_account: donor_account1) expect do siebel.send(:add_or_update_address, siebel_address, contact, donor_account2) end.to change(Address, :count).from(1).to(2) expect(contact.addresses.where(primary_mailing_address: true).count).to eq(1) expect(contact.addresses.where.not(remote_id: nil).first.primary_mailing_address).to be false # survives a second import contact.reload expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to_not change(Address, :count) expect(contact.addresses.where(primary_mailing_address: true).count).to eq(1) expect(contact.addresses.where.not(remote_id: nil).first.primary_mailing_address).to be false end def stub_siebel_address_smarty address_smarty = '[{"delivery_line_1":"1697 Marabu Way","components":{"city_name":"Fremont",'\ '"state_abbreviation":"CA","zipcode":"94539","plus4_code":"3683"}}]' stub_request(:get, %r{https://api\.smartystreets\.com/.*}).to_return(body: address_smarty) end it 'matches and updates an address with the same master but different formatting' do stub_siebel_address_smarty contact.addresses << create(:address, primary_mailing_address: true, master_address: nil, street: '1697 Marabu', city: 'Fremont', state: 'CA', postal_code: '94539') expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to_not change(Address, :count).from(1) address = contact.addresses.first expect(address.street).to eq('1697 Marabu Way') expect(address.postal_code).to eq('94539-3683') expect(address.primary_mailing_address).to be true expect(address.source).to eq('Siebel') expect(address.remote_id).to_not be_nil expect(address.source_donor_account).to eq(source_donor_account) expect(address.start_date).to eq(Date.new(2014, 2, 14)) end it 'prefers match by place and disconnects remote id of old address now points to new place' do stub_siebel_address_smarty new_manual_address = create(:address, primary_mailing_address: true, master_address: nil, street: '1697 Marabu', city: 'Fremont', state: 'CA', postal_code: '94539', source: 'Manual', start_date: Date.new(2014, 1, 1), remote_id: nil) old_remote_address = create(:address, primary_mailing_address: false, remote_id: '1-IQ5-1006') contact.addresses << new_manual_address contact.addresses << old_remote_address expect do siebel.send(:add_or_update_address, siebel_address, contact, source_donor_account) end.to_not change(Address, :count).from(2) expect(contact.addresses.where(primary_mailing_address: true).count).to eq(1) new_manual_address.reload expect(new_manual_address.street).to eq('1697 Marabu Way') expect(new_manual_address.postal_code).to eq('94539-3683') expect(new_manual_address.primary_mailing_address).to be true expect(new_manual_address.source).to eq('Siebel') expect(new_manual_address.remote_id).to eq('1-IQ5-1006') expect(new_manual_address.source_donor_account).to eq(source_donor_account) expect(new_manual_address.start_date).to eq(Date.new(2014, 2, 14)) expect(new_manual_address.primary_mailing_address).to be true old_remote_address.reload expect(old_remote_address.primary_mailing_address).to be false expect(old_remote_address.remote_id).to be_nil end end context '#add_or_update_phone_number' do let(:siebel_phone_number) { SiebelDonations::PhoneNumber.new(Oj.load('{"id":"1-CI7-4832","type":"Work","primary":true,"phone":"408/269-4782"}')) } it 'adds a new phone number' do expect do siebel.send(:add_or_update_phone_number, siebel_phone_number, person) end.to change { PhoneNumber.count }.by(1) end it 'updates an existing phone number' do pn = create(:phone_number, person: person, remote_id: siebel_phone_number.id) expect do siebel.send(:add_or_update_phone_number, siebel_phone_number, person) end.not_to change { PhoneNumber.count } expect(pn.reload.number).to eq('+14082694782') end end context '#add_or_update_email_address' do let(:siebel_email) { SiebelDonations::EmailAddress.new(Oj.load('{"id":"1-CEX-8425","type":"Home","primary":true,"email":"<EMAIL>"}')) } it 'adds a new email address' do expect do siebel.send(:add_or_update_email_address, siebel_email, person) end.to change { EmailAddress.count }.by(1) end it 'updates an existing email address' do email = create(:email_address, person: person, remote_id: siebel_email.id) expect do siebel.send(:add_or_update_email_address, siebel_email, person) end.not_to change { EmailAddress.count } expect(email.reload.email).to eq(siebel_email.email) end end context '#add_or_update_company' do it 'adds a new company' do expect do siebel.send(:add_or_update_company, account_list, siebel_donor, donor_account) end.to change { Company.count }.by(1) end it 'updates an existing company' do mc = create(:master_company, name: siebel_donor.account_name) company = create(:company, master_company: mc) account_list.companies << company expect do siebel.send(:add_or_update_company, account_list, siebel_donor, donor_account) end.not_to change { Company.count } expect(company.reload.name).to eq(siebel_donor.account_name) end end context '#profiles_with_designation_numbers' do it 'returns a hash of attributes' do expect(siebel).to receive(:profiles).and_return( [SiebelDonations::Profile.new('id' => '', 'name' => 'Profile 1', 'designations' => [{ 'number' => '1234' }])] ) expect(siebel.profiles_with_designation_numbers) .to eq([{ name: 'Profile 1', code: '', designation_numbers: ['1234'] }]) end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/people/bulk_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'People Bulk' do include_context :json_headers doc_helper = DocumentationHelper.new(resource: :people) let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact) { create(:contact, account_list: account_list) } let!(:person_one) { create(:person, contacts: [contact]) } let!(:person_two) { create(:person, contacts: [contact]) } let!(:resource_type) { 'people' } let!(:user) { create(:user_with_account) } let(:new_person_attributes) do attributes_for(:person) .merge(updated_in_db_at: person_one.updated_at) end let(:contacts_relationship) do { contacts: { data: [ type: 'contacts', id: contact.id ] } } end let(:bulk_create_form_data) do [ { data: { type: resource_type, id: SecureRandom.uuid, attributes: new_person_attributes, relationships: contacts_relationship } } ] end let(:bulk_update_form_data) do [ { data: { type: resource_type, id: person_one.id, attributes: new_person_attributes } } ] end context 'authorized user' do before { api_login(user) } post '/api/v2/contacts/people/bulk' do doc_helper.insert_documentation_for(action: :bulk_create, context: self) example doc_helper.title_for(:bulk_create), document: doc_helper.document_scope do explanation doc_helper.description_for(:bulk_create) do_request data: bulk_create_form_data expect(response_status).to eq(200) expect(json_response.first['data']['attributes']['name']).to eq new_person_attributes[:name] end end put '/api/v2/contacts/people/bulk' do doc_helper.insert_documentation_for(action: :bulk_update, context: self) example doc_helper.title_for(:bulk_update), document: doc_helper.document_scope do explanation doc_helper.description_for(:bulk_update) do_request data: bulk_update_form_data expect(response_status).to eq(200) expect(json_response.first['data']['attributes']['name']).to eq new_person_attributes[:name] end end delete '/api/v2/contacts/people/bulk' do doc_helper.insert_documentation_for(action: :bulk_delete, context: self) example doc_helper.title_for(:bulk_delete), document: doc_helper.document_scope do explanation doc_helper.description_for(:bulk_delete) do_request data: [ { data: { type: resource_type, id: person_one.id } }, { data: { type: resource_type, id: person_two.id } } ] expect(response_status).to eq(200) expect(json_response.size).to eq(2) expect(json_response.collect { |hash| hash.dig('data', 'id') }).to match_array([person_one.id, person_two.id]) end end end end
chuckmersereau/api_practice
spec/models/email_address_spec.rb
require 'rails_helper' describe EmailAddress do context '.add_for_person' do let(:person) { create(:person) } let(:address) { '<EMAIL>' } let(:address_changed_case) { '<EMAIL>' } include_examples 'updatable_only_when_source_is_mpdx_validation_examples', attributes: [:email, :remote_id, :location], factory_type: :email_address include_examples 'after_validate_set_source_to_mpdx_examples', factory_type: :email_address it "should create an email address if it's new" do expect do EmailAddress.add_for_person(person, email: address) expect(person.email_addresses.first.email).to eq(address) end.to change(EmailAddress, :count).from(0).to(1) end it "doesn't create an email address if it exists" do EmailAddress.add_for_person(person, email: address) expect do EmailAddress.add_for_person(person, email: address) expect(person.email_addresses.first.email).to eq(address) end.to_not change(EmailAddress, :count) end it "doesn't create an email address if it exists - case insensitive" do person.email = address expect do person.email = address_changed_case person.save! expect(person.reload.email_addresses.first.email).to eq(address) end.to_not change(EmailAddress, :count) end it 'creates a duplicate email address if it is from an TntImport' do EmailAddress.add_for_person(person, email: address) expect do EmailAddress.add_for_person(person, email: address, source: 'TntImport') expect(person.email_addresses.first.email).to eq(address) end.to change(EmailAddress, :count).from(1).to(2) end it 'should be invalid if email address with different case already exists' do EmailAddress.add_for_person(person, email: address) email = EmailAddress.create(person: person, email: address_changed_case) expect(email.errors[:email]).to include('has already been taken') end it "doesn't create an email address if it exists and are both from TntImports" do EmailAddress.add_for_person(person, email: address, source: 'TntImport') expect do EmailAddress.add_for_person(person, email: address, source: 'TntImport') expect(person.email_addresses.first.email).to eq(address) end.to_not change(EmailAddress, :count) end it 'does nothing when adding itself to a person' do email = EmailAddress.add_for_person(person, email: address) expect do EmailAddress.add_for_person(person, email: address, id: email.id) end.to_not change(EmailAddress, :count) end it 'sets only the first email to primary' do EmailAddress.add_for_person(person, email: address) expect(person.email_addresses.first).to be_primary EmailAddress.add_for_person(person, email: 'foo' + address) expect(person.email_addresses.last).to_not be_primary end it 'sets a prior email to not-primary if the new one is primary' do email1 = EmailAddress.add_for_person(person, email: address) expect(email1).to be_primary email2 = EmailAddress.add_for_person(person, email: 'foo' + address, primary: true) expect(email2).to be_primary email2.send(:ensure_only_one_primary) expect(email1.reload).to_not be_primary end it 'leaves prior email as primary if the new one is not primary' do email1 = EmailAddress.add_for_person(person, email: address) expect do email2 = EmailAddress.add_for_person(person, email: 'foo' + address) expect(email2).to_not be_primary end.to_not change { email1.reload.primary? }.from(true) end it 'gracefully handles duplicate emails on an unsaved person' do person = build(:person) email = '<EMAIL>' person.email_address = { email: email } EmailAddress.add_for_person(person, email: email) person.save expect(person.email_addresses.first.email).to eq(email) expect(person.email_addresses.length).to eq(1) end it 'handles emails that differ by a zero-width chars on person.save(validate: false)' do create(:email_address, email: '<EMAIL>', person: person) person.email_address = { email: "j\u200E\<EMAIL>\u200E\u200B", primary: true } person.save(validate: false) expect(person.reload.email_addresses.count).to eq 1 expect(person.reload.email_addresses.first.email).to eq '<EMAIL>' end end context '#clean_and_split_emails' do it 'splits emails by commas and semicolons, removes names and handles comma in name' do { '' => [], nil => [], '<NAME> <<EMAIL>>' => ['<EMAIL>'], '<NAME><<EMAIL>>' => ['<EMAIL>'], '"<NAME> <<EMAIL>' => ['<EMAIL>'], '<EMAIL>, <EMAIL>;<EMAIL>' => ['<EMAIL>', '<EMAIL>', '<EMAIL>'], '"<NAME>" <<EMAIL>>,<EMAIL>' => ['<EMAIL>', '<EMAIL>'], '<EMAIL>; "<NAME>" <<EMAIL>>' => ['<EMAIL>', '<EMAIL>'], '<EMAIL>; "<NAME> <<EMAIL>' => ['<EMAIL>', '<EMAIL>'], '<NAME> <<EMAIL>>, <EMAIL>' => ['<EMAIL>', '<EMAIL>'], '<EMAIL>; <NAME> <<EMAIL>>' => ['<EMAIL>', '<EMAIL>'] }.each do |email_str, expected_cleaned_and_split| expect(EmailAddress.clean_and_split_emails(email_str)).to eq(expected_cleaned_and_split) end end end context '#expand_and_clean_emails' do it 'expands the email field if it has multiple emails, makes only the first primary, keeps other attrs' do { { email: '<EMAIL>', historic: true } => [{ email: '<EMAIL>', historic: true }], { email: '<EMAIL>, <EMAIL>', location: 'a' } => [ { email: '<EMAIL>', location: 'a' }, { email: '<EMAIL>', location: 'a' } ], { email: '<EMAIL>; <NAME> <<EMAIL>>', primary: true, location: 'b' } => [ { email: '<EMAIL>', primary: true, location: 'b' }, { email: '<EMAIL>', primary: false, location: 'b' } ] }.each do |email_attrs, expected_expanded| expect(EmailAddress.expand_and_clean_emails(email_attrs)).to eq(expected_expanded) end end end it 'strips out whitespace and zero-width characters before saving email' do email = build(:email_address, email: "\t zero-width-spaces\u200B\u200E<EMAIL> \n") email.save expect(email.email).to eq '<EMAIL>' end describe '#set_valid_values' do it "sets valid_values to true if this is the person's only email address, or the source is manual" do email_address_one = create(:email_address, source: 'not mpdx') expect(email_address_one.valid_values).to eq(true) expect(email_address_one.source).to_not eq(EmailAddress::MANUAL_SOURCE) email_address_two = create(:email_address, source: 'not mpdx', person: email_address_one.person) expect(email_address_two.valid_values).to eq(false) expect(email_address_two.source).to_not eq(EmailAddress::MANUAL_SOURCE) email_address_three = create(:email_address, source: EmailAddress::MANUAL_SOURCE, person: email_address_one.person) expect(email_address_three.valid_values).to eq(true) end end describe '#start_google_plus_account_fetcher_job' do it 'starts the GooglePlusAccountFetcherWorker job' do allow_any_instance_of(EmailAddress).to receive(:start_google_plus_account_fetcher_job).and_call_original expect(GooglePlusAccountFetcherWorker).to receive(:perform_async) create(:email_address) end end describe '#sync_with_mail_chimp_account' do let!(:mail_chimp_account) { build(:mail_chimp_account, primary_list_id: 'primary_list_id') } let!(:account_list) { create(:account_list, mail_chimp_account: mail_chimp_account) } let!(:contact) do create( :contact, primary_person: first_person, people: [second_person], account_list: account_list, send_newsletter: 'Email' ) end let!(:first_person) { create(:person, primary_email_address: build(:email_address)) } let!(:second_person) { create(:person, email_addresses: [build(:email_address)]) } it 'syncs the contact when a primary email_address is added to a primary_person' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [contact.id] ) create(:email_address, person: first_person, primary: true) end it 'syncs the contact when a primary email_address is added to a secondary person' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [contact.id] ) create(:email_address, person: second_person, primary: true) end it 'does not sync the contact when a none primary email_address is added' do expect(MailChimp::ExportContactsWorker).not_to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [contact.id] ) create(:email_address, person: first_person) end it 'syncs the contact when a primary_email_address is updated with a new email' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [contact.id] ) first_person.primary_email_address.reload.update(email: '<EMAIL>') end it 'triggers sync when changing primary email address' do expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with( mail_chimp_account.id, 'primary_list_id', [contact.id] ) not_primary = first_person.email_addresses.create(email: '<EMAIL>') not_primary.update(primary: true) end end end
chuckmersereau/api_practice
spec/services/csv_file_reader_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/services/csv_file_reader_spec.rb require 'rails_helper' describe CsvFileReader do let(:file_path) { Rails.root.join('spec/fixtures/sample_csv_with_custom_headers.csv') } let(:service) { CsvFileReader.new(file_path) } it 'initializes' do expect(service).to be_a CsvFileReader end describe '#each_row' do it 'enumerates through the csv rows' do rows = [] service.each_row do |csv_row| expect(csv_row).to be_a(CSV::Row) expect(csv_row.headers).to be_present expect(csv_row.fields).to be_present rows << csv_row end expect(rows.size).to eq(3) end it 'skips blank rows' do file_path = Rails.root.join('spec/fixtures/sample_csv_with_some_invalid_rows.csv') expect(CSV.read(file_path).size).to eq(5) service = CsvFileReader.new(file_path) rows = [] service.each_row { |csv_row| rows << csv_row } expect(rows.size).to eq(3) expect(rows.all? { |row| row.to_h.values.compact.present? }).to eq(true) end it 'does not error if the csv file has a byte order mark' do service = CsvFileReader.new(Rails.root.join('spec/fixtures/sample_csv_with_bom.csv')) rows = [] service.each_row { |csv_row| rows << csv_row } expect(rows.size).to eq(1) expect(rows.first.headers).to eq(['Contact Name', 'First Name', 'Last Name', 'Spouse First Name', 'Greeting', 'Envelope Greeting', 'Church', 'Mailing Street Address', 'Mailing City', 'Mailing State', 'Mailing Postal Code', 'Mailing Country', 'Status', 'Commitment Amount', 'Commitment Frequency', 'Newsletter', 'Commitment Received', 'Commitment Currency', 'Tags', 'Primary Email', 'Spouse Email', 'Primary Phone', 'Spouse Phone', 'Notes']) expect(rows.first.fields).to eq(['Doe, John and Jane', 'John', 'Doe', 'Jane', 'Hi John and Jane', 'Doe family', 'Westside Baptist Church', '1 Example Ave, Apt 6', 'Sample City', 'IL', '60201', 'USA', 'Partner - Pray', '50', 'Monthly', 'Both', 'Yes', 'CAD', 'christmas-card, family', '<EMAIL>', '<EMAIL>', '(213) 222-3333', '(407) 555-6666', 'test notes']) end it 'does not error if the csv file has a non-utf-8 encoding' do service = CsvFileReader.new(Rails.root.join('spec/fixtures/sample_csv_iso_8950_1.csv')) rows = [] service.each_row { |csv_row| rows << csv_row } expect(rows.size).to eq(1) expect(rows.first.headers).to eq(['Contact Name', 'First Name', 'Last Name', 'Spouse First Name', 'Spouse Last Name', 'Greeting', 'Envelope Greeting', 'Church', 'Mailing Street Address', 'Mailing City', 'Mailing State', 'Mailing Postal Code', 'Mailing Country', 'Status', 'Commitment Amount', 'Commitment Frequency', 'Newsletter', 'Commitment Received', 'Commitment Currency', 'Tags', 'Primary Email', 'Spouse Email', 'Primary Phone', 'Spouse Phone', 'Notes']) expect(rows.first.fields).to eq(['<NAME>', 'John', 'Lané', nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]) end end end
chuckmersereau/api_practice
app/workers/add_pledges_to_donations_worker.rb
class AddPledgesToDonationsWorker include Sidekiq::Worker def perform donations_without_pledges.find_each do |donation| appeal = donation.appeal next unless appeal account_list = appeal.account_list next unless account_list contact = donation.donor_account.contacts.where(account_list: account_list).first next unless contact create_pledge(account_list, donation, contact, appeal) end end private def donations_without_pledges Donation.where .not(appeal: nil) .includes(:pledge_donations) .where(pledge_donations: { id: nil }) end def create_pledge(account_list, donation, contact, appeal) donation_amount = donation.appeal_amount.to_i.positive? ? donation.appeal_amount : donation.amount pledge = account_list.pledges.find_or_initialize_by(appeal: appeal, contact: contact) if pledge.id pledge.donations << donation pledge.update(amount: pledge.amount + donation_amount) else pledge.assign_attributes(amount: donation_amount, expected_date: donation.donation_date, donations: [donation]) pledge.save end end end
chuckmersereau/api_practice
db/migrate/20150228143706_change_donation_fields_to_money_type.rb
<gh_stars>0 class ChangeDonationFieldsToMoneyType < ActiveRecord::Migration def change_field_to_money(table, field) ActiveRecord::Base.connection.execute("ALTER TABLE #{table} ALTER COLUMN #{field} TYPE money") end def change change_field_to_money :appeals, :amount change_field_to_money :contacts, :pledge_amount change_field_to_money :contacts, :total_donations change_field_to_money :designation_accounts, :balance change_field_to_money :designation_profiles, :balance change_field_to_money :donations, :tendered_amount change_field_to_money :donations, :amount change_field_to_money :donations, :appeal_amount change_field_to_money :donor_accounts, :total_donations end end
chuckmersereau/api_practice
spec/services/contact/filter/state_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/services/contact/filter/state_spec.rb require 'rails_helper' RSpec.describe Contact::Filter::State do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact_one) { create(:contact, account_list_id: account_list.id) } let!(:contact_two) { create(:contact, account_list_id: account_list.id) } let!(:contact_three) { create(:contact, account_list_id: account_list.id) } let!(:contact_four) { create(:contact, account_list_id: account_list.id) } let!(:contact_five) { create(:contact, account_list_id: account_list.id) } let!(:address_one) { create(:address) } let!(:address_two) { create(:address) } let!(:address_three) { create(:address, state: nil) } let!(:address_four) { create(:address, state: nil) } let!(:address_five) { create(:address, historic: true) } before do contact_one.addresses << address_one contact_two.addresses << address_two contact_three.addresses << address_three contact_four.addresses << address_four contact_five.addresses << address_five end describe '#config' do it 'returns expected config' do options = [{ name: '-- Any --', id: '', placeholder: 'None' }, { name: '-- None --', id: 'none' }, { name: 'CA', id: 'CA' }] expect(described_class.config([account_list])).to include(multiple: true, name: :state, options: options, parent: 'Contact Location', title: 'State', type: 'multiselect', default_selection: '') end end describe '#query' do let(:contacts) { Contact.all } context 'no filter params' do it 'returns nil' do expect(described_class.query(contacts, {}, nil)).to eq(nil) expect(described_class.query(contacts, { state: {} }, nil)).to eq(nil) expect(described_class.query(contacts, { state: [] }, nil)).to eq(nil) expect(described_class.query(contacts, { state: '' }, nil)).to eq(nil) end end context 'filter by no state' do it 'returns only contacts that have no state' do result = described_class.query(contacts, { state: 'none' }, nil).to_a expect(result).to match_array [contact_three, contact_four] end end context 'filter by state' do it 'filters multiple states' do result = described_class.query(contacts, { state: 'CA, CA' }, nil).to_a expect(result).to match_array [contact_one, contact_two] end it 'filters a single state' do result = described_class.query(contacts, { state: 'CA' }, nil).to_a expect(result).to match_array [contact_one, contact_two] end end context 'multiple filters' do it 'returns contacts matching multiple filters' do result = described_class.query(contacts, { state: 'CA, none' }, nil).to_a expect(result).to match_array [contact_one, contact_two, contact_three, contact_four] end end context 'address historic' do it 'returns contacts matching the state with historic addresses' do result = described_class.query(contacts, { state: 'CA', address_historic: 'true' }, nil).to_a expect(result).to eq [contact_five] end end end end
chuckmersereau/api_practice
spec/support/shared_controller_examples/index_examples.rb
<gh_stars>0 RSpec.shared_examples 'index_examples' do |options = {}| options[:except] ||= [] include_context 'common_variables' let(:active_record_association) { ActiveRecord::Relation } describe '#index' do include_examples 'including related resources examples', action: :index unless options[:except].include?(:includes) include_examples 'sparse fieldsets examples', action: :index unless options[:except].include?(:sparse_fieldsets) include_examples 'sorting examples', action: :index unless options[:except].include?(:sorting) include_examples 'filtering examples', action: :index unless options[:except].include?(:filtering) it 'shows resources to users that are signed in' do api_login(user) get :index, parent_param_if_needed expect(response.status).to eq(200), invalid_status_detail expect(response.body).to include(resource.class.order(:created_at).first.send(reference_key).to_s) if reference_key end it 'does not show resources that do not belong to the signed in user' do api_login(user) expect { create(factory_type) }.not_to change { get :index, parent_param_if_needed JSON.parse(response.body)['data'].count } end it 'does not shows resources to users that are not signed in' do get :index, parent_param_if_needed expect(response.status).to eq(401), invalid_status_detail end it 'does not show resources to signed in users if they do not own the parent' do if defined?(parent_param) && parent_param.present? api_login(create(:user)) get :index, parent_param expect(response.status).to eq(403), invalid_status_detail end end it 'paginates differently when specified in params' do api_login(user) get :index, parent_param_if_needed.merge(per_page: 1, page: 2) expect(response.status).to eq(200), invalid_status_detail json_body = JSON.parse(response.body) expect(json_body['data'].length).to eq(1) expect(json_body['data'].first['id']).to_not eq(resource.id) expect(json_body['meta']['pagination']['per_page']).to eq('1') expect(json_body['meta']['pagination']['page']).to eq('2') expect(json_body['meta']['pagination']['total_count']).not_to be_nil expect(json_body['meta']['pagination']['total_pages']).not_to be_nil end unless options[:except].include?(:pagination) end end
chuckmersereau/api_practice
spec/factories/mail_chimp_appeal_lists.rb
FactoryBot.define do factory :mail_chimp_appeal_list do association :mail_chimp_account association :appeal sequence(:appeal_list_id) { |n| n } end end
chuckmersereau/api_practice
spec/support/shared_controller_examples/update_examples.rb
RSpec.shared_examples 'update_examples' do |options = {}| options[:except] ||= [] include_context 'common_variables' describe '#update' do include_examples 'including related resources examples', action: :update unless options[:except].include?(:includes) include_examples 'sparse fieldsets examples', action: :update unless options[:except].include?(:sparse_fieldsets) it 'updates resource for users that are signed in' do api_login(user) put :update, full_update_attributes expect(response.status).to eq(200), invalid_status_detail expect(resource.reload.send(update_reference_key)).to eq(update_reference_value) end it 'does not update the resource with unpermitted relationships' do if defined?(unpermitted_relationships) api_login(user) put :update, full_unpermitted_attributes expect(response.status).to eq(403), invalid_status_detail expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value) end end it 'does not update the resource when there are errors in sent data' do if can_run_incorrect_update_specs && incorrect_attributes api_login(user) put :update, full_incorrect_attributes expect(response.status).to eq(400), invalid_status_detail expect(response.body).to include('errors') expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value) expect(response_errors).to be_present if response_error_pointers.present? expect( incorrect_attributes.keys.any? do |incorrect_attribute| pointer_reference = "/data/attributes/#{incorrect_attribute}" response_error_pointers.include?(pointer_reference) end ).to be true end end end it 'does not update resources with outdated updated_at field' do api_login(user) full_update_attributes[:data][:attributes][:updated_in_db_at] = 1.year.ago full_update_attributes[:data][:attributes][:overwrite] = nil put :update, full_update_attributes expect(response.status).to eq(409), invalid_status_detail expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value) expect(response_errors).to be_present end it 'does not update resource for users that do not own the resource' do if defined?(id) api_login(create(:user)) put :update, full_update_attributes expect(response.status).to eq(403), invalid_status_detail expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value) expect(response_errors).to be_present end end it 'does not allow account_list to be set if account_list_id is in url' do if resource.respond_to?(:account_list_id) && parent_param_if_needed[:account_list_id].present? api_login(user) expect do put :update, account_list_id: account_list.id, id: resource.id, data: { type: resource_type, id: resource.id, relationships: { account_list: { data: { type: 'account_lists', id: create(:account_list).id } } }, attributes: { overwrite: true } } end.not_to change { resource.reload.account_list_id } expect(response.status).to eq(200) end end it 'does not updates resource for users that are not signed in' do put :update, full_update_attributes expect(response.status).to eq(401), invalid_status_detail expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value) expect(response_errors).to be_present end it 'does not update a resource if the resource_type is incorrect' do api_login(user) put :update, attributes_with_incorrect_resource_type expect(response.status).to eq(409), invalid_status_detail expect(response_errors).to be_present end end def can_run_incorrect_update_specs !(defined?(dont_run_incorrect_update) && dont_run_incorrect_update) end end
chuckmersereau/api_practice
app/models/google_email_activity.rb
<reponame>chuckmersereau/api_practice class GoogleEmailActivity < ApplicationRecord belongs_to :activity belongs_to :google_email end
chuckmersereau/api_practice
spec/lib/sidekiq_monitor_spec.rb
require 'rails_helper' describe SidekiqMonitor do context '.queue_latency_too_high' do before do ENV['SIDEKIQ_WARN_DEFAULT_QUEUE_LATENCY'] = '600' end it 'returns true if default queue latency above threshold' do stub_latency(599.5) expect(SidekiqMonitor.queue_latency_too_high?).to be false end it 'returns false if default queue latency below threshold' do stub_latency(601.1) expect(SidekiqMonitor.queue_latency_too_high?).to be true end def stub_latency(latency) default_queue = double expect(Sidekiq::Queue).to receive(:new) { default_queue } expect(default_queue).to receive(:latency) { latency } end end end
chuckmersereau/api_practice
db/migrate/20171108032537_change_index_on_background_batch_requests.rb
class ChangeIndexOnBackgroundBatchRequests < ActiveRecord::Migration def change remove_index :background_batch_requests, :uuid add_index :background_batch_requests, :uuid, unique: true end end
chuckmersereau/api_practice
spec/models/notification_type/thank_partner_once_per_year_spec.rb
<gh_stars>0 require 'rails_helper' describe NotificationType::ThankPartnerOncePerYear do let!(:thank_partner_once_per_year) { NotificationType::ThankPartnerOncePerYear.first_or_initialize } context '#check' do it 'does not add a notification for a partner with frequency of semi-annual or rarer' do account_list = create(:account_list) contact = create(:contact, account_list: account_list, pledge_frequency: 6.0) create(:task, activity_type: 'Thank', contacts: [contact], account_list: contact.account_list, start_at: 2.years.ago) notifications = thank_partner_once_per_year.check(contact.account_list) expect(notifications.length).to eq(0) end it 'does not add a notification for a partner with frequency of semi-annual or rarer' do account_list = create(:account_list) contact = create(:contact, account_list: account_list, pledge_frequency: 6.0) create(:task, activity_type: 'Thank', contacts: [contact], account_list: contact.account_list, completed_at: 2.years.ago) notifications = thank_partner_once_per_year.check(contact.account_list) expect(notifications.length).to eq(0) end end end
chuckmersereau/api_practice
spec/factories/help_requests.rb
<gh_stars>0 FactoryBot.define do factory :help_request do name 'MyString' browser 'MyText' problem 'MyText' email '<EMAIL>' user_id 1 account_list_id 1 session 'MyText' user_preferences 'MyText' account_list_settings 'MyText' request_type 'Problem' factory :help_request_with_attachment do file Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/fixtures/sample_csv_blank.csv'))) end end end
chuckmersereau/api_practice
spec/lib/batch_request_handler/instruments/request_limiter_spec.rb
require 'spec_helper' describe BatchRequestHandler::Instruments::RequestLimiter do let(:params) { {} } # see documentation on Instrument initialize arguments subject { described_class.new(params) } let(:not_too_many_requests) do 1.upto(100).map do |num| { method: 'GET', path: "/url/for/request/#{num}" } end end let(:too_many_requests) do 1.upto(101).map do |num| { method: 'GET', path: "/url/for/request/#{num}" } end end describe '#around_perform_requests' do context 'with 100 or less requests' do it 'accepts the batch request of requests' do expect do |block| subject.around_perform_requests(not_too_many_requests, &block) end.to yield_with_args(not_too_many_requests) end end context 'with more than 100 requests' do it 'rejects the batch request of requests' do expect do |block| subject.around_perform_requests(too_many_requests, &block) end.not_to yield_control end end end describe '#around_build_response' do let(:json_responses) { double('json_responses') } context 'when the request had not too many requests' do it 'yields the json_responses' do expect do |block| subject.around_build_response(json_responses, &block) end.to yield_with_args(json_responses) end end context 'when the request had too many requests' do before do subject.around_perform_requests(too_many_requests) { |requests| requests } end it 'does not yield the json_responses' do expect do |block| subject.around_build_response(json_responses, &block) end.not_to yield_control end it 'returns an error' do response = subject.around_build_response(json_responses) do |responses| responses end status, headers, body = response expect(status).to eq 429 expect(headers).to eq('Content-Type' => 'application/json') expect(body).to eq( [ { errors: [ { status: 429, title: 'Too Many Requests', detail: 'You only able to send up to 100 requests in a batch request' } ] }.to_json ] ) end end end end
chuckmersereau/api_practice
spec/factories/donation_amount_recommendations.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 FactoryBot.define do factory :donation_amount_recommendation do suggested_pledge_amount 25 suggested_special_amount 50 ask_at { Time.zone.now + 5.days } after(:build) do |record| record.build_designation_account(attributes_for(:designation_account)) unless record.designation_account record.build_donor_account(attributes_for(:donor_account)) unless record.donor_account end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/tools/analytics_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Tools Analytics' do include_context :json_headers documentation_scope = :tools_api_analytics let(:resource_type) { 'tools_analytics' } let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let(:resource_attributes) do %w( counts_by_type created_at updated_at updated_in_db_at ) end let(:counts_by_type) { json_response['data']['attributes']['counts_by_type'] } context 'authorized user' do before { api_login(user) } # show get '/api/v2/tools/analytics' do parameter 'filter[account_list_id]', 'Filter by Account List Id', type: 'String' with_options scope: [:data, :attributes] do response_field 'counts_by_type', 'Gives the number of contacts, addresses, '\ 'phone numbers and email addresses that '\ 'need to be fixed by the user. It also gives '\ 'a count of the number of duplicated contacts '\ 'and people associated to him/her.', type: 'Object' response_field 'created_at', 'Time when analytics were observed', type: 'String' response_field 'updated_at', 'Time when analytics were observed', type: 'String' end example 'Analytics [GET]', document: documentation_scope do explanation 'Analytics with information allowing the user to decide if he should use any of the tools.' do_request expect(response_status).to eq 200 check_resource expect(counts_by_type.first['id']).to be_present expect(counts_by_type.first['counts'].first).to be_a Hash end end end end
chuckmersereau/api_practice
app/services/account_list/merge.rb
class AccountList::Merge def initialize(winner, loser) @winner = winner @loser = loser end def merge AccountList.transaction { merge_fields_and_associations } end private def merge_fields_and_associations # Intentionally don't copy over notification_preferences since they may conflict between accounts [:activities, :appeals, :company_partnerships, :contacts, :designation_profiles, :google_integrations, :help_requests, :imports, :messages].each do |has_many| @loser.send(has_many).update_all(account_list_id: @winner.id) end [:mail_chimp_account, :prayer_letters_account].each do |has_one| next unless @winner.send(has_one).nil? && @loser.send(has_one).present? @loser.send(has_one).update(account_list_id: @winner.id) end [:designation_accounts, :companies].each do |copy_if_missing| @loser.send(copy_if_missing).each do |item| @winner.send(copy_if_missing) << item unless @winner.send(copy_if_missing).include?(item) end end @loser.users.each do |user| next if @winner.users.include?(user) @winner.users << user user.update(preferences: nil) end @loser.reload @loser.unsafe_destroy @winner.save(validate: false) deactivate_dup_designations end def deactivate_dup_designations designations = @winner.designation_accounts.reload return unless DesignationAccount::DupByBalanceFix.deactivate_dups(designations) # If a dup designation account is found and deactivated, re-run the donor # import to fix balances for the designation profiles so that the users # won't see incorrect balances for long. @winner.async(:import_data) end end
chuckmersereau/api_practice
app/services/reports/pledge_histories.rb
<filename>app/services/reports/pledge_histories.rb class Reports::PledgeHistories < Reports::Base protected def default_range '13m' end def generate_report_for_period(start_date:, end_date:) Reports::PledgeHistoriesPeriod.new(account_list: account_list, start_date: start_date, end_date: end_date) end end
chuckmersereau/api_practice
app/validators/credential_validator.rb
<gh_stars>0 class CredentialValidator < ActiveModel::Validator def validate(record) # we don't want this error to show up if there is already an error return if record.errors[:organization_id].present? || record.errors[:person_id].present? return if valid_credentials?(record) record.errors[:base] << format(_('Your credentials for %{org} are invalid.'), org: record.organization) end private def valid_credentials?(record) return false unless record.username.present? && record.password.present? || record.token.present? return record.organization.api(record).validate_credentials rescue Person::OrganizationAccount::InvalidCredentialsError return false rescue DataServerError => e return false if e.message.include?('user') raise end end
chuckmersereau/api_practice
config/initializers/regex_constants.rb
<reponame>chuckmersereau/api_practice UUID_REGEX = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i unless defined? UUID_REGEX
chuckmersereau/api_practice
db/migrate/20150423195307_add_webhook_token_to_mail_chimp_account.rb
class AddWebhookTokenToMailChimpAccount < ActiveRecord::Migration def change add_column :mail_chimp_accounts, :webhook_token, :string end end
chuckmersereau/api_practice
app/policies/designation_account_policy.rb
<filename>app/policies/designation_account_policy.rb class DesignationAccountPolicy < AccountListChildrenPolicy end
chuckmersereau/api_practice
app/workers/user_adobe_campaign_subscriber_worker.rb
class UserAdobeCampaignSubscriberWorker include Sidekiq::Worker sidekiq_options queue: :api_user_adobe_campaign_subscriber sidekiq_retries_exhausted do |message, error| ::Rollbar.error(error.class.new(error.message), message) end def perform(user_id) User.subscribe_to_adobe_campaign(user_id) rescue ::JSON::ParserError, ::RestClient::ServiceUnavailable, ::RestClient::BadGateway, ::RestClient::GatewayTimeout => error ::Rollbar.silenced { raise error } end end
chuckmersereau/api_practice
spec/factories/mail_chimp_members.rb
FactoryBot.define do factory :mail_chimp_member do association :mail_chimp_account contact_locale 'en' email '<EMAIL>' first_name 'John' greeting 'John' last_name 'Smith' list_id 'list1' status 'Partner - Financial' end end
chuckmersereau/api_practice
app/services/contact/filter/base.rb
<gh_stars>0 class Contact::Filter::Base < ApplicationFilter protected def contact_ids_with_phone(contacts, location) contacts .where.not(phone_numbers: { number: nil }) .where(phone_numbers: { historic: false, location: location }) .joins(people: :phone_numbers) .pluck(:id) end def contact_instance @@contact_instance ||= Contact.new end private def designation_account_ids account_lists.map(&:designation_account_ids).flatten end def date_range?(param) # we are expecting the param to be range of dates, if it is a range and in the correct direction, # `min` will return the first value, otherwise `min` will be nil param.is_a?(Range) && param.first.is_a?(Date) && param.min end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/addresses_spec.rb
<filename>spec/acceptance/api/v2/contacts/addresses_spec.rb require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > Addresses' do include_context :json_headers doc_helper = DocumentationHelper.new(resource: [:contacts, :addresses]) let!(:user) { create(:user_with_full_account) } let(:resource_type) { 'addresses' } let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) } let(:contact_id) { contact.id } let!(:address) { create(:address, addressable: contact) } let(:id) { address.id } let(:new_address) do attributes_for(:address, addressable: contact) .reject { |key| key.to_s.end_with?('_id', '_at') } .merge(updated_in_db_at: address.updated_at) end let(:form_data) { build_data(new_address) } let(:resource_attributes) do %w( city country created_at end_date geo historic location metro_area postal_code primary_mailing_address region remote_id seasonal source start_date state street updated_at updated_in_db_at valid_values ) end let(:resource_associations) do %w( source_donor_account ) end context 'authorized user' do before { api_login(user) } get '/api/v2/contacts/:contact_id/addresses' do doc_helper.insert_documentation_for(action: :index, context: self) example doc_helper.title_for(:index), document: doc_helper.document_scope do explanation doc_helper.description_for(:index) do_request expect(response_status).to eq(200), invalid_status_detail check_collection_resource 1, %w(relationships) end end get '/api/v2/contacts/:contact_id/addresses/:id' do doc_helper.insert_documentation_for(action: :show, context: self) example doc_helper.title_for(:show), document: doc_helper.document_scope do explanation doc_helper.description_for(:show) do_request expect(response_status).to eq(200), invalid_status_detail check_resource %w(relationships) end end post '/api/v2/contacts/:contact_id/addresses' do doc_helper.insert_documentation_for(action: :create, context: self) example doc_helper.title_for(:create), document: doc_helper.document_scope do explanation doc_helper.description_for(:create) do_request data: form_data expect(response_status).to eq(201), invalid_status_detail expect(resource_object['street']).to(be_present) && eq(new_address['street']) end end put '/api/v2/contacts/:contact_id/addresses/:id' do doc_helper.insert_documentation_for(action: :update, context: self) example doc_helper.title_for(:update), document: doc_helper.document_scope do explanation doc_helper.description_for(:update) do_request data: form_data expect(response_status).to eq(200), invalid_status_detail expect(resource_object['street']).to(be_present) && eq(new_address['street']) end end delete '/api/v2/contacts/:contact_id/addresses/:id' do doc_helper.insert_documentation_for(action: :delete, context: self) example doc_helper.title_for(:delete), document: doc_helper.document_scope do explanation doc_helper.description_for(:delete) do_request expect(response_status).to eq(204) end end end end
chuckmersereau/api_practice
app/validators/tag_validator.rb
class TagValidator def validate(tag_name) errors = {} errors[:name] = ["can't be blank"] if tag_name.blank? return false if errors.empty? errors end end
chuckmersereau/api_practice
app/services/web_router.rb
# Handles routes to the frontend web client. These routes are typically used in mailers. class WebRouter def self.env Rails.env end def self.protocol env == 'development' ? 'http' : 'https' end def self.host case env when 'development' 'localhost:8080' when 'staging' 'stage.mpdx.org' else 'mpdx.org' end end def self.base_url "#{protocol}://#{host}" end def self.account_list_invite_url(invite) "#{base_url}/account_lists/#{invite.account_list.id}/accept_invite/#{invite.id}?code=#{invite.code}" end def self.integration_preferences_url(integration_name) "#{base_url}/preferences/integrations?selectedTab=#{integration_name}" end def self.notifications_preferences_url "#{base_url}/preferences/notifications" end def self.contact_url(contact, tab = nil) "#{base_url}/contacts/#{contact.id}#{"/#{tab}" if tab}" end def self.tasks_url "#{base_url}/tasks" end def self.person_url(person, contact = nil) contact ||= person.contact "#{base_url}/contacts/#{contact.id}?personId=#{person.id}" end def self.logout_url "#{base_url}/logout" end end
chuckmersereau/api_practice
app/preloaders/api/v2/contacts_preloader.rb
<reponame>chuckmersereau/api_practice class Api::V2::ContactsPreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = { account_list: Api::V2::AccountListsPreloader, appeals: Api::V2::AppealsPreloader, contact_referrals_by_me: self, contact_referrals_to_me: self, contacts_referred_by_me: self, contacts_that_referred_me: self, donor_accounts: Api::V2::AccountLists::DonorAccountsPreloader }.freeze FIELD_ASSOCIATION_MAPPING = { avatar: { primary_person: [:primary_picture, :facebook_account, primary_email_address: :google_plus_account] }, tag_list: :tags }.freeze end