repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
lib/sidekiq_audited_user.rb
|
class SidekiqAuditedUser
def call(_worker, job, _queue)
klass = job['class'].is_a?(String) ? job['class'].constantize : job['class']
::Audited.store[:audited_user] = klass.new
yield
end
end
|
chuckmersereau/api_practice
|
spec/preloaders/application_preloader/field_associations_fetcher_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe ApplicationPreloader::FieldAssociationsFetcher do
context '#fetch_field_associations' do
let(:field_params) { %w(first_name avatar) }
let(:field_association_mapping) { { avatar: :primary_picture, email: :primary_email_address } }
let(:serializer_class) { MockPersonSerializer }
subject { described_class.new(field_association_mapping, serializer_class) }
it 'returns all associations if no field_params is provided' do
expect(subject.fetch_field_associations(nil)).to match_array(
[:email_addresses, :primary_email_address, :primary_picture]
)
end
it 'returns required associations when field_params are provided' do
expect(subject.fetch_field_associations(field_params)).to eq(
[:primary_picture]
)
end
class MockPersonSerializer < ApplicationSerializer
belongs_to :email_addresses
end
end
end
|
chuckmersereau/api_practice
|
spec/exhibits/constant_list_exhibit_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
require Rails.root.join('app', 'seeders', 'notification_types_seeder.rb')
describe ConstantListExhibit do
subject { ConstantListExhibit.new(constant_list, context) }
let(:context) { double }
let(:constant_list) { ConstantList.new }
shared_examples 'expect method to translate values' do |options|
before { I18n.locale = :en }
after { I18n.locale = :en }
it do
expect { I18n.locale = :de }.to change { subject.send(options[:method]).first[:value] }
end
end
describe '.applicable_to?' do
it 'applies only to ConstantList and not other stuff' do
expect(ConstantListExhibit.applicable_to?(ConstantList.new)).to be true
expect(ConstantListExhibit.applicable_to?(Address.new)).to be false
end
end
describe '#bulk_update_options' do
let(:opts) { subject.bulk_update_options }
it { expect(opts['likely_to_give']).to eq subject.assignable_likely_to_give }
it { expect(opts['status']).to eq subject.assignable_statuses }
it { expect(opts['send_newsletter']).to eq subject.assignable_send_newsletter }
end
describe '#dates' do
it { expect(subject.dates).to be_a_hash_with_types String, String }
end
describe '#languages' do
it { expect(subject.languages).to be_a_hash_with_types String, String }
end
describe '#locales' do
it 'should have the correct data structure' do
subject.locales.each do |_code, locale|
expect(locale).to be_a_hash_with_types Symbol, String
end
expect(subject.locales).to be_a_hash_with_types Symbol, Hash
end
it 'should have a name with the locale code in parentheses' do
subject.locales.each do |_code, locale|
expect(locale[:english_name]).to match(/\A[^\(]+\(\w+(?:-\w+)?\)\z/)
end
end
it 'should have ISO 3166-1 alpha-2 codes' do
subject.locales.each do |code, _locale|
expect(code).to match(/\w\w/)
end
end
end
describe '#pledge_currencies' do
it { expect(subject.pledge_currencies).to be_a_hash_with_types String, Hash }
it { expect(subject.pledge_currencies['USD'][:code]).to eq('USD') }
it { expect(subject.pledge_currencies['USD'][:code_symbol_string]).to eq('USD ($)') }
it { expect(subject.pledge_currencies['USD'][:name]).to eq('US dollar') }
it { expect(subject.pledge_currencies['USD'][:symbol]).to eq('$') }
end
describe '#pledge_received' do
it { expect(subject.pledge_received).to eq %w(Yes No) }
end
describe '#activity_hashes' do
it 'should return array of hashes' do
subject.activity_hashes.each do |activity|
expect(activity).to be_a Hash
end
end
include_examples 'expect method to translate values', method: :activity_hashes
end
describe '#assignable_likely_to_give_hashes' do
it 'should return array of hashes' do
subject.assignable_likely_to_give_hashes.each do |likelihood|
expect(likelihood).to be_a Hash
end
end
include_examples 'expect method to translate values', method: :assignable_likely_to_give_hashes
end
describe '#assignable_location_hashes' do
it 'should return array of hashes' do
subject.assignable_location_hashes.each do |assignable_location|
expect(assignable_location).to be_a Hash
end
end
include_examples 'expect method to translate values', method: :assignable_location_hashes
end
describe '#assignable_send_newsletter_hashes' do
it 'should return array of hashes' do
subject.assignable_send_newsletter_hashes.each do |newsletter|
expect(newsletter).to be_a Hash
end
end
include_examples 'expect method to translate values', method: :assignable_send_newsletter_hashes
end
describe '#assignable_status_hashes' do
it 'should return array of hashes' do
subject.assignable_status_hashes.each do |status|
expect(status).to be_a Hash
end
end
include_examples 'expect method to translate values', method: :assignable_status_hashes
end
describe '#notification_hashes' do
before do
NotificationTypesSeeder.new(true).seed
end
it 'should return array of hashes' do
subject.notification_hashes.each do |notification|
expect(notification).to be_a Hash
end
end
it 'should translate' do
expect(FastGettext).to receive('cached_find').at_least(:once)
subject.notification_hashes
end
end
describe '#pledge_currency_hashes' do
let(:us_currency) { subject.pledge_currency_hashes.find { |currency| currency[:id] == 'USD' } }
it { expect(subject.pledge_currency_hashes).to be_a(Array) }
it { expect(us_currency.keys).to eq(%i(id key value)) }
it { expect(us_currency[:value]).to eq('USD ($)') }
it { expect(us_currency[:id]).to eq('USD') }
it { expect(us_currency[:key]).to eq('USD') }
end
describe '#pledge_frequency_hashes' do
it 'should return array of hashes' do
subject.pledge_frequency_hashes.each do |pledge_frequency|
expect(pledge_frequency).to be_a Hash
end
end
include_examples 'expect method to translate values', method: :pledge_frequency_hashes
end
describe '#pledge_received_hashes' do
it 'should return array of hashes' do
subject.pledge_received_hashes.each do |pledge_received|
expect(pledge_received).to be_a Hash
end
end
include_examples 'expect method to translate values', method: :pledge_received_hashes
end
describe '#send_appeals_hashes' do
it 'should return array of hashes' do
subject.send_appeals_hashes.each do |send_appeal|
expect(send_appeal).to be_a Hash
expect(send_appeal.keys).to eq([:id, :value])
end
end
include_examples 'expect method to translate values', method: :send_appeals_hashes
end
describe '#status_hashes' do
it 'should return array of hashes' do
subject.status_hashes.each do |status|
expect(status).to be_a Hash
end
end
include_examples 'expect method to translate values', method: :status_hashes
end
end
|
chuckmersereau/api_practice
|
engines/auth/auth.gemspec
|
<reponame>chuckmersereau/api_practice
$LOAD_PATH.push File.expand_path('../lib', __FILE__)
# Maintain your gem's version:
require 'auth/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = 'auth'
s.version = Auth::VERSION
s.authors = ['<NAME>']
s.email = ['<EMAIL>']
s.summary = 'Implements OmniAuth for MPDX API'
s.license = 'MIT'
s.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.rdoc']
s.test_files = Dir['spec/**/*']
s.add_dependency 'oauth2', '~> 1.2.0'
s.add_dependency 'omniauth', '~> 1.3.1'
s.add_dependency 'omniauth-donorhub', '~> 0.1.1'
s.add_dependency 'omniauth-google-oauth2', '~> 0.4.1'
s.add_dependency 'omniauth-mailchimp', '~> 1.2.0'
s.add_dependency 'omniauth-prayer-letters', '~> 0.0.3'
s.add_dependency 'rails', '~> 4.2'
s.add_dependency 'sass-rails', '~> 5.0.1'
s.add_dependency 'warden', '~> 1.2.3'
s.add_development_dependency 'capybara'
s.add_development_dependency 'dotenv-rails', '~> 2.1.1'
s.add_development_dependency 'factory_girl_rails'
s.add_development_dependency 'rspec-rails'
s.add_development_dependency 'rubocop', '~> 0.49.0'
end
|
chuckmersereau/api_practice
|
db/migrate/20120309211002_add_code_to_designation_profile.rb
|
<filename>db/migrate/20120309211002_add_code_to_designation_profile.rb
class AddCodeToDesignationProfile < ActiveRecord::Migration
def change
add_column :designation_profiles, :code, :string
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/tasks/analytics_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Tasks > Analytics' do
include_context :json_headers
documentation_scope = :tasks_api_analytics
# This is required!
# This is the resource's JSONAPI.org `type` attribute to be validated against.
let(:resource_type) { 'task_analytics' }
# Remove this and the authorized context below if not authorizing your requests.
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:alternate_account_list) do
create(:account_list).tap do |account_list|
user.account_lists << account_list
end
end
let!(:overdue_tasks) do
Task::TASK_ACTIVITIES.each do |activity_type|
trait_key = activity_type.parameterize.underscore.to_sym
create(:task, trait_key, :overdue, account_list: account_list)
end
end
let!(:last_physical_newsletter_logged_for_primary_account_list) do
create(:task,
:newsletter_physical,
:complete,
account_list: account_list,
completed_at: 1.day.ago)
end
let!(:last_electronic_newsletter_logged_for_primary_account_list) do
create(:task,
:newsletter_email,
:complete,
account_list: account_list,
completed_at: 1.day.ago)
end
let!(:last_electronic_newsletter_logged_for_alterate_account_list) do
create(:task,
:newsletter_email,
:complete,
account_list: alternate_account_list,
completed_at: 2.days.ago)
end
# List your expected resource keys vertically here (alphabetical please!)
let(:expected_attribute_keys) do
%w(
created_at
last_electronic_newsletter_completed_at
last_physical_newsletter_completed_at
tasks_overdue_or_due_today_counts
total_tasks_due_count
updated_at
updated_in_db_at
)
end
let(:returned_electronic_newsletter_completed_at) do
json_response['data']['attributes']['last_electronic_newsletter_completed_at']
end
let(:returned_physical_newsletter_completed_at) do
json_response['data']['attributes']['last_physical_newsletter_completed_at']
end
let(:returned_overdue_or_due_today_data) do
json_response['data']['attributes']['tasks_overdue_or_due_today_counts']
end
let(:returned_total_tasks_due_count) do
json_response['data']['attributes']['total_tasks_due_count']
end
context 'authorized user' do
before { api_login(user) }
context 'without specifying an `account_list_id`' do
# show
get '/api/v2/tasks/analytics' do
with_options scope: [:data, :attributes] do
response_field 'last_electronic_newsletter_completed_at', 'Last Electronic Newsletter Completed At', type: 'DateTime'
response_field 'last_physical_newsletter_completed_at', 'Last Physical Newsletter Completed At', type: 'DateTime'
response_field 'tasks_overdue_or_due_today_counts', 'Tasks Overdue or Due Today Counts', type: 'Array[Object]'
response_field 'total_tasks_due_count', 'Total Tasks Due Count', type: 'Number'
end
example 'Analytics [GET]', document: documentation_scope do
explanation "Viewing Analytical information for the User's Tasks for all Account Lists"
do_request
check_resource
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 200
expect(returned_electronic_newsletter_completed_at)
.to eq(
last_electronic_newsletter_logged_for_primary_account_list
.completed_at
.to_time
.utc
.iso8601
)
expect(returned_physical_newsletter_completed_at)
.to eq(
last_physical_newsletter_logged_for_primary_account_list
.completed_at
.to_time
.utc
.iso8601
)
expect(returned_overdue_or_due_today_data.count).to eq Task::TASK_ACTIVITIES.count + 1
expect(returned_total_tasks_due_count).to eq Task::TASK_ACTIVITIES.count
end
end
end
context 'when specifying an `account_list_id`' do
# show
get '/api/v2/tasks/analytics' do
with_options scope: [:data, :attributes] do
response_field 'last_electronic_newsletter_completed_at', 'Last Electronic Newsletter Completed At', type: 'DateTime'
response_field 'last_physical_newsletter_completed_at', 'Last Physical Newsletter Completed At', type: 'DateTime'
response_field 'tasks_overdue_or_due_today_counts', 'Tasks Overdue or Due Today Counts', type: 'Array[Object]'
response_field 'total_tasks_due_count', 'Total Tasks Due Count', type: 'Number'
end
example 'Analytics [GET]', document: documentation_scope do
explanation "Viewing Analytical information for a specific Account Lists' Tasks"
do_request filter: { account_list_id: alternate_account_list.id }
check_resource
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 200
expect(returned_electronic_newsletter_completed_at)
.to eq(
last_electronic_newsletter_logged_for_alterate_account_list
.completed_at
.to_time
.utc
.iso8601
)
expect(returned_physical_newsletter_completed_at).to be_nil
expect(returned_overdue_or_due_today_data.count).to eq Task::TASK_ACTIVITIES.count + 1
expect(returned_total_tasks_due_count).to eq 0
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/validators/file_size_validator_spec.rb
|
require 'rails_helper'
describe FileSizeValidator do
subject { FileSizeValidator.new(attributes: [:file], less_than: 1000).validate_each(record_double, :file, record_double.file) }
context 'file size is less than the max' do
let(:record_double) { double(errors: { file: [] }, file: double(size: 999)) }
it 'does not add any errors' do
subject
expect(record_double.errors[:file]).to eq []
expect(record_double.errors.keys).to eq [:file]
end
end
context 'file size is more than the max' do
let(:record_double) { double(errors: { file: [] }, file: double(size: 1001)) }
it 'adds an error message to errors' do
subject
expect(record_double.errors[:file]).to eq ['File size must be less than 1000 bytes']
expect(record_double.errors.keys).to eq [:file]
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20150528170855_move_active_to_designation_accounts.rb
|
<filename>db/migrate/20150528170855_move_active_to_designation_accounts.rb
class MoveActiveToDesignationAccounts < ActiveRecord::Migration
def change
add_column :designation_accounts, :active, :boolean, null: false, default: true
DesignationAccount.where(id: AccountListEntry.where(active: false).pluck(:designation_account_id)).update_all(active: false)
remove_column :account_list_entries, :active
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120529190915_contact_person_should_be_unique.rb
|
class ContactPersonShouldBeUnique < ActiveRecord::Migration
def up
remove_index :contact_people, :contact_id
add_index :contact_people, [:contact_id, :person_id], unique: true
end
def down
add_index :contact_people, :contact_id
remove_index :contact_people, [:contact_id, :person_id]
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/background_batches_controller.rb
|
<gh_stars>0
class Api::V2::BackgroundBatchesController < Api::V2Controller
def index
load_background_batches
render json: @background_batches.preload_valid_associations(include_associations),
meta: meta_hash(@background_batches),
include: include_params,
fields: field_params
end
def show
load_background_batch
authorize_background_batch
render_background_batch
end
def create
persist_background_batch
end
def destroy
load_background_batch
authorize_background_batch
destroy_background_batch
end
private
def destroy_background_batch
@background_batch.destroy
head :no_content
end
def load_background_batches
@background_batches = background_batch_scope.reorder(sorting_param)
.page(page_number_param)
.per(per_page_param)
end
def load_background_batch
@background_batch ||= BackgroundBatch.find(params[:id])
end
def render_background_batch
render json: @background_batch,
status: success_status,
include: include_params,
fields: field_params
end
def persist_background_batch
build_background_batch
authorize_background_batch
if save_background_batch
render_background_batch
else
render_with_resource_errors(@background_batch)
end
end
def build_background_batch
@background_batch ||= background_batch_scope.build
@background_batch.assign_attributes(background_batch_params)
end
def save_background_batch
@background_batch.save(context: persistence_context)
end
def background_batch_params
params
.require(:background_batch)
.permit(BackgroundBatch::PERMITTED_ATTRIBUTES)
end
def background_batch_scope
current_user.background_batches
end
def authorize_background_batch
authorize @background_batch
end
def pundit_user
PunditContext.new(current_user)
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/name_builder_spec.rb
|
<filename>spec/services/contact/name_builder_spec.rb
require 'rails_helper'
RSpec.describe Contact::NameBuilder, type: :model do
let(:params) { {} }
let(:builder) { Contact::NameBuilder.new(params) }
it 'initializes' do
expect(builder).to be_a(Contact::NameBuilder)
end
subject { builder.name }
context 'nil values' do
context 'hash param' do
let(:params) do
{
first_name: nil,
middle_name: nil,
last_name: nil,
spouse_first_name: nil,
spouse_middle_name: nil,
spouse_last_name: nil
}
end
it 'builds the name' do
expect(subject).to eq('')
end
end
context 'string param' do
let(:params) { nil }
it 'raises an error' do
expect { subject }.to raise_error(ArgumentError)
end
end
end
context 'all parts' do
context 'hash param' do
let(:params) do
{
first_name: 'First',
middle_name: 'Middle',
last_name: 'Last',
spouse_first_name: 'Spousefirst',
spouse_middle_name: 'Spousemiddle',
spouse_last_name: 'Spouselast'
}
end
it 'builds the name' do
expect(subject).to eq('Last and Spouselast, First Middle and Spousefirst Spousemiddle')
end
end
context 'string param' do
let(:params) { 'First Middle Last and Spousefirst Spousemiddle Spouselast' }
it 'builds the name' do
expect(subject).to eq('Last and Spouselast, First Middle and Spousefirst Spousemiddle')
end
end
end
context 'last name only' do
context 'hash param' do
let(:params) do
{
first_name: nil,
middle_name: nil,
last_name: 'Last',
spouse_first_name: nil,
spouse_middle_name: nil,
spouse_last_name: nil
}
end
it 'builds the name' do
expect(subject).to eq('Last')
end
end
context 'string param' do
let(:params) { 'Last' }
it 'builds the name' do
expect(subject).to eq('Last')
end
end
end
context 'first name only' do
context 'hash param' do
let(:params) do
{
first_name: 'First'
}
end
it 'builds the name' do
expect(subject).to eq('First')
end
end
end
context 'spouse first name only' do
context 'hash param' do
let(:params) do
{
spouse_first_name: 'Spousefirst'
}
end
it 'builds the name' do
expect(subject).to eq('Spousefirst')
end
end
end
context 'spouse last name only' do
context 'hash param' do
let(:params) do
{
spouse_last_name: 'Spouselast'
}
end
it 'builds the name' do
expect(subject).to eq('Spouselast')
end
end
end
context 'no spouse names' do
context 'hash param' do
let(:params) do
{
first_name: 'First',
last_name: 'Last'
}
end
it 'builds the name' do
expect(subject).to eq('Last, First')
end
end
context 'string param' do
let(:params) { 'First Last' }
it 'builds the name' do
expect(subject).to eq('Last, First')
end
end
end
context 'no primary names' do
context 'hash param' do
let(:params) do
{
spouse_first_name: 'Spousefirst',
spouse_last_name: 'Spouselast'
}
end
it 'builds the name' do
expect(subject).to eq('Spouselast, Spousefirst')
end
end
end
context 'name is nonhuman' do
context 'string param' do
let(:params) { ["Bob's Church", "Joe's Coffee LTD", "Joe's Coffee Ltd.", 'community school'] }
it 'returns the input' do
params.each do |param|
expect(Contact::NameBuilder.new(param).name).to eq(param.titleize)
end
end
it 'only looks at whole words when looking for a nonhuman name' do
expect(Contact::NameBuilder.new('<NAME>').name).to eq('Schurch, John')
expect(Contact::NameBuilder.new('<NAME>').name).to eq('<NAME>')
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130119193907_add_description_for_email_to_notification_type.rb
|
class AddDescriptionForEmailToNotificationType < ActiveRecord::Migration
def change
add_column :notification_types, :description_for_email, :text
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_type_spec.rb
|
require 'rails_helper'
RSpec.describe Task::Filter::ContactType 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!(:task_one) { create(:task, account_list: account_list, contacts: [contact_one]) }
let!(:task_two) { create(:task, account_list: account_list, contacts: [contact_two]) }
let!(:person_one) { create(:person) }
let!(:donor_account) { create(:donor_account, master_company: create(:master_company)) }
before do
contact_one.people << person_one
contact_two.donor_accounts << donor_account
end
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, { contact_type: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_type: [] }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_type: '' }, account_list)).to eq(nil)
end
end
context 'filter tasks by contact type person' do
it 'returns tasks with contacts that are the correct type' do
expect(described_class.query(tasks, { contact_type: 'person' }, account_list).to_a).to eq [task_one]
end
end
context 'filter tasks by contact type company' do
it 'returns tasks with contacts that are the correct type' do
expect(described_class.query(tasks, { contact_type: 'company' }, account_list).to_a).to eq [task_two]
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20161216004043_add_uuid_to_account_list_entries.rb
|
<reponame>chuckmersereau/api_practice<filename>db/migrate/20161216004043_add_uuid_to_account_list_entries.rb
class AddUuidToAccountListEntries < ActiveRecord::Migration
def change
add_column :account_list_entries, :uuid, :uuid, null: false, default: 'uuid_generate_v4()'
add_index :account_list_entries, :uuid, unique: true
end
end
|
chuckmersereau/api_practice
|
app/models/concerns/year_completable.rb
|
<reponame>chuckmersereau/api_practice
module YearCompletable
private
def get_four_digit_year_from_value(year_value)
return unless year_value
return year_value if year_value.to_s.length > 2
"#{first_two_digits_of_year(year_value)}#{last_two_digits_of_year(year_value)}".to_i
end
def last_two_digits_of_year(year_value)
return "0#{year_value}" if year_value.to_s.length == 1
year_value
end
def first_two_digits_of_year(last_two_digits_of_year)
if last_two_digits_of_current_year > last_two_digits_of_year.to_i
first_two_digits_of_current_year
else
first_two_digits_of_current_year - 1
end
end
def last_two_digits_of_current_year
@last_two_digits_of_current_year ||= Date.today.year.to_s.last(2).to_i
end
def first_two_digits_of_current_year
@first_two_digits_of_current_year ||= Date.today.year.to_s.first(2).to_i
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/reports/expected_monthly_totals_controller.rb
|
<gh_stars>0
class Api::V2::Reports::ExpectedMonthlyTotalsController < Api::V2Controller
def show
load_report
authorize_report
render_report
end
private
def load_report
@report ||= ::Reports::ExpectedMonthlyTotals.new(report_params)
end
def report_params
report_params = { filter_params: filter_params.except(:account_list_id) }
report_params[:account_list] = load_account_list if load_account_list
report_params
end
def load_account_list
@account_list ||= account_lists.order(:created_at).first
end
def render_report
render json: @report, fields: field_params, include: include_params
end
def permitted_filters
[:account_list_id, :designation_account_id, :donor_account_id]
end
def authorize_report
authorize(load_account_list, :show?)
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/pledges_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Pledges' do
include_context :json_headers
# This is required!
# This is the resource's JSONAPI.org `type` attribute to be validated against.
let(:resource_type) { 'pledges' }
# Remove this and the authorized context below if not authorizing your requests.
let(:user) { create(:user_with_account) }
let(:attributes) { attributes_for(:pledge).except(:account_list_id, :contact_id, :donation_id) }
let(:account_list) { create(:account_list, users: [user]) }
let(:contact) { create(:contact, account_list: account_list) }
let!(:pledge) { create(:pledge, account_list: account_list, contact: contact) }
let(:id) { pledge.id }
let(:account_list_id) { account_list.id }
# This is the reference data used to create/update a resource.
# specify the `attributes` specifically in your request actions below.
let(:form_data) do
build_data(attributes).merge(
relationships: {
contact: {
data: {
id: contact.id,
type: 'contacts'
}
}
}
)
end
# List your expected resource keys vertically here (alphabetical please!)
let(:expected_attribute_keys) do
%w(
amount
created_at
expected_date
status
updated_at
updated_in_db_at
)
end
let(:expected_relationships) do
%w(
account_list
contact
donation
)
end
# List out any additional attribute keys that will be alongside
# the attributes of the resources.
#
# Remove if not needed.
let(:additional_attribute_keys) do
%w(
relationships
)
end
# DOCUMENTATION SCOPE
#
# This is the scope in how these endpoints will be organized in the
# generated documentation.
#
# :entities should be used for "top level" route resources, like AccountList, Contacts, Tasks, etc
# For nested resources, a symbolized version of a "top level" resource should be used.
#
# Ex: Api > v2 > Contacts - :entities would be the scope
# Ex: Api > v2 > Contacts > Email Addresses - :contacts would be the scope
# Ex: Api > v2 > Contacts > People > Phones - :contacts would be the scope
#
# As such, replace FIXME below for the desired scope for the endpoints below,
# and feel free to remove this sentence.
documentation_scope = :pledges
context 'authorized user' do
before { api_login(user) }
# index
get '/api/v2/account_lists/:account_list_id/pledges' do
parameter 'account_list_id', 'Account List ID', required: true
with_options scope: :filter do
parameter 'contact_id', 'Filter by Contact Id', type: 'String'
end
with_options scope: :sort do
parameter 'amount', 'Sort by Amount', type: 'Number'
parameter 'expected_date', 'Sort by Expected Date', type: 'String'
parameter 'status', 'Sort by the status of the appeal (not_received, received_not_processed, or processed)', type: 'String'
parameter 'contact.name', 'Sort by Contact Name', type: 'String'
end
example 'Pledge [LIST]', document: documentation_scope do
explanation 'List of Pledges'
do_request
check_collection_resource(1, additional_attribute_keys)
expect(response_status).to eq 200
end
end
# show
get '/api/v2/account_lists/:account_list_id/pledges/:id' do
parameter 'account_list_id', 'Account List ID', required: true
parameter 'id', 'Pledge ID', required: true
with_options scope: :data do
with_options scope: :attributes do
# list out the attributes here
response_field 'amount', 'Amount of Pledge', type: 'Number'
response_field 'expected_date', 'Expected Date of Donation', type: 'String'
response_field 'status', 'State of the processing of the donations on the pledge', type: 'String'
end
with_options scope: :relationships do
response_field 'donation', 'Donation associated to Pledge', type: 'Object'
response_field 'contact', 'Contact associated to Pledge', type: 'Object'
end
end
example 'Pledge [GET]', document: documentation_scope do
explanation 'The Pledge for the given ID'
do_request
check_resource(additional_attribute_keys)
expect(response_status).to eq 200
end
end
# create
post '/api/v2/account_lists/:account_list_id/pledges' do
parameter 'account_list_id', 'Account List ID', required: true
with_options scope: :data do
with_options scope: :attributes do
# list out the POST params here
parameter 'amount', 'Amount of expected donation', type: 'Number'
parameter 'expected_date', 'Expected Date of Donation', type: 'String'
end
with_options scope: :relationships do
parameter 'donation', 'Donation associated to Pledge', type: 'Object'
parameter 'contact', 'Contact associated to Pledge', type: 'Object'
end
end
example 'Pledge [CREATE]', document: documentation_scope do
explanation 'Create Pledge'
Pledge.destroy_all
do_request data: form_data
check_resource(additional_attribute_keys)
expect(response_status).to eq 201
end
end
# update
put '/api/v2/account_lists/:account_list_id/pledges/:id' do
parameter 'account_list_id', 'Account List ID', required: true
parameter 'id', 'Pledge ID', required: true
with_options scope: [:data, :attributes] do
# list out the PUT params here
parameter 'amount', 'Amount of expected donation', type: 'Number'
parameter 'expected_date', 'Expected Date of Donation', type: 'String'
end
example 'Pledge [UPDATE]', document: documentation_scope do
explanation 'Update Pledge'
# Merge with the updated_in_db_at value provided by the server.
# Ex: updated_in_db_at: email_address.updated_at
do_request data: form_data.merge!(attributes: { updated_in_db_at: pledge.updated_at })
check_resource(additional_attribute_keys)
expect(response_status).to eq 200
end
end
# destroy
delete '/api/v2/account_lists/:account_list_id/pledges/:id' do
parameter 'account_list_id', 'Account List ID', required: true
parameter 'id', 'Pledge ID', required: true
example 'Pledge [DELETE]', document: documentation_scope do
explanation 'Delete Pledge'
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/pledge_currency_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::PledgeCurrency 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, pledge_currency: 'CAD') }
let!(:contact_two) { create(:contact, account_list_id: account_list.id, pledge_currency: 'GBP') }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, pledge_currency: 'USD') }
let!(:contact_four) { create(:contact, account_list_id: account_list.id, pledge_currency: 'USD') }
describe '#config' do
it 'returns expected config' do
options = [{ name: '-- Any --', id: '', placeholder: 'None' },
{ name: 'CAD', id: 'CAD' },
{ name: 'GBP', id: 'GBP' },
{ name: 'USD', id: 'USD' }]
expect(described_class.config([account_list])).to include(name: :pledge_currency,
options: options,
parent: 'Commitment Details',
title: 'Commitment Currency',
type: 'multiselect')
end
end
describe '#query' do
let(:contacts) { Contact.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(contacts, {}, nil)).to eq(nil)
expect(described_class.query(contacts, { locale: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { locale: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { locale: '' }, nil)).to eq(nil)
end
end
context 'filter by address historic' do
it 'returns only contacts that have the locale' do
results = described_class.query(contacts, { pledge_currency: 'USD' }, [account_list]).to_a
expect(results).to match_array [contact_three, contact_four]
results = described_class.query(contacts, { pledge_currency: 'CAD' }, [account_list]).to_a
expect(results).to eq [contact_one]
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180201214927_add_type_to_organizations.rb
|
class AddTypeToOrganizations < ActiveRecord::Migration
def change
add_column :organizations, :organization_type, :string, default: 'Non-Cru'
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/filtering.rb
|
module Filtering
BASE_DATE_REGEX = /\d{4}\-\d{2}\-\d{2}/
DATE_REGEX = /(#{BASE_DATE_REGEX})/
DATE_TIME_REGEX = /(#{BASE_DATE_REGEX}T\d{2}\:\d{2}\:\d{2}(?:Z|\+\d{2}:\d{2}))/
DATE_RANGE_REGEX = /(#{BASE_DATE_REGEX})(\.\.\.?)(#{BASE_DATE_REGEX})/
DATE_TIME_RANGE_REGEX = /#{DATE_TIME_REGEX}(\.\.\.?)#{DATE_TIME_REGEX}/
DEFAULT_PERMITTED_FILTERS = %i(updated_at).freeze
UNCASTED_FILTERS = %i(wildcard_seach tags).freeze
def filter_params(filter_params = params[:filter])
return {} unless filter_params
filter_params
.to_hash
.transform_keys { |key| key.to_s.underscore.to_sym }
.keep_if { |key, _| permitted_filters_with_defaults.include?(key) }
.map { |key, value| cast_hash_entry(key, value) }
.reduce({}, :merge)
.each { |key, value| validate_casted_filter_value!(key, value) }
end
private
def cast_hash_entry(key, value)
casted = value
casted = cast_filter_value(value) unless UNCASTED_FILTERS.include?(key)
{ key => casted }
end
def cast_filter_value(value)
case value
when DATE_RANGE_REGEX, DATE_TIME_RANGE_REGEX
cast_to_datetime_range($LAST_MATCH_INFO)
when DATE_REGEX
cast_date_to_datetime_range($LAST_MATCH_INFO)
when DATE_TIME_REGEX
cast_to_datetime($LAST_MATCH_INFO)
else
value
end
end
def cast_to_datetime_range(match_data)
start_datetime = DateTime.parse(match_data[1])
end_datetime = DateTime.parse(match_data[3])
exclusive = match_data[2].length == 3
Range.new(start_datetime, end_datetime, exclusive)
rescue ArgumentError
match_data[0] # return the original string
end
def cast_date_to_datetime_range(match_data)
datetime = DateTime.parse(match_data[1])
start_datetime = datetime.beginning_of_day
end_datetime = datetime.end_of_day
Range.new(start_datetime, end_datetime)
rescue ArgumentError
match_data[0] # return the original string
end
def cast_to_datetime(match_data)
DateTime.parse(match_data[1])
rescue ArgumentError
match_data[0] # return the original string
end
def invalid_date_range_format_message(key)
"Wrong format of date range for filter '#{key}', should follow 'YYYY-MM-DD...YYYY-MM-DD' for "\
"dates and 'YYYY-MM-DDThh:mm:ssZ...YYYY-MM-DDThh:mm:ssZ' for datetimes"
end
def permitted_filters
[]
end
def permitted_filters_with_defaults
permitted_filters + DEFAULT_PERMITTED_FILTERS
end
def raise_invalid_date_range_message(key)
raise Exceptions::BadRequestError, invalid_date_range_format_message(key)
end
def excluded_filter_keys_from_casting_validation
[]
end
def validate_casted_filter_value!(key, value)
return if key.in? excluded_filter_keys_from_casting_validation
CastedValueValidator.validate!(attribute: key, value: value)
rescue CastedValueValidator::DateTimeCastingError
raise_invalid_date_range_message(key)
end
end
|
chuckmersereau/api_practice
|
spec/factories/person_twitter_accounts.rb
|
<filename>spec/factories/person_twitter_accounts.rb
FactoryBot.define do
factory :twitter_account, class: 'Person::TwitterAccount' do
screen_name { Faker::Internet.user_name }
association :person
sequence(:remote_id, 1)
token '<PASSWORD>'
secret 'MyString'
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/people_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::Contacts::PeopleController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:resource_type) { :person }
let(:contact) { create(:contact, account_list: account_list) }
let!(:resource) { create(:person).tap { |person| create(:contact_person, contact: contact, person: person) } }
let!(:second_resource) { create(:person).tap { |person| create(:contact_person, contact: contact, person: person) } }
let(:id) { resource.id }
let(:parent_param) { { contact_id: contact.id } }
let(:correct_attributes) do
{ first_name: 'Billy', email_address: { email: '<EMAIL>' }, updated_at: 1.day.from_now }
end
let(:incorrect_attributes) { nil }
let(:factory_type) { :person }
let(:resource_scope) { contact.people }
before do
create(:email_address, person: resource) # Test inclusion of related resources.
end
include_examples 'show_examples'
include_examples 'update_examples'
include_examples 'create_examples'
include_examples 'destroy_examples'
include_examples 'index_examples'
context 'all contacts' do
let(:parent_param) { {} }
include_examples 'index_examples'
include_examples 'update_examples'
include_examples 'show_examples'
include_examples 'destroy_examples'
end
context 'a specific contact' do
let(:parent_param) { { contact_id: contact.id } }
include_examples 'index_examples'
end
context 'filter by phone_number_valid' do
let(:filter_params) { { phone_number_valid: 'false' } }
before { Contact.first.people.first.delete }
include_examples 'filtering examples', action: :index
end
context 'account_list_id filter' do
let!(:account_list_two) { create(:account_list, users: [user]) }
let!(:person_two) { create(:contact_with_person, account_list: account_list_two).primary_person }
it 'filters results' do
api_login(user)
get :index, filter: { account_list_id: account_list_two.id }
expect(response.status).to eq(200), invalid_status_detail
expect(JSON.parse(response.body)['data'].length).to eq(1)
end
end
describe 'Nested Examples' do
describe 'Creating / Updating a Facebook Account nested under Person' do
let(:generated_id) { SecureRandom.uuid }
let(:params) do
{
id: resource.id,
contact_id: contact.id,
data: {
type: 'people',
id: resource.id,
attributes: {
updated_in_db_at: resource.updated_at
},
relationships: {
facebook_accounts: {
data: [
{
type: 'facebook_accounts',
id: generated_id
}
]
}
}
},
included: [
{
type: 'facebook_accounts',
id: generated_id,
attributes: {
username: 'captain.america'
}
}
]
}
end
it 'Correctly creates the Facebook Account' do
expect(resource.facebook_accounts.count).to eq(0)
api_login(user)
put :update, params
expect(response.status).to eq(200), invalid_status_detail
expect(resource.reload.facebook_accounts.count).to eq(1)
expect(resource.facebook_accounts.first.id).to eq generated_id
expect(resource.facebook_accounts.first.username).to eq 'captain.america'
end
end
describe 'Creating / Updating a Linkedin Account nested under Person' do
let(:linkedin_account) do
create(:linkedin_account, public_url: 'https://linkedin.com/old-url',
person: resource)
end
let(:params) do
{
id: resource.id,
contact_id: contact.id,
data: {
type: 'people',
id: resource.id,
attributes: {
updated_in_db_at: resource.updated_at
},
relationships: {
linkedin_accounts: {
data: [
{
type: 'linkedin_accounts',
id: linkedin_account.id
}
]
}
}
},
included: [
{
type: 'linkedin_accounts',
id: linkedin_account.id,
attributes: {
public_url: 'https://linkedin.com/new-url'
}
}
]
}
end
it 'Correctly creates the Linkedin Account' do
expect(linkedin_account.public_url).to eq 'https://linkedin.com/old-url'
api_login(user)
put :update, params
expect(response.status).to eq(200), invalid_status_detail
expect(linkedin_account.reload.public_url).to eq 'https://linkedin.com/new-url'
end
end
describe 'Creating / Updating a Phone Number nested under Person' do
let(:generated_id) { SecureRandom.uuid }
let(:params) do
{
id: resource.id,
contact_id: contact.id,
data: {
type: 'people',
id: resource.id,
attributes: {
updated_in_db_at: resource.updated_at
},
relationships: {
phone_numbers: {
data: [
{
type: 'phone_numbers',
id: generated_id
}
]
}
}
},
included: [
{
type: 'phone_numbers',
id: generated_id,
attributes: {
number: '5011231234'
}
}
]
}
end
it 'Correctly creates the Phone Number' do
expect(resource.facebook_accounts.count).to eq(0)
api_login(user)
put :update, params
expect(response.status).to eq(200), invalid_status_detail
expect(resource.reload.phone_numbers.count).to eq(1)
expect(resource.phone_numbers.first.id).to eq generated_id
expect(resource.phone_numbers.first.number).to eq '+5011231234'
end
end
describe 'Creating / Updating an Email Address under Person' do
let(:generated_id) { SecureRandom.uuid }
let(:params) do
{
id: resource.id,
contact_id: contact.id,
data: {
type: 'people',
id: resource.id,
attributes: {
updated_in_db_at: resource.updated_at
},
relationships: {
email_addresses: {
data: [
{
type: 'email_addresses',
id: generated_id
}
]
}
}
},
included: [
{
type: 'email_addresses',
id: generated_id,
attributes: {
email: '<EMAIL>'
}
}
]
}
end
it 'Correctly creates the Email Address' do
expect(resource.email_addresses.count).to eq(1)
api_login(user)
put :update, params
expect(response.status).to eq(200), invalid_status_detail
expect(resource.reload.email_addresses.count).to eq(2)
expect(resource.email_addresses.last.id).to eq generated_id
expect(resource.email_addresses.last.email).to eq '<EMAIL>'
end
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/donations_controller.rb
|
<gh_stars>0
class Api::V2::AccountLists::DonationsController < Api::V2Controller
include Concerns::Reports::DonationSumHelper
def index
authorize load_account_list, :show?
load_donations
render json: @donations.preload(include_associations.except(:contact)),
scope: { account_list: load_account_list, locale: locale },
meta: meta_hash_with_totals,
include: include_params,
fields: field_params
end
def show
load_donation
authorize_donation
render_donation
end
def create
persist_donation
end
def update
load_donation
authorize_donation
persist_donation
end
def destroy
load_donation
authorize_donation
destroy_donation
end
private
def destroy_donation
@donation.destroy
head :no_content
end
def load_donations
@donations = donation_scope.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def load_donation
@donation ||= Donation.find(params[:id])
end
def render_donation
render json: @donation,
scope: { account_list: load_account_list, locale: locale },
status: success_status,
include: include_params,
fields: field_params
end
def persist_donation
build_donation
authorize_donation
if save_donation
render_donation
else
render_with_resource_errors(@donation)
end
end
def build_donation
@donation ||= donation_scope.build
@donation.assign_attributes(donation_params)
end
def authorize_donation
authorize @donation
end
def save_donation
@donation.save(context: persistence_context)
end
def donation_params
params
.require(:donation)
.permit(Donation::PERMITTED_ATTRIBUTES)
end
def donation_scope
load_account_list.donations
end
def load_account_list
@account_list ||= AccountList.find(params[:account_list_id])
end
def permitted_filters
[:donor_account_id, :donation_date, :designation_account_id]
end
def permitted_sorting_params
%w(donation_date)
end
def default_sort_param
Donation.arel_table[:created_at].asc
end
def pundit_user
PunditContext.new(current_user, account_list: load_account_list)
end
def meta_hash_with_totals
hash = meta_hash(@donations)
hash.merge(totals: donoations_with_currency(@donations))
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/user/options_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'User > Options' do
include_context :json_headers
documentation_scope = :user_api_options
let(:resource_type) { 'user_options' }
let(:user) { create(:user_with_account) }
let(:form_data) { build_data(attributes).merge }
let!(:option) { create(:user_option, user: user) }
let(:key) { option.key }
let(:new_user_option_params) do
attributes_for(:user_option)
.merge(updated_in_db_at: option.updated_at)
.select { |k, _v| expected_attribute_keys.include?(k.to_s) }
end
let(:form_data) { build_data(new_user_option_params) }
let(:expected_attribute_keys) do
%w(
created_at
key
updated_at
updated_in_db_at
value
)
end
let(:additional_attribute_keys) { [] }
context 'authorized user' do
before { api_login(user) }
get '/api/v2/user/options' do
example 'Option [LIST]', document: documentation_scope do
explanation 'List of Options'
do_request
check_collection_resource(1, additional_attribute_keys)
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 200
end
end
# show
get '/api/v2/user/options/:key' do
with_options scope: [:data, :attributes] do
response_field 'key', 'Key to reference option (only contain alphanumeric and underscore chars)', type: 'String'
response_field 'value', 'Value of option', type: 'String'
end
example 'Option [GET]', document: documentation_scope do
explanation 'The Option for the given key'
do_request
check_resource(additional_attribute_keys)
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 200
end
end
# create
post '/api/v2/user/options' do
with_options scope: [:data, :attributes] do
parameter 'key', 'Key to reference option (only contain alphanumeric and underscore chars)'
parameter 'value', 'Value of option'
end
example 'Option [CREATE]', document: documentation_scope do
explanation 'Create Option'
do_request data: form_data
check_resource(additional_attribute_keys)
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 201
end
end
# update
put '/api/v2/user/options/:key' do
with_options scope: [:data, :attributes] do
parameter 'value', 'Value of option'
end
example 'Option [UPDATE]', document: documentation_scope do
explanation 'Update Option'
do_request data: form_data
check_resource(additional_attribute_keys)
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 200
end
end
# destroy
delete '/api/v2/user/options/:key' do
example 'Option [DELETE]', document: documentation_scope do
explanation 'Delete Option'
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/donation.rb
|
class Donation < ApplicationRecord
include Deletable
audited on: [:destroy]
belongs_to :donor_account
belongs_to :designation_account
belongs_to :appeal
has_many :contacts, through: :donor_account
has_many :pledge_donations, dependent: :destroy
has_many :pledges, through: :pledge_donations
# Our current business rules state that donations should only be attached to one pledge.
# We would like to do away with the many-to-many PledgeDonation relationship, but in the meantime
# these will return the first row.
has_one :pledge_donation
has_one :pledge, through: :pledge_donation
validates :amount, :donation_date, presence: { message: _('can not be blank') }
scope :for, -> (designation_account) { where(designation_account_id: designation_account.id) }
scope :for_accounts, -> (designation_accounts) { where(designation_account: designation_accounts) }
scope :since, -> (date) { where('donation_date > ?', date) }
scope :between, -> (from, to) { where(donation_date: from.to_date..to.to_date) }
scope :currencies, -> { reorder(nil).pluck('DISTINCT currency') }
scope :without_gift_aid, -> { where.not(payment_method: GIFT_AID) }
GIFT_AID = 'Gift Aid'.freeze
PERMITTED_ATTRIBUTES = [:amount,
:appeal_amount,
:appeal_id,
:channel,
:created_at,
:currency,
:designation_account_id,
:donation_date,
:donor_account_id,
:memo,
:motivation,
:overwrite,
:payment_method,
:payment_type,
:remote_id,
:tendered_amount,
:tendered_currency,
:updated_at,
:updated_in_db_at,
:id].freeze
# Used by Contact::DonationsEagerLoader
attr_accessor :loaded_contact
default_scope { order('donation_date desc, created_at') }
scope :currencies, -> { reorder(nil).pluck('DISTINCT currency') }
after_create :update_totals
after_save :update_contacts, if: :donor_account_id_changed?, on: :update
after_save :update_appeal_relations
after_destroy :reset_totals
before_validation :set_amount_from_tendered_amount
def deleted_from
designation_account
end
def localized_amount
amount.to_f.localize.to_currency.to_s(currency: currency)
end
def localized_date
I18n.l donation_date, format: :long
end
def self.all_from_offline_orgs?(donations)
org_api_classes(donations).all? { |api_class| api_class == 'OfflineOrg' }
end
def self.org_api_classes(donations)
donations.reorder('').joins(:donor_account)
.joins(donor_account: :organization).pluck('DISTINCT api_class')
end
def converted_amount
CurrencyRate.convert_on_date(amount: amount,
from: currency,
to: converted_currency,
date: donation_date)
end
def converted_appeal_amount
CurrencyRate.convert_on_date(amount: pledge_amount,
from: currency,
to: converted_currency,
date: donation_date)
end
def converted_currency
designation_account.currency
end
def pledge_amount
appeal_amount&.positive? ? appeal_amount : amount
end
private
def update_contacts
DonorAccount.find(donor_account_id_was)&.contacts&.each(&:save) if donor_account_id_was
contacts.each(&:save)
end
def update_appeal_relations
add_appeal_contacts
# creating a pledge requires the AppealContact to be setup already
update_related_pledge
end
def update_related_pledge
return pledge_donations.each(&:destroy) if appeal.blank?
pledge_match = AccountList::PledgeMatcher.new(self)
pledge_match.pledge.donations << self if pledge_match.needs_pledge?
end
def update_totals(reset: false)
donor_account&.update_donation_totals(self, reset: reset)
designation_account&.update_donation_totals(self, reset: reset)
end
def reset_totals
update_totals(reset: true)
end
def set_amount_from_tendered_amount
if tendered_amount.present?
self.tendered_amount = tendered_amount_before_type_cast.to_s.gsub(/[^\d\.\-]+/, '').to_f
self.amount ||= tendered_amount_before_type_cast
end
end
def add_appeal_contacts
return unless appeal&.account_list
contacts = appeal.account_list
.contacts
.joins(:contact_donor_accounts)
.where(contact_donor_accounts: { donor_account_id: donor_account.id })
appeal.bulk_add_contacts(contacts: contacts)
end
end
|
chuckmersereau/api_practice
|
app/validators/upload_extension_validator.rb
|
<gh_stars>0
class UploadExtensionValidator < ActiveModel::EachValidator
def initialize(options)
options[:message] ||= 'You must specify a file with extension .#{options[:extension]}'
super
end
def validate_each(record, attribute, value)
file_extension = File.extname(value&.path || '').delete('.').to_s.downcase
extensions = Array.wrap(options[:extension])
return if value.present? && extensions.include?(file_extension)
record.errors[attribute] << _(options[:message])
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/constants_controller_spec.rb
|
<filename>spec/controllers/api/v2/constants_controller_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe Api::V2::ConstantsController, type: :controller do
include_examples 'common_variables'
let(:user) { create(:user_with_account) }
describe '#index' do
it 'shows resources to users that are signed in' do
api_login(user)
get :index
expect(response.status).to eq(200)
end
it 'does not shows resources to users that are not signed in' do
get :index
expect(response.status).to eq(401)
end
end
describe '#index fields' do
let(:resource_type) { 'constant_list' }
let(:parent_param_if_needed) { {} }
let(:serializer) { ConstantListSerializer.new(ConstantList.new) }
include_examples 'sparse fieldsets examples',
action: :index,
expected_response_code: 200
end
end
|
chuckmersereau/api_practice
|
app/models/person/key_account.rb
|
<reponame>chuckmersereau/api_practice
class Person::KeyAccount < ApplicationRecord
include Person::Account
validates :remote_id, :email, :person_id, presence: true
validates :remote_id, uniqueness: true
PERMITTED_ATTRIBUTES = [:created_at,
:email,
:first_name,
:last_name,
:overwrite,
:person_id,
:remote_id,
:updated_at,
:updated_in_db_at,
:id].freeze
def self.find_or_create_from_auth(auth_hash, person)
relation_scope = person.key_accounts
extra_attributes = auth_hash.extra.attributes.first
remote_id = extra_attributes.ssoGuid.upcase
attributes = {
remote_id: remote_id,
relay_remote_id: extra_attributes.relayGuid.upcase,
first_name: extra_attributes.firstName,
last_name: extra_attributes.lastName,
username: extra_attributes.email,
email: extra_attributes.email,
designation: extra_attributes.try(:designation),
employee_id: extra_attributes.try(:emplid)
}
account = find_or_create_person_account(
person: person,
attributes: attributes,
relation_scope: relation_scope
)
account.find_or_create_org_account if person.organization_accounts.where(organization_id: Organization.cru_usa.id).empty?
account
end
def self.find_related_account(rel, attributes)
account = rel.authenticated.find_by('upper(remote_id) = ?', attributes[:remote_id])
account
end
def self.create_user_from_auth(auth_hash)
attributes = {
first_name: auth_hash.extra.attributes.first.firstName || 'Unknown',
last_name: auth_hash.extra.attributes.first.lastName
}
super(attributes)
end
def self.find_authenticated_user(auth_hash)
extra_attributes = auth_hash.extra.attributes.first
remote_id = extra_attributes.ssoGuid.upcase
user_id = authenticated.where('upper(remote_id) = ?', remote_id).pluck(:person_id).first
User.find_by(id: user_id)
end
def to_s
username
end
def find_or_create_org_account
return if Rails.env.development? && ENV['DEV_SIEBEL_ORG_ACCOUNT'].blank?
begin
return unless SiebelDonations::Profile.find(ssoGuid: remote_id).present?
rescue StandardError => ex
Rollbar.raise_or_notify(ex)
return
end
org = Organization.cru_usa
# we need to create an organization account if we don't already have one
account = person.organization_accounts.where(organization_id: org.id).first_or_initialize
account.assign_attributes(remote_id: remote_id,
authenticated: true,
valid_credentials: true)
account.save(validate: false)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20171006035430_drop_unnecessary_fields_from_recommendations.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class DropUnnecessaryFieldsFromRecommendations < ActiveRecord::Migration
def change
remove_column :donation_amount_recommendations, :organization_id, :integer
remove_column :donation_amount_recommendations, :previous_amount, :decimal
remove_column :donation_amount_recommendations, :amount, :decimal
remove_column :donation_amount_recommendations, :gift_min, :decimal
remove_column :donation_amount_recommendations, :gift_max, :decimal
remove_column :donation_amount_recommendations, :income_min, :decimal
remove_column :donation_amount_recommendations, :income_max, :decimal
remove_column :donation_amount_recommendations, :zip_code, :string
remove_column :donation_amount_recommendations, :donor_number, :string
remove_column :donation_amount_recommendations, :designation_number, :string
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120323163229_add_payment_type_and_channel_to_donations.rb
|
class AddPaymentTypeAndChannelToDonations < ActiveRecord::Migration
def change
add_column :donations, :payment_type, :string
add_column :donations, :channel, :string
end
end
|
chuckmersereau/api_practice
|
app/services/coaching/contact/filterer.rb
|
<filename>app/services/coaching/contact/filterer.rb<gh_stars>0
class Coaching::Contact::Filterer < ApplicationFilterer
FILTERS_TO_DISPLAY = %w(
Pledge
).freeze
FILTERS_TO_HIDE = %w(
).freeze
end
|
chuckmersereau/api_practice
|
spec/validators/upload_extension_validator_spec.rb
|
require 'rails_helper'
describe UploadExtensionValidator do
subject do
UploadExtensionValidator.new(extension: 'xml', message: 'Must be xml!',
attributes: [:file])
end
let(:import) { build(:import, source: 'tnt') }
context 'extension is a string' do
it 'gives a validation error for a filename with an invalid extension' do
import = stub_import('not-xml.other')
subject.validate(import)
expect(import.errors[:file]).to include('Must be xml!')
end
it 'gives no error if extension is correct' do
import = stub_import('valid.xml')
subject.validate(import)
expect(import.errors[:file]).to be_empty
end
it 'gives no error if extension is correct but different case' do
import = stub_import('VALID.XML')
subject.validate(import)
expect(import.errors[:file]).to be_empty
end
end
context 'extension is an array [tntdatasync tntmpd]' do
subject do
UploadExtensionValidator.new(extension: %w(tntdatasync tntmpd), message: 'Must be tnt output!',
attributes: [:file])
end
it 'gives a validation error for a filename with an invalid extension' do
import = stub_import('not-tnt.other')
subject.validate(import)
expect(import.errors[:file]).to include('Must be tnt output!')
end
context 'extension is tntdatasync' do
it 'gives no error if extension is tntdatasync' do
import = stub_import('valid.tntdatasync')
subject.validate(import)
expect(import.errors[:file]).to be_empty
end
it 'gives no error if extension is tntdatasync but different case' do
import = stub_import('VALID.TNTDATASYNC')
subject.validate(import)
expect(import.errors[:file]).to be_empty
end
end
context 'extension is tntmpd' do
it 'gives no error if extension is tntmpd' do
import = stub_import('valid.tntmpd')
subject.validate(import)
expect(import.errors[:file]).to be_empty
end
it 'gives no error if extension is tntmpd but different case' do
import = stub_import('VALID.TNTMPD')
subject.validate(import)
expect(import.errors[:file]).to be_empty
end
end
end
def stub_import(filename)
file = double(path: filename)
import = double(errors: { file: [] }, file: file)
allow(import).to receive(:read_attribute_for_validation).with(:file) { file }
import
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160204190101_add_index_to_google_email_activities_activity_id.rb
|
class AddIndexToGoogleEmailActivitiesActivityId < ActiveRecord::Migration
self.disable_ddl_transaction!
def change
add_index :google_email_activities, :activity_id, algorithm: :concurrently
end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/webhook/base/email_bounce_handler.rb
|
# This class handles the case where an email has bounced after it was sent by Mail Chimp.
class MailChimp::Webhook::Base
class EmailBounceHandler
def initialize(account_list, email, reason)
@account_list = account_list
@email = email
@reason = reason
end
def handle_bounce
emails_to_clean = EmailAddress.joins(person: [:contacts])
.where(contacts: { account_list_id: @account_list.id }, email: @email)
emails_to_clean.each do |email_to_clean|
email_to_clean.update(historic: true, primary: false)
SubscriberCleanedMailer.delay.subscriber_cleaned(@account_list, email_to_clean)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/workers/user_adobe_campaign_subscriber_worker_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe UserAdobeCampaignSubscriberWorker do
let!(:user) { create(:person_with_gender) }
let(:email_address) { user.email_addresses.first.email }
let(:attrs) do
{ email: email_address,
firstName: user.first_name,
lastName: user.last_name }
end
let(:user_agent) do
"rest-client/2.0.2 (#{::RbConfig::CONFIG['host_os']} x86_64) ruby/2.5.1p57"
end
def content_length(hash)
::ActiveSupport::JSON.encode(hash).size
end
def auth_body
{ client_id: 'asdf',
client_secret: 'asdf',
jwt_token: 'asdf' }
end
def stub_all_requests
adobe_login_stub
adobe_campaign_stub
adobe_campaign_profile_stub
cru_campaign_stub
cru_campaign_stub_post
profile_services_stub
end
def adobe_login_stub
headers = {
'Accept' => '*/*',
'Accept-Encoding' => 'gzip, deflate',
'Content-Length' => '48',
'Content-Type' => 'application/x-www-form-urlencoded',
'Host' => 'ims-na1.adobelogin.com',
'User-Agent' => user_agent
}
stub_request(:post, 'https://ims-na1.adobelogin.com/ims/exchange/jwt')
.with(body: auth_body, headers: headers)
.to_return(status: 200, body: { content: [] }.to_json, headers: {})
end
def adobe_campaign_stub
headers = {
'Accept' => '*/*',
'Accept-Encoding' => 'gzip, deflate',
'Authorization' => 'Bearer',
'Host' => 'mc.adobe.io',
'User-Agent' => user_agent,
'X-Api-Key' => 'asdf'
}
stub_request(:get, "https://mc.adobe.io/cru/campaign/profileAndServices/profile/byEmail?email=#{email_address}")
.with(headers: headers)
.to_return(status: 200, body: { content: [] }.to_json, headers: {})
end
def adobe_campaign_profile_stub
headers = {
'Accept' => '*/*',
'Accept-Encoding' => 'gzip, deflate',
'Authorization' => 'Bearer',
'Content-Length' => content_length(attrs),
'Content-Type' => 'application/json',
'Host' => 'mc.adobe.io',
'User-Agent' => user_agent,
'X-Api-Key' => 'asdf'
}
stub_request(:post, 'https://mc.adobe.io/cru/campaign/profileAndServices/profile')
.with(body: attrs.to_json, headers: headers)
.to_return(status: 200, body: { content: [{ serviceName: ENV['ADOBE_SERVICE_NAME'] }] }.to_json, headers: {})
end
def cru_campaign_stub
headers = {
'Accept' => '*/*',
'Accept-Encoding' => 'gzip, deflate',
'Authorization' => 'Bearer',
'Host' => 'mc.adobe.io',
'User-Agent' => user_agent,
'X-Api-Key' => 'asdf'
}
stub_request(:get, 'https://mc.adobe.io/cru/campaign/')
.with(headers: headers)
.to_return(status: 200, body: { subscriber: { PKey: '' } }.to_json, headers: {})
end
def cru_campaign_stub_post
headers = {
'Accept' => '*/*',
'Accept-Encoding' => 'gzip, deflate',
'Authorization' => 'Bearer',
'Content-Length' => '28',
'Content-Type' => 'application/json',
'Host' => 'mc.adobe.io',
'User-Agent' => user_agent,
'X-Api-Key' => 'asdf'
}
stub_request(:post, 'https://mc.adobe.io/cru/campaign/')
.with(headers: headers)
.to_return(status: 200, body: { content: [] }.to_json, headers: {})
end
def profile_services_stub
headers = {
'Accept' => '*/*',
'Accept-Encoding' => 'gzip, deflate',
'Authorization' => 'Bearer',
'Host' => 'mc.adobe.io',
'User-Agent' => user_agent,
'X-Api-Key' => 'asdf'
}
stub_request(:get, 'https://mc.adobe.io/cru/campaign/profileAndServices/service/byText?text=MPDXSVC44')
.with(headers: headers)
.to_return(status: 200, body: { content: [] }.to_json, headers: {})
end
it 'queues up adobe campaign subscription' do
stub_all_requests
expect do
UserAdobeCampaignSubscriberWorker.perform_async(user.id)
end.to change(UserAdobeCampaignSubscriberWorker.jobs, :size).by(1)
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/referrer.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class Contact::Filter::Referrer < Contact::Filter::Base
def execute_query(contacts, filters)
filters = parse_list(filters[:referrer])
contacts = contacts.joins(:contact_referrals_to_me).where.not(contact_referrals: { referred_by_id: nil }) if filters.delete('any')
contacts = contacts.joins('LEFT OUTER JOIN "contact_referrals" ON "contact_referrals"."referred_to_id" = "contacts"."id"')
.where(contact_referrals: { referred_by_id: contact_referrer_ids(filters) }) if filters.present?
contacts
end
def title
_('Referrer')
end
def type
'multiselect'
end
def custom_options
[{ name: _('-- None --'), id: 'none' },
{ name: _('-- Has referrer --'), id: 'any' }] +
account_lists.map { |account_list| account_list.contacts.with_referrals.order('name') }
.flatten
.uniq
.collect { |c| { name: c.name, id: c.id } }
end
private
def contact_referrer_ids(filters)
contact_referrer_ids = Contact.where(id: filters - ['none']).ids
contact_referrer_ids << nil if filters.include?('none')
contact_referrer_ids
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/appeals_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::AppealsController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:factory_type) { :appeal }
let!(:resource) { create(:appeal, account_list: account_list) }
let!(:second_resource) { create(:appeal, account_list: account_list) }
let(:id) { resource.id }
let(:correct_attributes) { attributes_for(:appeal, name: 'Appeal 2') }
let(:unpermitted_attributes) { attributes_for(:appeal, name: 'Appeal 3') }
let(:incorrect_attributes) { attributes_for(:appeal, name: nil) }
let(:given_update_reference_key) { :name }
let(:given_update_reference_value) { 'Appeal 2' }
let(:correct_relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: account_list.id
}
}
}
end
let(:unpermitted_relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: create(:account_list).id
}
}
}
end
before do
resource.contacts << create(:contact, account_list: account_list) # Test inclusion of related resources.
end
include_examples 'create_examples'
include_examples 'show_examples'
include_examples 'update_examples'
include_examples 'destroy_examples'
include_examples 'index_examples'
describe '#index' do
before { api_login(user) }
describe 'filter[account_list_id]' do
let!(:first_account_list) { account_list }
let!(:second_account_list) { create(:account_list) }
let!(:appeal_for_second_account_list) { create(:appeal, account_list: second_account_list) }
before do
user.account_lists << second_account_list
end
it 'returns appeals from multiple accounts lists when not filtering' do
get :index
data = JSON.parse(response.body)['data']
expect(data.size).to eq(3)
ids = data.map { |d| d['id'] }
expect(ids).to contain_exactly(resource.id,
second_resource.id,
appeal_for_second_account_list.id)
end
it 'returns appeals from one account list when filtering' do
get :index, filter: { account_list_id: first_account_list.id }
data = JSON.parse(response.body)['data']
expect(data.size).to eq(2)
ids = data.map { |d| d['id'] }
expect(ids).to contain_exactly(resource.id,
second_resource.id)
end
it "includes the donation's contact when filtering" do
donor_account = create(:donor_account)
contact = create(:contact, account_list: account_list)
donor_account.contacts << contact
donation = create(:donation, donor_account: donor_account)
resource.donations << donation
get :index, include: 'donations.contacts', filter: { account_list_id: first_account_list.id }
body = JSON.parse(response.body)
expect(body['included'].first['id']).to eq(donation.id)
expect(body['included'].first['relationships']['contact']['data']['id']).to eq(contact.id)
end
it "does not permit filtering by an account list that's not owned by current user" do
not_my_account_list = create(:account_list)
get :index, filter: { account_list_id: not_my_account_list.id }
expect(response.code).to eq('403')
end
end
describe 'filter[wildcard_search]' do
context 'name contains' do
let!(:appeal) { create(factory_type, name: 'abcd', account_list: account_list) }
it 'returns appeal' do
get :index, filter: { wildcard_search: 'bc' }
expect(JSON.parse(response.body)['data'][0]['id']).to eq(appeal.id)
end
end
context 'name does not contain' do
let!(:appeal) { create(factory_type, name: 'abcd', account_list: account_list) }
it 'returns no appeals' do
get :index, filter: { wildcard_search: 'def' }
expect(JSON.parse(response.body)['data'].count).to eq(0)
end
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180209020330_change_wv_donation_amt_recommendation_to_uuid.rb
|
# This table is being created for Test and Development Environments
# On Prod there is a view being added to the database
class ChangeWvDonationAmtRecommendationToUuid < ActiveRecord::Migration
def change
remove_column :wv_donation_amt_recommendation, :organization_id, :integer
add_column :wv_donation_amt_recommendation, :organization_id, :uuid
end
end
|
chuckmersereau/api_practice
|
spec/factories/user_options.rb
|
<filename>spec/factories/user_options.rb
FactoryBot.define do
factory :user_option, class: 'User::Option' do
sequence(:key) { |n| "key_#{n}" }
value { Faker::Hipster.word }
user
end
end
|
chuckmersereau/api_practice
|
spec/services/google_email_integrator_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe GoogleEmailIntegrator, '#sync_mail' do
it 'imports emails if email integration enable' do
integration = build_google_integration(true)
integrator = GoogleEmailIntegrator.new(integration)
gmail_account = double
expect(Person::GmailAccount).to receive(:new) { gmail_account }
expect(gmail_account).to receive(:import_emails)
.with(integration.account_list, ['<EMAIL>'])
integrator.sync_mail
end
it 'does not import emails if integration not enabled' do
integrator = GoogleEmailIntegrator.new(build_google_integration(false))
expect(Person::GmailAccount).to_not receive(:new)
integrator.sync_mail
end
def build_google_integration(email_integration)
account_list = build(:account_list)
build(:google_integration, email_integration: email_integration,
account_list: account_list, email_blacklist: ['<EMAIL>'])
end
end
|
chuckmersereau/api_practice
|
app/policies/appeal_contact_policy.rb
|
<filename>app/policies/appeal_contact_policy.rb
class AppealContactPolicy < ApplicationPolicy
def initialize(context, resource)
@user = context.user
@resource = resource
end
private
def resource_owner?
user.account_lists.exists?(id: resource.appeal.account_list_id)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170830234109_add_index_on_contacts_status.rb
|
<gh_stars>0
class AddIndexOnContactsStatus < ActiveRecord::Migration
disable_ddl_transaction!
def change
add_index :contacts, :status, algorithm: :concurrently
end
end
|
chuckmersereau/api_practice
|
app/serializers/coaching/pledge_serializer.rb
|
class Coaching::PledgeSerializer < ApplicationSerializer
attributes :amount, :expected_date
belongs_to :contact, serializer: Coaching::ContactSerializer
end
|
chuckmersereau/api_practice
|
spec/models/person/facebook_account_spec.rb
|
<filename>spec/models/person/facebook_account_spec.rb
require 'rails_helper'
describe Person::FacebookAccount do
describe 'when authenticating' do
before do
@auth_hash = Hashie::Mash.new(uid: '5', credentials: { token: 'a', expires_at: 5 }, info: { first_name: 'John', last_name: 'Doe' })
end
describe 'create from auth' do
it 'creates an account linked to a person' do
person = create(:person)
expect do
@account = Person::FacebookAccount.find_or_create_from_auth(@auth_hash, person)
end.to change(Person::FacebookAccount, :count).by(1)
expect(person.facebook_accounts).to include(@account)
end
end
describe 'create user from auth' do
it 'creates a user with a first and last name' do
expect do
user = Person::FacebookAccount.create_user_from_auth(@auth_hash)
expect(user.first_name).to eq(@auth_hash.info.first_name)
expect(user.last_name).to eq(@auth_hash.info.last_name)
end.to change(User, :count).by(1)
end
end
it 'uses uid to find an authenticated user' do
user = create(:user)
Person::FacebookAccount.find_or_create_from_auth(@auth_hash, user)
expect(Person::FacebookAccount.find_authenticated_user(@auth_hash)).to eq(user)
end
end
it 'returns name for to_s' do
account = Person::FacebookAccount.new(first_name: 'John', last_name: 'Doe')
expect(account.to_s).to eq('<NAME>')
end
it 'generates a facebook url if there is a remote_id' do
account = Person::FacebookAccount.new(remote_id: 1)
expect(account.url).to eq('https://www.facebook.com/profile.php?id=1')
end
describe 'setting & getting facebook url which includes id/username' do
let(:account) { Person::FacebookAccount.new }
it 'defaults to url to nil' do
expect(account.url).to be_nil
end
it 'sets and gets the url based on username' do
account.url = 'http://www.facebook.com/john.doe'
expect(account.username).to eq('john.doe')
expect(account.url).to eq('https://www.facebook.com/john.doe')
end
it 'sets and gets the url based on id' do
account.url = 'facebook.com/profile.php?id=1'
expect(account.remote_id).to eq(1)
expect(account.url).to eq('https://www.facebook.com/profile.php?id=1')
end
end
context '#token_missing_or_expired?' do
it 'returns true if the token is expired' do
stub_request(:post, 'https://graph.facebook.com/oauth/access_token')
.to_return(status: 401, body: '')
account = Person::FacebookAccount.new(token: 'asdf', token_expires_at: 10.days.ago)
expect(account.token_missing_or_expired?).to be true
end
it 'tries to refresh once if the token is expired' do
account = Person::FacebookAccount.new(token: 'asdf', token_expires_at: 10.days.ago)
expect(account).to receive(:refresh_token)
expect(account.token_missing_or_expired?).to be true
end
it 'returns true if the token is missing' do
account = Person::FacebookAccount.new(token: '', token_expires_at: 10.days.from_now)
expect(account.token_missing_or_expired?).to be true
end
it 'returns false if the token is not expired' do
account = Person::FacebookAccount.new(token: 'asdf', token_expires_at: 10.days.from_now)
expect(account.token_missing_or_expired?).to be false
end
end
describe '#username=' do
subject { described_class.new }
context 'only name' do
let(:username) { 'tony.stark' }
it 'does not set remote id' do
expect { subject.username = username }.to_not change { subject.remote_id }
end
it 'persists value as-is' do
expect { subject.username = username }.to change { subject.username }.to(username)
end
end
context 'url with id' do
let(:username) { 'http://facebook.com/profile.php?id=1234345' }
it 'saves remote id' do
expect { subject.username = username }.to change { subject.remote_id }.to(1_234_345)
end
it 'persists path as username' do
expect { subject.username = username }.to change { subject.username }.to('profile.php?id=1234345')
end
end
context 'url with name' do
let(:username) { 'https://facebook.com/tony.stark' }
it 'does not set remote id' do
expect { subject.username = username }.to_not change { subject.remote_id }
end
it 'persists name as username' do
expect { subject.username = username }.to change { subject.username }.to('tony.stark')
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/mail_chimp_appeal_list_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe MailChimpAppealList do
end
|
chuckmersereau/api_practice
|
dev/migrate/2016_07_13_add_accounts_to_offorgs.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class AddAccountsToOfforgs
def add_accounts_to_off_orgs
off_orgs_with_no_designation_accounts.each do |org|
org.organization_accounts.find_each(batch_size: 400) do |org_account|
org.api(org_account).import_profiles
end
end
end
private
def off_orgs_with_no_designation_accounts
off_orgs = []
Organization.where(api_class: 'OfflineOrg').find_each do |org|
result = DesignationProfileAccount.where(
'designation_profile_id IN (?) AND designation_account_id NOT IN (?)',
org.designation_profiles.collect(&:id),
org.designation_accounts.collect(&:id)
)
off_orgs << org if result.empty?
end
off_orgs
end
end
|
chuckmersereau/api_practice
|
db/migrate/20121203214837_add_staff_account_id_and_chartfield_to_designation_account.rb
|
<gh_stars>0
class AddStaffAccountIdAndChartfieldToDesignationAccount < ActiveRecord::Migration
def change
add_column :designation_accounts, :staff_account_id, :string
add_column :designation_accounts, :chartfield, :string
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/wildcard_search_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Task::Filter::WildcardSearch do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:contact) { create(:contact, name: '<NAME>') }
let!(:task_one) do
create(:task,
account_list_id: account_list.id,
subject: 'I have Subject1 in here',
tag_list: 'tag1,tag2',
start_at: 1.day.ago,
completed: true)
end
let!(:task_two) do
create(:task,
account_list_id: account_list.id,
subject: 'subject2 is here',
tag_list: 'tag1',
contacts: [contact])
end
let!(:task_three) do
create(:task,
account_list_id: account_list.id,
subject: 'Subject3',
tag_list: 'tag3',
contacts: [contact])
end
let!(:task_four) do
create(:task,
account_list_id: account_list.id,
subject: 'Subject4',
comments: [build(:activity_comment, body: 'Commented right now!')])
end
describe '#query' do
let(:tasks) { account_list.tasks }
context 'with wildcard subject' do
it 'returns all tasks that match the subject' do
expect(described_class.query(tasks, { wildcard_search: 'subject1' }, nil).to_a).to eq [task_one]
expect(described_class.query(tasks, { wildcard_search: 'subject1' }, nil).to_a).not_to match_array(
[task_one, task_two, task_three]
)
end
end
context 'with a single wildcard tag (partial or not)' do
it 'returns all tasks that match the tag' do
expect(described_class.query(tasks, { wildcard_search: 'tag1' }, nil).to_a).to match_array(
[task_one, task_two]
)
expect(described_class.query(tasks, { wildcard_search: 'tag' }, nil).to_a).to match_array(
[task_one, task_two, task_three]
)
end
end
context 'with a comment body containing the string' do
it 'returns all tasks with a matching comment' do
expect(described_class.query(tasks, { wildcard_search: 'commented right' }, nil).to_a).to match_array(
[task_four]
)
expect(described_class.query(tasks, { wildcard_search: 'now' }, nil).to_a).to match_array(
[task_four]
)
end
end
context 'with a contact name containing the string' do
it 'returns all tasks with a matching contact' do
expect(described_class.query(tasks, { wildcard_search: 'contact name' }, nil).to_a).to match_array(
[task_two, task_three]
)
expect(described_class.query(tasks, { wildcard_search: 'act na' }, nil).to_a).to match_array(
[task_two, task_three]
)
end
end
context 'has a filter already applied' do
it 'returns all tasks that match the subject' do
filtered_tasks =
tasks.where(completed: true, account_list: account_list, start_at: 1.week.ago..2.weeks.from_now)
.order(:start_at)
.uniq
expect(described_class.query(filtered_tasks, { wildcard_search: 'subject1' }, nil).to_a).to eq(
[task_one]
)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/appeals/excluded_appeal_contacts_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Appeals > ExcludedAppealContacts' do
include_context :json_headers
documentation_scope = :appeals_api_excluded_appeal_contacts
let(:resource_type) { 'excluded_appeal_contacts' }
let!(:user) { create(:user_with_full_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:appeal) { create(:appeal, account_list: account_list) }
let(:appeal_id) { appeal.id }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:new_contact) { create(:contact, account_list: account_list) }
let!(:excluded_appeal_contact) { create(:appeal_excluded_appeal_contact, appeal: appeal, contact: contact) }
let(:id) { excluded_appeal_contact.id }
let(:resource_attributes) do
%w(
reasons
created_at
updated_at
updated_in_db_at
)
end
let(:resource_associations) do
%w(
contact
appeal
)
end
context 'authorized user' do
before do
api_login(user)
end
get '/api/v2/appeals/:appeal_id/excluded_appeal_contacts' do
with_options scope: :sort do
parameter 'contact.name', 'Sort by Contact Name', type: 'String'
end
response_field 'data', 'Data', type: 'Array[Object]'
example 'ExcludedAppealContact [LIST]', document: documentation_scope do
explanation 'List of Excluded Contacts associated to the Appeal'
do_request
check_collection_resource(1, %w(relationships))
expect(response_status).to eq 200
end
end
get '/api/v2/appeals/:appeal_id/excluded_appeal_contacts/:id' do
with_options scope: [:data, :attributes] do
end
example 'ExcludedAppealContact [GET]', document: documentation_scope do
explanation 'The Excluded Appeal Contact with the given ID'
do_request
check_resource(%w(relationships))
expect(response_status).to eq 200
end
end
delete '/api/v2/appeals/:appeal_id/excluded_appeal_contacts/:id' do
parameter 'id', 'ID', required: true
example 'ExcludedAppealContact [DELETE]', document: documentation_scope do
explanation 'Remove the Excluded Appeal Contact with the given ID from the Appeal'
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120228124823_make_street_a_text_field.rb
|
class MakeStreetATextField < ActiveRecord::Migration
def up
change_column :addresses, :street1, :text
rename_column :addresses, :street1, :street
remove_column :addresses, :street2
remove_column :addresses, :street3
add_column :addresses, :primary_mailing_address, :boolean, default: false
add_column :addresses, :address_type, :string
end
def down
remove_column :addresses, :address_type
remove_column :addresses, :primary_mailing_address
add_column :addresses, :street3, :string
add_column :addresses, :street2, :string
rename_column :addresses, :street, :street1
change_column :addresses, :street1, :string
end
end
|
chuckmersereau/api_practice
|
dev/util/mailchimp_util.rb
|
<gh_stars>0
def schedule_sync(mc_account, index)
id = mc_account.id
num_secs = index * 60
MailChimpAccount.perform_in(num_secs.seconds, id, :call_mail_chimp, :export_to_primary_list)
end
def backup_mc_account(mc_account)
puts mc_account.id
json = {
account_list: mc_account.account_list,
members: mc_account.list_members(mc_account.primary_list_id)
}.to_json
filename = "mc_backup/#{mc_account.id}.json"
File.open(filename, 'w') { |file| file.write(json) }
rescue StandardError => e
puts e
end
# this class exists to help understand the state of data synced (or not synced) to a Mailchimp.
class MailChimpReport
@report = {}
attr_reader :report, :not_in_mailchimp, :mailchimp_dups, :wrapper
def run(account_list, list_id = nil)
if account_list.is_a? AccountList
mca = account_list.mail_chimp_account
elsif account_list.is_a? MailChimpAccount
mca = account_list
account_list = mca.account_list
else
raise 'needs an account list or mailchimp account'
end
raise 'no active mailchimp account' unless mca&.active
list_id ||= mca.primary_list_id
raise 'no primary_list_id' unless list_id
@wrapper = MailChimp::GibbonWrapper.new(mca)
members = @wrapper.list_members(list_id)
members.each { |member| member['email_address'] = member['email_address'].downcase }
@mailchimp_dups = members.group_by { |member| member['email_address'] }
.select { |_, group| group.count > 1 }
account_list_emails = EmailAddress.joins(person: [:contacts])
.where(contacts: { account_list_id: account_list.id })
active_emails = account_list_emails.where(historic: false)
primary_emails = active_emails.where(primary: true)
non_opt_out_people_emails = primary_emails.where(people: { optout_enewsletter: false })
newsletter_emails = non_opt_out_people_emails.where(contacts: { send_newsletter: %w(Email Both) })
@report = {}
members.each do |member|
email = member['email_address']
next add_to_list(:newsletter_contacts, member) if newsletter_emails.exists?(email: email)
next add_to_list(:active_contacts, member) if non_opt_out_people_emails.exists?(email: email)
next add_to_list(:opted_out, member) if primary_emails.exists?(email: email)
next add_to_list(:non_primary, member) if active_emails.exists?(email: email)
next add_to_list(:inactive_email, member) if account_list_emails.exists?(email: email)
add_to_list(:not_in_mpdx, member)
end
@not_in_mailchimp = newsletter_emails.pluck(:email) - members.map { |member| member['email_address'] }
print_report
nil
end
private
def add_to_list(list, member)
@report[list] ||= { subscribed: [], unsubscribed: [], manual_unsubscribed: [], cleaned: [], pending: [] }
status = member['status'].to_sym
status = :manual_unsubscribed if status == :unsubscribed && !MailChimpMember.mpdx_unsubscribe?(member)
@report[list][status] << member
end
def puts_counts(list)
unless @report[list]
puts 'None'
puts ' '
return
end
puts @report[list].transform_values(&:count)
bad_category = list == :newsletter_contacts ? :unsubscribed : :subscribed
puts @report[list][bad_category].map { |member| member['email_address'] } if @report[list][bad_category].any?
puts ' '
end
def print_report
if @mailchimp_dups.keys.any?
puts '=========='
puts 'Duplicate emails in mailchimp:'
puts @mailchimp_dups.keys
end
if @not_in_mailchimp.any?
puts '=========='
puts 'Emails in MPDX but not in mailchimp:'
puts 'We can try to resubscribe them if you agree they should be in Mailchimp.'
puts @not_in_mailchimp
end
puts '=========='
puts 'Newsletter contacts:'
puts 'These email addresses are primary on a contact that has newsletter set to either Email or Both.'
puts 'We can try to resubscribe them if you think they were unsubscribed in error.'
puts_counts :newsletter_contacts
puts 'Active Contacts (Physical or none newsletter):'
puts_counts :active_contacts
puts 'Opted Out = true:'
puts 'These emails addresses are primary on a person in MPDX who is labeled '\
'with "Opt-out of Email Newsletter", but are subscribed on Mailchimp.'
puts 'They should either be unsubscribed on Mailchimp if they asked you to mark them as such,'
puts 'or that flag should be removed in MPDX if they should be subscribed.'
puts_counts :opted_out
puts 'Non-primary email addresses:'
puts 'These emails addresses are non-primary on people in MPDX, but are subscribed in Mailchimp.'
puts 'We can unsubscribe them on Mailchimp if they are old email addresses.'
puts_counts :non_primary
puts 'Historic Emails:'
puts 'These emails addresses are marked as "Invalid" in MPDX, but are subscribed in Mailchimp.'
puts 'We can unsubscribe them on Mailchimp if they are old email addresses.'
puts_counts :inactive_email
puts 'Not in MPDX:'
puts 'These email addresses are subscribed on Mailchimp, but are not in MPDX.'
puts "We suggest adding them to a contact in MPDX so they don't fall through the cracks."
puts_counts :not_in_mpdx
end
end
# something like
# set_member_status('<EMAIL>', :unsubscribed, mca, mca.primary_list_id)
# or
# set_member_status(@wrapper.list_members(list_id).first, 'subscribed', mca)
def set_member_status(member, status, mail_chimp_account, list_id = nil)
email = if member.is_a? String
member
else
member['email_address']
end
return unless email
list_id ||= member['list_id']
gibbon = Gibbon::Request.new(api_key: mail_chimp_account.api_key, debug: true)
gibbon.lists(list_id).members(mail_chimp_account.email_hash(email)).update(body: { status: status.to_s })
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/addresses_controller.rb
|
class Api::V2::Contacts::AddressesController < Api::V2Controller
def index
authorize_index
load_addresses
render json: @addresses.preload_valid_associations(include_associations),
meta: meta_hash(@addresses),
include: include_params,
fields: field_params
end
def show
load_address
authorize_address
render_address
end
def create
persist_address
end
def update
load_address
authorize_address
persist_address
end
def destroy
load_address
authorize_address
destroy_address
end
private
def address_params
params
.require(:address)
.permit(address_attributes)
end
def address_attributes
Address::PERMITTED_ATTRIBUTES
end
def address_scope
current_contact.addresses
end
def current_contact
@contact ||= Contact.find(params[:contact_id])
end
def authorize_index
authorize(current_contact, :show?)
end
def authorize_address
authorize(current_contact)
end
def build_address
@address ||= address_scope.build
@address.assign_attributes(address_params)
end
def destroy_address
@address.destroy
head :no_content
end
def load_address
@address ||= address_scope.find(params[:id])
end
def load_addresses
@addresses = address_scope.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def persist_address
build_address
authorize_address
if save_address
render_address
else
render_with_resource_errors(@address)
end
end
def render_address
render json: @address,
status: success_status,
include: include_params,
fields: field_params
end
def save_address
@address.save(context: persistence_context)
end
def pundit_user
PunditContext.new(current_user, contact: current_contact)
end
def default_sort_param
Address.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
spec/support/shared_controller_examples/sparse_fieldsets_examples.rb
|
RSpec.shared_examples 'sparse fieldsets examples' do |options|
context "action #{options[:action]} sparse fieldsets" do
let(:action) { options[:action].to_sym }
let(:example_attributes) { serializer.attributes.except(:id).keys.first(2).collect(&:to_s) }
let(:fields) { { resource_type => example_attributes.join(',') } }
let(:expected_response_code) do
if options[:expected_response_code]
options[:expected_response_code]
else
case action
when :index, :show, :update
200
when :create
201
end
end
end
let(:response_attributes) do
data = JSON.parse(response.body)['data']
data.is_a?(Array) ? data.first['attributes'] : data['attributes']
end
subject do
api_login(user)
case action
when :index
get action, parent_param_if_needed.merge(fields: fields)
when :show
get action, full_params.merge(fields: fields)
when :update
put action, full_correct_attributes.merge(fields: fields)
when :create
post action, full_correct_attributes.merge(fields: fields)
end
end
it 'supports sparse fieldsets' do
subject
expect(response.status).to eq(expected_response_code), invalid_status_detail
expect(response_attributes.keys).to match_array(example_attributes)
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170918022812_create_background_batches.rb
|
<filename>db/migrate/20170918022812_create_background_batches.rb
class CreateBackgroundBatches < ActiveRecord::Migration
def change
create_table :background_batches do |t|
t.string :batch_id
t.belongs_to :user, index: true
t.uuid :uuid, null: false, index: true, default: 'uuid_generate_v4()'
t.timestamps null: false
end
add_foreign_key :background_batches, :people, column: :user_id
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120202203409_create_person_facebook_accounts.rb
|
class CreatePersonFacebookAccounts < ActiveRecord::Migration
def change
create_table :person_facebook_accounts do |t|
t.integer :person_id, null: false
t.column :remote_id, :bigint, null: false
t.string :token
t.datetime :token_expires_at
t.timestamps null: false
end
add_index :person_facebook_accounts, [:person_id, :remote_id], unique: true
add_index :person_facebook_accounts, :remote_id
end
end
|
chuckmersereau/api_practice
|
app/models/person.rb
|
class Person < ApplicationRecord
include BetweenScopeable
include YearCompletable
include Deceased
PAPER_TRAIL_IGNORED_FIELDS = [
:updated_at, :global_registry_id, :global_registry_mdm_id, :sign_in_count,
:current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip
].freeze
audited associated_with: :contact, except: PAPER_TRAIL_IGNORED_FIELDS
between_scopes_for :anniversary
between_scopes_for :birthday
RELATIONSHIPS_MALE =
[_('Husband'), _('Son'), _('Father'), _('Brother'), _('Uncle'), _('Nephew'), _('Cousin (Male)'), _('Grandfather'),
_('Grandson')].freeze
RELATIONSHIPS_FEMALE =
[_('Wife'), _('Daughter'), _('Mother'), _('Sister'), _('Aunt'), _('Niece'), _('Cousin (Female)'), _('Grandmother'),
_('Granddaughter')].freeze
TITLES = [_('Mr.'), _('Mrs.'), _('Miss'), _('Ms.'), _('Rev.'), _('Hon.'), _('Dr.')].freeze
SUFFIXES = [_('Jr.'), _('Sr.')].freeze
MARITAL_STATUSES = [_('Single'), _('Engaged'), _('Married'), _('Separated'), _('Divorced'), _('Widowed')].freeze
belongs_to :master_person
has_many :email_addresses,
-> { order('email_addresses.primary::int desc') },
dependent: :destroy,
autosave: true
has_one :primary_email_address,
-> { where('email_addresses.primary' => true) },
class_name: 'EmailAddress',
foreign_key: :person_id
has_many :phone_numbers,
-> { order('phone_numbers.primary::int desc') },
dependent: :destroy
has_one :primary_phone_number,
-> { where('phone_numbers.primary' => true) },
class_name: 'PhoneNumber',
foreign_key: :person_id
has_many :family_relationships,
dependent: :delete_all
has_many :related_people,
through: :family_relationships
has_one :company_position,
-> { where('company_positions.end_date is null').order('company_positions.start_date desc') },
class_name: 'CompanyPosition',
foreign_key: :person_id
has_many :company_positions,
dependent: :delete_all
has_many :twitter_accounts,
class_name: 'Person::TwitterAccount',
foreign_key: :person_id,
dependent: :delete_all,
autosave: true
has_one :twitter_account,
-> { where('person_twitter_accounts.primary' => true) },
class_name: 'Person::TwitterAccount',
foreign_key: :person_id
has_many :facebook_accounts,
class_name: 'Person::FacebookAccount',
foreign_key: :person_id,
dependent: :delete_all,
autosave: true
has_one :facebook_account,
class_name: 'Person::FacebookAccount',
foreign_key: :person_id
has_many :linkedin_accounts,
class_name: 'Person::LinkedinAccount',
foreign_key: :person_id,
dependent: :delete_all,
autosave: true
has_one :linkedin_account,
-> { where('person_linkedin_accounts.valid_token' => true) },
class_name: 'Person::LinkedinAccount',
foreign_key: :person_id
has_many :websites,
class_name: 'Person::Website',
foreign_key: :person_id,
dependent: :delete_all,
autosave: true
has_one :website,
-> { where('person_websites.primary' => true) },
class_name: 'Person::Website',
foreign_key: :person_id
has_many :google_accounts,
class_name: 'Person::GoogleAccount',
foreign_key: :person_id,
dependent: :destroy, autosave: true
has_many :google_integrations, through: :google_accounts
has_many :organization_accounts,
class_name: 'Person::OrganizationAccount',
foreign_key: :person_id,
dependent: :destroy
has_many :key_accounts,
class_name: 'Person::KeyAccount',
foreign_key: :person_id,
dependent: :delete_all
has_many :companies,
through: :company_positions
has_many :donor_account_people
has_many :donor_accounts,
through: :donor_account_people
has_many :contact_people,
dependent: :destroy
has_many :contacts,
through: :contact_people
has_many :account_lists,
through: :contacts
has_many :pictures,
as: :picture_of,
dependent: :destroy
has_one :primary_picture,
-> { where(primary: true) },
as: :picture_of,
class_name: 'Picture'
has_many :comments,
dependent: :destroy,
class_name: 'ActivityComment'
has_many :messages_sent,
class_name: 'Message',
foreign_key: :from_id,
dependent: :delete_all
has_many :messages_received,
class_name: 'Message',
foreign_key: :to_id,
dependent: :delete_all
has_many :google_contacts,
autosave: true
scope :alive, -> { where.not(deceased: true) }
scope :by_anniversary, -> { order('anniversary_month, anniversary_day') }
scope :by_birthday, -> { order('birthday_month, birthday_day') }
scope :search_for_contacts, lambda { |contacts = []|
joins(:contact_people)
.where(contact_people: { contact: contacts })
}
accepts_nested_attributes_for :email_addresses,
reject_if: -> (e) { e[:email].blank? },
allow_destroy: true
accepts_nested_attributes_for :phone_numbers,
reject_if: -> (p) { p[:number].blank? },
allow_destroy: true
accepts_nested_attributes_for :family_relationships,
reject_if: -> (p) { p[:related_person_id].blank? },
allow_destroy: true
accepts_nested_attributes_for :facebook_accounts,
reject_if: -> (p) { p[:username].blank? },
allow_destroy: true
accepts_nested_attributes_for :twitter_accounts,
reject_if: -> (p) { p[:screen_name].blank? },
allow_destroy: true
accepts_nested_attributes_for :linkedin_accounts,
reject_if: -> (p) { p[:public_url].blank? },
allow_destroy: true
accepts_nested_attributes_for :pictures,
reject_if: -> (p) { p[:image].blank? && p[:image_cache].blank? },
allow_destroy: true
accepts_nested_attributes_for :websites,
reject_if: -> (p) { p[:url].blank? },
allow_destroy: true
PERMITTED_ATTRIBUTES = [
:id,
:age,
:anniversary_day,
:anniversary_month,
:anniversary_year,
:birthday_day,
:birthday_month,
:birthday_year,
:contact_ids,
:created_at,
:deceased,
:employer,
:first_name,
:gender,
:last_name,
:legal_first_name,
:marital_status,
:middle_name,
:occupation,
:optout_enewsletter,
:overwrite,
:suffix,
:title,
:updated_at,
:updated_in_db_at,
{
email_address: :email,
email_addresses_attributes: [
:_destroy,
:id,
:_client_id,
:email,
:historic,
:location,
:overwrite,
:primary,
:source,
:valid_values,
:updated_in_db_at
],
facebook_accounts_attributes: [
:_destroy,
:id,
:_client_id,
:overwrite,
:username,
:updated_in_db_at
],
family_relationships_attributes: [
:_destroy,
:id,
:_client_id,
:overwrite,
:related_person_id,
:relationship,
:updated_in_db_at
],
linkedin_accounts_attributes: [
:_destroy,
:id,
:_client_id,
:overwrite,
:public_url,
:updated_in_db_at
],
phone_number: :number,
phone_numbers_attributes: [
:_destroy,
:id,
:_client_id,
:historic,
:location,
:number,
:overwrite,
:primary,
:source,
:valid_values,
:updated_in_db_at
],
pictures_attributes: [
:_destroy,
:id,
:_client_id,
:image,
:image_cache,
:overwrite,
:primary,
:updated_in_db_at
],
twitter_accounts_attributes: [
:_destroy,
:id,
:_client_id,
:overwrite,
:primary,
:screen_name,
:updated_in_db_at
],
websites_attributes: [
:_destroy,
:id,
:_client_id,
:overwrite,
:primary,
:url,
:updated_in_db_at
]
}
].freeze
before_create :find_master_person
after_destroy :clean_up_master_person
before_save :check_state_for_mail_chimp_sync
after_save :trigger_mail_chimp_syncs_to_relevant_contacts, if: :sync_with_mail_chimp_required?
validates :first_name, presence: true
alias_attribute :birth_year, :birthday_year
alias_attribute :birth_month, :birthday_month
alias_attribute :birth_day, :birthday_day
alias_attribute :marriage_year, :anniversary_year
alias_attribute :marriage_month, :anniversary_month
alias_attribute :marriage_day, :anniversary_day
alias_attribute :deceased_flag, :deceased
global_registry_bindings mdm_id_column: :global_registry_mdm_id,
fields: { birth_year: :integer,
birth_month: :integer,
birth_day: :integer,
marriage_year: :integer,
marriage_month: :integer,
marriage_day: :integer,
first_name: :string,
last_name: :string,
title: :string,
suffix: :string,
gender: :string,
marital_status: :string,
middle_name: :string,
deceased_flag: :boolean,
occupation: :string,
employer: :string }
def to_s
[first_name, last_name].join(' ')
end
def to_s_last_first
[last_name, first_name].join(', ')
end
def add_spouse(spouse)
relationship = case spouse.gender
when 'male'
'Husband'
when 'female'
'Wife'
else
'Wife' # Default to wife
end
begin
family_relationships.where(related_person_id: spouse.id).first_or_create(relationship: relationship)
rescue ActiveRecord::RecordNotUnique
end
end
def spouse
family_relationships.find_by(relationship: %w(Husband Wife)).try(:related_person)
end
def to_user
@user ||= User.find(id)
end
def email=(val)
self.email_address = { email: val, primary: true }
end
def email
primary_email_address || email_addresses.first
end
def facebook_accounts_attributes=(attributes_data)
cleaned_data = reject_duplicate_facebook_username_data(attributes_data)
super(cleaned_data)
end
def family_relationships_attributes=(data_object)
case data_object
when Array
data_object.each { |attributes| assign_family_relationships_from_data_attributes(attributes) }
when Hash
assign_family_relationships_with_data_hash(data_object)
end
end
def assign_family_relationships_from_data_attributes(attributes)
if attributes[:id]
fr = family_relationships.find(attributes[:id])
if attributes[:_destroy] == '1' || attributes[:related_person_id].blank?
fr.destroy
else
begin
fr.update_attributes(attributes.except(:id, :_destroy))
rescue ActiveRecord::RecordNotUnique
fr.destroy
end
end
elsif attributes[:related_person_id].present?
FamilyRelationship.add_for_person(self, attributes)
end
end
def assign_family_relationships_with_data_hash(hash)
hash = hash.with_indifferent_access
hash.each do |_, attributes|
assign_family_relationships_from_data_attributes(attributes)
end
end
def email_address=(hash)
hash = hash.with_indifferent_access
if hash['_destroy'].to_s == '1'
email_addresses.find(hash['id']).destroy
elsif hash['email'].present?
EmailAddress.add_for_person(self, hash)
end
end
def email_addresses_attributes=(attributes)
if attributes.is_a?(Hash)
attributes.each do |_, v|
self.email_address = v
end
elsif attributes.is_a?(Array)
attributes.each do |v|
self.email_address = v
end
else
super
end
end
def phone_number=(hash)
add_phone_number(hash)
end
def add_phone_number(hash)
hash = hash.with_indifferent_access
PhoneNumber.add_for_person(self, hash) if hash.with_indifferent_access['number'].present?
end
def phone_number
primary_phone_number
end
def phone
primary_phone_number.try(:number)
end
def phone=(number)
self.phone_number = { number: number }
end
def merge_phone_numbers
phone_numbers.reload.each do |phone_number|
other_phone = phone_numbers.find do |pn|
pn.id != phone_number.id &&
pn == phone_number
end
next unless other_phone
phone_number.merge(other_phone)
merge_phone_numbers
break
end
end
def title=(value)
value_with_trail = "#{value}."
if Person::TITLES.include?(value_with_trail)
super value_with_trail
else
super value
end
end
def suffix=(value)
value_with_trail = "#{value}."
if Person::SUFFIXES.include?(value_with_trail)
super value_with_trail
else
super value
end
end
def profession=(value)
self.occupation ||= value
end
def merge(other)
Person.transaction(requires_new: true) do
# This is necessary in case this is executed in a loop of merges which could cause the master_person
# stored in memory to become out of date with what's in the database and cause an error.
reload
other.reload
other.messages_sent.update_all(from_id: id)
other.messages_received.update_all(to_id: id)
%w(phone_numbers company_positions).each do |relationship|
other.send(relationship.to_sym).each do |other_rel|
next if send(relationship.to_sym).find { |rel| rel == other_rel }
other_rel.update_column(:person_id, id)
end
end
merge_phone_numbers
# handle a few things separately to check for duplicates
%w(twitter_accounts facebook_accounts linkedin_accounts
google_accounts key_accounts organization_accounts).each do |relationship|
other.send(relationship).each do |record|
next if send(relationship).where(person_id: id, remote_id: record.remote_id).any?
record.update_attribute(:person_id, id)
end
end
other.email_addresses.each do |email_address|
next if email_addresses.find_by(email: email_address.email)
if primary_email_address.present?
# if there is already a primary email address on a person, we don't want to try to move the
# loser's primary, which will override the winner's primary setting.
email_address.update(person_id: id, primary: false)
else
email_address.update(person_id: id)
end
end
other.pictures.each do |picture|
picture.picture_of = self
picture.save
end
# because we're in a transaction, we need to keep track of which relationships we've updated so
# we don't create duplicates on the next part
FamilyRelationship.where(related_person_id: other.id).find_each do |fr|
next if FamilyRelationship.find_by(person_id: fr.person_id, related_person_id: id)
fr.update_attributes(related_person_id: id)
end
FamilyRelationship.where(person_id: other.id).find_each do |fr|
next if FamilyRelationship.where(related_person_id: fr.person_id, person_id: id)
fr.update_attributes(person_id: id)
end
# Copy fields over updating any field that's blank on the winner
[:first_name, :last_name, :age, :legal_first_name, :birthday_month, :birthday_year, :birthday_day, :anniversary_month,
:anniversary_year, :anniversary_day, :title, :suffix, :gender, :marital_status,
:middle_name, :access_token].each do |field|
next unless send(field).blank? && other.send(field).present?
send("#{field}=".to_sym, other.send(field))
end
# Assume the winner has the nickname and the loser has the full name, and increment the times merged to
# track which nicknames are useful and to add new nicknames over time.
Nickname.increment_times_merged(other.first_name, first_name)
# Save the master person sources for the winner to add after it (and usually its master person) are destroyed
other_master_person_id = other.master_person.id
other_master_person_sources = other.master_person.master_person_sources.pluck(:organization_id, :remote_id)
ids = [id, other.id]
DuplicateRecordPair.type(self.class).find_by(record_one_id: ids, record_two_id: ids)&.destroy
other.reload
other.destroy
# Merge the master person records if they were different.
Person.where(master_person_id: other_master_person_id).find_each do |person_same_master_other|
person_same_master_other.update(master_person: master_person)
end
MasterPerson.find_by(id: other_master_person_id).try(:destroy) unless other_master_person_id == master_person_id
other_master_person_sources.each do |organization_id, remote_id|
master_person.master_person_sources.find_or_create_by(organization_id: organization_id, remote_id: remote_id)
end
end
save(validate: false)
end
def self.clone(person)
new_person = new(
person.attributes.except(
'id', 'access_token', 'created_at', 'current_sign_in_at', 'current_sign_in_ip', 'last_sign_in_at',
'last_sign_in_ip', 'preferences', 'sign_in_count'
)
)
person.email_addresses.each { |e| new_person.email = e.email }
person.phone_numbers.each { |pn| new_person.phone_number = pn.attributes.slice(:number, :country_code, :location) }
new_person.save(validate: false)
new_person
end
def contact
@contact ||= contacts.first
end
def contact_id
contact.try(:id)
end
def to_person
self
end
def age=(value)
@age = value
end
def age
@birthday_year = birthday_year
if @birthday_year != nil && @age == nil
@age = Time.current.year - @birthday_year
end
return @age
end
def birthday_year
get_four_digit_year_from_value(attributes['birthday_year']) || placeholder_for_missing_year(:birthday)
end
def anniversary_year
get_four_digit_year_from_value(attributes['anniversary_year']) || placeholder_for_missing_year(:anniversary)
end
def entity_attributes_to_push
entity_attributes = super
entity_attributes[:gender] = gender_entity_attribute
entity_attributes.merge! authentication_attributes
entity_attributes.merge! linked_identities_entity_attributes
end
private
def gender_entity_attribute
case gender
when 'female', 'Female'
'Female'
when 'male', 'Male'
'Male'
else
'Male'
end
end
def authentication_attributes
# Global Registry only allows one of each authentication type
authentication = {}
# If more than 1 key account, last wins
key_accounts.each { |a| authentication[:key_guid] = a.remote_id }
authentication[:facebook_uid] = facebook_account&.remote_id if facebook_account
authentication.present? ? { authentication: authentication } : {}
end
def linked_identities_entity_attributes
# Link account_number to siebel or peoplesoft if present
account_number = donor_accounts.first&.account_number
return {} unless account_number.present? && account_number.length > 5
{ account_number: account_number,
linked_identities: {
pshr: { account_number: account_number },
siebel: { account_number: account_number }
} }
end
def trigger_mail_chimp_syncs_to_relevant_contacts
contacts.each(&:sync_with_mail_chimp)
end
def sync_with_mail_chimp_required?
@mail_chimp_sync
end
def check_state_for_mail_chimp_sync
@mail_chimp_sync = true if should_trigger_mail_chimp_sync?
end
def should_trigger_mail_chimp_sync?
optout_enewsletter_changed?
end
def find_master_person
self.master_person_id = MasterPerson.find_or_create_for_person(self).id unless master_person_id
end
def clean_up_master_person
master_person.destroy if master_person && (master_person.people - [self]).blank?
end
def reject_duplicate_facebook_username_data(attributes_data)
case attributes_data
when Array
reject_duplicate_facebook_usernames_from_data_array(attributes_data)
when Hash
reject_duplicate_facebook_usernames_from_data_array(attributes_data.values)
end
end
def reject_duplicate_facebook_usernames_from_data_array(data_array)
data_array = data_array.map(&:deep_symbolize_keys)
persisted_records, new_records = data_array.partition { |attrs| attrs[:id].present? }
new_records.each_with_object(persisted_records) do |new_record, records_to_keep|
records_to_keep << new_record unless records_to_keep.any? { |record_to_keep| record_to_keep[:username] == new_record[:username] }
end
end
# If the date has a day and a month but no year then we want to default the year to a particular value.
# If day, month, and year are all nil then year should remain nil.
def placeholder_for_missing_year(date_name)
day_attribute_name = "#{date_name}_day"
month_attribute_name = "#{date_name}_month"
return unless send(day_attribute_name) && send(month_attribute_name)
1900
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170419001725_add_file_row_failures_to_imports.rb
|
class AddFileRowFailuresToImports < ActiveRecord::Migration
def change
add_column :imports, :file_row_failures, :text
end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/webhook/appeal_list.rb
|
# This class holds all the methods associated to the Mail Chimp webhooks that are linked to an appeal list.
module MailChimp::Webhook
class AppealList < Base
def subscribe_hook(email)
# This will have to be implemented one day
end
def unsubscribe_hook(_email, _reason)
# This will have to be implemented one day
end
def email_update_hook(old_email, new_email)
# This will have to be implemented one day
end
def email_cleaned_hook(email, reason)
return if reason == 'abuse'
EmailBounceHandler.new(@account_list, email, reason).handle_bounce
end
end
end
|
chuckmersereau/api_practice
|
config/initializers/sidekiq.rb
|
require 'sidekiq_job_args_logger'
require 'sidekiq_mem_notifier'
require 'datadog/statsd'
require Rails.root.join('config', 'initializers', 'redis').to_s
Sidekiq.configure_client do |config|
config.redis = { url: Redis.current.client.id,
namespace: "MPDX:#{Rails.env}:resque" }
end
if Sidekiq::Client.method_defined? :reliable_push!
Sidekiq::Client.reliable_push!
end
Sidekiq.configure_server do |config|
Sidekiq::Logging.logger.level = Logger::WARN unless Rails.env.development?
Rails.logger = Sidekiq::Logging.logger
config.super_fetch!
config.reliable_scheduler!
config.redis = { url: Redis.current.client.id,
namespace: "MPDX:#{Rails.env}:resque" }
config.server_middleware do |chain|
chain.add SidekiqAuditedUser
end
config.error_handlers << Proc.new { |exception, context_hash| Rollbar.error(exception, context_hash) }
end
Sidekiq.default_worker_options = {
backtrace: false,
# Set uniqueness lock expiration to 24 hours to balance preventing
# duplicate jobs from running (if uniqueness time is too short) and donor
# import / email jobs not getting queued because the locks don't
# always get cleared properly (perhaps on new deploys/out of memory
# errors).
unique_expiration: 24.hours
}
unless Rails.env.development? || Rails.env.test?
Sidekiq::Pro.dogstatsd = -> { Datadog::Statsd.new(ENV['DATADOG_HOST'], ENV['DATADOG_PORT']) }
end
Sidekiq::Extensions.enable_delay!
SidekiqMemNotifier.start
|
chuckmersereau/api_practice
|
spec/factories/activities.rb
|
<filename>spec/factories/activities.rb
FactoryBot.define do
factory :activity do
association :account_list
starred false
location 'MyString'
subject 'MyString'
start_at '2012-03-08 14:59:46'
end_at '2012-03-08 14:59:46'
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170814230054_deprecate_contacts_not_duplicated_with.rb
|
class DeprecateContactsNotDuplicatedWith < ActiveRecord::Migration
def change
rename_column :contacts, :not_duplicated_with, :deprecated_not_duplicated_with
end
end
|
chuckmersereau/api_practice
|
lib/json_api_service/resource_lookup.rb
|
module JsonApiService
class ResourceLookup
attr_reader :custom_references
def initialize(custom_references = {})
@custom_references = custom_references
end
def find(resource_type)
find_class_by_type(resource_type).constantize
end
def find_type_by_class(resource_class)
resource_class_name = resource_class.to_s
return nil if resource_class_name.blank?
custom_references.detect { |_, class_name| class_name == resource_class_name }&.first ||
resource_class_name.underscore.pluralize.to_sym
end
private
def find_class_by_type(resource_type)
normalized_type = resource_type.to_s.pluralize
custom_references[normalized_type.to_sym] || normalized_type.classify
end
end
end
|
chuckmersereau/api_practice
|
app/services/person/filterer.rb
|
<gh_stars>0
class Person::Filterer < ApplicationFilterer
FILTERS_TO_HIDE = %w(
Deceased
EmailAddressValid
PhoneNumberValid
UpdatedAt
WildcardSearch
).freeze
end
|
chuckmersereau/api_practice
|
db/migrate/20140915141209_add_sync_info_to_google_contacts.rb
|
class AddSyncInfoToGoogleContacts < ActiveRecord::Migration
def change
add_column :google_contacts, :last_synced, :datetime
add_column :google_contacts, :last_etag, :string
add_column :google_contacts, :last_data, :text
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170223165218_add_validation_columns_to_email_addresses.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class AddValidationColumnsToEmailAddresses < ActiveRecord::Migration
def change
add_column :email_addresses, :valid_values, :boolean, default: true
add_column :email_addresses, :source, :string, default: 'MPDX'
end
end
|
chuckmersereau/api_practice
|
app/services/donation_imports/base.rb
|
class DonationImports::Base
attr_reader :organization_account, :organization
def initialize(organization_account)
@organization_account = organization_account
@organization = organization_account.organization
end
# Data server supports two date formats, try both of those,
# as I work on different donation integrations, this will probably have to be moved to a module.
def parse_date(date_object)
return date_object.to_date if date_object.is_a?(Date) || date_object.is_a?(Time)
extract_date_from_string(date_object, '%Y-%m-%d') || extract_date_from_string(date_object, '%m/%d/%Y')
end
private
def extract_date_from_string(date_object, date_format)
Date.strptime(date_object, date_format)
rescue ArgumentError
nil
end
end
|
chuckmersereau/api_practice
|
spec/lib/json_api_service/data_object_spec.rb
|
require 'spec_helper'
require 'json_api_service/data_object'
require 'json_api_service/object_store'
require 'json_api_service/relationships_object'
module JsonApiService
RSpec.describe DataObject do
describe '#initialize' do
it 'initializes with data and a store' do
data = build_data
store = build_store
object = build_object(data: data, store: store)
expect(object.data).to eq data
expect(object.store).to eq store
end
end
describe '#id' do
it 'pulls the id from the object data' do
data = {
id: 'abc123-abc123-abc123-abc123'
}
object = build_object(data: data)
expect(object.id).to eq 'abc123-abc123-abc123-abc123'
end
end
describe '#attributes' do
it 'pulls the attributes from the object data' do
data = {
attributes: {
first_name: 'Steve',
last_name: 'Rogers'
}
}
object = build_object(data: data)
expect(object.attributes).to eq data[:attributes]
end
end
describe '#relationships' do
it 'pulls and converts the relationships from the object data' do
object = build_object
expect(object.relationships).to be_kind_of RelationshipsObject
end
end
describe '#type' do
it 'pulls the type from the object data' do
data = {
type: 'users'
}
object = build_object(data: data)
expect(object.type).to eq 'users'
end
end
describe '#to_h' do
it 'turns the objects back into a hash' do
object = build_object
expect(object.to_h).to eq build_data
end
end
describe '#merge' do
it 'pulls the attributes / relationships from another object if missing' do
initial_data = {
type: 'users',
id: 'abc-123',
attributes: {},
relationships: {}
}
initial_object = build_object(data: initial_data)
alternate_data = {
type: 'users',
id: 'abc-123',
attributes: {
name: '<NAME>'
},
relationships: {
account_list: {
data: {
type: 'account_lists',
id: 'id-account-list'
}
}
}
}
alternate_object = build_object(data: alternate_data)
expect(initial_object.attributes) .to be_empty
expect(initial_object.relationships).to be_empty
initial_object.merge(alternate_object)
expect(initial_object.attributes) .to eq alternate_object.attributes
expect(initial_object.relationships).to eq alternate_object.relationships
end
end
describe '#validate_against_store' do
let(:store) { build_store }
before do
contact_data = {
type: 'contacts',
id: 'id-contact',
attributes: {
first_name: 'Tony',
last_name: 'Stark'
}
}
email_data = {
type: 'emails',
id: 'id-email',
attributes: {
email: '<EMAIL>'
}
}
# ensure store already has data
build_object(data: contact_data, store: store)
build_object(data: email_data, store: store)
end
it 'will fetch attributes from stored versions if they exist' do
data = {
type: 'contacts',
id: 'id-contact',
attributes: {}, # empty on purpose
relationships: {
emails: {
data: [
{
type: 'emails',
id: 'id-email'
}
]
}
}
}
object = build_object(data: data, store: store)
expect(store['contacts'][object.id]).not_to eq object
expect(object.attributes).to be_empty
expect(object.relationships[:emails].first.attributes).to be_empty
object.validate_against_store
expect(object.attributes).to eq(
first_name: 'Tony',
last_name: 'Stark'
)
expect(object.relationships[:emails].first.attributes).to eq(
email: '<EMAIL>'
)
expect(store['contacts'][object.id]).to eq object
end
end
private
def build_data
{
type: 'contacts',
id: 'abc123-abc123-abc123-abc123',
attributes: {
first_name: 'Steve',
last_name: 'Rogers'
},
relationships: {
account_list: {
data: {
type: 'account_lists',
id: 'abc123-abc123-abc123-abc123-'
}
},
addresses: {
data: [
{
type: 'addresses',
id: 'def456-def456-def456-def456'
},
{
type: 'addresses',
id: 'ghi456-ghi456-ghi456-ghi456'
}
]
}
}
}
end
def build_object(data: build_data, store: build_store)
DataObject.new(data, store: store)
end
def build_store
ObjectStore.new
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/social_items.rb
|
FactoryBot.define do
factory :social_item do
end
end
|
chuckmersereau/api_practice
|
spec/services/expected_totals_report/row_formatter_spec.rb
|
require 'rails_helper'
module ExpectedTotalsReport
describe RowFormatter, '#format' do
it 'converts currency and expands out contact fields' do
allow(CurrencyRate).to receive(:latest_for_pair) { 0.5 }
account_list = build_stubbed(:account_list, salary_currency: 'USD')
contact = build_stubbed(:contact,
name: 'Joe', pledge_currency: 'EUR',
pledge_amount: 2, status: 'Partner - Special',
pledge_frequency: 1)
row = { type: 'likely', contact: contact, donation_amount: 10,
donation_currency: 'EUR' }
formatted = RowFormatter.new(account_list).format(row)
expect(formatted[:type]).to eq 'likely'
expect(formatted[:contact_id]).to eq contact.id
expect(formatted[:contact_name]).to eq 'Joe'
expect(formatted[:contact_status]).to eq 'Partner - Special'
expect(formatted[:pledge_amount]).to eq 2
expect(formatted[:pledge_frequency]).to eq 'Monthly'
expect(formatted[:pledge_currency]).to eq 'EUR'
expect(formatted[:pledge_currency_symbol]).to eq '€'
expect(formatted[:donation_amount]).to eq 10
expect(formatted[:donation_currency]).to eq 'EUR'
expect(formatted[:donation_currency_symbol]).to eq '€'
expect(formatted[:converted_amount]).to eq 5
expect(formatted[:converted_currency]).to eq 'USD'
expect(formatted[:converted_currency_symbol]).to eq '$'
expect(CurrencyRate).to have_received(:latest_for_pair)
.with(from: 'EUR', to: 'USD')
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/donations_eager_loader.rb
|
<reponame>chuckmersereau/api_practice
class Contact::DonationsEagerLoader
def initialize(account_list:, donations_scoper: nil, contacts_scoper: nil)
@account_list = account_list
@donations_scoper = donations_scoper
@contacts_scoper = contacts_scoper
end
def contacts_with_donations
contacts = scoped_contacts.to_a
contacts.each do |contact|
contact.loaded_donations = donations_for_contact(contact)
end
contacts
end
def donations_and_contacts
donations = scoped_donations
contacts = Set.new
scoped_donations.each do |donation|
contact = contacts_by_donor_id[donation.donor_account_id]
donation.loaded_contact = contact
contacts << contact
end
[donations, contacts.to_a]
end
private
def scoped_contacts
contacts = @account_list.contacts
contacts = @contacts_scoper.call(contacts) if @contacts_scoper
contacts.includes(:contact_donor_accounts)
end
def donations_for_contact(contact)
contact_donor_ids(contact).flat_map(&method(:donations_for_donor_id))
end
def contact_donor_ids(contact)
# contact_donor_accounts is eager loaded below, so just use map and not
# a join and pluck.
contact.contact_donor_accounts.map(&:donor_account_id)
end
def donations_for_donor_id(donor_account_id)
@donations_by_donor_id ||= scoped_donations.group_by(&:donor_account_id)
@donations_by_donor_id[donor_account_id] || []
end
def contacts_by_donor_id
return @contacts_by_donor_id if @contacts_by_donor_id
@contacts_by_donor_id = {}
scoped_contacts.each do |contact|
contact_donor_ids(contact).each do |donor_id|
@contacts_by_donor_id[donor_id] ||= contact
end
end
@contacts_by_donor_id
end
def scoped_donations
@scoped_donations ||=
begin
donations = contact_donations
donations = @donations_scoper.call(donations) if @donations_scoper
donations.to_a
end
end
def contact_donations
@account_list.scope_donations_by_designations(
Donation.where(donor_account_id: all_contact_donor_ids)
)
end
def all_contact_donor_ids
scoped_contacts.joins(:contact_donor_accounts)
.pluck('contact_donor_accounts.donor_account_id')
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/reports/activity_results_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::Reports::ActivityResultsController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:given_serializer_class) { Reports::ActivityResultsPeriodSerializer }
let(:given_resource_type) { 'reports_activity_results_periods' }
let(:factory_type) { :account_list }
let(:resource) do
Reports::ActivityResultsPeriod.new(account_list: account_list,
start_date: 1.week.ago,
end_date: DateTime.current)
end
let(:correct_attributes) { {} }
describe 'index' do
before do
contact = create(:contact, account_list: account_list)
account_list.primary_appeal = create(:appeal)
create(:pledge, contact: contact, appeal: account_list.primary_appeal)
end
include_examples 'index_examples', except: [:sorting, :pagination]
end
describe 'Filters' do
it 'allows a user to request from their account_list' do
api_login(user)
get :index, filter: { account_list_id: account_list.id }
expect(response.status).to eq 200
end
it 'blocks a user from accessing others account lists' do
api_login(create(:user))
get :index, filter: { account_list_id: account_list.id }
expect(response.status).to eq 404
end
end
describe 'meta' do
let(:averages) { response_json['meta']['averages'] }
it 'sends averages of values in ActivityResultsPeriod objects' do
api_login(user)
get :index, filter: { account_list_id: account_list.id }
expect(averages.keys).to match_array %w(average_completed_appointment
average_completed_call
average_completed_email
average_uncompleted_text_message
average_uncompleted_thank
average_uncompleted_to_do
average_completed_facebook_message
average_completed_letter
average_uncompleted_support_letter
average_uncompleted_talk_to_in_person
average_completed_newsletter_email
average_completed_newsletter_physical
average_uncompleted_pre_call_letter
average_uncompleted_reminder_letter
average_completed_prayer_request
average_completed_pre_call_letter
average_uncompleted_newsletter_physical
average_uncompleted_prayer_request
average_completed_reminder_letter
average_completed_support_letter
average_uncompleted_letter
average_uncompleted_newsletter_email
average_completed_talk_to_in_person
average_completed_text_message
average_uncompleted_call
average_uncompleted_email
average_uncompleted_facebook_message
average_completed_thank
average_completed_to_do
average_uncompleted_appointment)
end
it 'sends only meta for requested fields' do
api_login(user)
get :index,
filter: { account_list_id: account_list.id },
fields: { reports_activity_results_periods: 'completed_call,completed_email' }
expect(averages.keys).to eq %w(average_completed_call average_completed_email)
end
end
context 'as coach' do
include_context 'common_variables'
let(:coach) { create(:user).becomes(User::Coach) }
let(:contact) do
create(:contact, account_list: account_list,
created_at: 4.months.ago,
status: 'Call for Appointment',
pledge_amount: nil)
end
before do
travel_to(1.week.ago) { contact.update(status: 'Partner - Financial', pledge_amount: 100) }
account_list.coaches << coach
full_params[:account_list_id] = account_list.id
end
it 'allows access to report' do
api_login(coach)
get :index, full_params
expect(response.status).to eq(200), invalid_status_detail
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160202105600_add_pledge_currency_to_contacts.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class AddPledgeCurrencyToContacts < ActiveRecord::Migration
def change
add_column :contacts, :pledge_currency, :string, limit: 4
end
end
|
chuckmersereau/api_practice
|
app/services/donation_reports/donation_info.rb
|
<filename>app/services/donation_reports/donation_info.rb
class DonationReports::DonationInfo < ActiveModelSerializers::Model
ATTRIBUTES = [
:amount,
:contact_id,
:contact_name,
:converted_amount,
:converted_currency,
:currency,
:donation_date,
:donation_id,
:likelihood_type
].freeze
attr_accessor(*ATTRIBUTES)
def self.from_donation(donation, converted_currency = 'USD')
new(
amount: donation.amount,
contact_id: donation.loaded_contact.try(:id),
contact_name: donation.loaded_contact.try(:name),
converted_amount: CurrencyRate.convert_on_date(
amount: donation.amount,
date: donation.donation_date,
from: donation.currency,
to: converted_currency
),
converted_currency: converted_currency,
currency: donation.currency,
donation_date: donation.donation_date,
donation_id: donation.id,
likelihood_type: 'received'
)
end
end
|
chuckmersereau/api_practice
|
app/models/concerns/after_validation_set_source_to_mpdx.rb
|
module Concerns::AfterValidationSetSourceToMPDX
extend ActiveSupport::Concern
included do
after_validation do
self.source = self.class::MANUAL_SOURCE if source_should_be_changed_to_mpdx?
true
end
end
private
def source_should_be_changed_to_mpdx?
persisted? &&
errors.none? &&
source == ::TntImport::SOURCE &&
!changes.keys.map(&:to_sym).include?(:source) &&
changes.any? { |_attribute, values| values.second.present? }
end
end
|
chuckmersereau/api_practice
|
app/services/application_duplicate_pairs_finder.rb
|
# This abstract class provides base behaviour for finding duplicate records within the given AccountList.
#
# The general process to find duplicates would go like this:
#
# 1. Load record data from the database into hashes.
# 2. Find duplicates by comparing values in the hashes.
# 3. Create DuplicateRecordPair records in the database.
class ApplicationDuplicatePairsFinder
attr_reader :account_list, :duplicate_ids, :duplicate_record_pairs
def initialize(account_list)
@account_list = account_list
@duplicate_ids = Set.new
@duplicate_record_pairs = []
raise "record_type #{record_type} is not valid!" unless DuplicateRecordPair::TYPES.include?(record_type)
end
def find_and_save
delete_pairs_with_missing_records
find_duplicates
duplicate_record_pairs.select(&:save)
end
private
def delete_pairs_with_missing_records
association = record_type.pluralize.downcase
all_records_scope = account_list.send(association)
[:record_one_id, :record_two_id].each do |id_attribute|
account_list.duplicate_record_pairs.type(record_type).where.not(id_attribute => all_records_scope).delete_all
end
end
def find_duplicates
raise 'This method should be overloaded by the child class'
end
def record_type
@record_type ||= self.class.to_s.split(':').first
end
# Given an Array of Hashes, find duplicate Hashes by comparing a particular key/value in each Hash.
# This method is designed for performance. Sorting the Array once and then looping once is much faster than if we used a nested loop.
# It assumes that each hash has an "id" key with value. Hashes with the same id will never be considered duplicates.
def find_duplicate_hashes_by_value(array_of_hashes, key_to_compare, comparison_method_name = :values_present_and_equal?)
# Sort the hashes by the value under key_to_compare, so that we can search for duplicates faster.
sorted_hashes = array_of_hashes.sort { |a, b| a[key_to_compare] <=> b[key_to_compare] }
sorted_hashes.each_with_index.collect do |target_hash, index|
next_hash = find_next_hash_to_compare(sorted_hashes: sorted_hashes, target_hash: target_hash, target_hash_index: index)
# Compare the hashes by their values under the key_to_compare.
next unless next_hash && send(comparison_method_name, target_hash[key_to_compare], next_hash[key_to_compare])
[next_hash, target_hash]
end.compact
end
# Find the next hash that has a different id, starting from the target_hash_index.
def find_next_hash_to_compare(sorted_hashes:, target_hash:, target_hash_index:)
index = target_hash_index
loop do
index += 1
next_hash = sorted_hashes[index]
break next_hash unless next_hash && next_hash[:id] == target_hash[:id]
end
end
def values_present_and_equal?(value_one, value_two)
value_one.present? && value_two.present? && value_one == value_two
end
def values_present_and_intersecting?(value_one, value_two)
value_one.present? && value_two.present? && (value_one & value_two).present?
end
def add_duplicate_pair_from_hashes(duplicates, reason)
record_one_id = duplicates.first[:id]
record_two_id = duplicates.second[:id]
return if duplicate_ids.include?(record_one_id) || duplicate_ids.include?(record_two_id)
duplicate_ids << record_one_id
duplicate_ids << record_two_id
duplicate_record_pairs << build_duplicate_record_pair(record_one_id, record_two_id, reason)
end
def build_duplicate_record_pair(record_one_id, record_two_id, reason)
DuplicateRecordPair.new(account_list_id: account_list.id, reason: reason,
record_one_id: record_one_id, record_one_type: record_type,
record_two_id: record_two_id, record_two_type: record_type)
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/prayer_letters_accounts_controller.rb
|
class Api::V2::AccountLists::PrayerLettersAccountsController < Api::V2Controller
def show
load_prayer_letters_account
authorize_prayer_letters_account
render_prayer_letters_account
end
def create
persist_prayer_letters_account
end
def destroy
load_prayer_letters_account
authorize_prayer_letters_account
destroy_prayer_letters_account
end
def sync
load_prayer_letters_account
authorize_prayer_letters_account
@prayer_letters_account.queue_subscribe_contacts
render_200
end
private
def destroy_prayer_letters_account
@prayer_letters_account.destroy
head :no_content
end
def load_prayer_letters_account
@prayer_letters_account ||= prayer_letters_acount_scope.prayer_letters_account
raise ActiveRecord::RecordNotFound unless @prayer_letters_account
end
def render_prayer_letters_account
render json: @prayer_letters_account,
status: success_status,
include: include_params,
fields: field_params
end
def persist_prayer_letters_account
build_prayer_letters_account
authorize_prayer_letters_account
if save_prayer_letters_account
render_prayer_letters_account
else
render_with_resource_errors(@prayer_letters_account)
end
end
def build_prayer_letters_account
@prayer_letters_account ||= prayer_letters_acount_scope.prayer_letters_account&.build || PrayerLettersAccount.new
@prayer_letters_account.assign_attributes(prayer_letters_account_params.merge(account_list_id: load_account_list.id))
authorize_prayer_letters_account
end
def save_prayer_letters_account
@prayer_letters_account.save(context: persistence_context)
end
def prayer_letters_account_params
params
.require(:prayer_letters_account)
.permit(PrayerLettersAccount::PERMITTED_ATTRIBUTES)
end
def authorize_prayer_letters_account
authorize @prayer_letters_account
end
def prayer_letters_acount_scope
load_account_list
end
def load_account_list
@account_list ||= AccountList.find(params[:account_list_id])
end
def pundit_user
PunditContext.new(current_user, account_list: load_account_list)
end
end
|
chuckmersereau/api_practice
|
spec/models/notification_type/task_if_period_past_spec.rb
|
require 'rails_helper'
describe NotificationType::TaskIfPeriodPast do
let!(:task_if_period_past) { NotificationType::TaskIfPeriodPast.first_or_initialize }
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact, created_at: 3.years.ago, account_list: account_list, status: 'Partner - Financial') }
context '#check' do
before { allow(task_if_period_past).to receive(:task_activity_type).and_return('Call') }
it 'add a notification if an activity came from more than a year ago' do
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
start_at: 2.years.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(1)
end
it 'adds no notification if an activity come from a financial partner within a year' do
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
start_at: 5.days.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(0)
end
it 'adds a notification for non-monthly partners' do
contact.update(pledge_frequency: 12.0)
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
start_at: 2.years.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(1)
end
it 'add no notification for non-financial partner' do
contact.update(status: 'Partner - Pray')
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
start_at: 2.years.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(0)
end
it 'add no notification if contact is created within a year and first activity is started at within a year' do
contact.update(created_at: 5.months.ago, status: 'Partner - Financial', pledge_frequency: 1.0)
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
start_at: 5.weeks.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(0)
end
it 'add a notification if contact is created within a year and first activity is started more than a year ago' do
contact.update(created_at: 5.months.ago)
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
start_at: 2.years.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(1)
end
it 'add no notification if the notification task was deleted to make sure it check for prior notifications' do
task = create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
start_at: 2.weeks.ago)
contact.notifications.create!(notification_type_id: task_if_period_past.id, event_date: 2.weeks.ago)
task.destroy
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(0)
end
it 'add no notification if a contact was created within a year and have no activities imported' do
contact.update(created_at: 3.months.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(0)
end
it 'add a notification if an activity came from more than a year ago' do
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
completed_at: 2.years.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(1)
end
it 'adds no notification if an activity come from a financial partner within a year' do
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
completed_at: 5.days.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(0)
end
it 'adds a notification for non-monthly partners' do
contact.update(pledge_frequency: 12.0)
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
completed_at: 2.years.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(1)
end
it 'add no notification for non-financial partner' do
contact.update(status: 'Partner - Pray')
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
completed_at: 2.years.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(0)
end
it 'add no notification if contact is created within a year and first activity is started at within a year' do
contact.update(created_at: 5.months.ago, status: 'Partner - Financial', pledge_frequency: 1.0)
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
completed_at: 5.weeks.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(0)
end
it 'add a notification if contact is created within a year and first activity is started more than a year ago' do
contact.update(created_at: 5.months.ago)
create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
completed_at: 2.years.ago)
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(1)
end
it 'add no notification if the notification task was deleted to make sure it check for prior notifications' do
task = create(:task, activity_type: 'Call', contacts: [contact], account_list: contact.account_list,
completed_at: 2.weeks.ago)
contact.notifications.create!(notification_type_id: task_if_period_past.id, event_date: 2.weeks.ago)
task.destroy
notifications = task_if_period_past.check(contact.account_list)
expect(notifications.length).to eq(0)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_timezone_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Task::Filter::ContactTimezone 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, timezone: 'Mountain Time (US & Canada)') }
let!(:contact_two) { create(:contact, account_list_id: account_list.id, timezone: 'Eastern Time (US & Canada)') }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, timezone: nil) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id, timezone: nil) }
let!(:task_one) { create(:task, account_list: account_list, contacts: [contact_one]) }
let!(:task_two) { create(:task, account_list: account_list, contacts: [contact_two]) }
let!(:task_three) { create(:task, account_list: account_list, contacts: [contact_three]) }
let!(:task_four) { create(:task, account_list: account_list, contacts: [contact_four]) }
describe '#query' do
let(:tasks) { account_list.tasks }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_timezone: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_timezone: [] }, account_list)).to eq(nil)
end
end
context 'filter task based on contact timezone' do
it 'returns the tasks with contacts whose timezone matches the provided filter' do
expect(described_class.query(tasks, { contact_timezone: 'Mountain Time (US & Canada)' }, account_list).to_a).to eq [task_one]
expect(described_class.query(tasks, { contact_timezone: 'Eastern Time (US & Canada)' }, account_list).to_a).to eq [task_two]
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20171101004028_add_oauth_to_organizations.rb
|
class AddOauthToOrganizations < ActiveRecord::Migration
def change
add_column :organizations, :oauth_url, :string
add_column :organizations, :oauth_get_challenge_start_num_url, :string
add_column :organizations, :oauth_get_challenge_start_num_params, :string
add_column :organizations, :oauth_get_challenge_start_num_oauth, :string
add_column :organizations, :oauth_convert_to_token_url, :string
add_column :organizations, :oauth_convert_to_token_params, :string
add_column :organizations, :oauth_convert_to_token_oauth, :string
add_column :organizations, :oauth_get_token_info_url, :string
add_column :organizations, :oauth_get_token_info_params, :string
add_column :organizations, :oauth_get_token_info_oauth, :string
add_column :organizations, :account_balance_oauth, :string
add_column :organizations, :donations_oauth, :string
add_column :organizations, :addresses_oauth, :string
add_column :organizations, :addresses_by_personids_oauth, :string
add_column :organizations, :profiles_oauth, :string
end
end
|
chuckmersereau/api_practice
|
app/services/task/filter/contact_status.rb
|
class Task::Filter::ContactStatus < Task::Filter::Base
def execute_query(tasks, filters)
filters = clean_contact_filter(filters)
tasks.joins(:contacts).merge(Contact::Filter::Status.query(Contact, filters, account_lists))
end
# Reversing is handled by {Contact::Filter::Status}
alias execute_reverse_query execute_query
def title
_('Contact Status')
end
delegate :custom_options,
:parent,
:type,
to: 'Contact::Filter::Status.new(account_lists)'
end
|
chuckmersereau/api_practice
|
spec/concerns/between_scopeable_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe BetweenScopeable, type: :concern do
describe '#with_`attribute`_this_week' do
let!(:person_with_birthday_last_week) do
date = (Date.current - 1.week).end_of_week
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let!(:person_with_birthday_this_week) do
date = Date.current
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let!(:person_with_birthday_next_week) do
date = (Date.current + 1.week).beginning_of_week
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
context 'without passing in a specific week start_date' do
let(:results) do
Person.with_birthday_this_week
end
it 'adds a scope for finding records within this current week' do
expect(results).not_to include person_with_birthday_last_week
expect(results).to include person_with_birthday_this_week
expect(results).not_to include person_with_birthday_next_week
end
end
context 'with passing in a specific week start_date' do
let(:next_week) { (Date.current + 1.week).beginning_of_week }
let(:results) do
Person.with_birthday_this_week(next_week)
end
it 'adds a scope for finding records within this current week' do
expect(results).not_to include person_with_birthday_last_week
expect(results).not_to include person_with_birthday_this_week
expect(results).to include person_with_birthday_next_week
end
end
end
describe '#with_`attribute`_in_same_month_between_two_dates' do
let(:start_date) { '2017-02-10'.to_date }
let(:end_date) { '2017-02-20'.to_date }
let!(:person_with_birthday_on_toothache_day) do
date = '2017-02-09'.to_date
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let!(:person_with_birthday_on_valentines_day) do
date = '2017-02-14'.to_date
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let!(:person_with_birthday_on_card_reading_day) do
date = '2017-02-21'.to_date
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let(:results) do
Person
.with_birthday_in_same_month_between_two_dates(start_date, end_date)
end
it 'finds records within the same month between two dates' do
expect(results).not_to include(person_with_birthday_on_toothache_day)
expect(results).to include(person_with_birthday_on_valentines_day)
expect(results).not_to include(person_with_birthday_on_card_reading_day)
end
it 'raises an error if the start_date is after the end_date' do
start_date = Date.current
end_date = start_date - 1.day
expect do
Person
.with_birthday_in_same_month_between_two_dates(start_date, end_date)
end.to raise_error(ArgumentError)
.with_message('start_date cannot take place after end_date')
end
it "raises an error if the start_date and end_date aren't in same month" do
start_date = Date.current
end_date = Date.current + 1.month
expect do
Person
.with_birthday_in_same_month_between_two_dates(start_date, end_date)
end.to raise_error(ArgumentError)
.with_message('dates must be in the same month')
end
end
describe '#with_`attribute`_in_neighboring_months_between_two_dates' do
let(:start_date) { '2016-12-25'.to_date }
let(:end_date) { '2017-01-02'.to_date }
let!(:person_with_birthday_on_christmas_eve) do
date = '2016-02-24'.to_date
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let!(:person_with_birthday_on_new_years_eve) do
date = '2016-12-31'.to_date
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let!(:person_with_birthday_on_new_years_day) do
date = '2017-01-01'.to_date
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let!(:person_with_birthday_on_festival_of_sleep_day) do
date = '2017-01-03'.to_date
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let(:results) do
Person
.with_birthday_in_neighboring_months_between_two_dates(start_date, end_date)
end
it 'finds records within neighboring months between two dates' do
expect(results).not_to include(person_with_birthday_on_christmas_eve)
expect(results).to include(person_with_birthday_on_new_years_eve)
expect(results).to include(person_with_birthday_on_new_years_day)
expect(results).not_to include(person_with_birthday_on_festival_of_sleep_day)
end
it 'raises an error if the start_date is after the end_date' do
start_date = Date.current
end_date = start_date - 1.day
expect do
Person
.with_birthday_in_neighboring_months_between_two_dates(start_date, end_date)
end.to raise_error(ArgumentError)
.with_message('start_date cannot take place after end_date')
end
it "raises an error if the start_date and end_date aren't neighboring months" do
start_date = '2016-12-01'.to_date
end_date = '2017-02-01'.to_date
expect do
Person
.with_birthday_in_neighboring_months_between_two_dates(start_date, end_date)
end.to raise_error(ArgumentError)
.with_message('dates cannot be more than one month apart')
end
end
end
|
chuckmersereau/api_practice
|
dev/migrate/off_orgs_test_data.rb
|
# Creates test data for users that belongs to offline organizations
def build_test_data
users.find_each do |user|
# Creates the organization account, account list and designation profile, according
# to OrganizationAccount class for offline organizations
build_org_account(user, off_org)
account_list = build_account_list(user)
build_designation_profile(off_org, user, account_list)
# Creates a contact, with his donor account and generates a donation
contact = build_contact(account_list)
donor_account = build_donor_account(off_org, account_list, contact)
build_donation(donor_account)
end
end
def users
User.offset(30).limit(10)
end
def off_org
@off_org ||= Organization.where(api_class: 'OfflineOrg').first
end
def build_org_account(user, organization)
Person::OrganizationAccount.create!(person_id: user.id,
organization_id: organization.id,
test_scene: true)
end
def build_account_list(user)
user.account_lists.create!(name: user.to_s, creator_id: user.id)
end
def build_designation_profile(organization, user, account_list)
organization.designation_profiles.create!(name: user.to_s,
user_id: user.id,
account_list_id: account_list.id)
end
def build_contact(account_list)
Contact.create!(name: 'Test',
account_list_id: account_list.id)
end
def build_donor_account(organization, account_list, contact)
donor_account = DonorAccount.create!(organization_id: organization.id,
account_number: account_list.id)
ContactDonorAccount.create!(donor_account_id: donor_account.id,
contact_id: contact.id)
end
def build_donation(donor_account)
Donation.create!(donor_account_id: donor_account.id,
designation_account_id: nil,
donation_date: Time.now.utc,
amount: 15)
end
|
chuckmersereau/api_practice
|
db/migrate/20130708164710_create_pictures.rb
|
<reponame>chuckmersereau/api_practice<filename>db/migrate/20130708164710_create_pictures.rb
class CreatePictures < ActiveRecord::Migration
def change
create_table :pictures do |t|
t.integer :picture_of_id
t.string :picture_of_type
t.string :image
t.boolean :primary, default: false, null: false
t.timestamps null: false
end
add_index :pictures, [:picture_of_id, :picture_of_type], name: 'picture_of'
end
end
|
chuckmersereau/api_practice
|
app/services/contact/partner_status_guesser.rb
|
<reponame>chuckmersereau/api_practice
class Contact::PartnerStatusGuesser
def initialize(contact)
@contact = contact
end
def assign_guessed_status
# If they have a donor account id, they are at least a special donor
# If they have given the same amount for the past 3 months, we'll assume they are
# a monthly donor.
gifts = donations.where(donor_account_id: contact.donor_account_ids,
designation_account_id: designation_account_ids)
.order('donation_date desc')
latest_donation = gifts[0]
return unless latest_donation
pledge_frequency = contact.pledge_frequency
pledge_amount = contact.pledge_amount
if latest_donation.donation_date.to_time > 2.months.ago && latest_donation.channel == 'Recurring'
status = 'Partner - Financial'
pledge_frequency = 1 unless contact.pledge_frequency
pledge_amount = latest_donation.amount unless contact.pledge_amount.to_i.positive?
else
status = 'Partner - Special'
end
contact.update(status: status, pledge_frequency: pledge_frequency,
pledge_amount: pledge_amount)
end
private
attr_reader :contact
delegate :donations, to: :contact
def designation_account_ids
contact.account_list.designation_account_ids
end
end
|
chuckmersereau/api_practice
|
spec/mailers/previews/run_once_preview.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/mailers/previews/run_once_preview.rb<gh_stars>0
class RunOncePreview < ApplicationPreview
def fix_newsletter_status
RunOnceMailer.fix_newsletter_status('<EMAIL>', 12, 'Staff Account')
end
def new_mailchimp_list
RunOnceMailer.new_mailchimp_list('<EMAIL>', 12, 'Staff Account', 'https://us1.admin.mailchimp.com/lists/members/?id=1234')
end
def gdpr_unsubscribes
contact = account_list.contacts.first || FactoryBot.create(:contact, account_list: account_list)
person = contact.people.first || FactoryBot.create(:person, contacts: [contact])
email = person.primary_email_address || FactoryBot.create(:email_address, primary: true, person: person)
unsubscribe = RunOnce::SendGDPRUnsubscribesWorker.new.build_unsubscribes_list(account_list, [email]).first
RunOnceMailer.gdpr_unsubscribes('<EMAIL>', account_list.name, unsubscribe)
end
end
|
chuckmersereau/api_practice
|
app/services/tnt_import/tnt_codes.rb
|
class TntImport::TntCodes
# This is an ordered array of the Tnt phone types. The order matters because the tnt PreferredPhoneType
# is an index that into this list and the PhoneIsValidMask is a bit vector that refers to these in order too.
TNT_PHONES = [
{ field: 'HomePhone', location: 'home', person: :both }, # index 0
{ field: 'HomePhone2', location: 'home', person: :both },
{ field: 'HomeFax', location: 'fax', person: :both },
{ field: 'OtherPhone', location: 'other', person: :both },
{ field: 'OtherFax', location: 'fax', person: :both },
{ field: 'MobilePhone', location: 'mobile', person: :primary },
{ field: 'MobilePhone2', location: 'mobile', person: :primary },
{ field: 'PagerNumber', location: 'other', person: :primary },
{ field: 'BusinessPhone', location: 'work', person: :primary },
{ field: 'BusinessPhone2', location: 'work', person: :primary },
{ field: 'BusinessFax', location: 'fax', person: :primary },
{ field: 'CompanyMainPhone', location: 'work', person: :primary },
{ field: 'SpouseMobilePhone', location: 'mobile', person: :spouse },
{ field: 'SpouseMobilePhone2', location: 'mobile', person: :spouse },
{ field: 'SpousePagerNumber', location: 'other', person: :spouse },
{ field: 'SpouseBusinessPhone', location: 'work', person: :spouse },
{ field: 'SpouseBusinessPhone2', location: 'work', person: :spouse },
{ field: 'SpouseBusinessFax', location: 'fax', person: :spouse },
{ field: 'SpouseCompanyMainPhone', location: 'work', person: :spouse } # index 18
].freeze
UNSUPPORTED_TNT_TASK_CODES = {
160 => 'Present',
170 => 'MailChimp',
180 => 'WhatsApp'
}.freeze
TNT_TASK_CODES_MAPPED_TO_MPDX_TASK_TYPES = {
1 => 'Appointment',
2 => 'Thank',
3 => 'To Do',
20 => 'Call',
30 => 'Reminder Letter',
40 => 'Support Letter',
50 => 'Letter',
60 => 'Newsletter - Physical',
65 => 'Newsletter - Email',
70 => 'Pre Call Letter',
100 => 'Email',
140 => 'Facebook Message',
150 => 'Text Message',
160 => nil, # "Present", i.e. a gift, not supported by MPDX
170 => 'Email', # "MailChimp"
180 => 'Text Message' # "WhatsApp"
}.freeze
TNT_TASK_RESULT_CODES_MAPPED_TO_MPDX_TASK_RESULTS = {
1 => 'Done',
2 => 'Received',
3 => 'Attempted'
}.freeze
TNT_MPD_PHASE_CODES_MAPPED_TO_MPDX_CONTACT_STATUSES = {
0 => nil, # A "0" value for MPDPhaseID means "n/a" in Tnt
10 => 'Never Contacted',
20 => 'Ask in Future',
30 => 'Contact for Appointment',
40 => 'Appointment Scheduled',
50 => 'Call for Decision',
60 => 'Partner - Financial',
70 => 'Partner - Special',
80 => 'Partner - Pray',
90 => 'Not Interested',
95 => 'Unresponsive',
100 => 'Never Ask',
110 => 'Research Abandoned',
130 => 'Expired Referral'
}.freeze
class << self
def task_type(task_type_id)
TNT_TASK_CODES_MAPPED_TO_MPDX_TASK_TYPES[task_type_id.to_i]
end
def unsupported_task_type(task_type_id)
UNSUPPORTED_TNT_TASK_CODES[task_type_id.to_i]
end
def import_task_type?(task_type_id)
# The TaskTypeID 190 indicates a "Data Change", we don't import data
# change types because it creates too many unhelpful tasks in Mpdx.
task_type_id.to_i != 190
end
def task_status_completed?(task_status_id)
task_status_id.to_i == 2
end
def history_result(history_result_id)
TNT_TASK_RESULT_CODES_MAPPED_TO_MPDX_TASK_RESULTS[history_result_id.to_i]
end
def mpd_phase(phase)
TNT_MPD_PHASE_CODES_MAPPED_TO_MPDX_CONTACT_STATUSES[phase.to_i]
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/contact_serializer.rb
|
<filename>app/serializers/contact_serializer.rb
class ContactSerializer < ApplicationSerializer
include DisplayCase::ExhibitsHelper
include ActionView::Helpers::NumberHelper
attributes :avatar,
:church_name,
: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,
:website
belongs_to :account_list
has_many :addresses
has_many :appeals
has_many :contact_referrals_by_me
has_many :contact_referrals_to_me
has_many :contacts_referred_by_me
has_many :contacts_that_referred_me
has_many :donation_amount_recommendations
has_many :donor_accounts
has_many :last_six_donations
has_many :people
has_many :tasks
has_one :primary_person
has_one :primary_or_first_person
has_one :spouse
def avatar
contact_exhibit.avatar(:large)
end
def square_avatar
contact_exhibit.avatar
end
def pledge_frequency
number_with_precision(object[:pledge_frequency], precision: 14, strip_insignificant_zeros: true)
end
def contact_exhibit
ContactExhibit.new(object, self)
end
delegate :account_list_id, to: :object
def tag_list
object.tags.collect(&:name)
end
end
|
chuckmersereau/api_practice
|
spec/lib/csv_util_spec.rb
|
require 'csv_util'
describe CSVUtil do
describe 'html_table_to_csv' do
it 'should convert html tables to csv' do
expect(CSVUtil.html_table_to_csv(<<-EOS
<table>
<tr><td>A</td><td>B</td></tr>
<tr><td>1</td><td>2</td></tr>
</table>
EOS
)).to eq(<<-EOS
A,B
1,2
EOS
)
expect(CSVUtil.html_table_to_csv(<<-EOS
<table>
<tr><td>A</td><td>B</td></tr>
<tr><td>1,
"</td>
<td>2</td></tr>
</table>
EOS
)).to eq(<<-EOS
A,B
"1,
""",2
EOS
)
expect(CSVUtil.html_table_to_csv(<<-EOS
<table>
<thead>
<tr>
<th>
A
</th>
<th> B </th>
</tr>
</thead>
<tbody>
<tr>
<td>
1
</td>
<td>2</td>
</tr>
</tbody>
</table>
EOS
)).to eq(<<-EOS
A,B
1,2
EOS
)
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130710152055_migrate_tnt_task_ids_to_remote_id_and_source.rb
|
<gh_stars>0
class MigrateTntTaskIdsToRemoteIdAndSource < ActiveRecord::Migration
def up
Activity.where("tnt_id is not null and tnt_id <> ''").update_all("remote_id = tnt_id, source = 'tnt'")
remove_column :activities, :tnt_id
end
def down
raise
end
end
|
chuckmersereau/api_practice
|
db/migrate/20151116162403_change_person_profession_to_text.rb
|
class ChangePersonProfessionToText < ActiveRecord::Migration
def change
change_column :people, :profession, :text
end
end
|
chuckmersereau/api_practice
|
spec/support/shared_model_examples/after_validate_set_source_to_mpdx_examples.rb
|
<reponame>chuckmersereau/api_practice
RSpec.shared_examples 'after_validate_set_source_to_mpdx_examples' do |options = {}|
describe 'after validate set source to MPDX' do
let(:create_record) { create(options[:factory_type], source: 'TntImport') }
let(:build_record) { build(options[:factory_type], source: 'TntImport') }
it 'replaces MPDX with TntImport as source on validation' do
record = create_record
record.updated_at = Time.now.getlocal
record.save!
expect(record.source).to eq 'MPDX'
end
it 'does not set MPDX as source if validation is skipped' do
record = create_record
record.updated_at = Time.now.getlocal
record.save!(validate: false)
expect(record.source).to eq 'TntImport'
end
it 'does not set MPDX as source on create' do
record = build_record
record.updated_at = Time.now.getlocal
record.save!(validate: false)
expect(record.source).to eq 'TntImport'
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180612162302_add_account_listable.rb
|
class AddAccountListable < ActiveRecord::Migration
def change
add_column :deleted_records, :account_listable_id, :uuid
add_column :deleted_records, :account_listable_type, :string
add_index :deleted_records, [:account_listable_id, :account_listable_type], name: :account_listable_index
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/tasks_import_spec.rb
|
<filename>spec/services/tnt_import/tasks_import_spec.rb
require 'rails_helper'
describe TntImport::TasksImport do
let(:user) { create(:user) }
let(:tnt_import) { create(:tnt_import, override: true, user: user) }
let(:tnt3_2_xml) { File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml')) }
let(:xml) { TntImport::XmlReader.new(tnt_import).parsed_xml }
let(:contacts) do
xml.tables['TaskContact'].map do |row|
create(:contact, tnt_id: row['ContactID'])
end
end
let(:contact_ids) { Hash[contacts.map { |c| [c.tnt_id.to_s, c.id] }] }
subject { described_class.new(tnt_import, contact_ids, xml) }
before do
stub_smarty_streets
end
describe '#import' do
context 'no xml task data' do
let(:xml) { double(tables: {}) }
let(:contact_ids) { {} }
it 'returns empty hash' do
expect(subject.import).to eq(nil)
end
end
context 'with data change task types' do
before do
xml.tables['Task'].first['TaskTypeID'] = '190'
end
it 'skips change data task items' do
expect { subject.import }.to_not change { Task.count }
end
end
context 'with WhatsApp task type' do
before do
xml.tables['Task'].first['TaskTypeID'] = '180'
end
it 'includes a comment' do
expect { subject.import }.to change { Task.count }.from(0).to(1)
task = Task.last
expect(task.activity_type).to eq 'Text Message'
expect(Task.last.comments.pluck(:body)).to include 'This task was given the type "WhatsApp" in TntConnect.'
end
end
context 'with Present task type' do
before do
xml.tables['Task'].first['TaskTypeID'] = '160'
end
it 'includes a comment' do
expect { subject.import }.to change { Task.count }.from(0).to(1)
task = Task.last
expect(task.activity_type).to eq nil
expect(Task.last.comments.pluck(:body)).to include 'This task was given the type "Present" in TntConnect.'
end
end
context 'with Categories' do
it 'includes tags for multiple categories' do
xml.tables['Task'].first['Categories'] = 'test, Another Category'
expect { subject.import }.to change { Task.count }.from(0).to(1)
task = Task.last
expect(task.tag_list).to include 'test', 'another category'
end
end
context 'with task assigned to' do
let(:user_row) { xml.tables['User'].first }
before do
tnt_import.file = tnt3_2_xml
# only one task
xml.tables['Task'] = xml.tables['Task'][0..0]
xml.tables['Task'].first['AssignedToUserID'] = user_row['id']
end
it 'includes a tag' do
expect { subject.import }.to change { Task.count }
task = Task.last
expect(task.tag_list).to include user_row['UserName'].downcase
end
end
context 'with LoggedByUserID' do
let(:user_row) { xml.tables['User'].first }
before do
tnt_import.file = tnt3_2_xml
# only one task
xml.tables['Task'] = xml.tables['Task'][0..0]
xml.tables['Task'].first['LoggedByUserID'] = user_row['id']
# mark task completed
xml.tables['Task'].first['Status'] = '2'
end
it 'adds user to comment' do
expect { subject.import }.to change(ActivityComment, :count)
task = Task.last
comments = task.comments.pluck(:body)
expect(comments).to include "Completed By: #{user_row['UserName']}"
end
end
context 'with task campaign' do
before do
tnt_import.file = File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml'))
# only one task
xml.tables['Task'] = xml.tables['Task'][0..0]
xml.tables['Task'].first['CampaignID'] = xml.tables['Campaign'].first['id']
end
it 'includes a tag' do
expect { subject.import }.to change { Task.count }
task = Task.last
expect(task.tag_list).to include xml.tables['Campaign'].first['Description'].downcase
end
end
context 'with multiple task contacts per task' do
let(:tnt_import) do
create(:tnt_import_with_multiple_task_contacts, override: true,
user: user)
end
it 'creates one for each contact' do
expect { subject.import }.to change { Task.count }.by(contacts.size)
end
it 'creates tasks with only a single associated contact' do
subject.import
Task.all.each { |task| expect(task.contacts.size).to eq 1 }
end
it 'creates a unique task record for each contact' do
subject.import
tasks = Contact.all.flat_map(&:tasks)
expect(tasks.size).to eq tasks.uniq.size
end
context 'a Task with the remote ID already exists' do
let!(:preexisting_task) do
create(:task, remote_id: xml.tables['Task'].first['id'],
source: 'tnt', account_list: tnt_import.account_list)
end
it 'creates copies for the other contacts' do
expect { subject.import }.to change { Task.count }.by(contacts.size - 1)
end
it 'creates tasks with only a single associated contact' do
subject.import
Task.all.each { |task| expect(task.contacts.size).to eq 1 }
end
it 'creates a unique task record for each contact' do
subject.import
tasks = Contact.all.flat_map(&:tasks)
expect(tasks.size).to eq tasks.uniq.size
end
end
end
context 'with comments' do
let(:unsupported_tnt_task_id) { TntImport::TntCodes::UNSUPPORTED_TNT_TASK_CODES.keys.first }
let(:task_row) { xml.tables['Task'].first }
let(:note) { 'A non-notable note' }
before do
task_row['Notes'] = note
end
it 'adds a comment for a tnt notes' do
expect do
subject.import
end.to change(ActivityComment, :count).from(0).to(1)
end
it 'does not add a duplicate comment for a note' do
subject.import
task = Task.first
expect do
subject.import
end.to_not change { task.reload.comments.count }
end
it 'adds a comment for an unsupported tnt task type' do
task_row['TaskTypeID'] = unsupported_tnt_task_id
expect do
subject.import
end.to change(ActivityComment, :count).from(0).to(2)
expect(Task.first.comments.where(body: 'This task was given the type "Present" in TntConnect.').count).to eq(1)
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/appeal_contact/filterer.rb
|
<filename>app/services/appeal_contact/filterer.rb
class AppealContact::Filterer < ApplicationFilterer
FILTERS_TO_DISPLAY = %w().freeze
FILTERS_TO_HIDE = %w(
PledgedToAppeal
).freeze
end
|
chuckmersereau/api_practice
|
spec/mailers/import_mailer_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe ImportMailer do
before do
Sidekiq::Testing.inline!
stub_smarty_streets
end
describe '#failed' do
let(:import) { create(:csv_import_with_mappings) }
it 'assigns expected params' do
mail = ImportMailer.failed(import)
expect(mail.to).to eq([import.user.email.email])
expect(mail.subject).to eq('[MPDX] Importing your CSV contacts failed')
end
context 'import source csv' do
before do
import.in_preview = false
allow_any_instance_of(ImportUploader).to receive(:path)
.and_return(Rails.root.join('spec/fixtures/sample_csv_with_some_invalid_rows.csv').to_s)
CsvImport.new(import).import
import.reload
end
it 'attaches a csv file containing the failed rows' do
mail = ImportMailer.failed(import)
expect(mail.attachments.size).to eq(1)
expected_content_type = 'text/comma-separated-values; filename="MPDX Import Failures.csv"'
expect(mail.attachments.first.content_type).to eq(expected_content_type)
body = mail.attachments.first.body.to_s
expect(body).to eq('Error Message,fullname,fname,lname,Spouse-fname,Spouse-lname,greeting,'\
'mailing-greeting,church,street,city,province,zip-code,country,status,'\
'amount,frequency,currency,newsletter,tags,email-address,'\
'Spouse-email-address,phone,Spouse-phone-number,extra-notes,skip,likely-giver,'\
"metro,region,appeals,website,referred_by\n"\
'"Validation failed: Email is invalid, Email is invalid",Bob,Park,Sara,' \
'Kim,Hello!,,,123 Street West,A Small Town,Quebec,L8D 3B9,Canada,' \
'Praying and giving,10,Monthly,,Both,bob,this is not a valid email,' \
'this is also not a valid email,+12345678901,' \
"+10987654321,,Yes,No,metro,region,No,website\n"\
"\"Validation failed: First name can't be blank, Name can't be blank\"," \
',,,,,,,"Apartment, Unit 123",Big City,BC,,CA,Praying,,,,Both,,<EMAIL>,,' \
"123.456.7890,,notes,,Yes,metro,region,Yes,website\n")
end
end
context 'import source tnt' do
let(:import) { create(:tnt_import) }
before do
import.in_preview = false
allow_any_instance_of(TntImport::ContactsImport).to receive(:import_contacts).and_raise(StandardError)
begin
TntImport.new(import).import
rescue StandardError
end
import.reload
end
it 'does not generate any attachments' do
mail = ImportMailer.failed(import)
expect(mail.attachments.size).to eq(0)
end
end
context 'import user has no email addresses' do
let(:import) { create(:tnt_import) }
before { import.user.email_addresses = [] }
it 'does not raise ArgumentError' do
expect { ImportMailer.failed(import).deliver_now! }.not_to raise_error
end
end
end
describe '#success' do
let(:email_address) { build(:email_address, email: '<EMAIL>') }
let(:user) { double(email: email_address, locale: 'en') }
let(:import) { double(user: user, user_friendly_source: 'tnt') }
let(:mail) { ImportMailer.success(import) }
it 'assigns to field correctly' do
expect(mail.to).to eq ['<EMAIL>']
end
context 'import user has no email addresses' do
let(:user) { double(email: nil, locale: 'en') }
it 'does not raise ArgumentError' do
expect { mail.deliver_now! }.not_to raise_error
end
end
end
describe '#success' do
let(:user) { create(:user) }
let(:account) { create(:organization_account, person: user) }
let(:mail) { ImportMailer.credentials_error(account) }
context 'import user has no email addresses' do
before { user.email_addresses = [] }
it 'does not raise ArgumentError' do
expect { mail.deliver_now! }.not_to raise_error
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/locale.rb
|
<filename>app/services/contact/filter/locale.rb
class Contact::Filter::Locale < Contact::Filter::Base
def execute_query(contacts, filters)
locale_filters = parse_list(filters[:locale])
contacts.where('contacts.locale' => locale_filters.map { |l| l == 'null' ? nil : l })
end
def title
_('Language')
end
def parent
_('Contact Details')
end
def type
'multiselect'
end
def custom_options
options = locale_codes.map do |locale_code|
name_in_english = TwitterCldr::Shared::Languages.from_code_for_locale(locale_code, :en)
translated_name = name_in_english.present? ? _(name_in_english) : locale_code
{
name: translated_name,
id: locale_code
}
end
default_custom_options + options
end
private
def default_custom_options
[
{
id: 'null',
name: _('-- Unspecified --')
}
]
end
def locale_codes
(account_lists.flat_map(&:contact_locales) - ['', nil]).uniq.sort
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/constants_controller.rb
|
<reponame>chuckmersereau/api_practice
class Api::V2::ConstantsController < Api::V2Controller
skip_after_action :verify_authorized
def index
load_constants
render_constants
end
private
def load_constants
@constants ||= ::ConstantList.new
end
def render_constants
render json: @constants,
fields: field_params
end
end
|
chuckmersereau/api_practice
|
spec/workers/google_contacts_sync_enqueuer_worker_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe GoogleContactsSyncEnqueuerWorker do
context 'Sync users Google contacts' do
let!(:user) { create(:user_with_account) }
let!(:google_integration) do
create(:google_integration,
calendar_integration: false,
contacts_integration: true,
account_list: user.account_lists.order(:created_at).first)
end
it 'queues the sync with Google contacts for the account list' do
expect(GoogleSyncDataWorker).to receive(:perform_async).with(google_integration.id, 'contacts')
subject.perform
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20141119012857_add_index_to_google_contacts_contact_id.rb
|
<filename>db/migrate/20141119012857_add_index_to_google_contacts_contact_id.rb
class AddIndexToGoogleContactsContactId < ActiveRecord::Migration
def change
add_index :google_contacts, :contact_id
add_index :google_contacts, [:person_id, :contact_id]
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/contact_info_phone.rb
|
<filename>app/services/contact/filter/contact_info_phone.rb
class Contact::Filter::ContactInfoPhone < Contact::Filter::Base
def execute_query(contacts, filters)
filter_home = filters[:contact_info_phone]
contacts_ids_with_home = contact_ids_with_phone(contacts, 'home')
return contacts.where(id: contacts_ids_with_home) if filter_home == 'Yes'
contacts.where.not(id: contacts_ids_with_home)
end
def title
_('Home Phone')
end
def parent
_('Contact Information')
end
def type
'radio'
end
def custom_options
[{ name: _('Yes'), id: 'Yes' }, { name: _('No'), id: 'No' }]
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.