repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
db/migrate/20140320213717_create_google_integration.rb
|
class CreateGoogleIntegration < ActiveRecord::Migration
def change
create_table :google_integrations do |t|
t.belongs_to :account_list, index: true
t.belongs_to :google_account, index: true
t.boolean :calendar_integration, null: false, default: false
t.text :calendar_integrations
t.string :calendar_id
t.string :calendar_name
end
add_column :activities, :google_event_id, :string
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/newsletter_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::Newsletter do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id, send_newsletter: 'Email') }
let!(:contact_two) { create(:contact, account_list_id: account_list.id, send_newsletter: 'Physical') }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, send_newsletter: 'Both') }
let!(:contact_four) { create(:contact, account_list_id: account_list.id) }
let!(:contact_five) { create(:contact, account_list_id: account_list.id, send_newsletter: 'None') }
before do
contact_four.update(send_newsletter: nil)
end
describe '#config' do
it 'returns expected config' do
expect(described_class.config([account_list])).to include(multiple: false,
name: :newsletter,
options: [{ name: _('Nothing Selected'), id: 'no_value' },
{ name: _('None'), id: 'none' },
{ name: _('All'), id: 'all' },
{ name: _('Physical and Both'), id: 'address' },
{ name: _('Email and Both'), id: 'email' },
{ name: _('Physical Only'), id: 'address_only' },
{ name: _('Email Only'), id: 'email_only' },
{ name: _('Both Only'), id: 'both' }],
parent: nil,
title: 'Newsletter Recipients',
type: 'radio',
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, { newsletter: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { newsletter: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { newsletter: '' }, nil)).to eq(nil)
end
end
context 'filter by newsletter no_value' do
it 'returns only contacts that have no newsletter option selected' do
expect(described_class.query(contacts, { newsletter: 'no_value' }, nil).to_a).to eq [contact_four]
end
end
context 'filter by newsletter none' do
it 'returns only contacts that have no newsletter option selected' do
expect(described_class.query(contacts, { newsletter: 'none' }, nil).to_a).to eq [contact_five]
end
end
context 'filter by newsletter all' do
it 'returns all contacts that have any newsletter option selected, but not blank' do
expect(described_class.query(contacts, { newsletter: 'all' }, nil).to_a).to match_array [contact_one, contact_two, contact_three]
end
end
context 'filter by newsletter physical' do
it 'returns all contacts that have physical or both newsletter options selected' do
expect(described_class.query(contacts, { newsletter: 'address' }, nil).to_a).to match_array [contact_two, contact_three]
end
end
context 'filter by newsletter email' do
it 'returns all contacts that have email or both newsletter options selected' do
expect(described_class.query(contacts, { newsletter: 'email' }, nil).to_a).to match_array [contact_one, contact_three]
end
end
context 'filter by newsletter both' do
it 'returns all contacts that have the both newsletter option selected' do
expect(described_class.query(contacts, { newsletter: 'both' }, nil).to_a).to eq [contact_three]
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20150915181704_create_currency_rates.rb
|
<reponame>chuckmersereau/api_practice
class CreateCurrencyRates < ActiveRecord::Migration
def change
create_table :currency_rates do |t|
t.date :exchanged_on, null: false
t.string :code, null: false
t.decimal :rate, precision: 20, scale: 10, null: false
t.string :source, null: false
end
add_index :currency_rates, :exchanged_on
add_index :currency_rates, :code
add_index :currency_rates, [:code, :exchanged_on], unique: true
end
end
|
chuckmersereau/api_practice
|
spec/serializers/balance_serializer_spec.rb
|
<filename>spec/serializers/balance_serializer_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe BalanceSerializer do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:designation_account) { create(:designation_account, account_lists: [account_list]) }
let(:balance) { create(:balance, resource: designation_account) }
subject { described_class.new(balance, scope: user).as_json }
it { expect(subject[:id]).to eq(balance.id) }
it { expect(subject[:balance]).to eq(balance.balance) }
it { expect(subject[:resource][:id]).to eq(designation_account.id) }
end
|
chuckmersereau/api_practice
|
app/serializers/service_serializer.rb
|
<gh_stars>0
class ServiceSerializer < ApplicationSerializer
def id
nil
end
def created_at
@created_at ||= Time.current
end
def updated_in_db_at
nil
end
alias updated_at updated_in_db_at
end
|
chuckmersereau/api_practice
|
spec/services/reports/expected_monthly_totals_spec.rb
|
<filename>spec/services/reports/expected_monthly_totals_spec.rb
require 'rails_helper'
RSpec.describe Reports::ExpectedMonthlyTotals, type: :model do
subject { described_class.new(account_list: account_list) }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:designation_account_1) { create(:designation_account) }
let!(:designation_account_2) { create(:designation_account) }
let!(:designation_account_3) { create(:designation_account) }
let!(:donor_account_1) { create(:donor_account) }
let!(:donor_account_2) { create(:donor_account) }
let!(:donor_account_3) { create(:donor_account) }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:contact_with_pledge) { create(:contact, account_list: account_list, pledge_amount: 50) }
let!(:cad_donation) do
create(:donation, donor_account: donor_account_1,
designation_account: designation_account_1,
amount: 3, currency: 'CAD',
donation_date: Date.current - 1.month)
end
let!(:eur_donation) do
create(:donation, donor_account: donor_account_2,
designation_account: designation_account_2,
amount: 2, currency: 'EUR',
donation_date: Date.current)
end
let!(:donation_last_year) do
create(:donation, donor_account: donor_account_3,
designation_account: designation_account_3,
amount: 88, currency: 'EUR',
donation_date: 13.months.ago.end_of_month - 1.day)
end
before do
account_list.designation_accounts << designation_account_1
account_list.designation_accounts << designation_account_2
account_list.designation_accounts << designation_account_3
contact.donor_accounts << donor_account_1
contact.donor_accounts << donor_account_2
contact.donor_accounts << donor_account_3
end
describe '#expected_donations' do
subject do
described_class.new(
account_list: account_list
).expected_donations
end
it 'returns donations infos' do
expect(subject).to be_a(Array)
expect(subject.size).to eq(2)
expect(subject.first[:contact_name]).to eq(contact.name)
end
it 'returns received donations' do
expect(subject.detect { |hash| hash[:type] == 'received' }).to be_present
end
it 'returns possible donations' do
expect(subject.detect { |hash| hash[:type] == 'unlikely' }).to be_present
end
context 'designation_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { designation_account_id: designation_account_1.id }
).expected_donations
end
it 'returns donations infos' do
expect(subject).to be_a(Array)
expect(subject.size).to eq(1)
expect(subject.first[:contact_name]).to eq(contact.name)
end
it 'returns received donations' do
expect(subject.detect { |hash| hash[:type] == 'received' }).to be_nil
end
it 'returns possible donations' do
expect(subject.detect { |hash| hash[:type] == 'unlikely' }).to be_present
end
end
context 'donor_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { donor_account_id: donor_account_2.id }
).expected_donations
end
it 'returns donations infos' do
expect(subject).to be_a(Array)
expect(subject.size).to eq(1)
expect(subject.first[:contact_name]).to eq(contact.name)
end
it 'returns received donations' do
expect(subject.detect { |hash| hash[:type] == 'received' }).to be_present
end
it 'returns possible donations' do
expect(subject.detect { |hash| hash[:type] == 'unlikely' }).to be_nil
end
end
end
describe '#total_currency' do
it 'returns total_currency' do
expect(subject.total_currency).to eq('USD')
end
end
describe '#total_currency_symbol' do
it 'returns total_currency_symbol' do
expect(subject.total_currency_symbol).to eq('$')
end
end
end
|
chuckmersereau/api_practice
|
app/models/notification_type/missing_contact_info.rb
|
<reponame>chuckmersereau/api_practice
class NotificationType::MissingContactInfo < NotificationType
def missing_info_filter(_contacts)
raise 'This method must be implemented in a subclass'
end
def check(account_list)
missing_info_filter(account_list.contacts).map do |contact|
prior_notification = Notification.active
.where(contact_id: contact.id, notification_type_id: id)
.where('event_date > ?', 1.year.ago)
.exists?
next if prior_notification
contact.notifications.create!(notification_type_id: id, event_date: Date.today)
end.compact
end
def task_activity_type
'To Do'
end
end
|
chuckmersereau/api_practice
|
app/services/csv_import_batch_callback_handler.rb
|
<filename>app/services/csv_import_batch_callback_handler.rb
# https://github.com/mperham/sidekiq/wiki/Batches
class CsvImportBatchCallbackHandler
def on_complete(status, options)
initialize_from_options(options)
begin
number_of_failures = @import.file_row_failures.size
number_of_successes = status.total - number_of_failures
if number_of_failures.positive?
@import_callback_handler.handle_failure(failures: number_of_failures, successes: number_of_successes)
else
@import_callback_handler.handle_success(successes: number_of_successes)
end
ensure
@import_callback_handler.handle_complete
end
end
private
def initialize_from_options(options)
options = options.with_indifferent_access
@import = Import.find(options[:import_id])
@import_callback_handler = ImportCallbackHandler.new(@import)
end
end
|
chuckmersereau/api_practice
|
spec/models/mail_chimp_account_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe MailChimpAccount do
let(:api_prefix) { 'https://us4.api.mailchimp.com/3.0' }
let(:primary_list_id) { '1e72b58b72' }
let(:primary_list_id_2) { '29a77ba541' }
let(:mail_chimp_account) do
create(:mail_chimp_account, api_key: 'fake-us4', primary_list_id: primary_list_id, account_list: account_list)
end
let(:account_list) { create(:account_list) }
let(:account_list_with_mailchimp) { create(:account_list, mail_chimp_account: mail_chimp_account) }
let(:appeal) { create(:appeal, account_list: account_list) }
let(:newsletter_contacts) do
contacts = []
2.times do
contacts << create(
:contact,
people: [create(:person, email_addresses: [build(:email_address)])],
account_list: account_list_with_mailchimp,
send_newsletter: 'Email'
)
end
contacts
end
let(:non_newsletter_contacts) do
[create(
:contact,
people: [create(:person, email_addresses: [build(:email_address)])],
account_list: account_list_with_mailchimp,
send_newsletter: 'Physical'
)]
end
let(:hidden_contacts) do
[create(
:contact,
people: [create(:person, email_addresses: [build(:email_address)])],
account_list: account_list_with_mailchimp,
send_newsletter: 'None',
status: 'Unresponsive'
)]
end
it 'validates the format of an api key' do
invalid_key = 'DEFAULT__{8D2385FE-5B3A-4770-A399-1AF1A6436A00}'
expect(MailChimpAccount.new(account_list_id: account_list.id, api_key: invalid_key)).not_to be_valid
valid_key = '<KEY>'
expect(MailChimpAccount.new(account_list_id: account_list.id, api_key: valid_key)).to be_valid
end
it 'deactivates the account if the api key is invalid' do
error = {
title: 'API Key Invalid', status: 401,
detail: "Your API key may be invalid, or you've attempted to access the wrong datacenter."
}
stub_request(:get, "#{api_prefix}/lists").to_return(status: 401, body: error.to_json)
mail_chimp_account.active = true
mail_chimp_account.validate_key
expect(mail_chimp_account.active).to be false
expect(mail_chimp_account.validation_error).to match(/Your API key may be invalid/)
end
describe '#appeal_open_rate' do
let(:mock_gibbon) { double(:mock_gibbon) }
let(:mock_gibbon_list) { double(:mock_gibbon_list) }
it 'returns the open rate given by the mail chimp api' do
expect_any_instance_of(MailChimp::GibbonWrapper).to receive(:gibbon).and_return(mock_gibbon)
expect(mock_gibbon).to receive(:lists).and_return(mock_gibbon_list)
expect(mock_gibbon_list).to receive(:retrieve).and_return(
{
lists: [
{
id: primary_list_id_2,
name: 'Appeal List',
stats: {
open_rate: 20
}
}
]
}.with_indifferent_access
)
MailChimpAppealList.create(mail_chimp_account: mail_chimp_account,
appeal_id: appeal.id,
appeal_list_id: primary_list_id_2)
mail_chimp_account.update!(active: true)
expect(mail_chimp_account.appeal_open_rate).to eq(20)
end
end
context 'email generating methods' do
let(:contacts) { newsletter_contacts + non_newsletter_contacts + hidden_contacts }
let(:contact_ids) { contacts.map(&:id) }
before do
newsletter_contacts
non_newsletter_contacts
end
describe '#relevant_contacts' do
context 'contact_ids set' do
it 'returns newsletter configured contacts' do
expect(mail_chimp_account.relevant_contacts(contact_ids)).to match_array(newsletter_contacts)
end
context 'force_sync is true' do
it 'return all contacts' do
expect(mail_chimp_account.relevant_contacts(contact_ids, true)).to match_array(contacts)
end
end
end
it 'returns newsletter configured contacts' do
expect(mail_chimp_account.relevant_contacts).to match_array(newsletter_contacts)
end
end
end
end
|
chuckmersereau/api_practice
|
engines/auth/app/controllers/auth/provider/prayer_letters_accounts_controller.rb
|
<reponame>chuckmersereau/api_practice
module Auth
module Provider
class PrayerLettersAccountsController < BaseController
protected
def find_or_create_account
prayer_letters_account.attributes = { oauth2_token: auth_hash.credentials.token, valid_token: true }
prayer_letters_account.save
end
def prayer_letters_account
@prayer_letters_account ||= current_account_list.prayer_letters_account || current_account_list.build_prayer_letters_account
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20121108200031_create_notification_preferences.rb
|
<filename>db/migrate/20121108200031_create_notification_preferences.rb
class CreateNotificationPreferences < ActiveRecord::Migration
def change
create_table :notification_preferences do |t|
t.integer :notification_type_id
t.integer :account_list_id
t.text :actions
t.timestamps null: false
end
add_index :notification_preferences, :account_list_id
add_index :notification_preferences, :notification_type_id
end
end
|
chuckmersereau/api_practice
|
spec/models/person/organization_account_spec.rb
|
<filename>spec/models/person/organization_account_spec.rb<gh_stars>0
require 'rails_helper'
describe Person::OrganizationAccount do
let(:user) { create(:user) }
let(:organization) { create(:fake_org, name: 'MyString') }
let(:org_account) do
create(:organization_account,
organization: organization,
person: user,
remote_id: SecureRandom.uuid)
end
let(:api) { FakeApi.new }
before do
allow(org_account.organization).to receive(:api).and_return(api)
allow(api).to receive(:profiles_with_designation_numbers)
.and_return([{ name: 'Profile 1', code: '', designation_numbers: ['1234'] }])
end
describe '.find_or_create_from_auth' do
let(:oauth_url) { 'https://www.mytntware.com/dataserver/toontown/staffportal/oauth/authorize.aspx' }
let!(:oauth_organization) { create(:fake_org, oauth_url: oauth_url) }
context 'organization_account does not exist' do
it 'creates an organization_account' do
expect { described_class.find_or_create_from_auth('abc', oauth_url, user) }.to(
change { described_class.count }.by(1)
)
organization_account = described_class.find_by(organization: oauth_organization, person: user)
expect(organization_account.user).to eq user
expect(organization_account.organization).to eq oauth_organization
expect(organization_account.token).to eq 'abc'
end
context 'organization cannot be found' do
it 'raise error' do
expect { described_class.find_or_create_from_auth('abc', 'fake_url', user) }.to(
raise_error(ActiveRecord::RecordNotFound)
)
end
end
end
context 'organization_account does exist' do
let!(:organization_account) do
create(:organization_account,
organization: oauth_organization,
person: user,
token: '<PASSWORD>')
end
it 'updates organization_account token' do
expect { described_class.find_or_create_from_auth('abc', oauth_url, user) }.to_not(
change { described_class.count }
)
organization_account = described_class.find_by(organization: oauth_organization, person: user)
expect(organization_account.token).to eq 'abc'
end
end
end
describe '#import_all_data' do
it 'updates last_download_attempt_at' do
travel_to Time.current do
expect { org_account.import_all_data }.to change { org_account.reload.last_download_attempt_at }.from(nil).to(Time.current)
end
end
it 'does not update the last_download column if no donations downloaded' do
org_account.downloading = false
org_account.last_download = nil
org_account.import_all_data
expect(org_account.reload.last_download).to be_nil
end
context 'when password error' do
before do
allow(api).to receive(:import_all).and_raise(Person::OrganizationAccount::InvalidCredentialsError)
org_account.person.email = '<EMAIL>'
org_account.downloading = false
org_account.locked_at = nil
expect(org_account.new_record?).to be false
end
it 'rescues invalid password error' do
expect do
org_account.import_all_data
end.to_not raise_error
end
it 'sends email' do
expect do
org_account.import_all_data
end.to change(Sidekiq::Extensions::DelayedMailer.jobs, :size).by(1)
end
it 'marks as not valid' do
org_account.import_all_data
expect(org_account.valid_credentials).to be false
end
end
context 'when password and username missing' do
before do
allow(api).to receive(:import_all).and_raise(Person::OrganizationAccount::MissingCredentialsError)
org_account.person.email = '<EMAIL>'
org_account.downloading = false
org_account.locked_at = nil
expect(org_account.new_record?).to be false
end
it 'rescues invalid password error' do
expect do
org_account.import_all_data
end.to_not raise_error
end
it 'sends email' do
expect do
org_account.import_all_data
end.to change(Sidekiq::Extensions::DelayedMailer.jobs, :size).by(1)
end
it 'marks as not valid' do
org_account.import_all_data
expect(org_account.valid_credentials).to be false
end
end
context 'when previous password error' do
it 'retries donor import but does not re-send email' do
org_account.valid_credentials = false
expect(api).to receive(:import_all)
expect do
org_account.import_all_data
end.to_not change(Sidekiq::Extensions::DelayedMailer.jobs, :size)
end
end
end
describe '#setup_up_account_list' do
let(:account_list) { create(:account_list) }
it "doesn't create a new list if an existing list contains only the designation number for a profile" do
account_list.designation_accounts << create(:designation_account, designation_number: '1234')
expect do
org_account.send(:set_up_account_list)
end.to_not change(AccountList, :count)
end
it "doesn't create a new designation profile if linking to an account list that already has one" do
account_list.designation_accounts << create(:designation_account, designation_number: '1234')
create(:designation_profile, name: 'Profile 1', account_list: account_list)
expect do
org_account.send(:set_up_account_list)
end.to_not change(DesignationProfile, :count)
end
end
describe '#to_s' do
it 'makes a pretty string' do
expect(org_account.to_s).to eq('MyString: foo')
end
end
describe '#requires_credentials' do
context 'organization requires credentials' do
before do
allow(organization).to receive(:requires_credentials?) { true }
end
it 'returns true' do
expect(org_account.requires_credentials?).to eq true
end
end
context 'organization does not require credentials' do
before do
allow(organization).to receive(:requires_credentials?) { false }
end
it 'returns false' do
expect(org_account.requires_credentials?).to eq false
end
end
context 'organization is nil' do
before { org_account.organization = nil }
it 'returns nil' do
expect(org_account.requires_credentials?).to eq nil
end
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/people/bulk_controller.rb
|
class Api::V2::Contacts::People::BulkController < Api::V2::BulkController
resource_type :people
def create
build_empty_people
persist_people
end
def update
load_people
persist_people
end
def destroy
load_people
authorize_people
destroy_people
end
private
def load_people
@people = person_scope.where(id: person_id_params).tap(&:first!)
end
def authorize_people
bulk_authorize(@people, :bulk_create?)
end
def destroy_people
@destroyed_people = @people.select(&:destroy)
render_people(@destroyed_people)
end
def pundit_user
PunditContext.new(current_user)
end
def person_id_params
params
.require(:data)
.collect { |hash| hash[:person][:id] }
end
def person_scope
Person.joins(:account_lists).where(account_lists: { id: account_lists })
end
def persist_people
build_people
authorize_people
save_people
render_people(@people)
end
def render_people(people)
render json: BulkResourceSerializer.new(resources: people),
include: include_params,
fields: field_params
end
def save_people
@people.each { |person| person.save(context: persistence_context) }
end
def build_empty_people
@people = params.require(:data).map { |data| Person.new(id: data['person']['id']) }
end
def build_people
@people.each do |person|
person_index = data_attribute_index(person)
attributes = params.require(:data)[person_index][:person]
person.assign_attributes(
person_params(attributes)
)
if create?
contacts = find_contacts_from_relationships(attributes[:contacts_attributes])
person.contacts << contacts
end
person
end
end
def find_contacts_from_relationships(contacts_data_array = nil)
contacts_data_array ||= []
contacts_data_array.map { |data| Contact.find(data[:id]) }
end
def data_attribute_index(person)
params
.require(:data)
.find_index { |person_data| person_data[:person][:id] == person.id }
end
def person_params(attributes)
attributes ||= params.require(:person)
attributes.permit(Person::PERMITTED_ATTRIBUTES)
end
def create?
params[:action].to_sym == :create
end
end
|
chuckmersereau/api_practice
|
app/preloaders/application_preloader/include_associations_fetcher.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class ApplicationPreloader
class IncludeAssociationsFetcher
attr_reader :association_preloader_mapping, :resource_path
def initialize(association_preloader_mapping, resource_path)
@association_preloader_mapping = association_preloader_mapping
@resource_path = resource_path
end
def fetch_include_associations(include_params, field_params)
@include_params = include_params
@field_params = field_params
indirect_include_association_parents.inject(direct_include_associations) do |associations, direct_association|
associations + [indirect_associations_hash(direct_association)]
end.compact
end
private
def indirect_associations_hash(direct_association)
indirect_associations = fetch_indirect_associations(direct_association)
{ direct_association.to_sym => indirect_associations } if indirect_associations.present?
end
def fetch_indirect_associations(direct_association)
relevant_include_params = fetch_relevant_include_params(direct_association)
included_parent_association = direct_include_associations.include?(direct_association.to_sym)
preloader_class_from_association(direct_association).new(relevant_include_params, @field_params, direct_association)
.associations_to_preload(included_parent_association)
rescue NameError
nil
end
def fetch_relevant_include_params(association)
params = @include_params.select { |param| param.include?('.') && param.split('.').first == association }
params.map { |param| param.split('.').drop(1).join('.') }
end
def preloader_class_from_association(association)
association_preloader_mapping[association.to_sym] ||
"::#{resource_path}::#{association.camelize}Preloader".constantize
end
def direct_include_associations
@direct_include_associations ||= @include_params.select { |param| !param.include?('.') }.map(&:to_sym)
end
def indirect_include_association_parents
@indirect_association_parents ||= @include_params.map { |param| param.split('.').first }.uniq
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/account_list_user_serializer.rb
|
<reponame>chuckmersereau/api_practice
class AccountListUserSerializer < ApplicationSerializer
attributes :first_name,
:last_name
type :users
end
|
chuckmersereau/api_practice
|
db/migrate/20120215143944_add_name_to_facebook_and_linkedin.rb
|
class AddNameToFacebookAndLinkedin < ActiveRecord::Migration
def change
add_column :person_facebook_accounts, :first_name, :string
add_column :person_facebook_accounts, :last_name, :string
add_column :person_linkedin_accounts, :first_name, :string
add_column :person_linkedin_accounts, :last_name, :string
end
end
|
chuckmersereau/api_practice
|
spec/lib/sidekiq_job_args_logger_spec.rb
|
require 'rails_helper'
describe SidekiqJobArgsLogger do
it 'logs job arguments and yields to the passed in block' do
job = {
'class' => 'A', 'enqueued_at' => 1, 'args' => [1], 'jid' => '1', 'x' => 2
}
logger = double
expect(Sidekiq).to receive(:logger) { logger }
expect(logger).to receive(:info).with('args' => [1], 'x' => 2)
block_called = false
subject.call(double, job, double) do
block_called = true
end
expect(block_called).to be true
end
end
|
chuckmersereau/api_practice
|
spec/workers/contact_dup_merge_worker_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe ContactDupMergeWorker 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: 'Tester', account_list: account_list) }
let(:contact_two) { create(:contact, name: 'Tester', account_list: account_list) }
before do
account_list.designation_accounts << designation_account
contact_one.donor_accounts << donor_account
contact_two.donor_accounts << donor_account
end
it 'merges contact duplicates' do
expect do
ContactDupMergeWorker.new.perform(account_list.id, contact_one.id)
end.to change { account_list.reload.contacts.count }.from(2).to(1)
end
context 'account_list and contact do not exist' do
it 'returns successfully' do
expect { ContactDupMergeWorker.new.perform(1234, 5678) }.to_not raise_error
end
end
end
|
chuckmersereau/api_practice
|
app/services/reports/expected_monthly_totals.rb
|
<gh_stars>0
class Reports::ExpectedMonthlyTotals < ActiveModelSerializers::Model
attr_accessor :account_list, :filter_params
delegate :total_currency,
:total_currency_symbol,
to: :formatter
def expected_donations
(received + possible).map(&method(:format_donation_row))
end
private
def received
ExpectedTotalsReport::ReceivedDonations.new(
account_list: account_list,
filter_params: filter_params
).donation_rows
end
def possible
ExpectedTotalsReport::PossibleDonations.new(
account_list: account_list,
filter_params: filter_params
).donation_rows
end
def format_donation_row(donation_row)
formatter.format(donation_row)
end
def formatter
@formatter ||= ExpectedTotalsReport::RowFormatter.new(account_list)
end
end
|
chuckmersereau/api_practice
|
spec/services/data_server/contact_address_update_spec.rb
|
require 'rails_helper'
describe DataServer::ContactAddressUpdate, '#update_from_donor_accont' do
let(:contact) { create(:contact) }
let(:donor_account) { create(:donor_account) }
before do
contact.donor_accounts << donor_account
end
it 'does not add the most recent address if it already exists on contact' do
address1 = create(:address, street: '1 Rd')
address2 = create(:address, street: '2 Rd', created_at: 2.days.ago)
donor_account.addresses << [address1, address2]
contact.addresses << create(:address, street: '1 Rd')
DataServer::ContactAddressUpdate.new(contact, donor_account).update_from_donor_account
expect(contact.addresses.count).to eq 1
expect(contact.addresses.first.street).to eq '1 Rd'
end
it 'adds address as non-primary if contact primary address not from DataServer' do
address1 = create(:address, street: '1 DataServer Rd', primary_mailing_address: true)
address2 = create(:address, street: '2 DataServer Rd', created_at: 2.days.ago)
donor_account.addresses << [address1, address2]
contact.addresses << create(:address, street: 'Tnt Rd', source: 'TntImport',
primary_mailing_address: true)
DataServer::ContactAddressUpdate.new(contact, donor_account).update_from_donor_account
expect(contact.addresses.count).to eq 2
expect(contact.reload.primary_address.street).to eq 'Tnt Rd'
expect(contact.addresses.map(&:street)).to include '1 DataServer Rd'
end
it 'adds address as primary if contact primary address is from DataServer' do
donor_account.addresses << create(:address, street: 'New DataServer',
primary_mailing_address: true)
contact.addresses << create(:address, street: 'Old DataServer', source: 'DataServer',
primary_mailing_address: true)
DataServer::ContactAddressUpdate.new(contact, donor_account).update_from_donor_account
expect(contact.addresses.count).to eq 2
expect(contact.addresses.where(primary_mailing_address: true).count).to eq 1
expect(contact.reload.primary_address.street).to eq 'New DataServer'
expect(contact.addresses.map(&:street)).to include 'Old DataServer'
end
it 'adds address as primary if contact has no non-historic addresses' do
donor_account.addresses << create(:address, street: '1 DataServer')
contact.addresses << create(:address, street: 'Historic Way', source: 'DataServer',
historic: true)
DataServer::ContactAddressUpdate.new(contact, donor_account).update_from_donor_account
expect(contact.addresses.count).to eq 2
expect(contact.reload.primary_address.street).to eq '1 DataServer'
expect(contact.addresses.map(&:street)).to include 'Historic Way'
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180321203714_remove_people_profession.rb
|
class RemovePeopleProfession < ActiveRecord::Migration
def up
TmpPerson.where.not(profession: nil).where(occupation: nil).find_each do |person|
person.update_attribute(:occupation, person.profession)
end
remove_column :people, :profession
end
def down
add_column :people, :profession, :text
end
end
class TmpPerson < ActiveRecord::Base
self.table_name = 'people'
end
|
chuckmersereau/api_practice
|
db/migrate/20160329200413_add_key_remote_id_to_person_relay_account.rb
|
class AddKeyRemoteIdToPersonRelayAccount < ActiveRecord::Migration
def change
add_column :person_relay_accounts, :key_remote_id, :string
end
end
|
chuckmersereau/api_practice
|
app/serializers/coaching/reports/pledge_increase_contact_serializer.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class Coaching::Reports::PledgeIncreaseContactSerializer < Reports::PledgeIncreaseContactSerializer
belongs_to :contact, serializer: Coaching::ContactSerializer
end
|
chuckmersereau/api_practice
|
app/services/data_server_stumo.rb
|
<filename>app/services/data_server_stumo.rb
class DataServerStumo < DataServer
def import_profiles
designation_profiles = org.designation_profiles
.where(user_id: org_account.person_id)
if org.profiles_url.present?
check_credentials!
profiles.each do |profile|
Retryable.retryable do
designation_profile = find_or_create_designation_profile(
user_id: org_account.person_id,
profile_data: profile
)
import_profile_balance(designation_profile)
AccountList::FromProfileLinker.new(designation_profile, org_account)
.link_account_list! unless designation_profile.account_list
end
end
else
# still want to update balance if possible
designation_profiles.each do |designation_profile|
Retryable.retryable do
import_profile_balance(designation_profile)
AccountList::FromProfileLinker.new(designation_profile, org_account)
.link_account_list! unless designation_profile.account_list
end
end
end
designation_profiles.reload
end
private
def find_or_create_designation_profile(user_id:, profile_data:)
name = profile_data[:name]
code = profile_data[:code]
attributes = {
user_id: user_id,
code: code
}
# If `code` isn't present - we assume that we want to find
# by another level of specificity, ie: `name`
#
# So, we add in the `name` as part of our query attributes.
#
# Assuming that a profile's `code` is unique in relation to `user_id`,
# and a profile's `name` is _not_ unique in relation to `user_id`,
# we don't want to find a profile by _only_ `name` and `user_id`.
#
# This would cause profiles with the same name but different code to be
# found - thus, we keep `code` in the query attributes - even if it's blank.
attributes[:name] = name if code.blank?
org.designation_profiles
.where(attributes)
.first_or_create
.tap { |profile| profile.update(name: name) if name.present? }
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/pledges_import_spec.rb
|
<filename>spec/services/tnt_import/pledges_import_spec.rb
require 'rails_helper'
describe TntImport::PledgesImport do
let(:import) { create(:tnt_import_campaigns_and_promises, override: true) }
let(:tnt_import) { TntImport.new(import) }
let(:xml) { tnt_import.xml }
let(:account_list) { import.account_list }
let(:pledges_import) { TntImport::PledgesImport.new(account_list, import, xml) }
before do
Array.wrap(xml.tables['Promise']).each do |row|
account_list.contacts.create!(name: 'Bob', tnt_id: row['ContactID'])
end
end
describe '#import' do
it 'creates expected number of pledge records' do
expect { pledges_import.import }.to change { Pledge.count }.from(0).to(13)
pledge = Pledge.order(:created_at).last
expect(pledge.amount).to eq(75)
expect(pledge.amount_currency).to eq('USD')
expect(pledge.expected_date).to eq(Date.parse('2017-06-10'))
expect(pledge.account_list_id).to eq(account_list.id)
expect(pledge.contact_id).to be_present
end
it 'does not import the same pledges a second time' do
expect { pledges_import.import }.to change { Pledge.count }.from(0).to(13)
expect { pledges_import.import }.to_not change { Pledge.count }.from(13)
end
end
end
|
chuckmersereau/api_practice
|
app/services/admin/account_primary_addresses_fix.rb
|
<reponame>chuckmersereau/api_practice
class Admin::AccountPrimaryAddressesFix
def initialize(account_list)
@account_list = account_list
end
def fix
@account_list.contacts.find_each(&method(:fix_contact))
end
private
def fix_contact(contact)
Admin::PrimaryAddressFix.new(contact).fix
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170728214336_add_estimated_annual_pledge_amount_to_contacts.rb
|
class AddEstimatedAnnualPledgeAmountToContacts < ActiveRecord::Migration
def change
add_column :contacts, :estimated_annual_pledge_amount, :decimal, precision: 19, scale: 2
end
end
|
chuckmersereau/api_practice
|
app/models/prayer_letters_account.rb
|
require 'async'
require 'open-uri'
class PrayerLettersAccount < ApplicationRecord
include Async
include Sidekiq::Worker
sidekiq_options queue: :api_prayer_letters_account, unique: :until_executed
SERVICE_URL = 'https://www.prayerletters.com'.freeze
belongs_to :account_list
after_create :queue_subscribe_contacts
validates :oauth2_token, :account_list_id, presence: true
PERMITTED_ATTRIBUTES = [:created_at,
:oauth2_token,
:overwrite,
:updated_at,
:updated_in_db_at,
:id,
:valid_token].freeze
def queue_subscribe_contacts
async(:subscribe_contacts)
end
def subscribe_contacts
contacts = account_list.contacts.includes([:primary_address, { primary_person: :companies }])
.select(&:should_be_in_prayer_letters?)
contact_subscribe_params = contacts.map { |c| contact_params(c, true) }
contact_params_map = Hash[contacts.map { |c| [c.id, contact_params(c)] }]
get_response(:put, '/api/v1/contacts', { contacts: contact_subscribe_params }.to_json)
account_list.contacts.update_all(prayer_letters_id: nil, prayer_letters_params: nil)
import_list(contact_params_map)
end
def import_list(contact_params_map = nil)
contacts = JSON.parse(get_response(:get, '/api/v1/contacts'))['contacts']
contacts.each do |pl_contact|
next unless pl_contact['external_id']
contact = account_list.contacts.find_by(id: pl_contact['external_id'])
next unless contact
contact.update_columns(prayer_letters_id: pl_contact['contact_id'],
prayer_letters_params: contact_params_map ? contact_params_map[contact.id] : nil)
end
end
def active?
valid_token?
end
def contacts(params = {})
JSON.parse(get_response(:get, '/api/v1/contacts?' + params.map { |k, v| "#{k}=#{v}" }.join('&')))['contacts']
end
def add_or_update_contact(contact)
async(:async_add_or_update_contact, contact.id)
end
def async_add_or_update_contact(contact_id)
contact = account_list.contacts.find(contact_id)
if contact.prayer_letters_id.present?
update_contact(contact)
else
create_contact(contact)
end
end
def create_contact(contact)
contact_params = contact_params(contact)
json = JSON.parse(get_response(:post, '/api/v1/contacts', contact_params))
contact.update_columns(prayer_letters_id: json['contact_id'], prayer_letters_params: contact_params)
rescue AccessError
# do nothing
rescue RestClient::BadRequest => e
# BadRequest: A contact must have a name or company. Monitor those cases for pattern / underlying causes.
Rollbar.raise_or_notify(e, parameters: contact_params)
end
def contact_needs_sync?(contact)
contact_params(contact) != contact.prayer_letters_params
end
def update_contact(contact)
params = contact_params(contact)
return if params == contact.prayer_letters_params
get_response(:post, "/api/v1/contacts/#{contact.prayer_letters_id}", contact_params(contact))
contact.update_column(:prayer_letters_params, params)
rescue AccessError
# do nothing
rescue RestClient::Gone, RestClient::ResourceNotFound
handle_missing_contact(contact)
end
def handle_missing_contact(contact)
contact.update_columns(prayer_letters_id: nil, prayer_letters_params: nil)
queue_subscribe_contacts
end
def delete_contact(contact)
get_response(:delete, "/api/v1/contacts/#{contact.prayer_letters_id}")
contact.update_columns(prayer_letters_id: nil, prayer_letters_params: nil)
end
def delete_all_contacts
get_response(:delete, '/api/v1/contacts')
account_list.contacts.update_all(prayer_letters_id: nil, prayer_letters_params: nil)
end
def contact_params(contact, subscribe_format = false)
params = { name: contact.siebel_organization? ? '' : contact.envelope_greeting,
greeting: contact.greeting, file_as: contact.name, external_id: contact.id,
company: contact.siebel_organization? ? contact.name : '' }
address = contact.mailing_address
address_params = { street: address.street, city: address.city, state: address.state,
postal_code: address.postal_code,
country: address.country == 'United States' ? '' : address.country.to_s }
address_params[:country] = address.country unless address.country == 'United States'
if subscribe_format
params[:contact_id] = contact.prayer_letters_id
params[:address] = address_params
else
params.merge!(address_params)
end
params
end
def get_response(method, path, params = nil)
return unless active?
RestClient::Request.execute(method: method, url: SERVICE_URL + path, payload: params, timeout: 5000,
headers: { 'Authorization' => "Bearer #{URI.encode(oauth2_token)}" })
rescue RestClient::Unauthorized, RestClient::Forbidden
handle_bad_token
end
def handle_bad_token
update_column(:valid_token, false)
AccountMailer.delay.prayer_letters_invalid_token(account_list)
raise AccessError
end
class AccessError < StandardError
end
end
|
chuckmersereau/api_practice
|
spec/factories/contacts.rb
|
<gh_stars>0
require 'faker'
FactoryBot.define do
factory :contact do
account_list
locale 'en'
name { "#{Faker::Name.last_name}, #{Faker::Name.first_name}" }
notes 'Test Note.'
pledge_amount 100
pledge_frequency 1
pledge_start_date { 35.days.ago }
status 'Partner - Financial'
website { Faker::Internet.url }
factory :contact_with_person do
after(:create) do |contact, evaluator|
create(:person, contacts: [contact],
first_name: evaluator.name.split(', ').first,
last_name: evaluator.name.split(', ').last)
.tap { contact.reload }
end
end
trait :with_tags do
after(:create) { |contact| contact.update_attributes(tag_list: 'one, two') }
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/contact_groups.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/factories/contact_groups.rb
FactoryBot.define do
factory :contact_group do
title 'Test Post'
end
end
|
chuckmersereau/api_practice
|
spec/controllers/reports/questions_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Reports::QuestionsController, type: :controller do
end
|
chuckmersereau/api_practice
|
config/application.rb
|
<filename>config/application.rb
require File.expand_path('../boot', __FILE__)
require 'active_model/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require "sprockets/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Mpdx
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(
#{config.root}/app/concerns
#{config.root}/app/errors
#{config.root}/app/preloaders
#{config.root}/app/roles
#{config.root}/app/validators
#{config.root}/lib
)
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :en
config.active_record.schema_format = :sql
config.active_record.cache_timestamp_format = :nsec
config.active_job.queue_adapter = :sidekiq
config.active_record.raise_in_transactional_callbacks = true
config.log_formatter = ::Logger::Formatter.new
config.assets.enabled = false
config.api_only = true
config.generators do |g|
g.assets false
end
config.middleware.insert_before 0, 'Rack::MethodOverride'
config.middleware.insert_before 'ActionDispatch::ShowExceptions', 'BatchRequestHandler::Middleware',
endpoint: '/api/v2/batch',
instruments: [
'BatchRequestHandler::Instruments::Logging',
'BatchRequestHandler::Instruments::RequestValidator',
'BatchRequestHandler::Instruments::RequestLimiter',
'BatchRequestHandler::Instruments::AbortOnError'
]
config.middleware.insert_before 'BatchRequestHandler::Middleware', 'JsonWebToken::Middleware'
config.after_initialize do |app|
app.routes.append{ match '*a', :to => 'api/error#not_found', via: [:get, :post] } unless config.consider_all_requests_local
end
resid_envs = YAML.load(ERB.new(File.read(Rails.root.join('config', 'redis.yml'))).result)
redis_host, redis_port = resid_envs['session'].split(':')
config.cache_store = :redis_store, {
host: redis_host,
port: redis_port,
db: 1,
namespace: "MPDX:#{Rails.env}:cache",
expires_in: 1.day
}
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170407154800_add_concurrent_index_on_people_anniversary_month_and_day.rb
|
<reponame>chuckmersereau/api_practice
class AddConcurrentIndexOnPeopleAnniversaryMonthAndDay < ActiveRecord::Migration
# Line added for concurrency,
# see: https://robots.thoughtbot.com/how-to-create-postgres-indexes-concurrently-in
disable_ddl_transaction!
def change
add_index :people, :anniversary_day, algorithm: :concurrently
add_index :people, :anniversary_month, algorithm: :concurrently
end
end
|
chuckmersereau/api_practice
|
app/workers/contact_suggested_changes_updater_worker.rb
|
<reponame>chuckmersereau/api_practice
class ContactSuggestedChangesUpdaterWorker
include Sidekiq::Worker
sidekiq_options queue: :api_contact_suggested_changes_updater_worker
def perform(user_id, since_time)
@user = User.find_by_id(user_id)
@since_time = since_time
return unless @user
Contact.includes(:donor_accounts, account_list: :designation_accounts).where(id: contact_ids).find_each do |contact|
Contact::SuggestedChangesUpdater.new(contact: contact).update_status_suggestions
end
end
private
def contact_ids
contact_ids_with_no_suggested_changes = @user.contacts.where(suggested_changes: nil).ids
contact_ids_with_no_suggested_changes + contact_ids_with_new_donations_since_time
end
def contact_ids_with_new_donations_since_time
return [] if @since_time.blank?
Contact.joins(donor_accounts: :donations)
.where(account_list: @user.account_lists)
.where('donations.created_at >= ?', @since_time)
.ids
end
end
|
chuckmersereau/api_practice
|
db/migrate/20151019190942_clean_contact_newsletter_data.rb
|
class CleanContactNewsletterData < ActiveRecord::Migration
def change
execute("update contacts set send_newsletter = '' where send_newsletter = 'none'")
execute("update contacts set send_newsletter = 'Physical' where send_newsletter = 'physical'")
end
end
|
chuckmersereau/api_practice
|
app/services/task/analytics.rb
|
<filename>app/services/task/analytics.rb
class Task::Analytics
alias read_attribute_for_serialization send
attr_reader :tasks
def initialize(tasks)
@tasks = tasks
end
def last_electronic_newsletter_logged
tasks.completed.newsletter_email.first
end
def last_electronic_newsletter_completed_at
last_electronic_newsletter_logged.try(:completed_at)
end
def last_physical_newsletter_logged
tasks.completed.newsletter_physical.first
end
def last_physical_newsletter_completed_at
last_physical_newsletter_logged.try(:completed_at)
end
def tasks_overdue_or_due_today_counts
analyzed_types.map do |label|
{
label: label,
count: hash_of_task_activities_counts[label] || 0
}
end
end
def total_tasks_due_count
tasks.overdue_and_today.count
end
private
def analyzed_types
Task::TASK_ACTIVITIES + [nil]
end
def hash_of_task_activities_counts
@hash_of_task_activities_counts ||= tasks.overdue_and_today
.group(:activity_type)
.count
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/bulk_controller.rb
|
class Api::V2::Contacts::BulkController < Api::V2::BulkController
resource_type :contacts
def create
build_empty_contacts
persist_contacts
end
def update
load_contacts
persist_contacts
end
def destroy
load_contacts
authorize_contacts
destroy_contacts
end
private
def load_contacts
@contacts = contact_scope.where(id: contact_id_params).tap(&:first!)
end
def authorize_contacts
bulk_authorize(@contacts)
end
def destroy_contacts
@destroyed_contacts = @contacts.select(&:destroy)
render_contacts(@destroyed_contacts)
end
def pundit_user
PunditContext.new(current_user)
end
def contact_id_params
params
.require(:data)
.collect { |hash| hash[:contact][:id] }
end
def contact_scope
current_user.contacts
end
def persist_contacts
build_contacts
authorize_contacts
save_contacts
render_contacts(@contacts)
end
def render_contacts(contacts)
render json: BulkResourceSerializer.new(resources: contacts),
include: include_params,
fields: field_params
end
def save_contacts
@contacts.each { |contact| contact.save(context: persistence_context) }
end
def build_empty_contacts
@contacts = params.require(:data).map { |data| Contact.new(id: data['contact']['id']) }
end
def build_contacts
@contacts.each do |contact|
contact_index = data_attribute_index(contact)
attributes = params.require(:data)[contact_index][:contact]
contact.assign_attributes(
contact_params(attributes)
)
end
end
def data_attribute_index(contact)
params
.require(:data)
.find_index { |contact_data| contact_data[:contact][:id] == contact.id }
end
def contact_params(attributes)
attributes ||= params.require(:contact)
attributes.permit(Contact::PERMITTED_ATTRIBUTES)
end
end
|
chuckmersereau/api_practice
|
app/services/contact/name_builder.rb
|
# This service class tries to build a Contact's name in a consistent format.
# Accepts a Hash (a name already parsed and into parts), or a String (needs to be parsed).
# If given a String, it will try to guess if it's not a human name.
class Contact::NameBuilder
WORDS_THAT_INDICATE_NONHUMAN_NAME = %w(agency alliance assembly baptist bible business calvary
charitable chinese christ church city college community
company construction cornerstone corp corporation evangelical
family fellowship financial foundation friends fund god inc
incorporated insurance international life limited ltd
lutheran management methodist ministry missionary national
org organization presbyterian reformed school service trust
united university).freeze
def initialize(original_input)
@original_input = original_input
if @original_input.is_a?(Hash)
extract_parts_from_hash(@original_input)
elsif @original_input.is_a?(String)
extract_parts_from_hash(HumanNameParser.new(@original_input).parse)
else
raise ArgumentError
end
end
def name
return format_ouput(@original_input) if name_appears_to_be_nonhuman?
format_ouput(build_name_from_parts)
end
private
def extract_parts_from_hash(hash)
@first_name = hash[:first_name]
@middle_name = hash[:middle_name]
@last_name = hash[:last_name]
@spouse_first_name = hash[:spouse_first_name]
@spouse_middle_name = hash[:spouse_middle_name]
@spouse_last_name = hash[:spouse_last_name]
end
def build_name_from_parts
first_name_with_middle = [@first_name, @middle_name].select(&:present?).join(' ')
spouse_first_name_with_middle = [@spouse_first_name, @spouse_middle_name].select(&:present?).join(' ')
first_names = [first_name_with_middle, spouse_first_name_with_middle].select(&:present?).join(' and ')
last_names = [@last_name, @spouse_last_name].select(&:present?).uniq.join(' and ')
[last_names, first_names].select(&:present?).join(', ')
end
def format_ouput(output)
output.squish.titleize.gsub(/\sand\s/i, ' and ')
end
def name_appears_to_be_nonhuman?
# If the name is given in parts (not a String) then we have no choice but to make a name out of the parts.
# If the name is given as a String we try to check if it's not a human name.
return false unless @original_input.is_a?(String)
original_input_parts = @original_input.downcase.gsub(/[^[:word:]]/, ' ').squish.split(' ')
!(original_input_parts & WORDS_THAT_INDICATE_NONHUMAN_NAME).empty?
end
end
|
chuckmersereau/api_practice
|
app/concerns/address_methods.rb
|
module AddressMethods
extend ActiveSupport::Concern
# Used by the copy_address below to know which attributes to exclude
FIELDS_TO_NOT_COPY = [
:id, :addressable_id, :created_at, :updated_at, :primary_mailing_address,
:addressable_type, :remote_id, :source, :source_donor_account_id
].freeze
included do
has_many :addresses, (lambda do
where(deleted: false)
.order('addresses.primary_mailing_address::int desc')
.order(:master_address_id, :street, :created_at)
end), as: :addressable
has_many :addresses_including_deleted, class_name: 'Address', as: :addressable
has_one :primary_address, (lambda do
where(primary_mailing_address: true, deleted: false).where.not(historic: true)
.joins(:master_address).order('master_addresses.created_at', :street, :created_at)
end), class_name: 'Address', as: :addressable, autosave: true
accepts_nested_attributes_for :addresses, reject_if: :blank_or_duplicate_address?, allow_destroy: true
after_destroy :destroy_addresses
end
def blank_or_duplicate_address?(attributes)
return false if attributes['id']
place_attrs = attributes.symbolize_keys.slice(:street, :city, :state, :country, :postal_code)
place_attrs[:country] = Address.normalize_country(place_attrs[:country])
place_attrs.all? { |_, v| v.blank? } || !addresses.where(place_attrs).empty?
end
def address
primary_address || addresses.order(:created_at).first
end
def destroy_addresses
addresses.map(&:destroy!)
end
def merge_addresses
addresses_ordered = addresses.reorder('created_at desc')
return unless addresses_ordered.length > 1
addresses_ordered.each do |address|
next if address.master_address_id
address.find_or_create_master_address
address.save
end
merge_prepped_addresses(addresses_ordered)
end
def copy_address(address:, source:, source_donor_account_id: nil)
attributes = attributes_to_copy(address).merge(
source_donor_account_id: source_donor_account_id,
source: source,
primary_mailing_address: !addresses.any?(&:primary_mailing_address)
)
addresses.create!(attributes)
end
private
def attributes_to_copy(address)
address.attributes.symbolize_keys.except(*FIELDS_TO_NOT_COPY)
end
# This aims to be efficient for large numbers of duplicate addresses
def merge_prepped_addresses(addresses)
merged = Set.new
addresses.each do |address|
next if merged.include?(address)
dups = addresses.select do |a|
a.equal_to?(address) && a.id != address.id && !merged.include?(a)
end
next if dups.empty?
dups.each do |dup|
merged << dup
address.merge(dup)
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120331175134_add_pledge_amount_to_contact.rb
|
class AddPledgeAmountToContact < ActiveRecord::Migration
def change
add_column :contacts, :pledge_amount, :decimal, precision: 8, scale: 2
end
end
|
chuckmersereau/api_practice
|
app/services/tnt_import/addresses_builder.rb
|
<gh_stars>0
class TntImport::AddressesBuilder
class << self
def build_address_array(row, contact = nil, override = true)
addresses = []
%w(Home Business Other).each_with_index do |location, i|
street = row["#{location}StreetAddress"]
city = row["#{location}City"]
state = row["#{location}State"]
postal_code = row["#{location}PostalCode"]
country = row["#{location}Country"] == 'United States of America' ? 'United States' : row["#{location}Country"]
next unless [street, city, state, postal_code].any?(&:present?)
primary_address = false
primary_address = row['MailingAddressType'].to_i == (i + 1) if override
if primary_address && contact
contact.addresses.each do |address|
next if address.street == street && address.city == city && address.state == state &&
address.postal_code == postal_code && address.country == country
address.primary_mailing_address = false
address.save
end
end
attrs = { street: street, city: city, state: state, postal_code: postal_code, country: country,
location: location, region: row['Region'], primary_mailing_address: primary_address,
source: TntImport::SOURCE }
addresses << attrs unless contact.addresses.where(attrs).any?
end
addresses
end
end
end
|
chuckmersereau/api_practice
|
app/services/concerns/tnt_import/appeal_helpers.rb
|
module Concerns
module TntImport
module AppealHelpers
private
def appeal_table_name
return 'Appeal' if @xml.version < 3.2
'Campaign'
end
def appeal_id_name
return 'AppealID' if @xml.version < 3.2
'CampaignID'
end
def appeal_amount_name
return 'AppealAmount' if @xml.version < 3.2
'CampaignAmount'
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/tasks_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::TasksController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:factory_type) { :task }
let!(:resource) { create(:task, account_list: account_list, start_at: 2.days.ago) }
let!(:second_resource) { create(:task, account_list: account_list, start_at: Time.now.getlocal) }
let(:id) { resource.id }
let(:unpermitted_relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: create(:account_list).id
}
}
}
end
let(:correct_attributes) do
{
subject: 'test subject',
start_at: Time.now.getlocal,
tag_list: 'tag1'
}
end
let(:unpermitted_attributes) do
{
subject: 'test subject',
start_at: Time.now.getlocal
}
end
let(:incorrect_attributes) do
{
subject: nil
}
end
before do
resource.update(tag_list: 'tag1') # Test inclusion of related resources.
end
include_examples 'show_examples'
include_examples 'update_examples'
include_examples 'create_examples'
include_examples 'destroy_examples'
include_examples 'index_examples'
describe 'default sorting' do
before { api_login(user) }
let!(:resource_1) { create(:task, account_list: account_list, start_at: 1.minute.ago) }
let!(:resource_2) { create(:task, account_list: account_list, completed: true, start_at: 4.days.ago) }
let!(:resource_3) { create(:task, account_list: account_list, completed: true, start_at: 3.days.ago) }
let!(:resource_4) { create(:task, account_list: account_list, start_at: 2.days.from_now) }
let!(:resource_5) { create(:task, account_list: account_list, start_at: nil) }
it 'orders results by completed and start_at' do
get :index
ids = response_json['data'].map { |obj| obj['id'] }
expect(ids).to eq [
resource_1.id, resource.id, second_resource.id, resource_4.id, resource_5.id, resource_3.id, resource_2.id
]
end
end
describe 'filtering' do
before { api_login(user) }
FILTERS = (
Task::Filterer::FILTERS_TO_DISPLAY.collect(&:underscore) +
Task::Filterer::FILTERS_TO_HIDE.collect(&:underscore)
)
FILTERS.each do |filter|
context "#{filter} filter" do
let(:value) { filter == 'updated_at' ? Date.today.to_s : '' }
it 'filters results' do
get :index, filter: { filter => value }
expect(response.status).to eq(200), invalid_status_detail
expect(JSON.parse(response.body)['meta']['filter'][filter]).to eq(value)
end
end
end
context 'account_list_id filter' do
let!(:user) { create(:user_with_account) }
let!(:account_list_two) { create(:account_list) }
let!(:task_two) { create(:task, 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)
expect(JSON.parse(response.body)['data'].length).to eq(1)
end
end
end
end
|
chuckmersereau/api_practice
|
app/workers/mail_chimp/batch_results_worker.rb
|
<filename>app/workers/mail_chimp/batch_results_worker.rb
class MailChimp::BatchResultsWorker
include Sidekiq::Worker
sidekiq_options queue: :api_mail_chimp_sync_worker, unique: :until_executed
def perform(mail_chimp_account_id, batch_id)
mail_chimp_account = MailChimpAccount.find_by(id: mail_chimp_account_id)
MailChimp::BatchResults.new(mail_chimp_account).check_batch(batch_id) if mail_chimp_account
end
end
|
chuckmersereau/api_practice
|
spec/factories/person_linkedin_accounts.rb
|
FactoryBot.define do
factory :linkedin_account, class: Person::LinkedinAccount do
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
public_url 'http://example.com/username1'
authenticated true
sequence(:remote_id, &:to_s)
association :person
valid_token true
token 'MyString'
secret 'MyString'
token_expires_at { 1.day.from_now }
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/tags_controller_spec.rb
|
<filename>spec/controllers/api/v2/contacts/tags_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V2::Contacts::TagsController, type: :controller do
let(:resource_type) { :tags }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:first_tag) { 'tag_one' }
let(:second_tag) { 'tag_two' }
let(:contact) { create(:contact, account_list: account_list, tag_list: [first_tag]) }
let(:correct_attributes) { { name: second_tag } }
let(:incorrect_attributes) { { name: nil } }
let(:full_correct_attributes) do
{
contact_id: contact.id,
data: {
type: resource_type,
attributes: correct_attributes
}
}
end
let(:full_incorrect_attributes) do
{
contact_id: contact.id,
data: {
type: resource_type,
attributes: incorrect_attributes
}
}
end
describe '#index' do
let!(:account_list_two) { create(:account_list) }
let!(:contact_one) { create(:contact, account_list: account_list, tag_list: [first_tag]) }
let!(:contact_two) { create(:contact, account_list: account_list_two, tag_list: [second_tag]) }
before { user.account_lists << account_list_two }
it 'lists resources for users that are signed in' do
api_login(user)
get :index
expect(JSON.parse(response.body)['data'].length).to eq 2
expect(JSON.parse(response.body)['data'][0]['attributes']['name']).to eq first_tag
expect(JSON.parse(response.body)['data'][1]['attributes']['name']).to eq second_tag
expect(response.status).to eq(200)
end
it 'does not list resources for users that are not signed in' do
get :index
expect(response.status).to eq(401)
end
context 'account_list_id filter' do
it 'filters results' do
api_login(user)
get :index, filter: { account_list_id: account_list_two.id }
expect(response.status).to eq(200)
expect(JSON.parse(response.body)['data'].length).to eq(1)
expect(JSON.parse(response.body)['data'][0]['attributes']['name']).to eq(second_tag)
end
end
end
describe '#create' do
it 'creates resource for users that are signed in' do
api_login(user)
expect do
post :create, full_correct_attributes
end.to change { contact.reload.tag_list.length }.by(1)
expect(response.status).to eq(201)
end
it 'does not create the resource when there are errors in sent data' do
api_login(user)
expect do
post :create, full_incorrect_attributes
end.not_to change { contact.reload.tag_list.length }
expect(response.status).to eq(400)
expect(response.body).to include('errors')
expect(contact.reload.tag_list).to_not include(second_tag)
end
it 'does not create resource for users that are not signed in' do
expect do
post :create, full_correct_attributes
end.not_to change { contact.reload.tag_list.length }
expect(response.status).to eq(401)
expect(contact.reload.tag_list).to_not include(second_tag)
end
end
describe '#destroy' do
it 'deletes the resource object for users that have that access' do
api_login(user)
expect do
delete :destroy, contact_id: contact.id, tag_name: first_tag
end.to change { contact.reload.tag_list.length }.by(-1)
expect(response.status).to eq(204)
end
it 'does not destroy the resource for users that do not own the resource' do
api_login(create(:user))
expect do
delete :destroy, contact_id: contact.id, tag_name: second_tag
end.not_to change { contact.tag_list.length }
expect(response.status).to eq(403)
end
it 'does not delete the resource object for users that are not signed in' do
expect do
delete :destroy, contact_id: contact.id, tag_name: second_tag
end.not_to change { contact.tag_list.length }
expect(response.status).to eq(401)
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/people/email_addresses_controller_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/controllers/api/v2/contacts/people/email_addresses_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V2::Contacts::People::EmailAddressesController, type: :controller do
# This is required!
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:contact) { create(:contact, account_list: account_list) }
let(:person) { create(:person, contacts: [contact]) }
# This is required!
let(:factory_type) do
# This is the type used to auto-generate a resource using FactoryBot,
# ex: The type `:email_address` would be used as create(:email_address)
:email_address
end
# This is required!spec/workers/duplicate_tasks_per_contact_spec.rb
let!(:resource) do
# Creates the Singular Resource for this spec - change as needed
# Example: create(:contact, account_list: account_list)
create(:email_address, person: person)
end
let!(:second_resource) do
create(:email_address, person: person)
end
# If needed, keep this ;)
let(:id) { resource.id }
# If needed, keep this ;)
let(:parent_param) do
# This is a hash of the nested keys needed for the URL,
# If the resource is listed more than once, you can add multiple.
# Ex: /api/v2/:account_list_id/contacts/:contact_id/addresses/:id
# --
# Note: Don't include :id
# Example: { account_list_id: account_list_id }
{
contact_id: contact.id,
person_id: person.id
}
end
# This is required!
let(:correct_attributes) do
# A hash of correct attributes for creating/updating the resource
# Example: { subject: 'test subject', start_at: Time.now, account_list_id: account_list.id }
{
email: '<EMAIL>',
historic: false,
location: 'mobile',
primary: true
}
end
# This is required!
let(:incorrect_attributes) do
# A hash of attributes that will fail validations
# Example: { subject: nil, account_list_id: account_list.id } }
# --
# If there aren't attributes that violate validations,
# you need to specifically return `nil`
{
email: 'INVALID_EMAIL!!!!!!!',
historic: false,
location: 'mobile',
primary: true
}
end
# These includes can be found in:
# spec/support/shared_controller_examples.rb
include_examples 'index_examples'
include_examples 'show_examples'
include_examples 'create_examples'
include_examples 'update_examples'
include_examples 'destroy_examples'
end
|
chuckmersereau/api_practice
|
config/initializers/redis.rb
|
require 'redis'
require 'redis/objects'
require 'redis/namespace'
redis_config = YAML.load(ERB.new(File.read(Rails.root.join('config', 'redis.yml'))).result)
host, port = redis_config[Rails.env].split(':')
Redis.current = Redis::Namespace.new("MPDX:#{Rails.env}", redis: Redis.new(host: host, port: port))
|
chuckmersereau/api_practice
|
dev/util/dev_user_util.rb
|
def add_dev_user(account_list)
dev_user.account_list_users.create(account_list: account_list)
end
def dev_user_back_to_normal
dev_user.account_list_users.select do |alu|
alu.account_list != dev_account
end.map(&:destroy)
end
def dev_user(id = nil)
id ||= ENV['DEV_USER_ID']
return @dev_user if @dev_user || id.blank?
@dev_user = User.find_by(id: id)
::Audited.store[:audited_user] = @dev_user
end
def dev_account(id = nil)
id ||= ENV['DEV_ACCOUNT_LIST_ID']
@dev_account ||= AccountList.find_by(id: id)
end
|
chuckmersereau/api_practice
|
spec/serializers/user_serializer_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/serializers/user_serializer_spec.rb
require 'rails_helper'
RSpec.describe UserSerializer, type: :serializer do
describe '#preferences' do
describe 'no account lists' do
let(:user) { create(:user) }
let(:parsed_json) { JSON.parse(UserSerializer.new(user).to_json) }
it 'setup returns no account_lists' do
expect(parsed_json['preferences']['setup']).to eq('no account_lists')
end
end
describe 'no default_account_list' do
let(:account_list) { create(:account_list) }
let(:user) { create(:user, account_lists: [account_list]) }
let(:parsed_json) { JSON.parse(UserSerializer.new(user).to_json) }
it 'setup returns no default_account_list' do
expect(parsed_json['preferences']['setup']).to eq('no default_account_list')
end
end
describe 'no organization_account on default_account_list' do
let(:account_list) { create(:account_list) }
let(:user) do
create(:user,
account_lists: [account_list],
preferences: { default_account_list: account_list.id })
end
let(:parsed_json) { JSON.parse(UserSerializer.new(user).to_json) }
it 'setup returns no organization_account on default_account_list' do
expect(parsed_json['preferences']['setup']).to eq('no organization_account on default_account_list')
end
end
describe 'organization_account on default_account_list' do
let!(:organization_account) { create(:organization_account, user: user) }
let(:account_list) { create(:account_list) }
let(:user) do
create(:user,
account_lists: [account_list],
preferences: { default_account_list: account_list.id })
end
let(:parsed_json) { JSON.parse(UserSerializer.new(user).to_json) }
it 'setup returns false' do
expect(parsed_json['preferences']['setup']).to be_nil
end
it 'default_account_list returns default_account_list.id' do
expect(parsed_json['preferences']['default_account_list']).to eq(account_list.id)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/reports/questions_controller_spec.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
require 'rails_helper'
RSpec.describe Api::V2::Reports::QuestionsController, type: :controller do
end
|
chuckmersereau/api_practice
|
app/services/csv_value_to_constant_mappings.rb
|
<gh_stars>0
# This class takes in import.file_constants_mappings on its initializer
# It simplifies conversion of CSV values to MPDX Constants and ensures
# there are no values mapped incorrectly
class CsvValueToConstantMappings
attr_accessor :mappings
def initialize(mappings)
@mappings = mappings.with_indifferent_access
end
def constant_names
mappings.keys
end
def convert_value_to_constant_id(constant_name, value)
constant_hash = find_constant_hash(constant_name, value)
return unless constant_hash
return constant_hash['key'] if constant_name == 'pledge_frequency'
constant_hash['id']
end
def find_unsupported_constants(constant_name)
mapping_ids = mappings[constant_name].collect { |hash| hash['id'] }.flatten
mapping_ids - (CsvImport.constants.with_indifferent_access[constant_name].map { |constant| constant['id'] } | [''])
end
def find_mapped_values(constant_name)
mappings[constant_name].collect { |hash| hash.with_indifferent_access['values'] }.flatten
end
protected
def find_constant_hash(constant_name, value)
value = '' if value.blank?
constant_id = find_constant_id_from_value(mappings[constant_name] || {}, value)
CsvImport.constants.with_indifferent_access[constant_name]&.find do |constant|
constant['id'] == constant_id
end
end
def find_constant_id_from_value(mapping, value)
mapping.find do |object|
object['values']&.include?(value)
end.try(:[], 'id')
end
end
|
chuckmersereau/api_practice
|
spec/services/reports/monthly_giving_graph_spec.rb
|
require 'rails_helper'
RSpec.describe Reports::MonthlyGivingGraph, type: :model do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:organization) { create(:organization) }
let(:designation_account) do
create(:designation_account, organization: organization)
end
let(:contact) { create(:contact, account_list: account_list) }
let(:donor_account) { create(:donor_account, organization: organization) }
let!(:donation) do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
donation_date: Date.parse('2099-03-04'),
amount: '1100')
end
let(:time_now) { Time.zone.parse('2099-06-22 12:34:56') }
subject { described_class.new(account_list: account_list) }
def mock_time
allow(Time).to receive(:current).and_return(time_now)
allow(Date).to receive(:today).and_return(time_now.to_date)
end
before do
contact.donor_accounts << donor_account
account_list.designation_accounts << designation_account
end
describe 'initializes' do
it 'initializes successfully' do
expect(subject).to be_a(Reports::MonthlyGivingGraph)
expect(subject.account_list).to eq(account_list)
end
end
describe '#totals' do
before { mock_time }
it { expect(subject.totals).to be_an Array }
it { expect(subject.totals).not_to be_empty }
it { expect(subject.totals.first[:currency]).to eq donation.currency }
it { expect(subject.totals.first[:total_amount]).to eq donation.amount }
end
describe '#pledges' do
it { expect(subject.pledges).to be_a Numeric }
it { expect(subject.pledges).to eq contact.pledge_amount.to_i }
end
describe '#monthly_average' do
it { expect(subject.monthly_average).to be_a Numeric }
it 'averages donations in the period requested' do
mock_time
expect(subject.monthly_average).to eq 100
end
it 'does not include donations made in the current month' do
mock_time
create(:donation, donor_account: donor_account,
designation_account: designation_account,
donation_date: Date.parse('2099-06-04'),
amount: '100')
expect(subject.monthly_average).to eq 100
end
end
describe '#months_to_dates' do
it { expect(subject.months_to_dates).to be_an Array }
it { expect(subject.months_to_dates).not_to be_empty }
it { expect(subject.months_to_dates.first).to be_a Date }
it do
mock_time
expect(subject.months_to_dates.first).to eq Date.parse('2098-07-01')
end
end
describe '#salary_currency' do
it { expect(subject.salary_currency).to be_a String }
it { expect(subject.salary_currency).to eq organization.default_currency_code }
end
describe '#display_currency' do
it { expect(subject.display_currency).to be_a String }
it { expect(subject.display_currency).to eq organization.default_currency_code }
context 'display_currency set' do
subject { Reports::MonthlyGivingGraph.new(account_list: account_list, display_currency: 'NZD') }
it { expect(subject.display_currency).to eq 'NZD' }
end
end
describe '#multi_currency' do
it { expect(subject.multi_currency).to be false }
end
describe '#number_of_months_in_range' do
it { expect(subject.send(:number_of_months_in_range)).to be_a Numeric }
it 'excludes last month if that month is the current month' do
mock_time
expect(subject.send(:number_of_months_in_range)).to eq 11
end
context 'has filter_params where end date is not in current month' do
before { mock_time }
subject do
described_class.new(account_list: account_list,
filter_params: {
donation_date: (Date.today - 14.months)...(Date.today - 2.months)
})
end
it 'includes last month' do
mock_time
expect(subject.send(:number_of_months_in_range)).to eq 13
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20151221004231_create_partner_status_logs.rb
|
class CreatePartnerStatusLogs < ActiveRecord::Migration
def change
create_table :partner_status_logs do |t|
t.integer :contact_id, null: false
t.date :recorded_on, null: false
t.string :status
t.decimal :pledge_amount
t.decimal :pledge_frequency
t.boolean :pledge_received
t.date :pledge_start_date
t.timestamps null: false
end
add_index :partner_status_logs, :contact_id
add_index :partner_status_logs, :recorded_on
end
end
|
chuckmersereau/api_practice
|
spec/services/account_list/from_designations_finder_spec.rb
|
<filename>spec/services/account_list/from_designations_finder_spec.rb
require 'rails_helper'
describe AccountList::FromDesignationsFinder, '#account_list' do
it 'returns nil if no account list contains the specified designations' do
org = create(:organization)
finder = AccountList::FromDesignationsFinder.new('1', org.id)
expect(finder.account_list).to be_nil
end
it 'returns the account list whose designations for that organization match' do
org1 = create(:organization)
org2 = create(:organization)
da1 = create(:designation_account, designation_number: '1', organization: org1)
da2 = create(:designation_account, designation_number: '2', organization: org1)
da3 = create(:designation_account,
designation_number: '3',
organization: org1,
name: '<NAME> (Imported from TntConnect)')
da4 = create(:designation_account, designation_number: '4', organization: org2)
account_list = create(:account_list)
account_list.designation_accounts << [da1, da2, da3, da4]
finder = AccountList::FromDesignationsFinder.new(%w(1 2), org1.id)
expect(finder.account_list).to eq account_list
end
it 'returns nil if no account list whose designations for that org match' do
org = create(:organization)
da1 = create(:designation_account, designation_number: '1', organization: org)
da2 = create(:designation_account, designation_number: '2', organization: org)
account_list = create(:account_list)
account_list.designation_accounts << [da1, da2]
finder = AccountList::FromDesignationsFinder.new(%w(1), org.id)
expect(finder.account_list).to be_nil
end
it 'returns nil if no account list contains all the specified designations' do
org = create(:organization)
da1 = create(:designation_account, designation_number: '1', organization: org)
account_list = create(:account_list)
account_list.designation_accounts << da1
create(:designation_account, designation_number: '2', organization: org)
finder = AccountList::FromDesignationsFinder.new(%w(1 2), org.id)
expect(finder.account_list).to be_nil
end
end
|
chuckmersereau/api_practice
|
spec/controllers/concerns/bulk_taggable_spec.rb
|
<filename>spec/controllers/concerns/bulk_taggable_spec.rb
require 'rails_helper'
class BulkTaggableTestController < Api::V2Controller
include BulkTaggable
resource_type :tags
skip_before_action :validate_and_transform_json_api_params
skip_after_action :verify_authorized
end
describe Api::V2Controller do
let!(:user) { create(:user_with_account) }
let!(:contact) { create(:contact) }
let(:data_param) do
{ data: { attributes: { name: name_param }, type: 'tags' } }
end
describe '#tag_names' do
controller BulkTaggableTestController do
def show
Contact.first.tag_list.add(*tag_names)
end
end
before do
routes.draw { get 'show' => 'bulk_taggable_test#show' }
api_login(user)
end
context 'valid tag name field' do
let(:name_param) { 'valid tag' }
it 'will not raise an error' do
expect { get :show, data: [data_param] }.not_to raise_error
end
it 'returns a status of HTTP 200: OK' do
get :show, data: [data_param]
expect(response.status).to eq(200)
end
end
context 'the provided tag name was not a string' do
let(:name_param) do
{ id: '12345678-b508-11e7-be77-9dcc9b77300c', name: 'not a string' }
end
it 'will not raise an error' do
expect { get :show, data: [data_param] }.not_to raise_error
end
it 'returns a status of HTTP 400: Bad Request' do
get :show, data: [data_param]
expect(response.status).to eq(400)
end
it 'returns a helpful error message' do
get :show, data: [data_param]
expect(response_json['errors'][0]['detail']).to include \
'Expected tag name to be a string, but it was an object'
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/designation_account/dup_by_balance_fix_spec.rb
|
require 'rails_helper'
describe DesignationAccount::DupByBalanceFix, '#deactivate_dups!' do
it 'returns false if no designation accounts were marked inactive' do
da = create(:designation_account, active: true, balance: nil)
result = DesignationAccount::DupByBalanceFix.deactivate_dups(DesignationAccount.all)
expect(result).to be false
expect(da.reload.active).to be true
end
it 'returns true and deactivates single person designation for dup balance' do
da1 = create(:designation_account, name: 'John', active: true, balance: 10.1)
da2 = create(:designation_account, name: '<NAME>', active: true,
balance: 10.1)
result = DesignationAccount::DupByBalanceFix.deactivate_dups(DesignationAccount.all)
expect(result).to be true
expect(da1.reload.active).to be false
expect(da1.balance).to eq 0.0
expect(da2.reload.active).to be true
end
it 'does not consider a zero balance to be a dup' do
da1 = create(:designation_account, name: '<NAME>', active: true, balance: 0)
da2 = create(:designation_account, name: '<NAME>', active: true,
balance: 0)
result = DesignationAccount::DupByBalanceFix.deactivate_dups(DesignationAccount.all)
expect(result).to be false
expect(da1.reload.active).to be true
expect(da2.reload.active).to be true
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/tasks/tags/bulk_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::Tasks::Tags::BulkController, type: :controller do
let(:resource_type) { :tags }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:first_tag) { 'tag_one' }
let(:second_tag) { 'tag_two' }
let(:task_one) { create(:task, account_list: account_list, tag_list: [first_tag]) }
let(:task_two) { create(:task, account_list: account_list, tag_list: [second_tag]) }
let(:params) do
{
data: [{
data: {
type: 'tags',
attributes: {
name: first_tag
}
}
}]
}
end
describe '#create' do
it 'creates the tag object for users that have that access' do
api_login(user)
expect do
post :create, params
end.to change { task_two.reload.tag_list.length }.by(1)
expect(response.status).to eq(200)
end
context 'with task_ids filter' do
let(:params) do
{
data: [{
data: {
type: 'tags',
attributes: {
name: first_tag
}
}
}, {
data: {
type: 'tags',
attributes: {
name: second_tag
}
}
}]
}
end
let(:filter_params) do
{
filter: {
task_ids: task_two.id
}
}
end
it 'applies the tag to the specified tasks' do
api_login(user)
expect do
post :create, params.merge(filter_params)
end.to change { task_two.reload.tag_list.length }.by(1)
expect(response.status).to eq(200)
end
it 'does not apply the tag to unspecified tasks' do
api_login(user)
expect do
post :create, params.merge(filter_params)
end.to_not change { task_one.reload.tag_list.length }
expect(response.status).to eq(200)
end
end
it 'does not create the tag for users that do not own the task' do
api_login(create(:user_with_account))
expect do
post :create, params
end.not_to change { task_two.reload.tag_list.length }
expect(response.status).to eq(404)
end
it 'does not create the tag object for users that are not signed in' do
expect do
post :create, params
end.not_to change { task_two.reload.tag_list.length }
expect(response.status).to eq(401)
end
end
describe '#destroy' do
it 'deletes the resource object for users that have that access' do
api_login(user)
expect do
delete :destroy, params
end.to change { task_one.reload.tag_list.length }.by(-1)
expect(response.status).to eq(204)
end
it 'does not destroy the resource for users that do not own the resource' do
api_login(create(:user_with_account))
expect do
delete :destroy, params
end.not_to change { task_one.reload.tag_list.length }
expect(response.status).to eq(404)
end
it 'does not delete the resource object for users that are not signed in' do
expect do
delete :destroy, params
end.not_to change { task_one.reload.tag_list.length }
expect(response.status).to eq(401)
end
end
end
|
chuckmersereau/api_practice
|
spec/lib/google_contact_sync_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
require 'google_contact_sync'
describe GoogleContactSync do
let(:sync) { GoogleContactSync }
let(:contact) { build(:contact) }
let(:g_contact_link) { build(:google_contact, last_data: { emails: [], websites: [], phone_numbers: [] }) }
let(:person) do
build(:person, first_name: 'John',
last_name: 'Doe',
middle_name: 'Henry',
title: 'Mr',
suffix: 'III',
occupation: 'Worker',
employer: 'Company, Inc')
end
let(:g_contact) do
GoogleContactsApi::Contact.new(
'gd$etag' => 'a',
'id' => { '$t' => '1' },
'gd$name' => { 'gd$givenName' => { '$t' => 'John' }, 'gd$familyName' => { '$t' => 'Doe' } }
)
end
before { stub_smarty_streets }
describe 'sync_notes' do
describe 'first sync' do
it 'sets blank mpdx notes with google contact notes' do
g_contact['content'] = { '$t' => 'google notes' }
contact.notes = ''
sync.sync_notes(contact, g_contact, g_contact_link)
expect(contact.notes).to eq('google notes')
expect(g_contact.prepped_changes).to eq({})
end
it 'sets blank google contact notes to mpdx notes' do
g_contact['content'] = { '$t' => '' }
contact.notes = 'mpdx notes'
sync.sync_notes(contact, g_contact, g_contact_link)
expect(contact.notes).to eq('mpdx notes')
expect(g_contact.prepped_changes).to eq(content: 'mpdx notes')
end
it 'prefer mpdx if both are present' do
g_contact['content'] = { '$t' => 'google notes' }
contact.notes = 'mpdx notes'
sync.sync_notes(contact, g_contact, g_contact_link)
expect(contact.notes).to eq('mpdx notes')
expect(g_contact.prepped_changes).to eq(content: 'mpdx notes')
end
it 'removes vertical tabs (\v) from both mpdx and google because is an invalid and non-escapable for XML' do
g_contact['content'] = { '$t' => '' }
contact.notes = "notes with vertical tab initially then newline: \v"
sync.sync_notes(contact, g_contact, g_contact_link)
expect(contact.notes).to eq("notes with vertical tab initially then newline: \n")
expect(g_contact.prepped_changes).to eq(content: "notes with vertical tab initially then newline: \n")
end
it 'handles nil values for MPDX and Google' do
g_contact['content'] = {}
contact.notes = nil
sync.sync_notes(contact, g_contact, g_contact_link)
expect(contact.notes).to be_nil
expect(g_contact.prepped_changes).to eq({})
end
end
describe 'subsequent sync' do
let(:g_contact_link) { build(:google_contact, last_data: { content: 'old notes' }) }
it 'sets google to mpdx if only mpdx changed' do
g_contact['content'] = { '$t' => 'old notes' }
contact.notes = 'new mpdx notes'
sync.sync_notes(contact, g_contact, g_contact_link)
expect(contact.notes).to eq('new mpdx notes')
expect(g_contact.prepped_changes).to eq(content: 'new mpdx notes')
end
it 'sets mpdx to google if only google changed' do
g_contact['content'] = { '$t' => 'new google notes' }
contact.notes = 'old notes'
sync.sync_notes(contact, g_contact, g_contact_link)
expect(contact.notes).to eq('new google notes')
expect(g_contact.prepped_changes).to eq({})
end
it 'sets mpdx to google if both changed' do
g_contact['content'] = { '$t' => 'new google notes' }
contact.notes = 'new mpdx notes'
sync.sync_notes(contact, g_contact, g_contact_link)
expect(contact.notes).to eq('new mpdx notes')
expect(g_contact.prepped_changes).to eq(content: 'new mpdx notes')
end
it 'sets google to blank if mpdx changed to blank' do
g_contact['content'] = { '$t' => 'google notes' }
contact.notes = ''
sync.sync_notes(contact, g_contact, g_contact_link)
expect(contact.notes).to eq('')
expect(g_contact.prepped_changes).to eq(content: '')
end
end
end
describe 'sync_basic_person_fields' do
it 'sets blank mpdx fields with google contact fields' do
person.update(title: nil, first_name: '', middle_name: nil, last_name: '', suffix: '')
g_contact['gd$name'] = {
'gd$namePrefix' => { '$t' => 'Mr' },
'gd$givenName' => { '$t' => 'John' },
'gd$additionalName' => { '$t' => 'Henry' },
'gd$familyName' => { '$t' => 'Doe' },
'gd$nameSuffix' => { '$t' => 'III' }
}
sync.sync_basic_person_fields(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq({})
expect(person.first_name).to eq('John')
expect(person.last_name).to eq('Doe')
end
it 'sets blank google fields to mpdx fields' do
person.update(title: 'Mr', middle_name: 'Henry', suffix: 'III')
g_contact['gd$name'] = {}
sync.sync_basic_person_fields(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq(given_name: 'John', family_name: 'Doe')
end
it 'prefers mpdx if both are present' do
g_contact['gd$name'] = {
'gd$namePrefix' => { '$t' => 'Not-Mr' },
'gd$givenName' => { '$t' => 'Not-John' },
'gd$additionalName' => { '$t' => 'Not-Henry' },
'gd$familyName' => { '$t' => 'Not-Doe' },
'gd$nameSuffix' => { '$t' => 'Not-III' }
}
person.update(title: 'Mr', middle_name: 'Henry', suffix: 'III')
sync.sync_basic_person_fields(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq(given_name: 'John', family_name: 'Doe')
expect(person.first_name).to eq('John')
expect(person.last_name).to eq('Doe')
end
it 'syncs changes between mpdx and google, but prefers mpdx if both changed' do
g_contact_link =
build(:google_contact,
last_data: {
name_prefix: 'Mr',
given_name: 'John',
additional_name: 'Henry',
family_name: 'Doe',
name_suffix: 'III'
})
g_contact['gd$name'] = {
'gd$namePrefix' => { '$t' => 'Mr-Google' },
'gd$givenName' => { '$t' => 'John' },
'gd$additionalName' => { '$t' => 'Henry' },
'gd$familyName' => { '$t' => 'Doe-Google' },
'gd$nameSuffix' => { '$t' => 'III' }
}
person.update(
title: 'Mr',
first_name: 'John-MPDX',
middle_name: 'Henry-MPDX',
last_name: 'Doe-MPDX',
suffix: 'III'
)
sync.sync_basic_person_fields(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq(given_name: 'John-MPDX', family_name: 'Doe-MPDX')
expect(person.first_name).to eq('John-MPDX')
expect(person.last_name).to eq('Doe-MPDX')
end
end
describe 'sync_employer_and_title' do
describe 'first sync' do
it 'sets blank mpdx employer and occupation from google' do
person.employer = ''
person.occupation = nil
g_contact['gd$organization'] =
[{ 'gd$orgName' => { '$t' => 'Company' }, 'gd$orgTitle' => { '$t' => 'Worker' } }]
sync.sync_employer_and_title(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq({})
expect(person.employer).to eq('Company')
expect(person.occupation).to eq('Worker')
end
it 'sets blank google employer and occupation from mpdx' do
person.employer = 'Company'
person.occupation = 'Worker'
g_contact['gd$organization'] = []
sync.sync_employer_and_title(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq(organizations: [{ org_name: 'Company', org_title: 'Worker',
primary: true, rel: 'work' }])
expect(person.employer).to eq('Company')
expect(person.occupation).to eq('Worker')
end
it 'prefers mpdx if both are present' do
person.employer = 'Company'
person.occupation = 'Worker'
g_contact['gd$organization'] =
[{ 'gd$orgName' => { '$t' => 'Not-Company' }, 'gd$orgTitle' => { '$t' => 'Not-Worker' } }]
sync.sync_employer_and_title(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq(organizations: [{ org_name: 'Company', org_title: 'Worker',
primary: true, rel: 'work' }])
expect(person.employer).to eq('Company')
expect(person.occupation).to eq('Worker')
end
end
describe 'subsequent syncs' do
let(:g_contact_link) do
build(:google_contact,
last_data: {
organizations: [{ org_name: 'Old Company', org_title: 'Old Title' }]
})
end
it 'syncs changes from mpdx to google' do
person.employer = '<NAME>'
person.occupation = 'MPDX Title'
g_contact['gd$organization'] =
[{ 'gd$orgName' => { '$t' => 'Old Company' }, 'gd$orgTitle' => { '$t' => 'Old Title' } }]
sync.sync_employer_and_title(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq(organizations: [{ org_name: 'MPDX Company', org_title: 'MPDX Title',
primary: true, rel: 'work' }])
expect(person.employer).to eq('MPDX Company')
expect(person.occupation).to eq('MPDX Title')
end
it 'syncs changes from google to mpdx' do
person.employer = '<NAME>'
person.occupation = 'Old Title'
g_contact['gd$organization'] =
[{ 'gd$orgName' => { '$t' => 'Google Company' }, 'gd$orgTitle' => { '$t' => 'Google Title' } }]
sync.sync_employer_and_title(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq({})
expect(person.employer).to eq('Google Company')
expect(person.occupation).to eq('Google Title')
end
it 'prefers mpdx if both changed' do
person.employer = '<NAME>'
person.occupation = 'MPDX Title'
g_contact['gd$organization'] =
[{ 'gd$orgName' => { '$t' => 'Gogle Company' }, 'gd$orgTitle' => { '$t' => 'Google Title' } }]
sync.sync_employer_and_title(person, g_contact, g_contact_link)
expect(g_contact.prepped_changes).to eq(organizations: [{ org_name: 'MPDX Company', org_title: 'MPDX Title',
primary: true, rel: 'work' }])
expect(person.employer).to eq('MPDX Company')
expect(person.occupation).to eq('MPDX Title')
end
end
end
describe 'sync numbers' do
it 'combines and formats numbers from mpdx and google' do
person.phone_number = { number: '+12123334444', location: 'mobile', primary: true }
person.save
g_contact.update('gd$phoneNumber' => [{
'$t' => '(717) 888-9999',
'primary' => 'true',
'rel' => 'http://schemas.google.com/g/2005#other'
}])
sync.sync_numbers(g_contact, person, g_contact_link)
expect(g_contact.prepped_changes).to eq(phone_numbers: [
{ number: '(717) 888-9999', primary: true, rel: 'other' },
{ number: '(212) 333-4444', primary: false, rel: 'mobile' }
])
expect(person.phone_numbers.count).to eq(2)
phone1 = person.phone_numbers.first
expect(phone1.number).to eq('+12123334444')
expect(phone1.location).to eq('mobile')
expect(phone1.primary).to be true
phone2 = person.phone_numbers.last
expect(phone2.number).to eq('+17178889999')
expect(phone2.location).to eq('other')
expect(phone2.primary).to be false
end
it 'normalizes the numbers for comparison between mpdx and google' do
person.phone_number = { number: '+12123334444', location: 'mobile', primary: true }
person.save
person.phone_numbers.first.update_column(:number, '2123334444')
g_contact.update('gd$phoneNumber' => [{
'$t' => '(212) 333-4444',
'primary' => 'true',
'rel' => 'http://schemas.google.com/g/2005#other'
}])
sync.sync_numbers(g_contact, person, g_contact_link)
expect(g_contact.prepped_changes).to eq(phone_numbers: [
{ number: '(212) 333-4444', primary: true, rel: 'other' }
])
person.save
expect(person.phone_numbers.count).to eq(1)
expect(person.phone_numbers.first.number).to eq('2123334444')
end
it 'excludes blank numbers from google sync' do
expect_number_excluded(' ')
end
it 'excludes numbers that will be blank when normalized from sync' do
expect_number_excluded('(')
end
def expect_number_excluded(number)
person.phone_number = { number: '+12123334444', location: 'mobile', primary: true }
person.save
# Set the blank number via update_column to skip validation
person.phone_numbers.first.update_column(:number, number)
sync.sync_numbers(g_contact, person, g_contact_link)
expect(g_contact.prepped_changes[:phone_numbers]).to be_empty
end
end
describe 'sync addresses' do
it 'combines addresses from mpdx and google by master address comparison which uses SmartyStreets' do
WebMock.reset!
stub_google_geocoder
richmond_smarty = '[{"input_index":0,"candidate_index":0,"delivery_line_1":"7229 Forest Ave Ste 208",'\
'"last_line":"Richmond VA 23226-3765","delivery_point_barcode":"232263765581",'\
'"components":{"primary_number":"7229","street_name":"Forest","street_suffix":"Ave",'\
'"secondary_number":"208","secondary_designator":"Ste","city_name":"Richmond",'\
'"state_abbreviation":"VA","zipcode":"23226","plus4_code":"3765",'\
'"delivery_point":"58","delivery_point_check_digit":"1"},'\
'"metadata":{"record_type":"H","zip_type":"Standard","county_fips":"51087",'\
'"county_name":"Henrico","carrier_route":"C023","congressional_district":"07",'\
'"rdi":"Commercial","elot_sequence":"0206","elot_sort":"A","latitude":37.60519,'\
'"longitude":-77.52963,"precision":"Zip9","time_zone":"Eastern","utc_offset":-5.0,"dst":true},'\
'"analysis":{"dpv_match_code":"Y","dpv_footnotes":"AABB","dpv_cmra":"N",'\
'"dpv_vacant":"N","active":"Y","footnotes":"N#"}}]'
anchorage_smarty = '[{"input_index":0,"candidate_index":0,"delivery_line_1":"2421 E Tudor Rd Ste 102",'\
'"last_line":"Anchorage AK 99507-1166","delivery_point_barcode":"995071166277",'\
'"components":{"primary_number":"2421","street_predirection":"E","street_name":"Tudor",'\
'"street_suffix":"Rd","secondary_number":"102","secondary_designator":"Ste",'\
'"city_name":"Anchorage","state_abbreviation":"AK","zipcode":"99507","plus4_code":"1166",'\
'"delivery_point":"27","delivery_point_check_digit":"7"},'\
'"metadata":{"record_type":"H","zip_type":"Standard","county_fips":"02020",'\
'"county_name":"Anchorage","carrier_route":"C024","congressional_district":"AL",'\
'"rdi":"Commercial","elot_sequence":"0106","elot_sort":"D","latitude":61.18135,'\
'"longitude":-149.83548,"precision":"Zip9","time_zone":"Alaska","utc_offset":-9.0,"dst":true},'\
'"analysis":{"dpv_match_code":"Y","dpv_footnotes":"AABB","dpv_cmra":"N",'\
'"dpv_vacant":"N","active":"Y","footnotes":"N#"}}]'
{
'city=orlando&state=fl&street=100%20lake%20hart%20dr.&zipcode=32832' => '[]',
'city=springfield&state=il&street=1025%20south%206th%20street&zipcode=62703' => '[]',
'city=richmond&state=va&street=7229%20forest%20avenue%20%23208&zipcode=23226' => richmond_smarty,
'city=richmond&state=va&street=7229%20forest%20ave.&street2=apt%20208&zipcode=23226' => richmond_smarty,
'city=richmond&state=va&street=7229%20forest%20ave%20suite%20208&zipcode=23226-3765' => richmond_smarty,
'city=anchorage&state=ak&street=2421%20east%20tudor%20road%20%23102&zipcode=99507-1166' => anchorage_smarty,
'city=anchorage&state=ak&street=2421%20e.%20tudor%20rd.&street2=apt%20102&zipcode=99507' => anchorage_smarty
}.each do |query, result|
smarty_url = "https://api.smartystreets.com/street-address/?auth-id=#{ENV.fetch('SMARTY_AUTH_ID')}"\
"&auth-token=#{ENV.fetch('SMARTY_AUTH_TOKEN')}&candidates=2&#{query}"
stub_request(:get, smarty_url)
.to_return(body: result)
end
contact.save!
person2 = create(:person, first_name: 'Jane', last_name: 'Doe')
person.save
contact.people << person
contact.people << person2
contact.addresses_attributes = [
{ street: '7229 Forest Avenue #208', city: 'Richmond', state: 'VA', postal_code: '23226',
country: 'United States', location: 'Home', primary_mailing_address: true },
{ street: '100 Lake Hart Dr.', city: 'Orlando', state: 'FL', postal_code: '32832',
country: 'United States', location: 'Business', primary_mailing_address: false }
]
contact.save!
contact.reload
expect(contact.addresses.where(historic: false).count).to eq(2)
g_contact1 = g_contact
g_contact2 = GoogleContactsApi::Contact.new(g_contact, nil, nil)
g_contact1['gd$structuredPostalAddress'] = [
{ 'rel' => 'http://schemas.google.com/g/2005#home', 'primary' => 'false',
'gd$street' => { '$t' => "7229 Forest Ave.\nApt 208" }, 'gd$city' => { '$t' => 'Richmond' },
'gd$region' => { '$t' => 'VA' }, 'gd$postcode' => { '$t' => '23226' },
'gd$country' => { '$t' => 'United States of America' } },
{ 'rel' => 'http://schemas.google.com/g/2005#other', 'primary' => 'false',
'gd$street' => { '$t' => '2421 East Tudor Road #102' }, 'gd$city' => { '$t' => 'Anchorage' },
'gd$region' => { '$t' => 'AK' }, 'gd$postcode' => { '$t' => '99507-1166' },
'gd$country' => { '$t' => 'United States of America' } },
{ 'rel' => 'http://schemas.google.com/g/2005#work', 'primary' => 'true',
'gd$street' => { '$t' => '1025 South 6th Street' }, 'gd$city' => { '$t' => 'Springfield' },
'gd$region' => { '$t' => 'IL' }, 'gd$postcode' => { '$t' => '62703' },
'gd$country' => { '$t' => 'United States of America' } }
]
g_contact2['gd$structuredPostalAddress'] = [
{ 'rel' => 'http://schemas.google.com/g/2005#home', 'primary' => 'false',
'gd$street' => { '$t' => '7229 Forest Ave Suite 208' }, 'gd$city' => { '$t' => 'Richmond' },
'gd$region' => { '$t' => 'VA' }, 'gd$postcode' => { '$t' => '23226-3765' },
'gd$country' => { '$t' => 'United States of America' } },
{ 'rel' => 'http://schemas.google.com/g/2005#other', 'primary' => 'true',
'gd$street' => { '$t' => "2421 E. Tudor Rd.\nApt 102" }, 'gd$city' => { '$t' => 'Anchorage' },
'gd$region' => { '$t' => 'AK' }, 'gd$postcode' => { '$t' => '99507' },
'gd$country' => { '$t' => 'United States of America' } }
]
g_contacts = [g_contact1, g_contact2]
g_contact_links = [
build(:google_contact, last_data: { addresses: [] }),
build(:google_contact, last_data: { addresses: [] })
]
sync.sync_addresses(g_contacts, contact, g_contact_links)
g_contact_addresses = [
{ rel: 'home', primary: false,
street: "7229 Forest Ave.\nApt 208", city: 'Richmond', region: 'VA', postcode: '23226',
country: 'United States of America' },
{ rel: 'other', primary: false,
street: '2421 East Tudor Road #102', city: 'Anchorage', region: 'AK', postcode: '99507-1166',
country: 'United States of America' },
{ rel: 'work', primary: false,
street: '1025 South 6th Street', city: 'Springfield', region: 'IL', postcode: '62703',
country: 'United States of America' },
{ rel: 'work', primary: false,
street: '100 Lake Hart Dr.', city: 'Orlando', region: 'FL', postcode: '32832',
country: 'United States of America' }
]
expect(g_contacts[0].prepped_changes).to eq(addresses: g_contact_addresses)
expect(g_contacts[1].prepped_changes).to eq(addresses: g_contact_addresses)
contact.reload
addresses = contact.addresses.order(:state).map do |address|
address.attributes.symbolize_keys.slice(:street, :city, :state, :postal_code, :country, :location,
:primary_mailing_address)
end
expect(addresses.to_set).to eq([
{ street: '7229 Forest Avenue #208', city: 'Richmond', state: 'VA', postal_code: '23226',
country: 'United States', location: 'Home', primary_mailing_address: true },
{ street: '2421 East Tudor Road #102', city: 'Anchorage', state: 'AK', postal_code: '99507-1166',
country: 'United States', location: 'Other', primary_mailing_address: false },
{ street: '100 Lake Hart Dr.', city: 'Orlando', state: 'FL', postal_code: '32832',
country: 'United States', location: 'Business', primary_mailing_address: false },
{ street: '1025 South 6th Street', city: 'Springfield', state: 'IL', postal_code: '62703',
country: 'United States', location: 'Business', primary_mailing_address: false }
].to_set)
end
end
describe 'sync websites' do
it 'combines websites from mpdx and google' do
person.websites << Person::Website.new(url: 'mpdx.example.com', primary: false)
person.save
g_contact['gContact$website'] = [{ 'href' => 'google.example.com', 'primary' => 'true', rel: 'blog' }]
sync.sync_websites(g_contact, person, g_contact_link)
expect(g_contact.prepped_changes).to eq(websites: [
{ href: 'google.example.com', primary: true, rel: 'blog' },
{ href: 'mpdx.example.com', primary: false, rel: 'other' }
])
expect(person.websites.count).to eq(2)
websites = person.websites.order(:url).to_a
expect(websites[0].url).to eq('google.example.com')
expect(websites[0].primary).to be true
expect(websites[1].url).to eq('mpdx.example.com')
expect(websites[1].primary).to be false
end
end
describe 'ensure_single_primary_address' do
it 'sets all but the first primary address in the list to do not primary' do
address1 = build(:address, primary_mailing_address: true)
address2 = build(:address, primary_mailing_address: false)
address3 = build(:address, primary_mailing_address: true)
sync.ensure_single_primary_address([address1, address2, address3])
expect(address1.primary_mailing_address).to be true
expect(address2.primary_mailing_address).to be false
expect(address3.primary_mailing_address).to be false
end
end
describe 'compare_considering_historic' do
it "doesn't add or delete historic items in MPDX, doesn't add them to Google, but does delete them from Google" do
last_sync_list = ['history1']
mpdx_list = ['history1']
g_contact_list = ['history2']
historic_list = %w(history1 history2)
mpdx_adds, mpdx_dels, g_contact_adds, g_contact_dels =
sync.compare_considering_historic(last_sync_list, mpdx_list, g_contact_list, historic_list)
expect(mpdx_adds.to_a).to eq([])
expect(mpdx_dels.to_a).to eq([])
expect(g_contact_adds.to_a).to eq([])
expect(g_contact_dels.to_a).to eq(%w(history1 history2))
end
end
describe 'compare_address_records' do
let(:master_address_id) { SecureRandom.uuid }
it 'uses historic list for comparision' do
contact.addresses << build(:address, master_address_id: master_address_id, historic: true)
contact.save
expect(sync).to(
receive(:compare_considering_historic).with([], [], [], [master_address_id])
.and_return([[], [], [], [1], [1]])
)
mpdx_adds, mpdx_dels, g_contact_adds, g_contact_dels, g_contact_address_records =
sync.compare_address_records([], contact, [])
expect(mpdx_adds.to_a).to eq([])
expect(mpdx_dels.to_a).to eq([])
expect(g_contact_adds.to_a).to eq([])
expect(g_contact_dels.to_a).to eq([1])
expect(g_contact_address_records.to_a).to eq([])
end
end
describe 'compare_emails_for_sync' do
it 'uses historic list for comparision' do
person.email_addresses << build(:email_address, email: '<EMAIL>', historic: true)
person.save!
expect(sync).to receive(:compare_considering_historic).with([], [], [], ['<EMAIL>']).and_return('compared')
expect(sync.compare_emails_for_sync(g_contact, person, g_contact_link)).to eq('compared')
end
end
describe 'compare_numbers_for_sync' do
it 'uses historic list for comparision' do
person.phone_numbers << build(:phone_number, number: '+12123334444', historic: true)
person.save!
expect(sync).to receive(:compare_considering_historic).with([], [], [], ['+12123334444']).and_return('compared')
expect(sync.compare_numbers_for_sync(g_contact, person, g_contact_link)).to eq('compared')
end
end
describe 'g_contact_organizations_for' do
it 'gives a valid Google contacts organization with primary and rel for an employer and title' do
expect(sync.g_contact_organizations_for('Company', 'Worker')).to eq([{ org_name: 'Company', org_title: 'Worker',
primary: true, rel: 'work' }])
end
it 'gives an empty list of both employer and title are blank' do
expect(sync.g_contact_organizations_for('', nil)).to eq([])
end
end
describe 'missing first name in sync' do
it 'marks the first name as Unknown and logs a message' do
g_contact['gd$name']['gd$givenName'] = nil
g_contact_link.last_data = { given_name: 'John' }
expect(Rails.logger).to receive(:error)
sync.sync_basic_person_fields(person, g_contact, g_contact_link)
expect(person.first_name).to eq 'Unknown'
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130613201210_add_not_duplicated_with_to_contact.rb
|
<reponame>chuckmersereau/api_practice
class AddNotDuplicatedWithToContact < ActiveRecord::Migration
def change
add_column :contacts, :not_duplicated_with, :string, limit: 2000
end
end
|
chuckmersereau/api_practice
|
spec/models/person/website_spec.rb
|
require 'rails_helper'
describe Person::Website do
it 'supports a really long url' do
website = build(:website)
website.url = 'http://www.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com'
expect { website.save! }.to_not raise_error
end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/connection_handler.rb
|
<gh_stars>0
# This class wraps the Mail Chimp API connection and handles most possible errors.
class MailChimp::ConnectionHandler
INVALID_KEY_ERROR_MESSAGES = [
'API Key Disabled',
'This account has been deactivated.',
'code 104',
"Your API key may be invalid, or you've attempted to access the wrong datacenter."
].freeze
attr_accessor :mail_chimp_account
delegate :active,
:primary_list_id,
to: :mail_chimp_account
def initialize(mail_chimp_account)
@mail_chimp_account = mail_chimp_account
end
# you can include require_primary: false as an argument when calling
# this to prevent it from returning when primary_list_id is blank
def call_mail_chimp(object, method, *args)
require_primary = args.last.delete(:require_primary) if args.last.is_a? Hash
args.pop if args.last == {}
return if inactive_account? || (primary_list_id.blank? && require_primary != false)
mail_chimp_account.update(importing: true)
object.send(method, *args)
rescue Gibbon::MailChimpError => error
handle_mail_chimp_error(error)
ensure
mail_chimp_account.update(importing: false)
end
private
def handle_mail_chimp_error(error)
@error = error
handle_request_or_account_or_server_error
end
def handle_request_or_account_or_server_error
return stop_trying_to_sync_and_send_invalid_api_key_email if api_key_disabled?
return forget_primary_list_and_send_merge_field_explanation_email if invalid_merge_fields?
return forget_primary_list if invalid_mail_chimp_list?
return if invalid_email? || email_already_subscribed?
handle_server_error
end
def handle_server_error
if server_temporarily_unavailable? || number_of_connections_limit_reached?
retry_without_alerting_rollbar
else
retry_while_alerting_rollbar
end
end
def invalid_merge_fields?
@error.message.include?('Your merge fields were invalid.')
end
def invalid_email?
@error.status_code == 400 &&
(@error.message =~ /looks fake or invalid, please enter a real email/ ||
@error.message =~ /username portion of the email address is invalid/ ||
@error.message =~ /domain portion of the email address is invalid/ ||
@error.message =~ /An email address must contain a single @/)
end
def email_already_subscribed?
@error.message.include?('code 214')
end
def api_key_disabled?
INVALID_KEY_ERROR_MESSAGES.any? { |error| @error.message.include? error }
end
def server_temporarily_unavailable?
@error.status_code.to_s == '503'
end
def number_of_connections_limit_reached?
@error.status_code.to_s == '429'
end
def invalid_mail_chimp_list?
return true if @error.message.include?('code 200')
# check if primary list still exists. This is the best guess we have at why a 404 would be thrown
@error.message.include?('The requested resource could not be found.') &&
mail_chimp_account.primary_list_id.present? &&
mail_chimp_account.gibbon_wrapper.list(mail_chimp_account.primary_list_id).nil?
end
def inactive_account?
!active
end
def stop_trying_to_sync_and_send_invalid_api_key_email
mail_chimp_account.update_column(:active, false)
AccountMailer.delay.invalid_mailchimp_key(mail_chimp_account.account_list)
end
def retry_without_alerting_rollbar
raise LowerRetryWorker::RetryJobButNoRollbarError
end
def retry_while_alerting_rollbar
raise @error
end
def forget_primary_list_and_send_merge_field_explanation_email
forget_primary_list
AccountMailer.delay.mailchimp_required_merge_field(mail_chimp_account.account_list)
end
def forget_primary_list
mail_chimp_account.update_column(:primary_list_id, nil)
end
end
|
chuckmersereau/api_practice
|
app/serializers/coaching/reports/activity_results_period_serializer.rb
|
class Coaching::Reports::ActivityResultsPeriodSerializer < Reports::ActivityResultsPeriodSerializer
end
|
chuckmersereau/api_practice
|
spec/models/mail_chimp_member_spec.rb
|
<filename>spec/models/mail_chimp_member_spec.rb
require 'rails_helper'
describe MailChimpMember do
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/donation_amount_range_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Contact::Filter::DonationAmountRange do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list: account_list) }
let!(:contact_two) { create(:contact, account_list: account_list) }
let!(:contact_three) { create(:contact, account_list: account_list) }
let!(:contact_four) { create(:contact, account_list: account_list) }
let!(:donor_account_one) { create(:donor_account, contacts: [contact_one]) }
let!(:donor_account_two) { create(:donor_account, contacts: [contact_two]) }
let!(:donor_account_three) { create(:donor_account, contacts: [contact_three]) }
let!(:donor_account_four) { create(:donor_account, contacts: [contact_four]) }
let!(:designation_account_one) { create(:designation_account, account_lists: [account_list]) }
let!(:designation_account_two) { create(:designation_account, account_lists: [account_list]) }
let!(:donation_one) do
create(:donation, donor_account: donor_account_one, designation_account: designation_account_one, amount: 12.34)
end
let!(:donation_two) do
create(:donation, donor_account: donor_account_two, designation_account: designation_account_one, amount: 4444.33)
end
let!(:donation_three) do
create(:donation, donor_account: donor_account_three, designation_account: designation_account_two, amount: 8.31)
end
let!(:donation_four) do
create(:donation, donor_account: donor_account_four, designation_account_id: nil, amount: 12.00)
end
describe '#config' do
it 'returns expected config' do
options = [{ name: 'Gift Amount Higher Than or Equal To', id: 'min', placeholder: 0 },
{ name: 'Gift Amount Less Than or Equal To', id: 'max', placeholder: 4444.33 }]
expect(described_class.config([account_list])).to include(default_selection: '',
multiple: false,
name: :donation_amount_range,
options: options,
parent: 'Gift Details',
title: 'Gift Amount Range',
type: 'text')
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, { donation_amount_range: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { donation_amount_range: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { donation_amount_range: [''] }, nil)).to eq(nil)
expect(described_class.query(contacts, { donation_amount_range: '' }, nil)).to eq(nil)
end
end
context 'filter by amount min' do
it 'returns only contacts that have given the at least the min amount' do
result = described_class.query(contacts, { donation_amount_range: { min: '10' } }, [account_list]).to_a
expect(result).to match_array [contact_one, contact_two]
end
end
context 'filter by amount max' do
it 'returns only contacts that have given no more than the max amount' do
result = described_class.query(contacts, { donation_amount_range: { max: '13' } }, [account_list]).to_a
expect(result).to match_array [contact_one, contact_three]
end
end
context 'filter by amount min and max' do
it 'returns only contacts that have given gifts within the min and max amounts' do
result = described_class.query(contacts, { donation_amount_range: { min: '10', max: '13' } }, [account_list]).to_a
expect(result).to match_array [contact_one]
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/errors/facebook_link.rb
|
<filename>app/services/errors/facebook_link.rb
class Errors::FacebookLink < StandardError
end
|
chuckmersereau/api_practice
|
app/exhibits/contact_exhibit.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class ContactExhibit < DisplayCase::Exhibit
include DisplayCase::ExhibitsHelper
include ApplicationHelper
include ActionView::Helpers::NumberHelper
# Use ||= to avoid "warning: already initialized contant" for specs
TABS ||= {
'details' => _('Details'),
'tasks' => _('Tasks'),
'history' => _('History'),
'referrals' => _('Referrals'),
'notes' => _('Notes')
}.freeze
def self.applicable_to?(object)
object.class.name == 'Contact'
end
def location
[address.city, address.state, address.country].select(&:present?).join(', ') if address
end
def website
if to_model.website.present?
url = to_model.website.include?('http') ? to_model.website : 'http://' + to_model.website
@context.link_to(@context.truncate(url, length: 30), url, target: '_blank')
else
''
end
end
def pledge_frequency
Contact.pledge_frequencies[to_model.pledge_frequency || 1.0]
end
def avatar(size = :square)
url = get_mpdx_picture_url_if_available(size)
url ||= get_facebook_picture_url_if_available(size)
url ||= get_google_plus_url_if_available(size)
url || default_image_url_by_gender
end
def pledge_amount_formatter
proc { |pledge| format_pledge_amount(pledge) }
end
def format_pledge_amount(pledge)
return if pledge.blank?
precision = whole_number?(pledge) ? 0 : 2
if account_list.multi_currency?
number_with_precision(pledge, precision: precision)
else
number_to_currency(pledge, precision: precision)
end
end
def notes_saved_at
return '' unless to_model.notes_saved_at
l(to_model.notes_saved_at.to_datetime, format: :medium)
end
def donor_ids
donor_accounts.map(&:account_number).join(', ')
end
def to_s
name
end
def send_newsletter_error
missing_address = !mailing_address.id
missing_email_address = people.joins(:email_addresses).blank?
if send_newsletter == 'Both' && missing_address && missing_email_address
_('No mailing address or email addess on file')
elsif (send_newsletter == 'Physical' || send_newsletter == 'Both') && missing_address
_('No mailing address on file')
elsif (send_newsletter == 'Email' || send_newsletter == 'Both') && missing_email_address
_('No email addess on file')
end
end
def csv_country
mailing_address.csv_country(account_list.home_country)
end
def address_block
"#{envelope_greeting}\n#{mailing_address.to_snail.gsub("\r\n", "\n")}"
end
private
def get_mpdx_picture_url_if_available(size)
picture = primary_or_first_person.primary_picture
picture&.image&.url(size)
end
def get_facebook_picture_url_if_available(size)
fb_account = primary_or_first_person.facebook_account
if fb_account&.remote_id.present?
return "https://graph.facebook.com/#{fb_account.remote_id}/picture?height=120&width=120" if size == :large_square
"https://graph.facebook.com/#{fb_account.remote_id}/picture?type=#{size}"
end
end
def get_google_plus_url_if_available(size)
return unless relevant_google_plus_profile_picture_url
"#{relevant_google_plus_profile_picture_url}?size=#{size_in_pixels(size)}"
end
def size_in_pixels(size)
case size
when :small_square
100
when :square
200
when :large_square
300
else
200
end
end
def relevant_google_plus_profile_picture_url
primary_or_first_person&.primary_email_address&.google_plus_account&.profile_picture_link
end
def default_image_url_by_gender
url = if primary_or_first_person.gender == 'female'
ActionController::Base.helpers.image_url('avatar_f.png')
else
ActionController::Base.helpers.image_url('avatar.png')
end
if url.start_with?('/')
root_url = 'https://mpdx.org'
url = URI.join(root_url, url).to_s
end
url
end
def whole_number?(number)
(number.to_f % 1).zero?
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180809035815_rename_person_relay_accounts.rb
|
class RenamePersonRelayAccounts < ActiveRecord::Migration
def up
sql_query = <<~SQL
DROP TABLE person_key_accounts;
CREATE TABLE person_key_accounts (LIKE person_relay_accounts INCLUDING ALL);
INSERT INTO person_key_accounts SELECT * FROM person_relay_accounts;
SQL
ActiveRecord::Base.connection.execute(sql_query)
end
def down; end
end
|
chuckmersereau/api_practice
|
app/models/pls_account.rb
|
<gh_stars>0
require 'async'
require 'open-uri'
class PlsAccount < ApplicationRecord
# :nocov:
# There are intentionally no specs for this yet as the PLS API is still buggy
# and under development, but I wanted to get this on the master branch so it
# will track with future changes while we wait on PLS.
include Async
include Sidekiq::Worker
sidekiq_options queue: :api_pls_account, unique: :until_executed
SERVICE_URL = 'https://www.myletterservice.org'.freeze
belongs_to :account_list
after_create :queue_subscribe_contacts
validates :oauth2_token, :account_list_id, presence: true
def queue_subscribe_contacts
async(:subscribe_contacts)
end
def subscribe_contacts
contacts = account_list.contacts.includes([:primary_address, { primary_person: :companies }])
.select(&:should_be_in_prayer_letters?)
contacts.each(&method(:add_or_update_contact))
contact_subscribe_params = contacts.map { |c| contact_params(c, true) }
contact_params_map = Hash[contacts.map { |c| [c.id, contact_params(c)] }]
get_response(:put, '/api/v1/contacts', { contacts: contact_subscribe_params }.to_json, 'application/json')
account_list.contacts.update_all(pls_id: nil, pls_params: nil)
import_list(contact_params_map)
end
def import_list(contact_params_map = nil)
contacts = JSON.parse(get_response(:get, '/api/v1/contacts'))['contacts']
contacts.each do |pl_contact|
next unless pl_contact['external_id']
contact = account_list.contacts.find_by(id: pl_contact['external_id'])
next unless contact
contact.update_columns(pls_id: pl_contact['contact_id'],
pls_params: contact_params_map ? contact_params_map[contact.id] : nil)
end
end
def active?
valid_token?
end
def add_or_update_contact(contact)
async(:async_add_or_update_contact, contact.id)
end
def async_add_or_update_contact(contact_id)
contact = account_list.contacts.find(contact_id)
if contact.pls_id.present?
update_contact(contact)
else
create_contact(contact)
end
end
def create_contact(contact)
contact_params = contact_params(contact)
json = JSON.parse(get_response(:post, '/api/v1/contacts', contact_params))
contact.update_columns(pls_id: json['contact_id'], pls_params: contact_params)
rescue AccessError
# do nothing
rescue RestClient::BadRequest => e
# BadRequest: A contact must have a name or company. Monitor those cases for pattern / underlying causes.
Rollbar.raise_or_notify(e, parameters: contact_params)
end
def contact_needs_sync?(contact)
contact_params(contact) != contact.pls_params
end
def update_contact(contact)
params = contact_params(contact)
return if params == contact.pls_params
get_response(:post, '/api/v1/contacts', params)
contact.update_column(:pls_params, params)
rescue AccessError
# do nothing
rescue RestClient::Gone, RestClient::ResourceNotFound
handle_missing_contact(contact)
end
def handle_missing_contact(contact)
contact.update_columns(pls_id: nil, pls_params: nil)
queue_subscribe_contacts
end
def delete_contact(contact)
get_response(:delete, "/api/v1/contacts/#{contact.pls_id}")
contact.update_columns(pls_id: nil, pls_params: nil)
rescue RestClient::InternalServerError
# Do nothing as this means the contact was already deleted
end
def delete_all_contacts
get_response(:delete, '/api/v1/contacts')
account_list.contacts.update_all(pls_id: nil, pls_params: nil)
end
def contact_params(contact, subscribe_format = false)
name = contact.siebel_organization? ? '' : contact.envelope_greeting
params = { name: name, greeting: contact.greeting, file_as: contact.name,
external_id: contact.id,
company: contact.siebel_organization? ? contact.name : '',
envLine: name }
address = contact.mailing_address
address_params = { street: address.street, city: address.city, state: address.state,
postCode: address.postal_code,
country: address.country == 'United States' ? '' : address.country.to_s }
address_params[:country] = address.country unless address.country == 'United States'
if subscribe_format
params[:contact_id] = contact.pls_id
params[:address] = address_params
else
params.merge!(address_params)
end
params
end
def get_response(method, path, params = nil, content_type = nil)
return unless active?
headers = { 'Authorization' => "Bearer #{URI.encode(oauth2_token)}" }
headers['Content-Type'] = content_type if content_type
RestClient::Request.execute(method: method, url: SERVICE_URL + path, payload: params, headers: headers)
rescue RestClient::ServiceUnavailable
# Do nothing, as the PLS api mistakenly returns this error
rescue RestClient::Unauthorized, RestClient::Forbidden
handle_bad_token
end
def handle_bad_token
update_column(:valid_token, false)
AccountMailer.delay.pls_invalid_token(account_list)
raise AccessError
end
class AccessError < StandardError
end
# :nocov:
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/analytics_controller.rb
|
<gh_stars>0
class Api::V2::Contacts::AnalyticsController < Api::V2Controller
def show
load_analytics
authorize_analytics
render_analytics
end
private
def authorize_analytics
account_lists.each { |account_list| authorize account_list, :show? }
end
def load_analytics
@analytics ||= Contact::Analytics.new(load_contacts)
end
def load_contacts
Contact.where(account_list: account_lists.map(&:id))
end
def permitted_filters
[:account_list_id]
end
def render_analytics
render json: @analytics,
include: include_params,
fields: field_params
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/filtering/contacts.rb
|
<filename>app/controllers/concerns/filtering/contacts.rb<gh_stars>0
module Filtering
module Contacts
def permitted_filters
@permitted_filters ||= reversible_filters_including_filter_flags + [:account_list_id, :any_tags]
end
def reversible_filters
::Contact::Filterer::FILTERS_TO_DISPLAY.collect(&:underscore).collect(&:to_sym) +
::Contact::Filterer::FILTERS_TO_HIDE.collect(&:underscore).collect(&:to_sym)
end
def reversible_filters_including_filter_flags
reversible_filters.map do |reversible_filter|
[reversible_filter, "reverse_#{reversible_filter}".to_sym]
end.flatten
end
def excluded_filter_keys_from_casting_validation
[:donation_amount_range]
end
end
end
|
chuckmersereau/api_practice
|
spec/lib/pundit_authorizer_spec.rb
|
<filename>spec/lib/pundit_authorizer_spec.rb
require 'rails_helper'
require 'pundit_context'
describe PunditAuthorizer do
let(:user) { create(:user) }
let(:object) { create(:account_list) }
describe 'initialize' do
it 'initializes' do
pundit_authorizer = PunditAuthorizer.new(user, object)
expect(pundit_authorizer).to be_a(PunditAuthorizer)
expect(pundit_authorizer.user).to eq(user)
expect(pundit_authorizer.obj).to eq(object)
end
end
describe '#authorize_on' do
it 'authorizes the object, without ?' do
pundit_authorizer = PunditAuthorizer.new(user, object)
expect(pundit_authorizer).to receive(:authorize).with(object, 'show?').and_return(true)
pundit_authorizer.authorize_on('show')
end
it 'authorizes the object, using ?' do
pundit_authorizer = PunditAuthorizer.new(user, object)
expect(pundit_authorizer).to receive(:authorize).with(object, 'show?').and_return(true)
pundit_authorizer.authorize_on('show?')
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/user/options_controller.rb
|
class Api::V2::User::OptionsController < Api::V2Controller
resource_type :user_options
def index
load_options
render json: @options.preload_valid_associations(include_associations),
meta: meta_hash(@options),
include: include_params,
fields: field_params
end
def show
load_option
authorize_option
render_option
end
def create
persist_option
end
def update
load_option
authorize_option
persist_option
end
def destroy
load_option
authorize_option
destroy_option
end
private
def option_params
params
.require(:user_option)
.permit(option_attributes)
end
def option_attributes
::User::Option::PERMITTED_ATTRIBUTES
end
def option_scope
current_user.options
end
def authorize_option
authorize @option
end
def build_option
@option ||= option_scope.build
@option.assign_attributes(option_params)
end
def destroy_option
@option.destroy
head :no_content
end
def load_option
@option ||= option_scope.find_by!(key: params[:id])
end
def load_options
@options = option_scope
.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def persist_option
build_option
authorize_option
if save_option
render_option
else
render_with_resource_errors(@option)
end
end
def render_option
render json: @option,
status: success_status,
include: include_params,
fields: field_params
end
def save_option
@option.save(context: persistence_context)
end
def default_sort_param
User::Option.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
spec/serializers/bulk_resource_serializer_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe BulkResourceSerializer, type: :serializer do
describe 'json output' do
let(:contact_with_error) do
contact = build(:contact)
contact.errors.add(:name, 'Cannot be blank')
contact
end
let(:contact_with_conflict_error) do
contact = build(:contact)
contact.errors.add(:updated_in_db_at, 'is not equal to the current value in the database')
contact
end
let(:contact) { build(:contact, id: SecureRandom.uuid) }
let(:resources) { [contact, create(:contact), contact_with_error, contact_with_conflict_error] }
let(:serializer) { BulkResourceSerializer.new(resources: resources) }
let(:parsed_json_response) { JSON.parse(serializer.to_json) }
it 'outputs the successes and failures in the correct format' do
expect(parsed_json_response.length).to eq(4)
expect(parsed_json_response.first['data']['id']).to eq(contact.id)
expect(parsed_json_response.first['data']['attributes']['name']).to eq(contact.name)
expect(parsed_json_response.third['id']).to eq(contact_with_error.id)
expect(parsed_json_response.third['errors'].first['title']).to eq('Cannot be blank')
expect(parsed_json_response.last['errors'].first['status']).to eq(409)
end
end
end
|
chuckmersereau/api_practice
|
spec/support/contact_status_suggester_spec_helpers.rb
|
module ContactStatusSuggesterSpecHelpers
def create_donations_to_match_frequency(pledge_frequency, one_time: true)
pledge_frequency_in_days = (pledge_frequency * 30).round
# Create consistent donations according to the given pledge_frequency
(1..Contact::StatusSuggester::NUMBER_OF_DONATIONS_TO_SAMPLE).each do |multiplier|
create_donation_with_details(50, (multiplier * pledge_frequency_in_days).days.ago, 'CAD')
end
# Optionally add a one time donation with a different amount, we want to make sure one time donations don't interfere
create_donation_with_details(20, pledge_frequency_in_days.days.ago, 'USD') if one_time
end
def create_donations_with_missing_month(pledge_frequency)
pledge_frequency_in_days = (pledge_frequency * 30).round
(1..Contact::StatusSuggester::NUMBER_OF_DONATIONS_TO_SAMPLE).each do |multiplier|
next if multiplier == 2
create_donation_with_details(50, (multiplier * pledge_frequency_in_days).days.ago)
end
end
def create_donation_with_details(amount, donation_date, currency = 'USD')
create(:donation, donor_account: donor_account, designation_account: designation_account,
tendered_amount: amount, tendered_currency: currency,
amount: amount, currency: currency,
donation_date: donation_date)
end
end
|
chuckmersereau/api_practice
|
lib/tasks/nicknames.rake
|
<gh_stars>0
require 'csv'
# Load the db/nicknames.csv file which was taken from
# https://code.google.com/p/nickname-and-diminutive-names-lookup
namespace :nicknames do
task load: :environment do
nicknames = []
nicknames_csv = File.new('db/nicknames.csv').read
CSV.new(nicknames_csv).each do |line|
primary_name = ''
line.each_with_index do |name, index|
if index.zero?
primary_name = name
else
nicknames << [primary_name, name]
end
end
end
nicknames.each do |names|
name, nickname = names
begin
Nickname.create(name: name, nickname: nickname, source: 'csv', suggest_duplicates: true)
rescue ActiveRecord::RecordNotUnique
# Do nothing if the name-nickname pair already exists
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/donation_imports/base/merge_donations.rb
|
<reponame>chuckmersereau/api_practice<filename>app/services/donation_imports/base/merge_donations.rb
# This class deals with duplicate donations during the import process.
# A mistake in previous versions of the import caused some donations to be duplicated,
# the duplicate donations belonged to different designation accounts.
class DonationImports::Base
class MergeDonations
attr_accessor :donations, :attributes
def initialize(donations)
@donations = donations.to_a
@attributes = {}.with_indifferent_access
end
def merge
return donations.first if donations.size <= 1
find_attributes_from_all_donations
merge_donations_into_one
end
private
def mergeable_attributes
@attributes_to_look_at ||= (Donation.attribute_names - %w(id created_at updated_at)).map(&:to_sym)
end
def find_attributes_from_all_donations
# Attributes might be missing if the value is imported from one
# source but not from another (such as tnt_id, or appeal_id).
@attributes = mergeable_attributes.each_with_object({}) do |attribute, hash|
hash[attribute] = donations.collect(&attribute).compact.first
end
end
def merge_donations_into_one
donations[1..-1].each(&:destroy)
donations.first.update!(attributes)
donations.first
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/deleted_records_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'DeletedRecords' do
include_context :json_headers
documentation_scope = :deleted_records_api
let(:factory_type) { :deleted_record }
# first user
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:resource) { create(:deleted_record, deleted_from: account_list, deleted_by: user, deleted_at: Date.current - 1.day) }
let!(:second_resource) { create(:deleted_record, deleted_from: account_list, deleted_by: user, deleted_at: Date.current - 1.day) }
let!(:third_resource) { create(:deleted_record, deleted_from: account_list, deleted_by: user, deleted_at: Date.current - 2.years) }
let!(:second_deleted_task_record) do
create(:deleted_task_record, deleted_from: account_list, deleted_by: user, deleted_at: Date.current - 2.years)
end
let(:resource_attributes) do
%w(
deletable_id
deletable_type
deleted_at
deleted_by_id
created_at
updated_at
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/deleted_records' do
parameter 'since_date', 'A Date Object/String', scope: :filter
parameter 'types', 'Contact, Activity', scope: :filter
example 'Deleted Records [LIST]', document: documentation_scope do
explanation 'List Deleted Records'
do_request filter: { since_date: (Date.today - 1.year), types: 'Contact, Activity' }
expect(response_status).to eq(200)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/mail_chimp/webhook/primary_list_spec.rb
|
require 'rails_helper'
describe MailChimp::Webhook::PrimaryList do
EXAMPLE_EMAIL = '<EMAIL>'.freeze
let(:account_list) { create(:account_list) }
let(:mail_chimp_account) do
create(:mail_chimp_account, account_list: account_list, auto_log_campaigns: true)
end
let(:subject) { described_class.new(mail_chimp_account) }
let(:contact) { create(:contact, account_list: account_list, send_newsletter: 'Email') }
let(:first_email_address) { create(:email_address, email: EXAMPLE_EMAIL) }
let!(:person) { create(:person, contacts: [contact], primary_email_address: first_email_address) }
let(:second_email_address) { create(:email_address, email: '<EMAIL>', person: person) }
let(:delayed) { double(:delayed) }
let(:mock_gibbon_wrapper) { double(:mock_gibbon_wrapper) }
let(:list_id) { 'PrimaryListID' }
context '#subscribe_hook' do
it "queues an import for the new subscriber if it doesn't exist" do
expect(MailChimp::MembersImportWorker).to receive(:perform_async).with(mail_chimp_account.id, ['<EMAIL>'])
subject.subscribe_hook('<EMAIL>')
end
it 'updates existing contacts to the list of MPDX subscribers' do
person.update(optout_enewsletter: true)
contact.update(send_newsletter: 'None')
subject.subscribe_hook(EXAMPLE_EMAIL)
expect(person.reload.optout_enewsletter).to eq(false)
expect(contact.reload.send_newsletter).to eq('Email')
end
end
context '#unsubscribe_hook' do
before do
allow(MailChimp::GibbonWrapper).to receive(:new).and_return(mock_gibbon_wrapper)
allow(mock_gibbon_wrapper).to receive(:list_member_info).and_return([
{
'unsubscribe_reason' => 'Unspecified',
'status' => 'unsubscribed'
}
])
end
it 'marks an unsubscribed person with opt out of enewsletter' do
subject.unsubscribe_hook(EXAMPLE_EMAIL, 'manual', list_id)
expect(person.reload.optout_enewsletter).to be_truthy
expect(person.contact.send_newsletter).to eq(nil)
end
it 'does not mark as unsubscribed someone with that email but not as set primary' do
first_email_address.update_column(:primary, false)
create(:email_address, email: '<EMAIL>', primary: true, person: person)
subject.unsubscribe_hook(EXAMPLE_EMAIL, 'manual', list_id)
expect(person.reload.optout_enewsletter).to be_falsey
expect(person.contact.send_newsletter).to eq('Email')
end
it 'does not mark as unsubscribed someone that was unsubscribed by the user' do
allow(mock_gibbon_wrapper).to receive(:list_member_info).and_return([
{
'unsubscribe_reason' => 'N/A (Unsubscribed by an admin)',
'status' => 'unsubscribed'
}
])
subject.unsubscribe_hook(EXAMPLE_EMAIL, 'manual', list_id)
expect(person.reload.optout_enewsletter).to be false
end
it 'updates send_newsletter if all people are opt out' do
create(:person, contacts: [contact], optout_enewsletter: true)
contact.update(send_newsletter: 'Both')
expect do
subject.unsubscribe_hook(EXAMPLE_EMAIL, 'manual', list_id)
end.to change { contact.reload.send_newsletter }.to('Physical')
end
it "doesn't update send_newsletter if some people are still not opted out" do
person2 = create(:person, contacts: [contact], optout_enewsletter: false)
person2.email_addresses.create(email: '<EMAIL>')
expect do
subject.unsubscribe_hook(EXAMPLE_EMAIL, 'manual', list_id)
end.to_not change { contact.reload.send_newsletter }
end
it 'updates send_newsletter if non-opted out people have no email addresses' do
person2 = create(:person, contacts: [contact], optout_enewsletter: false)
person2.email_addresses.destroy_all
expect do
subject.unsubscribe_hook(EXAMPLE_EMAIL, 'manual', list_id)
end.to change { contact.reload.send_newsletter }.to(nil)
end
it 'cleans up MailChimpMember of unsubscribed email' do
MailChimpMember.find_or_create_by!(mail_chimp_account: mail_chimp_account, list_id: list_id, email: EXAMPLE_EMAIL)
expect do
subject.unsubscribe_hook(EXAMPLE_EMAIL, 'manual', list_id)
end.to change(MailChimpMember, :count).by(-1)
end
end
context '#email_update_hook' do
it 'creates a new email address for the updated email if it is not there' do
subject.email_update_hook(EXAMPLE_EMAIL, '<EMAIL>')
expect(person.reload.email_addresses.count).to eq(2)
expect(person.email_addresses.find_by(email: EXAMPLE_EMAIL).primary).to be_falsey
expect(person.email_addresses.find_by(email: '<EMAIL>').primary).to be_truthy
end
it 'sets the new email address as primary if it is there' do
create(:email_address, email: '<EMAIL>', primary: false, person: person)
subject.email_update_hook(EXAMPLE_EMAIL, '<EMAIL>')
expect(person.reload.email_addresses.count).to eq(2)
expect(person.email_addresses.find_by(email: EXAMPLE_EMAIL).primary).to be_falsey
expect(person.email_addresses.find_by(email: '<EMAIL>').primary).to be_truthy
end
end
context '#email_cleaned_hook' do
it 'marks the cleaned email as no longer valid and not primary and queues a mailing' do
expect(SubscriberCleanedMailer).to receive(:delay).and_return(delayed)
expect(delayed).to receive(:subscriber_cleaned).with(account_list, first_email_address)
subject.email_cleaned_hook(EXAMPLE_EMAIL, 'hard', list_id)
expect(first_email_address.reload.historic).to be_truthy
expect(first_email_address.primary).to be_falsey
end
it 'makes another valid email as primary but not as invalid' do
second_email_address
subject.email_cleaned_hook(EXAMPLE_EMAIL, 'hard', list_id)
expect(first_email_address.reload.historic).to be_truthy
expect(first_email_address.primary).to be_falsey
expect(second_email_address.reload.historic).to be_falsey
expect(second_email_address.primary).to be_truthy
end
it 'triggers the unsubscribe hook for an email marked as spam (abuse)' do
expect(subject).to receive(:unsubscribe_hook).with(EXAMPLE_EMAIL, 'abuse', list_id).and_return(true)
subject.email_cleaned_hook(EXAMPLE_EMAIL, 'abuse', list_id)
end
it 'cleans up MailChimpMember of cleaned email' do
MailChimpMember.find_or_create_by!(mail_chimp_account: mail_chimp_account, list_id: list_id, email: EXAMPLE_EMAIL)
expect do
subject.email_cleaned_hook(EXAMPLE_EMAIL, 'hard', list_id)
end.to change(MailChimpMember, :count).by(-1)
end
end
context '#campaign_status_hook' do
it 'does nothing if the status is not sent' do
expect(MailChimp::CampaignLoggerWorker).to_not receive(:perform_async)
subject.campaign_status_hook('campaign1', 'not-sent', 'subject')
end
it 'asyncronously calls the mail chimp account to log the sent campaign' do
expect(MailChimp::CampaignLoggerWorker).to receive(:perform_async).with(mail_chimp_account.id, 'c1', 'subject')
subject.campaign_status_hook('c1', 'sent', 'subject')
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/address_historic.rb
|
class Contact::Filter::AddressHistoric < Contact::Filter::Base
def execute_query(contacts, filters)
contacts.where('addresses.historic' => filters[:address_historic] == 'true')
.joins(:addresses)
end
def title
_('Address No Longer Valid')
end
def parent
_('Contact Location')
end
def type
'single_checkbox'
end
def empty?
false
end
def default_selection
false
end
end
|
chuckmersereau/api_practice
|
spec/models/admin/reset_spec.rb
|
require 'rails_helper'
describe Admin::Reset, '#reset!' do
let!(:admin_user) { create(:admin_user) }
let!(:resetted_user) { create(:user_with_full_account) }
let!(:user_finder) { Admin::UserFinder }
let!(:reset_logger) { Admin::ResetLog }
let!(:resetted_user_email) { '<EMAIL>' }
let!(:account_list) { resetted_user.account_lists.order(:created_at).first }
before do
Sidekiq::Testing.inline!
resetted_user.key_accounts.first.update!(email: resetted_user_email)
end
describe '.reset!' do
it 'performs a reset' do
expect do
expect(Admin::Reset.reset!(
reason: 'because', admin_resetting: admin_user, resetted_user_email: resetted_user_email,
user_finder: user_finder, reset_logger: reset_logger, account_list_name: account_list.name
)).to eq(true)
end.to change(AccountListUser, :count).by(-1)
.and change(AccountList, :count).by(-1)
.and change(Admin::ResetLog, :count).by(1)
end
it 'performs the reset by insantiating a new instance' do
expect(Admin::Reset).to receive(:new).and_return(Admin::Reset.new)
expect_any_instance_of(Admin::Reset).to receive(:reset!)
Admin::Reset.reset!
end
end
describe '#reset!' do
it 'finds the user to reset and logs the reset' do
subject = Admin::Reset.new(
reason: 'because', admin_resetting: admin_user, resetted_user_email: resetted_user_email,
user_finder: user_finder, reset_logger: reset_logger, account_list_name: account_list.name
)
expect do
expect(subject.reset!).to eq(true)
end.to change(AccountListUser, :count).by(-1)
.and change(AccountList, :count).by(-1)
.and change(Admin::ResetLog, :count).by(1)
end
it 'returns false and adds an error if no users found' do
subject = Admin::Reset.new(
reason: 'because', admin_resetting: admin_user, resetted_user_email: '<EMAIL>',
user_finder: user_finder, reset_logger: reset_logger, account_list_name: account_list.name
)
expect do
expect(subject.reset!).to eq(false)
end.to_not change(AccountList, :count)
expect(Admin::ResetLog.count).to eq(0)
expect(subject.errors[:resetted_user]).to be_present
end
it 'returns false and adds error if no reason given' do
subject = Admin::Reset.new(
reason: '', admin_resetting: admin_user, resetted_user_email: resetted_user_email,
user_finder: user_finder, reset_logger: reset_logger, account_list_name: account_list.name
)
expect do
expect(subject.reset!).to eq(false)
end.to_not change(AccountList, :count)
expect(Admin::ResetLog.count).to eq(0)
expect(subject.errors[:reason]).to be_present
end
it 'returns false and adds error if account list cannot be found' do
AccountList.delete_all
subject = Admin::Reset.new(
reason: 'test', admin_resetting: admin_user, resetted_user_email: resetted_user_email,
user_finder: user_finder, reset_logger: reset_logger, account_list_name: account_list.name
)
expect do
expect(subject.reset!).to eq(false)
end.to_not change(AccountList, :count)
expect(Admin::ResetLog.count).to eq(0)
expect(subject.errors[:account_list]).to be_present
end
it 'returns false and adds error if multiple account lists are found' do
resetted_user.account_lists << create(:account_list, name: account_list.name)
subject = Admin::Reset.new(
reason: 'test', admin_resetting: admin_user, resetted_user_email: resetted_user_email,
user_finder: user_finder, reset_logger: reset_logger, account_list_name: account_list.name
)
expect do
expect(subject.reset!).to eq(false)
end.to_not change(AccountList, :count)
expect(Admin::ResetLog.count).to eq(0)
expect(subject.errors[:account_list]).to be_present
end
it 'raises unauthorized error if admin_resetting is not an admin' do
subject = Admin::Reset.new(
reason: 'because', admin_resetting: resetted_user, resetted_user_email: resetted_user_email,
user_finder: user_finder, reset_logger: reset_logger, account_list_name: account_list.name
)
expect do
expect { subject.reset! }.to raise_error(Pundit::NotAuthorizedError)
end.to_not change(AccountList, :count)
expect(Admin::ResetLog.count).to eq(0)
end
it 'sends an email notifying the reset user to logout and login again' do
subject = Admin::Reset.new(
reason: 'because', admin_resetting: admin_user, resetted_user_email: resetted_user_email,
user_finder: user_finder, reset_logger: reset_logger, account_list_name: account_list.name
)
expect_delayed_email(AccountListResetMailer, :logout)
subject.reset!
end
end
describe '#account_list' do
it 'returns the located account list' do
subject = Admin::Reset.new(
reason: 'because', admin_resetting: admin_user, resetted_user_email: resetted_user_email,
user_finder: user_finder, reset_logger: reset_logger, account_list_name: account_list.name
)
expect(subject.account_list).to eq(account_list)
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/pledge_amount.rb
|
class Contact::Filter::PledgeAmount < Contact::Filter::Base
def execute_query(contacts, filters)
contacts.where(pledge_amount: parse_list(filters[:pledge_amount]))
end
def title
_('Commitment Amount')
end
def parent
_('Commitment Details')
end
def type
'multiselect'
end
def custom_options
account_lists.collect { |account_list| account_list.contacts.pluck(:pledge_amount).uniq.compact.sort }
.flatten
.uniq
.collect { |amount| { name: amount, id: amount } }
end
end
|
chuckmersereau/api_practice
|
spec/support/shared_controller_examples/including_related_resources_examples.rb
|
RSpec.shared_examples 'including related resources examples' do |options|
context "action #{options[:action]} including related resources" do
let(:action) { options[:action].to_sym }
let(:includes) { '*' }
let(:expected_response_code) do
if options[:expected_response_code]
options[:expected_response_code]
else
case action
when :index, :show, :update
200
when :create
201
end
end
end
subject do
api_login(user)
case action
when :index
get action, parent_param_if_needed.merge(include: includes)
when :show
get action, full_params.merge(include: includes)
when :update
put action, full_correct_attributes.merge(include: includes)
when :create
post action, full_correct_attributes.merge(include: includes)
end
end
context 'with unpermitted filter params' do
let(:includes) { described_class::UNPERMITTED_INCLUDE_PARAMS.join(',') }
it 'does not permit unpermitted filter params' do
if serializer.associations.any?
expect(described_class::UNPERMITTED_INCLUDE_PARAMS).to be_present
subject
expect(response.status).to eq(expected_response_code), invalid_status_detail
expect(JSON.parse(response.body)['included']).to be_nil
end
end
end
it 'includes one level of related resources' do
if serializer.associations.any?
subject
expect(response.status).to eq(expected_response_code), invalid_status_detail
expect(JSON.parse(response.body).keys).to include('included')
included_types = JSON.parse(response.body)['included'].collect { |i| i['type'] }
expect(included_types).to be_present
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/donation_imports/base_spec.rb
|
require 'rails_helper'
RSpec.describe DonationImports::Base do
let(:organization_account) { double(:organization_account) }
before { allow(organization_account).to receive(:organization) }
subject { described_class.new(organization_account) }
describe '#parse_date' do
it 'parse the date string given as argument' do
expect(subject.parse_date('11/15/2001')).to eq(Date.new(2001, 11, 15))
expect(subject.parse_date('2001-11-15')).to eq(Date.new(2001, 11, 15))
end
it 'returns the date when given a datetime object' do
expect(subject.parse_date(Date.new(2001, 11, 15))).to eq(Date.new(2001, 11, 15))
expect(subject.parse_date(Time.new(2001, 11, 15).utc)).to eq(Date.new(2001, 11, 15))
expect(subject.parse_date(DateTime.new(2001, 11, 15).utc)).to eq(Date.new(2001, 11, 15))
end
it 'rescues Argument errors when parsing' do
expect(subject.parse_date('invalid address')).to eq(nil)
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/appeals/appeal_contacts_controller_spec.rb
|
<filename>spec/controllers/api/v2/appeals/appeal_contacts_controller_spec.rb
require 'rails_helper'
describe Api::V2::Appeals::AppealContactsController, type: :controller do
let(:factory_type) { :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!(:appeal_contact) { create(:appeal_contact, appeal: appeal, contact: contact) }
let!(:second_contact) { create(:contact, account_list: account_list) }
let!(:second_appeal_contact) { create(:appeal_contact, appeal: appeal, contact: second_contact) }
let(:unassociated_contact) { create(:contact, account_list: account_list) }
let(:id) { appeal_contact.id }
let(:resource) { appeal_contact }
let(:parent_param) { { appeal_id: appeal_id } }
let(:correct_attributes) { {} }
let(:correct_relationships) do
{
contact: {
data: {
type: 'contacts',
id: unassociated_contact.id
}
}
}
end
let(:full_correct_attributes_with_force) do
{
data: {
type: resource_type,
attributes: correct_attributes.merge(overwrite: true, force_list_deletion: true)
}.merge(relationships_params)
}.merge(full_params)
end
include_examples 'index_examples'
describe 'filtering' do
before { api_login(user) }
context 'pledged_to_appeal filter' do
let!(:user) { create(:user_with_account) }
it 'filters results' do
create(:pledge, contact: contact, appeal: appeal, account_list: account_list)
get :index, appeal_id: appeal_id, filter: { pledged_to_appeal: 'true' }
expect(response.status).to eq(200)
expect(JSON.parse(response.body)['data'].length).to eq(1)
end
it "doesn't break if filtering everything" do
appeal.pledges.destroy_all
get :index, appeal_id: appeal_id, filter: { pledged_to_appeal: 'false' }, sort: 'contact.name'
expect(response.status).to eq(200)
expect(JSON.parse(response.body)['data'].length).to eq(appeal.appeal_contacts.count)
end
end
end
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!(:appeal_contact1) { create(:appeal_contact, contact: contact1, appeal: sorting_appeal) }
let!(:appeal_contact2) { create(:appeal_contact, contact: contact2, appeal: sorting_appeal) }
it 'sorts results desc' do
get :index,
appeal_id: sorting_appeal.id,
sort: 'contact.name',
fields: {
contact: 'name,pledge_amount,pledge_currency,pledge_frequency'
},
filter: {
pledged_to_appeal: false
},
include: 'contact'
expect(response.status).to eq(200)
data = JSON.parse(response.body)['data']
expect(data.length).to eq(2)
expect(data[0]['id']).to eq(appeal_contact1.id)
expect(data[1]['id']).to eq(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(appeal_contact2.id)
expect(data[1]['id']).to eq(appeal_contact1.id)
end
end
end
describe '#create' do
let!(:contact) { create(:contact, account_list: account_list) }
include_context 'common_variables'
include_examples 'including related resources examples', action: :create, expected_response_code: 200
include_examples 'sparse fieldsets examples', action: :create, expected_response_code: 200
it 'creates resource for users that are signed in' do
api_login(user)
expect do
post :create, full_correct_attributes
appeal.appeal_contacts.reload
end.to change { appeal.appeal_contacts.count }.by(1)
expect(response.status).to eq(200)
end
context 'excluded_appeal_contact exists' do
let!(:appeal_excluded_appeal_contact) do
create(:appeal_excluded_appeal_contact,
contact: unassociated_contact,
appeal: appeal)
end
it 'destroys appeal_excluded_appeal_contact not allowed' do
api_login(user)
expect do
post :create, full_correct_attributes
appeal.appeal_contacts.reload
end.not_to change { appeal.excluded_appeal_contacts.count }
expect(response.status).to eq(400)
end
it 'will force destroy the appeal_excluded_appeal_contact' do
api_login(user)
expect do
post :create, full_correct_attributes_with_force
appeal.appeal_contacts.reload
end.to change { appeal.excluded_appeal_contacts.count }.by(-1)
expect(response.status).to eq(200)
end
end
it 'does not create resource for users that are not signed in' do
expect do
post :create, full_correct_attributes
appeal.appeal_contacts.reload
end.not_to change { appeal.appeal_contacts.count }
expect(response.status).to eq(401)
end
end
include_examples 'show_examples'
describe '#destroy' do
include_context 'common_variables'
it 'destroys resource object to users that are signed in' do
api_login(user)
expect do
delete :destroy, full_params
appeal.appeal_contacts.reload
end.to change { appeal.appeal_contacts.count }.by(-1)
expect(response.status).to eq(204)
end
it 'does not destroy the resource for users that do not own the resource' do
if defined?(id)
api_login(create(:user))
expect do
delete :destroy, full_params
appeal.appeal_contacts.reload
end.not_to change { appeal.appeal_contacts.count }
expect(response.status).to eq(403)
end
end
it 'does not destroy resource object to users that are signed in' do
expect do
delete :destroy, full_params
appeal.appeal_contacts.reload
end.not_to change { appeal.appeal_contacts.count }
expect(response.status).to eq(401)
end
end
end
|
chuckmersereau/api_practice
|
spec/serializers/contact_detail_serializer_spec.rb
|
require 'rails_helper'
RSpec.describe ContactDetailSerializer, type: :serializer do
describe 'lifetikme_donations' do
let(:designation_account) { create(:designation_account) }
let(:account_list) { create(:account_list, designation_accounts: [designation_account]) }
let(:contact) { create(:contact, account_list: account_list) }
let(:donor_account) { create(:donor_account, contacts: [contact]) }
let!(:donation_one) { create(:donation, donor_account: donor_account, designation_account: designation_account, amount: 80.0) }
let!(:donation_two) { create(:donation, donor_account: donor_account, designation_account: designation_account, amount: 140.0) }
let(:serializer) { ContactDetailSerializer.new(contact) }
let(:parsed_json_response) { JSON.parse(serializer.to_json) }
it 'outputs the successes and failures in the correct format' do
expect(parsed_json_response['lifetime_donations']).to eq('220.0')
end
end
end
|
chuckmersereau/api_practice
|
app/preloaders/api/v2/contacts/people/twitter_accounts_preloader.rb
|
class Api::V2::Contacts::People::TwitterAccountsPreloader < ApplicationPreloader
ASSOCIATION_PRELOADER_MAPPING = {}.freeze
FIELD_ASSOCIATION_MAPPING = {}.freeze
private
def serializer_class
Person::TwitterAccountSerializer
end
end
|
chuckmersereau/api_practice
|
spec/models/user/coach_spec.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
require 'rails_helper'
RSpec.describe User::Coach do
subject { create(:user_coach) }
let(:account_list) { create(:account_list) }
it { is_expected.to have_many(:coaching_account_lists).through(:account_list_coaches) }
context '#remove_coach_access' do
it 'removes coach from account list coaches' do
account_list.coaches << subject
subject.remove_coach_access(account_list)
expect(account_list.reload.coaches).to_not include subject
end
end
end
|
chuckmersereau/api_practice
|
app/services/task/filter/wildcard_search.rb
|
class Task::Filter::WildcardSearch < Task::Filter::Base
def execute_query(tasks, filters)
if filters[:wildcard_search] != 'null' && filters[:wildcard_search].present?
@tasks = tasks
@filters = filters
tasks = tasks.where('activities.subject ilike ? OR activities.id IN (?)', wildcard_string, relevant_task_ids)
end
tasks
end
private
def relevant_task_ids
(tagged_task_ids + task_ids_with_relevant_contact_name + task_ids_with_relevant_comment).uniq
end
def tagged_task_ids
@tasks.tagged_with(@filters[:wildcard_search].split(',').flatten, wild: true, any: true).reorder(:id).ids
end
def task_ids_with_relevant_contact_name
@tasks.joins(:contacts).where('contacts.name ilike ?', wildcard_string).reorder(:id).ids
end
def task_ids_with_relevant_comment
@tasks.joins(:comments).where('activity_comments.body ilike ?', wildcard_string).reorder(:id).ids
end
def wildcard_string
"%#{@filters[:wildcard_search]}%"
end
def valid_filters?(filters)
super && filters[:wildcard_search].is_a?(String)
end
end
|
chuckmersereau/api_practice
|
app/serializers/reports/pledge_increase_contact_serializer.rb
|
<reponame>chuckmersereau/api_practice
class Reports::PledgeIncreaseContactSerializer < ServiceSerializer
SERVICE_ATTRIBUTES = [:beginning_monthly, :beginning_currency, :end_monthly, :end_currency, :increase_amount].freeze
attributes(*SERVICE_ATTRIBUTES)
delegate(*SERVICE_ATTRIBUTES, to: :object)
belongs_to :contact
delegate(:contact, to: :object)
end
|
chuckmersereau/api_practice
|
lib/tasks/uuid_migration.rake
|
<gh_stars>0
# rubocop:disable BlockLength
namespace :mpdx do
task ensure_uuids: :environment do
tables_for_uuid_fill = %w(activities activity_comments activity_contacts appeal_contacts appeal_excluded_appeal_contacts)
tables_for_uuid_fill.each do |table_name|
sql = "UPDATE #{table_name} SET uuid = uuid_generate_v4() WHERE uuid IS NULL;"
puts "-- execute(#{sql})"
ActiveRecord::Base.connection.execute sql
end
end
# this runs really slow when the rails server is on and has database connections
task readd_indexes: :environment do
path = Rails.root.join('db', 'dropped_indexes.csv')
raise "indexes file doesn't exist!" unless File.exist?(path)
CSV.read(path, headers: true).each do |index_row|
puts "attempting to add index: #{index_row['indexname']}"
next unless ActiveRecord::Base.connection.table_exists?(index_row['tablename'])
ActiveRecord::Base.connection.execute index_row['indexdef'].sub('INDEX', 'INDEX CONCURRENTLY IF NOT EXISTS')
end
end
task index_created_at: :environment do
tables_query = "SELECT DISTINCT table_name
FROM information_schema.columns
WHERE table_schema = 'public'
and column_name = 'id' and data_type = 'uuid'"
ActiveRecord::Base.connection.execute(tables_query).each do |foreign_table_row|
table = foreign_table_row['table_name']
next if ActiveRecord::Base.connection.index_exists?(table, :created_at)
next unless ActiveRecord::Base.connection.column_exists?(table, :created_at)
puts "indexing #{table}"
ActiveRecord::Base.connection.add_index table, :created_at, algorithm: :concurrently
end
end
# a task that sets the status of sidekiq
# This will change the counts of running instances, so don't do it if you don't know for sure.
# It will use your local aws config, so make sure you run `aws configure` before starting here.
#
# To turn sidekiq on: rake mpdx:set_sidekiq
#
# To turn sidekiq off: rake mpdx:set_sidekiq[false], or if you're using zsh: rake mpdx:set_sidekiq\[false\]
#
# For extra excitement, you can change the status of production by setting the second arg to 'production':
# rake mpdx:set_sidekiq[true, production]
task :set_sidekiq, [:up, :env] => [:environment] do |_t, args|
args.with_defaults(up: true, env: 'staging')
direction = args[:up] != 'false' ? :up : :down
env_name = args[:env]
puts "Turning #{env_name} sidekiq #{args[:up] != 'false' ? 'on' : 'off'}"
confirm do
count = env_name == 'production' ? 8 : 2
cluster = env_name == 'production' ? 'prod' : 'stage'
container_name = lambda do |n, env|
"mpdx_api-#{env}-sidekiq-#{n}-sv2"
end
desired_count = direction == :up ? 1 : 0
count.times do |i|
service_name = container_name.call(i, env_name)
system "#{access_args} aws ecs update-service --cluster #{cluster} --service #{service_name} --desired-count #{desired_count}"
end
end
end
# a task that sets the status of the rails app
# This will change the counts of running instances, so don't do it if you don't know for sure.
# It will use your local aws config, so make sure you run `aws configure` before starting here.
#
# To turn the application on: rake mpdx:set_application_status
#
# To turn the application off: rake mpdx:set_application_status[false], or if you're using zsh: rake mpdx:set_application_status\[false\]
#
# For extra excitement, you can change the status of production by setting the second arg to 'production':
# rake mpdx:set_application_status[true, production]
task :set_application_status, [:up, :env] => [:environment] do |_t, args|
args.with_defaults(up: true, env: 'staging')
direction = args[:up] != 'false' ? :up : :down
puts "Turning #{args[:env]} application #{args[:up] != 'false' ? 'on' : 'off'}"
confirm do
count = if direction == :up
args[:env] == 'production' ? 8 : 2
else
0
end
cluster = args[:env] == 'production' ? 'prod' : 'stage'
container_name = "mpdx_api-#{args[:env]}-app-sv2"
system "#{access_args} aws ecs update-service --cluster #{cluster} --service #{container_name} --desired-count #{count}"
end
end
def confirm
puts 'Are you sure? (yes/n)'
input = STDIN.gets.strip
if input == 'yes'
puts 'OK...'
yield
else
puts 'So sorry for the confusion'
end
end
def access_args
aws_home = `echo $AWS_HOME`.sub("\n", '')
cred_lines = File.readlines(aws_home + '/credentials')
access_key = cred_lines.find { |l| l.start_with? 'aws_access_key_id' }.to_s.split(' = ').last.sub("\n", '')
secret_key = cred_lines.find { |l| l.start_with? 'aws_secret_access_key' }.to_s.split(' = ').last.sub("\n", '')
"AWS_ACCESS_KEY_ID=#{access_key} AWS_SECRET_ACCESS_KEY=#{secret_key}"
end
# delete all of the import processes that are currently pending
task drain_sidekiq: :environment do
Sidekiq::Queue.new('api_account_list_import_data').each(&:delete)
end
# re-enqueue all of the import tasks that we previously killed
task refill_import_queue: :environment do
# code pulled from AccountListImportDataEnqueuerWorker
active_users = User.where('current_sign_in_at >= ?', 2.months.ago)
account_list_scope = AccountList.with_linked_org_accounts
.has_users(active_users)
.where('last_download_attempt_at IS NULL OR last_download_attempt_at <= ?', 12.hours.ago)
ids = account_list_scope.pluck(:id)
ids.each do |account_list_id|
Sidekiq::Client.push(
'class' => AccountList,
'args' => [account_list_id, :import_data],
'queue' => :api_account_list_import_data
)
end
end
end
|
chuckmersereau/api_practice
|
app/policies/account_list_policy.rb
|
class AccountListPolicy < ApplicationPolicy
def show?
resource_owner? || resource_coach?
end
private
def resource_owner?
user.account_lists.exists?(id: @resource.id)
end
def resource_coach?
coach.coaching_account_lists.exists?(id: @resource.id)
end
end
|
chuckmersereau/api_practice
|
spec/workers/audit_change_worker_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe AuditChangeWorker do
let(:attrs) do
{
action: 'update',
audited_changes: '{"legal_first_name"=>["Spenc", nil]}',
comment: nil, 'created_at' => '2018-03-09T10:47:24-05:00',
request_uuid: nil,
remote_address: nil,
user_id: 1,
user_type: 'User',
auditable_id: 1, 'auditable_type' => 'User',
associated_id: 1, 'associated_type' => 'Contact'
}
end
let(:mock_gateway) { double(:mock_gateway) }
subject { described_class.new.perform(attrs) }
before do
allow(Audited::AuditElastic).to receive(:gateway).and_return(mock_gateway)
end
context 'race condition on index_creation' do
before do
exception = Elasticsearch::Transport::Transport::Errors::BadRequest.new({ type: 'index_already_exists_exception' }.to_json)
allow(mock_gateway).to receive(:create_index!).and_raise(exception)
end
it 'still saves' do
expect(mock_gateway).to receive(:save).and_return({})
subject
end
end
it 'creates the index' do
expect(mock_gateway).to receive(:create_index!)
allow(mock_gateway).to receive(:save).and_return({})
subject
end
end
|
chuckmersereau/api_practice
|
spec/models/master_address_spec.rb
|
require 'rails_helper'
describe MasterAddress do
let!(:address) { create :master_address, latitude: '', longitude: nil }
describe 'scope requires_geocode' do
it 'compares updated_at and last_geocoded_at ignoring milliseconds' do
master_address_two = build(:master_address, latitude: nil, longitude: nil)
# last_geocoded_at and updated_at will have the same second, but different milliseconds.
master_address_two.last_geocoded_at = Time.current
master_address_two.save!
expect(MasterAddress.requires_geocode.ids).to eq([address.id])
end
end
describe '#geocode' do
it 'adds latitude and longitude' do
expect(address.geocode).to be_truthy
address.reload
expect(address.latitude).to be_present
expect(address.longitude).to be_present
end
it 'moves latitude from smarty to own field' do
smarty_response = [
{ metadata: { latitude: 12.3456, longitude: -33.3333 } }
]
address.update_attribute(:smarty_response, smarty_response)
address.geocode
expect(address.reload.latitude).to eq '12.3456'
end
it 'returns true if geocode took place' do
address.last_geocoded_at = nil
expect(address.geocode).to eq(true)
end
it 'returns false if geocode did not take place' do
address.last_geocoded_at = address.updated_at + 1.hour
expect(address.geocode).to eq(false)
end
it 'geocodes if last_geocoded_at is blank' do
address.last_geocoded_at = nil
address.geocode
address.reload
expect(address.latitude).to be_present
expect(address.longitude).to be_present
expect(address.last_geocoded_at.to_i).to eq(address.updated_at.to_i)
end
it 'geocodes if last_geocoded_at is less than updated_at' do
address.last_geocoded_at = address.updated_at - 1.minute
address.geocode
address.reload
expect(address.latitude).to be_present
expect(address.longitude).to be_present
expect(address.last_geocoded_at.to_i).to eq(address.updated_at.to_i)
end
it 'does not geocode if last_geocoded_at is greater than updated_at' do
address.last_geocoded_at = address.updated_at + 1.minute
expect { address.geocode && address.reload }.to_not change { address.last_geocoded_at }
expect(address.latitude).to be_blank
expect(address.longitude).to be_blank
end
it 'does not geocode if last_geocoded_at is equal to updated_at' do
address.last_geocoded_at = address.updated_at
expect { address.geocode && address.reload }.to_not change { address.last_geocoded_at }
expect(address.latitude).to be_blank
expect(address.longitude).to be_blank
end
end
describe '.populate_lat_long' do
it 'geocodes master addresses that are missing latitude' do
MasterAddress.populate_lat_long
expect(address.reload.latitude).to be_present
end
end
describe '#find_timezone' do
it 'geocodes first and returns nil if the latitude and longitude are missing' do
expect(address).to receive(:geocode)
expect(address.find_timezone).to be_nil
end
it 'fetches the timezone from Google using latitude and longitude' do
timezone = double(time_zone_id: 'America/New_York')
expect(GoogleTimezone).to receive(:fetch).with('40.7', '-74.0') { timezone }
expect(address.find_timezone).to eq('Eastern Time (US & Canada)')
end
it 'returns the string of the timezone if not in ActiveSupport::TimeZone::MAPPING and valid' do
timezone = double(time_zone_id: 'America/Vancouver')
expect(GoogleTimezone).to receive(:fetch).with('40.7', '-74.0') { timezone }
expect(address.find_timezone).to eq('America/Vancouver')
end
it 'returns the nil if not in ActiveSupport::TimeZone::MAPPING and invalid' do
timezone = double(time_zone_id: 'NonExistantTimezone')
expect(GoogleTimezone).to receive(:fetch).with('40.7', '-74.0') { timezone }
expect(address.find_timezone).to be_nil
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/task_due_date_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/services/contact/filter/task_due_date_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe Contact::Filter::TaskDueDate do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:activity_one) { create(:activity, account_list: account_list, start_at: 1.month.ago) }
let!(:activity_two) { create(:activity, account_list: account_list, start_at: 1.month.from_now) }
before do
contact_one.activities << activity_one
contact_two.activities << activity_two
end
describe '#config' do
it 'returns expected config' do
expect(described_class.config([account_list]).except(:options)).to include(
default_selection: '',
multiple: false,
name: :task_due_date,
parent: 'Tasks',
title: 'Due Date',
type: 'daterange'
)
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, { task_due_date: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { task_due_date: { wut: '???', hey: 'yo' } }, nil)).to eq(nil)
expect(described_class.query(contacts, { task_due_date: '' }, nil)).to eq(nil)
end
end
context 'filter by end and start date' do
it 'returns only contacts with a task due after the start date and before the end date' do
result = described_class.query(contacts, { task_due_date: Range.new(1.year.ago, 1.year.from_now) }, nil).to_a
expect(result).to match_array [contact_one, contact_two]
result = described_class.query(contacts, { task_due_date: Range.new(1.day.ago, 2.months.from_now) }, nil).to_a
expect(result).to eq [contact_two]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/mail_chimp/campaign_logger_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe MailChimp::CampaignLogger do
let(:mail_chimp_account) { create(:mail_chimp_account, auto_log_campaigns: true) }
let(:account_list) { mail_chimp_account.account_list }
let(:mock_gibbon) { double(:mock_gibbon) }
let(:mock_gibbon_campaigns) { double(:mock_gibbon_campaigns) }
subject { described_class.new(mail_chimp_account) }
context '#log_sent_campaign' do
before do
allow(Gibbon::Request).to receive(:new).and_return(mock_gibbon)
allow(mock_gibbon).to receive(:timeout)
allow(mock_gibbon).to receive(:timeout=)
end
context 'auto_log_campaigns is false' do
before do
mail_chimp_account.update(auto_log_campaigns: false)
end
it 'should not log' do
expect(subject).to_not receive(:log_sent_campaign!)
subject.log_sent_campaign('Random_id', 'Random Subject')
end
end
context 'automation type campaign' do
before do
allow(mock_gibbon).to receive(:campaigns).with('Random_id').and_return(mock_gibbon_campaigns)
campaign_values = { 'send_time' => 30.minutes.ago.to_s, 'type' => 'automation' }
allow(mock_gibbon_campaigns).to receive(:retrieve).and_return(campaign_values)
end
it 'should not log' do
expect(subject).to_not receive(:log_sent_campaign!)
subject.log_sent_campaign('Random_id', 'Random Subject')
end
end
context 'error handling' do
it 'handles case where campaign not completely sent' do
expect(subject).to receive(:log_sent_campaign!).and_raise(Gibbon::MailChimpError, 'code 301')
expect(mock_gibbon).to receive(:campaigns).with('Random_id').and_return(mock_gibbon_campaigns)
expect(mock_gibbon_campaigns).to receive(:retrieve).and_return('send_time' => 30.minutes.ago.to_s)
expect do
subject.log_sent_campaign('Random_id', 'Random Subject')
end.to raise_error LowerRetryWorker::RetryJobButNoRollbarError
end
it 'handles case where campaign has been running for more than one hour' do
expect(subject).to receive(:log_sent_campaign!).and_raise(Gibbon::MailChimpError, 'code 301')
expect(mock_gibbon).to receive(:campaigns).with('Random_id').and_return(mock_gibbon_campaigns)
expect(mock_gibbon_campaigns).to receive(:retrieve).and_return('send_time' => 2.hours.ago.to_s)
expect do
subject.log_sent_campaign('Random_id', 'Random Subject')
end.not_to raise_error
end
it 'handles case where campaign is under compliance review' do
exception = Gibbon::MailChimpError.new('Error', title: 'Compliance Related', status_code: 403)
expect(subject).to receive(:log_sent_campaign!).and_raise(exception)
expect(mock_gibbon).to receive(:campaigns).with('Random_id').and_return(mock_gibbon_campaigns)
expect(mock_gibbon_campaigns).to receive(:retrieve).and_return('send_time' => 2.hours.ago.to_s)
expect do
subject.log_sent_campaign('Random_id', 'Random Subject')
end.not_to raise_error
end
it 'handles all other errors by raising the Mail Chimp error' do
allow(mock_gibbon).to receive(:campaigns).and_return(mock_gibbon_campaigns)
allow(mock_gibbon_campaigns).to receive(:retrieve).and_return('send_time' => 2.hours.ago.to_s)
expect(subject).to receive(:log_sent_campaign!).and_raise(Gibbon::MailChimpError)
expect do
subject.log_sent_campaign('Random_id', 'Random Subject')
end.to raise_error Gibbon::MailChimpError
end
it 'handles invalid api key' do
allow(mock_gibbon).to receive(:campaigns).and_return(mock_gibbon_campaigns)
exception = Gibbon::MailChimpError.new("Your API key may be invalid, or you've attempted to access the wrong datacenter.")
allow(mock_gibbon_campaigns).to receive(:retrieve).and_raise(exception)
mail_chimp_account.update_column(:active, true)
expect do
subject.log_sent_campaign('Random_id', 'Random Subject')
end.to change { mail_chimp_account.reload.active }.to(false)
end
end
context 'successful logging' do
let(:sent_to_email) { '<EMAIL>' }
let!(:person) { create(:person, primary_email_address: build(:email_address, email: sent_to_email)) }
let!(:contact) { create(:contact, account_list: account_list, primary_person: person) }
let(:mock_gibbon_reports) { double(:mock_gibbon_reports) }
let(:mock_gibbon_sent_to) { double(:mock_gibbon_sent_to) }
let(:sent_to_reports) do
{
sent_to: [
{
email_address: sent_to_email
}
]
}
end
let(:logged_task) { Task.last }
let(:send_time) { 30.minutes.ago.to_s }
let(:mock_second_gibbon_campaigns) { double(:mock_second_gibbon_campaigns) }
before do
allow(mock_gibbon).to receive(:campaigns).with('random_campaign_id').and_return(mock_gibbon_campaigns)
allow(mock_gibbon_campaigns).to receive(:retrieve).and_return('send_time' => send_time)
allow(mock_gibbon).to receive(:campaigns).with('second_random_campaign_id').and_return(mock_second_gibbon_campaigns)
allow(mock_second_gibbon_campaigns).to receive(:retrieve).and_return('send_time' => 2.days.ago.to_s)
allow(mock_gibbon).to receive(:reports).and_return(mock_gibbon_reports)
allow(mock_gibbon_reports).to receive(:sent_to).and_return(mock_gibbon_sent_to)
allow(mock_gibbon_sent_to).to receive(:retrieve).and_return(sent_to_reports)
end
it 'logs the sent campaign' do
expect do
subject.log_sent_campaign('random_campaign_id', 'Random Subject')
end.to change { Task.count }.by(1)
expect(logged_task.completed).to be_truthy
expect(logged_task.start_at).to eq(send_time)
expect(logged_task.completed_at).to eq(send_time)
expect(logged_task.subject).to eq('MailChimp: Random Subject')
end
it 'does not log the same campaign more than once' do
expect { subject.log_sent_campaign('random_campaign_id', 'Random Subject') }.to change { Task.count }.by(1)
expect(mock_gibbon).to receive(:reports).and_return(mock_gibbon_reports)
expect(mock_gibbon_reports).to receive(:sent_to).and_return(mock_gibbon_sent_to)
expect(mock_gibbon_sent_to).to receive(:retrieve).and_return(sent_to_reports)
expect { subject.log_sent_campaign('random_campaign_id', 'Random Subject') }.to_not change { Task.count }
end
it 'does log two campaigns with the same subject but sent at different times' do
logger1 = subject
expect { logger1.log_sent_campaign('random_campaign_id', 'Random Subject') }.to change { Task.count }.by(1)
expect(mock_gibbon).to receive(:reports).and_return(mock_gibbon_reports)
expect(mock_gibbon_reports).to receive(:sent_to).and_return(mock_gibbon_sent_to)
expect(mock_gibbon_sent_to).to receive(:retrieve).and_return(sent_to_reports)
logger2 = described_class.new(mail_chimp_account)
expect { logger2.log_sent_campaign('second_random_campaign_id', 'Random Subject') }.to change { Task.count }.by(1)
end
it 'updates prayer_letter_last_sent' do
expect do
subject.log_sent_campaign('random_campaign_id', 'Random Subject')
end.to change { mail_chimp_account.prayer_letter_last_sent }
end
it 'does not updates prayer_letter_last_sent if lower' do
mail_chimp_account.update(prayer_letter_last_sent: DateTime.now.utc)
expect do
subject.log_sent_campaign('random_campaign_id', 'Random Subject')
end.to_not change { mail_chimp_account.prayer_letter_last_sent }
end
end
end
end
|
chuckmersereau/api_practice
|
app/preloaders/api/v2/appeals_preloader.rb
|
class Api::V2::AppealsPreloader < ApplicationPreloader
ASSOCIATION_PRELOADER_MAPPING = {}.freeze
FIELD_ASSOCIATION_MAPPING = {}.freeze
end
|
chuckmersereau/api_practice
|
spec/factories/contact_donor_accounts.rb
|
<reponame>chuckmersereau/api_practice
FactoryBot.define do
factory :contact_donor_account do
contact nil
donor_account nil
end
end
|
chuckmersereau/api_practice
|
app/policies/person/google_account_policy.rb
|
class Person::GoogleAccountPolicy < ApplicationPolicy
private
def resource_owner?
resource.person_id == user.id
end
end
|
chuckmersereau/api_practice
|
spec/workers/google_calendar_sync_task_worker_spec.rb
|
require 'rails_helper'
describe GoogleCalendarSyncTaskWorker do
let(:task_id) { 1 }
let(:google_integration_id) { 2 }
it 'tells the GoogleCalendarIntegrator to sync_task' do
google_integration_double = instance_double('GoogleIntegration')
calendar_integrator_double = instance_double('GoogleCalendarIntegrator')
expect(GoogleIntegration).to receive(:find).with(google_integration_id).and_return(google_integration_double)
expect(google_integration_double).to receive(:calendar_integrator).and_return(calendar_integrator_double)
expect(calendar_integrator_double).to receive(:sync_task).with(task_id)
GoogleCalendarSyncTaskWorker.new.perform(google_integration_id, task_id)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.