repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
app/models/user.rb
|
<reponame>chuckmersereau/api_practice
class User < Person
include AdobeCampaignable
has_many :account_list_users, dependent: :destroy
has_many :account_lists, -> { uniq }, through: :account_list_users
has_many :account_list_coaches, dependent: :destroy, foreign_key: :coach_id
has_many :account_list_invites
has_many :contacts, through: :account_lists
has_many :account_list_entries, through: :account_lists
has_many :designation_accounts, through: :account_list_entries
has_many :donations, through: :designation_accounts
has_many :designation_profiles, dependent: :destroy
has_many :notification_preferences, dependent: :destroy
has_many :partner_companies, through: :account_lists, source: :companies
has_many :imports, dependent: :destroy
has_many :options, dependent: :destroy
has_many :background_batches, dependent: :destroy
has_many :tasks, through: :account_lists
devise :trackable
store :preferences, accessors: [:time_zone, :locale, :locale_display, :contacts_filter,
:tasks_filter, :contacts_view_options,
:tab_orders, :developer, :admin]
validate :default_account_list_is_valid, if: 'default_account_list.present?'
PERMITTED_ATTRIBUTES = Person::PERMITTED_ATTRIBUTES.deep_dup.concat(
[preferences: [
:contacts_filter,
:contacts_view_options,
:default_account_list,
:locale,
:locale_display,
:tasks_filter,
:tab_orders,
:time_zone
]]
).freeze
# Queue data imports
def queue_imports
organization_accounts.each do |oa|
oa.queue_import_data unless oa.last_download
# oa.queue_import_data unless oa.downloading? || (oa.last_download && oa.last_download > 1.day.ago)
end
end
def tab_order_by_location(location)
orders = tab_orders || {}
orders[location] || []
end
def merge(other)
User.transaction do
other.account_list_users.each do |other_alu|
other_alu.update_column(:user_id, id) unless account_list_users.find { |alu| alu.account_list_id == other_alu.account_list_id }
end
other.designation_profiles.each do |other_dp|
other_dp.update_column(:user_id, id) unless designation_profiles.find { |dp| dp.code == other_dp.code }
end
imports.update_all(user_id: id)
end
super
end
def setup
return 'no account_lists' if account_lists.empty?
return 'no default_account_list' if default_account_list_record.nil?
return 'no organization_account on default_account_list' if default_account_list_record.organization_accounts.empty?
end
def default_account_list_record
account_lists.find_by(id: default_account_list)
end
def designation_numbers(organization_id)
designation_accounts.where(organization_id: organization_id).pluck('designation_number')
end
def self.find_by_guid(guid)
account = if guid.is_a?(Array)
Person::KeyAccount.find_by('lower(remote_id) IN (?)', guid.map(&:downcase))
else
Person::KeyAccount.find_by('lower(remote_id) = ?', guid.downcase)
end
account&.person&.to_user
end
def self.find_by_email(email)
Person::KeyAccount.where('lower(email) = ?', email.downcase)
.limit(1)
.try(:first)
.try(:user)
end
def to_person
Person.find(id)
end
def assign_time_zone(timezone_object)
raise ArgumentError unless timezone_object.is_a?(ActiveSupport::TimeZone)
self.time_zone = timezone_object.name
end
def can_manage_sharing?(account_list)
# We only allow users to manage sharing if the donor system linked them to
# the account list via a designation profile. Otherwise, they only have
# access through an invite from another user and they are not allowed to
# manage sharing.
designation_profiles.where(account_list: account_list).any?
end
def remove_user_access(account_list)
account_list_users.where(account_list: account_list).find_each(&:destroy)
end
def contacts_filter=(hash)
old_value = contacts_filter || {}
super(old_value.merge(hash))
end
def preferences=(preferences_attributes)
return unless preferences_attributes
preferences_attributes = preferences_attributes.with_indifferent_access
if preferences_attributes[:default_account_list]
self.default_account_list = preferences_attributes.delete :default_account_list
end
super(preferences.merge(preferences_attributes))
end
def readable_account_lists
AccountList.readable_by(self)
end
def email_address
email&.email
end
private
def default_account_list_is_valid
return if account_lists.map(&:id).include?(default_account_list)
errors.add(:default_account_list, 'is not included in list of account_lists')
end
end
|
chuckmersereau/api_practice
|
app/services/data_server.rb
|
require 'csv'
require 'erb'
class DataServer
delegate :requires_credentials?, to: :class
attr_accessor :org, :org_account
include ERB::Util
KNOWN_DIFFERING_IMPORT_PERSON_TYPES = [
'I', # Navigators
].freeze
def self.requires_credentials?
true
end
def initialize(org_account)
@org_account = org_account
@org = org_account.organization
end
def import_all(date_from)
Rails.logger.debug 'Importing Profiles'
designation_profiles = import_profiles
designation_profiles.each do |p|
Rails.logger.debug 'Importing Donors'
import_donors(p, date_from)
Rails.logger.debug 'Importing Donations'
import_donations(p, date_from)
end
end
def import_profiles
designation_profiles = org.designation_profiles.where(user_id: org_account.person_id)
if org.profiles_url.present?
check_credentials!
profiles.each do |profile|
Retryable.retryable do
designation_profile =
org.designation_profiles.where(
user_id: org_account.person_id,
name: profile[:name],
code: profile[:code]
).first_or_create
import_profile_balance(designation_profile)
AccountList::FromProfileLinker.new(designation_profile, org_account)
.link_account_list! unless designation_profile.account_list
end
end
else
# still want to update balance if possible
designation_profiles.each do |designation_profile|
Retryable.retryable do
import_profile_balance(designation_profile)
AccountList::FromProfileLinker.new(designation_profile, org_account)
.link_account_list! unless designation_profile.account_list
end
end
end
designation_profiles.reload
end
def import_donors(profile, date_from = nil)
check_credentials!
date_from = date_from.strftime('%m/%d/%Y') if date_from.present?
user = org_account.user
account_list = profile.account_list
begin
response = Retryable.retryable on: Errors::UrlChanged, times: 1, then: update_url(:addresses_url) do
get_response(
org.addresses_url,
get_params(
org.addresses_params,
profile: profile.code.to_s,
datefrom: (date_from || org.minimum_gift_date).to_s,
personid: org_account.remote_id
)
)
end
rescue DataServerError => e
if e.message.include?('no profile associated')
profile.destroy
return
end
raise
end
import_donors_from_csv(account_list, profile, response, user)
true
end
def import_donors_from_csv(account_list, profile, csv, user)
CSV.new(csv, headers: :first_row, header_converters: ->(h) { h.upcase }).each do |line|
next unless line['PEOPLE_ID']
line['LAST_NAME'] = line['LAST_NAME_ORG']
line['FIRST_NAME'] = line['ACCT_NAME'] if line['FIRST_NAME'].blank?
begin
donor_account = add_or_update_donor_account(line, profile, account_list)
# handle bad data
unless %w(P O).include?(line['PERSON_TYPE'])
report_invalid_import_person_type(line)
# Go ahead and assume this is a person
# This follows the same expectations of TntConnect
#
# Contact <NAME>, <EMAIL>, for questions about TntConnect
line['PERSON_TYPE'] = 'P'
end
case line['PERSON_TYPE']
when 'P' # Person
# Create or update people associated with this account
primary_person, primary_contact_person = add_or_update_primary_contact(account_list, line, donor_account)
# Now the secondary person (persumably spouse)
if line['SP_FIRST_NAME'].present?
spouse, contact_spouse = add_or_update_spouse(account_list, line, donor_account)
# Wed the two peple
primary_person.add_spouse(spouse)
primary_contact_person.add_spouse(contact_spouse)
end
when 'O' # Company/Organization
add_or_update_company(account_list, user, line, donor_account)
end
rescue ArgumentError => e
raise line.inspect + "\n\n" + e.message.inspect
end
end
end
def import_donations(profile, date_from = nil, date_to = nil)
check_credentials!
# if no date_from was passed in, use min date from query_ini
date_from = date_from.strftime('%m/%d/%Y') if date_from.present?
date_from = org.minimum_gift_date || '1/1/2004' if date_from.blank?
date_to = Time.now.strftime('%m/%d/%Y') if date_to.blank?
response = Retryable.retryable on: Errors::UrlChanged, times: 1, then: update_url(:donations_url) do
get_response(
org.donations_url,
get_params(
org.donations_params,
profile: profile.code.to_s,
datefrom: date_from,
dateto: date_to,
personid: org_account.remote_id
)
)
end
imported_donations = import_donations_from_csv(profile, response)
delete_removed_donations(parse_date(date_from), parse_date(date_to),
imported_donations)
end
def delete_removed_donations(date_from, date_to, imported_donations)
imported_by_designation = group_by_designation(imported_donations)
imported_by_designation.keys.each do |designation_account|
designation_account.donations.between(date_from, date_to)
.where.not(remote_id: imported_by_designation[designation_account].map(&:remote_id))
.where.not(remote_id: nil).find_each(&:destroy)
end
end
def group_by_designation(imported_donations)
by_designation = {}
imported_donations.each do |donation|
by_designation[donation.designation_account] ||= []
by_designation[donation.designation_account] << donation
end
by_designation
end
def import_donations_from_csv(profile, response)
CSV.new(response, headers: :first_row, header_converters: ->(h) { h.upcase }).read.map do |line|
designation_account = find_or_create_designation_account(line['DESIGNATION'], profile)
add_or_update_donation(line, designation_account, profile)
end
end
def import_profile_balance(profile)
check_credentials!
balance = profile_balance(profile.code)
attributes = { balance: balance[:balance], balance_updated_at: balance[:date] }
profile.update_attributes(attributes)
return unless balance[:designation_numbers] && balance[:designation_numbers].length == 1
attributes[:name] = balance[:account_names].first
balance[:designation_numbers].each_with_index do |number, _i|
find_or_create_designation_account(number, profile, attributes)
end
end
def check_credentials!
return unless requires_credentials?
raise_missing_credentials unless org_account.username && org_account.password || org_account.token
unless org_account.valid_credentials?
raise Person::OrganizationAccount::InvalidCredentialsError,
format(_('Your credentials for %{org} are invalid.'), org: org)
end
end
def validate_credentials
begin
if org.profiles_url.present?
Retryable.retryable on: Errors::UrlChanged, times: 1, then: update_url(:profiles_url) do
get_response(org.profiles_url, get_params(org.profiles_params))
end
else
Retryable.retryable on: Errors::UrlChanged, times: 1, then: update_url(:account_balances_url) do
get_response(org.account_balance_url, get_params(org.account_balance_params))
end
end
rescue DataServerError => e
# provid?ed is necessary because there is a typo in the error message
return false if e.message =~ /password/ || e.message =~ /No client_id was provid?ed/
raise e
rescue Errno::ETIMEDOUT
return false
end
true
end
def profiles_with_designation_numbers
@profiles_with_designation_numbers ||= profiles.map do |profile|
{ designation_numbers: designation_numbers(profile[:code]) }
.merge(profile.slice(:name, :code, :balance, :balance_udated_at))
end
end
protected
def profile_balance(profile_code)
return {} unless org.account_balance_url
balance = {}
response = Retryable.retryable on: Errors::UrlChanged, times: 1, then: update_url(:account_balance_url) do
get_response(org.account_balance_url,
get_params(org.account_balance_params, profile: profile_code.to_s))
end
# This csv should always only have one line (besides the headers)
begin
CSV.new(response, headers: :first_row).each do |line|
balance[:designation_numbers] = line['EMPLID'].split(',').map { |e| e.delete('"') } if line['EMPLID']
balance[:account_names] = line['ACCT_NAME'].split('\n') if line['ACCT_NAME']
balance_match = line['BALANCE'].delete(',').match(/([-]?\d+\.?\d*)/)
balance[:balance] = balance_match[0] if balance_match
balance[:date] = line['EFFDT'] ? DateTime.strptime(line['EFFDT'], '%Y-%m-%d %H:%M:%S') : Time.now
break
end
end
balance
end
def designation_numbers(profile_code)
balance = profile_balance(profile_code)
balance[:designation_numbers]
end
def profiles
unless @profiles
@profiles = []
unless org.profiles_url.blank?
response = Retryable.retryable on: Errors::UrlChanged, times: 1, then: update_url(:profiles_url) do
get_response(org.profiles_url, get_params(org.profiles_params))
end
begin
CSV.new(response, headers: :first_row).each do |line|
name = line['PROFILE_DESCRIPTION'] || line['ROLE_DESCRIPTION']
code = line['PROFILE_CODE'] || line['ROLE_CODE']
@profiles << { name: name, code: code }
end
rescue CSV::MalformedCSVError
raise "CSV::MalformedCSVError: #{response}"
end
end
end
@profiles
end
def get_params(raw_params, options = {})
params = Hash[raw_params.split('&').map { |p| p.split('=') }]
replaced_params = {}
params.each do |k, v|
if v == '$ACCOUNT$'
replaced_params[k] = org_account.token.blank? ? org_account.username : ''
end
if v == '$PASSWORD$'
replaced_params[k] = org_account.token.blank? ? org_account.password : ''
end
replaced_params[k] = options[:profile] if options[:profile] && v == '$PROFILE$'
replaced_params[k] = options[:datefrom] if options[:datefrom] && v == '$DATEFROM$'
replaced_params[k] = options[:dateto] if options[:dateto].present? && v == '$DATETO$'
replaced_params[k] = options[:personid].to_s if options[:personid].present? && v == '$PERSONIDS$'
end
unless org_account.token.blank?
params['client_id'] = ENV.fetch('DONORHUB_CLIENT_ID')
params['client_secret'] = ENV.fetch('DONORHUB_CLIENT_SECRET')
params['client_instance'] = 'app'
params['oauth_token'] = org_account.token
end
replaced_params.merge!(params.slice(*(params.keys - replaced_params.keys)))
replaced_params
end
def get_response(url, params)
request_params = {
method: :post,
url: url,
payload: params,
timeout: 600,
user: u(org_account.username),
password: u(<PASSWORD>)
}
Rails.logger.debug(request_params)
RestClient::Request.execute(request_params) do |response, _request, _result, &_block|
raise_if_error_code(response)
handle_ok_response(response)
end
rescue OpenSSL::SSL::SSLError => e
raise DataServerError,
format('Could not securely connect to host %p. Reason: %s',
URI(url).host, e)
end
def raise_if_error_code(response)
code = response.code
case code
when 403 then
raise_invalid_credentials
when 404 then
raise_missing_credentials
when 500 then
raise DataServerError, response
end
end
def handle_ok_response(response)
response = EncodingUtil.normalized_utf8(response.to_str)
# check for error response
lines = response.split(/\r?\n|\r/)
first_line = lines.first.to_s.upcase
first_two_lines = first_line + lines[1].to_s
# provid?ed is necessary because there is a typo in the error message
invalid_creds_errors = ['password', 'not registered', 'not authorized',
'oauth_token is not recognized', 'oauth_token is expired',
'No client_id was provid?ed']
invalid_creds_regex = Regexp.new invalid_creds_errors.join('|'), true
if first_two_lines =~ invalid_creds_regex
raise_invalid_credentials
elsif first_two_lines =~ /not found/i
raise_missing_credentials
elsif first_two_lines =~ /Timeout expired/i
# if we encounter a network timeout, retry but don't alert rollbar
raise LowerRetryWorker::RetryJobButNoRollbarError
elsif first_line.include?('ERROR') || first_line.include?('HTML')
raise DataServerError, response
end
# look for a redirect
raise Errors::UrlChanged, lines[1].split('=')[1] if lines[1]&.include?('RedirectQueryIni')
response
end
def raise_invalid_credentials
org_account.update_column(:valid_credentials, false) if org_account.valid_credentials? && !org_account.new_record?
raise Person::OrganizationAccount::InvalidCredentialsError,
format(_('Your credentials for %{org} are invalid.'), org: org)
end
def raise_missing_credentials
raise Person::OrganizationAccount::MissingCredentialsError,
_('Your credentials are missing for this account.')
end
def add_or_update_primary_contact(account_list, line, donor_account)
remote_id = "#{donor_account.account_number}-1"
add_or_update_person(account_list, line, donor_account, remote_id, '')
end
def add_or_update_spouse(account_list, line, donor_account)
remote_id = "#{donor_account.account_number}-2"
add_or_update_person(account_list, line, donor_account, remote_id, 'SP_')
end
def add_or_update_person(account_list, line, donor_account, remote_id, prefix = '')
org = donor_account.organization
master_person_from_source = org.master_people.find_by('master_person_sources.remote_id' => remote_id.to_s)
contact = donor_account.link_to_contact_for(account_list)
if master_person_from_source
person = donor_account.people
.joins(:contacts)
.where(master_person_id: master_person_from_source.id)
.where('contacts.account_list_id' => account_list.id)
.readonly(false)
.first
end
person ||= contact.people.find_by(first_name: line[prefix + 'FIRST_NAME'], last_name: line[prefix + 'LAST_NAME'])
person ||= donor_account.people.find_by(master_person_id: master_person_from_source.id) if master_person_from_source
person ||= Person.new(master_person: master_person_from_source)
person.attributes = { first_name: line[prefix + 'FIRST_NAME'],
last_name: line[prefix + 'LAST_NAME'],
middle_name: line[prefix + 'MIDDLE_NAME'],
title: line[prefix + 'TITLE'],
suffix: line[prefix + 'SUFFIX'],
gender: prefix.present? ? 'female' : 'male' }
# Make sure spouse always has a last name
person.last_name = line['LAST_NAME'] if person.last_name.blank?
# Phone numbers
if line[prefix + 'PHONE'].present? && line[prefix + 'PHONE'] != line[prefix + 'MOBILE_PHONE']
person.phone_number = { 'number' => line[prefix + 'PHONE'] }
end
if line[prefix + 'MOBILE_PHONE'].present?
person.phone_number = { 'number' => line[prefix + 'MOBILE_PHONE'], 'location' => 'mobile' }
end
# email address
if line[prefix + 'EMAIL'] && line[prefix + 'EMAIL_VALID'] != 'FALSE'
email = line[prefix + 'EMAIL'].downcase
unless person.email_addresses.exists?(email: email)
person.email_address = { email: email, primary: true, source: 'DataServer' }
end
end
person.master_person_id ||= MasterPerson.find_or_create_for_person(person, donor_account: donor_account).try(:id)
person.save(validate: false)
donor_account.people << person unless donor_account.people.include?(person)
unless donor_account.master_people.include?(person.master_person)
donor_account.master_people << person.master_person
end
contact = account_list.contacts.for_donor_account(donor_account).first
contact_person = contact.add_person(person, donor_account)
# create the master_person_source if needed
unless master_person_from_source
Retryable.retryable do
org.master_person_sources
.where(remote_id: remote_id.to_s)
.first_or_create(master_person_id: person.master_person.id)
end
end
[person, contact_person]
end
def add_or_update_company(account_list, user, line, donor_account)
master_company = MasterCompany.find_by(name: line['LAST_NAME_ORG'])
company = user.partner_companies.find_by(master_company_id: master_company.id) if master_company
company ||= account_list.companies.new(master_company: master_company)
company.assign_attributes(
name: line['LAST_NAME_ORG'],
phone_number: line['PHONE'],
street: [line['ADDR1'], line['ADDR2'], line['ADDR3'], line['ADDR4']].select(&:present?).join("\n"),
city: line['CITY'],
state: line['STATE'],
postal_code: line['ZIP'],
country: line['CNTRY_DESCR']
)
company.save!
unless donor_account.master_company_id == company.master_company.id
donor_account.update_attributes(master_company_id: company.master_company_id)
end
company
end
def add_or_update_donor_account(line, profile, account_list = nil)
account_list ||= profile.account_list
donor_account = Retryable.retryable do
donor_account = org.donor_accounts.where(account_number: line['PEOPLE_ID']).first_or_initialize
# if the acccount already existed, update the name
donor_account.attributes = { name: line['ACCT_NAME'],
donor_type: line['PERSON_TYPE'] == 'P' ? 'Household' : 'Organization' }
# physical address
address_fields = [
line['ADDR1'], line['ADDR2'], line['ADDR3'], line['ADDR4'], line['CITY'], line['STATE'], line['ZIP'],
line['CNTRY_DESCR']
]
if address_fields.any?(&:present?)
donor_account.addresses_attributes = [{
street: [line['ADDR1'], line['ADDR2'], line['ADDR3'], line['ADDR4']].select(&:present?).join("\n"),
city: line['CITY'],
state: line['STATE'],
postal_code: line['ZIP'],
country: line['CNTRY_DESCR'],
source: 'DataServer',
start_date: parse_date(line['ADDR_CHANGED']),
primary_mailing_address: donor_account.addresses.find_by(primary_mailing_address: true).blank?
}]
end
donor_account.save!
donor_account
end
contact = donor_account.link_to_contact_for(account_list)
raise 'Failed to link to contact' unless contact
DataServer::ContactAddressUpdate.new(contact, donor_account).update_from_donor_account
donor_account
end
def find_or_create_designation_account(number, profile, extra_attributes = {})
@designation_accounts ||= {}
unless @designation_accounts.key?(number)
da = Retryable.retryable do
org.designation_accounts.where(designation_number: number).first_or_create
end
profile.designation_accounts << da unless profile.designation_accounts.include?(da)
da.update_attributes(extra_attributes) if extra_attributes.present?
@designation_accounts[number] = da
end
@designation_accounts[number]
end
def add_or_update_donation(line, designation_account, profile)
default_currency = org.default_currency_code || 'USD'
donor_account = add_or_update_donor_account(line, profile)
Retryable.retryable do
date = line['DISPLAY_DATE'] ? Date.strptime(line['DISPLAY_DATE'], '%m/%d/%Y') : nil
attributes = {
amount: line['AMOUNT'],
currency: default_currency,
designation_account_id: designation_account.id,
donation_date: date,
donor_account_id: donor_account.id,
memo: line['MEMO'],
motivation: line['MOTIVATION'],
payment_method: line['PAYMENT_METHOD'],
remote_id: line['DONATION_ID'],
tendered_amount: line['TENDERED_AMOUNT'].presence || line['AMOUNT'],
tendered_currency: line['TENDERED_CURRENCY'].presence || default_currency
}
donation =
DonationImports::Base::FindDonation.new(
designation_profile: profile,
attributes: attributes
).find_and_merge
donation ||= Donation.new
donation.update!(attributes)
donation
end
end
def update_url(url)
proc do |exception, _handler, _attempts, _retries, _times|
org.update_attributes(url => exception.message)
end
end
# Data server supports two date formats, try both of those
def parse_date(date_obj)
return if date_obj.blank?
return date_obj if date_obj.is_a?(Date)
return date_obj.to_date if date_obj.is_a?(Time)
Date.strptime(date_obj, '%m/%d/%Y')
rescue ArgumentError
begin
Date.strptime(date_obj, '%Y-%m-%d')
rescue ArgumentError
end
end
def report_invalid_import_person_type(line)
person_type = line['PERSON_TYPE']
Rollbar.error(
"Unknown PERSON_TYPE: #{line['PERSON_TYPE']}",
parameters: {
line: line,
org: org.inspect,
user: org_account.person.inspect,
org_account: org_account.inspect
}
) unless KNOWN_DIFFERING_IMPORT_PERSON_TYPES.include?(person_type) || person_type.to_s.empty?
end
end
class DataServerError < StandardError
end
|
chuckmersereau/api_practice
|
app/services/designation_account/dup_by_balance_fix.rb
|
class DesignationAccount::DupByBalanceFix
class << self
# This should take a scoped activerecord relation for the designation
# accounts to deactivate by dup balance, i.e. the designation_accounts for
# an account list
def deactivate_dups(designation_accounts)
any_account_deactivated = false
accounts_by_balance(designation_accounts).each do |_balance, accounts|
# Deactivate all but the first designation account for a balance group
accounts[1..-1].each do |da|
da.update!(active: false, balance: 0)
any_account_deactivated = true
end
end
any_account_deactivated
end
private
def accounts_by_balance(designation_accounts)
ordered_designations(designation_accounts).group_by(&:balance)
end
def ordered_designations(designation_accounts)
designation_accounts.where.not(balance: nil).where.not(balance: 0.0)
.order("CASE WHEN name LIKE '% and %' THEN 0 ELSE 1 END")
.order(created_at: :desc).to_a
end
end
end
|
chuckmersereau/api_practice
|
app/models/person/facebook_account.rb
|
require 'async'
require 'retryable'
class Person::FacebookAccount < ApplicationRecord
include Person::Account
include Redis::Objects
include Async
include Sidekiq::Worker
sidekiq_options queue: :api_person_facebook_account, unique: :until_executed
PERMITTED_ATTRIBUTES = [:created_at,
:first_name,
:last_name,
:overwrite,
:remote_id,
:updated_at,
:updated_in_db_at,
:username,
:id].freeze
validates :username, presence: true, uniqueness: { scope: :person_id }
validates :remote_id, uniqueness: { scope: :person_id, allow_nil: true }
def self.find_or_create_from_auth(auth_hash, person)
relation_scope = person.facebook_accounts
remote_id = auth_hash['uid']
attributes = {
remote_id: remote_id,
token: auth_hash.credentials.token,
token_expires_at: Time.at(auth_hash.credentials.expires_at),
first_name: auth_hash.info.first_name,
last_name: auth_hash.info.last_name,
valid_token: true,
username: remote_id
}
find_or_create_person_account(
person: person,
attributes: attributes,
relation_scope: relation_scope
)
end
def self.create_user_from_auth(auth_hash)
attributes = {
first_name: auth_hash.info.first_name,
last_name: auth_hash.info.last_name
}
super(attributes)
end
def to_s
[first_name, last_name].join(' ')
end
def url
prefix = 'https://www.facebook.com/'
return prefix + "profile.php?id=#{remote_id}" if remote_id.to_i.positive?
prefix + username if username
end
def url=(value)
return unless value.present?
self.remote_id = self.class.id_from_url(value)
self.username = self.class.username_from_url(value) unless remote_id
end
def username=(value)
new_remote_id = self.class.id_from_url(value)
self.remote_id = new_remote_id if new_remote_id
super(self.class.username_from_url(value) || value)
end
def self.id_from_url(url)
return unless url.present? && url.include?('id=')
url.split('id=').last.split('&').first
end
def self.username_from_url(url)
return unless url.present? && url.include?('facebook.com/')
url.split('/').last.split('&').first
end
def queue_import_contacts(import)
async(:import_contacts, import.id)
end
def token_missing_or_expired?(tries = 0)
# If we have an expired token, try once to refresh it
if tries.zero? && token && (!token_expires_at || token_expires_at < Time.now)
begin
refresh_token
rescue StandardError; end
token_missing_or_expired?(1)
else
token.blank? || !token_expires_at || token_expires_at < Time.now
end
end
def refresh_token
info = Koala::Facebook::OAuth.new(ENV.fetch('FACEBOOK_KEY'), ENV.fetch('FACEBOOK_SECRET')).exchange_access_token_info(token)
self.token = info['access_token']
begin
self.token_expires_at = Time.at(info['expires'].to_i)
rescue StandardError => e
raise e.message + ': ' + info.inspect
end
save
end
def self.search(user, params)
account = user.facebook_accounts.first
return [] unless account
FbGraph::User.search(params.slice(:first_name, :last_name).values.join(' '), access_token: account.token)
end
private
def import_contacts(import_id)
import = Import.find(import_id)
FacebookImport.new(self, import).import_contacts
ensure
update_column(:downloading, false)
end
end
|
chuckmersereau/api_practice
|
lib/batch_request_handler/batch_request.rb
|
module BatchRequestHandler
class BatchRequest
InvalidBatchRequestError = Class.new(StandardError)
attr_reader :requests, :params
def initialize(env)
request_body = parse_batch_request_object(env)
@env = env
@requests = request_body.fetch('requests')
@params = request_body.except('requests').freeze
@instruments = []
@responses = []
rescue KeyError, JSON::ParserError
raise InvalidBatchRequestError
end
def add_instrumentation(instrument_class)
@instruments << instrument_class.new(@params) if instrument_class.enabled_for?(self)
end
def process(app)
perform_requests!(app)
build_response!
end
private
def perform_requests!(app)
@responses = instrument(:around_perform_requests, @requests) do |requests|
requests.map do |request|
perform_request!(app, request)
end
end
end
def perform_request!(app, request)
new_env = build_env_for_request(@env, request)
instrument(:around_perform_request, new_env) do |instrumented_env|
app.call(instrumented_env)
end
end
def build_response!
json_responses = @responses.map { |response| response_to_json(response) }
instrument(:around_build_response, json_responses) do |json|
response_body = JSON.dump(json)
[200, { 'Content-Type' => 'application/json' }, [response_body]]
end
end
# `instrument` is responsible for making sure that all of the
# instrumentation classes get called. It takes the method name to call on
# the instrument class, the arguments to pass to the method, and the block.
# It reduces all of the instruments methods into a nested proc.
def instrument(method, *yielded_arguments, &block)
instrumented_block = @instruments.reverse.reduce(block) do |inner_block, instrument|
-> (*yielded_args) { instrument.send(method, *yielded_args, &inner_block) }
end
instrumented_block.call(*yielded_arguments)
end
def parse_batch_request_object(env)
body = env['rack.input'].read
JSON.parse(body)
end
def build_env_for_request(env, request)
body = request.fetch('body', '')
body = coerce_body_to_string(body)
env.deep_dup.tap do |new_env|
new_env['BATCH_REQUEST'] = true
new_env['REQUEST_METHOD'] = request['method']
new_env['PATH_INFO'] = request['path']
new_env['CONTENT_LENGTH'] = body.bytesize
new_env['rack.input'] = StringIO.new(body)
end
end
def coerce_body_to_string(body)
case body
when String then body
else
JSON.dump(body)
end
end
def response_to_json(response)
status, headers, body_proxy = response
body = ''
body_proxy.each { |chunk| body << chunk }
body_proxy.close if body_proxy.respond_to?(:close)
{
status: status,
headers: headers,
body: body
}
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20121223145052_add_remote_id_to_contact_methods.rb
|
<reponame>chuckmersereau/api_practice
class AddRemoteIdToContactMethods < ActiveRecord::Migration
def change
add_column :addresses, :remote_id, :string
add_column :email_addresses, :remote_id, :string
add_column :phone_numbers, :remote_id, :string
add_index :addresses, :remote_id
add_index :email_addresses, :remote_id
add_index :phone_numbers, :remote_id
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/user/organization_accounts_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::User::OrganizationAccountsController, type: :controller do
let(:user) { create(:user) }
let(:factory_type) { :organization_account }
let!(:resource) { create(:organization_account, person: user) }
let!(:second_resource) { create(:organization_account, person: user, created_at: 1.week.from_now) }
let(:id) { resource.id }
let(:unpermitted_relationships) do
{
person: {
data: {
type: 'people',
id: create(:user).id
}
},
organization: {
data: {
type: 'organizations',
id: create(:organization).id
}
}
}
end
let(:correct_attributes) do
{ username: 'random_username', password: '<PASSWORD>' }
end
let(:correct_relationships) do
{
person: {
data: {
type: 'people',
id: user.id
}
},
organization: {
data: {
type: 'organizations',
id: create(:organization).id
}
}
}
end
let(:incorrect_attributes) { nil }
before do
allow_any_instance_of(DataServer).to receive(:validate_credentials).and_return(true)
allow_any_instance_of(Person::OrganizationAccount).to receive(:set_up_account_list)
end
include_examples 'show_examples'
include_examples 'update_examples'
include_examples 'create_examples'
include_examples 'destroy_examples'
include_examples 'index_examples'
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/coaching/account_lists_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::Coaching::AccountListsController, type: :controller do
let(:resource_type) { 'account_lists' }
let(:factory_type) { :account_list }
let!(:user) { create(:user, locale: :en) }
let!(:owner) { create(:user_with_account) }
let!(:coaches) { create_list(:user_coach, 2) }
let!(:account_list) { owner.account_lists.order(:created_at).first }
let!(:account_list_2) { create(:account_list, created_at: 1.week.from_now) }
let(:account_list_id) { account_list.id }
let(:id) { account_list.id }
before do
[account_list, account_list_2].each do |list|
list.coaches += coaches
list.coaches << user.becomes(User::Coach)
end
end
let(:resource) { account_list }
let(:correct_attributes) { attributes_for(:account_list) }
include_examples 'index_examples'
include_examples 'show_examples'
end
|
chuckmersereau/api_practice
|
spec/seeders/application_seeder_spec.rb
|
require 'rails_helper'
describe ApplicationSeeder do
let!(:seeder) { ApplicationSeeder.new }
it 'seeds all models without error' do
expect(seeder.all_models_seeded?).to be_falsey
expect { seeder.seed }.to_not raise_error
seeder.quiet = false # Print out missing seeds.
expect(seeder.all_models_seeded?).to be_truthy, "If you've created a new model, please make "\
'sure that you add a corresponding factory, '\
"and add your seeds to #{described_class}"
end
context 'staging env' do
before do
allow(Rails).to receive(:env).and_return('staging')
end
it 'fails to run' do
expect { seeder.seed }.to raise_exception RuntimeError
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/contact_notes_logs.rb
|
<reponame>chuckmersereau/api_practice
FactoryBot.define do
factory :contact_notes_log do
association :contact
recorded_on '2016-11-30 14:20:20 -0500'
notes 'Notes'
end
end
|
chuckmersereau/api_practice
|
app/services/account_list/pledges_total.rb
|
<filename>app/services/account_list/pledges_total.rb
class AccountList::PledgesTotal
attr_accessor :account_list, :contacts, :rates
def initialize(account_list, contacts)
@account_list = account_list
@contacts = contacts
@rates = {}
end
def total
total_usd = contacts.map(&method(:monthly_pledge_usd)).sum
(total_usd * default_currency_rate).round(2)
end
def default_currency_rate
latest_rate(account_list.salary_currency_or_default)
end
def monthly_pledge_usd(partner)
partner.monthly_pledge / latest_rate(partner.pledge_currency)
end
def latest_rate(currency)
return 1 if currency == 'USD'
rates[currency] ||= find_latest_rate(currency)
end
def find_latest_rate(currency)
rate = CurrencyRate.where(code: currency).order(exchanged_on: :desc).limit(1).first
rate ? rate.rate : 1
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/likely_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::Likely do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id, likely_to_give: 'Least Likely') }
let!(:contact_two) { create(:contact, account_list_id: account_list.id, likely_to_give: 'Likely') }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, likely_to_give: 'Most Likely') }
let!(:contact_four) { create(:contact, account_list_id: account_list.id, likely_to_give: nil) }
describe '#config' do
it 'returns expected config' do
options = [{ name: '-- Any --', id: '', placeholder: 'None' },
{ name: '-- None --', id: 'none' },
{ name: 'Least Likely', id: 'Least Likely' },
{ name: 'Likely', id: 'Likely' },
{ name: 'Most Likely', id: 'Most Likely' }]
expect(described_class.config([account_list])).to include(multiple: true,
name: :likely,
options: options,
parent: 'Contact Details',
title: 'Likely To Give',
type: 'multiselect',
default_selection: '')
end
end
describe '#query' do
let(:contacts) { Contact.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(contacts, {}, nil)).to eq(nil)
expect(described_class.query(contacts, { referrer: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { referrer: [] }, nil)).to eq(nil)
end
end
context 'filter by no likely to give' do
it 'returns only contacts that have no likely to give' do
expect(described_class.query(contacts, { likely: 'none' }, nil).to_a).to eq [contact_four]
end
end
context 'filter by likely to give' do
it 'filters multiple likely to give' do
result = described_class.query(contacts, { likely: 'Least Likely, Likely' }, nil).to_a
expect(result).to match_array [contact_one, contact_two]
end
it 'filters a single likely to give' do
expect(described_class.query(contacts, { likely: 'Most Likely' }, nil).to_a).to eq [contact_three]
end
end
context 'multiple filters' do
it 'returns contacts matching multiple filters' do
result = described_class.query(contacts, { likely: 'none, Most Likely, Likely' }, nil).to_a
expect(result).to match_array [contact_two, contact_three, contact_four]
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/admin/impersonation_log.rb
|
class Admin::ImpersonationLog < ApplicationRecord
belongs_to :impersonator, foreign_key: :impersonator_id, class_name: 'User'
belongs_to :impersonated, foreign_key: :impersonated_id, class_name: 'User'
end
|
chuckmersereau/api_practice
|
spec/services/csv_value_to_constant_mappings_spec.rb
|
<filename>spec/services/csv_value_to_constant_mappings_spec.rb
require 'rails_helper'
describe CsvValueToConstantMappings do
let(:file_constants_mappings) do
{
'status' => [
{ 'id' => 'Partner - Financial', 'values' => ['Praying and giving'] },
{ 'id' => 'What', 'values' => ['Just praying'] },
{ 'id' => '', 'values' => [''] }
],
'pledge_frequency' => [
{ 'id' => 'Monthly', 'values' => ['Monthly'] },
{ 'id' => '12.0', 'values' => ['Annual'] }
],
'newsletter' => [
{ 'id' => 'Both', 'values' => %w(Both Anything) }
]
}
end
subject { described_class.new(file_constants_mappings) }
it 'initializes' do
expect(described_class.new({})).to be_a(described_class)
end
describe '#constant_names' do
it 'returns the header ids' do
expect(subject.constant_names).to eq(%w(status pledge_frequency newsletter))
end
end
describe '#convert_value' do
it 'converts expected values' do
expect(subject.convert_value_to_constant_id('status', 'Praying and giving')).to eq('Partner - Financial')
expect(subject.convert_value_to_constant_id('status', '')).to eq(nil)
expect(subject.convert_value_to_constant_id('pledge_frequency', 'Monthly')).to eq(1.0)
expect(subject.convert_value_to_constant_id('pledge_frequency', '')).to eq(nil)
expect(subject.convert_value_to_constant_id('newsletter', 'Anything')).to eq('Both')
end
end
describe '#find_unsupported_constants' do
it 'finds expected values that are unsupported' do
expect(subject.find_unsupported_constants('status')).to eq(['What'])
expect(subject.find_unsupported_constants('pledge_frequency')).to eq(['12.0'])
expect(subject.find_unsupported_constants('newsletter')).to eq([])
end
end
describe '#find_mapped_values' do
it 'finds expected values that are mapped' do
expect(subject.find_mapped_values('status')).to eq(['Praying and giving', 'Just praying', ''])
expect(subject.find_mapped_values('pledge_frequency')).to eq(%w(Monthly Annual))
expect(subject.find_mapped_values('newsletter')).to eq(%w(Both Anything))
end
end
end
|
chuckmersereau/api_practice
|
app/models/google_contact.rb
|
class GoogleContact < ApplicationRecord
belongs_to :person
belongs_to :contact
belongs_to :google_account, class_name: 'Person::GoogleAccount'
belongs_to :picture
serialize :last_data, Hash
end
|
chuckmersereau/api_practice
|
db/migrate/20121115201514_add_notification_id_to_activity.rb
|
class AddNotificationIdToActivity < ActiveRecord::Migration
def change
add_column :activities, :notification_id, :integer
add_index :activities, :notification_id
end
end
|
chuckmersereau/api_practice
|
app/preloaders/api/v2/account_lists/donor_accounts_preloader.rb
|
class Api::V2::AccountLists::DonorAccountsPreloader < ApplicationPreloader
ASSOCIATION_PRELOADER_MAPPING = {}.freeze
FIELD_ASSOCIATION_MAPPING = {}.freeze
end
|
chuckmersereau/api_practice
|
app/serializers/donor_account_serializer.rb
|
<reponame>chuckmersereau/api_practice
class DonorAccountSerializer < ApplicationSerializer
attributes :account_number,
:donor_type,
:first_donation_date,
:last_donation_date,
:total_donations,
:display_name
belongs_to :organization
has_many :contacts
def display_name
return object.account_number if name.blank?
return name if object.account_number.blank? || name.include?(object.account_number)
"#{name} (#{object.account_number})"
end
def contacts
return object.contacts.none unless scope && scope[:account_list]
object.contacts.where(account_list: scope[:account_list])
end
protected
def name
return @name if @name
@name = if scope && scope[:account_list] && object.name?
object.link_to_contact_for(scope[:account_list]).name
elsif object.name?
object.name
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/donation_amount_recommendations_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contact > DonationAmountRecommendations' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:contacts, :donation_amount_recommendations])
let(:resource_type) { 'donation_amount_recommendations' }
let!(:user) { create(:user_with_full_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:contact) { create(:contact, account_list: account_list) }
let(:contact_id) { contact.id }
let!(:organization) { create :organization }
let!(:designation_account) { create :designation_account, organization: organization }
let!(:donor_account) { create :donor_account, organization: organization }
let!(:donation_amount_recommendation) do
create(
:donation_amount_recommendation,
designation_account: designation_account,
donor_account: donor_account
)
end
let(:id) { donation_amount_recommendation.id }
before do
contact.donor_accounts << donor_account
end
let(:additional_attributes) do
%w(
created_at
updated_at
updated_in_db_at
)
end
let(:additional_keys) do
%w(
relationships
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/contacts/:contact_id/donation_amount_recommendations' 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
expect(response_status).to eq(200), invalid_status_detail
check_collection_resource(1, additional_keys)
end
end
get '/api/v2/contacts/:contact_id/donation_amount_recommendations/: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(additional_keys, additional_attributes)
expect(resource_object['started_at']).to eq donation_amount_recommendation.started_at
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160627171818_add_gift_aid_to_organization.rb
|
class AddGiftAidToOrganization < ActiveRecord::Migration
def change
add_column :organizations, :gift_aid_percentage, :decimal
end
end
|
chuckmersereau/api_practice
|
spec/services/reports/pledge_histories_spec.rb
|
require 'rails_helper'
RSpec.describe Reports::PledgeHistories, type: :model do
let(:account_list) { create(:account_list) }
subject { described_class.new(account_list: account_list, filter_params: {}) }
describe 'initializes' do
it 'initializes successfully' do
expect(subject).to be_a(described_class)
expect(subject.account_list).to eq account_list
end
it 'sets defaults' do
expect(subject.range).to eq '13m'
expect(subject.end_date).to eq Date.today
end
end
describe '#periods_data' do
context 'range of 2m' do
before { subject.filter_params[:range] = '2m' }
around(:example) do |example|
travel_to DateTime.new(2018, 4, 12, 12, 0, 0).getlocal, &example
end
it 'creates two month-long periods' do
expect(Reports::PledgeHistoriesPeriod).to receive(:new).with(
account_list: account_list,
start_date: Date.new(2018, 3, 1).beginning_of_day,
end_date: Date.new(2018, 3, 31).end_of_day
)
expect(Reports::PledgeHistoriesPeriod).to receive(:new).with(
account_list: account_list,
start_date: Date.new(2018, 4, 1).beginning_of_day,
end_date: Date.new(2018, 4, 30).end_of_day
)
subject.periods_data
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20171006024505_create_wv_donation_amt_recommendation.rb
|
<filename>db/migrate/20171006024505_create_wv_donation_amt_recommendation.rb
# This table is being created for Test and Development Environments
# On Prod there is a view being added to the database
class CreateWvDonationAmtRecommendation < ActiveRecord::Migration
def change
unless ActiveRecord::Base.connection.table_exists? 'wv_donation_amt_recommendation'
create_table :wv_donation_amt_recommendation, id: false do |t|
t.integer :organization_id
t.string :donor_number
t.string :designation_number
t.decimal :previous_amount
t.decimal :amount
t.timestamp :started_at
t.decimal :gift_min
t.decimal :gift_max
t.decimal :income_min
t.decimal :income_max
t.decimal :suggested_pledge_amount
t.timestamp :ask_at
t.string :zip_code
t.timestamps null: false
end
end
end
end
|
chuckmersereau/api_practice
|
dev/rails_c_funcs.rb
|
<filename>dev/rails_c_funcs.rb
# All of the methods in the dev folder are intended to be run from "rails c"
# to help debugging and fixing user issues.
# By default all *_util.rb files in the util folder are loaded
Dir['./dev/util/*_util.rb'].each { |file| load file }
# Other files such as those in dev/migrate or dev/fixers can be loaded manually
# The migrate folder is for processes that are run to transform the data in some
# way that would be more complicated than a typical Rails migration e.g. to run
# a process to set some type of computed default values for a column before
# deploying code that will display that column.
# The fixers folder is intended for more specialized or complex fixes for
# specific users. They may end up being useful for fixing other user accounts
# but because of their specific nature to that user they might not be applicable
# to as wide a range of cases to warrant moving to the util folder to be
# auto-loaded.
|
chuckmersereau/api_practice
|
db/migrate/20170109220413_change_task_newsletters_to_newsletters_physical.rb
|
class ChangeTaskNewslettersToNewslettersPhysical < ActiveRecord::Migration
def up
Task.of_type('Newsletter').update_all(activity_type: 'Newsletter - Physical')
end
def down
Task.of_type('Newsletter - Physical').update_all(activity_type: 'Newsletter')
end
end
|
chuckmersereau/api_practice
|
lib/json_api_service/params_object.rb
|
<filename>lib/json_api_service/params_object.rb
require 'active_support/hash_with_indifferent_access'
require 'json_api_service/object_store'
require 'json_api_service/data_object'
module JsonApiService
class ParamsObject
attr_reader :data,
:data_params,
:included_data,
:included_params,
:non_json_api_params,
:params,
:store
def initialize(params:, store: ObjectStore.new)
@data = nil
@included_data = []
@params = params.deep_symbolize_keys
@data_params = @params[:data] || {}
@included_params = @params[:included] || []
@non_json_api_params = @params.except(:data, :included)
@store = store
after_initialize
end
def to_h
return {} if params.empty?
{
data: data.to_h
}.merge(non_json_api_params)
end
private
def after_initialize
included_params.each do |included_data|
DataObject.new(included_data, store: store)
end
@data = DataObject.new(data_params, store: store)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/expected_totals_report/google_import_spec.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/services/expected_totals_report/google_import_spec.rb
require 'rails_helper'
describe GoogleImport do
let!(:user) { create(:user) }
let!(:account) { create(:google_account, person_id: user.id) }
let!(:account_list) { create(:account_list, creator: user) }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:import) do
create(:import, source: 'google', source_account_id: account.id, account_list: account_list, user: user)
end
subject! { GoogleImport.new(import) }
before do
stub_g_contacts('spec/fixtures/google_contacts.json')
stub_g_contact_photo
stub_smarty_and_cloudinary
end
def stub_g_contacts(file)
stub_request(:get, 'https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=100000&v=3')
.with(headers: { 'Authorization' => "Bearer #{account.token}" })
.to_return(body: File.new(Rails.root.join(file)).read)
end
def stub_g_contact_photo
stub_request(:get, 'https://www.google.com/m8/feeds/photos/media/test.user@cru.org/6b70f8bb0372c?v=3')
.with(headers: { 'Authorization' => "Bearer #{account.token}" })
.to_return(body: 'photo data', headers: { 'content-type' => 'image/jpeg' })
end
def stub_smarty_and_cloudinary
stub_request(:get, %r{https://api\.smartystreets\.com/street-address/.*}).to_return(body: '[]')
# Based on sample from docs at http://cloudinary.com/documentation/upload_images
cloudinary_reponse = {
url: "http://res.cloudinary.com/#{ENV.fetch('CLOUDINARY_CLOUD_NAME')}/image/upload/v1/img.jpg",
secure_url: "https://res.cloudinary.com/#{ENV.fetch('CLOUDINARY_CLOUD_NAME')}/image/upload/v1/img.jpg",
public_id: 'img',
version: '1',
width: 864,
height: 564,
format: 'jpg',
resource_type: 'image',
signature: 'abcdefgc024acceb1c5baa8dca46797137fa5ae0c3'
}.to_json
stub_request(:post, %r{https://api\.cloudinary\.com/v1_1/.*/auto/upload}).to_return(body: cloudinary_reponse)
end
describe 'when importing contacts' do
it 'matches an existing person on my list' do
person = create(:person)
contact.people << person
expect do
expect(subject).to receive(:create_or_update_person).and_return(person)
subject.import
end.to_not change(Contact, :count)
end
it 'creates a new contact for someone not on my list and ignore contact without first name' do
# note the json file has a blank contact record which should be ignored, so the count changes by 1 only
expect do
expect do
expect(subject).to receive(:create_or_update_person).and_return(create(:person))
subject.import
end.to change(Person, :count).by(1)
end.to change(Contact, :count).by(1)
end
it 'adds tags from the import' do
expect(subject).to receive(:create_or_update_person).and_return(create(:person))
import.update_column(:tags, 'hi, mom')
subject.import
expect(Contact.order(:created_at).last.tag_list.sort).to eq(%w(hi mom))
end
end
describe 'create_or_update_person' do
let(:google_contact) do
OpenStruct.new(given_name: 'John', family_name: 'Doe',
emails_full: [], phone_numbers_full: [], organizations: [],
websites: [], id: Time.zone.now.to_i.to_s)
end
it 'updates the person if they already exist by google remote_id if override set' do
import.override = true
person = create(:person, first_name: 'Not-John')
create(:google_contact, person: person, remote_id: google_contact.id)
contact.people << person
expect do
subject.send(:create_or_update_person, google_contact)
expect(person.reload.first_name).to eq('John')
end.to_not change(Person, :count)
end
it 'does not create a new person if their name matches' do
contact.people << create(:person, first_name: 'John', last_name: 'Doe')
expect do
subject.send(:create_or_update_person, google_contact)
end.to_not change(Person, :count)
end
it "creates a person and master person if we can't find a match" do
expect do
expect do
subject.send(:create_or_update_person, google_contact)
end.to change(Person, :count)
end.to change(MasterPerson, :count)
end
end
describe 'spouse import' do
def stub_g_contacts_with_spouse(spouse)
file = 'spec/fixtures/google_contacts.json'
json = JSON.parse(File.new(Rails.root.join(file)).read)
json['feed']['entry'][0]['gContact$relation'] = [{ 'rel' => 'spouse', '$t' => spouse }]
stub_request(:get, 'https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=100000&v=3')
.with(headers: { 'Authorization' => "Bearer #{account.token}" })
.to_return(body: json.to_json)
end
it 'does not import a spouse if none specified' do
subject.import
contact = Contact.find_by(name: '<NAME>')
expect(contact.people.count).to eq(1)
end
def import_and_expect_names(contact_name, person1_name, person2_name)
subject.import
contact = Contact.find_by(name: contact_name)
people_names = contact.people.map { |p| [p.first_name, p.last_name] }
expect(people_names.size).to eq(2)
expect(people_names).to include(person1_name)
expect(people_names).to include(person2_name)
end
it 'imports a spouse with a first name and assumes same last name' do
stub_g_contacts_with_spouse('Jane')
import_and_expect_names('Google, John and Jane', %w(John Google), %w(Jane Google))
end
it 'imports a spouse with a different last name' do
stub_g_contacts_with_spouse('<NAME>')
import_and_expect_names('Google, John and Jane (Smith)', %w(<NAME>), %w(<NAME>))
end
it 'imports a spouse with a compound first name and a last name' do
stub_g_contacts_with_spouse('<NAME>')
import_and_expect_names('Google, John and <NAME> (Smith)', %w(<NAME>), ['<NAME>', 'Smith'])
end
it 'does not import spouse or change contact name if spouse person already exists in contact' do
contact.update(name: '<NAME>')
john = create(:person, first_name: 'John', last_name: 'Google')
jane = create(:person, first_name: 'Jane', last_name: 'Google', middle_name: 'Already there')
contact.people << john
contact.people << jane
stub_g_contacts_with_spouse('Jane')
subject.import
expect(Contact.count).to eq(1)
contact = Contact.first
expect(contact).to eq(contact)
expect(contact.people).to include(john)
expect(contact.people).to include(jane)
expect(contact.people.map(&:middle_name)).to include('Already there')
end
end
describe 'overall import results' do
# rubocop:disable Metrics/AbcSize
def check_imported_data
contacts = account_list.contacts.where(name: '<NAME>')
expect(contacts.to_a.size).to eq(1)
contact = contacts.first
expect(contact.people.count).to eq(1)
person = contact.people.first
expect(contact.people).to include(person)
expect(person.contacts).to include(contact)
expect(contact.name).to eq('Google, John')
expect(person.first_name).to eq('John')
expect(person.last_name).to eq('Google')
expect(person.middle_name).to eq('Henry')
expect(person.title).to eq('Mr.')
expect(person.suffix).to eq('III')
expect(person.birthday_year).to eq(1988)
expect(person.birthday_month).to eq(5)
expect(person.birthday_day).to eq(12)
expect(person.employer).to eq('Example, Inc')
expect(person.occupation).to eq('Worker Person')
expect(person.websites.to_a.size).to eq(2)
website1 = person.websites.order(:url).first
expect(website1.url).to eq('blog.example.com')
expect(website1.primary).to be false
website2 = person.websites.order(:url).last
expect(website2.url).to eq('www.example.com')
expect(website2.primary).to be true
expect(contact.notes).to eq('Notes here')
expect(contact.addresses.to_a.size).to eq(2)
address1 = contact.addresses.order(:postal_code).first
expect(address1.country).to eq('United States')
expect(address1.city).to eq('Somewhere')
expect(address1.street).to eq('2345 Long Dr. #232')
expect(address1.state).to eq('IL')
expect(address1.postal_code).to eq('12345')
expect(address1.primary_mailing_address).to be true
address2 = contact.addresses.order(:postal_code).last
expect(address2.country).to eq('United States')
expect(address2.city).to eq('Anywhere')
expect(address2.street).to eq('123 Big Rd')
expect(address2.state).to eq('MO')
expect(address2.postal_code).to eq('56789')
expect(person.email_addresses.to_a.size).to eq(1)
email = person.email_addresses.order(:email).first
expect(email.email).to eq('<EMAIL>')
expect(email.location).to eq('other')
expect(email.primary).to be true
expect(person.phone_numbers.to_a.size).to eq(1)
phone = person.phone_numbers.order(:number).first
expect(phone.number).to eq('+12133345158')
expect(phone.location).to eq('mobile')
expect(phone.primary).to be true
expect(person.pictures.count).to eq(1)
picture = person.pictures.first
expect(picture.image.url).to eq(
"https://res.cloudinary.com/#{ENV.fetch('CLOUDINARY_CLOUD_NAME')}/image/upload/v1/img.jpg"
)
expect(picture.primary).to be true
expect(person.google_contacts.count).to eq(1)
google_contact = person.google_contacts.first
expect(google_contact.google_account).to eq(account)
expect(google_contact.picture_etag).to eq('dxt2DAEZfCp7ImA-AV4zRxBoPG4UK3owXBM.')
expect(google_contact.picture).to eq(picture)
expect(google_contact.contact).to eq(contact)
end
it 'imports correct person data if no people exist and be the same for repeat imports' do
subject.import
check_imported_data
# Repeat the import and make sure the data is the same
subject.import
check_imported_data
end
it 'handles the case when the Google auth token cannot be refreshed' do
expect_any_instance_of(Person::GoogleAccount).to receive(:contacts_api_user)
.at_least(1).times.and_raise(Person::GoogleAccount::MissingRefreshToken)
expect { subject.import }.to raise_error(Import::UnsurprisingImportError)
expect(account_list.contacts.count).to eq(1)
end
end
describe 'import override/non-override behavior for primary contact info' do
let(:person) { build(:person, first_name: 'John', last_name: 'Google') }
before do
contact.addresses_attributes = [{
street: '1 Way', city: 'Town', state: 'IL', postal_code: '22222',
country: 'United States', location: 'Home', primary_mailing_address: true
}]
contact.save
person.email_address = { email: '<EMAIL>', primary: true }
person.phone_number = { number: '414-555-5555', primary: true }
person.save
Person::Website.create(url: 'original.example.com', primary: true, person: person)
contact.people << person
end
it 'makes imported phone/email/address primary if set to override (and marked as primary in imported data)' do
import.override = true
subject.import
contact.reload
expect(contact.primary_address.street).to eq('2345 Long Dr. #232')
person.reload
expect(person.primary_email_address.email).to eq('<EMAIL>')
expect(person.primary_phone_number.number).to eq('+12133345158')
expect(person.website.url).to eq('www.example.com')
end
it 'does not not make imported phone/email/address primary if not set to override' do
import.override = false
subject.import
contact.reload
expect(contact.primary_address.street).to eq('1 Way')
person.reload
expect(person.primary_email_address.email).to eq('<EMAIL>')
expect(person.primary_phone_number.number).to eq('+14145555555')
expect(person.website.url).to eq('original.example.com')
end
end
it 'assigns the last website a primary role if no websites existed before and none imported are marked as primary' do
person = create(:person, last_name: 'Doe')
contact.people << person
g_contact = double(websites: [{ href: 'example.com' }, { href: 'other.example.com' }])
subject.update_person_websites(person, g_contact)
person.reload
expect(person.websites.count).to eq(2)
website1 = person.websites.order(:url).first
expect(website1.url).to eq('example.com')
expect(website1.primary).to be false
website2 = person.websites.order(:url).last
expect(website2.url).to eq('other.example.com')
expect(website2.primary).to be true
end
describe 'import override behavior for basic fields' do
let!(:existing_contact) { create(:contact, account_list: account_list, notes: 'Original notes') }
let!(:existing_person) do
create(
:person, first_name: 'Not-John', last_name: 'Not-Doe',
middle_name: 'Not-Henry', title: 'Not-Mr', suffix: 'Not-III'
)
end
let!(:remote_id) { 'http://www.google.com/m8/feeds/contacts/test.user%40cru.org/base/6b70f8bb0372c' }
let!(:original_picture) { create(:picture, picture_of: existing_person, primary: true) }
before do
existing_person.google_contacts << create(:google_contact, remote_id: remote_id)
existing_person.pictures << original_picture
existing_contact.people << existing_person
end
it 'updates fields if set to override' do
import.override = true
subject.import
existing_person.reload
existing_contact.reload
expect(existing_contact.notes).to eq("Original notes \n \nNotes here")
expect(existing_person.first_name).to eq('John')
expect(existing_person.last_name).to eq('Google')
expect(existing_person.middle_name).to eq('Henry')
expect(existing_person.title).to eq('Mr.')
expect(existing_person.suffix).to eq('III')
original_picture.reload
expect(original_picture.primary).to be false
expect(existing_person.pictures.count).to eq(2)
expect(existing_person.primary_picture.image.url).to eq(
"https://res.cloudinary.com/#{ENV.fetch('CLOUDINARY_CLOUD_NAME')}/image/upload/v1/img.jpg"
)
end
it 'does not append the contact notes twice' do
import.override = true
subject.import
existing_contact.reload
expect(existing_contact.notes).to eq("Original notes \n \nNotes here")
subject.import
existing_contact.reload
expect(existing_contact.notes).to eq("Original notes \n \nNotes here")
end
it 'does not not update fields if not set to override (except for notes)' do
import.override = false
subject.import
existing_person.reload
existing_contact.reload
expect(existing_contact.notes).to eq("Original notes \n \nNotes here")
expect(existing_person.first_name).to eq('Not-John')
expect(existing_person.last_name).to eq('Not-Doe')
expect(existing_person.middle_name).to eq('Not-Henry')
expect(existing_person.title).to eq('Not-Mr')
expect(existing_person.suffix).to eq('Not-III')
original_picture.reload
# Check that it does add the picture but doesn't set it to primary
expect(original_picture.primary).to be true
expect(existing_person.pictures.count).to eq(2)
expect(existing_person.primary_picture.image.url).to be_nil
end
it 'updates notes fields if they were blank even if set to not override' do
existing_contact.update notes: ''
existing_person.pictures.first.destroy
import.override = false
subject.import
existing_person.reload
existing_contact.reload
expect(existing_contact.notes).to eq('Notes here')
expect(existing_person.pictures.count).to eq(1)
expect(existing_person.primary_picture.image.url).to eq(
"https://res.cloudinary.com/#{ENV.fetch('CLOUDINARY_CLOUD_NAME')}/image/upload/v1/img.jpg"
)
end
end
it "doesn't import a picture if the person has an associated facebook account" do
person = build(:person)
contact.people << person
create(:facebook_account, person: person)
subject.import
expect(person.pictures.count).to eq(0)
end
describe 'import by group' do
it 'does nothing if no groups specified' do
import.import_by_group = true
import.save
expect do
subject.import
end.to_not change(Contact, :count)
end
it 'imports a specified group' do
import.import_by_group = true
group_url = 'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/6'
import.groups = [group_url]
import.group_tags = {
'http://www.google.com/m8/feeds/groups/test.user%40cru.org/base/6' => 'more, tags'
}
import.tags = 'hi, mom'
import.save
stub_request(
:get,
'https://www.google.com/m8/feeds/contacts/default/full?alt=json&group='\
"#{URI.escape(group_url)}&max-results=100000&v=3"
)
.with(headers: { 'Authorization' => "Bearer #{account.token}" })
.to_return(body: File.new(Rails.root.join('spec/fixtures/google_contacts.json')).read)
.times(1)
expect do
subject.import
end.to change(Contact, :count).by(1)
expect(Contact.order(:created_at).last.tag_list.sort).to eq(%w(hi mom more tags))
end
it 'handles the case when the Google auth token cannot be refreshed' do
expect_any_instance_of(Person::GoogleAccount).to receive(:contacts_api_user)
.at_least(1).times.and_raise(Person::GoogleAccount::MissingRefreshToken)
expect { subject.import }.to raise_error(Import::UnsurprisingImportError)
expect(account_list.contacts.count).to eq(1)
end
end
describe 'import primary field default' do
it "assigns one arbitrary address/email/phone/website as primary if MPDX and Google didn't specify primary" do
WebMock.reset!
stub_g_contacts('spec/fixtures/google_contacts_no_primary.json')
stub_g_contact_photo
stub_smarty_and_cloudinary
stub_google_geocoder
import.override = false
subject.import
contact = account_list.contacts.where(name: '<NAME>').first
person = contact.people.first
expect(person.websites.to_a.size).to eq(2)
website1 = person.websites.order(:url).first
website2 = person.websites.order(:url).last
expect(website1.primary || website2.primary).to be true
expect(website1.primary && website2.primary).to be false
expect(contact.addresses.to_a.size).to eq(2)
address1 = contact.addresses.order(:postal_code).first
address2 = contact.addresses.order(:postal_code).last
expect(address1.primary_mailing_address || address1.primary_mailing_address).to be true
expect(address2.primary_mailing_address && address2.primary_mailing_address).to be false
expect(person.email_addresses.to_a.size).to eq(2)
email1 = person.email_addresses.order(:email).first
email2 = person.email_addresses.order(:email).last
expect(email1.primary || email1.primary).to be true
expect(email2.primary && email2.primary).to be false
expect(person.phone_numbers.to_a.size).to eq(2)
phone1 = person.phone_numbers.order(:number).first
phone2 = person.phone_numbers.order(:number).last
expect(phone1.primary || phone1.primary).to be true
expect(phone2.primary && phone2.primary).to be false
expect(person.pictures.count).to eq(1)
picture = person.pictures.first
expect(picture.primary).to be true
end
end
end
|
chuckmersereau/api_practice
|
spec/serializers/reports/goal_progress_serializer_spec.rb
|
require 'rails_helper'
describe Reports::GoalProgressSerializer do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:organization) { create(:organization) }
let(:object) { Reports::GoalProgress.new(account_list: account_list) }
subject { Reports::GoalProgressSerializer.new(object).as_json }
before do
account_list.salary_organization_id = organization.id
end
it 'serializes salary_organization_id' do
expect(subject[:salary_organization_id]).to eq organization.id
end
end
|
chuckmersereau/api_practice
|
app/models/pledge_donation.rb
|
class PledgeDonation < ApplicationRecord
belongs_to :pledge
belongs_to :donation
validates :donation_id, uniqueness: { scope: :pledge_id }
validates :pledge_id, uniqueness: { scope: :donation_id }
after_save :set_processed, if: :donation_id_changed?
after_destroy :set_processed
delegate :set_processed, to: :pledge, allow_nil: true
end
|
chuckmersereau/api_practice
|
lib/pundit_authorizer.rb
|
# This class was taken from a Pundit PR: https://github.com/elabs/pundit/pull/136/files
# The PR has not been merged into the current version of Pundit we're using, so the class was manually copied here instead.
# When Pundit is updated to include PunditAuthorizer then this file can be deleted.
# This is a stand alone authorizer without any
# dependency on controller.
#
# It is very useful on service object.
#
# Example usage:
#
# authorizer = PunditAuthorizer.new(user, post)
# authorizer.authorize_on 'create'
#
# Example on a service object
#
# class PostCreator
# attr_reader :user, :post
# def initialize(user, params)
# @user = user
# @post = Post.new(params)
# end
#
# def create
# authorize_post
# save_post
# process_things_after_save
# end
#
# def authorize_post
# authorizer = PunditAuthorizer.new(user, post)
# authorizer.authorize_on 'create'
# end
class PunditAuthorizer
include Pundit
attr_reader :user, :obj
def initialize(user, obj)
@user = user
@obj = obj
end
# The only API
# query can end with '? optionally
def authorize_on(query)
query += '?' unless query.last == '?'
authorize(obj, query)
end
private
# Override Pundit to refer user to @user, instead of current_user
def pundit_user
user
end
end
|
chuckmersereau/api_practice
|
db/migrate/20131119030333_update_nzl_endpoint.rb
|
class UpdateNzlEndpoint < ActiveRecord::Migration
def change
cccnz = Organization.find_by_name("Campus Crusade for Christ - NZ")
tandem = Organization.find_by_name("Tandem Ministries")
unless cccnz.nil?
cccnz.query_ini_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
cccnz.staff_portal_url = "https://tntdataserverasia.com/dataserver/nzl/"
cccnz.account_balance_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
cccnz.donations_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
cccnz.addresses_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
cccnz.addresses_by_personids_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
cccnz.profiles_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
cccnz.save
say "Updated Campus Crusade for Christ - NZ"
end
unless tandem.nil?
tandem.query_ini_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
tandem.staff_portal_url = "https://tntdataserverasia.com/dataserver/nzl/"
tandem.account_balance_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
tandem.donations_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
tandem.addresses_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
tandem.addresses_by_personids_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
tandem.profiles_url = "https://tntdataserverasia.com/dataserver/nzl/dataquery/tntquery.aspx"
tandem.save
say "Updated Tandem Ministries"
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/google_emails.rb
|
FactoryBot.define do
factory :google_email do
google_email_id 1
association :google_account
end
end
|
chuckmersereau/api_practice
|
app/services/task/filter/contact_info_work_phone.rb
|
class Task::Filter::ContactInfoWorkPhone < Task::Filter::Base
def execute_query(tasks, filters)
tasks.joins(:contacts).merge(Contact::Filter::ContactInfoWorkPhone.query(Contact, filters, account_lists))
end
delegate :custom_options,
:parent,
:type,
:title,
to: 'Contact::Filter::ContactInfoWorkPhone.new(account_lists)'
end
|
chuckmersereau/api_practice
|
db/migrate/20171004041321_add_ids_to_recommendations.rb
|
class AddIdsToRecommendations < ActiveRecord::Migration
def change
add_belongs_to :donation_amount_recommendations,
:designation_account,
index: { name: 'recommendations_designation_account_id' },
foreign_key: { dependent: :nullify }
add_belongs_to :donation_amount_recommendations,
:donor_account,
index: { name: 'recommendations_donor_account_id' },
foreign_key: { dependent: :nullify }
end
end
|
chuckmersereau/api_practice
|
app/policies/task_policy.rb
|
class TaskPolicy < ApplicationPolicy
private
def resource_owner?
user.account_lists.exists?(id: resource.account_list_id)
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/church_names_controller_spec.rb
|
<filename>spec/controllers/api/v2/contacts/church_names_controller_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe Api::V2::Contacts::ChurchNamesController, type: :controller do
let(:resource_type) { :churches }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:second_user) { create(:user_with_account) }
let(:second_account_list) { second_user.account_lists.order(:created_at).first }
let(:church_name) { 'Beautiful Saviour' }
let(:second_church_name) { 'Cross of Christ' }
let(:third_church_name) { 'Calvary Chapel' }
let!(:contact) { create(:contact, account_list: account_list, church_name: church_name) }
let!(:second_contact) { create(:contact, account_list: account_list, church_name: second_church_name) }
let!(:third_contact) { create(:contact, account_list: second_account_list, church_name: third_church_name) }
let(:correct_attributes) { { church_name: church_name } }
let(:incorrect_attributes) { { church_name: nil } }
describe '#index' do
it 'returns the list of church names for all the users contacts' do
api_login(user)
get :index
data = ::JSON.parse(response.body)['data']
expect(data.size).to eq(2)
expect(data[0]['attributes']['church_name']).to eq(church_name)
expect(data[1]['attributes']['church_name']).to eq(second_church_name)
end
it 'only returns the users contacts church names' do
api_login(second_user)
get :index
data = ::JSON.parse(response.body)['data']
expect(data.size).to eq(1)
expect(data[0]['attributes']['church_name']).to eq(third_church_name)
end
it 'will search for similar church names' do
api_login(user)
get :index, filter: { church_name_like: 'saviour' }
data = ::JSON.parse(response.body)['data']
expect(data.size).to eq(1)
expect(data[0]['attributes']['church_name']).to eq(church_name)
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/background_batches.rb
|
FactoryBot.define do
factory :background_batch do
batch_id 'MyString'
user
after :build do |background_batch|
background_batch.requests << build(:background_batch_request, background_batch: nil)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/suggested_changes_updater_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::SuggestedChangesUpdater, type: :model do
include ContactStatusSuggesterSpecHelpers
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact, account_list: account_list) }
let(:donor_account) { create(:donor_account) }
let(:designation_account) { create(:designation_account) }
let(:service) { Contact::SuggestedChangesUpdater.new(contact: contact) }
subject { service.update_status_suggestions }
before do
travel_to Time.current.beginning_of_year
account_list.designation_accounts << designation_account
contact.donor_accounts << donor_account
contact.donations.each(&:destroy!)
end
after do
travel_back
end
it 'initializes' do
expect(service).to be_a Contact::SuggestedChangesUpdater
expect(service.contact).to eq contact
end
# Run the following specs for each pledge frequency
Contact.pledge_frequencies.keys.sort.each do |pledge_frequency|
describe '#update_status_suggestions' do
context 'suggested status does not match current status' do
before do
create_donations_to_match_frequency(pledge_frequency)
contact.update_columns(status: nil,
pledge_frequency: nil,
pledge_amount: nil,
pledge_currency: nil)
end
it 'does not change updated_at' do
expect { subject }.to_not change { contact.reload.updated_at }
end
it 'updates suggested_changes' do
subject
expect(contact.suggested_changes[:pledge_frequency]).to eq pledge_frequency
expect(contact.status_valid).to eq false
expect(contact.suggested_changes[:status]).to eq 'Partner - Financial'
expect(contact.suggested_changes[:pledge_amount]).to eq 50
expect(contact.suggested_changes[:pledge_currency]).to eq 'CAD'
end
end
context 'suggested status matches current status' do
before do
create_donations_to_match_frequency(pledge_frequency)
contact.update_columns(status: 'Partner - Financial',
pledge_frequency: pledge_frequency,
pledge_amount: 50,
pledge_currency: 'CAD')
end
it 'does not change updated_at' do
expect { subject }.to_not change { contact.reload.updated_at }
end
it 'updates suggested_changes' do
subject
expect(contact.suggested_changes.keys.include?(:pledge_frequency)).to eq false
expect(contact.status_valid).to eq true
expect(contact.suggested_changes.keys.include?(:status)).to eq false
expect(contact.suggested_changes.keys.include?(:pledge_amount)).to eq false
expect(contact.suggested_changes.keys.include?(:pledge_currency)).to eq false
end
end
context 'contact has status that we do not support suggesting' do
before do
contact.update_columns(status: 'Partner - Prayer')
end
it 'does not suggest a nil status' do
subject
expect(contact.suggested_changes.keys.include?(:status)).to eq false
end
end
context 'contact has nil pledge_currency' do
before do
contact.update_columns(status: 'Partner - Prayer', pledge_amount: nil, pledge_frequency: nil, pledge_currency: 'CAD')
end
it 'does not suggest a nil pledge_currency' do
subject
expect(contact.suggested_changes.keys.include?(:pledge_currency)).to eq false
end
end
context 'pledge_amount is 0' do
before do
contact.update_columns(status: 'Partner - Prayer', pledge_amount: 0, pledge_frequency: nil, pledge_currency: nil)
end
it 'does not suggest a pledge_amount' do
subject
expect(contact.suggested_changes.keys.include?(:pledge_amount)).to eq false
end
end
end
end
context 'pledge_frequency is 0' do
before do
contact.update_columns(status: 'Partner - Prayer', pledge_amount: nil, pledge_frequency: 0, pledge_currency: nil)
end
it 'does not suggest a pledge_frequency' do
subject
expect(contact.suggested_changes.keys.include?(:pledge_frequency)).to eq false
end
end
context 'suggesting changes again after the contact has been updated' do
before do
create_donations_to_match_frequency(1.0)
contact.update_columns(status: nil,
pledge_frequency: nil,
pledge_amount: nil,
pledge_currency: nil)
end
it 'does not suggest the same change after it has been applied to the contact' do
service.update_status_suggestions
expect(contact.reload.suggested_changes).to be_present
contact.update!(contact.reload.suggested_changes)
service.update_status_suggestions
expect(contact.reload.suggested_changes).to be_blank
end
end
describe '#status_confirmed_recently?' do
it 'updates suggested_changes if status_confirmed_at is nil' do
contact.update!(status_confirmed_at: nil)
expect { service.update_status_suggestions }.to change { contact.reload.suggested_changes }.from({})
end
it 'does not update suggested_changes if status_confirmed_at is less than a year ago' do
contact.update!(status_confirmed_at: 11.months.ago)
expect { service.update_status_suggestions }.to_not change { contact.reload.suggested_changes }.from({})
end
it 'updates suggested_changes if status_confirmed_at is more than a year ago' do
contact.update!(status_confirmed_at: 13.months.ago)
expect { service.update_status_suggestions }.to change { contact.reload.suggested_changes }.from({})
end
end
describe 'the financial partner giving extra' do
before do
contact.update_columns(status: 'Partner - Financial',
status_valid: true,
pledge_frequency: nil,
pledge_amount: nil,
pledge_currency: nil)
create_donations_to_match_frequency(1.0)
end
it 'should NOT be suggested for "Partner - Special"' do
service.update_status_suggestions
expect(contact.suggested_changes.keys.include?(:status)).to be false
end
end
describe 'the financial partner misses one month' do
before do
contact.update_columns(status: 'Partner - Financial',
status_valid: true,
pledge_frequency: nil,
pledge_amount: nil,
pledge_currency: nil)
create_donations_with_missing_month(1.0)
end
it 'should NOT be suggested for "Partner - Special"' do
service.update_status_suggestions
expect(contact.suggested_changes.keys.include?(:status)).to be false
end
end
end
|
chuckmersereau/api_practice
|
spec/models/contact_notes_log_spec.rb
|
require 'rails_helper'
describe ContactNotesLog, versioning: true do
it 'tracks notes at most once per day in separate table from partner status' do
contact = nil
travel_to Date.new(2015, 12, 19) do
contact = create(:contact, notes: 'old')
end
travel_to Date.new(2015, 12, 20) do
expect do
contact.update(notes: 'changed')
end.to change(PartnerStatusLog, :count).by(0)
.and change(ContactNotesLog, :count).by(1)
end
expect(contact.notes_on_date(Date.new(2015, 12, 19))).to eq 'old'
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_newsletter_spec.rb
|
require 'rails_helper'
RSpec.describe Task::Filter::ContactNewsletter do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let!(:email_contact) { create(:contact, account_list: account_list, send_newsletter: 'Email') }
let!(:physical_contact) { create(:contact, account_list: account_list, send_newsletter: 'Physical') }
let!(:both_contact) { create(:contact, account_list: account_list, send_newsletter: 'Both') }
let!(:none_contact) { create(:contact, account_list: account_list, send_newsletter: 'None') }
let!(:nil_contact) { create(:contact, account_list: account_list) }
before do
nil_contact.update(send_newsletter: nil)
end
let!(:task_one) { create(:task, account_list: account_list, contacts: [email_contact]) }
let!(:task_two) { create(:task, account_list: account_list, contacts: [physical_contact]) }
let!(:task_three) { create(:task, account_list: account_list, contacts: [both_contact]) }
let!(:task_four) { create(:task, account_list: account_list, contacts: [none_contact]) }
let!(:task_five) { create(:task, account_list: account_list, contacts: [nil_contact]) }
describe '#query' do
let(:tasks) { account_list.tasks }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, account_list)).to eq(nil)
expect(described_class.query(tasks, { newsletter: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { newsletter: [] }, account_list)).to eq(nil)
expect(described_class.query(tasks, { newsletter: '' }, account_list)).to eq(nil)
end
end
context 'filter by contact newsletter none' do
it 'returns only tasks with contacts that have the none newsletter option selected' do
results = described_class.query(tasks, { contact_newsletter: 'none' }, account_list).to_a
expect(results).to eq [task_four]
end
end
context 'filter by contact newsletter none' do
it 'returns only tasks with contacts that have the no_value newsletter option selected' do
results = described_class.query(tasks, { contact_newsletter: 'no_value' }, account_list).to_a
expect(results).to eq [task_five]
end
end
context 'filter by contact newsletter all' do
it 'returns all tasks with contacts that have the all newsletter option selected, but not blank' do
results = described_class.query(tasks, { contact_newsletter: 'all' }, account_list).to_a
expect(results).to match_array [task_one, task_two, task_three]
end
end
context 'filter by contact newsletter physical' do
it 'returns all tasks with contacts that have physical or both newsletter options selected' do
results = described_class.query(tasks, { contact_newsletter: 'address' }, account_list).to_a
expect(results).to match_array [task_two, task_three]
end
end
context 'filter by contact newsletter email' do
it 'returns all tasks with contacts that have email or both newsletter options selected' do
results = described_class.query(tasks, { contact_newsletter: 'email' }, account_list).to_a
expect(results).to match_array [task_one, task_three]
end
end
context 'filter by contact newsletter both' do
it 'returns all tasks with contacts that have both newsletter options selected' do
results = described_class.query(tasks, { contact_newsletter: 'both' }, account_list).to_a
expect(results).to eq [task_three]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/exhibits/email_address_exhibit_spec.rb
|
require 'rails_helper'
describe EmailAddressExhibit do
subject { EmailAddressExhibit.new(email_address, context) }
let(:email_address) { build(:email_address) }
let(:context) { double }
it 'returns a mailto link for to_s' do
allow(context).to receive(:mail_to).and_return('<a href="mailto:MyString">MyString</a>')
expect(subject.to_s).to eq('<a href="mailto:MyString">MyString</a>')
end
end
|
chuckmersereau/api_practice
|
spec/models/company_spec.rb
|
require 'rails_helper'
describe Company do
it 'should return the company name for to_s' do
expect(Company.new(name: 'foo').to_s).to eq('foo')
end
it 'should delete master_company on destroy if there are no other companies for that master' do
company = FactoryBot.create(:company)
expect do
company.destroy
end.to change(MasterCompany, :count).from(1).to(0)
end
it 'should NOT delete master_company on destroy if there are other companies for that master' do
company = FactoryBot.create(:company)
FactoryBot.create(:company, master_company: company.master_company)
expect do
company.destroy
end.to_not change(MasterCompany, :count)
end
end
|
chuckmersereau/api_practice
|
app/services/coaching/contact/filter/pledge.rb
|
<filename>app/services/coaching/contact/filter/pledge.rb
module Coaching::Contact
class Filter::Pledge < Filter::Base
def execute_query(contacts, filters)
case filters[:pledge]
when 'completed'
contacts.financial_partners.where(pledge_received: true)
when 'outstanding'
contacts.financial_partners
.where(pledge_received: false)
.where('pledge_start_date < ?', today)
when 'pending'
contacts.financial_partners
.where(pledge_received: false)
.where('pledge_start_date >= ?', today)
else # 'all'
contacts.all
end
end
def title
_('Pledge Status')
end
def type
'radio'
end
def default_options
[]
end
def custom_options
[{ name: _('-- All --'), id: 'all' },
{ name: _('Outstanding'), id: 'outstanding' },
{ name: _('Completed'), id: 'completed' },
{ name: _('Pending'), id: 'pending' }]
end
private
def today
Time.zone.now.to_date
end
end
end
|
chuckmersereau/api_practice
|
config/initializers/audited.rb
|
# money patch Audit class to save to Elasticsearch instead of the db
require 'elasticsearch/persistence/model'
require 'audited'
Elasticsearch::Persistence.client = if Rails.env.test?
Elasticsearch::Client.new host: 'example.com'
else
Elasticsearch::Client.new host: ENV['ELASTICSEARCH_URL'],
port: ENV['ELASTICSEARCH_PORT']
end
module Audited
class Audit
def self.exists?
true
end
end
# monkey-patch gem module
module Auditor
module AuditedInstanceMethods
def write_audit(attrs)
# clear comment if it was added
self.audit_comment = nil
return unless system_auditing_enabled && auditing_enabled
attrs[:audited_changes] = attrs[:audited_changes].to_s
attrs[:created_at] = DateTime.now
set_request_uuid(attrs)
set_remote_address(attrs)
set_audit_user(attrs)
set_auditable(attrs)
set_associated(attrs)
run_callbacks(:audit) { AuditChangeWorker.perform_async(attrs) }
end
def audits
Audited::AuditSearch.search_by(auditable_type: self.class.to_s, auditable_id: id)
end
private
def system_auditing_enabled
ENV['ELASTICSEARCH_URL'].present? && !Rails.env.test?
end
def set_request_uuid(attrs)
attrs[:request_uuid] ||= ::Audited.store[:current_request_uuid]
end
def set_remote_address(attrs)
attrs[:remote_address] ||= ::Audited.store[:current_remote_address]
end
def set_audit_user(attrs)
return if attrs[:user_id]
user = ::Audited.store[:audited_user] || ::Audited.store[:current_user]&.call
set_model_field(attrs, :user, user)
end
def set_auditable(attrs)
set_model_field(attrs, :auditable, self)
end
def set_associated(attrs)
return if audit_associated_with.nil?
set_model_field(attrs, :associated, send(audit_associated_with))
end
def set_model_field(attrs, field, object)
return unless object
attrs["#{field}_id".to_sym] = object.try(:id)
attrs["#{field}_type".to_sym] = object.class.to_s
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/status_valid.rb
|
<reponame>chuckmersereau/api_practice
class Contact::Filter::StatusValid < Contact::Filter::Base
def execute_query(contacts, filters)
contacts.where(status_valid: filters[:status_valid] == 'true')
end
end
|
chuckmersereau/api_practice
|
app/serializers/family_relationship_serializer.rb
|
<reponame>chuckmersereau/api_practice<filename>app/serializers/family_relationship_serializer.rb
class FamilyRelationshipSerializer < ApplicationSerializer
attributes :relationship
belongs_to :related_person
end
|
chuckmersereau/api_practice
|
spec/services/reports/appointment_results_spec.rb
|
require 'rails_helper'
RSpec.describe Reports::AppointmentResults, type: :model do
let(:account_list) { create(:account_list) }
let(:report) { described_class.new(account_list: account_list, filter_params: {}) }
describe 'initializes' do
it 'initializes successfully' do
expect(report).to be_a(Reports::AppointmentResults)
expect(report.account_list).to eq account_list
end
it 'sets defaults' do
expect(report.range).to eq '4w'
expect(report.end_date).to eq Date.today
end
end
describe '#periods_data' do
context 'range of 2m' do
before { report.filter_params[:range] = '2m' }
around(:example) do |example|
travel_to DateTime.new(2018, 4, 12, 12, 0, 0).getlocal, &example
end
it 'creates two month-long periods' do
expect(Reports::AppointmentResultsPeriod).to receive(:new).with(account_list: account_list,
start_date: Date.new(2018, 3, 1).beginning_of_day,
end_date: Date.new(2018, 3, 31).end_of_day)
expect(Reports::AppointmentResultsPeriod).to receive(:new).with(account_list: account_list,
start_date: Date.new(2018, 4, 1).beginning_of_day,
end_date: Date.new(2018, 4, 30).end_of_day)
report.periods_data
end
end
it 'takes thread timezone into account'
end
describe '#meta' do
it 'returns a summary of averages' do
i = -1
monthly_increase_periods = [71, 50, 70, 51]
period_double = double('period', individual_appointments: 3,
group_appointments: 1,
new_monthly_partners: 1,
new_special_pledges: 1,
pledge_increase: 1)
allow(period_double).to receive(:monthly_increase) { monthly_increase_periods[i += 1] }
allow(Reports::AppointmentResultsPeriod).to receive(:new).and_return(period_double)
# the average is 60.5, but we expect it to round up
expect(report.meta['average_monthly_increase']).to be 61
end
it 'only averages requested fields' do
meta = report.meta('reports_appointment_results_periods' => ['monthly_increase'])
expect(meta.keys).to eq ['average_monthly_increase']
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/contact_info_addr.rb
|
class Contact::Filter::ContactInfoAddr < Contact::Filter::Base
def execute_query(contacts, filters)
contacts_with_addr = contacts.where.not(addresses: { street: '' })
.where(addresses: { historic: false })
.joins(:addresses)
contacts_with_addr_ids = contacts_with_addr.ids
return contacts.where(id: contacts_with_addr_ids) if filters[:contact_info_addr] == 'Yes'
return contacts if contacts_with_addr_ids.empty?
contacts.where.not(id: contacts_with_addr_ids)
end
def title
_('Address')
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
|
spec/acceptance/api/v2/account_lists/designation_accounts_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Account Lists > Designation Accounts' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: %i(account_lists designation_accounts))
let(:resource_type) { 'designation_accounts' }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:designation_account) { create(:designation_account) }
let(:id) { designation_account.id }
let(:new_designation_account) { { active: true, overwrite: true } }
let(:expected_attribute_keys) do
%w(
active
display_name
balance
balance_updated_at
converted_balance
created_at
currency
currency_symbol
designation_number
exchange_rate
name
organization_name
updated_at
updated_in_db_at
)
end
let(:resource_associations) do
%w(
balances
organization
)
end
context 'authorized user' do
before do
account_list.designation_accounts << designation_account
api_login(user)
end
get '/api/v2/account_lists/:account_list_id/designation_accounts' do
doc_helper.insert_documentation_for(action: :index, context: self)
example doc_helper.title_for(:index), document: doc_helper.document_scope do
explanation doc_helper.description_for(:index)
do_request
check_collection_resource(1, ['relationships'])
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 200
end
end
get '/api/v2/account_lists/:account_list_id/designation_accounts/:id' do
doc_helper.insert_documentation_for(action: :get, context: self)
example doc_helper.title_for(:get), document: doc_helper.document_scope do
explanation doc_helper.description_for(:get)
explanation 'The Designation Account with the given ID'
do_request
check_resource(['relationships'])
expect(resource_object.keys).to match_array expected_attribute_keys
expect(resource_object['designation_number']).to eq designation_account.designation_number
expect(response_status).to eq 200
end
end
put '/api/v2/account_lists/:account_list_id/designation_accounts/:id' do
doc_helper.insert_documentation_for(action: :update, context: self)
example doc_helper.title_for(:update), document: doc_helper.document_scope do
explanation doc_helper.description_for(:update)
do_request data: build_data(new_designation_account)
expect(response_status).to eq(200), invalid_status_detail
expect(resource_object['active']).to eq new_designation_account[:active]
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130119202905_add_settings_to_account_list.rb
|
class AddSettingsToAccountList < ActiveRecord::Migration
def change
add_column :account_lists, :settings, :text
end
end
|
chuckmersereau/api_practice
|
db/migrate/20141031142740_add_contact_id_to_google_contacts.rb
|
<filename>db/migrate/20141031142740_add_contact_id_to_google_contacts.rb
class AddContactIdToGoogleContacts < ActiveRecord::Migration
def change
add_column :google_contacts, :contact_id, :integer
end
end
|
chuckmersereau/api_practice
|
app/services/donation_imports/siebel.rb
|
<filename>app/services/donation_imports/siebel.rb<gh_stars>0
class DonationImports::Siebel < DonationImports::Base
delegate :requires_credentials?, to: :class
def import_all(date_from = 1.year.ago)
import_profiles
import_donors
import_donations(date_from)
end
def self.requires_credentials?
false
end
def import_profiles
ProfileImporter.new(self).import_profiles
end
private
def import_donors
DonorImporter.new(self).import_donors
end
def import_donations(date_from)
DonationImporter.new(self).import_donations(start_date: date_from)
end
end
|
chuckmersereau/api_practice
|
app/serializers/duplicate_record_pair_serializer.rb
|
class DuplicateRecordPairSerializer < ApplicationSerializer
attributes :reason,
:ignore
belongs_to :account_list
has_many :records
def reason
_(object.reason)
end
end
|
chuckmersereau/api_practice
|
app/serializers/reports/donation_monthly_totals_serializer.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class Reports::DonationMonthlyTotalsSerializer < ServiceSerializer
delegate :donation_totals_by_month,
to: :object
attributes :donation_totals_by_month
end
|
chuckmersereau/api_practice
|
app/models/admin/reset_log.rb
|
<reponame>chuckmersereau/api_practice<filename>app/models/admin/reset_log.rb
class Admin::ResetLog < ApplicationRecord
belongs_to :admin_resetting, class_name: 'User'
belongs_to :resetted_user, class_name: 'User'
validates :resetted_user_id, :admin_resetting_id, :reason, presence: true
end
|
chuckmersereau/api_practice
|
db/migrate/20180504141434_add_pledge_currency_to_partner_status_logs.rb
|
class AddPledgeCurrencyToPartnerStatusLogs < ActiveRecord::Migration
def change
add_column :partner_status_logs, :pledge_currency, :string
end
end
|
chuckmersereau/api_practice
|
app/services/donation_imports/siebel/donor_importer/person_importer.rb
|
<filename>app/services/donation_imports/siebel/donor_importer/person_importer.rb
class DonationImports::Siebel
class DonorImporter
class PersonImporter
attr_reader :siebel_import
delegate :organization, to: :siebel_import
def initialize(siebel_import)
@siebel_import = siebel_import
end
def add_or_update_person_on_contact(siebel_person:, contact:, donor_account:, date_from: nil)
@siebel_person = siebel_person
@contact = contact
@donor_account = donor_account
@date_from = date_from
add_person
add_or_update_phone_numbers
add_or_update_email_addresses
true
end
private
def add_person
find_and_set_master_person_from_siebel_person
@mpdx_person = find_mpdx_person_from_siebel_person
@mpdx_person.attributes = generate_new_mpdx_person_attributes if @mpdx_person.new_record?
@mpdx_person.master_person_id ||=
MasterPerson.find_or_create_for_person(@mpdx_person, donor_account: @donor_account).try(:id)
@mpdx_person.save
@donor_account.people << @mpdx_person unless @donor_account.people.exists?(@mpdx_person&.id)
existing_master_person = @donor_account.master_people.exists?(@mpdx_person&.master_person&.id)
@donor_account.master_people << @mpdx_person.master_person unless existing_master_person
@contact.people << @mpdx_person unless @contact.people.exists?(@mpdx_person&.id)
create_master_person_if_needed
end
def generate_new_mpdx_person_attributes
{
legal_first_name: @siebel_person.first_name,
first_name: @siebel_person.preferred_name || @siebel_person.first_name,
last_name: @siebel_person.last_name,
middle_name: @siebel_person.middle_name,
title: @siebel_person.title,
suffix: @siebel_person.suffix,
gender: gender_from_siebel_person
}
end
def find_and_set_master_person_from_siebel_person
@master_person_from_source =
organization.master_people.find_by('master_person_sources.remote_id' => @siebel_person.id)
return if @master_person_from_source
remote_id = @siebel_person.primary ? "#{@donor_account.account_number}-1" : "#{@donor_account.account_number}-2"
@master_person_from_source = organization.master_people.find_by('master_person_sources.remote_id' => remote_id)
if @master_person_from_source
MasterPersonSource.where(organization_id: organization.id, remote_id: remote_id)
.update_all(remote_id: siebel_person.id)
end
end
def find_mpdx_person_from_siebel_person
@mpdx_person =
@contact.people.find_by(first_name: @siebel_person.first_name, last_name: @siebel_person.last_name)
@mpdx_person ||=
@contact.people.find_by(master_person_id: @master_person_from_source.id) if @master_person_from_source
@mpdx_person || Person.new(master_person: @master_person_from_source)
end
def create_master_person_if_needed
return if @master_person_from_source
organization.master_person_sources.where(remote_id: @siebel_person.id)
.first_or_create(master_person_id: @mpdx_person.master_person.id)
end
def gender_from_siebel_person
if @siebel_person.sex == 'F'
'female'
elsif @siebel_person.sex == 'M'
'male'
end
end
def add_or_update_phone_numbers
@siebel_person.phone_numbers&.each do |siebel_phone_number|
next if siebel_phone_number_irrelevant?(siebel_phone_number)
add_or_update_phone_number(siebel_phone_number)
end
end
def add_or_update_email_addresses
@siebel_person.email_addresses&.each do |siebel_email_address|
next if siebel_phone_number_irrelevant?(siebel_email_address)
add_or_update_email_address(siebel_email_address)
end
end
def siebel_phone_number_irrelevant?(siebel_phone_number)
siebel_object_irrelevant?(siebel_phone_number) && @mpdx_person.phone_numbers.present?
end
def siebel_email_address_irrelevant?(siebel_email_address)
siebel_object_irrelevant?(siebel_email_address) && @mpdx_person.email_addresses.present?
end
def siebel_object_irrelevant?(siebel_object)
@date_from.present? &&
siebel_object.updated_at &&
DateTime.parse(siebel_object.updated_at) < @date_from
end
def add_or_update_phone_number(siebel_phone_number)
attributes = {
number: siebel_phone_number.phone,
location: siebel_phone_number.type.try(:downcase),
primary: siebel_phone_number.primary,
remote_id: siebel_phone_number.id
}
existing_phone = @mpdx_person.phone_numbers.find do |person_phone_number|
person_phone_number.remote_id == siebel_phone_number.id
end
if existing_phone
existing_phone.update_attributes(attributes)
else
@mpdx_person.phone_numbers.create(attributes)
end
end
def add_or_update_email_address(siebel_email_address)
attributes = {
email: siebel_email_address.email,
primary: siebel_email_address.primary,
location: siebel_email_address.type,
remote_id: siebel_email_address.id
}
existing_email = @mpdx_person.email_addresses.find do |person_email_address|
person_email_address.remote_id == siebel_email_address.id
end
if existing_email
begin
existing_email.update_attributes(attributes)
rescue StandardError
ActiveRecord::RecordNotUnique
end
# If they already have the email address we're trying to update to, don't do anything
else
@mpdx_person.email_addresses.create(attributes)
end
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/exporter/interest_adder.rb
|
# This class takes care of adding tags and status interests to Mail Chimp
# This is needed to add those categories and tags to the contacts that will be exported to Mailchimp.
# For reference, see:
# https://developer.mailchimp.com/documentation/mailchimp/reference/lists/interest-categories/interests
class MailChimp::Exporter
class InterestAdder
attr_reader :mail_chimp_account, :gibbon_wrapper, :list_id
def initialize(mail_chimp_account, gibbon_wrapper, list_id)
@mail_chimp_account = mail_chimp_account
@gibbon_wrapper = gibbon_wrapper
@list_id = list_id
end
def add_tags_interests(tags_to_add)
add_interests('Tags', :tags, tags_to_add)
end
def add_status_interests(statuses_to_add)
add_interests('Partner Status', :statuses, statuses_to_add)
end
private
def gibbon_list
gibbon_wrapper.gibbon_list_object(list_id)
end
def add_interests(interest_category_name, attribute, interests_to_add)
interest_category_id = mail_chimp_account.get_interest_attribute_for_list(group: attribute,
attribute: :interest_category_id,
list_id: list_id)
interest_category = find_or_create_interest_category(interest_category_id, interest_category_name)
interest_category_id = interest_category['id']
mail_chimp_account.set_interest_attribute_for_list(group: attribute,
attribute: :interest_category_id,
list_id: list_id,
value: interest_category_id)
interests = find_or_create_interests(interest_category_id, interests_to_add)
mail_chimp_account.set_interest_attribute_for_list(group: attribute,
attribute: :interest_ids,
list_id: list_id,
value: interests)
mail_chimp_account.save(validate: false)
mail_chimp_account.reload
end
def find_or_create_interest_category(interest_category_id, interest_category_name)
find_interest_category(interest_category_id, interest_category_name) ||
create_interest_category(interest_category_name)
end
def find_interest_category(interest_category_id, interest_category_name)
interest_categories = gibbon_list.interest_categories.retrieve(params: { 'count': '100' })['categories']
interest_categories.find { |interest_category| interest_category['id'] == interest_category_id } ||
interest_categories.find { |interest_category| interest_category['title'] == _(interest_category_name) }
rescue Gibbon::MailChimpError => error
raise unless does_not_have_interest_interests_enabled?(error)
end
def create_interest_category(group_type)
interest_category_body = { title: _(group_type), type: 'hidden' }
gibbon_list.interest_categories.create(body: interest_category_body)
find_interest_category(nil, group_type)
end
def find_or_create_interests(interest_category_id, interests_to_add)
interests_already_present = find_interests(interest_category_id)
interests_created = create_interests(interest_category_id, interests_to_add - interests_already_present.keys)
interests_already_present.merge(interests_created)
end
def find_interests(interest_category_id)
gibbon_list.interest_categories(interest_category_id)
.interests
.retrieve(params: { fields: 'interests.id,interests.name', count: 60 })['interests']
.map { |interest| { interest['name'] => interest['id'] } }
.reduce({}, :merge) || {}
end
def create_interests(interest_category_id, interests)
hash = {}
interests.reject(&:blank?).each do |interest|
begin
interest = gibbon_list.interest_categories(interest_category_id).interests.create(body: { name: interest })
hash[interest['name']] = interest['id']
rescue Gibbon::MailChimpError => error
break if maximum_number_of_interests_per_list?(error)
raise unless already_exists_on_list?(error)
end
end
hash
end
def does_not_have_interest_interests_enabled?(error)
error.message.include?('code 211')
end
def already_exists_on_list?(error)
error.status_code == 400 && error.detail =~ /Cannot add .* because it already exists on the list/
end
def maximum_number_of_interests_per_list?(error)
error.status_code == 400 && error.detail =~ /Cannot have more than .* interests per list/
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/coaching/account_lists_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Coaching Account Lists' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: %i(coaching account_lists))
let(:resource_type) { 'account_lists' }
let!(:user) { create(:user) }
let!(:coach) { user.becomes(User::Coach) }
let(:account_list) do
create(:account_list).tap do |account_list|
coach.coaching_account_lists << account_list
end
end
let(:id) { account_list.id }
let(:new_account_list) do
attributes_for(:account_list)
.except(:creator_id)
.merge(updated_in_db_at: account_list.updated_at)
end
let(:form_data) { build_data(new_account_list) }
let(:resource_attributes) do
%w(
active_mpd_finish_at
active_mpd_monthly_goal
active_mpd_start_at
balance
committed
created_at
currency
default_currency
home_country
last_prayer_letter_at
monthly_goal
name
progress
received
salary_organization
staff_account_ids
tester
total_pledges
updated_at
updated_in_db_at
weeks_on_mpd
primary_appeal
)
end
let(:resource_associations) do
%w(
notification_preferences
organization_accounts
primary_appeal
users
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/coaching/account_lists' do
doc_helper.insert_documentation_for(action: :index, context: self)
before { account_list }
example doc_helper.title_for(:index), document: doc_helper.document_scope do
explanation doc_helper.description_for(:index)
do_request
check_collection_resource(1, ['relationships'])
expect(response_status).to eq 200
end
end
get '/api/v2/coaching/account_lists/: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(['relationships'])
expect(resource_object['name']).to eq account_list.name
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/task/filterer.rb
|
class Task::Filterer < ApplicationFilterer
FILTERS_TO_DISPLAY = %w(
ActivityType
ContactIds
ContactChurch
ContactCity
ContactCountry
ContactInfoAddr
ContactInfoEmail
ContactInfoMobile
ContactInfoPhone
ContactInfoWorkPhone
ContactLikely
ContactMetroArea
ContactNewsletter
ContactPledgeFrequency
ContactReferrer
ContactRegion
ContactState
ContactStatus
ContactTimezone
ContactType
ContactDonationAmountRecommendation
ContactDesignationAccountId
).freeze
FILTERS_TO_HIDE = %w(
Completed
DateRange
ExcludeTags
Ids
Overdue
Starred
Tags
UpdatedAt
WildcardSearch
).freeze
end
|
chuckmersereau/api_practice
|
app/serializers/bulk_resource_serializer.rb
|
class BulkResourceSerializer
def initialize(resources: [])
@resources = resources
end
def as_json(*args)
@resources.map do |resource|
resource_or_error_json(resource, *args)
end.as_json(*args)
end
private
def resource_or_error_json(resource, args)
if resource.errors.any?
{ id: resource.id }.as_json(args).merge(
ErrorSerializer.new(hash: resource.errors, resource: resource, status: error_status_code(resource)).as_json(args)
)
else
serializer = ActiveModel::Serializer.serializer_for(resource).new(resource, args)
ActiveModelSerializers::Adapter.create(serializer, args).as_json(args)
end
end
def error_status_code(resource)
conflict_error?(resource) ? 409 : 400
end
def conflict_error?(resource)
resource.errors[:updated_in_db_at].any? { |error| error.include?(ApplicationRecord::CONFLICT_ERROR_MESSAGE) }
end
end
|
chuckmersereau/api_practice
|
app/policies/phone_number_policy.rb
|
<reponame>chuckmersereau/api_practice<filename>app/policies/phone_number_policy.rb
class PhoneNumberPolicy < ApplicationPolicy
attr_reader :contact, :person
def initialize(context, resource)
@user = context.user
@contact = context.contact
@resource = resource
@person = @resource.person
end
private
def resource_owner?
resource &&
contact_belongs_to_current_user? &&
person_belongs_to_contact?
end
def contact_belongs_to_current_user?
user.account_lists.exists?(id: contact.account_list_id)
end
def person_belongs_to_contact?
person.contacts.exists?(id: contact.id)
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/tasks/filters_controller.rb
|
class Api::V2::Tasks::FiltersController < Api::V2Controller
def index
authorize_index
load_filters
render json: @filters, include: include_params, fields: field_params
end
private
def load_filters
@filters ||= Task::Filterer.config(account_lists)
end
def authorize_index
account_lists.each { |account_list| authorize(account_list, :show?) }
end
def permitted_filters
[:account_list_id]
end
end
|
chuckmersereau/api_practice
|
app/serializers/coaching/reports/appointment_results_period_serializer.rb
|
class Coaching::Reports::AppointmentResultsPeriodSerializer < Reports::AppointmentResultsPeriodSerializer
has_many :pledge_increase_contacts, serializer: Coaching::Reports::PledgeIncreaseContactSerializer
has_many :new_pledges, serializer: Coaching::PledgeSerializer
end
|
chuckmersereau/api_practice
|
app/serializers/reports/monthly_giving_graph_serializer.rb
|
<reponame>chuckmersereau/api_practice
class Reports::MonthlyGivingGraphSerializer < ServiceSerializer
include DisplayCase::ExhibitsHelper
delegate :account_list,
:totals,
:pledges,
:monthly_average,
:monthly_goal,
:months_to_dates,
:multi_currency,
:salary_currency,
:display_currency,
to: :object
delegate :salary_currency_symbol,
to: :report_exhibit
belongs_to :account_list
attributes :totals,
:pledges,
:monthly_average,
:monthly_goal,
:months_to_dates,
:multi_currency,
:salary_currency_symbol,
:salary_currency,
:display_currency
def report_exhibit
exhibit(object)
end
end
|
chuckmersereau/api_practice
|
spec/serializers/service_serializer_spec.rb
|
require 'rails_helper'
RSpec.describe ServiceSerializer, type: :serializer do
let(:account_list) { create(:account_list) }
let(:service_resource) { Reports::YearDonations.new(account_list: account_list) }
subject { JSON.parse(ServiceSerializer.new(service_resource).to_json) }
it 'id is nil' do
expect(subject['id']).to be_nil
end
it 'created_at is current time' do
time = Time.current
travel_to time do
expect(subject['created_at']).to eq(time.utc.iso8601)
end
end
it 'updated_at is nil' do
expect(subject['updated_at']).to be_nil
end
it 'updated_in_db_at is nil' do
expect(subject['updated_in_db_at']).to be_nil
end
end
|
chuckmersereau/api_practice
|
db/migrate/20141201142757_change_activity_subject_max_length.rb
|
class ChangeActivitySubjectMaxLength < ActiveRecord::Migration
def change
change_column :activities, :subject, :string, limit: 2000
end
end
|
chuckmersereau/api_practice
|
dev/util/data_privacy_util.rb
|
def anonymize_contacts_by_email(emails)
p 'WARNING No email addresses provided' if emails.blank?
contacts = Contact.joins(people: :email_addresses).where(email_addresses: { email: emails })
contacts.find_each do |contact|
p "CONTACT: #{contact.id} #{contact.name}"
end
p "#{contacts.count} contact(s) found. Continue (Y/N)?"
confirm = $stdin.gets.chomp.upcase
return unless confirm == 'Y'
contacts.find_each do |contact|
ActiveRecord::Base.transaction do
new_contact_name = "DataPrivacy, Deleted #{Date.today.strftime('%Y/%m/%d')}"
contact.taggings.destroy_all
contact.tasks.destroy_all
contact.addresses.destroy_all
contact.people.destroy_all
contact.contact_referrals_to_me.destroy_all
contact.contact_referrals_by_me.destroy_all
contact.donor_accounts.update_all(
name: new_contact_name
)
contact.update(
name: new_contact_name,
pledge_amount: nil,
status: 'Never Ask',
notes: '',
full_name: new_contact_name,
greeting: '',
website: '',
church_name: '',
send_newsletter: nil,
timezone: nil,
envelope_greeting: '',
pledge_currency_code: nil,
pledge_currency: nil,
pledge_frequency: 0,
likely_to_give: nil,
locale: nil
)
end
Rollbar.scope(contact: { id: contact.id }).info("PII Removal Completed for #{contact.id}")
p "COMPLETED PII Removal for #{contact.id}"
end
end
|
chuckmersereau/api_practice
|
spec/services/email_address/google_plus_account_fetcher_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe EmailAddress::GooglePlusAccountFetcher do
context '#fetch_google_plus_account' do
before do
stub_request(:get, "https://picasaweb.google.com/data/entry/api/user/#{encoded_email}?alt=json")
.to_return(status: 200,
body: response_body,
headers: { accept: 'application/json' })
end
let(:google_plus_account_fetcher) { described_class.new(email_address) }
let(:encoded_email) { URI.encode_www_form_component(email_address.email) }
context 'when the api email_address is associated to google plus account' do
let(:email_address) { build(:email_address) }
let(:account_id) { 'random_account_id' }
let(:profile_picture_link) { 'pics.google.com/random_account_id' }
let(:response_body) do
"{\"gphoto$user\": {\"$t\": \"#{account_id}\"}, \"gphoto$thumbnail\": {\"$t\": \"#{profile_picture_link}\"}}"
end
it 'builds the proper google_plus_account object from the google api response' do
google_plus_account = google_plus_account_fetcher.fetch_google_plus_account
expect(google_plus_account.account_id).to eq(account_id)
expect(google_plus_account.profile_picture_link).to eq(profile_picture_link)
end
end
context 'when the api email_address is associated to google plus account' do
let(:email_address) { build(:email_address, email: '<EMAIL>') }
let(:response_body) { "Unable to find user with email #{email_address}" }
it 'builds the proper google_plus_account object from the google api response' do
expect(google_plus_account_fetcher.fetch_google_plus_account).to be_nil
end
end
context 'when the api email_address has invalid URI characters' do
let(:email_address) { build(:email_address, email: 'r/a[n]d?o=<EMAIL>') }
let(:response_body) { "Unable to find user with email #{email_address}" }
it 'does not raise an error' do
expect { google_plus_account_fetcher.fetch_google_plus_account }
.not_to raise_error
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/address_valid.rb
|
<gh_stars>0
class Contact::Filter::AddressValid < Contact::Filter::Base
def execute_query(contacts, filters)
self.contacts = contacts
return contacts unless filters[:address_valid] == 'false'
# Fetching a second time to allow loading of both valid and invalid addresses.
# Without this, it'll return contacts, but only invalid addresses will be included.
Contact.where(id: contacts_with_invalid_addresses.ids)
end
private
attr_accessor :contacts
def filter_scope
contacts.includes(:addresses).references(:addresses)
end
def contacts_with_invalid_addresses
filter_scope.where(contacts: { id: (contact_ids_with_duplicate_primary_addresses +
contact_ids_with_address_valid_values_false) })
end
def contact_ids_with_address_valid_values_false
filter_scope.where(addresses: { valid_values: false }).pluck(:addressable_id)
end
def contact_ids_with_duplicate_primary_addresses
Address.select(:addressable_id)
.where(addressable_type: 'Contact',
addressable_id: contacts.ids,
primary_mailing_address: true,
deleted: false)
.group(:addressable_id)
.having('count(*) > 1')
.pluck(:addressable_id)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160928195843_add_prayer_letter_last_sent_to_mail_chimp_accounts.rb
|
class AddPrayerLetterLastSentToMailChimpAccounts < ActiveRecord::Migration
def change
add_column :mail_chimp_accounts, :prayer_letter_last_sent, :datetime
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180207204733_index_tables_on_created_at.rb
|
<reponame>chuckmersereau/api_practice<filename>db/migrate/20180207204733_index_tables_on_created_at.rb<gh_stars>0
class IndexTablesOnCreatedAt < ActiveRecord::Migration
disable_ddl_transaction!
def up
# we don't want running this to prevent production from starting
return if Rails.env.production? || Rails.env.staging?
tables_query = "SELECT DISTINCT table_name
FROM information_schema.columns
WHERE table_schema = 'public'
and column_name = 'id' and data_type = 'uuid'"
ActiveRecord::Base.connection.execute(tables_query).each do |foreign_table_row|
table = foreign_table_row['table_name']
next if index_exists?(table, :created_at)
next unless column_exists?(table, :created_at)
add_index table, :created_at, algorithm: :concurrently
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/donor_account_people.rb
|
FactoryBot.define do
factory :donor_account_person do
donor_account nil
person nil
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/appeals/appeal_contacts_controller.rb
|
<filename>app/controllers/api/v2/appeals/appeal_contacts_controller.rb
class Api::V2::Appeals::AppealContactsController < Api::V2Controller
before_action :load_appeal
def index
authorize @appeal, :show?
load_appeal_contacts
render json: @appeal_contacts.preload_valid_associations(include_associations),
meta: meta_hash(@appeal_contacts),
include: include_params,
fields: field_params
end
def create
persist_appeal_contact
end
def show
load_appeal_contact
authorize_appeal_contact
render_appeal_contact
end
def destroy
load_appeal_contact
authorize_appeal_contact
@appeal_contact.destroy
head :no_content
end
private
def load_appeal_contacts
@appeal_contacts = AppealContact::Filterer.new(filter_params.merge(appeal_id: @appeal.id))
.filter(scope: appeal_contact_scope, account_lists: account_lists)
.distinct(false)
.joins(sorting_join)
.reorder(sorting_param)
.page(page_number_param)
.per(per_page_param)
end
def load_appeal_contact
@appeal_contact ||= appeal_contact_scope.find(params[:id])
end
def persist_appeal_contact
build_appeal_contact
authorize_appeal_contact
if save_appeal_contact
render_appeal_contact
else
render_with_resource_errors(@appeal_contact)
end
end
def build_appeal_contact
@appeal_contact ||= appeal_contact_scope.build
@appeal_contact.assign_attributes(appeal_contact_params)
end
def save_appeal_contact
@appeal_contact.save(context: persistence_context)
end
def appeal_contact_params
params
.require(:appeal_contact)
.permit(AppealContact::PERMITTED_ATTRIBUTES)
end
def appeal_contact_scope
AppealContact.where(appeal: @appeal)
end
def render_appeal_contact
render json: @appeal_contact,
status: :ok,
include: include_params,
fields: field_params
end
def authorize_appeal_contact
authorize @appeal_contact
end
def load_appeal
@appeal ||= Appeal.find(params[:appeal_id])
end
def pundit_user
PunditContext.new(current_user)
end
def permitted_sorting_params
%w(contact.name)
end
def permitted_filters
[:pledged_to_appeal]
end
end
|
chuckmersereau/api_practice
|
spec/support/shared_controller_examples/create_examples.rb
|
<reponame>chuckmersereau/api_practice
RSpec.shared_examples 'create_examples' do |options = {}|
options[:except] ||= []
include_context 'common_variables'
describe '#create' do
include_examples 'including related resources examples', action: :create unless options[:except].include?(:includes)
include_examples 'sparse fieldsets examples', action: :create
it 'creates resource for users that are signed in' do
api_login(user)
expect do
post :create, full_correct_attributes
end.to change { resource.class.count }.by(options[:count] || 1)
expect(response.status).to eq(201), invalid_status_detail
end
it 'creates a resource associated to the correct parent' do
if parent_association_if_needed.present?
api_login(user)
post :create, full_correct_attributes
created_resource = resource.class.find_by_id(JSON.parse(response.body)['data']['id'])
expect(created_resource.send(parent_association_if_needed).id).to eq parent_param_if_needed.values.last
end
end
it 'does not create the resource when there are unpermitted relationships' do
if defined?(unpermitted_relationships)
api_login(user)
expect do
post :create, full_unpermitted_attributes
end.not_to change { resource.class.count }
expect(response.status).to eq(403), invalid_status_detail
end
end
it 'does not create the resource when there are errors in sent data' do
if incorrect_attributes
api_login(user)
expect do
post :create, full_incorrect_attributes
end.not_to change { resource.class.count }
expect(response.status).to eq(400), invalid_status_detail
expect(response.body).to include('errors')
end
end
it 'does not create resource for users that are not signed in' do
expect do
post :create, full_correct_attributes
end.not_to change { resource.class.count }
expect(response.status).to eq(401), invalid_status_detail
end
it 'does not create a resource if the resource_type is incorrect' do
api_login(user)
expect { post :create, attributes_with_incorrect_resource_type }
.not_to change { resources_count }
expect(response.status).to eq(409), invalid_status_detail
expect(response_errors).to be_present
end
end
end
|
chuckmersereau/api_practice
|
spec/support/json_headers.rb
|
shared_context :json_headers do
header 'Content-Type', 'application/vnd.api+json'
let(:raw_post) { JSON.pretty_generate(params) unless params.blank? }
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/task_due_date.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class Contact::Filter::TaskDueDate < Contact::Filter::Base
def execute_query(contacts, filters)
params = daterange_params(filters[:task_due_date])
contacts = contacts.joins(:activities)
contacts = contacts.where('activities.start_at >= ?', params[:start]) if params[:start]
contacts = contacts.where('activities.start_at <= ?', params[:end]) if params[:end]
contacts
end
def title
_('Due Date')
end
def parent
_('Tasks')
end
def type
'daterange'
end
def custom_options
[
{ name: _('Yesterday'), start: 1.day.ago.beginning_of_day + 1.hour, end: 1.day.ago.end_of_day },
{ name: _('Today'), start: Time.current.beginning_of_day + 1.hour, end: Time.current.end_of_day },
{ name: _('Tomorrow'), start: 1.day.from_now.beginning_of_day + 1.hour, end: 1.day.from_now.end_of_day },
{ name: _('This Week'), start: Time.current.beginning_of_week, end: Time.current.end_of_week - 1.day },
{ name: _('Next Week'), start: 1.week.from_now.beginning_of_week, end: 1.week.from_now.end_of_week - 1.day },
{ name: _('This Month'), start: Time.current.beginning_of_month + 1.hour, end: Time.current.end_of_month },
{ name: _('Next Month'), start: 1.month.from_now.beginning_of_month + 1.hour, end: 1.month.from_now.end_of_month }
]
end
def valid_filters?(filters)
super && daterange_params(filters[:task_due_date]).present?
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/no_appeals.rb
|
<gh_stars>0
class Contact::Filter::NoAppeals < Contact::Filter::Base
def execute_query(scope, filters)
scope.where(no_appeals: (filters[:no_appeals].to_s == 'true'))
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170209205030_change_address_source_default_to_mpdx.rb
|
class ChangeAddressSourceDefaultToMpdx < ActiveRecord::Migration
def up
change_column :addresses, :source, :string, default: 'MPDX'
end
def down
change_column :addresses, :source, :string, default: nil
end
end
|
chuckmersereau/api_practice
|
spec/models/account_list_user_spec.rb
|
<filename>spec/models/account_list_user_spec.rb
require 'rails_helper'
describe AccountListUser do
context '#after_destroy' do
context '#change_user_default_account_list' do
let(:first_account_list) { create(:account_list) }
let(:second_account_list) { create(:account_list) }
let(:user) { create(:user, account_lists: [first_account_list, second_account_list], default_account_list: first_account_list.id) }
it 'sets a new default_account_list when previous default account list is no longer available to the user' do
expect(user.default_account_list).to eq(first_account_list.id)
first_account_list.account_list_users.first.destroy
expect(user.reload.default_account_list).to eq(second_account_list.id)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/user_spec.rb
|
require 'rails_helper'
describe User do
subject { build(:user) }
let(:account_list) { create(:account_list) }
it { is_expected.to have_many(:options).dependent(:destroy) }
it { is_expected.to have_many(:account_list_coaches).dependent(:destroy) }
context '#validations' do
context '#default_account_list_is_valid' do
let(:user) { build(:user, default_account_list: account_list.id) }
it "doesn't allow you to save a default_account_list unless the account_list is associated to the user" do
expect(user.valid?).to be_falsey
user.account_lists << account_list
expect(user.valid?).to be_truthy
end
end
end
describe 'fundraiser role' do
before(:each) do
@org = FactoryBot.create(:organization)
@user = FactoryBot.create(:user)
FactoryBot.create(:designation_profile, organization: @org, user: @user)
@account = FactoryBot.create(:designation_account, organization: @org)
@account_list = FactoryBot.create(:account_list)
FactoryBot.create(:account_list_entry, account_list: @account_list, designation_account: @account)
FactoryBot.create(:account_list_user, account_list: @account_list, user: @user)
end
it 'should return a list of account numbers from a given org' do
expect(@user.designation_numbers(@org.id)).to include(@account.designation_number)
end
end
context '#can_manage_sharing?' do
it 'can manage sharing if it has a designation profile for account list' do
expect(subject.can_manage_sharing?(account_list)).to be false
end
it 'cannot manage sharing if it does not have a designation profile for it' do
subject.save
create(:designation_profile, account_list: account_list, user: subject)
expect(subject.can_manage_sharing?(account_list)).to be true
end
end
context '#remove_user_access' do
it 'removes user from account list users' do
subject.save
account_list.users << subject
subject.remove_user_access(account_list)
expect(account_list.reload.users).to_not include subject
end
end
context '.find_by_guid' do
it 'finds a person with a relay account' do
user = create(:user)
user.key_accounts << create(:key_account, remote_id: 'B163530-7372-551R-KO83-1FR05534129F')
found_user = User.find_by_guid('B163530-7372-551R-KO83-1FR05534129F')
expect(found_user.id).to eq user.id
expect(found_user).to be_a User
end
it 'finds a person with a key account' do
user = create(:user)
# Key and relay account models both use the same db table
user.key_accounts << create(:key_account, remote_id: 'B163530-7372-551R-KO83-1FR05534129F')
found_user = User.find_by_guid('B163530-7372-551R-KO83-1FR05534129F')
expect(found_user.id).to eq user.id
expect(found_user).to be_a User
end
it 'returns nil if user is not found' do
expect(User.find_by_guid('B163530-7372-551R-KO83-1FR05534129F')).to be_nil
end
end
context 'contacts_filter=' do
it 'merges instead of mass assigns' do
user = create(:user, contacts_filter: {
'1' => {
test: 'asdf'
}
})
user.update(contacts_filter: {
'2' => {
status: ['Partner - Financial']
}
})
user.reload
expect(user.contacts_filter['1']).to_not be_nil
expect(user.contacts_filter['2']).to_not be_nil
end
end
describe '#preferences=' do
let(:user) { create(:user) }
before do
user.preferences = {
time_zone: 'Auckland',
developer: true
}
end
context 'user is overriding preference' do
it 'should keep other preferences intact' do
user.preferences = {
developer: false
}
expect(user.preferences).to eq('time_zone' => 'Auckland',
'developer' => false)
end
end
context 'user is appending a preference' do
it 'should keep other preferences intact' do
user.preferences = {
admin: true
}
expect(user.preferences).to eq('time_zone' => 'Auckland',
'developer' => true,
'admin' => true)
end
end
end
describe '#assign_time_zone' do
let(:user) { build(:user) }
context "when the value isn't an ActiveSupport::Timezone object" do
it 'raises an Argument Error' do
expect { user.assign_time_zone('Non Time Zone Object') }
.to raise_error(ArgumentError)
end
end
context 'when the value is an ActiveSupport::Timezone object' do
let(:different_time_zone) do
ActiveSupport::TimeZone.all.detect { |zone| zone != Time.zone }
end
it "changes the user's timezone" do
expect(user.time_zone).to eq Time.zone.name
user.assign_time_zone(different_time_zone)
expect(user.time_zone).to eq different_time_zone.name
expect(user.time_zone).not_to eq Time.zone.name
end
end
end
describe '#find_by_email' do
let!(:user) { create(:user) }
let!(:key_account) { create(:key_account, email: '<EMAIL>', person: user) }
it 'returns the user with a relay account associated to a provided email' do
expect(User.find_by_email('<EMAIL>')).to eq(user)
end
end
describe '#setup' do
describe 'no account lists' do
let(:user) { create(:user) }
it 'return no account_lists' do
expect(user.setup).to eq('no account_lists')
end
end
describe 'no default_account_list' do
let(:account_list) { create(:account_list) }
let(:user) { create(:user, account_lists: [account_list]) }
it 'return no default_account_list' do
expect(user.setup).to eq('no default_account_list')
end
end
describe 'no organization_account on default_account_list' do
let(:account_list) { create(:account_list) }
let(:user) do
create(:user,
account_lists: [account_list],
preferences: { default_account_list: account_list.id })
end
it 'return true' do
expect(user.setup).to eq('no organization_account on default_account_list')
end
end
describe 'organization_account on default_account_list' do
let!(:organization_account) { create(:organization_account, user: user) }
let(:account_list) { create(:account_list) }
let(:user) do
create(:user,
account_lists: [account_list],
preferences: { default_account_list: account_list.id })
end
it 'return nil' do
expect(user.setup).to be_nil
end
end
end
describe '#default_account_list_record' do
describe 'default_account_list set' do
let(:account_list) { create(:account_list) }
let(:user) do
create(:user,
account_lists: [account_list],
preferences: { default_account_list: account_list.id })
end
it 'returns account_list' do
expect(user.default_account_list_record).to eq account_list
end
it 'returns nil if AccountList is not associated with user' do
other_account_list = create(:account_list)
user.update(default_account_list: other_account_list.id)
expect(other_account_list.id).to_not be_nil
expect(user.default_account_list_record).to be_nil
end
end
describe 'default_account_list not set' do
let(:account_list) { create(:account_list) }
let(:user) { create(:user, account_lists: [account_list]) }
it 'returns nil' do
expect(user.default_account_list_record).to be_nil
end
end
end
describe '#email_address' do
context 'has email_address set up' do
let(:address) { '<EMAIL>' }
before { subject.email_addresses.build(email: address) }
it 'returns a string' do
expect(subject.email_address).to eq address
end
end
context 'has no email_address' do
before { subject.email_addresses.delete_all }
it 'returns nil' do
expect(subject.email_address).to be nil
end
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/reports/expected_monthly_totals_serializer.rb
|
class Reports::ExpectedMonthlyTotalsSerializer < ServiceSerializer
delegate :account_list,
:expected_donations,
:total_currency,
:total_currency_symbol,
to: :object
belongs_to :account_list
attributes :expected_donations,
:total_currency,
:total_currency_symbol
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/tasks/filters_controller_spec.rb
|
require 'rails_helper'
require 'json'
describe Api::V2::Tasks::FiltersController, type: :controller do
let!(:user) { create(:user_with_account) }
context 'authorized user' do
before do
api_login(user)
end
describe '#index' do
it 'gets filters for tasks' do
get :index
filters_displayed = JSON.parse(response.body)['data'].map do |filter|
filter['type'].gsub('task_filter_', '').camelize
end
expect(Task::Filterer::FILTERS_TO_DISPLAY.map(&:pluralize)).to include(*filters_displayed)
expect(response.status).to eq 200
end
end
end
context 'unauthorized user' do
describe '#index' do
it 'does not get a list of filters' do
get :index
expect(response.status).to eq 401
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/contact_referral_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe ContactReferral do
end
|
chuckmersereau/api_practice
|
db/migrate/20130710141952_create_messages.rb
|
class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.belongs_to :from
t.belongs_to :to
t.string :subject
t.text :body
t.datetime :sent_at
t.string :source
t.string :remote_id
t.belongs_to :contact
t.belongs_to :account_list
t.timestamps null: false
end
add_index :messages, :from_id
add_index :messages, :to_id
add_index :messages, :contact_id
add_index :messages, :account_list_id
end
end
|
chuckmersereau/api_practice
|
app/services/tnt_import/referrals_import.rb
|
<reponame>chuckmersereau/api_practice
class TntImport::ReferralsImport
def initialize(contact_ids_by_tnt_contact_id, tnt_contact_rows)
attributes_for_contacts = Contact.where(id: contact_ids_by_tnt_contact_id.values)
.pluck(:id, :name, :full_name, :greeting)
@contact_attributes_by_tnt_contact_id = contact_ids_by_tnt_contact_id.transform_values do |id|
attributes_for_contacts.find do |(contact_id, _name, _full_name, _greeting)|
contact_id == id
end
end
@tnt_contact_rows = tnt_contact_rows
end
def import
# Loop over the whole list again now that we've added everyone and try to link up referrals
@tnt_contact_rows.each do |row|
next unless row['ReferredBy'].present?
referred_by_id, *_the_rest = @contact_attributes_by_tnt_contact_id.values.find do |(_contact_id, name, full_name, greeting)|
name == row['ReferredBy'] || full_name == row['ReferredBy'] || greeting == row['ReferredBy']
end
import_referred_by_id(row, referred_by_id)
end
end
private
def import_referred_by_id(row, referred_by_id)
contact_id, *_the_rest = @contact_attributes_by_tnt_contact_id[row['id']]
return if contact_id.blank?
if referred_by_id.present?
ContactReferral.where(referred_to_id: contact_id, referred_by_id: referred_by_id).first_or_create!
else
contact = Contact.find(contact_id)
contact.tag_list.add('Missing Tnt Referred By')
contact.add_to_notes("Referred by: #{row['ReferredBy']}")
end
rescue ActiveRecord::RecordNotFound => error
Rollbar.info(error)
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/merges_spec.rb
|
<filename>spec/acceptance/api/v2/contacts/merges_spec.rb
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts > Merges' do
include_context :json_headers
# This is the scope in how these endpoints will be organized in the
# generated documentation.
#
# :entities should be used for "top level" resources, and the top level
# resources should be used for nested resources.
#
# Ex: Api > v2 > Contacts - :entities would be the scope
# Ex: Api > v2 > Contacts > Email Addresses - :contacts would be the scope
documentation_scope = :contacts_api_merges
# This is required!
# This is the resource's JSONAPI.org `type` attribute to be validated against.
let(:resource_type) { 'contacts' }
let(:request_type) { 'merges' }
# 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!(:winner) { create(:contact, name: '<NAME>', account_list: account_list) }
let!(:loser) { create(:contact, name: '<NAME>', account_list: account_list) }
# This is the reference data used to create/update a resource.
# specify the `attributes` specifically in your request actions below.
let(:form_data) { build_data(attributes, relationships: relationships) }
# List your expected resource keys vertically here (alphabetical please!)
let(:resource_attributes) do
%w(
avatar
church_name
created_at
deceased
direct_deposit
envelope_greeting
greeting
last_activity
last_appointment
last_donation
last_letter
last_phone_call
last_pre_call
last_thank
late_at
likely_to_give
locale
magazine
name
next_ask
no_appeals
no_gift_aid
notes
notes_saved_at
pledge_amount
pledge_currency
pledge_currency_symbol
pledge_frequency
pledge_received
pledge_start_date
send_newsletter
square_avatar
status
status_valid
suggested_changes
tag_list
timezone
uncompleted_tasks_count
updated_at
updated_in_db_at
website
)
end
let(:resource_associations) do
%w(
account_list
addresses
appeals
contact_referrals_by_me
contact_referrals_to_me
contacts_referred_by_me
contacts_that_referred_me
donation_amount_recommendations
donor_accounts
last_six_donations
people
primary_or_first_person
primary_person
spouse
tasks
)
end
# List out any additional attribute keys that will be alongside
# the attributes of the resources.
#
# Remove if not needed.
let(:additional_attribute_keys) do
%w(
relationships
)
end
context 'authorized user' do
before { api_login(user) }
# create
post '/api/v2/contacts/merges' do
with_options scope: [:data, :attributes] do
parameter 'winner_id', 'The ID of the contact that should win the merge'
parameter 'loser_id', 'The ID of the contact that should lose the merge'
end
let(:relationships) do
{
loser: {
data: {
type: 'contacts',
id: loser.id
}
},
winner: {
data: {
type: 'contacts',
id: winner.id
}
}
}
end
let(:attributes) { {} }
example 'Merge [CREATE]', document: documentation_scope do
explanation 'Create Merge'
do_request data: form_data
check_resource(additional_attribute_keys)
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
spec/workers/admin/fix_worker_spec.rb
|
require 'rails_helper'
describe Admin::FixWorker, '#perform' do
let(:id) { SecureRandom.uuid }
it 'finds account list and runs the specified fix for it' do
account_list = double('account_list')
allow(AccountList).to receive(:find).with(id) { account_list }
fix = double('fix', fix: nil)
allow(Admin::AccountPrimaryAddressesFix).to receive(:new)
.with(account_list) { fix }
Admin::FixWorker.new.perform('account_primary_addresses', 'AccountList', id)
expect(fix).to have_received(:fix)
end
end
|
chuckmersereau/api_practice
|
spec/services/sidekiq_cron_loader_spec.rb
|
<filename>spec/services/sidekiq_cron_loader_spec.rb
require 'rails_helper'
describe SidekiqCronLoader do
it 'has all existing worker classes with correct perform methods' do
Sidekiq.logger.level = Logger::ERROR
SidekiqCronLoader.new.load!
jobs = Sidekiq::Cron::Job.all
expect(jobs.size).to eq SidekiqCronLoader::SIDEKIQ_CRON_HASH.size
expect(jobs.all?(&:valid?)).to be true
jobs.each do |job|
klass = job.klass.constantize
expect(klass).to be_present
perform = klass.instance_method(:perform)
expect(perform).to be_present
expect(perform.arity == -1 || perform.arity == job.args.size).to be true
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/tasks/comments_controller.rb
|
class Api::V2::Tasks::CommentsController < Api::V2Controller
resource_type :comments
def index
authorize_index
load_comments
render json: @comments.preload_valid_associations(include_associations),
meta: meta_hash(@comments),
status: success_status,
include: include_params,
fields: field_params
end
def show
load_comment
authorize_comment
render_comment
end
def create
persist_comment
end
def update
load_comment
authorize_comment
persist_comment
end
def destroy
load_comment
authorize_comment
destroy_comment
end
private
def load_comments
@comments = comments_scope.where(filter_params)
.reorder(sorting_param)
.page(page_number_param)
.per(per_page_param)
end
def load_comment
@comment ||= comments_scope.find(params[:id])
end
def destroy_comment
@comment.destroy
head :no_content
end
def build_comment
@comment ||= comments_scope.build
@comment.assign_attributes(comment_params)
end
def persist_comment
build_comment
authorize_comment
if save_comment
render_comment
else
render_with_resource_errors(@comment)
end
end
def activity_param_id
params[:activity_id].presence || params[:task_id]
end
def load_activity
@activity ||= Activity.find(activity_param_id)
end
def comments_scope
load_activity.comments
end
def authorize_index
authorize(load_activity, :show?)
end
def authorize_comment
authorize(load_comment)
end
def comment_params
params.require(:comment)
.permit(ActivityComment::PERMITTED_ATTRIBUTES)
end
def render_comment
render json: @comment,
status: success_status,
include: include_params,
fields: field_params
end
def save_comment
@comment.save(context: persistence_context)
end
end
|
chuckmersereau/api_practice
|
app/serializers/person_serializer.rb
|
class PersonSerializer < ApplicationSerializer
include DisplayCase::ExhibitsHelper
attributes :anniversary_day,
:anniversary_month,
:anniversary_year,
:avatar,
:birthday_day,
:birthday_month,
:birthday_year,
:deceased,
:employer,
:first_name,
:gender,
:last_name,
:legal_first_name,
:marital_status,
:middle_name,
:occupation,
:optout_enewsletter,
:parent_contacts,
:suffix,
:title,
:age
has_many :email_addresses
has_many :facebook_accounts
has_many :family_relationships
has_many :linkedin_accounts
has_many :phone_numbers
has_many :twitter_accounts
has_many :websites
def avatar
person_exhibit.avatar(:large)
end
def person_exhibit
exhibit(object)
end
def parent_contacts
object.contacts.map(&:id)
end
end
|
chuckmersereau/api_practice
|
spec/services/account_list/notifications_sender_spec.rb
|
require 'rails_helper'
RSpec.describe AccountList::NotificationsSender do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
subject { described_class.new(account_list) }
describe '#initialize' do
it 'should set account_list instance variable' do
expect(subject.instance_variable_get(:@account_list)).to eq account_list
end
end
describe '#send_notifications' do
it 'should call NotificationType.check_all' do
expect(NotificationType).to receive(:check_all).and_return({})
subject.send_notifications
end
describe 'notifications to send' do
let(:contact) { create(:contact, account_list: account_list) }
let(:notification_type) { create(:notification_type) }
let(:notification) { create(:notification, contact: contact, notification_type: notification_type) }
let(:message_delivery) { instance_double(ActionMailer::MessageDelivery) }
before do
allow(NotificationType).to receive(:check_all).and_return(notification_type.type => [notification])
allow(NotificationType).to receive(:types).and_return([notification_type.type])
allow(notification_type.class).to receive(:first).and_return(notification_type)
end
it 'should create_tasks' do
account_list.notification_preferences.create(notification_type: notification_type, user: nil, task: true)
expect(notification_type).to receive(:create_task).with(account_list, notification)
subject.send_notifications
end
it 'should create_emails' do
account_list.notification_preferences.create(notification_type: notification_type, user: user, email: true)
allow(notification_type).to receive(:create_task).with(account_list, notification).and_return(nil)
subject.send_notifications
expect(NotificationMailer.instance_method(:notify)).to be_delayed(user, { notification_type => [notification] }, nil)
end
it 'sends account_list_id if multiple account_lists' do
user.account_lists << create(:account_list)
account_list.notification_preferences.create(notification_type: notification_type, user: user, email: true)
allow(notification_type).to receive(:create_task).with(account_list, notification).and_return(nil)
subject.send_notifications
worker_args = [user, { notification_type => [notification] }, account_list.id]
expect(NotificationMailer.instance_method(:notify)).to be_delayed(*worker_args)
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120224195315_remove_seasonal_from_address.rb
|
<gh_stars>0
class RemoveSeasonalFromAddress < ActiveRecord::Migration
def up
remove_column :addresses, :seasonal
end
def down
add_column :addresses, :seasonal, boolean: true
end
end
|
chuckmersereau/api_practice
|
app/exhibits/coaching/person_exhibit.rb
|
class Coaching::PersonExhibit < PersonExhibit
def self.applicable_to?(object)
object.class.name == 'User'
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130708222442_add_last_email_sync_to_google_account.rb
|
class AddLastEmailSyncToGoogleAccount < ActiveRecord::Migration
def change
add_column :person_google_accounts, :last_email_sync, :datetime
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/tasks_all_completed.rb
|
<reponame>chuckmersereau/api_practice
class Contact::Filter::TasksAllCompleted < Contact::Filter::Base
def execute_query(contacts, filters)
contacts = contacts.where.not(id: contacts_with_incomplete_tasks(contacts)) if filters[:tasks_all_completed]&.to_s == 'true'
contacts
end
def contacts_with_incomplete_tasks(contacts)
contacts.joins(:activities).where(activities: { completed: false })
end
def title
_('No Incomplete Tasks')
end
def parent
_('Tasks')
end
def type
'single_checkbox'
end
def empty?
false
end
def default_selection
false
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/imports/csv_controller.rb
|
# This controller supports Content-Type multipart/form-data for file uploads. An example request in curl could look like:
#
# curl "http://localhost:3000/api/v2/account_lists/23882dc0-e7d2-4170-8667-f1896e8427fa/imports/csv" \
# -X POST \
# -H "Authorization: ..." \
# -H 'Content-Type: multipart/form-data' \
# -F 'data[attributes][file]=@/Users/sheldon/Dev/mpdx_api/spec/fixtures/sample_csv_to_import.csv' \
# -F "data[type]=imports"
class Api::V2::AccountLists::Imports::CsvController < Api::V2Controller
resource_type :imports
supports_content_types 'multipart/form-data', 'application/vnd.api+json'
def index
authorize_imports
load_imports
render_imports
end
def show
load_import
authorize_import
render_import
end
def create
persist_import
end
def update
load_import
authorize_import
persist_import
end
private
def load_import
@import ||= import_scope.find(params[:id])
end
def load_imports
@imports = import_scope.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def render_import
render json: @import,
status: success_status,
include: include_params,
fields: field_params
end
def render_imports
render json: @imports.preload_valid_associations(include_associations),
meta: meta_hash(@imports),
include: include_params,
fields: field_params
end
def persist_import
build_import
authorize_import
if save_import
CsvImport.new(@import).update_cached_file_data
render_import
else
render_with_resource_errors(@import)
end
end
def build_import
@import ||= import_scope.build(in_preview: true)
@import.assign_attributes(import_params)
end
def authorize_import
authorize @import
end
def authorize_imports
authorize load_account_list, :show?
end
def save_import
@import.save(context: persistence_context)
end
def import_params
params
.require(:import)
.permit(Import::PERMITTED_ATTRIBUTES)
.merge(source: 'csv', user_id: current_user.id)
.tap do |permit_params| # Permit all parameters underneath the mappings params
const_mapping_nil = params.dig(:import, :file_constants_mappings).nil?
permit_params[:file_constants_mappings] = params[:import][:file_constants_mappings] unless const_mapping_nil
header_mapping_nil = params.dig(:import, :file_headers_mappings).nil?
permit_params[:file_headers_mappings] = params[:import][:file_headers_mappings] unless header_mapping_nil
end
end
def import_scope
load_account_list.imports.where(source: 'csv')
end
def load_account_list
@account_list ||= AccountList.find(params[:account_list_id])
end
def pundit_user
PunditContext.new(current_user, account_list: load_account_list)
end
def default_sort_param
Import.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
app/helpers/localization_helper.rb
|
<reponame>chuckmersereau/api_practice
module LocalizationHelper
def number_to_current_currency(value, options = {})
options[:precision] ||= 0
options[:currency] ||= current_currency
options[:locale] ||= locale
amount_with_symbol = format_with_currency_options(value, options)
currency_code_or_blank = (options[:show_code] ? " #{options[:currency]}" : '')
amount_with_symbol + currency_code_or_blank
end
def current_currency(account_list = nil)
unless @current_currency
account_list ||= current_account_list
@current_currency = account_list ? account_list.default_currency : 'USD'
end
@current_currency
end
def currency_options(account_list)
Hash[account_list.currencies.map do |currency|
[currency, currency_with_symbol(currency)]
end.compact]
end
def currency_with_symbol(currency)
"#{currency} (#{currency_symbol(currency)})"
end
def currency_symbol(currency_code)
info = TwitterCldr::Shared::Currencies.for_code(currency_code)
info ? info[:symbol] : currency_code
end
def supported_locales
TwitterCldr::Shared::Languages
.all
.select { |k, _| TwitterCldr.supported_locales.include?(k) }
end
private
def format_with_currency_options(value, options)
value.to_f.localize(options[:locale]).to_currency.to_s(options)
rescue Errno::ENOENT
# If a bad locale is passed in, fall back to using the spanish currency
# locale because it's probably the most common format globally speaking.
value.to_f.localize(:es).to_currency.to_s(options)
end
end
|
chuckmersereau/api_practice
|
spec/serializers/account_list_serializer_spec.rb
|
require 'rails_helper'
RSpec.describe AccountListSerializer do
let(:organization) { create(:organization) }
let(:account_list) { create(:account_list, salary_organization_id: organization) }
let(:serializer) { AccountListSerializer.new(account_list) }
let(:parsed_json_response) { JSON.parse(serializer.to_json) }
context 'salary_organization' do
it 'returns the id of the salary_organization_id' do
expect(parsed_json_response['salary_organization']).to eq(organization.id)
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160211113711_create_admin_impersonation_log.rb
|
class CreateAdminImpersonationLog < ActiveRecord::Migration
def change
create_table :admin_impersonation_logs do |t|
t.text :reason, null: false
t.integer :impersonator_id, null: false
t.integer :impersonated_id, null: false
t.timestamps null: false
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/background_batches_controller_spec.rb
|
<filename>spec/controllers/api/v2/background_batches_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V2::BackgroundBatchesController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:factory_type) { :background_batch }
let!(:resource) { create(:background_batch, user: user) }
let!(:second_resource) { create(:background_batch, user: user) }
let(:id) { resource.id }
let(:correct_attributes) { {} }
let(:incorrect_attributes) { nil }
let(:correct_relationships) do
{
requests: {
data: [
{
type: 'background_batch_requests',
id: SecureRandom.uuid,
attributes: {
path: 'api/v2/user'
}
}
]
}
}
end
include_examples 'show_examples'
include_examples 'create_examples'
include_examples 'destroy_examples'
include_examples 'index_examples'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.