repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
spec/services/user/authenticate_spec.rb
|
require 'rails_helper'
RSpec.describe User::Authenticate, type: :model do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:resource) { User::Authenticate.new(user: user) }
it 'initializes' do
expect(resource).to be_a User::Authenticate
expect(resource.user).to eq user
end
describe '#json_web_token' do
subject { resource.json_web_token }
it 'returns a json_web_token which decodes to the same user id' do
expect(subject).to be_present
expect(User.find_by(id: JsonWebToken.decode(subject)['user_id']).id).to eq user.id
end
end
end
|
chuckmersereau/api_practice
|
spec/mailers/subscriber_cleaned_mailer_spec.rb
|
require 'rails_helper'
describe SubscriberCleanedMailer do
let!(:account_list) { create(:account_list) }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:person) { create(:person) }
let!(:person_email) { create(:email_address) }
let!(:user) { create(:user) }
let!(:user_email) { create(:email_address) }
before do
contact.people << person
user.email_addresses << user_email
person.email_addresses << person_email
account_list.users << user
end
it 'renders the mail' do
mail = SubscriberCleanedMailer.subscriber_cleaned(account_list, person_email)
expect(mail.subject).to eq('MailChimp subscriber email bounced')
expect(mail.to).to eq([user_email.email])
expect(mail.from).to eq(['<EMAIL>'])
expect(mail.body.raw_source).to include("https://mpdx.org/contacts/#{contact.id}?personId=#{person.id}")
end
end
|
chuckmersereau/api_practice
|
spec/workers/mail_chimp/primary_list_sync_worker_spec.rb
|
<filename>spec/workers/mail_chimp/primary_list_sync_worker_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe MailChimp::PrimaryListSyncWorker do
let(:mail_chimp_account) { create(:mail_chimp_account) }
it 'starts the sync with primary list' do
expect_any_instance_of(MailChimp::Syncer).to receive(:two_way_sync_with_primary_list)
MailChimp::PrimaryListSyncWorker.new.perform(mail_chimp_account.id)
end
end
|
chuckmersereau/api_practice
|
spec/workers/google_plus_account_fetcher_worker_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe GooglePlusAccountFetcherWorker do
context '#perform' do
let(:email_address) { create(:email_address) }
let(:mock_google_plus_account_fetcher) { double(:mock_google_plus_account_fetcher) }
it 'fetches the google plus account and marks the email_address as checked_for_google_account' do
expect(EmailAddress::GooglePlusAccountFetcher).to receive(:new).with(email_address).and_return(mock_google_plus_account_fetcher)
expect(mock_google_plus_account_fetcher).to receive(:fetch_google_plus_account).and_return(build(:google_plus_account))
described_class.new.perform(email_address.id)
expect(email_address.reload.checked_for_google_plus_account).to be_truthy
expect(email_address.google_plus_account.reload).to be_present
end
it 'returns nil if the EmailAddress Id doesnt exist' do
expect(described_class.new.perform(10_000)).to be_nil
end
end
end
|
chuckmersereau/api_practice
|
lib/documentation_helper.rb
|
require 'indefinite_article'
class DocumentationHelper
attr_reader :resource
def initialize(resource:, filepath: nil)
@resource = Array[resource].flatten
@filepath = filepath
@data = {}
end
def additional_attributes
@additional_attributes ||= {
'attributes.created_at': {
description: 'The timestamp of when this resource was created',
type: 'ISO8601 timestamp'
},
'attributes.updated_at': {
description: 'The timestamp of when this resource was last updated',
type: 'ISO8601 timestamp'
},
'attributes.updated_in_db_at': {
description: 'This is to be used as a reference for the last time the resource was '\
'updated in the remote database - specifically for when data is updated '\
'while the client is offline.',
type: 'ISO8601 timestamp',
required: true
}
}
end
def additional_update_parameter_attributes
@additional_update_parameter_attributes ||= {
'attributes.overwrite': {
description: "Only used for updating a record where you want to ignore the server's '\
'`updated_in_db_at` value and _force overwrite_ the values for the record. '\
'Must be `true` to work.",
type: 'boolean'
}
}
end
def data_for(type:, action:)
data.dig(type, action) || parse_raw_data_for(type, action)
end
def description_for(action)
raw_data.dig(:actions, action, :description) || title_for(action)
end
def document_parameters_for(action:, context:)
data_for(type: :parameters, action: action).deep_dup.sort.each do |name, attributes|
next if attributes.key?(:ignore)
attributes.delete(:required) if action == :update && !name.to_s.include?('updated_in_db_at')
description = attributes.delete(:description)
context.send(
:parameter,
name,
description,
attributes
)
end
end
def document_response_fields_for(action:, context:)
data_for(type: :response_fields, action: action).deep_dup.sort.each do |name, attributes|
next if attributes.key?(:ignore)
description = attributes.delete(:description)
context.send(
:response_field,
name,
description,
attributes
)
end
end
def document_scope
dup = resource.dup
if dup.count > 1
scope_front = "#{dup.shift}_api"
scope_back = dup.map(&:to_s).join('_')
"#{scope_front}_#{scope_back}".to_sym
else
"entities_#{dup.first}".to_sym
end
end
def filename
@filename ||= "#{resource.last}.yml"
end
def filepath
@filepath ||= build_filepath
end
def insert_documentation_for(action:, context:)
document_parameters_for(action: action, context: context)
document_response_fields_for(action: action, context: context)
end
def raw_data
@raw_data ||= YAML.load_file(filepath).deep_symbolize_keys
end
def title_for(action)
raw_data.dig(:actions, action, :title) || generate_title_for(action)
end
private
attr_reader :data
def additional_attributes_for(type, action)
case type
when :parameters
additional_parameter_attributes_for(action)
when :response_fields
additional_response_field_attributes_for(action)
end
end
def additional_parameter_attributes_for(action)
attributes = additional_attributes.deep_dup
case action
when :create
attributes[:'attributes.updated_in_db_at'].delete(:required)
attributes
when :update
attributes.merge(additional_update_parameter_attributes)
else
{}
end
end
def additional_response_field_attributes_for(action)
attributes = additional_attributes.deep_dup
case action
when :index
{}
when :delete
{}
when :bulk_delete
{}
else
attributes
end
end
def assign_parsed_data_to_data(type, action, parsed_data)
data[type] ||= {}
data[type][action] ||= {}
data[type][action] = parsed_data
parsed_data
end
def build_filepath
resource_scope = resource[0..-2] << filename
dirs = %w(spec support documentation) + resource_scope.map(&:to_s)
Rails.root.join(*dirs).to_s
end
def generate_title_for(action)
plural_name = resource.last.to_s.titleize
singular_name = singular_name_from_plural(plural_name)
case action
when :index
"#{singular_name} [LIST]"
when :show
"#{singular_name} [GET]"
when :create
"#{singular_name} [POST]"
when :update
"#{singular_name} [PUT]"
when :delete
"#{singular_name} [DELETE]"
when :bulk_create
"#{plural_name} [BULK POST]"
when :bulk_update
"#{plural_name} [BULK PUT]"
when :bulk_delete
"#{plural_name} [BULK DELETE]"
end
end
def parse_attributes(attributes)
attributes.each_with_object({}) do |(name, attrs), hash|
new_name = "attributes.#{name}"
hash[new_name] = attrs
end
end
def parse_filters(filters)
return {} if filters.empty?
filters.each_with_object({}) do |(name, attrs), hash|
new_name = "filter.#{name}"
hash[new_name] = attrs
end
end
def parse_object(object)
return {} if object.empty?
{ data: object }
end
def parse_sorts(sorts)
return {} if sorts.empty?
sorts.each_with_object({}) do |(name, attrs), hash|
new_name = "sort.#{name}"
hash[new_name] = attrs
end
end
def parameters_data(action)
data.dig(:parameters, action) || {}
end
def parse_raw_data_for(type, action)
found_data = raw_data.dig(type, action) || {}
additional_attributes = additional_attributes_for(type, action)
parsed_attributes = parse_attributes(found_data.dig(:attributes) || {})
parsed_object = parse_object(found_data.dig(:data) || {})
parsed_sorts = parse_sorts(found_data.dig(:sorts) || {})
parsed_filters = parse_filters(found_data.dig(:filters) || {})
parsed_relationships = parse_relationships(found_data.dig(:relationships) || {})
parsed_data = parsed_object.merge(additional_attributes)
.merge(parsed_attributes)
.merge(parsed_filters)
.merge(parsed_sorts)
.merge(parsed_relationships)
.deep_symbolize_keys
assign_parsed_data_to_data(type, action, parsed_data)
end
def parse_relationships(relationships)
relationships.each_with_object({}) do |(name, attrs), hash|
new_name = "relationships.#{name}.data"
new_attrs = attrs.dig(:data) || {}
if new_attrs.key?(:description)
hash[new_name] = new_attrs
elsif attrs.key?(:ignore)
hash[new_name] = attrs
else
new_name = "#{new_name}.id"
hash[new_name] = new_attrs.dig(:id)
end
end
end
def response_fields_data(action)
(data.dig(:response_fields, action) || {}).tap do |fields_data|
break unless fields_data.present?
additional_response_field_data.each do |key, value|
fields_data[key] = value unless fields_data.key?(key)
end
end
end
def singular_name_from_plural(plural_name)
plural_name.singularize
end
end
|
chuckmersereau/api_practice
|
app/policies/family_relationship_policy.rb
|
class FamilyRelationshipPolicy < ApplicationPolicy
attr_reader :current_contact
attr_reader :current_person
def initialize(context, resource)
@user = context.user
@current_contact = context.contact
@resource = resource
end
private
def resource_owner?
user.account_lists.exists?(id: current_contact.account_list_id) &&
resource.person.contacts.exists?(id: current_contact.id)
end
end
|
chuckmersereau/api_practice
|
spec/factories/google_email_activities.rb
|
<gh_stars>0
FactoryBot.define do
factory :google_email_activity do
association :google_email
association :activity
end
end
|
chuckmersereau/api_practice
|
spec/serializers/reports/monthly_giving_graph_serializer_spec.rb
|
require 'rails_helper'
describe Reports::MonthlyGivingGraphSerializer do
let(:organization) { create(:organization) }
let(:locale) { 'en' }
let(:account_list) do
create(:account_list, monthly_goal: 1234,
salary_organization_id: organization)
end
let(:report) do
Reports::MonthlyGivingGraph.new(account_list: account_list,
locale: locale)
end
subject { Reports::MonthlyGivingGraphSerializer.new(report).as_json }
it { expect(subject[:account_list][:name]).to be account_list.name }
it { expect(subject[:monthly_goal]).to eq 1234 }
it { expect(subject[:display_currency]).to eq organization.default_currency_code }
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/admin/resets_controller.rb
|
<reponame>chuckmersereau/api_practice<filename>app/controllers/api/v2/admin/resets_controller.rb<gh_stars>0
class Api::V2::Admin::ResetsController < Api::V2Controller
skip_after_action :verify_authorized
def create
authorize_reset
persist_reset
end
private
def authorize_reset
raise Pundit::NotAuthorizedError,
'must be admin level user to create resets' unless current_user.admin
end
def persist_reset
build_reset
if save_reset
render_account_list
else
render_with_resource_errors(@reset)
end
end
def build_reset
@reset ||= reset_scope.new(reset_params)
end
def save_reset
return Admin::Reset.delay.reset!(reset_params) if @reset.valid?
false
end
def render_account_list
render json: @reset.account_list,
status: :ok,
include: include_params,
fields: field_params
end
def reset_scope
::Admin::Reset
end
def reset_params
params.require(:reset)
.permit(:resetted_user_email, :reason, :account_list_name).merge(
user_finder: ::Admin::UserFinder,
reset_logger: ::Admin::ResetLog,
admin_resetting: current_user
)
end
end
|
chuckmersereau/api_practice
|
app/services/concerns/reports/date_range_filterable.rb
|
#
# DateRangeFilterable Concern expects to have the +filter_params+ be
# a +Hash+, that includes +month_range+ which is an instance of the
# +Range+ Object. The first argument of the range object is the starting date,
# the second argument of the range is the end date.
#
# e.g.
#
# (Date.yesterday..Date.today)
#
module Concerns::Reports::DateRangeFilterable
extend ActiveSupport::Concern
MONTHS_BACK = 12
def months
(start_date..end_date).select { |date| date.day == 1 }
end
def start_date
determine_start_date&.beginning_of_month || (end_date.beginning_of_month - MONTHS_BACK.months)
end
def end_date
ending_on = filter_params&.fetch(:month_range, nil).try(:last)
return ::Date.today if ending_on.blank?
ending_on.to_date
end
def determine_start_date
starting_on = filter_params&.fetch(:month_range, nil).try(:first)
return nil if starting_on.blank?
return nil if starting_on.to_date > end_date
starting_on.to_date
end
end
|
chuckmersereau/api_practice
|
app/services/reports/salary_currency_donations.rb
|
<gh_stars>0
class Reports::SalaryCurrencyDonations < Reports::DonorCurrencyDonations
def donation_currency(donation)
donation.converted_currency
end
def donation_amount(donation)
donation.converted_amount
end
end
|
chuckmersereau/api_practice
|
app/serializers/contact/analytics_serializer.rb
|
class Contact
class AnalyticsSerializer < ::ServiceSerializer
attributes :first_gift_not_received_count,
:partners_30_days_late_count,
:partners_60_days_late_count,
:partners_90_days_late_count
has_many :birthdays_this_week
has_many :anniversaries_this_week
end
end
|
chuckmersereau/api_practice
|
spec/workers/run_once/send_gdpr_unsubbscribes_worker_spec.rb
|
<filename>spec/workers/run_once/send_gdpr_unsubbscribes_worker_spec.rb
require 'rails_helper'
describe RunOnce::SendGDPRUnsubscribesWorker do
let(:emails) { ['<EMAIL>', '<EMAIL>', '<EMAIL>'] }
subject { described_class.new.perform(emails) }
it 'sends two emails' do
account_list = create(:user_with_full_account).account_lists.first
contact1 = create(:contact_with_person, account_list: account_list, send_newsletter: 'Email')
contact1.primary_person.email = emails[0]
contact2 = create(:contact_with_person, account_list: account_list, send_newsletter: 'Both')
contact2.primary_person.email = emails[1]
expect { subject }.to change { Sidekiq::Extensions::DelayedMailer.jobs.size }.by(2)
job = Sidekiq::Extensions::DelayedMailer.jobs.last
parsed_args = YAML.safe_load(job['args'].first, [Symbol])
email_arg = parsed_args.last.last[:email]
# they might be in any order, what matters is that a job was enqueued with one of the emails
expect(emails[0..1].include?(email_arg)).to be true
end
end
|
chuckmersereau/api_practice
|
lib/tasks/mpdx.rake
|
<filename>lib/tasks/mpdx.rake<gh_stars>0
require 'rspec_doc_combiner'
namespace :mpdx do
task set_special: :environment do
AccountList.find_each do |al|
al.contacts.includes(:donor_accounts).where.not(donor_accounts: { id: nil }).find_each do |contact|
contact.update_attributes(status: 'Partner - Special') if contact.status.blank?
end
end
end
task merge_contacts: :environment do
AccountList.where('id > 125').find_each do |al|
puts al.id
al.async_merge_contacts(1.year.ago)
end
end
task merge_accounts: :environment do
def merge_account_lists
AccountList.order('created_at').each do |al|
other_list = AccountList.where(name: al.name).where("id <> #{al.id} AND name like 'Staff Account (%'").first
next unless other_list # && other_contact.donor_accounts.first == contact.donor_accounts.first
puts other_list.name
al.merge(other_list)
al.async_merge_contacts(1.year.ago)
merge_account_lists
break
end
end
merge_account_lists
end
task merge_donor_accounts: :environment do
def merge_donor_accounts
account_numbers_query =
<<~HEREDOC
select account_number, organization_id from donor_accounts
where account_number <> ''
group by account_number, organization_id
having count(*) > 1
HEREDOC
account_numbers = DonorAccount.connection.select_values(account_numbers_query)
DonorAccount.where(account_number: account_numbers).order('created_at').each do |al|
other_account = DonorAccount.where(account_number: al.account_number, organization_id: al.organization_id)
.where.not(id: al.id)
.first
next unless other_account
puts other_account.account_number
al.merge(other_account)
merge_donor_accounts
break
end
end
merge_donor_accounts
end
task address_cleanup: :environment do
us_address = [nil, '', 'United States', 'United States of America']
Contact.joins(:addresses)
.where.not(addresses: { id: nil })
.where(addresses: { country: us_address })
.find_each(&:merge_addresses)
end
task address_primary_fixes: :environment do
Contact.find_each do |contact|
puts "Primary address fix for contact: #{contact.id}"
contact.addresses_including_deleted.where(deleted: true).update_all(primary_mailing_address: false)
contact.addresses.where(historic: true).update_all(primary_mailing_address: false)
next unless contact.addresses.where(historic: false).count == 1
next unless contact.addresses.where(primary_mailing_address: true).count.zero?
contact.addresses.first.update_column(:primary_mailing_address, true)
end
end
task clear_stalled_downloads: :environment do
Person::OrganizationAccount.clear_stalled_downloads
end
task timezones: :environment do
us_address = [nil, '', 'United States', 'United States of America']
us_contacts = Contact.joins(addresses: :master_address)
.preload(addresses: :master_address)
.where.not(master_addresses: { id: nil })
.where(master_addresses: { country: us_address })
us_contacts.find_each do |c|
addresses = c.addresses
# Find the contact's home address, or grab primary/first address
address = addresses.find { |a| a.location == 'Home' } ||
addresses.find(&:primary_mailing_address?) ||
addresses.first
# Make sure we have a smarty streets response on file
next unless address&.master_address && address.master_address.smarty_response.present?
smarty = address.master_address.smarty_response
meta = smarty.first['metadata']
# Convert the smarty time zone to a rails time zone
zone = ActiveSupport::TimeZone.us_zones.find do |tz|
tz.tzinfo.current_period.offset.utc_offset / 3600 == meta['utc_offset']
end
next unless zone
# The result of the join above was a read-only record
contact = Contact.find(c.id)
contact.update_column(:timezone, zone.name)
end
end
desc 'Generate Docs from Specs'
task generate_docs: :environment do
Rake::Task['docs:generate:ordered'].invoke
RSpecDocCombiner.combine!
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/ids_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Task::Filter::Ids do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:task_one) { create(:task, account_list_id: account_list.id) }
let!(:task_two) { create(:task, account_list_id: account_list.id) }
let!(:task_three) { create(:task, account_list_id: account_list.id) }
describe '#query' do
let(:tasks) { account_list.tasks }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, nil)).to eq(nil)
expect(described_class.query(tasks, { ids: {} }, nil)).to eq(nil)
expect(described_class.query(tasks, { ids: [] }, nil)).to eq(nil)
expect(described_class.query(tasks, { ids: '' }, nil)).to eq(nil)
end
end
context 'filter by id' do
it 'filters multiple ids' do
expect(described_class.query(tasks, { ids: "#{task_one.id}, #{task_two.id}" }, nil).to_a).to include(task_one, task_two)
end
it 'filters a single id' do
expect(described_class.query(tasks, { ids: task_one.id }, nil).to_a).to include(task_one)
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filterer.rb
|
class Contact::Filterer < ApplicationFilterer
FILTERS_TO_DISPLAY = %w(
Status
PledgeReceived
PledgeAmount
PledgeCurrency
PledgeFrequency
PledgeLateBy
Newsletter
Referrer
Likely
ContactType
PrimaryAddress
City
State
Country
AddressHistoric
MetroArea
Region
ContactInfoEmail
ContactInfoPhone
ContactInfoMobile
ContactInfoWorkPhone
ContactInfoAddr
ContactInfoFacebook
Church
RelatedTaskAction
Appeal
Timezone
Locale
Donation
DonationAmount
DonationAmountRange
DonationDate
DonationAmountRecommendation
DesignationAccountId
TasksAllCompleted
TaskDueDate
Notes
).freeze # These filters are displayed in this way on purpose, do not alphabetize them
FILTERS_TO_HIDE = %w(
AddressValid
ExcludeTags
GaveMoreThanPledgedRange
Ids
NameLike
NoAppeals
NotIds
PledgeAmountIncreasedRange
StartedGivingRange
StatusValid
StoppedGivingRange
Tags
UpdatedAt
WildcardSearch
).freeze
end
|
chuckmersereau/api_practice
|
app/preloaders/api/v2/tasks_preloader.rb
|
<reponame>chuckmersereau/api_practice
class Api::V2::TasksPreloader < ApplicationPreloader
ASSOCIATION_PRELOADER_MAPPING = {
account_list: Api::V2::AccountListsPreloader,
contacts: Api::V2::ContactsPreloader,
email_addresses: Api::V2::Contacts::People::EmailAddressesPreloader,
people: Api::V2::Contacts::PeoplePreloader,
phone_numbers: Api::V2::Contacts::People::PhoneNumbersPreloader
}.freeze
FIELD_ASSOCIATION_MAPPING = {
tag_list: :tags,
location: {
contacts: [
:primary_address,
:addresses
]
}
}.freeze
end
|
chuckmersereau/api_practice
|
app/models/google_event.rb
|
<filename>app/models/google_event.rb
class GoogleEvent < ApplicationRecord
belongs_to :activity
belongs_to :google_integration
end
|
chuckmersereau/api_practice
|
dev/migrate/2016_07_14_fix_donations_without_designation_acc.rb
|
require 'logger'
class AddAccountsToDonations
@logger = nil
def add_accounts_to_donations(last_donor_id = 0)
log_action_for_donor(nil, 0)
last_id = 0
donor_accounts(last_donor_id).limit(800).each do |donor_account|
last_id = donor_account.id
if donor_account.contacts&.map(&:account_list_id)&.uniq&.count == 1
account_list = donor_account.contacts.first.account_list
else
log_action_for_donor(donor_account, 1)
next
end
org_accounts = donor_org_accounts(account_list)
unless org_accounts.count == 1
log_action_for_donor(donor_account, 2)
next
end
org_account = org_accounts.first
designation_account = org_account_designation_account(org_account)
unless designation_account
log_action_for_donor(donor_account, 3)
next
end
donor_account.donations.where(designation_account_id: nil).update_all(designation_account_id: designation_account.id)
log_action_for_donor(donor_account, 4)
end
log_action_for_donor(nil, 5)
FixDonationsWorker.perform_async(last_id) if last_id.positive?
end
private
def donations_without_designation_accounts
Donation.where(designation_account_id: nil)
end
def donor_accounts(last_donor_id = 0)
DonorAccount.joins(:donations)
.where(donations: { designation_account_id: nil })
.group('donor_accounts.id')
.order('donor_accounts.id asc')
.where('donor_accounts.id > ?', last_donor_id)
end
def donor_org_accounts(account_list)
account_list.organization_accounts.select do |oa|
account_list.creator_id == oa.person_id
end
end
def org_account_designation_account(org_account)
DesignationAccount.find_by(
organization_id: org_account.organization_id,
active: true,
designation_number: org_account.id.to_s
)
end
def log_action(donation, status)
logger.info("Start script at #{Time.zone.now}") if status.zero?
logger.info("Don. ##{donation.id}: DonorAcc has more than 1 Contact.") if status == 1
logger.info("Don. ##{donation.id}: AccountList has more than 1 OrgAcc.") if status == 2
logger.info("Don. ##{donation.id}: DesignationAcc was not found for OrgAcc.") if status == 3
logger.info("Don. ##{donation.id}: DesignationAcc was added to donation.") if status == 4
logger.info("End of script at #{Time.zone.now}") if status == 5
end
def log_action_for_donor(donor_account, status)
logger.info("Start script at #{Time.zone.now}") if status.zero?
logger.info("DA. ##{donor_account.id}: DonorAcc has more than 1 Contact.") if status == 1
logger.info("DA. ##{donor_account.id}: AccountList has more than 1 OrgAcc.") if status == 2
logger.info("DA. ##{donor_account.id}: DesignationAcc was not found for OrgAcc.") if status == 3
logger.info("DA. ##{donor_account.id}: DesignationAcc was added to donations.") if status == 4
logger.info("End of script at #{Time.zone.now}") if status == 5
end
def logger
@logger ||= Logger.new('log/2016_07_14_fix_donations_without_designation_acc.log', 10, 1_024_000_000)
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/donor_accounts_import_spec.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
require 'rails_helper'
describe TntImport::DonorAccountsImport do
subject { described_class.new(xml, orgs_by_tnt_id) }
let(:user) { create(:user) }
let(:import) do
create(:tnt_import_short_donor_code, override: true, user: user,
account_list: account_list)
end
let(:tnt_import) { TntImport.new(import) }
let(:xml) { tnt_import.xml }
let(:account_list) { create(:account_list) }
let(:designation_profile) { create(:designation_profile, account_list: account_list) }
let(:organization) { designation_profile.organization }
let(:orgs_by_tnt_id) { TntImport::OrgsFinder.orgs_by_tnt_id(xml, organization) }
let(:first_donor_row) { xml.tables['Donor'].first }
let!(:donor_account) do
create(:donor_account, organization: organization, name: donor_account_name,
account_number: first_donor_row['OrgDonorCode'])
end
describe '#add_or_update_donor' do
context 'donor_account has a name' do
let(:donor_account_name) { 'A preset name' }
it 'does not change it' do
expect { subject.import }.not_to change { donor_account.name }
end
end
context 'donor_account has no name' do
let(:donor_account_name) { nil }
it 'is updated from the import' do
expect { subject.import }.to change { donor_account.reload.name }
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/analytics_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Analytics, type: :model do
let(:today) { Date.current }
let(:account_list) { create(:account_list) }
describe '#initialize' do
it 'initializes with a contacts collection' do
contacts = double(:contacts)
analytics = Contact::Analytics.new(contacts)
expect(analytics.contacts).to eq contacts
end
end
describe '#first_gift_not_received_count' do
before do
create(:contact, account_list_id: account_list.id, status: 'Partner - Financial', pledge_received: false)
create(:contact, account_list_id: account_list.id, status: 'Partner - Financial', pledge_received: true)
create(:contact, account_list_id: account_list.id, status: nil, pledge_received: true)
end
let(:contacts) { Contact.where(account_list_id: account_list.id) }
it "gives the count of financial partners where pledge hasn't been received" do
analytics = Contact::Analytics.new(contacts)
expect(analytics.first_gift_not_received_count).to eq(1)
end
end
describe '#partners_30_days_late_count' do
before do
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 10.days.ago)
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 30.days.ago)
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 31.days.ago)
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 61.days.ago)
create(:contact, account_list: account_list, status: nil, pledge_received: true)
end
let(:contacts) { Contact.where(account_list_id: account_list.id) }
it 'gives the count of financial partners who are late between 31 and 60 days' do
analytics = Contact::Analytics.new(contacts)
expect(analytics.partners_30_days_late_count).to eq(1)
end
end
describe '#partners_60_days_late_count' do
before do
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 10.days.ago)
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 30.days.ago)
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 61.days.ago)
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 90.days.ago)
create(:contact, account_list: account_list, status: nil, pledge_received: true)
end
let(:contacts) { Contact.where(account_list_id: account_list.id) }
it 'gives the count of financial partners who are late greater than 61 days' do
analytics = Contact::Analytics.new(contacts)
expect(analytics.partners_60_days_late_count).to eq(2)
end
end
describe '#partners_90_days_late_count' do
before do
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 10.days.ago)
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 60.days.ago)
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 91.days.ago)
create(:contact, account_list: account_list, status: 'Partner - Financial')
.update_columns(late_at: 100.days.ago)
create(:contact, account_list: account_list, status: nil, pledge_received: true)
end
let(:contacts) { Contact.where(account_list_id: account_list.id) }
it 'gives the count of financial partners who are late greater than 61 days' do
analytics = Contact::Analytics.new(contacts)
expect(analytics.partners_90_days_late_count).to eq(2)
end
end
describe '#birthdays_this_week' do
let(:person_with_birthday_this_week) do
create(:person, birthday_month: today.month,
birthday_day: today.day,
birthday_year: (today + 10.years).year)
end
let(:person_with_birthday_next_week) do
date = today + 1.week
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date + 10.years).year)
end
let(:person_with_birthday_last_week) do
date = today - 1.week
create(:person, birthday_month: date.month,
birthday_day: date.day,
birthday_year: (date - 10.years).year)
end
let(:deceased_person_with_birthday_this_week) do
create(:person, birthday_month: today.month,
birthday_day: today.day,
birthday_year: (today + 10.years).year,
deceased: true)
end
let(:person_with_birthday_this_week_belonging_to_inactive_contact) do
create(:person, birthday_month: today.month,
birthday_day: today.day,
birthday_year: (today + 10.years).year)
end
let(:active_contact) { create(:contact, status: 'Partner - Financial') }
let(:inactive_contact) { create(:contact, status: 'Not Interested') }
let(:contacts) { Contact.where(id: [active_contact.id, inactive_contact.id]) }
before do
active_contact.people << person_with_birthday_this_week
active_contact.people << person_with_birthday_next_week
active_contact.people << person_with_birthday_last_week
active_contact.people << deceased_person_with_birthday_this_week
inactive_contact.people << person_with_birthday_this_week_belonging_to_inactive_contact
end
it "pulls the people and associated contacts who's birthdays are this week" do
analytics = Contact::Analytics.new(contacts)
found_person_ids = analytics.birthdays_this_week.map(&:person).map(&:id)
found_contact_ids = analytics.birthdays_this_week.map(&:parent_contact).map(&:id)
expect(found_person_ids.count).to eq(1)
expect(found_person_ids).to include person_with_birthday_this_week.id
expect(found_person_ids).not_to include person_with_birthday_last_week.id
expect(found_person_ids).not_to include person_with_birthday_next_week.id
expect(found_person_ids).not_to include deceased_person_with_birthday_this_week.id
expect(found_person_ids).not_to include person_with_birthday_this_week_belonging_to_inactive_contact.id
expect(found_contact_ids).to include person_with_birthday_this_week.contacts.ids.first
end
end
describe '#anniversaries_this_week' do
let(:person_with_anniversary_this_week) do
create(:person, anniversary_month: today.month,
anniversary_day: today.day,
anniversary_year: (today + 10.years).year)
end
let(:wife_with_anniversary_this_week) do
create(:person, anniversary_month: today.month,
anniversary_day: today.day,
anniversary_year: (today + 10.years).year)
end
let(:deceased_person_with_anniversary_this_week) do
create(:person, anniversary_month: today.month,
anniversary_day: today.day,
anniversary_year: (today + 10.years).year,
deceased: true)
end
let(:person_with_anniversary_next_week) do
date = today + 1.week
create(:person, anniversary_month: date.month,
anniversary_day: date.day,
anniversary_year: (date + 10.years).year)
end
let(:person_with_anniversary_last_week) do
date = today - 1.week
create(:person, anniversary_month: date.month,
anniversary_day: date.day,
anniversary_year: (date - 10.years).year)
end
let(:active_contact_with_person_with_anniversary_this_week) do
create(:contact, account_list_id: account_list.id, status: 'Partner - Financial')
end
let(:active_contact_with_deceased_person_with_anniversary_this_week) do
create(:contact, account_list_id: account_list.id, status: 'Partner - Financial')
end
let(:active_contact_with_person_with_anniversary_last_week) do
create(:contact, account_list_id: account_list.id, status: 'Partner - Financial')
end
let(:active_contact_with_person_with_anniversary_next_week) do
create(:contact, account_list_id: account_list.id, status: 'Partner - Financial')
end
let(:inactive_contact_with_person_with_anniversary_this_week) do
create(:contact, account_list_id: account_list.id, status: 'Not Interested')
end
let(:contacts) do
ids = [
active_contact_with_person_with_anniversary_this_week,
active_contact_with_deceased_person_with_anniversary_this_week,
active_contact_with_person_with_anniversary_next_week,
active_contact_with_person_with_anniversary_last_week,
inactive_contact_with_person_with_anniversary_this_week
].map(&:id)
Contact.where(id: ids)
end
before do
active_contact_with_person_with_anniversary_this_week.people << person_with_anniversary_this_week
active_contact_with_person_with_anniversary_this_week.people << wife_with_anniversary_this_week
active_contact_with_deceased_person_with_anniversary_this_week.people << deceased_person_with_anniversary_this_week
active_contact_with_person_with_anniversary_next_week.people << person_with_anniversary_next_week
active_contact_with_person_with_anniversary_last_week.people << person_with_anniversary_last_week
inactive_contact_with_person_with_anniversary_this_week.people << person_with_anniversary_this_week
end
it 'pulls the contacts with people having anniversaries this week' do
analytics = Contact::Analytics.new(contacts)
found_ids = analytics.anniversaries_this_week.ids
expect(found_ids.count).to eq(1)
expect(found_ids).to include active_contact_with_person_with_anniversary_this_week.id
expect(found_ids).not_to include active_contact_with_deceased_person_with_anniversary_this_week.id
expect(found_ids).not_to include active_contact_with_person_with_anniversary_last_week.id
expect(found_ids).not_to include active_contact_with_person_with_anniversary_next_week.id
expect(found_ids).not_to include inactive_contact_with_person_with_anniversary_this_week.id
end
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/settings_import_spec.rb
|
require 'rails_helper'
describe TntImport::SettingsImport do
let(:xml) do
TntImport::XmlReader.new(tnt_import).parsed_xml
end
let(:tnt_import) { create(:tnt_import, override: true) }
let(:account_list) do
account_list = tnt_import.account_list
account_list.settings[:monthly_goal] = nil
account_list.save
account_list
end
let(:import) do
TntImport::SettingsImport.new(tnt_import.account_list, xml, true)
end
context '#import_settings' do
it 'updates monthly goal' do
expect do
import.import
end.to change(account_list, :monthly_goal).from(nil).to(6300)
end
end
context '#import_mail_chimp' do
it 'creates a mailchimp account' do
expect do
import.import_mail_chimp('asdf', 'asasdfdf-us4', false)
end.to change(MailChimpAccount, :count).by(1)
end
it 'updates a mailchimp account' do
account_list.create_mail_chimp_account(api_key: '5', primary_list_id: '6')
expect do
import.import_mail_chimp('1', '2', true)
end.to change(account_list.mail_chimp_account, :api_key).from('5').to('2')
end
end
end
|
chuckmersereau/api_practice
|
app/models/currency_alias.rb
|
<filename>app/models/currency_alias.rb
# This class makes a link between two currency codes
# It has three required values:
# - alias_code: This is the currency code that is not currently in the system
# - rate_api_code: This is the currency code that our exchange rate API gives us (should be in the system already)
# - ratio: This is a transform value that will adjust the exchange rate of the aliased currency rate
#
# Once a record of this type is saved to the DB, next time CurrencyRatesFetcherWorker runs it will
# create duplicates of all of the rates with code: rate_api_code for the new alias_code.
class CurrencyAlias < ApplicationRecord
end
|
chuckmersereau/api_practice
|
spec/factories/google_integrations.rb
|
FactoryBot.define do
factory :google_integration do
calendar_integration true
calendar_id 'cal1'
association :account_list
association :google_account
email_blacklist ['<EMAIL>']
end
end
|
chuckmersereau/api_practice
|
app/policies/donor_account_policy.rb
|
class DonorAccountPolicy < AccountListChildrenPolicy
private
def resource_owner?
user.can_manage_sharing?(current_account_list)
end
end
|
chuckmersereau/api_practice
|
spec/factories/donation_amount_recommendation_remotes.rb
|
FactoryBot.define do
factory :donation_amount_recommendation_remote, class: 'DonationAmountRecommendation::Remote' do
organization
donor_number 'MyString'
designation_number 'MyString'
previous_amount 9.99
amount 9.99
started_at { Time.zone.now - 1.year }
gift_min 0
gift_max 100
income_min 50_000
income_max 75_000
suggested_pledge_amount 25
ask_at { Time.zone.now + 5.days }
zip_code '32817'
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160413150136_add_country_to_organization.rb
|
class AddCountryToOrganization < ActiveRecord::Migration
def up
add_column :organizations, :country, :string
Organization.all.each do |org|
country = guess_country(org.name)
org.update(country: country) if country
end
end
def down
remove_column :organizations, :country
end
def guess_country(org_name)
org_prefixes = ['Campus Crusade for Christ - ', 'Cru - ', 'Power To Change - ',
'Gospel For Asia', 'Agape']
org_prefixes.each do |prefix|
org_name = org_name.gsub(prefix, '')
end
org_name = org_name.split(' - ').last if org_name.include? ' - '
org_name = org_name.strip
return 'Canada' if org_name == 'CAN'
match = ::CountrySelect::COUNTRIES_FOR_SELECT.find do |country|
country[:name] == org_name || country[:alternatives].split(' ').include?(org_name)
end
return match[:name] if match
nil
end
end
|
chuckmersereau/api_practice
|
spec/services/person/filter/updated_at_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Person::Filter::UpdatedAt do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:person_one) { create(:person, contacts: [contact_one], updated_at: 2.months.ago) }
let!(:person_two) { create(:person, contacts: [contact_one], updated_at: 5.days.ago) }
let!(:person_three) { create(:person, contacts: [contact_two], updated_at: 2.days.ago) }
let!(:person_four) { create(:person, contacts: [contact_two], updated_at: Time.now.getlocal) }
describe '#query' do
let(:scope) { Person.all }
context 'filter by updated_at range' do
it 'returns only people that haveupdated_at value within the range' do
results = described_class.query(scope, { updated_at: Range.new(1.month.ago, 1.day.ago) }, nil).to_a
expect(results).to match_array [person_two, person_three]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/people/relationships_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts > People > Relationships' do
include_context :json_headers
documentation_scope = :people_api_relationships
let(:resource_type) { :family_relationships }
let!(:user) { create(:user_with_full_account) }
let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) }
let(:contact_id) { contact.id }
let(:person) { create(:person, contacts: [contact]) }
let(:person_id) { person.id }
let!(:family_relationship) { create(:family_relationship, person: person) }
let(:id) { family_relationship.id }
let(:new_family_relationship) do
attributes_for(:family_relationship)
.reject { |key| key.to_s.end_with?('_id') }
.merge(overwrite: true)
end
let(:relationships) do
{
person: {
data: {
type: 'people',
id: person.id
}
},
related_person: {
data: {
type: 'people',
id: create(:person).id
}
}
}
end
let(:form_data) { build_data(new_family_relationship, relationships: relationships) }
let(:resource_associations) do
%w(
related_person
)
end
let(:resource_attributes) do
%w(
created_at
relationship
updated_at
updated_in_db_at
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/contacts/:contact_id/people/:person_id/relationships' do
example 'Relationship [LIST]', document: documentation_scope do
explanation 'List of Relationships associated to the Person'
do_request
expect(response_status).to eq 200
check_collection_resource(1, %w(relationships))
end
end
get '/api/v2/contacts/:contact_id/people/:person_id/relationships/:id' do
with_options scope: [:data, :attributes] do
response_field 'created_at', 'Created At', type: 'String'
response_field 'updated_at', 'Updated At', type: 'String'
response_field 'updated_in_db_at', 'Updated In Db At', type: 'String'
end
example 'Relationship [GET]', document: documentation_scope do
explanation 'The Person\'s Relationship with the given ID'
do_request
expect(response_status).to eq 200
check_resource(%w(relationships))
end
end
post '/api/v2/contacts/:contact_id/people/:person_id/relationships' do
with_options required: true, scope: [:data, :attributes] do
parameter 'relationship', 'Relationship'
end
example 'Relationship [CREATE]', document: documentation_scope do
explanation 'Create a Relationship associated with the Person'
do_request data: form_data
expect(response_status).to eq 201
expect(resource_object['relationship']).to eq new_family_relationship[:relationship]
end
end
put '/api/v2/contacts/:contact_id/people/:person_id/relationships/:id' do
with_options required: true, scope: [:data, :attributes] do
parameter 'relationship', 'Relationship'
end
example 'Relationship [UPDATE]', document: documentation_scope do
explanation 'Update the Person\'s Relationship with the given ID'
do_request data: form_data
expect(response_status).to eq 200
expect(resource_object['relationship']).to eq new_family_relationship[:relationship]
end
end
delete '/api/v2/contacts/:contact_id/people/:person_id/relationships/:id' do
example 'Relationship [DELETE]', document: documentation_scope do
explanation 'Delete the Person\'s Relationship with the given ID'
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/people/email_addresses_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts > People > Email Addresses' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:people, :email_addresses])
# This is required!
# This is the resource's JSONAPI.org `type` attribute to be validated against.
let(:resource_type) { 'email_addresses' }
# 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(:contact) { create(:contact, account_list: account_list) }
let(:contact_id) { contact.id }
let(:person) { create(:person, contacts: [contact]) }
let(:person_id) { person.id }
let!(:email_address) { create(:email_address, person: person) }
let(:id) { email_address.id }
let(:form_data) do
build_data(
attributes
.reject { |key| key.to_s.end_with?('_id') }
.merge(updated_in_db_at: email_address.updated_at)
)
end
let(:expected_attribute_keys) do
# list your expected resource keys vertically here (alphabetical please!)
%w(
created_at
email
historic
location
primary
source
updated_at
updated_in_db_at
valid_values
)
end
context 'authorized user' do
before { api_login(user) }
# index
get '/api/v2/contacts/:contact_id/people/:person_id/email_addresses' do
doc_helper.insert_documentation_for(action: :index, context: self)
before { email_address }
example doc_helper.title_for(:index), document: doc_helper.document_scope do
explanation doc_helper.description_for(:index)
do_request
check_collection_resource(1)
expect(resource_object.keys).to match_array expected_attribute_keys
expect(resource_object['email']).to eq email_address.email
expect(response_status).to eq 200
end
end
# show
get '/api/v2/contacts/:contact_id/people/:person_id/email_addresses/:id' do
doc_helper.insert_documentation_for(action: :show, context: self)
example doc_helper.title_for(:show), document: doc_helper.document_scope do
explanation doc_helper.description_for(:show)
do_request
check_resource
expect(resource_object.keys.sort).to eq expected_attribute_keys
expect(resource_object['email']).to eq email_address.email
expect(response_status).to eq 200
end
end
# create
post '/api/v2/contacts/:contact_id/people/:person_id/email_addresses' do
doc_helper.insert_documentation_for(action: :create, context: self)
let(:attributes) { attributes_for(:email_address).merge(person_id: person.id) }
example doc_helper.title_for(:create), document: doc_helper.document_scope do
explanation doc_helper.description_for(:create)
do_request data: form_data
check_resource
expect(resource_object.keys).to match_array expected_attribute_keys
expect(resource_object['email']).to eq attributes[:email]
expect(response_status).to eq 201
end
end
# update
put '/api/v2/contacts/:contact_id/people/:person_id/email_addresses/:id' do
doc_helper.insert_documentation_for(action: :update, context: self)
let(:attributes) { email_address.attributes.merge(person_id: person.id) }
before { attributes.merge!(email: '<EMAIL>') }
example doc_helper.title_for(:update), document: doc_helper.document_scope do
explanation doc_helper.description_for(:update)
do_request data: form_data
check_resource
expect(resource_object.keys).to match_array expected_attribute_keys
expect(resource_object['email']).to eq '<EMAIL>'
expect(response_status).to eq 200
end
end
# destroy
delete '/api/v2/contacts/:contact_id/people/:person_id/email_addresses/:id' do
doc_helper.insert_documentation_for(action: :delete, context: self)
example doc_helper.title_for(:delete), document: doc_helper.document_scope do
explanation doc_helper.description_for(:delete)
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/notification_preferences/bulk_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/acceptance/api/v2/account_lists/notification_preferences/bulk_spec.rb<gh_stars>0
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Account Lists > Notification Preferences > Bulk' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:account_lists, :notification_preferences, :bulk])
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:resource_type) { 'notification_preferences' }
let!(:user) { create(:user_with_account) }
let(:bulk_create_form_data) do
[{
data: {
type: resource_type,
id: SecureRandom.uuid,
attributes: {
email: true,
task: true
},
relationships: {
notification_type: {
data: {
type: 'notification_types',
id: create(:notification_type).id
}
}
}
}
}]
end
context 'authorized user' do
before { api_login(user) }
post '/api/v2/account_lists/:account_list_id/notification_preferences/bulk' do
doc_helper.insert_documentation_for(action: :bulk_create, context: self)
example doc_helper.title_for(:bulk_create), document: doc_helper.document_scope do
explanation doc_helper.description_for(:bulk_create)
do_request data: bulk_create_form_data
expect(response_status).to eq(200)
expect(json_response.first['data']['attributes']['email']).to eq true
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/notification_preferences/bulk_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::AccountLists::NotificationPreferences::BulkController, type: :controller do
include_context 'common_variables'
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:account_list_id) { account_list.id }
let!(:id) { resource.id }
let!(:resource) { create(:notification_preference, account_list: account_list) }
let!(:second_resource) { create(:notification_preference, account_list: account_list) }
let!(:third_resource) { create(:notification_preference, account_list: account_list) }
let!(:user) { create(:user_with_account) }
let!(:resource_type) { :notification_preferences }
let(:first_id) { SecureRandom.uuid }
let(:second_id) { SecureRandom.uuid }
let(:third_id) { SecureRandom.uuid }
let(:full_params) { bulk_create_attributes.merge(account_list_id: account_list_id) }
let(:response_body) { JSON.parse(response.body) }
let(:response_errors) { response_body['errors'] }
let(:unauthorized_resource) { create(:notification_preference) }
let!(:correct_attributes) do
attributes_for(:notification_preference, email: true, task: true)
end
def relationships
{
notification_type: {
data: {
type: 'notification_types',
id: create(:notification_type).id
}
}
}
end
let(:bulk_create_attributes) do
{
data: [
{
data: {
type: resource_type,
id: first_id,
attributes: correct_attributes
}.merge(relationships: relationships)
},
{
data: {
type: resource_type,
id: second_id,
attributes: correct_attributes,
relationships: {}
}
},
{
data: {
type: resource_type,
id: third_id,
attributes: correct_attributes
}.merge(relationships: relationships)
}
]
}
end
before do
api_login(user)
end
it 'returns a 200 and the list of created resources' do
post :create, full_params
expect(response.status).to eq(200), invalid_status_detail
expect(response_body.length).to eq(3)
end
context "one of the data objects doesn't contain an id" do
before { full_params[:data].append(data: { attributes: {} }) }
it 'returns a 400' do
post :create, full_params
expect(response.status).to eq(400), invalid_status_detail
end
end
it 'creates the resources which belong to users and do not have errors' do
expect do
post :create, full_params
end.to change { resource.class.count }.by(4)
expect(response_body.detect { |hash| hash.dig('data', 'id') == first_id }['errors']).to be_blank
expect(response_body.detect { |hash| hash.dig('id') == second_id }['errors']).to be_present
expect(response_body.detect { |hash| hash.dig('data', 'id') == third_id }['errors']).to be_blank
end
it 'returns error objects for resources that were not created, but belonged to user' do
expect do
put :create, full_params
end.to_not change { second_resource.reload.send(reference_key) }
response_with_errors = response_body.detect { |hash| hash.dig('id') == second_id }
expect(response_with_errors['errors']).to be_present
expect(response_with_errors['errors'].detect do |hash|
hash.dig('source', 'pointer') == '/data/attributes/notification_type'
end).to be_present
end
context 'resources forbidden' do
let!(:bulk_create_attributes_with_forbidden_resource) do
{
data: [
{
data: {
type: resource_type,
id: first_id,
attributes: correct_attributes
}.merge(relationships: relationships)
},
{
data: {
type: resource_type,
id: second_id,
attributes: correct_attributes,
relationships: {}
}
},
{
data: {
type: resource_type,
id: third_id,
attributes: correct_attributes
}.merge(relationships: relationships)
}
]
}
end
let(:full_params) do
bulk_create_attributes_with_forbidden_resource.merge(account_list_id: account_list_id)
end
it 'does not create resources for users that are not signed in' do
api_logout
expect do
post :create, account_list_id: account_list_id
end.not_to change { resource.class.count }
expect(response.status).to eq(401), invalid_status_detail
end
it "returns a 403 when users tries to associate resource to an account list that doesn't belong to them" do
expect do
post :create, full_params.merge(account_list_id: create(:account_list).id)
end.not_to change { resource.class.count }
expect(response.status).to eq(403), invalid_status_detail
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/error_controller.rb
|
class Api::ErrorController < ApiController
rescue_from ActionController::RoutingError, with: :render_404_from_exception
def not_found
raise ActionController::RoutingError.new('Route not found', [])
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/reports/appointment_results_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Reports > Appointments Report' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:reports, :appointment_results])
let(:resource_type) { 'reports_appointment_results_periods' }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:resource_attributes) do
%w(
created_at
start_date
end_date
individual_appointments
weekly_individual_appointment_goal
group_appointments
new_monthly_partners
new_special_pledges
monthly_increase
pledge_increase
updated_at
updated_in_db_at
)
end
context 'authorized user' do
before { api_login(user) }
# index
get '/api/v2/reports/appointment_results/' do
doc_helper.insert_documentation_for(action: :index, context: self)
example doc_helper.title_for(:index), document: doc_helper.document_scope do
explanation doc_helper.description_for(:index)
do_request
check_collection_resource(4, %w(relationships))
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/appeal_contact_serializer.rb
|
<gh_stars>0
class AppealContactSerializer < ApplicationSerializer
belongs_to :appeal
belongs_to :contact
end
|
chuckmersereau/api_practice
|
spec/lib/batch_request_handler/instrument_spec.rb
|
<filename>spec/lib/batch_request_handler/instrument_spec.rb<gh_stars>0
require 'spec_helper'
describe BatchRequestHandler::Instrument do
let(:params) { {} }
subject { described_class.new(params) }
describe '.enabled_for?' do
it 'matches anything' do
batch_request = double('batch_request')
expect(described_class.enabled_for?(batch_request)).to be(true)
end
end
describe '#initialize' do
it 'accepts one argument' do
expect(described_class).to respond_to(:new).with(1).argument
end
end
describe '#around_perform_requests' do
let(:requests) { double('requests') }
it 'accepts one argument' do
expect(subject).to respond_to(:around_perform_requests).with(1).argument
end
it 'yields the provided argument' do
expect { |b| subject.around_perform_requests(requests, &b) }
.to yield_with_args(requests)
end
it 'returns the result of yield' do
responses = double('responses')
block = -> (_requests) { responses }
expect(subject.around_perform_requests(requests, &block)).to be(responses)
end
end
describe '#around_perform_request' do
let(:env) { double('env') }
it 'accepts one argument' do
expect(subject).to respond_to(:around_perform_request).with(1).argument
end
it 'yields the provided argument' do
expect { |b| subject.around_perform_request(env, &b) }
.to yield_with_args(env)
end
it 'returns the result of yield' do
response = double('response')
block = -> (_env) { response }
expect(subject.around_perform_request(env, &block)).to be(response)
end
end
describe '#around_build_response' do
let(:json_responses) { double('json_responses') }
it 'accepts one argument' do
expect(subject).to respond_to(:around_build_response).with(1).argument
end
it 'yields the provided argument' do
expect { |b| subject.around_perform_request(json_responses, &b) }
.to yield_with_args(json_responses)
end
it 'returns the result of yield' do
batch_response = double('batch_response')
block = -> (_env) { batch_response }
expect(subject.around_perform_request(json_responses, &block))
.to be(batch_response)
end
end
end
|
chuckmersereau/api_practice
|
app/models/company_partnership.rb
|
<filename>app/models/company_partnership.rb
class CompanyPartnership < ApplicationRecord
belongs_to :account_list
belongs_to :company
end
|
chuckmersereau/api_practice
|
db/migrate/20180123202818_move_pref_blog_foreign_keys.rb
|
class MovePrefBlogForeignKeys < ActiveRecord::Migration
def up
after = 1.week.ago if Rails.env.production?
TmpUser.move_default_account_list_ids(after)
TmpAccountList.move_salary_organization_ids(after)
rename_column :people, :default_account_list_id_holder, :default_account_list
rename_column :account_lists, :salary_organization_id_holder, :salary_organization_id
end
def down
rename_column :people, :default_account_list, :default_account_list_id_holder
rename_column :account_lists, :salary_organization_id, :salary_organization_id_holder
end
end
class TmpUser < ActiveRecord::Base
self.table_name = 'people'
self.primary_key = 'id'
store :preferences
def self.move_default_account_list_ids(after)
scope = where("preferences like '%default_account_list: %'").where(default_account_list_id_holder: nil)
scope = scope.where('updated_at > ?', after) if after
p @i = scope.count
scope.find_each do |user|
@i -= 1
p @i if @i % 500 == 0
id = user.preferences[:default_account_list]
user.update_column(:default_account_list_id_holder, id) if id
end
end
end
class TmpAccountList < ActiveRecord::Base
self.table_name = 'account_lists'
self.primary_key = 'id'
store :settings
def self.move_salary_organization_ids(after)
scope = where("settings like '%salary_organization_id: %'")
scope = scope.where('updated_at > ?', after) if after
p @i = scope.count
scope.find_each do |al|
@i -= 1
p @i if @i % 500 == 0
id = al.settings[:salary_organization_id]
al.update_column(:salary_organization_id_holder, id) if id
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/concerns/resource_type_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/controllers/concerns/resource_type_spec.rb
require 'rails_helper'
RSpec.describe ResourceType, type: :concern do
context 'when a custom resource_type is set' do
it 'allows the setting of a custom resource_type for a controller' do
controller = Mock::ControllerForCustomResourceType.new
expect(controller.resource_type).to eq :mock_resource_type
end
end
context "when a custom resource_type isn't set" do
it 'pulls the resource type from the controller name' do
controller = Mock::UsersController.new
expect(controller.resource_type).to eq :users
end
end
describe '.custom_resource_type' do
context 'when a resource_type is set' do
it 'returns the resource_type as a :sym' do
expect(Mock::ControllerForCustomResourceType.custom_resource_type)
.to eq(:mock_resource_type)
end
end
context "when a resource_type isn't set" do
it 'is nil' do
expect(Mock::UsersController.custom_resource_type).to be_nil
end
end
end
end
module Mock
class ControllerForCustomResourceType
include ResourceType
resource_type :mock_resource_type
end
class UsersController
include ResourceType
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/reports/year_donations_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::Reports::YearDonationsController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:resource) do
Reports::YearDonations.new(account_list: account_list)
end
let(:parent_param) do
{
filter: {
account_list_id: account_list.id
}
}
end
let(:given_reference_key) { 'donor_infos' }
include_examples 'show_examples', except: [:sparse_fieldsets]
end
|
chuckmersereau/api_practice
|
app/models/account_list_entry.rb
|
class AccountListEntry < ApplicationRecord
audited
belongs_to :account_list
belongs_to :designation_account
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/name_like.rb
|
class Contact::Filter::NameLike < Contact::Filter::Base
def execute_query(contacts, filters)
contacts.where('name ilike ?', "#{filters[:name_like]}%")
end
end
|
chuckmersereau/api_practice
|
spec/services/contact_filter_spec.rb
|
require 'rails_helper'
describe ContactFilter do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
describe 'filters' do
it 'filters by comma separated ids' do
c1 = create(:contact)
c2 = create(:contact)
create(:contact)
filtered = ContactFilter.new(ids: "#{c1.id},#{c2.id}").filter(Contact, account_list)
expect(filtered.count).to eq(2)
expect(filtered).to include(c1)
expect(filtered).to include(c2)
end
it 'allows all if ids blank' do
create(:contact)
expect(ContactFilter.new(ids: '').filter(Contact, account_list).count).to eq(1)
end
it 'can handle a list of blank elements ",,"' do
expect { ContactFilter.new(ids: ',,').filter(Contact, account_list).count }.to_not raise_error
end
it 'filters contacts with newsletter = Email and state' do
c = create(:contact, send_newsletter: 'Email')
a = create(:address, addressable: c)
p = create(:person)
c.people << p
create(:email_address, person: p)
cf = ContactFilter.new(newsletter: 'email', state: a.state)
expect(
cf.filter(Contact, user.account_lists.order(:created_at).first)
.includes([{ primary_person: [:facebook_account, :primary_picture] },
:tags, :primary_address, { people: :primary_phone_number }])
).to eq([c])
end
it 'filters contacts with statuses null and another' do
nil_status = create(:contact, status: nil)
has_status = create(:contact, status: 'Never Contacted')
cf = ContactFilter.new(status: ['null', 'Never Contacted'])
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include nil_status
expect(filtered_contacts).to include has_status
end
it 'filters by person name on wildcard search with and without comma' do
c = create(:contact, name: '<NAME>')
p = create(:person, first_name: 'John', last_name: 'Doe')
c.people << p
expect(ContactFilter.new(wildcard_search: '<NAME>').filter(Contact, account_list)).to include c
expect(ContactFilter.new(wildcard_search: ' Doe, John ').filter(Contact, account_list)).to include c
end
it 'does not cause an error if wildcard search less than two words with or without comma' do
expect { ContactFilter.new(wildcard_search: 'john').filter(Contact, account_list) }.to_not raise_error
expect { ContactFilter.new(wildcard_search: '').filter(Contact, account_list) }.to_not raise_error
expect { ContactFilter.new(wildcard_search: ',').filter(Contact, account_list) }.to_not raise_error
expect { ContactFilter.new(wildcard_search: 'doe,').filter(Contact, account_list) }.to_not raise_error
end
it 'filters by commitment received' do
received = create(:contact, pledge_received: true)
not_received = create(:contact, pledge_received: false)
cf = ContactFilter.new(pledge_received: 'true')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to eq [received]
cf = ContactFilter.new(pledge_received: 'false')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to eq [not_received]
cf = ContactFilter.new(pledge_received: '')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts.length).to be 2
end
context 'pledge frequency' do
it "doesn't error when passed a 'null'" do
received = create(:contact, pledge_received: true)
cf = ContactFilter.new(pledge_frequencies: 'null', received: true)
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to eq [received]
end
end
context '#contact_info_email' do
let!(:has_email) do
c = create(:contact)
c.people << create(:person)
c.people << create(:person)
c.primary_or_first_person.email_addresses << create(:email_address)
c
end
let!(:no_email) do
c = create(:contact)
c.people << create(:person)
c.primary_or_first_person.email_addresses << create(:email_address, historic: true)
c
end
it 'filters when looking for emails' do
cf = ContactFilter.new(contact_info_email: 'Yes')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to eq [has_email]
end
it 'filters when looking for no emails' do
cf = ContactFilter.new(contact_info_email: 'No')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to eq [no_email]
end
it 'works when combined with newsletter and ordered by name' do
cf = ContactFilter.new(contact_info_email: 'No', newsletter: 'address')
expect(cf.filter(Contact.order('name'), account_list).to_a).to eq([])
end
it 'works when combined with facebook and status' do
has_email.update_attribute(:status, 'Partner - Pray')
has_email.primary_or_first_person.facebook_accounts << create(:facebook_account)
another_contact = create(:contact, status: 'Contact for Appointment')
p = create(:person)
p.email_addresses << create(:email_address)
p.facebook_accounts << create(:facebook_account)
another_contact.people << p
cf = ContactFilter.new(contact_info_email: 'Yes', contact_info_facebook: 'Yes', status: ['Contact for Appointment'])
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to eq [another_contact]
end
end
context '#contact_info_phone' do
let!(:has_home) do
c = create(:contact)
c.people << create(:person)
c.people << create(:person)
c.primary_or_first_person.phone_numbers << create(:phone_number, location: 'home')
c
end
let!(:has_mobile) do
c = create(:contact)
c.people << create(:person)
c.primary_or_first_person.phone_numbers << create(:phone_number, location: 'mobile')
c
end
let!(:has_both) do
c = create(:contact)
c.people << home_person = create(:person)
home_person.phone_numbers << create(:phone_number, location: 'home')
c.people << mobile_person = create(:person)
mobile_person.phone_numbers << create(:phone_number, location: 'mobile')
c
end
let!(:no_phone) do
c = create(:contact)
c.people << create(:person)
c.primary_or_first_person.phone_numbers << create(:phone_number, historic: true)
c
end
it 'filters when looking for home phone' do
cf = ContactFilter.new(contact_info_phone: 'Yes')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include has_home
expect(filtered_contacts).to_not include has_mobile
expect(filtered_contacts).to_not include no_phone
cf = ContactFilter.new(contact_info_phone: 'Yes', contact_info_mobile: 'No')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include has_home
expect(filtered_contacts).to_not include has_mobile
expect(filtered_contacts).to_not include no_phone
end
it 'filters when looking for mobile phone' do
cf = ContactFilter.new(contact_info_mobile: 'Yes')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include has_mobile
expect(filtered_contacts).to_not include has_home
expect(filtered_contacts).to_not include no_phone
cf = ContactFilter.new(contact_info_mobile: 'Yes', contact_info_phone: 'No')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include has_mobile
expect(filtered_contacts).to_not include has_home
expect(filtered_contacts).to_not include no_phone
end
it 'filters when looking for both phones' do
cf = ContactFilter.new(contact_info_mobile: 'Yes', contact_info_phone: 'Yes')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include has_both
expect(filtered_contacts).to_not include has_home
expect(filtered_contacts).to_not include has_mobile
expect(filtered_contacts).to_not include no_phone
end
it 'filters when looking for no phones' do
cf = ContactFilter.new(contact_info_phone: 'No', contact_info_mobile: 'No')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to_not include has_home
expect(filtered_contacts).to_not include has_mobile
expect(filtered_contacts).to include no_phone
end
it 'works when combined with newsletter and order by name' do
cf = ContactFilter.new(contact_info_phone: 'No', newsletter: 'address')
expect(cf.filter(Contact.order('name'), account_list).to_a).to eq([])
end
end
context '#contact_info_address' do
let!(:has_address) do
c = create(:contact)
c.addresses << create(:address)
c.addresses << create(:address, historic: true)
c
end
it 'filters by contact address present' do
no_address = create(:contact)
historic_address_contact = create(:contact)
historic_address_contact.addresses << create(:address, historic: true)
cf = ContactFilter.new(contact_info_addr: 'Yes')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include has_address
expect(filtered_contacts).to_not include no_address
expect(filtered_contacts).to_not include historic_address_contact
cf = ContactFilter.new(contact_info_addr: 'No', contact_info_email: 'No')
no_address_contacts = cf.filter(Contact, account_list)
expect(no_address_contacts).to_not include has_address
expect(no_address_contacts).to include no_address
expect(no_address_contacts).to include historic_address_contact
end
it 'works when combined with newsletter and ordered by name' do
create(:contact).addresses << create(:address)
cf = ContactFilter.new(contact_info_addr: 'No', newsletter: 'address')
expect(cf.filter(Contact.order('name'), account_list).to_a).to eq([])
end
it 'works when combined with status' do
has_address.update_attribute(:status, 'Partner - Pray')
another_contact = create(:contact, status: 'Contact for Appointment')
another_contact.addresses << create(:address)
cf = ContactFilter.new(contact_info_addr: 'Yes', status: ['Contact for Appointment'])
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to eq [another_contact]
end
end
context '#contact_info_facebook' do
let!(:has_fb) do
c = create(:contact)
c.people << create(:person)
c.people << create(:person)
c.primary_or_first_person.facebook_accounts << create(:facebook_account)
c
end
let!(:no_fb) do
c = create(:contact)
c.people << create(:person)
c
end
it 'filters when looking for facebook_account' do
cf = ContactFilter.new(contact_info_facebook: 'Yes')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to eq [has_fb]
end
it 'filters when looking for no facebook_account' do
cf = ContactFilter.new(contact_info_facebook: 'No')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include no_fb
expect(filtered_contacts).to_not include has_fb
end
end
it 'includes contacts with no email when set to email newsletter' do
has_email = create(:contact, send_newsletter: 'Email')
p = create(:person)
has_email.people << p
create(:email_address, person: p)
no_email = create(:contact, send_newsletter: 'Email')
cf = ContactFilter.new(newsletter: 'email')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include no_email
expect(filtered_contacts).to include has_email
end
it 'includes contacts no currency if account default currency is selected' do
no_currency_contact = create(:contact, pledge_currency: nil)
cf = ContactFilter.new(pledge_currency: 'USD')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include no_currency_contact
end
it 'filters when looking for EUR contacts' do
no_currency_contact = create(:contact, pledge_currency: nil)
eur_contact = create(:contact, pledge_currency: 'EUR')
cf = ContactFilter.new(pledge_currency: 'EUR')
filtered_contacts = cf.filter(Contact, account_list)
expect(filtered_contacts).to include eur_contact
expect(filtered_contacts).not_to include no_currency_contact
end
it 'filters based on tag' do
contact1 = create(:contact, tag_list: 'asdf')
contact2 = create(:contact)
contact2.donor_accounts << create(:donor_account, master_company: create(:master_company))
cf = ContactFilter.new(tags: 'asdf')
expect(cf.filter(Contact.all, build_stubbed(:account_list)))
.to contain_exactly(contact1)
end
it "doesn't display entries when filtering by Newsletter Recipients With Mailing Address" do
contact = create(:contact, send_newsletter: 'Physical')
create(:contact)
2.times do
contact.addresses << create(:address, addressable: contact)
end
cf = ContactFilter.new(newsletter: 'address')
filtered = cf.filter(Contact.all, build_stubbed(:account_list))
expect(filtered.length).to be 1
expect(filtered).to match_array [contact]
end
it "doesn't display entries when filtering by Newsletter Recipients With Email Address" do
contact = create(:contact, send_newsletter: 'Email')
create(:contact, send_newsletter: 'Physical')
p = create(:person)
contact.people << p
2.times do
create(:email_address, person: p)
end
cf = ContactFilter.new(newsletter: 'email')
filtered = cf.filter(Contact.all, build_stubbed(:account_list))
expect(filtered.length).to be 1
expect(filtered).to match_array [contact]
end
end
context '#locale' do
it 'filters contacts with locale null and another' do
contact1 = create(:contact, locale: nil)
contact2 = create(:contact, locale: 'es')
create(:contact, locale: 'fr')
cf = ContactFilter.new(locale: %w(null es))
expect(cf.filter(Contact, build_stubbed(:account_list)))
.to contain_exactly(contact1, contact2)
end
it 'does not filter out if contacts if locale filter blank' do
contact1 = create(:contact, locale: 'fr')
cf = ContactFilter.new(locale: [''])
expect(cf.filter(Contact, build_stubbed(:account_list)))
.to contain_exactly(contact1)
end
it 'filters only for nil locales if only null given' do
contact1 = create(:contact, locale: nil)
create(:contact, locale: 'es')
cf = ContactFilter.new(locale: ['null'])
expect(cf.filter(Contact, build_stubbed(:account_list)))
.to contain_exactly(contact1)
end
it 'filters for contacts with specified locales' do
contact1 = create(:contact, locale: 'de')
contact2 = create(:contact, locale: 'es')
create(:contact, locale: 'fr')
cf = ContactFilter.new(locale: %w(es de))
expect(cf.filter(Contact, build_stubbed(:account_list)))
.to contain_exactly(contact1, contact2)
end
context '#contact_type' do
it 'includes both when not filtered' do
contact1 = create(:contact)
contact2 = create(:contact)
contact2.donor_accounts << create(:donor_account, master_company: create(:master_company))
cf = ContactFilter.new
expect(cf.filter(Contact.all, build_stubbed(:account_list)))
.to contain_exactly(contact1, contact2)
end
it 'filters out companies' do
contact1 = create(:contact)
contact2 = create(:contact)
contact2.donor_accounts << create(:donor_account, master_company: create(:master_company))
cf = ContactFilter.new(contact_type: 'person')
expect(cf.filter(Contact.all, build_stubbed(:account_list)))
.to contain_exactly(contact1)
end
it 'filters out people' do
create(:contact)
contact2 = create(:contact)
contact2.donor_accounts << create(:donor_account, master_company: create(:master_company))
cf = ContactFilter.new(contact_type: 'company')
expect(cf.filter(Contact.all, build_stubbed(:account_list)))
.to contain_exactly(contact2)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/serializers/donation_reports/donation_info_serializer_spec.rb
|
require 'rails_helper'
describe DonationReports::DonationInfoSerializer do
let(:account_list) { create(:account_list) }
let(:donation_info) { DonationReports::DonationInfo.from_donation(build(:donation)) }
subject { DonationReports::DonationInfoSerializer.new(donation_info).as_json }
it 'serializes amount' do
expect(subject[:amount]).to eq(9.99)
end
it 'serializes currency_symbol' do
expect(subject[:currency_symbol]).to eq('R')
end
context 'converted currency' do
it 'serializes converted_currency_symbol' do
expect(subject[:converted_currency_symbol]).to eq('$')
end
it 'serializes converted_amount' do
expect(subject[:converted_amount]).to eq(9.99)
end
it 'serializes converted_currency' do
expect(subject[:converted_currency]).to eq('USD')
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/contact_info_facebook.rb
|
<filename>app/services/contact/filter/contact_info_facebook.rb
class Contact::Filter::ContactInfoFacebook < Contact::Filter::Base
def execute_query(contacts, filters)
contacts_with_fb = contacts.where.not(person_facebook_accounts: { username: nil })
.joins(people: :facebook_account)
return contacts_with_fb if filters[:contact_info_facebook] == 'Yes'
contacts_with_fb_ids = contacts_with_fb.ids
return contacts if contacts_with_fb_ids.empty?
contacts.where.not(id: contacts_with_fb_ids)
end
def title
_('Facebook Profile')
end
def parent
_('Contact Information')
end
def type
'radio'
end
def custom_options
[{ name: _('Yes'), id: 'Yes' }, { name: _('No'), id: 'No' }]
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170210004955_add_status_validation_to_contacts.rb
|
<reponame>chuckmersereau/api_practice
class AddStatusValidationToContacts < ActiveRecord::Migration
def change
add_column :contacts, :status_valid, :boolean
add_column :contacts, :status_validated_at, :datetime
add_index :contacts, :status_validated_at
add_column :contacts, :suggested_changes, :text
end
end
|
chuckmersereau/api_practice
|
db/migrate/20161216004159_add_uuid_to_mail_chimp_appeal_lists.rb
|
class AddUuidToMailChimpAppealLists < ActiveRecord::Migration
def change
add_column :mail_chimp_appeal_lists, :uuid, :uuid, null: false, default: 'uuid_generate_v4()'
add_index :mail_chimp_appeal_lists, :uuid, unique: true
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180726140120_add_default_value_for_subject_hidden.rb
|
<reponame>chuckmersereau/api_practice
class AddDefaultValueForSubjectHidden < ActiveRecord::Migration
def up
change_column_default :activities, :subject_hidden, false
end
def down
change_column_default :activities, :subject_hidden, nil
end
end
|
chuckmersereau/api_practice
|
spec/services/mail_chimp/syncer_spec.rb
|
require 'rails_helper'
RSpec.describe MailChimp::Syncer do
subject { described_class.new(mail_chimp_account) }
let(:list_id) { 'list_one' }
let(:webhook_token) { 'webhook_token' }
let(:mail_chimp_account) { create(:mail_chimp_account, active: true, primary_list_id: list_id) }
let(:mock_importer) { double(:mock_importer) }
let(:mock_exporter) { double(:mock_exporter) }
let(:mock_connection_handler) { double(:mock_connection_handler) }
let(:mock_list) { double(:mock_list) }
let(:mock_request) { double(:mock_request) }
let(:mock_wrapper) { double(:mock_wrapper) }
let(:mock_webhooks) { double(:mock_webhooks) }
context '#sync_with_primary_list' do
context 'connection_handler, importer and exporter' do
let!(:mail_chimp_member_one) { create(:mail_chimp_member, mail_chimp_account: mail_chimp_account, list_id: list_id) }
let!(:mail_chimp_member_two) { create(:mail_chimp_member, mail_chimp_account: mail_chimp_account, list_id: 'random_list') }
let!(:mail_chimp_member_three) do
create(:mail_chimp_member, mail_chimp_account: mail_chimp_account,
list_id: list_id,
email: '<EMAIL>')
end
let!(:mail_chimp_member_four) do
create(:mail_chimp_member, mail_chimp_account: mail_chimp_account,
list_id: list_id,
email: '<EMAIL>')
end
before do
allow(Gibbon::Request).to receive(:new).and_return(mock_request)
allow(mock_request).to receive(:lists).with(list_id).and_return(mock_list)
allow(mock_list).to receive(:webhooks).and_return(mock_webhooks)
allow(mock_webhooks).to receive(:retrieve)
allow(mock_webhooks).to receive(:create)
allow(MailChimp::GibbonWrapper).to receive(:new).and_return(mock_wrapper)
mock_member_info_one = {
'status' => 'unsubscribed',
'email_address' => mail_chimp_member_one.email
}
mock_member_info_three = {
'status' => 'subscribed',
'email_address' => mail_chimp_member_three.email
}
allow(mock_wrapper).to receive(:list_members).and_return([mock_member_info_one, mock_member_info_three])
end
it 'it uses the connection handler' do
expect(MailChimp::ConnectionHandler).to receive(:new).and_return(mock_connection_handler)
expect(mock_connection_handler).to receive(:call_mail_chimp).with(subject, :two_way_sync_with_primary_list!)
subject.two_way_sync_with_primary_list
end
it 'deletes existing members' do
subject.two_way_sync_with_primary_list
expect(MailChimpMember.exists?(mail_chimp_member_one.id)).to be false
# doesn't delete if not on list_id
expect(MailChimpMember.exists?(mail_chimp_member_two.id)).to be true
# doesn't delete if still subscribed
expect(MailChimpMember.exists?(mail_chimp_member_three.id)).to be true
# deletes if not in member info list
expect(MailChimpMember.exists?(mail_chimp_member_four.id)).to be false
end
# it 'calls the importer and exporter classes' do
# expect(MailChimp::Importer).to receive(:new).and_return(mock_importer)
# expect(mock_importer).to receive(:import_all_members)
#
# expect(MailChimp::ExportContactsWorker).to receive(:perform_async).with(mail_chimp_account.id, list_id, nil)
#
# expect do
# subject.two_way_sync_with_primary_list!
# end.to change { mail_chimp_account.mail_chimp_members.reload.count }.from(2).to(1)
# end
end
context 'webhooks' do
before do
allow_any_instance_of(MailChimp::Importer).to receive(:import_all_members)
allow_any_instance_of(MailChimp::Exporter).to receive(:export_contacts)
allow_any_instance_of(MailChimp::Syncer).to receive(:delete_mail_chimp_members)
allow(Rails.env).to receive(:staging?).and_return(true)
end
it 'sets up webhooks when it was never done before for the mail_chimp_account webhook_token' do
mail_chimp_account.webhook_token = '<PASSWORD>'
expect_webhooks_instantiation_and_retrieve_call
expect(mock_webhooks).to receive(:create)
subject.two_way_sync_with_primary_list!
end
it 'does not set up webhooks when it was done before' do
mail_chimp_account.webhook_token = webhook_token
expect_webhooks_instantiation_and_retrieve_call
expect(mock_webhooks).to_not receive(:create)
subject.two_way_sync_with_primary_list!
end
def expect_webhooks_instantiation_and_retrieve_call
allow(Gibbon::Request).to receive(:new).and_return(mock_request)
allow(mock_request).to receive(:lists).with(list_id).and_return(mock_list)
allow(mock_list).to receive(:webhooks).and_return(mock_webhooks)
expect(mock_webhooks).to receive(:retrieve).and_return(
'webhooks' => [
{
'url' => "https://api.mpdx.test/mail_chimp_webhook/#{webhook_token}"
}
]
)
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130213173322_create_help_requests.rb
|
class CreateHelpRequests < ActiveRecord::Migration
def change
create_table :help_requests do |t|
t.string :name
t.text :browser
t.text :problem
t.string :email
t.string :file
t.integer :user_id
t.integer :account_list_id
t.text :session
t.text :user_preferences
t.text :account_list_settings
t.string :request_type
t.timestamps null: false
end
end
end
|
chuckmersereau/api_practice
|
spec/services/account_list/email_collection_spec.rb
|
<filename>spec/services/account_list/email_collection_spec.rb<gh_stars>0
require 'rails_helper'
describe AccountList::EmailCollection do
let!(:account_list) { create(:account_list) }
it 'initializes' do
expect(AccountList::EmailCollection.new(account_list)).to be_a(AccountList::EmailCollection)
end
describe '#select_by_email' do
let!(:contact_1) { create(:contact_with_person, account_list: account_list).reload }
let!(:person_1) { contact_1.primary_person }
let!(:email_address_1) { create(:email_address, person: person_1) }
let!(:contact_2) { create(:contact_with_person, account_list: account_list).reload }
let!(:person_2) { contact_2.primary_person }
let!(:person_3) { contact_2.spouse = create(:person) }
let!(:email_address_2) { create(:email_address, person: person_2) }
let!(:email_address_3) { create(:email_address, email: " #{email_address_2.email.upcase} ", person: person_3) }
let!(:email_address_4) { create(:email_address, person: person_2, deleted: true) }
it 'selects the data by normalized emails without the deleted emails' do
collection = AccountList::EmailCollection.new(account_list)
person1_hash = { contact_id: contact_1.id, person_id: person_1.id, email: email_address_1.email }
expect(collection.select_by_email(email_address_1.email)).to match_array([person1_hash])
expect(collection.select_by_email(" #{email_address_1.email.upcase} ")).to match_array([person1_hash])
person2_hash = { contact_id: contact_2.id, person_id: person_2.id, email: email_address_2.email }
person3_hash = { contact_id: contact_2.id, person_id: person_3.id, email: email_address_3.email }
expect(collection.select_by_email(email_address_2.email)).to match_array([person2_hash, person3_hash])
end
it 'handles a nil argument' do
expect(AccountList::EmailCollection.new(account_list).select_by_email(nil)).to eq([])
end
end
end
|
chuckmersereau/api_practice
|
dev/migrate/2016_02_23_set_default_currencies.rb
|
# These methods are useful in setting the initial currency values
# as we prepare to deploy the multi-currency feature.
def default_pledge_currencies!
sql = <<-EOS
update contacts
set pledge_currency = (
select currency
from donations
where donations.donor_account_id = donor_accounts.id
limit 1
)
from contact_donor_accounts, donor_accounts
where
contact_donor_accounts.contact_id = contacts.id and
donor_accounts.id = contact_donor_accounts.donor_account_id and
contacts.pledge_currency is null;
EOS
ActiveRecord::Base.connection.execute(sql)
end
def default_account_list_currencies!
org_currencies = Hash[Organization.pluck(:id, :default_currency_code)]
AccountList.where.not("settings like '%currency%'").find_each do |account_list|
default_account_list_currency!(account_list, org_currencies)
end
end
def default_account_list_currency!(account_list, org_currencies)
org_ids = account_list.organization_accounts.map(&:organization_id)
account_org_currencies = org_ids.map { |id| org_currencies[id] }.compact.uniq
if account_org_currencies.size == 1
currency = account_org_currencies.first
account_list.update(currency: currency)
puts "Set currency for account #{account_list.id} to #{currency} by org"
else
default_currencies_by_pledges!(account_list)
end
end
def default_currencies_by_pledges!(account_list)
currency_counts = account_list.contacts.where
.not(pledge_currency: nil).group(:pledge_currency).count
if currency_counts.empty?
puts "No currency info for account #{account_list.id}"
return
end
currency = currency_counts.max_by { |_k, v| v }.first
if currency.blank?
puts "No currency info for account #{account_list.id}"
else
account_list.update(currency: currency)
puts "Set currency for account #{account_list.id} to #{currency} by pledges"
end
end
|
chuckmersereau/api_practice
|
spec/services/reports/year_donations_spec.rb
|
require 'rails_helper'
RSpec.describe Reports::YearDonations, type: :model do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:year_donations) { Reports::YearDonations.new(account_list: account_list) }
let!(:designation_account) { create(:designation_account) }
let!(:donor_account) { create(:donor_account) }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:currency_rate) { CurrencyRate.create(exchanged_on: Date.current, code: 'EUR', rate: 0.5, source: 'test') }
let!(:donation) do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
amount: 2, currency: 'EUR',
donation_date: Date.current)
end
let!(:donation_last_year) do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
amount: 2, currency: 'EUR',
donation_date: 13.months.ago.end_of_month - 1.day)
end
before do
account_list.designation_accounts << designation_account
contact.donor_accounts << donor_account
end
describe 'initializes' do
it 'initializes successfully' do
expect(year_donations).to be_a(Reports::YearDonations)
expect(year_donations.account_list).to eq(account_list)
end
end
describe '#donor_infos' do
it 'returns donor infos' do
expect(year_donations.donor_infos).to be_a(Array)
expect(year_donations.donor_infos.size).to eq(1)
expect(year_donations.donor_infos.first).to be_a(DonationReports::DonorInfo)
expect(year_donations.donor_infos.first.contact_name).to eq(contact.name)
end
end
describe '#donation_infos' do
it 'returns donation infos' do
expect(year_donations.donation_infos).to be_a(Array)
expect(year_donations.donation_infos.size).to eq(1)
expect(year_donations.donation_infos.first).to be_a(DonationReports::DonationInfo)
expect(year_donations.donation_infos.first.amount).to eq(2)
end
it 'does not return donations made more than 12 months ago' do
expect(donor_account.donations.size).to eq(2)
expect(year_donations.donation_infos.size).to eq(1)
expect(year_donations.donation_infos.first.donation_date).to eq(Date.current)
end
it 'converts amount' do
expect(year_donations.donation_infos.first.converted_amount).to eq(4.0)
end
end
end
|
chuckmersereau/api_practice
|
app/services/reports/donation_monthly_totals.rb
|
class Reports::DonationMonthlyTotals < ActiveModelSerializers::Model
include Concerns::Reports::DonationSumHelper
attr_accessor :account_list,
:end_date,
:start_date,
:months
validates :account_list, :start_date, :end_date, presence: true
def initialize(account_list:, start_date:, end_date:)
super
date_range = start_date.beginning_of_month.to_date..end_date.beginning_of_month.to_date
@months = date_range.map { |date| Date.new(date.year, date.month, 1) }.uniq
end
def donation_totals_by_month
donations_by_month = group_donations_by_month(all_received_donations, months)
months.each_with_index.map do |month, month_index|
{
month: month.to_date,
totals_by_currency: amounts_by_currency(donations_by_month[month_index])
}
end
end
private
def amounts_by_currency(donations_for_one_month)
donations_by_currency(donations_for_one_month).map do |currency, donations|
{
donor_currency: currency,
total_in_donor_currency: sum_donations(donations),
converted_total_in_salary_currency: sum_converted_donations(donations, account_list.salary_currency)
}
end
end
def all_received_donations
@all_received_donations = received_donations_object.donations
end
def received_donations_object
@received_donations_object ||=
DonationReports::ReceivedDonations.new(
account_list: account_list,
donations_scoper: ->(donation) { donation.where(donation_date: @months.first..@months.last.end_of_month) }
)
end
end
|
chuckmersereau/api_practice
|
spec/workers/import_gifts_and_appeals_from_tnt_worker_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe ImportGiftsAndAppealsFromTntWorker do
let!(:appeal) { create(:appeal) }
let!(:account_list) { appeal.account_list }
let!(:user) { create(:user).tap { |user| account_list.users << user } }
let!(:organization_account) { create(:organization_account, person: user) }
let!(:import) { create(:tnt_import_campaigns_and_promises, account_list: account_list) }
let!(:worker) { ImportGiftsAndAppealsFromTntWorker.new }
before do
stub_smarty_streets
end
it 'sends the message to run the import' do
expect(worker).to receive(:perform_import)
worker.perform(import.id)
end
it 'does not import if the source is not tnt' do
import.update_columns(source: 'csv')
expect(worker).to_not receive(:perform_import)
worker.perform(import.id)
end
it 'does not import if the account list does not exist' do
account_list.delete
expect(worker).to_not receive(:perform_import)
worker.perform(import.id)
end
it 'does not import if the account has no appeals' do
appeal.delete
expect(worker).to_not receive(:perform_import)
worker.perform(import.id)
end
it 'imports appeals, pledges, and gifts' do
expect_any_instance_of(TntImport::AppealsImport).to receive(:import)
expect_any_instance_of(TntImport::PledgesImport).to receive(:import)
expect_any_instance_of(TntImport::GiftsImport).to receive(:import)
worker.perform(import.id)
end
it 'imports appeals with expected parameters' do
appeal = create(:appeal, tnt_id: 183_362_175)
account_list.appeals << appeal
contact = create(:contact)
account_list.contacts << contact
appeal.contacts << contact # Add a contact to the appeal to test that it shows up in the arguments below.
tnt_import = TntImport.new(import)
expect(worker).to receive(:tnt_import).and_return(tnt_import)
expect(TntImport::AppealsImport).to receive(:new).with(account_list,
{ '183362175' => [contact.id], '291896527' => [],
'681505203' => [], '830704017' => [],
'936046261' => [], '936046262' => [],
'1494330654' => [], '1541020410' => [] },
tnt_import.xml).and_return(double(import: true))
worker.perform(import.id)
end
it 'imports pledges with expected parameters' do
tnt_import = TntImport.new(import)
expect(worker).to receive(:tnt_import).and_return(tnt_import)
expect(TntImport::PledgesImport).to receive(:new)
.with(account_list, import, tnt_import.xml)
.and_return(double(import: true))
worker.perform(import.id)
end
it 'imports gifts with expected parameters' do
tnt_import = TntImport.new(import)
contact = create(:contact, tnt_id: 1)
# Add a contact to the account_list to test that it shows up in the arguments below.
account_list.contacts << contact
expect(worker).to receive(:tnt_import).and_return(tnt_import)
expect(TntImport::GiftsImport).to receive(:new)
.with(account_list, { '1' => contact.id }, tnt_import.xml, import)
.and_return(double(import: true))
worker.perform(import.id)
end
end
|
chuckmersereau/api_practice
|
spec/workers/account_list_import_data_enqueuer_worker_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe AccountListImportDataEnqueuerWorker do
def expect_user_to_be_enqueued(user)
user.account_lists.each do |account_list|
expect(Sidekiq::Client).to receive(:push).with(
'class' => AccountList,
'args' => [account_list.id, :import_data],
'queue' => :api_account_list_import_data
).once
end
end
def expect_user_to_not_be_enqueued(user)
user.account_lists.each do |account_list|
expect(Sidekiq::Client).to_not receive(:push).with(
'class' => AccountList,
'args' => [account_list.id, :import_data],
'queue' => :api_account_list_import_data
)
end
end
subject { AccountListImportDataEnqueuerWorker.new.perform }
context 'queuing multiple jobs at a time' do
let!(:first_active_user) { create(:user_with_full_account, current_sign_in_at: 1.day.ago) }
let!(:second_active_user) { create(:user_with_full_account, current_sign_in_at: 1.month.ago) }
let!(:inactive_user) do
create(:user_with_full_account, current_sign_in_at: 70.days.ago).tap do |user|
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: Time.current)
end
end
let!(:account_list_without_org_account) { create(:account_list) }
it 'queues jobs for active users' do
expect_user_to_be_enqueued(first_active_user)
expect_user_to_be_enqueued(second_active_user)
expect_user_to_not_be_enqueued(inactive_user)
expect(Sidekiq::Client).to_not receive(:push).with(
'class' => AccountList,
'args' => [account_list_without_org_account.id, :import_data],
'queue' => :api_account_list_import_data
)
subject
end
end
context 'a user has signed in recently' do
let!(:user) { create(:user_with_full_account, current_sign_in_at: 10.days.ago) }
it 'queues a job if the last_download_attempt_at is recent' do
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: Time.current)
expect_user_to_be_enqueued(user)
subject
end
it 'queues a job if the last_download_attempt_at is more than a week ago' do
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: 8.days.ago)
expect_user_to_be_enqueued(user)
subject
end
it 'queues a job if the last_download_attempt_at is blank' do
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: nil)
expect_user_to_be_enqueued(user)
subject
end
end
context 'a user has not signed in for a long time' do
let!(:user) { create(:user_with_full_account, current_sign_in_at: 90.days.ago) }
it 'does not queue a job if the last_download_attempt_at is recent' do
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: 3.days.ago)
expect_user_to_not_be_enqueued(user)
subject
end
it 'queues a job if the last_download_attempt_at is more than a week ago' do
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: 8.days.ago)
expect_user_to_be_enqueued(user)
subject
end
it 'queues a job if the last_download_attempt_at is blank' do
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: nil)
expect_user_to_be_enqueued(user)
subject
end
end
context 'a user has never signed in' do
let!(:user) { create(:user_with_full_account, current_sign_in_at: nil) }
it 'does not queue a job if the last_download_attempt_at is recent' do
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: 3.days.ago)
expect_user_to_not_be_enqueued(user)
subject
end
it 'queues a job if the last_download_attempt_at is more than a week ago' do
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: 8.days.ago)
expect_user_to_be_enqueued(user)
subject
end
it 'queues a job if the last_download_attempt_at is blank' do
user.account_lists.order(:created_at).first.organization_accounts.first.update!(last_download_attempt_at: nil)
expect_user_to_be_enqueued(user)
subject
end
end
end
|
chuckmersereau/api_practice
|
lib/batch_request_handler/middleware.rb
|
module BatchRequestHandler
class Middleware
BATCH_ENDPOINT = '/api/v2/batch'.freeze
def initialize(app, endpoint: BATCH_ENDPOINT, instruments: [])
@app = app
@endpoint = endpoint
@instrument_classes = instruments.map(&:safe_constantize)
end
def call(env)
if batch_request?(env)
handle_batch_request(env)
else
@app.call(env)
end
end
private
def batch_request?(env)
request_path_matches?(env) && env['REQUEST_METHOD'] == 'POST'
end
def request_path_matches?(env)
request_path = env['PATH_INFO'].to_s.squeeze('/')
request_path[0, @endpoint.length] == @endpoint &&
(request_path[@endpoint.length].nil? || request_path[@endpoint.length] == '/')
end
def handle_batch_request(env)
batch_request = ::BatchRequestHandler::BatchRequest.new(env)
@instrument_classes.each do |instrument_class|
batch_request.add_instrumentation(instrument_class)
end
batch_request.process(@app)
rescue ::BatchRequestHandler::BatchRequest::InvalidBatchRequestError
render_invalid_batch_request_response
rescue StandardError => e
Rollbar.error(e)
render_unknown_error_response
end
def invalid_batch_request_message
[
'Invalid batch request.',
'A batch request must have a body of a JSON object with a `requests` key that has an array of request objects.',
'A request object must have a `method`, and a `path`, and optionally a `body`.',
'The `body` must be a string.'
].join
end
def render_invalid_batch_request_response
json_payload = {
errors: [
{
status: 400,
message: invalid_batch_request_message
}
]
}.to_json
[400, { 'Content-Type' => 'application/json' }, [json_payload]]
end
def render_unknown_error_response
json_payload = {
errors: [
{
status: 500,
message: 'There was an unknown error in the batch request handler. The error has been logged.'
}
]
}.to_json
[500, { 'Content-Type' => 'application/json' }, [json_payload]]
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists_controller.rb
|
class Api::V2::AccountListsController < Api::V2Controller
def index
load_account_lists
render_account_lists
end
def show
load_account_list
authorize_account_list
render_account_list
end
def update
load_account_list
authorize_account_list
persist_account_list
end
private
def coach?
if params[:action] == 'show'
!load_account_list.users.where(id: current_user).exists? &&
load_account_list.coaches.where(id: current_user).exists?
else
false
end
end
def load_account_lists
@account_lists = account_list_scope.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def load_account_list
@account_list ||= AccountList.find(params[:id])
end
def render_account_list
options = {
json: @account_list,
status: success_status,
include: include_params,
fields: field_params
}
options[:serializer] = Coaching::AccountListSerializer if coach?
render options
end
def render_account_lists
options = {
json: @account_lists.preload_valid_associations(include_associations),
meta: meta_hash(@account_lists),
include: include_params,
fields: field_params
}
options[:each_serializer] = Coaching::AccountListSerializer if coach?
render options
end
def persist_account_list
build_account_list
authorize_account_list
if save_account_list
render_account_list
else
render_with_resource_errors(@account_list)
end
end
def build_account_list
@account_list ||= account_list_scope.build
@account_list.assign_attributes(account_list_params)
end
def save_account_list
@account_list.save(context: persistence_context)
end
def account_list_params
params
.require(:account_list)
.permit(AccountList::PERMITTED_ATTRIBUTES)
end
def account_list_scope
current_user.account_lists
end
def authorize_account_list
authorize @account_list
end
def pundit_user
if action_name == 'show'
current_user
else
PunditContext.new(current_user, account_list: load_account_list)
end
end
def default_sort_param
AccountList.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
app/models/user/coach.rb
|
class User::Coach < User
has_many :coaching_account_lists, -> { uniq }, through: :account_list_coaches, source: :account_list
has_many :coaching_contacts, -> { uniq }, through: :coaching_account_lists, source: :contacts
has_many :coaching_pledges, -> { uniq }, through: :coaching_account_lists, source: :pledges
def remove_coach_access(account_list)
account_list_coaches.where(account_list: account_list).destroy_all
end
end
|
chuckmersereau/api_practice
|
spec/models/account_list_entry_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe AccountListEntry do
end
|
chuckmersereau/api_practice
|
app/serializers/donation_serializer.rb
|
<reponame>chuckmersereau/api_practice
class DonationSerializer < ApplicationSerializer
include LocalizationHelper
attributes :amount,
:appeal_amount,
:channel,
:converted_amount,
:converted_appeal_amount,
:converted_currency,
:currency,
:donation_date,
:memo,
:motivation,
:payment_method,
:payment_type,
:remote_id,
:tendered_amount,
:tendered_currency
belongs_to :appeal
belongs_to :contact
belongs_to :designation_account
belongs_to :donor_account
has_one :pledge
def contact
return unless scope&.[](:account_list)
object.donor_account.contacts.where(account_list: scope[:account_list]).first
end
end
|
chuckmersereau/api_practice
|
spec/services/admin/account_dup_phones_fix_spec.rb
|
<filename>spec/services/admin/account_dup_phones_fix_spec.rb
require 'rails_helper'
describe Admin::AccountDupPhonesFix, '#fix' do
it 'does a dup phone number fix for every person with multiple numbers' do
account_list = create(:account_list)
contact = create(:contact, account_list: account_list)
person_1_phone = create(:person)
person_1_phone.add_phone_number(number: '123-45-6789')
person_1_phone.save
person_2_phones = create(:person)
person_2_phones.add_phone_number(number: '123-45-6789')
person_2_phones.add_phone_number(number: '223-45-6789')
person_2_phones.save
contact.people << [person_1_phone, person_2_phones]
allow(Admin::DupPhonesFix).to receive(:new) { double(fix: nil) }
Admin::AccountDupPhonesFix.new(account_list).fix
expect(Admin::DupPhonesFix).to have_received(:new) do |person|
expect(person).to eq person_2_phones
end
end
end
|
chuckmersereau/api_practice
|
lib/tasks/tasks_subject_hidden.rake
|
namespace :tasks do
task subject_hidden: :environment do
batch_size = 10_000
0.step(Task.count, batch_size).each do |offset|
Task.where(subject_hidden: nil).order(:id).offset(offset).limit(batch_size).update_all(subject_hidden: false)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/contact_info_work_phone_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Contact::Filter::ContactInfoWorkPhone do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:contact_three) { create(:contact, account_list_id: account_list.id) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id) }
let!(:person_one) { create(:person) }
let!(:person_two) { create(:person) }
let!(:phone_number_one) { create(:phone_number, location: 'home') }
let!(:phone_number_two) { create(:phone_number, location: 'mobile') }
let!(:phone_number_three) { create(:phone_number, location: 'work') }
let!(:phone_number_four) { create(:phone_number, location: 'mobile') }
before do
contact_one.people << person_one
contact_two.people << person_two
person_one.phone_numbers << phone_number_one
person_one.phone_numbers << phone_number_two
person_one.phone_numbers << phone_number_three
person_two.phone_numbers << phone_number_four
end
describe '#config' do
it 'returns expected config' do
options = [
{ name: '-- Any --', id: '', placeholder: 'None' },
{ name: 'Yes', id: 'Yes' },
{ name: 'No', id: 'No' }
]
expect(described_class.config([account_list])).to include(multiple: false,
name: :contact_info_work_phone,
options: options,
parent: 'Contact Information',
title: 'Work Phone',
type: 'radio',
default_selection: '')
end
end
describe '#query' do
let(:contacts) { Contact.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(contacts, {}, nil)).to eq(nil)
expect(described_class.query(contacts, { contact_info_work_phone: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { contact_info_work_phone: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { contact_info_work_phone: '' }, nil)).to eq(nil)
end
end
context 'filter by no work phone' do
it 'returns only contacts that have no work phone' do
result = described_class.query(contacts, { contact_info_work_phone: 'No' }, nil).to_a
expect(result).to match_array [contact_two, contact_three, contact_four]
end
end
context 'filter by work phone' do
it 'returns only contacts that have a work phone' do
result = described_class.query(contacts, { contact_info_work_phone: 'Yes' }, nil).to_a
expect(result).to match_array [contact_one]
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170731185156_add_next_ask_amount_to_contacts.rb
|
<gh_stars>0
class AddNextAskAmountToContacts < ActiveRecord::Migration
def change
add_column :contacts, :next_ask_amount, :decimal, precision: 19, scale: 2
end
end
|
chuckmersereau/api_practice
|
app/services/person/filter/deceased.rb
|
<filename>app/services/person/filter/deceased.rb
class Person::Filter::Deceased < Person::Filter::Base
def execute_query(people, filters)
people.where(deceased: filters[:deceased]&.to_s == 'true')
end
end
|
chuckmersereau/api_practice
|
app/services/tnt_import.rb
|
<reponame>chuckmersereau/api_practice
class TntImport
SOURCE = 'TntImport'.freeze
def initialize(import)
@import = import
@account_list = @import.account_list
@user = @import.user
@designation_profile = @account_list.designation_profiles.first || @user.designation_profiles.first
@tags_by_contact_id = {}
end
def xml
@xml ||= TntImport::XmlReader.new(@import).parsed_xml
end
def import
@import.file.cache_stored_file!
return false unless xml.present?
contact_ids_by_tnt_contact_id = import_contacts
import_referrals(contact_ids_by_tnt_contact_id)
import_tasks(contact_ids_by_tnt_contact_id)
contact_ids_by_tnt_appeal_id = import_history(contact_ids_by_tnt_contact_id)
import_settings
import_appeals(contact_ids_by_tnt_appeal_id)
import_pledges
import_offline_org_gifts(contact_ids_by_tnt_contact_id)
false
ensure
CarrierWave.clean_cached_files!
end
private
def import_contacts
TntImport::ContactsImport.new(@import, @designation_profile, xml)
.import_contacts
end
def import_referrals(tnt_contacts)
rows = xml.tables['Contact']
TntImport::ReferralsImport.new(tnt_contacts, rows).import
end
def import_tasks(tnt_contacts = {})
TntImport::TasksImport.new(@import, tnt_contacts, xml).import
end
def import_history(tnt_contacts = {})
TntImport::HistoryImport.new(@import, tnt_contacts, xml).import
end
def import_offline_org_gifts(contact_ids_by_tnt_contact_id)
TntImport::GiftsImport.new(@account_list, contact_ids_by_tnt_contact_id, xml, @import).import
end
def import_settings
TntImport::SettingsImport.new(@account_list, xml, @import.override?).import
end
def import_appeals(contact_ids_by_tnt_appeal_id)
TntImport::AppealsImport.new(@account_list, contact_ids_by_tnt_appeal_id, xml)
.import
end
def import_pledges
TntImport::PledgesImport.new(@account_list, @import, xml).import
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170816144835_add_last_geocoded_at_to_master_addresses.rb
|
<gh_stars>0
class AddLastGeocodedAtToMasterAddresses < ActiveRecord::Migration
def change
add_column :master_addresses, :last_geocoded_at, :datetime
end
end
|
chuckmersereau/api_practice
|
spec/models/phone_number_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe PhoneNumber do
let(:user) do
u = create(:user_with_account)
u.account_lists.order(:created_at).first.update(home_country: 'Australia')
u
end
let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) }
let(:person) { contact.people.create(first_name: 'test').reload }
include_examples 'updatable_only_when_source_is_mpdx_validation_examples',
attributes: [:number, :country_code, :location, :remote_id],
factory_type: :phone_number
include_examples 'after_validate_set_source_to_mpdx_examples', factory_type: :phone_number
describe 'adding a phone number to a person' do
it "creates a phone number normalized to home country if it's new" do
expect do
PhoneNumber.add_for_person(person, number: '(02) 7010 1111')
phone_number = person.reload.phone_numbers.first
expect(phone_number.number).to eq('+61270101111')
end.to change(PhoneNumber, :count).from(0).to(1)
end
it 'accepts phone numbers with country code different from home country' do
PhoneNumber.add_for_person(person, number: '+161712345678')
expect(person.reload.phone_numbers.first.number).to eq('+161712345678')
end
it 'adds a number invalid for home country but without country code' do
# In this case the user's home country is Australia, but the number they
# are entering does not look like an Australian phone number. In that
# case, at least normalize it in a consistent way to avoid duplicates
# (note that there is no +1 on the number, just a + in front of the 617).
PhoneNumber.add_for_person(person, number: '617-123-5678')
expect(person.reload.phone_numbers.first.number).to eq('+6171235678')
end
it "doesn't create a phone number if it exists" do
PhoneNumber.add_for_person(person, number: '213-345-2313')
expect do
PhoneNumber.add_for_person(person, number: '213-345-2313')
end.to_not change(PhoneNumber, :count)
end
it 'creates a duplicate phone number if it is from an TntImport' do
PhoneNumber.add_for_person(person, number: '213-345-2313')
expect do
PhoneNumber.add_for_person(person, number: '213-345-2313', source: 'TntImport')
end.to change(PhoneNumber, :count).from(1).to(2)
end
it "doesn't create a phone number if it exists and are both from TntImports" do
PhoneNumber.add_for_person(person, number: '213-345-2313', source: 'TntImport')
expect do
PhoneNumber.add_for_person(person, number: '213-345-2313', source: 'TntImport')
end.to_not change(PhoneNumber, :count)
end
it "doesn't create a phone number if it exists in normalized form" do
contact.account_list.update(home_country: 'United States')
PhoneNumber.add_for_person(person, number: '+12133452313')
expect do
PhoneNumber.add_for_person(person, number: '213-345-2313')
end.to_not change(PhoneNumber, :count)
end
it "doesn't create a phone number if it exists in non-normalized form" do
PhoneNumber.add_for_person(person, number: '213-345-2313')
person.phone_numbers.last.update_column(:number, '213-345-2313')
expect do
PhoneNumber.add_for_person(person, number: '213-345-2313')
end.to_not change(PhoneNumber, :count)
end
it "doesn't duplicated numbers with different formats if home country nil" do
contact.account_list.update(home_country: nil)
PhoneNumber.add_for_person(person, number: '213-345-2313')
expect do
PhoneNumber.add_for_person(person, number: '(213) 345-2313')
end.to_not change(PhoneNumber, :count)
end
it 'sets only the first phone number to primary' do
PhoneNumber.add_for_person(person, number: '213-345-2313')
expect(person.phone_numbers.first).to be_primary
PhoneNumber.add_for_person(person, number: '313-313-3142')
expect(person.phone_numbers.last).to_not be_primary
end
it 'sets a prior phone number to not-primary if the new one is primary' do
phone1 = PhoneNumber.add_for_person(person, number: '213-345-2313')
expect(phone1).to be_primary
phone2 = PhoneNumber.add_for_person(person, number: '313-313-3142', primary: true)
expect(phone2).to be_primary
phone2.send(:ensure_only_one_primary)
expect(phone1.reload).to_not be_primary
end
it 'leaves prior phone as primary if the new one is not primary' do
phone1 = PhoneNumber.add_for_person(person, number: '213-345-2313')
expect do
phone2 = PhoneNumber.add_for_person(person, number: '313-313-3142')
expect(phone2).to_not be_primary
end.to_not change { phone1.reload.primary? }.from(true)
end
end
describe 'clean_up_number' do
it 'should parse out the country code' do
pn = PhoneNumber.add_for_person(person, number: '+44 12345532')
pn.clean_up_number
expect(pn.country_code).to eq('44')
end
it 'returns a number and extension when provided' do
phone = PhoneNumber.add_for_person(person, number: '213-345-2313;23')
phone.clean_up_number
expect(phone.number).to eq('+12133452313;23')
end
it 'defaults to United States normalizating when user home country unset' do
user.account_lists.order(:created_at).first.update(home_country: '')
phone = PhoneNumber.add_for_person(person, number: '213-345-2313;23')
phone.clean_up_number
expect(phone.number).to eq('+12133452313;23')
end
# Badly formatted numbers can be imported into MPDX by the TntMPD import.
# Rather than cleaning those numbers to nil or not importing them from
# TntMPD (or any other import that might skip validation), this will allow
# the user to see the badly formatted numbers in MPDX and then fix them
# gradually as they edit contacts.
it 'leaves a number with non-digit characters in it as-is' do
pn = PhoneNumber.add_for_person(person, number: 'none')
pn.clean_up_number
expect(pn.number).to eq 'none'
end
end
describe 'validate phone number' do
it 'allows numbers with non-numeric characters' do
# The reason for this is that the Tnt import and donor system import will
# sometimes have non-numeric values for phone numbers. We used to have
# validation for phone numbers to match a regex but it caused more
# problems in terms of failed imports than it helped with data
# cleanliness.
expect(PhoneNumber.new(number: 'asdf')).to be_valid
expect(PhoneNumber.new(number: '(213)BAD-PHONE')).to be_valid
end
it 'allows international numbers not in strict phonelib database' do
expect(PhoneNumber.new(number: '+6427751138')).to be_valid
end
end
describe 'comparing numbers' do
it 'returns true for two numbers that are the same except for formatting' do
user.account_lists.order(:created_at).first.update(home_country: 'United States')
pn = PhoneNumber.add_for_person(person, number: '+16173194567')
pn2 = PhoneNumber.add_for_person(person, number: '(617) 319-4567')
expect(pn.reload).to eq(pn2.reload)
end
it 'return false for two numbers that are not the same' do
pn = PhoneNumber.create(number: '6173191234')
pn2 = PhoneNumber.create(number: '6173191235')
expect(pn).to_not eq(pn2)
end
end
describe '==' do
it 'compares by numeric parts of number' do
p1 = PhoneNumber.new(number: '123')
p2 = PhoneNumber.new(number: '1-2x3')
expect(p1).to eq p2
end
it 'does not error if one of the numbers is nil' do
p1 = PhoneNumber.new(number: nil)
p2 = PhoneNumber.new(number: '1-2x3')
expect(p1).to_not eq p2
end
end
describe 'permitted attributes' do
it 'defines permitted attributes' do
expect(PhoneNumber::PERMITTED_ATTRIBUTES).to be_present
end
end
describe '#set_valid_values' do
it "sets valid_values to true if this is the person's only phone number, or the source is manual" do
phone_number_one = create(:phone_number, source: 'not mpdx')
expect(phone_number_one.valid_values).to eq(true)
expect(phone_number_one.source).to_not eq(PhoneNumber::MANUAL_SOURCE)
phone_number_two = create(:phone_number, source: 'not mpdx', person: phone_number_one.person)
expect(phone_number_two.valid_values).to eq(false)
expect(phone_number_two.source).to_not eq(PhoneNumber::MANUAL_SOURCE)
phone_number_three = create(:phone_number, source: PhoneNumber::MANUAL_SOURCE, person: phone_number_one.person)
expect(phone_number_three.valid_values).to eq(true)
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/reports/questions_controller.rb
|
class Reports::QuestionsController < ApplicationController
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/people/merges/bulk_controller_spec.rb
|
<filename>spec/controllers/api/v2/contacts/people/merges/bulk_controller_spec.rb
require 'rails_helper'
describe Api::V2::Contacts::People::Merges::BulkController, type: :controller do
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:account_list_id) { account_list.id }
let!(:correct_attributes) { attributes_for(:contact, name: '<NAME>', account_list_id: account_list_id, tag_list: 'tag1') }
let!(:factory_type) { :contact }
let!(:id) { resource.id }
let!(:incorrect_attributes) { attributes_for(:contact, name: nil, account_list_id: account_list_id) }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:resource) { create(:person, contacts: [contact]) }
let!(:second_resource) { create(:person, contacts: [contact]) }
let!(:third_resource) { create(:person, contacts: [contact]) }
let!(:fourth_resource) { create(:person, contacts: [contact]) }
let(:winner_id) { resource.id }
let(:loser_id) { second_resource.id }
let(:first_merge_attributes) { { winner_id: winner_id, loser_id: loser_id } }
let(:second_merge_attributes) { { winner_id: third_resource.id, loser_id: fourth_resource.id } }
let!(:user) { create(:user_with_account) }
describe '#create' do
let(:unauthorized_resource) { create(factory_type) }
let(:bulk_create_attributes) do
{ data: [
{ data: { attributes: first_merge_attributes } },
{ data: { attributes: second_merge_attributes } }
] }
end
let(:response_body) { JSON.parse(response.body) }
let(:response_errors) { response_body['errors'] }
before do
api_login(user)
end
it 'returns a 200 and the list of updated resources' do
post :create, bulk_create_attributes
expect(response.status).to eq(200)
expect(response_body.length).to eq(2)
end
context 'when the user is unauthorized to perform one of the merges' do
let(:second_resource) { create(:person) }
it 'returns a 200 and only performs the authorized merge' do
post :create, bulk_create_attributes
expect(response.status).to eq(200)
expect(response_body.length).to eq(1)
end
end
context 'when one of the contacts in one of the merges is non-existant' do
let(:winner_id) { SecureRandom.uuid }
it 'returns a 200 and skips the errant merge' do
post :create, bulk_create_attributes
expect(response.status).to eq(200)
expect(response_body.length).to eq(1)
end
context 'and there is only one merge being performed' do
let(:bulk_create_attributes) do
{ data: [
{ data: { attributes: first_merge_attributes } }
] }
end
it 'returns a 404' do
post :create, bulk_create_attributes
expect(response.status).to eq(404)
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_region_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/services/task/filter/contact_region_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe Task::Filter::ContactRegion do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:contact_three) { create(:contact, account_list_id: account_list.id) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id) }
let!(:contact_five) { create(:contact, account_list_id: account_list.id) }
let!(: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]) }
let!(:task_five) { create(:task, account_list: account_list, contacts: [contact_five]) }
let!(:address_one) { create(:address, region: 'My Region') }
let!(:address_two) { create(:address, region: 'My Region') }
let!(:address_three) { create(:address, region: nil) }
let!(:address_four) { create(:address, region: nil) }
let!(:address_five) { create(:address, region: 'My Region', historic: true) }
before do
contact_one.addresses << address_one
contact_two.addresses << address_two
contact_three.addresses << address_three
contact_four.addresses << address_four
contact_five.addresses << address_five
end
describe '#query' do
let(:tasks) { Task.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_region: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_region: [] }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_region: '' }, account_list)).to eq(nil)
end
end
context 'filter by no region' do
it 'returns only tasks with contacts that have no region' do
result = described_class.query(tasks, { contact_region: 'none' }, account_list).to_a
expect(result).to match_array [task_three, task_four]
end
end
context 'filter by region' do
it 'filters multiple regions' do
result = described_class.query(tasks, { contact_region: 'My Region, My Region' }, account_list).to_a
expect(result).to match_array [task_one, task_two]
end
it 'filters a single region' do
result = described_class.query(tasks, { contact_region: 'My Region' }, account_list).to_a
expect(result).to match_array [task_one, task_two]
end
end
context 'multiple filters' do
it 'returns tasks with contacts matching multiple filters' do
result = described_class.query(tasks, { contact_region: 'My Region, none' }, account_list).to_a
expect(result).to match_array [task_one, task_two, task_three, task_four]
end
end
context 'address historic' do
it 'returns tasks with contacts matching the region with historic addresses' do
query = { contact_region: 'My Region', address_historic: 'true' }
result = described_class.query(tasks, query, account_list).to_a
expect(result).to eq [task_five]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/master_people.rb
|
FactoryBot.define do
factory :master_person do
end
end
|
chuckmersereau/api_practice
|
app/serializers/reports/pledge_histories_period_serializer.rb
|
<gh_stars>0
class Reports::PledgeHistoriesPeriodSerializer < ServiceSerializer
REPORT_ATTRIBUTES = [:start_date,
:end_date,
:pledged,
:received].freeze
attributes(*REPORT_ATTRIBUTES)
delegate(*REPORT_ATTRIBUTES, to: :object)
def id
start_date.strftime('%F')
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/tags/bulk_controller_spec.rb
|
<filename>spec/controllers/api/v2/contacts/tags/bulk_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V2::Contacts::Tags::BulkController, type: :controller do
let(:resource_type) { :tags }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:first_tag) { 'tag_one' }
let(:second_tag) { 'tag_two' }
let(:contact_one) { create(:contact, account_list: account_list, tag_list: [first_tag]) }
let(:contact_two) { create(:contact, account_list: account_list, tag_list: [second_tag]) }
let(:params) do
{
data: [{
data: {
type: 'tags',
attributes: {
name: first_tag
}
}
}]
}
end
describe '#create' do
it 'creates the tag object for users that have that access' do
api_login(user)
expect do
post :create, params
end.to change { contact_two.reload.tag_list.length }.by(1)
expect(response.status).to eq(200)
end
context 'with contact_ids filter' do
let(:params) do
{
data: [{
data: {
type: 'tags',
attributes: {
name: first_tag
}
}
}, {
data: {
type: 'tags',
attributes: {
name: second_tag
}
}
}]
}
end
let(:filter_params) do
{
filter: {
contact_ids: contact_two.id
}
}
end
it 'applies the tag to the specified contacts' do
api_login(user)
expect do
post :create, params.merge(filter_params)
end.to change { contact_two.reload.tag_list.length }.by(1)
expect(response.status).to eq(200)
end
it 'does not apply the tag to unspecified contacts' do
api_login(user)
expect do
post :create, params.merge(filter_params)
end.to_not change { contact_one.reload.tag_list.length }
expect(response.status).to eq(200)
end
end
it 'does not create the tag for users that do not own the contact' do
api_login(create(:user_with_account))
expect do
post :create, params
end.not_to change { contact_two.reload.tag_list.length }
expect(response.status).to eq(404)
end
it 'does not create the tag object for users that are not signed in' do
expect do
post :create, params
end.not_to change { contact_two.reload.tag_list.length }
expect(response.status).to eq(401)
end
end
describe '#destroy' do
it 'deletes the resource object for users that have that access' do
api_login(user)
expect do
delete :destroy, params
end.to change { contact_one.reload.tag_list.length }.by(-1)
expect(response.status).to eq(204)
end
it 'does not destroy the resource for users that do not own the resource' do
api_login(create(:user_with_account))
expect do
delete :destroy, params
end.not_to change { contact_one.reload.tag_list.length }
expect(response.status).to eq(404)
end
it 'does not delete the resource object for users that are not signed in' do
expect do
delete :destroy, params
end.not_to change { contact_one.reload.tag_list.length }
expect(response.status).to eq(401)
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/analytics_controller_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Api::V2::AccountLists::AnalyticsController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let!(:task_one) do
create(:task, account_list: account_list, activity_type: 'Talk to In Person',
completed: true, completed_at: 6.days.ago)
end
let!(:task_two) do
create(:task, account_list: account_list, activity_type: 'Talk to In Person',
completed: true, completed_at: 3.weeks.ago)
end
let(:resource) do
AccountList::Analytics.new(
account_list: account_list,
start_date: 1.month.ago,
end_date: Time.current
)
end
let(:given_reference_key) { 'appointments' }
let(:parent_param) { { account_list_id: account_list.id } }
include_examples 'show_examples', except: [:sparse_fieldsets]
context 'filtering by date_range' do
let(:incorrect_datetime_range) { "#{1.week.ago.iso8601}...#{Time.current.iso8601}" }
let(:incorrect_date_range) { "#{1.week.ago.iso8601}...#{Time.current.iso8601}" }
let(:full_params) do
{
filter: {
date_range: range
},
account_list_id: account_list.id
}
end
context 'with a valid datetime or date range' do
context 'with date and time' do
let(:range) { "#{1.week.ago.utc.iso8601}...#{Time.current.utc.iso8601}" }
it 'filters out tasks that are not in the specified date range' do
api_login(user)
get :show, full_params
expect(response.status).to eq(200)
expect(JSON.parse(response.body)['data']['attributes']['phone']['talktoinperson']).to eq(1)
end
end
context 'with date only' do
let(:range) { "#{1.week.ago.utc.to_date}...#{Time.current.utc.to_date}" }
it 'filters out tasks that are not in the specified date range' do
api_login(user)
get :show, full_params
expect(response.status).to eq(200)
expect(JSON.parse(response.body)['data']['attributes']['phone']['talktoinperson']).to eq(1)
end
end
end
context 'with an invalid datetime or date range' do
context 'with date and time' do
let(:range) { '9999-99-99T99:99:99Z...9999-99-99T99:99:99Z' }
it 'raises a bad_request error when the datetime range follows the wrong format' do
api_login(user)
get :show, full_params
expect(response.status).to eq(400), invalid_status_detail
end
end
context 'with date only' do
let(:range) { '10/12/2015...10/12/2016' }
it 'raises a bad_request error when the datetime range follows the wrong format' do
api_login(user)
get :show, full_params
expect(response.status).to eq(400)
end
end
end
end
describe '#show (for a User::Coach)' do
include_context 'common_variables'
let(:coach) { create(:user).becomes(User::Coach) }
before do
account_list.coaches << coach
end
it 'shows resource to users that are signed in' do
api_login(coach)
get :show, full_params
expect(response.status).to eq(200), invalid_status_detail
expect(response.body)
.to include(resource.send(reference_key).to_json) if reference_key
end
it 'does not show resource to users that are not signed in' do
get :show, full_params
expect(response.status).to eq(401), invalid_status_detail
end
end
end
|
chuckmersereau/api_practice
|
app/services/tnt_import/xml.rb
|
<gh_stars>0
class TntImport::Xml
attr_reader :table_names,
:tables,
:version
def initialize(xml)
@table_names = xml.css('Database > Tables > *').map(&:name)
@tables = @table_names.each_with_object({}) do |table_name, hash|
hash[table_name] = xml.css("Database > Tables > #{table_name} > row").map(&method(:parse_row))
end
@version = xml.at_css('Database > Version').content.to_f
end
def table(name)
tables[name]
end
# finds a row from table_name table matching either the id given, or the whole hash
def find(table_name, value)
return unless tables[table_name.to_s]
tables[table_name.to_s].find do |r|
next r.slice(*value.keys) == value if value.is_a? Hash
r['id'] == value
end
end
private
def parse_row(row)
{
'id' => row.attr('id')
}.merge(extract_row_columns(row))
end
def extract_row_columns(row)
Hash[
row.element_children.map { |column| [column.name, column.content] }
]
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/merge_controller_spec.rb
|
<filename>spec/controllers/api/v2/account_lists/merge_controller_spec.rb
require 'rails_helper'
describe Api::V2::AccountLists::MergeController, type: :controller do
include_examples 'common_variables'
let(:resource_type) { :merge }
let(:factory_type) { :merge }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:account_list2) { create(:account_list) }
let(:account_list_id) { account_list.id }
let(:account_list2_id) { account_list2.id }
context 'authorized user' do
before do
account_list2.users << user
api_login(user)
end
describe '#create' do
it 'makes a merge' do
data = {
type: resource_type,
relationships: {
account_list_to_merge: {
data: {
type: 'account_lists',
id: account_list2.id
}
}
}
}
post :create, account_list_id: account_list_id, data: data
expect(response.status).to eq(201), invalid_status_detail
end
it 'does not make a merge' do
data = {
type: resource_type,
relationships: {
account_list_to_merge: {
data: {
type: 'account_lists',
id: account_list.id
}
}
}
}
post :create, account_list_id: account_list_id, data: data
expect(response.status).to eq(400), invalid_status_detail
end
end
end
context 'unauthorized user' do
describe '#create' do
it 'does not make a merge' do
post :create, account_list_id: account_list_id
expect(response.status).to eq(401), invalid_status_detail
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/appeals_import_spec.rb
|
require 'rails_helper'
describe TntImport::AppealsImport do
let(:import) { create(:tnt_import, override: true) }
let(:tnt_import) { TntImport.new(import) }
let(:xml) { tnt_import.xml }
before { stub_smarty_streets }
context 'version 3.2 and higher' do
before { import.file = File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml')) }
it 'expects the right xml version' do
expect(xml.version).to eq 3.2
end
it 'imports Appeals' do
expect { tnt_import.import }.to change { Appeal.count }.from(0).to(2)
expect(Appeal.first.attributes.except('id', 'created_at', 'updated_at', 'id')).to eq(
'name' => '2017 Increase Campaign',
'account_list_id' => import.account_list_id,
'amount' => 10_000,
'description' => nil,
'end_date' => nil,
'tnt_id' => 1_510_627_109,
'active' => true,
'monthly_amount' => 100
)
expect(Appeal.second.attributes.except('id', 'created_at', 'updated_at', 'id')).to eq(
'name' => '2017 Increase Strategy',
'account_list_id' => import.account_list_id,
'amount' => 0,
'description' => nil,
'end_date' => nil,
'tnt_id' => 1_510_627_107,
'active' => true,
'monthly_amount' => 0
)
end
end
context 'version 3.1 and lower' do
before { import.file = File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_0_export_appeals.xml')) }
it 'expects the right xml version' do
expect(xml.version).to eq 3.0
end
it 'imports Appeals' do
expect { tnt_import.import }.to change { Appeal.count }.from(0).to(1)
expect(Appeal.last.attributes.except('id', 'created_at', 'updated_at', 'id')).to eq(
'name' => 'CSU',
'account_list_id' => import.account_list_id,
'amount' => nil,
'description' => nil,
'end_date' => nil,
'tnt_id' => -2_079_150_908,
'active' => true,
'monthly_amount' => nil
)
end
end
end
|
chuckmersereau/api_practice
|
spec/serializers/person/google_account/contact_group_serializer_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Person::GoogleAccount::ContactGroupSerializer do
let(:contact_group) do
Person::GoogleAccount::ContactGroup.new(
id: 'contact_group_id_0',
title: 'System Group: My Family',
created_at: Date.today,
updated_at: Date.today
)
end
subject { described_class.new(contact_group).as_json }
describe '#title' do
it 'returns title without System Group' do
expect(subject[:title]).to eq('My Family')
end
end
describe '#tag' do
it 'returns tag without System Group' do
expect(subject[:tag]).to eq('my-family')
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/contact_type.rb
|
<reponame>chuckmersereau/api_practice
class Contact::Filter::ContactType < Contact::Filter::Base
def execute_query(contacts, filters)
case filters[:contact_type]
when 'person'
contacts.people
when 'company'
contacts.companies
end
end
def title
_('Type')
end
def parent
_('Contact Details')
end
def type
'multiselect'
end
def custom_options
[{ name: _('Person'), id: 'person' }, { name: _('Company'), id: 'company' }]
end
end
|
chuckmersereau/api_practice
|
db/migrate/20171113062557_update_unique_index_columns_on_email_addresses.rb
|
class UpdateUniqueIndexColumnsOnEmailAddresses < ActiveRecord::Migration
def change
reversible do |dir|
dir.up do
remove_index :email_addresses, [:email, :person_id]
add_index :email_addresses, [:email, :person_id, :source], unique: true
end
dir.down do
remove_index :email_addresses, [:email, :person_id, :source]
add_index :email_addresses, [:email, :person_id], unique: true
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/reports/monthly_giving_losses_controller_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/controllers/api/v2/reports/monthly_giving_losses_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V2::Reports::MonthlyLossesGraphsController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:response_json) { JSON.parse(response.body).deep_symbolize_keys }
let(:resource) do
Reports::MonthlyLossesGraph.new(account_list: account_list, months: 5)
end
let(:correct_attributes) { {} }
let(:id) { account_list.id }
include_examples 'show_examples', except: [:sparse_fieldsets]
describe '#show (for a User::Coach)' do
include_context 'common_variables'
let(:coach) { create(:user).becomes(User::Coach) }
let(:account_list_2) { create(:account_list) }
before do
account_list_2.users << coach
account_list.coaches << coach
end
it 'shows resource to users that are signed in' do
api_login(coach)
get :show, full_params
expect(response.status).to eq(200), invalid_status_detail
expect(response_json[:data][:relationships][:account_list][:data][:id])
.to eq account_list.id
expect(response.body)
.to include(resource.send(reference_key).to_json) if reference_key
end
it 'does not show resource to users that are not signed in' do
get :show, full_params
expect(response.status).to eq(401), invalid_status_detail
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170301173502_add_file_headers_to_imports.rb
|
class AddFileHeadersToImports < ActiveRecord::Migration
def change
add_column :imports, :file_headers, :text
end
end
|
chuckmersereau/api_practice
|
app/models/email_address.rb
|
class EmailAddress < ApplicationRecord
include Concerns::AfterValidationSetSourceToMPDX
include HasPrimary
@@primary_scope = :person
audited associated_with: :person, except: [:updated_at, :global_registry_id, :checked_for_google_plus_account]
PERMITTED_ATTRIBUTES = [:created_at,
:email,
:historic,
:location,
:overwrite,
:primary,
:source,
:updated_at,
:updated_in_db_at,
:id,
:valid_values].freeze
belongs_to :person, touch: true
has_one :google_plus_account
before_save :strip_email_attribute, :check_state_for_mail_chimp_sync
before_create :set_valid_values
after_save :trigger_mail_chimp_syncs_to_relevant_contacts, if: :sync_with_mail_chimp_required?
after_create :start_google_plus_account_fetcher_job, unless: :checked_for_google_plus_account
validates :email, presence: true, email: true, uniqueness: { scope: [:person_id, :source], case_sensitive: false }
validates :email, :remote_id, :location, updatable_only_when_source_is_mpdx: true
global_registry_bindings parent: :person,
fields: { email: :email, primary: :boolean }
def to_s
email
end
def email=(email)
super(email&.downcase)
end
class << self
def add_for_person(person, attributes)
attributes = attributes.with_indifferent_access.except(:_destroy)
then_cb = proc do |_exception, _handler, _attempts, _retries, _times|
person.email_addresses.reload
end
attributes['email'] = strip_email(attributes['email'].to_s).downcase
email = Retryable.retryable on: ActiveRecord::RecordNotUnique,
then: then_cb do
if attributes['id']
replace_existing_email(person, attributes)
else
create_or_update_email(person, attributes)
end
end
email.save unless email.new_record?
email
end
def expand_and_clean_emails(email_attrs)
cleaned_attrs = []
clean_and_split_emails(email_attrs[:email]).each_with_index do |cleaned_email, index|
cleaned = email_attrs.dup
cleaned[:primary] = false if index.positive? && email_attrs[:primary]
cleaned[:email] = cleaned_email
cleaned_attrs << cleaned
end
cleaned_attrs
end
def clean_and_split_emails(emails_str)
return [] if emails_str.blank?
emails_str.scan(/([^<>,;\s]+@[^<>,;\s]+)/).map(&:first)
end
def strip_email(email)
# Some email addresses seem to get zero-width characters like the
# zero-width-space (\u200B) or left-to-right mark (\u200E)
email.to_s.gsub(/\p{Z}|\p{C}/, '')
end
private
def replace_existing_email(person, attributes)
existing_email = person.email_addresses.find(attributes['id'])
email = person.email_addresses.find { |e| e.email == attributes['email'] && e.id != attributes['id'] }
# make sure we're not updating this record to another email that already exists
if email
email.attributes = attributes
existing_email.destroy
email
else
existing_email.attributes = attributes
existing_email
end
end
def create_or_update_email(person, attributes)
email = person.email_addresses.find { |e| e.email == attributes['email'] }
if both_from_tnt_sources?(email, attributes)
email.attributes = attributes
else
attributes['primary'] ||= person.email_addresses.empty?
new_or_create = person.new_record? ? :new : :create
email = person.email_addresses.send(new_or_create, attributes)
end
email
end
def both_from_tnt_sources?(email, attrs)
email && (attrs[:source] != TntImport::SOURCE || email.source == attrs[:source])
end
end
private
def trigger_mail_chimp_syncs_to_relevant_contacts
person.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?
primary? && (primary_changed? || email_changed? || !persisted?)
end
def start_google_plus_account_fetcher_job
GooglePlusAccountFetcherWorker.perform_async(id)
end
def strip_email_attribute
self.email = self.class.strip_email(email)
end
def contact
@contact ||= person.try(:contacts).try(:first)
end
def set_valid_values
self.valid_values = (source == MANUAL_SOURCE) || !self.class.where(person: person).exists?
true
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120330025557_add_locked_at_to_person_organization_account.rb
|
<gh_stars>0
class AddLockedAtToPersonOrganizationAccount < ActiveRecord::Migration
def change
add_column :person_organization_accounts, :locked_at, :datetime
end
end
|
chuckmersereau/api_practice
|
dev/util/admin_worker_util.rb
|
<gh_stars>0
# The fix parameter should be in underscore format e.g. account_dup_phones, but
# it will correspond to an admin fixer class, i.e. Admin::AccountDupPhonesFix
def schedule_admin_fixes(fix, time_period)
count = AccountList.count
interval = time_period / count
Sidekiq.redis do |conn|
conn.pipelined { schedule_fixes_at_intervals(fix, interval) }
end
end
def schedule_fixes_at_intervals(fix, interval)
AccountList.pluck(:id).sort.each_with_index do |account_list_id, index|
Admin::FixWorker.perform_in(interval * index, fix,
'AccountList', account_list_id)
end
end
def schedule_dup_phone_fixes
schedule_admin_fixes('account_dup_phones', 48.hours)
end
def schedule_primary_address_fixes
schedule_admin_fixes('account_primary_addresses', 24.hours)
end
|
chuckmersereau/api_practice
|
spec/validators/casted_value_validator_spec.rb
|
require 'spec_helper'
require './app/validators/casted_value_validator'
RSpec.describe CastedValueValidator, type: :validator do
describe 'DATE_FIELD_ENDINGS' do
it 'returns the correct values' do
expect(CastedValueValidator::DATE_FIELD_ENDINGS)
.to eq %w(_at _date _range)
end
end
describe '#validate!' do
context 'when the date provided is a date, datetime, or date range' do
it "is nil when the attribute doesn't end with date endings" do
result = CastedValueValidator.validate!(
attribute: 'not_in_date_endings',
value: DateTime.new.utc
)
expect(result).to be_nil
end
it 'is valid when using a date range' do
result = CastedValueValidator.validate!(
attribute: 'month_range',
value: (Date.yesterday..Date.today)
)
expect(result).to be_truthy
end
date_values = {
date: Date.new,
datetime: DateTime.new.utc,
date_range: Date.new(2017, 2, 10)..Date.new(2017, 3, 10)
}
date_values.each do |label, value|
it "is true when the attribute ends with date endings & is a #{label}" do
result = CastedValueValidator.validate!(
attribute: 'created_at',
value: value
)
expect(result).to eq true
end
end
end
context 'when the date provided is not a date' do
it "is nil when the attribute doesn't end with date endings" do
result = CastedValueValidator.validate!(
attribute: 'not_in_date_endings',
value: DateTime.new.utc
)
expect(result).to be_nil
end
date_values = {
date: 'not a date',
datetime: 'not a datetime',
date_range: 'not a date range'
}
date_values.each do |label, value|
it "is true when the attribute ends with date endings & is a #{label}" do
expect do
CastedValueValidator.validate!(
attribute: 'created_at',
value: value
)
end.to raise_error(CastedValueValidator::DateTimeCastingError)
end
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170418035928_add_index_on_donations_on_created_at.rb
|
<reponame>chuckmersereau/api_practice
class AddIndexOnDonationsOnCreatedAt < ActiveRecord::Migration
disable_ddl_transaction!
def change
add_index :donations, :created_at, algorithm: :concurrently
end
end
|
chuckmersereau/api_practice
|
app/policies/account_list_children_policy.rb
|
class AccountListChildrenPolicy < ApplicationPolicy
attr_accessor :current_account_list
def initialize(context, resource)
@resource = resource
@user = context.user
@current_account_list = context.account_list
end
private
def resource_owner?
user.account_lists.exists?(id: current_account_list.id)
end
end
|
chuckmersereau/api_practice
|
spec/workers/contact_suggested_changes_updater_worker_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe ContactSuggestedChangesUpdaterWorker do
let!(:since_donation_date) { 1.year.ago }
let!(:account_list) { create(:account_list) }
let!(:contact_one) { create(:contact, account_list: account_list) }
let!(:contact_two) { create(:contact, account_list: account_list) }
let!(:donor_account_one) { create(:donor_account) }
let!(:donor_account_two) { create(:donor_account) }
let!(:designation_account_one) { create(:designation_account) }
let!(:designation_account_two) { create(:designation_account) }
let!(:donation_one) do
create(:donation, donation_date: 1.day.ago,
designation_account: designation_account_one,
donor_account: donor_account_one)
end
let!(:donation_two) do
create(:donation, donation_date: 1.day.ago,
designation_account: designation_account_two,
donor_account: donor_account_two,
created_at: 2.years.ago)
end
let(:user) { account_list.users.first }
before do
account_list.designation_accounts << designation_account_one
account_list.designation_accounts << designation_account_two
contact_one.donor_accounts << donor_account_one
contact_two.donor_accounts << donor_account_two
account_list.users << create(:user)
end
it 'updates contacts suggested_changes' do
expect { ContactSuggestedChangesUpdaterWorker.new.perform(user.id, since_donation_date) }
.to change { contact_two.reload.suggested_changes }
.from({})
.to(pledge_frequency: nil, pledge_amount: nil, status: 'Partner - Special')
suggested_changes = contact_one.reload.suggested_changes
expect(suggested_changes).to eq(pledge_frequency: nil, pledge_amount: nil, status: 'Partner - Special')
end
context 'only updating contacts with updated donations' do
before do
contact_two.update_columns(suggested_changes: { pledge_frequency: nil })
end
it 'updates only some contacts suggested_changes' do
expect { ContactSuggestedChangesUpdaterWorker.new.perform(user.id, since_donation_date) }
.to_not change { contact_two.reload.suggested_changes }
.from(pledge_frequency: nil)
suggested_changes = contact_one.reload.suggested_changes
expect(suggested_changes).to eq(pledge_frequency: nil, pledge_amount: nil, status: 'Partner - Special')
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170922152101_add_tnt_id_to_donations.rb
|
class AddTntIdToDonations < ActiveRecord::Migration
def change
add_column :donations, :tnt_id, :string
add_index :donations, :tnt_id
end
end
|
chuckmersereau/api_practice
|
engines/auth/app/controllers/auth/user_accounts_controller.rb
|
require_dependency 'auth/application_controller'
module Auth
class UserAccountsController < ApplicationController
before_action :jwt_authorize!
def create
session.clear
warden.set_user(fetch_current_user, scope: :user)
session['redirect_to'] = params[:redirect_to]
session['account_list_id'] = params[:account_list_id]
if params[:provider] == 'donorhub'
organization = Organization.find(params[:organization_id])
redirect_to "/auth/donorhub?oauth_url=#{URI.encode(organization.oauth_url)}"
elsif params[:provider] == 'sidekiq'
raise AuthenticationError unless current_user.developer
redirect_to '/sidekiq'
else
redirect_to "/auth/#{params[:provider]}"
end
end
def failure
raise AuthenticationError
end
private
def jwt_authorize!
raise AuthenticationError unless user_id_in_token?
rescue JWT::VerificationError, JWT::DecodeError
raise AuthenticationError
end
# The check for user_uuid should be removed 30 days after the following PR is merged to master
# https://github.com/CruGlobal/mpdx_api/pull/993
def user_id_in_token?
http_token && jwt_payload && (jwt_payload['user_id'].present? || jwt_payload['user_uuid'].present?)
end
def http_token
return @http_token ||= auth_header.split(' ').last if auth_header.present?
return @http_token ||= params[:access_token] if params[:access_token]
end
def auth_header
request.headers['Authorization']
end
def jwt_payload
@jwt_payload ||= JsonWebToken.decode(http_token) if http_token
end
# The check for user_uuid should be removed 30 days after the following PR is merged to master
# https://github.com/CruGlobal/mpdx_api/pull/993
def fetch_current_user
@current_user ||= User.find(jwt_payload['user_id'] || jwt_payload['user_uuid']) if jwt_payload
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120402220056_add_status_to_contact.rb
|
class AddStatusToContact < ActiveRecord::Migration
def change
add_column :contacts, :status, :string
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120219080953_create_phone_numbers.rb
|
class CreatePhoneNumbers < ActiveRecord::Migration
def change
create_table :phone_numbers do |t|
t.belongs_to :person
t.string :number
t.string :country_code
t.string :location
t.boolean :primary, default: false
t.timestamps null: false
end
add_index :phone_numbers, :person_id
end
end
|
chuckmersereau/api_practice
|
app/models/donor_account.rb
|
<gh_stars>0
require_dependency 'address_methods'
class DonorAccount < ApplicationRecord
include AddressMethods
audited associated_with: :organization, except: [:total_donations, :updated_at, :last_donation_date]
belongs_to :organization
belongs_to :master_company
has_many :master_person_donor_accounts, dependent: :destroy
has_many :master_people, through: :master_person_donor_accounts
has_many :donor_account_people, dependent: :destroy
has_many :people, through: :donor_account_people
has_many :donations, dependent: :destroy
has_many :contact_donor_accounts, dependent: :destroy
has_many :contacts, through: :contact_donor_accounts, inverse_of: :donor_accounts
has_many :donation_amount_recommendations, dependent: :destroy, inverse_of: :donor_account
validates :account_number, uniqueness: { scope: :organization_id }
validates :account_number, presence: true
scope :filter, lambda { |account_list, filter_params|
filtered_scope = where(filter_params.except(:wildcard_search))
return filtered_scope unless filter_params.key?(:wildcard_search)
filtered_scope.by_wildcard_search(account_list, filter_params[:wildcard_search])
}
scope :by_wildcard_search, lambda { |account_list, wildcard_search_params|
includes(:contacts)
.references(:contacts).where('"contacts"."name" ilike :name AND "contacts"."account_list_id" = :account_list_id OR '\
'"donor_accounts"."name" ilike :name OR '\
'"donor_accounts"."account_number" iLIKE :account_number',
name: "%#{wildcard_search_params}%",
account_number: "%#{wildcard_search_params}%",
account_list_id: account_list.id)
}
def primary_master_person
master_people.find_by('master_person_donor_accounts.primary' => true)
end
def link_to_contact_for(account_list, contact = nil)
contact ||= account_list.contacts.where('donor_accounts.id' => id).includes(:donor_accounts).first # already linked
# If that dind't work, try to find a contact for this user that matches based on name
contact ||= account_list.contacts.find { |c| c.name == name }
contact ||= Contact.create_from_donor_account(self, account_list)
contact.donor_accounts << self unless contact.donor_accounts.include?(self)
contact
end
def update_donation_totals(donation, reset: false)
self.first_donation_date = donation.donation_date if first_donation_date.nil? || donation.donation_date < first_donation_date
self.last_donation_date = donation.donation_date if last_donation_date.nil? || donation.donation_date > last_donation_date
self.total_donations = reset ? total_donations_query : (total_donations.to_f + donation.amount)
save(validate: false)
end
def merge(other)
return false unless other.account_number == account_number
self.total_donations = total_donations.to_f + other.total_donations.to_f
self.last_donation_date = [last_donation_date, other.last_donation_date].compact.max
self.first_donation_date = [first_donation_date, other.first_donation_date].compact.min
self.donor_type = other.donor_type if donor_type.blank?
self.master_company_id = other.master_company_id if master_company_id.blank?
self.organization_id = other.organization_id if organization_id.blank?
self.name = other.name unless attribute_present?(:name)
save
other.master_person_donor_accounts.each do |mpda|
next if master_person_donor_accounts.find_by(master_person_id: mpda.master_person_id)
mpda.update_column(:donor_account_id, id)
end
other.donations.update_all(donor_account_id: id)
other.contact_donor_accounts.each do |cda|
next if contact_donor_accounts.find { |contact_donor_account| contact_donor_account.contact_id == cda.contact_id }
cda.update_column(:donor_account_id, id)
end
other.reload
other.destroy
true
end
def addresses_attributes
attrs = %w(street city state country postal_code start_date primary_mailing_address source source_donor_account_id remote_id)
Hash[addresses.collect.with_index { |address, i| [i, address.attributes.slice(*attrs)] }]
end
def name
self[:name].presence || _('Donor')
end
private
def total_donations_query
donations.sum(:amount)
end
end
|
chuckmersereau/api_practice
|
spec/exhibits/contact_exhibit_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe ContactExhibit do
let(:exhib) { ContactExhibit.new(contact, context) }
let(:contact) { build(:contact) }
let(:context) { double }
it 'should figure out location based on address' do
allow(exhib).to receive(:address).and_return(OpenStruct.new(city: 'Rome', state: 'Empire', country: 'Gross'))
expect(exhib.location).to eq('Rome, Empire, Gross')
end
it 'should not have a newsletter error' do
contact.send_newsletter = _('Physical')
address = create(:address, addressable: contact)
contact.addresses << address
expect(contact.mailing_address).to eq address
expect(exhib.send_newsletter_error).to be_nil
end
it 'should have a newsletter error' do
contact.send_newsletter = _('Physical')
expect(contact.mailing_address.equal_to?(Address.new)).to be true
expect(exhib.send_newsletter_error).to be_present
contact.send_newsletter = _('Both')
expect(exhib.send_newsletter_error).to eq('No mailing address or email addess on file')
end
context '#avatar' do
before { allow(context).to receive(:root_url).and_return('https://mpdx.org') }
it 'ignore images with nil content' do
person = double(facebook_account: nil,
primary_email_address: nil,
primary_picture: double(image: double(url: nil)),
gender: nil)
allow(contact).to receive(:primary_person).and_return(person)
expect(exhib.avatar).to eq('https://mpdx.org/images/avatar.png')
end
it 'uses facebook image if remote_id present' do
person = double(facebook_account: double(remote_id: 1234),
primary_picture: double(image: double(url: nil)))
allow(contact).to receive(:primary_person).and_return(person)
expect(exhib.avatar).to eq('https://graph.facebook.com/1234/picture?type=square')
end
it 'uses google plus avatar if relevant google_account profile_picture_url' do
google_plus_account = double(profile_picture_link: 'https://google.com/image')
email_address = double(google_plus_account: google_plus_account)
person = double(facebook_account: double(remote_id: nil),
primary_email_address: email_address,
primary_picture: double(image: double(url: nil)))
allow(contact).to receive(:primary_person).and_return(person)
expect(exhib.avatar).to eq('https://google.com/image?size=200')
end
it 'uses default avatar if facebook remote_id not present' do
email_address = double(google_plus_account: nil)
person = double(facebook_account: double(remote_id: nil),
primary_picture: double(image: double(url: nil)),
primary_email_address: email_address,
gender: nil)
allow(contact).to receive(:primary_person).and_return(person)
expect(exhib.avatar).to eq('https://mpdx.org/images/avatar.png')
end
end
context '#csv_country' do
let(:account_list) { build(:account_list, home_country: 'Canada') }
let(:contact) { build(:contact, addresses: [build(:address)], account_list: account_list) }
it 'returns the country only if it is different from the account_list home country' do
expect(ContactExhibit.new(contact, nil).csv_country).to eq(contact.mailing_address.country)
contact.mailing_address.country = 'Canada'
expect(ContactExhibit.new(contact, nil).csv_country).to be_blank
end
end
context '#address_block' do
let(:contact) { build(:contact, addresses: [build(:address)]) }
it 'returns the greeting and mailing address' do
expect(ContactExhibit.new(contact, nil).address_block).to eq("#{contact.envelope_greeting}\n123 Somewhere St\nFremont CA 94539")
end
end
# it "should show return the default avatar filename" do
# contact.gender = 'female'
# expect(exhib.avatar).to eq('avatar_f.png')
# contact.gender = 'male'
# expect(exhib.avatar).to eq('avatar.png')
# contact.gender = nil
# expect(exhib.avatar).to eq('avatar.png')
# end
end
|
chuckmersereau/api_practice
|
spec/workers/run_once/account_password_removal_worker_spec.rb
|
require 'rails_helper'
describe RunOnce::AccountPasswordRemovalWorker do
subject { described_class.new.perform }
it 'removes some passwords' do
account_with_token = create(:organization_account, token: '<PASSWORD>')
account_without_token = create(:organization_account)
subject
expect(account_with_token.reload.password).to be nil
expect(account_without_token.reload.password).to_not be nil
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/orgs_finder_spec.rb
|
require 'rails_helper'
describe TntImport::OrgsFinder, '#orgs_by_tnt_id' do
def build_parsed_xml(code:)
Nokogiri::XML(
<<~XML
<Database>
<Tables>
<Organization>
<row id="2">
<Code>#{code}</Code>
</row>
</Organization>
</Tables>
<Version>
3.2
</Version>
</Database>
XML
)
end
it 'looks up the organizations by code' do
ptc_canada = Organization.find_by(code: 'PTC-CAN') ||
create(:organization, code: 'PTC-CAN')
parsed_xml = build_parsed_xml(code: 'PTC-CAN')
wrapped_xml = TntImport::Xml.new(parsed_xml)
orgs = TntImport::OrgsFinder.orgs_by_tnt_id(wrapped_xml, nil)
expect(orgs).to eq('2' => ptc_canada)
end
it 'uses the passed default org if none found by code' do
default_org = double
parsed_xml = build_parsed_xml(code: 'RANDOM')
wrapped_xml = TntImport::Xml.new(parsed_xml)
orgs = TntImport::OrgsFinder.orgs_by_tnt_id(wrapped_xml, default_org)
expect(orgs).to eq('2' => default_org)
end
end
|
chuckmersereau/api_practice
|
app/services/person/filter/updated_at.rb
|
class Person::Filter::UpdatedAt < Person::Filter::Base
def execute_query(people, filters)
people.where(updated_at: filters[:updated_at])
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.