repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/reports/pledge_histories_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Reports > Pledge Histories Report' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:reports, :pledge_histories])
let(:resource_type) { 'reports_pledge_histories_periods' }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:resource_attributes) do
%w(
created_at
start_date
end_date
pledged
received
updated_at
updated_in_db_at
)
end
context 'authorized user' do
before { api_login(user) }
# index
get '/api/v2/reports/pledge_histories/' do
doc_helper.insert_documentation_for(action: :index, context: self)
example doc_helper.title_for(:index), document: doc_helper.document_scope do
explanation doc_helper.description_for(:index)
do_request
check_collection_resource(13)
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/merge_spec.rb
|
<gh_stars>0
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Account Lists > Merges' do
include_context :json_headers
documentation_scope = :account_list_api_merges
let(:resource_type) { 'merge' }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:account_list_id) { account_list.id }
let!(:account_list2) { create(:account_list) }
let!(:account_list2_id) { account_list2.id }
let(:form_data) do
{
data: {
type: 'merge',
relationships: {
account_list_to_merge: {
data: {
type: 'account_lists',
id: account_list2_id
}
}
}
}
}
end
before do
account_list2.users << user
end
context 'authorized user' do
before { api_login(user) }
post '/api/v2/account_lists/:account_list_id/merge' do
parameter 'account_list_id', 'Account List ID', required: true
parameter 'id', 'ID (id of account list to be merged)', required: true, scope: [:data, :attributes]
example 'Account List [MERGE]', document: documentation_scope do
explanation 'Merges the contacts of the given Account List into this Account List'
do_request form_data
expect(response_status).to eq(201), invalid_status_detail
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120517205400_add_time_zone_and_locale_to_person.rb
|
class AddTimeZoneAndLocaleToPerson < ActiveRecord::Migration
def change
add_column :people, :time_zone, :string, limit: 100
add_column :people, :locale, :string, limit: 10
end
end
|
chuckmersereau/api_practice
|
app/helpers/contacts_helper.rb
|
module ContactsHelper
PLEDGE_AMOUNT_INDEX = 12
def spreadsheet_header_titles
[_('Contact Name'), _('First Name'), _('Last Name'), _('Spouse First Name'), _('Greeting'),
_('Envelope Greeting'), _('Mailing Street Address'), _('Mailing City'), _('Mailing State'),
_('Mailing Postal Code'), _('Mailing Country'), _('Status'), _('Commitment Amount'),
_('Commitment Currency'), _('Commitment Frequency'), _('Newsletter'), _('Commitment Received'),
_('Tags'), _('Primary Email'), _('Spouse Email'), _('Other Email'), _('Spouse Other Email'),
_('Primary Phone'), _('Spouse Phone'), _('Other Phone'), _('Spouse Other Phone')]
end
def spreadsheet_header_titles_joined
spreadsheet_header_titles.map { |h| _(h) }.join('","')
end
def spreadsheet_values(contact)
@contact = contact
@row = []
return @row unless @contact
@primary_person, @spouse = [@contact.primary_person, @contact.spouse].reject { |person| person&.deceased? }
if @primary_person
add_preliminary_values_to_row
add_email_addresses_to_row
add_phone_numbers_to_row
end
@row
end
def type_array
a = Array.new(spreadsheet_header_titles.count, :string)
# Commitment Amount is a number
a[PLEDGE_AMOUNT_INDEX] = :float
a
end
private
def add_preliminary_values_to_row
@row << @contact.name
@row << @primary_person.first_name
@row << @primary_person.last_name
@row << @spouse&.first_name
@row << @contact.greeting
@row << @contact.envelope_greeting
@row << @contact.mailing_address.csv_street
@row << @contact.mailing_address.city
@row << @contact.mailing_address.state
@row << @contact.mailing_address.postal_code
@row << @contact.mailing_address.csv_country(@contact.account_list.home_country)
@row << @contact.status
@row << @contact.pledge_amount
@row << @contact.pledge_currency
@row << Contact.pledge_frequencies[@contact.pledge_frequency || 1.0]
@row << @contact.send_newsletter
@row << (@contact.pledge_received ? 'Yes' : 'No')
@row << @contact.tag_list
end
def add_email_addresses_to_row
@primary_email_address = @primary_person&.primary_email_address
@spouse_primary_email_address = @spouse&.primary_email_address
@row << @primary_email_address&.email || ''
@row << @spouse_primary_email_address&.email || ''
@other_relevant_email_addresses = fetch_other_relevant_email_addresses
@row << find_email_address_by_person_id(@primary_person&.id)&.email || ''
@row << find_email_address_by_person_id(@spouse&.id)&.email || ''
end
def add_phone_numbers_to_row
@primary_phone_number = @primary_person&.primary_phone_number
@spouse_primary_phone_number = @spouse&.primary_phone_number
@row << @primary_phone_number&.number || ''
@row << @spouse_primary_phone_number&.number || ''
@other_relevant_phone_numbers = fetch_other_relevant_phone_numbers
@row << find_phone_number_by_person_id(@primary_person&.id)&.number || ''
@row << find_phone_number_by_person_id(@spouse&.id)&.number || ''
end
def find_email_address_by_person_id(person_id)
return unless person_id
@other_relevant_email_addresses.find do |email_address|
email_address.person_id == person_id
end
end
def find_phone_number_by_person_id(person_id)
return unless person_id
@other_relevant_phone_numbers.find do |phone_number|
phone_number.person_id == person_id
end
end
def fetch_other_relevant_email_addresses
@contact.people
.alive
.map(&:email_addresses)
.flatten
.compact
.select do |email_address|
ids = [@primary_email_address&.id, @spouse_primary_email_address&.id]
ids.exclude?(email_address.id) && email_address.historic == false
end
end
def fetch_other_relevant_phone_numbers
@contact.people
.alive
.map(&:phone_numbers)
.flatten
.compact
.select do |phone_number|
ids = [@primary_phone_number&.id, @spouse_primary_phone_number&.id]
ids.exclude?(phone_number.id) && phone_number.historic == false
end
end
def contact_locale_filter_options(account_list)
options = account_list.contact_locales.select(&:present?).map do |locale|
[_(MailChimpAccount::Locales::LOCALE_NAMES[locale]), locale]
end
options_for_select(
[[_('-- Any --'), ''], [_('-- Unspecified --'), 'null']] +
options
)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120606235805_create_contact_donor_accounts.rb
|
<reponame>chuckmersereau/api_practice
class CreateContactDonorAccounts < ActiveRecord::Migration
def change
create_table :contact_donor_accounts do |t|
t.belongs_to :contact
t.belongs_to :donor_account
t.timestamps null: false
end
remove_index :contacts, name: :index_contacts_on_donor_account_id_and_account_list_id
Contact.all.each do |c|
ContactDonorAccount.create!(contact_id: c.id, donor_account_id: c.donor_account_id)
end
remove_column :contacts, :donor_account_id
add_index :contact_donor_accounts, :contact_id
add_index :contact_donor_accounts, :donor_account_id
end
end
|
chuckmersereau/api_practice
|
app/policies/google_integration_policy.rb
|
class GoogleIntegrationPolicy < ApplicationPolicy
def sync?
resource_owner?
end
private
def resource_owner?
@user.account_lists.exists?(id: @resource.account_list_id) &&
@user.google_accounts.exists?(id: @resource.google_account_id)
end
end
|
chuckmersereau/api_practice
|
dev/util/donor_system_util.rb
|
<reponame>chuckmersereau/api_practice<filename>dev/util/donor_system_util.rb
def data_server_profiles(user)
data_server = DataServer.new(org_account(user))
data_server.send(:profiles)
end
def siebel_profiles(user)
siebel = Siebel.new(org_account(user))
siebel.send(:profiles)
end
def org_account(user)
org_accounts = user.organization_accounts
puts "User #{user} has #{org_accounts.count} org accounts" if org_accounts.count > 1
org_accounts.first
end
def donors_response(org_account, profile)
d = DataServer.new(org_account)
org = org_account.organization
params = d.send(:get_params,
org.addresses_params,
profile: profile.code.to_s,
datefrom: org.minimum_gift_date.to_s,
personid: org_account.remote_id)
d.send(:get_response, org.addresses_url, params)
end
def desig_profile(profile, oa)
Retryable.retryable do
if profile.id
oa.organization.designation_profiles.where(user_id: oa.person_id, code: profile.id)
.first_or_create(name: profile.name)
else
oa.organization.designation_profiles.where(user_id: oa.person_id, code: nil)
.first_or_create(name: profile.name)
end
end
end
def fix_donation_totals(account_list)
account_list = account_list.id unless account_list.blank? || account_list.is_a?(Integer)
sql = '
UPDATE contacts
SET total_donations = correct_totals.total
FROM (
SELECT contacts.id contact_id, SUM(donations.amount) total
FROM contacts, contact_donor_accounts, account_list_entries, donations
WHERE contacts.id = contact_donor_accounts.contact_id
AND donations.donor_account_id = contact_donor_accounts.donor_account_id
AND contacts.account_list_id = account_list_entries.account_list_id ' +
(account_list ? "AND account_list_entries.account_list_id = #{account_list}" : '') +
' AND donations.designation_account_id = account_list_entries.designation_account_id
GROUP BY contacts.id
) correct_totals
WHERE correct_totals.contact_id = contacts.id
'
Donation.connection.execute(sql)
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/pledge_late_by.rb
|
<reponame>chuckmersereau/api_practice
class Contact::Filter::PledgeLateBy < Contact::Filter::Base
def execute_query(contacts, filters)
return contacts unless filters[:pledge_late_by]
min_days, max_days = filters[:pledge_late_by].split('_').map(&:to_i).map(&:days)
contacts.late_by(min_days, max_days)
end
def title
_('Late By')
end
def parent
_('Commitment Details')
end
def type
'radio'
end
def custom_options
[{ name: _('Less than 30 days late'), id: '0_30' },
{ name: _('More than 30 days late'), id: '30_60' },
{ name: _('More than 60 days late'), id: '60_90' },
{ name: _('More than 90 days late'), id: '90' }]
end
end
|
chuckmersereau/api_practice
|
config/initializers/global_registry.rb
|
<filename>config/initializers/global_registry.rb
require 'global_registry'
require 'global_registry_bindings'
GlobalRegistry.configure do |config|
config.access_token = ENV.fetch('GLOBAL_REGISTRY_TOKEN') { 'fake' }
config.base_url = ENV.fetch('GLOBAL_REGISTRY_URL') { 'https://backend.global-registry.org' }
end
GlobalRegistry::Bindings.configure do |config|
config.sidekiq_options = { queue: :api_global_registry_bindings }
end
unless ENV['ENABLE_GR_BINDINGS'] == 'true'
module GlobalRegistry
module Bindings
class Worker
class << self
def perform_async(*_args)
end
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/chalkline_mails_controller_spec.rb
|
<filename>spec/controllers/api/v2/account_lists/chalkline_mails_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V2::AccountLists::ChalklineMailsController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:resource) { AccountList::ChalklineMails.new(account_list: account_list) }
let(:parent_param) { { account_list_id: account_list.id } }
let(:parsed_response_body) { JSON.parse(response.body) }
describe 'POST create' do
subject { post :create, { data: { type: 'chalkline_mails' } }.merge(parent_param) }
context 'unauthenticated' do
before do
subject
end
it 'responds forbidden' do
expect(response.status).to eq(401)
end
it 'returns a json api spec body' do
expect(parsed_response_body).to eq(
'errors' => [{
'status' => '401', 'title' => 'Unauthorized', 'detail' => 'Exceptions::AuthenticationError'
}]
)
end
end
context 'authenticated' do
before do
travel_to Time.current
api_login(user)
expect_any_instance_of(AccountList::ChalklineMails).to receive(:send_later).once
subject
end
after { travel_back }
it 'responds success' do
expect(response.status).to eq(201)
end
it 'returns a json api spec body' do
expect(parsed_response_body).to eq(
'data' => {
'id' => '',
'type' => 'chalkline_mails',
'attributes' => { 'created_at' => Time.current.utc.iso8601, 'updated_at' => nil, 'updated_in_db_at' => nil }
}
)
end
end
context 'account list does not belong to user' do
let(:account_list) { create(:account_list) }
let(:expected_error_data) do
{
errors: [{
status: '404',
title: 'Not Found',
detail: "Couldn't find AccountList with 'id'=#{account_list.id} "\
'[WHERE "account_list_users"."user_id" = ?]'
}]
}.deep_stringify_keys
end
before do
api_login(user)
subject
end
it 'responds not found' do
expect(response.status).to eq(404)
end
it 'returns a json api spec body' do
expect(parsed_response_body).to eq(expected_error_data)
end
end
end
end
|
chuckmersereau/api_practice
|
config/initializers/controller_to_serializer_lookup.rb
|
<gh_stars>0
CONTROLLER_TO_SERIALIZER_LOOKUP = {
'Api::V2::AccountLists::AnalyticsController' => 'AccountList::AnalyticsSerializer',
'Api::V2::AccountLists::UsersController' => 'AccountList::UserSerializer',
'Api::V2::AccountLists::CoachesController' => 'AccountList::UserSerializer',
'Api::V2::Contacts::AnalyticsController' => 'Contact::AnalyticsSerializer',
'Api::V2::Contacts::DuplicatesController' => 'DuplicateRecordPairSerializer',
'Api::V2::Contacts::MergesController' => 'ContactSerializer',
'Api::V2::Contacts::People::DuplicatesController' => 'DuplicateRecordPairSerializer',
'Api::V2::Contacts::People::MergesController' => 'PersonSerializer',
'Api::V2::Contacts::ReferrersController' => 'ContactSerializer',
'Api::V2::Reports::DonorCurrencyDonationsController' => 'Reports::DonorCurrencyDonationsSerializer',
'Api::V2::Reports::ExpectedMonthlyTotalsController' => 'Reports::ExpectedMonthlyTotalsSerializer',
'Api::V2::Reports::GoalProgressesController' => 'Reports::GoalProgressSerializer',
'Api::V2::Reports::MonthlyGivingGraphsController' => 'Reports::MonthlyGivingGraphSerializer',
'Api::V2::Reports::MonthlyLossesGraphsController' => 'Reports::MonthlyLossesGraphSerializer',
'Api::V2::Reports::PledgeHistoriesController' => 'Reports::PledgeHistoriesSerializer',
'Api::V2::Reports::SalaryCurrencyDonationsController' => 'Reports::SalaryCurrencyDonationsSerializer',
'Api::V2::Reports::YearDonationsController' => 'Reports::YearDonationsSerializer',
'Api::V2::Reports::AppointmentResultsController' => 'Reports::AppointmentResultsPeriodSerializer',
'Api::V2::Reports::ActivityResultsController' => 'Reports::ActivityResultsSerializer',
'Api::V2::Tasks::AnalyticsController' => 'Task::AnalyticsSerializer'
}.freeze
|
chuckmersereau/api_practice
|
app/services/contact/status_suggester.rb
|
<reponame>chuckmersereau/api_practice
class Contact::StatusSuggester
# This constant represents how far back in time we will look to discover a Contact's pledge frequency.
# For example, a value of a 4 would mean we get the last 4 Donations that the Contact gave, and try
# to establish if it was 4 years for a annual giver, or 4 months for a monthly giver, etc.
# A higher value might produce less results, as there might not be enough Donations to sample.
# This number should not be lower than 4.
NUMBER_OF_DONATIONS_TO_SAMPLE = 4
attr_reader :contact, :pledge_frequencies, :donation_scope, :sample_donations,
:samples_most_frequent_amount
def initialize(contact:)
@contact = contact
@pledge_frequencies = Contact.pledge_frequencies.keys
@donation_scope = contact.donations.order(donation_date: :desc)
@sample_donations = donation_scope.limit(NUMBER_OF_DONATIONS_TO_SAMPLE)
@samples_most_frequent_amount = find_most_frequent_amount_in_sample_donations
end
def suggested_pledge_frequency
return @suggested_pledge_frequency if defined?(@suggested_pledge_frequency)
@suggested_pledge_frequency = suggested_status == 'Partner - Financial' ? find_suggested_pledge_frequency : nil
end
def suggested_pledge_amount
return @suggested_pledge_amount if defined?(@suggested_pledge_amount)
@suggested_pledge_amount = suggested_status == 'Partner - Financial' ? samples_most_frequent_amount : nil
end
def suggested_pledge_currency
return @suggested_pledge_currency if defined?(@suggested_pledge_currency)
@suggested_pledge_currency = suggested_pledge_amount.present? ? find_most_frequent_currency_in_sample_donations : nil
end
# We currently only suggest two possible statuses: Partner - Financial, or Partner - Special
def suggested_status
if (find_suggested_pledge_frequency.present? && !contact_has_stopped_giving?) || extra_donation_given?
'Partner - Financial'
elsif sample_donations.present?
'Partner - Special'
end
end
def contact_has_stopped_giving?
return false unless find_suggested_pledge_frequency.present?
suggested_pledge_frequency_in_days = convert_pledge_frequency_to_days(find_suggested_pledge_frequency)
sample_donations.present? && donation_scope.where('donation_date > ?', (suggested_pledge_frequency_in_days * 2).days.ago).blank?
end
private
def find_suggested_pledge_frequency
return nil if donation_scope.blank?
@found_suggested_pledge_frequency ||= find_pledge_frequency_using_primary_method || find_pledge_frequency_using_secondary_method
end
# This method counts the number of times the Contact donated at the given frequency and amount.
# This approach is intended to catch inconsistent donations, as it doesn't matter when exactly the donation was made,
# as long as it was sometime within the expected period.
def find_pledge_frequency_using_primary_method
find_donations_given_within_a_period
end
def extra_donation_given?
return nil if donation_scope.blank?
find_donations_given_within_a_period(NUMBER_OF_DONATIONS_TO_SAMPLE + 1)
end
def find_donations_given_within_a_period(sample_size = NUMBER_OF_DONATIONS_TO_SAMPLE)
pledge_frequencies.sort.detect do |pledge_frequency|
look_back_date = find_look_back_date_for_pledge_frequency(pledge_frequency)
# Count the number of donations given within the look back period (we also need to consider the current period, which is incomplete)
donation_scope.where(amount: samples_most_frequent_amount)
.where('donation_date >= ?', look_back_date)
.count == sample_size
end
end
# This method calculates the number of days in-between the donations,
# and then finds the most frequently occurring number.
# This method is useful if there are not very many donations available to analyze (maybe the donor is new).
def find_pledge_frequency_using_secondary_method
donations = sample_donations.where(amount: samples_most_frequent_amount)
# Convert the number days in-between donations into pledge frequencies
frequencies = number_of_days_in_between_donations(donations).collect do |d|
convert_number_of_days_to_pledge_frequency(d)
end
# Find the most frequently occuring frequency, and return it
frequencies.uniq.max_by do |frequency_to_look_for|
frequencies.count { |frequency| frequency == frequency_to_look_for }
end
end
# Based on the given pledge_frequency, find the earliest date after which the donor
# would hopefully have given the number of donations equal to NUMBER_OF_DONATIONS_TO_SAMPLE.
def find_look_back_date_for_pledge_frequency(pledge_frequency)
frequency_in_days = convert_pledge_frequency_to_days(pledge_frequency)
# The range of time we will look within is based on the most recent donation,
# this let's us guess the frequency even if they have stopped giving.
latest_donation_date = donation_scope.first.donation_date
look_back_date = latest_donation_date - (frequency_in_days * NUMBER_OF_DONATIONS_TO_SAMPLE).round.days
# Remove half of one period, otherwise periods will start to overlap too much and we'll get worse results.
look_back_date + (frequency_in_days / 2).round.days
end
# Donors that have pledged regular support usually give the same amount each time,
# but they might give the occasional one-off gift (which is probably of a different amount).
# We want to exclude the one-off gifts. So, we will find the most frequently given amount,
# and use that as our guess for the suggested_pledge_amount.
def find_most_frequent_amount_in_sample_donations
amounts = sample_donations.pluck(:amount)
amounts.max_by do |amount_to_look_for|
amounts.count { |amount| amount == amount_to_look_for }
end
end
# Find the currency that matches our suggested_pledge_amount.
def find_most_frequent_currency_in_sample_donations
currencies = sample_donations.where(amount: suggested_pledge_amount).pluck(:currency)
currencies.max_by do |currency_to_look_for|
currencies.count { |currency| currency == currency_to_look_for }
end
end
def convert_pledge_frequency_to_days(frequency)
(frequency * 30).round
end
def number_of_days_in_between_donations(donations)
(0..donations.size - 2).collect do |index|
((donations[index].donation_date.to_time - donations[index + 1].donation_date.to_time) / 60 / 60 / 24).round
end
end
# Pledge frequencies are stored relative to month (1.0 frequency is one month).
# This method will try to convert a number of days to a pledge frequency.
# For example, 30 days should return 1.0
# (we need some flexability, because some months have more days than others)
def convert_number_of_days_to_pledge_frequency(number_of_days)
pledge_frequencies.sort.detect do |frequency|
((27 * frequency).round..(32 * frequency).round).cover?(number_of_days)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/mail_chimp/batch_results_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe MailChimp::BatchResults do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.first }
let(:mail_chimp_account) { create(:mail_chimp_account, active: true, account_list: account_list) }
let(:mock_gibbon) { double(:mock_gibbon) }
let(:mock_gibbon_batches) { double(:mock_gibbon_batches) }
let(:batch_id) { 'asdf_batch_id' }
let(:invalid_email) { '<EMAIL>' }
subject { described_class.new(mail_chimp_account) }
context '#check_batch' 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=)
allow(mock_gibbon).to receive(:batches).with(batch_id).and_return(mock_gibbon_batches)
end
context 'finished batch' do
before do
failed_batch_fixture = 'spec/fixtures/failed_mc_batch.tar.gz'
allow(mock_gibbon_batches).to receive(:retrieve).and_return('status' => 'finished',
'errored_operations' => 1,
'response_body_url' => failed_batch_fixture)
end
context 'two contacts with invalid emails' do
let!(:contact1) do
create(:contact_with_person, account_list: account_list).tap do |c|
c.primary_person.update(email: invalid_email)
end
end
let!(:contact2) do
create(:contact_with_person, account_list: account_list).tap do |c|
c.primary_person.update(email: invalid_email)
end
end
it 'mark emails as historic' do
subject.check_batch(batch_id)
expect(contact1.primary_person.email_addresses.find_by(email: invalid_email)).to be_historic
expect(contact2.primary_person.email_addresses.find_by(email: invalid_email)).to be_historic
end
it 'marks second emails as primary' do
contact1.primary_person.email_addresses.create(email: '<EMAIL>')
contact1.primary_person.email_addresses.find_by(email: invalid_email).update(primary: true)
expect { subject.check_batch(batch_id) }.to change { contact1.primary_person.reload.email }
end
it 'do not update email address if it is not primary' do
contact1.primary_person.update(email: '<EMAIL>')
subject.check_batch(batch_id)
expect(contact1.primary_person.email_addresses.find_by(email: invalid_email)).to_not be_historic
expect(contact2.primary_person.email_addresses.find_by(email: invalid_email)).to be_historic
end
it 'sends an email to users on account list' do
account_list.users << create(:user)
expect { subject.check_batch(batch_id) }.to change { Sidekiq::Extensions::DelayedMailer.jobs.size }.by(2)
end
end
context 'compliance error' do
let!(:contact) do
create(:contact_with_person, account_list: account_list).tap do |c|
c.primary_person.update(email: invalid_email)
end
end
before do
mock_json = [
{
'status_code' => 400,
'operation_id' => nil,
'response' => "{\"status\":400,\"detail\":\"#{invalid_email} is in a compliance state "\
'due to unsubscribe, bounce, or compliance review and cannot be subscribed."}'
}
]
allow(subject).to receive(:load_batch_json).and_return(mock_json)
member_info = [{ 'status' => 'cleaned' }]
allow(subject.send(:wrapper)).to receive(:list_member_info).and_return(member_info)
end
it 'sends an email to users on account list' do
expect { subject.check_batch(batch_id) }.to change { Sidekiq::Extensions::DelayedMailer.jobs.size }.by(1)
end
end
context 'unknown error' do
let!(:contact) do
create(:contact_with_person, account_list: account_list).tap do |c|
c.primary_person.update(email: invalid_email)
end
end
before do
mock_json = [
{
'status_code' => 400,
'operation_id' => nil,
'response' => '{"status":400,"detail":"Some un-expected error from MailChimp"}'
}
]
allow(subject).to receive(:load_batch_json).and_return(mock_json)
end
it 'notifies Rollbar' do
expect(Rollbar).to receive(:info)
subject.check_batch(batch_id)
end
end
context '404 error' do
before do
allow(mock_gibbon_batches).to receive(:retrieve).and_return('status' => 'finished',
'errored_operations' => 1,
'response_body_url' => 'url')
not_found_response = [
{
"status_code": 404,
"operation_id": nil,
"response": '{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",'\
'"title":"Resource Not Found","status":404,'\
'"detail":"The requested resource could not be found.","instance":""}'
}
].to_json
allow(subject).to receive(:read_first_file_from_tar).and_return(not_found_response)
end
it 'does not send an email' do
expect { subject.check_batch(batch_id) }.to_not change { Sidekiq::Extensions::DelayedMailer.jobs.size }
end
end
context 'no failures' do
before do
allow(mock_gibbon_batches).to receive(:retrieve).and_return('status' => 'finished', 'errored_operations' => 0)
end
it 'does not try to load the zip file' do
expect(subject).to_not receive(:read_first_file_from_tar)
subject.check_batch(batch_id)
end
end
end
context 'pending batch' do
before do
allow(mock_gibbon_batches).to receive(:retrieve).and_return('status' => 'pending')
end
it 'should retry' do
expect { subject.check_batch(batch_id) }.to raise_error LowerRetryWorker::RetryJobButNoRollbarError
end
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/tasks/bulk_controller.rb
|
class Api::V2::Tasks::BulkController < Api::V2::BulkController
resource_type :tasks
def create
build_empty_tasks
persist_tasks
end
def update
load_tasks
persist_tasks
end
def destroy
load_tasks
authorize_tasks
destroy_tasks
end
private
def load_tasks
@tasks = task_scope.where(id: task_id_params).tap(&:first!)
end
def authorize_tasks
bulk_authorize(@tasks)
end
def destroy_tasks
@destroyed_tasks = @tasks.select(&:destroy)
render_tasks(@destroyed_tasks)
end
def task_id_params
params
.require(:data)
.collect { |hash| hash[:task][:id] }
end
def task_scope
current_user.tasks
end
def persist_tasks
build_tasks
authorize_tasks
save_tasks
render_tasks(@tasks)
end
def render_tasks(tasks)
render json: BulkResourceSerializer.new(resources: tasks),
include: include_params,
fields: field_params
end
def save_tasks
@tasks.each { |task| task.save(context: persistence_context) }
end
def build_empty_tasks
@tasks = params.require(:data).map { |data| Task.new(id: data['task']['id']) }
end
def build_tasks
@tasks.each do |task|
task_index = data_attribute_index(task)
attributes = params.require(:data)[task_index][:task]
task.assign_attributes(
task_params(attributes)
)
end
end
def data_attribute_index(task)
params
.require(:data)
.find_index { |task_data| task_data[:task][:id] == task.id }
end
def task_params(attributes)
attributes ||= params.require(:task)
attributes.permit(Task::PERMITTED_ATTRIBUTES)
end
end
|
chuckmersereau/api_practice
|
app/services/tnt_import/xml_reader.rb
|
<gh_stars>0
class TntImport::XmlReader
UNPARSABLE_UTF8_CHARACTERS = [
"\u0000" # "null" character
].freeze
def initialize(import)
@import = import
end
def parsed_xml
TntImport::Xml.new(read_xml)
end
private
def file_path
@import.file.cache_stored_file!
@import.file.path
end
def read_xml
contents = File.open(file_path, 'r:utf-8').read
UNPARSABLE_UTF8_CHARACTERS.each do |unparsable_utf8_character|
contents.gsub!(unparsable_utf8_character, '')
end
Nokogiri::XML(contents)
rescue ArgumentError => exception
Rollbar.info(exception)
contents = File.open(file_path, 'r:windows-1251:utf-8').read
Nokogiri::XML(contents)
end
end
|
chuckmersereau/api_practice
|
spec/services/application_filter_spec.rb
|
<filename>spec/services/application_filter_spec.rb
require 'rails_helper'
describe ApplicationFilter do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
describe '#query' do
let(:contact_one) { create(:contact, name: 'name') }
let(:contact_two) { create(:contact, name: 'not name') }
describe '#without reverse flag' do
let(:filter) { { simple_name_search: 'name' } }
it 'returns the resources after filtering' do
expect(SimpleNameSearch.new(account_list).query(Contact, filter)).to eq [contact_one]
end
end
describe '#with reverse flag' do
let(:filter) { { simple_name_search: 'name', reverse_simple_name_search: true } }
it 'returns the revese of resources that would be returned by filtering' do
expect(SimpleNameSearch.new(account_list).query(Contact, filter)).to eq [contact_two]
end
end
class SimpleNameSearch < ApplicationFilter
def execute_query(scope, filters)
scope.where(name: filters[:simple_name_search])
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20141215161039_create_nicknames.rb
|
class CreateNicknames < ActiveRecord::Migration
def change
create_table :nicknames do |t|
t.string "name", null: false
t.string "nickname", null: false
t.string "source"
t.integer "num_merges", default: 0, null: false
t.integer "num_not_duplicates", default: 0, null: false
t.integer "num_times_offered", default: 0, null: false
t.boolean "suggest_duplicates", default: false, null: false
t.timestamps null: false
end
add_index :nicknames, :name
add_index :nicknames, :nickname
add_index :nicknames, [:name, :nickname], unique: true
end
end
|
chuckmersereau/api_practice
|
spec/mailers/account_list_invite_mailer_spec.rb
|
require 'rails_helper'
describe AccountListInviteMailer do
context '#email' do
let(:user_inviting) { create(:user, first_name: 'Java', last_name: 'Script') }
let(:invite_link) do
"https://mpdx.org/account_lists/#{invite.account_list.id}/accept_invite/#{invite.id}?code=#{invite.code}"
end
let(:mail) { AccountListInviteMailer.email(invite) }
context 'coach' do
let!(:invite) { create(:account_list_invite, invited_by_user_id: user_inviting.id, invite_user_as: 'coach') }
it 'renders the headers and the body contains the correct link' do
expect(mail.subject).to eq('You\'ve been invited to be a coach for an account on MPDX')
expect(mail.to).to eq(['<EMAIL>'])
expect(mail.from).to eq(['<EMAIL>'])
expect(mail.body.raw_source).to include(invite_link)
invite_message = 'You are getting this email because an MPDX user has '\
'invited you to be a coach for an account they manage.'
expect(mail.body.raw_source).to include(invite_message)
expect(mail.body.raw_source).to include('invited by Java Script')
expect(mail.body.raw_source).to include(invite.account_list.name)
end
end
context 'user' do
let!(:invite) { create(:account_list_invite, invited_by_user_id: user_inviting.id, invite_user_as: 'user') }
it 'renders the headers and the body contains the correct link' do
expect(mail.subject).to eq('You\'ve been invited to access an account on MPDX')
expect(mail.to).to eq(['<EMAIL>'])
expect(mail.from).to eq(['<EMAIL>'])
expect(mail.body.raw_source).to include(invite_link)
invite_message = 'You are getting this email because an MPDX user '\
'has invited you to access an account they manage.'
expect(mail.body.raw_source).to include(invite_message)
expect(mail.body.raw_source).to include('invited by Java Script')
expect(mail.body.raw_source).to include(invite.account_list.name)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/imports/google_controller_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe Api::V2::AccountLists::Imports::GoogleController, type: :controller do
let(:factory_type) { :import }
let(:resource_type) { :imports }
let!(:user) { create(:user_with_account) }
let!(:google_account) { create(:google_account, person: user) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:import) { create(:google_import, account_list: account_list, user: user) }
let(:id) { import.id }
let(:resource) { import }
let(:parent_param) { { account_list_id: account_list_id } }
let(:correct_attributes) do
{
'in_preview' => false,
'tag_list' => 'test,poster',
'groups' => [
'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/d',
'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/f'
],
'import_by_group' => 'true',
'override' => 'true',
'source' => 'google',
'group_tags' => {
'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/6' => 'my-contacts',
'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/d' => 'friends'
}
}
end
let(:correct_relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: account_list.id
}
},
user: {
data: {
type: 'users',
id: user.id
}
},
source_account: {
data: {
type: 'google_accounts',
id: google_account.id
}
}
}
end
let(:incorrect_attributes) { { source: nil } }
let(:unpermitted_attributes) { nil }
include_examples 'create_examples'
describe '#create' do
it 'defaults source to google' do
api_login(user)
post :create, full_correct_attributes.merge(source: 'bogus')
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.source).to eq 'google'
end
it 'defaults user_id to current user' do
api_login(user)
full_correct_attributes[:data][:relationships].delete(:user)
post :create, full_correct_attributes
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.user_id).to eq user.id
end
end
end
|
chuckmersereau/api_practice
|
spec/lib/batch_request_handler/instruments/logging_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/lib/batch_request_handler/instruments/logging_spec.rb
require 'spec_helper'
describe BatchRequestHandler::Instruments::Logging do
let(:params) { {} }
subject { described_class.new(params) }
describe '#around_perform_request' do
let(:env) { Rack::MockRequest.env_for('/api/v2/users') }
let(:block) { -> (_env) {} }
it 'logs to the logger' do
expect(Rails.logger).to receive(:info)
subject.around_perform_request(env, &block)
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/including.rb
|
<filename>app/controllers/concerns/including.rb
module Including
UNPERMITTED_INCLUDE_PARAMS = ['**'].freeze
private
def include_params
return [] unless params[:include]
if requested_include_params_that_are_permitted.include?('*')
fetch_full_list_of_include_params
else
requested_include_params_that_are_permitted
end
end
def requested_include_params_that_are_permitted
@requested_include_params_that_are_permitted ||= params[:include].split(',').map(&:strip) - UNPERMITTED_INCLUDE_PARAMS
end
def fetch_full_list_of_include_params
(full_list_of_direct_associations + requested_include_params_that_are_permitted - ['*']).uniq.map(&:to_s)
end
def full_list_of_direct_associations
serializer_class._reflections.keys
end
def serializer_class
(CONTROLLER_TO_SERIALIZER_LOOKUP[self.class.to_s] || "#{resource_class_name}Serializer").constantize
end
def resource_class_name
normalized_type = resource_type.to_s.pluralize
JsonApiService.configuration.custom_references[normalized_type.to_sym] || normalized_type.classify
end
def include_associations
::JSONAPI::IncludeDirective.new(include_params - ['*']).to_hash
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/tasks_all_completed_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::TasksAllCompleted do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:contact_three) { create(:contact, account_list_id: account_list.id) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id) }
before do
contact_one.tasks << create(:task, completed: false)
contact_one.tasks << create(:task, completed: true)
contact_two.tasks << create(:task, completed: true)
contact_two.tasks << create(:task, completed: true)
contact_three.tasks << create(:task, completed: false)
contact_three.tasks << create(:task, completed: false)
contact_four.tasks.delete_all
end
describe '#config' do
it 'returns expected config' do
expect(described_class.config([account_list])).to include(name: :tasks_all_completed,
parent: 'Tasks',
title: 'No Incomplete Tasks',
type: 'single_checkbox',
default_selection: false)
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, { tasks_all_completed: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { tasks_all_completed: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { tasks_all_completed: '' }, nil)).to eq(nil)
end
end
context 'filter by tasks_all_completed true' do
it 'returns only contacts that have no incomplete tasks' do
result = described_class.query(contacts, { tasks_all_completed: 'true' }, nil).to_a
expect(result).to match_array [contact_two, contact_four]
contact_one.tasks.update_all(completed: true)
result = described_class.query(contacts, { tasks_all_completed: 'true' }, nil).to_a
expect(result).to match_array [contact_one, contact_two, contact_four]
contact_four.tasks << create(:task, completed: false)
result = described_class.query(contacts, { tasks_all_completed: 'true' }, nil).to_a
expect(result).to match_array [contact_one, contact_two]
end
end
context 'filter by tasks_all_completed false' do
it 'does not filter' do
result = described_class.query(contacts, { tasks_all_completed: 'false' }, nil).to_a
expect(result).to match_array [contact_one, contact_two, contact_three, contact_four]
contact_five = create(:contact, account_list_id: account_list.id)
result = described_class.query(contacts, { tasks_all_completed: 'false' }, nil).to_a
expect(result).to match_array [contact_one, contact_two, contact_three, contact_four, contact_five]
end
end
end
end
|
chuckmersereau/api_practice
|
lib/json_api_service/validator.rb
|
<filename>lib/json_api_service/validator.rb
module JsonApiService
class Validator
def self.validate!(params:, context:, configuration:)
new(
params: params,
context: context,
configuration: configuration
).validate!
end
attr_reader :configuration,
:context,
:params
def initialize(params:, configuration:, context:)
@configuration = configuration
@context = context
@params = params
end
def validate!
verify_resource_type! if create? || update? || (destroy? && data?)
verify_type_existence! if create? || update? || (destroy? && data?)
verify_absence_of_invalid_keys_in_attributes! if create? || update?
true
end
def create?
params.dig(:action).to_s.to_sym == :create
end
def update?
params.dig(:action).to_s.to_sym == :update
end
def destroy?
params.dig(:action).to_s.to_sym == :destroy
end
def data?
!params.dig(:data).nil?
end
private
def foreign_key_present_detail(reference_array)
pointer_ref = "/#{reference_array.join('/')}"
'Foreign keys SHOULD NOT be referenced in the #attributes of a JSONAPI resource object. '\
"Reference: #{pointer_ref}"
end
def foreign_key_present_error(reference_array)
raise ForeignKeyPresentError, foreign_key_present_detail(reference_array)
end
def invalid_primary_key_placement_detail(reference_array)
actual = "/#{reference_array[0..-2].join('/')}/id"
expected = "/#{reference_array[0..-3].join('/')}/id"
'A primary key, if sent in a request, CANNOT be referenced in the #attributes of a JSONAPI '\
"resource object. It must instead be sent as a top level member of the resource's `data` "\
"object. Reference: `#{actual}`. Expected `#{expected}`"
end
def invalid_primary_key_placement_error(reference_array)
raise InvalidPrimaryKeyPlacementError, invalid_primary_key_placement_detail(reference_array)
end
def ignored_foreign_keys
configuration.ignored_foreign_keys
end
def invalid_resource_type_detail
"'#{resource_type_from_params}' is not a valid resource type for this endpoint. "\
"Expected '#{context.resource_type}' instead"
end
def missing_resource_type_error(reference_array)
raise MissingTypeError, missing_resource_type_detail(reference_array)
end
def missing_resource_type_detail(reference_array)
pointer_ref = "/#{reference_array.join('/')}/type"
'JSONAPI resource objects MUST contain a `type` top-level member of its hash for POST and '\
"PATCH requests. Expected to find a `type` member at #{pointer_ref}"
end
def resource_type_from_params?
!resource_type_from_params.to_s.empty?
end
def resource_type_from_params
params.dig(:data, :type)
end
def verify_resource_type!
matching_resource_type = resource_type_from_params.to_s == context.resource_type.to_s
raise InvalidTypeError, invalid_resource_type_detail if !matching_resource_type && resource_type_from_params?
end
def verify_absence_of_invalid_keys_in_attributes!
data_object = params.dig(:data)
includes_objects = params.dig(:included) || []
verify_absence_of_invalid_key_attributes_in_data_object(data_object, [:data])
verify_absence_of_invalid_key_attributes_in_objects_array(includes_objects, [:included])
end
def verify_absence_of_invalid_key_attributes_in_data_object(data_object, reference_array)
resource_type = data_object.dig(:type)
attributes = data_object.dig(:attributes) || {}
attributes.each do |attribute_key, _value|
next if ignored_foreign_keys[resource_type.to_sym].include?(attribute_key.to_sym)
new_reference_array = reference_array.dup << :attributes << attribute_key
if attribute_key.end_with?('_id')
foreign_key_present_error(new_reference_array)
elsif attribute_key == 'id'
invalid_primary_key_placement_error(new_reference_array)
end
end
relationships = data_object.dig(:relationships) || {}
verify_absence_of_invalid_key_attributes_in_relationships(relationships, reference_array)
end
def verify_absence_of_invalid_key_attributes_in_relationships(relationships, reference_array)
reference_array << :relationships
relationships.each do |reference, relationships_object|
data_object = relationships_object.dig(:data)
next unless data_object
new_reference_array = reference_array.dup << reference << :data
if data_object&.is_a? Array
verify_absence_of_invalid_key_attributes_in_objects_array(data_object, new_reference_array)
elsif data_object&.is_a? Hash
verify_absence_of_invalid_key_attributes_in_data_object(data_object, new_reference_array)
end
end
end
def verify_absence_of_invalid_key_attributes_in_objects_array(objects_array, reference_array)
objects_array.each_with_index do |object, index|
new_reference_array = reference_array.dup << index
verify_absence_of_invalid_key_attributes_in_data_object(object, new_reference_array)
end
end
def verify_type_existence!
data_object = params.dig(:data) || {}
includes_object = params.dig(:included) || []
verify_type_existence_in_data_object(data_object, [:data])
verify_type_existence_in_objects_array(includes_object, [:included])
end
def verify_type_existence_in_data_object(data_object, reference_array)
missing_resource_type_error(reference_array) unless data_object.dig(:type)
relationships = data_object.dig(:relationships) || {}
verify_type_existince_in_relationships(relationships, reference_array.dup)
end
def verify_type_existence_in_objects_array(objects_array, reference_array)
objects_array.each_with_index do |object, index|
new_reference_array = reference_array.dup << index
verify_type_existence_in_data_object(object, new_reference_array)
end
end
def verify_type_existince_in_relationships(relationships, reference_array)
reference_array << :relationships
relationships.each do |reference, relationships_object|
data_object = relationships_object.dig(:data)
next unless data_object
new_reference_array = reference_array.dup << reference << :data
if data_object&.is_a? Array
verify_type_existence_in_objects_array(data_object, new_reference_array)
elsif data_object&.is_a? Hash
verify_type_existence_in_data_object(data_object, new_reference_array)
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/address_spec.rb
|
<filename>spec/models/address_spec.rb
require 'rails_helper'
describe Address do
# Old way that DataServer used to do encoding that mangled special characters.
def old_encoding(str)
str.unpack('C*').pack('U*')
end
context 'validates updatable_only_when_source_is_mpdx' do
before { stub_smarty_streets }
include_examples 'updatable_only_when_source_is_mpdx_validation_examples',
attributes: [:street, :city, :state, :country, :postal_code,
:start_date, :end_date, :remote_id, :region, :metro_area],
factory_type: :address
end
include_examples 'after_validate_set_source_to_mpdx_examples', factory_type: :address
context '#find_master_address' do
it 'normalized an address using smarty streets' do
stub_request(:get, %r{https:\/\/api\.smartystreets\.com\/street-address})
.to_return(status: 200, body:
'[{"input_index":0,"candidate_index":0,"delivery_line_1":"12958 Fawns Dell Pl",'\
'"last_line":"Fishers IN 46038-1026","delivery_point_barcode":"460381026587",'\
'"components":{"primary_number":"12958","street_name":"<NAME>","street_suffix":"Pl",'\
'"city_name":"Fishers","state_abbreviation":"IN","zipcode":"46038","plus4_code":"1026",'\
'"delivery_point":"58","delivery_point_check_digit":"7"},'\
'"metadata":{"record_type":"S","county_fips":"18057","county_name":"Hamilton",'\
'"carrier_route":"C013","congressional_district":"05","rdi":"Residential",'\
'"elot_sequence":"0006","elot_sort":"A","latitude":39.97531,"longitude":-86.02973,"precision":"Zip9"},'\
'"analysis":{"dpv_match_code":"Y","dpv_footnotes":"AABB","dpv_cmra":"N","dpv_vacant":"N","active":"Y"}}]')
address = build(:address)
master_address = create(:master_address, street: '12958 fawns dell pl',
city: 'fishers',
state: 'in',
country: 'united states',
postal_code: '46038-1026')
# Force update of the master address
address.master_address_id = nil
address.send(:determine_master_address)
expect(address.master_address).to eq(master_address)
end
end
context '#clean_up_master_address' do
it 'cleans up the master address when destroyed if it is no longer needed by others' do
master = create(:master_address)
address1 = create(:address, master_address: master)
address2 = create(:address, master_address: master)
expect do
address1.destroy!
end.to_not change(MasterAddress, :count).from(1)
expect do
address2.destroy!
end.to change(MasterAddress, :count).from(1).to(0)
end
end
context '#destroy' do
it 'clears the primary mailing address flag when destroyed' do
address1 = create(:address, primary_mailing_address: true)
address1.destroy
expect(address1.primary_mailing_address).to be false
end
end
context '#country=' do
it 'normalizes the country when assigned' do
address = build(:address)
expect(Address).to receive(:normalize_country).with('USA').and_return('United States')
address.country = 'USA'
expect(address.country).to eq('United States')
end
end
context '#normalize_country' do
it 'normalizes country by case' do
expect(Address.normalize_country('united STATES')).to eq('United States')
end
it 'normalizes by alternate country name' do
expect(Address.normalize_country('uSa')).to eq('United States')
end
it 'returns a country not in the list as is' do
expect(Address.normalize_country('Some non-Existent country')).to eq('Some non-Existent country')
end
it 'strips white space out from input' do
expect(Address.normalize_country(' united STATES ')).to eq('United States')
end
it 'strips white space out if country not in list' do
expect(Address.normalize_country(' Not-A-Country ')).to eq('Not-A-Country')
end
it 'returns nil for nil' do
expect(Address.normalize_country(nil)).to be_nil
end
it 'returns nil for blank space' do
expect(Address.normalize_country(' ')).to be_nil
end
end
context '#merge' do
let(:a1) { create(:address, start_date: Date.new(2014, 1, 1)) }
let(:a2) { create(:address, start_date: Date.new(2014, 1, 2)) }
describe 'takes the min first start_date of the two addresses' do
it 'works with a1 winner' do
a1.merge(a2)
expect(a1.start_date).to eq(Date.new(2014, 1, 1))
end
it 'works with a2 winner' do
a2.merge(a1)
expect(a2.start_date).to eq(Date.new(2014, 1, 1))
end
end
it 'takes the non-nil start date if only one specified' do
a1.update(start_date: nil)
a1.merge(a2)
expect(a1.start_date).to eq(Date.new(2014, 1, 2))
end
it 'sets source to Siebel if remote_id specified' do
a2.remote_id = 'a'
a1.update(source: 'not-siebel')
a1.merge(a2)
expect(a1.source).to eq('Siebel')
end
it 'it has the "MPDX" source by default' do
expect(a1.source).to eq('MPDX')
end
it 'taks the non-nil source_donor_account' do
donor_account = create(:donor_account)
a2.source_donor_account = donor_account
a1.merge(a2)
expect(a1.source_donor_account).to eq(donor_account)
end
end
describe 'start_date and manual source behavior' do
it 'sets source to manual and start_date to today for a new user changed address' do
address = build(:address, user_changed: true)
address.save
expect(address.start_date).to eq(Date.today)
expect(address.source).to eq(Address::MANUAL_SOURCE)
end
it 'does not update start_date for a user changed when only address meta data is updated' do
da = create(:donor_account)
start = Date.new(2014, 1, 15)
a = Address.create(start_date: start, source: 'import', source_donor_account: da)
a.update(seasonal: true, primary_mailing_address: true, remote_id: '5', master_address_id: 2,
location: 'Other', user_changed: true)
expect(a.start_date).to eq(start)
expect(a.source).to eq('import')
expect(a.source_donor_account).to eq(da)
end
it 'updates to today for a user changed address when place attributes change' do
da = create(:donor_account)
[:street, :city, :state, :postal_code, :country].each do |field|
a = Address.create(start_date: Date.new(2014, 1, 15), source: 'import', source_donor_account: da)
a.update!(field => 'not-nil', user_changed: true)
expect(a.start_date).to eq(Date.today)
expect(a.source).to eq(Address::MANUAL_SOURCE)
expect(a.source_donor_account).to be_nil
end
end
it 'does not update start date or source for non-user changed address when place attributes change' do
start = Date.new(2014, 1, 15)
[:street, :city, :state, :postal_code, :country].each do |field|
a = Address.create(source: 'import', start_date: start)
a.update(field => 'a')
expect(a.start_date).to eq(start)
expect(a.source).to eq('import')
end
end
it 'does not update start date and source for changes affecting only whitespace or nil to blank' do
start = Date.new(2014, 1, 15)
[:street, :city, :state, :postal_code, :country].each do |field|
# rubocop:disable DuplicatedKey
{ nil => '', ' a ' => 'a', ' ' => nil, nil => ' ', 'b' => ' b ' }.each do |from_val, to_val|
a = Address.create(source: 'import', start_date: start, field => from_val)
a.update(field => to_val, user_changed: true)
expect(a.start_date).to eq(start)
expect(a.source).to eq('import')
end
end
end
end
context '#csv_street' do
it 'normalizes newlines and strips whitespace' do
address = build(:address, street: "123 Somewhere\r\n#1\n")
expect(address.csv_street).to eq("123 Somewhere\n#1")
end
it 'gives nil for nil' do
expect(build(:address, street: nil).csv_street).to be_nil
end
end
context '#csv_country' do
let(:address) { create(:address, country: 'Test Country') }
it 'returns blank when the passed in country equals the address country' do
expect(address.csv_country('Test Country')).to eq('')
end
it 'returns the country when none is passed in' do
expect(address.csv_country('')).to eq(address.country)
end
end
context '#equal_to?' do
let(:master_address_id_1) { SecureRandom.uuid }
let(:master_address_id_2) { SecureRandom.uuid }
it 'matches addresses that share a master_address_id' do
a1 = build(:address, street: '1 Rd', master_address_id: master_address_id_1)
a2 = build(:address, street: '1 Road', master_address_id: master_address_id_1)
expect(a1).to be_equal_to a2
end
it 'matches addresses that match on address attributes' do
a1 = build(:address, master_address_id: master_address_id_1, street: '1 way',
city: 'Some Where', state: 'MA', country: 'USA',
postal_code: '02472')
a2 = build(:address, master_address_id: master_address_id_2, street: '1 Way',
city: 'somewhere', state: 'ma', country: 'united states',
postal_code: '02472-3061')
expect(a1).to be_equal_to a2
end
it 'matches if one country is blank and other fields match' do
a1 = build(:address, master_address_id: master_address_id_1, street: '1 way',
city: 'Somewhere ', state: 'MA ', country: '',
postal_code: '02 472')
a2 = build(:address, master_address_id: master_address_id_2, street: '1 Way',
city: 'somewhere', state: 'ma', country: 'Canada',
postal_code: '02472-3061')
expect(a1).to be_equal_to a2
end
it 'does not match if address fields differ' do
a1 = build(:address, master_address_id: master_address_id_1, street: '2 way',
city: 'Nowhere', state: 'IL', country: 'USA',
postal_code: '60201')
a2 = build(:address, master_address_id: master_address_id_2, street: '1 Way',
city: 'somewhere', state: 'ma', country: 'Canada',
postal_code: '02472-3061')
expect(a1).to_not be_equal_to a2
end
it 'matches addresses that differ by old data server encoding' do
street = '16C Boulevard de la Liberté'
city = 'Cité'
state = 'état'
country = 'Rhône-Alpes'
postal_code = '35220'
a1 = build(:address, master_address_id: master_address_id_1, street: street,
city: city, state: state, country: country,
postal_code: postal_code)
a2 = build(:address, master_address_id: master_address_id_2, street: old_encoding(street),
city: old_encoding(city), state: old_encoding(state),
country: old_encoding(country),
postal_code: old_encoding(postal_code))
expect(a1).to be_equal_to a2
end
end
context '#fix_encoding_if_equal' do
it 'leaves a correctly encoding address alone' do
a1 = build(:address, street: '1 Liberté')
a2 = build(:address, street: old_encoding('1 Liberté'))
a1.fix_encoding_if_equal(a2)
expect(a1.street).to eq '1 Liberté'
end
it 'updates fields to match correctly encoded address if equal' do
a1 = create(:address, street: old_encoding('1 Liberté'))
a2 = create(:address, street: '1 Liberté')
a1.fix_encoding_if_equal(a2)
expect(a1.street).to eq '1 Liberté'
end
it 'leaves address alone if other is not equal' do
a1 = build(:address, street: '1 Way')
a2 = build(:address, street: '2 Way')
a1.fix_encoding_if_equal(a2)
expect(a1.street).to eq '1 Way'
end
end
describe 'permitted attributes' do
it 'defines permitted attributes' do
expect(Address::PERMITTED_ATTRIBUTES).to be_present
end
end
it 'should allow editing location if source is not mpdx' do
address = create(:address, location: 'Home', source: Address::MANUAL_SOURCE)
expect do
expect { address.update!(location: 'Business') }.to_not raise_error
end.to change { address.reload.location }.from('Home').to('Business')
end
describe '#location' do
it 'should allow a valid location to be set' do
expect { create(:address, location: 'Rep Address') }.to_not raise_error
end
it 'should not allow an invalid location to be set' do
expect { create(:address, location: 'Invalid Location') }.to raise_error
end
end
describe '#set_valid_values' do
it "sets valid_values to true if this is the person's only address, or the source is manual" do
address_one = create(:address, source: 'not mpdx')
expect(address_one.valid_values).to eq(true)
expect(address_one.source).to_not eq(Address::MANUAL_SOURCE)
address_two = create(:address, source: 'not mpdx', addressable: address_one.addressable)
expect(address_two.valid_values).to eq(false)
expect(address_two.source).to_not eq(Address::MANUAL_SOURCE)
address_three = create(:address, source: Address::MANUAL_SOURCE, addressable: address_one.addressable)
expect(address_three.valid_values).to eq(true)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/mail_chimp/webhook/appeal_list_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe MailChimp::Webhook::AppealList do
let(:account_list) { create(:account_list) }
let(:mail_chimp_account) { create(:mail_chimp_account, account_list: account_list) }
let(:subject) { described_class.new(mail_chimp_account) }
context '#email_cleaned_hook' do
let(:bounce_handler) { double(handle_bounce: nil) }
let(:email_bouncer_class) { MailChimp::Webhook::Base::EmailBounceHandler }
it 'ignores it if the reason is abuse (user marking email as spam)' do
expect(email_bouncer_class).to_not receive(:new)
subject.email_cleaned_hook('<EMAIL>', 'abuse')
end
it 'passes along to email bounce handler if not abuse' do
allow(email_bouncer_class).to receive(:new).and_return(bounce_handler)
subject.email_cleaned_hook('<EMAIL>', 'hard')
expect(bounce_handler).to have_received(:handle_bounce)
end
end
context '#campaign_status_hook' do
it 'ignores it if the status is not sent' do
expect(MailChimp::CampaignLoggerWorker).to_not receive(:perform_async)
subject.campaign_status_hook('1', 'not_sent', 'subject')
end
it 'queues it if the status is sent' do
expect(MailChimp::CampaignLoggerWorker).to receive(:perform_async).with(mail_chimp_account.id, '1', 'subject')
subject.campaign_status_hook('1', 'sent', 'subject')
end
end
end
|
chuckmersereau/api_practice
|
app/services/account_list/duplicates_finder.rb
|
class AccountList::DuplicatesFinder
def initialize(account_list)
@account_list = account_list
end
protected
def exec_query(sql)
# Scope to the account list
sql = sql.gsub(':account_list_id', @account_list.id.to_s)
AccountList.connection.exec_query(sql)
end
def create_temp_tables
drop_temp_tables
CREATE_TEMP_TABLES_SQL_QUERIES.each(&method(:exec_query))
end
def drop_temp_tables
[
'DROP TABLE IF EXISTS tmp_account_ppl',
'DROP TABLE IF EXISTS tmp_unsplit_names',
'DROP TABLE IF EXISTS tmp_names',
'DROP TABLE IF EXISTS tmp_dups_by_name',
'DROP TABLE IF EXISTS tmp_dups_by_contact_info',
'DROP TABLE IF EXISTS tmp_name_male_ratios',
'DROP TABLE IF EXISTS tmp_dups'
].each(&method(:exec_query))
end
# To help prevent merging a male person with a female person (and because the
# gender field can be unreliable), we use the name_male_ratios table which has
# data on male ratios of people. To avoid false positives with duplicate
# matching, require a certain threshold of the name ratio to confidently
# assume the person is male/female for the sake of suggesting duplicates.
# Assume male if more than this ratio with name are male
MALE_NAME_CONFIDENCE_LVL = 0.9
# Assume female if fewer than this ratio with name are male
FEMALE_NAME_CONFIDENCE_LVL = 0.1
# The reason these are large queries with temp tables and not Ruby code with
# loops is that as I introduced more duplicate search options, that code got
# painfully slow and so I re-wrote the logic as self-join queries for
# performance. # Temporary tables are unique per database connection and the
# Rails connection pool gives each thread a unique connection, so it's OK for
# this model to create temporary tables even if another instance somewhere
# else is doing the same action and creating its own temp tables with the same
# names. See:
# http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html
# http://www.postgresql.org/docs/9.4/static/sql-createtable.html under
# "Compatibility", "Temporary Tables"
CREATE_TEMP_TABLES_SQL_QUERIES = [
# First just scope people to the account list and filter out anonymous
# contacts or people with name "Unknown".
<<~SQL,
SELECT people.id, first_name, legal_first_name, middle_name, last_name
INTO TEMP tmp_account_ppl
FROM people
INNER JOIN contact_people ON people.id = contact_people.person_id
INNER JOIN contacts ON contacts.id = contact_people.contact_id
WHERE contacts.account_list_id = :account_list_id
AND contacts.name NOT ilike '%nonymous%'
AND first_name NOT ilike '%nknow%'
SQL
'CREATE INDEX ON tmp_account_ppl (id)',
# Next combine in the three name fields: first_name, legal_first_name,
# middle_name and track first/middle distinction.
<<~SQL,
SELECT *
INTO TEMP tmp_unsplit_names
FROM (
SELECT first_name AS name, 'first' AS name_field, id, first_name,
last_name
FROM tmp_account_ppl
UNION
SELECT legal_first_name, 'legal_first' AS name_field, id, first_name,
last_name
FROM tmp_account_ppl
WHERE legal_first_name IS NOT NULL AND legal_first_name <> ''
UNION
SELECT middle_name, 'middle' AS name_field, id, first_name, last_name
FROM tmp_account_ppl
WHERE middle_name IS NOT NULL AND middle_name <> ''
) AS people_unsplit_names_query
SQL
# Break apart various parts of names (initials, capitals, spaces, etc.) into
# a single table, and make names lowercase. Also filter out people with
# names like "Friend of the ministry"
<<~SQL,
SELECT lower(name) AS name, name_field, id, first_name,
lower(last_name) AS last_name
INTO TEMP tmp_names
FROM (
/* Try replacing the space to match e.g. 'Marybeth' and '<NAME>'.
* This also brings in all names that don't match patterns below. */
SELECT replace(name, ' ', '') AS name, name_field, id, first_name,
last_name
FROM tmp_unsplit_names
UNION
/* Split the name by '-', ' ', and '.' to capture initials and multiple
* names like 'J.W.' or '<NAME>' * The regexp_replace is to get rid
* of any separator characters at the end to reduce blank rows. */
SELECT regexp_split_to_table(
regexp_replace(name, '[\\.-]+$', ''),
'([\\. -]+|$)+'
), name_field, id, first_name, last_name
FROM tmp_unsplit_names WHERE name ~ '[\\. -]'
UNION
/* Split the name by two capitals in a row like 'JW' or a capital
* within a name like 'MaryBeth', but don't split * three letter
* capitals which are common in organization acrynomys like 'CCC NEHQ'
* or 'City UMC' */
SELECT regexp_split_to_table(
regexp_replace(name, '(^[A-Z]|[a-z])([A-Z])', '\\1 \\2'),
' '
), name_field, id, first_name, last_name
FROM tmp_unsplit_names
WHERE name ~ '(^[A-Z]|[a-z])([A-Z])' AND name !~ '[A-Z]{3}'
) AS people_names_query
WHERE first_name || last_name NOT ilike 'friend%of%the%ministry'
SQL
'CREATE INDEX ON tmp_names (id)',
'CREATE INDEX ON tmp_names (name)',
'CREATE INDEX ON tmp_names (last_name)',
# Join the names table to itself to find duplicate names. Require a match on
# last name, and then a match either by matching name, a (name, nickname)
# pair or a matching initial. Don't allow matches just by middle names.
# Order the person_id, dup_person_id so that the person_id (the default
# winner in the merge) will have reasonable defaults for which of the two
# names is picked. Those defaults are reflected in the priority field.
<<~SQL,
SELECT ppl.id AS person_id, dups.id AS dup_person_id,
nicknames.id AS nickname_id,
CASE
/* Nickname over the long name (Dave over David) */
WHEN ppl.name = nicknames.nickname THEN 800
/* Prefer first name over middle when first name is well-formed
(David over <NAME>) */
WHEN dups.name_field = 'middle' AND
ppl.first_name ~ '^[A-Z].*[a-z]' THEN 700
/* Prefer names with inside capitals (MaryBeth over Marybeth) */
WHEN ppl.first_name ~ '^[A-Z][a-z]+[A-Z][a-z]' THEN 600
/* Prefer two letter initials (CS over Clive Staples) */
WHEN ppl.first_name ~ '^[A-Z][A-Z]$|^[A-Z]\\.\s?[A-Z]\\.$' THEN 500
/* Prefer multi-word names (<NAME> over Mary) */
WHEN ppl.first_name ~ '^[A-Z][A-Za-z]+ [A-Z][a-z]' THEN 400
/* Prefer names that start with upper case, end with a lower case,
and don't start with an initial. (John over D John, john, J. or J) */
WHEN ppl.first_name ~ '^[A-Z]([^\s\\.].*)?[a-z]$' THEN 300
/* More arbitrary preference by id. */
WHEN dups.id > ppl.id THEN 100 ELSE 50
END AS priority,
/* Verify genders if the match used a middle (or legal first) name/initial
as those are more often wrong in the data. */
(
char_length(ppl.name) = 1 OR char_length(dups.name) = 1
OR dups.name_field <> 'first' OR ppl.name_field <> 'first'
) AS check_genders,
ppl.name_field, dups.name_field AS dup_name_field
INTO TEMP tmp_dups_by_name
FROM tmp_names AS ppl
INNER JOIN tmp_names AS dups ON ppl.id <> dups.id
LEFT JOIN nicknames ON nicknames.suggest_duplicates = 't'
AND ((ppl.name = nicknames.nickname AND dups.name = nicknames.name)
OR (ppl.name = nicknames.name AND dups.name = nicknames.nickname))
WHERE ppl.last_name = dups.last_name
AND (ppl.name_field = 'first' OR dups.name_field = 'first')
AND (
nicknames.id IS NOT NULL
OR (dups.name = ppl.name AND char_length(ppl.name) > 1)
OR ((char_length(dups.name) = 1 OR char_length(ppl.name) = 1)
AND (
dups.name = substring(ppl.name from 1 for 1)
OR ppl.name = substring(dups.name from 1 for 1)
)
)
)
SQL
'CREATE INDEX ON tmp_dups_by_name (person_id)',
'CREATE INDEX ON tmp_dups_by_name (dup_person_id)',
# Join the emails and phone number tables together to find duplicate people
# by contact info. Always check gender for these matches as husband and wife
# often have common contact info. Strip out non-numeric characters from the
# phone numbers as we match them
<<~SQL,
SELECT *, true AS check_genders
INTO TEMP tmp_dups_by_contact_info
FROM (
SELECT ppl.id AS person_id, dups.id AS dup_person_id
FROM tmp_account_ppl AS ppl
INNER JOIN tmp_account_ppl AS dups ON ppl.id <> dups.id
INNER JOIN email_addresses ON email_addresses.person_id = ppl.id
INNER JOIN email_addresses AS dup_email_addresses ON
dup_email_addresses.person_id = dups.id
WHERE lower(email_addresses.email) = lower(dup_email_addresses.email)
UNION
SELECT ppl.id AS person_id, dups.id AS dup_person_id
FROM tmp_account_ppl AS ppl
INNER JOIN tmp_account_ppl AS dups ON ppl.id <> dups.id
INNER JOIN phone_numbers ON phone_numbers.person_id = ppl.id
INNER JOIN phone_numbers AS dup_phone_numbers ON
dup_phone_numbers.person_id = dups.id
WHERE regexp_replace(phone_numbers.number, \ '[^0-9]\', \ '\', \ 'g\') =
regexp_replace(dup_phone_numbers.number, \ '[^0-9]\', \ '\', \ 'g\')
) tmp_dups_by_contact_info_query
SQL
'CREATE INDEX ON tmp_dups_by_contact_info (person_id)',
'CREATE INDEX ON tmp_dups_by_contact_info (dup_person_id)',
# Join to the name_male_ratios table and get an average name male ratio for
# the various name parts of a person.
<<~SQL,
SELECT tmp_names.id, AVG(name_male_ratios.male_ratio) AS male_ratio
INTO TEMP tmp_name_male_ratios
FROM tmp_names
LEFT JOIN name_male_ratios ON tmp_names.name = name_male_ratios.name
GROUP BY tmp_names.id
SQL
'CREATE INDEX ON tmp_name_male_ratios (id)',
# Combine the duplicate people by name and contact info and join it to the
# name male ratios table. Only select as duplicates pairs whose name male
# ratios strongly agree, or pairs without that info and which match on the
# gender field (or don't have gender info). The gender field by itself isn't
# a strong enough indicator because it can often be wrong. (E.g. if in Tnt
# someone puts the husband and wife in opposite fields then imports.)
<<~SQL,
SELECT dups.*
INTO TEMP tmp_dups
FROM (
SELECT person_id, dup_person_id, nickname_id, priority, check_genders,
name_field,dup_name_field
FROM tmp_dups_by_name
UNION
SELECT person_id, dup_person_id, NULL, NULL, check_genders, NULL, NULL
FROM tmp_dups_by_contact_info
) dups
INNER JOIN people ON dups.person_id = people.id
INNER JOIN people AS dup_people ON dups.dup_person_id = dup_people.id
LEFT JOIN tmp_name_male_ratios name_male_ratios ON
name_male_ratios.id = people.id
LEFT JOIN tmp_name_male_ratios dup_name_male_ratios ON
dup_name_male_ratios.id = dup_people.id
WHERE check_genders = 'f'
OR (
(
name_male_ratios.male_ratio IS NULL
OR dup_name_male_ratios.male_ratio IS NULL
)
AND (
people.gender = dup_people.gender
OR people.gender IS NULL
OR dup_people.gender IS NULL
)
OR (
name_male_ratios.male_ratio < #{FEMALE_NAME_CONFIDENCE_LVL}
AND dup_name_male_ratios.male_ratio < #{FEMALE_NAME_CONFIDENCE_LVL}
)
OR (
name_male_ratios.male_ratio > #{MALE_NAME_CONFIDENCE_LVL}
AND dup_name_male_ratios.male_ratio > #{MALE_NAME_CONFIDENCE_LVL}
)
)
SQL
'CREATE INDEX ON tmp_dups (person_id)',
'CREATE INDEX ON tmp_dups (dup_person_id)'
].freeze
end
|
chuckmersereau/api_practice
|
db/migrate/20180202024131_re_add_indexes.rb
|
<filename>db/migrate/20180202024131_re_add_indexes.rb
class ReAddIndexes < ActiveRecord::Migration
disable_ddl_transaction!
def up
# we don't want running this to prevent production from starting
return if Rails.env.production? || Rails.env.staging?
path = Rails.root.join('db','dropped_indexes.csv')
CSV.read(path, headers: true).each do |index_row|
execute index_row['indexdef'].sub('INDEX', 'INDEX CONCURRENTLY IF NOT EXISTS')
end
end
end
|
chuckmersereau/api_practice
|
app/services/reports/appointment_results_period.rb
|
<gh_stars>0
class Reports::AppointmentResultsPeriod < ActiveModelSerializers::Model
attr_accessor :account_list, :start_date, :end_date
def individual_appointments
appointments_during_dates.count
end
# default that Jimmy wants used for now
def weekly_individual_appointment_goal
10
end
def group_appointments
0
end
def new_monthly_partners
@new_monthly_partners ||= cached_changed_contacts_with_pledges.count do |monthly_increase|
monthly_increase.beginning_monthly.zero? && monthly_increase.end_monthly.positive?
end
end
def new_special_pledges
return 0 unless account_list.primary_appeal_id.present?
account_list.contacts
.joins(:pledges)
.where(pledges: { appeal: account_list.primary_appeal, created_at: start_date..end_date })
.count
end
def monthly_increase
pledge_increase_contacts.sum(&:increase_amount)
end
def pledge_increase
new_pledges.sum(:amount)
end
def new_pledges
Pledge.where(appeal: account_list.primary_appeal, created_at: start_date..end_date)
end
def pledge_increase_contacts
@pledge_increase_contacts ||= cached_changed_contacts_with_pledges.select do |monthly_increase|
monthly_increase.increase_amount.positive?
end
end
private
def cached_changed_contacts_with_pledges
@changed_contacts_with_pledges ||= changed_contacts_with_pledges
end
def changed_contacts_with_pledges
ids = (changed_contacts + new_financial_partners.pluck(:id)).uniq
contacts_with_changes = account_list.contacts.where(id: ids).to_a
# it might be just as fast to load all of the logs at once
logs = PartnerStatusLog.where(contact_id: ids).where('recorded_on >= ?', start_date).order(recorded_on: :asc)
contacts_with_changes.map do |contact|
old_status = logs.find { |log| log.contact_id == contact.id }
end_status = logs.find { |log| log.contact_id == contact.id && log.recorded_on > end_date.to_date }
::Reports::PledgeIncreaseContact.new(contact: contact, beginning: old_status, end_status: end_status)
end
end
def changed_contacts
# we want to know which people ever changed during the period
PartnerStatusLog.joins(:contact)
.where(contacts: { account_list_id: account_list.id }, recorded_on: start_date..end_date)
.pluck(:contact_id)
end
def new_financial_partners
account_list.contacts.where(created_at: start_date..end_date, status: 'Partner - Financial')
end
def appointments_during_dates(type = 'Appointment')
account_list.tasks.completed.where(activity_type: type, start_at: start_date..end_date, result: %w(Completed Done))
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130708194848_add_uncompleted_tasks_count_to_contact.rb
|
<reponame>chuckmersereau/api_practice
class AddUncompletedTasksCountToContact < ActiveRecord::Migration
def change
add_column :contacts, :uncompleted_tasks_count, :integer, default: 0, null: false
#Contact.find_each do |c|
#c.update_column(:uncompleted_tasks_count, c.tasks.uncompleted.count)
#end
end
end
|
chuckmersereau/api_practice
|
spec/concerns/has_primary_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe HasPrimary do
context '#ensure_only_one_primary? for person and email addresses (responds to :historic)' do
let(:person) { create(:person) }
let(:email1) { create(:email_address, email: '<EMAIL>', person: person, primary: true) }
let(:email2) { create(:email_address, email: '<EMAIL>', person: person, primary: false) }
it 'leaves the existing primary one if one is specified' do
email1.send(:ensure_only_one_primary)
expect(email1.reload.primary).to be true
expect(email2.reload.primary).to be false
end
it 'updates one of the items to become primary if none are' do
email1.update_column(:primary, false)
email1.send(:ensure_only_one_primary)
email1.reload
email2.reload
expect(email1.primary || email2.primary).to be true
expect(email1.primary && email2.primary).to be false
end
it 'makes it so that only one of the items can be primary' do
email2.update_column(:primary, true)
email2.send(:ensure_only_one_primary)
email1.reload
email2.reload
expect(email1.primary || email2.primary).to be true
expect(email1.primary && email2.primary).to be false
end
it 'sets historic items to not primary' do
email1.update_column(:historic, true)
email1.send(:ensure_only_one_primary)
expect(email1.reload.primary).to be false
expect(email2.reload.primary).to be true
email2.update_column(:historic, true)
email2.send(:ensure_only_one_primary)
expect(email1.reload.primary).to be false
expect(email2.reload.primary).to be false
end
end
context '#ensure_only_one_primary? case for person and email addresses (does not respond to :historic)' do
let!(:contact) { create(:contact) }
let!(:person1) { create(:person) }
let!(:person2) { create(:person) }
let!(:contact_person1) { create(:contact_person, contact: contact, person: person1, primary: true) }
let!(:contact_person2) do
create(:contact_person, contact: contact.reload, person: person2.reload, primary: false)
end
it 'leaves the existing primary one if one is specified' do
expect(contact_person1.reload.primary).to be true
contact_person1.send(:ensure_only_one_primary)
expect(contact_person1.reload.primary).to be true
expect(contact_person2.reload.primary).to be false
end
it 'updates one of the items to become primary if none are' do
contact_person1.update_column(:primary, false)
contact_person1.send(:ensure_only_one_primary)
contact_person1.reload
contact_person2.reload
expect(contact_person1.primary || contact_person2.primary).to be true
expect(contact_person1.primary && contact_person2.primary).to be false
end
it 'makes it so that only one of the items can be primary' do
contact_person2.update_column(:primary, true)
contact_person2.send(:ensure_only_one_primary)
contact_person1.reload
contact_person2.reload
expect(contact_person1.primary || contact_person2.primary).to be true
expect(contact_person1.primary && contact_person2.primary).to be false
end
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_church_spec.rb
|
require 'rails_helper'
RSpec.describe Task::Filter::ContactChurch 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, church_name: 'My Church') }
let!(:contact_two) { create(:contact, account_list_id: account_list.id, church_name: 'First Pedestrian Church') }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, church_name: nil) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id, church_name: nil) }
let!(:task_one) { create(:task, account_list: account_list, contacts: [contact_one]) }
let!(:task_two) { create(:task, account_list: account_list, contacts: [contact_two]) }
let!(:task_three) { create(:task, account_list: account_list, contacts: [contact_three]) }
let!(:task_four) { create(:task, account_list: account_list, contacts: [contact_four]) }
describe '#query' do
let(:tasks) { account_list.tasks }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, account_list)).to eq(nil)
expect(described_class.query(tasks, { church: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { church: [] }, account_list)).to eq(nil)
end
end
context 'filter by no church' do
it 'returns only tasks with contacts that have no church' do
result = described_class.query(tasks, { contact_church: 'none' }, account_list).to_a
expect(result).to match_array [task_three, task_four]
end
end
context 'filter by church' do
it 'filters multiple churches' do
result = described_class.query(tasks, { contact_church: 'My Church, First Pedestrian Church' }, account_list).to_a
expect(result).to match_array [task_one, task_two]
end
it 'filters a single church' do
expect(described_class.query(tasks, { contact_church: 'My Church' }, account_list).to_a).to eq [task_one]
end
end
context 'multiple filters' do
it 'returns tasks with contacts matching multiple filters' do
result = described_class.query(tasks, { contact_church: 'My Church, none' }, account_list).to_a
expect(result).to match_array [task_one, task_three, task_four]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/account_list_spec.rb
|
require 'rails_helper'
require 'csv'
describe AccountList do
before do
NotificationTypesSeeder.new.seed # Specs depend on NotificationType records.
end
subject { described_class.new }
it { is_expected.to have_many(:account_list_coaches).dependent(:destroy) }
it { is_expected.to have_many(:coaches).through(:account_list_coaches) }
it { is_expected.to belong_to(:primary_appeal) }
describe '.with_linked_org_accounts scope' do
let!(:org_account) { create(:organization_account) }
it 'returns non-locked account lists with organization accounts' do
expect(AccountList.with_linked_org_accounts).to include org_account.account_list
end
it 'does not return locked accounts' do
org_account.update_column(:locked_at, 1.minute.ago)
expect(AccountList.with_linked_org_accounts).to_not include org_account.account_list
end
end
describe '.has_users scope' do
let!(:user_one) { create(:user_with_account) }
let!(:user_two) { create(:user_with_account) }
let!(:user_three) { create(:user_with_account) }
let!(:account_without_user) { create(:account_list) }
it 'scopes account_lists when receiving a User relation' do
expect(AccountList.has_users(User.where(id: [user_one.id, user_two.id])).to_a).to(
contain_exactly(
user_one.account_lists.order(:created_at).first,
user_two.account_lists.order(:created_at).first
)
)
end
it 'scopes account_lists when receiving a User instance' do
expect(AccountList.has_users(user_one).to_a).to eq([user_one.account_lists.order(:created_at).first])
end
end
describe '#salary_organization=()' do
let(:organization) { create(:organization, default_currency_code: 'GBP') }
it 'finds the id when given a id' do
subject.salary_organization = organization.id
expect(subject.salary_organization_id).to eq(organization.id)
end
it 'updates salary_currency' do
subject.name = 'test account list'
expect do
subject.update!(salary_organization: organization.id)
end.to change { subject.salary_currency }.to('GBP')
end
end
describe '#valid_mail_chimp_account' do
let(:account_list) { create(:account_list) }
let!(:mail_chimp_account) { create(:mail_chimp_account, account_list: account_list, active: true) }
let(:mock_list) { double(:mock_list) }
it 'returns true when the mail_chimp_account is valid' do
expect_any_instance_of(MailChimp::GibbonWrapper).to receive(:primary_list).and_return(mock_list)
expect(account_list.valid_mail_chimp_account).to be_truthy
end
it 'returns false when the mail_chimp_account is invalid' do
mail_chimp_account.active = false
expect(account_list.valid_mail_chimp_account).to be_falsey
end
end
describe '#destroy' do
it 'raises an error' do
expect { AccountList.new.destroy }.to raise_error RuntimeError
end
end
describe '#destroy!' do
it 'raises an error' do
expect { AccountList.new.destroy! }.to raise_error RuntimeError
end
end
describe '#unsafe_destroy' do
it 'destroys the account list' do
account_list = create(:account_list)
expect { account_list.unsafe_destroy }.to change { AccountList.count }.by(-1)
end
end
context '#send_account_notifications' do
it 'checks all notification types' do
expect(NotificationType).to receive(:check_all).and_return({})
AccountList.new.send(:send_account_notifications)
end
end
context '#valid_mail_chimp_account' do
let(:account_list) { build(:account_list) }
it 'returns true if there is a mailchimp associated with this account list that has a valid primary list' do
mail_chimp_account = double(active?: true, primary_list: { id: 'foo', name: 'bar' })
expect(account_list).to receive(:mail_chimp_account).twice.and_return(mail_chimp_account)
expect(account_list.valid_mail_chimp_account).to eq(true)
end
it 'returns a non-true value when primary list is not present' do
mail_chimp_account = double(active?: true, primary_list: nil)
expect(account_list).to receive(:mail_chimp_account).twice.and_return(mail_chimp_account)
expect(account_list.valid_mail_chimp_account).not_to eq(true)
end
it 'returns a non-true value when mail_chimp_account is not active' do
mail_chimp_account = double(active?: false, primary_list: nil)
expect(account_list).to receive(:mail_chimp_account).once.and_return(mail_chimp_account)
expect(account_list.valid_mail_chimp_account).not_to eq(true)
end
it 'returns a non-true value when there is no mail_chimp_account' do
expect(account_list).to receive(:mail_chimp_account).once.and_return(nil)
expect(account_list.valid_mail_chimp_account).not_to eq(true)
end
end
context '#top_partners' do
let(:account_list) { create(:account_list) }
it 'returns the top 10 donors on your list' do
11.times do |i|
account_list.contacts << create(:contact, total_donations: i)
end
expect(account_list.top_partners).to eq(account_list.contacts.order(:created_at)[1..-1].reverse)
end
end
context '#people_with_birthdays' do
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact) }
let(:person) { create(:person, birthday_month: 8, birthday_day: 30) }
before do
contact.people << person
account_list.contacts << contact
end
it 'handles a date range where the start and end day are in the same month' do
expect(account_list.people_with_birthdays(Date.new(2012, 8, 29), Date.new(2012, 8, 31))).to eq([person])
end
it 'handles a date range where the start and end day are in different months' do
expect(account_list.people_with_birthdays(Date.new(2012, 8, 29), Date.new(2012, 9, 1))).to eq([person])
end
it 'excludes deceased people' do
person.update(deceased: true)
expect(account_list.people_with_birthdays(Date.new(2012, 8, 29), Date.new(2012, 8, 31))).to be_empty
end
end
context '#contacts_with_anniversaries' do
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact) }
let(:person) { create(:person, anniversary_month: 8, anniversary_day: 30) }
before do
contact.people << person
account_list.contacts << contact
end
it 'handles a date range where the start and end day are in the same month' do
expect(account_list.contacts_with_anniversaries(Date.new(2012, 8, 29), Date.new(2012, 8, 31)))
.to eq([contact])
end
it 'handles a date range where the start and end day are in different months' do
expect(account_list.contacts_with_anniversaries(Date.new(2012, 8, 29), Date.new(2012, 9, 1)))
.to eq([contact])
end
it 'excludes contacts who have any deceased people in them' do
contact.people << create(:person, deceased: true)
expect(account_list.contacts_with_anniversaries(Date.new(2012, 8, 29), Date.new(2012, 9, 1)))
.to be_empty
end
it 'only includes people with anniversaries in the loaded people association' do
person_without_anniversary = create(:person)
contact.people << person_without_anniversary
contact_with_anniversary = account_list
.contacts_with_anniversaries(Date.new(2012, 8, 29), Date.new(2012, 9, 1))
.first
expect(contact_with_anniversary.people.size).to eq 1
expect(contact_with_anniversary.people).to include(person)
end
end
context '#users_combined_name' do
let(:account_list) { create(:account_list, name: 'account list') }
it 'combines first and second user names and gives account list name if no uers' do
{
[] => 'account list',
[{ first_name: 'John' }] => 'John',
[{ first_name: 'John', last_name: 'Doe' }] => '<NAME>',
[{ first_name: 'John', last_name: 'Doe' }, { first_name: 'Jane', last_name: 'Doe' }] => 'John and <NAME>',
[{ first_name: 'John', last_name: 'A' }, { first_name: 'Jane', last_name: 'B' }] => '<NAME> and <NAME>',
[{ first_name: 'John' }, { first_name: 'Jane' }, { first_name: 'Paul' }] => 'John and Jane'
}.each do |people_attrs, name|
Person.destroy_all
people_attrs.each do |person_attrs|
account_list.users << create(:user, person_attrs)
end
expect(account_list.users_combined_name).to eq(name)
end
end
end
context '#user_emails_with_names' do
let(:account_list) { create(:account_list) }
it 'handles the no users case and no email fine' do
expect(account_list.user_emails_with_names).to be_empty
account_list.users << create(:user)
expect(account_list.user_emails_with_names).to be_empty
end
it 'gives the names of the users with the email addresses' do
user1 = create(:user, first_name: 'John')
user1.email = '<EMAIL>'
user1.save
user2 = create(:user, first_name: 'Jane', last_name: 'Doe')
user2.email = '<EMAIL>'
user2.save
user3 = create(:user)
account_list.users << user1
expect(account_list.user_emails_with_names.first).to eq('John <<EMAIL>>')
account_list.users << user2
account_list.users << user3
expect(account_list.user_emails_with_names.size).to eq(2)
expect(account_list.user_emails_with_names).to include('John <<EMAIL>>')
expect(account_list.user_emails_with_names).to include('<NAME> <<EMAIL>>')
end
end
context '#no_activity_since' do
let(:account_list) { create(:account_list) }
it 'filters contacts' do
contact1 = create(:contact, account_list: account_list)
contact1.tasks << create(:task, completed: true, completed_at: 1.day.ago)
contact2 = create(:contact, account_list: account_list)
no_act_list = account_list.no_activity_since(6.months.ago)
expect(no_act_list).to_not include contact1
expect(no_act_list).to include contact2
end
end
context '#churches' do
let(:account_list) { create(:account_list) }
it 'returns all churches' do
create(:contact, account_list: account_list, church_name: 'church2')
create(:contact, account_list: account_list, church_name: 'church1')
create(:contact, account_list: account_list, church_name: 'church1')
expect(account_list.churches).to eq %w(church1 church2)
end
end
context '#contact_tags' do
let(:account_list) { create(:account_list) }
it 'returns all tags for contacts' do
create(:contact, account_list: account_list, tag_list: ['c_tag2'])
create(:contact, account_list: account_list, tag_list: ['c_tag1'])
create(:contact, tag_list: ['other tag'])
expect(account_list.contact_tags.map(&:name)).to include('c_tag1', 'c_tag2')
end
end
context '#activity_tags' do
let(:account_list) { create(:account_list) }
it 'returns all tags for activities' do
create(:activity, account_list: account_list, tag_list: ['t_tag2'])
create(:activity, account_list: account_list, tag_list: ['t_tag1'])
create(:activity, tag_list: ['other tag'])
expect(account_list.activity_tags.map(&:name)).to include('t_tag1', 't_tag2')
end
end
context '#cities' do
let(:account_list) { create(:account_list) }
it 'returns all cities' do
contact = create(:contact, account_list: account_list)
contact.addresses << create(:address, city: 'City1')
contact.addresses << create(:address, city: 'City2')
expect(account_list.cities).to eq %w(City1 City2)
end
end
context '#states' do
let(:account_list) { create(:account_list) }
it 'returns all states' do
contact = create(:contact, account_list: account_list)
contact.addresses << create(:address, state: 'WI')
contact.addresses << create(:address, state: 'FL')
expect(account_list.states).to eq %w(FL WI)
end
end
context '#all_contacts' do
let(:account_list) { create(:account_list) }
it 'returns all contacts' do
c1 = create(:contact, account_list: account_list)
c2 = create(:contact, account_list: account_list, status: 'Unresponsive')
expect(account_list.all_contacts).to include(c1, c2)
end
end
it 'percent calculations' do
account_list = create(:account_list, monthly_goal: '200')
create(:contact, pledge_amount: 100, account_list: account_list)
create(:contact, pledge_amount: 50, pledge_received: true, account_list: account_list)
expect(account_list.in_hand_percent).to eq 25
expect(account_list.pledged_percent).to eq 75
end
context '#queue_sync_with_google_contacts' do
let(:account_list) { create(:account_list) }
let(:integration) { create(:google_integration, contacts_integration: true, calendar_integration: false) }
before do
account_list.google_integrations << integration
end
it 'queues a job if there is a google integration that syncs contacts' do
account_list.queue_sync_with_google_contacts
expect(GoogleSyncDataWorker.jobs.size).to eq(1)
end
it 'does not queue if there are no google integrations with contact sync set' do
integration.update(contacts_integration: false)
account_list.queue_sync_with_google_contacts
expect(GoogleSyncDataWorker.jobs).to be_empty
account_list.google_integrations.destroy_all
account_list.queue_sync_with_google_contacts
expect(GoogleSyncDataWorker.jobs).to be_empty
end
it 'does not queue if is an import is running' do
create(:import, account_list: account_list, importing: true, source: 'google')
account_list.queue_sync_with_google_contacts
expect(GoogleSyncDataWorker.jobs).to be_empty
end
it 'does not queue if is an account is downloading' do
account_list.users << create(:user)
create(:organization_account, downloading: true, person: account_list.users.first)
account_list.queue_sync_with_google_contacts
expect(GoogleSyncDataWorker.jobs).to be_empty
end
it 'does not queue if the mail chimp account is importing' do
create(:mail_chimp_account, account_list: account_list, importing: true)
expect do
account_list.queue_sync_with_google_contacts
end.to_not change(GoogleSyncDataWorker.jobs, :size)
end
end
context '#import_data' do
let(:account_list) { create(:account_list) }
let(:user) { create(:user) }
let(:organization_account) { create(:organization_account) }
before do
account_list.users << user
user.organization_accounts << organization_account
end
it 'imports data for each org account, then sends notifications and queues google contact sync' do
expect_any_instance_of(Person::OrganizationAccount).to receive(:import_all_data)
expect(account_list).to receive(:send_account_notifications)
expect(account_list).to receive(:queue_sync_with_google_contacts)
account_list.send(:import_data)
end
it 'does not import from org accounts with skip_downloads set' do
organization_account.update(disable_downloads: true)
expect_any_instance_of(Person::OrganizationAccount).to_not receive(:import_all_data)
account_list.send(:import_data)
end
it 'runs dup balance fix' do
expect(DesignationAccount::DupByBalanceFix).to receive(:deactivate_dups)
account_list.send(:import_data)
end
end
describe 'top and bottom donor halves by pledge value' do
subject { create(:account_list) }
let(:high_pledger) do
create(:contact, status: 'Partner - Financial', pledge_amount: 100)
end
let(:low_pledger) do
create(:contact, status: 'Partner - Financial', pledge_amount: 600, pledge_frequency: 12)
end
before do
subject.contacts << high_pledger
subject.contacts << low_pledger
end
it 'calculates the top 50 percent' do
expect(subject.reload.top_50_percent.to_a).to eq [high_pledger]
end
it 'calculates the bottom 50 percent' do
expect(subject.bottom_50_percent.to_a).to eq [low_pledger]
end
end
context '#async_merge_contacts' do
it 'merges duplicate contacts by common name and donor number / address' do
Sidekiq::Testing.inline!
account_list = create(:account_list)
donor = create(:donor_account)
# Create the contacts that will be merged
contact1 = create(:contact, name: 'John', account_list: account_list)
contact2 = create(:contact, name: 'John', account_list: account_list)
# Create the contacts that won't be merged because they have a different name and were updated_at earlier
contact3 = create(:contact, name: 'Peter', account_list: account_list)
contact3.update_column(:updated_at, 2.hours.ago)
contact4 = create(:contact, name: 'Peter', account_list: account_list)
contact4.update_column(:updated_at, 2.hours.ago)
contact1.donor_accounts << donor
contact2.donor_accounts << donor
contact3.donor_accounts << donor
contact4.donor_accounts << donor
expect do
account_list.async_merge_contacts(1.hour.ago)
end.to change(Contact, :count).from(4).to(3)
end
end
context '#currencies' do
it 'gives the currencies of contacts, organizations and configured default' do
account_list = create(:account_list, settings: { currency: 'EUR' })
create(:contact, account_list: account_list, pledge_currency: 'GBP')
user = create(:user)
account_list.users << user
org = create(:fake_org, default_currency_code: 'JPY')
user.organization_accounts << create(:organization_account, organization: org)
expect(account_list.currencies).to contain_exactly('EUR', 'GBP', 'JPY')
end
end
context '#donations' do
it 'shows no online org donations for account list with no designations' do
online_org = create(:organization, api_class: 'Siebel')
donor_account = create(:donor_account, organization: online_org)
designation_account = create(:designation_account, organization: online_org)
account_list = create(:account_list)
contact = create(:contact, account_list: account_list)
contact.donor_accounts << donor_account
create(:donation, donor_account: donor_account,
designation_account: designation_account)
expect(account_list.donations).to be_empty
end
it 'shows donations for account list that has designations' do
online_org = create(:organization, api_class: 'Siebel')
donor_account = create(:donor_account, organization: online_org)
designation_account = create(:designation_account, organization: online_org)
account_list = create(:account_list)
donation = create(:donation, donor_account: donor_account,
designation_account: designation_account)
contact = create(:contact, account_list: account_list)
contact.donor_accounts << donor_account
account_list.designation_accounts << designation_account
expect(account_list.donations.to_a).to eq([donation])
end
it 'shows offline org donations for account with designations' do
account_list = create(:account_list)
contact = create(:contact, account_list: account_list)
offline_org = create(:organization, api_class: 'OfflineOrg')
donor_account = create(:donor_account, organization: offline_org)
designation_account = create(:designation_account, organization: offline_org)
designation_profile = create(:designation_profile, account_list: account_list)
create(:designation_profile_account, designation_account: designation_account,
designation_profile: designation_profile)
donation = create(:donation, donor_account: donor_account,
designation_account: designation_account)
contact.donor_accounts << donor_account
expect(account_list.donations.to_a).to eq([donation])
end
end
context '#active_mpd_start_at_is_before_active_mpd_finish_at' do
subject { create(:account_list) }
before do
subject.active_mpd_start_at = Date.today
end
describe 'start_at date is set but finish_at date is not set' do
it 'validates' do
expect(subject.valid?).to eq(true)
end
end
describe 'start_at date is set but finish_at date is set' do
describe 'start_at date is before finish_at date' do
before do
subject.active_mpd_finish_at = Date.today + 1.month
end
it 'validates' do
expect(subject.valid?).to eq(true)
end
end
describe 'start_at date is finish_at date' do
before do
subject.active_mpd_finish_at = subject.active_mpd_start_at
end
it 'validates' do
expect(subject.valid?).to eq(false)
expect(subject.errors[:active_mpd_start_at]).to eq ['is after or equal to active mpd finish at date']
end
end
describe 'start_at date is after finish_at date' do
before do
subject.active_mpd_finish_at = Date.today - 1.month
end
it 'does not validates' do
expect(subject.valid?).to eq(false)
expect(subject.errors[:active_mpd_start_at]).to eq ['is after or equal to active mpd finish at date']
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/google_email_activity_spec.rb
|
require 'rails_helper'
RSpec.describe GoogleEmailActivity, type: :model do
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/notes.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class Contact::Filter::Notes < Contact::Filter::Base
def execute_query(contacts, filters)
search_term = filters[:notes][:wildcard_note_search].to_s.downcase
return contacts if search_term.blank?
contacts.where('contacts.notes ilike ?', "%#{search_term}%")
end
def title
_('Notes')
end
def parent
_('Search Notes')
end
def type
'text'
end
def custom_options
[{ name: _('Search note contents'), id: 'wildcard_note_search' }]
end
def valid_filters?(filters)
filters[:notes].present? && filters[:notes][:wildcard_note_search].to_s.present?
end
end
|
chuckmersereau/api_practice
|
app/services/task/filter/base.rb
|
class Task::Filter::Base < ApplicationFilter
private
def clean_contact_filter(filters)
(filters.keys.map { |k| k.to_s.sub(/contact_/i, '').to_sym }.zip filters.values).to_h
end
def contact_scope(tasks)
Contact.joins(:activity_contacts).where(activity_contacts: { activity: tasks })
end
end
|
chuckmersereau/api_practice
|
app/services/employee_csv_importer.rb
|
require 'csv'
require 'ostruct'
class EmployeeCsvImporter
REQUIRED_HEADERS = %w(
email
first_name
last_name
relay_guid
key_guid
).freeze
attr_reader :import_group_size,
:path
def initialize(path:, import_group_size: nil)
@path = path
@import_group_size = import_group_size || default_import_group_size
end
def converted_data
@converted_data ||= convert_row_data
end
def default_import_group_size
180
end
def import(from:, to:)
converted_data[from..to].each do |user_for_import|
cas_attributes = user_for_import.cas_attributes
UserFromCasService.find_or_create(cas_attributes)
end
end
def queue!
range_groups = (0...converted_data.count).each_slice(import_group_size)
range_groups.each_with_index do |range_group, index|
from = range_group.first
to = range_group.last
EmployeeCsvGroupImportWorker.perform_in(index.hours, path, from, to)
end
end
def row_data
@row_data ||= fetch_row_data
end
def self.import(path:, from:, to:)
new(path: path).import(from: from, to: to)
end
def self.queue(path:, import_group_size: nil)
new(path: path, import_group_size: import_group_size).queue!
end
private
def convert_row_data
row_data.map do |single_row|
attrs = single_row.to_h.keep_if { |key, _| key.present? }
UserForImport.new(attrs)
end
end
def csv_options
{
col_sep: ',',
headers: true
}
end
def fetch_row_data
file = open(path)
data = CSV.read(file, csv_options)
headers = data.first.to_h.keys.compact
all_required_headers = REQUIRED_HEADERS.all? { |required_header| headers.include?(required_header) }
raise InvalidHeadersError, invalid_headers_error(headers) unless all_required_headers
data
end
def invalid_headers_error(wrong_headers)
required_headers_list = REQUIRED_HEADERS.join(', ')
wrong_headers_list = wrong_headers.join(', ')
"Your CSV file must have the headers: #{required_headers_list}, instead it has: #{wrong_headers_list}"
end
class UserForImport < OpenStruct
def cas_attributes
{
email: email,
firstName: first_name,
lastName: last_name,
relayGuid: relay_guid || '',
ssoGuid: key_guid || '',
theKeyGuid: key_guid || ''
}
end
end
class InvalidHeadersError < StandardError; end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/exporter/batcher.rb
|
<gh_stars>0
# This class handles all batch operations used when communicating with the MailChimp API.
class MailChimp::Exporter
class Batcher
attr_reader :mail_chimp_account, :gibbon_wrapper, :list_id
delegate :email_hash, to: :mail_chimp_account
def initialize(mail_chimp_account, gibbon_wrapper, list_id, appeal = nil)
@mail_chimp_account = mail_chimp_account
@gibbon_wrapper = gibbon_wrapper
@list_id = list_id
@appeal = appeal
end
def subscribe_contacts(contacts)
members_params = fetch_member_params_from_contacts(contacts).uniq
batch_create_members(members_params)
create_member_records(members_params)
end
def unsubscribe_members(emails_with_reasons)
return if emails_with_reasons.none?
operations = emails_with_reasons.map do |email, reason|
[unsubscribe_operation(email), note_reason_operation(email, reason)]
end.flatten.compact
send_batch_operations(operations)
delete_member_records(emails_with_reasons.keys)
end
def unsubscribe_operation(email)
{
method: 'PATCH',
path: "/lists/#{list_id}/members/#{email_hash(email)}",
body: { status: 'unsubscribed' }.to_json
}
end
def note_reason_operation(email, reason)
return unless reason.present?
{
method: 'POST',
path: "/lists/#{list_id}/members/#{email_hash(email)}/notes",
body: { note: "Unsubscribed by MPDX: #{reason}" }.to_json
}
end
def fetch_member_params_from_contacts(contacts)
relevant_people = Person.joins(:contact_people, :primary_email_address)
.where(contact_people: { contact: contacts })
.preload(:contact_people, :primary_email_address)
contacts.each_with_object([]) do |contact, members_params|
people_that_belong_to_contact(relevant_people, contact).each do |person|
next if person.optout_enewsletter?
members_params << person_to_member_param(person, contact)
end
end
end
def people_that_belong_to_contact(people, contact)
people.select do |person|
person_belongs_to_contact?(person, contact)
end
end
def person_belongs_to_contact?(person, contact)
person.contact_people.map(&:contact_id).each do |contact_id|
return true if contact_id == contact.id
end
false
end
def person_to_member_param(person, contact)
member_params = fetch_base_member_params(person, contact)
member_params[:merge_fields].merge(DONATED_TO_APPEAL: @appeal.donated?(contact)) if appeal_export?
member_params[:language] = contact.locale if contact.locale.present?
add_status_and_tags_groupings_to_params(contact, member_params)
end
def add_status_and_tags_groupings_to_params(contact, member_params)
member_params[:interests] = member_params[:interests].to_h
member_params[:interests].merge!(interests_for_status(contact.status))
member_params[:interests].merge!(interests_for_tags(contact.tag_list))
member_params
end
def fetch_base_member_params(person, contact)
return unless person.primary_email_address
{
status: 'subscribed',
email_address: person.primary_email_address.email,
merge_fields: {
EMAIL: person.primary_email_address.email, FNAME: person.first_name,
LNAME: person.last_name || '', GREETING: contact.greeting
}
}
end
def batch_create_members(members_params)
operations = members_params.map do |member_params|
{
method: 'PUT',
path: "/lists/#{list_id}/members/#{email_hash(member_params[:email_address])}",
body: member_params.to_json
}
end
send_batch_operations(operations)
end
def send_batch_operations(operations)
# MailChimp is giving a weird error every once in a while.
# At first glance it seems to be a Bad Request Error, however the
# legitimate Bad Request error message is different. Because I've never
# seen this happen more than twice in a row, I think that this solution
# will do.
groups_with_batches = operations.in_groups_of(50, false).map do |group_of_operations|
escape_intermittent_bad_request_error do
batch = gibbon_wrapper.batches.create(body: { operations: group_of_operations })
{ batch: batch, operations: group_of_operations }
end
end
groups_with_batches.each(&method(:log_batches))
end
def log_batches(group_with_batch)
batch = group_with_batch[:batch]
self_link = batch['_links'].find { |link| link['rel'] == 'self' }.try(:[], 'href')
group_with_batch[:operations].each do |operation|
AuditChangeWorker.perform_async(
created_at: Time.zone.now,
action: 'create',
auditable_type: 'MailChimpBatch',
audtiable_id: batch['id'],
audited_changes: operation.to_json,
associated_id: mail_chimp_account.id,
associated_type: 'MailChimpAccount',
comment: self_link
)
end
MailChimp::BatchResultsWorker.perform_in(15.minutes, mail_chimp_account.id, batch['id'])
end
def escape_intermittent_bad_request_error
retry_count ||= 0
yield
rescue Gibbon::MailChimpError => error
raise unless intermittent_error?(error)
sleep 10 if too_many_batches_error?(error)
# If the MC API responds with the 'too many batches opened' error,
# we wait for 10 seconds hoping that other batches will complete in that time.
raise if (retry_count += 1) >= 5
retry
end
def intermittent_error?(error)
intermittent_bad_request_error?(error) ||
intermittent_nesting_too_deep_error?(error) ||
too_many_batches_error?(error)
end
def too_many_batches_error?(error)
error.message.include?('You have more than 500 pending batches.')
end
def intermittent_nesting_too_deep_error?(error)
error.message.include?('nested too deeply')
end
def intermittent_bad_request_error?(error)
error.message.include?('<H1>Bad Request</H1>')
end
def create_member_records(members_params)
members_params.each do |member_params|
member = mail_chimp_account.mail_chimp_members.find_or_create_by(list_id: list_id,
email: member_params[:email_address])
member.update(first_name: member_params[:merge_fields][:FNAME],
greeting: member_params[:merge_fields][:GREETING],
last_name: member_params[:merge_fields][:LNAME],
status: status_for_interest_ids(member_params[:interests]),
tags: tags_for_interest_ids(member_params[:interests]))
end
end
def delete_member_records(emails)
MailChimpMember.where('lower(email) in (?)', emails)
.where(list_id: list_id, mail_chimp_account_id: mail_chimp_account.id)
.each(&:destroy)
end
def interests_for_tags(tags)
Hash[cached_interest_ids(:tags).map do |tag, interest_id|
[interest_id, tags.include?(tag)]
end]
end
def interests_for_status(contact_status)
Hash[cached_interest_ids(:statuses).map do |status, interest_id|
[interest_id, status == _(contact_status)]
end]
end
def tags_for_interest_ids(interests)
mail_chimp_account.tags_interest_ids_for_list(list_id).invert.values_at(
fetch_interest_ids(:tags, interests).first
) if interests.present?
end
def status_for_interest_ids(interests)
mail_chimp_account.statuses_interest_ids_for_list(list_id).invert[
fetch_interest_ids(:statuses, interests).first
] if interests.present?
end
def fetch_interest_ids(attribute, interests)
cached_interest_ids(attribute).values &
interests.select { |_, value| value.present? }.keys
end
def cached_interest_ids(attribute)
InterestIdsCacher.new(mail_chimp_account, gibbon_wrapper, list_id).cached_interest_ids(attribute)
end
def appeal_export?
@appeal
end
def gibbon_list
gibbon_wrapper.gibbon_list_object(list_id)
end
end
end
|
chuckmersereau/api_practice
|
config/initializers/fb_graph.rb
|
FbGraph.http_config do |http_client|
http_client.connect_timeout = 120
end
|
chuckmersereau/api_practice
|
app/validators/class_validator.rb
|
<reponame>chuckmersereau/api_practice
class ClassValidator < ActiveModel::EachValidator
def initialize(options)
raise(ArgumentError, 'You must supply a validation value for is_a') unless options[:is_a].present?
options[:message] ||= "should be a #{json_type(options[:is_a])}"
options[:allow_nil] ||= false
super
end
def validate_each(record, attribute, value)
return if options[:allow_nil] && value.nil?
return if value.is_a?(options[:is_a])
record.errors[attribute] << options[:message]
end
private
def json_type(klass)
{
'Hash' => 'Object'
}[klass.to_s] || klass.to_s
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180615175942_change_account_listable_name.rb
|
<filename>db/migrate/20180615175942_change_account_listable_name.rb<gh_stars>0
class ChangeAccountListableName < ActiveRecord::Migration
def change
add_column :deleted_records, :deleted_from_id, :uuid
add_column :deleted_records, :deleted_from_type, :string
add_index :deleted_records, [:deleted_from_id, :deleted_from_type], name: :deleted_from_index
remove_index :deleted_records, name: :account_listable_index
remove_column :deleted_records, :account_listable_id
remove_column :deleted_records, :account_listable_type
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/chalkline_mails_spec.rb
|
<filename>spec/acceptance/api/v2/account_lists/chalkline_mails_spec.rb<gh_stars>0
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Account List ChalkLine Mail' do
include_context :json_headers
documentation_scope = :account_lists_api_chalkline_mail
let(:resource_type) { 'chalkline_mails' }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:resource_attributes) do
%w(
created_at
)
end
context 'authorized user' do
before { api_login(user) }
post '/api/v2/account_lists/:account_list_id/chalkline_mail' do
example 'ChalkLine Mail [CREATE]', document: documentation_scope do
explanation 'Enqueues a job that will send ChalkLine Mail for this Account List'
travel_to Time.current do
do_request account_list_id: account_list_id, data: { type: 'chalkline_mails' }
expect(response_status).to eq 201
expect(json_response).to eq('data' => {
'id' => '',
'type' => 'chalkline_mails',
'attributes' => {
'created_at' => Time.current.utc.iso8601,
'updated_at' => nil,
'updated_in_db_at' => nil
}
})
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/bulk_spec.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts Bulk' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: :contacts)
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!(:resource_type) { 'contacts' }
let!(:user) { create(:user_with_account) }
let(:new_contact) do
attributes_for(:contact)
.except(
:first_donation_date,
:last_activity,
:last_appointment,
:last_donation_date,
:last_letter,
:last_phone_call,
:last_pre_call,
:last_thank,
:late_at,
:notes_saved_at,
:pls_id,
:prayer_letters_id,
:prayer_letters_params,
:tnt_id,
:total_donations,
:uncompleted_tasks_count
).merge(updated_in_db_at: contact_one.updated_at)
end
let(:account_list_relationship) do
{
account_list: {
data: {
id: account_list.id,
type: 'account_lists'
}
}
}
end
let(:bulk_create_form_data) do
[{ data: { type: resource_type, id: SecureRandom.uuid, attributes: new_contact, relationships: account_list_relationship } }]
end
let(:bulk_update_form_data) do
[{ data: { type: resource_type, id: contact_one.id, attributes: new_contact } }]
end
context 'authorized user' do
before { api_login(user) }
post '/api/v2/contacts/bulk' do
doc_helper.insert_documentation_for(action: :bulk_create, context: self)
example doc_helper.title_for(:bulk_create), document: doc_helper.document_scope do
explanation doc_helper.description_for(:bulk_create)
do_request data: bulk_create_form_data
expect(response_status).to eq(200)
expect(json_response.first['data']['attributes']['name']).to eq new_contact[:name]
end
end
put '/api/v2/contacts/bulk' do
doc_helper.insert_documentation_for(action: :bulk_update, context: self)
example doc_helper.title_for(:bulk_update), document: doc_helper.document_scope do
explanation doc_helper.description_for(:bulk_update)
do_request data: bulk_update_form_data
expect(response_status).to eq(200)
expect(json_response.first['data']['attributes']['name']).to eq new_contact[:name]
end
end
delete '/api/v2/contacts/bulk' do
doc_helper.insert_documentation_for(action: :bulk_delete, context: self)
example doc_helper.title_for(:bulk_delete), document: doc_helper.document_scope do
explanation doc_helper.description_for(:bulk_delete)
do_request data: [
{ data: { type: resource_type, id: contact_one.id } },
{ data: { type: resource_type, id: contact_two.id } }
]
expect(response_status).to eq(200)
expect(json_response.size).to eq(2)
expect(json_response.collect { |hash| hash.dig('data', 'id') }).to match_array([contact_one.id, contact_two.id])
end
end
end
end
|
chuckmersereau/api_practice
|
app/exhibits/reports/monthly_giving_graph_exhibit.rb
|
<gh_stars>0
class Reports::MonthlyGivingGraphExhibit < DisplayCase::Exhibit
include ApplicationHelper
def self.applicable_to?(object)
object.class.name == 'Reports::MonthlyGivingGraph'
end
def salary_currency_symbol
currency_symbol(salary_currency)
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/notifications_controller.rb
|
<reponame>chuckmersereau/api_practice
class Api::V2::AccountLists::NotificationsController < Api::V2Controller
def index
authorize load_account_list, :show?
load_notifications
render json: @notifications.preload_valid_associations(include_associations),
scope: { account_list: load_account_list, locale: locale },
meta: meta_hash(@notifications),
include: include_params,
fields: field_params
end
def show
load_notification
authorize_notification
render_notification
end
def create
persist_notification
end
def update
load_notification
authorize_notification
persist_notification
end
def destroy
load_notification
authorize_notification
destroy_notification
end
private
def destroy_notification
@notification.destroy
head :no_content
end
def load_notifications
@notifications = notification_scope.where(filter_params)
.reorder(sorting_param)
.page(page_number_param)
.per(per_page_param)
end
def load_notification
@notification ||= Notification.find(params[:id])
end
def render_notification
render json: @notification,
scope: { account_list: load_account_list, locale: locale },
status: success_status,
include: include_params,
fields: field_params
end
def persist_notification
build_notification
authorize_notification
if save_notification
render_notification
else
render_with_resource_errors(@notification)
end
end
def build_notification
@notification ||= notification_scope.build
@notification.assign_attributes(notification_params)
end
def save_notification
@notification.save(context: persistence_context)
end
def notification_params
params
.require(:notification)
.permit(Notification::PERMITTED_ATTRIBUTES)
end
def authorize_notification
authorize @notification
end
def notification_scope
load_account_list.notifications
end
def load_account_list
@account_list ||= AccountList.find(params[:account_list_id])
end
def pundit_user
PunditContext.new(current_user, account_list: load_account_list)
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/referrals_import_spec.rb
|
require 'rails_helper'
describe TntImport::ReferralsImport do
let(:user) { create(:user) }
let(:import) { create(:tnt_import, override: true, user: user) }
let(:tnt_import) { TntImport.new(import) }
it 'handles a nil contact id without crashing' do
contact_rows = tnt_import.xml.tables['Contact']
contact_ids_by_tnt_contact_id = contact_rows.each_with_object({}) { |row, hash| hash[row['id']] = nil }
expect { TntImport::ReferralsImport.new(contact_ids_by_tnt_contact_id, contact_rows).import }.to_not raise_error
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/xml_reader_spec.rb
|
<filename>spec/services/tnt_import/xml_reader_spec.rb
require 'rails_helper'
describe TntImport::Xml do
let(:tnt_import) { create(:tnt_import, override: true) }
let(:xml_reader) { TntImport::XmlReader.new(tnt_import) }
describe 'initialize' do
it 'initializes' do
expect(xml_reader).to be_a TntImport::XmlReader
end
end
describe '#parsed_xml' do
context 'unparsable characters' do
let(:test_file_path) { Rails.root.join('spec/fixtures/tnt/tnt_unparsable_characters.xml') }
let(:tnt_import) { create(:tnt_import, override: true, file: File.new(test_file_path)) }
it 'verify that the test file has unparsable characters' do
contents = File.open(test_file_path).read
expect(TntImport::XmlReader::UNPARSABLE_UTF8_CHARACTERS).to be_present
expect(TntImport::XmlReader::UNPARSABLE_UTF8_CHARACTERS.all? do |unparsable_utf8_character|
contents.include?(unparsable_utf8_character)
end).to eq(true)
end
it 'handles unparsable utf8 characters' do
# If the xml is not parsed properly we expect the number of returned tables to be less than 21
expect(xml_reader.parsed_xml.tables.keys.size).to eq(21)
end
end
end
end
|
chuckmersereau/api_practice
|
app/uploaders/image_uploader.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class ImageUploader < CarrierWave::Uploader::Base
include Cloudinary::CarrierWave
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def cache_dir
"#{Rails.root}/tmp/uploads"
end
# Process files as they are uploaded:
process resize_to_limit: [500, 500]
version :large do
eager
process resize_and_pad: [180, 180]
end
version :square do
eager
cloudinary_transformation width: 50, height: 50, crop: :fill, gravity: :face
end
def extension_white_list
%w(jpg jpeg png)
end
end
|
chuckmersereau/api_practice
|
spec/serializers/reports/activity_results_period_serializer_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe Reports::ActivityResultsPeriodSerializer do
let(:account_list) { create(:account_list) }
let(:object) do
Reports::ActivityResultsPeriod.new(account_list: account_list,
start_date: 1.week.ago,
end_date: DateTime.current)
end
let(:attrs) do
Reports::ActivityResultsPeriodSerializer::REPORT_ATTRIBUTES + [:created_at, :id, :updated_at, :updated_in_db_at]
end
subject { Reports::ActivityResultsPeriodSerializer.new(object).as_json }
it 'serializes attributes' do
expect(subject.keys).to match_array attrs
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160523203413_add_status_interest_ids_to_mail_chimp_account.rb
|
class AddStatusInterestIdsToMailChimpAccount < ActiveRecord::Migration
def change
add_column :mail_chimp_accounts, :status_interest_ids, :text
end
end
|
chuckmersereau/api_practice
|
app/models/pledge.rb
|
<gh_stars>0
class Pledge < ApplicationRecord
audited associated_with: :appeal, on: [:destroy]
belongs_to :account_list
belongs_to :appeal
belongs_to :contact
has_many :pledge_donations, dependent: :destroy
has_many :donations, through: :pledge_donations
validates :account_list, :amount, :contact, :expected_date, presence: true
validates :appeal_id, uniqueness: { scope: :contact_id }
PERMITTED_ATTRIBUTES = [:amount,
:amount_currency,
:appeal_id,
:created_at,
:contact_id,
:donation_id,
:expected_date,
:overwrite,
:status,
:updated_at,
:updated_in_db_at,
:id].freeze
enum status: {
not_received: 'not_received',
received_not_processed: 'received_not_processed',
processed: 'processed'
}
def merge(loser)
return unless appeal_id == loser.appeal_id
loser.pledge_donations.each do |pledge_donation|
pledge_donation.update!(pledge: self)
end
if loser.amount.to_d > amount.to_d
merged_attributes = [:amount, :amount_currency, :expected_date]
loser_attrs = loser.attributes.symbolize_keys.slice(*merged_attributes).reject { |_, v| v.blank? }
update!(loser_attrs)
end
set_processed
# must reload first so it doesn't try delete the donations we just moved over
loser.reload.destroy
end
def set_processed
update(status: pledge_status)
end
private
def pledge_status
all_donations_have_been_received? ? :processed : :received_not_processed
end
def all_donations_have_been_received?
# floating point comparison is yucky, converting to a BigDecimal should be a little better
amount.to_d <= donations.reload.to_a.sum(&:converted_amount).to_d
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130607202118_remove_designation_profile_id_from_account_list.rb
|
<reponame>chuckmersereau/api_practice
class RemoveDesignationProfileIdFromAccountList < ActiveRecord::Migration
def up
remove_column :account_lists, :designation_profile_id
end
def down
add_column :account_lists, :designation_profile_id, :integer
end
end
|
chuckmersereau/api_practice
|
config/initializers/default.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
# https://github.com/rails/rails/pull/23666
# This PR was never backported to 4.2-stable and is needed to use default_scope on an abstract class
# can
module ActiveRecord
module Scoping
module Default
module ClassMethods
protected
def build_default_scope(base_rel = relation) # :nodoc:
return if abstract_class?
if !Base.is_a?(method(:default_scope).owner)
# The user has defined their own default scope method, so call that
evaluate_default_scope { default_scope }
elsif default_scopes.any?
evaluate_default_scope do
default_scopes.inject(base_rel) do |default_scope, scope|
scope = scope.respond_to?(:to_proc) ? scope : scope.method(:call)
default_scope.merge(base_rel.instance_exec(&scope))
end
end
end
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/serializers/designation_account_serializer_spec.rb
|
require 'rails_helper'
describe DesignationAccountSerializer 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(:serializer) { DesignationAccountSerializer.new(designation_account, scope: user) }
it 'balances list' do
expect(serializer.as_json).to include :balances
expect(serializer.as_json[:balances][0][:id]).to eq(designation_account.balances[0].id)
end
describe '#currency_symbol' do
it 'returns symbol for designation account currency' do
expect(designation_account).to receive(:currency).and_return('USD')
expect(serializer.currency_symbol).to eq('$')
end
end
describe '#converted_balance' do
it 'returns balance of designation account in salary currency' do
expect(designation_account).to receive(:converted_balance).with(account_list.salary_currency_or_default)
expect(serializer.converted_balance).to eq(0.0)
end
end
describe '#total_currency' do
it 'returns symbol for total currency' do
expect(serializer.total_currency).to eq(account_list.salary_currency_or_default)
end
it 'when list is null' do
account_list.delete
expect(serializer.total_currency).to eq nil
end
end
describe '#exchange_rate' do
it 'returns exchange rate for currency to total currency' do
expect(CurrencyRate).to(
receive(:latest_for_pair).with(from: serializer.currency, to: serializer.total_currency)
.and_return(0.5)
)
expect(serializer.exchange_rate).to eq 0.5
end
end
describe '#active' do
context 'object active' do
before { allow(designation_account).to receive(:active).and_return(true) }
let(:salary_organization_id) { create(:organization).id }
context 'object organization is salary organization' do
before do
account_list.update(salary_organization_id: salary_organization_id)
designation_account.update(organization_id: salary_organization_id)
end
it 'returns true' do
expect(serializer.active).to be_truthy
end
end
context 'object organization is not salary organization' do
before do
account_list.update(salary_organization_id: salary_organization_id)
designation_account.update(organization_id: create(:organization).id)
end
it 'returns false' do
expect(serializer.active).to be_falsy
end
end
it 'when list does not exist' do
account_list.delete
expect(serializer.active).to be(false)
end
end
context 'object inactive' do
before { allow(designation_account).to receive(:active).and_return(false) }
it 'returns false' do
expect(serializer.active).to be_falsy
end
end
end
describe '#display_name' do
context 'designation_account has name and number' do
let(:designation_account) { create(:designation_account, name: 'Name', designation_number: 'Number') }
it 'returns designation_account name (number)' do
expect(serializer.display_name).to eq 'Name (Number)'
end
end
context 'designation_account has name with number and number' do
let(:designation_account) { create(:designation_account, name: '<NAME>', designation_number: 'Number') }
it 'returns designation_account name' do
expect(serializer.display_name).to eq 'Name Number'
end
end
context 'designation_account has no name' do
let(:designation_account) { create(:designation_account, name: nil, designation_number: 'Number') }
it 'returns designation_account number' do
expect(serializer.display_name).to eq 'Number'
end
end
context 'designation_account has no number' do
let(:designation_account) { create(:designation_account, name: 'Name', designation_number: nil) }
it 'returns designation_account name' do
expect(serializer.display_name).to eq 'Name'
end
end
context 'designation_account has no name and no number' do
let(:designation_account) { create(:designation_account, name: nil, designation_number: nil) }
it 'returns designation_account name' do
expect(serializer.display_name).to eq 'Unknown'
end
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/background_batch/request_serializer.rb
|
class BackgroundBatch::RequestSerializer < ApplicationSerializer
attributes :path,
:request_body,
:request_headers,
:request_method,
:request_params,
:response_body,
:response_headers,
:default_account_list
belongs_to :background_batch
end
|
chuckmersereau/api_practice
|
app/controllers/api_controller.rb
|
<reponame>chuckmersereau/api_practice
class ApiController < ActionController::API
rescue_from ActiveRecord::RecordNotFound, with: :render_404_from_exception
rescue_from ActiveRecord::RecordNotUnique, with: :render_409_from_exception
rescue_from Exceptions::AuthenticationError, with: :render_401_from_exception
rescue_from Exceptions::BadRequestError, with: :render_400_from_exception
rescue_from JsonApiService::ForeignKeyPresentError, with: :render_409_from_exception
rescue_from JsonApiService::InvalidPrimaryKeyPlacementError, with: :render_409_from_exception
rescue_from JsonApiService::InvalidTypeError, with: :render_409_from_exception
rescue_from JsonApiService::MissingTypeError, with: :render_409_from_exception
before_action :verify_request
MEDIA_TYPE_MATCHER = /.+".+"[^,]*|[^,]+/
ALL_MEDIA_TYPES = '*/*'.freeze
DEFAULT_SUPPORTED_CONTENT_TYPE = 'application/vnd.api+json'.freeze
class << self
def supports_content_types(*content_types)
@supported_content_types = content_types.compact.presence
end
def supports_accept_header_content_types(*content_types)
@supported_accept_header_content_types = content_types.compact.presence
end
def supported_content_types
@supported_content_types ||= []
@supported_content_types.presence || [DEFAULT_SUPPORTED_CONTENT_TYPE]
end
def supported_accept_header_content_types
@supported_accept_header_content_types ||= []
@supported_accept_header_content_types.presence || [DEFAULT_SUPPORTED_CONTENT_TYPE]
end
end
protected
def conflict_error?(resource)
resource.errors.full_messages.any? do |error_message|
error_message.include?(ApplicationRecord::CONFLICT_ERROR_MESSAGE)
end
end
def current_account_list
@account_list ||= current_user.account_lists
.find_by(id: params[:account_list_id])
end
def given_media_types(header)
(request.headers[header] || '')
.scan(MEDIA_TYPE_MATCHER)
.map(&:strip)
end
def render_200
head :ok
end
def render_201
head :created
end
def render_400(title: 'Bad Request', detail: nil)
render_error(title: title, detail: detail, status: '400')
end
def render_400_from_exception(exception)
render_400(detail: exception&.message)
end
def render_with_resource_errors(resource)
if resource.is_a? Hash
render_error(hash: resource, status: '400')
elsif conflict_error?(resource)
render_409(detail: detail_for_resource_first_error(resource), resource: resource)
else
render_400_with_errors(resource)
end
end
def render_400_with_errors(resource_or_hash)
render_error(resource: resource_or_hash, status: '400')
end
def render_401(title: 'Unauthorized', detail: nil)
render_error(title: title, detail: detail, status: '401')
end
def render_401_from_exception(exception)
render_401(detail: exception&.message)
end
def render_403(title: 'Forbidden', detail: nil)
render_error(title: title, detail: detail, status: '403')
end
def render_403_from_exception(exception)
return render_403 unless exception&.record.try(:id)
type = JsonApiService.configuration.resource_lookup.find_type_by_class(exception&.record&.class)
render_403(detail: 'Not allowed to perform that action on the '\
"resource with ID #{exception.record.id} of type #{type}")
end
def render_404(title: 'Not Found', detail: nil)
render_error(title: title, detail: detail, status: '404')
end
def render_404_from_exception(exception)
render_404(detail: exception&.message)
end
def render_406
render_error(title: 'Not Acceptable', status: '406')
end
def render_409(title: 'Conflict', detail: nil, resource: nil)
render_error(title: title, detail: detail, status: '409', resource: resource)
end
def render_409_from_exception(exception)
detail = exception&.cause&.message || exception&.message || 'Conflict'
render_409(detail: detail)
end
def render_415
render_error(title: 'Unsupported Media Type', status: '415')
end
def render_error(hash: nil, resource: nil, title: nil, detail: nil, status:)
serializer = ErrorSerializer.new(
hash: hash,
resource: resource,
title: title,
detail: detail,
status: status
)
render json: serializer,
status: status
end
def success_status
if action_name == 'create'
:created
else
:ok
end
end
def valid_accept_header?
return true if self.class.supported_accept_header_content_types.include?(:any)
media_types = given_media_types('Accept')
media_types.blank? || media_types.any? do |media_type|
(self.class.supported_accept_header_content_types.include?(media_type) || media_type.start_with?(ALL_MEDIA_TYPES))
end
end
def valid_content_type_header?
return true if self.class.supported_content_types.include?(:any)
content_types = request.headers['CONTENT_TYPE']&.gsub(',', ';')&.split(';') || []
(self.class.supported_content_types & content_types).present?
end
def verify_request
verify_request_content_type
verify_request_accept_type
end
def verify_request_accept_type
render_406 unless valid_accept_header?
end
def verify_request_content_type
render_415 unless valid_content_type_header?
end
def detail_for_resource_first_error(resource)
first_key = resource.errors.messages.keys.first
val = resource.errors.messages.select do |key, _value|
key.to_s.include?('updated_in_db_at')
end.values.flatten.last
"#{first_key} #{val}"
end
end
|
chuckmersereau/api_practice
|
app/models/audited/audit_search.rb
|
<reponame>chuckmersereau/api_practice
require 'elasticsearch/persistence/model'
module Audited
class AuditSearch < Audited::AuditElastic
include Elasticsearch::Persistence::Model
index_name [Audited::AuditElastic::INDEX_BASE, '*'].join('-')
def self.dump(klass)
search_by(
bool: {
must: [
{ match: { auditable_type: klass } }
]
}
)
end
# can accept a complicated query value like:
# {
# bool: {
# must: [
# { match: { auditable_type: klass } },
# { match: { auditable_id: 1 } }
# ]
# }
# }
#
# or something simple like:
# { auditable_type: klass, auditable_id: 1 }
# which will be converted to the verbose form
def self.search_by(query)
query = expand_hash(query) unless query.any? { |_, value| value.is_a? Hash }
find_each(type: nil,
query: query,
sort: ['_doc'],
size: 100)
end
def self.expand_hash(hash)
{
bool: {
must: hash.map { |k, v| { match: { k => v } } }
}
}
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/wildcard_search.rb
|
class Contact::Filter::WildcardSearch < Contact::Filter::Base
include ::Concerns::Filter::SearchableInParts
def execute_query(contacts, filters)
@search_term = filters[:wildcard_search].downcase
@contacts = contacts
contacts_where_name_like_search_term_or_with_ids
end
private
def contacts_where_name_like_search_term_or_with_ids
or_conditions = build_sql_conditions_for_search
@contacts.where(
or_conditions.join(' OR '),
query_params(search_term_parts_hash.merge(contact_ids: gather_contact_ids))
)
end
def valid_filters?(filters)
super && filters[:wildcard_search].is_a?(String)
end
def gather_contact_ids
(contact_ids_from_people_relevant_to_search_term || []) +
(contact_ids_from_donor_account_numbers_like_search_term || [])
end
def build_sql_conditions_for_search
[
sql_condition_to_search_columns_in_parts('contacts.name'),
'contacts.id IN (:contact_ids)'
]
end
def contact_ids_from_people_relevant_to_search_term
ContactPerson.find_ids_with_search_term(
people_relevant_to_search_term
).pluck(:contact_id)
end
def people_relevant_to_search_term
Person::Filter::WildcardSearch.query(
Person.search_for_contacts(@contacts),
{ wildcard_search: @search_term },
account_lists
)
end
def contact_ids_from_donor_account_numbers_like_search_term
@contacts.search_donor_account_numbers(@search_term).ids
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_data_sync_import_spec.rb
|
require 'rails_helper'
require Rails.root.join('app', 'seeders', 'notification_types_seeder.rb')
describe TntDataSyncImport do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
before do
stub_smarty_streets
NotificationTypesSeeder.new.seed # Specs depend on NotificationType records.
end
it 'imports donors and donations, and sends notifications' do
expect(account_list).to receive(:send_account_notifications)
subject = build_import('tnt_data_sync_file.tntmpd')
subject.import
expect(account_list.contacts.count).to eq 1
contact = account_list.contacts.first.reload
expect(contact.name).to eq 'Mr. and Mrs. <NAME>'
expect(contact.people.first.first_name).to eq 'Cliff'
expect(account_list.donations.count).to eq 1
donation = account_list.donations.first
expect(donation.amount).to eq 85
expect(donation.tendered_amount).to eq 85
end
it 'works even if [ORGANIZATIONS] section missing and headers are lowercase' do
subject = build_import('tnt_data_sync_no_org_lowercase_fields.tntmpd')
expect do
subject.import
end.to change(Donation, :count).by(1)
end
it 'gives an erorr if the file has invalid data' do
subject = build_import('tnt_data_sync_invalid.tntmpd')
expect { subject.import }.to raise_error(Import::UnsurprisingImportError)
end
def build_import(file)
TntDataSyncImport.new(
build(:import,
source: 'tnt_data_sync', account_list: account_list, user: user,
file: File.new(Rails.root.join("spec/fixtures/tnt/#{file}")),
source_account_id: user.organization_accounts.first.id)
)
end
end
|
chuckmersereau/api_practice
|
app/services/application_filter.rb
|
class ApplicationFilter
include ActiveModel::Serialization
attr_reader :account_lists
def initialize(account_lists = nil)
@account_lists = account_lists
end
def self.config(account_lists)
filter = new(account_lists)
{
name: filter.name,
title: filter.title,
type: filter.type,
priority: filter.priority,
parent: filter.parent,
default_selection: filter.default_selection
}.merge(filter.select_options) if filter.display_filter_option? && !filter.empty?
end
def self.query(scope, filters, account_list)
new(account_list).query(scope, filters)
end
def query(scope, filters)
filters[name] ||= default_selection if default_selection.present?
return unless valid_filters?(filters)
return reverse_query(scope, filters) if reverse?(filters)
execute_query(scope, filters).distinct
end
def select_options
return {
multiple: %w(checkbox multiselect).include?(type),
options: options
} if custom_options?
{}
end
def display_filter_option?
filterer::FILTERS_TO_DISPLAY.index(class_name.demodulize).present?
end
def empty?
custom_options? ? custom_options.empty? : false
end
def multiple
%w(checkbox multiselect).include?(type)
end
def options
default_options + custom_options
end
def filterer
"#{class_name.split('::')[0...-2].join('::')}::Filterer".constantize
end
def custom_options?
%w(radio dropdown checkbox multiselect dates daterange text).include?(type)
end
def priority
filterer::FILTERS_TO_DISPLAY.index(class_name.demodulize) || 100
end
def parent
end
def default_options
return [] if %w(text dates daterange).include?(type)
[{ name: _('-- Any --'), id: '', placeholder: _('None') }]
end
def default_selection
return true if type == 'single_checkbox'
''
end
def custom_options
[]
end
def title
raise NotImplementedError, 'You must add a title for this filter'
end
def type
nil
end
def execute_query(_contacts, _filters)
end
# Override this method if your filter needs special logic (ie: not the default
# "WHERE NOT ..." functionality) to reverse a given filter.
# @return [ActiveRecord::Relation, nil] A Relation which reverses the given
# filters, or +nil+ to fall back to the default "WHERE NOT" behavior.
def execute_reverse_query(scope, filters)
end
def name
class_name.demodulize.underscore.to_sym
end
def class_name
self.class.name
end
alias id priority
private
def fetch_beginning_of_end_month_from_date_range(date_range)
return date_range.last.beginning_of_month unless date_range_in_same_month?(date_range)
date_range.last.end_of_month
end
def date_range_in_same_month?(date_range)
date_range.first.month == date_range.last.month
end
def daterange_params(date_range)
{ start: date_range.first.beginning_of_day,
end: date_range.last.end_of_day }
end
def parse_list(string)
string.split(',').select(&:present?).map(&:strip)
end
def cast_bool_value(string)
ActiveRecord::Type::Boolean.new.type_cast_from_user(string)
end
def valid_filters?(filters)
return false unless filters[name].present?
return false if filters[name].is_a?(Array)
return false if filters[name].is_a?(Hash)
true
end
def reverse?(filters)
filters[:"reverse_#{name}"].to_s == 'true'
end
def reverse_query(scope, filters)
reverse = execute_reverse_query(scope, filters.dup)
reverse || scope.where.not(id: execute_query(scope, filters).ids.uniq)
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/background_batch_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Background Batches' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: :background_batches)
before do
stub_request(:get, 'https://api.mpdx.org/api/v2/user')
.to_return(status: 200,
body: '{"id": 1234}',
headers: { accept: 'application/json' })
stub_request(:get, 'http://api.lvh.me:3000/api/v2/user')
.to_return(status: 200,
body: '{"id": 1234}',
headers: { accept: 'application/json' })
end
let!(:user) { create(:user_with_full_account) }
let!(:background_batch) { create(:background_batch, user: user) }
let(:resource_type) { 'background_batches' }
let(:excluded) { 0 }
let(:id) { background_batch.id }
let(:form_data) do
attributes = attributes_for(:background_batch).except(:user_id)
build_data(attributes, relationships: relationships)
end
let(:relationships) do
{
requests: {
data: [
{
type: 'background_batch_requests',
id: SecureRandom.uuid,
attributes: {
path: 'api/v2/user'
}
}
]
}
}
end
let(:resource_attributes) do
%w(
created_at
pending
total
updated_at
updated_in_db_at
)
end
let(:resource_asociations) do
%w(
requests
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/background_batches' do
doc_helper.insert_documentation_for(action: :index, context: self)
example doc_helper.title_for(:index), document: doc_helper.document_scope do
explanation doc_helper.description_for(:index)
do_request
check_collection_resource(1, %w(relationships))
expect(response_status).to eq(200), invalid_status_detail
end
end
get '/api/v2/background_batches/:id' do
doc_helper.insert_documentation_for(action: :show, context: self)
example doc_helper.title_for(:show), document: doc_helper.document_scope do
explanation doc_helper.description_for(:show)
do_request
check_resource(%w(relationships))
expect(response_status).to eq(200), invalid_status_detail
end
end
post '/api/v2/background_batches' do
doc_helper.insert_documentation_for(action: :create, context: self)
example doc_helper.title_for(:create), document: doc_helper.document_scope do
explanation doc_helper.description_for(:create)
do_request data: form_data
expect(response_status).to eq(201), invalid_status_detail
background_batch = BackgroundBatch.find_by(id: json_response['data']['id'])
expect(background_batch.requests.length).to eq(1)
end
end
delete '/api/v2/background_batches/:id' do
doc_helper.insert_documentation_for(action: :delete, context: self)
example doc_helper.title_for(:delete), document: doc_helper.document_scope do
explanation doc_helper.description_for(:delete)
do_request
expect(response_status).to eq(204), invalid_status_detail
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/deleted_record_spec.rb
|
require 'rails_helper'
RSpec.describe DeletedRecord, type: :model do
let(:account_list) { create(:account_list) }
let(:designation_account) { create(:designation_account) }
let(:contact) { create(:contact, account_list: account_list) }
let(:user) { create(:user_with_account) }
let!(:deleted_record) do
create(:deleted_record,
deleted_from_id: account_list.id,
deleted_from_type: account_list.class.name,
deleted_by: user,
deleted_at: Date.current - 1.day)
end
let!(:second_deleted_record) do
create(:deleted_record,
deleted_from_id: account_list.id,
deleted_from_type: account_list.class.name,
deleted_by: user,
deleted_at: Date.current - 3.days)
end
let!(:third_deleted_record) do
create(:deleted_donation_record,
deleted_from_id: designation_account.id,
deleted_from_type: designation_account.class.name,
deleted_by: user,
deleted_at: Date.current - 3.days)
end
context 'filter' do
it 'should filter account list ids' do
expect(DeletedRecord.account_list_ids(account_list.id)).to include(deleted_record)
expect(DeletedRecord.account_list_ids('1234-abce')).to_not include(deleted_record)
end
it 'should filter by designation account' do
expect(DeletedRecord.where(deleted_from_id: designation_account.id)).to include(third_deleted_record)
end
it 'should filter since date' do
expect(DeletedRecord.since_date(Date.current - 2.days)).to include(deleted_record)
expect(DeletedRecord.since_date(Date.current)).to_not include(deleted_record)
end
it 'should filter types' do
expect(DeletedRecord.types('Contact')).to include(deleted_record)
expect(DeletedRecord.types('Task')).to_not include(deleted_record)
end
it 'should filter with multiple filters' do
records = DeletedRecord.types('Contact').since_date(Date.today - 2.days)
expect(records).to include(deleted_record)
expect(records).to_not include(second_deleted_record)
expect(records.size).to eq(1)
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/coaching/contact_serializer.rb
|
class Coaching::ContactSerializer < ApplicationSerializer
attributes :late_at,
:locale,
:name,
:pledge_amount,
:pledge_currency,
:pledge_currency_symbol,
:pledge_frequency,
:pledge_received,
:pledge_start_date
delegate :total,
to: :contact_exhibit
def contact_exhibit
@exhibit ||= Coaching::ContactExhibit.new(object, nil)
end
end
|
chuckmersereau/api_practice
|
spec/lib/json_web_token/middleware_spec.rb
|
<gh_stars>0
require 'spec_helper'
require 'json_web_token'
require 'json_web_token/middleware'
describe JsonWebToken::Middleware do
let(:app) { MockRackApp.new }
let(:decode_callback) { -> (env) { env } }
subject { described_class.new(app, &decode_callback) }
it 'is a middleware' do
expect(subject).to respond_to(:call).with(1).argument
end
context 'during a request to a non api/v2 endpoint' do
before { make_request }
let(:request_env) { Rack::MockRequest.env_for('/api/v1/users') }
it 'does not modify the environment' do
expect(app.env).to eq(request_env)
end
end
context 'during a request to an api/v2 endpoint' do
# before { make_request }
let(:request_env) { Rack::MockRequest.env_for('/api/v2/users') }
context 'when there is no Authorization header present' do
it 'does not modify the environment' do
make_request
expect(app.env).to eq(request_env)
end
it 'does not fire the callback' do
expect(decode_callback).to_not receive(:call)
make_request
end
end
context 'when there is an Authorization header present' do
context 'and it contains an invalid JWT token' do
let(:request_env) { Rack::MockRequest.env_for('/api/v2/users', 'HTTP_AUTHORIZATION' => 'Bearer asdf') }
it 'does not modify the environment' do
make_request
expect(app.env).to eq(request_env)
end
it 'does not fire the callback' do
expect(decode_callback).to_not receive(:call)
make_request
end
end
context 'and it contains a valid JWT token' do
let(:jwt_payload) { { user_id: 'abc-123' } }
let(:jwt_token) { JsonWebToken.encode(jwt_payload) }
let(:request_env) { Rack::MockRequest.env_for('/api/v2/users', 'HTTP_AUTHORIZATION' => "Bearer #{jwt_token}") }
it 'adds the decoded jwt_token to the request env' do
make_request
expect(app.env).to have_key('auth.jwt_payload')
expect(app.env['auth.jwt_payload']).to match(jwt_payload)
end
it 'fires the callback' do
expect(decode_callback).to receive(:call).and_call_original
make_request
end
end
end
end
def make_request
subject.call(request_env)
end
end
class MockRackApp
attr_reader :env
def call(env)
@env = env
[200, { 'Content-Type' => 'text/plain' }, ['OK']]
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/reports/donor_currency_donations_controller.rb
|
<filename>app/controllers/api/v2/reports/donor_currency_donations_controller.rb
class Api::V2::Reports::DonorCurrencyDonationsController < Api::V2Controller
include Reportable
def show
load_report
authorize_report
render_report
end
private
def load_report
@report ||= ::Reports::DonorCurrencyDonations.new(report_params)
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/json_web_token_authentication.rb
|
module JsonWebTokenAuthentication
private
def jwt_authorize!
raise Exceptions::AuthenticationError unless user_id_in_token?
rescue JWT::VerificationError, JWT::DecodeError
raise Exceptions::AuthenticationError
end
# The check for user_uuid should be removed 30 days after the following PR is merged to master
# https://github.com/CruGlobal/mpdx_api/pull/993
def user_id_in_token?
http_token && jwt_payload && (jwt_payload['user_id'].present? || jwt_payload['user_uuid'].present?)
end
def http_token
return @http_token ||= auth_header.split(' ').last if auth_header.present?
return @http_token ||= params[:access_token] if params[:access_token]
end
def auth_header
request.headers['Authorization']
end
def jwt_payload
@jwt_payload ||= JsonWebToken.decode(http_token) if http_token
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180530134251_create_deleted_records.rb
|
class CreateDeletedRecords < ActiveRecord::Migration
def change
create_table :deleted_records, id: :uuid do |t|
t.uuid :account_list_id, null: false, index: true
t.uuid :deleted_by_id
t.datetime :deleted_on, null: false, index: true
t.uuid :deletable_id
t.string :deletable_type
t.timestamps null: false
end
add_index :deleted_records, [:deletable_id, :deletable_type]
end
end
|
chuckmersereau/api_practice
|
spec/controllers/auth/provider/google_accounts_controller_spec.rb
|
require 'rails_helper'
describe Auth::Provider::GoogleAccountsController, :auth, type: :controller do
routes { Auth::Engine.routes }
let(:user) { create(:user_with_account) }
before(:each) do
auth_login(user)
request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:google]
end
it 'should find or create a Google Account' do
expect(Person::GoogleAccount)
.to receive(:find_or_create_from_auth)
.with(OmniAuth.config.mock_auth[:google], user)
get :create
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/deleted_records_controller.rb
|
<gh_stars>0
class Api::V2::DeletedRecordsController < Api::V2Controller
def index
authorize_index
format_since_date
@deleted_records = filter_deleted_records.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
render json: @deleted_records.preload_valid_associations(include_associations),
meta: meta_hash(@deleted_records),
include: include_params,
fields: field_params
end
private
# The current filter will change a date to a datetime range, with the end date set to
# the end of the day, of the date, which will not work for a simple +since_date+. So,
# we'll do an early detection and put today's date as the end date, if needed.
def format_since_date
return unless params[:filter] && params[:filter][:since_date]
params[:filter][:since_date] += "..#{1.day.from_now.utc.iso8601}" unless params[:filter][:since_date].include?('..')
end
def filter_deleted_records
DeletedRecords::Filterer.new(filter_params).filter(scope: deleted_records_scope, account_lists: account_lists)
end
def deleted_records_scope
DeletedRecord.where(deleted_from_id: deleted_from_ids)
end
def deleted_from_ids
account_lists.map(&:id) + designation_account_ids
end
def designation_account_ids
@designation_account_ids ||= AccountListEntry.where(account_list_id: account_lists.map(&:id)).distinct.pluck(:designation_account_id)
end
def authorize_index
account_lists.each { |account_list| authorize(account_list, :show?) }
end
def permitted_filters
[:account_list_id, :since_date, :types]
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/donation_amount_recommendations_controller.rb
|
<gh_stars>0
class Api::V2::Contacts::DonationAmountRecommendationsController < Api::V2Controller
def index
authorize current_contact, :show?
load_donation_amount_recommendations
render json: @donation_amount_recommendations.preload_valid_associations(include_associations),
meta: meta_hash(@donation_amount_recommendations),
include: include_params,
fields: field_params
end
def show
load_donation_amount_recommendation
authorize_donation_amount_recommendation
render_donation_amount_recommendation
end
private
def current_contact
@current_contact ||= Contact.find(params[:contact_id])
end
def donation_amount_recommendation_scope
current_contact.donation_amount_recommendations
end
def authorize_donation_amount_recommendation
authorize @donation_amount_recommendation
end
def load_donation_amount_recommendation
@donation_amount_recommendation ||= donation_amount_recommendation_scope.find(params[:id])
end
def load_donation_amount_recommendations
@donation_amount_recommendations = donation_amount_recommendation_scope.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def render_donation_amount_recommendation
render json: @donation_amount_recommendation,
status: success_status,
include: include_params,
fields: field_params
end
def pundit_user
PunditContext.new(current_user, contact: current_contact)
end
def default_sort_param
DonationAmountRecommendation.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
app/services/contact_merge.rb
|
<gh_stars>0
class ContactMerge
def initialize(winner, loser)
@winner = winner
@other = loser
end
def merge
begin
Contact.find(@winner.id)
Contact.find(@other.id)
rescue ActiveRecord::RecordNotFound
return
end
merge_contacts
delete_losing_contact
begin
@winner.reload
rescue ActiveRecord::RecordNotFound
return
end
fixup_winning_contact
end
def self.merged_send_newsletter(winner, other)
return 'Both' if winner == 'Both' || other == 'Both'
send_newsletter_word(winner == 'Email' || other == 'Email',
winner == 'Physical' || other == 'Physical')
end
def self.send_newsletter_word(email, physical)
if email && physical
'Both'
elsif email
'Email'
elsif physical
'Physical'
end
end
private
def merge_contacts
Contact.transaction(requires_new: true) do
# Update related records
@other.messages.update_all(contact_id: @winner.id)
@other.contact_people.each do |r|
next if @winner.contact_people.find_by(person_id: r.person_id)
r.update_attributes(contact_id: @winner.id)
end
@other.contact_donor_accounts.each do |other_contact_donor_account|
other_account_number = other_contact_donor_account.donor_account.account_number
next if @winner.donor_accounts.map(&:account_number).include?(other_account_number)
other_contact_donor_account.update_column(:contact_id, @winner.id)
end
@other.activity_contacts.each do |other_activity_contact|
next if @winner.activities.map(&:subject).include?(other_activity_contact.activity.subject)
other_activity_contact.update_column(:contact_id, @winner.id)
end
@winner.update_uncompleted_tasks_count
@other.addresses.each do |other_address|
next if @winner.addresses.find { |address| address.equal_to? other_address }
other_address.update_columns(
primary_mailing_address: false,
addressable_id: @winner.id
)
end
merge_appeals_and_pledges
@other.notifications.update_all(contact_id: @winner.id)
@winner.merge_addresses
ContactReferral.where(referred_to_id: @other.id).find_each do |contact_referral|
unless @winner.contact_referrals_to_me.find_by(referred_by_id: contact_referral.referred_by_id)
contact_referral.update_column(:referred_to_id, @winner.id)
end
end
ContactReferral.where(referred_by_id: @other.id).update_all(referred_by_id: @winner.id)
# Copy fields over updating any field that's blank on the winner
Contact::MERGE_COPY_ATTRIBUTES.each do |field|
next unless @winner[field].blank? && @other[field].present?
@winner.send("#{field}=".to_sym, @other[field])
end
@winner.send_newsletter = self.class.merged_send_newsletter(@winner.send_newsletter,
@other.send_newsletter)
# If one of these is marked as a finanical partner, we want that status
if @winner.status != 'Partner - Financial' && @other.status == 'Partner - Financial'
@winner.status = 'Partner - Financial'
end
# Make sure first and last donation dates are correct
if @winner.first_donation_date &&
@other.first_donation_date &&
@winner.first_donation_date > @other.first_donation_date
@winner.first_donation_date = @other.first_donation_date
end
if @winner.last_donation_date &&
@other.last_donation_date &&
@winner.last_donation_date < @other.last_donation_date
@winner.last_donation_date = @other.last_donation_date
end
@winner.notes = [@winner.notes, @other.notes].compact.join("\n").strip if @other.notes.present?
@winner.tag_list += @other.tag_list
@winner.save(validate: false)
end
end
def merge_appeals_and_pledges
@other.appeal_contacts.each do |appeal_contact|
next if @winner.appeal_contacts.find { |ac| ac.appeal_id == appeal_contact.appeal_id }
appeal_contact.update_columns(contact_id: @winner.id)
end
@other.pledges.each do |other_pledge|
winner_match = @winner.pledges.find { |pledge| pledge.appeal_id == other_pledge.appeal_id }
if winner_match
winner_match.merge(other_pledge)
else
other_pledge.update_columns(contact_id: @winner.id)
end
end
end
def delete_losing_contact
DuplicateRecordPair.type('Contact').where(record_one_id: ids, record_two_id: ids).first&.destroy
@other.reload
@other.destroy
rescue ActiveRecord::RecordNotFound
end
def fixup_winning_contact
@winner.merge_people
@winner.merge_donor_accounts
# Update donation total after donor account ids are all assigned correctly
@winner.update_all_donation_totals
end
def ids
[@winner.id, @other.id]
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180202024130_change_foreign_keys_to_uuid.rb
|
class ChangeForeignKeysToUuid < ActiveRecord::Migration
def up
fix_uuid_columns
remove_foreign_key_constraints
find_indexes
migrate_foreign_keys
convert_primary_keys_to_uuids
save_indexes
readd_foreign_key_constraints
end
def fix_uuid_columns
add_column :export_logs, :uuid, :uuid, null: false, default: 'uuid_generate_v4()'
add_index :export_logs, :uuid, unique: true
add_column :account_list_coaches, :uuid, :uuid, null: false, default: 'uuid_generate_v4()'
add_index :account_list_coaches, :uuid, unique: true
tables_for_uuid_fill = %w(activities activity_comments activity_contacts appeal_contacts appeal_excluded_appeal_contacts)
tables_for_uuid_fill.each do |table_name|
execute "UPDATE #{table_name} SET uuid = uuid_generate_v4() WHERE uuid IS NULL;"
end
end
def find_indexes
@indexes = quiet_execute "select * from pg_indexes where schemaname = 'public'"
end
def migrate_foreign_keys
foreign_keys = CSV.read(Rails.root.join('db','foriegn_key_to_class_map.csv'))
keys_grouped_by_table = foreign_keys.group_by { |fk| fk[0] }
create_temp_tables
# make sure tmp'ed table has it's rows copied over
query_duplicated_table_names.each { |table_name| keys_grouped_by_table[table_name] ||= [] }
keys_grouped_by_table.each do |table_name, group|
copy_rows(table_name, group)
end
end
def create_temp_tables
temp_table_file = Rails.root.join('db','create_temp_tables.sql')
sql = File.open(temp_table_file) { |file| file.read }
execute sql
end
def drop_indexes_for(table_name)
@indexes.each do |index_row|
next unless index_row['tablename'] == table_name
next if index_row['indexname'].ends_with?('_pkey')
execute "DROP INDEX IF EXISTS #{index_row['indexname']}"
end
end
def copy_rows(table_name, foreign_keys_list)
# if foreign relation is polymorphic, we have to do some more complicated work.
poly_relation = foreign_keys_list.find { |fk| fk[2] == 'Poly' }
if table_name == 'imports'
imports_uuid_convert(table_name, foreign_keys_list)
elsif poly_relation
relation_name = poly_relation[1].sub(/_id$/, '')
poly_id_to_uuid(table_name, relation_name, foreign_keys_list)
else
execute_row_load(table_name, foreign_keys_list)
end
end
def poly_id_to_uuid(table_name, relation_name, foreign_keys)
foreign_tables = quiet_execute("SELECT DISTINCT #{relation_name}_type as type from #{table_name} where #{relation_name}_type is not null")
foreign_tables.each do |foreign_table_row|
poly_class = foreign_table_row['type']
next unless poly_class.present?
execute_row_load(table_name, foreign_keys, poly_class)
end
end
def imports_uuid_convert(table_name, foreign_keys)
foreign_tables = quiet_execute("SELECT DISTINCT source as type from #{table_name} where source is not null")
foreign_tables.each do |foreign_table_row|
poly_class = foreign_table_row['type']
next unless poly_class.present?
execute_row_load(table_name, foreign_keys, poly_class)
end
end
def execute_row_load(table_name, foreign_keys, poly_class = nil)
join_list = {}
foreign_keys.each do |fk|
foreign_class = fk[2] == 'Poly' ? poly_class : fk[2]
join_list[fk[1]] = {
foreign_table_name: table_name(foreign_class),
alias: "#{fk[1]}_table",
join_type: fk[3] == 'drop' ? 'INNER' : 'LEFT OUTER'
}
end
columns_query = "SELECT column_name FROM information_schema.columns where table_name = '#{table_name}'"
columns = quiet_execute(columns_query).collect { |r| r['column_name'] } - ['uuid']
select_columns = columns.map do |col|
next "#{table_name}.uuid as id" if col == 'id'
next "#{table_name}.#{col}" unless join_list[col]
"#{join_list[col][:alias]}.uuid as #{col}"
end
select_columns = select_columns.join(', ')
where_clause = ''
if poly_class
poly_foreign_key = foreign_keys.find { |fk| fk[2] == 'Poly'}
where_clause = "WHERE #{table_name}.#{poly_type_field(poly_foreign_key[1])} = '#{poly_class}'"
end
joins_list = join_list.map do |col, info|
"#{info[:join_type]} JOIN #{info[:foreign_table_name]} #{info[:alias]} on #{table_name}.#{col} = #{info[:alias]}.id"
end.join(' ')
query = "INSERT INTO tmp_#{table_name}(\"#{columns.join('","')}\") ("\
"SELECT #{select_columns} FROM #{table_name} "\
"#{joins_list} "\
"#{where_clause}"\
")"
execute query
end
def poly_type_field(poly_foreign_key)
return 'source' if poly_foreign_key == 'source_account_id'
poly_foreign_key.sub(/_id$/, '_type')
end
def table_name(string)
return 'addresses' if string == 'Addressable'
return Person.const_get(string).table_name if string.starts_with? 'Person::'
return Person::OrganizationAccount.table_name if string == 'tnt_data_sync'
# any tnt or csv imports don't have source_account_id, so it doesn't matter what table it's joined to
return Person.table_name if %w(tnt csv).include? string
return "person_#{string}_accounts" if %w(google facebook).include? string
string.classify.constantize.table_name
end
def try_class(string)
return Person.const_get(string) if string.starts_with? 'Person::'
string.classify.constantize
rescue NameError
nil
end
private
def convert_primary_keys_to_uuids
query_duplicated_table_names.each do |good_name|
table = "tmp_#{good_name}"
execute "DROP TABLE #{good_name};"
execute "ALTER TABLE #{table} RENAME TO #{good_name};"
execute "ALTER TABLE #{good_name} ADD PRIMARY KEY (id);"
end
end
def remove_foreign_key_constraints
remove_foreign_key :appeal_excluded_appeal_contacts, :contacts
remove_foreign_key :appeal_excluded_appeal_contacts, :appeals
remove_foreign_key :background_batch_requests, :background_batches
remove_foreign_key :background_batches, :users
remove_foreign_key :donation_amount_recommendations, :donor_accounts
remove_foreign_key :donation_amount_recommendations, :designation_accounts
remove_foreign_key :master_person_sources, :master_people
remove_foreign_key :notification_preferences, :users
remove_foreign_key :people, :master_people
end
def readd_foreign_key_constraints
add_foreign_key :appeal_excluded_appeal_contacts, :contacts, dependent: :delete
add_foreign_key :appeal_excluded_appeal_contacts, :appeals, dependent: :delete
add_foreign_key :background_batch_requests, :background_batches
add_foreign_key :background_batches, :people, column: :user_id
add_foreign_key :donation_amount_recommendations, :donor_accounts, dependent: :nullify
add_foreign_key :donation_amount_recommendations, :designation_accounts, dependent: :nullify
add_foreign_key :master_person_sources, :master_people
add_foreign_key :notification_preferences, :people, dependent: :delete, column: :user_id
add_foreign_key :people, :master_people, dependent: :restrict
end
def save_indexes
CSV.open(Rails.root.join('db','dropped_indexes.csv'), 'wb') do |csv|
csv << @indexes.fields
@indexes = @indexes.each do |index_row|
next if index_row['indexname'].ends_with?('_pkey') ||
index_row['indexdef'].ends_with?(' (uuid)') ||
%w(active_admin_comments admin_users schema_migrations versions).include?(index_row['tablename'])
# execute index_row['indexdef']
csv << index_row.values
end
end
end
def query_duplicated_table_names
tables_sql = "SELECT DISTINCT table_name
FROM information_schema.columns
WHERE table_schema = 'public'
and table_name LIKE 'tmp_%'"
quiet_execute(tables_sql).collect { |row| row['table_name'].sub('tmp_', '') }
end
def quiet_execute(query)
ActiveRecord::Base.connection.execute(query)
end
end
|
chuckmersereau/api_practice
|
spec/services/cas_ticket_validator_service_spec.rb
|
require 'rails_helper'
RSpec.describe CasTicketValidatorService, type: :service do
let!(:service) do
described_class.new(ticket: 'ST-314971-9fjrd0HfOINCehJ5TKXX-cas2a', service: 'http://my.service')
end
after do
ENV['CAS_BASE_URL'] = 'https://stage.thekey.me/cas'
end
describe '#initialize' do
it 'initializes attributes successfully' do
service = described_class.new(ticket: 'test-ticket', service: 'http://my.service')
expect(service.ticket).to eq('test-ticket')
expect(service.service).to eq('http://my.service')
end
end
context 'invalid ticket' do
before do
stub_request(
:get,
"#{ENV['CAS_BASE_URL']}/p3/serviceValidate?"\
'service=http://my.service&ticket=ST-314971-9fjrd0HfOINCehJ5TKXX-cas2a'
).to_return(
status: 200,
body: File.open(
Rails.root.join('spec', 'fixtures', 'cas', 'invalid_ticket_validation_response_body.xml')
).read
)
end
describe '#validate' do
it 'raises an authentication error with a message' do
expect { service.validate }.to(
raise_error(
Exceptions::AuthenticationError,
"INVALID_TICKET: Ticket 'ST-314971-9fjrd0HfOINCehJ5TKXX-cas2a' not recognized"
)
)
end
end
describe '#attribute' do
it 'does not return sso guid' do
expect(service.attribute('ssoGuid')).to be_nil
end
end
end
context 'valid ticket' do
before do
stub_request(
:get,
"#{ENV['CAS_BASE_URL']}/p3/serviceValidate?"\
'service=http://my.service&ticket=ST-314971-9fjrd0HfOINCehJ5TKXX-cas2a'
).to_return(
status: 200,
body: File.open(
Rails.root.join('spec', 'fixtures', 'cas', 'successful_ticket_validation_response_body.xml')
).read
)
end
describe '#validate' do
it 'does not raise any error' do
expect { service.validate }.to_not raise_error
end
it 'returns true' do
expect(service.validate).to eq true
end
end
describe '#attribute' do
it 'returns the sso guid of the validated user' do
expect(service.attribute('ssoGuid')).to eq 'B163530-7372-551R-KO83-1FR05534129F'
end
it 'returns nil if the attribute does not exist' do
expect(service.attribute('wut')).to be_nil
end
end
describe '#attributes' do
it 'returns attributes from the CAS response with normalized keys' do
expected_hash = {
authenticationDate: 'Tue Jan 24 19:84:25 UTC 2017',
email: '<EMAIL>',
firstName: 'Cas',
isFromNewLogin: 'true',
lastName: 'User',
longTermAuthenticationRequestTokenUsed: 'false',
relayGuid: 'B163530-7372-551R-KO83-1FR05534129F',
ssoGuid: 'B163530-7372-551R-KO83-1FR05534129F',
theKeyGuid: 'B163530-7372-551R-KO83-1FR05534129F'
}
expect(service.attributes).to eq expected_hash
end
end
end
describe 'depends on CAS_BASE_URL environment variable' do
it 'raises an error if the variable is not present' do
ENV['CAS_BASE_URL'] = nil
expect { service.validate }.to(
raise_error(
RuntimeError,
'expected CAS_BASE_URL environment variable to be present and using https'
)
)
end
it 'raises an error if the url is not secure' do
ENV['CAS_BASE_URL'] = 'http://stage.thekey.me/cas'
expect { service.validate }.to(
raise_error(
RuntimeError,
'expected CAS_BASE_URL environment variable to be present and using https'
)
)
end
end
end
|
chuckmersereau/api_practice
|
spec/mailers/chalkline_mailer_spec.rb
|
require 'rails_helper'
describe ChalklineMailer do
describe 'email' do
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact, account_list: account_list) }
it 'pulls in the newsletter list, and users name and emails from account list' do
expect(account_list).to receive(:users_combined_name).and_return('John and <NAME>')
expect(account_list).to receive(:user_emails_with_names).and_return(['<EMAIL>', '<EMAIL>'])
expect(CsvExport).to receive(:mailing_addresses).with(account_list.contacts).and_return("a,b\n1,2\n")
time = Time.new(2013, 3, 15, 18, 35, 20).getlocal
expect(Time).to receive(:now).at_least(:once).and_return(time)
expect(time).to receive(:in_time_zone).with(ChalklineMailer::TIME_ZONE).and_return(time)
email = ChalklineMailer.mailing_list(account_list)
expect(email.subject).to eq('MPDX List: <NAME> <NAME>')
expect(email.cc).to eq(['<EMAIL>', '<EMAIL>'])
expect(email.reply_to).to eq(['<EMAIL>', '<EMAIL>'])
expect(email.attachments.size).to eq(1)
expect(email.attachments.first.filename).to eq('john_and_jane_doe_20130315_635pm.csv')
expect(email.attachments.first.mime_type).to eq('text/csv')
expect(email.attachments.first.body).to eq("a,b\n1,2\n")
end
end
end
|
chuckmersereau/api_practice
|
spec/mailers/previews/notification_mailer_preview.rb
|
<gh_stars>0
class NotificationMailerPreview < ApplicationPreview
def notify
type = NotificationType::SpecialGift.first
contact = Contact.first || Contact.new(name: '<NAME>')
contact.name = '<h3>asdf</h3>'
donation = Donation.new(amount: '20',
donation_date: Date.yesterday,
designation_account: contact.account_list.designation_accounts.first)
notification = Notification.new(notification_type: type, contact: contact,
event_date: DateTime.current, donation: donation)
NotificationMailer.notify(user, type => [notification])
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: :contacts)
let(:resource_type) { 'contacts' }
let!(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:contact) { create(:contact, account_list: account_list) }
let(:id) { contact.id }
let(:new_contact) do
attributes_for(:contact)
.except(
:first_donation_date,
:last_activity,
:last_appointment,
:last_donation_date,
:last_letter,
:last_phone_call,
:last_pre_call,
:last_thank,
:late_at,
:notes_saved_at,
:pls_id,
:prayer_letters_id,
:prayer_letters_params,
:tnt_id,
:total_donations,
:uncompleted_tasks_count
).merge(overwrite: true)
end
let(:form_data) do
build_data(new_contact, relationships: relationships)
end
let(:relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: account_list.id
}
}
}
end
let(:additional_keys) { ['relationships'] }
let(:resource_attributes) do
%w(
avatar
church_name
created_at
deceased
direct_deposit
envelope_greeting
greeting
last_activity
last_appointment
last_donation
last_letter
last_phone_call
last_pre_call
last_thank
late_at
likely_to_give
locale
magazine
name
next_ask
no_appeals
no_gift_aid
notes
notes_saved_at
pledge_amount
pledge_currency
pledge_currency_symbol
pledge_frequency
pledge_received
pledge_start_date
send_newsletter
square_avatar
status
status_valid
suggested_changes
tag_list
timezone
uncompleted_tasks_count
updated_at
updated_in_db_at
website
)
end
let(:resource_associations) do
%w(
account_list
addresses
appeals
contact_referrals_by_me
contact_referrals_to_me
contacts_referred_by_me
contacts_that_referred_me
donation_amount_recommendations
donor_accounts
last_six_donations
people
primary_or_first_person
primary_person
spouse
tasks
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/contacts' do
doc_helper.insert_documentation_for(action: :index, context: self)
with_options scope: :sort do
parameter :created_at, 'Sort By CreatedAt'
parameter :name, 'Sort By Name'
parameter :updated_at, 'Sort By UpdatedAt'
end
parameter 'filter', 'Filter the list of returned contacts. Any filter '\
'can be reversed by adding reverse_FILTER_NAME_HERE = true'
[
any_filters: 'If set to true any result where at least one of the filters apply will be returned',
reverse_FILTER_NAME: "If set to true, the filter defined as FILTER_NAME will return results that don't apply",
account_list_id: 'Filter by Account List; Accepts Account List ID',
address_historic: 'Filter by Address Historic; Accepts values "true", or "false"',
address_valid: %(Filter by Address Invalid; A Contact's Address is invalid if \
the Address's valid attribute is set to false, or if the Contact has \
multiple Addresses marked as primary; Accepts value "false"),
appeal: 'Filter by Appeal; Accepts multiple parameters, with value "no_appeals", or an appeal ID',
church: 'Filter by Church; Accepts multiple parameters, with value "none", or a church name',
city: 'Filter by City; Accepts multiple parameters, with value "none", or a city name',
contact_info_addr: 'Filter by Address; Accepts values "Yes", or "No"',
contact_info_email: 'Filter by Email; Accepts values "Yes", or "No"',
contact_info_facebook: 'Filter by Facebook Profile; Accepts values "Yes", or "No"',
contact_info_mobile: 'Filter by Mobile Phone; Accepts values "Yes", or "No"',
contact_info_phone: 'Filter by Home Phone; Accepts values "Yes", or "No"',
contact_info_work_phone: 'Filter by Work Phone; Accepts values "Yes", or "No"',
contact_type: 'Filter by Type; Accepts multiple parameters, with values "person", and "company"',
country: 'Filter by Country; Accepts multiple parameters, with values "none", or a country',
donation: 'Filter by Gift Options; Accepts multiple parameters, with values "none", "one", "first", and "last"',
donation_amount: 'Filter by Exact Gift Amount; Accepts multiple parameters, with values like "9.99"',
'donation_amount_range:min' => 'Filter by Gift Amount Range, Minimum; Accepts values like "9.99"',
'donation_amount_range:max' => 'Filter by Gift Amount Range, Maximum; Accepts values like "9.99"',
donation_date: 'Filter by Gift Date; Accepts date range with text value like "YYY-MM-DD..YYYY-MM-DD"',
gave_more_than_pledged_range: 'Will return contacts that have given more than pledged within a date range.
Accepts date range with text value like "MM/DD/YYYY - MM/DD/YYYY"',
likely: 'Filter by Likely To Give; Accepts multiple parameters, with values '\
'"none", "Least Likely", "Likely", and "Most Likely"',
locale: 'Filter by Language; Accepts multiple parameters,',
metro_area: 'Filter by Metro Area; Accepts multiple parameters, with values "none", or a metro area name',
newsletter: 'Filter by Newsletter Recipients; Accepts values "none", "all", "address", "email", and "both"',
no_appeals: 'Filter by Due Date; Pass the value "true" if the '\
'contacts do not wish to be contacted for appeals.',
pledge_amount: 'Filter by Commitment Amount; Accepts multiple parameters, with values like "100.0"',
pledge_amount_increased_range: 'Will return contacts that have increased their pledge within the time range. '\
'Accepts date range with text value like "YYY-MM-DD..YYYY-MM-DD"',
pledge_currency: 'Filter by Commitment Currency; Accepts multiple parameters, with values like "USD"',
pledge_frequencies: 'Filter by Commitment Frequency; Accepts multiple parameters, with '\
'numeric values like "0.23076923076923" (Weekly), '\
'"0.46153846153846" (Every 2 Weeks), "1.0" (Monthly), '\
'"2.0" (Every 2 Months), "3.0", "4.0", "6.0", "12.0" (Yearly), '\
'and "24.0" (Every 2 Years)',
pledge_late_by: 'Filter by Late By; Accepts values "", "0_30" (Less than 30 days late), '\
'"30_60" (More than 30 days late), "60_90" (More than 60 days late), or '\
'"90" (More than 90 days late)',
pledge_received: 'Filter by Commitment Received; Accepts values "true", or "false"',
referrer: 'Filter by Referrer; Accepts multiple parameters, with values "none", "any", or a Contact ID',
region: 'Filter by Region; Accepts multiple parameters, with values "none", or a region name',
related_task_action: 'Filter by Action; Accepts multiple parameters, '\
'with values "none", or an activity type like "Call"',
state: 'Filter by State; Accepts multiple parameters, with values "none", or a state',
status: 'Filter by Status; Accepts multiple parameters, with values "active", "hidden", "null", '\
'"Never Contacted", "Ask in Future", "Cultivate Relationship", "Contact for Appointment", '\
'"Appointment Scheduled", "Call for Decision", "Partner - Financial", "Partner - Special", '\
'"Partner - Pray", "Not Interested", "Unresponsive", '\
'"Never Ask", "Research Abandoned", and "Expired Referral"',
status_valid: 'Filter by Status Valid; Accepts values "true", or "false"',
started_giving_range: 'Will return contacts that have started giving within the date range;'\
'Accepts date range with text value like "YYY-MM-DD..YYYY-MM-DD"',
stopped_giving_range: 'Will return contacts that have stopped giving during the date range;'\
'Note that for this filter to work the end date must be more than 1 month ago.'\
'Accepts date range with text value like "YYY-MM-DD..YYYY-MM-DD"',
tasks_all_completed: 'Return contacts that have no incomplete tasks if given the value "true"',
task_due_date: 'Filter by Due Date; Accepts date range with text value like "YYY-MM-DD..YYYY-MM-DD"',
timezone: 'Filter by Timezone; Accepts multiple parameters,',
wildcard_search: 'Filter by keyword, searches through name, notes, donor account numbers, '\
'email_addresses, phone_numbers and people names'
].each { |field, description| parameter "filter[#{field}]", description, required: false }
response_field :data, 'Data', 'Type' => 'Array[Object]'
example doc_helper.title_for(:index), document: doc_helper.document_scope do
explanation doc_helper.description_for(:index)
do_request
expect(response_status).to eq(200), invalid_status_detail
check_collection_resource(1, additional_keys)
end
end
let(:additional_attributes) { %w(lifetime_donations) }
get '/api/v2/contacts/:id' do
doc_helper.insert_documentation_for(action: :show, context: self)
with_options scope: :relationships do
response_field :primary_person, 'Primary Person Object', 'Type' => 'Object'
response_field :primary_or_first_person, 'Primary Or First Person', 'Type' => 'Object'
response_field :spouse, 'Spouse Person Object', 'Type' => 'Object'
end
example doc_helper.title_for(:show), document: doc_helper.document_scope do
explanation doc_helper.description_for(:show)
do_request
check_resource(additional_keys, additional_attributes)
expect(resource_object['name']).to eq contact.name
expect(response_status).to eq 200
end
end
post '/api/v2/contacts' do
doc_helper.insert_documentation_for(action: :create, context: self)
example doc_helper.title_for(:create), document: doc_helper.document_scope do
explanation doc_helper.description_for(:create)
do_request data: form_data
expect(response_status).to eq(201), invalid_status_detail
expect(resource_object['name']).to eq new_contact[:name]
end
end
put '/api/v2/contacts/:id' do
doc_helper.insert_documentation_for(action: :update, context: self)
example doc_helper.title_for(:update), document: doc_helper.document_scope do
explanation doc_helper.description_for(:update)
do_request data: form_data
expect(response_status).to eq(200), invalid_status_detail
expect(resource_object['name']).to eq new_contact[:name]
end
end
delete '/api/v2/contacts/:id' do
doc_helper.insert_documentation_for(action: :delete, context: self)
example doc_helper.title_for(:delete), document: doc_helper.document_scope do
explanation doc_helper.description_for(:delete)
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
config/initializers/carrier_wave.rb
|
<reponame>chuckmersereau/api_practice<filename>config/initializers/carrier_wave.rb
if Rails.env.development? || Rails.env.test? || Rails.env.cucumber?
CarrierWave.configure do |config|
config.storage = :file
# config.enable_processing = false
end
else
CarrierWave.configure do |config|
config.fog_credentials = {
provider: 'AWS', # required
aws_access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'), # required
aws_secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY') # required
}
config.fog_directory = ENV.fetch('AWS_BUCKET') # required
config.fog_public = false # optional, defaults to true
config.fog_attributes = { 'x-amz-storage-class' => 'REDUCED_REDUNDANCY' }
config.fog_authenticated_url_expiration = 1.day
config.storage :fog
end
end
|
chuckmersereau/api_practice
|
app/services/appeal_contact/filter/pledged_to_appeal.rb
|
class AppealContact::Filter::PledgedToAppeal < AppealContact::Filter::Base
def execute_query(appeal_contacts, filters)
appeal_contacts_with_pledges = appeal_contacts.joins(contact: :pledges)
.where(pledges: { appeal_id: filters[:appeal_id] })
.pluck(:id)
if cast_bool_value(filters[:pledged_to_appeal])
appeal_contacts.where(id: appeal_contacts_with_pledges)
else
appeal_contacts.where.not(id: appeal_contacts_with_pledges)
end
end
private
def valid_filters?(filters)
return false unless filters[:appeal_id]
filter_value = cast_bool_value(filters[name])
[true, false].include? filter_value
end
end
|
chuckmersereau/api_practice
|
spec/models/donation_amount_recommendation/remote_spec.rb
|
require 'rails_helper'
RSpec.describe DonationAmountRecommendation::Remote, type: :model do
let(:organization) { create(:organization) }
let(:designation_account) { create(:designation_account, organization: organization) }
let(:donor_account) { create(:donor_account, organization: organization) }
subject do
create(
:donation_amount_recommendation_remote,
organization: organization,
designation_number: designation_account.designation_number,
donor_number: donor_account.account_number
)
end
it { is_expected.to belong_to(:organization) }
describe '#designation_account' do
it 'should retrieve designation_account' do
expect(subject.designation_account).to eq designation_account
end
context 'designation_number is nil' do
before { subject.designation_number = nil }
it 'should return nil' do
expect(subject.designation_account).to be_nil
end
end
context 'designation_number is non existent' do
before { subject.designation_number = '123' }
it 'should return nil' do
expect(subject.designation_account).to be_nil
end
end
context 'organization is nil' do
before { subject.organization = nil }
it 'should return nil' do
expect(subject.designation_account).to be_nil
end
end
end
describe '#donor_account' do
it 'should retrieve donor_account' do
expect(subject.donor_account).to eq donor_account
end
context 'donor_number is nil' do
before { subject.donor_number = nil }
it 'should return nil' do
expect(subject.donor_account).to be_nil
end
end
context 'donor_number is non existent' do
before { subject.donor_number = '123' }
it 'should return nil' do
expect(subject.donor_account).to be_nil
end
end
context 'organization is nil' do
before { subject.organization = nil }
it 'should return nil' do
expect(subject.designation_account).to be_nil
end
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/google_events.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
FactoryBot.define do
factory :google_event do
association :activity
association :google_integration
google_event_id 'MyString'
calendar_id 'cal1'
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/contact_import_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe TntImport::ContactImport do
include TntImportHelpers
def load_yaml_row(filename)
YAML.safe_load(File.new(Rails.root.join("spec/fixtures/tnt/#{filename}.yaml")).read)
end
def shared_attributes_options
@shared_attributes_options ||= []
end
let(:file) { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export.xml')) }
let(:tnt_import) { create(:tnt_import, override: true, file: file) }
let(:xml) { TntImport::XmlReader.new(tnt_import).parsed_xml }
let(:contact_rows) { xml.tables['Contact'] }
let(:tags) { %w(tag1 tag2) }
let(:import) do
donor_accounts = []
TntImport::ContactImport.new(tnt_import, tags, donor_accounts, xml)
end
before { stub_smarty_streets }
describe '#update_contact' do
let(:contact) { create(:contact, notes: 'Another note') }
let(:expected_note) do
"Principal\nHas run into issues with <NAME>. \n \nChildren: Mark and Robert " \
"\n \nUser Status: Custom user status \n \nCategories: Custom category one, Category two " \
"\n \nInterests: Working Out, Bowling, Solving Crimes \n \nSpouse Interests: HelensInterests " \
"\n \nNickname: BobsNickname \n \nSpouse Nickname: Helen's Nickname"
end
it 'updates notes correctly' do
contact = Contact.new
import.send(:update_contact, contact, contact_rows.first)
expect(contact.notes).to eq(expected_note)
end
it 'doesnt add the children and tnt notes twice to notes' do
contact = Contact.new
import.send(:update_contact, contact, contact_rows.first)
import.send(:update_contact, contact, contact_rows.first)
expect(contact.notes).to eq(expected_note)
end
it 'updates newsletter preferences correctly' do
import.send(:update_contact, contact, contact_rows.first)
expect(contact.send_newsletter).to eq('Physical')
end
it 'sets the address region' do
import.send(:update_contact, contact, contact_rows.first)
expect(contact.addresses.first.region).to eq('State College')
end
it 'creates a duplicate address if original is not from TntImport' do
import.send(:update_contact, contact, contact_rows.first)
contact.addresses.first.update!(source: 'Something Else')
import.send(:update_contact, contact, contact_rows.first)
expect(contact.addresses.count).to eq 2
expect(contact.addresses.first.source).to eq 'Something Else'
expect(contact.addresses.second.source).to eq 'TntImport'
end
it 'sets the greeting' do
greeting = import.import_contact(tnt_import_parsed_xml_sample_contact_row).greeting
expect(greeting).to eq 'Parr Custom Greeting'
end
it 'sets the envelope_greeting' do
row = tnt_import_parsed_xml_sample_contact_row
envelope_greeting = import.import_contact(row).envelope_greeting
expect(envelope_greeting).to eq 'Parr Custom Fullname'
row['MailingAddressBlock'] = ''
row['FullName'] = 'My Special Full Name'
envelope_greeting = import.import_contact(row).envelope_greeting
expect(envelope_greeting).to eq 'My Special Full Name'
end
it 'sets is_organization' do
row = tnt_import_parsed_xml_sample_contact_row
expect(import.import_contact(row).is_organization).to eq false
row['IsOrganization'] = 'true'
expect(import.import_contact(row).is_organization).to eq true
end
context 'has social web fields' do
let(:file) { File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml')) }
it 'adds unsupported social fields to the contact notes' do
notes = import.import_contact(tnt_import_parsed_xml_sample_contact_row).notes
expect(notes).to include('Other Social: bob-other-social')
expect(notes).to include('Spouse Other Social: @helenothersocial')
expect(notes).to include('Voice/Skype: bobparrskype')
expect(notes).to include('Spouse Voice/Skype: HelenParrSkype')
expect(notes).to include('IM Address: bobsIMaddress')
expect(notes).to include('Spouse IM Address: helenIMaddress')
end
end
context 'has newsletter language field' do
let(:file) { File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml')) }
it 'adds supported language to contact field' do
# language in xml is French
contact = import.import_contact(tnt_import_parsed_xml_sample_contact_row)
expect(contact.locale).to eq 'fr'
end
it 'adds unsupported language to the contact notes' do
# language spoken in Wakanda
xml.find('NewsletterLang', '557339175')['Description'] = 'Xhosa'
tags_list = import.import_contact(tnt_import_parsed_xml_sample_contact_row).tag_list
expect(tags_list).to include('xhosa')
end
end
context 'importing send_newsletter' do
it 'supports overriding' do
row = tnt_import_parsed_xml_sample_contact_row
tnt_import.override = false
import = TntImport::ContactImport.new(tnt_import, tags, [], xml)
expect(import.import_contact(row).send_newsletter).to eq('Both')
row['SendNewsletter'] = 'false'
expect(import.import_contact(row).send_newsletter).to eq('Both')
tnt_import.override = true
import = TntImport::ContactImport.new(tnt_import, tags, [], xml)
expect(import.import_contact(row).send_newsletter).to eq('None')
end
end
end
it 'does not cause an error and increases contact count for case with first email not preferred' do
row = load_yaml_row(:tnt_row_multi_email)
expect { import.send(:import_contact, row) }.to change(Contact, :count).by(1)
end
it 'does not cause an error if phone is invalid and person has email' do
account_list = create(:account_list)
tnt_import = double(user: build(:user), account_list: account_list,
override?: true)
import = TntImport::ContactImport.new(tnt_import, [], [], xml)
row = load_yaml_row(:bad_phone_valid_email_row)
expect do
import.import_contact(row)
end.to change(Contact, :count).by(1)
contact = Contact.last
expect(contact.people.count).to eq 1
person = contact.people.first
expect(person.phone_numbers.count).to eq 1
expect(person.phone_numbers.first.number).to eq '(UNLISTED) call office'
expect(person.email_addresses.count).to eq 1
expect(person.email_addresses.first.email).to eq '<EMAIL>'
end
it 'ignores negative PledgeFrequencyID' do
row = contact_rows.first
row['PledgeFrequencyID'] = -11
tnt_import.override = true
import.import_contact(row)
expect(Contact.last.pledge_frequency).to eq nil
end
it 'ignores a zero PledgeFrequencyID' do
row = contact_rows.first
row['PledgeFrequencyID'] = 0
tnt_import.override = true
import.import_contact(row)
expect(Contact.last.pledge_frequency).to eq nil
end
it 'imports given tags' do
expected_tags = tags + ['new tag; other tag']
tags << 'new tag, other tag'
row = contact_rows.first
expect(import.import_contact(row).tag_list).to eq(expected_tags)
end
describe 'importing Contact attributes' do
let(:shared_attributes_options) do
[
{
attribute_name: :name, first_value: 'Bob', expected_first_value: 'Bob',
second_value: 'Joe', tnt_row_key: 'FileAs', required: true
},
{
attribute_name: :full_name, first_value: 'Bob', expected_first_value: 'Bob',
second_value: 'Joe', tnt_row_key: 'FullName'
},
{
attribute_name: :greeting, first_value: 'Bob', expected_first_value: 'Bob',
second_value: 'Joe', tnt_row_key: 'Greeting'
},
{
attribute_name: :envelope_greeting, first_value: 'Address One', expected_first_value: 'Address One',
second_value: 'Address Two', tnt_row_key: 'MailingAddressBlock'
},
{
attribute_name: :website, first_value: 'www.mpdx.org', expected_first_value: 'www.mpdx.org',
second_value: 'www.cru.org', tnt_row_key: 'WebPage'
},
{
attribute_name: :church_name, first_value: 'Cool Church', expected_first_value: 'Cool Church',
second_value: 'Brisk Basilica', tnt_row_key: 'ChurchName'
},
{
attribute_name: :direct_deposit, first_value: 'true', expected_first_value: true,
second_value: 'false', tnt_row_key: 'DirectDeposit'
},
{
attribute_name: :magazine, first_value: 'true', expected_first_value: true,
second_value: 'false', tnt_row_key: 'Magazine'
},
{
attribute_name: :tnt_id, first_value: 1, expected_first_value: 1,
second_value: 2, tnt_row_key: 'id', uses_override: false
},
{
attribute_name: :is_organization, first_value: 'true', expected_first_value: true,
second_value: 'false', tnt_row_key: 'IsOrganization'
},
{
attribute_name: :pledge_amount, first_value: 1234.56, expected_first_value: 1234.56.to_d,
second_value: 7890, tnt_row_key: 'PledgeAmount'
},
{
attribute_name: :pledge_frequency, first_value: 1, expected_first_value: 1.0,
second_value: 2, tnt_row_key: 'PledgeFrequencyID'
},
{
attribute_name: :pledge_received, first_value: 'true', expected_first_value: true,
second_value: 'false', tnt_row_key: 'PledgeReceived'
},
{
attribute_name: :status, first_value: 10, expected_first_value: 'Never Contacted',
second_value: 20, tnt_row_key: 'MPDPhaseID'
},
{
attribute_name: :likely_to_give, first_value: 1, expected_first_value: 'Least Likely',
second_value: 2, tnt_row_key: 'LikelyToGiveID'
},
{
attribute_name: :no_appeals, first_value: 'true', expected_first_value: true,
second_value: 'false', tnt_row_key: 'NeverAsk'
},
{
attribute_name: :estimated_annual_pledge_amount, first_value: 1234.56, expected_first_value: 1234.56.to_d,
second_value: 7890, tnt_row_key: 'EstimatedAnnualCapacity'
},
{
attribute_name: :next_ask_amount, first_value: 1234.56, expected_first_value: 1234.56.to_d,
second_value: 7890, tnt_row_key: 'NextAskAmount'
},
{
attribute_name: :pledge_currency, first_value: '1828601813', expected_first_value: 'USD',
second_value: '997892546', tnt_row_key: 'PledgeCurrencyID'
}
]
end
let(:override_options) { shared_attributes_options.reject { |options| options[:uses_override] == false } }
let(:row) { contact_rows.first }
before do
shared_attributes_options.each do |options|
raise 'Values should be different!' if options[:first_value] == options[:second_value]
end
end
def values_for(object, attribute_names)
attribute_names.each_with_object({}) do |attribute_name, hash|
hash[attribute_name] = object.send(attribute_name).to_s
end
end
def expected_values(options_hash, value_key)
options_hash.each_with_object({}) do |o, hash|
hash[o[:attribute_name]] = o[value_key].to_s
end
end
def run_first_import(override = true)
row = contact_rows.first
shared_attributes_options.each { |options| row[options[:tnt_row_key]] = options[:first_value] }
tnt_import.override = override
import.import_contact(row)
end
it 'imports attribute' do
run_first_import
attributes = values_for(Contact.last, shared_attributes_options.collect { |o| o[:attribute_name] })
expect(attributes).to eq expected_values(shared_attributes_options, :expected_first_value)
end
it 'imports attribute when nil' do
tnt_import.override = true
shared_attributes_options.reject { |o| o[:required] }.each do |options|
row.delete options[:tnt_row_key]
end
expect { import.import_contact(row) }.to change { Contact.count }
end
it "doesn't import if missing required values" do
tnt_import.override = true
shared_attributes_options.select { |o| o[:required] }.each do |options|
Contact.destroy_all
row.delete options[:tnt_row_key]
expect { import.import_contact(row) }.to_not change { Contact.count }
end
end
it 'overrides if override is true' do
run_first_import
contact = Contact.last
attributes = values_for(contact, override_options.collect { |o| o[:attribute_name] })
expect(attributes).to eq expected_values(override_options, :expected_first_value)
# fill row with import values
override_options.each { |options| row[options[:tnt_row_key]] = options[:second_value] }
expect { import.import_contact(row) }.to_not change { Contact.count }
# expect all values to have changed
attributes = values_for(contact.reload, override_options.collect { |o| o[:attribute_name] })
old_values = expected_values(override_options, :expected_first_value)
diff = (attributes.to_a - old_values.to_a).to_h
expect(diff.keys).to eq override_options.collect { |o| o[:attribute_name] }
end
it 'does not override if override is false' do
run_first_import(false)
contact = Contact.last
# expect values to be set on first run even though override = false
attributes = values_for(contact, override_options.collect { |o| o[:attribute_name] })
expect(attributes).to eq expected_values(override_options, :expected_first_value)
# fill row with import values
override_options.each { |options| row[options[:tnt_row_key]] = options[:second_value] }
expect { import.import_contact(row) }.to_not change { Contact.count }
# expect all values to still expect first value
attributes = values_for(contact.reload, override_options.collect { |o| o[:attribute_name] })
expect(attributes).to eq expected_values(override_options, :expected_first_value)
end
end
end
|
chuckmersereau/api_practice
|
dev/util/active_record_util.rb
|
<gh_stars>0
def log_active_record
ActiveRecord::Base.logger = Logger.new(STDOUT)
end
def reconnect
ActiveRecord::Base.connection.reconnect!
rescue PG::UnableToSend
ActiveRecord::Base.connection.reconnect!
end
|
chuckmersereau/api_practice
|
spec/models/person/key_account_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe Person::KeyAccount do
let!(:organization) { Organization.find_by(code: 'CCC-USA') || create(:ccc) }
let(:user) { create(:user) }
let(:person) { create(:person) }
let(:auth_hash) do
Hashie::Mash.new(
uid: '<EMAIL>',
extra: {
attributes: [{
firstName: 'John', lastName: 'Doe', email: '<EMAIL>',
ssoGuid: 'F167605D-94A4-7121-2A58-8D0F2CA6E024',
relayGuid: 'F167605D-94A4-7121-2A58-8D0F2CA6E024',
keyGuid: '<KEY>'
}]
}
)
end
describe 'create from auth' do
it 'should create an account linked to a person' do
allow_any_instance_of(Person::KeyAccount).to receive(:find_or_create_org_account)
account = nil
expect do
account = Person::KeyAccount.find_or_create_from_auth(auth_hash, person)
end.to change(Person::KeyAccount, :count).by(1)
expect(person.key_accounts.pluck(:id)).to include(account.id)
end
end
describe 'create user from auth' do
let(:user) { Person::KeyAccount.create_user_from_auth(auth_hash) }
it 'should create a user with a first and last name' do
expect do
expect(user.first_name).to eq auth_hash.extra.attributes.first.firstName
expect(user.last_name).to eq auth_hash.extra.attributes.first.lastName
end.to change(User, :count).by(1)
end
end
it 'should use guid to find an authenticated user' do
allow_any_instance_of(Person::KeyAccount).to receive(:find_or_create_org_account)
Person::KeyAccount.find_or_create_from_auth(auth_hash, user)
expect(Person::KeyAccount.find_authenticated_user(auth_hash)).to eq(user)
end
it 'should raise_or_notify exeception raised by siebel for an authenticated user with organization_account' do
create(:organization_account, user: user)
expect(SiebelDonations::Profile).to receive(:find).with(ssoGuid: auth_hash.extra.attributes.first.ssoGuid) do
raise RestClient::Exception
end
expect(Rollbar).to receive(:raise_or_notify)
Person::KeyAccount.find_or_create_from_auth(auth_hash, user)
end
it 'should use guid to find an authenticated user created with Relay' do
allow_any_instance_of(Person::KeyAccount).to receive(:find_or_create_org_account)
expect do
Person::KeyAccount.find_or_create_from_auth(auth_hash, user)
end.to change(Person::KeyAccount, :count).by(1)
expect(Person::KeyAccount.find_authenticated_user(auth_hash)).to eq(user)
end
it 'should return name for to_s' do
account = Person::KeyAccount.new(username: '<EMAIL>')
expect(account.to_s).to eq('<EMAIL>')
end
describe 'relay_account' do
let(:guid) { 'F167605D-94A4-7121-2A58-8D0F2CA6E024' }
before(:each) do
@org = Organization.find_by(code: 'CCC-USA') || create(:ccc) # Spec requires CCC-USA org to exist.
user_attributes = [{ firstName: 'John', lastName: 'Doe', username: '<EMAIL>',
email: '<EMAIL>', designation: '0000000', emplid: '000000000',
ssoGuid: guid, relayGuid: guid, keyGuid: guid }]
@auth_hash = Hashie::Mash.new(uid: '<EMAIL>', extra: { attributes: user_attributes })
@wsapi_headers = { 'Authorization' => "Bearer #{ENV.fetch('WSAPI_KEY')}" }
stub_request(:get, "https://wsapi.cru.org/wsapi/rest/profiles?response_timeout=600&ssoGuid=#{guid}")
.with(headers: @wsapi_headers)
.to_return(status: 200, body: '[]', headers: {})
end
describe 'find or create from auth' do
it 'should create an account linked to a person' do
person = create(:user)
allow(@org).to receive(:api).and_return(FakeApi.new)
expect do
@account = Person::KeyAccount.find_or_create_from_auth(@auth_hash, person)
end.to change(Person::KeyAccount, :count).by(1)
expect(person.key_accounts.pluck(:id)).to include(@account.id)
end
it 'should gracefully handle a duplicate' do
@person = create(:user)
@person2 = create(:user)
allow(@org).to receive(:api).and_return(FakeApi.new)
@account = Person::KeyAccount.find_or_create_from_auth(@auth_hash, @person)
expect do
@account2 = Person::KeyAccount.find_or_create_from_auth(@auth_hash, @person2)
end.to_not change(Person::KeyAccount, :count)
expect(@account).to eq(@account2)
end
it 'creates an organization account if this user has a profile at cru' do
stub_request(:get, "https://wsapi.cru.org/wsapi/rest/profiles?response_timeout=600&ssoGuid=#{guid}")
.with(headers: @wsapi_headers)
.to_return(status: 200, headers: {},
body: '[{"name":"Staff Account(000555555)",'\
'"designations":[{"number":"0555555","description":"Jon and <NAME>(000555555)",'\
'"staffAccountId":"000555555"}]}]')
person = create(:user)
allow(@org).to receive(:api).and_return(FakeApi.new)
expect do
@account = Person::KeyAccount.find_or_create_from_auth(@auth_hash, person)
end.to change(Person::OrganizationAccount, :count).by(1)
end
end
describe 'create user from auth' do
it 'should create a user with a first and last name' do
expect do
user = Person::KeyAccount.create_user_from_auth(@auth_hash)
expect(user.first_name).to eq @auth_hash.extra.attributes.first.firstName
expect(user.last_name).to eq @auth_hash.extra.attributes.first.lastName
end.to change(User, :count).by(1)
end
end
it 'should use guid to find an authenticated user' do
user = create(:user)
allow(@org).to receive(:api).and_return(FakeApi.new)
Person::KeyAccount.find_or_create_from_auth(@auth_hash, user)
expect(Person::KeyAccount.find_authenticated_user(@auth_hash)).to eq user
end
it 'should return name for to_s' do
account = Person::KeyAccount.new(username: '<EMAIL>')
expect(account.to_s).to eq('<EMAIL>')
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130107193956_add_index_to_activity_contact.rb
|
class AddIndexToActivityContact < ActiveRecord::Migration
def change
add_index :activity_contacts, [:contact_id, :activity_id], unique: true
end
end
|
chuckmersereau/api_practice
|
spec/services/donations_chart/monthly_totaler_spec.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
require 'rails_helper'
describe DonationsChart::MonthlyTotaler, '#monthly_totals' do
let(:account_list) { create(:account_list, salary_currency: 'EUR') }
let(:designation_account) { create(:designation_account) }
let(:donor_account) { create(:donor_account) }
let(:contact) { create(:contact, account_list: account_list) }
before do
account_list.designation_accounts << designation_account
contact.donor_accounts << donor_account
end
around do |example|
travel_to(Date.new(2016, 4, 30)) { example.run }
end
it 'groups the donations by month and gives converted totals' do
create(:currency_rate, code: 'EUR', rate: 0.7, exchanged_on: Date.new(2016, 3, 1))
create(:currency_rate, code: 'EUR', rate: 0.9, exchanged_on: Date.new(2016, 4, 1))
add_donation('EUR', 50, Date.new(2016, 4, 1))
add_donation('EUR', 25, Date.new(2016, 4, 20))
add_donation('EUR', 40, Date.new(2016, 2, 1))
add_donation('USD', 25, Date.new(2016, 2, 2))
add_donation('USD', 30, Date.new(2016, 2, 15))
totaler = DonationsChart::MonthlyTotaler.new(account_list)
expect(totaler.months_back).to eq 2
totals = totaler.totals
expect(totals[0][:currency]).to eq 'EUR'
expect(totals[0][:total_amount]).to eq 115
expect(totals[0][:total_converted]).to eq 115
expect(totals[0][:month_totals].size).to eq 3
eur_month_totals = totals[0][:month_totals]
expect(eur_month_totals[0][:amount]).to eq 40
expect(eur_month_totals[0][:converted]).to eq 40
expect(eur_month_totals[1][:amount]).to eq 0
expect(eur_month_totals[1][:converted]).to eq 0
expect(eur_month_totals[2][:amount]).to eq 75
expect(eur_month_totals[2][:converted]).to eq 75
expect(totals[1][:currency]).to eq 'USD'
expect(totals[1][:total_amount]).to eq 55
expect(totals[1][:total_converted]).to be_within(0.1).of(38.5)
expect(totals[1][:month_totals].size).to eq 3
usd_month_totals = totals[1][:month_totals]
expect(usd_month_totals[0][:amount]).to eq 55
expect(usd_month_totals[0][:converted]).to be_within(0.1).of(38.5)
end
def add_donation(currency, amount, date)
create(:donation, donor_account: donor_account, designation_account: designation_account,
currency: currency, amount: amount, donation_date: date)
end
it 'excludes donations with blank currencies' do
create(:donation, donor_account: donor_account, currency: nil, amount: 10,
designation_account: designation_account,
donation_date: Date.new(2016, 4, 1))
totaler = DonationsChart::MonthlyTotaler.new(account_list)
expect(totaler.totals).to be_empty
end
end
|
chuckmersereau/api_practice
|
engines/auth/app/controllers/auth/provider/base_controller.rb
|
module Auth
class Provider::BaseController < ApplicationController
def create
find_or_create_account
redirect_to session['redirect_to'] || 'http://mpdx.org'
reset_session
end
protected
def find_or_create_account
raise 'MUST OVERRIDE'
end
def auth_hash
request.env['omniauth.auth']
end
def current_account_list
@account_list ||= current_user.account_lists
.find_by(id: session['account_list_id'])
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/master_address_serializer.rb
|
<filename>app/serializers/master_address_serializer.rb
class MasterAddressSerializer < ApplicationSerializer
attributes :city,
:country,
:postal_code,
:state,
:street
end
|
chuckmersereau/api_practice
|
app/serializers/excluded_appeal_contact_serializer.rb
|
class ExcludedAppealContactSerializer < ApplicationSerializer
attributes :donations,
:reasons
belongs_to :appeal
belongs_to :contact
def donations
object.contact.donations.where(donation_date: start_date..end_date).collect do |d|
d.attributes.with_indifferent_access.slice(:currency, :amount, :donation_date)
end
end
def start_date
(end_date - 6.months).beginning_of_month
end
def end_date
Time.zone.today
end
def reasons
object.reasons.map do |r|
case r
when 'marked_do_not_ask'
_('Are marked as do not ask for appeals')
when 'joined_recently'
_('Joined my team in the last 3 months')
when 'special_gift'
_('Gave a special gift in the last 3 months')
when 'stopped_giving'
_('Stopped giving for the last 2 months')
when 'increased_recently'
_('Increased their giving in the last 3 months')
end
end
end
end
|
chuckmersereau/api_practice
|
spec/mailers/task_notification_mailer_spec.rb
|
require 'rails_helper'
describe TaskNotificationMailer do
describe 'notify' do
let(:user) { create(:user, email: create(:email_address)) }
let(:account_list) { create(:account_list, users: [user]) }
let(:task) { create(:task, account_list: account_list) }
let(:contact) { create(:contact) }
it 'renders the email correctly' do
task.contacts << contact
mail = TaskNotificationMailer.notify(task.id, user.id)
expect(mail.to)
expect(mail.body.raw_source).to include("https://mpdx.org/contacts/#{contact.id}/tasks")
end
end
end
|
chuckmersereau/api_practice
|
spec/models/admin/reset_log_spec.rb
|
<filename>spec/models/admin/reset_log_spec.rb
require 'rails_helper'
describe Admin::ResetLog do
end
|
chuckmersereau/api_practice
|
app/validators/updatable_only_when_source_is_mpdx_validator.rb
|
class UpdatableOnlyWhenSourceIsMpdxValidator < ActiveModel::EachValidator
# Since classic still needs to be supported, manual must be added to the list of valid sources,
# however this should be removed once we stop supporting classic.
VALID_SOURCES = %w(MPDX TntImport manual).freeze
def validate_each(record, attribute, _value)
return if !record.persisted? || VALID_SOURCES.include?(record.source) || record.changes[attribute].blank?
record.errors[attribute] << 'cannot be changed because the source is not MPDX or TntImport'
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160603231000_add_tags_to_mail_chimp.rb
|
<filename>db/migrate/20160603231000_add_tags_to_mail_chimp.rb
class AddTagsToMailChimp < ActiveRecord::Migration
def change
change_table :mail_chimp_accounts do |t|
t.rename :grouping_id, :status_grouping_id
t.string :tags_grouping_id
t.text :tags_interest_ids
end
end
end
|
chuckmersereau/api_practice
|
app/workers/fix_duplicate_donations.rb
|
class FixDuplicateDonations
include Sidekiq::Worker
sidekiq_options queue: :default, retry: 3
MATCH_ATTRIBUTES = %i(amount donation_date tendered_currency).freeze
def perform(designation_account_id)
@designation_account = DesignationAccount.find(designation_account_id)
return unless @designation_account
@cleaned_donations = []
log_worker_progress do
donations_scope.find_each(&method(:cleanup_donation))
end
send_email
end
private
def log_worker_progress
pre_count = donations_scope.count
start_time = Time.zone.now
log(format('Started at %p', start_time))
yield
post_count = donations_scope.count
changed_ids = donations_scope.where('updated_at >= ?', start_time).pluck(:id)
log(format('Finished Job after %d seconds', Time.zone.now - start_time))
log(format('Donation.count: before<%p>, after<%p>, delta<%p>',
pre_count, post_count, pre_count - post_count))
log(format('Updated Donations<ids: %p>', changed_ids))
end
def cleanup_donation(d)
matches = find_donations(d).to_a
return if matches.empty?
Donation.transaction do
# only try to move appeal if there isn't already a match
link_appeal(d, matches) if d.appeal_id && matches.none? { |m| m.appeal_id == d.appeal_id }
donor_account = d.donor_account
destroy_donation(d)
destroy_donor_account(donor_account)
end
end
def destroy_donation(donation)
memo = "Moved from Designation Account #{donation.designation_account_id}, "\
"Account List #{account_list.id}; "\
"Donor Account #{donation.donor_account.account_number} #{donation.donor_account.name}; "\
"#{donation.memo}"
donation.update!(designation_account: temp_designation_account, donor_account: temp_donor_account, memo: memo)
@cleaned_donations << donation
end
def temp_donor_account
return @temp_donor_account if @temp_donor_account
name = 'MPDX-4335 Duplicate Donation Pot'
org = Organization.find_by(name: 'MPDX Trainers') || Organization.first
@temp_donor_account = DonorAccount.find_or_create_by(name: name, organization: org, account_number: '-1')
end
def temp_designation_account
return @temp_designation_account if @temp_designation_account
name = 'MPDX-4335 Duplicate Donation Pot'
org = Organization.find_by(name: 'MPDX Trainers') || Organization.first
@temp_designation_account = DesignationAccount.find_or_create_by(name: name, organization: org)
end
def destroy_donor_account(donor_account)
donor_account.destroy unless donor_account.donations.exists?
end
def account_list
@account_list ||= @designation_account.account_lists.order(:created_at).first
end
def find_contact(donation)
@contact_cache ||= {}
return @contact_cache[donation.donor_account_id] if @contact_cache[donation.donor_account_id]
@contact_cache[donation.donor_account_id] = donation.donor_account.contacts.find_by(account_list: account_list)
end
def find_donations(donation)
match_attributes = donation.attributes.with_indifferent_access.slice(*MATCH_ATTRIBUTES)
match_attributes[:appeal_id] = [donation.appeal_id, nil] if donation.appeal_id
contact = find_contact(donation)
return unless contact
contact.donations
.where(match_attributes)
.where.not(designation_account_id: donation.designation_account_id)
end
def link_appeal(donation, matches)
new_appeal_donation = matches.find { |d| d.appeal_id.blank? || d.appeal_id == donation.appeal_id }
new_appeal_donation.update!(appeal_id: donation.appeal_id, appeal_amount: donation.appeal_amount)
end
def donations_scope
@designation_account.donations
end
def send_email
return if @cleaned_donations.empty?
addresses = account_list.users.collect(&:email_address).uniq.compact
return if addresses.empty?
mail = ActionMailer::Base.mail(from: '<EMAIL>',
to: addresses,
subject: 'MPDX - Duplicate Donations Merged',
body: email_body)
mail.deliver_later
end
def email_body
'Hi friend! We wanted to drop you a line to let you know that we ran a process to clean up '\
"the extra donations we had imported from your TNT Export. We identified #{@cleaned_donations.count} "\
"donations that were already in your account \"#{account_list.name}\". If you find that you are "\
"missing donations, please let us know (we've tucked them away for safe keeping). Additionally, "\
'if you still see a handful of duplicates, please clean them up by deleting the "This donation '\
'was imported from Tnt." donation. If there are more than a handful that remain, please reach '\
"out to us and we'll take another round to clean them up.
Have a great day!
Your MPDX Team
<EMAIL>".gsub(/ +/, ' ')
end
def log(message)
# Because the sidekiq config sets the logging level to Fatal, log to fatal
# so that we can see these in the logs
Rails.logger.fatal("DonationDups[worker]: #{message}")
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/church.rb
|
class Contact::Filter::Church < Contact::Filter::Base
def execute_query(contacts, filters)
church_filters = parse_list(filters[:church])
church_filters << nil if church_filters.delete('none')
contacts.where(church_name: church_filters)
end
def title
_('Church')
end
def parent
_('Contact Details')
end
def type
'multiselect'
end
def custom_options
[{ name: _('-- None --'), id: 'none' }] + account_lists.map(&:churches).flatten.uniq.select(&:present?).map { |a| { name: a, id: a } }
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/donation_amount_range.rb
|
<filename>app/services/contact/filter/donation_amount_range.rb
class Contact::Filter::DonationAmountRange < Contact::Filter::Base
def execute_query(contacts, filters)
sanitize_filters(filters)
contacts = contacts.joins(donor_accounts: [:donations])
if filters[:donation_amount_range][:min].present?
contacts = contacts.where('donations.amount >= :donation_amount_min AND '\
'donations.designation_account_id IN (:designation_account_ids)',
donation_amount_min: filters[:donation_amount_range][:min],
designation_account_ids: designation_account_ids)
end
if filters[:donation_amount_range][:max].present?
contacts = contacts.where('donations.amount <= :donation_amount_max AND '\
'donations.designation_account_id IN (:designation_account_ids)',
donation_amount_max: filters[:donation_amount_range][:max],
designation_account_ids: designation_account_ids)
end
contacts
end
def title
_('Gift Amount Range')
end
def parent
_('Gift Details')
end
def type
'text'
end
def custom_options
account_list_highest = account_lists.collect do |account_list|
account_list.donations.where.not(amount: nil).reorder(:amount).last&.amount
end
highest_account_donation = account_list_highest.compact.max
[{ name: _('Gift Amount Higher Than or Equal To'), id: 'min', placeholder: 0 },
{ name: _('Gift Amount Less Than or Equal To'), id: 'max', placeholder: highest_account_donation }]
end
def valid_filters?(filters)
filters[:donation_amount_range].is_a?(Hash) &&
(filters[:donation_amount_range][:min].present? || filters[:donation_amount_range][:max].present?)
end
def sanitize_filters(filters)
[:min, :max].each do |option|
next unless filters[:donation_amount_range][option].present?
filters[:donation_amount_range][option] = filters[:donation_amount_range][option].gsub(/[^\.\d]/, '').to_f
end
end
end
|
chuckmersereau/api_practice
|
app/workers/google_sync_data_worker.rb
|
<filename>app/workers/google_sync_data_worker.rb
class GoogleSyncDataWorker
include Sidekiq::Worker
sidekiq_options queue: :api_google_sync_data_worker, unique: :until_executed
def perform(google_integration_id, integration)
begin
google_integration = GoogleIntegration.find(google_integration_id)
rescue ActiveRecord::RecordNotFound
return
end
google_integration.sync_data(integration)
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/user/organization_accounts_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'User > Organization Accounts' do
include_context :json_headers
documentation_scope = :user_api_organization_accounts
let!(:user) { create(:user_with_full_account) }
let(:resource_type) { 'organization_accounts' }
let!(:organization_account) { create(:organization_account, person: user) }
let(:id) { organization_account.id }
let(:new_organization_account_params) do
attributes_for(:organization_account)
.merge(updated_in_db_at: organization_account.updated_at)
.tap do |attrs|
attrs.delete(:person_id)
attrs.delete(:organization_id)
end
end
let(:form_data) { build_data(new_organization_account_params, relationships: relationships) }
let(:relationships) do
{
person: {
data: {
type: 'people',
id: user.id
}
},
organization: {
data: {
type: 'organizations',
id: create(:organization).id
}
}
}
end
let(:resource_attributes) do
%w(
created_at
disable_downloads
last_download
locked_at
remote_id
username
updated_at
updated_in_db_at
)
end
before do
allow_any_instance_of(DataServer).to receive(:validate_credentials).and_return(true)
allow_any_instance_of(Person::OrganizationAccount).to receive(:queue_import_data)
allow_any_instance_of(Person::OrganizationAccount).to receive(:set_up_account_list)
end
context 'authorized user' do
before { api_login(user) }
lock_time_around
get '/api/v2/user/organization_accounts' do
example 'Organization Account [LIST]', document: documentation_scope do
do_request
explanation 'List of Organization Accounts associated to current_user'
expect(response_status).to eq(200), invalid_status_detail
check_collection_resource(2, %w(relationships))
end
end
get '/api/v2/user/organization_accounts/:id' do
with_options scope: [:data, :attributes] do
response_field 'created_at', 'Created At', type: 'String'
response_field 'disable_downloads', 'Disable Downloads', type: 'String'
response_field 'last_download', 'Last Download', type: 'String'
response_field 'locked_at', 'Locked At', type: 'String'
response_field 'remote_id', 'Remote Id', type: 'String'
response_field 'username', 'Username', type: 'String'
response_field 'updated_at', 'Updated At', type: 'String'
response_field 'updated_in_db_at', 'Updated In Db At', type: 'String'
end
example 'Organization Account [GET]', document: documentation_scope do
explanation 'The User\'s Organization Account with the given ID'
do_request
expect(response_status).to eq(200), invalid_status_detail
check_resource(%w(relationships))
end
end
post '/api/v2/user/organization_accounts' do
with_options required: true, scope: [:data, :attributes] do
parameter 'organization_id', 'Organization Id'
parameter 'password', 'Password'
parameter 'person_id', 'Person Id'
parameter 'username', 'Username'
end
example 'Organization Account [CREATE]', document: documentation_scope do
explanation 'Create an Organization Account associated with the current_user'
do_request data: form_data
expect(response_status).to eq(201), invalid_status_detail
expect(resource_object['username']).to eq new_organization_account_params[:username]
end
end
put '/api/v2/user/organization_accounts/:id' do
with_options required: true, scope: [:data, :attributes] do
parameter 'organization_id', 'Organization Id'
parameter 'password', 'Password'
parameter 'person_id', 'Person Id'
parameter 'username', 'Username'
end
example 'Organization Account [UPDATE]', document: documentation_scope do
explanation 'Update the current_user\'s Organization Account with the given ID'
do_request data: form_data
expect(response_status).to eq(200), invalid_status_detail
expect(resource_object['username']).to eq new_organization_account_params[:username]
end
end
delete '/api/v2/user/organization_accounts/:id' do
example 'Organization Account [DELETE]', document: documentation_scope do
explanation 'Delete the current_user\'s Organization Account with the given ID'
do_request
expect(response_status).to eq(204), invalid_status_detail
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/donation_reports/donors_and_donations.rb
|
class DonationReports::DonorsAndDonations
include ActiveModel::Model
include ActiveModel::Serializers
attr_accessor :donors, :donations
end
|
chuckmersereau/api_practice
|
app/policies/weekly_policy.rb
|
<reponame>chuckmersereau/api_practice<filename>app/policies/weekly_policy.rb
class WeeklyPolicy < ApplicationPolicy
def show?
true
end
def create?
true
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170926155821_populate_contacts_status_confirmed_at.rb
|
class PopulateContactsStatusConfirmedAt < ActiveRecord::Migration
def up
current_time = Time.current
# If the contact was updated after the status was validated and the contact status_valid is true then assume it doesn't need to be confirmed for another year.
Contact.where.not(status_validated_at: nil, suggested_changes: nil).where('updated_at > status_validated_at').where(status_valid: true).update_all(status_confirmed_at: current_time)
# If the contact has suggested_changes but the status_valid is true then it implies that the user already confirmed the status.
Contact.where.not(suggested_changes: [nil, {}]).where(status_valid: true).update_all(status_confirmed_at: current_time)
end
def down
Contact.update_all(status_confirmed_at: nil)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130612033951_change_pledge_frequency_to_decimal.rb
|
<gh_stars>0
class ChangePledgeFrequencyToDecimal < ActiveRecord::Migration
def self.up
change_column :contacts, :pledge_frequency, :decimal
execute <<-SQL
update contacts set pledge_frequency = pledge_frequency * 1.0
SQL
end
def self.down
change_column :contacts, :pledge_frequency, :integer
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.