repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
app/services/account_list/email_collection.rb
|
<reponame>chuckmersereau/api_practice<filename>app/services/account_list/email_collection.rb<gh_stars>0
class AccountList::EmailCollection
attr_reader :account_list
def initialize(account_list)
@account_list = account_list
end
def select_by_email(email)
return [] unless email
grouped_by_email[normalize_email(email)]
end
private
def grouped_by_email
@grouped_by_email ||= group_collection_by_email
end
def fetch_email_collection_for_account_list
account_list
.contacts
.active
.joins(people: [:email_addresses])
.where(email_addresses: { deleted: false })
.pluck(:contact_id, 'people.id', 'email_addresses.email')
end
def group_collection_by_email
fetch_email_collection_for_account_list.each_with_object({}) do |record_data_array, hash|
contact_id, person_id, email = record_data_array
normalized_email = normalize_email(email)
record_data_hash = {
contact_id: contact_id,
person_id: person_id,
email: email
}
hash[normalized_email] ||= []
hash[normalized_email] << record_data_hash
end
end
def normalize_email(email)
email.downcase.strip
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/admin/organizations_controller_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Api::V2::Admin::OrganizationsController do
let(:admin_user) { create(:user, admin: true) }
let(:given_resource_type) { :organizations }
let(:correct_attributes) do
{
name: 'Cru (Offline)',
org_help_url: 'https://cru.org',
country: 'United States'
}
end
let(:response_data) { JSON.parse(response.body)['data'] }
let(:response_errors) { JSON.parse(response.body)['errors'] }
include_context 'common_variables'
context 'create' do
it 'returns a 401 when someone is not logged in' do
post :create, full_correct_attributes
expect(response.status).to eq(401)
end
it 'returns a 403 when someone that is not an admin tries to create an organization' do
api_login(create(:user))
post :create, full_correct_attributes
expect(response.status).to eq(403)
end
it 'returns a 400 when the name is not set' do
full_correct_attributes[:data][:attributes][:name] = ''
api_login(admin_user)
post :create, full_correct_attributes
expect(response.status).to eq(400)
expect(response_errors).to_not be_empty
end
it 'returns a 201 when an admin provides correct attributes' do
api_login(admin_user)
post :create, full_correct_attributes
expect(response.status).to eq(201)
end
it 'creates an organization' do
api_login(admin_user)
expect { post :create, full_correct_attributes }.to change { Organization.count }.from(0).to(1)
organization = Organization.first
expect(organization.query_ini_url).to match '.{8}\.example\.com'
expect(organization.api_class.to_s).to eq 'OfflineOrg'
expect(organization.addresses_url).to eq 'example.com'
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20161214195836_add_created_at_and_updated_at_to_google_integrations.rb
|
class AddCreatedAtAndUpdatedAtToGoogleIntegrations < ActiveRecord::Migration
def up
execute('ALTER TABLE "google_integrations" ADD COLUMN "created_at" timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP')
execute('ALTER TABLE "google_integrations" ADD COLUMN "updated_at" timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP')
end
def down
remove_column :google_integrations, :created_at
remove_column :google_integrations, :updated_at
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160202192709_add_new_indexes.rb
|
<filename>db/migrate/20160202192709_add_new_indexes.rb
class AddNewIndexes < ActiveRecord::Migration
def change
add_index :master_addresses, :postal_code
add_index :activities, :completed
execute "create index index_addresses_on_lower_city
on addresses(lower(city));"
end
end
|
chuckmersereau/api_practice
|
spec/support/zonebie.rb
|
<gh_stars>0
# Keep this toggled to false in order to allow for new developers to understand
# that the specs are always run with a random timezone
Zonebie.quiet = false
Zonebie.set_random_timezone
|
chuckmersereau/api_practice
|
lib/exceptions.rb
|
module Exceptions
class AuthenticationError < StandardError; end
class BadRequestError < StandardError; end
end
|
chuckmersereau/api_practice
|
db/migrate/20150302140850_change_donation_fields_back_to_decimal.rb
|
<filename>db/migrate/20150302140850_change_donation_fields_back_to_decimal.rb
class ChangeDonationFieldsBackToDecimal < ActiveRecord::Migration
def change
change_column :appeals, :amount, :decimal, precision: 19, scale: 2
change_column :contacts, :pledge_amount, :decimal, precision: 19, scale: 2
change_column :contacts, :total_donations, :decimal, precision: 19, scale: 2
change_column :designation_accounts, :balance, :decimal, precision: 19, scale: 2
change_column :designation_profiles, :balance, :decimal, precision: 19, scale: 2
change_column :donations, :tendered_amount, :decimal, precision: 19, scale: 2
change_column :donations, :amount, :decimal, precision: 19, scale: 2
change_column :donations, :appeal_amount, :decimal, precision: 19, scale: 2
change_column :donor_accounts, :total_donations, :decimal, precision: 19, scale: 2
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170306203922_add_file_constants_and_mappings_fields_to_imports.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class AddFileConstantsAndMappingsFieldsToImports < ActiveRecord::Migration
def change
add_column :imports, :file_constants, :text
add_column :imports, :file_headers_mappings, :text
add_column :imports, :file_constants_mappings, :text
end
end
|
chuckmersereau/api_practice
|
app/services/person/gmail_account.rb
|
<gh_stars>0
# This class has the potential to be broken out into several classes to handle
# gmail account importing. It could then be packaged up into a library/gem.
class Person::GmailAccount
attr_reader :google_account, :since
def initialize(google_account)
@google_account = google_account
@since = (google_account.last_email_sync || 1.day.ago).to_date
end
def gmail_connection
return false unless token?
Gmail.connect(:xoauth2, google_account.email, google_account.token) do |gmail_client|
yield gmail_client
end
end
def import_emails(account_list, blacklisted_emails = [])
return false unless token?
self.blacklisted_emails = (blacklisted_emails.presence || []).collect(&:strip)
self.email_collection = AccountList::EmailCollection.new(account_list)
gmail_connection do |gmail|
begin
sent_mailbox = gmail.mailbox('[Gmail]/Sent Mail')
received_mailbox = gmail.mailbox('[Gmail]/All Mail')
(since..Date.today).each do |date|
process_sent_emails(gmail, sent_mailbox, date)
process_received_emails(gmail, received_mailbox, date)
google_account.update_attributes(last_email_sync: date)
end
rescue Net::IMAP::NoResponseError => e
# swallow it if the user doesn't have those mailboxes
raise unless e.message.include?('Unknown Mailbox')
end
end
end
def record_email(gmail_message, account_list_id, contact_id, person_id, result)
contact = Contact.find(contact_id)
body = format_message_body(gmail_message.message)
return unless body
google_email = google_account.google_emails.find_or_create_by!(google_email_id: gmail_message.msg_id)
return if contact.tasks.exists?(id: google_email.activities.ids)
task = create_task_for_contact(gmail_message, account_list_id, contact, result)
task.comments.create!(body: body, person_id: person_id)
google_email.activities << task
google_email.save!
task
# Rescue all errors so that the sync can continue (otherwise it would
# repeat and get stuck at the same spot logging the same email).
rescue StandardError => error
Rollbar.error(error) # Report the error so that we still know about it.
end
private
attr_accessor :email_collection, :blacklisted_emails
def token?
!google_account.token_expired?
end
def fetch_account_email_data(email_address)
return unless email_address
# While `email_collection.index_data[email_address]` could return an array of multiple items,
# based on the possiblity that multiple Contacts can each have a person with the same email address -
# we're selecting the first item in the array to maintain feature parity with legacy only fetching
# and logging emails for an email address once.
#
# For context: https://github.com/CruGlobal/mpdx_api/blob/6412f53/app/services/person/gmail_account.rb#L35-L46
email_collection.select_by_email(email_address)&.first
end
def force_encode_body(body_needing_encoding)
body_needing_encoding
.body
.decoded
.to_s
.unpack('C*')
.pack('U*')
.force_encoding('UTF-8')
.encode!
.delete("\0")
end
def format_message_body(message_body)
body = message_body.multipart? ? message_body.text_part : message_body
return unless body
encoded_body = force_encode_body(body)
return unless encoded_body.strip.present?
encoded_body
end
def format_subject(gmail_message_subject)
if gmail_message_subject.present?
gmail_message_subject.truncate(2000, omission: '')
else
_('No Subject')
end
end
def record_received_email(message:)
account_list_id = email_collection.account_list.id
sender_email_address = sender_email_address_from_envelope(message.envelope)
account_email_data = fetch_account_email_data(sender_email_address)
return unless account_email_data.present? && not_blacklisted?(account_email_data[:email])
record_email(message, account_list_id, account_email_data[:contact_id], account_email_data[:person_id], 'Received')
end
def record_sent_email(message:)
account_list_id = email_collection.account_list.id
recipient_email_addresses = recipient_email_addresses_from_envelope(message.envelope)
recipient_email_addresses.each do |recipient_email_address|
account_email_data = fetch_account_email_data(recipient_email_address)
next unless account_email_data.present? && not_blacklisted?(account_email_data[:email])
record_email(message, account_list_id, account_email_data[:contact_id], account_email_data[:person_id], 'Done')
end
end
def recipient_email_addresses_from_envelope(envelope)
envelope.to.to_a.map do |address|
"#{address.mailbox}@#{address.host}"
end
end
def sender_email_address_from_envelope(envelope)
address = envelope.sender&.first
return unless address
"#{address.mailbox}@#{address.host}"
end
def not_blacklisted?(email)
return false unless email
!blacklisted_domain?(email) && !blacklisted_emails.include?(email)
end
def blacklisted_domains
@blacklisted_domains ||= begin
blacklisted_emails.select { |email| email.starts_with?('*') }
.map { |domain| domain.split('@').last }
end
end
def blacklisted_domain?(email)
blacklisted_domains.include?(email.split('@').last)
end
def process_sent_emails(gmail, sent_mailbox, date)
sent_uids = sent_mailbox.fetch_uids(on: date) || []
process_each_message(sent_uids, sent_mailbox, gmail) do |gmail_message|
record_sent_email(message: gmail_message)
end
end
def process_received_emails(gmail, received_mailbox, date)
received_uids = received_mailbox.fetch_uids(on: date) || []
process_each_message(received_uids, received_mailbox, gmail) do |gmail_message|
record_received_email(message: gmail_message)
end
end
def process_each_message(uids, mailbox, gmail)
uids.each_slice(20) do |uid_group|
gmail.conn.uid_fetch(uid_group, Gmail::Message::PREFETCH_ATTRS).each do |imap_data|
next unless imap_data
gmail_message = Gmail::Message.new(mailbox, nil, imap_data)
block_given? ? yield(gmail_message) : gmail_message
end
end
end
def create_task_for_contact(gmail_message, account_list_id, contact, result)
contact.tasks.create!(subject: format_subject(gmail_message.subject),
start_at: gmail_message.envelope.date,
completed: true,
completed_at: gmail_message.envelope.date,
account_list_id: account_list_id,
activity_type: 'Email',
result: result,
remote_id: gmail_message.envelope.message_id,
source: 'gmail')
end
end
|
chuckmersereau/api_practice
|
spec/services/person/duplicate_pairs_finder_spec.rb
|
require 'rails_helper'
describe Person::DuplicatePairsFinder do
let!(:account_list) { create(:user_with_account).account_lists.order(:created_at).first }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:unique_person_one) do
create(:person, first_name: 'This person should have no duplicates', last_name: 'No Duplicates').tap do |person|
person.email_addresses << create(:email_address, email: '<EMAIL>')
person.phone_numbers << create(:phone_number, number: '21123864192836465189346712893467')
contact.people << person
end
end
let!(:unique_person_two) do
create(:person,
first_name: 'This is another person that is a totally unique individual',
last_name: 'Totally Unique').tap do |person|
person.email_addresses << create(:email_address, email: '<EMAIL>')
person.phone_numbers << create(:phone_number, number: '1623487916235819367419283467')
contact.people << person
end
end
def build_finder
Person::DuplicatePairsFinder.new(account_list)
end
it 'deletes pairs with missing records' do
valid_pair = DuplicateRecordPair.create!(
account_list: account_list,
reason: 'Test',
record_one: unique_person_one,
record_two: unique_person_two
)
person = create(:person, first_name: 'John', last_name: 'Doe').tap do |created_person|
contact.people << created_person
end
pair_missing_record_one = DuplicateRecordPair.new(
account_list: account_list,
reason: 'Test',
record_one_id: SecureRandom.uuid,
record_one_type: 'Person',
record_two_id: person.id,
record_two_type: 'Person'
)
pair_missing_record_one.save(validate: false)
pair_missing_record_two = DuplicateRecordPair.new(
account_list: account_list,
reason: 'Test',
record_one_id: person.id,
record_one_type: 'Person',
record_two_id: SecureRandom.uuid,
record_two_type: 'Person'
)
pair_missing_record_two.save(validate: false)
expect { build_finder.find_and_save }.to change { DuplicateRecordPair.count }.by(-2)
expect(DuplicateRecordPair.exists?(pair_missing_record_one.id)).to eq(false)
expect(DuplicateRecordPair.exists?(pair_missing_record_two.id)).to eq(false)
expect(DuplicateRecordPair.exists?(valid_pair.id)).to eq(true)
end
it 'does not find duplicates from a different account list' do
person = create(:person, first_name: 'John', last_name: 'Doe')
create(:contact, account_list: account_list).people << person
create(:contact).people << person
expect do
expect(build_finder.find_and_save).to eq([])
end.to_not change { DuplicateRecordPair.count }.from(0)
end
it 'does not find duplicates from a different contact in the same account list' do
person = create(:person, first_name: 'John', last_name: 'Doe')
create(:contact, account_list: account_list).people << person
create(:contact, account_list: account_list).people << person
expect do
expect(build_finder.find_and_save).to eq([])
end.to_not change { DuplicateRecordPair.count }.from(0)
end
context 'people with the same first and last names' do
let!(:person_one) do
create(:person, first_name: 'John', last_name: 'Doe').tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: 'John', last_name: 'Doe').tap { |person| contact.people << person }
end
it 'finds and saves the DuplicateRecordPair' do
expect { build_finder.find_and_save }.to change {
DuplicateRecordPair.type('Person').where(reason: 'Similar names', record_one_id: person_one.id,
record_two_id: person_two.id).count
}.from(0).to(1)
expect(DuplicateRecordPair.count).to eq(1)
end
end
context 'people with the same first and last names but different formatting' do
let!(:person_one) do
create(:person, first_name: ' john, ', last_name: 'DOE ').tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: "\nJohn\r", last_name: "Doe'").tap { |person| contact.people << person }
end
it 'finds and saves the DuplicateRecordPair' do
expect { build_finder.find_and_save }.to change {
DuplicateRecordPair.type('Person').where(reason: 'Similar names', record_one_id: person_one.id,
record_two_id: person_two.id).count
}.from(0).to(1)
expect(DuplicateRecordPair.count).to eq(1)
end
end
context 'people with the same first name but missing last names' do
let!(:person_one) do
create(:person, first_name: 'John', last_name: 'Doe').tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: 'John', last_name: nil).tap { |person| contact.people << person }
end
it 'finds and saves the DuplicateRecordPair' do
expect { build_finder.find_and_save }.to change {
DuplicateRecordPair.type('Person').where(reason: 'Similar names', record_one_id: person_one.id,
record_two_id: person_two.id).count
}.from(0).to(1)
expect(DuplicateRecordPair.count).to eq(1)
end
end
context 'people with the same first name but different last names' do
let!(:person_one) do
create(:person, first_name: 'John', last_name: 'Doe').tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: 'John', last_name: 'Jones').tap { |person| contact.people << person }
end
it 'does not consider them duplicates' do
expect { build_finder.find_and_save }.to_not change {
DuplicateRecordPair.count
}.from(0)
end
end
context 'people with the same email addresses and same gender' do
let!(:person_one) do
create(:person, first_name: 'John', last_name: 'Doe', gender: 'male').tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: 'Bob', last_name: 'Jones', gender: 'male').tap { |person| contact.people << person }
end
let!(:email_address_one) do
create(:email_address, email: ' <EMAIL> ').tap do |email_address|
person_one.email_addresses << email_address
end
end
let!(:email_address_two) do
create(:email_address, email: '<EMAIL>').tap do |email_address|
person_two.email_addresses << email_address
end
end
it 'finds and saves the DuplicateRecordPair' do
expect { build_finder.find_and_save }.to change {
DuplicateRecordPair.type('Person').where(reason: 'Similar email addresses', record_one_id: person_one.id,
record_two_id: person_two.id).count
}.from(0).to(1)
expect(DuplicateRecordPair.count).to eq(1)
end
end
context 'people with the same email addresses and different gender' do
let!(:person_one) do
create(:person, first_name: 'Jane', last_name: 'Doe', gender: 'female').tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: 'Bob', last_name: 'Jones', gender: 'male').tap { |person| contact.people << person }
end
let!(:email_address_one) do
create(:email_address, email: ' <EMAIL> ').tap do |email_address|
person_one.email_addresses << email_address
end
end
let!(:email_address_two) do
create(:email_address, email: '<EMAIL>').tap do |email_address|
person_two.email_addresses << email_address
end
end
it 'does not consider them duplicates' do
expect { build_finder.find_and_save }.to_not change {
DuplicateRecordPair.count
}.from(0)
end
end
context 'people with the same email addresses and no gender' do
let!(:person_one) do
create(:person, first_name: 'Jane', last_name: 'Doe', gender: nil).tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: 'Bob', last_name: 'Jones', gender: nil).tap { |person| contact.people << person }
end
let!(:email_address_one) do
create(:email_address, email: ' <EMAIL> ').tap do |email_address|
person_one.email_addresses << email_address
end
end
let!(:email_address_two) do
create(:email_address, email: '<EMAIL>').tap do |email_address|
person_two.email_addresses << email_address
end
end
it 'does not consider them duplicates' do
expect { build_finder.find_and_save }.to_not change {
DuplicateRecordPair.count
}.from(0)
end
end
context 'people with the same phone numbers and same gender' do
let!(:person_one) do
create(:person, first_name: 'John', last_name: 'Doe', gender: 'male').tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: 'Bob', last_name: 'Jones', gender: 'male').tap { |person| contact.people << person }
end
let!(:phone_number_one) do
create(:phone_number, number: '1.234.567.890! ').tap { |phone_number| person_one.phone_numbers << phone_number }
end
let!(:phone_number_two) do
create(:phone_number, number: '+1234567890').tap { |phone_number| person_two.phone_numbers << phone_number }
end
it 'finds and saves the DuplicateRecordPair' do
expect { build_finder.find_and_save }.to change {
DuplicateRecordPair.type('Person').where(reason: 'Similar phone numbers', record_one_id: person_one.id,
record_two_id: person_two.id).count
}.from(0).to(1)
expect(DuplicateRecordPair.count).to eq(1)
end
end
context 'people with the same phone numbers and different gender' do
let!(:person_one) do
create(:person, first_name: 'Jane', last_name: 'Doe', gender: 'female').tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: 'Bob', last_name: 'Jones', gender: 'male').tap { |person| contact.people << person }
end
let!(:phone_number_one) do
create(:phone_number, number: '1.234.567.890! ').tap { |phone_number| person_one.phone_numbers << phone_number }
end
let!(:phone_number_two) do
create(:phone_number, number: '+1234567890').tap { |phone_number| person_two.phone_numbers << phone_number }
end
it 'does not consider them duplicates' do
expect { build_finder.find_and_save }.to_not change {
DuplicateRecordPair.count
}.from(0)
end
end
context 'people with the same phone numbers and no gender' do
let!(:person_one) do
create(:person, first_name: 'Jane', last_name: 'Doe', gender: nil).tap { |person| contact.people << person }
end
let!(:person_two) do
create(:person, first_name: 'Bob', last_name: 'Jones', gender: nil).tap { |person| contact.people << person }
end
let!(:phone_number_one) do
create(:phone_number, number: '1.234.567.890! ').tap { |phone_number| person_one.phone_numbers << phone_number }
end
let!(:phone_number_two) do
create(:phone_number, number: '+1234567890').tap { |phone_number| person_two.phone_numbers << phone_number }
end
it 'does not consider them duplicates' do
expect { build_finder.find_and_save }.to_not change {
DuplicateRecordPair.count
}.from(0)
end
end
context 'person with nil phone numbers' do
let!(:person) do
create(:person, first_name: 'Jane', last_name: 'Doe', gender: nil).tap { |person| contact.people << person }
end
let!(:phone_number) do
create(:phone_number, number: '1.234.567.890! ').tap { |phone_number| person.phone_numbers << phone_number }
end
before { phone_number.update_column(:number, nil) }
it 'does not raise a NoMethodError' do
expect { build_finder.find_and_save }.to_not raise_error
end
end
end
|
chuckmersereau/api_practice
|
spec/workers/add_pledges_to_donations_worker_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe AddPledgesToDonationsWorker do
describe '#perform' do
context 'donation has no appeal' do
let!(:donation) { create(:donation) }
it 'should not create pledges' do
expect { described_class.new.perform }.to_not change { Pledge.count }
end
end
context 'donation has appeal' do
let!(:account_list) { create(:account_list) }
let!(:appeal) { create(:appeal, account_list: account_list) }
let!(:donation) { create(:donation, appeal: appeal) }
context 'appeal has no account_list' do
before { appeal.update(account_list: nil) }
it 'should not create pledges' do
expect { described_class.new.perform }.to_not change { Pledge.count }
end
end
context 'donation donor_account which belongs to contact on account list' do
let!(:donor_account) { create(:donor_account) }
let!(:contact) { create(:contact, account_list: account_list) }
before { donor_account.contacts << contact }
let!(:donation) { create(:donation, appeal: appeal, donor_account: donor_account) }
it 'should create pledges' do
expect { described_class.new.perform }.to change { Pledge.count }.by(1)
pledge = Pledge.first
expect(pledge.amount).to eq donation.amount
expect(pledge.appeal).to eq appeal
expect(pledge.contact).to eq contact
expect(pledge.donations).to eq [donation]
expect(pledge.expected_date).to eq donation.donation_date
end
context 'donation has appeal amount' do
before { donation.update(amount: 100, appeal_amount: 50) }
it 'should create pledges with appeal amount' do
described_class.new.perform
pledge = Pledge.first
expect(pledge.amount).to eq donation.appeal_amount
end
end
end
context 'contact has two donations on appeal' do
let!(:donor_account) { create(:donor_account) }
let!(:contact) { create(:contact, account_list: account_list) }
before { donor_account.contacts << contact }
let!(:donation1) { create(:donation, donor_account: donor_account) }
let!(:donation2) { create(:donation, donor_account: donor_account) }
it 'should create pledges' do
donor_account.donations.update_all(appeal_id: appeal.id)
expect { described_class.new.perform }.to change { Pledge.count }.by(1)
pledge = Pledge.first
expect(pledge.amount).to eq(donation1.amount + donation2.amount)
expect(pledge.donations).to match_array [donation1, donation2]
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/appeal_contacts.rb
|
FactoryBot.define do
factory :appeal_contact do
appeal
contact do |appeal_contact|
build(:contact, account_list: appeal_contact.appeal.account_list)
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/notification_preferences/bulk_controller.rb
|
<gh_stars>0
class Api::V2::AccountLists::NotificationPreferences::BulkController < Api::V2::BulkController
resource_type :notification_preferences
def create
load_notification_preferences
persist_notification_preferences
end
private
def load_notification_preferences
@notification_preferences = notification_preference_scope.where(
id: notification_preference_id_params.compact
)
end
def authorize_notification_preferences
bulk_authorize(@notification_preferences)
end
def pundit_user
PunditContext.new(current_user, account_list: load_account_list)
end
def notification_preference_id_params
params
.require(:data)
.collect { |hash| hash[:notification_preference][:id] }
end
def notification_preference_scope
current_user.notification_preferences.where(account_list: load_account_list)
end
def persist_notification_preferences
build_empty_notification_preferences
build_notification_preferences
authorize_notification_preferences
save_notification_preferences
render json: BulkResourceSerializer.new(resources: @notification_preferences),
include: include_params,
fields: field_params
end
def save_notification_preferences
@notification_preferences.each do |notification_preference|
notification_preference.save(context: persistence_context)
end
end
def build_empty_notification_preferences
sent_ids = params.require(:data).map { |data| data['notification_preference']['id'] }
existing_ids = NotificationPreference.where(id: sent_ids).pluck(:id)
new_ids = sent_ids - existing_ids
@notification_preferences += new_ids.map { |id| notification_preference_scope.build(id: id) }
end
def build_notification_preferences
@notification_preferences.each do |notification_preference|
notification_preference_index = data_attribute_index(notification_preference)
attributes = params.require(:data)[notification_preference_index][:notification_preference]
notification_preference.assign_attributes(
notification_preference_params(attributes)
)
end
end
def data_attribute_index(notification_preference)
params
.require(:data)
.find_index do |notification_preference_data|
notification_preference_data[:notification_preference][:id] == notification_preference.id
end
end
def notification_preference_params(attributes)
attributes ||= params.require(:notification_preference)
attributes.permit(NotificationPreference::PERMITTED_ATTRIBUTES)
end
def load_account_list
@account_list ||= AccountList.find(params[:account_list_id])
end
end
|
chuckmersereau/api_practice
|
spec/lib/json_api_service/configuration_spec.rb
|
require 'spec_helper'
require 'json_api_service/configuration'
require 'support/json_api_service_helper'
module JsonApiService
RSpec.describe Configuration, type: :service do
let(:configuration) { Configuration.new }
describe '#initialize' do
it 'initializes with a fresh ResourceLookup' do
expect(configuration.resource_lookup).to be_a ResourceLookup
end
it 'initializes with an empty hash for ignored_foreign_keys' do
expect(configuration.ignored_foreign_keys).to be_empty
end
end
describe '#custom_references' do
before do
allow_any_instance_of(ResourceLookup)
.to receive(:custom_references)
.and_return(users: 'UserAccounts')
end
it 'returns the custom_references of the lookup' do
expect(configuration.custom_references)
.to eq(users: 'UserAccounts')
end
end
describe '#custom_references=' do
it 'assigns new custom_references' do
expect(configuration.custom_references).to eq({})
configuration.custom_references = { users: 'UserAccounts' }
expect(configuration.custom_references).to eq(users: 'UserAccounts')
end
end
describe '#ignored_foreign_keys' do
it 'returns an empty array as a default value' do
expect(configuration.ignored_foreign_keys).to eq({})
expect(configuration.ignored_foreign_keys[:missing]).to eq([])
end
end
describe '#ignored_foreign_keys=' do
it 'assigns new ignored_foreign_keys' do
expect(configuration.ignored_foreign_keys).to eq({})
configuration.ignored_foreign_keys = { donations: [:remote_id] }
expect(configuration.ignored_foreign_keys).to eq(donations: [:remote_id])
end
it 'still returns an empty array as a default value' do
configuration.ignored_foreign_keys = { donations: [:remote_id] }
expect(configuration.ignored_foreign_keys[:missing]).to eq([])
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/referrals_controller_spec.rb
|
<filename>spec/controllers/api/v2/contacts/referrals_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V2::Contacts::ReferralsController, type: :controller do
# This is required!
let(:user) { create(:user_with_account) }
# This MAY be required!
let(:account_list) { user.account_lists.order(:created_at).first }
let(:contact) { create(:contact, account_list: account_list) }
let(:contact_referred) { create(:contact, account_list: account_list) }
let(:alternate) { create(:contact, account_list: account_list) }
# This is required!
let(:factory_type) do
# This is the type used to auto-generate a resource using FactoryBot,
# ex: The type `:email_address` would be used as create(:email_address)
:contact_referral
end
# This is required!
let!(:resource) do
# Creates the Singular Resource for this spec - change as needed
# Example: create(:contact, account_list: account_list)
attributes = {
referred_by: contact,
referred_to: contact_referred
}
create(:contact_referral, attributes)
end
# This is required for the index action!
let!(:second_resource) do
# Creates a second resource for this spec - change as needed
# Example: create(:contact, account_list: account_list)
attributes = {
referred_by: contact,
referred_to: contact_referred
}
create(:contact_referral, attributes)
end
# If needed, keep this ;)
let(:id) { resource.id }
# If needed, keep this ;)
let(:parent_param) do
# This is a hash of the nested keys needed for the URL,
# If the resource is listed more than once, you can add multiple.
# Ex: /api/v2/:account_list_id/contacts/:contact_id/addresses/:id
# --
# Note: Don't include :id
# Example: { account_list_id: account_list_id }
{
contact_id: contact.id
}
end
let!(:parent_association) { :referred_by }
# This is required!
let(:correct_attributes) do
# A hash of correct attributes for creating/updating the resource
# Example: { subject: 'test subject', start_at: Time.now, account_list_id: account_list.id }
{}
end
let(:correct_relationships) do
{
referred_by: {
data: {
type: 'contacts',
id: contact.id
}
},
referred_to: {
data: {
type: 'contacts',
id: contact_referred.id
}
}
}
end
let(:update_attributes) do
{ overwrite: true }
end
let(:update_relationships) do
{
referred_to: {
data: {
type: 'contacts',
id: alternate.id
}
}
}
end
let(:given_reference_key) { nil }
let(:given_update_reference_key) { :referred_to_id }
let(:given_update_reference_value) { alternate.id }
# This is required!
let(:unpermitted_attributes) do
# A hash of attributes that include unpermitted attributes for the current user to update
# Example: { subject: 'test subject', start_at: Time.now, account_list_id: create(:account_list).id } }
# --
# If there aren't attributes that are unpermitted,
# you need to specifically return `nil`
nil
end
# This is required!
let(:incorrect_attributes) do
# A hash of attributes that will fail validations
# Example: { subject: nil, account_list_id: account_list.id } }
# --
# If there aren't attributes that violate validations,
# you need to specifically return `nil`
#
{}
end
let(:incorrect_relationships) do
{}
end
let(:dont_run_incorrect_update) { true }
# These includes can be found in:
# spec/support/shared_controller_examples.rb
include_examples 'index_examples'
include_examples 'show_examples'
include_examples 'create_examples'
include_examples 'update_examples'
include_examples 'destroy_examples'
end
|
chuckmersereau/api_practice
|
engines/auth/config/environments/staging.rb
|
<gh_stars>0
require 'omniauth'
OmniAuth.config.full_host = 'https://auth.stage.mpdx.org'
|
chuckmersereau/api_practice
|
spec/services/contact/dup_contacts_merge_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::DupContactsMerge, type: :model do
let(:account_list) { create(:account_list) }
let(:designation_account) { create(:designation_account) }
let(:donor_account) { create(:donor_account) }
let(:contact) { create(:contact, name: 'Tester', account_list: account_list) }
describe 'initialize' do
it 'initializes' do
expect(
Contact::DupContactsMerge.new(account_list: account_list, contact: contact)
).to be_a(Contact::DupContactsMerge)
end
end
describe '#find_duplicates' do
context 'contacts have the same name' do
let!(:contact_one) { contact }
let!(:contact_two) { create(:contact, name: 'Tester', account_list: account_list) }
let!(:contact_three) { create(:contact, name: 'Tester', account_list: account_list) }
let!(:contact_four) { create(:contact, name: 'Someone Else', account_list: account_list) }
before do
contact_one.people << build(:person, first_name: 'Fname', last_name: 'Lname')
contact_two.people << build(:person, first_name: 'Fname', last_name: 'Lname')
contact_three.people << build(:person, first_name: 'Fname', last_name: 'Lname')
contact_four.people << build(:person, first_name: 'Fname', last_name: 'Lname')
end
subject { Contact::DupContactsMerge.new(account_list: account_list, contact: contact).find_duplicates }
context 'contacts do not share donor accounts and do not share addresses' do
it 'does not find any duplicate contact' do
expect(subject).to eq([])
end
end
context 'contacts share donor accounts' do
before do
account_list.designation_accounts << designation_account
contact_one.donor_accounts << donor_account
contact_two.donor_accounts << donor_account
contact_three.donor_accounts << create(:donor_account)
contact_four.donor_accounts << donor_account
end
it 'finds a duplicate contact' do
expect(subject).to eq([contact_two])
end
end
context 'contacts share addresses' do
let(:master_address_id_1) { SecureRandom.uuid }
let(:master_address_id_2) { SecureRandom.uuid }
before do
contact_one.addresses << build(:address, master_address_id: master_address_id_1)
contact_two.addresses << build(:address, master_address_id: master_address_id_1)
contact_three.addresses << build(:address,
master_address_id: master_address_id_2,
city: 'Somewhere Else',
postal_code: '1234asdf')
contact_four.addresses << build(:address, master_address_id: master_address_id_1)
end
it 'finds a duplicate contact' do
expect(subject).to eq([contact_two])
end
end
end
end
describe '#merge_duplicates' do
context 'contacts have the same name' do
let!(:contact_one) { contact }
let!(:contact_two) { create(:contact, name: 'Tester', account_list: account_list) }
let!(:contact_three) { create(:contact, name: 'Tester', account_list: account_list) }
let!(:contact_four) { create(:contact, name: 'Someone Else', account_list: account_list) }
before do
contact_one.people << build(:person, first_name: 'Fname', last_name: 'Lname')
contact_two.people << build(:person, first_name: 'Fname', last_name: 'Lname')
contact_three.people << build(:person, first_name: 'Fname', last_name: 'Lname')
contact_four.people << build(:person, first_name: 'Fname', last_name: 'Lname')
end
subject { Contact::DupContactsMerge.new(account_list: account_list, contact: contact).merge_duplicates }
context 'contacts do not share donor accounts and do not share addresses' do
it 'does not merge contacts' do
expect { subject }.to_not change { account_list.reload.contacts.count }.from(4)
end
end
context 'contacts share donor accounts' do
before do
account_list.designation_accounts << designation_account
contact_one.donor_accounts << donor_account
contact_two.donor_accounts << donor_account
contact_three.donor_accounts << create(:donor_account)
contact_four.donor_accounts << donor_account
end
it 'merges contacts' do
expect { subject }.to change { account_list.reload.contacts.count }.from(4).to(3)
end
it 'merges people' do
expect { subject }.to change { Person.count }.from(4).to(3)
end
end
context 'contacts share addresses' do
let(:master_address_id_1) { SecureRandom.uuid }
let(:master_address_id_2) { SecureRandom.uuid }
before do
contact_one.addresses << build(:address, master_address_id: master_address_id_1)
contact_two.addresses << build(:address, master_address_id: master_address_id_1)
contact_three.addresses << build(:address,
master_address_id: master_address_id_2,
city: 'Somewhere Else',
postal_code: '1234asdf')
contact_four.addresses << build(:address, master_address_id: master_address_id_1)
end
it 'merges contacts' do
expect { subject }.to change { account_list.reload.contacts.count }.from(4).to(3)
end
it 'merges addresses' do
expect { subject }.to change { Address.count }.from(4).to(3)
end
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/account_list.rb
|
<filename>app/services/contact/filter/account_list.rb
class Contact::Filter::AccountList < Contact::Filter::Base
def execute_query(contacts, filters)
contacts.where(account_list_id: parse_list(filters[:account_list_id]))
end
def title
_('Account List')
end
def type
'multiselect'
end
def custom_options
account_lists.collect { |account_list| { name: account_list.name, id: account_list.id } }
end
end
|
chuckmersereau/api_practice
|
app/services/contact_filter.rb
|
<reponame>chuckmersereau/api_practice
class ContactFilter
attr_accessor :contacts, :filters
def initialize(filters = nil)
@filters = filters || {}
# strip extra spaces from filters
@filters.map { |k, v| @filters[k] = v.strip if v.is_a?(String) }
end
def filter(contacts, account_list)
@contacts = filtered_contacts = contacts
if filters.present?
if @filters[:ids].present?
filtered_contacts = filtered_contacts.where('contacts.id' => @filters[:ids].split(','))
end
filtered_contacts = filtered_contacts.where('contacts.id not in (?)', @filters[:not_ids]) if @filters[:not_ids]
if @filters[:tags].present? && @filters[:tags].first != ''
filtered_contacts = filtered_contacts.tagged_with(@filters[:tags].split(','))
end
if @filters[:name_like]
# See if they've typed a first and last name
filtered_contacts =
if @filters[:name_like].split(/\s+/).length > 1
filtered_contacts.where("concat(first_name,' ',last_name) like ? ", "%#{@filters[:name_like]}%")
else
filtered_contacts.where('first_name like :search OR last_name like :search',
search: "#{@filters[:name_like]}%")
end
end
filtered_contacts = city(filtered_contacts)
filtered_contacts = church(filtered_contacts)
filtered_contacts = state(filtered_contacts)
filtered_contacts = region(filtered_contacts)
filtered_contacts = metro_area(filtered_contacts)
filtered_contacts = country(filtered_contacts)
filtered_contacts = likely(filtered_contacts)
filtered_contacts = status(filtered_contacts)
filtered_contacts = referrer(filtered_contacts)
filtered_contacts = newsletter(filtered_contacts)
filtered_contacts = contact_name(filtered_contacts)
filtered_contacts = timezone(filtered_contacts)
filtered_contacts = pledge_currency(filtered_contacts, account_list)
filtered_contacts = locale(filtered_contacts, account_list)
filtered_contacts = related_task_action(filtered_contacts)
filtered_contacts = appeal(filtered_contacts)
filtered_contacts = contact_type(filtered_contacts)
filtered_contacts = wildcard_search(filtered_contacts)
filtered_contacts = pledge_freq(filtered_contacts)
filtered_contacts = pledge_received(filtered_contacts)
filtered_contacts = contact_info_email(filtered_contacts)
filtered_contacts = contact_info_phone(filtered_contacts)
filtered_contacts = contact_info_address(filtered_contacts)
filtered_contacts = contact_info_facebook(filtered_contacts)
end
filtered_contacts
end
def city(filtered_contacts)
return filtered_contacts unless @filters[:city].present? && @filters[:city].first != ''
filtered_contacts.where('addresses.city' => @filters[:city],
'addresses.historic' => @filters[:address_historic] || false)
.includes(:addresses)
.references('addresses')
end
def church(filtered_contacts)
return filtered_contacts unless @filters[:church].present? && @filters[:church].first != ''
filtered_contacts.where('contacts.church_name' => @filters[:church])
end
def state(filtered_contacts)
return filtered_contacts unless @filters[:state].present? && @filters[:state].first != ''
filtered_contacts.where('addresses.state' => @filters[:state],
'addresses.historic' => @filters[:address_historic] || false)
.includes(:addresses)
.references('addresses')
end
def region(filtered_contacts)
return filtered_contacts unless @filters[:region].present? && @filters[:region].first != ''
filtered_contacts.where('addresses.region' => @filters[:region],
'addresses.historic' => @filters[:address_historic] || false)
.includes(:addresses)
.references('addresses')
end
def metro_area(filtered_contacts)
return filtered_contacts unless @filters[:metro_area].present? && @filters[:metro_area].first != ''
filtered_contacts.where('addresses.metro_area' => @filters[:metro_area],
'addresses.historic' => @filters[:address_historic] || false)
.includes(:addresses)
.references('addresses')
end
def country(filtered_contacts)
return filtered_contacts unless @filters[:country].present? && @filters[:country].first != ''
filtered_contacts.where('addresses.country' => @filters[:country],
'addresses.historic' => @filters[:address_historic] || false)
.includes(:addresses)
.references('addresses')
end
def likely(filtered_contacts)
return filtered_contacts unless @filters[:likely].present? && @filters[:likely].first != ''
filtered_contacts.where(likely_to_give: @filters[:likely])
end
def status(filtered_contacts)
if @filters[:status].present? && @filters[:status].first != ''
unless @filters[:status].include? '*'
@filters[:status] << 'null' if @filters[:status].include?('') && !@filters[:status].include?('null')
@filters[:status] << '' if @filters[:status].include?('null') && !@filters[:status].include?('')
filtered_contacts = if @filters[:status].include? 'null'
filtered_contacts.where('status is null OR status in (?)', @filters[:status])
else
filtered_contacts.where(status: @filters[:status])
end
end
else
filtered_contacts = filtered_contacts.active
end
filtered_contacts
end
def referrer(filtered_contacts)
return filtered_contacts unless @filters[:referrer].present? && @filters[:referrer].first != ''
if @filters[:referrer].first == '*'
filtered_contacts.joins(:contact_referrals_to_me)
.where('contact_referrals.referred_by_id is not null').uniq
else
filtered_contacts.joins(:contact_referrals_to_me)
.where('contact_referrals.referred_by_id' => @filters[:referrer]).uniq
end
end
def newsletter(filtered_contacts)
return filtered_contacts unless @filters[:newsletter].present?
filtered_contacts = case @filters[:newsletter]
when 'none'
filtered_contacts.where("send_newsletter is null OR send_newsletter = ''")
when 'address'
filtered_contacts.where(send_newsletter: %w(Physical Both))
when 'email'
filtered_contacts.where(send_newsletter: %w(Email Both))
else
filtered_contacts.where("send_newsletter is not null AND send_newsletter <> ''")
end
filtered_contacts.uniq unless filtered_contacts.to_sql.include?('DISTINCT')
end
def contact_name(filtered_contacts)
return filtered_contacts unless @filters[:name].present?
filtered_contacts.where('lower(contacts.name) like ?', "%#{@filters[:name].downcase}%")
end
def timezone(filtered_contacts)
return filtered_contacts unless @filters[:timezone].present? && @filters[:timezone].first != ''
filtered_contacts.where('contacts.timezone' => @filters[:timezone])
end
def pledge_currency(filtered_contacts, account_list)
return filtered_contacts unless @filters[:pledge_currency].present? && @filters[:pledge_currency].first != ''
if @filters[:pledge_currency].include?(account_list.default_currency)
filtered_contacts.where(pledge_currency: [@filters[:pledge_currency], '', nil])
else
filtered_contacts.where(pledge_currency: @filters[:pledge_currency])
end
end
def locale(filtered_contacts, _account_list)
return filtered_contacts unless @filters[:locale].present? && @filters[:locale].first != ''
locales = @filters[:locale].map { |l| l == 'null' ? nil : l }
filtered_contacts.where('contacts.locale' => locales)
end
def related_task_action(filtered_contacts)
return filtered_contacts unless @filters[:relatedTaskAction].present? && @filters[:relatedTaskAction].first != ''
if @filters[:relatedTaskAction].first == 'null'
contacts_with_activities = filtered_contacts.where('activities.completed' => false)
.includes(:activities).map(&:id)
filtered_contacts.where('contacts.id not in (?)', contacts_with_activities)
else
filtered_contacts.where('activities.activity_type' => @filters[:relatedTaskAction])
.where('activities.completed' => false)
.includes(:activities)
end
end
def appeal(filtered_contacts)
return filtered_contacts unless @filters[:appeal].present? && @filters[:appeal].first != ''
filtered_contacts.where('appeal_contacts.appeal_id' => @filters[:appeal]).includes(:appeals).uniq
end
def contact_type(filtered_contacts)
case @filters[:contact_type]
when 'person'
filtered_contacts = filtered_contacts.people
when 'company'
filtered_contacts = filtered_contacts.companies
end
filtered_contacts
end
def wildcard_search(filtered_contacts)
return filtered_contacts unless @filters[:wildcard_search].present? && @filters[:wildcard_search] != 'null'
if @filters[:wildcard_search].include?(',')
last_name, first_name = @filters[:wildcard_search].split(',')
else
first_name, last_name = @filters[:wildcard_search].split
end
if first_name.present? && last_name.present?
first_name = first_name.downcase.strip
last_name = last_name.downcase.strip
person_search = ' OR (lower(people.first_name) like :first_name AND lower(people.last_name) like :last_name)'
else
person_search = ''
end
filtered_contacts.where(
'lower(email_addresses.email) like :search '\
'OR lower(contacts.name) like :search '\
'OR lower(donor_accounts.account_number) like :search '\
'OR lower(phone_numbers.number) like :search' + person_search,
search: "%#{@filters[:wildcard_search].downcase}%",
first_name: first_name,
last_name: last_name
)
.includes(people: :email_addresses)
.references('email_addresses')
.includes(:donor_accounts)
.references('donor_accounts')
.includes(people: :phone_numbers)
.references('phone_numbers')
end
def pledge_freq(filtered_contacts)
if @filters[:pledge_frequencies].present? && @filters[:pledge_frequencies].first != ''
frequencies_not_null = Array.wrap(@filters[:pledge_frequencies]) - ['null']
return filtered_contacts unless frequencies_not_null.present?
filtered_contacts = filtered_contacts.where(pledge_frequency: frequencies_not_null)
end
filtered_contacts
end
def pledge_received(filtered_contacts)
return filtered_contacts unless @filters[:pledge_received].present?
filtered_contacts.where(pledge_received: @filters[:pledge_received])
end
def contact_info_email(filtered_contacts)
return filtered_contacts unless @filters[:contact_info_email].present?
contacts_with_emails = @contacts.where.not(email_addresses: { email: nil })
.where(email_addresses: { historic: false })
.includes(people: :email_addresses)
contacts_with_emails_ids = contacts_with_emails.pluck(:id)
return filtered_contacts.where(id: contacts_with_emails_ids) if @filters[:contact_info_email] == 'Yes'
return filtered_contacts if contacts_with_emails_ids.empty?
filtered_contacts.where.not(id: contacts_with_emails_ids)
end
def contact_info_phone(filtered_contacts)
filter_home_phone = @filters[:contact_info_phone]
filter_mobile_phone = @filters[:contact_info_mobile]
# set up contact id arrays
if filter_home_phone.present?
contacts_with_home_phone_ids = @contacts
.where.not(phone_numbers: { number: nil })
.where(phone_numbers: { historic: false, location: 'home' })
.includes(people: :phone_numbers)
.pluck(:id)
filter_home_phone = '' if contacts_with_home_phone_ids.empty?
end
if filter_mobile_phone.present?
contacts_with_mobile_phone_ids = @contacts
.where.not(phone_numbers: { number: nil })
.where(phone_numbers: { historic: false, location: 'mobile' })
.includes(people: :phone_numbers)
.pluck(:id)
filter_mobile_phone = '' if contacts_with_mobile_phone_ids.empty?
end
# guard blank filters
return filtered_contacts unless filter_home_phone.present? || filter_mobile_phone.present?
# one but not the other
if filter_home_phone.blank?
result = if filter_mobile_phone == 'Yes'
filtered_contacts.where(id: contacts_with_mobile_phone_ids)
else
filtered_contacts.where.not(id: contacts_with_mobile_phone_ids)
end
return result
end
if filter_mobile_phone.blank?
result = if filter_home_phone == 'Yes'
filtered_contacts.where(id: contacts_with_home_phone_ids)
else
filtered_contacts.where.not(id: contacts_with_home_phone_ids)
end
return result
end
# both filters present
if filter_home_phone == 'Yes' && filter_mobile_phone == 'Yes'
# & is intersection
return filtered_contacts.where(id: contacts_with_mobile_phone_ids & contacts_with_home_phone_ids)
end
if filter_home_phone == 'Yes' && filter_mobile_phone == 'No'
return filtered_contacts.where(id: contacts_with_home_phone_ids - contacts_with_mobile_phone_ids)
end
if filter_home_phone == 'No' && filter_mobile_phone == 'Yes'
return filtered_contacts.where(id: contacts_with_mobile_phone_ids - contacts_with_home_phone_ids)
end
if filter_home_phone == 'No' && filter_mobile_phone == 'No'
# | is union
return filtered_contacts.where.not(id: contacts_with_mobile_phone_ids | contacts_with_home_phone_ids)
end
filtered_contacts
end
def contact_info_address(filtered_contacts)
return filtered_contacts unless @filters[:contact_info_addr].present?
contacts_with_addr = @contacts.where.not(addresses: { street: '' })
.where(addresses: { historic: false })
.includes(:addresses)
contacts_with_addr_ids = contacts_with_addr.pluck(:id)
return filtered_contacts.where(id: contacts_with_addr_ids) if @filters[:contact_info_addr] == 'Yes'
return filtered_contacts if contacts_with_addr_ids.empty?
filtered_contacts.where.not(id: contacts_with_addr_ids)
end
def contact_info_facebook(filtered_contacts)
return filtered_contacts unless @filters[:contact_info_facebook].present?
contacts_with_fb = filtered_contacts.where.not(person_facebook_accounts: { remote_id: nil })
.includes(people: :facebook_account)
return contacts_with_fb if @filters[:contact_info_facebook] == 'Yes'
contacts_with_fb_ids = contacts_with_fb.reorder('').pluck(:id)
return filtered_contacts if contacts_with_fb_ids.empty?
filtered_contacts.where.not(id: contacts_with_fb_ids)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170404211028_migrate_pledges_donation_id_data_to_join_table.rb
|
<filename>db/migrate/20170404211028_migrate_pledges_donation_id_data_to_join_table.rb
class MigratePledgesDonationIdDataToJoinTable < ActiveRecord::Migration
def up
Pledge.where.not(donation_id: nil).find_each do |pledge|
PledgeDonation.create(donation_id: pledge.donation_id, pledge_id: pledge.id)
end
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
|
chuckmersereau/api_practice
|
locale/unfound_translations.rb
|
# Activity types
_('Appointment')
_('Call')
_('Email')
_('Facebook Message')
_('Letter')
_('Newsletter - Email')
_('Newsletter - Physical')
_('Prayer Request')
_('Pre Call Letter')
_('Reminder Letter')
_('Support Letter')
_('Talk to In Person')
_('Text Message')
_('Thank')
_('To Do')
# Alerts
_('You must select at least 2 contacts to merge.')
# Date Ranges
_('Last Week')
_('Last month')
_('Last Year')
_('Last Two Years')
_('Overdue')
_('Today')
_('Tomorrow')
_('Future')
_('Upcoming')
# For multi-currency reports
_('Commitment')
_('Avg.')
_('Min.')
_('Total')
_('converted as')
_('of total')
# Giving likelihoods
_('Least Likely')
_('Likely')
_('Most Likely')
# Headings
_('Insights for ')
_('Balance: %{balance}')
# Info Messages
_('You have no monthly recurring gift recommendations.')
# Multi-currency report CSV Export
_('Partner')
_('Status')
_('Pledge')
_('Average')
_('Minimum')
_('Total (last month excluded from total)')
_('Currency')
_('Totals')
# Send newsletter
_('Physical')
_('Email')
_('Both')
# Statuses
_('Never Contacted')
_('Ask in Future')
_('Contact for Appointment')
_('Appointment Scheduled')
_('Call for Decision')
_('Partner - Financial')
_('Partner - Special')
_('Partner - Pray')
_('Not Interested')
_('Unresponsive')
_('Never Ask')
_('Research Abandoned')
_('Expired Referral')
# Titles
_('New Donation')
# Tool Tips
_('May take a few days to update')
# Assignable Locations
_('Business')
_('Home')
_('Mailing')
_('Other')
_('Seasonal')
_('Temporary')
# Placeholders & Labels
_('Add a tag')
_('Select an Option')
_('Minutes')
|
chuckmersereau/api_practice
|
spec/services/contact/filter/church_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::Church 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) }
describe '#config' do
it 'returns expected config' do
options = [{ name: '-- Any --', id: '', placeholder: 'None' },
{ name: '-- None --', id: 'none' },
{ name: 'First Pedestrian Church', id: 'First Pedestrian Church' },
{ name: 'My Church', id: 'My Church' }]
expect(described_class.config([account_list])).to include(multiple: true,
name: :church,
options: options,
parent: 'Contact Details',
title: 'Church',
type: 'multiselect',
default_selection: '')
end
end
describe '#query' do
let(:contacts) { Contact.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(contacts, {}, nil)).to eq(nil)
expect(described_class.query(contacts, { church: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { church: [] }, nil)).to eq(nil)
end
end
context 'filter by no church' do
it 'returns only contacts that have no church' do
results = described_class.query(contacts, { church: 'none' }, nil).to_a
expect(results).to match_array [contact_three, contact_four]
end
end
context 'filter by church' do
it 'filters multiple churches' do
results = described_class.query(contacts, { church: 'My Church, First Pedestrian Church' }, nil).to_a
expect(results).to match_array [contact_one, contact_two]
end
it 'filters a single churche' do
expect(described_class.query(contacts, { church: 'My Church' }, nil).to_a).to eq [contact_one]
end
end
context 'multiple filters' do
it 'returns contacts matching multiple filters' do
results = described_class.query(contacts, { church: 'My Church, none' }, nil).to_a
expect(results).to match_array [contact_one, contact_three, contact_four]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/reports/appointment_results_controller_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/controllers/api/v2/reports/appointment_results_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V2::Reports::AppointmentResultsController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:given_serializer_class) { Reports::AppointmentResultsPeriodSerializer }
let(:given_resource_type) { 'reports_appointment_results_periods' }
let(:factory_type) { :account_list }
let(:resource) do
Reports::AppointmentResultsPeriod.new(account_list: account_list,
start_date: 1.week.ago,
end_date: DateTime.current)
end
let(:correct_attributes) { {} }
describe 'index' do
before do
contact = create(:contact, account_list: account_list)
account_list.primary_appeal = create(:appeal)
create(:pledge, contact: contact, appeal: account_list.primary_appeal)
end
include_examples 'index_examples', except: [:sorting, :pagination]
end
describe 'Filters' do
it 'allows a user to request from their account_list' do
api_login(user)
get :index, filter: { account_list_id: account_list.id }
expect(response.status).to eq 200
end
it 'blocks a user from accessing others account lists' do
api_login(create(:user))
get :index, filter: { account_list_id: account_list.id }
expect(response.status).to eq 404
end
end
describe 'meta' do
let(:averages) { response_json['meta']['averages'] }
it 'sends averages of values in AppointmentResultsPeriod objects' do
api_login(user)
get :index, filter: { account_list_id: account_list.id }
expect(averages.keys).to match_array %w(average_individual_appointments
average_group_appointments
average_new_monthly_partners
average_new_special_pledges
average_monthly_increase
average_pledge_increase)
end
it 'sends only meta for requested fields' do
api_login(user)
get :index,
filter: { account_list_id: account_list.id },
fields: { reports_appointment_results_periods: 'individual_appointments,group_appointments' }
expect(averages.keys).to eq %w(average_individual_appointments average_group_appointments)
end
end
context 'as coach' do
include_context 'common_variables'
let(:coach) { create(:user).becomes(User::Coach) }
let(:contact) do
create(:contact, account_list: account_list,
created_at: 4.months.ago,
status: 'Call for Appointment',
pledge_amount: nil)
end
before do
travel_to(1.week.ago) { contact.update(status: 'Partner - Financial', pledge_amount: 100) }
account_list.coaches << coach
full_params[:include] = 'pledge_increase_contacts,pledge_increase_contacts.contact'
full_params[:account_list_id] = account_list.id
end
it 'allows access to report' do
api_login(coach)
get :index, full_params
expect(response.status).to eq(200), invalid_status_detail
end
it 'renders pledges and contacts with coach serializers' do
api_login(coach)
expect(Coaching::Reports::AppointmentResultsPeriodSerializer).to receive(:new).exactly(4).times.and_call_original
expect(Coaching::ContactSerializer).to receive(:new).exactly(2).times.and_call_original
get :index, full_params
contact_json = response_json['included'].find { |json| json['id'] == contact.id }
expect(contact_json).to_not be nil
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/pledge_frequency.rb
|
class Contact::Filter::PledgeFrequency < Contact::Filter::Base
def execute_query(contacts, filters)
frequencies_not_null = parse_list(filters[:pledge_frequency]) - ['null']
return unless frequencies_not_null.present?
contacts.where(pledge_frequency: frequencies_not_null)
end
def title
_('Commitment Frequency')
end
def parent
_('Commitment Details')
end
def type
'multiselect'
end
def custom_options
Contact.pledge_frequencies.invert.to_a.collect { |a| { name: a[0], id: a[1] } }
end
end
|
chuckmersereau/api_practice
|
spec/models/notification_type_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe NotificationType do
let(:notification_type) { create(:notification_type) }
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact, name: '<NAME>', account_list: account_list) }
let!(:donation) { create(:donation, currency: 'MyString') }
let(:designation_account) { create(:designation_account) }
let!(:special_gift) { NotificationType::SpecialGift.create! }
context '.check_all' do
it 'checks for notifications of each type' do
create(:notification_preference, account_list: account_list, notification_type: special_gift)
expect(NotificationType).to receive(:types).and_return(['NotificationType::SpecialGift'])
expect(NotificationType::SpecialGift).to receive(:first).and_return(special_gift)
expect(special_gift).to receive(:check)
NotificationType.check_all(account_list)
end
end
describe '#create_task default implementation' do
before do
description = '%{contact_name} gave a gift of %{amount} on %{date}'
expect(notification_type).to receive(:task_description_template).and_return(description)
end
it 'creates a task for the activity list' do
donation.update(donation_date: Date.new(2015, 3, 18))
expect do
notification_type.create_task(account_list, contact.notifications.new(donation_id: donation.id))
end.to change(Activity, :count).by(1)
activity = Activity.first
expect(activity.subject).to eq('<NAME> gave a gift of MyString9.99 on March 18, 2015')
expect(activity.activity_type).to eq('Thank')
expect(activity.source).to eq('NotificationType::CallPartnerOncePerYear')
end
it 'associates the contact with the task created' do
task = notification_type.create_task(account_list, contact.notifications.new(donation_id: donation.id))
expect(task.contacts.reload).to include(contact)
end
end
describe '#check default implementation' do
it 'does not add a notification twice' do
expect(notification_type).to receive(:check_for_donation_to_notify).twice.with(contact).and_return(donation)
account_list.contacts.reload
expect do
notification_type.check(account_list)
end.to change(Notification, :count).from(0).to(1)
expect do
notification_type.check(account_list)
end.to_not change(Notification, :count).from(1)
end
it 'can have the same notification on two contacts' do
contact2 = create(:contact, account_list: account_list)
create(:notification, notification_type: notification_type, contact: contact2, donation: donation)
expect(notification_type).to receive(:check_for_donation_to_notify).with(contact).and_return(donation)
expect(notification_type).to receive(:check_for_donation_to_notify).with(contact2).and_return(donation)
expect { notification_type.check(account_list) }.to change(Notification, :count).by(1)
end
it 'does not send a notification for gifts given a long time ago' do
donation.update(donation_date: 75.days.ago)
expect(notification_type).to receive(:check_for_donation_to_notify).with(contact).and_return(donation)
expect do
notification_type.check(account_list)
end.to_not change(Notification, :count).from(0)
end
end
describe '#task_description default implementation' do
it 'interpolates and localizes contact name, amount and date' do
donation.update(donation_date: Date.new(2015, 3, 18))
template = '%{contact_name} gave %{amount} on %{date}'
expect(notification_type).to receive(:task_description_template).and_return(template)
notification = contact.notifications.new(donation: donation)
description = '<NAME> gave MyString9.99 on March 18, 2015'
expect(notification_type.task_description(notification)).to eq(description)
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/imports.rb
|
FactoryBot.define do
factory :import do
source 'twitter'
association :account_list
association :user
importing false
after :create do |i|
i.user.email_addresses << create(:email_address)
end
end
factory :tnt_import, parent: :import do
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export.xml')) }
source 'tnt'
end
factory :tnt_import_non_donor, parent: :tnt_import do
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_non_donor.xml')) }
end
factory :tnt_import_short_donor_code, parent: :tnt_import do
association :account_list, factory: :account_list_with_designation_profile
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_short_donor_code.xml')) }
end
factory :tnt_import_groups, parent: :tnt_import do
association :account_list, factory: :account_list_with_designation_profile
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_groups.xml')) }
end
factory :tnt_import_multi_donor_accounts, parent: :tnt_import do
association :account_list, factory: :account_list_with_designation_profile
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_multi_donor_accounts.xml')) }
end
factory :tnt_import_gifts, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_0_export_gifts.xml')) }
end
factory :tnt_import_broad, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml')) }
end
factory :tnt_import_no_gifts, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_no_gifts.xml')) }
end
factory :tnt_import_with_personal_gift, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_export_with_personal_gift.xml')) }
end
factory :tnt_import_gifts_added, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_gifts_1added.xml')) }
end
factory :tnt_import_gifts_multiple_same_day, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_gifts_multiple_same_day.xml')) }
end
factory :tnt_import_first_email_not_preferred, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_row_multi_email.yaml')) }
end
factory :tnt_import_3_0_appeals, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_0_export_appeals.xml')) }
end
factory :tnt_import_3_2_campaigns, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_campaigns.xml')) }
end
factory :tnt_import_campaigns_and_promises, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_with_campaign_promises.xml')) }
end
factory :tnt_import_gifts_without_appeal, parent: :tnt_import do
association :account_list
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_export_gifts_without_appeals.xml')) }
end
factory :csv_import, parent: :import do
association :account_list
source 'csv'
file { File.new(Rails.root.join('spec/fixtures/sample_csv_to_import.csv')) }
end
factory :csv_import_fullname, parent: :import do
association :account_list
source 'csv'
file { File.new(Rails.root.join('spec/fixtures/sample_csv_with_fullname.csv')) }
end
factory :csv_import_with_bom, parent: :import do
association :account_list
source 'csv'
file { File.new(Rails.root.join('spec/fixtures/sample_csv_with_bom.csv')) }
end
factory :csv_import_invalid, parent: :import do
association :account_list
source 'csv'
file { File.new(Rails.root.join('spec/fixtures/csv_invalid.csv')) }
end
factory :csv_import_custom_headers, parent: :import do
association :account_list
source 'csv'
file { File.new(Rails.root.join('spec/fixtures/sample_csv_with_custom_headers.csv')) }
end
factory :google_import, parent: :import do
source 'google'
end
factory :csv_import_with_mappings, parent: :csv_import_custom_headers do
after :build do |import|
import.in_preview = true
end
after :create do |import|
CsvImport.new(import).update_cached_file_data
import.file_headers_mappings = {
'church' => 'church',
'city' => 'city',
'pledge_amount' => 'amount',
'pledge_currency' => 'currency',
'pledge_frequency' => 'frequency',
'country' => 'country',
'email_1' => 'email_address',
'first_name' => 'fname',
'full_name' => 'fullname',
'greeting' => 'greeting',
'envelope_greeting' => 'mailing_greeting',
'last_name' => 'lname',
'likely_to_give' => 'likely_giver',
'metro_area' => 'metro',
'newsletter' => 'newsletter',
'notes' => 'extra_notes',
'phone_1' => 'phone',
'region' => 'region',
'send_appeals' => 'appeals',
'spouse_email' => 'spouse_email_address',
'spouse_first_name' => 'spouse_fname',
'spouse_last_name' => 'spouse_lname',
'spouse_phone' => 'spouse_phone_number',
'state' => 'province',
'status' => 'status',
'street' => 'street',
'tags' => 'tags',
'website' => 'website',
'zip' => 'zip_code'
}
import.file_constants_mappings = {
'pledge_currency' => [
{ id: 'CAD', values: ['CAD'] },
{ id: 'USD', values: [''] }
],
'pledge_frequency' => [
{ id: 'Monthly', values: ['Monthly'] },
{ id: '', values: [''] }
],
'likely_to_give' => [
{ id: 'Most Likely', values: ['Yes'] },
{ id: 'Least Likely', values: ['No'] }
],
'newsletter' => [
{ id: 'Both', values: ['Both'] }
],
'send_appeals' => [
{ id: true, values: ['Yes'] },
{ id: false, values: ['No'] }
],
'status' => [
{ id: 'Partner - Financial', values: ['Praying and giving'] },
{ id: 'Partner - Pray', values: ['Praying'] }
]
}
import.save
end
end
factory :tnt_import_multi_org, parent: :import do
association :account_list
source 'tnt'
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_multi_org.xml')) }
end
factory :tnt_import_with_multiple_task_contacts, parent: :import do
file { File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_with_multiple_task_contacts.xml')) }
source 'tnt'
end
end
|
chuckmersereau/api_practice
|
app/models/account_list_coach.rb
|
class AccountListCoach < ApplicationRecord
belongs_to :coach, class_name: 'User::Coach'
belongs_to :account_list
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/people/relationships_controller.rb
|
<reponame>chuckmersereau/api_practice<filename>app/controllers/api/v2/contacts/people/relationships_controller.rb<gh_stars>0
class Api::V2::Contacts::People::RelationshipsController < Api::V2Controller
before_action :load_relationship, :authorize_relationship, only: [:show, :update, :destroy]
resource_type :family_relationships
def index
load_relationships
authorize @person, :show?
render json: @relationships.preload_valid_associations(include_associations),
meta: meta_hash(@relationships),
include: include_params,
fields: field_params
end
def show
render_relationship
end
def create
persist_relationship
end
def update
persist_relationship
end
def destroy
destroy_relationship
end
private
def destroy_relationship
@relationship.destroy
head :no_content
end
def persist_relationship
build_relationship
authorize_relationship
return show if save_relationship
render_with_resource_errors(@relationship)
end
def load_relationships
@relationships = relationship_scope.where(filter_params)
.reorder(sorting_param)
.page(page_number_param)
.per(per_page_param)
end
def load_relationship
@relationship ||= relationship_scope.find(params[:id])
end
def authorize_relationship
authorize @relationship
end
def render_relationship
render json: @relationship,
status: success_status,
include: include_params,
fields: field_params
end
def build_relationship
@relationship ||= relationship_scope.build
@relationship.assign_attributes(relationship_params)
end
def save_relationship
@relationship.save(context: persistence_context)
end
def relationship_scope
current_person.family_relationships
end
def current_contact
@contact ||= Contact.find(params[:contact_id])
end
def current_person
@person ||= current_contact.people.find(params[:person_id])
end
def relationship_params
params.require(:family_relationship)
.permit(relationship_attributes)
end
def relationship_attributes
FamilyRelationship::PERMITTED_ATTRIBUTES
end
def pundit_user
PunditContext.new(current_user, contact: current_contact)
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/reports/year_donations_controller.rb
|
class Api::V2::Reports::YearDonationsController < Api::V2Controller
def show
load_report
authorize_report
render_report
end
private
def load_report
@report ||= ::Reports::YearDonations.new(report_params)
end
def report_params
load_account_list ? { account_list: load_account_list } : {}
end
def load_account_list
@account_list ||= account_lists.order(:created_at).first
end
def render_report
render json: @report, fields: field_params, include: include_params
end
def permitted_filters
[:account_list_id]
end
def authorize_report
authorize(load_account_list, :show?)
end
end
|
chuckmersereau/api_practice
|
app/services/csv_file_constants_reader.rb
|
# This service object will read a CSV file and extract the unique values in each column.
# The purpose is to help map values in a user's CSV file to MPDX constants.
# Columns are ignored if they obviously aren't constants (like "name"), so not every column is returned.
# There is also a max number of values returned per column, to prevent an excessively large response.
class CsvFileConstantsReader
MAX_MAPPINGS_PER_HEADER = 100
EXCLUDE_HEADERS_CONTAINING_STRINGS = %w(
address
church
city
country
mail
metro
name
note
phone
postal
province
referred
region
state
street
tags
website
zip
).freeze
def initialize(file_path)
self.file_path = file_path
self.constants_hash = Hash.new { |hash, key| hash[key] = Set.new }
end
def constants
build_constant_sets
constants_hash
end
private
attr_accessor :file_path, :constants_hash, :headers
def build_constant_sets
@headers = nil
CsvFileReader.new(file_path).each_row do |csv_row|
@headers ||= csv_row.headers
csv_row.fields.each_with_index do |value, index|
header = headers[index]&.parameterize&.underscore
next if exclude_column_with_header?(header)
constant_set = constants_hash[header]
value = '' if value.blank? # Use empty strings instead of nil
constant_set << value if constant_set.size < MAX_MAPPINGS_PER_HEADER
end
end
end
def exclude_column_with_header?(header)
return true if header.blank?
header = header.to_s.downcase
EXCLUDE_HEADERS_CONTAINING_STRINGS.any? { |substring| header.include?(substring) }
end
end
|
chuckmersereau/api_practice
|
app/policies/email_address_policy.rb
|
class EmailAddressPolicy < ApplicationPolicy
attr_reader :contact
attr_reader :person
def initialize(context, resource)
@contact = context.contact
@person = context.person
@resource = resource
@user = context.user
end
private
def person_has_ownership_of_email_address?(email = resource)
person.id = email.person_id
end
def resource_owner?
user_can_access_current_persons_email_addresses? &&
person_has_ownership_of_email_address?
end
def user_can_access_current_persons_email_addresses?
user_is_person? || user_has_ownership_of_person?
end
def user_has_ownership_of_person?
user.account_lists.exists?(id: contact.account_list_id) &&
person.contacts.exists?(id: contact.id)
end
def user_is_person?
user.id == person.id
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/stopped_giving_range.rb
|
# We define stopped giving any contact with at least 3
# gifts that gave his last donation within the time range.
class Contact::Filter::StoppedGivingRange < Contact::Filter::Base
# If a donor stopped giving after 3 gifts we can assume
# that he actually gave regularly and then stopped
PRIOR_NUMBER_OF_GIFTS = 3
def execute_query(scope, filters)
@contacts_that_have_stopped_giving = scope.where(last_donation_date: filters[:stopped_giving_range])
end_date = filters[:stopped_giving_range].last
@last_ten_months = (end_date - 10.months)..end_date
@contacts_that_have_stopped_giving.where(id: stopped_giving_and_many_donations_contact_ids)
end
def valid_filters?(filters)
super &&
date_range?(filters[:stopped_giving_range]) &&
filters[:stopped_giving_range].last <= valid_end_date
end
private
def valid_end_date
1.month.ago + 1.day
end
def stopped_giving_and_many_donations_contact_ids
conditions = {
contact_donor_accounts: { contact_id: @contacts_that_have_stopped_giving.pluck(:id) },
donations: { donation_date: @last_ten_months }
}
DonorAccount.joins({ contact_donor_accounts: :contact }, :donations)
.where(conditions)
.group('contacts.id')
.having('COUNT(*) >= ?', PRIOR_NUMBER_OF_GIFTS).pluck('contacts.id')
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_donation_amount_recommendation_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/services/task/filter/contact_donation_amount_recommendation_spec.rb
require 'rails_helper'
RSpec.describe Task::Filter::ContactDonationAmountRecommendation do
subject { described_class.new }
describe '#execute_query' do
let(:organization) { create(:organization) }
let(:designation_account) { create(:designation_account, organization: organization) }
let!(:account_list) { create(:account_list, designation_accounts: [designation_account]) }
let(:tasks) { account_list.activities }
let(:donor_account1) { create(:donor_account, organization: organization, account_number: '123') }
let(:donor_account2) { create(:donor_account, organization: organization, account_number: '456') }
let(:donor_account3) { create(:donor_account, organization: organization, account_number: '789') }
let!(:contact1) do
create(
:contact,
account_list: account_list,
pledge_amount: 10,
pledge_frequency: 1,
donor_accounts: [donor_account1]
)
end
let!(:contact2) do
create(
:contact,
account_list: account_list,
pledge_amount: 10,
pledge_frequency: 1,
donor_accounts: [donor_account2]
)
end
let!(:contact3) do
create(
:contact,
account_list: account_list,
pledge_amount: 20,
pledge_frequency: 1,
donor_accounts: [donor_account3]
)
end
let!(:contact4) { create(:contact, account_list: account_list) }
let!(:donation_amount_recommendation1) do
create(
:donation_amount_recommendation,
suggested_pledge_amount: 20,
donor_account: donor_account1,
designation_account: designation_account
)
end
let!(:donation_amount_recommendation2) do
create(
:donation_amount_recommendation,
suggested_pledge_amount: 20,
donor_account: donor_account2,
designation_account: designation_account
)
end
let!(:donation_amount_recommendation3) do
create(
:donation_amount_recommendation,
suggested_pledge_amount: 20,
donor_account: donor_account3,
designation_account: designation_account
)
end
let!(:task1) { create :task, contacts: [contact1], account_list: account_list }
let!(:task2) { create :task, contacts: [contact2], account_list: account_list }
let!(:task3) { create :task, contacts: [contact3], account_list: account_list }
let!(:task4) { create :task, contacts: [contact4], account_list: account_list }
context 'filter is Yes' do
it 'should return tasks with contacts with recommendations' do
expect(subject.execute_query(tasks, contact_donation_amount_recommendation: 'Yes')).to match_array(
[task1, task2]
)
end
end
context 'filter is No' do
it 'should return tasks with contacts without recommendations' do
expect(subject.execute_query(tasks, contact_donation_amount_recommendation: 'No')).to match_array(
[task3, task4]
)
end
end
end
describe '#title' do
it 'should return "Increase Gift Recommendation"' do
expect(subject.title).to eq 'Increase Gift Recommendation'
end
end
describe '#parent' do
it 'should return "Contact Gift Details"' do
expect(subject.parent).to eq 'Contact Gift Details'
end
end
describe '#type' do
it 'should return "radio"' do
expect(subject.type).to eq 'radio'
end
end
describe '#custom_options' do
it 'should return array of options' do
expect(subject.custom_options).to eq(
[{ name: _('Yes'), id: 'Yes' }, { name: _('No'), id: 'No' }]
)
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120924065159_add_result_to_activity.rb
|
<filename>db/migrate/20120924065159_add_result_to_activity.rb
class AddResultToActivity < ActiveRecord::Migration
def change
add_column :activities, :result, :string
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170511182604_add_missing_indexes.acts_as_taggable_on_engine.rb
|
# This migration comes from acts_as_taggable_on_engine (originally 6)
class AddMissingIndexes < ActiveRecord::Migration
disable_ddl_transaction!
def change
add_index :taggings, :tag_id, algorithm: :concurrently
add_index :taggings, :taggable_type, algorithm: :concurrently
add_index :taggings, :tagger_id, algorithm: :concurrently
add_index :taggings, :context, algorithm: :concurrently
add_index :taggings, [:tagger_id, :tagger_type], algorithm: :concurrently
add_index :taggings, [:taggable_id, :taggable_type, :tagger_id, :context], name: 'taggings_idy', algorithm: :concurrently
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/bulk_taggable.rb
|
module BulkTaggable
extend ActiveSupport::Concern
included do
skip_before_action :validate_and_transform_bulk_json_api_params
end
def tag_names
params
.require(:data)
.collect(&method(:extract_tag_name))
end
def taggable_ids
tags_scope.tagged_with(tag_names, any: true).ids.uniq
end
def tags_scope
raise NotImplementedError, 'must implement this in the controller directly'
end
private
def missing_id_error
# This method is a no-op because we do not care about IDs for tags
end
def extract_tag_name(hash)
name = hash.dig(:data, :attributes, :name)
return name if name.is_a?(String)
type = type_name(name)
raise Exceptions::BadRequestError,
format('Expected tag name to be a string, but it was %s %s with a value of %p',
type.indefinite_article, type, name)
end
def type_name(object)
if object.is_a?(Hash) || object.is_a?(ActionController::Parameters)
'object'
else
name.class.name.downcase
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/notifications.rb
|
FactoryBot.define do
factory :notification do
notification_type
cleared false
event_date '2012-10-23 17:03:15'
contact
donation
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/tasks/analytics_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::Tasks::AnalyticsController, type: :controller do
# This is required!
let(:user) { create(:user_with_account) }
# This MAY be required!
let(:account_list) { user.account_lists.order(:created_at).first }
# This is required!
let!(:resource) do
# Creates the Singular Resource for this spec - change as needed
# Example: create(:contact, account_list: account_list)
Task::Analytics.new(user.tasks)
end
# If needed, keep this ;)
let(:parent_param) do
# This is a hash of the nested keys needed for the URL,
# If the resource is listed more than once, you can add multiple.
# Ex: /api/v2/:account_list_id/contacts/:contact_id/addresses/:id
# --
# Note: Don't include :id
# Example: { account_list_id: account_list.id }
{}
end
# This is required!
let(:correct_attributes) do
# A hash of correct attributes for creating/updating the resource
# Example: { subject: 'test subject', start_at: Time.now, account_list_id: account_list.id }
{}
end
# These includes can be found in:
# spec/support/shared_controller_examples
include_examples 'show_examples', except: [:sparse_fieldsets]
end
|
chuckmersereau/api_practice
|
app/models/contact_donor_account.rb
|
class ContactDonorAccount < ApplicationRecord
belongs_to :contact, inverse_of: :contact_donor_accounts
belongs_to :donor_account, inverse_of: :contact_donor_accounts
validate :ensure_one_contact_per_donor_account_number
audited associated_with: :contact
def ensure_one_contact_per_donor_account_number
if contact.account_list.donor_accounts.where(account_number: donor_account.account_number).any?
contact.errors.add(:base, _('Another contact on your account already has the donor '\
"account number you've tried to assign to this contact."))
false
end
# Organization either doesn't sync automatically or doesn't support donors with same ID
if contact.account_list.designation_accounts.empty? &&
donor_account.organization.donor_accounts.where(account_number: donor_account.account_number).any?
contact.errors.add(:base, _('Another contact in your organization already has the donor '\
"account number you've tried to assign to this contact. "\
'Please make it more unique.'))
false
end
true
end
end
|
chuckmersereau/api_practice
|
spec/services/contact_merge_spec.rb
|
<filename>spec/services/contact_merge_spec.rb
require 'rails_helper'
# Note, the Contact spec has a number of cases for contact merging as well
describe ContactMerge do
let(:account_list) { create(:account_list) }
it 'combines the send_newsletter field' do
winner = create(:contact, send_newsletter: 'Email')
loser = create(:contact, send_newsletter: 'Physical')
winner.merge(loser)
expect(winner.reload.send_newsletter).to eq 'Both'
end
it 'prefers a non-default greeting and envelope greeting to default' do
winner = create(:contact, greeting: nil, envelope_greeting: nil)
loser = create(:contact, greeting: 'Hi', envelope_greeting: 'Hello')
winner.merge(loser)
winner.reload
expect(winner.greeting).to eq 'Hi'
expect(winner.envelope_greeting).to eq 'Hello'
end
it 'transfers activities, but does not duplicate them' do
winner = create(:contact)
loser = create(:contact)
winner.activities << create(:activity, subject: 'Random Task')
loser.activities << create(:activity, subject: 'Random Task')
loser.activities << create(:activity, subject: 'Random Task #2')
winner.merge(loser)
winner.reload
expect(winner.activities.count).to eq(2)
end
it 'transfers pledges' do
winner = create(:contact, account_list: account_list)
loser = create(:contact, account_list: account_list)
appeal = create(:appeal, account_list: account_list)
appeal.contacts << loser
pledge = create(:pledge, contact: loser, appeal: appeal)
winner.merge(loser)
expect(appeal.contacts.reload).to include winner
expect(pledge.reload.contact).to eq winner
end
it 'marks loser addresses as not primary' do
winner = create(:contact)
loser = create(:contact)
create(:address, primary_mailing_address: true, addressable: winner, street: '1 Test Road')
loser_address = create(:address, primary_mailing_address: true, addressable: loser, street: '2 Test Road')
winner.merge(loser)
winner.reload
expect(winner.addresses.find(loser_address.id).primary_mailing_address).to eq false
end
it 'removes the DuplicateRecordPair' do
account_list = create(:account_list)
winner = create(:contact, account_list: account_list)
loser = create(:contact, account_list: account_list)
duplicate_record_pair = DuplicateRecordPair.create!(record_one: winner, record_two: loser,
account_list: account_list, reason: 'Testing')
DuplicateRecordPair.new(record_one_id: winner.id, record_one_type: 'Person', record_two_id: loser.id,
record_two_type: 'Contact', account_list: account_list, reason: 'Testing')
.save(validate: false)
expect { winner.merge(loser) }.to change { DuplicateRecordPair.count }.from(2).to(1)
expect(DuplicateRecordPair.exists?(duplicate_record_pair.id)).to eq(false)
end
context '.merged_send_newsletter' do
it 'combines email and physical for all cases' do
[
['Email', '', 'Email'],
%w(Email Physical Both),
[nil, 'Physical', 'Physical'],
[nil, '', nil]
].each do |winner, loser, merged|
expect(ContactMerge.merged_send_newsletter(winner, loser)).to eq merged
expect(ContactMerge.merged_send_newsletter(loser, winner)).to eq merged
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/expected_totals_report/likely_donation_spec.rb
|
require 'rails_helper'
describe ExpectedTotalsReport::LikelyDonation, '#likely_more' do
it 'gives zero if pledge not received' do
contact = build_stubbed(:contact, pledge_received: false,
status: 'Partner - Financial')
expect_zero_amount(contact)
end
it 'gives zero if not financial partner' do
contact = build_stubbed(:contact, pledge_received: false,
status: 'Partner - Special')
expect_zero_amount(contact)
end
it 'gives zero if there is no commitment amount' do
contact = build_stubbed(:contact, pledge_received: true,
status: 'Partner - Financial', pledge_amount: nil)
expect_zero_amount(contact)
end
it 'gives zero if pledge_frequency is nil' do
contact = build_stubbed(:contact, pledge_received: true,
status: 'Partner - Financial', pledge_amount: 5,
pledge_frequency: nil)
expect_zero_amount(contact)
end
def expect_zero_amount(contact)
expect(ExpectedTotalsReport::LikelyDonation
.new(contact: contact, recent_donations: [], date_in_month: Date.new(2016, 1, 1))
.likely_more)
.to eq 0.0
end
# These are for a financial partner with a pledge amount of 5.
MONTH_BASED_TEST_CASES = [
# Expect zero if no donations given yet
{ pledge_frequency: 1, recent_donations: [], likely_more: 0 },
# Expect full commitment if started giving and no missed months (first zero
# is for current month).
{ pledge_frequency: 1, recent_donations: [0, 5], likely_more: 5 },
{ pledge_frequency: 1, recent_donations: [0, 5, 5, 5], likely_more: 5 },
# Expect 0 if partner already gave this month.
{ pledge_frequency: 1, recent_donations: [5], likely_more: 0 },
# Partner started, has been consistent last 3+ months, but only gave
# partial amount this month. Most likely they give twice per month. I have a
# ministry partner like that who gives $50/mo from both husband and wife at
# slightly different times of the month.
{ pledge_frequency: 1, recent_donations: [3, 5, 5, 5], likely_more: 2 },
# Partner started, has not been consistent for 3+ months, and only gave
# partial amount. Most likely they are kind of flaky and they may not be
# willing to follow through on their commitment.
{ pledge_frequency: 1, recent_donations: [3, 5, 5], likely_more: 0 },
# Partner has not been consistent the past 3 months even though they gave
# full amount previous month. Assume they are flaky and won't give.
{ pledge_frequency: 1, recent_donations: [0, 5, 0, 5], likely_more: 0 },
# Partner has averaged out to consistent over the past 3 months even though
# they have missed a specific month in the past 3. They have given at
# least something in at least 2 of the 3 last months. Expect they will give.
{ pledge_frequency: 1, recent_donations: [0, 0, 10, 5], likely_more: 5 },
# Partner has averaged out to consistent over the past 3 months, but they
# have missed 2 of the last 3 months. Assume they won't give this month
# because they seem to be more of a sporatic giver.
{ pledge_frequency: 1, recent_donations: [0, 0, 0, 15], likely_more: 0 },
# Partner has not averaged out to consistent over the past 3 months and they
# have also missed last month. Assume they are not going to give this month.
{ pledge_frequency: 1, recent_donations: [0, 0, 5, 5], likely_more: 0 },
# Partner has been giving less than their commitment. Assume they are
# giving special gifts but are not keeping up with their commitment.
# This could motivate the user to contact the partner and correct the amount.
{ pledge_frequency: 1, recent_donations: [0, 4, 4, 4], likely_more: 0 },
# Partner has been consistent on average but only occasionally gives (less
# than 2 of past 3 months have any gifts) even though their specified
# commitment frequency is monthly. Assume they give when they feel like
# it to randomly making up missed months and to be conservative assume they
# won't choose this month to make it up.
{ pledge_frequency: 1, recent_donations: [0, 0, 0, 15], likely_more: 0 },
# Partner has been giving more than their commitment, but only assume they
# will give their commitment this month.
{ pledge_frequency: 1, recent_donations: [0, 8, 6, 7], likely_more: 5 },
# Partner started giving and this is their month to give because they gave
# two months ago.
{ pledge_frequency: 2, recent_donations: [0, 0, 5], likely_more: 5 },
# Partner has started giving but this is not their month to give because
# they gave last month.
{ pledge_frequency: 2, recent_donations: [0, 5], likely_more: 0 },
# Partner has been somewhat inconsistent in which month they give,
# but they gave two months ago (and are bi-monthly), so assume they will
# give this month.
{ pledge_frequency: 2, recent_donations: [0, 0, 5, 5, 0, 0, 5, 0, 5],
likely_more: 5 },
# Annual partner gave this month last year, but has only given once.
# Assume they won't give this month - subtly prompting the user to follow
# up with them (they should have gotten the "expected gift in a month"
# notice if they had that setting turned on). Last gift did not have the
# channel of "Recurring"
{ pledge_frequency: 12, recent_donations: Array.new(12, 0) + [5],
channel: 'Mail', likely_more: 0 },
# Annual partner gave only once on this month last year but gift channel
# was "Recurring". Assume they will give.
{ pledge_frequency: 12, recent_donations: Array.new(12, 0) + [5],
channel: 'Recurring', likely_more: 5 },
# Annual partner gave this month last year and the same month the year
# before. Assume they will give this month.
{ pledge_frequency: 12,
recent_donations: Array.new(12, 0) + [5] + Array.new(11, 0) + [5],
channel: 'Mail', likely_more: 5 },
# Partner is set as Annual but they have been making up their annual
# commitment by giving at random increments throughout the year.
# Assume they won't give this month.
{ pledge_frequency: 12,
recent_donations: [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 3] +
Array.new(11, 0) + [5],
channel: 'Mail', likely_more: 0 },
# Partner is set to Annual, has given for the past two years but last year
# gave less than their commitment. Assume won't give this month.
{ pledge_frequency: 12,
recent_donations: Array.new(12, 0) + [4] + Array.new(11, 0) + [5],
channel: 'Mail', likely_more: 0 },
# Annual partner is up to date in their giving, but occasionally gives
# special gifts, that's OK, that shouldn't confuse the system to think
# they are inconsistent. (Assuming they gave the past 2 years on the same
# month).
{ pledge_frequency: 12,
recent_donations: [0, 0, 0, 2, 0, 0, 1, 1, 0, 0, 0, 0, 5] +
Array.new(11, 0) + [5],
channel: 'Mail', likely_more: 5 }
].freeze
it 'examines recent donation history and guesses expected gift amounts' do
contact = build_stubbed(:contact, pledge_received: true,
status: 'Partner - Financial', pledge_amount: 5)
MONTH_BASED_TEST_CASES.each do |test_case|
expect_correct_amount(contact, test_case)
end
end
def expect_correct_amount(contact, test_case)
contact.pledge_frequency = test_case[:pledge_frequency]
donations = []
test_case[:recent_donations].each_with_index do |amount, index|
next if amount.zero?
date = Date.current << index
donations << build_stubbed(:donation, tendered_amount: amount,
donation_date: date,
channel: test_case[:channel])
end
update_donation_dates(contact, donations)
actual_amount = ExpectedTotalsReport::LikelyDonation
.new(contact: contact, recent_donations: donations, date_in_month: Date.current)
.likely_more
return if actual_amount == test_case[:likely_more]
message = "Expected #{test_case[:likely_more]} but got #{actual_amount} "\
"for case #{test_case.inspect}"
expect(actual_amount).to eq(test_case[:likely_more]), message
end
describe 'for weekly donors' do
let(:weekly) { Contact.pledge_frequencies.invert['Weekly'] }
let(:contact) do
build_stubbed(:contact, pledge_amount: 5, pledge_frequency: weekly,
pledge_received: true)
end
it 'gives zero if fewer than two weeks worth of gifts in past 17 days' do
donations = [
build_stubbed(:donation, amount: 5, donation_date: Date.new(2016, 4, 20))
]
update_donation_dates(contact, donations)
expect(ExpectedTotalsReport::LikelyDonation
.new(contact: contact, recent_donations: donations,
date_in_month: Date.new(2016, 4, 29)).likely_more)
.to eq 0.0
end
it 'gives pledge times full weeks remaining in month if recently consistent' do
donations = [
build_stubbed(:donation, amount: 5, donation_date: Date.new(2016, 4, 3)),
build_stubbed(:donation, amount: 5, donation_date: Date.new(2016, 4, 10))
]
update_donation_dates(contact, donations)
expect(ExpectedTotalsReport::LikelyDonation
.new(contact: contact, recent_donations: donations,
date_in_month: Date.new(2016, 4, 13)).likely_more)
.to eq 10
end
end
describe 'for fortnightly donors' do
let(:fortnightly) { Contact.pledge_frequencies.invert['Every 2 Weeks'] }
let(:contact) do
build_stubbed(:contact, pledge_amount: 5, pledge_received: true,
pledge_frequency: fortnightly)
end
it 'gives zero if fewer than two gifts worth received in past 31 days' do
donations = [
build_stubbed(:donation, amount: 5, donation_date: Date.new(2016, 4, 20))
]
update_donation_dates(contact, donations)
expect(ExpectedTotalsReport::LikelyDonation
.new(contact: contact, recent_donations: donations,
date_in_month: Date.new(2016, 4, 29)).likely_more)
.to eq 0.0
end
it 'gives pledge times full 14 day periods remaining in month' do
donations = [
build_stubbed(:donation, amount: 5, donation_date: Date.new(2016, 3, 27)),
build_stubbed(:donation, amount: 5, donation_date: Date.new(2016, 4, 10))
]
update_donation_dates(contact, donations)
expect(ExpectedTotalsReport::LikelyDonation
.new(contact: contact, recent_donations: donations,
date_in_month: Date.new(2016, 4, 10)).likely_more)
.to eq 5
end
end
def update_donation_dates(contact, donations)
contact.first_donation_date = donations.map(&:donation_date).min
contact.last_donation_date = donations.map(&:donation_date).max
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/pundit_helpers.rb
|
<reponame>chuckmersereau/api_practice
module PunditHelpers
private
def bulk_authorize(resources, action = nil)
resources.all? do |resource|
authorize(resource, action)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/notes_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Contact::Filter::Notes do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:person) do
create(:person, first_name: 'PersonFirstName', last_name: 'PersonLastName',
email_addresses: [build(:email_address, email: '<EMAIL>')],
phone_numbers: [build(:phone_number, number: '514 122-4362')])
end
let!(:contact_one) do
create(:contact, account_list: account_list,
notes: 'the random notes',
name: '<NAME>',
donor_accounts: [build(:donor_account, account_number: '1234567890')])
end
let!(:contact_two) do
create(:contact, account_list: account_list, notes: 'this is my favourite person', name: '<NAME>')
end
let!(:contact_three) do
create(:contact, account_list: account_list, notes: 'missing notes', name: '<NAME>', people: [person])
end
let!(:contact_four) { create(:contact, account_list: account_list, notes: nil, name: '<NAME>') }
def wildcard_search_notes(value, note_search)
described_class.query(contacts, { wildcard_search: value, notes: { wildcard_note_search: note_search } }, nil).to_a
end
describe '#query' do
let(:contacts) { account_list.contacts }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(contacts, {}, nil)).to eq(nil)
expect(described_class.query(contacts, { wildcard_search: {} }, nil)).to eq nil
expect(described_class.query(contacts, { wildcard_search: [] }, nil)).to eq nil
expect(described_class.query(contacts, { wildcard_search: '' }, nil)).to eq nil
end
end
context 'filter notes with wildcard search' do
it 'returns only contacts that match the search query' do
expect(wildcard_search_notes('Jones', 'notes')).to match_array [contact_one, contact_three]
expect(wildcard_search_notes('Jones', 'missing notes')).to eq [contact_three]
expect(wildcard_search_notes('Freddie', 'random notes')).to eq [contact_one]
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/email_address/google_plus_account_fetcher.rb
|
require 'net/http'
class EmailAddress::GooglePlusAccountFetcher
attr_accessor :email_address
def initialize(email_address)
@email_address = email_address
end
def fetch_google_plus_account
google_plus_json_object = fetch_google_plus_json_object
return unless google_plus_json_object
GooglePlusAccount.new(account_id: google_plus_json_object.dig('gphoto$user', '$t'),
profile_picture_link: google_plus_json_object.dig('gphoto$thumbnail', '$t'))
end
private
def fetch_google_plus_json_object
uri = URI("https://picasaweb.google.com/data/entry/api/user/#{email_encoded}?alt=json")
response = Net::HTTP.get(uri)
JSON.parse(response)
rescue JSON::ParserError
nil
end
def email_encoded
URI.encode_www_form_component(email_address.email)
end
end
|
chuckmersereau/api_practice
|
app/serializers/person/key_account_serializer.rb
|
class Person::KeyAccountSerializer < ApplicationSerializer
type :key_accounts
attributes :email,
:first_name,
:last_download,
:last_name,
:primary,
:remote_id
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/appeals/excluded_appeal_contacts_controller.rb
|
class Api::V2::Appeals::ExcludedAppealContactsController < Api::V2Controller
resource_type :excluded_appeal_contacts
before_action :load_appeal
def index
authorize @appeal, :show?
load_excluded_appeal_contacts
render json: @excluded_appeal_contacts.preload_valid_associations(include_associations),
meta: meta_hash(@excluded_appeal_contacts),
include: include_params,
fields: field_params
end
def show
load_excluded_appeal_contact
authorize_excluded_appeal_contact
render_excluded_appeal_contact
end
def destroy
load_excluded_appeal_contact
authorize_excluded_appeal_contact
@excluded_appeal_contact.destroy
head :no_content
end
private
def load_excluded_appeal_contacts
@excluded_appeal_contacts = excluded_appeal_contact_scope.where(filter_params)
.joins(sorting_join)
.reorder(sorting_param)
.page(page_number_param)
.per(per_page_param)
end
def load_excluded_appeal_contact
@excluded_appeal_contact ||= excluded_appeal_contact_scope.find(params[:id])
end
def excluded_appeal_contact_scope
Appeal::ExcludedAppealContact.where(appeal: @appeal)
end
def render_excluded_appeal_contact
render json: @excluded_appeal_contact,
status: :ok,
include: include_params,
fields: field_params
end
def authorize_excluded_appeal_contact
authorize @excluded_appeal_contact
end
def load_appeal
@appeal ||= Appeal.find(params[:appeal_id])
end
def pundit_user
PunditContext.new(current_user)
end
def permitted_sorting_params
%w(contact.name)
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/donation_amount_recommendations_controller_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Api::V2::Contacts::DonationAmountRecommendationsController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:resource_type) { :donation_amount_recommendation }
let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) }
let!(:organization) { create :organization }
let!(:designation_account) { create :designation_account, organization: organization }
let!(:donor_account1) { create :donor_account, organization: organization, account_number: '123' }
let!(:donor_account2) { create :donor_account, organization: organization, account_number: '456' }
let!(:resource) do
create(
:donation_amount_recommendation,
designation_account: designation_account,
donor_account: donor_account1
)
end
let!(:second_resource) do
create(
:donation_amount_recommendation,
designation_account: designation_account,
donor_account: donor_account2
)
end
let(:id) { resource.id }
let(:parent_param) { { contact_id: contact.id } }
let(:parent_association) { :donation_amount_recommendations }
let(:factory_type) { :donation_amount_recommendation }
let(:correct_attributes) do
{
suggested_pledge_amount: 123,
suggested_special_amount: 456,
ask_at: Time.zone.now + 1.day,
started_at: Time.zone.now - 2.years
}
end
before(:each) do
designation_account.account_lists << account_list
contact.donor_accounts << donor_account1
contact.donor_accounts << donor_account2
end
include_examples 'index_examples'
include_examples 'show_examples'
describe '#index authorization' do
it 'does not show resources for contact that user does not own' do
api_login(user)
contact = create(:contact, account_list: create(:user_with_account).account_lists.order(:created_at).first)
get :index, contact_id: contact.id
expect(response.status).to eq(403)
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/auth/provider/mail_chimp_accounts_controller_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe Auth::Provider::MailChimpAccountsController, :auth, type: :controller do
routes { Auth::Engine.routes }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
before(:each) do
auth_login(user)
request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:mailchimp]
end
context 'with no preexisting MailChimpAccount' do
it 'should create a MailChimpAccount' do
expect do
get :create, nil, account_list_id: account_list_id
end.to change(MailChimpAccount, :count).by(1)
expect(MailChimpAccount.order(:created_at).last.active).to be true
end
end
context 'with a preexisting MailChimpAccount' do
let!(:mail_chimp_account) { create(:mail_chimp_account, account_list: account_list) }
it 'should not create a MailChimpAccount' do
expect do
get :create, nil, account_list_id: account_list_id
end.to_not change(MailChimpAccount, :count)
end
it 'should update the existing MailChimpAccount' do
expect do
get :create, nil, account_list_id: account_list_id
mail_chimp_account.reload
end.to change { mail_chimp_account.api_key }.and(change { mail_chimp_account.active }.to(true))
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/exports_controller_spec.rb
|
<gh_stars>0
require 'rails_helper'
require 'tempfile'
require 'roo'
describe Api::V2::Contacts::ExportsController, type: :controller do
let(:factory_type) { :contact }
let!(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:second_account_list) { create(:account_list, users: [user]) }
let(:resource) { create(:export_log, user: user) }
let(:id) { resource.id }
let(:incorrect_attributes) { nil }
let(:correct_attributes) do
{
params: {
filter: {
status: 'active'
}
}
}
end
let!(:contact) { create(:contact, account_list: account_list, name: 'Last Contact', primary_person: primary_person) }
let!(:second_contact) { create(:contact_with_person, account_list: account_list, name: 'First Contact') }
let!(:third_contact) { create(:contact_with_person, account_list: second_account_list, name: 'Missing Contact') }
let!(:primary_person) { create(:person, first_name: 'Bill') }
let!(:spouse_person) { create(:person, contacts: [contact], first_name: 'Vonette') }
let!(:primary_email_address) { create(:email_address, primary: true, person: primary_person) }
let!(:spouse_email_address) { create(:email_address, primary: true, person: spouse_person) }
let!(:spouse_other_email_address) { create(:email_address, primary: false, person: spouse_person) }
let!(:primary_phone_number) { create(:phone_number, primary: true, person: primary_person) }
let!(:spouse_phone_number) { create(:phone_number, primary: true, person: spouse_person) }
let!(:spouse_other_phone_number) { create(:phone_number, primary: false, person: spouse_person) }
let(:expected_headers1) { '"Primary Email","Spouse Email","Other Email","Spouse Other Email"' }
let(:expected_headers2) { '"Primary Phone","Spouse Phone","Other Phone","Spouse Other Phone"' }
include_examples 'show_examples'
include_examples 'create_examples'
describe '#show' do
it 'only allows export display to occur once' do
api_login(user)
get :show, id: resource.id
expect(response.status).to eq(200)
get :show, id: resource.id
expect(response.status).to eq(403)
end
it 'sets active to false' do
api_login(user)
get :show, id: resource.id
expect(resource.reload.active).to eq(false)
end
it 'uses contact filtering instead of generic filtering' do
resource.update(
params: {
filter: {
donation_amount_range: {
min: '500'
},
account_list_id: account_list_id,
any_tags: false
}
}.to_json
)
api_login(user)
get :show, id: resource.id, format: :csv
expect(response.status).to eq(200)
end
end
render_views
context 'CSV and XLSX export' do
it 'does not shows resources to users that are not signed in' do
[:csv, :xlsx].each do |format|
get :index, format: format
expect(response.status).to eq(401)
end
end
it 'logs the CSV export if successful' do
api_login(user)
expect do
get :index, format: :csv
end.to change { ExportLog.count }.from(0).to(1)
expect(response.status).to eq(200)
expect(ExportLog.first.active).to eq(false)
end
it 'logs the XLSX export if successful' do
api_login(user)
expect do
get :index, format: :xlsx
end.to change { ExportLog.count }.from(0).to(1)
expect(response.status).to eq(200)
expect(ExportLog.first.active).to eq(false)
expect(ExportLog.first.type).to eq('Contacts')
end
end
context 'CSV export' do
let(:contact_index) { response.body.index(contact.name) }
let(:second_contact_index) { response.body.index(second_contact.name) }
it 'renders the export sorted alphabetically for users that are signed in' do
api_login(user)
get :index, format: :csv
expect(response.status).to eq(200)
expect(contact_index).to be_present
expect(response.body).to be_present
expect(contact_index).to be > second_contact_index
end
it 'renders the export with right contacts when contact_ids is provided' do
api_login(user)
get :index, format: :csv, filter: { ids: contact.id }
expect(response.status).to eq(200)
expect(contact_index).to be_present
expect(response.body).to be_present
end
it 'allows filtering by account_list_id' do
api_login(user)
get :index, format: :csv, filter: { account_list_id: second_account_list.id }
expect(response.status).to eq(200)
expect(response.body).to include(third_contact.name)
expect(response.body).to_not include(contact.name)
end
it 'renders both the primary person and spouse phone and email address' do
api_login(user)
get :index, format: :csv
expect(response.status).to eq(200)
expect(response.body).to include(expected_headers1)
expect(response.body).to include(expected_headers2)
email_addresses = "#{primary_email_address.email},#{spouse_email_address.email}"\
",,#{spouse_other_email_address.email}"
expect(response.body).to include(email_addresses)
phone_numbers = "#{primary_phone_number.number},#{spouse_phone_number.number}"\
",,#{spouse_other_phone_number.number}"
expect(response.body).to include(phone_numbers)
end
end
context 'XLSX export' do
let(:contact_index) { spreadsheet.to_csv.index(contact.name) }
let(:second_contact_index) { spreadsheet.to_csv.index(second_contact.name) }
let(:third_contact_index) { spreadsheet.to_csv.index(third_contact.name) }
it 'renders the export sorted alphabetically for users that are signed in' do
api_login(user)
get :index, format: :xlsx
expect(contact_index).to be_present
expect(second_contact_index).to be_present
expect(contact_index).to be > second_contact_index
end
it 'renders the export with right contacts when contact_ids is provided' do
api_login(user)
get :index, format: :xlsx, filter: { ids: contact.id }
expect(response.status).to eq(200)
expect(contact_index).to be_present
expect(second_contact_index).to be_blank
end
it 'allows filtering by account_list_id' do
api_login(user)
get :index, format: :xlsx, filter: { account_list_id: second_account_list.id }
expect(response.status).to eq(200)
expect(contact_index).to be_blank
expect(third_contact_index).to be_present
end
it 'renders both the primary person and spouse phone and email address' do
api_login(user)
get :index, format: :xlsx
expect(response.status).to eq(200)
expect(spreadsheet.to_csv).to include(expected_headers1)
expect(spreadsheet.to_csv).to include(expected_headers2)
email_addresses = "#{primary_email_address.email}\",\"#{spouse_email_address.email}\""\
",,\"#{spouse_other_email_address.email}"
expect(spreadsheet.to_csv).to include(email_addresses)
phone_numbers = "#{primary_phone_number.number}\",\"#{spouse_phone_number.number}\""\
",,\"#{spouse_other_phone_number.number}"
expect(spreadsheet.to_csv).to include(phone_numbers)
end
end
context 'Primary Person is deceased' do
before { primary_person.update!(deceased: true) }
it 'renders only the spouse as the primary person' do
api_login(user)
get :index, format: :csv
expect(response.status).to eq(200)
row = CSV.parse(response.body, headers: true).find { |r| r['Contact Name'] == contact.name }
expect(row).to_not be nil
expect(row.to_hash).to include('First Name' => 'Vonette',
'Last Name' => spouse_person.last_name,
'Primary Email' => spouse_email_address.email,
'Spouse Email' => nil,
'Other Email' => spouse_other_email_address.email,
'Spouse Other Email' => nil,
'Primary Phone' => spouse_phone_number.number,
'Spouse Phone' => nil,
'Other Phone' => spouse_other_phone_number.number,
'Spouse Other Phone' => nil)
end
end
context 'Spouse is deceased' do
before { spouse_person.update!(deceased: true) }
it 'renders only the primary person phone and email address' do
api_login(user)
get :index, format: :csv
expect(response.status).to eq(200)
row = CSV.parse(response.body, headers: true).find { |r| r['Contact Name'] == contact.name }
expect(row).to_not be nil
expect(row.to_hash).to include('First Name' => 'Bill',
'Last Name' => primary_person.last_name,
'Primary Email' => primary_email_address.email,
'Spouse Email' => nil,
'Other Email' => nil,
'Spouse Other Email' => nil,
'Primary Phone' => primary_phone_number.number,
'Spouse Phone' => nil,
'Other Phone' => nil,
'Spouse Other Phone' => nil)
end
end
context 'Both Primary Person and Spouse are deceased' do
before { primary_person.update!(deceased: true) }
before { spouse_person.update!(deceased: true) }
it 'does not render the row at all' do
api_login(user)
get :index, format: :csv
expect(response.status).to eq(200)
row = CSV.parse(response.body, headers: true).find { |r| r['Contact Name'] == contact.name }
expect(row).to be nil
end
end
def spreadsheet
temp_xlsx = Tempfile.new('temp')
temp_xlsx.write(response.body)
temp_xlsx.rewind
Roo::Spreadsheet.open(temp_xlsx.path, extension: :xlsx)
end
end
|
chuckmersereau/api_practice
|
app/workers/mail_chimp/export_contacts_worker.rb
|
class MailChimp::ExportContactsWorker
include Sidekiq::Worker
sidekiq_options queue: :api_mail_chimp_sync_worker, unique: :until_executed
def perform(mail_chimp_account_id, list_id, contact_ids, ignore_status = false)
mail_chimp_account = MailChimpAccount.find_by(id: mail_chimp_account_id)
return unless mail_chimp_account
MailChimp::Exporter.new(mail_chimp_account, list_id)
.export_contacts(contact_ids, ignore_status)
end
end
|
chuckmersereau/api_practice
|
config/initializers/resource_type_to_db_type.rb
|
<reponame>chuckmersereau/api_practice<filename>config/initializers/resource_type_to_db_type.rb
RESOURCE_TYPE_TO_DB_TYPE = {
comments: 'activity_comments',
excluded_appeal_contacts: 'appeal_excluded_appeal_contacts',
facebook_accounts: 'person_facebook_accounts',
google_accounts: 'person_google_accounts',
key_accounts: 'person_key_accounts',
linkedin_accounts: 'person_linkedin_accounts',
organization_accounts: 'person_organization_accounts',
referrers: 'contacts',
tasks: 'activities',
user_options: 'person_options',
users: 'people',
websites: 'person_websites'
}.freeze
|
chuckmersereau/api_practice
|
spec/services/contact/filter/donation_amount_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::DonationAmount 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!(:donor_account_one) { create(:donor_account) }
let!(:designation_account_one) { create(:designation_account) }
let!(:donation_one) do
create(:donation, donor_account: donor_account_one, designation_account: designation_account_one)
end
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:donor_account_two) { create(:donor_account) }
let!(:designation_account_two) { create(:designation_account) }
let!(:donation_two) do
create(:donation, donor_account: donor_account_two, designation_account: designation_account_two, amount: 12.34)
end
let!(:donation_three) do
create(:donation, donor_account: donor_account_two, designation_account: designation_account_two, amount: 4444.33)
end
let!(:contact_three) { create(:contact, account_list_id: account_list.id) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id) }
let!(:donor_account_four) { create(:donor_account) }
let!(:donation_four) do
create(:donation, donor_account: donor_account_four, designation_account_id: nil, amount: 12.34)
end
before do
account_list.designation_accounts << designation_account_one
account_list.designation_accounts << designation_account_two
contact_one.donor_accounts << donor_account_one
contact_two.donor_accounts << donor_account_two
donation_one.update(donation_date: 1.year.ago)
donation_two.update(donation_date: 1.month.ago)
donation_three.update(donation_date: 1.week.ago)
end
describe '#config' do
it 'returns expected config' do
options = [{ name: '-- Any --', id: '', placeholder: 'None' },
{ name: 9.99, id: 9.99 },
{ name: 12.34, id: 12.34 },
{ name: 4444.33, id: 4444.33 }]
expect(described_class.config([account_list])).to include(default_selection: '',
multiple: true,
name: :donation_amount,
options: options,
parent: 'Gift Details',
title: 'Exact Gift Amount',
type: 'multiselect')
end
end
describe '#query' do
let(:contacts) { Contact.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(contacts, {}, nil)).to eq(nil)
expect(described_class.query(contacts, { donation_amount: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { donation_amount: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { donation_amount: [''] }, nil)).to eq(nil)
expect(described_class.query(contacts, { donation_amount: '' }, nil)).to eq(nil)
end
end
context 'filter by amounts' do
it 'returns only contacts that have given the exact amount' do
results = described_class.query(contacts, { donation_amount: '9.99' }, [account_list]).to_a
expect(results).to match_array [contact_one]
end
it 'returns only contacts that have given multiple exact amounts' do
results = described_class.query(contacts, { donation_amount: '9.99, 12.34' }, [account_list]).to_a
expect(results).to match_array [contact_one, contact_two]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/mailers/previews/task_notification_mailer_preview.rb
|
class TaskNotificationMailerPreview < ApplicationPreview
def notify
@contacts = account_list.contacts.limit(2)
if @contacts.empty?
@contacts << account_list.contacts.create(name: 'Ryan & Sarah, Connor')
@contacts << account_list.contacts.create(name: 'Mike & <NAME>')
end
@task = account_list.tasks.create(
subject: 'Call for Decision',
start_at: Time.current,
activity_type: 'Call',
location: '142 Emailer Road, Railstown',
contacts: @contacts
)
TaskNotificationMailer.notify(@task.id, user.id)
end
end
|
chuckmersereau/api_practice
|
spec/services/coaching/contact/filter/pledge_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/services/coaching/contact/filter/pledge_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe Coaching::Contact::Filter::Pledge do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
describe '#config' do
it 'returns expected config' do
expect(described_class.config([account_list])).to include(
multiple: false,
name: :pledge,
options: [{ name: '-- All --', id: 'all' },
{ name: 'Outstanding', id: 'outstanding' },
{ name: 'Completed', id: 'completed' },
{ name: 'Pending', id: 'pending' }],
title: 'Pledge Status',
type: 'radio'
)
end
end
describe '#query' do
let!(:contact_completed) do
create :contact, account_list_id: account_list.id, pledge_received: true
end
let!(:contact_outstanding) do
create :contact, account_list_id: account_list.id, pledge_received: false,
pledge_start_date: 2.days.ago
end
let!(:contact_pending) do
create :contact, account_list_id: account_list.id, pledge_received: false,
pledge_start_date: 2.days.from_now
end
let!(:contact_completed_start_past) do
create :contact, account_list_id: account_list.id, pledge_received: true,
pledge_start_date: 2.days.ago
end
let!(:contact_completed_start_future) do
create :contact, account_list_id: account_list.id, pledge_received: true,
pledge_start_date: 2.days.from_now
end
let!(:used_to_be_committed) do
create :contact, account_list_id: account_list.id, pledge_received: false,
status: 'Partner - Pray', pledge_start_date: 2.days.ago
end
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, { pledge: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { pledge: [] }, nil)).to eq(nil)
end
end
context 'filter by all contacts' do
it 'accepts "all" as a filter' do
expect(described_class.query(contacts, { pledge: 'all' }, nil).to_a) \
.to match_array [contact_completed, contact_outstanding, contact_pending,
contact_completed_start_past, contact_completed_start_future,
used_to_be_committed]
end
it 'treats an unknown value as "all"' do
expect(described_class.query(contacts, { pledge: 'unknown filter' }, nil).to_a) \
.to match_array [contact_completed, contact_outstanding, contact_pending,
contact_completed_start_past, contact_completed_start_future,
used_to_be_committed]
end
end
context 'filter by completed contacts' do
it 'accepts "completed" as a filter' do
expect(described_class.query(contacts, { pledge: 'completed' }, nil).to_a) \
.to include contact_completed, contact_completed_start_past,
contact_completed_start_future
expect(described_class.query(contacts, { pledge: 'completed' }, nil).to_a) \
.not_to include contact_outstanding, contact_pending, used_to_be_committed
end
end
context 'filter by outstanding contacts' do
it 'accepts "outstanding" as a filter' do
expect(described_class.query(contacts, { pledge: 'outstanding' }, nil).to_a) \
.to include contact_outstanding
expect(described_class.query(contacts, { pledge: 'outstanding' }, nil).to_a) \
.not_to include contact_completed, contact_pending,
contact_completed_start_past,
contact_completed_start_future,
used_to_be_committed
end
end
context 'filter by pending contacts' do
it 'accepts "pending" as a filter' do
expect(described_class.query(contacts, { pledge: 'pending' }, nil).to_a) \
.to include contact_pending
expect(described_class.query(contacts, { pledge: 'pending' }, nil).to_a) \
.not_to include contact_completed, contact_outstanding,
contact_completed_start_past,
contact_completed_start_future,
used_to_be_committed
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170905043431_add_mpd_season_to_account_lists.rb
|
class AddMpdSeasonToAccountLists < ActiveRecord::Migration
def change
add_column :account_lists, :active_mpd_start_at, :date
add_column :account_lists, :active_mpd_finish_at, :date
add_column :account_lists, :active_mpd_monthly_goal, :decimal
end
end
|
chuckmersereau/api_practice
|
spec/services/application_filterer_spec.rb
|
require 'rails_helper'
describe ApplicationFilterer do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
describe '.config' do
it 'returns an empty array' do
expect(described_class.config([account_list])).to eq []
end
end
describe '.filter_classes' do
it 'returns an empty array' do
expect(described_class.filter_classes).to eq []
end
end
describe '.filter_params' do
it 'returns an empty array' do
expect(described_class.filter_params).to eq []
end
end
describe '#initialize' do
it 'initializes filters variable' do
expect(described_class.new(abc: '123').filters).to eq('abc' => '123')
end
it 'intializes filters with_indifferent_access' do
expect(described_class.new(abc: { 'def' => '123' }).filters[:abc][:def]).to eq('123')
end
it 'strips filter string params' do
expect(described_class.new(abc: ' 1 2 3 ').filters).to eq('abc' => '1 2 3')
end
end
describe '#filter' do
it 'returns the resource scope' do
resource_scope = Contact.all
expect(described_class.new.filter(scope: resource_scope, account_lists: [account_list])).to eq resource_scope
end
end
describe '#with any_filter flag' do
let(:account_list) { create(:account_list) }
let!(:contact_one) { create(:contact, account_list: account_list) }
let!(:contact_two) { create(:contact, account_list: account_list, name: 'name') }
let!(:contact_three) { create(:contact, account_list: account_list) }
let(:filters) { { simple_name_search: 'name', simple_date_search: contact_one.created_at, any_filter: true } }
it 'returns results that apply to any filter' do
result = Contact::ContactFilterer.new(filters).filter(scope: account_list.contacts, account_lists: [account_list])
expect(result).to eq [contact_one, contact_two]
end
class Contact::ContactFilterer < ApplicationFilterer
FILTERS_TO_HIDE = %w(SimpleNameSearch SimpleDateSearch).freeze
end
module Contact::Filter
class SimpleNameSearch < ApplicationFilter
def execute_query(scope, filters)
scope.where(name: filters[:simple_name_search])
end
end
class SimpleDateSearch < ApplicationFilter
def execute_query(scope, filters)
scope.where(created_at: filters[:simple_date_search])
end
end
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/users_controller.rb
|
<filename>app/controllers/api/v2/users_controller.rb
class Api::V2::UsersController < Api::V2Controller
def show
load_user
authorize_user
render_user
end
def update
load_user
authorize_user
persist_user
end
private
def load_user
@user ||= current_user
end
def render_user
render json: @user,
status: success_status,
include: include_params,
fields: field_params
end
def persist_user
build_user
authorize_user
if save_user
render_user
else
render_with_resource_errors(@user)
end
end
def build_user
@user.assign_attributes(user_params)
end
def save_user
@user.save(context: persistence_context)
end
def user_params
params
.require(:user)
.permit(User::PERMITTED_ATTRIBUTES)
end
def authorize_user
authorize @user
end
def preferences_params
params.dig(:user, :preferences)
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/imports/csv_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Account Lists > Imports > from CSV' do
include_context :multipart_form_data_headers
include ActionDispatch::TestProcess
documentation_scope = :account_lists_api_imports
before { stub_smarty_streets }
let(:resource_type) { 'imports' }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:imports) do
create_list(:csv_import, 2, account_list: account_list, user: user,
in_preview: true,
file_headers_mappings: file_headers_mappings,
file_constants_mappings: file_constants_mappings)
end
let!(:import) { imports.first }
let(:id) { import.id }
let(:file_headers_mappings) do
{
'city' => 'city',
'pledge_amount' => 'amount',
'pledge_frequency' => 'frequency',
'contact_name' => 'fname',
'country' => 'country',
'email_1' => 'email_address',
'envelope_greeting' => 'envelope_greeting',
'first_name' => 'fname',
'greeting' => 'greeting',
'last_name' => 'lname',
'newsletter' => 'newsletter',
'notes' => 'extra_notes',
'phone_1' => 'phone',
'spouse_email' => 'spouse_email_address',
'spouse_first_name' => 'spouse_fname',
'spouse_last_name' => 'spouse_lname',
'spouse_phone' => 'spouse_phone_number',
'state' => 'province',
'status' => 'status',
'street' => 'street',
'zip' => 'zip_code'
}
end
let(:file_constants_mappings) do
{
'status' => [
{ 'id' => 'Partner - Financial', 'values' => ['Praying and giving'] }
],
'pledge_frequency' => [
{ 'id' => '1.0', 'values' => ['Monthly'] }
],
'newsletter' => [
{ 'id' => 'Both', 'values' => ['Both'] }
]
}
end
let(:new_import) do
attrs = {
file: Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/sample_csv_with_custom_headers.csv')),
file_headers_mappings: file_headers_mappings,
file_constants_mappings: file_constants_mappings
}
build(:csv_import)
.attributes
.reject { |attr| attr.to_s.end_with?('_id') }
.tap { |attributes| attributes.delete('id') }
.tap { |attributes| attributes.delete('in_preview') }
.tap { |attributes| attributes['updated_in_db_at'] = import.updated_at }
.tap { |attributes| attributes['updated_at'] = import.updated_at }
.tap { |attributes| attributes['created_at'] = import.created_at }
.merge(attrs)
end
let(:relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: account_list.id
}
},
user: {
data: {
type: 'users',
id: user.id
}
}
}
end
let(:resource_attributes) do
%w(
account_list_id
created_at
file_constants
file_constants_mappings
file_headers
file_headers_mappings
file_url
group_tags
groups
import_by_group
in_preview
override
source
tag_list
updated_at
updated_in_db_at
)
end
let(:resource_associations) do
%w(
user
sample_contacts
)
end
let(:form_data) { build_data(new_import, relationships: relationships) }
context 'authorized user' do
before { api_login(user) }
get '/api/v2/account_lists/:account_list_id/imports/csv' do
parameter 'account_list_id', 'Account List ID', type: 'String', required: true
example 'CSV Import [LIST]', document: documentation_scope do
explanation 'List of CSV Imports associated with the Account List'
do_request
check_collection_resource(2, ['relationships'])
expect(response_status).to eq 200
expect(resource_data.first['attributes']['file_url']).to be_present
expect(resource_data.first['attributes']['source']).to eq 'csv'
end
end
get '/api/v2/account_lists/:account_list_id/imports/csv/:id' do
with_options scope: [:data, :attributes] do
response_field 'account_list_id',
'Account List ID',
type: 'Number'
response_field 'created_at',
'Created At',
type: 'String'
response_field 'file_url',
'A URL to download the file',
type: 'String'
response_field 'file_headers_mappings',
"An Object that maps attributes in MPDX (keys) to headers in the users's " \
'CSV file (values); The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported attributes',
type: 'Object'
response_field 'file_headers',
'A list of all the headers in the uploaded CSV file',
type: 'Object'
response_field 'file_constants',
"File constants are intended to help map values in the user's CSV file to " \
'MPDX constants. This is a list of unique values for each column in the ' \
"CSV. Columns are ignored if they obviously aren't constants " \
'(like "name"), so not every column is returned. At most ' \
"#{CsvFileConstantsReader::MAX_MAPPINGS_PER_HEADER} results will be returned " \
'for each column.',
type: 'Object'
response_field 'file_constants_mappings',
"An Object that maps constants in MPDX to constants in the users's " \
'CSV file; The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported constants',
type: 'Object'
response_field 'group_tags',
'Group Tags',
type: 'String'
response_field 'groups',
'Groups',
type: 'Array[String]'
response_field 'import_by_group',
'Import by Group',
type: 'String'
response_field 'in_preview',
"The Import will not be performed while it's in preview; Defaults to true",
type: 'Boolean'
response_field 'override',
'Override',
type: 'Boolean'
response_field 'source',
'Source; Defaults to "csv"',
type: 'String'
response_field 'tag_list',
'Comma delimited list of tags to apply to the imported Contacts',
type: 'String'
response_field 'updated_at',
'Updated At',
type: 'String'
response_field 'updated_in_db_at',
'Updated In Db At',
type: 'String'
end
example 'CSV Import [GET]', document: documentation_scope do
explanation 'The Import with the given ID'
do_request
check_resource(['relationships'])
expect(response_status).to eq 200
expect(resource_data['attributes']['file_url']).to be_present
expect(resource_data['attributes']['source']).to eq 'csv'
expect(resource_data['attributes']['file_constants_mappings']).to eq(file_constants_mappings)
expect(resource_data['attributes']['file_headers_mappings']).to eq(file_headers_mappings)
end
end
put '/api/v2/account_lists/:account_list_id/imports/csv/:id' do
with_options scope: [:data, :attributes] do
parameter 'file',
'The CSV file uploaded as form-data',
type: 'String'
parameter 'file_headers_mappings',
"An Object that maps attributes in MPDX (keys) to headers in the users's " \
'CSV file (values); The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported attributes',
type: 'Object'
parameter 'file_constants_mappings',
"An Object that maps constants in MPDX (keys) to constants in the users's " \
'CSV file (values); The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported constants',
type: 'Object'
parameter 'groups', 'Groups', type: 'String'
parameter 'group_tags', 'Group Tags', type: 'String'
parameter 'import_by_group', 'Import by Group', type: 'String'
parameter 'override', 'Override', type: 'Boolean'
parameter 'source_account_id', 'Source Account ID', type: 'String'
parameter 'tag_list', 'Comma delimited list of Tags', type: 'String'
parameter 'user_id', 'User ID', type: 'String'
end
with_options scope: [:data, :attributes] do
response_field 'account_list_id',
'Account List ID',
type: 'Number'
response_field 'created_at',
'Created At',
type: 'String'
response_field 'file_url',
'A URL to download the file',
type: 'String'
response_field 'file_headers_mappings',
"An Object that maps attributes in MPDX (keys) to headers in the users's " \
'CSV file (values); The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported attributes',
type: 'Object'
response_field 'file_headers',
'A list of all the headers in the uploaded CSV file',
type: 'Object'
response_field 'file_constants',
"File constants are intended to help map values in the user's CSV file to " \
'MPDX constants. This is a list of unique values for each column in the ' \
"CSV. Columns are ignored if they obviously aren't constants " \
'(like "name"), so not every column is returned. At most ' \
"#{CsvFileConstantsReader::MAX_MAPPINGS_PER_HEADER} results will be returned " \
'for each column.',
type: 'Object'
response_field 'file_constants_mappings',
"An Object that maps constants in MPDX to constants in the users's " \
'CSV file; The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported constants',
type: 'Object'
response_field 'group_tags',
'Group Tags',
type: 'String'
response_field 'groups',
'Groups',
type: 'Array[String]'
response_field 'import_by_group',
'Import by Group',
type: 'String'
response_field 'in_preview',
"The Import will not be performed while it's in preview; Defaults to true",
type: 'Boolean'
response_field 'override',
'Override',
type: 'Boolean'
response_field 'source',
'Source; Defaults to "csv"',
type: 'String'
response_field 'tag_list',
'Comma delimited list of Tags to apply to the imported Contacts',
type: 'String'
response_field 'updated_at',
'Updated At',
type: 'String'
response_field 'updated_in_db_at',
'Updated In Db At',
type: 'String'
end
with_options scope: [:data, :relationships] do
response_field 'user', 'User that the Import belongs to', type: 'Object'
response_field 'sample_contacts',
'The sample Contacts are a preview of what the imported Contacts would look like. ' \
'It uses the first few rows of the CSV file to generate the samples.',
type: 'Object'
end
example 'CSV Import [UPDATE]', document: documentation_scope do
explanation 'Update a CSV Import associated with the Account List. For more details '\
'regarding the CSV Import see the description on the create request.'
do_request data: form_data
check_resource(['relationships'])
expect(response_status).to eq(200), invalid_status_detail
expect(response_headers['Content-Type']).to eq 'application/vnd.api+json; charset=utf-8'
expect(resource_data['id']).to be_present
expect(resource_data['attributes']['file_url']).to be_present
expect(resource_data['attributes']['source']).to eq 'csv'
expect(resource_data['attributes']['in_preview']).to eq true
expect(resource_data['attributes']['file_constants_mappings']).to eq(file_constants_mappings)
expect(resource_data['attributes']['file_headers_mappings']).to eq(file_headers_mappings)
expect(resource_data['relationships']['sample_contacts']['data'].size).to eq(3)
end
end
post '/api/v2/account_lists/:account_list_id/imports/csv' do
with_options scope: [:data, :attributes] do
parameter 'file',
'The CSV file uploaded as form-data',
type: 'String'
parameter 'file_headers_mappings',
"An Object that maps attributes in MPDX (keys) to headers in the users's " \
'CSV file (values); The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported attributes',
type: 'Object'
parameter 'file_constants_mappings',
"An Object that maps constants in MPDX (keys) to constants in the users's " \
'CSV file (values); The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported constants',
type: 'Object'
parameter 'groups', 'Groups', type: 'String'
parameter 'group_tags', 'Group Tags', type: 'String'
parameter 'import_by_group', 'Import by Group', type: 'String'
parameter 'override', 'Override', type: 'Boolean'
parameter 'source_account_id', 'Source Account ID', type: 'String'
parameter 'tag_list', 'Comma delimited list of Tags', type: 'String'
parameter 'user_id', 'User ID', type: 'String'
end
with_options scope: [:data, :attributes] do
response_field 'account_list_id',
'Account List ID',
type: 'Number'
response_field 'created_at',
'Created At',
type: 'String'
response_field 'file_url',
'A URL to download the file',
type: 'String'
response_field 'file_headers_mappings',
"An Object that maps attributes in MPDX (keys) to headers in the users's " \
'CSV file (values); The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported attributes',
type: 'Object'
response_field 'file_headers',
'A list of all the headers in the uploaded CSV file',
type: 'Object'
response_field 'file_constants',
"File constants are intended to help map values in the user's CSV file to " \
'MPDX constants. This is a list of unique values for each column in the ' \
"CSV. Columns are ignored if they obviously aren't constants " \
'(like "name"), so not every column is returned. At most ' \
"#{CsvFileConstantsReader::MAX_MAPPINGS_PER_HEADER} results will be returned " \
'for each column.',
type: 'Object'
response_field 'file_constants_mappings',
"An Object that maps constants in MPDX (keys) to constants in the users's " \
'CSV file (values); The client must supply this before import can begin; ' \
'Please see the Constants endpoint for a list of supported constants',
type: 'Object'
response_field 'group_tags',
'Group Tags',
type: 'String'
response_field 'groups',
'Groups',
type: 'Array[String]'
response_field 'import_by_group',
'Import by Group',
type: 'String'
response_field 'in_preview',
"The Import will not be performed while it's in preview; Defaults to true",
type: 'Boolean'
response_field 'override',
'Override',
type: 'Boolean'
response_field 'source',
'Source; Defaults to "csv"',
type: 'String'
response_field 'tag_list',
'Comma delimited list of Tags to apply to the imported Contacts',
type: 'String'
response_field 'updated_at',
'Updated At',
type: 'String'
response_field 'updated_in_db_at',
'Updated In Db At',
type: 'String'
end
with_options scope: [:data, :relationships] do
response_field 'user', 'User that the Import belongs to', type: 'Object'
response_field 'sample_contacts',
'The sample Contacts are a preview of what the imported Contacts would look like. ' \
'It uses the first few rows of the CSV file to generate the samples.',
type: 'Object'
end
example 'CSV Import [CREATE]', document: documentation_scope do
explanation <<~HEREDOC
<p>
Creates a new CSV Import associated with the Account List. This endpoint expects a CSV
file to be uploaded using Content-Type "multipart/form-data", this makes the endpoint
unique in that it does not expect only JSON content. Unless otherwise specified, the
Import will be created with "in_preview" set to true.
</p><p>
A CSV Import is expected to take multiple steps to setup:
</p><p>
1. The first step is to create a new Import via a POST request, the client can upload
the CSV file in the POST request using "multipart/form-data". If the file upload is successful
then the file_headers and file_constants will be returned to the client in the response.
</p><p>
2. In the second step the client is expected to update (via PUT) the file_headers_mappings
according to the user's desire (based on the file_headers). This step could take several attempts.
</p><p>
3. In the third step the client is expected to update (via PUT) the file_constants_mappings
according to the user's desire (based on the file_constants). This step could take several attempts.
</p><p>
4. The fourth step is to show a sample of the import to the user.
The sample_contacts relationship should be used.
</p><p>
5. The fifth step is to start the import. The client is expected to update (via PUT) the
"in_preview" attribute to "false", which will trigger the import to begin (as a
background job). If the mappings are incorrect or incomplete, or the record is otherwise
invalid, then the import will not begin and an error object will be returned instead.
</p>
HEREDOC
do_request data: form_data
check_resource(['relationships'])
expect(response_status).to eq(201), invalid_status_detail
expect(response_headers['Content-Type']).to eq 'application/vnd.api+json; charset=utf-8'
expect(resource_data['id']).to be_present
expect(resource_data['attributes']['file_url']).to be_present
expect(resource_data['attributes']['source']).to eq 'csv'
expect(resource_data['attributes']['in_preview']).to eq true
expect(resource_data['relationships']['sample_contacts']['data'].size).to eq(3)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/group_tags_loader_spec.rb
|
require 'rails_helper'
describe TntImport::GroupTagsLoader do
let(:import) { create(:tnt_import, override: true) }
let(:tnt_import) { TntImport.new(import) }
let(:xml) { tnt_import.xml }
subject { described_class.tags_by_tnt_contact_id(xml) }
context 'version 3.2 and higher' do
before { import.file = File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml')) }
it 'expects the right xml version' do
expect(xml.version).to eq 3.2
end
describe '.tags_by_tnt_contact_id' do
it 'returns a hash of expected tags grouped by contat id' do
expect(subject).to eq('748459734' => %w(Call-this-summer Group-5 Pacific-Time-Zone Group-9 Green-Light
Group-6 Yet-Another-Group Group-7 Red-Light Increase-Project
Increase-Project\\Ask Group-Category
Group-Category\\My-Big-Named-Group-for-Summer-02 Group-3 Group-Set-1
Group-Set-1\\Group2 Group-Category\\My-Big-Named-Group-for-Summer-01
Increase-Project\\Call-Back Increase-Project\\Ask-Again
Group-Set-1\\Group1 Group-Category\\My-Big-Named-Group-for-Summer-03
Group-4 Really-Important-Group Send-Christmas-Cookies Group-8
Increase-Project\\Try-a-third-time 2017-Increase-Campaign
2017-Increase-Campaign\\1-Top-Level),
'1' => %w(2017-Increase-Campaign 2017-Increase-Campaign\\4-Prospect),
'748459735' => %w(2017-Increase-Campaign 2017-Increase-Campaign\\4-Prospect))
end
end
end
context 'version 3.1 and lower' do
before { import.file = File.new(Rails.root.join('spec/fixtures/tnt/tnt_export_groups.xml')) }
it 'expects the right xml version' do
expect(xml.version).to eq 3.0
end
describe '.tags_by_tnt_contact_id' do
it 'returns a hash of expected tags grouped by contat id' do
expect(subject).to eq('1' => %w(Group-with-Dave-comma Category-1-comma Testers))
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/address_historic_spec.rb
|
<filename>spec/services/contact/filter/address_historic_spec.rb
require 'rails_helper'
RSpec.describe Contact::Filter::AddressHistoric do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:contact_three) { create(:contact, account_list_id: account_list.id) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id) }
let!(:address_one) { create(:address) }
let!(:address_two) { create(:address) }
let!(:address_three) { create(:address, city: nil, historic: true) }
let!(:address_four) { create(:address, city: nil, historic: true) }
before do
contact_one.addresses << address_one
contact_two.addresses << address_two
contact_three.addresses << address_three
contact_four.addresses << address_four
end
describe '#config' do
it 'returns expected config' do
expect(described_class.config([account_list])).to include(name: :address_historic,
parent: 'Contact Location',
title: 'Address No Longer Valid',
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, { address_historic: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { address_historic: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { address_historic: '' }, nil)).to eq(nil)
end
end
context 'filter by address historic' do
it 'returns only contacts that have a no longer valid address' do
expect(described_class.query(contacts, { address_historic: 'true' }, nil).to_a).to match_array [contact_three, contact_four]
end
end
context 'filter by not address historic' do
it 'returns only contacts that have a valid address' do
expect(described_class.query(contacts, { address_historic: 'false' }, nil).to_a).to match_array [contact_one, contact_two]
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20171215011225_add_uniqueness_constraint_to_notification_preferences.rb
|
<reponame>chuckmersereau/api_practice
class AddUniquenessConstraintToNotificationPreferences < ActiveRecord::Migration
def change
add_index :notification_preferences,
[:user_id, :account_list_id, :notification_type_id],
name: 'index_notification_preferences_unique',
unique: true
end
end
|
chuckmersereau/api_practice
|
spec/models/appeal_spec.rb
|
<filename>spec/models/appeal_spec.rb
require 'rails_helper'
describe Appeal do
let(:account_list) { create(:account_list) }
subject { create(:appeal, account_list: account_list) }
let(:contact) { create(:contact, account_list: account_list) }
describe '.filter' do
context 'wildcard_search' do
context 'name contains' do
let!(:appeal) { create(:appeal, name: 'abcd', account_list: account_list) }
it 'returns donor_account' do
expect(described_class.filter(wildcard_search: 'bc')).to eq([appeal])
end
end
context 'name does not contain' do
let!(:appeal) { create(:appeal, name: 'abcd', account_list: account_list) }
it 'returns no designation_accounts' do
expect(described_class.filter(wildcard_search: 'def')).to be_empty
end
end
end
context 'not wildcard_search' do
let!(:appeal) { create(:appeal, amount: 10, account_list: account_list) }
it 'returns designation_account' do
expect(described_class.filter(amount: 10)).to eq([appeal])
end
end
end
describe '#bulk_add_contacts' do
let(:contact2) { create(:contact, account_list: account_list) }
it 'bulk adds the contacts but removes duplicates first and does not create dups when run again' do
expect do
subject.bulk_add_contacts(contacts: [contact, contact, contact2])
end.to change(subject.contacts, :count).from(0).to(2)
expect do
subject.bulk_add_contacts(contacts: [contact, contact, contact2])
end.to_not change(subject.contacts, :count).from(2)
end
it 'bulk adds the contact_ids but removes duplicates first and does not create dups when run again' do
expect do
subject.bulk_add_contacts(contact_ids: [contact.id, contact.id, contact2.id])
end.to change(subject.contacts, :count).from(0).to(2)
expect do
subject.bulk_add_contacts(contact_ids: [contact.id, contact.id, contact2.id])
end.to_not change(subject.contacts, :count).from(2)
end
end
describe '#donated?' do
let(:donor_account) { create(:donor_account, contacts: [contact]) }
let(:donation) { create(:donation, donor_account: donor_account, appeal: subject) }
before do
contact.donor_accounts << donor_account
end
it 'responds with false when a contact has not given' do
expect(subject.donated?(contact)).to be_falsy
end
it 'responds with true when a contact has given' do
donation
expect(subject.donated?(contact)).to be_truthy
end
end
context 'pledges related fields' do
subject { create(:appeal) }
let!(:processed_pledge) do
create(
:pledge,
status: :processed,
amount: 200.00,
appeal: subject,
created_at: Time.now.getlocal.beginning_of_day
)
end
let!(:received_not_processed_pledge) do
create(
:pledge,
status: :received_not_processed,
amount: 300.00,
appeal: subject,
created_at: Time.now.getlocal.beginning_of_day
)
end
let!(:not_received_not_processed_pledge) do
create(
:pledge,
amount: 400.00,
appeal: subject,
created_at: Time.now.getlocal.beginning_of_day
)
end
describe '#pledges_amount_total' do
it 'returns the total amount of all pledges' do
expect(ConvertedTotal).to receive(:new).and_call_original
expect(subject.pledges_amount_total).to eq(900.00)
end
end
describe '#pledges_amount_not_received_not_processed' do
it 'returns the total amount of pledges that were not processed and received' do
expect(ConvertedTotal).to receive(:new).with(
[[not_received_not_processed_pledge.amount,
not_received_not_processed_pledge.contact.read_attribute(:pledge_currency),
not_received_not_processed_pledge.created_at]],
subject.account_list.salary_currency_or_default
).and_call_original
expect(subject.pledges_amount_not_received_not_processed).to eq(400.00)
end
end
describe '#pledges_amount_received_not_processed' do
it 'returns the total amount of all pledges that were received and not processed' do
expect(ConvertedTotal).to receive(:new).with(
[[received_not_processed_pledge.amount,
received_not_processed_pledge.contact.read_attribute(:pledge_currency),
received_not_processed_pledge.created_at]],
subject.account_list.salary_currency_or_default
).and_call_original
expect(subject.pledges_amount_received_not_processed).to eq(300.00)
end
end
describe '#pledges_amount_processed' do
let(:part_donation) { create(:donation, amount: 100, appeal_amount: 50, appeal: subject) }
let(:full_donation) { create(:donation, amount: 150, appeal: subject) }
before do
create(:pledge_donation, pledge: processed_pledge, donation: part_donation)
create(:pledge_donation, pledge: processed_pledge, donation: full_donation)
end
it 'returns the total amount of all pledges that were received and processed' do
expect(ConvertedTotal).to receive(:new).with(
[
[
part_donation.appeal_amount,
part_donation.currency,
part_donation.donation_date
], [
full_donation.amount,
full_donation.currency,
full_donation.donation_date
]
],
subject.account_list.salary_currency_or_default
).and_call_original
expect(subject.pledges_amount_processed).to eq(200.00)
end
end
end
describe '#create_contact_associations' do
subject { build(:appeal, account_list: account_list) }
let!(:contact1) do
create(:contact,
account_list: account_list,
status: 'Partner - Financial',
send_newsletter: 'Both')
end
let!(:contact2) do
create(:contact,
account_list: account_list,
status: 'Never Contacted',
send_newsletter: 'Both')
end
let!(:contact3) do
create(:contact,
account_list: account_list,
status: 'Partner - Pray',
pledge_currency: 'NZD',
send_newsletter: 'Both')
end
let!(:contact4) do
create(:contact,
account_list: account_list,
status: 'Partner - Financial',
pledge_currency: 'NZD',
send_newsletter: 'Both')
end
it 'adds appeal_contacts (with a id) for contacts within inclusion filter' do
subject.inclusion_filter = {
status: 'Partner - Financial',
newsletter: 'Both'
}
subject.save
expect(subject.contacts).to match_array [contact1, contact4]
expect(subject.appeal_contacts.first.id).to be_present
end
it 'adds excluded_appeal_contacts (with a id) for all contacts in the exclusion filters' do
subject.inclusion_filter = {
newsletter: 'Both'
}
subject.exclusion_filter = {
status: 'Partner - Financial',
pledge_currency: 'NZD'
}
subject.save
expect(subject.contacts).to eq([contact2])
expect(subject.excluded_contacts).to match_array([contact1, contact3, contact4])
expect(subject.excluded_appeal_contacts.first.id).to be_present
end
it 'adds filter name as reason for exclusion' do
end_date = Date.today
start_date = end_date - 5.months
expect(Contact::Filterer).to receive(:new).with(
newsletter: 'Both'
).at_least(:once).and_call_original
expect(Contact::Filterer).to receive(:new).with(
status: 'Partner - Financial'
).once.and_call_original
expect(Contact::Filterer).to receive(:new).with(
pledge_currency: 'NZD'
).once.and_call_original
expect(Contact::Filterer).to receive(:new).with(
no_appeals: true
).once.and_call_original
expect(Contact::Filterer).to receive(:new).with(
gave_more_than_pledged_range: Range.new(start_date, end_date)
).once.and_call_original
subject.inclusion_filter = {
'newsletter' => 'Both'
}
subject.exclusion_filter = {
'status' => 'Partner - Financial',
'pledge_currency' => 'NZD',
'no_appeals' => true,
'gave_more_than_pledged_range' => "#{start_date.strftime('%Y-%m-%d')}...#{end_date.strftime('%Y-%m-%d')}"
}
contact.update(no_appeals: nil)
subject.save
excluded_appeal_contact1 = subject.excluded_appeal_contacts.find_by(contact: contact1)
excluded_appeal_contact2 = subject.excluded_appeal_contacts.find_by(contact: contact2)
excluded_appeal_contact3 = subject.excluded_appeal_contacts.find_by(contact: contact3)
excluded_appeal_contact4 = subject.excluded_appeal_contacts.find_by(contact: contact4)
expect(excluded_appeal_contact1.reasons).to eq(['status'])
expect(excluded_appeal_contact2).to be nil
expect(excluded_appeal_contact3.reasons).to eq(['pledge_currency'])
expect(excluded_appeal_contact4.reasons).to match_array(%w(status pledge_currency))
end
it 'does not add any contacts when filters are not included' do
subject.save
expect(subject.appeal_contacts.count).to eq(0)
expect(subject.excluded_appeal_contacts.count).to eq(0)
end
it 'successes with all front-end filters' do
end_date = Date.today
start_date = end_date - 5.months
date_range = "#{start_date.strftime('%Y-%m-%d')}..#{end_date.strftime('%Y-%m-%d')}"
contact1.update(tag_list: %w(cru))
subject.inclusion_filter = {
'account_list_id' => account_list.id,
'tags' => 'asdf',
'any_tags' => true
}
subject.exclusion_filter = {
'gave_more_than_pledged_range' => date_range,
'pledge_amount_increased_range' => date_range,
'started_giving_range' => date_range,
'stopped_giving_range' => "#{start_date.strftime('%Y-%m-%d')}..#{(end_date - 1.month).strftime('%Y-%m-%d')}",
'no_appeals' => true
}
expect { subject.save }.to_not raise_exception
end
end
describe '#destroy' do
let(:donor_account) { create(:donor_account, contacts: [contact]) }
let!(:donation) { create(:donation, donor_account: donor_account, appeal: subject) }
it 'nullifies related donations' do
subject.destroy
expect(donation.reload.appeal_id).to be nil
end
end
end
|
chuckmersereau/api_practice
|
spec/services/person/filter/wildcard_search_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Person::Filter::WildcardSearch do
let!(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let!(:person_one) do
create(:person, email_addresses: [build(:email_address, email: '<EMAIL>')],
phone_numbers: [build(:phone_number, number: '514 122-4362')])
end
let!(:person_two) { create(:person, first_name: 'Freddie', last_name: 'Jones') }
let!(:person_three) { create(:person, first_name: 'Donald', last_name: 'Duck') }
let!(:person_four) { create(:person) }
describe '#config' do
it 'does not have config' do
expect(described_class.config([account_list])).to eq(nil)
end
end
describe '#query' do
let(:people) { Person.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(people, {}, nil)).to eq(nil)
expect(described_class.query(people, { wildcard_search: {} }, nil)).to eq nil
expect(described_class.query(people, { wildcard_search: [] }, nil)).to eq nil
expect(described_class.query(people, { wildcard_search: '' }, nil)).to eq nil
end
end
context 'filter with wildcard search' do
it 'returns only contacts that match the search query' do
expect(described_class.query(people, { wildcard_search: 'Freddie' }, nil).to_a).to match_array [person_two]
expect(described_class.query(people, { wildcard_search: 'Duck' }, nil).to_a).to match_array [person_three]
expect(described_class.query(people, { wildcard_search: '122' }, nil).to_a).to match_array [person_one]
expect(described_class.query(people, { wildcard_search: 'email' }, nil).to_a).to match_array [person_one]
end
it 'searches person first and last name regardless of order, case, or commas' do
expect(described_class.query(people, { wildcard_search: '<NAME>,' }, nil).to_a).to match_array [person_two]
expect(described_class.query(people, { wildcard_search: 'jones, freddie' }, nil).to_a).to match_array [person_two]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/google_contacts.rb
|
FactoryBot.define do
factory :google_contact do
end
end
|
chuckmersereau/api_practice
|
app/serializers/email_address_serializer.rb
|
<filename>app/serializers/email_address_serializer.rb<gh_stars>0
class EmailAddressSerializer < ApplicationSerializer
attributes :email,
:location,
:primary,
:historic,
:source,
:valid_values
end
|
chuckmersereau/api_practice
|
config/initializers/hash.rb
|
# remove this if Rails is >= 4.2.1
# http://apidock.com/rails/v4.2.1/Hash/transform_values
class Hash
def transform_values
return enum_for(:transform_values) unless block_given?
result = self.class.new
each do |key, value|
result[key] = yield(value)
end
result
end
end
|
chuckmersereau/api_practice
|
app/services/person/filter/wildcard_search.rb
|
class Person::Filter::WildcardSearch < Person::Filter::Base
include ::Concerns::Filter::SearchableInParts
def execute_query(people, filters)
@search_term = filters[:wildcard_search].downcase
@people = people
person_ids = person_ids_from_email_addresses_like_search_term
person_ids += person_ids_from_phone_numbers_like_search_term
people_from_ids_or_first_or_last_name_like_search_term(person_ids)
end
private
def person_ids_from_email_addresses_like_search_term
@people
.joins(:email_addresses)
.where('email_addresses.email ilike :search', query_params)
.ids
end
def person_ids_from_phone_numbers_like_search_term
@people
.joins(:phone_numbers)
.where('phone_numbers.number ilike :search', query_params)
.ids
end
def people_from_ids_or_first_or_last_name_like_search_term(person_ids)
or_conditions = [
sql_condition_to_search_columns_in_parts('people.first_name', 'people.last_name'),
'people.id IN (:person_ids)'
].join(' OR ')
@people.where(or_conditions, query_params(search_term_parts_hash.merge(person_ids: person_ids)))
end
def valid_filters?(filters)
super && filters[:wildcard_search].is_a?(String)
end
end
|
chuckmersereau/api_practice
|
app/services/donation_imports/siebel/donation_importer.rb
|
class DonationImports::Siebel
class DonationImporter
# Donations should sometimes be deleted if they were misclassifed and then
# later correctly re-classified. However, we have had 2 recent occasions when
# the Siebel API incorectly returned no donations (or a lot fewer than
# expected) and it caused MPDX users to unexpectedly lose bunches of
# donations. So as a safety measure for that only remove a few donations per
# import as typically only a couple at most will be misclassified.
MAX_DONATIONS_TO_DELETE_AT_ONCE = 3
attr_reader :siebel_import
delegate :organization,
:organization_account,
to: :siebel_import
delegate :designation_profiles, to: :organization_account
def initialize(siebel_import)
@siebel_import = siebel_import
end
def import_donations(start_date: nil, end_date: nil)
@start_date = (start_date || organization.minimum_gift_date || Date.new(2004, 1, 1)).strftime('%Y-%m-%d')
@end_date = (end_date || Time.now).strftime('%Y-%m-%d')
designation_profiles.each do |designation_profile|
import_donations_by_designation_profile(designation_profile)
end
true
end
private
def import_donations_by_designation_profile(designation_profile)
siebel_donations_by_designation_profile(designation_profile).each do |siebel_donation|
add_or_update_mpdx_donation(siebel_donation, designation_profile)
end
remove_deleted_siebel_donations(designation_profile)
end
def remove_deleted_siebel_donations(designation_profile)
# Sometimes the Siebel API flakes out and doesn't return any donations.
# When that happened before it would cause all MPDX's donation records to
# be destroyed (for Cru USA users). As a sanity check for that flaky API
# condition, don't remove any donations if there are no donations in the
# range we are checking (past 50 days typically).
relevant_mpdx_donations = Donation.joins(:designation_account)
.where(designation_account: designation_profile.designation_accounts)
.where('donation_date >= ? AND donation_date <= ?', @start_date, @end_date)
.where.not(remote_id: nil)
remove_maximum_number_of_relevant_mpdx_donations(designation_profile, relevant_mpdx_donations)
end
def remove_maximum_number_of_relevant_mpdx_donations(designation_profile, relevant_mpdx_donations)
# We are removing mpdx donations which have a remote_id but are no longer on Siebel
donations_destroyed = 0
relevant_mpdx_donations.each do |mpdx_donation|
break if donations_destroyed == MAX_DONATIONS_TO_DELETE_AT_ONCE
next if mpdx_donation.appeal.present?
next if find_siebel_donation_by_mpdx_donation(designation_profile, mpdx_donation)
mpdx_donation.destroy
donations_destroyed += 1
end
end
def find_siebel_donation_by_mpdx_donation(designation_profile, mpdx_donation)
siebel_donations_by_designation_profile(designation_profile).find do |siebel_donation|
siebel_donation.id == mpdx_donation.remote_id
end
end
def siebel_donations_by_designation_profile(designation_profile)
@siebel_donations_by_designation_profile ||= {}
@siebel_donations_by_designation_profile[designation_profile.id] ||=
fetch_siebel_donations_by_designation_profile(designation_profile)
end
def fetch_siebel_donations_by_designation_profile(designation_profile)
designation_profile.designation_accounts.pluck(:designation_number).map do |designation_number|
SiebelDonations::Donation.find(posted_date_start: @start_date,
posted_date_end: @end_date,
designations: designation_number)
end.flatten
end
def add_or_update_mpdx_donation(siebel_donation, designation_profile)
default_currency = organization.default_currency_code || 'USD'
donor_account = organization.donor_accounts.find_by(account_number: siebel_donation.donor_id)
designation_account = designation_profile.designation_accounts.find_by(designation_number: siebel_donation.designation)
attributes = {
amount: siebel_donation.amount,
channel: siebel_donation.channel,
currency: default_currency,
designation_account_id: designation_account.id,
donation_date: siebel_donation.donation_date.to_date,
donor_account_id: donor_account.id,
motivation: siebel_donation.campaign_code,
payment_method: siebel_donation.payment_method,
payment_type: siebel_donation.payment_type,
remote_id: siebel_donation.id,
tendered_amount: siebel_donation.amount,
tendered_currency: default_currency
}
mpdx_donation = FindDonation.new(designation_profile: designation_profile, attributes: attributes).find_and_merge
mpdx_donation ||= Donation.new
mpdx_donation.update!(attributes)
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/admin_impersonation_logs.rb
|
FactoryBot.define do
factory :admin_impersonation_log, class: 'Admin::ImpersonationLog' do
association :impersonator
association :impersonated
reason 'Test'
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/gave_more_than_pledged_range.rb
|
<reponame>chuckmersereau/api_practice
## I kept things on a monthly basis here since the only way to make sure that we get all contacts that have
# given more than pledged is to look at the entire month.
class Contact::Filter::GaveMoreThanPledgedRange < Contact::Filter::Base
def execute_query(contacts, filters)
beginning_of_start_month = filters[:gave_more_than_pledged_range].first.beginning_of_month
beginning_of_end_month = fetch_beginning_of_end_month_from_date_range(filters[:gave_more_than_pledged_range])
number_of_months = (beginning_of_end_month.year * 12 + beginning_of_end_month.month) -
(beginning_of_start_month.year * 12 + beginning_of_start_month.month)
contacts.where("contacts.id IN (#{above_pledge_contacts_ids_sql})",
account_list_id: account_lists.first.id,
beginning_of_start_month: beginning_of_start_month,
beginning_of_end_month: beginning_of_end_month,
number_of_months: number_of_months)
end
def valid_filters?(filters)
date_range?(filters[:gave_more_than_pledged_range])
end
private
def above_pledge_contacts_ids_sql
'SELECT contact_donations.contact_id
FROM
(
SELECT DISTINCT contacts.id as contact_id,
contacts.last_donation_date, contacts.pledge_amount,
contacts.pledge_frequency, donations.id as donation_id,
donations.amount as donation_amount
FROM contacts
INNER JOIN contact_donor_accounts cda on cda.contact_id = contacts.id
INNER JOIN donor_accounts da on da.id = cda.donor_account_id
INNER JOIN donations ON donations.donor_account_id = da.id
WHERE contacts.account_list_id = :account_list_id AND donations.donation_date >= :beginning_of_start_month
AND donations.designation_account_id IN (
SELECT designation_account_id FROM account_list_entries WHERE account_list_id = :account_list_id
)
) contact_donations
GROUP BY contact_id, pledge_amount, pledge_frequency, last_donation_date
HAVING
SUM(donation_amount)
/ ((CASE WHEN contact_donations.last_donation_date >= :beginning_of_end_month THEN 1 ELSE 0 END) + :number_of_months)
> coalesce(pledge_amount, 0.0) / coalesce(pledge_frequency, 1.0)'
end
end
|
chuckmersereau/api_practice
|
spec/models/tagging_spec.rb
|
require 'rails_helper'
describe ActsAsTaggableOn::Tagging do
let(:bob) { create(:contact) }
let!(:tag) { create(:tag) }
it 'should not allow duplicate tags' do
expect do
ActsAsTaggableOn::Tagging.create(tag: tag, taggable: bob, context: 'test')
end.to change { ActsAsTaggableOn::Tagging.count }
expect do
ActsAsTaggableOn::Tagging.create(tag: tag, taggable: bob, context: 'test')
end.to_not change { ActsAsTaggableOn::Tagging.count }
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts_controller.rb
|
class Api::V2::ContactsController < Api::V2Controller
include Filtering::Contacts
def index
authorize_index
load_contacts
render json: Api::V2::ContactsPreloader.new(include_params, field_params).preload(@contacts),
meta: meta_hash(@contacts),
include: include_params,
fields: field_params
end
def show
load_contact
authorize_contact
render_contact
end
def create
persist_contact
end
def update
load_contact
authorize_contact
persist_contact
end
def destroy
load_contact
authorize_contact
destroy_contact
end
private
def destroy_contact
@contact.deleted_by = current_user
@contact.destroy
head :no_content
end
def load_contacts
@contacts = ::Contact::Filterer.new(filter_params)
.filter(scope: contact_scope, account_lists: account_lists)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def load_contact
@contact ||= Contact.find(params[:id])
end
def authorize_contact
authorize @contact
end
def authorize_index
account_lists.each { |account_list| authorize(account_list, :show?) }
end
def render_contact
render json: @contact,
status: success_status,
include: include_params,
fields: field_params,
serializer: ContactDetailSerializer
end
def build_contact
@contact ||= Contact.new(prefill_attributes_on_create: create_default_person)
@contact.assign_attributes(contact_params)
end
def save_contact
@contact.save(context: persistence_context)
end
def persist_contact
build_contact
authorize_contact
if save_contact
render_contact
else
render_with_resource_errors(@contact)
end
end
def contact_params
params.require(:contact)
.permit(Contact::PERMITTED_ATTRIBUTES)
end
def contact_scope
Contact.where(account_list_id: account_lists.collect(&:id)).includes(:tags, :account_list)
end
def pundit_user
PunditContext.new(current_user, contact: @contact)
end
def permitted_sorting_params
%w(name)
end
def default_sort_param
Contact.arel_table[:created_at].asc
end
def create_default_person
return false if params[:contact][:create_default_person] == false
true
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/tasks/tags/bulk_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Tasks > Tags > Bulk Delete' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:tasks, :tags])
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:tag_one) { 'tag_one' }
let(:tag_two) { 'tag_two' }
let(:tag_three) { 'tag_three' }
let!(:task_one) { create(:task, account_list: account_list, tag_list: [tag_one, tag_two]) }
let!(:task_two) { create(:task, account_list: account_list, tag_list: [tag_one, tag_three]) }
let!(:task_three) { create(:task, account_list: account_list, tag_list: [tag_two, tag_three]) }
let(:task_ids) { [task_one, task_two].map(&:id).join(', ') }
let(:form_data) do
{
data: [
{
data: {
type: 'tags',
attributes: {
name: tag_one
}
}
},
{
data: {
type: 'tags',
attributes: {
name: tag_two
}
}
}
]
}.merge(filter_params)
end
let(:filter_params) do
{
filter: {
task_ids: task_ids
}
}
end
context 'authorized user' do
before { api_login(user) }
before do
expect(task_one.tag_list.count).to eq 2
expect(task_two.tag_list.count).to eq 2
expect(task_three.tag_list.count).to eq 2
end
# create
post '/api/v2/tasks/tags/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 form_data
expect(response_status).to eq(200), invalid_status_detail
expect(task_one.reload.tag_list.count).to eq 2
expect(task_two.reload.tag_list.count).to eq 3
expect(task_three.reload.tag_list.count).to eq 2
end
end
# destroy
delete '/api/v2/tasks/tags/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 form_data
expect(response_status).to eq(204), invalid_status_detail
expect(task_one.reload.tag_list.count).to eq 0
expect(task_two.reload.tag_list.count).to eq 1
expect(task_three.reload.tag_list.count).to eq 2
end
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/reports/activity_results_period_serializer.rb
|
<gh_stars>0
class Reports::ActivityResultsPeriodSerializer < ServiceSerializer
ACTIVITY_TYPE_SCOPES = ::Task::TASK_ACTIVITIES.map do |activity_type|
scope = activity_type.parameterize.underscore.to_sym
::Activity::REPORT_STATES.map { |state| "#{state}_#{scope}".to_sym }
end.flatten.freeze
DATE_ATTRIBUTES = [:start_date,
:end_date].freeze
REPORT_ATTRIBUTES = ACTIVITY_TYPE_SCOPES + DATE_ATTRIBUTES
attributes(*REPORT_ATTRIBUTES)
delegate(*REPORT_ATTRIBUTES, to: :object)
def id
start_date.strftime('%F')
end
end
|
chuckmersereau/api_practice
|
dev/util/address_history_util.rb
|
<gh_stars>0
def address_versions(contact)
Version.where(related_object_type: 'Contact',
related_object_id: contact.id,
item_type: 'Address').order(:created_at)
end
def print_address_versions(contact)
address_versions(contact).each do |v|
o = YAML.safe_load(v.object)
puts "#{v.event} #{v.item_id} at #{v.created_at} street: #{o['street']} added #{o['created_at'].to_date} by #{v.whodunnit}"
end
nil
end
def pl_param_history(contact, detail = false)
address_change_versions = []
last_pl_params = nil
contact.versions.order(:created_at).each do |version|
object = YAML.safe_load(version.object)
pl_params = object['prayer_letters_params']
if pl_params != last_pl_params
data = {
pl_params: pl_params, created_at: version.created_at
}
data[:version] = version if detail
address_change_versions << data
end
last_pl_params = pl_params
end
address_change_versions << { pl_params: YAML.dump(contact.prayer_letters_params) }
address_change_versions
end
|
chuckmersereau/api_practice
|
spec/requests/api/v2/base_request_spec.rb
|
require 'rails_helper'
RSpec.describe 'Server Responsibilites', type: :request do
describe 'Headers' do
let(:user) { create(:user_with_account) }
context 'logged in users' do
before { api_login(user) }
context 'with no Content-Type' do
let(:headers) { { 'CONTENT_TYPE' => '', 'ACCEPT' => '' } }
it 'should return a unsupported media type status (415)' do
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 415
end
it 'should return "application/vnd.api+json" as the Content-Type' do
get api_v2_contacts_path, nil, headers
expect(response.content_type).to eq('application/vnd.api+json')
end
end
context 'with a correct Content-Type' do
it 'should return a success status (200)' do
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json', 'ACCEPT' => '' }
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 200
end
end
context 'with an incorrect Content-Type' do
it 'should return an unsupported media type status (415)' do
headers = { 'CONTENT_TYPE' => 'application/foobar', 'ACCEPT' => '' }
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 415
end
end
context 'with a jsonapi Accept header' do
it 'should return a success status (200)' do
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => 'application/vnd.api+json'
}
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 200
end
end
context 'with a mixed jsonapi Accept header' do
it 'should return a success status (200)' do
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => 'application/vnd.api+json,application/vnd.api+json;charset=test'
}
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 200
end
end
context 'with multiple modified jsonapi Accept header' do
it 'should return a not acceptable status (406)' do
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => 'application/vnd.api+json;charset=test,application/vnd.api+json;charset=test'
}
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 406
end
end
context 'with a glob Accept header' do
it 'should return a succes status (200)' do
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => '*/*'
}
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 200
end
end
context 'with a modified glob Accept header' do
it 'should return a succes status (200)' do
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => '*/*q=1.2'
}
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 200
end
end
context 'with modified jsonapi Accept header' do
it 'should return a not acceptable status (406)' do
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => 'application/vnd.api+json;charset=test'
}
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 406
end
end
context 'with an Accept header that is not jsonapi' do
it 'should return a not acceptable status (406)' do
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => 'text/plain'
}
get api_v2_contacts_path, nil, headers
expect(response.status).to eq 406
end
end
context 'with no Accept and/or CONTENT_TYPE header for controllers accepting it' do
it 'should return a succes status (200)' do
headers = {
'CONTENT_TYPE' => 'multipart/form-data',
'ACCEPT' => 'text/csv'
}
get api_v2_exports_path, nil, headers
expect(response.status).to eq 200
end
end
end
context 'authorization' do
context 'with a correct json web token' do
it 'should return a succes status (200)' do
json_web_token = JsonWebToken.encode(
user_id: user.id,
exp: 24.hours.from_now.utc.to_i
)
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => '*/*',
'Authorization' => "Bearer #{json_web_token}"
}
get api_v2_exports_path, nil, headers
expect(response.status).to eq 200
end
end
context 'with an incorrect json web token' do
it 'should return a succes status (200)' do
json_web_token = JsonWebToken.encode(
random_field: 123_456
)
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => '*/*',
'Authorization' => "Bearer #{json_web_token}"
}
get api_v2_exports_path, nil, headers
expect(response.status).to eq 401
end
end
context 'with a json web token that is expired' do
it 'should return an unauthorized status (401)' do
json_web_token = JsonWebToken.encode(
user_id: user.id,
exp: 10.minutes.ago.utc
)
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => '*/*',
'Authorization' => "Bearer #{json_web_token}"
}
get api_v2_exports_path, nil, headers
expect(response.status).to eq 401
end
end
context "with an old jwt (doesn't have an exp attribute)" do
# This spec should be removed once the mobile app
# can handle expiring tokens.
it 'should return an unauthorized status (401)' do
json_web_token = JsonWebToken.encode(
user_id: user.id
)
headers = {
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => '*/*',
'Authorization' => "Bearer #{json_web_token}"
}
get api_v2_exports_path, nil, headers
expect(response.status).to eq 401
end
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120208190407_create_person_google_accounts.rb
|
class CreatePersonGoogleAccounts < ActiveRecord::Migration
def change
create_table :person_google_accounts do |t|
t.string :remote_id
t.belongs_to :person
t.string :token
t.string :refresh_token
t.datetime :expires_at
t.boolean :valid_token, default: false
t.timestamps null: false
end
add_index :person_google_accounts, :person_id
add_column :person_twitter_accounts, :valid_token, :boolean, default: false
add_column :person_facebook_accounts, :valid_token, :boolean, default: false
add_column :person_linkedin_accounts, :valid_token, :boolean, default: false
end
end
|
chuckmersereau/api_practice
|
app/services/reports/activity_results_period.rb
|
<filename>app/services/reports/activity_results_period.rb
class Reports::ActivityResultsPeriod < ActiveModelSerializers::Model
attr_accessor :account_list, :start_date, :end_date
::Task::TASK_ACTIVITIES.each do |activity_type|
scope = activity_type.parameterize.underscore.to_sym
::Activity::REPORT_STATES.each do |state|
define_method(:"#{state}_#{scope}") do
activities.send(state.to_sym).where(activity_type: activity_type).count
end
end
end
def activities
account_list.activities.where(created_at: (start_date..end_date))
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/filters_controller_spec.rb
|
<gh_stars>0
require 'rails_helper'
require 'json'
describe Api::V2::Contacts::FiltersController, type: :controller do
let(:factory_type) { 'account_lists' }
let!(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
context 'authorized user' do
before do
api_login(user)
end
describe '#index' do
it 'gets filters for contacts' do
get :index
filters_displayed = JSON.parse(response.body)['data'].map do |filter|
filter['type'].gsub('contact_filter_', '').camelize
end
expect(Contact::Filterer::FILTERS_TO_DISPLAY.map(&:pluralize)).to include(*filters_displayed)
expect(response.status).to eq 200
end
end
end
context 'unauthorized user' do
describe '#index' do
it 'does not get a list of filters' do
get :index, account_list_id: account_list_id
expect(response.status).to eq 401
end
end
end
end
|
chuckmersereau/api_practice
|
app/preloaders/api/v2/contacts/people/websites_preloader.rb
|
<filename>app/preloaders/api/v2/contacts/people/websites_preloader.rb
class Api::V2::Contacts::People::WebsitesPreloader < ApplicationPreloader
ASSOCIATION_PRELOADER_MAPPING = {}.freeze
FIELD_ASSOCIATION_MAPPING = {}.freeze
private
def serializer_class
Person::WebsiteSerializer
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/chalkline_mails_controller.rb
|
<gh_stars>0
class Api::V2::AccountLists::ChalklineMailsController < Api::V2Controller
def create
authorize_chalkline_mails
load_chalkline_mails
send_chalkline_mails
render_chalkline_mails
end
private
def authorize_chalkline_mails
authorize(load_account_list, :show?)
end
def account_lists_scope
account_lists
end
def load_account_list
@account_list ||= account_lists_scope.find(params[:account_list_id])
end
def load_chalkline_mails
@chalkline_mails ||= AccountList::ChalklineMails.new(account_list: load_account_list)
end
def send_chalkline_mails
load_chalkline_mails.send_later
end
def permitted_filters
[]
end
def render_chalkline_mails
render json: @chalkline_mails,
status: success_status
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/locale_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Contact::Filter::Locale 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, locale: 'fr-CA') }
let!(:contact_two) { create(:contact, account_list_id: account_list.id, locale: 'fr-FR') }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, locale: 'en-US') }
let!(:contact_four) { create(:contact, account_list_id: account_list.id, locale: 'en-US') }
let!(:contact_five) { create(:contact, account_list_id: account_list.id, locale: 'Something else') }
describe '#config' do
it 'returns expected config' do
options = [
{ name: '-- Any --', id: '', placeholder: 'None' },
{ id: 'null', name: '-- Unspecified --' },
{ name: 'Something else', id: 'Something else' },
{ name: 'US English', id: 'en-US' },
{ name: 'Canadian French', id: 'fr-CA' },
{ name: 'fr-FR', id: 'fr-FR' }
]
expected_config = {
name: :locale,
multiple: true,
default_selection: '',
options: options,
parent: 'Contact Details',
title: 'Language',
type: 'multiselect'
}
expect(described_class.config([account_list])).to include(expected_config)
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, { locale: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { locale: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { locale: '' }, nil)).to eq(nil)
end
end
context 'filter by address historic' do
it 'returns only contacts that have the locale' do
expect(described_class.query(contacts, { locale: 'en-US' }, nil).to_a).to match_array [contact_three, contact_four]
expect(described_class.query(contacts, { locale: 'fr-CA' }, nil).to_a).to eq [contact_one]
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/donation_imports/base/find_donation.rb
|
<gh_stars>0
# This class looks for a donation that already exists in MPDX to match to a donation that is being imported.
# We don't want to import a donation more than once into the same designation profile.
# The attributes passed on initialize will be considered authoritative.
class DonationImports::Base
class FindDonation
attr_accessor :designation_profile, :attributes
def initialize(designation_profile:, attributes:)
@designation_profile = designation_profile
@attributes = attributes.with_indifferent_access
end
def find_and_merge
donations = find_donations_by_remote_id # First look for the donation by it's remote id or Tnt id.
if donations.empty?
# If the donation couldn't be found by it's id look for it by it's other attributes.
# One way this could happen is if the donation was imported
# from Tnt before we started storing the tnt_id.
donations = find_donations_by_donor_and_amount_and_date
end
# The donation may have ended up in the incorrect designation account, or in multiple
# designation accounts (duplicated). One way this could happen is because the Tnt import
# does not know which designation account to put it in, so it makes up a new one.
# Since we now know the correct designation account (in attributes)
# we will correct the error by running a merge process.
MergeDonations.new(donations).merge
end
private
def find_donations_by_remote_id
return [] if attributes[:remote_id].blank?
donation_scope.where('tnt_id = :id OR remote_id = :id', id: attributes[:remote_id]).to_a
end
def find_donations_by_donor_and_amount_and_date
where_fields = attributes.slice(:donor_account_id, :amount, :donation_date).merge(remote_id: nil)
donation_scope.where(where_fields).to_a
end
def donation_scope
Donation.where(designation_account_id: searchable_designation_ids)
end
# because the DesignationAccount created when the user imports from Tnt was created
# un-associated to a DesignationProfile, we need to also look at those 'placeholder' accounts
def searchable_designation_ids
profile_accounts = designation_profile.designation_accounts.pluck(:id)
# include specified designation if account is specified
profile_accounts = (profile_accounts + [attributes[:designation_account_id]]).compact.uniq
account_list = designation_profile.account_list
return profile_accounts unless account_list
placeholder_accounts = account_list.designation_accounts.where(designation_number: nil).pluck(:id)
profile_accounts + placeholder_accounts
end
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/activity_type_spec.rb
|
require 'rails_helper'
RSpec.describe Task::Filter::ActivityType do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:task_one) { create(:task, account_list: account_list, activity_type: 'Call') }
let!(:task_two) { create(:task, account_list: account_list, activity_type: 'Appointment') }
let!(:task_three) { create(:task, account_list: account_list, activity_type: 'Email') }
let!(:task_four) { create(:task, account_list: account_list, activity_type: nil) }
let!(:task_five) { create(:task, account_list: account_list, activity_type: '') }
describe '#config' do
it 'returns expected config' do
options = [
{ name: '-- Any --', id: '', placeholder: 'None' },
{ name: '-- None --', id: 'none' },
{ name: 'Call', id: 'Call' },
{ name: 'Appointment', id: 'Appointment' },
{ name: 'Email', id: 'Email' },
{ name: 'Text Message', id: 'Text Message' },
{ name: 'Facebook Message', id: 'Facebook Message' },
{ name: 'Letter', id: 'Letter' },
{ name: 'Newsletter - Physical', id: 'Newsletter - Physical' },
{ name: 'Newsletter - Email', id: 'Newsletter - Email' },
{ name: 'Pre Call Letter', id: 'Pre Call Letter' },
{ name: 'Reminder Letter', id: 'Reminder Letter' },
{ name: 'Support Letter', id: 'Support Letter' },
{ name: 'Thank', id: 'Thank' },
{ name: 'To Do', id: 'To Do' },
{ name: 'Talk to In Person', id: 'Talk to In Person' },
{ name: 'Prayer Request', id: 'Prayer Request' }
]
expect(described_class.config([account_list])).to include(multiple: true,
name: :activity_type,
options: options,
parent: nil,
priority: 0,
title: 'Action',
type: 'multiselect',
default_selection: '')
end
end
describe '#query' do
let(:tasks) { account_list.tasks }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, nil)).to eq(nil)
expect(described_class.query(tasks, { activity_type: {} }, nil)).to eq(nil)
expect(described_class.query(tasks, { activity_type: [] }, nil)).to eq(nil)
expect(described_class.query(tasks, { activity_type: '' }, nil)).to eq(nil)
end
end
context 'filter by activity_type' do
it 'filters multiple activity_types' do
result = described_class.query(tasks, { activity_type: 'Call, Appointment,none' }, nil).to_a
expect(result).to match_array([task_one, task_two, task_four, task_five])
result = described_class.query(tasks, { activity_type: 'call,none, Email,' }, nil).to_a
expect(result).to match_array([task_three, task_four, task_five])
end
it 'filters a single activity_type' do
expect(described_class.query(tasks, { activity_type: 'Email' }, nil).to_a).to match_array([task_three])
end
it 'filters by non existing activity_type' do
expect(described_class.query(tasks, { activity_type: 'Newsletter' }, nil).to_a).to eq([])
end
it 'filters by none' do
expect(described_class.query(tasks, { activity_type: 'none' }, nil).to_a).to match_array([task_four, task_five])
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/addresses_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::Contacts::AddressesController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:resource_type) { :address }
let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) }
let!(:resource) { create(:address, addressable: contact, source_donor_account: build(:donor_account)) }
let!(:second_resource) { create(:address, addressable: contact) }
let(:id) { resource.id }
let(:parent_param) { { contact_id: contact.id } }
let(:parent_association) { :addressable }
let(:correct_attributes) { { street: '123 Street' } }
let(:incorrect_attributes) { nil }
let!(:not_destroyed_scope) { Address.current }
let(:factory_type) { :address }
before(:each) do
stub_request(:get, %r{api\.smartystreets\.com/.*}).to_return(status: 200, body: '{}', headers: {})
end
include_examples 'show_examples'
include_examples 'update_examples'
include_examples 'create_examples', except: [:includes]
include_examples 'destroy_examples'
include_examples 'index_examples'
describe '#index authorization' do
it 'does not show resources for contact that user does not own' do
api_login(user)
contact = create(:contact, account_list: create(:user_with_account).account_lists.order(:created_at).first)
get :index, contact_id: contact.id
expect(response.status).to eq(403)
end
end
end
|
chuckmersereau/api_practice
|
app/workers/csv_import_contact_worker.rb
|
<gh_stars>0
class CsvImportContactWorker
include Sidekiq::Worker
MAX_RETRIES = 3
sidekiq_options queue: :api_csv_import_contact_worker, retries: MAX_RETRIES
def initialize
@retries = 0
end
def perform(import_id, csv_headers, csv_fields)
import = Import.find(import_id)
csv_row = CSV::Row.new(csv_headers, csv_fields)
begin
CsvRowContactBuilder.new(csv_row: csv_row, import: import).build.save!
rescue StandardError => exception
if retryable_exception?(exception)
Rollbar.error(exception)
@retries += 1
retry if @retries <= MAX_RETRIES
end
import.with_lock do
import.file_row_failures << [message_for_exception(exception)] + csv_fields
import.save!
end
end
end
private
def retryable_exception?(exception)
!exception.is_a?(ActiveRecord::RecordInvalid) &&
!exception.is_a?(ActiveRecord::RecordNotUnique)
end
def message_for_exception(exception)
if exception.is_a?(ActiveRecord::RecordNotUnique)
'Record not unique error: Please ensure you are not importing duplicate '\
'data (such as duplicate email addresses, which must be unique)'
else
exception.message
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170921212918_add_checked_for_google_plus_account_to_email_addresses.rb
|
<gh_stars>0
class AddCheckedForGooglePlusAccountToEmailAddresses < ActiveRecord::Migration
def change
add_column :email_addresses,
:checked_for_google_plus_account,
:boolean,
null: false,
default: false
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/contacts_import_spec.rb
|
require 'rails_helper'
describe TntImport::ContactsImport do
let(:user) { create(:user) }
let(:import) { create(:tnt_import, override: true, user: user) }
let(:tnt_import) { TntImport.new(import) }
it 'does not include the contacts in the return hash if they were not saved' do
importer = TntImport::ContactsImport.new(import, create(:designation_profile), tnt_import.xml)
expect(importer).to receive(:import_contact).and_return(double(id: nil)).twice
expect(importer.import_contacts).to eq({})
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/tags/bulk_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts > Tags > Bulk' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:contacts, :tags])
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:tag_one) { 'tag_one' }
let(:tag_two) { 'tag_two' }
let(:tag_three) { 'tag_three' }
let!(:contact_one) { create(:contact, account_list: account_list, tag_list: [tag_one, tag_two]) }
let!(:contact_two) { create(:contact, account_list: account_list, tag_list: [tag_one, tag_three]) }
let!(:contact_three) { create(:contact, account_list: account_list, tag_list: [tag_two, tag_three]) }
let(:contact_ids) { [contact_one, contact_two].map(&:id).join(',') }
let(:form_data) do
{
data: [
{
data: {
type: 'tags',
attributes: {
name: tag_one
}
}
},
{
data: {
type: 'tags',
attributes: {
name: tag_two
}
}
}
]
}.merge(filter_params)
end
let(:filter_params) do
{
filter: {
contact_ids: contact_ids
}
}
end
context 'authorized user' do
before { api_login(user) }
before do
expect(contact_one.tag_list.count).to eq 2
expect(contact_two.tag_list.count).to eq 2
expect(contact_three.tag_list.count).to eq 2
end
post '/api/v2/contacts/tags/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 form_data
expect(response_status).to eq(200), invalid_status_detail
expect(contact_one.reload.tag_list.count).to eq 2
expect(contact_two.reload.tag_list.count).to eq 3
expect(contact_three.reload.tag_list.count).to eq 2
end
end
# destroy
delete '/api/v2/contacts/tags/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 form_data
expect(response_status).to eq(204), invalid_status_detail
expect(contact_one.reload.tag_list.count).to eq 0
expect(contact_two.reload.tag_list.count).to eq 1
expect(contact_three.reload.tag_list.count).to eq 2
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/notification_type/larger_gift.rb
|
class NotificationType::LargerGift < NotificationType
def check_contacts_filter(contacts)
contacts.financial_partners
end
def check_for_donation_to_notify(contact)
larger_gift(contact) if had_larger_gift?(contact)
end
def had_larger_gift?(contact)
return false unless contact.pledge_frequency && contact.pledge_amount
if contact.pledge_frequency < 1
first_gift_without_aid_amount = contact.donations.without_gift_aid.first&.amount || 0
return contact.last_donation.present? &&
(contact.amount_with_gift_aid(first_gift_without_aid_amount) > contact.pledge_amount)
end
return false if long_time_frame_gift_given_early?(contact)
contact_monthly_avg_current = contact.monthly_avg_current(except_payment_method: Donation::GIFT_AID)
monthly_avg_without_gift_aid = contact.amount_with_gift_aid(contact_monthly_avg_current)
monthly_avg_with_prev_gift_without_gift_aid = contact.amount_with_gift_aid(contact.monthly_avg_with_prev_gift)
monthly_avg_without_gift_aid > contact.monthly_pledge &&
monthly_avg_with_prev_gift_without_gift_aid > contact.monthly_pledge &&
!caught_up_earlier_months?(contact)
end
def caught_up_earlier_months?(contact)
return unless contact.prev_month_donation_date
from_date = contact.prev_month_donation_date << 1
while from_date >= [Date.today << 12, contact.first_donation_date].compact.max
contact_monthly_avg = contact.monthly_avg_from(from_date, except_payment_method: Donation::GIFT_AID)
monthly_avg_without_gift_aid = contact.amount_with_gift_aid(contact_monthly_avg)
return true if monthly_avg_without_gift_aid == contact.monthly_pledge
from_date <<= contact.pledge_frequency
end
end
def long_time_frame_gift_given_early?(contact)
return unless contact.pledge_frequency.to_i >= LongTimeFrameGift::LONG_TIME_FRAME_PLEDGE_FREQUENCY &&
contact.prev_month_donation_date.present?
last_donation_month_end = contact.last_donation.donation_date.end_of_month
previous_frame_start_date = (last_donation_month_end << contact.pledge_frequency - 1).beginning_of_month
previous_frame_end_date = (last_donation_month_end << 1).end_of_month
prev_donation_amount = contact.donations.where('donation_date >= ? AND donation_date <= ?',
previous_frame_start_date,
previous_frame_end_date).sum(:amount)
prev_donation_amount == contact.last_donation.amount &&
prev_donation_amount == contact.pledge_amount
end
def larger_gift(contact)
contact.current_pledge_interval_donations.where.not(amount: contact.pledge_amount).first ||
contact.last_donation
end
def task_description_template(notification = nil)
if notification&.account_list&.designation_accounts&.many?
_('%{contact_name} gave a larger than usual gift of %{amount} on %{date} to %{designation}. Send them a Thank You.')
else
_('%{contact_name} gave a larger than usual gift of %{amount} on %{date}. Send them a Thank You.')
end
end
end
|
chuckmersereau/api_practice
|
spec/serializers/reports/monthly_losses_graph_serializer_spec.rb
|
<filename>spec/serializers/reports/monthly_losses_graph_serializer_spec.rb
require 'rails_helper'
describe Reports::MonthlyLossesGraphSerializer do
let(:organization) { create(:organization) }
let(:account_list) do
create(:account_list, salary_organization_id: organization)
end
let(:report) do
Reports::MonthlyLossesGraph.new(account_list: account_list, months: 5)
end
subject { Reports::MonthlyLossesGraphSerializer.new(report).as_json }
it { expect(subject[:account_list][:name]).to be account_list.name }
it { expect(subject[:losses].size).to eq 5 }
it { expect(subject[:month_names].size).to eq 5 }
end
|
chuckmersereau/api_practice
|
lib/tasks/assets.rake
|
<filename>lib/tasks/assets.rake<gh_stars>0
namespace :assets do
task clobber: :environment do
end
task compile: :environment do
end
task precompile: :environment do
end
end
|
chuckmersereau/api_practice
|
spec/services/donation_imports/siebel/donor_importer/person_importer_spec.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
require 'rails_helper'
RSpec.describe DonationImports::Siebel::DonorImporter::PersonImporter do
let(:mock_siebel_import) { double(:mock_siebel_import) }
let!(:user) { create(:user_with_account) }
let(:organization_account) { user.organization_accounts.first }
let(:organization) { organization_account.organization }
let(:contact) { create(:contact) }
let(:donor_account) { create(:donor_account, contacts: [contact]) }
EmailAddressStructure = Struct.new(:id, :email, :updated_at, :type, :primary)
PhoneNumberStructure = Struct.new(:id, :phone, :updated_at, :type, :primary)
PersonStructure = Struct.new(:id, :first_name, :last_name, :primary, :email_addresses,
:phone_numbers, :preferred_name, :middle_name, :title, :suffix, :sex)
let(:first_siebel_email_address) do
EmailAddressStructure.new('email_id_one', '<EMAIL>')
end
let(:second_siebel_email_address) do
EmailAddressStructure.new('email_id_two', '<EMAIL>', 3.months.ago.to_s)
end
let(:siebel_phone_number) { PhoneNumberStructure.new('phone_id_one', '111 222-3333') }
let(:siebel_person) do
PersonStructure.new('person_id_one',
'Jacob', 'Rudie',
true,
[first_siebel_email_address, second_siebel_email_address],
[siebel_phone_number])
end
before do
allow(mock_siebel_import).to receive(:organization).and_return(organization)
end
subject { described_class.new(mock_siebel_import) }
context '#import_profiles' do
it 'adds a person and its email and phone number to a contact' do
expect do
result = subject.add_or_update_person_on_contact(siebel_person: siebel_person,
contact: contact,
donor_account: donor_account,
date_from: 2.months.ago)
expect(result).to be_truthy
end.to change { contact.people.count }.by(1)
.and change { EmailAddress.count }.by(1)
.and change { PhoneNumber.count }.by(1)
expect(contact.primary_person.reload.first_name).to eq('Jacob')
expect(contact.primary_person.reload.last_name).to eq('Rudie')
expect(contact.primary_person.email_addresses.pluck(:email).first).to eq('<EMAIL>')
expect(contact.primary_person.phone_numbers.pluck(:number).first).to eq('+1112223333')
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/batch_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Batch' do
include_context :json_headers
documentation_scope = :requests
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
context 'authorized user' do
before { api_login(user) }
let(:first_response) { JSON.parse(response_body).first }
let(:second_response) { JSON.parse(response_body).second }
let(:second_response_attributes) { JSON.parse(second_response['body'])['data']['attributes'] }
let!(:task) { create(:task, account_list: account_list) }
# Activities
post '/api/v2/batch' do
with_options scope: :requests do
parameter :method, 'GET, POST, PATCH, PUT or DELETE'
parameter :path, 'The path (URL) of the request'
parameter :body, 'The JSON body of the request'
end
example 'Batch', document: documentation_scope do
explanation <<~HEREDOC
A batch endpoint that allows you to send an array of requests. It expects a JSON payload
with a requests key that has an array of request objects. A request object needs to have a
method key and a path key. It may also have a body key. The response will be a JSON array
of response objects. A response object has a status key, a headers key, and a body key.
The body is a string of the server response. In addition to the requests key in the
payload, you may also specify a on_error key which may be set to CONTINUE, or ABORT.
CONTINUE is the default, and it will return a 200 no matter what, and give a response for
every request, no matter if they errored or not. ABORT will end the batch request early
if one of the requests fails. The batch response will have the status code of the failing
request, and the response will include responses up to and including the errored request,
but no more. Some endpoints are unable to be used within a batch request. At this time,
only bulk endpoints are disallowed from being used in a batch request.
HEREDOC
do_request requests: [
{ method: 'GET', path: "/api/v2/account_lists/#{account_list.id}/donations" },
{ method: 'PATCH', path: "/api/v2/tasks/#{task.id}", body: {
data: {
id: task.id,
type: 'tasks',
attributes: {
subject: 'Random Task Subject',
overwrite: true
}
}
} }
]
expect(response_status).to eq 200
expect(first_response['status']).to eq(200)
expect(first_response['body']['data']).to be_present
expect(first_response['body']['meta']).to be_present
expect(first_response['headers']).to be_present
expect(second_response['status']).to eq(200)
expect(second_response_attributes['subject']).to eq 'Random Task Subject'
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/concerns/date_range_filterable_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe Concerns::Reports::DateRangeFilterable do
class DefaultSample
include Concerns::Reports::DateRangeFilterable
def filter_params
{}
end
end
class SpecificSample
include Concerns::Reports::DateRangeFilterable
def filter_params
{ month_range: ((Date.today - 3.years)..(Date.today - 1.year)) }
end
end
class InvalidSample
include Concerns::Reports::DateRangeFilterable
def filter_params
{ month_range: ((Date.today - 1.year)..(Date.today - 3.years)) }
end
end
let(:default_start_date) { 12.months.ago.to_date.beginning_of_month }
let(:three_years_ago) { Date.today - 3.years }
let(:one_year_ago) { Date.today - 1.year }
let(:specific_sample_dates) { (three_years_ago..one_year_ago) }
let(:invalid_sample_date) { (one_year_ago..three_years_ago) }
let(:specific_sample) { SpecificSample.new }
let(:invalid_sample) { InvalidSample.new }
it 'should have a default number of months back' do
expect(Concerns::Reports::DateRangeFilterable::MONTHS_BACK).to eq(12)
end
it 'should get a default end date' do
expect(DefaultSample.new.end_date).to eq(Date.today)
end
it 'should get a default start date' do
expect(DefaultSample.new.start_date).to eq(default_start_date)
end
it 'should get a specified start date' do
expect(specific_sample.start_date).to eq(three_years_ago.beginning_of_month)
end
it 'should get a specified end date' do
expect(specific_sample.end_date).to eq(specific_sample_dates.last)
end
it 'should handle cases where the start date is after the end date' do
date = invalid_sample.end_date.beginning_of_month - InvalidSample::MONTHS_BACK.months
expect(invalid_sample.start_date).to eq(date)
end
it 'should build an array of dates that are all the beginning of the month' do
expect(specific_sample.months.size).to eq(25)
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/people/merges_controller_spec.rb
|
<filename>spec/controllers/api/v2/contacts/people/merges_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V2::Contacts::People::MergesController, type: :controller do
# This is required!
let(:user) { create(:user_with_account) }
# This MAY be required!
let(:account_list) { user.account_lists.order(:created_at).first }
# This is required!
let(:factory_type) do
:person
end
let(:given_resource_type) { 'merges' }
let!(:contact) { create(:contact, name: '<NAME>', account_list: account_list) }
let!(:winner) { create(:person, first_name: 'John', last_name: 'Doe') }
let!(:loser) { create(:person, first_name: 'John', last_name: '<NAME>') }
before do
contact.people << winner
contact.people << loser
create(:email_address, person: resource) # Test inclusion of related resources.
end
# This is required!
let!(:resource) do
winner
end
let(:parent_param) do
{ contact_id: contact.id }
end
# This is required!
let(:correct_attributes) do
{}
end
# This is required!
let(:correct_relationships) do
{
winner: {
data: {
type: 'people',
id: winner.id
}
},
loser: {
data: {
type: 'people',
id: loser.id
}
}
}
end
let(:incorrect_attributes) do
{}
end
let(:incorrect_relationships) do
{}
end
include_context 'common_variables'
describe '#create' do
include_examples 'including related resources examples',
action: :create,
expected_response_code: 200
include_examples 'sparse fieldsets examples',
action: :create,
expected_response_code: 200
it 'merges the two contacts for users that are signed in' do
api_login(user)
expect do
post :create, full_correct_attributes
end.to change(&count_proc).by(-1)
expect(response.status).to eq(200)
end
it 'does not perform the merge when there are errors in sent data' do
if incorrect_attributes
api_login(user)
expect do
post :create, full_incorrect_attributes
end.not_to change(&count_proc)
expect(response.status).to be_between(400, 499)
expect(response.body).to include('errors')
end
end
it 'does not perform the merge for users that are not signed in' do
expect do
post :create, full_correct_attributes
end.not_to change(&count_proc)
expect(response.status).to eq(401)
expect(response_errors).to be_present
end
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/history_import_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/services/tnt_import/history_import_spec.rb
require 'rails_helper'
describe TntImport::HistoryImport do
let(:user) { create(:user) }
let(:tnt_import) { create(:tnt_import, override: true, user: user) }
let(:xml) { TntImport::XmlReader.new(tnt_import).parsed_xml }
let(:history_row) { xml.tables['History'].first }
let(:contacts) do
xml.tables['HistoryContact']&.map do |row|
create(:contact, tnt_id: row['ContactID'])
end || {}
end
let(:contact_ids) { Hash[contacts.map { |c| [c.tnt_id.to_s, c.id] }] }
subject { TntImport::HistoryImport.new(tnt_import, contact_ids, xml) }
before do
stub_smarty_streets
end
describe '#import' do
context 'no xml history data' do
let(:xml) { double(tables: {}) }
it 'returns empty hash' do
expect(subject.import).to eq({})
end
end
context 'with data change task types' do
before do
history_row['TaskTypeID'] = '190'
end
it 'skips change data history items' do
expect { subject.import }.to_not change { Task.count }
end
end
context 'with appeal mapping' do
let(:appeal) { xml.tables['Appeal'].first }
before do
xml.tables['History'].first['AppealID'] = appeal['id']
end
it 'returns mapping of contacts to appeal ids' do
expect(subject.import).to eq(appeal['id'] => contact_ids.values)
end
it 'adds a tag' do
expect { subject.import }.to change { Task.count }
task = Task.last
expect(task.tag_list).to include appeal['Description'].downcase
end
end
context 'with multiple task contacts per task' do
let(:tnt_import) do
create(:tnt_import_with_multiple_task_contacts, override: true, user: user)
end
it 'creates one for each contact' do
expect { subject.import }.to change { Task.count }.by(contacts.size)
end
it 'creates tasks with only a single associated contact' do
subject.import
Task.all.each { |task| expect(task.contacts.size).to eq 1 }
end
context 'activity_type of Newsletter - Physical' do
before do
xml.tables['History'].first['TaskTypeID'] = 60
end
it 'does not create a task for every contact' do
expect_any_instance_of(Task).to_not receive(:log_newsletter)
expect { subject.import }.to change { Task.count }.by(contacts.size)
end
end
end
it 'does not increment the tasks counts' do
expect(contacts.count).to be 1
contact = contacts.first
expect { subject.import }.to change { contact.tasks.count }.by(1).and change { contact.uncompleted_tasks_count }.by(0)
end
context 'with LoggedByUserID' do
let(:user_row) do
{ 'id' => '394614727', 'LastEdit' => '2016-11-16 11:54:58', 'UserName' => 'Clark',
'PasswordHash' => '0', 'IsActive' => 'true', 'IsAdmin' => 'true' }
end
let(:note) { 'testing notes in a logged task' }
before do
xml.tables['User'] ||= [user_row]
history_row['LoggedByUserID'] = user_row['id']
history_row['Notes'] = note
end
it 'adds user to comment' do
expect { subject.import }.to change(ActivityComment, :count).by(2)
task = Task.last
comments = task.comments.pluck(:body)
expect(comments).to include "Completed By: #{user_row['UserName']}"
expect(comments).to include note
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/admin/reset.rb
|
<reponame>chuckmersereau/api_practice<filename>app/models/admin/reset.rb
class Admin::Reset
include ActiveModel::Model
attr_accessor :reason, :admin_resetting, :user_finder, :reset_logger, :resetted_user_email, :account_list_name
validates :reason, :resetted_user, :account_list, :reset_log, :admin_resetting, presence: true
validate :account_list_is_unique
def self.reset!(*args)
new(*args).reset!
end
def reset!
return false unless valid?
authorize_reset_log
save_reset_log
queue_reset_job
true
end
def account_list
@account_list ||= account_list_scope&.first
end
private
attr_accessor :reset_log
def reset_log
@reset_log ||= reset_logger.new(admin_resetting: admin_resetting, resetted_user: resetted_user, reason: reason)
end
def authorize_reset_log
PunditAuthorizer.new(admin_resetting, reset_log).authorize_on('create')
end
def save_reset_log
reset_log.save!
end
def queue_reset_job
Admin::AccountListResetWorker.perform_async(account_list.id, resetted_user.id, reset_log.id)
end
def resetted_user
@resetted_user ||= user_finder&.find_user_by_email(resetted_user_email)
end
def account_list_scope
resetted_user&.account_lists&.where(name: account_list_name)
end
def account_list_is_unique
return if account_list_scope&.count == 1
errors[:account_list] << "is not unique or cannot be found, make sure the user's account list name is correct and also unique"
end
end
|
chuckmersereau/api_practice
|
spec/factories/notification_preferences.rb
|
FactoryBot.define do
factory :notification_preference do
association :notification_type
association :account_list
email { true }
end
end
|
chuckmersereau/api_practice
|
spec/support/i18n.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
RSpec.configure do |config|
config.after(:each) do |_example|
I18n.locale = I18n.default_locale
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.