repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
app/services/reports/monthly_giving_graph.rb
|
<filename>app/services/reports/monthly_giving_graph.rb
class Reports::MonthlyGivingGraph < ActiveModelSerializers::Model
attr_accessor :account_list,
:filter_params,
:locale
attr_writer :display_currency
delegate :monthly_goal, to: :account_list
def initialize(attributes)
super
self.filter_params ||= {}
end
def totals
currencies.map(&method(:totals_for_currency))
.sort_by { |totals| totals[:total_converted] }
.reverse
end
def pledges
account_list.total_pledges.to_i
end
def monthly_average
total_converted.sum.fdiv(number_of_months_in_range).to_i
end
def months_to_dates
filter_params[:donation_date].select { |d| d.day == 1 }
end
def salary_currency
account_list.salary_currency_or_default
end
def display_currency
@display_currency || salary_currency
end
def multi_currency
account_list.multi_currency?
end
def filter_params=(filter_params)
filter_params.delete(:account_list_id)
filter_params[:donation_date] = 11.months.ago.beginning_of_month.to_date..Date.today.end_of_month unless filter_params[:donation_date]
@filter_params = filter_params
end
protected
def total_converted
return total_converted_by_month_excluding_last_month if end_date == Date.today.end_of_month
total_converted_by_month
end
def total_converted_by_month_excluding_last_month
totals.map { |t| t[:month_totals][0...-1].map { |m| m[:converted] }.sum }
end
def total_converted_by_month
totals.map { |t| t[:total_converted] }
end
def number_of_months_in_range
(end_date.year * 12 + end_date.month) -
(start_date.year * 12 + start_date.month) +
(end_date == Date.today.end_of_month ? 0 : 1)
end
def start_date
filter_params[:donation_date].first
end
def end_date
filter_params[:donation_date].end
end
def currencies
# It is possible for some donations to have a `nil` value for their
# currency, but that that is a rarer case and something we should fix
# earlier in the process than here. What we do to handle that case is to
# just ignore donations with no currencies to prevent an invalid call on
# `nil` in the chart itself.
@currencies ||= donation_scope.currencies.select(&:present?)
end
def totals_for_currency(currency)
month_totals = currency_month_totals(currency)
{
currency: currency,
total_amount: month_totals.map { |t| t[:amount] }.sum,
total_converted: month_totals.map { |t| t[:converted] }.sum,
month_totals: month_totals
}
end
def currency_month_totals(currency)
filter_params[:donation_date].select { |d| d.day == 1 }.map do |start_date|
end_date = start_date.end_of_month
amount = donation_scope.where(donation_date: start_date..end_date)
.where(currency: currency)
.sum(:amount)
mid_month = Date.new(start_date.year, start_date.month, 15)
converted = CurrencyRate.convert_on_date(amount: amount, from: currency,
to: display_currency, date: mid_month)
{ amount: amount, converted: converted }
end
end
def donation_scope
account_list.donations.where(filter_params)
end
end
|
chuckmersereau/api_practice
|
spec/serializers/user/authenticate_serializer_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe User::AuthenticateSerializer do
let(:user) { create(:user) }
let(:resource) { User::Authenticate.new(user: user) }
subject { User::AuthenticateSerializer.new(resource).as_json }
it { should include :json_web_token }
describe 'json_web_token' do
it 'delegates to user' do
expect(subject[:json_web_token]).to eq resource.json_web_token
end
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_referrer_spec.rb
|
require 'rails_helper'
RSpec.describe Task::Filter::ContactReferrer do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list: account_list) }
let!(:contact_two) { create(:contact, account_list: account_list) }
let!(:contact_three) { create(:contact, account_list: account_list) }
let!(:contact_four) { create(:contact, account_list: account_list) }
before do
ContactReferral.create! referred_by: contact_one, referred_to: contact_two
end
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 'task filter by no contact referrer' do
it 'only returns tasks with contacts that have no referrer' do
result = described_class.query(tasks, { contact_referrer: 'none' }, account_list).to_a
expect(result).to match_array [task_one, task_three, task_four]
end
end
context 'task filter by any contact referrer' do
it 'only returns tasks with contacts that have any referrer' do
expect(described_class.query(tasks, { contact_referrer: 'any' }, account_list).to_a).to eq [task_two]
end
end
context 'task filter by referrer' do
it 'filters tasks with contacts that have a single referrer' do
result = described_class.query(tasks, { contact_referrer: contact_one.id.to_s }, account_list).to_a
expect(result).to eq [task_two]
end
it 'filters tasks with contacts that have multiple referrers' do
query = { contact_referrer: "#{contact_one.id}, #{contact_one.id}" }
result = described_class.query(tasks, query, account_list).to_a
expect(result).to eq [task_two]
end
end
context 'task filter by multiple filters' do
it 'returns tasks matching multiple filters' do
result = described_class.query(tasks, { contact_referrer: "#{contact_one.id}, none" }, account_list).to_a
expect(result).to match_array [task_one, task_two, task_three, task_four]
end
end
end
end
|
chuckmersereau/api_practice
|
dev/migrate/2016_05_17_add_org_locales.rb
|
<reponame>chuckmersereau/api_practice
# This updates the organization locales based on the manually entered data
# below. I tracked the org id and name for the data entry but then wanted to
# run this on stage first and realized some ids would be different, so it
# looks by name and id (should have done it by query_ini_url).
def update_org_locales
org_countries_and_locales.each do |org_id, org_name, country, locale|
org = Organization.find_by(id: org_id)
if org && org.name != org_name
org_by_name = Organization.find_by(name: org_name)
if org_by_name
org = org_by_name
else
# This happens because my copy-paste to prod_console doesn't like
# accented characters.
puts "Organization name differs for id #{org_id}. "\
"Expected #{org_name} but was #{org.name}"
end
else
org = Organization.find_by(name: org_name)
end
unless org
puts "Organization id #{org_id} and name #{org_name} not found"
next
end
puts "Updating org #{org.name} (#{org.id}) "
puts " country from #{org.country} to #{country}"
puts " locale from #{org.locale} to #{locale}"
org.update(country: country, locale: locale)
end
nil
end
# This is from data partially generated through the guess_org_country and
# guess_org_locale methods, but then reviewed and corrected by a person.
def org_countries_and_locales
[
[60, 'DonorElf', 'United States', 'en'],
[5, 'Agape Leadership Dev - Surinam', 'Suriname', 'nl'],
[81, 'Olive Branch International', 'United States', 'en'],
[22, 'Campus Crusade for Christ - Canada (Intl.)', 'United States', 'en'],
[6, 'Agapè Nederland', 'Netherlands', 'nl'],
[2, 'Agape Europe AOA', 'United States', 'en'],
[8, 'Agape Österreich - GAIN', 'Austria', 'de'],
[15, 'Calvary International', 'United States', 'en'],
[61, 'e3 Partners Ministry', 'United States', 'en'],
[59, 'DiscipleMakers', 'United States', 'en'],
[65, 'Food for the Hungry', 'United States', 'en'],
[67, 'Global Hope Network International', 'United States', 'en'],
[68, 'Global Impact Resources', 'United States', 'en'],
[70, 'Gospel for Asia', 'United States', 'en'],
[74, 'Kingdom Building Ministries', 'United States', 'en'],
[62, 'Every Nation Ministries - Philippines', 'Philippines', 'tl'],
[63, 'Every Nation Ministries - USA', 'United States', 'en'],
[79, 'Novy zivot', 'Czech Republic', 'cs'],
[80, 'Obra Social Agape', 'United States', 'en'],
[77, 'Missions Door', 'United States', 'en'],
[86, 'Tactical Chaplains Service', 'United States', 'en'],
[93, 'Trinity Church - Dallas, TX', 'United States', 'en'],
[95, 'Word Made Flesh', 'United States', 'en'],
[97, '<NAME>', 'United States', 'en'],
[1, 'Agape Bulgaria', 'Bulgaria', 'bg'],
[14, 'Cadence International', 'United States', 'en'],
[13, 'Asociatia Alege Viata Romania', 'Romania', 'ro'],
[256, 'Hope of Glory', 'United States', 'en'],
[31, 'Campus Crusade for Christ - Jamaica', 'Jamaica', 'en'],
[37, 'Campus Crusade for Christ - Pacific Islands', 'United States', 'en'],
[38, 'Campus Crusade for Christ - PNG', 'United States', 'en'],
[52, 'CCO Canada', 'Canada', 'en'],
[39, 'Campus Crusade for Christ - Russia', 'Russia', 'ru'],
[71, 'Hesed Consulting', 'United States', 'en'],
[88, 'The Impact Movement', 'United States', 'en'],
[53, 'Cruzada Estudiantil - Costa Rica', 'Costa Rica', 'es'],
[54, 'Cruzada Estudiantil - Dominican Republic', 'Dominican Republic', 'es'],
[73, 'Instituti Jeta e Re', 'Albania', 'en'],
[78, 'Nova Nadezh', 'Bulgaria', 'bg'],
[75, 'Life Action Ministries', 'United States', 'en'],
[142, 'Gospel For Asia USA', 'United States', 'en'],
[87, 'Center for Mission Mobilization', 'United States', 'en'],
[141, 'Gospel For Asia CAN', 'Canada', 'en'],
[99, '306 Foundation', 'United States', 'en'],
[3, 'Agape France', 'France', 'fr'],
[149, 'Tandem Ministries - Family Life', 'New Zealand', 'en'],
[64, 'FOCUS', 'United States', 'en'],
[154, 'Kingdom Mobilization', 'United States', 'en'],
[153, 'International Graduate School of Leadership (IGSL)', 'United States', 'en'],
[271, 'Living Truth', 'United States', 'en'],
[85, 'SIM USA', 'United States', 'en'],
[98, 'Zoweh Ministries', 'United States', 'en'],
[280, 'Ratio Christi', 'United States', 'en'],
[7, '<NAME>reich', 'Austria', 'de'],
[4, 'Agape Greece', 'Greece', 'el'],
[155, 'Living Waters Canada', 'Canada', 'en'],
[157, 'The Navigators - South Africa', 'South Africa', 'af'],
[294, 'Lutheran Bible Translators', 'United States', 'en'],
[82, 'Perspectives', 'United States', 'en'],
[148, 'Tandem Ministries', 'New Zealand', 'en'],
[76, 'Mission Aviation Fellowship', 'United States', 'en'],
[47, 'Campus Crusade for Christ - Trinidad', 'Trinidad', 'en'],
[160, 'New Life Moldova', 'Moldova', 'ro'],
[161, 'Ruch Nowego Zycia - POLAND', 'Poland', 'pl'],
[265, 'Grace Ministries', 'United States', 'en'],
[170, 'Agape Lithuania', 'Lithuania', 'lt'],
[9, 'Agape Portugal', 'Portugal', 'pt_PT'],
[169, 'Agape Ireland', 'Ireland', 'en'],
[310, 'Reach Beyond', 'United States', 'en'],
[10, 'Agape Spain', 'Spain', 'es_ES'],
[334, 'Converge Worldwide', 'United States', 'en'],
[324, 'Global Training Network', 'United States', 'en'],
[44, 'Campus Crusade for Christ - Taiwan', 'Taiwan', 'zh'],
[72, 'India Campus Crusade For Christ - Bangalore', 'India', 'hi'],
[35, 'Campus Crusade for Christ - Nepal', 'Nepal', 'en'],
[249, 'Agape Eesti', 'Estonia', 'et'],
[214, 'Cross Trail Outfitters of Illinois', 'United States', 'en'],
[94, 'UFC', 'United States', 'en'],
[69, 'Global Service Network', 'United States', 'en'],
[250, 'Be One Together', 'United States', 'en'],
[211, 'Forest Springs', 'United States', 'en'],
[213, 'SIM Canada', 'Canada', 'en'],
[145, 'LA 2020', 'United States', 'en'],
[146, 'Master Plan Ministries', 'United States', 'en'],
[11, 'Agape UK', 'United Kingdom', 'en'],
[1015, 'Eurasia Partners Network', 'United States', 'en'],
[1358, 'SHIFT Ministries', 'United States', 'en'],
[1359, 'Time To Revive', 'United States', 'en'],
[1360, 'TntWare', 'United States', 'en'],
[92, 'ToonTown Ministries', 'United States', 'en'],
[96, 'Wycliffe Associates', 'United States', 'en'],
[1362, 'Kingdom Rain', 'United States', 'en'],
[1363, 'Storyline', 'United States', 'en'],
[1364, 'LIFE MINISTRY ZIMBABWE', 'Zimbabwe', 'en'],
[1357, 'e3 PARTNERS', 'United States', 'en'],
[21, 'Campus Crusade for Christ - Canada', 'Canada', 'en'],
[28, 'Campus Crusade for Christ - Guyana', 'Guyana', 'en'],
[26, 'Campus Crusade for Christ - Fiji', 'Fiji', 'en'],
[16, 'Campus Crusade for Christ - Argentina', 'Argentina', 'es'],
[90, 'The Navigators - Canada', 'Canada', 'en'],
[19, 'Campus Crusade for Christ - Bolivia', 'Bolivia', 'es'],
[45, 'Campus Crusade for Christ - Thailand', 'Thailand', 'th'],
[41, 'Campus Crusade for Christ - Solomon Islands', 'Solomon Islands', 'en'],
[46, 'Campus Crusade for Christ - Tonga', 'Tonga', 'en'],
[51, 'Campus fuer Christus e.V. - Germany', 'Germany', 'de'],
[56, 'Cruzada Estudiantil - Guatemala', 'Guatemala', 'es'],
[58, 'Cruzada Estudiantil - Mexico', 'Mexico', 'es'],
[91, 'The Navigators - Singapore', 'Singapore', 'en'],
[117, 'Campus Crusade for Christ - Mongolia', 'Mongolia', 'mn'],
[152, 'Campus Crusade for Christ - Slovenia', 'Slovenia', 'sl'],
[12, 'Alfa y Omega - Panama', 'Panama', 'es'],
[18, 'Campus Crusade for Christ - Bangladesh', 'Bangladesh', 'bn'],
[159, 'Campus Crusade for Christ - Philippines', 'Philippines', 'tl'],
[43, 'Campus Crusade for Christ - Sri Lanka', 'Sri Lanka', 'si'],
[20, 'Campus Crusade for Christ - Brasil', 'Brazil', 'pt'],
[34, 'Campus Crusade for Christ - Latvia', 'Latvia', 'lv'],
[32, 'Campus Crusade for Christ - Japan', 'Japan', 'ja'],
[29, 'Campus Crusade for Christ - Hong Kong', 'Hong Kong', 'en'],
[40, 'Cru - Singapore', 'Singapore', 'en'],
[158, 'Campus Crusade for Christ - Ethiopia', 'Ethiopia', 'am'],
[173, 'Campus Crusade for Christ - Sierra Leone', 'Sierra Leone', 'en'],
[30, 'Campus Crusade for Christ - Italy', 'Italy', 'it'],
[55, 'Cruzada Estudiantil - El Salvador', 'El Salvador', 'es'],
[23, 'Campus Crusade for Christ - Chile', 'Chile', 'es'],
[24, 'Campus Crusade for Christ - Colombia', 'Colombia', 'es'],
[25, 'Campus Crusade for Christ - Ecuador', 'Ecuador', 'es'],
[27, 'Campus Crusade for Christ - Ghana', 'Ghana', 'en'],
[171, 'Campus Crusade for Christ - Liberia', 'Liberia', 'en'],
[172, 'Campus Crusade for Christ - Nigeria', 'Nigeria', 'en'],
[42, 'Campus Crusade for Christ - South Africa', 'South Africa', 'af'],
[49, 'Campus Crusade for Christ - Venezuela', 'Venezuela', 'es'],
[50, 'Campus Crusade for Christ - Zambia', 'Zambia', 'en'],
[57, 'Cruzada Estudiantil - Honduras', 'Honduras', 'es'],
[33, 'Campus Crusade for Christ - Kenya', 'Kenya', 'en'],
[17, 'Power to Change - Australia', 'Australia', 'en'],
[206, 'International Friendships, Inc (IFI)', 'United States', 'en'],
[167, 'TeachBeyond - Canada', 'Canada', 'en'],
[168, 'TeachBeyond - USA', 'United States', 'en'],
[1365, 'The Global Mission', 'United States', 'en'],
[156, 'United World Mission', 'United States', 'en'],
[1368, 'University Christian Outreach', 'United States', 'en']
]
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/exclude_tags_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::ExcludeTags 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, tag_list: 'tag1,tag2') }
let!(:contact_two) { create(:contact, account_list_id: account_list.id, tag_list: 'tag1') }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, tag_list: 'tag3') }
let!(:contact_four) { create(:contact, account_list_id: account_list.id, tag_list: '') }
describe '#config' do
it 'does not have 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, { exclude_tags: {} }, nil)).to eq nil
expect(described_class.query(contacts, { exclude_tags: [] }, nil)).to eq nil
expect(described_class.query(contacts, { exclude_tags: '' }, nil)).to eq nil
end
end
context 'filter exclude tags' do
it 'returns only contacts that do not have the tag' do
expect(described_class.query(contacts, { exclude_tags: 'tag1' }, nil).to_a).to match_array [contact_three, contact_four]
end
it 'returns only contacts that do not have multiple tags' do
expect(described_class.query(contacts, { exclude_tags: 'tag1,tag2,tag3' }, nil).to_a).to match_array [contact_four]
end
it 'accepts tags as comma separated string' do
expect(described_class.query(contacts, { exclude_tags: 'tag1,tag2,tag3' }, nil).to_a).to match_array [contact_four]
end
context 'with a backslash' do
before { contact_four.update!(tag_list: 'foo\bar') }
it 'does not fail with tags that include backslashes' do
expected_array = [contact_one, contact_two, contact_three]
expect(described_class.query(contacts, { exclude_tags: 'foo\bar' }, nil).to_a).to match_array expected_array
end
end
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/user/organization_accounts_controller.rb
|
class Api::V2::User::OrganizationAccountsController < Api::V2Controller
def index
load_organization_accounts
render json: @organization_accounts.preload_valid_associations(include_associations),
meta: meta_hash(@organization_accounts),
include: include_params,
fields: field_params
end
def show
load_organization_account
authorize_organization_account
render_organization_account
end
def create
persist_organization_account
end
def update
load_organization_account
authorize_organization_account
persist_organization_account
end
def destroy
load_organization_account
authorize_organization_account
destroy_organization_account
end
private
def destroy_organization_account
@organization_account.destroy
head :no_content
end
def load_organization_accounts
@organization_accounts = organization_account_scope.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def load_organization_account
@organization_account ||= Person::OrganizationAccount.find(params[:id])
end
def render_organization_account
render json: @organization_account,
status: success_status,
include: include_params,
fields: field_params
end
def persist_organization_account
build_organization_account
authorize_organization_account
if save_organization_account
render_organization_account
else
render_with_resource_errors(@organization_account)
end
end
def build_organization_account
@organization_account ||= organization_account_scope.build
@organization_account.assign_attributes(organization_account_params)
end
def save_organization_account
@organization_account.save(context: persistence_context)
end
def organization_account_params
params
.require(:organization_account)
.permit(Person::OrganizationAccount::PERMITTED_ATTRIBUTES)
end
def authorize_organization_account
authorize @organization_account
end
def organization_account_scope
load_user.organization_accounts
end
def load_user
@user ||= current_user
end
def default_sort_param
Person::OrganizationAccount.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
lib/tasks/organizations.rake
|
require 'open-uri'
require 'csv'
namespace :organizations do
task fetch: :environment do
OrganizationsFromCsvUrlWorker.new.perform(
'https://download.tntware.com/tntconnect/TntConnect_Organizations.csv'
)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160602005533_ga_notification_failure.rb
|
<gh_stars>0
class GaNotificationFailure < ActiveRecord::Migration
def change
add_column :person_google_accounts, :notified_failure, :boolean
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/not_ids.rb
|
class Contact::Filter::NotIds < Contact::Filter::Base
def execute_query(contacts, filters)
contacts.where.not(id: parse_list(filters[:not_ids]))
end
end
|
chuckmersereau/api_practice
|
db/migrate/20121003213137_make_likely_to_give_a_string.rb
|
class MakeLikelyToGiveAString < ActiveRecord::Migration
def up
change_column :contacts, :likely_to_give, :string
Contact.where(likely_to_give: '1').update_all(likely_to_give: 'Least Likely')
Contact.where(likely_to_give: '2').update_all(likely_to_give: 'Likely')
Contact.where(likely_to_give: '3').update_all(likely_to_give: 'Most Likely')
end
def down
change_column :contacts, :likely_to_give, :integer
end
end
|
chuckmersereau/api_practice
|
app/serializers/person/google_account/contact_group_serializer.rb
|
<filename>app/serializers/person/google_account/contact_group_serializer.rb
class Person::GoogleAccount::ContactGroupSerializer < ApplicationSerializer
type :contact_groups
attributes :title, :tag
def title
object.title.gsub('System Group: ', '')
end
def tag
title.downcase.tr(' ', '-')
end
end
|
chuckmersereau/api_practice
|
spec/concerns/tags_eager_loading_spec.rb
|
require 'rails_helper'
describe TagsEagerLoading do
let(:contact) { create(:contact) }
before do
contact.tag_list = %w(a b)
contact.save
end
it 'retrieves tags with no eager load' do
expect_correct_tag_list(contact.tag_list)
end
it 'retrieves tags with an eager load association' do
expect_correct_tag_list(Contact.includes(:tags).first.tag_list)
end
def expect_correct_tag_list(tag_list)
expect(tag_list).to match_array(%w(a b))
expect(tag_list.to_s.split(', ')).to match_array(%w(a b))
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120609125936_add_fields_to_contact.rb
|
<reponame>chuckmersereau/api_practice
class AddFieldsToContact < ActiveRecord::Migration
def change
change_table :contacts, bulk: true do |t|
t.string :full_name
t.string :greeting
t.string :website, limit: 1000
t.integer :pledge_frequency
t.date :pledge_start_date
t.boolean :deceased, default: false, null: false
t.date :next_ask
t.boolean :never_ask, default: false, null: false
t.integer :likely_to_give
t.string :church_name
t.string :send_newsletter
t.boolean :direct_deposit, default: false, null: false
t.boolean :magazine, default: false, null: false
t.date :last_activity
t.date :last_appointment
t.date :last_letter
t.date :last_phone_call
t.date :last_pre_call
t.date :last_thank
end
end
end
|
chuckmersereau/api_practice
|
spec/support/stub_sleep.rb
|
RSpec.configure do |config|
config.before(:suite) do
$stdout.puts("Stubbing all calls to Ruby's #sleep")
module Kernel
def sleep(time)
time.round # Preserve return value.
end
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/people/websites_controller.rb
|
class Api::V2::Contacts::People::WebsitesController < Api::V2Controller
def index
authorize load_person, :show?
load_websites
render json: @websites.preload_valid_associations(include_associations),
meta: meta_hash(@websites),
include: include_params,
fields: field_params
end
def show
load_website
authorize_website
render_website
end
def create
persist_website
end
def update
load_website
authorize_website
persist_website
end
def destroy
load_website
authorize_website
destroy_website
end
private
def destroy_website
@website.destroy
head :no_content
end
def load_websites
@websites = website_scope.where(filter_params)
.reorder(sorting_param)
.page(page_number_param)
.per(per_page_param)
end
def load_website
@website ||= website_scope.find(params[:id])
end
def authorize_website
authorize @website
end
def render_website
render json: @website,
status: success_status,
include: include_params,
fields: field_params
end
def persist_website
build_website
authorize_website
if save_website
render_website
else
render_with_resource_errors(@website)
end
end
def build_website
@website ||= website_scope.build
@website.assign_attributes(website_params)
end
def save_website
@website.save(context: persistence_context)
end
def website_params
params.require(:website)
.permit(Person::Website::PERMITTED_ATTRIBUTES)
end
def website_scope
load_person.websites
end
def load_person
@person ||= load_contact.people.find(params[:person_id])
end
def load_contact
@contact ||= Contact.find(params[:contact_id])
end
def pundit_user
action_name == 'index' ? PunditContext.new(current_user, contact: load_contact) : current_user
end
end
|
chuckmersereau/api_practice
|
app/serializers/google_integration_serializer.rb
|
<gh_stars>0
class GoogleIntegrationSerializer < ApplicationSerializer
attributes :calendar_id,
:calendar_integration,
:calendar_integrations,
:calendar_name,
:calendars,
:contacts_integration,
:email_blacklist,
:email_integration
belongs_to :account_list
belongs_to :google_account
def calendars
object.calendars.collect do |calendar_list_entry|
{ id: calendar_list_entry.id, name: calendar_list_entry.summary }
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/primary_address_spec.rb
|
<filename>spec/services/contact/filter/primary_address_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe Contact::Filter::PrimaryAddress do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:contact_three) { create(:contact, account_list_id: account_list.id) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id) }
let!(:address_one) do
create(:address,
country: 'United States',
primary_mailing_address: true,
addressable: contact_one)
end
let!(:address_two) do
create(:address,
country: 'United States',
historic: false,
addressable: contact_two)
end
let!(:address_three) do
create(:address,
country: 'United States',
primary_mailing_address: false,
addressable: contact_three)
end
let!(:address_four) do
create(:address,
country: 'United States',
historic: true,
addressable: contact_four)
end
it 'returns the expected config' do
options = [{ name: _('Primary'), id: 'primary' },
{ name: _('Active'), id: 'active' },
{ name: _('Inactive'), id: 'inactive' },
{ name: _('All'), id: 'null' }]
expect(described_class.config([account_list])).to include(name: :primary_address,
options: options,
parent: 'Contact Location',
title: 'Address Type',
type: 'multiselect',
default_selection: 'primary, null',
multiple: true)
end
describe '#query' do
let(:contacts) { Contact.all }
it 'filters by primary address' do
result = described_class.query(contacts, { primary_address: 'primary' }, nil).to_a
expect(result).to include(contact_one)
end
it 'filters by active' do
result = described_class.query(contacts, { primary_address: 'active' }, nil).to_a
expect(result).to include(contact_two)
end
it 'filters by inactive' do
result = described_class.query(contacts, { primary_address: 'inactive' }, nil).to_a
expect(result).to include(contact_four)
end
it 'filters by all' do
result = described_class.query(contacts, {}, nil).to_a
expect(result).to be_empty
end
end
end
|
chuckmersereau/api_practice
|
engines/auth/lib/auth/exceptions.rb
|
module Auth
module Exceptions
class BadRequestError < StandardError; end
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/tnt_codes_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe TntImport::TntCodes do
describe '.task_status_completed?' do
it 'returns true' do
[2, '2'].each do |input|
expect(described_class.task_status_completed?(input)).to eq(true)
end
end
it 'returns false' do
[0, '0', nil, 1, '1'].each do |input|
expect(described_class.task_status_completed?(input)).to eq(false)
end
end
end
describe '.task_type' do
it 'only includes types that are supported by MPDX' do
types = described_class::TNT_TASK_CODES_MAPPED_TO_MPDX_TASK_TYPES.keys.collect do |tnt_type_code|
described_class.task_type(tnt_type_code)
end
expect(types - Task::TASK_ACTIVITIES).to eq([nil])
expect(described_class::TNT_TASK_CODES_MAPPED_TO_MPDX_TASK_TYPES.values - Task::TASK_ACTIVITIES).to eq([nil])
end
end
describe '.unsupported_task_type' do
it 'returns mapped value' do
expect(described_class.unsupported_task_type('170')).to eq 'MailChimp'
end
end
describe '.import_task_type?' do
it 'returns false' do
expect(described_class.import_task_type?('190')).to eq(false)
expect(described_class.import_task_type?(190)).to eq(false)
end
it 'returns true' do
expect(described_class.import_task_type?('')).to eq(true)
expect(described_class.import_task_type?(nil)).to eq(true)
described_class::TNT_TASK_CODES_MAPPED_TO_MPDX_TASK_TYPES.keys.each do |id|
expect(described_class.import_task_type?(id)).to eq(true)
end
end
end
describe '.task_status_completed?' do
it 'is true for 2' do
expect(described_class.task_status_completed?(2)).to eq(true)
end
it 'is false for other values' do
[0, 1, 3, nil, 'string'].each do |test_value|
expect(described_class.task_status_completed?(test_value)).to eq(false)
end
end
end
describe '.history_result' do
it 'only includes results that are supported by MPDX' do
results = described_class::TNT_TASK_RESULT_CODES_MAPPED_TO_MPDX_TASK_RESULTS.keys.collect do |tnt_result_code|
described_class.history_result(tnt_result_code)
end
acceptable_result_values = Task.all_result_options.values.flatten.uniq
expect(results - acceptable_result_values).to eq([])
expect(described_class::TNT_TASK_RESULT_CODES_MAPPED_TO_MPDX_TASK_RESULTS.values - acceptable_result_values).to eq([])
end
end
describe '.mpd_phase' do
it 'only includes statuses that are supported by MPDX, including nil' do
statuses = described_class::TNT_MPD_PHASE_CODES_MAPPED_TO_MPDX_CONTACT_STATUSES.keys.collect do |tnt_mpd_code|
described_class.mpd_phase(tnt_mpd_code)
end
expect(statuses - Contact::ASSIGNABLE_STATUSES).to eq([nil])
expect(described_class::TNT_MPD_PHASE_CODES_MAPPED_TO_MPDX_CONTACT_STATUSES.values - Contact::ASSIGNABLE_STATUSES).to eq([nil])
end
end
end
|
chuckmersereau/api_practice
|
dev/util/user_info_util.rb
|
<filename>dev/util/user_info_util.rb
def user_info(u)
puts "Account Lists for user ##{u.id} #{u.first_name} #{u.last_name}"
puts '-' * 20
u.account_lists.each do |a|
puts account_list_str(a)
a.users.each do |a_u|
puts ' ' + user_str(a_u)
a_u.key_accounts.each do |ka|
puts ' ' + key_account_str(ka)
end
end
a.designation_accounts.each do |da|
puts ' ' + designation_account_str(da)
end
a.designation_profiles.each do |dp|
puts ' ' + designation_profile_str(dp)
dp.designation_accounts.each do |da|
puts ' ' + designation_account_str(da)
end
end
end
true
end
def user_str(u)
"user ##{u.id} #{u.first_name} #{u.last_name}"
end
def key_account_str(ka)
"key #{ka.email}"
end
def account_list_str(a)
"#{a.name} ##{a.id}"
end
def designation_account_str(da)
"desig ##{da.id} '#{da.name}' (#{da.designation_number}) $#{da.balance}"
end
def designation_profile_str(dp)
"prof ##{dp.id} '#{dp.name}' (#{dp.code}) $#{dp.balance}"
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/tags.rb
|
class Contact::Filter::Tags < Contact::Filter::Base
def execute_query(contacts, filters)
contacts.tagged_with(parse_list(filters[:tags]), any: filters[:any_tags].to_s == 'true')
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/appeals_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Appeals' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: :appeals)
let(:resource_type) { 'appeals' }
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!(:contact1) { create(:contact, account_list: account_list, status: 'Partner - Pray') }
let!(:contact2) { create(:contact, account_list: account_list, status: 'Partner - Financial') }
let(:excluded) { 0 }
let!(:appeal) do
create(:appeal, account_list: account_list).tap do |appeal|
create(:donation, appeal: appeal)
end
end
let(:id) { appeal.id }
let(:form_data) do
attributes = attributes_for(:appeal).except(:account_list_id)
.merge(
updated_in_db_at: appeal.updated_at,
inclusion_filter: { status: 'Partner - Financial,Partner - Pray' },
exclusion_filter: { status: 'Partner - Financial' }
)
build_data(attributes, relationships: relationships)
end
let(:relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: account_list.id
}
}
}
end
let(:resource_attributes) do
%w(
amount
created_at
currencies
description
end_date
name
pledges_amount_not_received_not_processed
pledges_amount_processed
pledges_amount_received_not_processed
pledges_amount_total
total_currency
updated_at
updated_in_db_at
)
end
let(:resource_associations) do
%w(
account_list
contacts
donations
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/appeals' do
doc_helper.insert_documentation_for(action: :index, context: self)
example doc_helper.title_for(:index), document: doc_helper.document_scope do
explanation doc_helper.description_for(:index)
do_request
check_collection_resource(1, %w(relationships))
expect(response_status).to eq(200), invalid_status_detail
end
end
get '/api/v2/appeals/:id' do
doc_helper.insert_documentation_for(action: :show, context: self)
example doc_helper.title_for(:show), document: doc_helper.document_scope do
explanation doc_helper.description_for(:show)
do_request
check_resource(%w(relationships))
expect(response_status).to eq(200), invalid_status_detail
end
end
post '/api/v2/appeals' do
doc_helper.insert_documentation_for(action: :create, context: self)
example doc_helper.title_for(:create), document: doc_helper.document_scope do
explanation doc_helper.description_for(:create)
do_request data: form_data
expect(response_status).to eq(201), invalid_status_detail
appeal = Appeal.find_by(id: json_response['data']['id'])
expect(appeal.appeal_contacts.first.contact_id).to eq(contact1.id)
expect(appeal.excluded_appeal_contacts.first.contact_id).to eq(contact2.id)
end
end
put '/api/v2/appeals/:id' do
doc_helper.insert_documentation_for(action: :update, context: self)
example doc_helper.title_for(:update), document: doc_helper.document_scope do
explanation doc_helper.description_for(:update)
do_request data: form_data.except(:relationships)
expect(response_status).to eq(200), invalid_status_detail
end
end
delete '/api/v2/appeals/:id' do
doc_helper.insert_documentation_for(action: :delete, context: self)
example doc_helper.title_for(:delete), document: doc_helper.document_scope do
explanation doc_helper.description_for(:delete)
do_request
expect(response_status).to eq(204), invalid_status_detail
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20140709113152_add_historic_to_address.rb
|
<gh_stars>0
class AddHistoricToAddress < ActiveRecord::Migration
def change
add_column :addresses, :historic, :boolean, default: false
end
end
|
chuckmersereau/api_practice
|
spec/models/family_relationship_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe FamilyRelationship do
describe 'adding a family relationship to a person' do
before(:each) do
@person = FactoryBot.create(:person)
@wife = FactoryBot.create(:person)
@relationship = 'wife'
@attributes = { related_person_id: @wife.id, relationship: @relationship }
end
it "should create a family relationship if it's new" do
expect do
FamilyRelationship.add_for_person(@person, @attributes)
expect(@person.family_relationships.first.relationship).to eq(@relationship)
end.to change(FamilyRelationship, :count).from(0).to(1)
end
it 'should not create a family relationship if it exists' do
FamilyRelationship.add_for_person(@person, @attributes)
expect do
FamilyRelationship.add_for_person(@person, @attributes)
expect(@person.family_relationships.first.relationship).to eq(@relationship)
end.to_not change(FamilyRelationship, :count)
end
end
end
|
chuckmersereau/api_practice
|
app/models/activity_contact.rb
|
class ActivityContact < ApplicationRecord
audited associated_with: :activity, on: [:destroy]
attr_accessor :skip_contact_task_counter_update
belongs_to :activity
belongs_to :task, foreign_key: 'activity_id'
belongs_to :contact
after_save :update_contact_uncompleted_tasks_count, unless: :skip_contact_task_counter_update
after_destroy :update_contact_uncompleted_tasks_count, unless: :skip_contact_task_counter_update
private
def update_contact_uncompleted_tasks_count
contact.try(:update_uncompleted_tasks_count)
end
end
|
chuckmersereau/api_practice
|
spec/models/activity_spec.rb
|
require 'rails_helper'
describe Activity do
let(:account_list) { create(:account_list) }
it 'returns subject for to_s' do
expect(Activity.new(subject: 'foo').to_s).to eq('foo')
end
describe 'scope' do
it '#overdue only includes uncompleted tasks' do
history_task = create(:task, account_list: account_list, start_at: Date.yesterday, completed: true)
overdue_task = create(:task, account_list: account_list, start_at: Date.yesterday)
today_task = create(:task, account_list: account_list, start_at: Time.now.getlocal)
overdue_tasks = account_list.tasks.overdue
expect(overdue_tasks).to include overdue_task
expect(overdue_tasks).not_to include history_task
expect(overdue_tasks).not_to include today_task
end
it '#starred includes starred' do
unstarred_task = create(:task, account_list: account_list)
starred_task = create(:task, account_list: account_list, starred: true)
starred_tasks = account_list.tasks.starred
expect(starred_tasks).to include starred_task
expect(starred_tasks).not_to include unstarred_task
end
end
context '#update_attributes' do
it 'saves a task with a blank related contact' do
task = create(:task)
ac = task.activity_contacts.create!
expect(
task.update_attributes('subject' => 'zvxzcz', 'start_at(2i)' => '12', 'start_at(3i)' => '10',
'start_at(1i)' => '2013', 'start_at(4i)' => '15', 'start_at(5i)' => '15',
'activity_type' => 'Call', 'tag_list' => '',
'comments_attributes' => { '0' => { 'body' => 'asdf' } },
'activity_contacts_attributes' => { '0' => { 'contact_id' => '', 'id' => ac.id.to_s } })
).to be true
end
end
context '#assignable_contacts' do
let(:task) { build(:task, account_list: account_list) }
let(:active_contact) { create(:contact, status: 'Partner - Pray') }
let(:inactive_contact) { create(:contact, status: 'Not Interested') }
before do
account_list.contacts << active_contact
account_list.contacts << inactive_contact
end
it 'gives only active contacts if none are assigned to task' do
expect(task.assignable_contacts.to_a).to eq([active_contact])
end
it 'includes inactive contacts that are assigned to the task' do
task.contacts << inactive_contact
task.save
contacts = task.assignable_contacts
expect(contacts).to include(active_contact)
expect(contacts).to include(inactive_contact)
end
end
end
|
chuckmersereau/api_practice
|
app/helpers/donations_helper.rb
|
<reponame>chuckmersereau/api_practice
module DonationsHelper
def totals_by_currency(donations)
donations.group_by { |d| d.currency == '' ? current_account_list.default_currency : d.currency }
.map do |currency, amount|
{
currency: currency,
count: amount.sum { 1 },
sum: amount.sum { |j| j.amount.to_f }
}
end
end
end
|
chuckmersereau/api_practice
|
spec/services/currency_rate/aliased_rates_filler_spec.rb
|
require 'rails_helper'
describe CurrencyRate::AliasedRatesFiller, '#fill_aliased_rates' do
it 'fills in missing rate records for aliases according to their ratio' do
create(:currency_rate, code: 'KES', rate: 100.0, exchanged_on: Date.new(2016, 5, 1))
create(:currency_rate, code: 'KES', rate: 110.0, exchanged_on: Date.new(2016, 4, 30))
create(:currency_alias, alias_code: 'KSH', rate_api_code: 'KES', ratio: 0.5)
expect do
CurrencyRate::AliasedRatesFiller.new.fill_aliased_rates
end.to change(CurrencyRate, :count).by(2)
expect(CurrencyRate.find_by(code: 'KSH', exchanged_on: Date.new(2016, 5, 1)).rate)
.to eq 50.0
expect(CurrencyRate.find_by(code: 'KSH', exchanged_on: Date.new(2016, 4, 30)).rate)
.to eq 55.0
# Running a second time does not re-create the same rates
expect do
CurrencyRate::AliasedRatesFiller.new.fill_aliased_rates
end.to_not change(CurrencyRate, :count)
end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/gibbon_wrapper.rb
|
# This class serves as a wrapper around the Gibbon class.
# It basically makes the process of communicating with the Mail Chimp API easier.
class MailChimp::GibbonWrapper
COUNT_PER_PAGE = 100
List = Struct.new(:id, :name, :open_rate)
delegate :api_key,
:primary_list_id,
:mail_chimp_appeal_list,
to: :mail_chimp_account
delegate :batches, to: :gibbon
attr_accessor :mail_chimp_account, :gibbon, :validation_error
def initialize(mail_chimp_account)
@mail_chimp_account = mail_chimp_account
end
def lists
@lists ||= build_list_objects || []
end
def list(list_id)
lists.find { |list| list.id == list_id }
end
def primary_list
list(primary_list_id) if primary_list_id.present?
end
def validate_key
return false unless api_key.present?
begin
@list_response ||= gibbon.lists.retrieve
active = true
rescue Gibbon::MailChimpError => error
active = false
@validation_error = error.detail
end
mail_chimp_account.update_column(:active, active) unless mail_chimp_account.new_record?
active
end
def active_and_valid?
active? && validate_key
end
def datacenter
api_key.to_s.split('-').last
end
def lists_available_for_appeals
lists.select { |list| list.id != primary_list_id }
end
def lists_available_for_newsletters
lists.select { |list| list.id != mail_chimp_appeal_list.try(:appeal_list_id) }
end
def queue_export_if_list_changed
queue_export_to_primary_list if changed.include?('primary_list_id')
end
def set_active
self.active = true
end
def gibbon
@gibbon ||= Gibbon::Request.new(api_key: api_key)
@gibbon.timeout ||= 600
@gibbon
end
def list_emails(list_id)
list_members(list_id).map { |list_member| list_member['email_address'].downcase }.uniq
end
def list_members(list_id)
page = list_members_page(list_id, 0)
total_items = page['total_items']
members = page['members']
more_pages = (total_items.to_f / COUNT_PER_PAGE).ceil - 1
more_pages.times do |i|
page = list_members_page(list_id, COUNT_PER_PAGE * (i + 1))
members.concat(page['members'])
end
members
end
def list_member_info(list_id, emails)
emails = Array.wrap(emails)
return [gibbon.lists(list_id).members(mail_chimp_account.email_hash(emails.first)).retrieve] if emails.one?
# The MailChimp API v3 doesn't provide an easy, syncronous way to retrieve
# member info scoped to a set of email addresses, so just pull it all and
# filter it for now.
email_set = emails.map(&:downcase).to_set
list_members(list_id).select { |m| m['email_address'].downcase.in?(email_set) }
end
def appeal_open_rate
list(mail_chimp_appeal_list.try(:appeal_list_id)).try(:open_rate)
end
def primary_list_name
primary_list.try(:name)
end
def lists_available_for_newsletters_formatted
lists_available_for_newsletters.collect { |l| { name: l.name, id: l.id } }
end
def lists_link
"https://#{datacenter}.admin.mailchimp.com/lists/"
end
def gibbon_list_object(list_id)
gibbon.lists(list_id)
end
private
def retrieve_lists
return unless api_key.present?
gibbon.lists.retrieve(params: { count: 100 })['lists']
end
def build_list_objects
fetched_lists = connection_handler.call_mail_chimp(self, :retrieve_lists, require_primary: false)
return [] unless fetched_lists.is_a? Array
fetched_lists.map do |list|
List.new(list['id'], list['name'], list.dig('stats', 'open_rate'))
end
end
def connection_handler
MailChimp::ConnectionHandler.new(mail_chimp_account)
end
def list_members_page(list_id, offset)
gibbon.lists(list_id).members.retrieve(
params: { count: COUNT_PER_PAGE, offset: offset }
)
end
end
|
chuckmersereau/api_practice
|
spec/serializers/person_serializer_spec.rb
|
<filename>spec/serializers/person_serializer_spec.rb
require 'rails_helper'
describe PersonSerializer do
let(:person) do
p = build(:person)
p.email_addresses << build(:email_address)
p.phone_numbers << build(:phone_number)
p
end
subject { PersonSerializer.new(person).as_json }
describe '#parent_contacts' do
before do
person.contacts = create_list(:contact, 2)
end
it 'returns an array of parent contacts' do
expect(subject[:parent_contacts].first).to eq(person.contacts.first.id)
expect(subject[:parent_contacts].count).to eq(2)
end
end
end
|
chuckmersereau/api_practice
|
spec/mailers/previews/mail_chimp_mailer_preview.rb
|
<reponame>chuckmersereau/api_practice
class MailChimpMailerPreview < ApplicationPreview
def invalid_email_addresses
email = '<EMAIL>'
contact1 = FactoryBot.create(:contact_with_person, account_list: account_list)
contact1.primary_person.update(email: email)
contact2 = FactoryBot.create(:contact_with_person, account_list: account_list)
contact2.primary_person.update(email: email)
emails_with_person_ids = {
email => [contact1.primary_person.id, contact2.primary_person.id]
}
MailChimpMailer.invalid_email_addresses(user.account_lists.first.id, emails_with_person_ids)
end
end
|
chuckmersereau/api_practice
|
spec/mailers/application_mailer_spec.rb
|
require 'rails_helper'
describe ApplicationMailer do
let(:mailers_queue) { Sidekiq::Queue.all.find { |queue| queue.name == 'mailers' } }
before do
Sidekiq::Testing.fake!
end
it 'queues jobs to mailers queue by default' do
expect { ApplicationMailer.delay.test }.to change {
Sidekiq::Extensions::DelayedMailer.jobs.select { |job| job['queue'] == 'mailers' }.size
}.by(1)
.and change {
Sidekiq::Extensions::DelayedMailer.jobs.size
}.by(1)
end
it 'allows queueing to a specified queue' do
expect { ApplicationMailer.delay(queue: 'my_special_queue').test }.to change {
Sidekiq::Extensions::DelayedMailer.jobs.select { |job| job['queue'] == 'my_special_queue' }.size
}.by(1)
.and change {
Sidekiq::Extensions::DelayedMailer.jobs.size
}.by(1)
end
end
|
chuckmersereau/api_practice
|
.irbrc.rb
|
<reponame>chuckmersereau/api_practice<filename>.irbrc.rb
require 'pry'
Pry.config.prompt = [
proc do
current_app = ENV['MARCO_POLO_APP_NAME'] || Rails.application.class.parent_name.underscore.tr('_', '-')
rails_env = Rails.env.downcase
# shorten some common long environment names
rails_env = 'dev' if rails_env == 'development'
rails_env = 'prod' if rails_env == 'production'
"#{current_app}-pry(#{rails_env})> "
end,
proc { '> ' }
]
Pry.start
exit
|
chuckmersereau/api_practice
|
app/serializers/task/analytics_serializer.rb
|
<reponame>chuckmersereau/api_practice
class Task
class AnalyticsSerializer < ::ServiceSerializer
attributes :last_electronic_newsletter_completed_at,
:last_physical_newsletter_completed_at,
:tasks_overdue_or_due_today_counts,
:total_tasks_due_count
end
end
|
chuckmersereau/api_practice
|
app/models/background_batch/request.rb
|
<reponame>chuckmersereau/api_practice
class BackgroundBatch::Request < ApplicationRecord
belongs_to :background_batch
validates :path, :request_method, presence: true
validates :request_method, inclusion: { in: %w(GET POST PUT DELETE) }
serialize :request_params, Hash
serialize :request_headers, Hash
serialize :response_headers
enum status: { pending: 0, complete: 1 }
delegate :user, to: :background_batch, prefix: true, allow_nil: true
def response_body
JSON.parse(super || '{}')
end
def formatted_path
@formatted_path ||=
URI(
ENV.fetch('API_URL') + (
if path.include? '%{default_account_list_id}'
format(path, default_account_list_id: default_account_list_id)
else
path
end
)
).to_s
end
def formatted_request_headers
@formatted_request_headers ||= {
'accept' => 'application/vnd.api+json',
'authorization' => "Bearer #{User::Authenticate.new(user: background_batch_user).json_web_token}",
'content-type' => 'application/vnd.api+json',
'params' => formatted_request_params
}.merge(request_headers || {})
end
def formatted_request_params
@formatted_request_params ||=
if default_account_list && default_account_list_id
formatted_request_params = {}
formatted_request_params['filter'] ||= {}
formatted_request_params['filter']['account_list_id'] = default_account_list_id
formatted_request_params.merge(request_params || {})
else
request_params
end
end
protected
def default_account_list_id
@default_account_list_id ||= AccountList.find_by(id: background_batch_user.try(:default_account_list)).try(:id)
end
end
|
chuckmersereau/api_practice
|
spec/factories/person_key_accounts.rb
|
FactoryBot.define do
factory :key_account, class: 'Person::KeyAccount' do
association :person
sequence(:remote_id) { |n| n }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
email { Faker::Internet.email }
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160518143500_rename_contact_locale_default_org_locale.rb
|
<gh_stars>0
class RenameContactLocaleDefaultOrgLocale < ActiveRecord::Migration
def change
rename_column :contacts, :contact_locale, :locale
change_column :organizations, :locale, :string, null: false, default: 'en'
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/prayer_letters_accounts_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Account Lists > Prayer Letters Account' do
include_context :json_headers
documentation_scope = :account_lists_api_prayer_letters_accounts
let(:resource_type) { 'prayer_letters_accounts' }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:contact) { create(:contact, account_list: account_list, send_newsletter: 'Both') }
let(:resource_attributes) do
%w(
created_at
token
updated_at
updated_in_db_at
)
end
before do
stub_request(:get, 'https://www.prayerletters.com/api/v1/contacts')
.to_return(status: 200, body: '{"contacts":[ {"name": "<NAME>", "file_as": "<NAME>",
"external_id": "' + contact.id.to_s + '", "street": "123 Somewhere St", "city": "Fremont",
"state": "CA", "postal_code": "94539"} ]}', headers: {})
stub_request(:put, 'https://www.prayerletters.com/api/v1/contacts')
.to_return(status: 200, body: '{"contacts":[ {"name": "<NAME>", "file_as": "<NAME>",
"external_id": "' + contact.id.to_s + '", "street": "123 Somewhere St", "city": "Fremont",
"state": "CA", "postal_code": "94539"} ]}', headers: {})
end
context 'existent prayer letters account' do
before do
create(:prayer_letters_account, account_list: account_list)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/account_lists/:account_list_id/prayer_letters_account' do
parameter 'account_list_id', 'Account List ID', required: true
with_options scope: [:data, :attributes] do
response_field 'created_at', 'Created At', type: 'String'
response_field 'token', 'Token', type: 'String'
response_field 'updated_at', 'Updated At', type: 'String'
response_field 'updated_in_db_at', 'Updated In Db At', type: 'String'
end
example 'Prayer Letters Account [GET]', document: documentation_scope do
explanation 'The Prayer Letters Account associated with the Account List'
do_request
check_resource
expect(response_status).to eq 200
end
end
delete '/api/v2/account_lists/:account_list_id/prayer_letters_account' do
parameter 'account_list_id', 'Account List ID', required: true
parameter 'id', 'ID', required: true
example 'Prayer Letters Account [DELETE]', document: documentation_scope do
explanation 'Deletes the Prayer Letters Account associated with the Account List'
do_request
expect(response_status).to eq 204
end
end
get '/api/v2/account_lists/:account_list_id/prayer_letters_account/sync' do
parameter 'account_list_id', 'Account List ID', required: true
example 'Prayer Letters Account [SYNC]', document: documentation_scope do
explanation "Synchronizes The Prayer Letters Account's subscribers with #{PrayerLettersAccount::SERVICE_URL}"
do_request
expect(response_status).to eq 200
end
end
end
end
context 'non-existent prayer letters account' do
post '/api/v2/account_lists/:account_list_id/prayer_letters_account' do
before { api_login(user) }
with_options scope: [:data, :attributes] do
parameter 'oauth2_token', 'OAuth2 Token', required: true
end
let(:form_data) { build_data(oauth2_token: 'token') }
example 'Prayer Letters Account [CREATE]', document: documentation_scope do
explanation 'Create a Prayer Letters Account associated with the Account List'
do_request data: form_data
expect(response_status).to eq 201
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/task/filter/tags.rb
|
class Task::Filter::Tags < Task::Filter::Base
def execute_query(tasks, filters)
tasks.tagged_with(parse_list(filters[:tags]), any: filters[:any_tags].to_s == 'true')
end
end
|
chuckmersereau/api_practice
|
app/serializers/contact_detail_serializer.rb
|
<gh_stars>0
class ContactDetailSerializer < ContactSerializer
attribute :lifetime_donations
def lifetime_donations
object.total_donations_query
end
end
|
chuckmersereau/api_practice
|
app/services/sidekiq_cron_loader.rb
|
class SidekiqCronLoader
SIDEKIQ_CRON_HASH = {
'TaskNotificationsWorker' => {
'class' => 'TaskNotificationsWorker',
'cron' => '0 * * * *',
'args' => []
},
'GoogleEmailSyncEnqueuerWorker' => {
'class' => 'GoogleEmailSyncEnqueuerWorker',
'cron' => '1 7 * * *',
'args' => []
},
'AccountListImportDataEnqueuerWorker' => {
'class' => 'AccountListImportDataEnqueuerWorker',
'cron' => '2 7 * * *',
'args' => []
},
'Populate Lat/Lon' => {
'class' => 'SidekiqCronWorker',
'cron' => '3 7 * * *',
'args' => ['MasterAddress.populate_lat_long']
},
'OrganizationsFromCsvUrlWorker' => {
'class' => 'OrganizationsFromCsvUrlWorker',
'cron' => '4 7 * * *',
'args' => ['https://download.tntware.com/donorhub/donorhub_api_organizations.csv']
},
'Clear Stalled Downloads' => {
'class' => 'SidekiqCronWorker',
'cron' => '5 7 * * *',
'args' => ['Person::OrganizationAccount.clear_stalled_downloads']
},
'CurrencyRatesFetcherWorker' => {
'class' => 'CurrencyRatesFetcherWorker',
'cron' => '6 7 * * *',
'args' => []
},
'GoogleContactsSyncEnqueuerWorker' => {
'class' => 'GoogleContactsSyncEnqueuerWorker',
'cron' => '7 7 * * *',
'args' => []
},
'DonationAmountRecommendation::RemoteWorker' => {
'class' => 'DonationAmountRecommendation::RemoteWorker',
'cron' => '0 0 * * *',
'args' => []
}
}.freeze
def load
return if !Rails.env.production? || precompiling_assets? || running_console?
load!
end
def load!
Sidekiq::Cron::Job.load_from_hash!(SIDEKIQ_CRON_HASH)
end
private
def precompiling_assets?
ARGV.any? { |e| e =~ /\Aassets:.+/ }
end
def running_console?
defined?(Rails::Console)
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/country.rb
|
class Contact::Filter::Country < Contact::Filter::Base
def execute_query(contacts, filters)
country_filters = parse_list(filters[:country])
country_filters << nil if country_filters.delete('none')
contacts.where('addresses.country' => country_filters,
'addresses.historic' => filters[:address_historic] == 'true')
.joins(:addresses)
end
def title
_('Country')
end
def parent
_('Contact Location')
end
def type
'multiselect'
end
def custom_options
account_list_countries = account_lists.collect(&:countries)
.flatten
.uniq
.select(&:present?)
.map { |a| { name: a, id: a } }
[{ name: _('-- None --'), id: 'none' }] + account_list_countries
end
end
|
chuckmersereau/api_practice
|
spec/exhibits/task_exhibit_spec.rb
|
require 'rails_helper'
describe TaskExhibit do
subject { TaskExhibit.new(task, context) }
let(:task) { build(:task) }
let(:context) { double }
context '#css_class' do
it 'should return high when start_at time is past' do
task.start_at = 1.hour.ago
expect(subject.css_class).to eql('high')
end
it 'should return mid when start_at time is in the next day' do
task.start_at = 1.hour.from_now
expect(subject.css_class).to eql('mid')
end
it 'should return nothing when start_at time over a day old' do
task.start_at = 1.week.from_now
expect(subject.css_class).to eql('')
end
end
end
|
chuckmersereau/api_practice
|
spec/models/background_batch/request_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/models/background_batch/request_spec.rb
require 'rails_helper'
RSpec.describe BackgroundBatch::Request do
subject { create :background_batch_request }
let(:account_list) { create(:account_list) }
describe '#response_body' do
it 'should return JSON parsed response_body' do
subject.response_body = '{ "id": 1234 }'
expect(subject.response_body).to eq('id' => 1234)
end
it 'should return empty hash' do
expect(subject.response_body).to eq({})
end
end
describe '#formatted_path' do
it 'should return path with url prepended' do
expect(subject.formatted_path).to eq('https://api.mpdx.org/api/v2/user')
end
it 'should replace %{default_account_list_id} with default account list id' do
subject.path = 'api/v2/account_lists/%{default_account_list_id}/donations'
account_list = create(:account_list)
subject.background_batch.user.update(default_account_list: account_list.id)
expect(subject.formatted_path).to eq("https://api.mpdx.org/api/v2/account_lists/#{account_list.id}/donations")
end
end
describe '#formatted_request_headers' do
it 'should return default set of headers' do
expect(subject.formatted_request_headers).to eq(
'accept' => 'application/vnd.api+json',
'authorization' => "Bearer #{User::Authenticate.new(user: subject.background_batch_user).json_web_token}",
'content-type' => 'application/vnd.api+json',
'params' => {}
)
end
it 'should set params as request_params' do
subject.request_params = { 'test' => 1234 }
expect(subject.formatted_request_headers['params']).to eq('test' => 1234)
end
it 'should merge request_headers and override defaults' do
subject.request_headers = { 'accept' => 'application/json', 'test' => 1234 }
expect(subject.formatted_request_headers).to eq(
'accept' => 'application/json',
'authorization' => "Bearer #{User::Authenticate.new(user: subject.background_batch_user).json_web_token}",
'content-type' => 'application/vnd.api+json',
'params' => {},
'test' => 1234
)
end
end
describe '#formatted_request_params' do
it 'should add default_account_list as filter' do
subject.default_account_list = true
subject.background_batch.user.update(default_account_list: account_list.id)
expect(subject.formatted_request_params).to eq('filter' => { 'account_list_id' => account_list.id })
end
it 'should merge request_params and override defaults' do
subject.default_account_list = true
subject.background_batch.user.update(default_account_list: account_list.id)
subject.request_params = { 'filter' => { 'account_list_id' => 1234 }, 'test' => 1234 }
expect(subject.formatted_request_params).to eq(
'filter' => { 'account_list_id' => 1234 },
'test' => 1234
)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/updated_at_spec.rb
|
<filename>spec/services/contact/filter/updated_at_spec.rb
require 'rails_helper'
RSpec.describe Contact::Filter::UpdatedAt do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list: account_list, updated_at: 1.day.ago) }
let!(:contact_two) { create(:contact, account_list: account_list, updated_at: 2.days.ago) }
describe '#config' do
it 'does not have config' do
expect(described_class.config([account_list])).to eq(nil)
end
end
describe '#query' do
let(:contacts) { account_list.contacts }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(contacts, {}, nil)).to eq(nil)
expect(described_class.query(contacts, { updated_at: {} }, nil)).to eq nil
expect(described_class.query(contacts, { updated_at: [] }, nil)).to eq nil
expect(described_class.query(contacts, { updated_at: '' }, nil)).to eq nil
end
end
context 'filter with updated_at value' do
it 'returns only tasks that have the updated_at value' do
expect(described_class.query(contacts, { updated_at: contact_one.updated_at }, nil).to_a).to eq [contact_one]
end
end
context 'filter with updated_at range' do
let(:one_day_ago) { 1.day.ago.beginning_of_day..1.day.ago.end_of_day }
let(:last_two_days) { 2.days.ago.beginning_of_day..1.day.ago.end_of_day }
it 'returns only tasks that are within the updated_at range' do
expect(described_class.query(contacts, { updated_at: one_day_ago }, nil).to_a).to eq [contact_one]
expect(described_class.query(contacts, { updated_at: last_two_days }, nil).to_a).to match_array [contact_one, contact_two]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/constants_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
require Rails.root.join('app', 'seeders', 'notification_types_seeder.rb')
resource 'Constants' do
include_context :json_headers
documentation_scope = :entities_constants
let(:user) { create(:user_with_account) }
before { NotificationTypesSeeder.new.seed }
before { api_login(user) }
get '/api/v2/constants' do
let(:resource_type) { 'constants' }
let(:array_hash_value_keys) do
%w(
activity_hashes
assignable_likely_to_give_hashes
assignable_location_hashes
assignable_send_newsletter_hashes
assignable_status_hashes
notification_hashes
notification_translated_hashes
pledge_currency_hashes
pledge_frequency_hashes
pledge_received_hashes
send_appeals_hashes
status_hashes
)
end
let(:array_value_keys) do
%w(
activities
assignable_likely_to_give
assignable_locations
assignable_send_newsletter
assignable_statuses
codes
pledge_received
statuses
)
end
let(:hash_array_hash_value_keys) do
%w(
bulk_update_option_hashes
)
end
let(:hash_array_value_keys) do
%w(
next_actions
results
sources
)
end
let(:hash_hash_value_keys) do
%w(
locales
organizations_attributes
pledge_currencies
)
end
let(:hash_value_keys) do
%w(
alert_frequencies
dates
languages
mobile_alert_frequencies
notifications
organizations
pledge_frequencies
)
end
let(:key_collections) do
%w(
array_hash_value_keys
array_value_keys
hash_array_hash_value_keys
hash_array_value_keys
hash_hash_value_keys
hash_value_keys
)
end
let(:custom_keys) do
%w(
bulk_update_options
csv_import
tnt_import
)
end
let(:keys) do
keys = custom_keys
key_collections.each do |key_collection|
keys += send(key_collection)
end
keys
end
example 'List constants', document: documentation_scope do
explanation 'List of Constants'
do_request
expect(response_status).to eq 200
expect(resource_object.keys).to match_array keys
expect(resource_object['bulk_update_options'].keys).to eq(
%w(likely_to_give send_newsletter pledge_currency pledge_received status)
)
expect(resource_object['csv_import'].keys).to eq(
%w(constants max_file_size_in_bytes required_headers supported_headers)
)
expect(resource_object['tnt_import'].keys).to eq(
%w(max_file_size_in_bytes)
)
key_collections.each do |key_collection|
send(key_collection).each do |key|
object_type_tester(resource_object[key], key_collection)
end
end
end
end
def object_type_tester(object, types)
current, descendents = types.split('_', 2)
send("#{current}?", object, descendents)
end
def array?(array, descendents)
expect(array).to be_a(Array)
array.each do |object|
object_type_tester(object, descendents)
end
end
def hash?(hash, descendents)
expect(hash).to be_a(Hash)
hash.each_value do |object|
object_type_tester(object, descendents)
end
end
def value?(value, _descendents)
expect(%(TrueClass FalseClass NilClass String)).to include(value.class.name)
end
end
|
chuckmersereau/api_practice
|
spec/lib/json_api_service_spec.rb
|
<filename>spec/lib/json_api_service_spec.rb
require 'spec_helper'
require 'json_api_service'
RSpec.describe JsonApiService, type: :service do
describe '.consume' do
let(:params) { double(:params) }
let(:context) { double(:context) }
let(:transformed_params) { double(:transformed_params) }
let(:configuration) { JsonApiService.configuration }
before do
allow(JsonApiService::Validator)
.to receive(:validate!)
.with(params: params, context: context, configuration: configuration)
.and_return(true)
allow(JsonApiService::Transformer)
.to receive(:transform)
.with(params: params, configuration: configuration)
.and_return(transformed_params)
end
it 'delegates to the validator and transformer, returning new params' do
expect(JsonApiService::Validator)
.to receive(:validate!)
.with(params: params, context: context, configuration: configuration)
expect(JsonApiService::Transformer)
.to receive(:transform)
.with(params: params, configuration: configuration)
result = JsonApiService.consume(params: params, context: context)
expect(result).to eq transformed_params
end
end
end
|
chuckmersereau/api_practice
|
app/models/concerns/deceased.rb
|
# frozen_string_literal: true
module Deceased
extend ActiveSupport::Concern
included do
scope :non_deceased, -> { where(deceased: false) }
scope :deceased, -> { where(deceased: true) }
before_save :deceased_check
end
class_methods do
def are_all_deceased?
deceased.count == count
end
def not_all_deceased?(id)
non_deceased.where.not(id: id).exists?
end
end
def deceased_check
return unless deceased_changed? && deceased?
self.optout_enewsletter = true
contacts.each do |contact|
if contact.people.not_all_deceased?(id)
contact_updates = strip_name_from_greetings(contact)
clear_primary_person(contact)
else
contact_updates = update_contact_when_all_people_are_deceased
end
next if contact_updates.blank?
contact_updates[:updated_at] = Time.current
# Call update_columns instead of save because a save of a contact can trigger saving its people which
# could eventually call this very deceased_check method and cause an infinite recursion.
contact.update_columns(contact_updates)
end
end
private
def update_contact_when_all_people_are_deceased
contact_updates = {}
# we should update their Newsletter Status to None
reset_newsletter_status(contact_updates)
# their Send Appeals to no
reset_appeals(contact_updates)
# and their Partner Status to Never Ask
reset_partner_status(contact_updates)
contact_updates
end
def reset_partner_status(contact_updates)
contact_updates.merge!(status: 'Never Ask')
end
def reset_appeals(contact_updates)
contact_updates.merge!(no_appeals: true)
end
def reset_newsletter_status(contact_updates)
contact_updates.merge!(send_newsletter: 'None')
end
# We need to access the field value directly via c[:greeting] because c.greeting defaults to the first name
# even if the field is nil. That causes an infinite loop here where it keeps trying to remove the first name
# from the greeting but it keeps getting defaulted back to having it.
def strip_name_from_greetings(contact, contact_updates = {})
if contact[:greeting].present? && contact[:greeting].include?(first_name)
contact_updates[:greeting] = contact.greeting.sub(first_name, '').sub(/ #{_('and')} /, ' ').strip
end
contact_updates[:envelope_greeting] = '' if contact[:envelope_greeting].present?
contact_updates = strip_first_name(contact, contact_updates)
contact_updates
end
def strip_first_name(contact, contact_updates = {})
if contact.name.include?(first_name)
# remove the name
contact_updates[:name] = contact.name.sub(first_name, '').sub(/ & | #{_('and')} /, '').strip
end
contact_updates
end
def clear_primary_person(contact)
if contact.primary_person_id == id && contact.people.count > 1
# This only modifies associated people via update_column, so we can call it directly
contact.clear_primary_person
end
end
end
|
chuckmersereau/api_practice
|
spec/models/google_integration_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe GoogleIntegration do
let(:google_integration) { build(:google_integration) }
let(:calendar_list_entry) { double(id: '1234', summary: 'My Calendar', access_role: 'owner') }
context '#queue_sync_data' do
it 'queues a data sync when an integration type is passed in' do
google_integration.save
expect(GoogleSyncDataWorker).to receive(:perform_async).with(google_integration.id, 'calendar')
google_integration.queue_sync_data('calendar')
end
it 'does not queue a data sync when the record is not saved' do
expect do
google_integration.queue_sync_data('calendar')
end.to raise_error(RuntimeError, 'Cannot queue sync on an unpersisted record!')
end
it 'does not queue a data sync when a bad integration type is passed in' do
google_integration.save
expect do
google_integration.queue_sync_data('bad')
end.to raise_error(RuntimeError, "Invalid integration 'bad'!")
end
end
context '#sync_data' do
it 'triggers a calendar_integration sync' do
expect(google_integration.calendar_integrator).to receive(:sync_data)
google_integration.sync_data('calendar')
end
end
context '#calendar_integrator' do
it 'should return the same GoogleCalendarIntegrator instance across multiple calls' do
expect(google_integration.calendar_integrator).to equal(google_integration.calendar_integrator)
end
end
context '#calendars' do
let(:calendar_list_entry_owner) { double(id: '1234', summary: 'My Calendar', access_role: 'owner') }
let(:calendar_list_entry_nonowner) { double(id: '1234', summary: 'My Calendar', access_role: 'nonowner') }
let(:calendar_list) { [calendar_list_entry_nonowner, calendar_list_entry_owner] }
it 'returns a list of calendars from google with access_role owner' do
allow(google_integration).to receive_message_chain(:calendar_service, :list_calendar_lists, :items)
.and_return(calendar_list)
expect(google_integration.calendars).to eq([calendar_list_entry_owner])
end
end
context '#toggle_calendar_integration_for_appointments' do
before do
allow(google_integration).to receive(:calendars).and_return([])
google_integration.calendar_id = ''
google_integration.calendar_integrations = []
google_integration.calendar_integration = true
google_integration.save!
end
it 'turns on Appointment syncing if calendar_integration is enabled and nothing is specified' do
expect(google_integration.calendar_integrations).to eq(['Appointment'])
end
it 'remove calendar_integrations when calendar_integration is set to false' do
google_integration.calendar_integrations = ['Appointment']
google_integration.calendar_integration = false
google_integration.save
expect(google_integration.calendar_integrations).to eq([])
end
end
context '#set_default_calendar' do
before do
google_integration.calendar_id = nil
end
it 'defaults to the first calendar if this google account only has 1' do
allow(google_integration).to receive(:calendars).and_return([calendar_list_entry])
first_calendar = calendar_list_entry
google_integration.send(:set_default_calendar)
expect(google_integration.calendar_id).to eq(first_calendar.id)
expect(google_integration.calendar_name).to eq(first_calendar.summary)
end
it 'returns nil if the api fails' do
allow(google_integration).to receive(:calendar_service).and_return(nil)
expect(google_integration.send(:set_default_calendar)).to eq(nil)
end
it 'returns nil if this google account has more than one calendar' do
allow(google_integration).to receive(:calendars).and_return([calendar_list_entry, calendar_list_entry])
expect(google_integration.send(:set_default_calendar)).to eq(nil)
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/users_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Users' do
include_context :json_headers
documentation_scope = :entities_user
let(:resource_type) { 'users' }
let(:user) { create(:user_with_full_account) }
let(:new_user_attributes) do
attributes_for(:user_with_full_account)
.except(:access_token, :email, :locale, :time_zone)
.merge(updated_in_db_at: user.updated_at).except(:email)
end
let(:form_data) { build_data(new_user_attributes) }
let(:resource_attributes) do
%w(
anniversary_day
anniversary_month
anniversary_year
avatar
birthday_day
birthday_month
birthday_year
deceased
employer
first_name
gender
last_name
legal_first_name
marital_status
middle_name
occupation
optout_enewsletter
parent_contacts
preferences
title
suffix
created_at
updated_at
updated_in_db_at
)
end
let(:resource_associations) do
%w(
account_lists
email_addresses
master_person
facebook_accounts
family_relationships
linkedin_accounts
phone_numbers
twitter_accounts
websites
)
end
context 'authorized user' do
before { api_login(user) }
lock_time_around
get '/api/v2/user' do
response_field 'attributes', 'User object', type: 'Object'
response_field 'id', 'User ID', type: 'Number'
response_field 'relationships', 'list of relationships related to that User', type: 'Array[Object]'
response_field 'type', 'Will be User', type: 'String'
with_options scope: [:data, :attributes] do
response_field 'anniversary_day', 'Anniversary Day', type: 'Number'
response_field 'anniversary_month', 'Anniversary Month', type: 'Number'
response_field 'anniversary_year', 'Anniversary Year', type: 'Number'
response_field 'avatar', 'Avatar', type: 'String'
response_field 'birthday_day', 'Birthday Day', type: 'Number'
response_field 'birthday_month', 'Birthday Month', type: 'Number'
response_field 'birthday_year', 'Birthday Year', type: 'Number'
response_field 'created_at', 'Created At', type: 'String'
response_field 'deceased', 'Deceased', type: 'Boolean'
response_field 'employer', 'Employer', type: 'String'
response_field 'first_name', 'First Name', type: 'String'
response_field 'gender', 'Gender', type: 'String'
response_field 'last_name', 'Last Name', type: 'String'
response_field 'legal_first_name', 'Legal First Name', type: 'String'
response_field 'marital_status', 'Marital Status', type: 'String'
response_field 'master_person_id', 'Master Person ID', type: 'Number'
response_field 'middle_name', 'Middle Name', type: 'String'
response_field 'occupation', 'Occupation', type: 'String'
response_field 'optout_enewsletter', 'Optout of Enewsletter or not', type: 'Boolean'
response_field 'parent_contacts', 'Array of Parent Contact Ids', type: 'Array'
response_field 'suffix', 'Suffix', type: 'String'
response_field 'title', 'Title', type: 'String'
response_field 'preferences', 'User preferences', type: 'Object'
response_field 'updated_at', 'Updated At', type: 'String'
response_field 'updated_in_db_at', 'Updated In Db At', type: 'String'
end
example 'Retrieve the current user', document: documentation_scope do
explanation 'The current_user'
do_request
check_resource(['relationships'])
expect(response_status).to eq 200
end
end
put '/api/v2/user' do
with_options scope: [:data, :attributes] do
parameter 'first_name', 'User first name', type: 'String', required: true
parameter 'last_name', 'User last name', type: 'String'
with_options scope: :preferences do
parameter 'contacts_filter', 'Contacts Filter', type: 'String'
parameter 'contacts_view_options', 'Contacts View Options', type: 'String'
parameter 'default_account_list', 'Default Account List', type: 'String'
parameter 'locale', 'User Locale', type: 'String'
parameter 'setup', 'User Preferences Setup', type: 'String'
parameter 'tab_orders', 'Tab Orders', type: 'String'
parameter 'tasks_filter', 'Tasks Filter', type: 'String'
parameter 'time_zone', 'User Time Zone', type: 'String'
end
end
example 'Update the current user', document: documentation_scope do
explanation 'Update the current_user'
do_request data: form_data
expect(resource_object['first_name']).to eq new_user_attributes[:first_name]
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/admin/dup_phones_fix.rb
|
class Admin::DupPhonesFix
def initialize(person)
@person = person
end
def fix
phones.each(&method(:normalize))
phones.each(&method(:fix_missing_us_country_prefix))
phones.group_by(&:number).each(&method(:merge_dup_phones))
end
private
attr_reader :person
def phones
@phones ||= person.phone_numbers.order(:created_at).to_a
end
def normalize(phone)
phone.clean_up_number
phone.save
end
def fix_missing_us_country_prefix(phone)
# Sometimes (in past or present code), a US phone number got saved
# without the +1 but with a +, i.e. +6171234567 instead of +1617234567.
return unless phone.number =~ /\A\+[2-9]\d{9}/
us_country_code_added = "+1#{phone.number[1..-1]}"
# Sometimes a 10-digit number with a + in front could actually be an
# international number, so only make the assumption that this number is
# actually a US number with a missing country code if there is another phone
# for that person where the country code is not missing.
return unless phones.any? { |p| p.number == us_country_code_added }
phone.update(number: us_country_code_added)
end
def merge_dup_phones(_number, phones)
return unless phones.size > 1
first_phone = phones[0]
phones[1..-1].each { |phone| first_phone.merge(phone) }
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/prayer_letters_accounts_controller_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe Api::V2::AccountLists::PrayerLettersAccountsController, type: :controller do
let(:factory_type) { :prayer_letters_account }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:contact) { create(:contact, account_list: account_list, send_newsletter: 'Both') }
let!(:resource) { create(:prayer_letters_account, account_list: account_list) }
let(:parent_param) { { account_list_id: account_list_id } }
let(:unpermitted_attributes) { nil }
let(:correct_attributes) { attributes_for(:prayer_letters_account) }
let(:incorrect_attributes) { attributes_for(:prayer_letters_account, oauth2_token: nil) }
include_examples 'show_examples'
include_examples 'destroy_examples'
describe '#create' do
before do
resource.destroy
end
include_examples 'create_examples'
end
describe '#sync' do
before do
api_login(user)
end
it 'syncs prayer letters account' do
expect(response.status).to eq 200
end
end
end
|
chuckmersereau/api_practice
|
app/models/session.rb
|
<gh_stars>0
class Session < ApplicationRecord
PERMITTED_ATTRIBUTES = [ :user,
:sid
].freeze
before_save :default
def default
if Session.maximum("sid") == nil
self.sid = 1
else
self.sid = Session.maximum("sid") +1
end
end
end
|
chuckmersereau/api_practice
|
config/initializers/faraday.rb
|
<reponame>chuckmersereau/api_practice
#require 'typhoeus/adapters/faraday'
#Faraday.default_adapter = :typhoeus
|
chuckmersereau/api_practice
|
app/preloaders/api/v2/tasks/comments_preloader.rb
|
class Api::V2::Tasks::CommentsPreloader < ApplicationPreloader
ASSOCIATION_PRELOADER_MAPPING = { person: Api::V2::Contacts::PeoplePreloader }.freeze
FIELD_ASSOCIATION_MAPPING = {}.freeze
private
def serializer_class
ActivityCommentSerializer
end
end
|
chuckmersereau/api_practice
|
spec/factories/taggings.rb
|
FactoryBot.define do
factory :tagging, class: 'ActsAsTaggableOn::Tagging' do
association :tag
association :taggable
context 'test'
end
end
|
chuckmersereau/api_practice
|
app/services/data_server_uk.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class DataServerUk < DataServer
def import_profile_balance(profile)
check_credentials!
balance = profile_balance(profile.code)
attributes = { balance: balance[:balance], balance_updated_at: balance[:date] }
profile.update_attributes(attributes)
return unless balance[:designation_numbers]
attributes[:name] = balance[:account_names].first if balance[:designation_numbers].length == 1
balance[:designation_numbers].each_with_index do |number, _i|
find_or_create_designation_account(number, profile, attributes)
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/users_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::AccountLists::UsersController, type: :controller do
let(:factory_type) { :user }
let!(:user) { create(:user_with_account) }
let!(:users) { create_list(:user, 2) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:user2) { users.last }
let(:id) { user2.id }
let(:original_user_id) { user.id }
before do
account_list.users += users
end
let(:resource) { user2 }
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 not delete self' do
delete :destroy, account_list_id: account_list_id, id: original_user_id
expect(response.status).to eq 403
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/csv_row_contact_builder.rb
|
# This service class accepts an instance of CSV::Row and an instance of Import and builds a contact record.
class CsvRowContactBuilder
def initialize(csv_row:, import:)
@csv_row = csv_row
@import = import
end
def build
contact_from_csv_row
end
private
delegate :account_list, to: :import
delegate :constants, to: CsvImport
attr_accessor :csv_row, :import, :contact, :person, :spouse, :names
def contact_scope
account_list.contacts
end
def contact_from_csv_row
rebuild_csv_row_with_mpdx_headers_and_mpdx_constants
strip_csv_row_fields
parse_names
build_contact
build_addresses
build_tags
build_primary_person
build_email_addresses
build_phone_numbers
build_spouse_person
build_referral
contact
end
def parse_names
@names = HumanNameParser.new(csv_row['full_name'] || '').parse
# first_name and last_name columns take precedence over full_name column
@names[:first_name] = csv_row['first_name'] if csv_row['first_name'].present?
@names[:last_name] = csv_row['last_name'] if csv_row['last_name'].present?
@names[:spouse_first_name] = csv_row['spouse_first_name'] if csv_row['spouse_first_name'].present?
@names[:spouse_last_name] = csv_row['spouse_last_name'].presence || @names[:last_name]
@names[:full_contact_name] = Contact::NameBuilder.new(@names.to_h).name
@names = @names.with_indifferent_access
end
def build_contact
self.contact = contact_scope.build(
church_name: csv_row['church'],
name: names['full_contact_name'],
greeting: csv_row['greeting'],
envelope_greeting: csv_row['envelope_greeting'],
status: csv_row['status'],
pledge_amount: csv_row['pledge_amount'],
notes: csv_row['notes'],
pledge_frequency: csv_row['pledge_frequency'],
send_newsletter: csv_row['newsletter'],
pledge_currency: csv_row['pledge_currency'],
likely_to_give: csv_row['likely_to_give'],
no_appeals: !true?(csv_row['send_appeals']),
website: csv_row['website']
)
end
def build_addresses
return if csv_row['street'].blank?
contact.addresses.build(
street: csv_row['street'],
city: csv_row['city'],
state: csv_row['state'],
postal_code: csv_row['zip'],
country: csv_row['country'],
metro_area: csv_row['metro_area'],
region: csv_row['region'],
primary_mailing_address: true
)
end
def build_tags
contact.tag_list = csv_row['tags']
contact.tag_list.add(import.tags, parse: true) if import.tags.present?
end
def build_primary_person
self.person = Person.new(first_name: names['first_name'],
last_name: names['last_name'])
contact.primary_person = person
end
def build_email_addresses
person.email_addresses.build(email: csv_row['email_1'],
primary: true) if csv_row['email_1'].present?
person.email_addresses.build(email: csv_row['email_2'],
primary: person.email_addresses.blank?) if csv_row['email_2'].present?
end
def build_phone_numbers
person.phone_numbers.build(number: csv_row['phone_1'],
primary: true) if csv_row['phone_1'].present?
person.phone_numbers.build(number: csv_row['phone_2'],
primary: person.phone_numbers.blank?) if csv_row['phone_2'].present?
person.phone_numbers.build(number: csv_row['phone_3'],
primary: person.phone_numbers.blank?) if csv_row['phone_3'].present?
end
def build_spouse_person
return if names['spouse_first_name'].blank?
spouse = Person.new(first_name: names['spouse_first_name'],
last_name: names['spouse_last_name'])
spouse.email_addresses.build(email: csv_row['spouse_email'],
primary: true) if csv_row['spouse_email'].present?
spouse.phone_numbers.build(number: csv_row['spouse_phone'],
primary: true) if csv_row['spouse_phone'].present?
contact.spouse = spouse
end
def build_referral
return if csv_row['referred_by'].blank?
referrer_contact = Contact::FindFromName.new(contact_scope, csv_row['referred_by']).first
if referrer_contact.blank?
contact.tag_list.add('Missing Csv Referred By')
contact.add_to_notes("Referred by: #{csv_row['referred_by']}")
else
contact.contact_referrals_to_me.build(referred_by: referrer_contact)
end
end
def true?(val)
val.to_s.casecmp('true').zero?
end
def strip_csv_row_fields
new_csv_row = csv_row
strippable_headers = csv_row.headers - csv_file_constants_mappings.constant_names
strippable_headers.each do |header|
new_csv_row[header] = csv_row[header]&.strip
end
self.csv_row = new_csv_row
end
def rebuild_csv_row_with_mpdx_headers_and_mpdx_constants
self.csv_row = rebuild_csv_row_with_mpdx_headers(csv_row)
self.csv_row = rebuild_csv_row_with_mpdx_constants(csv_row)
end
def rebuild_csv_row_with_mpdx_headers(old_csv_row)
return old_csv_row if import.file_headers_mappings.blank?
mpdx_headers = import.file_headers_mappings.keys
fields = mpdx_headers.collect do |mpdx_header|
csv_header = import.file_headers[import.file_headers_mappings[mpdx_header]]
old_csv_row[csv_header]
end
CSV::Row.new(mpdx_headers, fields)
end
def rebuild_csv_row_with_mpdx_constants(old_csv_row)
return old_csv_row if import.file_constants_mappings.blank?
new_csv_row = old_csv_row
csv_file_constants_mappings.constant_names.each do |mpdx_constant_header|
value_to_change = old_csv_row[mpdx_constant_header]
new_csv_row[mpdx_constant_header] =
csv_file_constants_mappings.convert_value_to_constant_id(mpdx_constant_header, value_to_change)
end
new_csv_row
end
def csv_file_constants_mappings
@csv_file_constants_mappings ||= CsvValueToConstantMappings.new(import.file_constants_mappings)
end
end
|
chuckmersereau/api_practice
|
spec/factories/donations.rb
|
FactoryBot.define do
factory :donation do
sequence(:remote_id, 1) { |n| n&.to_s }
amount '9.99'
donation_date { Date.today }
appeal_amount '0.00'
association :donor_account
association :designation_account
motivation 'MyString'
payment_method 'MyString'
tendered_currency 'ZAR'
tendered_amount '9.99'
currency 'ZAR'
memo 'MyText'
payment_type 'MyString'
channel 'MyString'
end
end
|
chuckmersereau/api_practice
|
spec/exhibits/person_exhibit_spec.rb
|
<filename>spec/exhibits/person_exhibit_spec.rb
require 'rails_helper'
describe PersonExhibit do
let(:exhib) { PersonExhibit.new(person, context) }
let(:person) { build(:person) }
let(:context) { double(root_url: 'https://mpdx.org') }
context '#avatar' do
it 'ignores images with nil content' do
allow(person).to receive(:facebook_account).and_return(nil)
allow(person).to receive(:primary_picture).and_return(double(image: double(url: nil)))
allow(person).to receive(:gender).and_return(nil)
expect(exhib.avatar).to eq('https://mpdx.org/images/avatar.png')
end
it 'uses facebook image if remote_id set' do
allow(person).to receive(:facebook_account).and_return(double(remote_id: 1234))
allow(person).to receive(:primary_picture).and_return(double(image: double(url: nil)))
expect(exhib.avatar).to eq('https://graph.facebook.com/1234/picture?type=square')
end
it 'uses default avatar if remote_id not present' do
allow(person).to receive(:facebook_account).and_return(double(remote_id: nil))
allow(person).to receive(:primary_picture).and_return(double(image: double(url: nil)))
allow(person).to receive(:gender).and_return(nil)
expect(exhib.avatar).to eq('https://mpdx.org/images/avatar.png')
end
end
context '#facebook_link' do
it 'gives blank if person has no facebook account' do
expect(exhib.facebook_link).to be_blank
end
it 'links to the facebook account url if person has an account' do
exhib = PersonExhibit.new(person, ActionView::Base.new)
allow(person).to receive(:facebook_account) { double(url: 'facebook.com/joe') }
expect(exhib.facebook_link).to eq %(<a target=\"_blank\" class=\"fa fa-facebook-square\" href=\"facebook.com/joe\"></a>)
end
end
context '#twitter_link' do
it 'gives blank if person has no twitter account' do
expect(exhib.twitter_link).to be_blank
end
it 'links to the twitter account url if the person has a twitter account' do
exhib = PersonExhibit.new(person, ActionView::Base.new)
allow(person).to receive(:twitter_account) { double(url: 'twitter.com/joe') }
expect(exhib.twitter_link).to eq %(<a target=\"_blank\" class=\"fa fa-twitter-square\" href=\"twitter.com/joe\"></a>)
end
end
context '#email_link' do
it 'gives blank if person has no primary email address' do
expect(exhib.email_link).to be_blank
end
it 'links to the email mailto url if person has a primary email' do
person.email_address = { email: '<EMAIL>', primary: true }
person.save
exhib = PersonExhibit.new(person, ActionView::Base.new)
expect(exhib.email_link).to eq %(<a class="fa fa-envelope" href="mailto:<EMAIL>"></a>)
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/organization_serializer.rb
|
class OrganizationSerializer < ApplicationSerializer
attributes :abbreviation,
:code,
:country,
:default_currency_code,
:logo,
:name,
:gift_aid_percentage,
:oauth
def oauth
object.oauth?
end
end
|
chuckmersereau/api_practice
|
app/models/task.rb
|
<filename>app/models/task.rb
require 'async'
class Task < Activity
include Async
include Deletable
include Sidekiq::Worker
sidekiq_options queue: :api_task, backtrace: true, unique: :until_executed
attr_accessor :skip_contact_task_counter_update
before_validation :update_completed_at
before_validation :auto_generate_subject, on: :create
after_save :update_contact_uncompleted_tasks_count, :queue_sync_to_google_calendar
after_destroy :update_contact_uncompleted_tasks_count, :queue_sync_to_google_calendar
after_create :log_newsletter, if: -> { should_log_to_all_contacts? }
enum notification_type: %w(email mobile both)
enum notification_time_unit: %w(minutes hours)
scope :of_type, -> (activity_type) { where(activity_type: activity_type) }
scope :with_result, -> (result) { where(result: result) }
scope :completed_between, lambda { |start_date, end_date|
completed.where('completed_at BETWEEN ? and ?', start_date.in_time_zone, (end_date + 1.day).in_time_zone)
}
scope :created_between, lambda { |start_date, end_date|
where('created_at BETWEEN ? and ?', start_date.in_time_zone, (end_date + 1.day).in_time_zone)
}
scope :that_belong_to, -> (user) { where(account_list_id: user.account_list_ids) }
scope :starting_between, ->(time_range) { where(start_at: time_range) }
scope :unscheduled, -> { where(notification_scheduled: nil) }
scope :with_notification_time, -> { where.not(notification_time_before: nil) }
scope :notify_by, ->(types) { where(notification_type: types) }
PERMITTED_ATTRIBUTES = [
:account_list_id,
:activity_type,
:completed,
:completed_at,
:created_at,
:end_at,
:location,
:next_action,
:notification_time_before,
:notification_time_unit,
:notification_type,
:overwrite,
:result,
:starred,
:start_at,
:subject,
:subject_hidden,
:tag_list,
:updated_at,
:updated_in_db_at,
:id,
{
comment: [
:body,
:overwrite
],
comments_attributes: [
:body,
:id,
:_client_id,
:person_id,
:overwrite
],
activity_contacts_attributes: [
:_destroy,
:id,
:_client_id,
:overwrite
],
contacts_attributes: [
:_destroy,
:id,
:_client_id,
:overwrite
]
}
].freeze
# validates :activity_type, :presence => { :message => _( '/ Action is required') }
CALL_RESULTS = ['Attempted - Left Message', 'Attempted', 'Completed', 'Received'].freeze
CALL_NEXT_ACTIONS = [
'Call',
'Email',
'Text Message',
'Facebook Message',
'Talk to In Person',
'Appointment',
'Prayer Request',
'Thank'
].freeze
APPOINTMENT_RESULTS = %w(Completed Attempted).freeze
APPOINTMENT_NEXT_ACTIONS = [
'Call',
'Email',
'Text Message',
'Facebook Message',
'Talk to In Person',
'Appointment',
'Prayer Request',
'Thank'
].freeze
EMAIL_RESULTS = %w(Completed Received).freeze
EMAIL_NEXT_ACTIONS = [
'Call',
'Email',
'Text Message',
'Facebook Message',
'Talk to In Person',
'Appointment',
'Prayer Request',
'Thank'
].freeze
FACEBOOK_MESSAGE_RESULTS = %w(Completed Received).freeze
FACEBOOK_MESSAGE_NEXT_ACTIONS = [
'Call',
'Email',
'Text Message',
'Facebook Message',
'Talk to In Person',
'Appointment',
'Prayer Request',
'Thank'
].freeze
TEXT_RESULTS = %w(Completed Received).freeze
TEXT_NEXT_ACTIONS = [
'Call',
'Email',
'Text Message',
'Facebook Message',
'Talk to In Person',
'Appointment',
'Prayer Request',
'Thank'
].freeze
TALK_TO_IN_PERSON_RESULTS = %w(Completed).freeze
TALK_TO_IN_PERSON_NEXT_ACTIONS = [
'Call',
'Email',
'Text Message',
'Facebook Message',
'Talk to In Person',
'Appointment',
'Prayer Request',
'Thank'
].freeze
PRAYER_REQUEST_RESULTS = %w(Completed).freeze
PRAYER_REQUEST_NEXT_ACTIONS = [
'Call',
'Email',
'Text Message',
'Facebook Message',
'Talk to In Person',
'Appointment',
'Prayer Request',
'Thank'
].freeze
LETTER_RESULTS = %w(Completed Received).freeze
LETTER_NEXT_ACTIONS = [
'Call',
'Email',
'Text Message',
'Facebook Message',
'Talk to In Person',
'None'
].freeze
PRE_CALL_LETTER_RESULTS = LETTER_RESULTS
PRE_CALL_LETTER_NEXT_ACTIONS = LETTER_NEXT_ACTIONS
REMINDER_LETTER_RESULTS = LETTER_RESULTS
REMINDER_LETTER_NEXT_ACTIONS = LETTER_NEXT_ACTIONS
SUPPORT_LETTER_RESULTS = LETTER_RESULTS
SUPPORT_LETTER_NEXT_ACTIONS = LETTER_NEXT_ACTIONS
THANK_RESULTS = LETTER_RESULTS
THANK_NEXT_ACTIONS = LETTER_NEXT_ACTIONS
STANDRD_NEXT_ACTIONS = [_('None')].freeze
MESSAGE_RESULTS = [_('Done'), _('Received')].freeze
STANDARD_RESULTS = [_('Done')].freeze
ALL_RESULTS = STANDARD_RESULTS +
APPOINTMENT_RESULTS +
CALL_RESULTS +
MESSAGE_RESULTS +
TALK_TO_IN_PERSON_RESULTS +
PRAYER_REQUEST_RESULTS +
PRE_CALL_LETTER_RESULTS
TASK_ACTIVITIES = [
'Call',
'Appointment',
'Email',
'Text Message',
'Facebook Message',
'Letter',
'Newsletter - Physical',
'Newsletter - Email',
'Pre Call Letter',
'Reminder Letter',
'Support Letter',
'Thank',
'To Do',
'Talk to In Person',
'Prayer Request'
].freeze
TASK_ACTIVITIES.each do |activity_type|
singleton_class.instance_eval do
scope_name = activity_type.parameterize.underscore.to_sym
define_method scope_name do
where(activity_type: activity_type)
end
end
end
assignable_values_for :activity_type, allow_blank: true do
TASK_ACTIVITIES
end
# assignable_values_for :result, :allow_blank => true do
# case activity_type
# when 'Call'
# CALL_RESULTS + STANDARD_RESULTS
# when 'Email', 'Text Message', 'Facebook Message', 'Letter'
# STANDARD_RESULTS + MESSAGE_RESULTS
# else
# STANDARD_RESULTS
# end
# end
def deleted_from
account_list
end
def attempted?
result == 'Attempted'
end
def default_length
case activity_type
when 'Appointment'
1.hour
when 'Call'
5.minutes
end
end
def location
return self[:location] unless self[:location].blank?
calculated_location
end
def calculated_location
case activity_type
when 'Call'
numbers = contacts.map(&:people).flatten.map do |person|
next unless person.phone_number&.present?
"#{person} #{PhoneNumberExhibit.new(person.phone_number, nil)}"
end
numbers.compact.join("\n")
else
return AddressExhibit.new(contacts.first.address, nil).to_google if contacts.first&.address
end
end
def result_options
case activity_type
when 'Call'
CALL_RESULTS
when 'Appointment'
APPOINTMENT_RESULTS
when 'Email'
EMAIL_RESULTS
when 'Facebook Message'
FACEBOOK_MESSAGE_RESULTS
when 'Text Message'
TEXT_RESULTS
when 'Talk to In Person'
TALK_TO_IN_PERSON_RESULTS
when 'Prayer Request'
PRAYER_REQUEST_RESULTS
when 'Letter'
LETTER_RESULTS
when 'Pre Call Letter'
PRE_CALL_LETTER_RESULTS
when 'Reminder Letter'
REMINDER_LETTER_RESULTS
when 'Support Letter'
REMINDER_LETTER_RESULTS
when 'Thank'
THANK_RESULTS
else
STANDARD_RESULTS
end
end
def next_action_options
case activity_type
when 'Call'
CALL_NEXT_ACTIONS
when 'Appointment'
APPOINTMENT_NEXT_ACTIONS
when 'Email'
EMAIL_NEXT_ACTIONS
when 'Facebook Message'
FACEBOOK_MESSAGE_NEXT_ACTIONS
when 'Text Message'
TEXT_NEXT_ACTIONS
when 'Talk to In Person'
TALK_TO_IN_PERSON_NEXT_ACTIONS
when 'Prayer Request'
PRAYER_REQUEST_NEXT_ACTIONS
when 'Letter'
LETTER_NEXT_ACTIONS
when 'Pre Call Letter'
PRE_CALL_LETTER_NEXT_ACTIONS
when 'Reminder Letter'
REMINDER_LETTER_NEXT_ACTIONS
when 'Support Letter'
SUPPORT_LETTER_NEXT_ACTIONS
when 'Thank'
THANK_NEXT_ACTIONS
else
STANDRD_NEXT_ACTIONS
end
end
def self.all_next_action_options
options = {}
options['Call'] = CALL_NEXT_ACTIONS
options['Appointment'] = APPOINTMENT_NEXT_ACTIONS
options['Email'] = EMAIL_NEXT_ACTIONS
options['Facebook Message'] = FACEBOOK_MESSAGE_NEXT_ACTIONS
options['Text Message'] = TEXT_NEXT_ACTIONS
options['Talk to In Person'] = TALK_TO_IN_PERSON_NEXT_ACTIONS
options['Prayer Request'] = PRAYER_REQUEST_NEXT_ACTIONS
options['Letter'] = LETTER_NEXT_ACTIONS
options['Pre Call Letter'] = PRE_CALL_LETTER_NEXT_ACTIONS
options['Reminder Letter'] = REMINDER_LETTER_NEXT_ACTIONS
options['Support Letter'] = SUPPORT_LETTER_NEXT_ACTIONS
options['Thank'] = THANK_NEXT_ACTIONS
options['default'] = STANDRD_NEXT_ACTIONS
options
end
def self.all_result_options
options = {}
options['Call'] = CALL_RESULTS
options['Appointment'] = APPOINTMENT_RESULTS
options['Email'] = EMAIL_RESULTS
options['Facebook Message'] = FACEBOOK_MESSAGE_RESULTS
options['Text Message'] = TEXT_RESULTS
options['Talk to In Person'] = TALK_TO_IN_PERSON_RESULTS
options['Letter'] = LETTER_RESULTS
options['Pre Call Letter'] = PRE_CALL_LETTER_RESULTS
options['Reminder Letter'] = REMINDER_LETTER_RESULTS
options['Support Letter'] = SUPPORT_LETTER_RESULTS
options['Thank'] = THANK_RESULTS
options['default'] = STANDARD_RESULTS
options
end
def self.alert_frequencies
{
'0' => _('at the time of event'),
'300' => _('5 minutes before'),
'900' => _('15 minutes before'),
'1800' => _('30 minutes before'),
'3600' => _('1 hour before'),
'7200' => _('2 hours before'),
'86400' => _('1 day before'),
'172800' => _('2 days before'),
'604800' => _('1 week before')
}
end
def self.mobile_alert_frequencies
{
'0' => _('at the time of event'),
'300' => _('5 minutes before'),
'900' => _('15 minutes before'),
'1800' => _('30 minutes before'),
'3600' => _('1 hour before'),
'7200' => _('2 hours before'),
'86400' => _('1 day before'),
'172800' => _('2 days before'),
'604800' => _('1 week before')
}
end
private
def update_completed_at
return unless changed.include?('completed')
if completed
self.completed_at ||= completed? ? Time.now : nil
self.start_at ||= completed_at
self.result = 'Done' if result.blank?
else
self.completed_at = ''
self.result = ''
end
end
def update_contact_uncompleted_tasks_count
contacts.map(&:update_uncompleted_tasks_count) unless skip_contact_task_counter_update
end
def queue_sync_to_google_calendar
return if google_sync_should_not_take_place?
account_list.google_integrations.each do |google_integration|
GoogleCalendarSyncTaskWorker.perform_async(google_integration.id, id)
end
end
def google_sync_should_not_take_place?
result.present? || start_at.nil? || Time.now > start_at
end
def log_newsletter
letter_type = activity_type.sub('Newsletter - ', '')
contacts_ids = account_list.contacts.where(send_newsletter: [letter_type, 'Both']).ids
contacts_ids.each do |contact_id|
task = Task.new(
account_list: account_list,
subject: subject,
activity_type: activity_type,
completed_at: completed_at,
completed: completed
)
task.activity_contacts.new(contact_id: contact_id, skip_contact_task_counter_update: completed)
comments.each do |comment|
task.comments.new(person_id: comment.person_id, body: comment.body)
end
task.skip_contact_task_counter_update = completed
task.save
end
end
def should_log_to_all_contacts?
(activity_type == 'Newsletter - Physical' || (activity_type == 'Newsletter - Email' && source.nil?)) &&
contacts.empty?
end
def auto_generate_subject
return unless subject.blank?
self.subject_hidden = true
self.subject = "#{activity_type} #{contacts.first&.name}"
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/referrers_spec.rb
|
<gh_stars>0
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts > Referrers' do
include_context :json_headers
documentation_scope = :contacts_api_referrers
let(:resource_type) { 'contacts' }
let(:user) { create(:user_with_account) }
let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) }
let(:contact_id) { contact.id }
let!(:resource) do
create(:contact).tap do |referrer|
contact.contacts_that_referred_me << referrer
end
end
let(:resource_attributes) do
%w(
avatar
church_name
created_at
deceased
direct_deposit
envelope_greeting
greeting
last_activity
last_appointment
last_donation
last_letter
last_phone_call
last_pre_call
last_thank
late_at
likely_to_give
locale
magazine
name
next_ask
no_appeals
no_gift_aid
notes
notes_saved_at
pledge_amount
pledge_currency
pledge_currency_symbol
pledge_frequency
pledge_received
pledge_start_date
send_newsletter
square_avatar
status
status_valid
suggested_changes
tag_list
timezone
uncompleted_tasks_count
updated_at
updated_in_db_at
website
)
end
let(:resource_associations) do
%w(
contacts_that_referred_me
)
end
context 'authorized user' do
before { api_login(user) }
# index
get '/api/v2/contacts/:contact_id/referrers' do
example 'list referrers', document: documentation_scope do
explanation 'List of Contacts that have referred the given Contact'
do_request
check_collection_resource(1, ['relationships'])
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/notification_type/missing_email_in_newsletter_spec.rb
|
require 'rails_helper'
describe NotificationType::MissingEmailInNewsletter do
subject { NotificationType::MissingEmailInNewsletter.first_or_initialize }
let(:account_list) { create(:account_list) }
let(:person_with_email) do
person = build(:person)
person.email_address = { email: '<EMAIL>' }
person.save
person
end
context '#missing_info_filter' do
it 'excludes contacts not on the email newsletter' do
contact = create(:contact)
contact.update(send_newsletter: nil)
account_list.contacts << contact
account_list.contacts << create(:contact, send_newsletter: 'Physical')
expect_filtered_contacts([])
end
it 'excludes enewsletter contacts with a person with a valid email address' do
contact = create(:contact, send_newsletter: 'Email')
contact.people << person_with_email
account_list.contacts << contact
expect_filtered_contacts([])
end
it 'excludes contacts with a person w/ email address, one person wo/ one' do
contact = create(:contact, send_newsletter: 'Email')
contact.people << person_with_email
contact.people << create(:person)
account_list.contacts << contact
expect_filtered_contacts([])
end
it 'includes enewsletter contacts with no people' do
contact = create(:contact, send_newsletter: 'Both')
account_list.contacts << contact
expect_filtered_contacts([contact])
end
it 'includes enewsletter contacts with a person with no email address' do
contact = create(:contact, send_newsletter: 'Both')
contact.people << create(:person)
account_list.contacts << contact
expect_filtered_contacts([contact])
end
it 'includes contacts on the newsletter with a historic email address' do
contact = create(:contact, send_newsletter: 'Email')
contact.people << person_with_email
person_with_email.email_addresses.first.update(historic: true)
account_list.contacts << contact
expect_filtered_contacts([contact])
end
end
def expect_filtered_contacts(expected)
actual = subject.missing_info_filter(account_list.contacts).to_a
expect(actual.size).to eq(expected.size)
expected.each { |c| expect(actual).to include(c) }
end
end
|
chuckmersereau/api_practice
|
app/services/admin/primary_address_fix.rb
|
class Admin::PrimaryAddressFix
def initialize(contact)
@contact = contact
end
def fix
mailing_address = @contact.mailing_address
make_historic_non_primary
# Contact#mailing_address returns Address.new if there is no mailing address
return if mailing_address.new_record?
if mailing_address.primary_mailing_address
make_others_non_primary(mailing_address)
else
mailing_address.update(primary_mailing_address: true)
end
end
private
def make_others_non_primary(mailing_address)
@contact.addresses.where.not(id: mailing_address.id)
.where(primary_mailing_address: true).find_each do |address|
# Update each record one-by-one so PaperTrail tracks changes
address.update(primary_mailing_address: false)
end
end
def make_historic_non_primary
@contact.addresses.where(historic: true, primary_mailing_address: true)
.find_each { |address| address.update(primary_mailing_address: false) }
end
end
|
chuckmersereau/api_practice
|
app/services/expected_totals_report/likely_donation.rb
|
<reponame>chuckmersereau/api_practice
class ExpectedTotalsReport::LikelyDonation
def initialize(contact:, recent_donations:, date_in_month:)
@contact = contact
@donations = recent_donations
@date_in_month = date_in_month
end
# How much the contact has already given this month
def received_this_month
@received_this_month ||= donations_total(months_ago: 0)
end
# How much we expect the contact will give more this month based on the logic
# below.
def likely_more
# Start with some basic checks of cases that make a gift unlikely
return 0.0 if unlikely_by_fields?
# The calculation will have a different basis depending on whether the
# partner gives with a weekly basis (weekly or fortnightly) or a monthly
# basis (month, quarterly, annual, etc.).
# NOTE: if we add the "twice a month" as a pledge frequency in the future
# this logic would need to be updated if we wanted to track that precisely
# (right now it would be treated as fortnightly)
if pledge_frequency < 1.0
likely_more_weekly_base
else
likely_more_monthly_base
end
end
private
# How many months back to check for monthly partners in order to determine
# whether they have enough track record to be considered a likely donor under
# certain circumstances (e.g. if they gave a partial amount this month).
MONTHS_BACK_TO_CHECK_FOR_MONTHLY = 3
# How many periods of gifts up to their pledge do we require for annual /
# biennial donors for them to be considered likely donors assuming they are
# not giving via a Recurring channel.
LONG_TIME_FRAME_NON_RECURRING_TRACK_RECORD_PERIODS = 2
attr_reader :contact
delegate :pledge_received?, :first_donation_date, :status, :pledge_amount,
:pledge_frequency, :last_donation_date, to: :contact
# Number of days of margin to allow for weekly gifts to still be considered
# consistent, e.g. if the margin is 3, then we consider someone as consistent
# for the past two weeks if they have two gifts in the past 2*7 + 3 = 17 days.
WEEKLY_MARGIN_DAYS = 3
# How many periods back to check for weekly / fortnightly donors.
WEEKLY_PERIODS_BACK_TO_CHECK = 2
# If the ministry partner has no pledge received, has no pledge, has never
# given or has already given their full pledge this month, assume they will
# not give any more this month.
def unlikely_by_fields?
!pledge_received? || pledge_amount.to_f.zero? || first_donation_date.nil? ||
last_donation_date.nil? || @donations.empty? || pledge_frequency.nil?
end
# How much more the ministry partner is expected to give if their pledge
# frequency basis is in weeks (weekly or fortnightly).
def likely_more_weekly_base
# Assume they will give zero if they didn't give recently
pledge_frequency_weeks = (pledge_frequency / weekly_frequency).round
return 0.0 unless gave_in_recent_weekly_periods?(pledge_frequency_weeks)
# Extrapolate the expected remaining they will give based on how many giving
# periods are left in the month.
periods_left_in_month(pledge_frequency_weeks) * pledge_amount
end
def periods_left_in_month(pledge_frequency_weeks)
(days_left_in_month / 7 / pledge_frequency_weeks).floor
end
def days_left_in_month
Time.days_in_month(@date_in_month.month, @date_in_month.year) -
@date_in_month.day
end
# Checks whether the ministry partner gave consistently in recent periods that
# have a weekly base. This is a fairly simple calculation for now that just
# checks whether a partner total gifts is at least their pledge over the
# recent period range.
def gave_in_recent_weekly_periods?(pledge_frequency_weeks)
# Add in a couple of margin days in case it takes a couple of days to
# process the weekly / fortnightly gifts.
days_back_to_check = pledge_frequency_weeks * 7 * WEEKLY_PERIODS_BACK_TO_CHECK +
WEEKLY_MARGIN_DAYS
recent_total = sum_over_date_range(@date_in_month - days_back_to_check, @date_in_month)
recent_total >= pledge_amount * WEEKLY_PERIODS_BACK_TO_CHECK
end
def weekly_frequency
Contact.pledge_frequencies.keys.first
end
def sum_over_date_range(from, to)
@donations.select { |d| d.donation_date >= from && d.donation_date <= to }
.sum(&:amount)
end
def likely_more_monthly_base
# Do some basic checks first for common cases when we would assume a partner
# will not give any more this month.
return 0.0 if received_this_month >= pledge_amount || unlikely_by_donation_history?
# Assuming there isn't anything in the fields or the donation history that
# indicates that this partner would be unlikely to give this month, then
# by default assume they will give their pledge amount minus what they gave so
# far. This can happen e.g. if a contact gives $100/mo but they give twice
# per month. Then at one part of the month they have given $50, so assuming
# they are consistent, at that opint the likely amount more is still $50.
amount_under_pledge_this_month
end
# Use slightly different logic for using the donation history to identify
# partners unlikely to give this month.
def unlikely_by_donation_history?
if pledge_frequency <= 1
unlikely_for_monthly?
elsif pledge_frequency <= 3
unlikely_for_bi_monthly_or_quarterly?
else
unlikely_for_long_time_frame?
end
end
# For monthly donors, consider a few different scenarios as monthly donors may
# sometimes miss a month and then make it up later.
def unlikely_for_monthly?
gave_less_this_month_and_not_much_track_record? ||
multiple_giving_gaps_recently? ||
behind_on_pledge_recently?
end
def gave_less_this_month_and_not_much_track_record?
received_this_month > 0.0 &&
received_this_month < pledge_amount &&
!given_pledge_in_past?(periods_back: MONTHS_BACK_TO_CHECK_FOR_MONTHLY)
end
def multiple_giving_gaps_recently?
# A giving cap only occurs if the partner had previously started their
# giving. Someone who gave for the first time last month has no giving gaps.
had_gift_in_further_past? && multiple_recent_months_below_pledge?
end
def had_gift_in_further_past?
month_index(first_donation_date) <=
month_index(MONTHS_BACK_TO_CHECK_FOR_MONTHLY.months.ago)
end
def multiple_recent_months_below_pledge?
periods_below_pledge(periods_back: MONTHS_BACK_TO_CHECK_FOR_MONTHLY) > 1
end
def behind_on_pledge_recently?
!averaging_to_pledge?(periods_back: MONTHS_BACK_TO_CHECK_FOR_MONTHLY)
end
# For bi-monthly (every other month) and quarterly donors, just look at
# whether they gave their last the same number of months ago as their pledge
# frequency, i.e. 3 months ago for quarterly or 2 months ago for bi-monthly.
# That will indicate that this month is the month they give and that we should
# expect them to give. This isn't really as complete of a check as the monthly
# cases above but it's a decent first approximation.
def unlikely_for_bi_monthly_or_quarterly?
last_gift_months_ago = months_ago(last_donation_date)
last_gift_months_ago != pledge_frequency.to_i
end
# For long time frame donors (every 6, 12 or 24 months), take the stance that
# they probably won't give unless they have enough track record. Specifically,
# we consider they have enough track record if their past gift was Recurring
# or if they had two on-time full-pledge gifts in the past two periods.
def unlikely_for_long_time_frame?
!enough_track_record_for_long_time_frame_partner? &&
!gave_on_time_last_period_and_by_recurring_channel?
end
def enough_track_record_for_long_time_frame_partner?
given_pledge_in_past?(
periods_back: LONG_TIME_FRAME_NON_RECURRING_TRACK_RECORD_PERIODS
)
end
def gave_on_time_last_period_and_by_recurring_channel?
given_pledge_in_past?(periods_back: 1) &&
gave_by_recurring_channel?(months_back: pledge_frequency.to_i)
end
def gave_by_recurring_channel?(months_back:)
@donations.any? do |donation|
months_ago(donation.donation_date) == months_back &&
donation.channel == 'Recurring'
end
end
def amount_under_pledge_this_month
[0.0, pledge_amount - donations_total(months_ago: 0)].max
end
def given_pledge_in_past?(periods_back:)
periods_below_pledge(periods_back: periods_back).zero?
end
def averaging_to_pledge?(periods_back:)
periods_back = [periods_back, first_donation_periods_back].min
total_for_periods = periods_back.times.sum do |periods_back_index|
months_ago = (periods_back_index + 1) * pledge_frequency.to_i
donations_total(months_ago: months_ago)
end
total_for_periods >= pledge_amount * periods_back
end
def first_donation_periods_back
months_ago(first_donation_date) / pledge_frequency.to_i
end
def periods_below_pledge(periods_back:)
periods_back.times.count do |periods_back_index|
months_ago = (periods_back_index + 1) * pledge_frequency.to_i
donations_total(months_ago: months_ago) < pledge_amount
end
end
def donations_total(months_ago:)
@totals_by_months_ago ||= calc_totals_by_months_ago
@totals_by_months_ago[months_ago] || 0.0
end
def calc_totals_by_months_ago
@donations.each_with_object({}) do |donation, totals_by_month|
months_ago = months_ago(donation.donation_date)
totals_by_month[months_ago] ||= 0.0
totals_by_month[months_ago] += donation.tendered_amount.to_f
end
end
def months_ago(date)
current_month_index - month_index(date)
end
def current_month_index
@current_month_index ||= month_index(@date_in_month)
end
def month_index(date)
date.year * 12 + date.month
end
end
|
chuckmersereau/api_practice
|
app/serializers/person/website_serializer.rb
|
<filename>app/serializers/person/website_serializer.rb
class Person::WebsiteSerializer < ApplicationSerializer
type :websites
attributes :created_at,
:primary,
:updated_at,
:url
end
|
chuckmersereau/api_practice
|
spec/support/shared_model_examples/updatable_only_when_source_is_mpdx_validation_examples.rb
|
RSpec.shared_examples 'updatable_only_when_source_is_mpdx_validation_examples' do |options = {}|
options[:attributes] ||= []
def change_attribute(record, attribute)
new_value = if attribute.to_s.ends_with?('date') || attribute.to_s.ends_with?('_at')
rand(1..100).days.ago
else
"a#{record.send(attribute)}z"
end
record.send("#{attribute}=", new_value)
end
options[:attributes].each do |attribute|
describe "#{attribute} validation" do
context 'when source is MPDX or Manual' do
it 'does not validate unsaved records' do
record = build(options[:factory_type])
%w(manual MPDX).each do |source|
record.source = source
change_attribute(record, attribute)
expect(record.valid?).to be true
expect(record.errors[attribute]).to be_blank
end
end
it 'permits updates to existing records' do
record = create(options[:factory_type])
%w(manual MPDX).each do |source|
record.source = source
change_attribute(record, attribute)
expect(record.valid?).to be true
expect(record.errors[attribute]).to be_blank
end
end
end
context 'when source is not MPDX' do
it 'does not validate unsaved records' do
record = build(options[:factory_type])
record.source = 'unknown'
change_attribute(record, attribute)
expect(record.valid?).to be true
expect(record.errors[attribute]).to be_blank
end
it 'does not permit updates to existing records' do
record = create(options[:factory_type])
record.source = 'unknown'
change_attribute(record, attribute)
expect(record.valid?).to be false
expect(record.errors[attribute]).to be_present
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/lib/batch_request_handler/batch_request_spec.rb
|
require 'spec_helper'
describe BatchRequestHandler::BatchRequest do
let(:batched_requests) do
[
{
method: 'GET',
path: '/api/v2/users'
},
{
method: 'GET',
path: '/api/v2/constants'
},
{
method: 'POST',
path: '/api/v2/contacts',
body: '{}'
}
]
end
let(:batch_request_json) { { requests: batched_requests } }
let(:batch_request_body) { JSON.dump(batch_request_json) }
let(:env) { Rack::MockRequest.env_for('/api/v2/batch', method: 'POST', input: batch_request_body) }
subject { BatchRequestHandler::BatchRequest.new(env) }
describe '#add_instrumentation' do
let(:instrument_class) { double('instrument') }
context 'with a matching instrument class' do
before do
allow(instrument_class).to receive(:enabled_for?).with(subject).and_return(true)
end
it 'should add an instance of the class' do
expect(instrument_class).to receive(:new).with(subject.params)
subject.add_instrumentation(instrument_class)
end
end
context 'with a non matching instrument class' do
before do
allow(instrument_class).to receive(:enabled_for?).with(subject).and_return(false)
end
it 'should add an instance of the class' do
expect(instrument_class).to_not receive(:new)
subject.add_instrumentation(instrument_class)
end
end
end
describe '#process' do
let(:app) { -> (_env) { [200, { 'Content-Type' => 'text/plain' }, ['Hello World']] } }
context 'with two instrumentations' do
let(:instrument_one_class) { Class.new(BatchRequestHandler::Instrument) }
let(:instrument_one_instance) { instrument_one_class.new({}) }
let(:instrument_two_class) { Class.new(BatchRequestHandler::Instrument) }
let(:instrument_two_instance) { instrument_two_class.new({}) }
before do
allow(instrument_one_class).to receive(:new).and_return(instrument_one_instance)
allow(instrument_two_class).to receive(:new).and_return(instrument_two_instance)
subject.add_instrumentation(instrument_one_class)
subject.add_instrumentation(instrument_two_class)
end
it 'should call all the instrumented hooks in order' do
expect(instrument_one_instance).to receive(:around_perform_requests).and_call_original.ordered
expect(instrument_two_instance).to receive(:around_perform_requests).and_call_original.ordered
batched_requests.length.times do
expect(instrument_one_instance).to receive(:around_perform_request).and_call_original.ordered
expect(instrument_two_instance).to receive(:around_perform_request).and_call_original.ordered
expect(app).to receive(:call).and_call_original.ordered
end
expect(instrument_one_instance).to receive(:around_build_response).and_call_original.ordered
expect(instrument_two_instance).to receive(:around_build_response).and_call_original.ordered
subject.process(app)
end
end
end
end
|
chuckmersereau/api_practice
|
app/policies/donation_amount_recommendation_policy.rb
|
class DonationAmountRecommendationPolicy < ApplicationPolicy
attr_reader :contact,
:resource,
:user
def initialize(context, resource)
@user = context.user
@contact = context.contact
@resource = resource
end
private
def resource_owner?
user.account_lists.exists?(contact.account_list_id)
end
end
|
chuckmersereau/api_practice
|
spec/controllers/concerns/pundit_helpers_spec.rb
|
<gh_stars>0
require 'rails_helper'
class PunditHelpersTestController < Api::V2Controller
skip_before_action :validate_and_transform_json_api_params
private
def contact_id_params
params.require(:data).collect { |hash| hash[:id] }
end
def pundit_user
PunditContext.new(current_user)
end
end
describe Api::V2Controller do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list: account_list) }
let!(:contact_two) { create(:contact, account_list: account_list) }
describe '#bulk_authorize' do
controller PunditHelpersTestController do
def show
@resources = Contact.where(id: contact_id_params)
render text: bulk_authorize(@resources)
end
end
before do
routes.draw { get 'show' => 'pundit_helpers_test#show' }
api_login(user)
end
it 'authorizes when current user owns all resources' do
get :show, data: [{ id: contact_one.id }, { id: contact_two.id }]
expect(response.status).to eq(200)
expect(response.body).to eq('true')
end
it 'does not authorize when current user owns some of resources' do
get :show, data: [{ id: contact_one.id }, { id: create(:contact).id }]
expect(response.status).to eq(403)
expect(response.body).to_not eq('true')
end
it 'does not authorize when current user owns none of resources' do
get :show, data: [{ id: create(:contact).id }, { id: create(:contact).id }]
expect(response.status).to eq(403)
expect(response.body).to_not eq('true')
end
it 'does not perform authorization if resources do not exist' do
expect do
get :show, data: [{ id: create(:task).id }, { id: create(:task).id }]
end.to raise_error Pundit::AuthorizationNotPerformedError
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/account_list_serializer.rb
|
<reponame>chuckmersereau/api_practice<filename>app/serializers/account_list_serializer.rb
class AccountListSerializer < ApplicationSerializer
attributes :currency,
:default_currency,
:home_country,
:monthly_goal,
:name,
:salary_organization,
:tester,
:total_pledges,
:active_mpd_start_at,
:active_mpd_finish_at,
:active_mpd_monthly_goal
has_many :notification_preferences
has_many :organization_accounts
belongs_to :primary_appeal, serializer: AppealSerializer
def salary_organization
object.salary_organization_id
end
end
|
chuckmersereau/api_practice
|
spec/services/reports/donation_monthly_totals_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Reports::DonationMonthlyTotals do
around do |test|
travel_to Time.zone.local(2017, 11, 2, 1, 4, 0) do
test.run
end
end
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:designation_account) { create(:designation_account, account_lists: [account_list]) }
let!(:donor_account) { create(:donor_account) }
let!(:contact) { create(:contact, account_list: account_list, donor_accounts: [donor_account]) }
let!(:cad_donation) do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
amount: 3, currency: 'CAD',
donation_date: 6.months.ago + 1.day)
end
let!(:eur_donation) do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
amount: 2, currency: 'EUR',
donation_date: 6.months.ago + 20.days)
end
before do
account_list.update(salary_currency: 'NZD')
create(:currency_rate, exchanged_on: 6.months.ago + 1.day, code: 'CAD', rate: 1.1)
create(:currency_rate, exchanged_on: 6.months.ago + 1.day, code: 'NZD', rate: 0.7)
create(:currency_rate, exchanged_on: 6.months.ago + 20.days, code: 'EUR', rate: 2.2)
create(:currency_rate, exchanged_on: 6.months.ago + 20.days, code: 'NZD', rate: 0.8)
end
subject do
described_class.new(account_list: account_list,
start_date: 6.months.ago - 1.day,
end_date: 5.months.ago)
end
context 'donation_totals_by_month' do
let(:totals) do
[
{
donor_currency: 'EUR',
total_in_donor_currency: 2.0,
converted_total_in_salary_currency:
CurrencyRate.convert_on_date(
amount: 2.0,
date: 6.months.ago + 20.days,
from: 'EUR',
to: account_list.salary_currency
)
},
{
donor_currency: 'CAD',
total_in_donor_currency: 3.0,
converted_total_in_salary_currency:
CurrencyRate.convert_on_date(
amount: 3.0,
date: 6.months.ago + 1.day,
from: 'CAD',
to: account_list.salary_currency
)
}
]
end
let(:months) do
[6.months.ago.beginning_of_month.to_date, 5.months.ago.beginning_of_month.to_date]
end
it 'returns a hash with monthly totals by currency' do
subject_totals = subject.donation_totals_by_month.map { |m| m[:totals_by_currency] }.flatten
subject_months = subject.donation_totals_by_month.map { |m| m[:month] }
expect(subject_months).to contain_exactly(*months)
expect(subject_totals).to contain_exactly(*totals)
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/invites_controller.rb
|
<gh_stars>0
class Api::V2::AccountLists::InvitesController < Api::V2Controller
resource_type :account_list_invites
skip_after_action :verify_authorized, only: :update
def index
authorize load_account_list, :show?
load_invites
render json: @invites.preload_valid_associations(include_associations),
meta: meta_hash(@invites),
include: include_params,
fields: field_params
end
def show
load_invite
authorize_invite
render_invite
end
def create
if authorize_and_save_invite
render_invite
else
render json: { success: false, errors: ['Could not send invite'] },
status: 400
end
end
def update
load_account_list_invite
validate_account_list_invite_code
if @invite.accept(current_user)
render_invite
else
render json: { success: false, errors: ['No longer valid'] },
status: 410
end
end
def destroy
load_invite
authorize_invite
destroy_invite
end
private
def validate_account_list_invite_code
if params.dig(:account_list_invite, :code).blank?
raise Exceptions::BadRequestError, "'data/attributes/code' cannot be blank"
end
raise Exceptions::BadRequestError, "'data/attributes/code' is invalid" unless valid_invite_code?
end
def permitted_filters
[:invite_user_as]
end
def valid_invite_code?
params.dig(:account_list_invite, :code) == load_account_list_invite.code
end
def destroy_invite
@invite.cancel(current_user)
head :no_content
end
def load_invites
@invites = invite_scope.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def load_invite
@invite ||= AccountListInvite.find(params[:id])
end
def render_invite
render json: @invite,
status: success_status,
include: include_params,
fields: field_params
end
def authorize_and_save_invite
invite_user_as = invite_params['invite_user_as'] || 'user'
email = invite_params['recipient_email']
authorize AccountListInvite.new(invited_by_user: current_user,
recipient_email: email,
invite_user_as: invite_user_as,
account_list: load_account_list), :update?
return false unless EmailValidator.valid?(email)
@invite = AccountListInvite.send_invite(current_user, load_account_list, email, invite_user_as)
end
def authorize_invite
authorize @invite
end
def invite_params
params
.require(:account_list_invite)
.permit(AccountListInvite::PERMITTED_ATTRIBUTES)
end
def invite_scope
load_account_list.account_list_invites.active
end
def load_account_list
@account_list ||= AccountList.find(params[:account_list_id])
end
def load_account_list_invite
@invite ||= AccountListInvite.find_by!(id: params[:id], account_list: load_account_list)
end
def pundit_user
PunditContext.new(current_user, account_list: load_account_list)
end
def default_sort_param
AccountListInvite.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160517174101_add_contact_locale_to_mail_chimp_members.rb
|
<filename>db/migrate/20160517174101_add_contact_locale_to_mail_chimp_members.rb
class AddContactLocaleToMailChimpMembers < ActiveRecord::Migration
def change
add_column :mail_chimp_members, :contact_locale, :string
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/people/phones_controller.rb
|
class Api::V2::Contacts::People::PhonesController < Api::V2Controller
resource_type :phone_numbers
def index
authorize_index
load_phones
render_phones
end
def show
load_phone
authorize_phone
render_phone
end
def create
persist_phone
end
def update
load_phone
persist_phone
end
def destroy
load_phone
authorize_phone
destroy_phone
end
private
def destroy_phone
@phone.destroy
head :no_content
end
def render_phones
render json: @phones.preload_valid_associations(include_associations),
meta: meta_hash(@phones),
include: include_params,
fields: field_params
end
def phone_params
params
.require(:phone_number)
.permit(phone_attributes)
end
def phone_attributes
PhoneNumber::PERMITTED_ATTRIBUTES
end
def phone_scope
current_person.phone_numbers
end
def current_contact
@contact ||= Contact.find(params[:contact_id])
end
def current_person
@person ||= current_contact.people.find(params[:person_id])
end
def authorize_index
authorize(current_person, :show?)
end
def authorize_phone
authorize(current_person, :show?)
authorize(@phone)
end
def build_phone
@phone ||= phone_scope.build
@phone.assign_attributes(phone_params)
end
def load_phone
@phone ||= phone_scope.find(params[:id])
end
def load_phones
@phones = phone_scope.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def persist_phone
build_phone
authorize_phone
if save_phone
render_phone
else
render_with_resource_errors(@phone)
end
end
def render_phone
render json: @phone,
status: success_status,
include: include_params,
fields: field_params
end
def save_phone
@phone.save(context: persistence_context)
end
def pundit_user
PunditContext.new(current_user, contact: current_contact)
end
def default_sort_param
PhoneNumber.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2_controller_spec.rb
|
require 'rails_helper'
describe Api::V2Controller do
include_examples 'common_variables'
let(:user) { create(:user_with_account) }
let(:account_list) { create(:account_list) }
let(:response_json) { JSON.parse(response.body).deep_symbolize_keys }
describe 'controller callbacks' do
controller(Api::V2Controller) do
skip_after_action :verify_authorized
resource_type :contacts
def index
raise 'Test Error' if params[:raise_error] == true
render json: {
filter_params: filter_params,
filter_params_with_id: permitted_filter_params_with_ids,
include_params: include_params,
current_time_zone: current_time_zone.name,
current_locale: I18n.locale
}
end
def create
render json: params[:test][:attributes] || {}
end
def update
render json: params[:test][:attributes] || {}
end
private
def permitted_filters
[:contact_id, :time_at]
end
end
describe 'JWT Authorize' do
it 'doesnt allow not signed in users to access the api' do
get :index
expect(response.status).to eq(401), invalid_status_detail
end
it 'allows signed_in users with a valid token to access the api' do
api_login(user)
get :index
expect(response.status).to eq(200), invalid_status_detail
end
end
describe 'Update user tracked info' do
context "the user's current_sign_in_at is recent" do
before do
api_login(user)
user.update_columns(sign_in_count: 0, current_sign_in_at: 6.hours.ago)
end
it 'does not update the user tracked info for an authenticated user' do
expect { get :index }.to_not change { user.reload.current_sign_in_at }
expect(user.sign_in_count).to eq(0)
end
end
context "the user's current_sign_in_at is a long time ago" do
before do
api_login(user)
user.update_columns(sign_in_count: 0, current_sign_in_at: 1.week.ago)
end
it 'updates the user tracked info for an authenticated user' do
travel_to(Time.current) do
expect { get :index }.to change { user.reload.sign_in_count }.from(0).to(1)
expect(user.current_sign_in_at).to eq(Time.current)
end
end
end
it 'does not update tracked fields if user is not authenticated' do
user
expect(User.count).to be_positive
expect_any_instance_of(User).to_not receive(:update_tracked_fields!)
expect_any_instance_of(User).to_not receive(:update_tracked_fields)
get :index
end
end
describe 'Filters' do
let(:contact) { create(:contact) }
let(:fake_contact_id) { SecureRandom.uuid }
it 'allows a user to filter by id' do
api_login(user)
get :index, filter: { contact_id: contact.id }
expect(response.status).to eq(200), invalid_status_detail
expect(response_json[:filter_params][:contact_id]).to eq(contact.id)
expect(response_json[:filter_params_with_id][:contact_id]).to eq(contact.id)
end
context '#date range' do
it 'returns a 400 when a user tries to filter with an invalid date range' do
api_login(user)
get :index, filter: { time_at: '2016-20-12...2016-23-12' }
expect(response.status).to eq(400), invalid_status_detail
expect(response.body).to include(
"Wrong format of date range for filter 'time_at', should follow 'YYYY-MM-DD...YYYY-MM-DD' for dates"
)
end
end
end
describe 'Includes' do
let(:contact) { create(:contact) }
it "includes all associated resources when the '*' flag is passed" do
api_login(user)
get :index, include: '*'
expect(response.status).to eq(200), invalid_status_detail
expect(response_json[:include_params]).to eq(ContactSerializer._reflections.keys.map(&:to_s))
end
end
context 'Timezone specific requests' do
before { travel_to(Time.local(2017, 1, 1, 12, 0, 0).getlocal) }
after { travel_back }
context 'When the user has a specified Time Zone' do
let(:zone) do
ActiveSupport::TimeZone.all.detect { |zone| Time.zone != zone }
end
let(:user) do
create(:user).tap do |user|
user.assign_time_zone(zone)
end
end
it "returns the correct time in the user's timezone" do
api_login(user)
get :index
expect(response.status).to eq(200), invalid_status_detail
expect(response_json[:current_time_zone]).to eq zone.name
expect(response_json[:current_time_zone]).not_to eq Time.zone.name
end
end
context "When the user doesn't have a specified Time Zone" do
let(:user) do
create(:user).tap do |user|
preferences = user.preferences
preferences[:time_zone] = nil
user.preferences = preferences
end
end
it "returns the application's Time Zone" do
api_login(user)
get :index
expect(response.status).to eq(200), invalid_status_detail
expect(response_json[:current_time_zone]).to eq Time.zone.name
end
end
end
context 'Locale specific requests' do
let(:italian_user) { create(:user, locale: 'it') }
it 'sets the correct locale defined in user preferences' do
api_login(italian_user)
get :index
expect(response_json[:current_locale]).to eq 'it'
end
it 'sets the correct locale when specified in the accept-language header' do
api_login(user)
request.env['HTTP_ACCEPT_LANGUAGE'] = 'fr-FR,fr-CA;q=0.8'
get :index
expect(response_json[:current_locale]).to eq 'fr-FR'
end
it 'defaults to english when no preference is defined' do
api_login(user)
get :index
expect(response_json[:current_locale]).to eq 'en-US'
end
it 'resets the locale constant to en-US in case of error' do
api_login(italian_user)
expect do
get :index, raise_error: true
end.to raise_error 'Test Error'
expect(I18n.locale.to_s).to eq 'en-US'
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20150202221959_add_master_address_id_constraint.rb
|
<filename>db/migrate/20150202221959_add_master_address_id_constraint.rb
class AddMasterAddressIdConstraint < ActiveRecord::Migration
def change
Address.where(master_address_id: nil).find_each(batch_size: 500) do |address|
address.find_or_create_master_address
address.save!
end
change_column_null :addresses, :master_address_id, false
end
end
|
chuckmersereau/api_practice
|
app/services/donation_imports/siebel/donor_importer.rb
|
<reponame>chuckmersereau/api_practice<filename>app/services/donation_imports/siebel/donor_importer.rb<gh_stars>0
class DonationImports::Siebel
class DonorImporter
attr_reader :siebel_import
delegate :organization,
:organization_account,
:parse_date,
to: :siebel_import
delegate :designation_profiles, to: :organization_account
def initialize(siebel_import)
@siebel_import = siebel_import
end
def import_donors(date_from: nil)
return unless designation_numbers.present?
@date_from = date_from
designation_profiles.each do |designation_profile|
import_donors_by_designation_profile(designation_profile)
end
end
private
def import_donors_by_designation_profile(designation_profile)
siebel_donors.each do |siebel_donor|
donor_account = add_or_update_donor_account(designation_profile.account_list, siebel_donor)
if siebel_donor.type == 'Business'
add_or_update_company(designation_profile.account_list, siebel_donor, donor_account)
end
end
end
def siebel_donors
@siebel_donors ||= fetch_siebel_donors
end
def fetch_siebel_donors
SiebelDonations::Donor.find(having_given_to_designations: designation_numbers.join(','),
contact_filter: :all,
account_address_filter: :primary,
contact_email_filter: :all,
contact_phone_filter: :all)
end
def designation_numbers
@designation_numbers ||=
DesignationAccount.joins(:designation_profile_accounts)
.where(designation_profile_accounts: { designation_profile: designation_profiles })
.pluck(:designation_number)
end
def add_or_update_company(account_list, siebel_donor, donor_account)
company = fetch_company_from_siebel_donor(account_list, siebel_donor)
contact = siebel_donor.primary_contact || SiebelDonations::Contact.new
address = siebel_donor.primary_address || SiebelDonations::Address.new
company.update!(
name: siebel_donor.account_name,
phone_number: contact.primary_phone_number.try(:phone),
street: fetch_street_from_address(address),
city: address.city,
state: address.state,
postal_code: address.zip
)
if company.persisted? && donor_account.master_company == company.master_company
donor_account.update!(master_company: company.master_company)
end
company
end
def fetch_company_from_siebel_donor(account_list, siebel_donor)
master_company = MasterCompany.find_by(name: siebel_donor.account_name)
if master_company
company = organization_account.user.partner_companies.find_by(master_company_id: master_company.id)
end
company || account_list.companies.new(master_company: master_company)
end
def fetch_street_from_address(address)
[address.address1, address.address2, address.address3, address.address4].compact.join("\n")
end
def add_or_update_donor_account(account_list, siebel_donor)
donor_account = find_or_initialize_donor_account_from_siebel_donor(siebel_donor)
donor_account.update!(name: siebel_donor.account_name, donor_type: siebel_donor.type)
contact = donor_account.link_to_contact_for(account_list)
save_donor_addresses(siebel_donor, donor_account, contact)
save_donor_people(siebel_donor, donor_account, contact)
donor_account
end
def save_donor_addresses(siebel_donor, donor_account, contact)
siebel_donor.addresses&.each do |siebel_address|
next unless relevant_siebel_address?(siebel_address)
add_or_update_address(siebel_address, donor_account, contact)
end
end
def relevant_siebel_address?(siebel_address)
@date_from.nil? || DateTime.parse(siebel_address.updated_at) > @date_from
end
def save_donor_people(siebel_donor, donor_account, contact)
# People are called contacts on siebel
siebel_donor.contacts&.each do |siebel_person|
next unless siebel_person_is_relevant?(siebel_person)
add_or_update_person(siebel_person, donor_account, contact)
end
end
def add_or_update_person(siebel_person, donor_account, contact)
PersonImporter.new(siebel_import)
.add_or_update_person_on_contact(siebel_person: siebel_person,
donor_account: donor_account,
contact: contact,
date_from: @date_from)
end
def siebel_person_is_relevant?(siebel_person)
@date_from.nil? || parse_date(siebel_person.updated_at) > @date_from
end
def find_or_initialize_donor_account_from_siebel_donor(siebel_donor)
organization.donor_accounts.where(account_number: siebel_donor.id).first_or_initialize
end
def add_or_update_address(siebel_address, donor_account, contact)
mpdx_address_instance = mpdx_address_instance_from_siebel_address(siebel_address, donor_account, contact)
mpdx_address_to_update = find_similar_mpdx_address_from_mpdx_address_instance(mpdx_address_instance, contact)
if mpdx_address_to_update
mpdx_address_attributes_needed = mpdx_address_instance.attributes.select { |_k, value| value }
mpdx_address_to_update.assign_attributes(mpdx_address_attributes_needed)
mpdx_address_to_update.save!(validate: false)
mpdx_address_to_update
else
contact.addresses.create(mpdx_address_instance.attributes)
end
end
def find_similar_mpdx_address_from_mpdx_address_instance(mpdx_address_instance, contact)
contact.addresses_including_deleted.find { |address| address.equal_to?(mpdx_address_instance) }
end
def mpdx_address_instance_from_siebel_address(siebel_address, donor_account, contact)
mpdx_address_instance = Address.new(street: [siebel_address.address1,
siebel_address.address2,
siebel_address.address3,
siebel_address.address4].compact.join("\n"),
city: siebel_address.city,
state: siebel_address.state,
postal_code: siebel_address.zip,
primary_mailing_address: should_be_primary?(
contact, siebel_address, donor_account
),
seasonal: siebel_address.seasonal,
location: siebel_address.type,
remote_id: siebel_address.id,
source: 'Siebel',
start_date: parse_date(siebel_address.updated_at),
source_donor_account: donor_account)
# Set the master address so we can match by the same address formatted differently
mpdx_address_instance.find_or_create_master_address
mpdx_address_instance
end
def should_be_primary?(contact, siebel_address, donor_account)
current_primary_address = contact.addresses.find_by(primary_mailing_address: true)
current_primary_address.blank? || (siebel_address.primary && current_primary_address.source == 'Siebel' &&
donor_account.present? && current_primary_address.source_donor_account == donor_account)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/appeal_contact/filter/pledged_to_appeal_spec.rb
|
<filename>spec/services/appeal_contact/filter/pledged_to_appeal_spec.rb
require 'rails_helper'
RSpec.describe AppealContact::Filter::PledgedToAppeal do
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!(:no_appeal_contact) { create(:contact, account_list_id: account_list.id) }
let!(:not_pledged_contact) { create(:contact, account_list_id: account_list.id) }
let!(:pledged_contact) { create(:contact, account_list_id: account_list.id) }
before do
not_pledged_contact.appeals << appeal
pledged_contact.appeals << appeal
pledged_contact.pledges << create(:pledge, account_list: account_list, appeal: appeal)
end
describe '#query' do
let(:appeal_contacts) { AppealContact.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(appeal_contacts, {}, nil)).to eq(nil)
expect(described_class.query(appeal_contacts, { pledged_to_appeal: '', appeal_id: appeal.id }, nil)).to eq(nil)
end
end
context 'filter by not pledged_to_appeal' do
it 'returns only contacts that have not pledged' do
filtered = described_class.query(appeal_contacts, { pledged_to_appeal: false, appeal_id: appeal.id }, nil).to_a
expect(filtered.collect(&:contact)).to match_array [not_pledged_contact]
end
end
context 'filter by pledged_to_appeal' do
it 'returns only contacts that have pledged' do
filtered = described_class.query(appeal_contacts, { pledged_to_appeal: true, appeal_id: appeal.id }, nil).to_a
expect(filtered.collect(&:contact)).to match_array [pledged_contact]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/donations_eager_loader_spec.rb
|
require 'rails_helper'
describe Contact::DonationsEagerLoader, '#contacts_with_donations' do
let(:account_list) { create(:account_list) }
let(:designation_account) { create(:designation_account) }
let(:donor_account) { create(:donor_account) }
let(:contact) do
create(:contact, account_list: account_list)
end
before do
account_list.designation_accounts << designation_account
contact.donor_accounts << donor_account
end
context '#contacts_with_donations' do
it 'returns contacts with loaded_donations set' do
donation = create(:donation, donor_account: donor_account,
designation_account: designation_account)
contacts = Contact::DonationsEagerLoader.new(account_list: account_list)
.contacts_with_donations
expect(contacts).to eq [contact]
expect(contacts.first.loaded_donations).to eq [donation]
end
it 'excludes contacts that do not match contact scoper' do
loader = Contact::DonationsEagerLoader
.new(account_list: account_list,
contacts_scoper: -> (contacts) { contacts.where(id: -1) })
expect(loader.contacts_with_donations).to be_empty
end
it 'excludes donations that do not match donation scoper' do
create(:donation, donation_date: Date.new(2015, 1, 1),
donor_account: donor_account,
designation_account: designation_account)
donations_scoper = lambda do |donations|
donations.where.not(donation_date: Date.new(2015, 1, 1))
end
contacts = Contact::DonationsEagerLoader
.new(account_list: account_list, donations_scoper: donations_scoper)
.contacts_with_donations
expect(contacts.first.loaded_donations).to be_empty
end
it 'excludes donations for designation not in account list' do
create(:donation, donor_account: donor_account,
designation_account: create(:designation_account))
contacts = Contact::DonationsEagerLoader.new(account_list: account_list)
.contacts_with_donations
expect(contacts).to eq [contact]
expect(contacts.first.loaded_donations).to be_empty
end
end
context '#donations_and_contacts' do
it 'returns donations and contacts with donations loaded_contact set' do
donation = create(:donation, donor_account: donor_account,
designation_account: designation_account)
donations, contacts = Contact::DonationsEagerLoader
.new(account_list: account_list)
.donations_and_contacts
expect(contacts).to eq [contact]
expect(donations).to eq [donation]
expect(donations.first.loaded_contact).to eq contact
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120314162022_create_donations.rb
|
class CreateDonations < ActiveRecord::Migration
def change
create_table :donations do |t|
t.string :remote_id
t.belongs_to :donor_account
t.belongs_to :designation_account
t.string :motivation
t.string :payment_method
t.string :tendered_currency
t.decimal :tendered_amount, precision: 8, scale: 2
t.string :currency
t.decimal :amount, precision: 8, scale: 2
t.text :memo
t.date :donation_date
t.timestamps null: false
end
add_index :donations, :donor_account_id
add_index :donations, [:designation_account_id, :remote_id], name: 'unique_donation_designation', unique: true
end
end
|
chuckmersereau/api_practice
|
config/initializers/adobe_campaigns.rb
|
<filename>config/initializers/adobe_campaigns.rb
# frozen_string_literal: true
Adobe::Campaign.configure do |config|
config.org_id = ENV['ADOBE_ORG_ID']
config.org_name = ENV['ADOBE_ORG_NAME']
config.tech_acct = ENV['ADOBE_TECH_ACCT']
config.api_key = ENV['ADOBE_API_KEY']
config.api_secret = ENV['ADOBE_API_SECRET']
config.signed_jwt = ENV['ADOBE_SIGNED_JWT']
end
|
chuckmersereau/api_practice
|
engines/auth/config/environments/production.rb
|
require 'omniauth'
OmniAuth.config.full_host = 'https://auth.mpdx.org'
|
chuckmersereau/api_practice
|
app/controllers/api/v2/admin/organizations_controller.rb
|
class Api::V2::Admin::OrganizationsController < Api::V2Controller
skip_after_action :verify_authorized
def create
authorize_organization
persist_organization
end
private
def authorize_organization
raise Pundit::NotAuthorizedError,
'must be admin level user to create organizations' unless current_user.admin
end
def persist_organization
build_organization
if save_organization
render_organization
else
render_with_resource_errors(@organization)
end
end
def render_organization
render json: @organization,
status: success_status,
include: include_params,
fields: field_params
end
def build_organization
@organization ||= organization_scope.create
@organization.attributes = organization_params
end
def save_organization
@organization.save
end
def organization_scope
::Organization
end
def organization_params
params.require(:organization)
.permit(:name, :org_help_url, :country).merge(
query_ini_url: "#{SecureRandom.hex(8)}.example.com",
api_class: 'OfflineOrg',
addresses_url: 'example.com'
)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160728174747_add_notification_to_activities.rb
|
<reponame>chuckmersereau/api_practice
class AddNotificationToActivities < ActiveRecord::Migration
def change
add_column :activities, :notification_type, :integer
add_column :activities, :notification_time_before, :integer
add_column :activities, :notification_time_unit, :integer
add_column :activities, :notification_scheduled, :boolean
end
end
|
chuckmersereau/api_practice
|
app/exhibits/constant_list_exhibit.rb
|
class ConstantListExhibit < DisplayCase::Exhibit
include ApplicationHelper
def self.applicable_to?(object)
object.class.name == 'ConstantList'
end
def bulk_update_options
{
'likely_to_give' => translate_array_to_strings(assignable_likely_to_give),
'send_newsletter' => translate_array_to_strings(assignable_send_newsletter),
'pledge_currency' => pledge_currencies,
'pledge_received' => translate_array_to_strings(pledge_received),
'status' => translate_array_to_strings(assignable_statuses)
}
end
def dates
Hash[DATE_FORMATS]
end
def languages
Hash[LANGUAGES_CONSTANT]
end
def locales
super.each_with_object({}) do |(name, code), hash|
native_name = TwitterCldr::Shared::Languages.translate_language(name, :en, code)
hash[code] = {
native_name: native_name,
english_name: format('%s (%s)', name, code)
}
end
end
def pledge_currencies
Hash[
codes.map { |code| [code.upcase, currency_information(code.upcase)] }
]
end
def pledge_received
%w(Yes No)
end
def activity_hashes
translate_array(activities)
end
def assignable_likely_to_give_hashes
translate_array(assignable_likely_to_give)
end
def assignable_location_hashes
translate_array(assignable_locations)
end
def assignable_send_newsletter_hashes
translate_array(assignable_send_newsletter)
end
def assignable_status_hashes
translate_array(assignable_statuses)
end
def bulk_update_option_hashes
{
'likely_to_give' => assignable_likely_to_give_hashes,
'pledge_currency' => pledge_currency_hashes,
'pledge_received' => pledge_received_hashes,
'send_newsletter' => assignable_send_newsletter_hashes,
'status' => assignable_status_hashes
}
end
def notification_hashes
translate_hash_with_key(notifications)
end
def pledge_currency_hashes
codes.map do |code|
currency = currency_information(code.upcase)
{
id: currency[:code],
key: currency[:code],
value: currency[:code_symbol_string]
}
end
end
def pledge_frequency_hashes
translate_hash_with_key(pledge_frequencies)
end
def pledge_received_hashes
translate_array(pledge_received)
end
def send_appeals_hashes
translate_hash(send_appeals)
end
def status_hashes
translate_array(statuses)
end
private
def currency_information(code)
twitter_cldr_hash = twitter_cldr_currency_information_hash(code)
{
code: code,
code_symbol_string: format('%s (%s)', code, twitter_cldr_hash[:symbol]),
name: twitter_cldr_hash[:name],
symbol: twitter_cldr_hash[:symbol]
}
end
def translate_array(array_of_strings)
array_of_strings.dup.map do |string|
{
id: string,
value: _(string)
}
end
end
def translate_hash(hash)
hash.collect do |key, value|
{
id: key,
value: _(value)
}
end
end
def translate_hash_with_key(hash)
hash.collect do |key, value|
{
id: value,
key: key,
value: _(value)
}
end
end
def translate_array_to_strings(array)
array.dup.map { |string| _(string) }
end
def twitter_cldr_currency_information_hash(code)
TwitterCldr::Shared::Currencies.for_code(code)
end
end
|
chuckmersereau/api_practice
|
app/models/notification_type/call_partner_once_per_year.rb
|
<filename>app/models/notification_type/call_partner_once_per_year.rb
class NotificationType::CallPartnerOncePerYear < NotificationType::TaskIfPeriodPast
def task_description_template(_notification = nil)
_('%{contact_name} have not had an attempted call logged in the past year. Call them.')
end
def task_activity_type
'Call'
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/people/facebook_accounts_controller.rb
|
<reponame>chuckmersereau/api_practice
class Api::V2::Contacts::People::FacebookAccountsController < Api::V2Controller
def index
authorize load_person, :show?
load_fb_accounts
render json: @fb_accounts.preload_valid_associations(include_associations),
meta: meta_hash(@fb_accounts),
include: include_params,
fields: field_params
end
def show
load_fb_account
authorize_fb_account
render_fb_account
end
def create
persist_fb_account
end
def update
load_fb_account
authorize_fb_account
persist_fb_account
end
def destroy
load_fb_account
authorize_fb_account
destroy_fb_account
end
private
def destroy_fb_account
@fb_account.destroy
head :no_content
end
def load_fb_accounts
@fb_accounts = fb_account_scope.where(filter_params)
.reorder(sorting_param)
.page(page_number_param)
.per(per_page_param)
end
def load_fb_account
@fb_account ||= fb_account_scope.find(params[:id])
end
def authorize_fb_account
authorize @fb_account
end
def render_fb_account
render json: @fb_account,
status: success_status,
include: include_params,
fields: field_params
end
def persist_fb_account
build_fb_account
authorize_fb_account
if save_fb_account
render_fb_account
else
render_with_resource_errors(@fb_account)
end
end
def build_fb_account
@fb_account ||= fb_account_scope.build
@fb_account.assign_attributes(fb_account_params)
end
def save_fb_account
@fb_account.save(context: persistence_context)
end
def fb_account_params
params.require(:facebook_account)
.permit(Person::FacebookAccount::PERMITTED_ATTRIBUTES)
end
def fb_account_scope
load_person.facebook_accounts
end
def load_person
@person ||= load_contact.people.find(params[:person_id])
end
def load_contact
@contact ||= Contact.find(params[:contact_id])
end
def pundit_user
action_name == 'index' ? PunditContext.new(current_user, contact: load_contact) : current_user
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/admin/resets_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Resets' do
include_context :json_headers
let(:admin_user) { create(:user, admin: true) }
let(:reset_user) { create(:user_with_account) }
let!(:key_account) { create(:key_account, person: reset_user) }
let(:account_list) { reset_user.account_lists.order(:created_at).first }
let(:request_type) { 'resets' }
let(:form_data) do
build_data(resetted_user_email: key_account.email,
reason: 'Resetting User Account',
account_list_name: account_list.name)
end
context 'authorized user' do
before { api_login(admin_user) }
post '/api/v2/admin/resets' do
with_options scope: [:data, :attributes] do
parameter :resetted_user_email, 'The Key/Relay Email of the user with access to the account to be reset'
parameter :reason, 'The reason for resetting this account'
parameter :account_list_name, 'The exact name of the account list to reset'
end
example 'Reset [CREATE]', document: false do
explanation 'This endpoint allows an admin to reset an account.'
do_request data: form_data
expect(response_status).to eq 200
expect(json_response['data']['attributes']['name']).to eq account_list.name
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/notification_type/long_time_frame_gift.rb
|
<reponame>chuckmersereau/api_practice<filename>app/models/notification_type/long_time_frame_gift.rb
class NotificationType::LongTimeFrameGift < NotificationType
LONG_TIME_FRAME_PLEDGE_FREQUENCY = 6
def check_contacts_filter(contacts)
contacts.financial_partners.where('pledge_amount > 0')
.where('pledge_frequency >= ?', LONG_TIME_FRAME_PLEDGE_FREQUENCY)
end
def check_for_donation_to_notify(contact)
contact.last_donation if contact.prev_month_donation_date.present? &&
contact.last_monthly_total == contact.pledge_amount
end
def interpolation_values(notification)
super(notification).merge(frequency: _(Contact.pledge_frequencies[notification.contact.pledge_frequency]))
end
def task_description_template(notification = nil)
if notification&.account_list&.designation_accounts&.many?
_('%{contact_name} gave their %{frequency} gift of %{amount} '\
'on %{date} to %{designation}. Send them a Thank You.')
else
_('%{contact_name} gave their %{frequency} gift of %{amount} on %{date}. Send them a Thank You.')
end
end
end
|
chuckmersereau/api_practice
|
app/exhibits/activity_comment_exhibit.rb
|
<reponame>chuckmersereau/api_practice
class ActivityCommentExhibit < DisplayCase::Exhibit
def self.applicable_to?(object)
object.class.name == 'ActivityComment'
end
def body
return if self[:body].nil?
EmailReplyParser.parse_reply(self[:body])
end
end
|
chuckmersereau/api_practice
|
spec/factories/prayer_letters_accounts.rb
|
<reponame>chuckmersereau/api_practice
FactoryBot.define do
factory :prayer_letters_account do
token '<PASSWORD>'
oauth2_token '<PASSWORD>'
valid_token true
association :account_list
end
factory :prayer_letters_account_oauth2, class: PrayerLettersAccount do
oauth2_token '<PASSWORD>'
valid_token true
association :account_list
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/reports/goal_progresses_spec.rb
|
<filename>spec/acceptance/api/v2/reports/goal_progresses_spec.rb
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Reports > Account Goal Progress Report' do
include_context :json_headers
documentation_scope = :reports_api_goal_progress
let(:resource_type) { 'reports_goal_progresses' }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:resource_attributes) do
%w(
created_at
in_hand_percent
monthly_goal
pledged_percent
received_pledges
salary_balance
salary_currency_or_default
salary_organization_id
total_pledges
updated_at
updated_in_db_at
)
end
context 'authorized user' do
before { api_login(user) }
# show
get '/api/v2/reports/goal_progress' do
parameter 'filter[account_list_id]', 'Account List ID', required: true
response_field 'data', 'Data object', type: 'Object'
with_options scope: [:data, :attributes] do
response_field 'created_at', 'Time when report was observed', type: 'String'
response_field 'in_hand_percent', 'Percent of monthly goal in hand', type: 'String'
response_field 'monthly_goal', 'The account list monthly goal', type: 'String'
response_field 'pledged_percent', 'Percent of monthly goal pledged', type: 'String'
response_field 'received_pledges', 'Percent of monthly goal received', type: 'String'
response_field 'salary_balance', 'Balance of organization salary accounts', type: 'String'
response_field 'salary_currency_or_default', 'Currency of salary', type: 'String'
response_field 'salary_organization_id', 'ID of salary Organization', type: 'String'
response_field 'total_pledges', 'Total pledges', type: 'String'
end
with_options scope: [:data, :relationships] do
response_field 'account_list', 'Account List', type: 'Object'
end
example 'Goal Progress [LIST]', document: documentation_scope do
explanation 'Lists information related to the progress towards the current Account List monthly goal'
do_request(filter: { account_list_id: account_list_id })
check_resource(['relationships'])
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
spec/support/auth_helper.rb
|
module AuthHelper
def auth_login(user)
allow_any_instance_of(Auth::UserAccountsController).to receive(:jwt_authorize!)
allow_any_instance_of(Auth::ApplicationController).to receive(:current_user).and_return(user)
allow_any_instance_of(Auth::UserAccountsController).to receive(:fetch_current_user).and_return(user)
end
def auth_logout
allow_any_instance_of(Auth::UserAccountsController).to receive(:jwt_authorize!).and_raise(Exceptions::AuthenticationError)
allow_any_instance_of(Auth::ApplicationController).to receive(:current_user).and_return(nil)
allow_any_instance_of(Auth::UserAccountsController).to receive(:fetch_current_user).and_return(nil)
end
end
|
chuckmersereau/api_practice
|
spec/models/audited/audit_search_spec.rb
|
require 'rails_helper'
RSpec.describe Audited::AuditSearch, type: :model do
let(:audited) { create(:person, first_name: 'Stephan') }
let(:user) { create(:user) }
let(:audit_attributes) do
{
action: 'update',
audited_changes: { first_name: %w(<NAME>) }.to_json,
user_id: user.id,
user_type: 'User',
auditable_id: audited.id,
auditable_type: audited.class.to_s
}
end
let(:audit) { Audited::AuditElastic.new(audit_attributes) }
let(:resp_body) do
{
"took": 1,
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": 'mpdx-uuid-test-2018.02.20',
"_type": 'audit_elastic',
"_id": '-Dals2EBy3eIl0ogkDQ5',
"_score": 1,
"_source": audit_attributes
}
]
}
}
end
before do
stub_request(:get, 'http://example.com:9200/mpdx-uuid-test-*/_search?scroll=5m&size=100&sort=_doc')
.with(body: '{"query":{"bool":{"must":[{"match":{"auditable_type":"Person"}}]}},"sort":["_doc"]}')
.to_return(status: 200, body: resp_body.to_json, headers: { 'content-type': 'application/json; charset=UTF-8' })
end
describe '#dump' do
it 'loads all of class' do
resp = described_class.dump('Person')
expect(resp.first.auditable_id).to eq audited.id
end
end
describe '#search_by' do
it 'loads by params' do
resp = described_class.search_by(bool: {
must: [
{ match: { auditable_type: 'Person' } }
]
})
expect(resp.first.auditable_id).to eq audited.id
end
it 'loads by simple params' do
resp = described_class.search_by(auditable_type: 'Person')
expect(resp.first.auditable_id).to eq audited.id
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/pledge_currency.rb
|
class Contact::Filter::PledgeCurrency < Contact::Filter::Base
def execute_query(contacts, filters)
pledge_currency_filters = parse_list(filters[:pledge_currency])
default_currencies = account_lists.collect(&:default_currency)
if (pledge_currency_filters & default_currencies).present?
contacts.where(pledge_currency: [pledge_currency_filters, '', nil].flatten)
else
contacts.where(pledge_currency: pledge_currency_filters)
end
end
def title
_('Commitment Currency')
end
def parent
_('Commitment Details')
end
def type
'multiselect'
end
def custom_options
account_lists.map(&:currencies).flatten.uniq.select(&:present?).map { |a| { name: a, id: a } }
end
end
|
chuckmersereau/api_practice
|
spec/models/notification_type/larger_gift_spec.rb
|
<filename>spec/models/notification_type/larger_gift_spec.rb<gh_stars>0
require 'rails_helper'
describe NotificationType::LargerGift do
let!(:larger_gift) { NotificationType::LargerGift.first_or_initialize }
let!(:da) { create(:designation_account) }
let!(:account_list) { create(:account_list) }
let!(:contact) { create(:contact, account_list: account_list, pledge_amount: 5, pledge_frequency: 6) }
let!(:donor_account) { create(:donor_account) }
let!(:donation) { create(:donation, donor_account: donor_account, designation_account: da) }
before do
account_list.account_list_entries.create!(designation_account: da)
contact.donor_accounts << donor_account
contact.update_donation_totals(donation)
end
context '#check' do
it 'adds a notification if a gift comes from a financial partner and is more than the pledge' do
expect(larger_gift.check(account_list).size).to eq(1)
end
it 'adds a notification if a gift came last month from a financial partner and is more than the pledge' do
donation.update(donation_date: Date.today << 1)
contact.update(last_donation_date: nil)
contact.update_donation_totals(donation)
expect(larger_gift.check(account_list).size).to eq(1)
end
it "doesn't add a notification if gift came before start of last month" do
donation.update(donation_date: Date.today << 3)
expect(larger_gift.check(account_list)).to be_empty
end
it 'adds a notification if two gifts which total to more than the pledge came in' do
donation.update(amount: 5, donation_date: Date.today.beginning_of_month)
expect(larger_gift.check(account_list)).to be_empty
donation2 = create(:donation, donor_account: donor_account,
designation_account: da, donation_date: Date.today.end_of_month)
expect(larger_gift.check(account_list).size).to eq(1)
expect(Notification.count).to eq(1)
expect(Notification.first.donation_id).to eq(donation2.id)
end
it 'does not add a notification for a regular gift after a larger gift in same month' do
donation.update(amount: 15, donation_date: Date.today.beginning_of_month)
contact.update_donation_totals(donation)
create(:donation, donor_account: donor_account, amount: 5,
designation_account: da, donation_date: Date.today.end_of_month)
expect(larger_gift.check(account_list).size).to eq(1)
expect(Notification.first.donation).to eq(donation)
end
it 'does not notify for a regular gift if an extra gift was given that month' do
donation.update(amount: 15, donation_date: Date.today.beginning_of_month)
expect(larger_gift.check(account_list).size).to eq(1)
expect(Notification.first.donation).to eq(donation)
create(:donation, donor_account: donor_account, amount: 5,
designation_account: da, donation_date: Date.today.end_of_month)
expect(larger_gift.check(account_list)).to be_empty
end
it "doesn't add a notification if gift is a long time frame gift that was given early" do
old_donation = create(:donation, donor_account: donor_account, designation_account: da, donation_date: Date.today << 5, amount: 5)
contact.update_donation_totals(old_donation)
donation.update(amount: 5.0)
contact.update_donation_totals(donation)
expect(larger_gift.check(account_list)).to be_empty
end
end
context '#caught_up_earlier_months?' do
it 'does not error if first_donation_date is nil' do
create(:donation, donor_account: donor_account,
designation_account: da, donation_date: Date.today << 1)
contact.update(first_donation_date: nil)
expect { larger_gift.caught_up_earlier_months?(contact) }.to_not raise_error
end
end
end
|
chuckmersereau/api_practice
|
app/policies/user/option_policy.rb
|
class User::OptionPolicy < ApplicationPolicy
private
def resource_owner?
resource.user_id == user.id
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.