repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
spec/serializers/reports/appointment_result_period_serializer_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe Reports::AppointmentResultsPeriodSerializer do
let(:account_list) { create(:account_list) }
let(:object) do
Reports::AppointmentResultsPeriod.new(account_list: account_list,
start_date: 1.week.ago,
end_date: DateTime.current)
end
subject { Reports::AppointmentResultsPeriodSerializer.new(object).as_json }
it 'serializes attributes' do
expect(subject.keys).to match_array [:start_date,
:end_date,
:individual_appointments,
:weekly_individual_appointment_goal,
:group_appointments,
:new_monthly_partners,
:new_special_pledges,
:monthly_increase,
:pledge_increase,
:created_at,
:id,
:updated_at,
:updated_in_db_at,
:pledge_increase_contacts,
:new_pledges]
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180302023505_change_collation_of_contacts_name_column.rb
|
<reponame>chuckmersereau/api_practice
class ChangeCollationOfContactsNameColumn < ActiveRecord::Migration
def up
ActiveRecord::Base.connection.execute(
'ALTER TABLE contacts ALTER name TYPE character varying COLLATE "C";'
)
end
def down
ActiveRecord::Base.connection.execute(
'ALTER TABLE contacts ALTER name TYPE character varying COLLATE "en_US.UTF-8";'
)
end
end
|
chuckmersereau/api_practice
|
app/models/account_list_user.rb
|
class AccountListUser < ApplicationRecord
belongs_to :user
belongs_to :account_list
after_create :duplicate_notification_preferences
after_destroy :destroy_notification_preferences
after_destroy :change_user_default_account_list_if_needed
audited on: [:destroy]
private
def duplicate_notification_preferences
account_list.notification_preferences.where(user_id: nil).find_each do |notification_preference|
notification_preference.dup.tap do |user_notification_preference|
user_notification_preference.id = nil
user_notification_preference.user = user
user_notification_preference.email = true
user_notification_preference.save!
end
end
end
def destroy_notification_preferences
account_list.notification_preferences.where(user: user).destroy_all
end
def change_user_default_account_list_if_needed
return unless user && user.default_account_list == account_list_id
user.update(default_account_list: user.account_lists.reload.order(:created_at).map(&:id).first)
end
end
|
chuckmersereau/api_practice
|
spec/support/database_cleaner.rb
|
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
end
|
chuckmersereau/api_practice
|
app/services/string_io_with_path.rb
|
<filename>app/services/string_io_with_path.rb
# Workaround for adding original_filename to StringIO as needed by CarrierWave see:
# https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Upload-from-a-string-in-Rails-3
class StringIOWithPath < StringIO
attr_reader :original_filename
def initialize(*args)
super(*args[1..-1])
@original_filename = args[0]
end
end
|
chuckmersereau/api_practice
|
spec/factories/name_male_ratios.rb
|
<filename>spec/factories/name_male_ratios.rb
FactoryBot.define do
factory :name_male_ratio do
sequence(:name) { |n| "Name#{n}" }
male_ratio 0.5
end
end
|
chuckmersereau/api_practice
|
spec/services/donation_reports/donation_info_spec.rb
|
require 'rails_helper'
describe DonationReports::DonationInfo do
let(:account_list) { create(:account_list) }
let(:donation) { create(:donation) }
describe '.from_donation' do
it 'intantiates an object with attributes' do
donation_info = DonationReports::DonationInfo.from_donation(donation)
expect(donation_info.amount).to eq(donation.amount)
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/analytics_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Account List Analytics' do
include_context :json_headers
documentation_scope = :account_lists_api_analytics
let(:resource_type) { 'account_list_analytics' }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:resource_attributes) do
%w(
appointments
contacts
correspondence
created_at
electronic
email
end_date
facebook
phone
start_date
text_message
updated_at
updated_in_db_at
)
end
context 'authorized user' do
before { api_login(user) }
# show
get '/api/v2/account_lists/:account_list_id/analytics' do
parameter 'account_list_id', 'Account List ID', required: true # type: 'Number'
parameter 'filter[start_date]', 'Starting Date for Analytics, in ISO8601' # type: 'String'
parameter 'filter[end_date]', 'Ending Date for Analytics, in ISO8601' # type: 'String'
with_options scope: [:data, :attributes] do
response_field 'appointments', 'Appointment related analytics', type: 'Object'
response_field 'contacts', 'Contact related analytics', type: 'Object'
response_field 'correspondence', 'Correspondence related analytics', type: 'Object'
response_field 'created_at', 'Time when analytics were observed', type: 'String'
response_field 'electronic', 'Electronic related analytics', type: 'Object'
response_field 'email', 'Email related analytics', type: 'Object'
response_field 'end_date', 'Ending date for analytics period', type: 'String'
response_field 'facebook', 'Facebook related analytics', type: 'Object'
response_field 'phone', 'Phone related analytics', type: 'Object'
response_field 'start_date', 'Starting date for analytics period', type: 'String'
response_field 'text_message', 'Text message related analytics', type: 'Object'
response_field 'updated_at', 'Time when analytics were observed', type: 'String'
end
example 'Analytics for the past 30 days [GET]', document: documentation_scope do
explanation 'List analytics related to the Account List for the past 30 days'
do_request(account_list_id: account_list_id)
check_resource
expect(response_status).to eq 200
end
example 'Analytics for a custom date range [GET]', document: documentation_scope do
explanation 'List analytics related to the Account List with a start and end date'
do_request(account_list_id: account_list_id, filter: { start_date: 1.week.ago.iso8601, end_date: Time.current.iso8601 })
check_resource
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
app/workers/admin/redis_hash_compactor_worker.rb
|
<gh_stars>0
# inspired by: https://gist.github.com/dennisfaust/c94f0e1aec54e37c52e431e9542ff042
# because of: https://github.com/mhenrixon/sidekiq-unique-jobs/issues/234
class RedisHashCompactorWorker
include Sidekiq::Worker
PER_PAGE = 1_000
# we normally don't put things in this queue because it is only run by one legacy worker (we had one
# queue reserved for mpdx classic that we haven't repurposed yet), but it seems logical to use it for this.
sidekiq_options queue: :default
def perform
# We need this to get a redis connection with no namespace gem
@conn = Redis.new(host: Redis.current.client.host, port: Redis.current.client.port)
cursor = '0'
loop do
cursor = scan_from(cursor)
break if cursor == '0'
end
end
private
def scan_from(start_cursor)
cursor, jobs = @conn.hscan(SidekiqUniqueJobs::HASH_KEY, [start_cursor, 'MATCH', '*', 'COUNT', PER_PAGE])
to_delete = jobs.map do |jid, unique_key|
# don't delete if job is still waiting to run
jid unless @conn.exists(unique_key)
end.compact
@conn.hdel(SidekiqUniqueJobs::HASH_KEY, to_delete) if to_delete.any?
cursor
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/region.rb
|
class Contact::Filter::Region < Contact::Filter::Base
def execute_query(contacts, filters)
region_filters = parse_list(filters[:region])
region_filters << nil if region_filters.delete('none')
contacts.where('addresses.region' => region_filters,
'addresses.historic' => filters[:address_historic] == 'true')
.joins(:addresses)
end
def title
_('Region')
end
def parent
_('Contact Location')
end
def type
'multiselect'
end
def custom_options
[{ name: _('-- None --'), id: 'none' }] + account_lists.map(&:regions).flatten.uniq.select(&:present?).map { |a| { name: a, id: a } }
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/tasks_controller.rb
|
<reponame>chuckmersereau/api_practice
require 'json_api_service'
class Api::V2::TasksController < Api::V2Controller
PERMIT_MULTIPLE_SORTING_PARAMS = true
def index
authorize_index
load_tasks
render json: Api::V2::TasksPreloader.new(include_params, field_params).preload(@tasks),
meta: meta_hash(@tasks),
include: include_params,
fields: field_params
end
def show
load_task
authorize_task
render_task
end
def create
persist_task
end
def update
load_task
authorize_task
persist_task
end
def destroy
load_task
authorize_task
destroy_task
end
private
def destroy_task
@task.deleted_by = current_user
@task.destroy
head :no_content
end
def load_tasks
@tasks = Task::Filterer.new(filter_params)
.filter(scope: task_scope, account_lists: account_lists)
.page(page_number_param)
.per(per_page_param)
order_tasks
end
def order_tasks
@tasks = @tasks.reorder(sorting_param)
@tasks = @tasks.select(
<<~SQL
"activities".*,
CASE WHEN "activities"."completed" != true AND "activities"."start_at" < now()
THEN "activities"."start_at" END AS "overdue"
SQL
) if sorting_param == default_sort_param
@tasks = @tasks.order(Task.arel_table[:created_at].asc)
end
def load_task
@task ||= Task.find(params[:id])
end
def render_task
render json: @task,
status: success_status,
include: include_params,
fields: field_params
end
def persist_task
build_task
authorize_task
if save_task
render_task
else
render_with_resource_errors(@task)
end
end
def build_task
@task ||= task_scope.build
@task.assign_attributes(task_params)
end
def save_task
@task.save(context: persistence_context)
end
def task_params
params
.require(:task)
.permit(Task::PERMITTED_ATTRIBUTES)
end
def task_attributes
end
def authorize_task
authorize(@task)
end
def authorize_index
account_lists.each { |account_list| authorize(account_list, :show?) }
end
def task_scope
Task.where(account_list: account_lists.collect(&:id))
end
def permitted_sorting_params
%w(start_at completed_at)
end
def default_sort_param
<<~SQL
"overdue" DESC NULLS LAST,
"activities"."completed_at" DESC,
"activities"."start_at" ASC NULLS LAST
SQL
end
def permitted_filters
@permitted_filters ||= reversible_filters_including_filter_flags + [:account_list_id, :any_tags]
end
def reversible_filters
Task::Filterer::FILTERS_TO_DISPLAY.collect(&:underscore).collect(&:to_sym) +
Task::Filterer::FILTERS_TO_HIDE.collect(&:underscore).collect(&:to_sym)
end
def reversible_filters_including_filter_flags
reversible_filters.map do |reversible_filter|
[reversible_filter, "reverse_#{reversible_filter}".to_sym]
end.flatten
end
def excluded_filter_keys_from_casting_validation
[:date_range]
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/mail_chimp_accounts_controller.rb
|
<gh_stars>0
class Api::V2::AccountLists::MailChimpAccountsController < Api::V2Controller
def show
load_mail_chimp_account
authorize_mail_chimp_account
render_mail_chimp_account
end
def create
persist_mail_chimp_account
end
def destroy
load_mail_chimp_account
authorize_mail_chimp_account
destroy_mail_chimp_account
end
def sync
load_mail_chimp_account
authorize_mail_chimp_account
MailChimp::PrimaryListSyncWorker.perform_async(@mail_chimp_account.id)
render_200
end
private
def destroy_mail_chimp_account
@mail_chimp_account.destroy
head :no_content
end
def load_mail_chimp_account
@mail_chimp_account ||= mail_chimp_account_scope
raise ActiveRecord::RecordNotFound unless @mail_chimp_account
end
def render_mail_chimp_account
render json: @mail_chimp_account,
status: success_status,
include: include_params,
fields: field_params
end
def persist_mail_chimp_account
build_mail_chimp_account
authorize_mail_chimp_account
if save_mail_chimp_account
MailChimp::PrimaryListSyncWorker.perform_async(@mail_chimp_account.id) if @mail_chimp_account.primary_list_id
render_mail_chimp_account
else
render_with_resource_errors(@mail_chimp_account)
end
end
def build_mail_chimp_account
@mail_chimp_account = load_account_list.build_mail_chimp_account(auto_log_campaigns: true)
@mail_chimp_account.assign_attributes(mail_chimp_account_params)
authorize_mail_chimp_account
end
def save_mail_chimp_account
@mail_chimp_account.save(context: persistence_context)
end
def authorize_mail_chimp_account
authorize @mail_chimp_account
end
def mail_chimp_account_params
params
.require(:mail_chimp_account)
.permit(MailChimpAccount::PERMITTED_ATTRIBUTES)
end
def mail_chimp_account_scope
load_account_list.mail_chimp_account
end
def load_account_list
@account_list ||= AccountList.find(params[:account_list_id])
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_likely_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Task::Filter::ContactLikely 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, likely_to_give: 'Least Likely') }
let!(:contact_two) { create(:contact, account_list_id: account_list.id, likely_to_give: 'Likely') }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, likely_to_give: 'Most Likely') }
let!(:contact_four) { create(:contact, account_list_id: account_list.id, likely_to_give: nil) }
let!(:task_one) { create(:task, account_list: account_list, contacts: [contact_one]) }
let!(:task_two) { create(:task, account_list: account_list, contacts: [contact_two]) }
let!(:task_three) { create(:task, account_list: account_list, contacts: [contact_three]) }
let!(:task_four) { create(:task, account_list: account_list, contacts: [contact_four]) }
describe '#query' do
let(:tasks) { account_list.tasks }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, account_list)).to eq(nil)
expect(described_class.query(tasks, { referrer: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { referrer: [] }, account_list)).to eq(nil)
end
end
context 'filter by no likely to give' do
it 'returns only tasks with contacts that have no likely to give' do
expect(described_class.query(tasks, { contact_likely: 'none' }, account_list).to_a).to eq [task_four]
end
end
context 'filter by likely to give' do
it 'filters multiple likely to give' do
result = described_class.query(tasks, { contact_likely: 'Least Likely, Likely' }, account_list).to_a
expect(result).to match_array [task_one, task_two]
end
it 'filters a single likely to give' do
expect(described_class.query(tasks, { contact_likely: 'Most Likely' }, account_list).to_a).to eq [task_three]
end
end
context 'multiple filters' do
it 'returns contacts matching multiple filters' do
result = described_class.query(tasks, { contact_likely: 'none, Most Likely, Likely' }, account_list).to_a
expect(result).to match_array [task_two, task_three, task_four]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/pledge_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Pledge, type: :model do
subject! { create(:pledge) }
let(:appeal) { create(:appeal) }
it { is_expected.to belong_to(:account_list) }
it { is_expected.to belong_to(:appeal) }
it { is_expected.to belong_to(:contact) }
it { is_expected.to have_many(:pledge_donations).dependent(:destroy) }
it { is_expected.to have_many(:donations).through(:pledge_donations) }
it { is_expected.to validate_presence_of(:account_list) }
it { is_expected.to validate_presence_of(:amount) }
it { is_expected.to validate_presence_of(:contact) }
it { is_expected.to validate_presence_of(:expected_date) }
it 'sets PERMITTED_ATTRIBUTES' do
expect(described_class::PERMITTED_ATTRIBUTES).to eq(
[
:amount,
:amount_currency,
:appeal_id,
:created_at,
:contact_id,
:donation_id,
:expected_date,
:overwrite,
:status,
:updated_at,
:updated_in_db_at,
:id
]
)
end
context '#appeal' do
let(:contact) { create(:contact) }
it 'restricted to a single entry per contact per appeal' do
create(:pledge, appeal: appeal, contact: contact)
expect { subject.update!(appeal: appeal, contact: contact) }.to \
raise_error ActiveRecord::RecordInvalid
end
end
context '#merge' do
let!(:loser_pledge) { create(:pledge, appeal: appeal) }
it 'moves donations' do
subject.update(appeal: appeal)
subject.donations << create(:donation)
loser_pledge.donations << create(:donation)
expect { subject.merge(loser_pledge) }.to change { subject.donations.count }.from(1).to(2)
end
it "won't merge if appeals don't match" do
expect { subject.merge(loser_pledge) }.to change(Pledge, :count).by(0)
subject.update(appeal: appeal)
expect { subject.merge(loser_pledge) }.to change(Pledge, :count).by(-1)
end
it 'combines pledge amount if loser has higher amount' do
subject.update(appeal: appeal)
loser_pledge.update(amount: 100)
expect { subject.merge(loser_pledge) }.to change { subject.reload.amount }
end
it "doesn't move attributes if loser has lower amount" do
subject.update(appeal: appeal)
loser_pledge.update(amount: 5)
expect { subject.merge(loser_pledge) }.to_not change { subject.reload.amount }
end
end
end
|
chuckmersereau/api_practice
|
app/services/admin/account_dup_phones_fix.rb
|
<gh_stars>0
class Admin::AccountDupPhonesFix
def initialize(account_list)
@account_list = account_list
end
def fix
Person.where(id: person_ids_multi_phones).includes(:phone_numbers)
.find_each(&method(:clean_dup_person_phones))
end
private
def people_phone_counts
@account_list.people.joins(:phone_numbers).group('phone_numbers.person_id').count
end
def person_ids_multi_phones
people_phone_counts.select do |_person_id, num_phones|
num_phones > 1
end.keys
end
def clean_dup_person_phones(person)
Admin::DupPhonesFix.new(person).fix
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/people/websites_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::Contacts::People::WebsitesController, type: :controller do
let(:factory_type) { :website }
let!(:user) { create(:user_with_full_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:person) { create(:person) }
let!(:person2) { create(:person) }
let!(:websites) { create_list(:website, 2, person: person) }
let(:website) { websites.first }
let(:id) { website.id }
let(:resource) { website }
let(:parent_param) { { contact_id: contact.id, person_id: person.id } }
let(:unpermitted_attributes) { nil }
let(:correct_attributes) { attributes_for(:website, person: person2, website: 'http://www.example192.com') }
let(:incorrect_attributes) { attributes_for(:website, person: nil, url: nil) }
before do
contact.people << person
end
include_examples 'index_examples'
include_examples 'show_examples'
include_examples 'create_examples'
include_examples 'update_examples'
include_examples 'destroy_examples'
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/merges/bulk_controller.rb
|
class Api::V2::Contacts::Merges::BulkController < Api::V2Controller
skip_before_action :validate_and_transform_json_api_params
before_action :reject_if_in_batch_request
Merge = Struct.new(:winner, :loser)
def create
skip_authorization
load_contacts
build_merge_structs
process_and_render_merges do |merge|
merge_contacts(merge)
merge.winner
end
end
private
def contact_ids
params[:data].flat_map do |merge_params|
attributes = extract_merge_attributes(merge_params)
[attributes[:winner_id], attributes[:loser_id]]
end
end
def extract_merge_attributes(params)
params
.require(:data)
.require(:attributes)
.permit(merge_attributes)
end
def merge_attributes
[:winner_id, :loser_id]
end
def load_contacts
@contacts = contact_scope.where(id: contact_ids).tap(&:first!).to_a
end
def contact_scope
current_user.contacts
end
def build_merge_structs
@merges = params[:data].map do |merge_params|
attributes = extract_merge_attributes(merge_params)
build_merge_from_attributes(attributes)
end.compact
raise ActiveRecord::RecordNotFound unless @merges.any?
end
def build_merge_from_attributes(attributes)
winner = @contacts.find { |contact| contact.id == attributes[:winner_id] }
loser = @contacts.find { |contact| contact.id == attributes[:loser_id] }
return nil unless (winner && loser) && (winner.account_list_id == loser.account_list_id)
Merge.new(winner, loser)
end
def process_and_render_merges(&process)
winners = @merges.map(&process)
render json: BulkResourceSerializer.new(resources: winners),
include: include_params,
fields: field_params
end
def merge_contacts(merge)
merge.winner.merge(merge.loser)
end
def pundit_user
PunditContext.new(current_user)
end
end
|
chuckmersereau/api_practice
|
dev/util/user_data_move_util.rb
|
<filename>dev/util/user_data_move_util.rb<gh_stars>0
def move_user_data(from_user:, to_user:)
UserDataMover.new(from_user: from_user, to_user: to_user).move_data
end
class UserDataMover
def initialize(from_user:, to_user:)
@from_user = from_user
@to_user = to_user
end
def move_data
puts "Moving data for user #{from_user.id} into user #{to_user.id} ..."
move_imports
move_invites
move_google_accounts
move_org_accounts
move_designation_profiles
move_account_lists
orphan_empty_account_lists
puts "Moved data for user #{from_user.id} into user #{to_user.id}"
end
private
attr_reader :from_user, :to_user
def move_imports
from_user.imports.each do |import|
puts " Moving import #{import.id} from #{from_user.id} to #{to_user.id}"
import.update_column(:user_id, to_user.id)
end
end
def move_invites
AccountListInvite.where(invited_by_user: from_user).each do |invite|
puts " Moving invited_by #{invite.id} from #{from_user.id} to #{to_user.id}"
invite.update(invited_by_user: to_user)
end
AccountListInvite.where(accepted_by_user: from_user).each do |invite|
puts " Moving acceptd_by #{invite.id} from #{from_user.id} to #{to_user.id}"
invite.update(accepted_by_user: to_user)
end
AccountListInvite.where(cancelled_by_user: from_user).each do |invite|
puts " Moving canceled_by #{invite.id} from #{from_user.id} to #{to_user.id}"
invite.update(cancelled_by_user: to_user)
end
end
def move_google_accounts
from_user.google_accounts.each do |google_account|
next if google_account.email.in?(to_user.google_accounts.pluck(:email))
puts " Moving Google account #{google_account.id} from #{from_user.id} to #{to_user.id}"
google_account.update(person: to_user)
end
end
def move_org_accounts
from_user.organization_accounts.each do |org_account|
next if org_account.organization_id.in?(to_user.organization_accounts.pluck(:organization_id))
puts " Moving org account #{org_account.id} from #{from_user.id} to #{to_user.id}"
org_account.update_column(:person_id, to_user.id)
end
end
def move_designation_profiles
from_user.designation_profiles.each do |dp|
next if dp.in?(to_user.designation_profiles)
puts " Adding designation profile #{dp.id} to #{to_user.id}"
to_user.designation_profiles << dp
end
end
def move_account_lists
from_user.account_lists.each do |account_list|
next if account_list.contacts.empty?
next if account_list.in?(to_user.account_lists)
puts " Adding account #{account_list.id} to #{to_user.id}"
to_user.account_lists << account_list
end
end
def orphan_empty_account_lists
if to_user.account_lists.present?
to_user.account_lists.each do |account_list|
next if account_list.contacts.present?
puts " Orphaning empty account list #{account_list.id} for #{to_user.id}"
to_user.account_list_users.where(account_list: account_list).each(&:destroy)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/workers/background_batch/request_worker_spec.rb
|
require 'rails_helper'
RSpec.describe BackgroundBatch::RequestWorker do
let(:user) { create :user }
let(:background_batch_request) { create :background_batch_request }
subject { described_class.new }
before do
stub_request(:get, 'https://api.mpdx.org/api/v2/user')
.to_return(status: 200,
body: "{\"id\":\"#{user.id}\"}",
headers: { accept: 'application/json' })
end
describe '#perform' do
it 'should find background_batch_request' do
expect(BackgroundBatch::Request).to(
receive(:find).with(background_batch_request.id).and_return(background_batch_request)
)
subject.perform(background_batch_request.id)
end
end
describe '#load_response' do
before do
allow(BackgroundBatch::Request).to(
receive(:find_by!).with(id: background_batch_request.id).and_return(background_batch_request)
)
end
it 'should call RestClient::Request.execute' do
expect(RestClient::Request).to(
receive(:execute).with(
method: background_batch_request.request_method,
payload: background_batch_request.request_body,
url: background_batch_request.formatted_path,
headers: background_batch_request.formatted_request_headers,
timeout: nil
).and_call_original
)
subject.perform(background_batch_request.id)
end
it 'should call update_request' do
allow(RestClient::Request).to(
receive(:execute).with(
method: background_batch_request.request_method,
payload: background_batch_request.request_body,
url: background_batch_request.formatted_path,
headers: background_batch_request.formatted_request_headers,
timeout: nil
).and_call_original
)
expect(subject).to receive(:update_request).and_call_original
subject.perform(background_batch_request.id)
end
end
describe '#request_params' do
it 'should return request_params for RestClient::Request.execute' do
subject.perform(background_batch_request.id)
expect(subject.send(:request_params)).to eq(
method: background_batch_request.request_method,
payload: background_batch_request.request_body,
url: background_batch_request.formatted_path,
headers: background_batch_request.formatted_request_headers,
timeout: nil
)
end
end
describe '#update_request' do
it 'should call background_batch_request.update' do
allow(BackgroundBatch::Request).to(
receive(:find).with(background_batch_request.id).and_return(background_batch_request)
)
expect(background_batch_request).to receive(:update).with(
response_body: "{\"id\":\"#{user.id}\"}",
response_headers: { accept: 'application/json' },
response_status: 200,
status: 'complete'
).and_call_original
subject.perform(background_batch_request.id)
end
end
end
|
chuckmersereau/api_practice
|
engines/auth/app/controllers/auth/provider/google_accounts_controller.rb
|
<gh_stars>0
module Auth
module Provider
class GoogleAccountsController < BaseController
protected
def find_or_create_account
@google_account ||= Person::GoogleAccount.find_or_create_from_auth(auth_hash, current_user)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/city_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::City do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:contact_three) { create(:contact, account_list_id: account_list.id) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id) }
let!(:contact_five) { create(:contact, account_list_id: account_list.id) }
let!(:address_one) { create(:address) }
let!(:address_two) { create(:address) }
let!(:address_three) { create(:address, city: nil) }
let!(:address_four) { create(:address, city: nil) }
let!(:address_five) { create(:address, historic: true) }
before do
contact_one.addresses << address_one
contact_two.addresses << address_two
contact_three.addresses << address_three
contact_four.addresses << address_four
contact_five.addresses << address_five
end
describe '#config' do
it 'returns expected config' do
options = [
{ name: '-- Any --', id: '', placeholder: 'None' },
{ name: '-- None --', id: 'none' },
{ name: 'Fremont', id: 'Fremont' }
]
expect(described_class.config([account_list])).to include(multiple: true,
name: :city,
options: options,
parent: 'Contact Location',
title: 'City',
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, { city: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { city: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { city: '' }, nil)).to eq(nil)
end
end
context 'filter by no city' do
it 'returns only contacts that have no city' do
result = described_class.query(contacts, { city: 'none' }, nil).to_a
expect(result).to include(contact_three, contact_four)
end
end
context 'filter by city' do
it 'filters multiple cities' do
result = described_class.query(contacts, { city: 'Fremont, Fremont' }, nil).to_a
expect(result).to include(contact_one, contact_two)
end
it 'filters a single cities' do
result = described_class.query(contacts, { city: 'Fremont' }, nil).to_a
expect(result).to include(contact_one, contact_two)
end
end
context 'multiple filters' do
it 'returns contacts matching multiple filters' do
result = described_class.query(contacts, { city: 'Fremont, none' }, nil).to_a
expect(result).to include(contact_one, contact_two, contact_three, contact_four)
end
end
context 'address historic' do
it 'returns contacts matching the city with historic addresses' do
result = described_class.query(contacts, { city: 'Fremont', address_historic: 'true' }, nil).to_a
expect(result).to include(contact_five)
end
end
end
end
|
chuckmersereau/api_practice
|
app/exhibits/phone_number_exhibit.rb
|
class PhoneNumberExhibit < DisplayCase::Exhibit
def self.applicable_to?(object)
object.class.name == 'PhoneNumber'
end
def to_s
location.present? ? [number, location].join(' - ') : number
end
def number
return unless self[:number]
phone = Phonelib.parse(self[:number])
phone_num =
if country_code == '1' || phone.country_code == '1' || (country_code.blank? &&
(self[:number].length == 10 || self[:number].length == 7))
phone.local_number
else
phone.e164
end
if phone.extension.blank?
phone_num
else
format(_('%{number} ext %{extension}'), number: phone_num, extension: phone.extension)
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120202171236_create_master_people.rb
|
class CreateMasterPeople < ActiveRecord::Migration
def change
create_table :master_people do |t|
t.timestamps null: false
end
add_column :people, :master_person_id, :integer, :null => false
add_index :people, :master_person_id
end
end
|
chuckmersereau/api_practice
|
db/migrate/20141203174739_add_envelope_greeting_to_contact.rb
|
class AddEnvelopeGreetingToContact < ActiveRecord::Migration
def change
add_column :contacts, :envelope_greeting, :string
end
end
|
chuckmersereau/api_practice
|
spec/workers/organization_from_query_url_worker_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe OrganizationFromQueryUrlWorker do
let(:name) { 'CCCNZ' }
let(:query_ini_url) { 'https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx' }
let(:organization) { Organization.first || create(:organization) }
let(:ini_body) { File.open(Rails.root.join('spec', 'fixtures', 'sample_query.ini')).read }
let(:ini) { IniParse.parse(ini_body) }
before do
stub_request(:get, query_ini_url)
.to_return(
body: ini_body
)
end
it 'has the correct sections' do
expect(described_class::SECTIONS.keys).to eq(
%w(ACCOUNT_BALANCE DONATIONS ADDRESSES ADDRESSES_BY_PERSONIDS PROFILES
OAuth_GetChallengeStartNum OAuth_ConvertToToken OAuth_GetTokenInfo)
)
end
describe '#perform' do
let(:perform) { described_class.new.perform(name, query_ini_url) }
it 'creates an organization' do
expect { perform }.to change { Organization.count }.from(0).to(1)
end
describe 'attributes' do
before { perform }
it 'sets the correct organization_attributes' do
expect(organization.name).to eq name
expect(organization.query_ini_url).to eq query_ini_url
expect(organization.redirect_query_ini).to eq ini['ORGANIZATION']['RedirectQueryIni']
expect(organization.abbreviation).to eq ini['ORGANIZATION']['Abbreviation']
expect(organization.logo).to eq ini['ORGANIZATION']['WebLogo-JPEG-470x120']
expect(organization.account_help_url).to eq ini['ORGANIZATION']['AccountHelpUrl']
expect(organization.minimum_gift_date).to eq ini['ORGANIZATION']['MinimumWebGiftDate']
expect(organization.code).to eq ini['ORGANIZATION']['Code']
expect(organization.query_authentication).to eq ini['ORGANIZATION']['QueryAuthentication'].to_i == 1
expect(organization.org_help_email).to eq ini['ORGANIZATION']['OrgHelpEmail']
expect(organization.org_help_url).to eq ini['ORGANIZATION']['OrgHelpUrl']
expect(organization.org_help_url_description).to eq ini['ORGANIZATION']['OrgHelpUrlDescription']
expect(organization.org_help_other).to eq ini['ORGANIZATION']['OrgHelpOther']
expect(organization.request_profile_url).to eq ini['ORGANIZATION']['RequestProfileUrl']
expect(organization.staff_portal_url).to eq ini['ORGANIZATION']['StaffPortalUrl']
expect(organization.default_currency_code).to eq ini['ORGANIZATION']['DefaultCurrencyCode']
expect(organization.allow_passive_auth).to eq ini['ORGANIZATION']['AllowPassiveAuth'] == 'True'
expect(organization.oauth_url).to eq ini['ORGANIZATION']['OAuthUrl']
end
described_class::SECTIONS.each do |key, section|
it "sets the correct #{section}_attributes" do
expect(organization.send("#{section}_url")).to eq ini[key]['Url']
expect(organization.send("#{section}_params")).to eq ini[key]['Post'] unless key == 'DONATIONS'
expect(organization.send("#{section}_oauth")).to eq ini[key]['OAuth']
end
end
it 'sets the correct donation_params' do
expect(organization.donations_params).to eq ini['DONATIONS.3.4']['Post']
end
end
context 'organization name already exists' do
before { create(:organization, name: name, query_ini_url: 'random', minimum_gift_date: Date.yesterday) }
it 'does not create an organization' do
expect { perform }.to_not change { Organization.count }
end
it 'updates query_ini_url' do
perform
expect(organization.query_ini_url).to eq query_ini_url
end
it 'does not change minimum_gift_date' do
perform
expect(organization.minimum_gift_date).to_not eq ini['ORGANIZATION']['MinimumWebGiftDate']
end
end
context 'organization query_ini_url already exists' do
before { create(:organization, query_ini_url: query_ini_url, name: 'random') }
it 'does not create an organization' do
expect { perform }.to_not change { Organization.count }
end
it 'updates name' do
perform
expect(organization.name).to eq name
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/donation_reports/received_donations_spec.rb
|
require 'rails_helper'
describe DonationReports::ReceivedDonations do
let(:all_scoper) { -> (donations) { donations } }
let(:account_list) { create(:account_list) }
let(:designation_account) { create(:designation_account) }
let(:donor_account) { create(:donor_account) }
let(:contact) { create(:contact, account_list: account_list) }
let(:received_donations) { DonationReports::ReceivedDonations.new(account_list: account_list, donations_scoper: all_scoper) }
before do
account_list.designation_accounts << designation_account
contact.donor_accounts << donor_account
end
describe '#donations' do
it 'includes received donations info' do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
amount: 2, currency: 'EUR',
donation_date: Date.current)
donations_info = received_donations.donations
expect(donations_info.size).to eq 1
expect(donations_info.first.likelihood_type).to eq 'received'
expect(donations_info.first.contact_id).to eq contact.id
expect(donations_info.first.amount).to eq 2
expect(donations_info.first.currency).to eq 'EUR'
end
it 'falls back to currency and amount when tendered currency/amount nil' do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
tendered_amount: nil, tendered_currency: nil,
amount: 3, currency: 'GBP',
donation_date: Date.current)
donations_info = received_donations.donations
expect(donations_info.first.currency).to eq 'GBP'
expect(donations_info.first.amount).to eq 3
end
end
describe '#donors' do
it 'includes donor info' do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
tendered_amount: 2, tendered_currency: 'EUR',
donation_date: Date.current)
donors_info = received_donations.donors
expect(donors_info.size).to eq 1
expect(donors_info.first.contact_name).to eq contact.name
end
end
context 'scoped to EUR' do
let(:all_scoper) { -> (donations) { donations.where(currency: 'EUR') } }
it 'excludes donations according to the given scoper' do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
tendered_amount: nil, tendered_currency: nil,
amount: 3, currency: 'GBP',
donation_date: Date.current)
donations_info = received_donations.donations
donors_info = received_donations.donors
expect(donations_info).to be_empty
expect(donors_info).to be_empty
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/reports/salary_currency_donations_serializer.rb
|
class Reports::SalaryCurrencyDonationsSerializer < Reports::DonorCurrencyDonationsSerializer
end
|
chuckmersereau/api_practice
|
config/initializers/datadog_trace.rb
|
<filename>config/initializers/datadog_trace.rb
Datadog.configure do |c|
# Tracer
c.tracer hostname: ENV['DATADOG_HOST'],
port: ENV['DATADOG_PORT'],
tags: { app: ENV['PROJECT_NAME'] },
debug: false,
enabled: (ENV['DATADOG_TRACE'].to_s == 'true'),
env: Rails.env
# Rails
c.use :rails,
service_name: ENV['PROJECT_NAME'],
controller_service: "#{ENV['PROJECT_NAME']}-controller",
cache_service: "#{ENV['PROJECT_NAME']}-cache",
database_service: "#{ENV['PROJECT_NAME']}-db"
# Redis
c.use :redis, service_name: "#{ENV['PROJECT_NAME']}-redis"
# Sidekiq
c.use :sidekiq, service_name: "#{ENV['PROJECT_NAME']}-sidekiq"
# Net::HTTP
c.use :http, service_name: "#{ENV['PROJECT_NAME']}-http"
end
# skipping the health check: if it returns true, the trace is dropped
Datadog::Pipeline.before_flush(Datadog::Pipeline::SpanFilter.new do |span|
span.name == 'rack.request' && span.get_tag('http.url') == '/monitors/lb'
end)
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/reports/sessions_controller_spec.rb
|
<filename>spec/controllers/api/v2/reports/sessions_controller_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe Api::V2::Reports::SessionsController, type: :controller do
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/coaches_controller_spec.rb
|
<filename>spec/controllers/api/v2/account_lists/coaches_controller_spec.rb<gh_stars>0
require 'rails_helper'
describe Api::V2::AccountLists::CoachesController, type: :controller do
let(:resource_type) { 'users' }
let(:factory_type) { :user }
let!(:user) { create(:user_with_account) }
let!(:coaches) { create_list(:user_coach, 2) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:coach2) { coaches.last }
let(:id) { coach2.id }
let(:original_user_id) { user.id }
before do
account_list.coaches += coaches
account_list.coaches << user.becomes(User::Coach)
end
let(:resource) { coach2 }
let(:parent_param) { { account_list_id: account_list_id } }
let(:correct_attributes) { attributes_for(:user) }
include_examples 'index_examples', except: [:includes, :sparse_fieldsets]
include_examples 'show_examples', except: [:includes, :sparse_fieldsets]
context 'authorized user' do
before do
api_login(user)
end
describe '#destroy' do
it 'deletes an user' do
delete :destroy, account_list_id: account_list_id, id: id
expect(response.status).to eq 204
end
it 'does delete self' do
delete :destroy, account_list_id: account_list_id, id: original_user_id
expect(response.status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
app/validators/csv_import_mappings_validator.rb
|
# This validator makes sure that the client has provided accurate and sufficient mappings for their CSV import.
# The mapping validation is intentionally aggressive to help prevent any possible issues during the import.
class CsvImportMappingsValidator < ActiveModel::Validator
def validate(import)
self.import = import
self.csv_import = CsvImport.new(import)
return if (import.errors.keys & [:file_constants_mappings, :file_headers_mappings]).present?
self.file_constants_mappings = CsvValueToConstantMappings.new(import.file_constants_mappings)
file_headers_mappings_contains_required_headers
file_headers_mappings_contains_only_supported_headers
file_headers_mappings_only_maps_to_headers_in_the_file
return if import.errors.keys.include?(:file_headers_mappings)
file_constants_mappings_contains_the_constants_needed_for_import
file_constants_mappings_only_maps_constants_that_are_supported
file_constants_mappings_only_maps_constants_that_are_also_in_file_headers_mappings
return if import.errors.keys.include?(:file_constants_mappings)
file_constants_mappings_only_maps_constants_to_values_found_in_the_csv
file_constants_mappings_maps_all_constants_values_found_in_the_csv
end
private
attr_accessor :import, :csv_import, :file_constants_mappings
def file_headers_mappings_contains_required_headers
return if CsvImport.required_headers.keys.blank?
return unless (CsvImport.required_headers.keys.map(&:to_s) & import.file_headers_mappings.keys).empty?
import.errors[:file_headers_mappings] << 'should specify a header mapping for at least one of '\
'the required headers. The required headers are: '\
"#{CsvImport.required_headers.keys}"
end
def file_headers_mappings_contains_only_supported_headers
supported_keys = import.file_headers_mappings.keys & CsvImport.supported_headers.keys.map(&:to_s)
return if supported_keys == import.file_headers_mappings.keys
unsupported_keys = import.file_headers_mappings.keys - CsvImport.supported_headers.keys.map(&:to_s)
import.errors[:file_headers_mappings] << 'has unsupported headers. One or more of the headers '\
'specified in file_headers_mappings is not supported, '\
'please refer to the constants endpoints for a list of '\
'supported headers. The unsupported headers you specifed '\
"are #{unsupported_keys}"
end
def file_headers_mappings_only_maps_to_headers_in_the_file
matches = import.file_headers_mappings.values & import.file_headers.keys
return if matches == import.file_headers_mappings.values.uniq
invalid_headers = import.file_headers_mappings.values - import.file_headers.keys
import.errors[:file_headers_mappings] << 'has unsupported mappings. One or more of the header '\
'mappings was not found in the headers of the given CSV '\
'file, refer to attribute "file_headers" for a list of '\
'headers extracted from the given file. '\
"The invalid headers are: #{invalid_headers}"
end
def file_constants_mappings_contains_the_constants_needed_for_import
constants_needing_to_be_imported = (CsvImport.constants.keys.map(&:to_s) & import.file_headers_mappings.keys)
matches = constants_needing_to_be_imported & file_constants_mappings.constant_names
return if matches == constants_needing_to_be_imported
missing_constant_mappings = constants_needing_to_be_imported - file_constants_mappings.constant_names
import.errors[:file_constants_mappings] << 'is missing mappings. One or more of the header '\
'constants specified in file_headers_mappings ' \
'does not have a mapping specified in file_constants_mappings. ' \
"The missing constant mappings are: #{missing_constant_mappings}"
end
def file_constants_mappings_only_maps_constants_that_are_supported
file_constants_mappings.constant_names.each do |header_id|
unless CsvImport.supported_headers.keys.map(&:to_s).include?(header_id)
import.errors[:file_constants_mappings] << 'has an invalid mapping. You cannot map to the '\
"constant \"#{header_id}\" because it's not a "\
'supported MPDX constant.'
next
end
unsupported_constants = file_constants_mappings.find_unsupported_constants(header_id)
next if unsupported_constants.blank?
import.errors[:file_constants_mappings] << 'has an invalid mapping. For the header '\
"\"#{header_id}\", you cannot map to the "\
"constants: #{unsupported_constants}"
end
end
def file_constants_mappings_only_maps_constants_that_are_also_in_file_headers_mappings
matches = file_constants_mappings.constant_names & import.file_headers_mappings.keys
return if matches == file_constants_mappings.constant_names
invalid_mapping_keys = file_constants_mappings.constant_names - import.file_headers_mappings.keys
import.errors[:file_constants_mappings] << 'has an invalid mapping. You cannot map to the '\
"constants #{invalid_mapping_keys} because they are "\
'not found in file_headers_mappings'
end
def file_constants_mappings_only_maps_constants_to_values_found_in_the_csv
file_constants_mappings.constant_names.each do |header_id|
mapping_values = file_constants_mappings.find_mapped_values(header_id)
file_constants = csv_import.file_constants_for_mpdx_header(header_id)
next if (mapping_values & file_constants) == mapping_values.uniq
invalid_mapping_values = mapping_values - file_constants
import.errors[:file_constants_mappings] << 'has an invalid mapping. For the header '\
"\"#{header_id}\", we couldn't find the following "\
"values in the CSV: #{invalid_mapping_values}"
end
end
def file_constants_mappings_maps_all_constants_values_found_in_the_csv
constants_needing_to_be_imported = (CsvImport.constants.keys.map(&:to_s) & import.file_headers_mappings.keys)
constants_needing_to_be_imported.each do |constant_header|
mapped_constants = file_constants_mappings.find_mapped_values(constant_header)
file_constants = csv_import.file_constants_for_mpdx_header(constant_header)
next if (file_constants & mapped_constants) == file_constants
missing_mappings = file_constants - mapped_constants
import.errors[:file_constants_mappings] << 'is missing mappings. For the header '\
"\"#{constant_header}\", we couldn't find the "\
"following mappings to the CSV values: #{missing_mappings}"
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/auth/provider/donorhub_accounts_controller_spec.rb
|
<filename>spec/controllers/auth/provider/donorhub_accounts_controller_spec.rb
require 'rails_helper'
describe Auth::Provider::DonorhubAccountsController, :auth, type: :controller do
routes { Auth::Engine.routes }
let(:user) { create(:user_with_account) }
let(:oauth_url) { 'https://www.mytntware.com/dataserver/toontown/staffportal/oauth/authorize.aspx' }
before(:each) do
auth_login(user)
request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:donorhub]
end
it 'should find or create a Organization Account' do
expect(Person::OrganizationAccount)
.to receive(:find_or_create_from_auth)
.with(OmniAuth.config.mock_auth[:donorhub][:credentials][:token], oauth_url, user)
get :create, oauth_url: oauth_url
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/fields.rb
|
<reponame>chuckmersereau/api_practice
module Fields
private
def field_params
return {} unless params[:fields]
params[:fields].transform_values do |field_value|
field_value.split(',')
end
end
end
|
chuckmersereau/api_practice
|
app/services/expected_totals_report/received_donations.rb
|
<reponame>chuckmersereau/api_practice
class ExpectedTotalsReport::ReceivedDonations
attr_reader :account_list, :filter_params
def initialize(account_list:, filter_params: nil)
@account_list = account_list
@filter_params = filter_params
end
def donation_rows
donations_this_month.map do |donation|
{
type: 'received',
contact: contacts_by_donor_id[donation.donor_account_id],
donation_amount: donation.tendered_amount || donation.amount,
donation_currency: donation.tendered_currency || donation.currency ||
account_list.default_currency
}
end
end
protected
def donations_scope(donations = account_list.donations)
return donations unless filter_params
if filter_params[:designation_account_id]
donations = donations.where(designation_account_id: filter_params[:designation_account_id])
end
if filter_params[:donor_account_id]
donations = donations.where(donor_account_id: filter_params[:donor_account_id])
end
donations
end
private
def donations_this_month
@donations_this_month ||= donations_scope.where('donation_date >= ?', Date.current.beginning_of_month)
end
def contacts_by_donor_id
@contacts_by_donor_id ||= group_contacts_by_donor_id
end
def group_contacts_by_donor_id
donor_contacts.each_with_object({}) do |contact, contacts_by_donor_id|
contact.donor_accounts.each do |donor_account|
contacts_by_donor_id[donor_account.id] ||= contact
end
end
end
def donor_contacts
account_list
.contacts
.joins(:contact_donor_accounts)
.includes(:contact_donor_accounts)
.where(contact_donor_accounts: { donor_account_id: donor_ids })
.order('contacts.id')
end
def donor_ids
donations_this_month.pluck(:donor_account_id)
end
end
|
chuckmersereau/api_practice
|
spec/lib/json_api_service/relationships_object_spec.rb
|
require 'spec_helper'
require 'json_api_service/object_store'
require 'json_api_service/relationships_object'
module JsonApiService
RSpec.describe RelationshipsObject do
describe '#initialize' do
it 'initializes with relationships data and a store' do
data = build_data
store = build_store
object = build_object(data: data, store: store)
expect(object.data).to eq data
expect(object.store).to eq store
end
end
describe '#relationships' do
it 'returns the relationships' do
object = build_object
relationships = object.relationships
expect(relationships[:account_list]).to be_kind_of DataObject
expect(relationships[:addresses]).to be_kind_of DataObjectCollection
expect(relationships[:emails]).to be_kind_of NullDataObject
end
end
private
def build_object(data: build_data, store: build_store)
RelationshipsObject.new(data, store: store)
end
def build_data
{
account_list: {
data: {
type: 'account_lists',
id: 'abc123-abc123-abc123-abc123'
}
},
addresses: {
data: [
{
type: 'addresses',
id: 'def456-def456-def456-def456'
},
{
type: 'addresses',
id: 'ghi456-ghi456-ghi456-ghi456'
}
]
},
emails: {
data: nil
}
}
end
def build_store
ObjectStore.new
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/reportable.rb
|
<reponame>chuckmersereau/api_practice
module Reportable
extend ActiveSupport::Concern
def report_params
report_params = { filter_params: filter_params.except(:account_list_id) }
report_params[:account_list] = load_account_list if load_account_list
report_params[:filter_params][:month_range] = filter_date_range
report_params
end
def filter_date_range
return nil if params.fetch(:filter, {})[:month_range].blank?
::Range.new(*params.fetch(:filter, {})[:month_range].split('...').map(&:to_date))
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, :designation_account_id, :donor_account_id]
end
def authorize_report
authorize(load_account_list, :show?)
end
end
|
chuckmersereau/api_practice
|
spec/factories/users.rb
|
<gh_stars>0
require 'faker'
FactoryBot.define do
factory :user do
association :master_person
first_name { Faker::Name.first_name }
preferences do
{
time_zone: Time.zone.name
}
end
end
factory :user_with_account, parent: :user do
sequence(:access_token) { |n| "243857230498572349898798#{n}" }
after :create do |u|
create(:organization_account, person: u)
account_list = u.reload.account_lists.order(:created_at).first
create(:key_account, person: u)
create(:designation_profile, user: u, account_list: account_list)
end
end
factory :user_with_full_account, parent: :user do
sequence(:email) { |n| "#{n}#{Faker::Internet.email}" }
sequence(:access_token) { |n| "1234567890#{n}" }
time_zone { 'Auckland' }
locale { 'en' }
after :create do |u|
create(:organization_account, person: u)
account_list = u.reload.account_lists.order(:created_at).first
create(:key_account, person: u)
create(:designation_profile, user: u, account_list: account_list)
end
end
factory :admin_user, parent: :user_with_account do
admin true
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_info_email_spec.rb
|
<filename>spec/services/task/filter/contact_info_email_spec.rb
require 'rails_helper'
RSpec.describe Task::Filter::ContactInfoEmail 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!(:task_one) { create(:task, account_list: account_list, contacts: [contact_one]) }
let!(:task_two) { create(:task, account_list: account_list, contacts: [contact_two]) }
let!(:person_one) { create(:person) }
let!(:person_two) { create(:person) }
let!(:email_address_one) { create(:email_address) }
before do
contact_one.people << person_one
contact_two.people << person_two
person_one.email_addresses << email_address_one
end
describe '#query' do
let(:tasks) { Task.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_info_email: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_info_email: [] }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_info_email: '' }, account_list)).to eq(nil)
end
end
context 'filter by no address' do
it 'returns only contacts that have no address' do
expect(described_class.query(tasks, { contact_info_email: 'No' }, account_list).to_a).to eq [task_two]
end
end
context 'filter by address' do
it 'returns only contacts that have a address' do
expect(described_class.query(tasks, { contact_info_email: 'Yes' }, account_list).to_a).to eq [task_one]
end
end
end
end
|
chuckmersereau/api_practice
|
app/concerns/person/account.rb
|
module Person::Account
extend ActiveSupport::Concern
included do
belongs_to :person
belongs_to :user, foreign_key: :person_id
scope :authenticated, -> { where(authenticated: true) }
end
module ClassMethods
def find_or_create_from_auth(_auth_hash, _person)
message = <<~HEREDOC
`.find_or_create_from_auth` must be defined on #{self} instead of through inheritance from Person::Account.
In order to work correctly, it must also pass:
- The person object
- A hash of attributes for the account
- A relation scope in which to look for and create the account, ie: `person.key_accounts`
to `.find_or_create_person_account` in order to return the created account.
Example:
def self.find_or_create_from_auth(auth_hash, person)
# ...
# pull needed arguments from auth_hash and person
# ...
find_or_create_person_account(
person: person,
attributes: attributes,
relation_scope: relation_scope
)
end
HEREDOC
raise NotImplementedError, message
end
def find_related_account(rel, attributes)
rel.authenticated.find_by(remote_id: attributes[:remote_id])
end
def create_user_from_auth(attributes)
attributes ||= {}
User.create!(attributes)
end
def find_authenticated_user(auth_hash)
User.find_by(id: authenticated.where(remote_id: auth_hash.uid).order(:created_at).pluck(:person_id).first)
end
def one_per_user?
true
end
def queue
:import
end
private
def find_or_create_person_account(person:, attributes:, relation_scope:)
attributes[:authenticated] = true
remote_id = attributes[:remote_id]
account = find_related_account(relation_scope, attributes)
other_account = find_by(remote_id: remote_id, authenticated: true)
if account
account.update_attributes(attributes)
elsif other_account
# if creating this authentication record is a duplicate, we have a duplicate person to merge
other_account.update_attributes(person_id: person.id)
account = other_account
else
account = relation_scope.create!(attributes)
end
person.first_name = attributes[:first_name] if person.first_name.blank?
person.last_name = attributes[:last_name] if person.last_name.blank?
person.email = attributes[:email] if person.email.blank?
# start a data import in the background
account.queue_import_data if account.respond_to?(:queue_import_data)
account
end
end
class NoSessionError < StandardError
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/donations_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Donations' do
include_context :json_headers
documentation_scope = :account_lists_api_donations
let(:resource_type) { 'donations' }
let!(:user) { create(:user_with_full_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:donor_account) { create(:donor_account) }
let!(:designation_account) { create(:designation_account) }
let!(:donations) do
create_list(:donation, 2, donor_account: donor_account,
designation_account: designation_account, amount: 10.00)
end
let(:donation) { donations.first }
let(:id) { donation.id }
let(:new_donation) do
attributes_for(:donation, amount: 10.00)
.reject { |attr| attr.to_s.end_with?('_id') }
.merge(updated_in_db_at: donation.updated_at)
end
let(:relationships) do
{
donor_account: {
data: {
type: 'donor_accounts',
id: donor_account.id
}
},
designation_account: {
data: {
type: 'designation_accounts',
id: designation_account.id
}
}
}
end
let(:form_data) { build_data(new_donation, relationships: relationships) }
let(:expected_attribute_keys) do
%w(
amount
appeal_amount
channel
converted_currency
converted_amount
converted_appeal_amount
created_at
currency
donation_date
memo
motivation
payment_method
payment_type
remote_id
tendered_amount
tendered_currency
updated_at
updated_in_db_at
)
end
let(:resource_associations) do
%w(
appeal
contact
designation_account
donor_account
pledge
)
end
before do
account_list.designation_accounts << designation_account
contact.donor_accounts << donor_account
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/account_lists/:account_list_id/donations' do
parameter 'account_list_id',
'Account List ID',
'Type' => 'String',
required: true
parameter 'filter[donor_account_id]',
'List of Donor Account Ids',
'Type' => 'Array[String]'
parameter 'filter[designation_account_id]',
'List of Designation Account Ids',
'Type' => 'Array[String]'
parameter 'filter[donation_date]',
'A donation date range with text value like "YYYY-MM-DD...YYYY-MM-DD" ',
'Type' => 'String'
response_field 'data',
'Data',
'Type' => 'Array[Object]'
example 'Donation [LIST]', document: documentation_scope do
explanation 'List of Donations associated with the the Account List'
do_request
check_collection_resource(2, ['relationships'])
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 200
end
end
get '/api/v2/account_lists/:account_list_id/donations/:id' do
with_options scope: [:data, :attributes] do
response_field 'amount', 'Amount', type: 'Number'
response_field 'appeal_amount', 'Appeal Amount', type: 'Number'
response_field 'appeal_id', 'Appeal ID', type: 'Number'
response_field 'channel', 'Channel', type: 'String'
response_field 'created_at', 'Created At', type: 'String'
response_field 'converted_amount', 'Converted Amount', type: 'Number'
response_field 'converted_appeal_amount', 'Converted Appeal Amount', type: 'Number'
response_field 'converted_currency', 'Converted Currency', type: 'String'
response_field 'currency', 'Currency', type: 'String'
response_field 'designation_account_id', 'Designation Account ID', type: 'Number'
response_field 'donation_date', 'Donation Date', type: 'String'
response_field 'donor_account_id', 'Donor Account ID', type: 'Number'
response_field 'memo', 'Memo', type: 'String'
response_field 'motivation', 'Motivation', type: 'String'
response_field 'payment_method', 'Payment Method', type: 'String'
response_field 'payment_type', 'Payment Type', type: 'String'
response_field 'remote_id', 'Remote ID', type: 'Number'
response_field 'tendered_amount', 'Tendered Ammount', type: 'Number'
response_field 'tendered_currency', 'Tendered Currency', type: 'String'
response_field 'updated_at', 'Updated At', type: 'String'
response_field 'updated_in_db_at', 'Updated In Db At', type: 'String'
end
example 'Donation [GET]', document: documentation_scope do
explanation 'The Account List Donation with the given ID'
do_request
check_resource(['relationships'])
expect(resource_object.keys).to match_array expected_attribute_keys
expect(resource_object['amount']).to eq '10.0'
expect(response_status).to eq 200
end
end
post '/api/v2/account_lists/:account_list_id/donations' do
with_options scope: [:data, :attributes] do
parameter 'amount', 'Amount'
parameter 'appeal_amount', 'Appeal Amount'
parameter 'appeal_id', 'Appeal ID'
parameter 'contact_id', 'Contact ID'
parameter 'designation_account_id', 'Designation Account ID'
parameter 'donation_date', 'Donation Date'
parameter 'donor_account_id', 'Donor Account ID'
end
example 'Donation [CREATE]', document: documentation_scope do
explanation 'Creates a new Donation associated with the Account List'
do_request data: form_data
expect(resource_object['amount']).to eq '10.0'
expect(response_status).to eq 201
end
end
put '/api/v2/account_lists/:account_list_id/donations/:id' do
parameter 'id', 'ID of the donation', required: true
with_options scope: [:data, :attributes] do
parameter 'amount', 'Amount'
parameter 'appeal_amount', 'Appeal Amount'
parameter 'appeal_id', 'Appeal ID'
parameter 'contact_id', 'Contact ID'
parameter 'designation_account_id', 'Designation Account ID'
parameter 'donation_date', 'Donation Date'
parameter 'donor_account_id', 'Donor Account ID'
end
example 'Donation [UPDATE]', document: documentation_scope do
explanation 'Updates a Donation associated with the Account List'
do_request data: build_data(new_donation)
expect(resource_object['amount']).to eq '10.0'
expect(response_status).to eq 200
end
end
delete '/api/v2/account_lists/:account_list_id/donations/:id' do
parameter 'account_list_id', 'Account List ID', required: true
parameter 'id', 'ID', required: true
example 'Donation [DELETE]', document: documentation_scope do
explanation 'Deletes the Donation associated with the Account List'
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/notification_type/smaller_gift.rb
|
class NotificationType::SmallerGift < NotificationType
def check_contacts_filter(contacts)
contacts.financial_partners
end
def check_for_donation_to_notify(contact)
contact.last_donation if smaller_gift?(contact)
end
def smaller_gift?(contact)
return unless contact.pledge_frequency&.positive? && contact.pledge_amount
donations = contact.donations.reorder(donation_date: :asc)
return unless donations.any?
last_donation_date = donations.last&.donation_date
start_last_donation_period = last_donation_date - pledge_frequency_as_time(contact.pledge_frequency)
amount_given = donations.where(donation_date: start_last_donation_period..last_donation_date).sum(:amount)
amount_given < contact.pledge_amount && !NotificationType::RecontinuingGift.had_recontinuing_gift?(contact)
end
def task_activity_type
'To Do'
end
def task_description_template(notification = nil)
if notification&.account_list&.designation_accounts&.many?
_('%{contact_name} gave a gift of %{amount} on %{date} to %{designation}, '\
'which is different from their pledge. Research the gift.')
else
_('%{contact_name} gave a gift of %{amount} on %{date}, which is different from their pledge. Research the gift.')
end
end
private
def pledge_frequency_as_time(pledge_frequency)
{
0.23076923076923.to_d => 1.week,
0.46153846153846.to_d => 2.weeks,
1.0.to_d => 1.month,
2.0.to_d => 2.months,
3.0.to_d => 3.months,
4.0.to_d => 4.months,
6.0.to_d => 6.months,
12.0.to_d => 1.year,
24.0.to_d => 2.years
}[pledge_frequency]
end
end
|
chuckmersereau/api_practice
|
app/workers/background_batch/request_worker.rb
|
class BackgroundBatch::RequestWorker
include Sidekiq::Worker
sidekiq_options queue: :api_background_batch_request, unique: :until_executed, retry: true
def perform(id)
@request = BackgroundBatch::Request.find(id)
load_response if @request
end
protected
def load_response
RestClient::Request.execute(request_params) do |response|
update_request(response)
end
end
def request_params
{
method: @request.request_method,
payload: @request.request_body,
url: @request.formatted_path,
headers: @request.formatted_request_headers,
timeout: nil
}
end
def update_request(response)
@request.update(
response_body: response.body,
response_headers: response.headers,
response_status: response.code,
status: 'complete'
)
end
end
|
chuckmersereau/api_practice
|
spec/lib/async_spec.rb
|
require 'async'
require 'rails_helper'
class Foo
include Async
include Sidekiq::Worker
def kill(_person) end
def self.find(_var); end
end
describe 'Async' do
let(:id) { SecureRandom.uuid }
it 'should perform a method with an id' do
foo = double('foo')
allow(Foo).to receive(:find).with(id).and_return(foo)
expect(foo).to receive(:kill).with('Todd')
Foo.new.perform(id, :kill, 'Todd')
end
it 'should perform a method without an id' do
foo = Foo.new
expect(foo).to receive(:kill).with('Todd')
foo.perform(nil, :kill, 'Todd')
end
end
|
chuckmersereau/api_practice
|
spec/factories/family_relationships.rb
|
FactoryBot.define do
factory :family_relationship do
association :person
association :related_person, factory: :person
relationship 'MyString'
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/batch_request_helpers.rb
|
module BatchRequestHelpers
private
def reject_if_in_batch_request
if request.env['BATCH_REQUEST']
error = BatchRequestHandler::Instruments::RequestValidator::InvalidBatchRequestError.new(
status: 403,
message: 'You cannot access this endpoint from within a batch request'
)
rack_request = Rack::Request.new(request.env)
json_payload = BatchRequestHandler::Instruments::RequestValidator.generate_invalid_batch_request_json_payload(error, rack_request)
render json: json_payload, status: 403
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20140807133855_add_employer_to_people.rb
|
class AddEmployerToPeople < ActiveRecord::Migration
def change
add_column :people, :employer, :string
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/export_to_mail_chimp_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::Contacts::ExportToMailChimpController, type: :controller do
let(:factory_type) { :mail_chimp_account }
let!(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let!(:appeal) { create(:appeal, account_list: account_list) }
let(:account_list_id) { account_list.id }
let(:appeal_id) { appeal.id }
let(:primary_list_id) { '1e72b58b72' }
let(:second_list_id) { '1e33b58b72' }
let(:mail_chimp_account) { build(:mail_chimp_account, primary_list_id: primary_list_id) }
let!(:first_contact) { create(:contact, account_list: account_list, appeals: [appeal]) }
let!(:second_contact) { create(:contact, account_list: account_list, appeals: [appeal]) }
before do
allow_any_instance_of(MailChimp::Exporter).to receive(:export_contacts)
allow_any_instance_of(MailChimpAccount).to receive(:lists).and_return([])
allow_any_instance_of(MailChimpAccount).to receive(:validate_key)
mail_chimp_account.account_list = account_list
mail_chimp_account.save
end
context '#export' do
it 'returns 401 when user is not signed in' do
post :create
expect(response.status).to eq(401)
end
it 'returns a 400 with error message when mailchimp_list_id is not provided' do
api_login(user)
post :create
expect(response.status).to eq(400)
expect(JSON.parse(response.body)['errors'].first['detail']).to eq('mail_chimp_list_id must be provided')
end
it 'returns a 400 with error message when mailchimp_list_id is the primary_list_id' do
api_login(user)
expect(MailChimp::ExportContactsWorker).not_to receive(:perform_async).with(
mail_chimp_account.id,
primary_list_id,
a_collection_containing_exactly(first_contact.id, second_contact.id),
true
)
post :create, mail_chimp_list_id: primary_list_id
expect(response.status).to eq(400)
error = JSON.parse(response.body)['errors'].first['detail']
expect(error).to eq('mail_chimp_list_id cannot be primary_list_id, select different list')
end
it 'queues export when user is logged in and provides mailchimp_list_id' do
api_login(user)
expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with(
mail_chimp_account.id,
second_list_id,
a_collection_containing_exactly(first_contact.id, second_contact.id),
true
)
post :create, mail_chimp_list_id: second_list_id
expect(response).to be_success
end
it 'queues export only the contacts in contact_id filter that belong to the user' do
api_login(user)
expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with(
mail_chimp_account.id, second_list_id, [first_contact.id], true
)
post :create, filter: { contact_ids: [first_contact.id, create(:contact).id] }, mail_chimp_list_id: second_list_id
expect(response).to be_success
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/reports/weeklies_controller.rb
|
class Api::V2::Reports::WeekliesController < Api::V2Controller
def index
@sessions = Weekly.select('distinct on (sid) *')
render json: @sessions
end
def show
load_report
authorize(@report)
render json: @report
end
def create
@report = Weekly.new(weekly_params)
@report.save
authorize(@report)
render jason: @report
end
private
def weekly_params
params.require(:weekly).permit(weekly_attributes)
end
def weekly_attributes
Weekly::PERMITTED_ATTRIBUTES
end
def load_report
@report = Weekly.where(:sid => params[:session_id])
#@report = @report.sort_by{|x| x.question_id}
end
end
|
chuckmersereau/api_practice
|
app/preloaders/api/v2/contacts/people/linkedin_accounts_preloader.rb
|
<reponame>chuckmersereau/api_practice
class Api::V2::Contacts::People::LinkedinAccountsPreloader < ApplicationPreloader
ASSOCIATION_PRELOADER_MAPPING = {}.freeze
FIELD_ASSOCIATION_MAPPING = {}.freeze
private
def serializer_class
Person::LinkedinAccountSerializer
end
end
|
chuckmersereau/api_practice
|
lib/rspec_doc_combiner.rb
|
class RSpecDocCombiner
def self.combine!
new.combine_children_into_parents
end
def combine_children_into_parents
files.map(&:combine!)
end
def files
@files ||= parent_folders.map do |folder_name|
fetch_files_for_folder(folder_name)
end
end
def parent_folders
@parent_folders ||= fetch_parent_folders
end
private
def base_path
Rails.root.join('doc/api')
end
def fetch_files_for_folder(folder_name)
parent_filepath = "#{base_path}/#{folder_name}/index.html.md"
children_filepaths = Dir["#{base_path}/#{folder_name}/**/*.md"].reject do |path|
path == parent_filepath
end.sort
parent = DocFile.new(parent_filepath, parent: true)
children_filepaths.each { |path| parent.add_child(DocFile.new(path)) }
parent
end
def fetch_parent_folders
Dir
.entries(base_path)
.select { |dir| !invalid_folder_names.include?(dir) }
end
def invalid_folder_names
[
'.',
'..',
'.DS_Store',
'_generated_examples.markdown',
'index.html.md'
]
end
class DocFile
attr_reader :children, :path
def initialize(path, parent: false)
@children = []
@combined = false
@parent = parent
@path = path
end
def <<(additional_file)
file << additional_file.read
end
def add_child(child)
children << child
end
def close
file.close
end
def combine!
return self if combined?
children.each do |child|
self << child
end
@combined = true
self
end
def combined?
@combined
end
def parent?
@parent
end
def read
@read ||= file.read
end
def file
@file ||= File.open(path, 'a+')
end
private
def after_initialize
raise ArgumentError, "No file at: #{path}" unless File.exist?(path)
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/state.rb
|
class Contact::Filter::State < Contact::Filter::Base
def execute_query(contacts, filters)
state_filters = parse_list(filters[:state])
state_filters << nil if state_filters.delete('none')
contacts.where('addresses.state' => state_filters,
'addresses.historic' => filters[:address_historic] == 'true')
.joins(:addresses)
end
def title
_('State')
end
def parent
_('Contact Location')
end
def type
'multiselect'
end
def custom_options
account_list_states = account_lists.map(&:states)
.flatten
.uniq
.select(&:present?)
.map { |state| { name: state, id: state } }
[{ name: _('-- None --'), id: 'none' }] + account_list_states
end
end
|
chuckmersereau/api_practice
|
app/controllers/mail_chimp_webhook_controller.rb
|
<filename>app/controllers/mail_chimp_webhook_controller.rb
class MailChimpWebhookController < ActionController::API
skip_before_action :redirect_to_mobile, :verify_authenticity_token, :ensure_setup_finished,
:ensure_login
before_action :find_account_and_ensure_valid
def index
# used by mailchimp to verify the webhook url
render nothing: true
end
def hook
unless hook_handler_class
render text: 'Unrecognized list id'
return
end
case hook_params[:type]
# when 'subscribe'
# handler.subscribe_hook(data_param(:email))
# when 'upemail'
# handler.email_update_hook(data_param(:old_email), data_param(:new_email))
when 'unsubscribe'
handler.unsubscribe_hook(data_param(:email), data_param(:reason), data_param(:list_id))
when 'cleaned'
handler.email_cleaned_hook(data_param(:email), data_param(:reason), data_param(:list_id))
when 'campaign'
handler.campaign_status_hook(data_param(:id), data_param(:status), data_param(:subject))
end
render nothing: true
end
private
def handler
@handler ||= hook_handler_class.new(@account)
end
def hook_handler_class
list_id = data_param(:list_id)
if list_id == @account.primary_list_id
MailChimp::Webhook::PrimaryList
elsif @account.mail_chimp_appeal_list &&
list_id == @account.mail_chimp_appeal_list.appeal_list_id
MailChimp::Webhook::AppealList
end
end
def find_account_and_ensure_valid
@account = MailChimpAccount.find_by(webhook_token: params[:token])
unless @account
render text: 'Invalid token', status: :unauthorized
return
end
unless @account.active
render text: 'Inactive account'
return
end
end
def data_param(key)
hook_params[:data][key]
end
def hook_params
@hook_params ||=
params.permit([:type, :fired_at,
{ data: [:id, :list_id, :email, :email_type, :ip_opt, :ip_signup, :action, :reason,
:campaign_id, :new_id, :new_email, :old_email, :subject, :status,
{ merges: [:EMAIL, :FNAME, :LNAME, :INTERESTS] }] }])
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170419004646_add_queued_for_import_at_to_imports.rb
|
class AddQueuedForImportAtToImports < ActiveRecord::Migration
def change
add_column :imports, :queued_for_import_at, :datetime
end
end
|
chuckmersereau/api_practice
|
spec/factories/contact_people.rb
|
FactoryBot.define do
factory :contact_person do
contact nil
person nil
primary false
end
end
|
chuckmersereau/api_practice
|
spec/services/reports/salary_currency_donations_spec.rb
|
<filename>spec/services/reports/salary_currency_donations_spec.rb
require 'rails_helper'
RSpec.describe Reports::SalaryCurrencyDonations, type: :model do
subject { described_class.new(account_list: account_list) }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:designation_account_1) { create(:designation_account) }
let!(:designation_account_2) { create(:designation_account) }
let!(:designation_account_3) { create(:designation_account) }
let!(:donor_account_1) { create(:donor_account) }
let!(:donor_account_2) { create(:donor_account) }
let!(:donor_account_3) { create(:donor_account) }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:cad_donation) do
create(:donation, donor_account: donor_account_1,
designation_account: designation_account_1,
amount: 3, currency: 'CAD',
donation_date: Date.current - 1.month)
end
let!(:eur_donation) do
create(:donation, donor_account: donor_account_2,
designation_account: designation_account_2,
amount: 2, currency: 'EUR',
donation_date: Date.current)
end
let!(:donation_last_year) do
create(:donation, donor_account: donor_account_3,
designation_account: designation_account_3,
amount: 88, currency: 'EUR',
donation_date: 13.months.ago.end_of_month - 1.day)
end
before do
account_list.designation_accounts << designation_account_1
account_list.designation_accounts << designation_account_2
account_list.designation_accounts << designation_account_3
contact.donor_accounts << donor_account_1
contact.donor_accounts << donor_account_2
contact.donor_accounts << donor_account_3
end
describe '#donor_infos' do
it 'returns donor infos' do
expect(subject.donor_infos).to be_a(Array)
expect(subject.donor_infos.size).to eq(1)
expect(subject.donor_infos.first).to be_a(DonationReports::DonorInfo)
expect(subject.donor_infos.first.contact_name).to eq(contact.name)
end
end
describe '#months' do
it { expect(subject.months.size).to eq 13 }
it { subject.months.each { |m| expect(m).to be_a Date } }
end
describe '#currency_groups' do
subject { described_class.new(account_list: account_list).currency_groups }
let(:usd) { subject['USD'] }
let(:totals) { usd[:totals] }
let(:donation_months) { usd[:donation_infos].flat_map { |d| d[:months] } }
it { expect(totals[:year]).to eq 5 }
it 'should sum donations by months' do
expect(totals[:months].select(&:zero?).size).to eq 11
expect(totals[:months].select(&:nonzero?).size).to eq 2
end
it 'should include each donation record' do
all_donations = donation_months.flat_map { |m| m[:donations] }
match = all_donations.find { |d| d.donation_id == cad_donation.id }
expect(match).to be_present
expect(match).to be_a DonationReports::DonationInfo
end
it 'does not return donations made more than 12 months ago' do
subject.each do |_, report|
report[:donation_infos].flat_map { |d| d[:months] }.each do |month|
expect(month[:donations].find { |d| d.donation_id == donation_last_year.id }).to be_nil
end
end
end
context 'can allow custom start and end date for donation viewing' do
let(:starting) { Date.today - 3.years }
let(:ending) { Date.today - 1.year }
subject do
described_class.new(
account_list: account_list,
filter_params: { month_range: (starting..ending) }
)
end
it 'should have the correct start date' do
expect(subject.start_date).to eq(starting.beginning_of_month)
end
it 'should have the correct end date' do
expect(subject.end_date).to eq(ending)
end
end
context 'designation_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { designation_account_id: designation_account_1.id }
).currency_groups
end
it 'should include each donation record' do
all_donations = donation_months.flat_map { |m| m[:donations] }
match = all_donations.first
expect(all_donations.length).to eq 1
expect(match).to be_a DonationReports::DonationInfo
expect(match.donation_id).to eq cad_donation.id
end
end
context 'donor_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { donor_account_id: donor_account_1.id }
).currency_groups
end
it 'should include each donation record' do
all_donations = donation_months.flat_map { |m| m[:donations] }
match = all_donations.first
expect(all_donations.length).to eq 1
expect(match).to be_a DonationReports::DonationInfo
expect(match.donation_id).to eq cad_donation.id
end
end
end
describe '#currency_groups hash structure' do
subject { described_class.new(account_list: account_list).currency_groups }
it { expect(subject).to be_a Hash }
it 'has the correct key/value structure' do
expect(subject.keys.size).to eq 1
expect(subject.keys).to include 'USD'
subject.each do |_, h|
expect(h.keys).to include :totals, :donation_infos
expect(h[:totals].keys).to include :year, :months
expect(h[:donation_infos]).not_to be_empty
h[:donation_infos].each do |info|
expect(info).to include :contact_id, :total, :average, :minimum,
:maximum, :months
info[:months].each do |month|
expect(month.keys).to include :total, :donations
end
expect(info[:months].last[:donations].first.attributes.keys).to include :converted_amount, :converted_currency
end
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/google_import.rb
|
<filename>app/services/google_import.rb
class GoogleImport
def initialize(import)
@user = import.user
@import = import
@account_list = import.account_list
end
def import
return false unless @import.source_account_id
google_account = @user.google_accounts.find_by(id: @import.source_account_id)
begin
google_account.update_column(:downloading, true)
import_contacts(google_account)
google_account.update_column(:last_download, Time.now)
ensure
google_account.update_column(:downloading, false)
end
false
end
def import_contacts(google_account)
if @import.import_by_group?
@import.groups.each do |group_id|
import_contacts_batch(google_account.contacts_for_group(group_id),
Array.wrap(@import.tags) + Array.wrap(@import.group_tags[group_id]))
end
else
import_contacts_batch(google_account.contacts, @import.tags)
end
rescue Person::GoogleAccount::MissingRefreshToken
# This triggers an "import failed" email to the user but won't log the error in Rollbar
raise Import::UnsurprisingImportError
end
def import_contacts_batch(google_contacts, tags)
google_contacts.each do |g_contact|
begin
import_contact(g_contact, tags)
rescue StandardError => e
Rollbar.raise_or_notify(e)
next
end
end
end
def import_contact(g_contact, tags)
return unless g_contact.given_name
person = create_or_update_person(g_contact)
contact = create_or_update_contact(person, g_contact, tags)
spouse = create_spouse_if_specified(contact, person, g_contact)
# Associate the local google contact to the mpdx contact
person.google_contacts.find_by_remote_id(g_contact.id)&.update(contact: contact)
contact.people.reload
# Associate the person to the contact
begin
contact.people << person unless contact.people.include?(person)
contact.people << spouse unless spouse.nil? || contact.people.include?(spouse)
rescue ActiveRecord::RecordNotUnique
end
end
def create_or_update_contact(person, g_contact, tags)
contact = @account_list.contacts.with_person(person).first
unless contact
name = "#{person.last_name}, #{person.first_name}"
contact = @account_list.contacts.find_or_create_by(name: name)
end
contact.add_to_notes(g_contact.content)
contact.addresses_attributes = build_addresses(contact, g_contact)
contact.tag_list.add(tags, parse: true) if tags.present?
contact.save
contact
end
def build_addresses(contact, g_contact)
mpdx_had_no_primary = contact.addresses.where(primary_mailing_address: true).empty?
addresses = g_contact.addresses.map do |g_contact_address|
address_attrs = format_address_for_mpdx(g_contact_address)
if address_attrs[:primary_mailing_address] && (@import.override? || mpdx_had_no_primary)
contact.addresses.each { |non_primary| non_primary.update(primary_mailing_address: false) }
else
address_attrs[:primary_mailing_address] = false
end
address_attrs
end
ensure_one_primary(addresses, :primary_mailing_address) if mpdx_had_no_primary
addresses
end
def ensure_one_primary(items, primary_attribute = :primary)
found_primary = false
items.each do |item|
if found_primary
item[primary_attribute] = false
else
found_primary = item[primary_attribute]
end
end
items[0][primary_attribute] = true if !items.empty? && !found_primary
end
def format_address_for_mpdx(google_address)
{ street: google_address[:street], city: google_address[:city], state: google_address[:region],
postal_code: google_address[:postcode],
country: format_g_contact_country(google_address[:country]),
location: google_address_rel_to_location(google_address[:rel]),
primary_mailing_address: google_address[:primary],
source: 'GoogleImport' }
end
def format_g_contact_country(country)
if country == 'United States of America'
'United States'
elsif country.nil? || country.is_a?(String)
country
else
raise "Unexpected country from Google Contacts import: #{country}"
end
end
def google_address_rel_to_location(rel)
if rel == 'work'
'Business'
elsif rel == 'home'
'Home'
else
'Other'
end
end
def create_spouse_if_specified(contact, person, g_contact)
spouse = g_contact.spouse
return if spouse.blank?
# This regexp makes the first name be all the words up to the last word, and the last name be the
# last word, so it can catch cases like, "Mary", "<NAME>" and "<NAME>".
first, last = spouse.split(/\s+(?=\S*+$)/)
# Assume same last names if none specified for spouse
last ||= person.last_name
return unless contact.people.where(first_name: first, last_name: last).empty?
name = if person.last_name == last
"#{person.last_name}, #{person.first_name} and #{first}"
else
"#{person.last_name}, #{person.first_name} and #{first} (#{last})"
end
contact.update(name: name)
Person.create!(first_name: first, last_name: last)
end
def create_or_update_person(g_contact)
person = create_or_update_person_basic_info(g_contact)
update_person_emails(person, g_contact)
update_person_phones(person, g_contact)
update_person_websites(person, g_contact)
google_contact = person.google_contacts.create_with(google_account_id: @import.source_account_id)
.find_or_create_by(remote_id: g_contact.id)
update_person_picture(person, google_contact, g_contact)
person.save
person
end
def create_or_update_person_basic_info(g_contact)
person = (@account_list.people.includes(:google_contacts).find_by('google_contacts.remote_id' => g_contact.id) ||
@account_list.people.find_by(first_name: g_contact.given_name, last_name: g_contact.family_name))
person_attrs = person_attr_from_g_contact(g_contact)
if person
person.update(person_attrs.select { |k, v| v.present? && (@import.override? || person.send(k).blank?) })
person
else
Person.create!(person_attrs)
end
end
def person_attr_from_g_contact(g_contact)
attrs = {
title: g_contact.name_prefix,
first_name: g_contact.given_name,
middle_name: g_contact.additional_name,
last_name: g_contact.family_name,
suffix: g_contact.name_suffix,
birthday_day: g_contact.birthday ? g_contact.birthday[:day] : nil,
birthday_month: g_contact.birthday ? g_contact.birthday[:month] : nil,
birthday_year: g_contact.birthday ? g_contact.birthday[:year] : nil
}
# The Google Contacts Web UI seems to only let you add a single organization for a contact, so let's just
# take the first one or the one that's primary and save that to the person's employer and occupation.
unless g_contact.organizations.empty?
primary_org = g_contact.organizations.first
g_contact.organizations.each { |org| primary_org = org if org[:primary] }
attrs[:occupation] = primary_org[:org_title]
attrs[:employer] = primary_org[:org_name]
end
attrs
end
def update_person_emails(person, g_contact)
num_emails_before_import = person.email_addresses.count
g_contact.emails_full.each do |import_email|
email = { email: import_email[:address], location: import_email[:rel] }
if import_email[:primary] && (@import.override? || num_emails_before_import.zero?)
person.email_addresses.update_all primary: false
email[:primary] = true
end
person.email_address = email
end
end
def update_person_phones(person, g_contact)
num_phones_before_import = person.phone_numbers.count
g_contact.phone_numbers_full.each do |import_phone|
phone = { number: import_phone[:number], location: import_phone[:rel] }
if import_phone[:primary] && (@import.override? || num_phones_before_import.zero?)
person.phone_numbers.update_all primary: false
phone[:primary] = true
end
person.phone_number = phone
end
end
def update_person_websites(person, g_contact)
num_websites_before_import = person.websites.count
at_least_one_primary = num_websites_before_import.positive?
g_contact.websites.each_with_index do |import_website, index|
next if import_website[:href].in? person.websites.pluck(:url)
if import_website[:primary] && (@import.override? || num_websites_before_import.zero?)
person.websites.update_all primary: false
import_website[:primary] = true
at_least_one_primary = true
elsif !at_least_one_primary && index == g_contact.websites.length - 1
import_website[:primary] = true
else
import_website[:primary] = false
end
person.websites << Person::Website.new(url: import_website[:href], primary: import_website[:primary])
end
end
def update_person_picture(person, google_contact, g_contact_to_import)
# Don't update the picture of people who have a connected facebook account as that will provide their picture
return if person.facebook_account
photo = g_contact_to_import.photo_with_metadata
return if photo.nil? || google_contact.picture_etag == photo[:etag]
primary = person.pictures.count.zero? || @import.override?
person.pictures.update_all(primary: false) if primary
image_io = StringIOWithPath.new(photo[:etag] + image_mime_to_extension(photo[:content_type]), photo[:data])
picture = Picture.create(image: image_io, primary: primary)
google_contact.update(picture_etag: photo[:etag], picture_id: picture.id)
person.pictures << picture
end
def image_mime_to_extension(mime)
'.' + mime.gsub('image/', '')
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180123202817_add_columns_for_pref_blog_foreign_keys.rb
|
class AddColumnsForPrefBlogForeignKeys < ActiveRecord::Migration
def change
add_column :people, :default_account_list_id_holder, :integer
add_column :account_lists, :salary_organization_id_holder, :integer
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170529002918_update_person_linkedin_accounts_public_url_length.rb
|
<reponame>chuckmersereau/api_practice
class UpdatePersonLinkedinAccountsPublicUrlLength < ActiveRecord::Migration
def change
change_column :person_linkedin_accounts, :public_url, :text
end
end
|
chuckmersereau/api_practice
|
app/services/errors/url_changed.rb
|
<reponame>chuckmersereau/api_practice
class Errors::UrlChanged < StandardError
end
|
chuckmersereau/api_practice
|
config/initializers/assets.rb
|
<reponame>chuckmersereau/api_practice
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
Rails.application.config.assets.precompile += [/^[a-z0-9]\w+.(css|js)$/]
Rails.application.config.assets.precompile += ['jquery-ui.css'] # Disable delivery errors, bad email addresses will be ignored
Rails.application.config.assets.precompile += [/angular-i18n/]
Rails.application.config.assets.precompile += [/twitter_cldr/]
|
chuckmersereau/api_practice
|
spec/services/admin/account_primary_addresses_fix_spec.rb
|
<filename>spec/services/admin/account_primary_addresses_fix_spec.rb
require 'rails_helper'
describe Admin::AccountPrimaryAddressesFix, '#fix!' do
it 'fixes the primary addresses for each contact in the account list' do
contact = create(:contact)
contacts = double('contacts')
allow(contacts).to receive(:find_each).and_yield(contact)
account_list = double('account_list', contacts: contacts)
fix = double('fix', fix: nil)
allow(Admin::PrimaryAddressFix).to receive(:new).with(contact) { fix }
Admin::AccountPrimaryAddressesFix.new(account_list).fix
expect(fix).to have_received(:fix)
end
end
|
chuckmersereau/api_practice
|
app/serializers/address_serializer.rb
|
class AddressSerializer < ApplicationSerializer
attributes :street,
:city,
:country,
:end_date,
:geo,
:historic,
:location,
:metro_area,
:postal_code,
:primary_mailing_address,
:region,
:remote_id,
:seasonal,
:source,
:start_date,
:state,
:valid_values
belongs_to :source_donor_account
end
|
chuckmersereau/api_practice
|
db/migrate/20150221153949_remove_never_ask_from_contacts.rb
|
<gh_stars>0
class RemoveNeverAskFromContacts < ActiveRecord::Migration
def change
Contact.where(never_ask: true).update_all(no_appeals: true)
remove_column :contacts, :never_ask
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160204190107_add_index_to_google_email_activities_email_id.rb
|
<filename>db/migrate/20160204190107_add_index_to_google_email_activities_email_id.rb
class AddIndexToGoogleEmailActivitiesEmailId < ActiveRecord::Migration
self.disable_ddl_transaction!
def change
add_index :google_email_activities, :google_email_id, algorithm: :concurrently
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160518122605_make_person_relay_accounts_remote_id_not_null.rb
|
<reponame>chuckmersereau/api_practice<filename>db/migrate/20160518122605_make_person_relay_accounts_remote_id_not_null.rb
class MakePersonRelayAccountsRemoteIdNotNull < ActiveRecord::Migration
def change
change_column_null :person_relay_accounts, :remote_id, false
end
end
|
chuckmersereau/api_practice
|
spec/serializers/contact_serializer_spec.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
require 'rails_helper'
describe ContactSerializer, deprecated: true do
describe 'contacts list' do
let(:contact) do
c = create(:contact)
c.addresses << build(:address)
c.donations << [create(:donation, amount: 21.00), create(:donation, amount: 7.00)]
c
end
let(:person) do
p = build(:person)
p.email_addresses << build(:email_address)
p.phone_numbers << build(:phone_number)
contact.people << p
p
end
it 'people list' do
expect(json).to include :people
end
it 'addresses list' do
expect(json).to include :addresses
end
it 'returns frequency without trailing zeros' do
monthly_json = ContactSerializer.new(contact).to_json
expect(JSON.parse(monthly_json)['contact']['pledge_frequency']).to eq '1'
contact.update_attribute(:pledge_frequency, 0.23076923076923)
contact.reload
weekly_json = ContactSerializer.new(contact).to_json
expect(JSON.parse(weekly_json)['contact']['pledge_frequency']).to eq '0.23076923076923'
end
it 'returns lifetime_donations' do
expect(JSON.parse(json)['contact']['lifetime_donations']).to eq(28.00)
end
# it "cache_key is dependant on include params" do
# key = ContactSerializer.new(contact, {scope: {include: 'person'}}).cache_key
# expect(key).not_to eq(ContactSerializer.new(contact).cache_key)
# end
#
# it "cache_key should change when updated" do
# expect{contact.touch}.to change { ContactSerializer.new(contact).cache_key }
# end
end
end
|
chuckmersereau/api_practice
|
spec/mailers/account_mailer_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/mailers/account_mailer_spec.rb
require 'rails_helper'
describe AccountMailer do
describe '#mailchimp_required_merge_field' do
it 'renders the mail' do
email = build(:email_address)
account_list = double(users: [double(email: email)])
mail = AccountMailer.mailchimp_required_merge_field(account_list)
expect(mail.subject).to eq('Mailchimp List is requiring an additional merge field')
expect(mail.to).to eq([email.email])
expect(mail.from).to eq(['<EMAIL>'])
expect(mail.body.raw_source).to include('https://mpdx.org/preferences/integrations?selectedTab=mailchimp')
end
end
describe '#google_account_refresh' do
it 'renders the mail' do
email = build(:email_address)
person = double(email: email)
integration = build_stubbed(:google_integration)
mail = AccountMailer.google_account_refresh(person, integration)
expect(mail.subject).to eq('Google account needs to be refreshed')
expect(mail.to).to eq([email.email])
expect(mail.from).to eq(['<EMAIL>'])
expect(mail.body.raw_source).to include('https://mpdx.org/preferences/integrations?selectedTab=google')
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180608133404_change_deleted_on.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class ChangeDeletedOn < ActiveRecord::Migration
def change
rename_column :deleted_records, :deleted_on, :deleted_at
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170317205005_add_valid_values_indexes.rb
|
<gh_stars>0
class AddValidValuesIndexes < ActiveRecord::Migration
def change
add_index :contacts, :status_valid
add_index :addresses, :valid_values
add_index :phone_numbers, :valid_values
add_index :email_addresses, :valid_values
add_index :addresses, :source
add_index :phone_numbers, :source
add_index :email_addresses, :source
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/status_suggester_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Contact::StatusSuggester, type: :model do
include ContactStatusSuggesterSpecHelpers
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact, account_list: account_list) }
let(:donor_account) { create(:donor_account) }
let(:designation_account) { create(:designation_account) }
let(:service) { Contact::StatusSuggester.new(contact: contact) }
before do
travel_to Time.current.beginning_of_year
account_list.designation_accounts << designation_account
contact.donor_accounts << donor_account
contact.donations.each(&:destroy!)
end
after do
travel_back
end
it 'initializes' do
expect(service).to be_a Contact::StatusSuggester
expect(service.contact).to eq contact
end
# Run the following specs for each pledge frequency
Contact.pledge_frequencies.keys.sort.each do |pledge_frequency|
pledge_frequency_in_days = (pledge_frequency * 30).round
context 'no donations' do
before { contact.donations.each(&:destroy!) }
it 'cannot make suggestions' do
expect(service.suggested_pledge_frequency).to eq nil
expect(service.suggested_pledge_amount).to eq nil
expect(service.suggested_pledge_currency).to eq nil
expect(service.suggested_status).to eq nil
expect(service.contact_has_stopped_giving?).to eq false
end
end
context 'perfectly consistent donations' do
before { create_donations_to_match_frequency(pledge_frequency) }
it "makes accurate suggestions for donations at pledge frequency #{pledge_frequency}" do
expect(service.suggested_pledge_frequency).to eq pledge_frequency
expect(service.suggested_pledge_amount).to eq 50
expect(service.suggested_pledge_currency).to eq 'CAD'
expect(service.suggested_status).to eq 'Partner - Financial'
expect(service.contact_has_stopped_giving?).to eq false
end
end
context 'only one donation is late' do
before do
create_donations_to_match_frequency(pledge_frequency) # Create the consistent donations
# Make one donation late by about half the period we're looking for
contact.donations.second.tap do |donation|
donation.update donation_date: donation.donation_date + (pledge_frequency_in_days / 2).round.days
end
end
it "makes accurate suggestions for donations at pledge frequency #{pledge_frequency}" do
expect(service.suggested_pledge_frequency).to eq pledge_frequency
expect(service.suggested_pledge_amount).to eq 50
expect(service.suggested_pledge_currency).to eq 'CAD'
expect(service.suggested_status).to eq 'Partner - Financial'
expect(service.contact_has_stopped_giving?).to eq false
end
end
context 'less donations than the look back period' do
before do
# Skip the one time donation, because it will mess up this strategy
create_donations_to_match_frequency(pledge_frequency, one_time: false)
end
it "makes accurate suggestions for donations at pledge frequency #{pledge_frequency}" do
while contact.donations.count > 2
contact.donations.last.destroy
expect(service.suggested_pledge_frequency).to eq pledge_frequency
expect(service.suggested_pledge_amount).to eq 50
expect(service.suggested_pledge_currency).to eq 'CAD'
expect(service.suggested_status).to eq 'Partner - Financial'
expect(service.contact_has_stopped_giving?).to eq false
end
end
end
context 'partner special' do
before do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
tendered_amount: 20,
donation_date: pledge_frequency_in_days.days.ago)
end
it "makes accurate suggestions for donations at pledge frequency #{pledge_frequency}" do
expect(service.suggested_pledge_frequency).to eq nil
expect(service.suggested_pledge_amount).to eq nil
expect(service.suggested_pledge_currency).to eq nil
expect(service.suggested_status).to eq 'Partner - Special'
expect(service.contact_has_stopped_giving?).to eq false
end
end
context 'contact was a financial partner but has now stopped giving' do
before do
create_donations_to_match_frequency(pledge_frequency)
# Move all donations back by two periods, to make it seem like they have stopped giving
Donation.all.each do |donation|
donation.update(donation_date: donation.donation_date - (pledge_frequency_in_days * 3).days)
end
end
it "makes accurate suggestions for donations at pledge frequency #{pledge_frequency}" do
expect(service.suggested_pledge_frequency).to eq nil
expect(service.suggested_pledge_amount).to eq nil
expect(service.suggested_pledge_currency).to eq nil
expect(service.suggested_status).to eq 'Partner - Special'
expect(service.contact_has_stopped_giving?).to eq true
end
end
end
end
|
chuckmersereau/api_practice
|
lib/json_api_service/data_object_collection.rb
|
<gh_stars>0
require 'json_api_service/base_object'
module JsonApiService
class DataObjectCollection < BaseObject
include Enumerable
attr_reader :items
def to_a
items.map(&:to_h)
end
def each
items.each { |item| yield(item) }
end
def validate_against_store
each(&:validate_against_store)
end
private
def after_initialize
parse_items
end
def parse_items
@items = data.map do |item_data|
DataObject.new(item_data, parent: self, store: store)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/users_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::UsersController, type: :controller do
let(:user) { create(:user_with_account) }
let(:factory_type) { :user }
let(:resource) { user }
let(:correct_attributes) { { first_name: 'test_first_name', preferences: { locale: 'fr-FR' } } }
let(:incorrect_attributes) { { first_name: nil } }
let(:unpermitted_attributes) { nil }
let(:given_update_reference_key) { :locale }
let(:given_update_reference_value) { 'fr-FR' }
let(:second_account_list) { create(:account_list, users: [user]) }
before do
create(:google_account, person: user) # Test inclusion of related resources.
end
include_examples 'show_examples'
include_examples 'update_examples'
context 'update#default_account_list' do
it 'correctly saves default_account_list when passed as a preference' do
api_login(user)
put :update, data: {
id: user.id,
type: 'users',
attributes: {
preferences: {
default_account_list: second_account_list.id
},
overwrite: true
}
}
expect(
JSON.parse(response.body)['data']['attributes']['preferences']['default_account_list']
).to eq(second_account_list.id)
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/people.rb
|
FactoryBot.define do
factory :person do
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
association :master_person
factory :person_with_email do
after(:build) do |person|
email_address = <EMAIL>"
create(:email_address, primary: true, email: email_address, person: person)
end
end
factory :person_with_gender do
after(:build) do |person|
email_address = <EMAIL>"
create(:email_address, primary: true, email: email_address, person: person)
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/company_position.rb
|
<reponame>chuckmersereau/api_practice
class CompanyPosition < ApplicationRecord
belongs_to :person
belongs_to :company
def to_s
position
end
end
|
chuckmersereau/api_practice
|
spec/services/converted_total_spec.rb
|
require 'rails_helper'
RSpec.describe ConvertedTotal, type: :service do
let(:data) do
[
[5.50, 'EUR', Date.new(2016, 2, 15)],
[200.82, 'RUB', Date.new(2017, 1, 21)],
[10.60, 'NZD', Date.new(2016, 4, 10)]
]
end
before do
create(:currency_rate, rate: 0.8, exchanged_on: '2016-02-15', code: 'EUR')
create(:currency_rate, rate: 0.78, exchanged_on: '2016-02-15', code: 'NZD')
create(:currency_rate, rate: 75.20, exchanged_on: '2017-01-21', code: 'RUB')
create(:currency_rate, rate: 0.62, exchanged_on: '2017-01-21', code: 'NZD')
create(:currency_rate, rate: 0.75, exchanged_on: '2016-04-10', code: 'NZD')
end
describe '#total' do
it 'converts currencies on their display date to the display currency' do
expect(described_class.new(data, 'NZD').total).to eq(
(5.50 / 0.8 * 0.78 + 200.82 / 75.20 * 0.62 + 10.60).round(2)
# EUR > USD > NZD + RUB > USD > NZD + NZD
)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/donation_reports/donor_info_spec.rb
|
require 'rails_helper'
describe DonationReports::DonorInfo do
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact) }
describe '.from_contact' do
it 'intantiates an object with attributes' do
donor_info = DonationReports::DonorInfo.from_contact(contact)
expect(donor_info.contact_name).to eq(contact.name)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/north_star_report_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe NorthStarReport, type: :model do
around do |example|
travel_to(Date.new(2016, 4, 20)) { example.run }
end
describe 'weeks' do
before do
u1 = create(:user_with_account)
u2 = create(:user_with_account)
u1.account_lists.order(:created_at).first.tasks << create(:task, completed_at: 1.week.ago)
u1.account_lists.order(:created_at).first.tasks << create(:task, completed_at: 2.weeks.ago)
u2.account_lists.order(:created_at).first.tasks << create(:task, completed_at: 1.week.ago)
end
it 'loads counts' do
report = NorthStarReport.new.weeks
expect(report.length).to be 2
expect(report.first['week']).to eq '04-04-16'
expect(report.first['users']).to eq '1'
expect(report.last['week']).to eq '04-11-16'
expect(report.last['users']).to eq '2'
end
end
describe 'months' do
before do
u1 = create(:user_with_account)
u2 = create(:user_with_account)
u1.account_lists.order(:created_at).first.tasks << create(:task, completed_at: 1.month.ago)
u1.account_lists.order(:created_at).first.tasks << create(:task, completed_at: 2.months.ago)
u2.account_lists.order(:created_at).first.tasks << create(:task, completed_at: 1.month.ago)
end
it 'loads counts' do
report = NorthStarReport.new.months
expect(report.length).to be 2
expect(report.first['month']).to eq '02-2016'
expect(report.first['users']).to eq '1'
expect(report.last['month']).to eq '03-2016'
expect(report.last['users']).to eq '2'
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170829211453_create_account_list_coaches.rb
|
<gh_stars>0
class CreateAccountListCoaches < ActiveRecord::Migration
def change
create_table :account_list_coaches do |t|
t.belongs_to :coach, index: true
t.belongs_to :account_list, index: true
t.timestamps null: false
end
add_index :account_list_coaches, [:coach_id, :account_list_id], unique: true
end
end
|
chuckmersereau/api_practice
|
app/services/person/filter/phone_number_valid.rb
|
class Person::Filter::PhoneNumberValid < Person::Filter::Base
def execute_query(people, filters)
self.people = people
return people unless filters[:phone_number_valid] == 'false'
# Fetching a second time to allow loading of both valid and invalid phone numbers.
# Without this, it'll return people, but only invalid phone numbers will be included.
Person.where(id: people_with_invalid_phone_numbers.ids)
end
private
attr_accessor :people
def filter_scope
people.includes(:phone_numbers).references(:phone_numbers)
end
def people_with_invalid_phone_numbers
filter_scope.where('phone_numbers.valid_values = :valid OR people.id IN(:people_ids)',
valid: false,
people_ids: select_person_id_with_duplicate_primary_phone_numbers)
end
def select_person_id_with_duplicate_primary_phone_numbers
PhoneNumber.select(:person_id)
.where(person_id: people.ids, primary: true)
.group(:person_id)
.having('count(*) > 1')
end
end
|
chuckmersereau/api_practice
|
lib/batch_request_handler/instruments/abort_on_error.rb
|
<gh_stars>0
module BatchRequestHandler
module Instruments
# AbortOnError only runs if the BatchRequest has 'on_error' set to 'ABORT'.
# It will process through the requests, but if a request errors, it will
# abort immediately and return only the responses up to and including the
# error response. It will also change the status of the batch request to be
# the status of the response from the errored request.
class AbortOnError < BatchRequestHandler::Instrument
def self.enabled_for?(batch_request)
batch_request.params['on_error'] == 'ABORT'
end
def initialize(_params)
# Because the mechanism for aborting early is a catch/throw, throwing
# will abort early out of the map over the requests, so no responses
# will get captured by the BatchRequest. So we have to keep track of
# responses ourselves, and make sure that they get returned in
# `around_perform_requests`
@responses = []
@errored = false
end
def around_perform_requests(requests)
catch(:error) do
yield requests
end
@responses
end
def around_perform_request(env)
response = yield env
@responses << response
if error?(response)
@errored = true
throw :error
end
end
def around_build_response(json_responses)
batch_response = yield json_responses
batch_response[0] = json_responses.last[:status] if @errored
batch_response
end
private
def error?(response)
status, = response
(status.to_i / 100) > 3 # considered an error if status is 4xx or 5xx
end
end
end
end
|
chuckmersereau/api_practice
|
spec/exhibits/phone_number_exhibit_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe PhoneNumberExhibit do
subject { PhoneNumberExhibit.new(phone_number, context) }
let(:phone_number) { build(:phone_number, number: '2134567890', country_code: '1') }
let(:context) { double }
it 'returns a formatted number' do
allow(context).to receive(:number_to_phone).and_return('(213) 456-7890')
expect(subject.number).to eq('(213) 456-7890')
end
it 'returns an extension when included in the local number' do
phone_number.number = '2135555555;ext=1234'
expect(subject.number).to eq('(213) 555-5555 ext 1234')
end
it 'returns an e164 formatted number when an intl number is provided' do
phone_number.country_code = ''
phone_number.number = '613-555-55555'
expect(subject.number).to eq('+61355555555')
end
it 'returns an e164 formatted number and ext when included with an intl number' do
phone_number.country_code = ''
phone_number.number = '613-555-55555;ext=1234'
expect(subject.number).to eq('+61355555555 ext 1234')
end
it 'returns a number, dash and location when a location is present' do
phone_number.location = 'Home'
phone_number.number = '4075555555'
expect(subject.to_s).to eq('(407) 555-5555 - Home')
end
it 'returns only a number, when no location is present' do
phone_number.location = nil
phone_number.number = '4075555555'
expect(subject.to_s).to eq('(407) 555-5555')
end
end
|
chuckmersereau/api_practice
|
app/seeders/application_seeder.rb
|
<reponame>chuckmersereau/api_practice
require 'factory_bot'
class ApplicationSeeder
ALLOWED_ENV = %w(test development).freeze
LOCAL = %w(localhost 127.0.0.1).freeze
attr_accessor :quiet
def initialize(quiet = !Rails.env.development?)
self.quiet = quiet
end
def seed
safe!
intro
2.times { seed_all_models }
all_models_seeded?
outro
end
def all_models_seeded?
Rails.application.eager_load!
unseeded = ActiveRecord::Base.descendants.reject do |klass|
klass.anonymous? || klass.abstract_class? || klass.exists?
end
unseeded.each { |record_class| Rails.logger.info "Warning: No records seeded for class #{record_class}" } unless quiet
unseeded.blank?
end
private
def safe!
raise "Turn Back! ApplicationSeeder is not permitted in #{Rails.env}" unless ALLOWED_ENV.include?(Rails.env)
db_host = Rails.configuration.database_configuration[Rails.env]['host']
raise 'ApplicationSeeder is not permitted connected to a remote host' unless LOCAL.include?(db_host)
end
def intro
return if quiet
Rails.logger.info '== Starting database seeding... ==============================================='
Rails.logger.info "The database will be seeded using FactoryBot factories.\nPrinting the name of each factory as it's created:"
end
def outro
return if quiet
Rails.logger.info "\n== Finished database seeding! ================================================="
end
def create(*args)
Rails.logger.info "#{args.first}... " unless quiet
FactoryBot.create(*args)
end
def seed_all_models
# Seed NotificationTypes separately:
NotificationTypesSeeder.new(quiet).seed
Rails.application.eager_load!
ApplicationRecord.descendants.each(&:reset_column_information)
# Create some fundamental records first so that we can reference them below to establish associations:
organization = create :organization
user = create :user_with_full_account
account_list = user.account_lists.reload.order(:created_at).last
contact = create :contact, account_list: account_list
master_person = create :master_person
person = create :person, master_person: master_person
contact.people << person
create :contact_referral, referred_by: contact, referred_to: create(:contact)
create :contact_notes_log, contact: contact
create :account_list_invite, account_list: account_list
create :account_list_coach, account_list: account_list, coach: user.becomes(User::Coach)
activity = create :activity, account_list: account_list
create :activity_comment, activity: activity, person: person
create :activity_contact, activity: activity, contact: contact
create :address, addressable: contact
create :admin_impersonation_log, impersonator: user, impersonated: create(:user)
create :admin_reset_log
appeal = create(:appeal, account_list: account_list)
create :appeal_contact, appeal: appeal, contact: contact
create :appeal_excluded_appeal_contact, appeal: appeal, contact: contact
company = create :company
create :company_partnership, company: company, account_list: account_list
create :company_position, company: company, person: person
create(:currency_alias) unless CurrencyAlias.any?
create(:currency_rate) unless CurrencyRate.any?
donor_account = create :donor_account, organization: organization
create :contact_donor_account, contact: contact, donor_account: donor_account
create :donor_account_person, donor_account: donor_account, person: person
designation_account = create :designation_account, organization: organization
create :designation_profile_account,
designation_profile: DesignationProfile.order(:created_at).last,
designation_account: designation_account
create :duplicate_contacts_pair, account_list: account_list
create :duplicate_people_pair, account_list: account_list
donation = create :donation,
donor_account: donor_account,
designation_account: designation_account
pledge = create :pledge, account_list: account_list, contact: contact
create :pledge_donation, pledge: pledge, donation: donation
create :phone_number, person: person
email_address = create :email_address, person: person
create :google_plus_account, email_address: email_address
create :event, account_list: account_list
create :family_relationship, person: person, related_person: create(:person)
google_account = create :google_account, person: person
create :google_contact, person: person
google_email = create :google_email, google_account: google_account
create :google_email_activity,
google_email: google_email,
activity: create(:activity, account_list: account_list)
google_integration = create :google_integration,
account_list: account_list,
google_account: google_account,
calendar_integration: false
create :google_event,
activity: create(:activity, account_list: account_list),
google_integration: google_integration
create :help_request, account_list: account_list
create :import, account_list: account_list
mail_chimp_account = create :mail_chimp_account, account_list: account_list
create :mail_chimp_appeal_list,
mail_chimp_account: mail_chimp_account,
appeal: appeal
create :mail_chimp_member, mail_chimp_account: mail_chimp_account
create :master_address
create :master_company
create :master_person_donor_account,
master_person: master_person,
donor_account: donor_account
create :master_person_source, master_person: master_person, organization: organization
create :message, account_list: account_list
create :name_male_ratio
create :nickname
create :notification_preference,
notification_type: NotificationType.order(:created_at).last,
account_list: account_list
create :notification, contact: contact
create :user_option, user: user
create :partner_status_log, contact: contact
create :facebook_account, person: person
create :key_account, person: person
create :linkedin_account, person: person
create :twitter_account, person: person
create :website, person: person
create :picture, picture_of: person
create :pls_account, account_list: account_list
create :prayer_letters_account, account_list: account_list
create :donation_amount_recommendation
create :donation_amount_recommendation_remote
task = create :task, account_list: account_list
tag = create :tag
create :tagging, tag: tag, taggable: contact
create :tagging, tag: tag, taggable: task
create :background_batch
create :export_log
create :deleted_record
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160427165242_move_org_account_remote_ids.rb
|
class MoveOrgAccountRemoteIds < ActiveRecord::Migration
def change
rename_column :person_relay_accounts, :remote_id, :relay_remote_id
rename_column :person_relay_accounts, :key_remote_id, :remote_id
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/status_valid_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::StatusValid 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, status_valid: false) }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, status_valid: true) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id, status_valid: true) }
describe '#config' do
it 'does not support returning config' do
expect(described_class.config([account_list])).to eq nil
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, { status_valid: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { status_valid: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { status_valid: '' }, nil)).to eq(nil)
end
end
context 'filter by status_valid' do
it 'returns only contacts that have a status_valid set to true' do
expect(described_class.query(contacts, { status_valid: 'true' }, nil).to_a).to match_array [contact_three, contact_four]
end
end
context 'filter by not status_valid' do
it 'returns only contacts that have a status_valid set to false' do
expect(described_class.query(contacts, { status_valid: 'false' }, nil).to_a).to eq [contact_two]
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/currency_rate.rb
|
class CurrencyRate < ApplicationRecord
class << self
def latest_for(currency_code)
rate_on_date(currency_code: currency_code, date: Date.current)
end
def latest_for_pair(from:, to:)
return 1.0 if from == to
from_rate = latest_for(from)
to_rate = latest_for(to)
to_rate / from_rate
end
def convert_with_latest!(amount:, from:, to:)
rate = latest_for_pair(from: from, to: to)
amount.to_f * rate
end
def convert_with_latest(amount:, from:, to:)
convert_with_latest!(amount: amount, from: from, to: to)
rescue CurrencyRate::RateNotFoundError => e
Rollbar.error(e)
0
end
def convert_on_date(amount:, from:, to:, date:)
rate = rate_for_pair_on_date(from: from, to: to, date: date)
amount.to_f * rate
end
def rate_for_pair_on_date(from:, to:, date:)
return 1.0 if from == to
from_rate = rate_on_date(currency_code: from, date: date)
to_rate = rate_on_date(currency_code: to, date: date)
to_rate / from_rate
end
def rate_on_date(currency_code:, date:)
currency_code = currency_code&.upcase
return 1.0 if usd?(currency_code)
@cached_rates ||= {}
@cached_rates[currency_code] ||= {}
@cached_rates[currency_code][date] ||= find_rate_on_date(
currency_code: currency_code, date: date
)
end
def cache_rates_for_dates(currency_code:, from_date:, to_date:)
return if usd?(currency_code)
return if cached_rates_for_date_range?(currency_code, from_date, to_date)
(from_date..to_date).each do |date|
rate_on_date(currency_code: currency_code, date: date)
end
end
def clear_rate_cache
@cached_rates = {}
end
private
def usd?(currency_code)
%w(USD USS USN).include?(currency_code)
end
def find_rate_on_date(currency_code:, date:)
return 1.0 if currency_code.blank?
rate_record =
where(code: currency_code).where('exchanged_on >= ?', date)
.order(:exchanged_on).first ||
where(code: currency_code).where('exchanged_on < ?', date)
.order(exchanged_on: :desc).first
raise RateNotFoundError, currency_code unless rate_record
rate_record.rate
rescue RateNotFoundError => e
# If a rate cannot be found, log that error to rollbar so we can debug it
# easily, but gracefully fall back to a rate of 1.0
Rollbar.info(e)
1.0
end
def cached_rates_for_date_range?(currency_code, from_date, to_date)
return false unless @cached_rates
cached_rates_by_date = @cached_rates[currency_code]
return false unless cached_rates_by_date.present?
(from_date..to_date).all? do |date|
cached_rates_by_date[date].present?
end
end
end
class RateNotFoundError < StandardError
end
end
|
chuckmersereau/api_practice
|
app/models/export_log.rb
|
class ExportLog < ApplicationRecord
self.inheritance_column = :_type_disabled
belongs_to :user
validates :user_id, :export_at, :type, presence: true
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/exports_controller.rb
|
require 'csv'
class Api::V2::Contacts::ExportsController < Api::V2Controller
supports_accept_header_content_types :any
supports_content_types :any
resource_type 'export_logs'
include ActionController::MimeResponds
include ActionController::Helpers
include Filtering::Contacts
include ContactsHelper
helper ContactsHelper
def index
persist_export
deactivate_export
end
def show
load_export
authorize_export
deactivate_export
render_export
end
def create
persist_export
end
protected
def load_export
@export ||= ExportLog.find(params[:id])
end
def deactivate_export
@export.update(active: false)
end
def authorize_export
authorize @export, :show?
end
def build_export
@export = ExportLog.new
@export.attributes = export_params
end
def save_export
@export.save
end
def persist_export
build_export
authorize_export
if save_export
render_export
else
render_with_resource_errors(@export)
end
end
def export_params
{
type: export_log_type,
params: (params.dig(:export_log, :params) || params).to_json,
user: current_user,
export_at: DateTime.now
}
end
def export_log_type
'Contacts'
end
def render_export
request.format = :json unless params[:format]
respond_to do |format|
format.csv do
load_contacts
render_csv("contacts-#{file_timestamp}.csv")
end
format.xlsx do
load_contacts
render_xlsx("contacts-#{file_timestamp}.xlsx")
end
format.json do
render json: @export,
status: success_status,
include: include_params,
fields: field_params
end
end
end
def render_csv(filename)
headers['Content-Type'] ||= 'text/csv'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
render csv: 'index', filename: filename
end
def render_xlsx(filename)
render xlsx: 'index', filename: filename
end
def load_contacts
@contacts ||= filter_contacts.order(name: :asc).preload(:primary_person, :spouse, :primary_address,
:tags, people: [:email_addresses, :phone_numbers])
end
def filter_contacts
Contact::Filterer.new(filter_params).filter(scope: contact_scope, account_lists: account_lists)
end
def account_list_filter
JSON.parse(@export.params).dig('filter', 'account_list_id')
end
def contact_scope
current_user.contacts.where(account_list: account_lists)
end
def permitted_filters
@permitted_filters ||=
Contact::Filterer::FILTERS_TO_DISPLAY.collect(&:underscore).collect(&:to_sym) +
Contact::Filterer::FILTERS_TO_HIDE.collect(&:underscore).collect(&:to_sym) +
[:account_list_id, :any_tags]
end
def file_timestamp
Time.now.strftime('%Y%m%d')
end
def filter_params
super(JSON.parse(@export.params).dig('filter'))
end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/webhook/primary_list.rb
|
# This class holds all the methods associated to the Mail Chimp webhooks that are linked to the primary list of a Mail Chimp Account.
module MailChimp::Webhook
class PrimaryList < Base
def subscribe_hook(email)
people_to_subscribe = account_list.people.joins(:email_addresses).where(email_addresses: { email: email, primary: true })
return MailChimp::MembersImportWorker.perform_async(mail_chimp_account.id, [email]) if people_to_subscribe.empty?
contacts_of_people_to_subscribe = Contact.joins(:contact_people).where(contact_people: { person: people_to_subscribe })
contacts_of_people_to_subscribe.where(send_newsletter: 'Physical').update_all(send_newsletter: 'Both')
contacts_of_people_to_subscribe.where(send_newsletter: ['None', nil]).update_all(send_newsletter: 'Email')
people_to_subscribe.update_all(optout_enewsletter: false)
end
def unsubscribe_hook(email, reason, list_id)
unless reason == 'abuse'
wrapper = MailChimp::GibbonWrapper.new(mail_chimp_account)
member = wrapper.list_member_info(mail_chimp_account.primary_list_id, email).first
return unless member
# don't trigger the opt-out update if mpdx or the list manager unsubscribed them
return if member['status'] == 'subscribed' || MailChimpMember.mpdx_unsubscribe?(member)
end
people = account_list.people.joins(:email_addresses).where(email_addresses: { email: email, primary: true })
# No need to trigger a callback because MailChimp has already unsubscribed this email
people.update_all(optout_enewsletter: true)
people.each do |person|
next unless %w(Email Both).include? person.contact.send_newsletter
next if person.contact.people.any? do |contact_person|
# don't remove newsletter status if there are any other
# people who are not opted out who have email addresses
!contact_person.optout_enewsletter && contact_person.email_addresses.any?
end
person.contact.update(send_newsletter: person.contact.send_newsletter == 'Both' ? 'Physical' : nil)
end
clean_up_members(email, list_id)
end
def email_update_hook(old_email, new_email)
ids_of_people_to_update = @account_list.people.joins(:email_addresses)
.where(email_addresses: { email: old_email, primary: true }).pluck(:id)
Person.where(id: ids_of_people_to_update).includes(:email_addresses).each do |person|
update_person_email(person, old_email, new_email)
end
end
def email_cleaned_hook(email, reason, list_id)
return unsubscribe_hook(email, reason, list_id) if reason == 'abuse'
MailChimp::Webhook::Base::EmailBounceHandler.new(account_list, email, reason).handle_bounce
clean_up_members(email, list_id)
end
private
def clean_up_members(email, list_id)
mail_chimp_account.mail_chimp_members.where(list_id: list_id, email: email).each(&:destroy)
end
def update_person_email(person, old_email, new_email)
old_email_record = person.email_addresses.find_by(email: old_email)
new_email_record = person.email_addresses.find_by(email: new_email)
if new_email_record
new_email_record.update(primary: true)
else
person.email_addresses.create(email: new_email, primary: true)
end
old_email_record.update(primary: false)
end
end
end
|
chuckmersereau/api_practice
|
app/validators/single_primary_validator.rb
|
<gh_stars>0
class SinglePrimaryValidator < ActiveModel::EachValidator
attr_reader :record, :attribute, :value
def initialize(options)
options[:primary_field] ||= :primary
options[:message] ||= 'must have one and only one set as valid and primary'
super
end
def validate_each(record, attribute, value)
@record = record
@attribute = attribute
@value = value
add_error unless valid?
end
private
def valid?
not_deleted = value.reject(&:marked_for_destruction?)
return false if not_deleted.select(&:historic).any?(&options[:primary_field])
non_historic = not_deleted.reject(&:historic)
non_historic.empty? || non_historic.count(&options[:primary_field]) == 1
end
def add_error
message = options[:message]
if message
record.errors[attribute] << message
else
record.errors.add(attribute, :invalid)
end
end
end
|
chuckmersereau/api_practice
|
app/models/contact_person.rb
|
<reponame>chuckmersereau/api_practice
class ContactPerson < ApplicationRecord
include HasPrimary
@@primary_scope = :contact
belongs_to :contact, touch: true
belongs_to :person
after_commit :delete_orphaned_person, on: :destroy
before_create :set_primary_contact
validates :person, presence: true
# Scopes
scope :find_ids_with_search_term, -> (search_term) { where(person: search_term) }
private
def delete_orphaned_person
# See if there is any other contact_person with the same person id
return if ContactPerson.where(person_id: person_id).where('id <> ?', id).any?
# if there isn't, delete the associated person
person&.destroy
end
def set_primary_contact
self.primary = true if contact && !contact.primary_person
end
end
|
chuckmersereau/api_practice
|
app/services/application_filterer.rb
|
class ApplicationFilterer
attr_accessor :account_lists, :filters, :initial_scope
FILTERS_TO_DISPLAY = [].freeze
FILTERS_TO_HIDE = [].freeze
def initialize(filters = nil)
@first_filter_queried = false
@filters = filters&.with_indifferent_access || {}
@filters.map { |k, v| @filters[k] = v.strip if v.is_a?(String) }
end
def filter(scope:, account_lists:)
@initial_scope = scope
@account_lists = account_lists
self.class.filter_classes.each do |klass|
scope = add_to_scope(klass, scope)
end
scope
end
def self.config(account_lists)
filter_classes.map do |klass|
filter = klass.new(account_lists)
filter if filter.display_filter_option? && !filter.empty?
end.compact
end
def self.filter_classes
@filter_classes ||= (self::FILTERS_TO_DISPLAY + self::FILTERS_TO_HIDE).sort.map do |class_name|
prefix = to_s.split('::')[0...-1].join('::')
"#{prefix}::Filter::#{class_name}".constantize
end
end
def self.filter_params
@filter_params ||= (self::FILTERS_TO_DISPLAY + self::FILTERS_TO_HIDE).sort.map do |class_name|
class_name.underscore.to_sym
end
end
private
def add_to_scope(klass, scope)
if filters[:any_filter].to_s == 'true'
scope_to_add = klass.new(account_lists).query(initial_scope, filters)
return scope unless scope_to_add
return scope_to_add if scope.to_sql == initial_scope.to_sql
resource_class.where(id: (scope.ids + scope_to_add.ids).uniq)
else
klass.new(account_lists).query(scope, filters) || scope
end
end
def resource_class
self.class.to_s.split('::').first.constantize
end
end
|
chuckmersereau/api_practice
|
spec/services/reports/pledge_histories_period_spec.rb
|
require 'rails_helper'
RSpec.describe Reports::PledgeHistoriesPeriod, type: :model do
let(:account_list) { create(:account_list, salary_currency: 'USD') }
let(:end_date) { Date.new(2018, 3, 30).end_of_day }
let(:params) { { account_list: account_list, end_date: end_date } }
let(:contact_1) { create(:contact, account_list: account_list) }
let(:contact_2) { create(:contact, account_list: account_list) }
let(:contact_3) { create(:contact, account_list: account_list) }
# use method to bust caching inside of the report
def report
described_class.new(params)
end
shared_examples 'expect method to return amounts' do |options|
context 'multiple partner_status_logs ahead' do
let!(:partner_status_log_1) do
contact_1.partner_status_logs.create(
pledge_amount: 10,
pledge_frequency: 2,
pledge_received: options[:pledge_received],
recorded_on: end_date + 1.week
)
end
before do
contact_1.partner_status_logs.create(
pledge_amount: 20,
pledge_frequency: 1,
pledge_received: options[:pledge_received],
recorded_on: end_date + 2.weeks
)
contact_2.partner_status_logs.create(
pledge_amount: 10,
pledge_frequency: 1,
pledge_received: options[:pledge_received],
recorded_on: end_date + 2.weeks
)
contact_2.partner_status_logs.create(
pledge_amount: 20,
pledge_frequency: 1,
pledge_received: options[:pledge_received],
recorded_on: end_date + 3.weeks
)
contact_3.partner_status_logs.create(
pledge_amount: 10,
pledge_frequency: 2,
pledge_received: !options[:pledge_received],
recorded_on: end_date + 3.weeks
)
end
it 'should return first partner_status_log amount' do
expect(report.send(options[:method])).to eq 15
end
context 'partner_status_log has different currency' do
before do
CurrencyRate.create(exchanged_on: end_date, code: 'CAD', rate: 0.5, source: 'test')
partner_status_log_1.update_attribute(:pledge_currency, 'CAD')
end
it 'should return partner_status_log amount coverted to account_list currency' do
expect(report.send(options[:method])).to eq 20
end
end
end
context 'no partner_status_logs ahead' do
let!(:contact_1) do
create(:contact,
account_list: account_list,
pledge_amount: 10,
pledge_frequency: 2,
pledge_received: options[:pledge_received])
end
let!(:contact_2) do
create(:contact,
account_list: account_list,
pledge_amount: 10,
pledge_frequency: 1,
pledge_received: options[:pledge_received])
end
let!(:contact_3) do
create(:contact,
account_list: account_list,
pledge_amount: 10,
pledge_frequency: 2,
pledge_received: !options[:pledge_received])
end
context 'contact.created_at > date' do
before do
contact_1.update_attribute(:created_at, end_date + 2.weeks)
contact_2.update_attribute(:created_at, end_date + 2.weeks)
contact_3.update_attribute(:created_at, end_date + 2.weeks)
end
it 'should return no amount' do
expect(report.send(options[:method])).to eq 0
end
end
context 'contact.created_at < date' do
before do
contact_1.update_attribute(:created_at, end_date - 2.weeks)
contact_2.update_attribute(:created_at, end_date - 2.weeks)
contact_3.update_attribute(:created_at, end_date - 2.weeks)
end
it 'should return contact amount' do
expect(report.send(options[:method])).to eq 15
end
context 'contact has different currency' do
before do
CurrencyRate.create(exchanged_on: end_date, code: 'CAD', rate: 0.5, source: 'test')
contact_1.update_attribute(:pledge_currency, 'CAD')
end
it 'should return partner_status_log amount coverted to account_list currency' do
expect(report.send(options[:method])).to eq 20
end
end
end
end
end
describe '#pledged' do
include_examples 'expect method to return amounts', method: :pledged, pledge_received: false
end
describe '#received' do
include_examples 'expect method to return amounts', method: :received, pledge_received: true
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170912232954_create_donation_amount_recommendations.rb
|
class CreateDonationAmountRecommendations < ActiveRecord::Migration
def change
create_table :donation_amount_recommendations do |t|
t.belongs_to :organization
t.string :donor_number
t.string :designation_number
t.decimal :previous_amount
t.decimal :amount
t.timestamp :started_at
t.decimal :gift_min
t.decimal :gift_max
t.decimal :income_min
t.decimal :income_max
t.decimal :suggested_pledge_amount_min
t.decimal :suggested_pledge_amount_max
t.decimal :suggested_special_amount_min
t.decimal :suggested_special_amount_max
t.timestamp :ask_at
t.string :zip_code
t.uuid :uuid, default: 'uuid_generate_v4()', null: false
t.timestamps null: false
end
add_index :donation_amount_recommendations,
[:organization_id, :designation_number, :donor_number],
unique: true,
name: 'index_donation_amount_recommendations'
add_index :donation_amount_recommendations, :uuid, unique: true
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180214193958_create_fix_counts.rb
|
class CreateFixCounts < ActiveRecord::Migration
def change
create_table :fix_counts do |t|
t.integer :account_list_id
t.integer :old_members, default: 0
t.integer :new_members, default: 0
t.integer :people_changed, default: 0
t.integer :contacts_changed, default: 0
t.integer :contacts_tagged, default: 0
t.timestamps null: false
t.index :account_list_id, unique: true
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170711194415_add_no_gift_aid_to_contacts.rb
|
class AddNoGiftAidToContacts < ActiveRecord::Migration
def change
add_column :contacts, :no_gift_aid, :boolean
end
end
|
chuckmersereau/api_practice
|
app/serializers/acts_as_taggable_on/tag_serializer.rb
|
class ActsAsTaggableOn::TagSerializer < ActiveModel::Serializer
type 'tags'
attributes :id, :name
end
|
chuckmersereau/api_practice
|
spec/services/person/filter/phone_number_valid_spec.rb
|
require 'rails_helper'
RSpec.describe Person::Filter::PhoneNumberValid 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!(:person_one) { create(:person, contacts: [contact_one]) }
let!(:person_two) { create(:person, contacts: [contact_one]) }
let!(:person_three) { create(:person, contacts: [contact_two]) }
let!(:person_four) { create(:person, contacts: [contact_two]) }
let!(:phone_number_one) { create(:phone_number, person: person_one) }
let!(:phone_number_two) { create(:phone_number, person: person_one) }
let!(:phone_number_three) { create(:phone_number, person: person_one) }
let!(:phone_number_four) { create(:phone_number, person: person_three) }
let!(:phone_number_five) { create(:phone_number, person: person_four) }
let!(:phone_number_six) { create(:phone_number, person: person_two) }
before do
phone_number_one.update_columns(valid_values: true, primary: true)
phone_number_two.update_columns(valid_values: true, primary: true)
phone_number_three.update_columns(valid_values: true, primary: false)
phone_number_four.update_columns(valid_values: false, primary: false)
phone_number_five.update_columns(valid_values: false, primary: false)
phone_number_six.update_columns(valid_values: true, primary: true)
end
describe '#query' do
let(:scope) { Person.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(scope, {}, nil)).to eq(nil)
expect(described_class.query(scope, { phone_number_valid: {} }, nil)).to eq(nil)
expect(described_class.query(scope, { phone_number_valid: [] }, nil)).to eq(nil)
expect(described_class.query(scope, { phone_number_valid: '' }, nil)).to eq(nil)
end
end
context 'filter by phone number invalid' do
it 'returns only people that have an invalid phone number' do
results = described_class.query(scope, { phone_number_valid: 'false' }, nil).to_a
expect(results).to match_array [person_one, person_three, person_four]
end
end
end
end
|
chuckmersereau/api_practice
|
app/workers/audit_change_worker.rb
|
<reponame>chuckmersereau/api_practice<filename>app/workers/audit_change_worker.rb
class AuditChangeWorker
include Sidekiq::Worker
sidekiq_options queue: :api_audit_change_worker
def perform(attrs)
send_audit_to_elastic(attrs)
end
private
def send_audit_to_elastic(attrs)
ensure_index
Audited::AuditElastic.create(attrs)
end
def ensure_index
# ensure the needed index is there
Audited::AuditElastic.gateway.create_index!
rescue Elasticsearch::Transport::Transport::Errors::BadRequest => e
# catch race condition where index already exists and it got past the internal `index_exists?`
raise e unless e.message.include? 'index_already_exists_exception'
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/donation.rb
|
<reponame>chuckmersereau/api_practice
class Contact::Filter::Donation < Contact::Filter::Base
attr_accessor :contacts, :filters, :all_filters
def execute_query(query_contacts, query_filters)
self.contacts = query_contacts.includes(donor_accounts: [:donations])
self.filters = query_filters
filter_contacts
end
def title
_('Gift Options')
end
def parent
_('Gift Details')
end
def type
'multiselect'
end
def custom_options
[{ name: _('No Gifts'), id: 'none' },
{ name: _('One or More Gifts'), id: 'one' },
{ name: _('First Gift'), id: 'first' },
{ name: _('Last Gift'), id: 'last' }]
end
private
def filters=(filters)
@all_filters = filters
@filters = parse_list(filters[:donation])
end
def filter_contacts
no_gifts
one_or_more_gifts
first_gift
last_gift
contacts
end
def no_gifts
return unless filters.include?('none')
contact_ids_with_donation = contact_ids_with_donation_to_account_lists(all_filters[:donation_date])
self.contacts = contacts.where.not(id: contact_ids_with_donation)
end
def one_or_more_gifts
return unless filters.include?('one')
self.contacts = contacts.where(id: contact_ids_with_donation_to_account_lists)
end
def first_gift
return unless filters.include?('first')
self.contacts = contacts.where(donations: { id: first_donation_ids_for_each_donor_account })
end
def last_gift
return unless filters.include?('last')
self.contacts = contacts.where(donations: { id: last_donation_ids_for_each_donor_account })
end
def contact_ids_with_donation_to_account_lists(date_range = nil)
date_range = nil unless date_range?(date_range)
@contact_ids_with_donations_cache ||= {}
@contact_ids_with_donations_cache[date_range] ||=
::Donation.unscoped
.where(account_lists_donations_as_sql_condition)
.joins(donor_account: [:contacts])
.where(contacts: { account_list_id: account_lists })
.where(date_range ? { donation_date: date_range } : nil)
.distinct
.pluck('"contacts"."id"')
end
# The last donation queries use the SQL aggregation MAX functions to
# find donation_date grouped by the donor_account_id.
def last_donation_ids_for_each_donor_account
::Donation.where(account_lists_donations_as_sql_condition).joins(
<<~JOIN
INNER JOIN (SELECT donor_account_id, MAX(donation_date) AS max_donation_date
FROM donations
WHERE #{account_lists_donations_as_sql_condition}
GROUP BY donor_account_id) grouped_donations
ON donations.donor_account_id = grouped_donations.donor_account_id
AND donations.donation_date = grouped_donations.max_donation_date
JOIN
).pluck(:id)
end
# The first donation queries use the SQL aggregation MIN functions to
# find donation_date grouped by the donor_account_id.
def first_donation_ids_for_each_donor_account
::Donation.where(account_lists_donations_as_sql_condition).joins(
<<~JOIN
INNER JOIN (SELECT donor_account_id, MIN(donation_date) AS min_donation_date
FROM donations
WHERE #{account_lists_donations_as_sql_condition}
GROUP BY donor_account_id) grouped_donations
ON donations.donor_account_id = grouped_donations.donor_account_id
AND donations.donation_date = grouped_donations.min_donation_date
JOIN
).pluck(:id)
end
# Build the SQL condition needed to return all donations for all account_lists.
def account_lists_donations_as_sql_condition
account_lists_donations_sql = account_lists.collect do |account_list|
account_list.donations.where_values.collect(&:to_sql).join(' AND ')
end
account_lists_donations_sql.collect { |sql| "(#{sql})" }.join(' OR ')
end
end
|
chuckmersereau/api_practice
|
app/serializers/deleted_record_serializer.rb
|
<reponame>chuckmersereau/api_practice
class DeletedRecordSerializer < ApplicationSerializer
attributes :deleted_at, :deletable_type, :deletable_id, :deleted_from_id, :deleted_from_type
belongs_to :deletable, polymorphic: true
belongs_to :deleted_from, polymorphic: true
belongs_to :deleted_by, class_name: 'Person', foreign_key: 'deleted_by_id'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.