repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
chuckmersereau/api_practice
app/services/csv_export.rb
class CsvExport def self.mailing_addresses(contacts) render({ 'Contact Name' => :name, 'Greeting' => :greeting, 'Envelope Greeting' => :envelope_greeting, 'Mailing Street Address' => :csv_street, 'Mailing City' => :city, 'Mailing State' => :state, 'Mailing Postal Code' => :postal_code, 'Mailing Country' => :csv_country, 'Address Block' => :address_block }, contacts) end def self.render(field_mapping, contacts) CSV.generate do |csv| csv << field_mapping.keys contacts.each do |contact| csv << field_mapping.values.map { |method| ContactExhibit.new(contact, nil).send(method) } end end end end
chuckmersereau/api_practice
app/models/designation_profile.rb
<reponame>chuckmersereau/api_practice<filename>app/models/designation_profile.rb class DesignationProfile < ApplicationRecord belongs_to :user belongs_to :organization has_many :designation_profile_accounts, dependent: :delete_all has_many :designation_accounts, through: :designation_profile_accounts has_many :balances, dependent: :delete_all, as: :resource belongs_to :account_list after_save :create_balance, if: :balance_changed? scope :for_org, -> (org_id) { where(organization_id: org_id) } audited associated_with: :account_list, except: [:updated_at, :balance, :balance_updated_at] def to_s name end def designation_account designation_accounts.first end def merge(other) DesignationProfile.transaction do other.designation_profile_accounts.each do |da| already_exists = designation_profile_accounts.find { |dpa| dpa.designation_account_id == da.designation_account_id } designation_profile_accounts << da unless already_exists end other.reload other.destroy save(validate: false) end end protected def create_balance balances.create(balance: balance) if balance end end
chuckmersereau/api_practice
spec/factories/designation_accounts.rb
<reponame>chuckmersereau/api_practice FactoryBot.define do factory :designation_account do sequence(:designation_number, 1) { |n| n&.to_s } association :organization balance 9.99 name '<NAME>' created_at Date.new updated_at Date.new end factory :designation_account_with_donor, parent: :designation_account do after(:create) do |designation_account, _evaluator| list = create(:account_list) create(:account_list_entry, account_list: list, designation_account: designation_account) contact = create(:contact, account_list: list) donor_account = create(:donor_account) create(:contact_donor_account, contact: contact, donor_account: donor_account) end end factory :designation_account_with_special_donor, parent: :designation_account do after(:create) do |designation_account, _evaluator| list = create(:account_list) create(:account_list_entry, account_list: list, designation_account: designation_account) contact = create(:contact, account_list: list, status: 'Partner - Special', pledge_frequency: nil, pledge_amount: nil) donor_account = create(:donor_account) create(:contact_donor_account, contact: contact, donor_account: donor_account) end end end
chuckmersereau/api_practice
spec/models/prayer_letters_account_spec.rb
require 'rails_helper' describe PrayerLettersAccount do let(:pla) { create(:prayer_letters_account) } let(:contact) { create(:contact, name: '<NAME>', account_list: pla.account_list, send_newsletter: 'Both') } let(:params) do { name: '<NAME>', greeting: '', file_as: '<NAME>', external_id: contact.id, company: '', street: '123 Somewhere St', city: 'Fremont', state: 'CA', postal_code: '94539', country: '' } end before do contact.addresses << create(:address, primary_mailing_address: true) end context '#get_response' do it 'marks token as invalid if response is a 401 for OAuth2' do stub_request(:get, %r{https:\/\/www\.prayerletters\.com\/*}).to_return(status: 401) pla = create(:prayer_letters_account_oauth2) expect(pla).to receive(:handle_bad_token).and_return('{}') pla.contacts end it 'marks token as invalid if response is a 403 for OAuth2' do stub_request(:get, %r{https:\/\/www\.prayerletters\.com\/*}).to_return(status: 403) pla = create(:prayer_letters_account_oauth2) expect(pla).to receive(:handle_bad_token).and_return('{}') pla.contacts end it 'uses OAuth2 if possible' do stub_request(:get, 'https://www.prayerletters.com/api/v1/contacts') .with(headers: { 'Authorization' => 'Bearer test_oauth2_token' }) .to_return(body: '{}') pla_oauth2 = create(:prayer_letters_account_oauth2) pla_oauth2.contacts end it 'uses OAuth1 if no oauth2_token present' do stub_request(:get, 'https://www.prayerletters.com/api/v1/contacts') .to_return(body: '{}') pla_oauth1 = create(:prayer_letters_account) pla_oauth1.contacts end end context '#handle_bad_token' do it 'sends an email to the account users' do expect_delayed_email(AccountMailer, :prayer_letters_invalid_token) expect do pla.handle_bad_token end.to raise_exception(PrayerLettersAccount::AccessError) end it 'sets valid_token to false' do allow(AccountMailer).to receive(:prayer_letters_invalid_token).and_return(double(deliver: true)) expect do pla.handle_bad_token end.to raise_exception(PrayerLettersAccount::AccessError) expect(pla.valid_token).to be false end end context '#update_contact' do before do contact.addresses << create(:address, primary_mailing_address: true) contact.update(prayer_letters_id: 'c1', send_newsletter: 'Both', prayer_letters_params: nil) end it 'calls the prayer letters api to create a contact and sets cached params value' do stub = stub_request(:post, 'https://www.prayerletters.com/api/v1/contacts/c1') .with(body: params, headers: { 'Authorization' => 'Bearer MyString' }).to_return(status: 204) pla.update_contact(contact) expect(contact.prayer_letters_id).to eq('c1') expect(contact.prayer_letters_params).to eq(params) expect(stub).to have_been_requested end it 'does not call the api if the contact params are the same as the cached value' do contact.update(prayer_letters_params: params) expect(pla).to_not receive(:get_response) pla.update_contact(contact) end def stub_update_error(code) stub = stub_request(:post, 'https://www.prayerletters.com/api/v1/contacts/c1').to_return(status: code) yield expect(stub).to have_been_requested end it 're-subscribes the contact list on 404' do stub_update_error(404) do expect(pla).to receive(:queue_subscribe_contacts) pla.update_contact(contact) end end it 're-subscribes the contact list on 410' do stub_update_error(410) do expect(contact.reload.prayer_letters_params).to eq({}) expect(pla).to receive(:queue_subscribe_contacts) pla.update_contact(contact) end end end context '#create_contact' do it 'calls the prayer letters api to create a contact and sets cached params value' do contact.addresses << create(:address) stub = stub_request(:post, 'https://www.prayerletters.com/api/v1/contacts') .with(body: params, headers: { 'Authorization' => 'Bearer MyString' }) .to_return(body: '{"contact_id": "c1"}') pla.create_contact(Contact.find(contact.id)) contact.reload expect(contact.prayer_letters_id).to eq('c1') expect(contact.prayer_letters_params).to eq(params) contact.reload_mailing_address expect(pla.contact_params(contact)).to eq(params) expect(stub).to have_been_requested end it 'does not raise an error on a 400 bad request code but logs it via Rollbar' do missing_name_body = <<-EOS { "status": 400, "error": "contacts.missing_name", "message": "A contact must have a name or company." } EOS stub_request(:post, 'https://www.prayerletters.com/api/v1/contacts').to_return(body: missing_name_body, status: 400) expect(Rollbar).to receive(:raise_or_notify) pla.create_contact(contact) end end context '#subscribe_contacts' do it 'syncronizes a contact even if it has no people' do contact.update(prayer_letters_id: 1) contact.addresses << create(:address) expect(contact.people.count).to eq(0) contacts_body = '{"contacts":[{"name":"<NAME>","greeting":"","file_as":"<NAME>",'\ '"external_id":"' + contact.id + '","company":"","contact_id":"1",'\ '"address":{"street":"123 Somewhere St","city":"Fremont","state":"CA","postal_code":"94539",'\ '"country":""}}]}' stub = stub_request(:put, 'https://www.prayerletters.com/api/v1/contacts') .with(body: contacts_body, headers: { 'Authorization' => 'Bearer MyString' }) expect(pla).to receive(:import_list).with(contact.id => params) pla.subscribe_contacts expect(stub).to have_been_requested end it 'clears the prayer letters params for removed contacts so they can be re-added later' do stub_request(:put, 'https://www.prayerletters.com/api/v1/contacts') .with(headers: { 'Authorization' => 'Bearer MyString' }) expect(pla).to receive(:import_list) contact.update_columns(send_newsletter: false, prayer_letters_params: { old: 'old values' }) pla.subscribe_contacts contact.reload expect(contact.prayer_letters_params).to be_blank expect(contact.prayer_letters_id).to be_nil end end context '#import_list' do it 'retrieves the prayer letters list and updates contacts with prayer_letters_id' do contact.addresses << create(:address, street: '123 Somewhere St', city: 'Fremont', state: 'CA', postal_code: '94539', country: 'United States') contacts_body = '{"contacts":[{"name":"<NAME>","greeting":"","file_as":"<NAME>","contact_id":"c1",'\ '"address":{"street":"123 Somewhere St","city":"Fremont","state":"CA","postal_code":"94539",'\ '"country":""},"external_id":"' + contact.id + '"}]}' stub = stub_request(:get, 'https://www.prayerletters.com/api/v1/contacts') .with(headers: { 'Authorization' => 'Bearer MyString' }).to_return(body: contacts_body) pla.import_list(contact.id => params) contact.reload expect(contact.prayer_letters_id).to eq('c1') expect(contact.reload.prayer_letters_params).to eq(params) expect(stub).to have_been_requested end end context '#delete_contact' do it 'calls the prayer letters api to delete and sets prayer letters info to blanks' do contact.update_columns(prayer_letters_id: 'c1', prayer_letters_params: params) stub = stub_request(:delete, 'https://www.prayerletters.com/api/v1/contacts/c1') .with(headers: { 'Authorization' => 'Bearer MyString' }) pla.delete_contact(contact) expect(stub).to have_been_requested contact.reload expect(contact.prayer_letters_id).to be_nil expect(contact.prayer_letters_params).to be_blank end end context '#delete_all_contacts' do it 'calls the prayer letters api to delete all and sets prayer letters info to blanks' do contact.update(prayer_letters_id: 'c1', prayer_letters_params: params) stub = stub_request(:delete, 'https://www.prayerletters.com/api/v1/contacts') .with(headers: { 'Authorization' => 'Bearer MyString' }) pla.delete_all_contacts expect(stub).to have_been_requested contact.reload expect(contact.prayer_letters_id).to be_nil expect(contact.prayer_letters_params).to be_blank end end context '#contact_params' do it 'specifies a blank name but non-blank company if the contact is a siebel org' do expect(contact).to receive(:siebel_organization?).at_least(:once).and_return(true) params = pla.contact_params(contact) expect(params.keys).to include(:name) expect(params[:name]).to be_blank end end end
chuckmersereau/api_practice
lib/json_api_service/null_data_object.rb
<gh_stars>0 module JsonApiService class NullDataObject def validate_against_store; end end end
chuckmersereau/api_practice
db/migrate/20120314141926_add_address_fields_to_company.rb
class AddAddressFieldsToCompany < ActiveRecord::Migration def change add_column :companies, :street, :text add_column :companies, :city, :string add_column :companies, :state, :string add_column :companies, :postal_code, :string add_column :companies, :country, :string add_column :companies, :phone_number, :string change_column :addresses, :street, :text end end
chuckmersereau/api_practice
dev/migrate/2016_05_18_set_contact_locales.rb
def default_contact_locales_from_orgs sql = ' WITH contact_locales AS ( SELECT contacts.id as contact_row_id, organizations.locale as org_locale FROM contacts INNER JOIN contact_donor_accounts cda on cda.contact_id = contacts.id INNER JOIN donor_accounts on cda.donor_account_id = donor_accounts.id INNER JOIN organizations on organizations.id = donor_accounts.organization_id ) UPDATE contacts SET locale = contact_locales.org_locale FROM contact_locales WHERE contacts.id = contact_locales.contact_row_id AND contacts.locale is null' Contact.connection.execute(sql) end
chuckmersereau/api_practice
spec/workers/duplicate_tasks_per_contact_spec.rb
require 'rails_helper' RSpec.describe DuplicateTasksPerContact do subject { described_class.new.perform(filter_account_list, min_contacts) } let(:filter_account_list) { nil } let(:min_contacts) { 2 } let!(:task) { create(:task) } let!(:contact_one) { create(:contact, tasks: [task]) } let!(:contact_two) { create(:contact, tasks: [task]) } # These fog_ variables are just to mock out the AWS S3 service let(:fog_storage) do Fog.mock! Fog::Storage.new(provider: 'AWS', aws_access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'), aws_secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY')) end let(:fog_dirs) { fog_storage.directories } let(:fog_dir) do fog_dirs.create(key: ENV.fetch('AWS_BUCKET')) end let!(:fog_file) do double('fog_file').tap do |file| expect(file).to receive(:save) end end let!(:fog_files) do double('fog_files').tap do |files| expect(files).to receive(:new) do |args| expect(args.keys).to include :key, :body fog_file end end end before do expect(Fog::Storage).to receive(:new).with(Hash).and_return(fog_storage) expect(fog_storage).to receive(:directories).and_return(fog_dirs) expect(fog_dirs).to receive(:get).with(String).and_return(fog_dir) expect(fog_dir).to receive(:files).and_return(fog_files) task.reload end it 'creates a duplicate task' do expect { subject }.to change { Task.count }.from(1).to(2) end it 'ensures all Tasks have unique ids' do subject expect(Task.all.pluck(:id).uniq.size).to eq Task.count end it 'results in all Tasks having exactly one Contact' do subject expect(Task.all.reject { |t| t.contacts.size == 1 }).to be_empty end it 'resuses the existing Task for the first Contact' do subject contact_one.reload contact_two.reload expect(contact_one.tasks.order(:created_at).first).to eq task expect(contact_two.tasks.order(:created_at).first).not_to eq task end it 'logs the created Task IDs to S3' do # we will replace the default expectation for :new RSpec::Mocks.space.proxy_for(fog_files).reset expect(fog_files).to receive(:new) do |args| expect(args[:key]).to match(%r{^worker_results/duplicate_tasks_per_contact__.+\.log$}) expect(args[:body]).to match(%r{workers/duplicate_tasks_per_contact\.rb}) expect(args[:body]).to match(/^#{task.id}(?:\s[^\s]+)+$/) expect(args[:body].lines[2].split(/\s/).size).to eq Task.count fog_file end subject end context 'with comments' do let(:comments) { ['comment one', 'comment two'] } before do comments.each { |text| task.comments.create!(body: text) } end it 'duplicates each comment' do expect { subject }.to change { ActivityComment.count }.from(2).to(4) comments.each do |text| expect(ActivityComment.where(body: text).count).to eq 2 end end it 'ensures each Task has unique comments' do subject new_task = Task.order(:created_at).last expect((task.comments.pluck(:id) - new_task.comments.pluck(:id)).size).to eq 2 end end context 'filter by account_list with no tasks' do let(:account_with_no_tasks) { create(:account_list) } let(:filter_account_list) { account_with_no_tasks } it 'creates no duplicate tasks' do expect { subject }.not_to change { Task.count } end it 'logs the created Task IDs to S3' do # we will replace the default expectation for :new RSpec::Mocks.space.proxy_for(fog_files).reset expect(fog_files).to receive(:new) do |args| expect(args[:key]).to match(/duplicate_tasks_per_contact__.+\.log/) expect(args[:body]).to match(%r{workers/duplicate_tasks_per_contact\.rb}) expect(args[:body]).to match(/^$/) fog_file end subject end end context 'filter by another account_list with separate tasks' do let(:another_task) { create(:task) } let!(:another_contact_one) { create(:contact, tasks: [another_task]) } let!(:another_contact_two) { create(:contact, tasks: [another_task]) } let(:filter_account_list) { another_task.account_list } before { another_task.reload } it 'creates only one duplicate task' do expect { subject }.to change { Task.count }.from(2).to(3) end it 'ensures all Tasks have unique ids' do subject expect(Task.all.pluck(:id).uniq.size).to eq Task.count end it 'results in all Tasks having exactly one Contact' do subject expect(Task.all.reject { |t| t.contacts.size == 1 }.size).to eq 1 expect(Task.all.reject { |t| t.contacts.size == 1 }.first).to eq task end it 'logs the created Task IDs to S3' do # we will replace the default expectation for :new RSpec::Mocks.space.proxy_for(fog_files).reset expect(fog_files).to receive(:new) do |args| expect(args[:key]).to match( %r{^worker_results/account-list-#{another_task.account_list_id}/duplicate_tasks_per_contact__.+\.log$} ) expect(args[:body]).to match(%r{workers/duplicate_tasks_per_contact\.rb}) expect(args[:body]).to match(/^#{another_task.id}(?:\s[^\s]+)+$/) expect(args[:body].lines[2].split(/\s/).size).to eq(Task.count - 1) fog_file end subject end end end
chuckmersereau/api_practice
spec/serializers/background_batch_serializer_spec.rb
require 'rails_helper' RSpec.describe BackgroundBatchSerializer, type: :serializer do let(:background_batch) { create(:background_batch) } subject { described_class.new(background_batch) } describe '#total' do it 'should return total number of requests' do # background_batch factory already creates request background_batch.requests.create(path: 'api/v2/user') background_batch.requests.create(path: 'api/v2/user') expect(subject.total).to eq 3 end end describe '#pending' do it 'should return total number of pending requests' do # background_batch factory already creates request background_batch.requests.create(path: 'api/v2/user', status: 'complete') background_batch.requests.create(path: 'api/v2/user') expect(subject.pending).to eq 2 end end end
chuckmersereau/api_practice
spec/controllers/api/v2/account_lists/notification_preferences_controller_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe Api::V2::AccountLists::NotificationPreferencesController, type: :controller do let(:factory_type) { :notification_preference } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let(:notification_type) { create(:notification_type) } let(:notification_type_1) { create(:notification_type) } let(:notification_type_2) { create(:notification_type) } let!(:notification_preferences) do [ create(:notification_preference, account_list_id: account_list.id, email: true, task: true, notification_type_id: notification_type.id, user_id: user.id), create(:notification_preference, account_list_id: account_list.id, email: true, task: true, notification_type_id: notification_type_1.id, user_id: user.id, created_at: 1.week.from_now) ] end let(:correct_attributes) do { email: true, task: true } end let(:correct_relationships) do { account_list: { data: { type: 'account_lists', id: account_list.id } }, notification_type: { data: { type: 'notification_types', id: notification_type_2.id } } } end let(:resource) { notification_preferences.first } let(:second_resource) { notification_preferences.second } let!(:given_reference_key) { :task } let(:id) { resource.id } let(:parent_param) { { account_list_id: account_list.id } } let(:unpermitted_attributes) { nil } let(:incorrect_attributes) { nil } # These includes can be found in: # spec/support/shared_controller_examples/* include_examples 'index_examples', except: [:sorting] include_examples 'show_examples' include_examples 'create_examples', count: 2 include_examples 'destroy_examples' end
chuckmersereau/api_practice
spec/services/tools/analytics_spec.rb
require 'rails_helper' RSpec.describe Tools::Analytics do let!(:account_list) { create(:account_list) } let!(:contact_one) { create(:contact, account_list: account_list, status_valid: false, send_newsletter: 'None') } let!(:contact_two) { create(:contact, account_list: account_list, send_newsletter: nil, status: 'Partner - Pray') } let!(:contact_three) { create(:contact, account_list: account_list, send_newsletter: 'Physical') } let!(:address) { create(:address, addressable: contact_one) } let!(:second_address) { create(:address, addressable: contact_one, source: 'Random Source') } let!(:person) { create(:person, contacts: [contact_two]) } let!(:email_address) { create(:email_address, person: person) } let!(:second_email_address) { create(:email_address, person: person, source: 'Random Source') } let!(:phone_number) { create(:phone_number, person: person) } let!(:second_phone_number) { create(:phone_number, person: person, source: 'Random Source') } # Inactive contacts should be excluded. let!(:contact_inactive) { create(:contact, account_list: account_list, status_valid: false, status: Contact::INACTIVE_STATUSES.first) } let!(:address_inactive) { create(:address, addressable: contact_inactive, source: 'Random Source', valid_values: false) } subject { described_class.new(account_lists: [account_list]) } describe '#counts_by_type' do let(:counts_by_type) { subject.counts_by_type } let(:first_counts_array) { counts_by_type.first[:counts] } let(:contact_duplicates) { double } let(:people_duplicates) { double } before do allow_any_instance_of(Contact::DuplicatePairsFinder).to receive(:find_and_save) dup_contact_pairs_double = double allow(dup_contact_pairs_double).to receive_message_chain(:where, :count).and_return(3) allow(DuplicateRecordPair).to receive(:type).with('Contact').and_return(dup_contact_pairs_double) allow_any_instance_of(Person::DuplicatePairsFinder).to receive(:find_and_save) dup_person_pairs_double = double allow(dup_person_pairs_double).to receive_message_chain(:where, :count).and_return(2) allow(DuplicateRecordPair).to receive(:type).with('Person').and_return(dup_person_pairs_double) end it 'returns the account_list id for each account_list' do expect(counts_by_type.first[:id]).to eq(account_list.id) end it 'returns the list of counts by type for each account list' do expect_type_and_count(first_counts_array[0], 'fix-commitment-info', 1) expect_type_and_count(first_counts_array[1], 'fix-phone-numbers', 1) expect_type_and_count(first_counts_array[2], 'fix-email-addresses', 1) expect_type_and_count(first_counts_array[3], 'fix-addresses', 1) expect_type_and_count(first_counts_array[4], 'fix-send-newsletter', 1) expect_type_and_count(first_counts_array[5], 'duplicate-contacts', 3) expect_type_and_count(first_counts_array[6], 'duplicate-people', 2) end it 'does not count hidden people' do contact_one.hide contact_two.hide expect_type_and_count(first_counts_array[1], 'fix-phone-numbers', 0) expect_type_and_count(first_counts_array[3], 'fix-addresses', 0) end it 'does count contacts with nil status' do contact_one.update!(status: nil) contact_two.update!(status: nil) expect_type_and_count(first_counts_array[1], 'fix-phone-numbers', 1) expect_type_and_count(first_counts_array[3], 'fix-addresses', 1) end def expect_type_and_count(count_object, type, count) expect(count_object[:type]).to eq(type) expect(count_object[:count]).to eq(count) end end end
chuckmersereau/api_practice
engines/auth/app/controllers/auth/provider/donorhub_accounts_controller.rb
<filename>engines/auth/app/controllers/auth/provider/donorhub_accounts_controller.rb module Auth module Provider class DonorhubAccountsController < BaseController protected def find_or_create_account @donorhub_account ||= Person::OrganizationAccount.find_or_create_from_auth( auth_hash['credentials']['token'], params[:oauth_url], current_user ) end end end end
chuckmersereau/api_practice
lib/tasks/name_male_ratios.rake
require 'csv' # Load the db/name_male_ratios_usa_1960_to_2013.csv file which was compiled from data at: # http://www.ssa.gov/oact/babynames/limits.html namespace :name_male_ratios do task load: :environment do CSV.new(File.new('db/name_male_ratios_usa_1960_to_2013.csv').read).each do |line| begin NameMaleRatio.create(name: line[0], male_ratio: line[1].to_f) rescue ActiveRecord::RecordNotUnique # Do nothing if the name male ratio already exists end end end end
chuckmersereau/api_practice
app/preloaders/api/v2/contacts/people/phone_numbers_preloader.rb
class Api::V2::Contacts::People::PhoneNumbersPreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = {}.freeze FIELD_ASSOCIATION_MAPPING = {}.freeze end
chuckmersereau/api_practice
app/models/notification_preference.rb
<reponame>chuckmersereau/api_practice class NotificationPreference < ApplicationRecord audited associated_with: :account_list belongs_to :account_list belongs_to :notification_type belongs_to :user validates :account_list, :notification_type, presence: true delegate :type, to: :notification_type before_save :update_other_notification_preferences, if: :user PERMITTED_ATTRIBUTES = [ :email, :task, :created_at, :id, :notification_type_id, :overwrite, :updated_at, :updated_in_db_at, :id ].freeze protected def update_other_notification_preferences create_notification_preference_without_user account_list.notification_preferences .where(notification_type_id: notification_type_id) .where('id != ?', id) .update_all(task: task) end def create_notification_preference_without_user account_list.notification_preferences .create_with( email: false, task: task ) .find_or_create_by( notification_type_id: notification_type_id, user_id: nil ) end end
chuckmersereau/api_practice
spec/models/company_position_spec.rb
<filename>spec/models/company_position_spec.rb require 'rails_helper' describe CompanyPosition do it 'should return the position name for to_s' do expect(CompanyPosition.new(position: 'foo').to_s).to eq('foo') end end
chuckmersereau/api_practice
spec/services/data_server_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe DataServer do let(:account_list) { create(:account_list) } let!(:organization) { create(:organization, name: 'MyString') } let!(:person) { create(:person) } let!(:organization_account) { build(:organization_account, person: person, organization: organization) } let!(:data_server) { described_class.new(organization_account) } let(:profile) do create(:designation_profile, organization: organization, user: person.to_user, account_list: account_list) end let(:raw_data1) do '"PEOPLE_ID","ACCT_NAME","ADDR1","CITY","STATE","ZIP","PHONE","COUNTRY","FIRST_NAME","MIDDLE_NAME","TITLE",'\ '"SUFFIX","SP_LAST_NAME","SP_FIRST_NAME","SP_MIDDLE_NAME","SP_TITLE","ADDR2","ADDR3","ADDR4","ADDR_CHANGED",'\ '"PHONE_CHANGED","CNTRY_DESCR","PERSON_TYPE","LAST_NAME_ORG","SP_SUFFIX"'\ "\r\n"\ '"17083","Rodriguez, <NAME> (Moreno)","Bahia Acapulco 379","Chihuahua","CHH","24555","(376) 706-670",'\ '"MEX","Ramon","","Sr.","","Moreno","Celeste","Gonzalez","Sra.","","","","4/4/2003","4/4/2003","","P","Rodriguez",'\ '""'\ "\r\n" end it 'should import all' do date_from = '01/01/1951' expect(data_server).to receive(:import_profiles).and_return([profile]) expect(data_server).to receive(:import_donors).with(profile, date_from) expect(data_server).to receive(:import_donations).with(profile, date_from) data_server.import_all(date_from) end it 'should return designation numbers for a profile code' do designation_numbers = ['031231'] expect(data_server).to receive(:profile_balance).and_return(designation_numbers: designation_numbers) expect(data_server.send(:designation_numbers, profile.code)).to eq(designation_numbers) end it 'should return a list of all profiles with their associated designation numbers' do designation_numbers = ['031231'] profiles = [{ name: 'Profile 1', code: 'Profile 1' }, { name: 'Profile 2', code: '' }] allow(data_server).to receive(:designation_numbers).and_return(designation_numbers) allow(data_server).to receive(:profiles).and_return(profiles) expect(data_server.profiles_with_designation_numbers.first[:name]).to eq 'Profile 1' expect(data_server.profiles_with_designation_numbers.first[:designation_numbers]) .to eq(designation_numbers) end context '.import_profiles' do let(:data_server) { described_class.new(organization_account) } it 'in US format' do stub_request(:post, /.*profiles/).to_return( body: 'ROLE_CODE,ROLE_DESCRIPTION'\ "\n"\ ',"Staff Account (0559826)"' ) stub_request(:post, /.*accounts/).to_return( body: '"EMPLID","EFFDT","BALANCE","ACCT_NAME"'\ "\n"\ '"0000000","2012-03-23 16:01:39.0","123.45","Test Account"'\ "\n" ) expect(data_server).to receive(:import_profile_balance) expect do data_server.import_profiles end.to change(DesignationProfile, :count).by(1) end it 'in DataServer format' do stub_request(:post, /.*profiles/).to_return( body: "\xEF\xBB\xBF"\ '"PROFILE_CODE","PROFILE_DESCRIPTION"'\ "\r\n"\ '"1769360689","MPD Coach (All Staff Donations)"'\ "\r\n"\ '"1769360688","My Campus Accounts"'\ "\r\n"\ '"","My Staff Account"'\ "\r\n" ) stub_request(:post, /.*accounts/).to_return( body: '"EMPLID","EFFDT","BALANCE","ACCT_NAME"'\ "\n"\ '"0000000","2012-03-23 16:01:39.0","123.45","Test Account"'\ "\n" ) expect do data_server.import_profiles end.to change(DesignationProfile, :count).by(3) end context 'links from profile correctly if no profile url present' do let(:profile_linker) { double(link_account_list!: nil) } before do organization.designation_profiles << profile organization.update(profiles_url: nil) allow(data_server).to receive(:import_profile_balance) allow(AccountList::FromProfileLinker).to receive(:new) { profile_linker } end it 'and only associates to account_list if missing' do profile.update(account_list_id: nil) profile.reload data_server.import_profiles expect(data_server).to have_received(:import_profile_balance) expect(AccountList::FromProfileLinker).to have_received(:new) .with(profile, organization_account) expect(profile_linker).to have_received(:link_account_list!) end it "doesn't associate to account_list if already present" do data_server.import_profiles expect(data_server).to have_received(:import_profile_balance) expect(AccountList::FromProfileLinker).not_to have_received(:new) .with(profile, organization_account) end end end describe 'import donors' do let(:account_list1) { create(:account_list) } let(:account_list2) { create(:account_list) } it 'should update the addresses_url on the org if the url changed' do stub_request(:post, /.*addresses/).to_return(body: "whatever\nRedirectQueryIni=foo") stub_request(:post, 'http://foo/') expect do data_server.import_donors(profile) end.to change(organization, :addresses_url).to('foo') end it 'removes a profile that a user no longer has access to' do stub_request(:post, /.*addresses/).to_return( body: 'ERROR The user logging in has no profile associated with "1983834942".' ) profile # instantiate record expect do data_server.import_donors(profile) end.to change(DesignationProfile, :count).by(-1) end it 'should import a company' do stub_request(:post, /.*addresses/).to_return( body: '"PEOPLE_ID","ACCT_NAME","ADDR1","CITY","STATE","ZIP","PHONE","COUNTRY","FIRST_NAME","MIDDLE_NAME",'\ '"TITLE","SUFFIX","SP_LAST_NAME","SP_FIRST_NAME","SP_MIDDLE_NAME","SP_TITLE","ADDR2","ADDR3","ADDR4",'\ '"ADDR_CHANGED","PHONE_CHANGED","CNTRY_DESCR","PERSON_TYPE","LAST_NAME_ORG","SP_SUFFIX"'\ "\r\n"\ '"19238","ACorporation","123 mi casa blvd.","Colima","COL","456788","(52) 45 456-5678",'\ '"MEX","","","","","","","","","","","","8/15/2003","8/15/2003","","O","ACorporation",""'\ "\r\n" ) expect(data_server).to receive(:add_or_update_donor_account) expect(data_server).to receive(:add_or_update_company) data_server.import_donors(profile) end it 'should import an individual' do stub_request(:post, /.*addresses/).to_return(body: raw_data1) primary_contact = double('person') other_person = double('person') expect(data_server).to receive(:add_or_update_primary_contact) .and_return([primary_contact, other_person]) expect(data_server).to receive(:add_or_update_spouse) expect(primary_contact).to receive(:add_spouse) expect(other_person).to receive(:add_spouse) data_server.import_donors(profile) end it 'should create a new contact in the right account list' do stub_request(:post, /.*addresses/).to_return(body: raw_data1) profile = create(:designation_profile, user: organization_account.user, account_list: account_list2) organization_account.user.account_lists = [account_list1, account_list2] expect do data_server.import_donors(profile) end.to change(Contact, :count) expect(account_list2.contacts.last.name).to eq('Rodriguez, <NAME> (Moreno)') end it 'should create a new person in the right account list and donor account' do stub_request(:post, /.*addresses/).to_return(body: raw_data1) profile = create(:designation_profile, user: organization_account.user, account_list: account_list2) organization_account.user.account_lists = [account_list1, account_list2] donor_account = create(:donor_account, organization: organization_account.organization, account_number: '17083') expect do data_server.import_donors(profile) end.to change(Person, :count) new_person = account_list2.contacts.last.people.order('contact_people.primary::int desc').references(:contact_people).last expect(new_person.last_name).to eq 'Rodriguez' expect(new_person.middle_name).to eq '' expect(new_person.donor_accounts.last).to eq donor_account stub_request(:post, /.*addresses/).to_return( body: '"PEOPLE_ID","ACCT_NAME","ADDR1","CITY","STATE","ZIP","PHONE","COUNTRY","FIRST_NAME","MIDDLE_NAME",'\ '"TITLE","SUFFIX","SP_LAST_NAME","SP_FIRST_NAME","SP_MIDDLE_NAME","SP_TITLE","ADDR2","ADDR3","ADDR4",'\ '"ADDR_CHANGED","PHONE_CHANGED","CNTRY_DESCR","PERSON_TYPE","LAST_NAME_ORG","SP_SUFFIX"'\ "\r\n"\ '"17083","<NAME> (Moreno)","Bahia Acapulco 379","Chihuahua","CHH",'\ '"24555","(376) 706-670","MEX","Ramon","C","Sr.","","Moreno","Celeste","Gonzalez","Sra.","","","",'\ '"4/4/2003","4/4/2003","","P","Rodrigues",""'\ "\r\n" ) data_server.import_donors(profile) expect(new_person.reload.last_name).to eq 'Rodrigues' expect(new_person.middle_name).to eq 'C' end it "should notify Rollbar if PERSON_TYPE is not 'O' or 'P'" do stub_request(:post, /.*addresses/).to_return( body: '"PEOPLE_ID","ACCT_NAME","ADDR1","CITY","STATE","ZIP","PHONE","COUNTRY","FIRST_NAME","MIDDLE_NAME",'\ '"TITLE","SUFFIX","SP_LAST_NAME","SP_FIRST_NAME","SP_MIDDLE_NAME","SP_TITLE","ADDR2","ADDR3","ADDR4",'\ '"ADDR_CHANGED","PHONE_CHANGED","CNTRY_DESCR","PERSON_TYPE","LAST_NAME_ORG","SP_SUFFIX"'\ "\r\n"\ '"17083","<NAME> (Moreno)","Bahia Acapulco 379","Chihuahua","CHH",'\ '"24555","(376) 706-670","MEX","Ramon","C","Sr.","","Moreno","Celeste","Gonzalez","Sra.","","","",'\ '"4/4/2003","4/4/2003","","BAD_PERSON_TYPE","Rodrigues",""'\ "\r\n" ) expect(Rollbar).to receive(:error) data_server.import_donors(profile) end it 'should add or update primary contact' do expect(data_server).to receive(:add_or_update_person) data_server.send(:add_or_update_primary_contact, create(:account_list), '', create(:donor_account)) end it 'should add or update spouse' do expect(data_server).to receive(:add_or_update_person) data_server.send(:add_or_update_spouse, create(:account_list), '', create(:donor_account)) end it 'should put the spouse last name correctly if it downloads a blank SP_LAST_NAME' do adams_line = { 'PEOPLE_ID' => '11111', 'ACCT_NAME' => '<NAME>', 'ADDR1' => '123 mi casa blvd.', 'CITY' => 'Colima', 'STATE' => 'COL', 'ZIP' => '456788', 'PHONE' => '(52) 45 456-5678', 'COUNTRY' => 'MEX', 'FIRST_NAME' => 'Tim', 'MIDDLE_NAME' => '', 'TITLE' => 'Mr', 'SUFFIX' => '', 'SP_LAST_NAME' => '', 'SP_FIRST_NAME' => 'Leah', 'SP_MIDDLE_NAME' => '', 'SP_TITLE' => 'Mrs', 'ADDR2' => '', 'ADDR3' => '', 'ADDR4' => '', 'ADDR_CHANGED' => '8/15/2003', 'PHONE_CHANGED' => '8/15/2003', 'CNTRY_DESCR' => '', 'PERSON_TYPE' => 'O', 'LAST_NAME' => 'Adams', 'SP_SUFFIX' => '' } al = create(:account_list) data_server.send(:add_or_update_spouse, al, adams_line, create(:donor_account)) person = Person.where(first_name: 'Leah').last expect(person.last_name).to eql('Adams') end describe 'add or update a company' do let(:line) do { 'PEOPLE_ID' => '19238', 'ACCT_NAME' => 'ACorporation', 'ADDR1' => '123 mi casa blvd.', 'CITY' => 'Colima', 'STATE' => 'COL', 'ZIP' => '456788', 'PHONE' => '(52) 45 456-5678', 'COUNTRY' => 'MEX', 'FIRST_NAME' => '', 'MIDDLE_NAME' => '', 'TITLE' => '', 'SUFFIX' => '', 'SP_LAST_NAME' => '', 'SP_FIRST_NAME' => '', 'SP_MIDDLE_NAME' => '', 'SP_TITLE' => '', 'ADDR2' => '', 'ADDR3' => '', 'ADDR4' => '', 'ADDR_CHANGED' => '8/15/2003', 'PHONE_CHANGED' => '8/15/2003', 'CNTRY_DESCR' => '', 'PERSON_TYPE' => 'O', 'LAST_NAME_ORG' => 'ACorporation', 'SP_SUFFIX' => '' } end let(:account_list) { create(:account_list) } let(:user) { User.find(person.id) } let(:donor_account) { create(:donor_account) } it 'should add a company with an existing master company' do create(:company, name: 'ACorporation') expect do data_server.send(:add_or_update_company, account_list, user, line, donor_account) end.to_not change(MasterCompany, :count) end it 'should add a company without an existing master company and create a master company' do expect do data_server.send(:add_or_update_company, account_list, user, line, donor_account) end.to change(MasterCompany, :count).by(1) end it 'should update an existing company' do company = create(:company, name: 'ACorporation') user.account_lists << account_list account_list.companies << company expect do new_company = data_server.send(:add_or_update_company, account_list, user, line, donor_account) expect(new_company).to eq(company) end.to_not change(Company, :count) end it 'should associate new company with the donor account' do data_server.send(:add_or_update_company, account_list, user, line, donor_account) expect(donor_account.master_company_id).not_to be_nil end end describe 'add or update contact' do let(:line) do { 'PEOPLE_ID' => '17083', 'ACCT_NAME' => 'Rodrigue', 'ADDR1' => 'Ramon y Celeste (Moreno)', 'CITY' => 'Bahia Acapulco 379', 'STATE' => 'Chihuahua', 'ZIP' => 'CHH', 'PHONE' => '24555', 'COUNTRY' => '(376) 706-670', 'FIRST_NAME' => 'MEX', 'MIDDLE_NAME' => 'Ramon', 'TITLE' => '', 'SUFFIX' => 'Sr.', 'SP_LAST_NAME' => '', 'SP_FIRST_NAME' => 'Moreno', 'SP_MIDDLE_NAME' => 'Celeste', 'SP_TITLE' => 'Gonzalez', 'ADDR2' => 'Sra.', 'ADDR3' => '', 'ADDR4' => '', 'ADDR_CHANGED' => '', 'PHONE_CHANGED' => '4/4/2003', 'CNTRY_DESCR' => '4/4/2003', 'PERSON_TYPE' => '', 'LAST_NAME_ORG' => 'P', 'SP_SUFFIX' => 'Rodriguez', 'EMAIL' => '<EMAIL>' } end let(:account_list) { create(:account_list) } let(:user) { User.find(person.id) } let(:donor_account) { create(:donor_account) } before do donor_account.link_to_contact_for(account_list) end it 'should add a contact with an existing master person' do mp = create(:master_person) donor_account.organization.master_person_sources.create(master_person_id: mp.id, remote_id: 1) expect do data_server.send(:add_or_update_person, account_list, line, donor_account, 1) end.to_not change(MasterPerson, :count) end it 'should add a contact without an existing master person and create a master person' do expect do data_server.send(:add_or_update_person, account_list, line, donor_account, 1) end.to change(MasterPerson, :count).by(1).and(change(Person, :count).by(2)) end it 'should add a new contact with no spouse prefix' do expect do data_server.send(:add_or_update_person, account_list, line, donor_account, 1) end.to change(MasterPerson, :count).by(1) end it 'should add a new contact with a spouse prefix' do expect do data_server.send(:add_or_update_person, account_list, line, donor_account, 1, 'SP_') end.to change(MasterPerson, :count).by(1) end it 'should update an existing person' do person = create(:person) user.account_lists << account_list donor_account.master_people << person.master_person donor_account.people << person donor_account.organization.master_person_sources.create(master_person_id: person.master_person_id, remote_id: 1) expect do new_contact, _other = data_server.send(:add_or_update_person, account_list, line, donor_account, 1) expect(new_contact).to eq(person) end.to_not change(MasterPerson, :count) end it 'should associate new contacts with the donor account' do expect do data_server.send(:add_or_update_person, account_list, line, donor_account, 1) end.to change(MasterPersonDonorAccount, :count).by(1) end it 'should add email address as primary if no other email addresses' do data_server.send(:add_or_update_person, account_list, line, donor_account, 1) expect(Contact.first.people.first.email_addresses.pluck(:email)).to eq ['<EMAIL>'] end it 'should not override primary if email already exists' do data_server.send(:add_or_update_person, account_list, line, donor_account, 1) Contact.first.people.first.email_addresses.create(email: '<EMAIL>', primary: true) data_server.send(:add_or_update_person, account_list, line, donor_account, 1) expect(Contact.first.people.first.primary_email_address.email).to eq '<EMAIL>' end it 'should override primary if email address is new' do expect do data_server.send(:add_or_update_person, account_list, line.except('EMAIL'), donor_account, 1) end.to_not change(EmailAddress, :count) Contact.first.people.first.email_addresses.create(email: '<EMAIL>', primary: true) data_server.send(:add_or_update_person, account_list, line, donor_account, 1) expect(Contact.first.people.first.primary_email_address.email).to eq '<EMAIL>' end end end context '#add_or_update_donor_account' do before do stub_request(:get, %r{https://api\.smartystreets\.com/street-address/.*}).to_return(body: '[]') end let(:line) do { 'PEOPLE_ID' => '17083', 'ACCT_NAME' => 'Rodrigue', 'ADDR1' => 'Ramon y Celeste (Moreno)', 'CITY' => 'Bahia Acapulco 379', 'STATE' => 'Chihuahua', 'ZIP' => '24555', 'PHONE' => '(376) 706-670', 'COUNTRY' => 'CHH', 'FIRST_NAME' => 'Ramon', 'MIDDLE_NAME' => '', 'TITLE' => '', 'SUFFIX' => 'Sr.', 'SP_LAST_NAME' => '', 'SP_FIRST_NAME' => 'Moreno', 'SP_MIDDLE_NAME' => 'Celeste', 'SP_TITLE' => 'Gonzalez', 'ADDR2' => 'Sra.', 'ADDR3' => '', 'ADDR4' => '', 'ADDR_CHANGED' => '2/14/2002', 'PHONE_CHANGED' => '4/4/2003', 'CNTRY_DESCR' => 'USA', 'PERSON_TYPE' => '', 'LAST_NAME_ORG' => 'P', 'SP_SUFFIX' => 'Rodriguez' } end it 'creates a new contact' do expect do data_server.send(:add_or_update_donor_account, line, profile) end.to change(Contact, :count) end it "doesn't add duplicate addresses with standard country name, just one correct address" do line['CNTRY_DESCR'] = 'United States' expect do data_server.send(:add_or_update_donor_account, line, profile) end.to change(Address, :count).by(2) expect do data_server.send(:add_or_update_donor_account, line, profile) end.to change(Address, :count).by(0) expect(account_list.contacts.count).to eq(1) contact = account_list.contacts.first expect(contact.donor_accounts.count).to eq(1) donor_account = contact.donor_accounts.first expect(contact.addresses.count).to eq(1) contact_address = contact.addresses.first expect(donor_account.addresses.count).to eq(1) donor_address = donor_account.addresses.first expected_attrs = { street: "Ramon y Celeste (Moreno)\nSra.", city: 'Bahia Acapulco 379', country: 'United States', postal_code: '24555', source: 'DataServer', start_date: Date.new(2002, 2, 14) } expect(contact_address.attributes.symbolize_keys.slice(*expected_attrs.keys)).to eq(expected_attrs) expect(donor_address.attributes.symbolize_keys.slice(*expected_attrs.keys)).to eq(expected_attrs) end it "doesn't add duplicate addresses with alternate country name" do expect do data_server.send(:add_or_update_donor_account, line, profile) end.to change(Address, :count).by(2) expect do data_server.send(:add_or_update_donor_account, line, profile) end.to change(Address, :count).by(0) end it 'sets the address as primary if the donor account has no other primary addresses' do data_server.send(:add_or_update_donor_account, line, profile) contact = account_list.contacts.first donor_account = contact.donor_accounts.first expect(contact.reload.addresses.where(primary_mailing_address: true).count).to eq(1) expect(donor_account.reload.addresses.where(primary_mailing_address: true).count).to eq(1) end it 'leaves existing primary address in the donor account' do donor_account = create(:donor_account, organization: organization, account_number: '17083') prior_address = create(:address, primary_mailing_address: true) donor_account.addresses << prior_address data_server.send(:add_or_update_donor_account, line, profile) contact = account_list.contacts.first expect(contact.reload.addresses.where(primary_mailing_address: true).count).to eq(1) expect(donor_account.reload.addresses.where(primary_mailing_address: true).count).to eq(1) expect(prior_address.reload.primary_mailing_address).to be true expect(contact.addresses.find_by(street: prior_address.street).primary_mailing_address).to be true end it 'updates the contact address based on the donor account' do updater = instance_double(DataServer::ContactAddressUpdate, update_from_donor_account: nil) allow(DataServer::ContactAddressUpdate).to receive(:new) { updater } data_server.send(:add_or_update_donor_account, line, profile) expect(updater).to have_received(:update_from_donor_account) end end describe 'check_credentials!' do it 'raise an error if credentials are missing' do no_user_account = organization_account.dup no_user_account.username = nil expect do described_class.new(no_user_account).import_donors(profile) end.to raise_error( Person::OrganizationAccount::MissingCredentialsError, 'Your credentials are missing for this account.' ) no_pass_account = organization_account.dup no_pass_account.password = <PASSWORD> expect do described_class.new(no_pass_account).import_donors(profile) end.to raise_error( Person::OrganizationAccount::MissingCredentialsError, 'Your credentials are missing for this account.' ) end it 'raise an error if credentials are invalid' do organization_account.valid_credentials = false expect do described_class.new(organization_account).import_donors(profile) end.to raise_error( Person::OrganizationAccount::InvalidCredentialsError, 'Your credentials for MyString are invalid.' ) end end describe 'validate_credentials' do it 'should validate using the profiles url if there is one' do expect(data_server).to receive(:get_params).and_return({}) expect(data_server).to receive(:get_response).with(organization.profiles_url, {}) expect(data_server.validate_credentials).to eq(true) end it 'should validate using the account balance url if there is no profiles url' do organization.profiles_url = nil expect(data_server).to receive(:get_params).and_return({}) expect(data_server).to receive(:get_response).with(organization.account_balance_url, {}) expect(data_server.validate_credentials).to eq(true) end it 'should return false if the error message says the username/password were wrong' do expect(data_server).to receive(:get_response).and_raise( DataServerError.new('Either your username or password were incorrect.') ) expect(data_server.validate_credentials).to eq(false) end it 'should re-raise other errors' do expect(data_server).to receive(:get_response).and_raise( DataServerError.new('other error') ) expect do data_server.validate_credentials end.to raise_error(DataServerError) end it 'returns false if the error message says oauth is required' do expect(data_server).to receive(:get_response).and_raise( DataServerError.new('ERROR\nNo client_id was provied. This application must use OAUTH to download data.') ) expect(data_server.validate_credentials).to eq(false) end end describe 'get_response' do it 'should raise a DataServerError if the first line of the response is ERROR' do stub_request(:post, 'http://example.com').to_return(body: "ERROR\nmessage") expect do data_server.send(:get_response, 'http://example.com', {}) end.to raise_error(DataServerError, "ERROR\nmessage") end def expect_bad_passsword_err(data_server_body) stub_request(:post, 'http://example.com').to_return(body: data_server_body) expect do data_server.send(:get_response, 'http://example.com', {}) end.to raise_error( Person::OrganizationAccount::InvalidCredentialsError, 'Your credentials for MyString are invalid.' ) end it 'raises InvalidCredentialsError if the first line of the response is BAD_PASSWORD' do expect_bad_passsword_err("BAD_PASSWORD\nmessage") end it 'raises InvalidCredentialsError if the first line includes the word "password"' do expect_bad_passsword_err("You have entered an invalid login and/or password\nmessage") end it 'raises InvalidCredentialsError if the second line includes the word "password"' do expect_bad_passsword_err("ERROR\rAn error occurred in GetServiceTicketFromUserNamePassword") end it 'raises InvalidCredentialsError if the second line includes the word "password"' do expect_bad_passsword_err("ERROR\nPerhaps the username or password are incorrect") end it 'raises InvalidCredentialsError if the second line includes the phrase "not registered"' do expect_bad_passsword_err("ERROR\nThe user logging in is not registered with this system") end it 'raises InvalidCredentialsError if the second line includes the phrase "not authorized"' do expect_bad_passsword_err("ERROR\nYou are not authorized to use that Profile.") end it 'raises InvalidCredentialsError if the first line includes a byte order mark' do expect_bad_passsword_err("ERROR\r\nAuthentication failed. Perhaps the username or password are incorrect.") end it 'raises InvalidCredentialsError if the server responds with HTTP 403' do stub_request(:post, 'http://example.com').to_return(status: 403) expect do data_server.send(:get_response, 'http://example.com', {}) end.to raise_error( Person::OrganizationAccount::InvalidCredentialsError, 'Your credentials for MyString are invalid.' ) end it 'raises InvalidCredentialsError if the second line includes the phrase "oauth_token is not recognized"' do expect_bad_passsword_err("ERROR\nThe oauth_token is not recognized.") end it 'raises MissingCredentialsError if the second line includes the phrase "not found"' do stub_request(:post, 'http://example.com').to_return(body: "ERROR\nNot Found") expect do data_server.send(:get_response, 'http://example.com', {}) end.to raise_error( Person::OrganizationAccount::MissingCredentialsError, 'Your credentials are missing for this account.' ) end it 'raises MissingCredentialsError if the server responds with HTTP 404' do stub_request(:post, 'http://example.com').to_return(status: 404) expect do data_server.send(:get_response, 'http://example.com', {}) end.to raise_error( Person::OrganizationAccount::MissingCredentialsError, 'Your credentials are missing for this account.' ) end it 'raises no error when the creds are encoded' do organization_account.username = '<EMAIL>' organization_account.password = '<PASSWORD>!' execute_params = { method: :post, url: 'http://example.com', payload: [], timeout: nil, user: 'tester%40tester.com', password: '<PASSWORD>' } # We can't use webmock to spec this since webmock smart matches on encoding expect(RestClient::Request).to_not receive(:execute).with(execute_params) data_server.send(:get_response, 'http://example.com', {}) end it 'correctly parses special characters in utf-8' do stub_request(:post, 'http://example.com').to_return(body: 'Agapé') expect(data_server.send(:get_response, 'http://example.com', {})) .to eq('Agapé') end it 'raises a DataServerError if the remote server has bad SSL configuration' do allow_any_instance_of(RestClient::Request).to receive(:execute) .and_raise(OpenSSL::SSL::SSLError, 'SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A') expected_messasge = 'Could not securely connect to host "example.com". '\ 'Reason: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A' expect do data_server.send(:get_response, 'http://example.com', {}) end.to raise_error(DataServerError, expected_messasge) end it 'raises a RetryJobButNoRollbarError if there is a timeout' do data_server_body = "ERROR\rTimeout expired. The timeout period elapsed prior to..." stub_request(:post, 'http://example.com').to_return(body: data_server_body) expect do data_server.send(:get_response, 'http://example.com', {}) end.to raise_error(LowerRetryWorker::RetryJobButNoRollbarError) end end describe 'import account balances' do it 'should update a profile balance' do stub_request(:post, /.*accounts/).to_return( body: '"EMPLID","EFFDT","BALANCE","ACCT_NAME"'\ "\n"\ '"0000000","2012-03-23 16:01:39.0","123.45","Test Account"'\ "\n" ) expect(data_server).to receive(:check_credentials!) expect do data_server.import_profile_balance(profile) end.to change(profile, :balance).to(123.45) end it 'should update a designation account balance' do stub_request(:post, /.*accounts/).to_return( body: '"EMPLID","EFFDT","BALANCE","ACCT_NAME"'\ "\n"\ '"0000000","2012-03-23 16:01:39.0","123.45","Test Account"'\ "\n" ) designation_account = create(:designation_account, organization: organization, designation_number: '0000000') data_server.import_profile_balance(profile) expect(designation_account.reload.balance).to eq(123.45) end it 'should not update a designation account balance when there is more than one designation number' do stub_request(:post, /.*accounts/).to_return( body: '"EMPLID","EFFDT","BALANCE","ACCT_NAME"'\ "\n"\ '"0000000,0000001","2012-03-23 16:01:39.0","123.45","Test Account"'\ "\n" ) designation_account = create(:designation_account, organization: organization, designation_number: '0000000', balance: 0) data_server.import_profile_balance(profile) expect(designation_account.reload.balance).to eq(0) end end describe 'import donations' do let(:line) do { 'DONATION_ID' => '1062', 'PEOPLE_ID' => '12271', 'ACCT_NAME' => '<NAME>', 'DESIGNATION' => '10640', 'MOTIVATION' => '', 'PAYMENT_METHOD' => 'EFECTIVO', 'TENDERED_CURRENCY' => 'MXN', 'MEMO' => '', 'DISPLAY_DATE' => '4/23/2003', 'AMOUNT' => '1000.0000', 'TENDERED_AMOUNT' => '1000.0000' } end def stub_donations_request stub_request(:post, /.*donations/).to_return( body: "\xEF\xBB\xBF"\ '"DONATION_ID","PEOPLE_ID","ACCT_NAME","DESIGNATION","MOTIVATION","PAYMENT_METHOD","TENDERED_CURRENCY",'\ '"MEMO","DISPLAY_DATE","AMOUNT","TENDERED_AMOUNT"'\ "\r\n"\ '"1062","12271","<NAME>","10640","","EFECTIVO","MXN","","4/23/2003","1000.0000","1000.0000"'\ "\r\n" ) expect(data_server).to receive(:check_credentials!) end it 'creates a donation' do stub_donations_request expect(data_server).to receive(:find_or_create_designation_account) expect(data_server).to receive(:add_or_update_donation) expect(data_server).to receive(:delete_removed_donations) data_server.import_donations(profile, DateTime.new(1951, 1, 1).utc, '2/2/2012') end it 'removes non-manual donations in the date range but no longer in import', versioning: true do stub_donations_request da = create(:designation_account, organization: organization, designation_number: line['DESIGNATION']) removed_donation = create(:donation) manual_donation = create(:donation, remote_id: nil) old_donation = create(:donation, donation_date: 1.month.ago) da.donations += [manual_donation, old_donation, removed_donation] other_designation = create(:donation) data_server.import_donations(profile, Date.today - 2.weeks, Date.today) expect(Donation.find_by(id: removed_donation.id)).to be_nil expect(Donation.find(manual_donation.id)).to be_present expect(Donation.find(old_donation.id)).to be_present expect(Donation.find(other_designation.id)).to be_present end it 'finds an existing designation account' do account = create(:designation_account, organization: organization, designation_number: line['DESIGNATION']) expect(data_server.send(:find_or_create_designation_account, line['DESIGNATION'], profile)).to eq(account) end it 'creates a new designation account' do expect do data_server.send(:find_or_create_designation_account, line['DESIGNATION'], profile) end.to change(DesignationAccount, :count) end describe 'add or update donation' do let(:designation_account) { create(:designation_account) } before do profile.designation_accounts << designation_account end it 'adds a new donation' do expect do data_server.send(:add_or_update_donation, line, designation_account, profile) end.to change(Donation, :count) end it 'updates an existing donation with a remote_id' do donation = create( :donation, remote_id: '1062', tnt_id: nil, amount: 1, designation_account: designation_account ) expect do donation = data_server.send( :add_or_update_donation, line.merge!('AMOUNT' => '5'), designation_account, profile ) expect(donation.amount).to eq(5) end.to_not change(Donation, :count) end it 'updates an existing donation with a tnt_id' do donation = create( :donation, remote_id: nil, tnt_id: '1062', amount: 1, designation_account: designation_account ) expect do donation = data_server.send( :add_or_update_donation, line.merge!('AMOUNT' => '5'), designation_account, profile ) expect(donation.amount).to eq(5) end.to_not change(Donation, :count) 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, amount: 100.00, donation_date: Date.parse('2003-04-23'), designation_account: designation_account ) donation.donor_account.update(organization: organization, account_number: line['PEOPLE_ID']) expect do donation = data_server.send( :add_or_update_donation, line.merge!('AMOUNT' => '100'), designation_account, profile ) expect(donation.remote_id).to eq('1062') end.to_not change(Donation, :count) end it 'imports multiple donations that were made on the same day, by the same donor, and of the same amount' do line_one = line line_two = line.merge('DONATION_ID' => '1063') expect { data_server.send(:add_or_update_donation, line_one, designation_account, profile) }.to( change { Donation.count }.from(0).to(1) ) expect { data_server.send(:add_or_update_donation, line_two, designation_account, profile) }.to( change { Donation.count }.from(1).to(2) ) end it 'uses the find donation service' do donation = create( :donation, remote_id: '1062', tnt_id: nil, amount: 1, designation_account: designation_account ) expect_any_instance_of(DonationImports::Base::FindDonation).to receive(:find_and_merge).and_return(donation) expect do data_server.send(:add_or_update_donation, line, designation_account, profile) end.to_not change { Donation.count }.from(1) end end context '#parse_date' do it 'supports dates formatted as %m/%d/%y %H:%M:%S' do expect(data_server.send(:parse_date, '5/15/2014 15:22:13')).to eq(Date.new(2014, 5, 15)) end it 'supports dates formatted as MM/DD/YYYY' do expect(data_server.send(:parse_date, '5/15/2014')).to eq(Date.new(2014, 5, 15)) end it 'supports dates formatted as YYYY-MM-DD' do expect(data_server.send(:parse_date, '2014-05-15')).to eq(Date.new(2014, 5, 15)) end it 'returns nil for a badly formatted date' do expect(data_server.send(:parse_date, '2014-99-2')).to be_nil end it 'returns nil for nil' do expect(data_server.send(:parse_date, nil)).to be_nil end it 'returns nil for empty string' do expect(data_server.send(:parse_date, '')).to be_nil end it 'returns the date if given a date object' do expect(data_server.send(:parse_date, Date.today)).to eq Date.today end it 'returns the date for a time if given' do expect(data_server.send(:parse_date, Time.now.getlocal)).to eq Date.today end end end describe '#get_params' do it 'returns hash of params with basic credentials' do expect( data_server.send( :get_params, organization.donations_params, profile: '', datefrom: '01/01/1951', dateto: '2/2/2012', personid: '1' ) ).to eq( 'UserName' => 'foo', 'Password' => '<PASSWORD>', 'Profile' => '', 'DateFrom' => '01/01/1951', 'DateTo' => '2/2/2012', 'Action' => 'Gifts' ) end context 'oauth' do before do allow(ENV).to receive(:fetch).with('DONORHUB_CLIENT_ID') { 'DONORHUB_CLIENT_ID' } allow(ENV).to receive(:fetch).with('DONORHUB_CLIENT_SECRET') { 'DONORHUB_CLIENT_SECRET' } organization_account.token = 'abc-123' end it 'returns hash of params with oauth credentials' do expect( data_server.send( :get_params, organization.donations_params, profile: '', datefrom: '01/01/1951', dateto: '2/2/2012', personid: '1' ) ).to eq( 'UserName' => '', 'Password' => '', 'Profile' => '', 'DateFrom' => '01/01/1951', 'DateTo' => '2/2/2012', 'Action' => 'Gifts', 'client_id' => 'DONORHUB_CLIENT_ID', 'client_secret' => 'DONORHUB_CLIENT_SECRET', 'client_instance' => 'app', 'oauth_token' => '<PASSWORD>' ) end end end end
chuckmersereau/api_practice
app/serializers/reports/appointment_results_period_serializer.rb
<reponame>chuckmersereau/api_practice class Reports::AppointmentResultsPeriodSerializer < ServiceSerializer REPORT_ATTRIBUTES = [:start_date, :end_date, :individual_appointments, :weekly_individual_appointment_goal, :group_appointments, :new_monthly_partners, :new_special_pledges, :monthly_increase, :pledge_increase].freeze attributes(*REPORT_ATTRIBUTES) delegate(*REPORT_ATTRIBUTES, to: :object) has_many :pledge_increase_contacts has_many :new_pledges delegate(:pledge_increase_contacts, :new_pledges, to: :object) def id start_date.strftime('%F') end end
chuckmersereau/api_practice
app/workers/org_donor_accounts_address_cleaner.rb
<reponame>chuckmersereau/api_practice # This is to clean up duplicated donor account addresses resulting from an # old way of doing the encoding for DataServer imports that didn't work with # special characters (and caused duplicated addresses once we fixed it). class OrgDonorAccountsAddressCleaner include Sidekiq::Worker sidekiq_options queue: :api_org_donor_accounts_address_cleaner, unique: :until_executed def self.queue_for_data_server_orgs Organization.using_data_server.pluck(:id).each_with_index do |org_id, index| perform_in(index * 1.minute, org_id) end end def perform(organization_id) donor_accounts_multi_addresses(organization_id).find_each(&:merge_addresses) update_addresses_source(organization_id) logger.info("Cleaned donor account addresses for org #{organization_id}") end private def donor_accounts_multi_addresses(organization_id) DonorAccount.where(organization_id: organization_id) .joins(:addresses).group('donor_accounts.id').having('count(*) > 1') end def update_addresses_source(organization_id) org = Organization.find(organization_id) return unless org.api_class == DataServer Address.where(addressable_type: 'DonorAccount') .joins('INNER JOIN donor_accounts ON donor_accounts.id = addresses.addressable_id') .where(donor_accounts: { organization_id: org.id }) .update_all(source: 'DataServer') end end
chuckmersereau/api_practice
app/workers/donation_amount_recommendation/remote_worker.rb
class DonationAmountRecommendation::RemoteWorker include Sidekiq::Worker sidekiq_options queue: :api_donation_amount_recommendation_remote_worker, unique: :until_executed, unique_expiration: 3.days def perform import_donation_amount_recommendations delete_old_donation_amount_records end private def import_donation_amount_recommendations per_page = 1000.0 pages = (DonationAmountRecommendation::Remote.count / per_page).ceil pages.times do |page| # we must re-order because created_at will return the current time, making it indeterminate # n.times starts at 0, but we want pages with 1 base DonationAmountRecommendation::Remote.reorder(:started_at) .page(page + 1) .per(per_page) .each(&method(:process_remote_recommendation)) end end def process_remote_recommendation(remote) return unless remote.organization && remote.designation_account && remote.donor_account DonationAmountRecommendation.find_or_initialize_by( designation_account: remote.designation_account, donor_account: remote.donor_account ).update( ask_at: remote.ask_at, started_at: remote.started_at, suggested_pledge_amount: remote.suggested_pledge_amount, updated_at: Time.now ) end def delete_old_donation_amount_records DonationAmountRecommendation.where('updated_at <= ?', 12.hours.ago).delete_all end end
chuckmersereau/api_practice
spec/acceptance/api/v2/account_lists/donor_accounts_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/acceptance/api/v2/account_lists/donor_accounts_spec.rb<gh_stars>0 require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Account Lists Api > Donor Accounts' do include_context :json_headers documentation_scope = :account_lists_api_donor_accounts let(:resource_type) { 'donor_accounts' } let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:contact) { create(:contact, account_list: account_list) } let!(:donor_account) { create(:donor_account) } let(:id) { donor_account.id } let(:expected_attribute_keys) do %w( account_number created_at display_name donor_type first_donation_date last_donation_date total_donations updated_at updated_in_db_at ) end let(:resource_associations) do %w( contacts organization ) end before do contact.donor_accounts << donor_account end context 'authorized user' do before { api_login(user) } get '/api/v2/account_lists/:account_list_id/donor_accounts' do parameter 'account_list_id', 'Account List ID', required: true parameter 'filter', 'Filter the list of returned donor_accounts' parameter 'filter[wildcard_search]', 'where name contains or account_number starts with wildcard_search' response_field 'data', 'Data', type: 'Array[Object]' example 'Donor Account [LIST]', document: documentation_scope do explanation 'List of Donor Accounts associated with the Account List' do_request check_collection_resource(1, ['relationships']) expect(resource_object.keys).to match_array expected_attribute_keys expect(response_status).to eq 200 end end get '/api/v2/account_lists/:account_list_id/donor_accounts/:id' do with_options scope: [:data, :attributes] do response_field 'account_number', 'Account Number', type: 'String' response_field 'display_name', 'Name to Display', type: 'String' response_field 'contact_ids', 'Contact IDs', type: 'Array[Number]' response_field 'created_at', 'Created At', type: 'String' response_field 'donor_type', 'Donor Type', type: 'String' response_field 'first_donation_date', 'First Donation Date', type: 'String' response_field 'last_donation_date', 'Last Donation Date', type: 'String' response_field 'organization_id', 'Organization ID', type: 'Number' response_field 'total_donations', 'Total Donations', type: 'Number' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end example 'Donor Account [GET]', document: documentation_scope do explanation 'The Account List Donor Account with the given ID' do_request check_resource(['relationships']) expect(resource_object.keys).to match_array expected_attribute_keys expect(resource_object['account_number']).to eq donor_account.account_number expect(response_status).to eq 200 end end end end
chuckmersereau/api_practice
db/migrate/20140111151946_add_subscribed_to_updates_to_person.rb
class AddSubscribedToUpdatesToPerson < ActiveRecord::Migration def change add_column :people, :subscribed_to_updates, :boolean end end
chuckmersereau/api_practice
spec/controllers/api/v2/appeals/excluded_appeal_contacts_controller_spec.rb
require 'rails_helper' describe Api::V2::Appeals::ExcludedAppealContactsController, type: :controller do let(:factory_type) { :appeal_excluded_appeal_contact } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:appeal) { create(:appeal, account_list: account_list) } let(:appeal_id) { appeal.id } let!(:contact) { create(:contact, account_list: account_list) } let!(:excluded_appeal_contact) { create(:appeal_excluded_appeal_contact, appeal: appeal, contact: contact) } let!(:second_contact) { create(:contact, account_list: account_list) } let!(:second_excluded_appeal_contact) do create(:appeal_excluded_appeal_contact, appeal: appeal, contact: second_contact) end let(:id) { excluded_appeal_contact.id } let(:resource) { excluded_appeal_contact } let(:parent_param) { { appeal_id: appeal_id } } let(:correct_attributes) { {} } include_examples 'index_examples' include_examples 'show_examples' include_examples 'destroy_examples' describe 'sorting' do before { api_login(user) } context 'contact.name sort' do let!(:sorting_appeal) { create(:appeal, account_list: account_list) } let!(:contact1) { create(:contact, account_list: account_list, name: '<NAME>') } let!(:contact2) { create(:contact, account_list: account_list, name: '<NAME>') } let!(:excluded_appeal_contact1) do create(:appeal_excluded_appeal_contact, contact: contact1, appeal: sorting_appeal) end let!(:excluded_appeal_contact2) do create(:appeal_excluded_appeal_contact, contact: contact2, appeal: sorting_appeal) end it 'sorts results desc' do get :index, appeal_id: sorting_appeal.id, sort: 'contact.name' expect(response.status).to eq(200) data = JSON.parse(response.body)['data'] expect(data.length).to eq(2) expect(data[0]['id']).to eq(excluded_appeal_contact1.id) expect(data[1]['id']).to eq(excluded_appeal_contact2.id) end it 'sorts results asc' do get :index, appeal_id: sorting_appeal.id, sort: '-contact.name' expect(response.status).to eq(200) data = JSON.parse(response.body)['data'] expect(data.length).to eq(2) expect(data[0]['id']).to eq(excluded_appeal_contact2.id) expect(data[1]['id']).to eq(excluded_appeal_contact1.id) end end end end
chuckmersereau/api_practice
spec/models/notification_type/remind_partner_in_advance_spec.rb
require 'rails_helper' describe NotificationType::RemindPartnerInAdvance do let(:remind_partner_in_advance) { NotificationType::RemindPartnerInAdvance.first_or_initialize } let(:da) { create(:designation_account_with_donor) } let(:contact) { da.contacts.financial_partners.first } let(:donation) do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 2.months.ago) end describe '#check' do context 'non-direct deposit donor' do before do contact.update(direct_deposit: false, pledge_received: true, pledge_frequency: 3.0) end it 'adds a notification if one month in advance' do donation.update(donation_date: 2.months.ago) contact.update(last_donation_date: donation.donation_date) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(1) end it "doesn't adds a notification if 32 days late" do donation.update(donation_date: 122.days.ago) contact.update(last_donation_date: donation.donation_date) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(0) end it "doesn't adds a notification if one month in advance but pledge_frequency is nil" do contact.update(pledge_frequency: nil) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(0) end it 'skips people with future pledge_start_date' do contact.update(pledge_start_date: 1.day.from_now) contact.update(last_donation_date: donation.donation_date) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(0) end it "doesn't add a notification if not one month in advance" do donation.update(donation_date: 1.month.ago) contact.update(last_donation_date: donation.donation_date) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(0) end it 'add a notification if less than one month in advance' do donation.update(donation_date: 65.days.ago) contact.update(last_donation_date: donation.donation_date) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(1) end it "doesn't add a notification if less than one month in advance with a recent prior notification" do donation.update(donation_date: 65.days.ago) contact.update(last_donation_date: donation.donation_date) contact.notifications.create!(notification_type_id: remind_partner_in_advance.id, event_date: 1.month.ago) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(0) end it 'add a notification if less than one month in advance with a remote prior nodifiction' do donation.update(donation_date: 65.days.ago) contact.update(last_donation_date: donation.donation_date) contact.notifications.create!(notification_type_id: remind_partner_in_advance.id, event_date: 3.months.ago) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(1) end it "doesn't add a notification if the contact is on a different account list with a shared designation account" do donation.update(donation_date: 2.months.ago) contact.update(last_donation_date: donation.donation_date) account_list2 = create(:account_list) account_list2.account_list_entries.create!(designation_account: da) notifications = remind_partner_in_advance.check(account_list2) expect(notifications.length).to eq(0) end end context 'has never given' do it "doesn't add a notification" do notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(0) end end context 'direct deposit donor' do before do contact.update(direct_deposit: true, pledge_received: true, pledge_frequency: 3.0) end it "doesn't adds a notification if one month in advance" do donation.update(donation_date: 2.months.ago) contact.update(last_donation_date: donation.donation_date) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(0) end end context 'less than quarterly donor' do before do contact.update(direct_deposit: false, pledge_received: true, pledge_frequency: 1.0) end it "doesn't adds a notification if one month in advance" do donation.update(donation_date: 2.months.ago) contact.update(last_donation_date: donation.donation_date) notifications = remind_partner_in_advance.check(contact.account_list) expect(notifications.length).to eq(0) end end end describe '#create_task' do let(:account_list) { create(:account_list) } it 'creates a task for the activity list' do expect do remind_partner_in_advance.create_task(account_list, contact.notifications.new) end.to change(Activity, :count).by(1) end it 'associates the contact with the task created' do task = remind_partner_in_advance.create_task(account_list, contact.notifications.new) expect(task.contacts.reload).to include(contact) end end end
chuckmersereau/api_practice
app/controllers/api/v2_controller.rb
<gh_stars>0 require 'json_api_service' class Api::V2Controller < ApiController include BatchRequestHelpers include Fields include Filtering include Including include Pagination include Pundit include PunditHelpers include ResourceType include Sorting rescue_from Pundit::NotAuthorizedError, with: :render_403_from_exception before_action :authenticate! before_action :validate_and_transform_json_api_params before_action :update_current_user_tracked_fields after_action :verify_authorized, except: :index around_action :scope_request_to_time_zone, :scope_request_to_locale protected def current_time_zone if current_user&.time_zone Time.find_zone(current_user.time_zone) || Time.zone else Time.zone end end def current_user @current_user ||= fetch_current_user end def account_lists @account_lists ||= fetch_account_lists end def permit_coach? false end private # The check for user_uuid should be removed 30 days after the following PR is merged to master # https://github.com/CruGlobal/mpdx_api/pull/993 def fetch_current_user # See JsonWebToken::Middleware and application.rb where the middleware is initialized jwt_payload = request.env['auth.jwt_payload'] return unless (jwt_payload.try(:[], 'user_id') || jwt_payload.try(:[], 'user_uuid')) && jwt_payload.try(:[], 'exp') User.find_by(id: jwt_payload['user_id'] || jwt_payload['user_uuid']) end def authenticate! raise Exceptions::AuthenticationError unless current_user end def meta_hash(resources) { pagination: pagination_meta_params(resources), sort: sorting_param_applied_to_query, filter: permitted_filter_params_with_ids } end def permitted_filter_params_with_ids @original_params[:filter]&.slice(*filter_params.keys) || {} end def persistence_context action_name == 'update' ? :update_from_controller : :create end def data_attributes params.dig(:data, :attributes) end def fetch_account_lists unless account_list_filter return current_user.account_lists unless permit_coach? return current_user.readable_account_lists end @account_lists = fetch_account_list_with_filter return @account_lists if @account_lists.present? raise ActiveRecord::RecordNotFound, "Resource 'AccountList' with id '#{account_list_filter}' does not exist." end def account_list_filter params.dig(:filter, :account_list_id) if permitted_filters.include?(:account_list_id) end def fetch_account_list_with_filter return current_user.account_lists.where(id: account_list_filter) unless permit_coach? current_user.readable_account_lists.where(id: account_list_filter) end def verify_primary_id_placement return unless params.dig(:data, :attributes, :id) render_403(title: 'A primary `id` cannot be sent at `/data/attributes/id`, it must be sent at `/data/id`') end def scope_request_to_time_zone(&block) Time.use_zone(current_time_zone, &block) end def scope_request_to_locale I18n.locale = locale_from_header_or_current_user.try(:tr, '-', '_') || 'en_US' yield ensure I18n.locale = 'en_US' end def locale_from_header_or_current_user request.env['HTTP_ACCEPT_LANGUAGE'].try(:split, /[,,;]/).try(:first) || current_user&.locale end def validate_and_transform_json_api_params @original_params = params @_params = JsonApiService.consume(params: params, context: self) end def update_current_user_tracked_fields return unless current_user return if current_user.current_sign_in_at.present? && current_user.current_sign_in_at > 12.hours.ago current_user.update_tracked_fields!(request) end end
chuckmersereau/api_practice
app/services/google_contacts_integrator.rb
<gh_stars>0 require 'google_contact_sync' require 'google_contacts_cache' class GoogleContactsIntegrator attr_accessor :assigned_remote_ids, :cache, :client CONTACTS_GROUP_TITLE = 'MPDX'.freeze # If a contact in MPDX gets marked as inactive, e.g. 'Not Interested', then they won't be synced with Google anymore # but they will be assigned to this Google group so the user can delete it if they want to. INACTIVE_GROUP_TITLE = 'Inactive'.freeze def initialize(google_integration) @integration = google_integration @account = google_integration.google_account end def self.retry_on_api_errs yield rescue GoogleContactsApi::UnauthorizedError # Try job again which will refresh the token raise LowerRetryWorker::RetryJobButNoRollbarError rescue OAuth2::Error => e if e.response && e.response.status >= 500 || e.response.status == 403 # Try again on server errs or rate limit exceeded raise LowerRetryWorker::RetryJobButNoRollbarError end raise e end def sync_data return unless @integration.contacts_integration? # Don't run the Google sync during imports, it can sync them all once the # import is done, which is much more efficient. return if @integration.account_list.organization_accounts.any?(&:downloading) return if @integration.account_list.imports.any?(&:importing) return if @integration.account_list.mail_chimp_account.try(&:importing) sync_and_return_num_synced cleanup_inactive_g_contacts rescue Person::GoogleAccount::MissingRefreshToken # Don't log this exception as we expect it to happen from time to time. # Person::GoogleAccount will turn off the contacts integration and send the user an email to refresh their Google login. rescue StandardError => e Rollbar.raise_or_notify(e) end alias sync_contacts sync_data def sync_and_return_num_synced @cache = GoogleContactsCache.new(@account) contacts = contacts_to_sync return 0 if contacts.empty? setup_assigned_remote_ids @contacts_to_retry_sync = [] # Each individual google_contact record also tracks a last synced time which will reflect when that particular person # was synced as well, this integration overall sync time is used though for querying the Google Contacts API for # updated google contacts, so setting the last synced time at the start of th sync would capture Google contacts # changed during the sync in the next sync. @integration.contacts_last_synced = Time.now contacts.find_each(&method(:sync_contact)) self.class.retry_on_api_errs { api_user.send_batched_requests } # For contacts syncs to the Google Contacts API that were either deleted or modified during the sync # and so caused a 404 Contact Not Found or a 412 Precondition Mismatch (i.e. ETag mismatch, i.e. contact changed), # we can attempt to retry them by re-executing the sync logic which will pull down the Google Contacts information # and re-compare with it. The save_g_contacts_then_links method below may populate @contacts_to_retry_sync. # Only retry the sync once though in case one of those problems was caused by something that would be ongoing # despite re-applying the sync logic. @contacts_to_retry_sync.each(&:reload) @contacts_to_retry_sync.each(&method(:sync_contact)) self.class.retry_on_api_errs { api_user.send_batched_requests } delete_g_contact_merge_losers @integration.save contacts.size end def delete_g_contact_merge_losers g_contact_merge_losers.each(&method(:delete_g_contact_merge_loser)) end def g_contact_merge_losers # Return the google_contacts for this Google account that are no longer associated with a contact-person pair # due to that contact or person being merged with another contact or person in MPDX. # Look for records that have both the contact_id and person_id set, because the Google Import uses an old method # of just setting the person_id and we don't want to wrongly interpret imported Google contacts as merge losers. @account.google_contacts .joins('LEFT JOIN contact_people ON '\ 'google_contacts.person_id = contact_people.person_id AND contact_people.contact_id = google_contacts.contact_id') .where('contact_people.id IS NULL').where.not(contact_id: nil).where.not(person_id: nil).readonly(false) end def delete_g_contact_merge_loser(g_contact_link) # In the past this method also deleted the contact inside the Google account. # We decided to never automatically delete contacts in Google, so that behaviour was removed. g_contact_link.destroy end def cleanup_inactive_g_contacts GoogleContact.joins(:contact).where(contacts: { account_list_id: @integration.account_list.id }) .where(Contact.inactive_conditions).where(google_account: @account).readonly(false) .each(&method(:cleanup_inactive_g_contact)) self.class.retry_on_api_errs { api_user.send_batched_requests } end def cleanup_inactive_g_contact(g_contact_link, num_retries = 1) g_contact = @cache.find_by_id(g_contact_link.remote_id) unless g_contact g_contact_link.destroy return end g_contact.prep_add_to_group(inactive_group) api_user.batch_create_or_update(g_contact) do |status| log_api_request_and_response(g_contact_link.contact, g_contact, status) inactive_cleanup_response(status, g_contact, g_contact_link, num_retries) end end def inactive_cleanup_response(status, g_contact, g_contact_link, num_retries) case status[:code] when 200, 404 # For success or contact not found, just go ahead and delete the link g_contact_link.destroy when 412 raise status.inspect if num_retries < 1 # For 412 Etags Mismatch, remove the cached Google contact and retry the operation again @cache.remove_g_contact(g_contact) cleanup_inactive_g_contact(g_contact_link, num_retries - 1) when 400 # HEADS UP! # Blindly covering up failures! # We currently aren't invested in fixing Google Contact sync, # so when 400 errors occur we can ignore them. return else raise format('HTTP %p returned. Could not clean up inactive contact (after %d tries): %p', status, num_retries, g_contact) end rescue StandardError => e Rollbar.raise_or_notify(e) end def api_user @account.contacts_api_user end def setup_assigned_remote_ids @assigned_remote_ids = @integration.account_list.contacts.joins(:people) .joins('INNER JOIN google_contacts ON google_contacts.person_id = people.id') .pluck('google_contacts.remote_id').to_set end def contacts_to_sync if @integration.contacts_last_synced updated_g_contacts = self.class.retry_on_api_errs do api_user.contacts_updated_min(@integration.contacts_last_synced, showdeleted: false) end queried_contacts_to_sync = contacts_to_sync_query(updated_g_contacts) @cache.cache_g_contacts(updated_g_contacts) queried_contacts_to_sync else # Cache all contacts for the initial sync as all active MPDX contacts will need to be synced so most likely worth it. @cache.cache_all_g_contacts @integration.account_list.active_contacts end end # Queries all contacts that: # - Have some associted records updated_at more recent than its google_contact.contacts_last_synced # - Or contacts without associated google_contacts records (i.e. which haven't been synced before) # - Or contacts whose google_contacts records have been updated remotely since the last sync as specified by the # updated_g_contacts list def contacts_to_sync_query(updated_g_contacts) updated_link_ids = updated_g_contact_links(updated_g_contacts).map(&:id) @integration.account_list.active_contacts .joins(:people) .joins("LEFT JOIN addresses ON addresses.addressable_id = contacts.id AND addresses.addressable_type = 'Contact'") .joins('LEFT JOIN email_addresses ON people.id = email_addresses.person_id') .joins('LEFT JOIN phone_numbers ON people.id = phone_numbers.person_id') .joins('LEFT JOIN person_websites ON people.id = person_websites.person_id') .joins('LEFT JOIN google_contacts ON google_contacts.person_id = people.id AND google_contacts.contact_id = contacts.id '\ "AND google_contacts.google_account_id = #{quote_sql(@account.id)}") .group('contacts.id, google_contacts.last_synced, google_contacts.id') .having('google_contacts.last_synced IS NULL ' \ 'OR google_contacts.last_synced < ' \ 'GREATEST(contacts.updated_at, MAX(contact_people.updated_at), MAX(people.updated_at), MAX(addresses.updated_at), ' \ 'MAX(email_addresses.updated_at), MAX(phone_numbers.updated_at), MAX(person_websites.updated_at))' + (updated_link_ids.empty? ? '' : " OR google_contacts.id IN (#{quote_sql_list(updated_link_ids)})")) .distinct .readonly(false) end # Finds Google contact link record that have been remotely modified since their last sync given a list of recently # modified remote Google contacts def updated_g_contact_links(updated_g_contacts) updated_remote_ids = updated_g_contacts.map(&:id) return [] if updated_remote_ids.empty? # Need to check after map as updated_g_contacts is GoogleContactsApi::ResultSet g_contacts_by_id = Hash[updated_g_contacts.map { |g_contact| [g_contact.id, g_contact] }] g_contact_links = GoogleContact.select(:id, :remote_id, :last_synced) .where(google_account: @account).where(remote_id: updated_remote_ids).where.not(last_synced: nil).to_a g_contact_links.select do |g_contact_link| g_contact = g_contacts_by_id[g_contact_link.remote_id] g_contact.updated > g_contact_link.last_synced end end def quote_sql_list(list) list.map { |item| ActiveRecord::Base.connection.quote(item) }.join(',') end def quote_sql(sql) ActiveRecord::Base.connection.quote(sql) end def sync_contact(contact) g_contacts_and_links = contact.contact_people.joins(:person) .order('contact_people.primary::int desc').order(:person_id) .map(&method(:get_g_contact_and_link)) return if g_contacts_and_links.empty? GoogleContactSync.sync_contact(contact, g_contacts_and_links) contact.save(validate: false) g_contacts_to_save = g_contacts_and_links.select(&method(:g_contact_needs_save?)).map(&:first) if g_contacts_to_save.empty? save_g_contact_links(g_contacts_and_links) else save_g_contacts_then_links(contact, g_contacts_to_save, g_contacts_and_links) end rescue StandardError => e Rollbar.raise_or_notify(e, parameters: { contact_id: contact.id, last_batch_xml: api_user.last_batch_xml }) end def get_g_contact_and_link(contact_person) g_contact_link = @account.google_contacts.where(person: contact_person.person, contact: contact_person.contact).first_or_initialize g_contact = get_or_query_g_contact(g_contact_link, contact_person.person) if g_contact @assigned_remote_ids << g_contact.id else g_contact = GoogleContactsApi::Contact.new g_contact_link.last_data = {} end g_contact.prep_add_to_group(my_contacts_group) g_contact.prep_add_to_group(mpdx_group) [g_contact, g_contact_link] end def groups @groups ||= self.class.retry_on_api_errs { api_user.groups } end def my_contacts_group @my_contacts_group ||= groups.find { |group| group.system_group_id == 'Contacts' } end def inactive_group @inactive_group ||= groups.find { |group| group.title == INACTIVE_GROUP_TITLE } || GoogleContactsApi::Group.create({ title: INACTIVE_GROUP_TITLE }, api_user.api) end def mpdx_group @mpdx_group ||= groups.find { |group| group.title == CONTACTS_GROUP_TITLE } || GoogleContactsApi::Group.create({ title: CONTACTS_GROUP_TITLE }, api_user.api) end def get_or_query_g_contact(g_contact_link, person) if g_contact_link.remote_id retrieved_g_contact = @cache.find_by_id(g_contact_link.remote_id) return retrieved_g_contact if retrieved_g_contact end @cache.select_by_name(person.first_name, person.last_name).find do |g_contact| !@assigned_remote_ids.include?(g_contact.id) end end def g_contact_needs_save?(g_contact_and_link) g_contact, g_contact_link = g_contact_and_link g_contact.attrs_with_changes != g_contact_link.last_data end def save_g_contacts_then_links(contact, g_contacts_to_save, g_contacts_and_links) retry_sync = false g_contacts_to_save.each_with_index do |g_contact, index| g_contact_link = g_contacts_and_links.find { |g_contact_and_link| g_contact_and_link.first == g_contact }.second # The Google Contacts API batch requests significantly speed up the sync by reducing HTTP requests self.class.retry_on_api_errs do api_user.batch_create_or_update(g_contact) do |status| log_api_request_and_response(contact, g_contact, status) # This block is called for each saved g_contact once its batch completes begin # If any g_contact save failed but can be retried, then mark that we should queue the MPDX contact for a retry # sync once we get to the last associated g_cotnact retry_sync = true if failed_but_can_retry?(status, g_contact, g_contact_link) # When we get to last associated g_contact, then either save or queue for retry the MPDX contact next unless index == g_contacts_to_save.size - 1 if retry_sync @contacts_to_retry_sync << contact else save_g_contact_links(g_contacts_and_links) end rescue LowerRetryWorker::RetryJobButNoRollbarError => e raise e rescue StandardError => e # Rescue within this block so that the exception won't cause the response callbacks for the whole batch to break Rollbar.raise_or_notify(e, parameters: { g_contact_attrs: g_contact.formatted_attrs, batch_xml: api_user.last_batch_xml }) end end end end end def failed_but_can_retry?(status, g_contact_saved, g_contact_link) case status[:code] when 200, 201 # Didn't fail, so by the method semantics, return false return false when 404, 412 # 404 is Not found, the google contact was deleted since the last sync # 412 is Precondition Failed (ETag mismatch), so the google contact was changed since the sync was started # Correct the cache to reflect that this contact has been modified or deleted and so shouldn't be cached @cache.remove_g_contact(g_contact_saved) if status[:code] == 404 # If the contact was not found, delete the associated g_contact_link record, so we'll recreate a Google Contact # on retry g_contact_link.destroy else # If the Google Contact was modified during the sync operation, set the last synced time to nul to force # re-comparing with the updated Google contact g_contact_link.update(last_synced: nil) end return true when 403 # 403 is user rate limit exceeded, so don't retry the particular contact, just queue the whole job for retry raise LowerRetryWorker::RetryJobButNoRollbarError else # Failed but can't just fix by resyncing the contact, so raise an error raise(status.inspect) end end def save_g_contact_links(g_contacts_and_links) g_contacts_and_links.each do |g_contact_and_link| g_contact, g_contact_link = g_contact_and_link @assigned_remote_ids.add(g_contact.id) g_contact_link.update(last_data: g_contact.formatted_attrs, remote_id: g_contact.id, last_etag: g_contact.etag, last_synced: Time.now) end end private def log_api_request_and_response(contact, g_contact, status) return unless @integration.account_list.log_debug_info log_request_if_not_already_logged Rails.logger.info( event: 'Google contacts API batch response', account_list_id: @integration.account_list.id, contact: contact, g_contact: g_contact.pretty_inspect, status: status ) end def log_request_if_not_already_logged @logged_api_requests ||= Set.new xml = api_user.last_batch_xml return if @logged_api_requests.include?(xml) Rails.logger.info( event: 'Google contacts API batch request', account_list_id: @integration.account_list_id, batch_xml: xml ) @logged_api_requests << xml end end
chuckmersereau/api_practice
db/migrate/20120424183505_create_activity_contacts.rb
<reponame>chuckmersereau/api_practice class CreateActivityContacts < ActiveRecord::Migration def change create_table :activity_contacts do |t| t.belongs_to :activity t.belongs_to :contact t.timestamps null: false end add_index :activity_contacts, [:activity_id, :contact_id] add_index :activity_contacts, :contact_id end end
chuckmersereau/api_practice
db/migrate/20180509181110_remove_no_date_from_activities.rb
class RemoveNoDateFromActivities < ActiveRecord::Migration def change remove_column :activities, :no_date end end
chuckmersereau/api_practice
db/migrate/20120302190237_create_person_key_accounts.rb
<filename>db/migrate/20120302190237_create_person_key_accounts.rb class CreatePersonKeyAccounts < ActiveRecord::Migration def change create_table :person_key_accounts do |t| t.belongs_to :person t.string :remote_id t.string :first_name t.string :last_name t.string :email t.boolean :authenticated, default: false, null: false t.timestamps null: false end add_index :person_key_accounts, :person_id add_index :person_key_accounts, [:remote_id, :authenticated], :unique => true end end
chuckmersereau/api_practice
app/models/donation_amount_recommendation/remote.rb
<reponame>chuckmersereau/api_practice # The source of this model's data is loaded from the BI tool into the data warehouse. # From their a view has been created on the staging and prod instances of the MPDX database. # Migrations exist for this model for testing and development purposes. class DonationAmountRecommendation::Remote < ApplicationRecord self.table_name = 'wv_donation_amt_recommendation' belongs_to :organization # a kludge that deals with the remote id's being in the old int id format def organization return Organization.cru_usa if organization_id.to_i == 48 super end def designation_account return unless organization organization.designation_accounts.find_by(designation_number: designation_number) end def donor_account return unless organization organization.donor_accounts.find_by(account_number: donor_number) end end
chuckmersereau/api_practice
app/serializers/donation_reports/donation_info_serializer.rb
class DonationReports::DonationInfoSerializer < ServiceSerializer include LocalizationHelper alias symbol_for_currency_code currency_symbol attributes :amount, :contact_id, :converted_amount, :converted_currency, :converted_currency_symbol, :currency, :currency_symbol, :donation_date, :likelihood_type delegate :contact_id, :converted_amount, :converted_currency, :currency, :donation_date, :likelihood_type, to: :object def amount object.amount.to_f end def currency_symbol symbol_for_currency_code(object.currency) end def converted_currency_symbol return nil unless object.converted_currency symbol_for_currency_code(object.converted_currency) end end
chuckmersereau/api_practice
app/models/address.rb
require 'smarty_streets' class Address < ApplicationRecord include Concerns::AfterValidationSetSourceToMPDX audited associated_with: :addressable, except: [:updated_at, :addressable_type] belongs_to :addressable, polymorphic: true, touch: true belongs_to :master_address belongs_to :source_donor_account, class_name: 'DonorAccount' scope :current, -> { where(deleted: false) } before_validation :determine_master_address before_validation :set_manual_source_if_user_changed after_destroy :clean_up_master_address after_save :update_contact_timezone before_create :set_valid_values validates :street, :city, :state, :country, :postal_code, :start_date, :end_date, :remote_id, :region, :metro_area, updatable_only_when_source_is_mpdx: true alias destroy! destroy attr_accessor :user_changed PERMITTED_ATTRIBUTES = [:city, :country, :created_at, :end_date, :historic, :location, :metro_area, :overwrite, :postal_code, :primary_mailing_address, :region, :remote_id, :seasonal, :source, :start_date, :state, :street, :updated_at, :updated_in_db_at, :id, :valid_values].freeze assignable_values_for :location, allow_blank: true do ['Home', 'Business', 'Mailing', 'Seasonal', 'Other', 'Temporary', 'Rep Address'] end def record_paper_trail? # This has the effect of logging all deletes, all creates and the updates # associated with a "log_debug_info" account list. changes['deleted'].present? || marked_for_destruction? || changes['id'].present? || (addressable.is_a?(Contact) && addressable&.account_list&.log_debug_info) end def equal_to?(other) return false unless other other.master_address_id && master_address_id == other.master_address_id || (address_fields_equal?(other) && country_equal?(other) && postal_code_equals?(other)) end def destroy update_attributes(deleted: true, primary_mailing_address: false) end def not_blank? attributes.with_indifferent_access .slice(:street, :city, :state, :country, :postal_code) .any? { |_, v| v.present? && v.strip != '(UNDELIVERABLE)' } end def merge(other_address) self.primary_mailing_address = (primary_mailing_address? || other_address.primary_mailing_address?) self.seasonal = (seasonal? || other_address.seasonal?) self.location = other_address.location if location.blank? self.remote_id = other_address.remote_id if remote_id.blank? self.source_donor_account = other_address.source_donor_account if source_donor_account.blank? self.start_date = [start_date, other_address.start_date].compact.min self.source = remote_id.present? ? 'Siebel' : [source, other_address.source].compact.first save(validate: false) other_address.destroy! end def country=(val) self[:country] = self.class.normalize_country(val) end def self.normalize_country(val) return if val.blank? val = val.strip countries = CountrySelect::COUNTRIES country = countries.find { |c| c[:name].casecmp(val.downcase).zero? } return country[:name] if country countries.each do |c| next unless c[:alternatives].downcase.include?(val.downcase) return c[:name] end # If we couldn't find a match anywhere, go ahead and return the country val end def valid_mailing_address? city.present? && street.present? end def geo return unless master_address master_address.geo end # Not private because Google Contacts sync uses it to normalize addresses without needing to create a record def find_or_create_master_address unless master_address_id master_address = find_master_address master_address ||= MasterAddress.create(attributes_for_master_address) self.master_address_id = master_address.id self.verified = master_address.verified end true end def csv_street street&.gsub("\r\n", "\n")&.strip end def csv_country(home_country) if country == home_country '' else country end end def to_snail origin = addressable.try(:account_list) ? Address.find_country_iso(addressable.account_list.home_country) : 'US' Snail.new( line_1: street, postal_code: postal_code, city: city, region: state, country: Address.find_country_iso(country), origin: origin ).to_s end def self.find_country_iso(val) return nil if val.nil? || val.empty? val = val.upcase Snail.lookup_country_iso(val) || Snail::Iso3166::ALPHA2.select { |_key, array| array.include? val }.keys.first || Snail::Iso3166::ALPHA2.select { |_key, array| array.include? val }.keys.first || Snail::Iso3166::ALPHA2_EXCEPTIONS.select { |_key, array| array.include? val }.keys.first end def fix_encoding_if_equal(other) return unless equal_to?(other) [:street, :city, :state, :country, :postal_code].each do |field| next unless send(field) == old_encoding(other.send(field)) self[field] = other.send(field) end save end def postal_code_prefix no_whitespace(postal_code).downcase[0..4] end private def postal_code_equals?(other) postal_code_prefix == other.postal_code_prefix || equals_old_encoding?(postal_code, other.postal_code) end def address_fields_equal?(other) [:street, :city, :state].all? do |field| equals_old_encoding?(send(field), other.send(field)) end end def country_equal?(other) country.blank? || other.country.blank? || equals_old_encoding?(country, other.country) end def equals_old_encoding?(s1, s2) s1.blank? && s2.blank? || no_whitespace(s1).casecmp(no_whitespace(s2)).zero? || old_encoding(s1) == s2 || s1 == old_encoding(s2) end def no_whitespace(str) str.to_s.gsub(/\s+/, '') end def old_encoding(str) return unless str # This encoding trick was used for a time in DataServer. It would mangle # special characters and was eventually replaced. That means that some # addresses be duplicated (having old and new encoding versions) if they # contained special characters. str.unpack('C*').pack('U*') end def set_manual_source_if_user_changed return unless user_changed && (new_record? || place_fields_changed?) self.source = MANUAL_SOURCE self.start_date = Date.today self.source_donor_account = nil end def place_fields_changed? place_fields = %w(street city state postal_code) place_fields.any? { |f| changes[f].present? && changes[f][0].to_s.strip != changes[f][1].to_s.strip } || (changes['country'].present? && self.class.normalize_country(changes['country'][0]) != self.class.normalize_country(changes['country'][1])) end def determine_master_address if id.blank? find_or_create_master_address else update_or_create_master_address end end def update_or_create_master_address if place_fields_changed? new_master_address_match = find_master_address if master_address.nil? || master_address != new_master_address_match new_master_address_match ||= MasterAddress.create(attributes_for_master_address) self.master_address_id = new_master_address_match.id self.verified = new_master_address_match.verified end end true end def clean_up_master_address return true unless master_address master_address.destroy if master_address.addresses.where.not(id: id).empty? end def find_master_address master_address = MasterAddress.find_by(attributes_for_master_address.slice(:street, :city, :state, :country, :postal_code)) # See if another address in the database matches this one and has a master address where_clause = attributes_for_master_address.symbolize_keys .slice(:street, :city, :state, :country, :postal_code) .map { |k, _v| "lower(#{k}) = :#{k}" }.join(' AND ') master_address ||= Address.where(where_clause, attributes_for_master_address) .find_by('master_address_id is not null') .try(:master_address) is_us_country = attributes_for_master_address[:country].to_s.casecmp('united states').zero? is_us_state = US_STATES.flatten.map(&:upcase).include?(attributes_for_master_address[:state].to_s.upcase) if !master_address && (attributes_for_master_address[:state].to_s.length == 2 || attributes_for_master_address[:postal_code].to_s.length == 5 || attributes_for_master_address[:postal_code].to_s.length == 10) && (is_us_country || (attributes_for_master_address[:country].blank? && is_us_state)) begin results = SmartyStreets.get(attributes_for_master_address) if results.length == 1 ss_address = results.first['components'] attributes_for_master_address[:street] = results.first['delivery_line_1'].downcase attributes_for_master_address[:city] = ss_address['city_name'].downcase attributes_for_master_address[:state] = ss_address['state_abbreviation'].downcase attributes_for_master_address[:postal_code] = [ss_address['zipcode'], ss_address['plus4_code']].compact.join('-').downcase attributes_for_master_address[:state] = ss_address['state_abbreviation'].downcase attributes_for_master_address[:country] = 'united states' attributes_for_master_address[:verified] = true master_address = MasterAddress.find_by(attributes_for_master_address.symbolize_keys .slice(:street, :city, :state, :country, :postal_code)) end attributes_for_master_address[:smarty_response] = results rescue RestClient::RequestFailed, SocketError, RestClient::ResourceNotFound # Don't blow up if smarty didn't like the request end if results && results[0] && results[0]['metadata'] meta = results[0]['metadata'] attributes_for_master_address[:latitude] = meta['latitude'].to_s attributes_for_master_address[:longitude] = meta['longitude'].to_s end unless attributes_for_master_address[:latitude] && attributes_for_master_address[:longitude] begin lat, long = Geocoder.coordinates([attributes_for_master_address[:street], attributes_for_master_address[:city], attributes_for_master_address[:state], attributes_for_master_address[:country]].join(',')) attributes_for_master_address[:latitude] = lat.to_s attributes_for_master_address[:longitude] = long.to_s rescue StandardError # Don't blow up if Google didn't like the request... Rate limit most likely. end end end master_address end def update_contact_timezone return unless primary_mailing_address? return unless (changed & %w(street city state country primary_mailing_address)).present? return unless addressable.respond_to?(:set_timezone) addressable.set_timezone end def attributes_for_master_address @attributes_for_master_address ||= Hash[attributes.symbolize_keys .slice(:street, :city, :state, :country, :postal_code) .select { |_k, v| v.present? } .map { |k, v| [k, v.downcase] }] end def set_valid_values self.valid_values = (source == MANUAL_SOURCE) || !self.class.where(addressable: addressable).exists? true end US_STATES = [ %w(Alabama AL), %w(Alaska AK), %w(Arizona AZ), %w(Arkansas AR), %w(California CA), %w(Colorado CO), %w(Connecticut CT), %w(Delaware DE), ['District of Columbia', 'DC'], %w(Florida FL), %w(Georgia GA), %w(Hawaii HI), %w(Idaho ID), %w(Illinois IL), %w(Indiana IN), %w(Iowa IA), %w(Kansas KS), %w(Kentucky KY), %w(Louisiana LA), %w(Maine ME), %w(Maryland MD), %w(Massachusetts MA), %w(Michigan MI), %w(Minnesota MN), %w(Mississippi MS), %w(Missouri MO), %w(Montana MT), %w(Nebraska NE), %w(Nevada NV), ['New Hampshire', 'NH'], ['New Jersey', 'NJ'], ['New Mexico', 'NM'], ['New York', 'NY'], ['North Carolina', 'NC'], ['North Dakota', 'ND'], %w(Ohio OH), %w(Oklahoma OK), %w(Oregon OR), %w(Pennsylvania PA), ['Puerto Rico', 'PR'], ['Rhode Island', 'RI'], ['South Carolina', 'SC'], ['South Dakota', 'SD'], %w(Tennessee TN), %w(Texas TX), %w(Utah UT), %w(Vermont VT), %w(Virginia VA), %w(Washington WA), ['West Virginia', 'WV'], %w(Wisconsin WI), %w(Wyoming WY) ].freeze end
chuckmersereau/api_practice
spec/acceptance/api/v2/tasks/comments_spec.rb
<gh_stars>0 require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Tasks > Comments' do include_context :json_headers documentation_scope = :tasks_api_comments let!(:user) { create(:user_with_full_account) } let(:resource_type) { :comments } let(:account_list) { user.account_lists.order(:created_at).first } let(:person) { create(:contact_with_person, account_list: account_list).reload.people.first } let(:task) { create(:task, account_list: user.account_lists.order(:created_at).first) } let(:task_id) { task.id } let!(:comment) { create(:activity_comment, activity: task) } let(:id) { comment.id } let(:new_comment) do attributes_for(:activity_comment, activity: task) .merge(updated_in_db_at: comment.updated_at, task_id: task_id) .except(:activity_id, :person_id) end let(:form_data) do build_data(new_comment.slice(*ActivityComment::PERMITTED_ATTRIBUTES), relationships: { person: { data: { type: 'people', id: user.id } } }) end let(:expected_attribute_keys) do %w( body created_at updated_at updated_in_db_at ) end context 'authorized user' do before { api_login(user) } get '/api/v2/tasks/:task_id/comments' do example 'Comment [LIST]', document: documentation_scope do explanation 'List of Comments associated to the Task' do_request check_collection_resource 1, ['relationships'] expect(response_status).to eq(200) end end get '/api/v2/tasks/:task_id/comments/:id' do with_options scope: [:data, :attributes] do response_field 'body', 'Comment body', type: 'String' response_field 'created_at', 'Created At', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end with_options scope: [:data, :relationships] do response_field 'person', 'The person who wrote the comment', type: 'Object' end example 'Comment [GET]', document: documentation_scope do explanation "The Task's Comment with the given ID" do_request check_resource(['relationships']) expect(resource_object.keys).to match_array expected_attribute_keys expect(response_status).to eq(200) end end post '/api/v2/tasks/:task_id/comments' do with_options required: true, scope: [:data, :attributes] do parameter 'body', 'Comment body', type: 'String' end with_options scope: [:data, :relationships] do parameter 'person', 'The person who wrote the comment', type: 'Object' end example 'Comment [CREATE]', document: documentation_scope do explanation 'Create a Comment associated with the Task' do_request data: form_data expect(resource_object['body']).to(be_present) && eq(new_comment[:body]) expect(response_status).to eq(201) end end put '/api/v2/tasks/:task_id/comments/:id' do with_options required: true, scope: [:data, :attributes] do parameter 'body', 'Comment body', type: 'String' end with_options scope: [:data, :relationships] do parameter 'person', 'The person who wrote the comment', type: 'Object' end example 'Comment [UPDATE]', document: documentation_scope do explanation "Update the Task's Comment with the given ID" do_request data: form_data expect(resource_object['body']).to(be_present) && eq(new_comment[:body]) expect(response_status).to eq(200) end end delete '/api/v2/tasks/:task_id/comments/:id' do example 'Comment [DELETE]', document: documentation_scope do explanation "Delete the Task's Comment with the given ID" do_request expect(response_status).to eq(204) end end end end
chuckmersereau/api_practice
spec/services/contact/filter/status_spec.rb
require 'rails_helper' RSpec.describe Contact::Filter::Status do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } describe '#query' do let!(:active_contact) { create(:contact, account_list: account_list, status: 'Ask in Future') } let!(:inactive_contact) { create(:contact, account_list: account_list, status: 'Not Interested') } let!(:contact_with_no_status) { create(:contact, account_list: account_list, status: nil) } let(:contacts) { Contact.all } context 'for single status' do it 'returns the correct contacts' do expect(described_class.query(contacts, { status: 'active' }, nil)).to( contain_exactly(active_contact, contact_with_no_status) ) expect(described_class.query(contacts, { status: 'hidden' }, nil)).to( contain_exactly(inactive_contact) ) expect(described_class.query(contacts, { status: 'null' }, nil)).to( contain_exactly(contact_with_no_status) ) expect(described_class.query(contacts, { status: 'Not Interested' }, nil)).to( contain_exactly(inactive_contact) ) end end context 'for multiple statuses' do it 'returns the correct contacts' do expect(described_class.query(contacts, { status: 'active, hidden' }, nil)).to( contain_exactly(active_contact, inactive_contact, contact_with_no_status) ) expect(described_class.query(contacts, { status: 'hidden, null' }, nil)).to( contain_exactly(contact_with_no_status, inactive_contact) ) end end context 'with reverse_FILTER' do subject { described_class.query(contacts, query, nil) } let(:query) { { status: status, reverse_status: true } } context 'status: "active"' do let(:status) { 'active' } it('returns hidden contacts') { is_expected.to contain_exactly(inactive_contact) } end context 'status: "null"' do let(:status) { 'null' } it('returns hidden contacts') { is_expected.to contain_exactly(inactive_contact) } end context 'status: "hidden"' do let(:status) { 'hidden' } it('returns null/blank contacts') { is_expected.to contain_exactly(contact_with_no_status) } end end end describe '#config' do it 'returns expected config' do expect(described_class.config([account_list])).to include( default_selection: 'active, null', multiple: true, name: :status, options: [{ name: '-- All Active --', id: 'active' }, { name: '-- All Hidden --', id: 'hidden' }, { name: '-- None --', id: 'null' }, { name: 'Never Contacted', id: 'Never Contacted' }, { name: 'Ask in Future', id: 'Ask in Future' }, { name: 'Cultivate Relationship', id: 'Cultivate Relationship' }, { name: 'Contact for Appointment', id: 'Contact for Appointment' }, { name: 'Appointment Scheduled', id: 'Appointment Scheduled' }, { name: 'Call for Decision', id: 'Call for Decision' }, { name: 'Partner - Financial', id: 'Partner - Financial' }, { name: 'Partner - Special', id: 'Partner - Special' }, { name: 'Partner - Pray', id: 'Partner - Pray' }, { name: 'Not Interested', id: 'Not Interested' }, { name: 'Unresponsive', id: 'Unresponsive' }, { name: 'Never Ask', id: 'Never Ask' }, { name: 'Research Abandoned', id: 'Research Abandoned' }, { name: 'Expired Referral', id: 'Expired Referral' }], parent: nil, title: 'Status', type: 'multiselect' ) end end end
chuckmersereau/api_practice
app/services/expected_totals_report/row_formatter.rb
<filename>app/services/expected_totals_report/row_formatter.rb class ExpectedTotalsReport::RowFormatter include LocalizationHelper def initialize(account_list) @account_list = account_list @currency_rates = {} end def format(type:, contact:, donation_amount:, donation_currency:) { contact_id: contact.id, contact_name: contact.name, contact_status: _(contact.status), converted_amount: (donation_amount * rate_for_currency(donation_currency)).to_f, converted_currency: total_currency, converted_currency_symbol: total_currency_symbol, donation_amount: donation_amount.to_f, donation_currency: donation_currency, donation_currency_symbol: currency_symbol(donation_currency), pledge_amount: contact.pledge_amount.to_f, pledge_currency: contact.pledge_currency, pledge_currency_symbol: currency_symbol(contact.pledge_currency), pledge_frequency: _(Contact.pledge_frequencies[contact.pledge_frequency]), type: type } end def total_currency_symbol currency_symbol(total_currency) end def total_currency @account_list.salary_currency_or_default end private def rate_for_currency(currency) @currency_rates[currency] ||= CurrencyRate.latest_for_pair(from: currency, to: total_currency) end end
chuckmersereau/api_practice
spec/factories/pledges.rb
FactoryBot.define do factory :pledge do amount '9.99' amount_currency 'USD' expected_date { Date.today } account_list contact end end
chuckmersereau/api_practice
spec/services/donation_imports/siebel/donor_importer_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe DonationImports::Siebel::DonorImporter do let!(:user) { create(:user_with_account) } let(:organization_account) { user.organization_accounts.first } let(:organization) { organization_account.organization } let(:designation_profile) { organization_account.designation_profiles.first } let!(:designation_account) do create(:designation_account, designation_profiles: [designation_profile], designation_number: 'the_designation_number') end let(:mock_siebel_import) { double(:mock_siebel_import) } let(:mock_profile) { double(:mock_profile) } let!(:first_donor_account) { create(:donor_account, organization: organization, account_number: 'donor_id_one') } let!(:second_donor_account) { create(:donor_account, organization: organization, account_number: 'donor_id_two') } before do allow(mock_siebel_import).to receive(:organization).and_return(organization) allow(mock_siebel_import).to receive(:organization_account).and_return(organization_account) allow(mock_siebel_import).to receive(:parse_date).and_return(1.week.ago) end subject { described_class.new(mock_siebel_import) } DonorStruct = Struct.new(:id, :account_name, :type, :addresses, :contacts) AddressStruct = Struct.new(:id, :address1, :primary, :address2, :address3, :address4, :city, :state, :zip, :seasonal, :type, :updated_at) PersonStruct = Struct.new(:id, :name) let(:siebel_person) { PersonStruct.new('person_id_one', 'Oliver') } let(:siebel_donors) do [ DonorStruct.new( 'id_one', 'Oliver', 'Partner Financial', [AddressStruct.new('address_id_one', '1 angie street', true)], [siebel_person] ), DonorStruct.new( 'id_one', "<NAME>", 'Partner Financial', [AddressStruct.new('address_id_one', '2 angie street')], [] ) ] end context '#import_donors' do it 'imports donors' do expect(SiebelDonations::Donor).to receive(:find) .with(having_given_to_designations: 'the_designation_number', contact_filter: :all, account_address_filter: :primary, contact_email_filter: :all, contact_phone_filter: :all) .and_return(siebel_donors) expect_any_instance_of(described_class::PersonImporter).to receive(:add_or_update_person_on_contact) .with(siebel_person: siebel_person, donor_account: instance_of(DonorAccount), contact: instance_of(Contact), date_from: nil) expect do expect(subject.import_donors).to be_truthy end.to change { DonorAccount.count }.by(1) .and change { Contact.count }.by(1) .and change { Address.count }.by(2) end end end
chuckmersereau/api_practice
app/services/contact/duplicate_pairs_finder.rb
# This class finds and saves DuplicateRecordPair records by looking through all Contacts in the given AccountList. # Duplicates are found primarily by comparing the Contact names and DonorAccount numbers. class Contact::DuplicatePairsFinder < ApplicationDuplicatePairsFinder private def find_duplicates find_duplicates_by_name find_duplicates_by_donor_number end def contacts_scope account_list.contacts end def contact_names_hashes @contact_names_hashes ||= build_hashes_for_comparing_contact_names end def build_hashes_for_comparing_contact_names contacts_scope.pluck(:id, :name).collect do |contact_id_and_name| contact_id = contact_id_and_name[0] original_name = contact_id_and_name[1] parsed_name = HumanNameParser.new(original_name).parse primary_name = Contact::NameBuilder.new(parsed_name.slice(:first_name, :last_name)).name spouse_name = Contact::NameBuilder.new(parsed_name.slice(:spouse_first_name, :spouse_last_name)).name.presence { id: contact_id, original_name: original_name.squish, rebuilt_name: Contact::NameBuilder.new(original_name).name, primary_name: primary_name, spouse_or_primary_name: spouse_name || primary_name } end end def find_duplicates_by_name find_duplicates_by_original_name find_duplicates_by_rebuilt_name find_duplicates_by_primary_name find_duplicates_by_spouse_or_primary_name end def find_duplicates_by_original_name find_duplicate_hashes_by_value(contact_names_hashes, :original_name).each do |duplicate_hashes| add_duplicate_pair_from_hashes(duplicate_hashes, 'Similar names') end end # We rebuild the name so that we can compare a consistent format of the name. # e.g. "<NAME>" and "<NAME>" should be considered duplicates. def find_duplicates_by_rebuilt_name find_duplicate_hashes_by_value(contact_names_hashes, :rebuilt_name).each do |duplicate_hashes| add_duplicate_pair_from_hashes(duplicate_hashes, 'Similar names') end end # Find duplicates where one Contact has both couple names and the other has just the primary name. # e.g. "<NAME> and Jane" and "<NAME>" should be considered duplicates. def find_duplicates_by_primary_name find_duplicate_hashes_by_value(contact_names_hashes, :primary_name).each do |duplicate_hashes| break unless (duplicate_hashes.first[:rebuilt_name] == duplicate_hashes.first[:primary_name]) || (duplicate_hashes.second[:rebuilt_name] == duplicate_hashes.second[:primary_name]) add_duplicate_pair_from_hashes(duplicate_hashes, 'Similar names') end end # Find duplicates where one Contact has both couple names and the other has just the spouse name. # e.g. "<NAME> and Jane" and "<NAME>" should be considered duplicates. def find_duplicates_by_spouse_or_primary_name find_duplicate_hashes_by_value(contact_names_hashes, :spouse_or_primary_name).each do |duplicate_hashes| break unless (duplicate_hashes.first[:rebuilt_name] == duplicate_hashes.first[:spouse_or_primary_name]) || (duplicate_hashes.second[:rebuilt_name] == duplicate_hashes.second[:spouse_or_primary_name]) add_duplicate_pair_from_hashes(duplicate_hashes, 'Similar names') end end def build_hashes_for_comparing_donor_numbers contact_account_numbers = ContactDonorAccount.joins(:donor_account) .where(contact: contacts_scope) .pluck(:contact_id, 'donor_accounts.account_number') contact_account_numbers.collect do |contact_id_and_donor_number| { id: contact_id_and_donor_number[0], donor_number: contact_id_and_donor_number[1] } end end def find_duplicates_by_donor_number contact_donor_numbers_hashes = build_hashes_for_comparing_donor_numbers find_duplicate_hashes_by_value(contact_donor_numbers_hashes, :donor_number).each do |duplicate_hashes| add_duplicate_pair_from_hashes(duplicate_hashes, 'Same donor account number') end end end
chuckmersereau/api_practice
spec/services/admin/dup_phones_fix_spec.rb
require 'rails_helper' describe Admin::DupPhonesFix, '#fix' do it 'combines dup numbers and keeps primary one the same' do person = build_person( { number: '617-456-7890', primary: true }, { number: '+16174567890' }, number: '220-456-7890' ) Admin::DupPhonesFix.new(person).fix numbers = person.reload.phone_numbers.order(:number).to_a expect(numbers.map(&:number)).to eq ['+16174567890', '+12204567890'] expect(numbers[0]).to be_primary expect(numbers[1]).to_not be_primary end it 'combines dup US phone numbers that differ by missing 1 after +' do expect_fix_result( [{ number: '+6042345678', country_code: '60' }, { number: '+16042345678' }], ['+16042345678'] ) end it 'leaves alone non-dup int numbers that look US number missing +1' do expect_fix_result( [{ number: '+4412345678', country_code: '1' }, { number: '+6431234567', country_code: '64' }], ['+4412345678', '+6431234567'] ) end def expect_fix_result(unfixed_numbers_attrs, fixed_numbers) person = build_person(*unfixed_numbers_attrs) Admin::DupPhonesFix.new(person).fix expect(person.reload.phone_numbers.pluck(:number)).to eq fixed_numbers end def build_person(*numbers_attrs) person = create(:person) numbers_attrs.each do |attrs| phone = create(:phone_number, attrs.merge(person: person)) # Calling update_column is needed to get around the auto-normalization of # the current phone number code (we are simulating old non-normalized numbers) phone.update_column(:number, attrs[:number]) phone.update_column(:country_code, attrs[:country_code]) if attrs[:country_code] end person end end
chuckmersereau/api_practice
app/services/reports/pledge_histories_period.rb
class Reports::PledgeHistoriesPeriod < ActiveModelSerializers::Model attr_accessor :account_list, :end_date, :start_date def pledged sum_partner_status_log_pledge_amounts(false) + sum_contact_pledge_amounts(false) end def received sum_partner_status_log_pledge_amounts(true) + sum_contact_pledge_amounts(true) end protected def sum_partner_status_log_pledge_amounts(pledge_received) partner_status_logs.where(pledge_received: pledge_received) .to_a.sum(&method(:convert_pledge_amount)) end def sum_contact_pledge_amounts(pledge_received) contacts = account_list.contacts .where(pledge_received: pledge_received) .where('created_at <= ?', end_date) contact_ids = partner_status_logs.pluck(:contact_id) contacts = contacts.where.not(id: contact_ids) unless contact_ids.empty? contacts.to_a.sum(&method(:convert_pledge_amount)) end def convert_pledge_amount(object) CurrencyRate.convert_on_date( amount: (object.pledge_amount || 0) / (object.pledge_frequency || 1), from: object.pledge_currency, to: account_list.salary_currency_or_default, date: end_date ) end def partner_status_logs @partner_status_logs ||= account_list.partner_status_logs .select('DISTINCT ON ("partner_status_logs"."contact_id") "partner_status_logs".*') .order(:contact_id, recorded_on: :asc) .where('recorded_on > ?', end_date) end end
chuckmersereau/api_practice
spec/support/shared_controller_examples/bulk_create_examples.rb
RSpec.shared_examples 'bulk_create_examples' do include_context 'common_variables' describe '#create' do let(:first_id) { SecureRandom.uuid } let(:second_id) { SecureRandom.uuid } let(:third_id) { SecureRandom.uuid } let(:unauthorized_resource) { create(factory_type) } let(:bulk_create_attributes) do { data: [ { data: { type: resource_type, id: first_id, attributes: correct_attributes }.merge!(relationships: relationships) }, { data: { type: resource_type, id: second_id, attributes: incorrect_attributes }.merge!(relationships: relationships) }, { data: { type: resource_type, id: third_id, attributes: correct_attributes }.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 created resources' do post :create, bulk_create_attributes expect(response.status).to eq(200), invalid_status_detail expect(response_body.length).to eq(3) end it "returns a 400 if one of the data objects doesn't contain an id" do post :create, data: bulk_create_attributes[:data].append(data: { attributes: {} }) expect(response.status).to eq(400), invalid_status_detail end context 'resources forbidden' do let!(:bulk_create_attributes_with_forbidden_resource) do { data: [ { data: { type: resource_type, id: first_id, attributes: correct_attributes }.merge(relationships: relationships) }, { data: { type: resource_type, id: second_id, attributes: correct_attributes }.merge(relationships: found_forbidden_relationships) }, { data: { type: resource_type, id: third_id, attributes: correct_attributes }.merge(relationships: relationships) } ] } end let!(:found_forbidden_relationships) do defined?(forbidden_relationships) ? forbidden_relationships : default_forbidden_relationships end let!(:default_forbidden_relationships) do { account_list: { data: { id: create(:account_list).id, type: 'account_lists' } } } end it 'does not create resources for users that are not signed in' do api_logout expect do post :create end.not_to change { resource.class.count } expect(response.status).to eq(401), invalid_status_detail end it "returns a 403 when users tries to associate resource to an account list that doesn't belong to them" do expect do post :create, bulk_create_attributes_with_forbidden_resource end.not_to change { resource.class.count } expect(response.status).to eq(403), invalid_status_detail end end end end
chuckmersereau/api_practice
app/services/account_list/from_profile_linker.rb
class AccountList::FromProfileLinker def initialize(profile, org_account) @profile = profile @org_account = org_account end def link_account_list! # look for an existing account list with the same designation numbers in it # otherwise create a new account list for this profile account_list = account_from_designation_numbers || AccountList.find_or_create_by!(name: profile.name, creator_id: user.id) add_designations(account_list) add_user(account_list) end private attr_reader :profile, :org_account delegate :user, to: :org_account def account_from_designation_numbers designation_numbers = profile.designation_accounts.map(&:designation_number) AccountList::FromDesignationsFinder .new(designation_numbers, org_account.organization_id) .account_list end def add_designations(account_list) profile.designation_accounts.each do |da| next if account_list.designation_accounts.include?(da) account_list.designation_accounts << da end end def add_user(account_list) account_list.users << user unless account_list.users.include?(user) profile.update(account_list_id: account_list.id) end end
chuckmersereau/api_practice
app/serializers/weekly_serializer.rb
<reponame>chuckmersereau/api_practice class WeeklySerializer < ApplicationSerializer attributes :id, :answer, :question_id, :sid end
chuckmersereau/api_practice
db/migrate/20170420161008_add_received_not_processed_to_pledges.rb
class AddReceivedNotProcessedToPledges < ActiveRecord::Migration def change add_column :pledges, :received_not_processed, :boolean end end
chuckmersereau/api_practice
app/workers/admin/fix_worker.rb
class Admin::FixWorker include Sidekiq::Worker sidekiq_options queue: :api_admin_fix_worker, unique: :until_executed, retry: false def perform(fix_name, record_class, id) record = record_class.constantize.find(id) "Admin::#{fix_name.camelize}Fix".constantize.new(record).fix end end
chuckmersereau/api_practice
app/controllers/api/v2/tools/analytics_controller.rb
class Api::V2::Tools::AnalyticsController < Api::V2Controller def show load_analytics authorize_analytics render_analytics end private def authorize_analytics account_lists.each do |account_list| authorize account_list, :show? end end def load_analytics @analytics ||= ::Tools::Analytics.new(analytics_params) end def analytics_params { account_lists: account_lists } end def permitted_filters [:account_list_id] end def render_analytics render json: @analytics, fields: field_params, include: include_params end end
chuckmersereau/api_practice
spec/controllers/api/v2/contacts/people/phones_controller_spec.rb
require 'rails_helper' RSpec.describe Api::V2::Contacts::People::PhonesController, type: :controller do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) } let(:person) { create(:person, contacts: [contact]) } let!(:resource) { create(:phone_number, person: person) } let!(:second_resource) { create(:phone_number, person: person) } let(:id) { resource.id } let(:parent_param) { { contact_id: contact.id, person_id: person.id } } let(:correct_attributes) { { location: 'home', number: '+11134567890', country_code: '1', primary: true } } let(:incorrect_attributes) { { number: nil } } let(:factory_type) { :phone_number } include_examples 'show_examples' include_examples 'update_examples' include_examples 'create_examples' include_examples 'destroy_examples' include_examples 'index_examples' describe '#index authorization' do it 'does not show resources for person that contact does not own' do api_login(user) get :index, parent_param.merge(person_id: create(:person).id) expect(response.status).to eq(404) end end end
chuckmersereau/api_practice
app/services/donation_imports/siebel/profile_importer.rb
class DonationImports::Siebel # This class imports designation profiles associated to a Siebel organization account. class ProfileImporter attr_accessor :siebel_import, :organization, :organization_account def initialize(siebel_import) @siebel_import = siebel_import @organization = siebel_import.organization @organization_account = siebel_import.organization_account end def import_profiles siebel_profiles.each do |siebel_profile| designation_profile = find_or_create_designation_profile(siebel_profile) add_included_designation_accounts(designation_profile, siebel_profile) import_profile_balance(designation_profile) link_account_list(designation_profile) unless designation_profile.account_list end true end private def siebel_profiles @siebel_profiles ||= fetch_siebel_profiles end def fetch_siebel_profiles return try_to_get_siebel_profiles if organization_account_is_valid? organization_account.destroy [] end def try_to_get_siebel_profiles set_relay_id_from_key_account unless organization_account.remote_id Retryable.retryable on: RestClient::InternalServerError do SiebelDonations::Profile.find(ssoGuid: organization_account.remote_id) end end def set_relay_id_from_key_account organization_account.update(remote_id: organization_account.user.key_accounts.pluck(:relay_remote_id).first) organization_account.reload end def organization_account_is_valid? organization_account.user.key_accounts.any? end def link_account_list(designation_profile) AccountList::FromProfileLinker.new(designation_profile, organization_account).link_account_list! end def add_included_designation_accounts(designation_profile, siebel_profile) siebel_profile.designations.each do |designation| find_or_create_designation_account(designation.number, designation_profile, name: designation.description, staff_account_id: designation.staff_account_id, chartfield: designation.chartfield) end end def find_or_create_designation_profile(siebel_profile) organization.designation_profiles.where(user_id: organization_account.person_id, code: siebel_profile.id) .first_or_create(name: siebel_profile.name) end def import_profile_balance(designation_profile) balance_total = designation_profile.designation_accounts.to_a.sum do |designation_account| balance_amount_from_designation_account(designation_account).to_f end designation_profile.update!(balance: balance_total, balance_updated_at: Time.now) end def balance_amount_from_designation_account(designation_account) return unless designation_account.staff_account_id balance_object = SiebelDonations::Balance.find(employee_ids: designation_account.staff_account_id).first balance_amount = balance_object.primary if designation_account.active? designation_account.update!(balance: balance_amount.to_f, balance_updated_at: Time.now) balance_amount end def find_or_create_designation_account(designation_number, designation_profile, extra_attributes = {}) designation_account = find_or_create_designation_account_by_number(designation_number) contains_des_account = designation_profile.designation_accounts.include?(designation_account) designation_profile.designation_accounts << designation_account unless contains_des_account designation_account.update_attributes!(extra_attributes) if extra_attributes.present? designation_account.reload end def find_or_create_designation_account_by_number(designation_number) organization.designation_accounts.where(designation_number: designation_number).first_or_create end end end
chuckmersereau/api_practice
app/concerns/between_scopeable.rb
module BetweenScopeable extend ActiveSupport::Concern module ClassMethods def between_scopes_for(attribute) singleton_class.instance_eval do define_method "with_#{attribute}_this_week" do |start_date = Date.current.beginning_of_week| end_date = start_date + 6.days if start_date.month == end_date.month send("with_#{attribute}_in_same_month_between_two_dates", start_date, end_date) else send("with_#{attribute}_in_neighboring_months_between_two_dates", start_date, end_date) end end define_method "with_#{attribute}_in_same_month_between_two_dates" do |start_date, end_date| between_scopeable_validate_date_order(start_date, end_date) between_scopeable_validate_same_month(start_date, end_date) sql = between_scopeable_same_month_sql(attribute) query_arguments = { month: start_date.month, start_day: start_date.day, end_day: end_date.day } where(sql, query_arguments) end define_method "with_#{attribute}_in_neighboring_months_between_two_dates" do |start_date, end_date| between_scopeable_validate_date_order(start_date, end_date) between_scopeable_validate_neighboring_months(start_date, end_date) sql = between_scopeable_neighboring_months_sql(attribute) query_arguments = { start_day: start_date.day, start_month: start_date.month, end_day: end_date.day, end_month: end_date.month } where(sql, query_arguments) end end end private def between_scopeable_neighboring_months_sql(attribute) <<~SQL ( #{attribute}_month = :start_month AND #{attribute}_day >= :start_day ) OR ( #{attribute}_month = :end_month AND #{attribute}_day <= :end_day ) SQL end def between_scopeable_same_month_sql(attribute) <<~SQL #{attribute}_month = :month AND #{attribute}_day BETWEEN :start_day AND :end_day SQL end def between_scopeable_validate_date_order(start_date, end_date) raise ArgumentError, 'start_date cannot take place after end_date' if start_date > end_date end def between_scopeable_validate_neighboring_months(start_date, end_date) return if start_date.month == 12 && end_date.month == 1 return if (end_date.month > start_date.month) && (end_date.month - start_date.month <= 1) raise ArgumentError, 'dates cannot be more than one month apart' end def between_scopeable_validate_same_month(start_date, end_date) raise ArgumentError, 'dates must be in the same month' if start_date.month != end_date.month end end end
chuckmersereau/api_practice
app/workers/employee_csv_import_worker.rb
<reponame>chuckmersereau/api_practice<filename>app/workers/employee_csv_import_worker.rb class EmployeeCsvImportWorker include Sidekiq::Worker sidekiq_options unique: :until_executed, queue: :api_import, retry: 1 def perform(cas_attributes) cas_attributes.deep_symbolize_keys! UserFromCasService.find_or_create(cas_attributes) end end
chuckmersereau/api_practice
spec/models/notification_type/missing_contact_info_spec.rb
require 'rails_helper' describe NotificationType::MissingContactInfo do subject { NotificationType::MissingContactInfo.create } let(:contact) { create(:contact) } let(:account_list) { contact.account_list } before do allow(subject).to receive(:missing_info_filter).with([contact]) { [contact] } end describe '#check' do it 'creates notifications for filtered missing info contacts' do notifications = subject.check(account_list) expect(notifications.size).to eq(1) notification = notifications.first expect(notification.new_record?).to be_falsey expect(notification.event_date).to be_present expect(notification.contact).to eq(contact) expect(notification.notification_type_id).to eq(subject.id) end it 'does not create notifications if no filtered contacts' do allow(subject).to receive(:missing_info_filter).with([contact]) { [] } expect do expect(subject.check(account_list)).to eq([]) end.to_not change(Notification, :count) end it 'does not create a notification a second time' do expect { subject.check(account_list) }.to change(Notification, :count).by(1) expect { subject.check(account_list) }.to_not change(Notification, :count) end it 'does create a notification if the last one was over a year ago' do notification = subject.check(account_list).first notification.update(event_date: 2.years.ago) expect { subject.check(account_list) }.to change(Notification, :count).by(1) end end end
chuckmersereau/api_practice
app/services/coaching/contact/filter/base.rb
<reponame>chuckmersereau/api_practice module Coaching::Contact class Filter::Base < ApplicationFilter end end
chuckmersereau/api_practice
db/migrate/20130607153639_add_account_list_id_to_designation_profile.rb
<filename>db/migrate/20130607153639_add_account_list_id_to_designation_profile.rb class AddAccountListIdToDesignationProfile < ActiveRecord::Migration def change add_column :designation_profiles, :account_list_id, :integer add_index :designation_profiles, :account_list_id AccountList.find_each do |al| if al.designation_profile al.designation_profile.update_column(:account_list_id, al.id) end end end end
chuckmersereau/api_practice
app/services/mail_chimp/campaign_logger.rb
<reponame>chuckmersereau/api_practice # This class is used to log MPDX tasks when a MailChimp campaign email is sent. class MailChimp::CampaignLogger IGNORED_TYPES = %w(automation).freeze attr_reader :mail_chimp_account, :account_list, :gibbon def initialize(mail_chimp_account) @mail_chimp_account = mail_chimp_account @account_list = mail_chimp_account.account_list end def log_sent_campaign(campaign_id, subject) @campaign_id = campaign_id return unless mail_chimp_account.auto_log_campaigns? return if ignored_campaign_type? campaign_send_time = fetch_campaign_send_time log_sent_campaign!(subject, campaign_send_time) rescue Gibbon::MailChimpError => error return deactivate_account if invalid_key?(error) raise unless campaign_not_completely_sent?(error) || campaign_under_review?(error) raise LowerRetryWorker::RetryJobButNoRollbarError if running_for_less_than_hour?(campaign_send_time) end private def ignored_campaign_type? IGNORED_TYPES.include? fetch_campaign_fields['type'] end def log_sent_campaign!(subject, campaign_send_time) update_prayer_letter_last_sent(campaign_send_time) sent_emails = mail_chimp_reports.map do |mail_chimp_report| mail_chimp_report[:email_address] end contacts_with_sent_emails(sent_emails).find_each do |contact| create_campaign_activity(contact, subject, campaign_send_time) end end def update_prayer_letter_last_sent(campaign_send_time) # compare as int in-case mail_chimp_account.prayer_letter_last_sent is nil return unless mail_chimp_account.prayer_letter_last_sent.to_i < campaign_send_time.to_i mail_chimp_account.update(prayer_letter_last_sent: campaign_send_time) end def gibbon @gibbon ||= MailChimp::GibbonWrapper.new(mail_chimp_account).gibbon end def contacts_with_sent_emails(sent_emails) account_list.contacts .joins(people: :primary_email_address) .where(email_addresses: { email: sent_emails }) end def mail_chimp_reports gibbon.reports(@campaign_id) .sent_to .retrieve(params: { count: 15_000 }).with_indifferent_access[:sent_to] end def invalid_key?(error) MailChimp::ConnectionHandler::INVALID_KEY_ERROR_MESSAGES.any? do |error_part| error.message.include? error_part end end def campaign_not_completely_sent?(error) # Campaign stats are not available until the campaign has been completely # sent. (code 301) error.message.include?('code 301') end def campaign_under_review?(error) error.status_code == 403 && error.title == 'Compliance Related' end def running_for_less_than_hour?(campaign_send_time) # keep retrying the job for one hour then give up. (Time.now.utc - campaign_send_time) < 1.hour end def fetch_campaign_send_time Time.parse(fetch_campaign_fields['send_time'] + ' UTC') end def fetch_campaign_fields @campaign_fields ||= gibbon.campaigns(@campaign_id).retrieve(params: { fields: 'send_time,type' }) end def create_campaign_activity(contact, subject, campaign_send_time) activity_attributes = { account_list: account_list, activity_type: 'Newsletter - Email', start_at: campaign_send_time, completed_at: campaign_send_time, completed: true, result: 'Completed', source: 'mailchimp', subject: "MailChimp: #{subject}", type: 'Task' } contact.tasks.find_or_create_by(activity_attributes) end def deactivate_account mail_chimp_account.update_column(:active, false) end end
chuckmersereau/api_practice
db/migrate/20120523190907_change_address_type_column.rb
<gh_stars>0 class ChangeAddressTypeColumn < ActiveRecord::Migration def change remove_column :addresses, :address_type end end
chuckmersereau/api_practice
spec/models/notification_preference_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe NotificationPreference do end
chuckmersereau/api_practice
spec/services/social_item_spec.rb
require 'rails_helper' describe SocialItem do end
chuckmersereau/api_practice
spec/services/contact/filter/appeal_spec.rb
require 'rails_helper' RSpec.describe Contact::Filter::Appeal do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:appeal_1) { create(:appeal, account_list_id: account_list.id) } let!(:contact_one) { create(:contact, account_list_id: account_list.id, no_appeals: true) } let!(:contact_two) { create(:contact, account_list_id: account_list.id, no_appeals: true) } let!(:contact_three) { create(:contact, account_list_id: account_list.id, no_appeals: nil) } let!(:contact_four) { create(:contact, account_list_id: account_list.id, no_appeals: false) } before do AppealContact.create! contact: contact_one, appeal: appeal_1 end describe '#config' do it 'returns expected config' do expect(described_class.config([account_list])).to include(multiple: true, name: :appeal, options: [{ name: '-- Any --', id: '', placeholder: 'None' }, { name: '-- Do not ask --', id: 'no_appeals' }, { name: appeal_1.name, id: appeal_1.id }], parent: nil, title: 'Appeal', 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, { appeal: {} }, nil)).to eq(nil) expect(described_class.query(contacts, { appeal: [] }, nil)).to eq(nil) expect(described_class.query(contacts, { appeal: [''] }, nil)).to eq(nil) end end context 'filter with no appeals' do it 'returns only contacts with no_appeals set to true' do expect(described_class.query(contacts, { appeal: 'no_appeals' }, nil).to_a).to match_array [contact_one, contact_two] end it 'returns only contacts with no_appeals set to true and who are part of the appeal' do expect(described_class.query(contacts, { appeal: "#{appeal_1.id}, no_appeals" }, nil).to_a).to eq [contact_one] end end context 'filter by appeals' do it 'returns only contacts associated to the selected appeal' do expect(described_class.query(contacts, { appeal: appeal_1.id }, nil).to_a).to eq [contact_one] end end end end
chuckmersereau/api_practice
app/models/concerns/deletable.rb
<filename>app/models/concerns/deletable.rb # frozen_string_literal: true module Deletable extend ActiveSupport::Concern included do attr_accessor :deleted_by # disabling because we want to retain the foreign_key id, but I'm not # yet sure what should be passed to +dependent+ to retain the default # setting. I removed the dependent for now, until I figure that. has_many :deleted_records, as: :deletable # rubocop:disable Rails/HasManyOrHasOneDependent before_destroy :save_to_deleted_records_table end private def save_to_deleted_records_table deleted_records.create!( deleted_by: deleted_by, deleted_at: ::Time.current, deleted_from_id: deleted_from.id, deleted_from_type: deleted_from.class.to_s ) end end
chuckmersereau/api_practice
app/services/tnt_import/donor_accounts_import.rb
class TntImport::DonorAccountsImport # Donation Services seems to pad donor accounts with zeros up to length 9. TntMPD does not though. DONOR_NUMBER_NORMAL_LEN = 9 def initialize(xml, orgs_by_tnt_id) @xml = xml @xml_tables = xml.tables @orgs_by_tnt_id = orgs_by_tnt_id || {} end def import return {} unless @xml_tables['Donor'].present? donors_by_tnt_contact_id = {} @xml_tables['Donor'].each do |row| contact_tnt_id = row['ContactID'] # Name the donor account after the contact FileAs name = contact_rows_by_tnt_id[contact_tnt_id]['FileAs'] donor = add_or_update_donor(row, name) donors_by_tnt_contact_id[contact_tnt_id] ||= [] donors_by_tnt_contact_id[contact_tnt_id] << donor if donor.present? end donors_by_tnt_contact_id end def add_or_update_donor(row, name) org = @orgs_by_tnt_id[row['OrganizationID']] return unless org.present? account_number = row['OrgDonorCode'] da = find_donor_account(org, account_number) if da # Donor accounts for non-Cru orgs could have nil names so update with the name from tnt da.update(name: name) unless da.name? da else create_donor_account(org, account_number, row, name) end end def find_donor_account(org, account_number) padded_account_number = account_number.rjust(DONOR_NUMBER_NORMAL_LEN, '0') org.donor_accounts.find_by(account_number: [account_number, padded_account_number]) end def create_donor_account(org, account_number, row, name) da = org.donor_accounts.new(account_number: account_number, name: name) add_address(da, row) da.save! da end def add_address(donor_account, row) donor_account.addresses_attributes = [ { street: row['StreetAddress'], city: row['City'], state: row['State'], postal_code: row['PostalCode'], country: tnt_country(row['CountryID']), primary_mailing_address: true, source: TntImport::SOURCE, start_date: Date.current } ] end def tnt_country(tnt_id) country = tnt_countries[tnt_id] country == 'United States of America' ? 'United States' : country end def tnt_countries @tnt_countries ||= TntImport::CountriesParser.countries_by_tnt_id(@xml) end def contact_rows_by_tnt_id @contact_rows_by_tnt_id ||= Hash[@xml_tables['Contact'].map do |contact_row| [contact_row['id'], contact_row] end.to_a] end end
chuckmersereau/api_practice
app/preloaders/application_preloader/field_associations_fetcher.rb
class ApplicationPreloader class FieldAssociationsFetcher attr_reader :field_association_mapping, :serializer_class def initialize(field_association_mapping, serializer_class) @field_association_mapping = field_association_mapping @serializer_class = serializer_class end def fetch_field_associations(field_params) return all_associations unless field_params field_association_mapping.map do |field_name, association| association if field_params.include?(field_name.to_s) end.compact end private def all_associations serializer_class._reflections.keys + all_field_associations end def all_field_associations field_association_mapping.values end end end
chuckmersereau/api_practice
db/migrate/20171002215149_change_suggested_amount_on_recommendations.rb
<filename>db/migrate/20171002215149_change_suggested_amount_on_recommendations.rb class ChangeSuggestedAmountOnRecommendations < ActiveRecord::Migration def change remove_column :donation_amount_recommendations, :suggested_pledge_amount_min remove_column :donation_amount_recommendations, :suggested_special_amount_min rename_column :donation_amount_recommendations, :suggested_pledge_amount_max, :suggested_pledge_amount rename_column :donation_amount_recommendations, :suggested_special_amount_max, :suggested_special_amount end end
chuckmersereau/api_practice
db/migrate/20120313144846_add_account_id_to_designation_account.rb
<gh_stars>0 class AddAccountIdToDesignationAccount < ActiveRecord::Migration def up add_column :designation_accounts, :account_id, :integer rename_column :designation_accounts, :account_number, :designation_number end def down rename_column :designation_accounts, :designation_number, :account_number remove_column :designation_accounts, :account_id end end
chuckmersereau/api_practice
app/services/donation_reports/donations_converter.rb
class DonationReports::DonationsConverter def initialize(donations:, account_list:) @donations = donations @account_list = account_list end def convert_amounts donation_currencies.each do |currency| CurrencyRate.cache_rates_for_dates( currency_code: currency, from_date: min_donation_date, to_date: max_donation_date ) end @donations.each(&method(:convert_donation)) end private def convert_donation(donation) donation.converted_amount = CurrencyRate.convert_on_date( amount: donation.amount, from: donation.currency, to: total_currency, date: donation.donation_date ) donation.converted_currency = total_currency end def total_currency @total_currency ||= @account_list.salary_currency_or_default end def donation_currencies @donations.map(&:currency).uniq end def min_donation_date @min_donation_date ||= donation_dates.min end def max_donation_date @min_donation_date ||= donation_dates.max end def donation_dates @donation_dates ||= @donations.map(&:donation_date) end end
chuckmersereau/api_practice
db/migrate/20170109201920_create_person_options.rb
class CreatePersonOptions < ActiveRecord::Migration def up unless table_exists?(:person_options) create_table :person_options do |t| t.string :key, null: false t.string :value t.integer :user_id t.uuid :uuid, null: false, default: 'uuid_generate_v4()' t.timestamps null: false end add_index :person_options, [:key, :user_id], unique: true add_index :person_options, :uuid, unique: true end end def down if table_exists?(:person_options) drop_table(:person_options) end end end
chuckmersereau/api_practice
app/services/expected_totals_report/possible_donations.rb
<filename>app/services/expected_totals_report/possible_donations.rb class ExpectedTotalsReport::PossibleDonations < ExpectedTotalsReport::ReceivedDonations # Check back 3 years + 2 months of donation history to feed to the # LikelyDonation calculation. RECENT_DONATIONS_MONTHS_BACK = 12 * 3 + 2 def donation_rows contacts_with_donations.map(&method(:row_for_contact)).compact end private def row_for_contact(contact) received_this_month, likely_more = received_and_likely_more_amounts(contact) if likely_more > 0.0 return { type: 'likely', contact: contact, donation_amount: likely_more, donation_currency: contact.pledge_currency } end return if received_this_month > 0.0 { type: 'unlikely', contact: contact, donation_amount: contact.pledge_amount, donation_currency: contact.pledge_currency } end def received_and_likely_more_amounts(contact) likely_donation = ExpectedTotalsReport::LikelyDonation.new( contact: contact, recent_donations: contact.loaded_donations, date_in_month: Date.current ) [likely_donation.received_this_month, likely_donation.likely_more] end def contacts_with_donations Contact::DonationsEagerLoader.new( account_list: account_list, donations_scoper: lambda do |donations| donations_scope(donations).where('donation_date > ?', recent_donations_cutoff_date) end, contacts_scoper: lambda do |contacts| contacts_scope(contacts).financial_partners.where('pledge_amount > 0') end ).contacts_with_donations end def recent_donations_cutoff_date RECENT_DONATIONS_MONTHS_BACK.months.ago.to_date.beginning_of_month end def contacts_scope(contacts) return contacts unless filter_params return contacts unless filter_params[:designation_account_id] || filter_params[:donor_account_id] contacts = contacts.includes(donor_accounts: :donations).where.not(donations: { id: nil }) if filter_params[:designation_account_id] contacts = contacts.where( donations: { designation_account_id: filter_params[:designation_account_id] } ) end if filter_params[:donor_account_id] contacts = contacts.where( donations: { donor_account_id: filter_params[:donor_account_id] } ) end contacts end end
chuckmersereau/api_practice
app/controllers/api/v2/tasks/tags/bulk_controller.rb
class Api::V2::Tasks::Tags::BulkController < Api::V2::BulkController include BulkTaggable resource_type :tags def create load_tasks authorize_tasks add_tags_to_tasks render_tasks end def destroy load_tags authorize_tags destroy_tags end private def add_tags_to_tasks @tasks.each do |task| task.tag_list.add(*tag_names) task.save end end def authorize_tags account_lists.each { |account_list| authorize(account_list, :show?) } end def authorize_tasks @tasks.each { |task| authorize(task, :update?) } end def destroy_tags @tags.destroy_all head :no_content end def load_tags @tags ||= ActsAsTaggableOn::Tagging.joins(:tag) .where(taggable_type: 'Activity', taggable_id: taggable_ids, tags: { name: tag_names }) end def load_tasks @tasks ||= tasks_scope end def permitted_filters [:account_list_id, :task_ids] end def render_tasks render json: BulkResourceSerializer.new(resources: @tasks), include: include_params, fields: field_params end def task_ids filter_params[:task_ids].to_s.split(',').map(&:strip) end def tasks_query { account_list: account_lists }.tap do |query| query[:id] = task_ids if task_ids.present? end end def tasks_scope @tasks_scope ||= scope_exists!(Task.where(tasks_query)) end alias tags_scope tasks_scope end
chuckmersereau/api_practice
spec/factories/account_list_entries.rb
FactoryBot.define do factory :account_list_entry do account_list designation_account end end
chuckmersereau/api_practice
app/serializers/reports/year_donations_serializer.rb
<reponame>chuckmersereau/api_practice<filename>app/serializers/reports/year_donations_serializer.rb class Reports::YearDonationsSerializer < ServiceSerializer delegate :account_list, :donation_infos, :donor_infos, to: :object belongs_to :account_list attributes :donor_infos, :donation_infos end
chuckmersereau/api_practice
lib/sidekiq_monitor.rb
<reponame>chuckmersereau/api_practice<filename>lib/sidekiq_monitor.rb class SidekiqMonitor class << self def queue_latency_too_high? default_queue_latency = Sidekiq::Queue.new.latency warn_threshold = ENV.fetch('SIDEKIQ_WARN_DEFAULT_QUEUE_LATENCY').to_i default_queue_latency > warn_threshold end end end
chuckmersereau/api_practice
app/models/person/google_account.rb
require 'signet/oauth_2/client' class Person::GoogleAccount < ApplicationRecord include Person::Account has_many :google_integrations, foreign_key: :google_account_id, dependent: :destroy has_many :google_emails, foreign_key: :google_account_id has_many :google_contacts, foreign_key: :google_account_id PERMITTED_ATTRIBUTES = [:created_at, :email, :overwrite, :person_id, :primary, :remote_id, :updated_at, :updated_in_db_at, :id].freeze def self.find_or_create_from_auth(auth_hash, person) Rails.logger.debug(auth_hash) relation_scope = person.google_accounts creds = auth_hash.credentials remote_id = auth_hash.uid expires_at = creds.expires ? Time.at(creds.expires_at) : nil attributes = { remote_id: remote_id, token: creds.token, refresh_token: creds.refresh_token, expires_at: expires_at, email: auth_hash.info.email, valid_token: true } find_or_create_person_account( person: person, attributes: attributes, relation_scope: relation_scope ) end def self.create_user_from_auth(_auth_hash) raise Person::Account::NoSessionError, 'Somehow a user without an account/session is trying to sign in using google' end def google_integration(account_list_id) google_integrations.find_by(account_list_id: account_list_id) end def to_s email end def self.one_per_user? false end def token_expired? (expires_at || Time.current) <= Time.current ? !refresh_token! : false end def token_failure? notified_failure == true end def contacts @contacts ||= contacts_api_user.contacts end def contact_groups @contact_groups ||= Person::GoogleAccount::ContactGroup.from_groups(contacts_api_user.groups) rescue Person::GoogleAccount::MissingRefreshToken [] end def contacts_for_group(group_id) GoogleContactsApi::Group.new({ 'id' => { '$t' => group_id } }, nil, contacts_api_user.api).contacts end def contacts_api_user raise Person::GoogleAccount::MissingRefreshToken if token_expired? unless @contact_api_user client = OAuth2::Client.new(ENV.fetch('GOOGLE_KEY'), ENV.fetch('GOOGLE_SECRET')) oath_token = OAuth2::AccessToken.new(client, token) @contact_api_user = GoogleContactsApi::User.new(oath_token) end @contact_api_user end def authorization return false if token_expired? @authorization ||= Signet::OAuth2::Client.new(authorization_uri: 'https://accounts.google.com/o/oauth2/auth', token_credential_uri: 'https://www.googleapis.com/oauth2/v3/token', client_id: ENV.fetch('GOOGLE_KEY'), client_secret: ENV.fetch('GOOGLE_SECRET'), access_token: token, refresh_token: refresh_token) end def refresh_token! if refresh_token.blank? needs_refresh return false end # Refresh auth token from google_oauth2. params = { client_id: ENV.fetch('GOOGLE_KEY'), client_secret: ENV.fetch('GOOGLE_SECRET'), refresh_token: refresh_token, grant_type: 'refresh_token' } request_options = ['https://accounts.google.com/o/oauth2/token', params, content_type: 'application/x-www-form-urlencoded'] RestClient.post(*request_options) do |response, _request, _result, &_block| json = JSON.parse(response) if response.code == 200 self.token = json['access_token'] self.expires_at = 59.minutes.from_now self.notified_failure = false save else case json['error'] when 'invalid_grant', 'invalid_client' needs_refresh else Rollbar.error(response.inspect) end return false end end end def needs_refresh google_integrations.each do |integration| integration.update_columns(calendar_integration: false, email_integration: false, contacts_integration: false) # no callbacks AccountMailer.delay.google_account_refresh(person, integration) unless notified_failure update(notified_failure: true) end end class MissingRefreshToken < StandardError end end
chuckmersereau/api_practice
config/initializers/spring.rb
# This prevents the "Running via Spring preloader messages" Spring.quiet = true if Rails.env.test? || Rails.env.development?
chuckmersereau/api_practice
spec/workers/google_sync_data_worker_spec.rb
require 'rails_helper' describe GoogleSyncDataWorker do let!(:google_integration) { create(:google_integration) } it 'tells the GoogleIntegration to sync_data' do google_integration_double = instance_double('GoogleIntegration') expect(GoogleIntegration).to receive(:find).with(google_integration.id).and_return(google_integration_double) expect(google_integration_double).to receive(:sync_data).with('email') GoogleSyncDataWorker.new.perform(google_integration.id, 'email') end it 'returns without error if the GoogleIntegration is not found' do expect(GoogleIntegration).to receive(:find).with(google_integration.id).and_raise(ActiveRecord::RecordNotFound) expect(GoogleSyncDataWorker.new.perform(google_integration.id, 'email')).to eq(nil) end end
chuckmersereau/api_practice
spec/lib/json_api_service/object_store_spec.rb
<filename>spec/lib/json_api_service/object_store_spec.rb<gh_stars>0 require 'spec_helper' require 'json_api_service/object_store' module JsonApiService RSpec.describe ObjectStore do it 'initializes with empty items' do store = ObjectStore.new expect(store.items).to be_empty end end end
chuckmersereau/api_practice
spec/workers/queue_contact_dup_merge_batch_worker_spec.rb
require 'rails_helper' describe QueueContactDupMergeBatchWorker do let(:account_list) { create(:account_list) } let(:designation_account) { create(:designation_account) } let(:donor_account) { create(:donor_account) } let(:contact_one) { create(:contact, name: 'Joe', account_list: account_list) } let(:contact_two) { create(:contact, name: 'Joe', account_list: account_list) } let(:contact_three) { create(:contact, name: 'Jane', account_list: account_list) } let(:contact_four) { create(:contact, name: 'Jane', account_list: account_list) } before do Sidekiq::Testing.inline! account_list.designation_accounts << designation_account contact_one.donor_accounts << donor_account contact_two.donor_accounts << donor_account contact_three.donor_accounts << donor_account contact_four.donor_accounts << donor_account end it 'merges contact duplicates' do expect do QueueContactDupMergeBatchWorker.new.perform(account_list.id, 0) end.to change { account_list.reload.contacts.count }.from(4).to(2) end it 'does not queue duplicate jobs' do Sidekiq::Testing.fake! bid = QueueContactDupMergeBatchWorker.new.perform(account_list.id, 0) expect(Sidekiq::Batch::Status.new(bid).total).to eq(2) end it 'returns the batch id' do expect(QueueContactDupMergeBatchWorker.new.perform(account_list.id, 0)).to be_a(String) end it 'sets the batch description' do batch_status = Sidekiq::Batch::Status.new(QueueContactDupMergeBatchWorker.new.perform(account_list.id, 0)) expected_description = "Merge duplicate Contacts for AccountList #{account_list.id} since 1970-01-01 00:00:00 UTC" expect(batch_status.description).to eq(expected_description) end it 'only merges contacts updated since the given time' do contact_three.update_column(:updated_at, 2.hours.ago) contact_four.update_column(:updated_at, 2.hours.ago) expect do QueueContactDupMergeBatchWorker.new.perform(account_list.id, 1.hour.ago) end.to change { account_list.reload.contacts.count }.from(4).to(3) end context 'account_list does not exist' do it 'returns successfully' do expect { QueueContactDupMergeBatchWorker.new.perform(1234, 0) }.to_not raise_error end end end
chuckmersereau/api_practice
app/services/mail_chimp/importer.rb
class MailChimp::Importer attr_reader :mail_chimp_account, :account_list, :gibbon_wrapper def initialize(mail_chimp_account) @mail_chimp_account = mail_chimp_account @account_list = mail_chimp_account.account_list @gibbon_wrapper = MailChimp::GibbonWrapper.new(mail_chimp_account) end def import_all_members MailChimp::ConnectionHandler.new(mail_chimp_account) .call_mail_chimp(self, :import_all_members!) end def import_members_by_email(member_emails) MailChimp::ConnectionHandler.new(mail_chimp_account) .call_mail_chimp(self, :import_members_by_email!, member_emails) end def import_all_members! # all_emails_to_import = fetch_all_emails_to_import # import_members_by_email(all_emails_to_import) end def import_members_by_email!(member_emails) # subscribed_members = list_of_members_info(member_emails) # formatted_subscribed_members = subscribed_members.map(&method(:format_member_info)) # import_members(formatted_subscribed_members) end private def email_to_name(email) email[/[^@]+/].split(/[.\-_]/).map(&:capitalize).join(' ') end def list_of_members_info(member_emails) gibbon_wrapper.list_member_info(mail_chimp_account.primary_list_id, member_emails) .map(&:with_indifferent_access) end def format_member_info(member_info) { email: member_info['email_address'], first_name: nil_if_hex_chars(member_info['merge_fields']['FNAME']), last_name: nil_if_hex_chars(member_info['merge_fields']['LNAME']), greeting: nil_if_hex_chars(member_info['merge_fields']['GREETING']), groupings: member_info['merge_fields']['GROUPINGS'], status: member_info['status'].downcase, unsubscribe_reason: member_info['unsubscribe_reason'] } end # Some users have unexpected random hex values in their mailchimp accounts: # https://secure.helpscout.net/conversation/207704672/57384/?folderId=378967 # I'm not sure as to the cause yet, but one simple thing we can do now is to # recognize the pattern (string of 12 hex chars) and then in that case don't # use the name/greeting field from mailchimp in the `format_member_info`. def nil_if_hex_chars(name) name =~ /[0-9a-f]{12}/ ? nil : name end def fetch_all_emails_to_import gibbon_wrapper.list_emails(mail_chimp_account.primary_list_id) - mail_chimp_account.newsletter_emails end def import_members(member_infos) matching_people_hash = Matcher.new(mail_chimp_account).find_matching_people(member_infos) import_matched(matching_people_hash) import_unmatched(member_infos, matching_people_hash) end def person_by_name_with_no_email(first_name, last_name) person = account_list.people.find_by(first_name: first_name, last_name: last_name) person if person.try(:primary_email_address).nil? end def import_matched(matching_people_hash) matching_people_hash.each do |person_id, member_info| add_or_remove_person_from_newsletter(Person.find(person_id), member_info) end end def import_unmatched(member_infos, matching_people_hash) member_infos_to_add = member_infos - matching_people_hash.values.map(&:symbolize_keys) member_infos_to_add.each do |member_info| add_or_remove_person_from_newsletter(create_person(member_info), member_info) end end def add_or_remove_person_from_newsletter(person, member_info) person.optout_enewsletter = person_opt_out_value(person, member_info) person.email = member_info[:email] person.save(validate: false) person.primary_email_address&.update(historic: true) if primary_email_address_should_be_made_historic?(member_info) add_or_remove_contact_from_newsletter(person.contact, member_info) end def primary_email_address_should_be_made_historic?(member_info) member_info[:status] == 'cleaned' end def person_opt_out_value(person, member_info) # We do not want to mark someone as opt-out if they were unsubscribed by the user or our system somehow. return person.optout_enewsletter if MailChimpMember.mpdx_unsubscribe?(member_info) member_info[:status] == 'unsubscribed' end def add_or_remove_contact_from_newsletter(contact, member_info) return if [nil, '', 'None'].include? contact.send_newsletter if member_info[:status] == 'unsubscribed' remove_from_newsletter_if_all_opt_out(contact) else contact.update(send_newsletter: (contact.send_newsletter == 'Physical' ? 'Both' : 'Email')) end end # it can be that only one of the people on a contact unsubscribes, # you would still want to keep the contact set to send newsletters def remove_from_newsletter_if_all_opt_out(contact) contact.update(send_newsletter: nil) if contact.send_newsletter != 'Physical' && contact.people.all?(&:optout_enewsletter) end def create_person(member) first_name = member[:first_name] || email_to_name(member[:email]) person = Person.create(first_name: first_name, last_name: member[:last_name], email: member[:email]) ContactPerson.create(person_id: person.id, contact_id: contact_from_member(member).id) person end def contact_from_member(member) grouping = member[:groupings].try(:first) || {} group_status = grouping['groups'].try(:split, ',').try(:first) acceptable_group_status = group_status.in?(Contact::ASSIGNABLE_STATUSES) ? group_status : 'Partner - Pray' account_list.contacts.create( name: contact_name(member[:first_name], member[:last_name], member[:email]), notes: 'Imported from MailChimp', greeting: member[:greeting], status: acceptable_group_status ) end def contact_name(first_name, last_name, email) if first_name.present? && last_name.present? "#{last_name}, #{first_name}" else email_to_name(email) end end def gibbon_list gibbon_wrapper.gibbon_list_object(mail_chimp_account.primary_list_id) end end
chuckmersereau/api_practice
spec/lib/batch_request_handler/middleware_spec.rb
require 'spec_helper' describe BatchRequestHandler::Middleware do let(:app) { -> (_env) { [200, { 'Content-Type' => 'text/plain' }, ['Hello World']] } } subject { described_class.new(app) } describe '#call' do context 'with a request to the batch endpoint' do let(:batched_requests) do [ { method: 'GET', path: '/api/v2/users' }, { method: 'GET', path: '/api/v2/constants' }, { method: 'POST', path: '/api/v2/contacts', body: '{}' } ] end let(:batch_request_json) { { requests: batched_requests } } let(:batch_request_body) { JSON.dump(batch_request_json) } let(:env) { Rack::MockRequest.env_for('/api/v2/batch', method: 'POST', input: batch_request_body) } it 'should call the app for each request in the batch' do expect(app).to receive(:call).exactly(batched_requests.size).times.and_call_original subject.call(env) end it 'should return a rack response' do response = subject.call(env) expect(response).to be_an(Array) expect(response.length).to eq(3) end it 'should serialize the batched responses to json' do response = subject.call(env) body = response.last[0] json = JSON.parse(body) expect(json).to be_an(Array) expect(json.length).to eq(batched_requests.length) end end context 'with a request for any other endpoint' do let(:env) { Rack::MockRequest.env_for('/api/v2/foo', method: 'GET') } it 'should fall through to the app' do expect(app).to receive(:call).once.with(env) subject.call(env) end end end end
chuckmersereau/api_practice
app/models/person/website.rb
<reponame>chuckmersereau/api_practice class Person::Website < ApplicationRecord belongs_to :person PERMITTED_ATTRIBUTES = [:created_at, :overwrite, :primary_url, :updated_at, :updated_in_db_at, :url, :id].freeze validates :url, presence: true end
chuckmersereau/api_practice
db/migrate/20170404210716_create_pledge_donations.rb
class CreatePledgeDonations < ActiveRecord::Migration def change create_table :pledge_donations do |t| t.integer :pledge_id t.integer :donation_id t.uuid :uuid, null: false, default: 'uuid_generate_v4()' t.timestamps null: false end add_index :pledge_donations, :pledge_id add_index :pledge_donations, :donation_id add_index :pledge_donations, :uuid end end
chuckmersereau/api_practice
db/migrate/20160302160145_add_versions_whodunnit_index.rb
class AddVersionsWhodunnitIndex < ActiveRecord::Migration self.disable_ddl_transaction! def change add_index :versions, :whodunnit, algorithm: :concurrently end end
chuckmersereau/api_practice
spec/controllers/api/v2/contacts_controller_spec.rb
require 'rails_helper' describe Api::V2::ContactsController, type: :controller do include_examples 'common_variables' 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(:contact) { create(:contact_with_person, status: 'Never Contacted', account_list: account_list) } let!(:second_contact) do create(:contact, status: 'Ask in Future', account_list: account_list, created_at: 1.week.from_now) end let!(:third_contact) do create(:contact, status: 'Ask in Future', account_list: account_list, created_at: 2.weeks.from_now) end let(:id) { contact.id } let!(:resource) { contact } let(:second_resource) { second_contact } let(:unpermitted_relationships) do { account_list: { data: { type: 'account_lists', id: create(:account_list).id } } } end let(:correct_attributes) do { name: 'Test Name' } end let(:incorrect_attributes) do { name: nil } end let(:reference_key) { :name } let(:reference_value) { correct_attributes[:name] } let(:incorrect_reference_value) { resource.send(reference_key) } let(:incorrect_attributes) { attributes_for(:contact, name: nil) } include_examples 'index_examples' describe 'sorting' do let!(:sorting_user) { create(:user_with_account) } let!(:sorting_account_list) { sorting_user.account_lists.first } let!(:contact_1) { create(:contact, name: '<NAME>', account_list: sorting_account_list) } let!(:contact_2) { create(:contact, name: '<NAME>', account_list: sorting_account_list) } let!(:contact_3) { create(:contact, name: '<NAME>', account_list: sorting_account_list) } before { api_login(sorting_user) } let(:response_body) { JSON.parse(response.body) } it 'sorts name field using C database collation' do get :index, sort: 'name' expect(response.status).to eq(200), invalid_status_detail expect(response_body['data'].map { |c| c['id'] }).to eq [contact_1.id, contact_3.id, contact_2.id] end end include_examples 'show_examples' include_examples 'create_examples' include_examples 'update_examples' include_examples 'destroy_examples' describe 'filtering' do before { api_login(user) } let(:filter_params) { { status: 'Never Contacted', reverse_status: true } } let(:filterer_class) { Contact::Filterer } before { Address.create(addressable: Contact.first).update(valid_values: false) } include_examples 'filtering examples', action: :index context 'account_list_id filter' do let!(:user) { create(:user_with_account) } let!(:account_list_two) { create(:account_list) } let!(:contact_two) { create(:contact, account_list: account_list_two) } before { user.account_lists << account_list_two } it 'filters results' do get :index, filter: { account_list_id: account_list_two.id } expect(response.status).to eq(200), invalid_status_detail expect(JSON.parse(response.body)['data'].length).to eq(1) end end context 'wildcard_search filter' do it 'does not blow up with date-like string' do expect { get :index, filter: { wildcard_search: '2011-11-01' } }.to_not raise_exception end end context 'with donation details filter' do it 'does not blow up' do expect { get :index, filter: { donation: 'one', donation_amount_range: { max: 1 } } }.to_not raise_exception end end end describe 'Creating a new contact with a default person' do it 'will create a default person' do api_login(user) full_correct_attributes[:data][:attributes][:create_default_person] = true expect do post :create, full_correct_attributes end.to change { Person.count }.by(1) end it 'will not create a default person' do api_login(user) full_correct_attributes[:data][:attributes][:create_default_person] = false expect do post :create, full_correct_attributes end.to change { Person.count }.by(0) end it 'will create a default person if create_default_person is nil' do api_login(user) full_correct_attributes[:data][:attributes][:create_default_person] = nil expect do post :create, full_correct_attributes end.to change { Person.count }.by(1) end end describe 'Nested Creating / Updating of Resources' do describe 'Created a nested Referral with an Account List' do lock_time_around let(:generated_id) { SecureRandom.uuid } let(:params) do { included: [ { type: 'contacts', id: generated_id, attributes: { name: '<NAME> and jan', primary_person_first_name: 'jim', primary_person_last_name: 'thomson', primary_person_email: '<EMAIL>', primary_person_phone: '4074969081', spouse_first_name: 'jan', spouse_last_name: 'thompson' }, relationships: { account_list: { data: { type: 'account_lists', id: account_list_id } } } } ], data: { type: 'contacts', id: id, attributes: { updated_in_db_at: Time.current }, relationships: { contacts_referred_by_me: { data: [ { type: 'contacts', id: generated_id } ] } } }, id: id } end it 'creates the nested referral' do expect(resource.contact_referrals_by_me.count).to eq(0) api_login(user) put :update, params expect(resource.reload.contact_referrals_by_me.count).to eq(1) expect(resource.contacts_referred_by_me.first.name).to eq 'thompson, jim and jan' expect(resource.contacts_referred_by_me.first.account_list_id).to eq account_list.id expect(resource.contacts_referred_by_me.first.id).to eq generated_id end end end end
chuckmersereau/api_practice
db/migrate/20160523162335_change_grouping_id_to_string.rb
<filename>db/migrate/20160523162335_change_grouping_id_to_string.rb class ChangeGroupingIdToString < ActiveRecord::Migration def change change_column :mail_chimp_accounts, :grouping_id, :string end end
chuckmersereau/api_practice
db/migrate/20160215185431_add_index_to_activities_completed_at.rb
class AddIndexToActivitiesCompletedAt < ActiveRecord::Migration self.disable_ddl_transaction! def change add_index :activities, :completed_at, algorithm: :concurrently end end
chuckmersereau/api_practice
lib/sidekiq_mem_notifier.rb
# Based on: https://github.com/andys/sidekiq_memlimit class SidekiqMemNotifier class << self attr_accessor :threshold_mb, :sleep_time, :max_mb_percent, :last_time_emailed attr_reader :monitor_thread def start self.sleep_time ||= 5 self.max_mb_percent = ENV['SIDEKIQ_WARN_PERCENT_MEM'].try(:to_f) || 0.95 self.threshold_mb = ENV['CONTAINER_MB'].to_i * max_mb_percent self.threshold_mb = nil unless threshold_mb > 1 start_monitor_thread if sidekiq_running? end def sidekiq_running? defined?(Sidekiq::CLI) end def start_monitor_thread if !@monitor_thread || !@monitor_thread.alive? @monitor_thread = Thread.new { check_memory_loop } @monitor_thread.priority = 1 end end def check_memory_loop loop { check_memory_iteration } rescue StandardError Sidekiq.logger.error "#{self}: #{$ERROR_INFO.class} exception: #{$ERROR_INFO}" end def check_memory_iteration sleep sleep_time return unless threshold_mb && rss_mb > threshold_mb GC.start mb = rss_mb return unless threshold_mb && mb > threshold_mb memory_threshold_exceeded(mb) end def rss_mb NewRelic::Agent::Samplers::MemorySampler.new.sampler.get_sample end def memory_threshold_exceeded(mb) msgs = threshold_exceeded_msgs(mb) msgs.each { |msg| Sidekiq.logger.error(msg) } notify_by_email(msgs) end def threshold_exceeded_msgs(mb) [ "#{self}: Exceeded memory threshold (#{mb} > #{threshold_mb} MB)", "ENV['DYNO']: #{ENV['DYNO']}", "All jobs: #{Sidekiq::Workers.new.to_a}" ] end def notify_by_email(msgs) return if last_time_emailed.present? && last_time_emailed > 2.hours.ago self.last_time_emailed = Time.current ActionMailer::Base.mail(from: '<EMAIL>', to: ENV['SIDEKIQ_WARN_EMAILS'], subject: 'Sidekiq memory threshold', body: msgs.join("\n")).deliver end end end
chuckmersereau/api_practice
app/mailers/notification_mailer.rb
class NotificationMailer < ApplicationMailer layout 'inky' def notify(user, notifications_by_type, account_list_id = nil) @account_list = AccountList.find_by(id: account_list_id) if account_list_id @notifications_by_type = notifications_by_type @user = user email = user&.email&.email return unless email mail to: email, subject: _('Notifications from MPDX') end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/people/facebook_accounts_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > People > Facebook Accounts' do include_context :json_headers documentation_scope = :people_api_facebook_accounts let(:resource_type) { 'facebook_accounts' } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:contact) { create(:contact, account_list: account_list) } let(:contact_id) { contact.id } let!(:person) { create(:person) } let(:person_id) { person.id } let!(:facebook_accounts) { create_list(:facebook_account, 2, person: person) } let(:facebook_account) { facebook_accounts.first } let(:id) { facebook_account.id } let(:new_facebook_account) do attributes_for(:facebook_account) .reject { |key| key.to_s.end_with?('_id') } .merge(updated_in_db_at: facebook_account.updated_at) end let(:form_data) { build_data(new_facebook_account) } let(:expected_attribute_keys) do %w( created_at first_name last_name remote_id updated_at updated_in_db_at username ) end context 'authorized user' do before do contact.people << person api_login(user) end get '/api/v2/contacts/:contact_id/people/:person_id/facebook_accounts' do parameter 'contact_id', 'Contact ID', required: true parameter 'person_id', 'Person ID', required: true response_field 'data', 'Data', type: 'Array[Object]' example 'Facebook Account [LIST]', document: documentation_scope do explanation 'List of Facebook Accounts associated to the Person' do_request check_collection_resource(2) expect(resource_object.keys).to match_array expected_attribute_keys expect(response_status).to eq 200 end end get '/api/v2/contacts/:contact_id/people/:person_id/facebook_accounts/:id' do with_options scope: [:data, :attributes] do response_field 'created_at', 'Created At', type: 'String' response_field 'first_name', 'First Name', type: 'String' response_field 'last_name', 'Last name', type: 'Number' response_field 'remote_id', 'Remote ID', type: 'Number' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_at_in_db', 'Updated In Db At', type: 'String' response_field 'username', 'Username', type: 'String' end example 'Facebook Account [GET]', document: documentation_scope do explanation 'The Person\'s Facebook Account with the given ID' do_request expect(resource_object.keys).to match_array expected_attribute_keys expect(response_status).to eq 200 end end post '/api/v2/contacts/:contact_id/people/:person_id/facebook_accounts' do with_options scope: [:data, :attributes] do parameter 'first_name', 'First Name' parameter 'last_name', 'Last Name' parameter 'remote_id', 'Remote ID' parameter 'username', 'Username' end example 'Facebook Account [CREATE]', document: documentation_scope do explanation 'Create a Facebook Account associated with the Person' do_request data: form_data expect(response_status).to eq 201 end end put '/api/v2/contacts/:contact_id/people/:person_id/facebook_accounts/:id' do with_options scope: [:data, :attributes] do parameter 'first_name', 'First Name' parameter 'last_name', 'Last Name' parameter 'remote_id', 'Remote ID' parameter 'username', 'Username' end example 'Facebook Account [UPDATE]', document: documentation_scope do explanation 'Update the Person\'s Facebook Account with the given ID' do_request data: form_data expect(response_status).to eq 200 end end delete '/api/v2/contacts/:contact_id/people/:person_id/facebook_accounts/:id' do parameter 'contact_id', 'Contact ID', required: true parameter 'person_id', 'Person ID', required: true example 'Facebook Account [DELETE]', document: documentation_scope do explanation 'Delete the Person\'s Facebook Account with the given ID' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
app/controllers/api/v2/reports/activity_results_controller.rb
<gh_stars>0 class Api::V2::Reports::ActivityResultsController < Api::V2Controller include Filtering def index load_report authorize_report render_report end private def render_report options = { json: @report.periods_data, fields: field_params, include: include_params, meta: meta_hash } options[:each_serializer] = Coaching::Reports::ActivityResultsPeriodSerializer if coach? render options end def permit_coach? true end def coach? !load_account_list.users.where(id: current_user).exists? && load_account_list.coaches.where(id: current_user).exists? end def load_report @report ||= ::Reports::ActivityResults.new(report_params) end def report_params { account_list: load_account_list }.merge(filter_params.except(:account_list_id)) end def meta_hash { sort: sorting_param_applied_to_query, filter: permitted_filter_params_with_ids, averages: @report.meta(field_params) } end def permitted_filters [:account_list_id, :period, :end_date] end def authorize_report authorize(load_account_list, :show?) end def load_account_list @account_list ||= account_lists.order(:created_at).first end end
chuckmersereau/api_practice
spec/lib/sidekiq_mem_notifier_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe SidekiqMemNotifier do before { ENV['CONTAINER_MB'] = '1000' } subject { SidekiqMemNotifier } context '#start' do it 'defaults threshold to 95% of container memory, and starts check thread' do expect(subject).to receive(:sidekiq_running?) { true } expect(subject).to receive(:start_monitor_thread) subject.start expect(subject.threshold_mb).to eq(950) end end context '#start_monitor_thread' do it 'creates a new thread to do the loop with priority 1' do thread = double expect(Thread).to receive(:new) { thread } expect(thread).to receive(:priority=).with(1) subject.start_monitor_thread end end context '#check_memory_iteration' do before do subject.threshold_mb = 950 expect(subject).to receive(:sleep).with(5) end it 'just sleeps if within threshold' do expect(subject).to receive(:rss_mb) { 949.1 } expect(subject).to_not receive(:memory_threshold_exceeded) subject.check_memory_iteration end it 'tries to GC and notifies if above threshold' do expect(subject).to receive(:rss_mb).ordered { 971.1 } expect(GC).to receive(:start) expect(subject).to receive(:rss_mb).ordered { 951.1 } expect(subject).to receive(:memory_threshold_exceeded).with(951.1) subject.check_memory_iteration end end context '#memory_threshold_exceeded' do it 'logs messages and sends an notification email' do expect(subject).to receive(:threshold_exceeded_msgs).with(951) { ['Oops', ':('] } expect(Sidekiq.logger).to receive(:error).with('Oops').ordered expect(Sidekiq.logger).to receive(:error).once.with(':(').ordered expect(subject).to receive(:notify_by_email).with(['Oops', ':(']) subject.memory_threshold_exceeded(951) end end context '#threshold_exceeded_msgs' do it 'gives explanatory messages' do ENV['DYNO'] = 'worker.1' workers = [{ work: 1 }, { work: 2 }] expect(Sidekiq::Workers).to receive(:new) { workers } subject.threshold_mb = 950 expected_msgs = [ 'SidekiqMemNotifier: Exceeded memory threshold (951.5 > 950 MB)', "ENV['DYNO']: worker.1", 'All jobs: [{:work=>1}, {:work=>2}]' ] expect(subject.threshold_exceeded_msgs(951.5)).to eq expected_msgs end end context '#notify_by_email' do let(:mail) { double } before do subject.last_time_emailed = nil ENV['SIDEKIQ_WARN_EMAILS'] = '<EMAIL>, <EMAIL>' allow(ActionMailer::Base).to receive(:mail) .with(from: '<EMAIL>', to: '<EMAIL>, <EMAIL>', subject: 'Sidekiq memory threshold', body: "Oops\n:(") .and_return(mail) end it 'sends a notification email the first time called' do expect(mail).to receive(:deliver) subject.notify_by_email(['Oops', ':(']) end it 'does not send notifications when called again right away' do expect(mail).to receive(:deliver).exactly(:once) subject.notify_by_email(['Oops', ':(']) subject.notify_by_email(['Oops', ':(']) end it 'will email again after 2 hours' do expect(mail).to receive(:deliver).exactly(:twice) subject.notify_by_email(['Oops', ':(']) travel_to 3.hours.since do subject.notify_by_email(['Oops', ':(']) end end end end
chuckmersereau/api_practice
app/policies/contact_policy.rb
<gh_stars>0 class ContactPolicy < ApplicationPolicy def initialize(context, resource) @user = context.is_a?(User) ? context : context.user @resource = resource end def show? resource_owner? || coaching_contact? end private def resource_owner? user.account_lists.ids & resource_account_list_ids == resource_account_list_ids end def resource_account_list_ids return [@resource.account_list_id] if @resource.is_a?(Contact) @resource_account_list_ids ||= @resource.collect(&:account_list_id).uniq end def coaching_contact? coaching_account_list_ids & resource_account_list_ids == resource_account_list_ids end def coaching_account_list_ids @coaching_account_list_ids ||= @user.becomes(User::Coach).coaching_contacts.map(&:account_list_id).uniq end end
chuckmersereau/api_practice
spec/models/organization_spec.rb
require 'rails_helper' describe Organization do it 'should return the org name for to_s' do expect(described_class.new(name: 'foo').to_s).to eq('foo') end describe '#guess_country' do context 'name does not convert to country' do subject { build(:organization, name: 'No match here') } it 'returns nil if no match found' do expect(subject.guess_country).to be_nil end end context 'name contains country name' do subject { build(:organization, name: 'Cru - Panama') } it 'finds a country after Parent org name' do expect(subject.guess_country).to eq 'Panama' end end context 'name contains country abbreviations' do context 'CAN' do subject { build(:organization, name: 'CAN') } it 'expands abbreviations' do expect(subject.guess_country).to eq 'Canada' end end context 'USA' do subject { build(:organization, name: 'Gospel For Asia USA') } it 'expands abbreviations' do expect(subject.guess_country).to eq 'United States' end end end end describe '#guess_locale' do context 'country is blank' do subject { build(:organization, country: nil) } it 'returns en' do expect(subject.guess_locale).to eq 'en' end end context 'country does not exist' do subject { build(:organization, country: 'Not-A-Country') } it 'returns en' do expect(subject.guess_locale).to eq 'en' end end context 'country is set' do subject { build(:organization, country: 'France') } it 'returns locale of country' do expect(subject.guess_locale).to eq 'fr' end end end describe '#oauth?' do context 'oauth_url is set' do subject { build(:organization, oauth_url: 'https://example.com') } it 'return true' do expect(subject.oauth?).to eq true end end context 'oauth_url is set' do subject { build(:organization, oauth_url: nil) } it 'return true' do expect(subject.oauth?).to eq false end end end end
chuckmersereau/api_practice
spec/models/appeal_contact_spec.rb
<filename>spec/models/appeal_contact_spec.rb<gh_stars>0 require 'rails_helper' RSpec.describe AppealContact, type: :model do subject { create(:appeal_contact) } it { is_expected.to belong_to(:appeal) } it { is_expected.to belong_to(:contact) } it { is_expected.to validate_presence_of(:appeal) } it { is_expected.to validate_presence_of(:contact) } it { is_expected.to validate_uniqueness_of(:contact_id).scoped_to(:appeal_id).case_insensitive } describe 'destroy_related_excluded_appeal_contact' do let(:account_list) { create(:account_list) } let(:appeal) { create(:appeal, account_list: account_list) } let(:contact) { create(:contact, account_list: account_list) } let(:contact_two) { create(:contact, account_list: account_list) } subject { create(:appeal_contact, appeal: appeal, contact: contact) } let(:appeal_contact_force) do create(:appeal_contact, appeal: appeal, contact: contact, force_list_deletion: true) end it 'should not destroy related excluded appeal contact' do create(:appeal_excluded_appeal_contact, appeal: appeal, contact: contact) expect do subject.destroy_related_excluded_appeal_contact end.to raise_error.with_message(/Contact is on the Excluded List/) end it 'should remove the contact from the exclusion list' do create(:appeal_excluded_appeal_contact, appeal: appeal, contact: contact) expect do appeal_contact_force.send(:remove_from_exclusion_list) end.to change { Appeal::ExcludedAppealContact.count } end it 'should be on the exclusion list' do contact = create(:appeal_contact, appeal: appeal, contact: contact_two) create(:appeal_excluded_appeal_contact, appeal: appeal, contact: contact_two) expect(contact.send(:contact_on_exclusion_list?)).to be true end it 'should not be on the exclusion list' do expect(subject.send(:contact_on_exclusion_list?)).to be false end end describe 'account list for appeal is not the same as contact' do let(:account_list) { create(:account_list) } let(:appeal) { create(:appeal, account_list: account_list) } let(:contact) { create(:contact) } subject { build(:appeal_contact, appeal: appeal, contact: contact) } it 'validates contact has same account list as appeal' do expect(subject).to_not be_valid expect(subject.errors[:contact]).to eq(['does not have the same account list as appeal']) end end end
chuckmersereau/api_practice
app/preloaders/api/v2/account_lists_preloader.rb
<filename>app/preloaders/api/v2/account_lists_preloader.rb<gh_stars>0 class Api::V2::AccountListsPreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = {}.freeze FIELD_ASSOCIATION_MAPPING = {}.freeze end
chuckmersereau/api_practice
app/serializers/contact_referral_serializer.rb
<reponame>chuckmersereau/api_practice<filename>app/serializers/contact_referral_serializer.rb class ContactReferralSerializer < ApplicationSerializer belongs_to :referred_by, serializer: ContactSerializer belongs_to :referred_to, serializer: ContactSerializer end
chuckmersereau/api_practice
spec/services/account_list/destroyer_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe AccountList::Destroyer do let(:user) { User.order(:created_at).first } let(:account_list) { user.account_lists.order(:created_at).first } let(:destroyer) { AccountList::Destroyer.new(account_list.id) } before do 2.times { ApplicationSeeder.new.seed } end describe 'initialize' do subject { AccountList::Destroyer.new(account_list.id) } it 'initializes' do expect(subject).to be_a(AccountList::Destroyer) end context 'account_list cannot be found' do before do account_list.delete end it 'raises an error' do expect { subject }.to raise_error(ActiveRecord::RecordNotFound) end end end describe '#destroy!' do subject { destroyer.destroy! } let(:records_to_delete) do [ 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_email_activities).flatten, account_list.appeals, account_list.appeals.collect(&:appeal_contacts).flatten, account_list.appeals.collect(&:excluded_appeal_contacts).flatten, account_list.company_partnerships, account_list.contacts, account_list.contacts.collect(&:contact_donor_accounts).flatten, account_list.contacts.collect(&:contact_people).flatten, account_list.contacts.collect(&:contact_referrals_by_me).flatten, account_list.contacts.collect(&:addresses).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(&:company_positions).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(&: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 ].collect(&:presence).flatten.collect do |record| record.is_a?(ActiveRecord::Associations::CollectionProxy) ? record.to_a.presence : record.presence end.flatten end let(:records_to_leave_alone) do (ApplicationRecord.descendants - [User, User::Coach, DonationAmountRecommendation::Remote]).collect do |klass| klass.all.to_a.presence end.flatten - records_to_delete end it 'deletes the account list and associated records' do expect(records_to_delete.all? { |record| record.class.exists?(record.id) }).to eq(true) subject records_not_deleted = records_to_delete.select { |record| record.class.exists?(record.id) } expect(records_not_deleted).to eq([]) end it 'does not delete records not associated to the account list' do expect(records_to_leave_alone.all? { |record| record.class.exists?(record.id) }).to eq(true) subject records_deleted = records_to_leave_alone.select { |record| !record.class.exists?(record.id) } expect(records_deleted).to eq([]) end end end
chuckmersereau/api_practice
app/serializers/person/facebook_account_serializer.rb
<filename>app/serializers/person/facebook_account_serializer.rb class Person::FacebookAccountSerializer < ApplicationSerializer type :facebook_accounts attributes :created_at, :first_name, :last_name, :remote_id, :updated_at, :username end
chuckmersereau/api_practice
app/workers/import_gifts_and_appeals_from_tnt_worker.rb
<reponame>chuckmersereau/api_practice<filename>app/workers/import_gifts_and_appeals_from_tnt_worker.rb # Historically the Tnt import did not import gifts (donations) from the Tnt xml for online orgs # (because they are imported from the org api, like Siebel). # Because the gifts were not imported from the xml they were not associated to appeals. # Recently the Tnt import was updated to import gifts from the Tnt xml, so that we can associate them to appeals. # This job will re-run the appeal, pledge, and gift part of the Tnt import. # We will run it on accounts that did not have their gifts associated to appeals. class ImportGiftsAndAppealsFromTntWorker include Sidekiq::Worker include Concerns::TntImport::AppealHelpers sidekiq_options queue: :api_import_gifts_and_appeals_from_tnt_worker def perform(import_id) @import = Import.joins(:account_list).where(id: import_id, source: 'tnt').first return unless import && account_list && account_list.appeals.any? perform_import end private attr_accessor :import def account_list @account_list ||= @import.account_list end def tnt_import @tnt_import ||= TntImport.new(import) end def xml @xml ||= tnt_import.xml end def contact_ids_by_tnt_contact_id tnt_ids = import.account_list.contacts.where.not(tnt_id: nil).pluck(:id, :tnt_id) @contact_ids_by_tnt_contact_id ||= tnt_ids.each_with_object({}) do |(mpdx_id, tnt_id), hash| hash[tnt_id.to_s] = mpdx_id end end def tnt_appeal_ids @tnt_appeal_ids ||= xml.tables[appeal_table_name].collect { |row| row['id'] } end def contact_ids_by_tnt_appeal_id @contact_ids_by_tnt_appeal_id ||= tnt_appeal_ids.each_with_object({}).each do |tnt_appeal_id, hash| appeal = account_list.appeals.find_by(tnt_id: tnt_appeal_id) contact_ids = appeal&.contacts&.pluck(:id) || [] hash[tnt_appeal_id] = contact_ids end end def perform_import @import.file.cache_stored_file! TntImport::AppealsImport.new(account_list, contact_ids_by_tnt_appeal_id, xml).import TntImport::PledgesImport.new(account_list, import, xml).import TntImport::GiftsImport.new(account_list, contact_ids_by_tnt_contact_id, xml, import).import end end
chuckmersereau/api_practice
spec/acceptance/api/v2/reports/monthly_giving_graph_spec.rb
<filename>spec/acceptance/api/v2/reports/monthly_giving_graph_spec.rb require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Reports > Monthly Giving Graph Report' do include_context :json_headers documentation_scope = :reports_api_monthly_giving let(:resource_type) { 'reports_monthly_giving_graphs' } 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( created_at display_currency monthly_average monthly_goal months_to_dates multi_currency pledges salary_currency salary_currency_symbol totals updated_at updated_in_db_at ) end context 'authorized user' do before { api_login(user) } # show get '/api/v2/reports/monthly_giving_graph' do parameter 'filter[account_list_id]', 'Account List ID', required: true parameter 'filter[donor_account_id]', 'List of Donor Account Ids', 'Type' => 'Array[String]' parameter 'filter[designation_account_id]', 'List of Designation Account Ids', 'Type' => 'Array[String]' response_field 'data', 'Data object', type: 'Object' with_options scope: [:data, :attributes] do response_field 'created_at', 'Time when report was observed', type: 'String' response_field 'display_currency', 'The currency converted values are in', type: 'String' response_field 'monthly_average', 'Average monthly total conversion', type: 'Number' response_field 'monthly_goal', 'The Account List\'s monthly goal', type: 'Number' response_field 'pledges', 'The sum of all pledges', type: 'Array' response_field 'months_to_dates', 'The first day of each month represented', type: 'Array' response_field 'multi_currency', 'If multiple currencies are used', type: 'Boolean' response_field 'salary_currency', 'Salary currency', type: 'String' response_field 'salary_currency_symbol', 'Salary currency symbol', type: 'String' end with_options scope: [:data, :relationships] do response_field 'account_list', 'Account List', type: 'Object' end example 'Monthly Giving Graph [LIST]', document: documentation_scope do explanation 'Lists information related to the Monthly Giving Graph' do_request(filter: { account_list_id: account_list_id }) check_resource(['relationships']) expect(response_status).to eq 200 end end end end
chuckmersereau/api_practice
spec/exhibits/address_exhibit_spec.rb
<gh_stars>0 require 'rails_helper' describe AddressExhibit do let(:context) { double } context '.applicable_to?' do it 'applies only to Address and not other stuff' do expect(AddressExhibit.applicable_to?(Address.new)).to be true expect(AddressExhibit.applicable_to?(Contact.new)).to be false end end context '#to_s and #to_google' do it 'renders the address in one line' do expect_address_single_line_string(:to_s) expect_address_single_line_string(:to_google) end def expect_address_single_line_string(method) address = build_stubbed(:address) exhibit_context = double exhibit = AddressExhibit.new(address, exhibit_context) expect(exhibit.public_send(method)) .to eq '123 Somewhere St, Fremont, CA, 94539, United States' end end context '#address_change_email_body' do it 'gives a form email to donor services to request address change' do exhibit = AddressExhibit.new(build_stubbed(:address), double) name = exhibit.addressable.name expected_email_body = "Dear Donation Services,\n\n"\ "One of my donors, \"#{name}\" has a new current address.\n\n"\ "Please update their address to:\n\n"\ "REPLACE WITH NEW STREET\nREPLACE WITH NEW CITY, STATE, ZIP\n\n"\ "Thanks!\n\n" expect(exhibit.address_change_email_body).to eq expected_email_body end end end
chuckmersereau/api_practice
db/migrate/20150915141504_add_cancelled_by_user_to_account_list_invites.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 class AddCancelledByUserToAccountListInvites < ActiveRecord::Migration def change add_column :account_list_invites, :cancelled_by_user_id, :integer end end
chuckmersereau/api_practice
app/services/tnt_data_sync_import.rb
class TntDataSyncImport def initialize(import) @import = import @account_list = import.account_list @user = import.user @profile = @account_list.designation_profiles.first || @user.designation_profiles.first @data_server = DataServer.new(Person::OrganizationAccount.find(import.source_account_id)) end def import raise Import::UnsurprisingImportError unless file_contents_valid? @data_server.import_donors_from_csv(@account_list, @profile, section('DONORS'), @user) @data_server.import_donations_from_csv(@profile, section('GIFTS')) @account_list.send_account_notifications false end private def file_contents_valid? section('DONORS').present? && section('GIFTS').present? end def section(heading) @import.file.cache_stored_file! file_contents = File.open(@import.file_path).read @sections_by_heading ||= Hash[file_contents.scan(/^\[(.*?)\]\r?\n(.*?)(?=^\[|\Z)/m)] @sections_by_heading[heading].try(:strip) end end