repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
app/services/tnt_import/countries_parser.rb
|
<gh_stars>0
class TntImport::CountriesParser
class << self
def countries_by_tnt_id(xml)
Hash[tnt_id_to_country_lists(xml).to_a]
end
private
def tnt_id_to_country_lists(xml)
xml.tables['Country'].map do |row|
[row['id'], row['Description']]
end
end
end
end
|
chuckmersereau/api_practice
|
lib/json_api_service/data_object.rb
|
<gh_stars>0
require 'json_api_service/base_object'
require 'json_api_service/relationships_object'
module JsonApiService
class DataObject < BaseObject
attr_reader :relationships
def attributes
@attributes ||= data.dig(:attributes) || {}
end
def id
data.dig(:id)
end
def merge(alternate)
@attributes = alternate.attributes if attributes.empty?
@relationships = alternate.relationships if relationships.empty?
self
end
def to_h
validate_against_store
{}.tap do |hash|
hash[:id] = id if id
hash[:type] = type
hash[:attributes] = attributes unless attributes.empty?
hash[:relationships] = relationships.to_h unless relationships.empty?
end
end
def type
data.dig(:type)
end
def validate_against_store
return unless version_from_store
merge(version_from_store)
relationships.validate_against_store
store.promote(self)
end
def version_from_store
return unless id && !id.to_s.empty?
store[type][id]
end
private
def after_initialize
parse_relationships
store.add(self)
end
def parse_relationships
relationships = data.dig(:relationships)
args = { parent: self, store: store }
@relationships = RelationshipsObject.new(relationships, args)
end
end
end
|
chuckmersereau/api_practice
|
spec/serializers/person/google_account_seralizer_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe Person::GoogleAccountSerializer do
let(:google_account) { create(:google_account) }
subject { Person::GoogleAccountSerializer.new(google_account).as_json }
before { allow_any_instance_of(Person::GoogleAccount).to receive(:contact_groups).and_return([]) }
describe '#token_expired' do
context 'token expired' do
before { allow(google_account).to receive(:token_expired?).and_return(true) }
it { expect(subject[:token_expired]).to eq true }
end
context 'token not expired' do
before { allow(google_account).to receive(:token_expired?).and_return(false) }
it { expect(subject[:token_expired]).to eq false }
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160401173537_add_remote_id_index_to_relay_accounts.rb
|
class AddRemoteIdIndexToRelayAccounts < ActiveRecord::Migration
def up
execute 'create unique index index_remote_id_on_person_relay_account '\
'on person_relay_accounts(lower(remote_id));'
end
def down
execute 'drop index if exists index_remote_id_on_person_relay_account'
end
end
|
chuckmersereau/api_practice
|
app/workers/cleanup/newsletter_task_cleanup_worker.rb
|
class Cleanup::NewsletterTaskCleanupWorker
include Sidekiq::Worker
# we normally don't put things in this queue because it is only run by one legacy worker (we had one
# queue reserved for mpdx classic that we haven't repurposed yet), but it seems logical to use it for this.
sidekiq_options queue: :default
# provide a comment if you want a way to group these actions in the audit logs
# provide a before_date if you want to only delete things created before a certain date
def perform(account_list_id, comment = nil, before_date = nil)
bad_tasks = Task.where(account_list_id: account_list_id,
activity_type: ['Newsletter - Physical', 'Newsletter - Email'],
remote_id: nil)
.includes(:activity_contacts, :account_list)
bad_tasks = bad_tasks.where('created_at < ?', before_date) if before_date
bad_tasks.find_each { |task| destroy_task(task, comment) }
end
private
def destroy_task(task, comment)
Task.transaction do
task.audit_comment = comment
task.skip_contact_task_counter_update = true
task.activity_contacts.each do |ac|
ac.audit_comment = comment
ac.skip_contact_task_counter_update = true
ac.destroy
end
task.destroy
end
end
end
|
chuckmersereau/api_practice
|
spec/services/employee_csv_importer_spec.rb
|
<filename>spec/services/employee_csv_importer_spec.rb
require 'rails_helper'
RSpec.describe EmployeeCsvImporter, type: :service do
describe 'REQUIRED_HEADERS' do
it 'returns the correct values' do
expected_headers = %w(
email
first_name
last_name
relay_guid
key_guid
)
expect(EmployeeCsvImporter::REQUIRED_HEADERS).to match expected_headers
end
end
describe '#initialize' do
it 'initializes with a path to a file or URL' do
importer = build_importer(path: 'https://google.com')
expect(importer.path).to eq 'https://google.com'
end
end
describe '#converted_data' do
it 'creates new objects from the row_data' do
importer = build_importer
expect(importer.converted_data.count).to eq 100
expect(importer.converted_data.first).to be_kind_of EmployeeCsvImporter::UserForImport
end
it 'returns objects with needed CAS attributes' do
importer = build_importer
user_for_import = importer.converted_data.first
expected_attributes_for_cas_importer = {
email: '<EMAIL>',
firstName: 'Adah',
lastName: 'Huels',
relayGuid: 'f5472481-bcee-4e9b-b7ad-00407b0eb04f',
ssoGuid: 'a7d48686-8385-42d6-8cd7-9f33adfab03',
theKeyGuid: 'a7d48686-8385-42d6-8cd7-9f33adfab03'
}
expect(user_for_import.cas_attributes)
.to eq expected_attributes_for_cas_importer
end
end
describe '#import' do
it 'delegates a range of converted_data items to UserFromCasService' do
importer = build_importer
first_user = importer.converted_data[0]
second_user = importer.converted_data[1]
third_user = importer.converted_data[2]
expect(UserFromCasService)
.to receive(:find_or_create)
.with(first_user.cas_attributes)
expect(UserFromCasService)
.to receive(:find_or_create)
.with(second_user.cas_attributes)
expect(UserFromCasService)
.to receive(:find_or_create)
.with(third_user.cas_attributes)
importer.import(from: 0, to: 2)
end
end
describe '#queue!' do
it 'will, based on the group size, queue up imports' do
group_size = 20
importer = build_importer(import_group_size: group_size)
sidekiq_queue_double = double('sidekiq_queue_double')
(0..4).each do |num|
expected_from = (num * group_size)
expected_to = expected_from + 19
expect(EmployeeCsvGroupImportWorker)
.to receive(:perform_in)
.with(num.hours, sample_data_path, expected_from, expected_to)
.and_return(sidekiq_queue_double)
end
importer.queue!
end
end
describe '#row_data' do
context 'with data that has valid headers' do
it 'returns the rows for the provided CSV' do
importer = build_importer
expect(importer.row_data).to be_kind_of CSV::Table
expect(importer.row_data.count).to eq 100
end
end
context 'with data that has invalid headers' do
it 'returns the rows for the provided CSV' do
importer = build_importer(path: invalid_headers_sample_data_path)
required_headers_list = EmployeeCsvImporter::REQUIRED_HEADERS.join(', ')
invalid_headers_list = 'cn, givenName, sn, employeeNumber, relayGuid, thekeyGuid'
message = "Your CSV file must have the headers: #{required_headers_list}, instead it has: #{invalid_headers_list}"
expect { importer.row_data }
.to raise_error(EmployeeCsvImporter::InvalidHeadersError)
.with_message(message)
end
end
end
describe '.import' do
it 'delegates to an instance of EmployeeCsvImporter' do
instance = double('employee_csv_importer')
allow(EmployeeCsvImporter)
.to receive(:new)
.with(path: sample_data_path)
.and_return(instance)
expect(instance).to receive(:import).with(from: 5, to: 10)
EmployeeCsvImporter.import(
path: sample_data_path,
from: 5,
to: 10
)
end
end
describe '.queue' do
it 'delegates to an instance of EmployeeCsvImporter' do
instance = double('employee_csv_importer')
allow(EmployeeCsvImporter)
.to receive(:new)
.with(path: sample_data_path, import_group_size: 10)
.and_return(instance)
expect(instance).to receive(:queue!)
EmployeeCsvImporter.queue(
path: sample_data_path,
import_group_size: 10
)
end
end
private
def build_importer(path: nil, import_group_size: nil)
path ||= sample_data_path
EmployeeCsvImporter.new(path: path, import_group_size: import_group_size)
end
def sample_data_path
Rails
.root
.join('spec/fixtures/employee_csv_importer/sample_employee_data.csv')
end
def invalid_headers_sample_data_path
Rails
.root
.join('spec/fixtures/employee_csv_importer/invalid_headers_sample.csv')
end
end
|
chuckmersereau/api_practice
|
app/serializers/balance_serializer.rb
|
class BalanceSerializer < ApplicationSerializer
belongs_to :resource
attributes :balance
end
|
chuckmersereau/api_practice
|
lib/json_api_service/object_store.rb
|
<filename>lib/json_api_service/object_store.rb<gh_stars>0
module JsonApiService
class ObjectStore
attr_reader :items
def initialize
@items = {}
end
def [](type)
items[type] || []
end
def add(data_object)
id = data_object.id
type = data_object.type
items[type] ||= {}
items[type][id] ||= data_object
self
end
def promote(item_to_promote)
type = item_to_promote.type
id = item_to_promote.id
return unless id && type
items[type][id] = item_to_promote
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170330210139_add_amount_currency_to_pledges.rb
|
<filename>db/migrate/20170330210139_add_amount_currency_to_pledges.rb<gh_stars>0
class AddAmountCurrencyToPledges < ActiveRecord::Migration
def change
add_column :pledges, :amount_currency, :string
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/exclude_tags.rb
|
class Contact::Filter::ExcludeTags < Contact::Filter::Base
def execute_query(contacts, filters)
tags = parse_list(filters[:exclude_tags])
contacts.tagged_with(escape_backslashes(tags), exclude: true)
end
private
# SQL's ILIKE query requires backslashes to be escaped, but the
# ActsAsTaggableOn gem doesn't do this, so we must.
def escape_backslashes(tags)
tags.map { |t| t.gsub('\\', '\\\\\\') }
end
end
|
chuckmersereau/api_practice
|
app/workers/duplicate_tasks_per_contact.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class DuplicateTasksPerContact
include Sidekiq::Worker
LOG_DIR = 'worker_results'.freeze
sidekiq_options queue: :default, unique: :until_executed
# @param account_list [AccountList, Integer, nil] an optional +AccountList+
# (or its ID) that owns the Tasks duplicate
# @param min_contacts [Integer] Tasks with more than this number of Contacts
# will be duplicated
# @param upload_log [Boolean] should a log file be uploaded to AWS S3?
def perform(account_list = nil, min_contacts = 100, upload_log = true)
new_tasks = {}
scope = task_scope(account_list)
Task.transaction do
scope.group('activities.id')
.having('count(activity_contacts.id) >= ?', min_contacts)
.find_each { |t| new_tasks[t.id] = duplicate_task!(t) }
Task.import!(new_tasks.values.flatten, recursive: true)
end
account_list_id = account_list.is_a?(Integer) ? account_list : account_list&.id
upload_log_to_s3(account_list_id, new_tasks, prefix: LOG_DIR) if upload_log
end
private
def task_scope(account_list)
scope = account_list ? Task.where(account_list: account_list) : Task
scope.joins(:activity_contacts).includes(:comments)
end
def duplicate_task!(task)
comment_attributes = task.comments.map { |c| c.attributes.slice('body') }
new_tasks =
task.contacts[1..-1].map do |contact|
task.dup.tap do |t|
t.assign_attributes(id: nil, contacts: [contact])
comment_attributes.each { |attr| t.comments.build(attr) }
end
end
# original task remains owned by the first contact
task.update!(contacts: [task.contacts.first])
new_tasks
end
def upload_log_to_s3(account_list_id, records, prefix: nil)
started_at = Time.zone.now
conn = Fog::Storage.new(provider: 'AWS',
aws_access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
aws_secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'))
dir = conn.directories.get(ENV.fetch('AWS_BUCKET'))
path = log_path(started_at, account_list_id, prefix: prefix)
file = dir.files.new(key: path, body: log_body(records, started_at))
file.save
Rails.logger.fatal "Saved in #{ENV.fetch('AWS_BUCKET')} bucket at #{path}"
end
def log_path(started_at, account_list_id, prefix: nil, delimiter: '/')
[
prefix,
("account-list-#{account_list_id}" if account_list_id),
"duplicate_tasks_per_contact__#{started_at}.log"
].compact.join(delimiter)
end
# @param records [Hash<Integer, Array<Task>]
def log_body(records, started_at)
body = "workers/duplicate_tasks_per_contact.rb: #{started_at}"
rows = records.map { |id, tasks| [id, tasks.map(&:id).join(' ')].join("\t") }
[body, ('=' * body.size), rows.join("\n"), 'Done!'].join("\n")
end
end
|
chuckmersereau/api_practice
|
spec/factories/person_facebook_accounts.rb
|
<reponame>chuckmersereau/api_practice<filename>spec/factories/person_facebook_accounts.rb
FactoryBot.define do
factory :facebook_account, class: 'Person::FacebookAccount' do
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
username { Faker::Internet.user_name("#{first_name} #{last_name}") }
association :person
sequence(:remote_id, 1)
token '<PASSWORD>'
token_expires_at { 1.day.from_now }
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/tasks_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Tasks' do
include_context :json_headers
documentation_scope = :entity_tasks
doc_helper = DocumentationHelper.new(resource: :tasks)
let(:resource_type) { 'tasks' }
let!(:user) { create(:user_with_full_account) }
let!(:task) { create(:task, account_list: user.account_lists.order(:created_at).first) }
let(:id) { task.id }
let(:new_task) do
attributes_for(:task)
.reject { |key| key.to_s.end_with?('_id') }
.except(:id, :completed, :notification_sent)
.merge(updated_in_db_at: task.updated_at)
end
let(:form_data) do
build_data(new_task, account_list_id: user.account_lists.order(:created_at).first.id)
end
let(:resource_attributes) do
%w(
activity_type
comments_count
completed
completed_at
created_at
location
next_action
notification_time_before
notification_time_unit
notification_type
result
starred
start_at
subject
subject_hidden
tag_list
updated_at
updated_in_db_at
)
end
let(:resource_associations) do
%w(
account_list
activity_contacts
comments
contacts
email_addresses
people
phone_numbers
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/tasks' do
parameter 'filter', 'Filter the list of returned tasks. Any filter '\
'can be reversed by adding reverse_FILTER_NAME_HERE = true'
parameter 'filter[account_list_id]', 'Filter by Account List; Accepts Account List ID', required: false
parameter 'filter[activity_type][]', 'Filter by Action; Accepts multiple parameters, '\
'with values "Call", "Appointment", "Email", '
parameter 'filter[account_list_id]', 'Filter by Account List; Accepts Account List ID', required: false
parameter 'filter[activity_type][]', 'Filter by Action; Accepts multiple parameters, with values '\
'"Call", "Appointment", "Email", "Text Message", '\
'"Facebook Message", "Letter", "Newsletter", '\
'"Pre Call Letter", "Reminder Letter", "Support Letter", '\
'"Thank", "To Do", "Talk to In Person", or '\
'"Prayer Request"', required: false
parameter 'filter[completed]', 'Filter by Completed; Accepts values "true", or "false"', required: false
parameter 'filter[contact_ids][]', 'Filter by Contact IDs; Accepts multiple '\
'parameters, with Contact IDs', required: false
parameter 'filter[date_range]', 'Filter by Date Range; Accepts values "last_month", '\
'"last_year", "last_two_years", "last_week", '\
'"overdue", "today", "tomorrow", "future", and "upcoming"', required: false
parameter 'filter[overdue]', 'Filter by Overdue; Accepts values "true", or "false"', required: false
parameter 'filter[starred]', 'Filter by Starred; Accepts values "true", or "false"', required: false
parameter 'filter[tags][]', 'Filter by Tags; Accepts multiple '\
'parameters, with text values', required: false
parameter 'filter[wildcard_search]', 'Filter by keyword, searches through subject and tags', required: false
parameter 'filter[any_filters]', 'If set to true any result where at least '\
'one of the filters apply will be returned', required: false
parameter 'filter[reverse_FILTER_NAME]', 'If set to true, the filter defined as FILTER_NAME '\
"will return results that don't apply", required: false
with_options scope: :sort do
parameter :completed_at, 'Sort by CompletedAt'
parameter :created_at, 'Sort By CreatedAt'
parameter :updated_at, 'Sort By UpdatedAt'
end
response_field :data, 'list of task objects', 'Type' => 'Array[Object]'
response_field :data, 'list of task objects', type: 'Array[Object]'
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/tasks/:id' do
parameter :id, 'the Id of the Task'
with_options scope: :data do
response_field 'id', 'Task id', type: 'Number'
response_field 'relationships', 'List of relationships related to that task object', type: 'Array[Object]'
response_field 'type', 'Type of object (Task in this case)', type: 'String'
with_options scope: :attributes do
response_field 'account_list_id', 'Account List Id', 'Type' => 'Number'
response_field 'activity_type', 'Activity Type', 'Type' => 'String'
response_field 'created_at', 'Created At', 'Type' => 'String'
response_field 'comments_count', 'Comments Count', 'Type' => 'Number'
response_field 'completed', 'Completed', 'Type' => 'Boolean'
response_field 'completed_at', 'Completed At', 'Type' => 'String'
response_field 'due_date', 'Due Date', 'Type' => 'String'
response_field 'location', 'Location', 'Type' => 'String'
response_field 'next_action', 'Next Action', 'Type' => 'String'
response_field 'notification_time_before', 'Notification Time Before', 'Type' => 'Number'
response_field 'notification_time_unit', 'Notification Time Unit', 'Type' => 'String'
response_field 'notification_type', 'Notification Type', 'Type' => 'String'
response_field 'restult', 'Result', 'Type' => 'String'
response_field 'starred', 'Starred', 'Type' => 'Boolean'
response_field 'start_at', 'Start At', 'Type' => 'String'
response_field 'subject', 'Subject', 'Type' => 'String'
response_field 'tag_list', 'Tag List', 'Type' => 'String'
response_field 'updated_at', 'Updated At', 'Type' => 'String'
response_field 'updated_in_db_at', 'Updated In Db At', 'Type' => 'String'
end
end
example doc_helper.title_for(:show), document: doc_helper.document_scope do
explanation doc_helper.description_for(:show)
do_request
check_resource(['relationships'])
expect(response_status).to eq 200
end
end
post '/api/v2/tasks' do
with_options scope: [:data, :attributes] do
parameter 'account_list_id', 'Account List Id', type: 'Number'
parameter 'activity_type', 'Activity Type', type: 'String'
parameter 'completed', 'Completed', type: 'Boolean'
parameter 'end_at', 'End At', type: 'String'
parameter 'location', 'Location', type: 'String'
parameter 'next_action', 'Next Action', type: 'String'
parameter 'notification_time_before', 'Notification Time Before', type: 'Number'
parameter 'notification_time_unit', 'Notification Time Unit', type: 'String'
parameter 'notification_type', 'Notification Type', type: 'String'
parameter 'remote_id', 'Remote Id', type: 'String'
parameter 'result', 'Result', type: 'String'
parameter 'source', 'Source', type: 'String'
parameter 'starred', 'Starred', type: 'Boolean'
parameter 'start_at', 'Start At', type: 'String'
parameter 'subject', 'Subject', type: 'String', required: true
parameter 'type', 'Type', type: 'String'
end
example doc_helper.title_for(:create), document: doc_helper.document_scope do
explanation doc_helper.description_for(:create)
do_request data: form_data
expect(resource_object['subject']).to eq new_task[:subject]
expect(response_status).to eq 201
end
end
put '/api/v2/tasks/:id' do
doc_helper.insert_documentation_for(action: :update, context: self)
example doc_helper.title_for(:update), document: doc_helper.document_scope do
explanation doc_helper.description_for(:update)
do_request data: form_data
expect(resource_object['subject']).to eq new_task[:subject]
expect(response_status).to eq 200
end
end
delete '/api/v2/tasks/:id' do
example 'Delete a task', document: documentation_scope do
explanation 'Delete the current_user\'s Task with the given ID'
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
spec/support/shared_controller_examples/show_examples.rb
|
<reponame>chuckmersereau/api_practice
RSpec.shared_examples 'show_examples' do |options = {}|
options[:except] ||= []
include_context 'common_variables'
describe '#show' do
include_examples 'including related resources examples', action: :show unless options[:except].include?(:includes)
include_examples 'sparse fieldsets examples', action: :show unless options[:except].include?(:sparse_fieldsets)
it 'shows resource to users that are signed in' do
api_login(user)
get :show, full_params
expect(response.status).to eq(200), invalid_status_detail
expect(response.body)
.to include(resource.send(reference_key).to_json) if reference_key
end
it 'does not show resource to users that do not own the resource' do
if defined?(id)
api_login(create(:user))
get :show, full_params
expect(response.status).to eq(403), invalid_status_detail
end
end
it 'does not show resource to users that are not signed in' do
get :show, full_params
expect(response.status).to eq(401), invalid_status_detail
end
end
end
|
chuckmersereau/api_practice
|
spec/models/pledge_donation_spec.rb
|
require 'rails_helper'
RSpec.describe PledgeDonation do
context '#processed status' do
let(:appeal) { create(:appeal) }
let(:pledge) { create(:pledge, donations: [donation_one], amount: 400.00, appeal: appeal) }
let(:donation_one) { create(:donation, amount: 200.00, appeal: appeal) }
let(:donation_two) { create(:donation, amount: 200.00, appeal: appeal) }
it 'is removed when associated donations are missing from pledge' do
expect(pledge).to_not be_processed
donation_two.update(pledges: [pledge])
donation_two.destroy
expect(pledge.reload).to_not be_processed
end
it 'is added when donations are all associated to pledge' do
donation_two.update(pledges: [pledge])
expect(pledge).to be_processed
end
it 'can be destroyed if pledge is nil' do
pledge = PledgeDonation.create
expect { pledge.destroy }.to_not raise_exception
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/newsletter.rb
|
class Contact::Filter::Newsletter < Contact::Filter::Base
def execute_query(contacts, filters)
contacts = case filters[:newsletter]
when 'all'
contacts.where.not(send_newsletter: [nil, '', 'None'])
when 'no_value'
contacts.where(send_newsletter: [nil, ''])
when 'none'
contacts.where(send_newsletter: 'None')
when 'address'
contacts.where(send_newsletter: %w(Physical Both))
when 'email'
contacts.where(send_newsletter: %w(Email Both))
when 'address_only'
contacts.where(send_newsletter: 'Physical')
when 'email_only'
contacts.where(send_newsletter: 'Email')
when 'both'
contacts.where(send_newsletter: 'Both')
else
contacts
end
contacts
end
def title
_('Newsletter Recipients')
end
def type
'radio'
end
def default_options
[]
end
def custom_options
[{ name: _('Nothing Selected'), id: 'no_value' },
{ name: _('None'), id: 'none' },
{ name: _('All'), id: 'all' },
{ name: _('Physical and Both'), id: 'address' },
{ name: _('Email and Both'), id: 'email' },
{ name: _('Physical Only'), id: 'address_only' },
{ name: _('Email Only'), id: 'email_only' },
{ name: _('Both Only'), id: 'both' }]
end
end
|
chuckmersereau/api_practice
|
app/models/help_request.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
# The HelpRequest feature is actively used on Classic MPDX, but not on API. We can consider removing it after Classic is retired.
require 'user_agent_decoder'
class HelpRequest < ApplicationRecord
mount_uploader :file, HelpRequestUploader
attr_accessor :user_agent
belongs_to :account_list
belongs_to :user
serialize :session, JSON
serialize :user_preferences, JSON
serialize :account_list_preferences, JSON
validates :name, :email, :problem, :request_type, presence: true
validates :email, email: true
def user_agent=(val)
@user_agent = val
self.browser = parse_browser(val)
end
def self.attachment_token(id)
message_verifier.generate(id)
end
def self.decrypt_token(signed_message)
message_verifier.verify(signed_message)
rescue ActiveSupport::MessageVerifier::InvalidSignature
end
def self.message_verifier
@message_verifier ||= ActiveSupport::MessageVerifier.new(ENV.fetch('ATTACHMENT_SECRET'))
end
private
def parse_browser(user_agent)
return '' unless user_agent
decoder = UserAgentDecoder.new(user_agent).parse
decoder[:browser][:name] + ' ' + decoder[:browser][:version]
end
end
|
chuckmersereau/api_practice
|
dev/fixers/make_account_multi_currency.rb
|
<gh_stars>0
# Provides a quick and dirty way to turn an account list into a multi-currency
# account for test purposes. Note that once the donation import is run again for
# this account the currencies will revert back to what they were from
# DataServer/Siebel. You can get around that by disconnecting the account from
# say ToonTown assumming no other users also have a connection to it.
def make_account_multi_currency(account_list)
account_list.contacts.find_each do |contact|
puts contact.id
if (contact.id % 3).zero?
contact.update(pledge_currency: 'GBP')
contact.donations.update_all(currency: 'GBP', tendered_currency: 'GBP')
elsif (contact.id % 5).zero?
contact.update(pledge_currency: 'EUR')
contact.donations.update_all(currency: 'EUR', tendered_currency: 'EUR')
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/mail_chimp_accounts.rb
|
FactoryBot.define do
factory :mail_chimp_account do
api_key 'fake-us4'
active false
primary_list_id 'MyString'
association :account_list
end
end
|
chuckmersereau/api_practice
|
app/exhibits/task_exhibit.rb
|
<filename>app/exhibits/task_exhibit.rb
class TaskExhibit < DisplayCase::Exhibit
def self.applicable_to?(object)
object.class.name == 'Task'
end
def to_s
subject
end
def css_class
if to_model.start_at < Time.now then 'high'
elsif to_model.start_at < Time.now + 1.day then 'mid'
else ''
end
end
def completed_at
to_model.completed_at ? @context.l(to_model.completed_at.to_datetime) : ''
end
def start_at
to_model.start_at ? @context.l(to_model.start_at.to_datetime) : ''
end
end
|
chuckmersereau/api_practice
|
spec/models/contact_person_spec.rb
|
<filename>spec/models/contact_person_spec.rb
require 'rails_helper'
describe ContactPerson do
# its hard to test delete_orphaned_person because after_commit doesn't get
# fired in rspec :(
end
|
chuckmersereau/api_practice
|
db/migrate/20160204190034_add_index_to_master_addresses_latitude.rb
|
<reponame>chuckmersereau/api_practice
class AddIndexToMasterAddressesLatitude < ActiveRecord::Migration
self.disable_ddl_transaction!
def change
add_index :master_addresses, :latitude, algorithm: :concurrently
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/invites_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::AccountLists::InvitesController, type: :controller do
let(:factory_type) { :account_list_invite }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:invite) do
create(:account_list_invite,
account_list: account_list,
invited_by_user: user,
accepted_by_user: nil,
cancelled_by_user: nil)
end
let!(:second_invite) do
create(:account_list_invite,
account_list: account_list,
invited_by_user: user,
accepted_by_user: nil,
cancelled_by_user: nil)
end
let(:id) { invite.id }
let(:resource) { invite }
let(:parent_param) { { account_list_id: account_list_id } }
let(:unpermitted_attributes) { nil }
let(:correct_attributes) { { recipient_email: '<EMAIL>' } }
let(:incorrect_attributes) { { recipient_email: nil } }
let(:unpermitted_attributes) { nil }
let(:correct_relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: account_list_id
}
}
}
end
include_examples 'index_examples'
include_examples 'show_examples'
include_examples 'create_examples'
describe '#update / accept' do
let(:correct_attributes) { { code: invite.code } }
before do
api_login(user)
end
it 'returns a 401 when a user is not logged in' do
api_logout
expect do
put :update, full_correct_attributes
end.to_not change { invite.reload.accepted_at }
expect(response.status).to eq 401
end
it 'returns a 400 when a blank code is passed' do
full_correct_attributes[:data][:attributes][:code] = ''
expect do
put :update, full_correct_attributes
end.to_not change { invite.reload.accepted_at }
expect(response.status).to eq 400
end
it 'returns a 400 when the code is wrong' do
full_correct_attributes[:data][:attributes][:code] = 'wrong code'
expect do
put :update, full_correct_attributes
end.to_not change { invite.reload.accepted_at }
expect(response.status).to eq 400
end
it 'returns a 404 when the id is not related to the account_list specified' do
full_correct_attributes[:id] = create(:account_list_invite).id
expect do
put :update, full_correct_attributes
end.to_not change { invite.reload.accepted_at }
expect(response.status).to eq 404
end
it 'returns a 410 when the invite was cancelled' do
invite.update(cancelled_by_user: create(:user))
expect do
put :update, full_correct_attributes
end.to_not change { invite.reload.accepted_at }
expect(response.status).to eq 410
end
it 'returns a 200 when the invite can be accepted' do
expect do
put :update, full_correct_attributes
end.to change { invite.reload.accepted_at }
expect(response.status).to eq 200
end
end
describe '#destroy' do
it 'returns a 401 when a user is not logged in' do
expect do
delete :destroy, account_list_id: account_list_id, id: id
end.to_not change { invite.reload.cancelled_by_user }
expect(response.status).to eq 401
end
it 'returns a 204 and deletes the invite when a user has correct access' do
api_login(user)
expect do
delete :destroy, account_list_id: account_list_id, id: id
end.to change { invite.reload.cancelled_by_user }
expect(response.status).to eq 204
end
end
end
|
chuckmersereau/api_practice
|
lib/json_api_service/errors.rb
|
<filename>lib/json_api_service/errors.rb
module JsonApiService
class InvalidTypeError < StandardError; end
class InvalidPrimaryKeyPlacementError < StandardError; end
class MissingTypeError < StandardError; end
class ForeignKeyPresentError < StandardError; end
end
|
chuckmersereau/api_practice
|
db/migrate/20140618153152_add_action_to_activity.rb
|
<reponame>chuckmersereau/api_practice<filename>db/migrate/20140618153152_add_action_to_activity.rb
class AddActionToActivity < ActiveRecord::Migration
def change
add_column :activities, :next_action, :string
end
end
|
chuckmersereau/api_practice
|
spec/serializers/coaching/account_list_serializer_spec.rb
|
require 'rails_helper'
RSpec.describe Coaching::AccountListSerializer, type: :serializer do
let(:organization) { create(:organization) }
let(:account_list) { create(:account_list, salary_organization_id: organization) }
let(:serializer) { Coaching::AccountListSerializer.new(account_list) }
subject { serializer }
context '#balance' do
it { expect(subject.balance).to be_a String }
it { expect(subject.balance).to include '$' }
end
context '#committed' do
it { expect(subject.committed).to be_a Numeric }
end
context '#received' do
it { expect(subject.received).to be_a Numeric }
end
context '#progress' do
it { expect(subject.progress).to be_a Hash }
it do
expect(subject.progress.keys).to include :monthly_goal, :pledged_percent,
:received_pledges, :total_pledges
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170926162140_remove_status_validated_at_from_contacts.rb
|
class RemoveStatusValidatedAtFromContacts < ActiveRecord::Migration
def change
remove_column :contacts, :status_validated_at, :datetime
end
end
|
chuckmersereau/api_practice
|
app/services/donation_imports/siebel/find_donation.rb
|
<filename>app/services/donation_imports/siebel/find_donation.rb
class DonationImports::Siebel
class FindDonation < DonationImports::Base::FindDonation
end
end
|
chuckmersereau/api_practice
|
spec/services/donation_imports/base/merge_donations_spec.rb
|
require 'rails_helper'
RSpec.describe DonationImports::Base::MergeDonations do
describe 'initialize' do
it 'initializes' do
expect(described_class.new([])).to be_a(described_class)
end
end
describe '#merge' do
let!(:account_list) { create(:account_list) }
let!(:donor_account) { create(:donor_account, total_donations: 0) }
let!(:designation_account) { create(:designation_account).tap { |da| da.account_lists << account_list } }
let(:appeal_id) { SecureRandom.uuid }
let!(:contact) do
create(:contact, account_list: account_list, total_donations: 0).tap { |c| c.donor_accounts << donor_account }
end
let!(:donation_one) do
create(:donation, appeal_id: appeal_id, tnt_id: nil, motivation: nil, amount: 1.0, donation_date: Date.new,
donor_account: donor_account, designation_account: designation_account)
end
let!(:donation_two) do
create(:donation, appeal_id: nil, tnt_id: '2', motivation: nil, amount: 1.0, donation_date: Date.new,
donor_account: donor_account, designation_account: designation_account)
end
let!(:donation_three) do
create(:donation, appeal_id: nil, tnt_id: '2', motivation: 'Motivation', amount: 1.0, donation_date: Date.new,
donor_account: donor_account, designation_account: designation_account)
end
let!(:other_donation) do
create(:donation, amount: 1.0, donor_account: donor_account, designation_account: designation_account)
end
it 'returns if the donations has one or zero elements' do
expect do
expect(described_class.new([donation_one]).merge).to eq(donation_one)
expect(described_class.new([]).merge).to eq(nil)
end.to_not change { Donation.count }.from(4)
end
it 'merges the donations' do
expect do
expect(described_class.new([donation_one, donation_two, donation_three]).merge).to eq(donation_one)
end.to change { Donation.count }.from(4).to(2)
expect(donation_one.reload.appeal_id).to eq(appeal_id)
expect(donation_one.tnt_id).to eq('2')
expect(donation_one.motivation).to eq('Motivation')
end
it 'resets the donor account donation totals' do
expect(donor_account.reload.total_donations).to eq(4)
described_class.new([donation_one, donation_two, donation_three]).merge
expect(donor_account.reload.total_donations).to eq(2)
end
it 'resets the contact donation totals' do
expect(contact.reload.total_donations).to eq(4)
described_class.new([donation_one, donation_two, donation_three]).merge
expect(contact.reload.total_donations).to eq(2)
end
end
end
|
chuckmersereau/api_practice
|
app/services/human_name_parser.rb
|
# This class attempts to parse a human name contained in a single String into smaller parts (as a Hash).
# The 'nameable' gem helps us do this. The nameable gem does not handle couple names, so we take care of
# splitting a couple name, as well as some other cleanup for couple names.
# Nameable should not need to be referenced outside of this class.
#
# Known limitations:
# * If a couple has different last names or middle names then it can be hard to differentiate them.
# * Does not handle non-human names (like businesses).
# * Not well tested on non-American names.
require 'nameable'
class HumanNameParser
def initialize(input_name)
@input_name = input_name
end
def parse
names_hash = build_names_hash
fill_in_middle_and_last_names_after_parsing(names_hash)
end
private
attr_accessor :input_name
def build_names_hash
{
first_name: parsed_names.first&.first,
middle_name: parsed_names.first&.middle,
last_name: parsed_names.first&.last,
spouse_first_name: parsed_names.second&.first,
spouse_middle_name: parsed_names.second&.middle,
spouse_last_name: parsed_names.second&.last
}
end
def parsed_names
@parsed_names ||= names.collect do |name|
begin
Nameable.parse(name)
rescue Nameable::InvalidNameError
if known_unparsable(name)
Nameable::Latin.new(first: name)
else
notify_rollbar(name)
Nameable::Latin.new
end
end
end
end
def notify_rollbar(name)
Rollbar.info(UnparsableNameError.new('A parseable name was not found.'),
name: name,
input_name: input_name)
end
# a list (mostly from Rollbar) of the strings that people enter as first names.
# This will return true if there are an number of these single characters in a row.
def known_unparsable(name)
[['.'], ['?'], [':'], ['!'], [',']].include? name.chars.to_a.uniq
end
def names
clean_input_name.split(' and ')
end
def clean_input_name
remove_couple_prefix(
remove_parenthesis(
normalize_and(input_name.strip)
)
).strip.squish
end
# Remove couple prefixes, like "Mr. and Mrs."
def remove_couple_prefix(string)
string.gsub(/\Am(rs|r|s|iss){1}[.]?\s*(and|&)\s*m(rs|r|s|iss){1}[.]?/i, '')
end
# Remove parenthesis, which are often used for nicknames or secondary info.
def remove_parenthesis(string)
string.gsub(/\([^()]*\)/, '')
.gsub('()', '')
end
def normalize_and(string)
string.gsub(/\sand\s/i, ' and ').gsub(' & ', ' and ')
end
# Try to fixup the middle and last names by comparing the two couples to each other.
def fill_in_middle_and_last_names_after_parsing(names_hash)
# This is necessary because often a couple's last name is only present once in the input:
# e.g. in "John and <NAME>" there is no last name given for John.
# Also, in this situation the last name can become confused with a middle name:
# e.g. in "Doe, John and <NAME>" it looks like Jane's last name is "Louise" but really it's "Doe".
#
# We know that there will never be a middle name without a last name at this point
# (i.e. if a person has a middle name, it's because they also have a last name).
# If neither person has a middle name, then try to get a last name from whoever has it.
if names_hash[:middle_name].blank? && names_hash[:spouse_middle_name].blank?
if names_hash[:last_name].present?
names_hash[:spouse_middle_name] = names_hash[:spouse_last_name]
names_hash[:spouse_last_name] = names_hash[:last_name]
else
names_hash[:middle_name] = names_hash[:last_name]
names_hash[:last_name] = names_hash[:spouse_last_name]
end
# If only one has a middle name and the last names are different then the real middle name probably went into the last name.
elsif names_hash[:middle_name].blank? && (names_hash[:last_name] != names_hash[:spouse_last_name])
names_hash[:middle_name] = names_hash[:last_name]
names_hash[:last_name] = names_hash[:spouse_last_name]
elsif names_hash[:spouse_middle_name].blank? && (names_hash[:last_name] != names_hash[:spouse_last_name])
names_hash[:spouse_middle_name] = names_hash[:spouse_last_name]
names_hash[:spouse_last_name] = names_hash[:last_name]
end
# If there is no first name for the spouse then don't return anything for spouse.
if names_hash[:spouse_first_name].blank?
names_hash[:spouse_last_name] = nil
names_hash[:spouse_middle_name] = nil
end
names_hash
end
class UnparsableNameError < StandardError; end
end
|
chuckmersereau/api_practice
|
db/migrate/20130628201906_move_deceased_column_to_person.rb
|
class MoveDeceasedColumnToPerson < ActiveRecord::Migration
def up
add_column :people, :deceased, :boolean, default: false, null: false
Contact.where(deceased: true).find_each do |c|
c.people.each do |p|
p.update_column(:deceased, true)
end
end
remove_column :contacts, :deceased
end
def down
add_column :contats, :deceased, :boolean, default: false, null: false
Person.where(deceased: true).find_each do |p|
p.contact.update_column(:deceased, true)
end
remove_column :people, :deceased
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/person_import_spec.rb
|
require 'rails_helper'
describe TntImport::PersonImport do
include TntImportHelpers
let(:row) { tnt_import_parsed_xml_sample_contact_row }
let(:prefix) { '' }
let(:contact) { create(:contact) }
let(:override) { true }
let(:import) do
TntImport::PersonImport.new(row, contact, prefix, override)
end
describe '#add_or_update_person' do
it 'creates a person' do
expect { import.import }.to change { Person.count }.from(0).to(1)
end
end
context '#update_person_emails' do
let(:person) { create(:person) }
it 'imports emails and sets the first preferred and valid one to primary' do
row = { 'SpouseEmail1' => '<EMAIL>', 'SpouseEmail2' => '<EMAIL>', 'SpouseEmail3' => '<EMAIL>',
'SpouseEmail1IsValid' => 'true', 'SpouseEmail2IsValid' => 'false', 'SpouseEmail3IsValid' => 'true' }
prefix = 'Spouse'
expect(import).to receive(:tnt_email_preferred?).and_return(false, true)
import.send(:update_person_emails, person, row, prefix)
expect(person.email_addresses.size).to eq(3)
expect(person.email_addresses.map { |e| [e.email, e.primary] }).to include(['<EMAIL>', false])
expect(person.email_addresses.map { |e| [e.email, e.primary] }).to include(['<EMAIL>', false])
expect(person.email_addresses.map { |e| [e.email, e.primary] }).to include(['<EMAIL>', true])
end
it 'only marks one email as primary even if there are multiple that are preferred and valid' do
prefix = ''
row = { 'Email1' => '<EMAIL>', 'Email2' => '<EMAIL>', 'Email1IsValid' => 'true', 'Email2IsValid' => 'true' }
expect(import).to receive(:tnt_email_preferred?).at_least(:once).and_return(true)
import.send(:update_person_emails, person, row, prefix)
expect(person.email_addresses.size).to eq(2)
expect(person.email_addresses.map { |e| [e.email, e.primary] }).to include(['<EMAIL>', true])
expect(person.email_addresses.map { |e| [e.email, e.primary] }).to include(['<EMAIL>', false])
end
it 'marks tnt "invalid" email addresses as historic in mpdx' do
prefix = ''
row = { 'Email1' => '<EMAIL>', 'Email1IsValid' => 'false' }
import.send(:update_person_emails, person, row, prefix)
expect(person.email_addresses.order(:created_at).first.historic).to be true
person.email_addresses.destroy_all
prefix = 'Spouse'
row = { 'SpouseEmail1' => '<EMAIL>', 'SpouseEmail2' => '<EMAIL>',
'SpouseEmail1IsValid' => 'true', 'SpouseEmail2IsValid' => 'false' }
import.send(:update_person_emails, person, row, prefix)
expect(person.email_addresses.count).to eq(2)
expect(person.email_addresses.map { |e| [e.email, e.historic] }).to include(['<EMAIL>', false])
expect(person.email_addresses.map { |e| [e.email, e.historic] }).to include(['<EMAIL>', true])
end
it 'removes the name formatting and splits multiple emails in a field' do
row = {
'Email1' => '<NAME> <<EMAIL>>, "<NAME>" <<EMAIL>; <EMAIL>',
'Email1IsValid' => 'true', 'PreferredEmailTypes' => '1'
}
expect do
import.send(:update_person_emails, person, row, '')
end.to change(person.email_addresses, :count).from(0).to(3)
expect(person.email_addresses.pluck(:email).sort).to eq(['<EMAIL>', '<EMAIL>', '<EMAIL>'])
expect(person.email_addresses.where(primary: true).count).to eq(1)
expect(person.email_addresses.find_by(email: '<EMAIL>').primary).to be true
end
it 'imports deceased boolean value' do
row = { 'Deceased' => 'true' }
import.send(:update_person_attributes, person, row)
expect(person.deceased).to eq(true)
end
end
context '#update_person_phones' do
let(:person) { create(:person) }
it 'marks tnt "invalid" phone numbers as historic in mpdx' do
row = { 'HomePhone2' => '212-222-2222', 'SpouseMobilePhone' => '313-333-3333',
'PhoneIsValidMask' => '4096' }
prefix = 'Spouse'
import.send(:update_person_phones, person, row, prefix)
expect(person.phone_numbers.count).to eq(2)
expect(person.phone_numbers.map { |p| [p.number, p.historic] }).to include(['+12122222222', true])
expect(person.phone_numbers.map { |p| [p.number, p.historic] }).to include(['+13133333333', false])
end
end
context '#update_person_social_media_accounts' do
it 'creates the social accounts' do
expect { import.import }.to change { Person.count }.from(0).to(1)
person = Person.last
expect(person.facebook_accounts.size).to eq 1
expect(person.facebook_accounts.order(:created_at).first.username).to eq '@bobfacebook'
expect(person.linkedin_accounts.size).to eq 1
expect(person.linkedin_accounts.order(:created_at).first.public_url).to eq '@boblinkedin'
expect(person.twitter_accounts.size).to eq 1
expect(person.twitter_accounts.order(:created_at).first.screen_name).to eq '@bobtwitter'
expect(person.websites.size).to eq 2
expect(person.websites.order(:created_at).first.url).to eq 'www.bobwebpage.com'
expect(person.websites.order(:created_at).second.url).to eq 'www.bobwebpage2.com'
end
context 'spouse' do
let(:prefix) { 'Spouse' }
it 'creates the social accounts' do
expect { import.import }.to change { Person.count }.from(0).to(1)
person = Person.last
expect(person.facebook_accounts.size).to eq 1
expect(person.facebook_accounts.order(:created_at).first.username).to eq '@helenfacebook'
expect(person.linkedin_accounts.size).to eq 1
expect(person.linkedin_accounts.order(:created_at).first.public_url).to eq '@helenlinkedin'
expect(person.twitter_accounts.size).to eq 1
expect(person.twitter_accounts.order(:created_at).first.screen_name).to eq '@helentwitter'
expect(person.websites.size).to eq 2
expect(person.websites.order(:created_at).first.url).to eq 'www.helenparr.com'
expect(person.websites.order(:created_at).second.url).to eq 'www.helenparr2.com'
end
end
context 'no social accounts' do
before do
%w(SocialWeb1 SocialWeb2 SocialWeb3 SocialWeb4 WebPage1 WebPage2).each do |key|
row.delete(key)
row.delete("Spouse#{key}")
end
end
it 'does not create social accounts' do
expect { import.import }.to change { Person.count }.from(0).to(1)
person = Person.order(:created_at).last
expect(person.facebook_accounts.size).to eq 0
expect(person.linkedin_accounts.size).to eq 0
expect(person.twitter_accounts.size).to eq 0
expect(person.websites.size).to eq 0
end
end
context 'full facebook url' do
before do
row['SocialWeb1'] = 'https://www.facebook.com/bobfacebook'
end
it 'condenses url before attempting to create' do
expect { import.import }.to change { Person.count }.from(0).to(1)
person = Person.last
expect(person.facebook_accounts.size).to eq 1
expect(person.facebook_accounts.order(:created_at).first.username).to eq 'bobfacebook'
# re-run import to see if it tries to override the facebook account
expect { import.import }.to_not change(Person::FacebookAccount, :count)
end
end
context 'id based facebook url' do
before do
row['SocialWeb1'] = 'https://www.facebook.com/profile?id=1234'
end
it 'condenses url before attempting to create' do
expect { import.import }.to change { Person.count }.from(0).to(1)
person = Person.last
expect(person.facebook_accounts.size).to eq 1
facebook_account = person.facebook_accounts.order(:created_at).first
expect(facebook_account.username).to eq 'profile?id=1234'
expect(facebook_account.remote_id).to eq 1234
# re-run import to see if it tries to override the facebook account
expect { import.import }.to_not change(Person::FacebookAccount, :count)
end
end
end
context '#tnt_email_preferred?' do
it 'interprets the tntmpd bit vector for PreferredEmailTypes to return true/false for prefix and email num' do
{
[{ 'PreferredEmailTypes' => '0' }, 1, ''] => false,
[{ 'PreferredEmailTypes' => '0' }, 2, ''] => false,
[{ 'PreferredEmailTypes' => '2' }, 1, ''] => true,
[{ 'PreferredEmailTypes' => '2' }, 2, ''] => false,
[{ 'PreferredEmailTypes' => '6' }, 1, ''] => true,
[{ 'PreferredEmailTypes' => '6' }, 2, ''] => true,
[{ 'PreferredEmailTypes' => '8' }, 1, ''] => false,
[{ 'PreferredEmailTypes' => '8' }, 2, ''] => false,
[{ 'PreferredEmailTypes' => '8' }, 3, ''] => true,
[{ 'PreferredEmailTypes' => '2' }, 1, 'Spouse'] => false,
[{ 'PreferredEmailTypes' => '16' }, 1, 'Spouse'] => true,
[{ 'PreferredEmailTypes' => '16' }, 2, 'Spouse'] => false,
[{ 'PreferredEmailTypes' => '24' }, 1, 'Spouse'] => true,
[{ 'PreferredEmailTypes' => '24' }, 2, ''] => false,
[{ 'PreferredEmailTypes' => '24' }, 3, ''] => true,
[{ 'PreferredEmailTypes' => '32' }, 2, 'Spouse'] => true
}.each do |inputs, preferred|
row, email_num, person_prefix = inputs
expect(import.send(:tnt_email_preferred?, row, email_num, person_prefix)).to eq(preferred)
end
end
end
context '#update_person_attributes' do
it 'imports basic fields for a person' do
contact_row = {
'PreferredPhoneType' => '0',
'PhoneIsValidMask' => '4385',
'PhoneCountryIDs' => '0=840',
'HomePhone' => '(515) 555-1234',
'MobilePhone' => '213-211-1111',
'BusinessPhone' => '(515) 555-9771;ext=301',
'SpouseMobilePhone' => '212-222-2222',
'BirthdayMonth' => '9',
'BirthdayDay' => '20',
'BirthdayYear' => '1989',
'AnniversaryMonth' => '11',
'AnniversaryDay' => '4',
'AnniversaryYear' => '1994',
'Profession' => 'Janitor',
'SpouseProfession' => 'Custodian',
'BusinessName' => 'Business A',
'SpouseBusinessName' => 'Business 1'
}
person = Person.new
expect do
person = import.send(:update_person_attributes, person, contact_row)
end.to change(person.phone_numbers, :length).by(3)
expect(person.birthday_month).to eq(9)
expect(person.birthday_day).to eq(20)
expect(person.birthday_year).to eq(1989)
expect(person.anniversary_month).to eq(11)
expect(person.anniversary_day).to eq(4)
expect(person.anniversary_year).to eq(1994)
expect(person.occupation).to eq('Janitor')
expect(person.employer).to eq('Business A')
end
context 'override == true' do
let(:override) { true }
it 'ensures import\'s primary person is set as the contact\'s #primary_person' do
import.import
TntImport::PersonImport.new(row, contact, 'Spouse', true).import
spouse = contact.people.find { |p| p.id != contact.primary_person_id }
contact.primary_person_id = spouse.id
expect(contact.reload.primary_person.first_name).to eq 'Helen'
import.import
expect(contact.reload.primary_person.first_name).to eq 'Bob'
end
it 'overrides values previously set' do
import.import
TntImport::PersonImport.new(row, contact, 'Spouse', true).import
spouse = contact.people.find { |p| p.id != contact.primary_person_id }
spouse.update(occupation: 'Architect')
expect do
TntImport::PersonImport.new(row, contact, 'Spouse', override).import
end.to change { spouse.reload.occupation }.to("Helen's Profession")
end
end
context 'override == false' do
let(:override) { false }
it 'ensures import\'s primary person is set as the contact\'s #primary_person' do
import.import
TntImport::PersonImport.new(row, contact, 'Spouse', true).import
spouse = contact.people.find { |p| p.id != contact.primary_person_id }
contact.primary_person_id = spouse.id
expect(contact.reload.primary_person.first_name).to eq 'Helen'
import.import
expect(contact.reload.primary_person.first_name).to eq 'Helen'
end
it 'does not change values previously set' do
import.import
TntImport::PersonImport.new(row, contact, 'Spouse', true).import
spouse = contact.people.find { |p| p.id != contact.primary_person_id }
spouse.update(occupation: 'Architect')
expect do
TntImport::PersonImport.new(row, contact, 'Spouse', override).import
end.to_not change { spouse.reload.occupation }
end
end
end
it 'converts two digit years to four digits' do
contact_row = {
'PreferredPhoneType' => '0',
'PhoneIsValidMask' => '4385',
'PhoneCountryIDs' => '0=840',
'HomePhone' => '(515) 555-1234',
'MobilePhone' => '213-211-1111',
'BusinessPhone' => '(515) 555-9771;ext=301',
'SpouseMobilePhone' => '212-222-2222',
'BirthdayMonth' => '9',
'BirthdayDay' => '20',
'BirthdayYear' => '89',
'AnniversaryMonth' => '11',
'AnniversaryDay' => '4',
'AnniversaryYear' => '10'
}
person = Person.new
person = import.send(:update_person_attributes, person, contact_row)
expect(person.birthday_year).to eq(1989)
expect(person.anniversary_year).to eq(2010)
end
end
|
chuckmersereau/api_practice
|
spec/services/data_server_uk_spec.rb
|
<filename>spec/services/data_server_uk_spec.rb
require 'rails_helper'
describe DataServerUk do
let(:account_list) { create(:account_list) }
let!(:organization) { create(:organization, name: 'MyString') }
let!(:person) { create(:person) }
let!(:organization_account) { build(:organization_account, person: person, organization: organization) }
let!(:data_server) { described_class.new(organization_account) }
let(:profile) do
create(:designation_profile, organization: organization, user: person.to_user, account_list: account_list)
end
it 'should update a designation account balance when there is more than one designation number' do
stub_request(:post, /.*accounts/).to_return(
body: '"EMPLID","EFFDT","BALANCE","ACCT_NAME"'\
"\n"\
'"0000000,0000001","2012-03-23 16:01:39.0","123.45","Test Account"'\
"\n"
)
designation_account = create(:designation_account, organization: organization, designation_number: '0000000', balance: 0)
designation_account2 = create(:designation_account, organization: organization, designation_number: '0000001', balance: 0)
data_server.import_profile_balance(profile)
expect(designation_account.reload.balance).to eq(123.45)
expect(designation_account2.reload.balance).to eq(123.45)
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/people/twitter_accounts_spec.rb
|
<filename>spec/acceptance/api/v2/contacts/people/twitter_accounts_spec.rb
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts > People > Twitter Accounts' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:people, :twitter_accounts])
let(:resource_type) { 'twitter_accounts' }
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!(:person) { create(:person) }
let(:person_id) { person.id }
let!(:twitter_accounts) { create_list(:twitter_account, 2, person: person) }
let(:twitter_account) { twitter_accounts.first }
let(:id) { twitter_account.id }
let(:new_twitter_account) do
attributes_for(:twitter_account)
.reject { |key| key.to_s.end_with?('_id') || key.to_s.in?(%w(secret token)) }
.merge(updated_in_db_at: twitter_account.updated_at)
end
let(:form_data) { build_data(new_twitter_account) }
let(:expected_attribute_keys) do
%w(
created_at
primary
remote_id
screen_name
updated_at
updated_in_db_at
)
end
context 'authorized user' do
before do
contact.people << person
api_login(user)
end
get '/api/v2/contacts/:contact_id/people/:person_id/twitter_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
expect(response_status).to eq(200), invalid_status_detail
check_collection_resource(2)
expect(resource_object.keys).to match_array expected_attribute_keys
end
end
get '/api/v2/contacts/:contact_id/people/:person_id/twitter_accounts/: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
expect(response_status).to eq(200), invalid_status_detail
expect(resource_object.keys).to match_array expected_attribute_keys
end
end
post '/api/v2/contacts/:contact_id/people/:person_id/twitter_accounts' do
doc_helper.insert_documentation_for(action: :create, context: self)
example doc_helper.title_for(:create), document: doc_helper.document_scope do
explanation doc_helper.description_for(:create)
do_request data: form_data
expect(response_status).to eq(201), invalid_status_detail
end
end
put '/api/v2/contacts/:contact_id/people/:person_id/twitter_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: form_data
expect(response_status).to eq(200), invalid_status_detail
end
end
delete '/api/v2/contacts/:contact_id/people/:person_id/twitter_accounts/:id' do
doc_helper.insert_documentation_for(action: :delete, context: self)
example doc_helper.title_for(:delete), document: doc_helper.document_scope do
explanation doc_helper.description_for(:delete)
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/people/merges/bulk_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'People > Merges > Bulk' do
include_context :json_headers
documentation_scope = :people_api_merges
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:person_one) { create(:person, contacts: [contact]) }
let!(:person_two) { create(:person, contacts: [contact]) }
let!(:resource_type) { 'people' }
let!(:user) { create(:user_with_account) }
context 'authorized user' do
before { api_login(user) }
post '/api/v2/contacts/people/merges/bulk' do
with_options scope: [:data, :attributes] do
parameter 'winner_id', 'The ID of the person that should win the merge'
parameter 'loser_id', 'The ID of the person that should lose the merge'
end
example 'Merge People [BULK POST]', document: documentation_scope do
explanation 'Bulk merge People with the given IDs'
do_request data: [{ data: { attributes: { winner_id: person_one.id, loser_id: person_two.id } } }]
expect(response_status).to eq(200)
expect(json_response.size).to eq(1)
expect(json_response.collect { |hash| hash.dig('data', 'id') }).to match_array([person_one.id])
end
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/user/authenticates_controller.rb
|
<reponame>chuckmersereau/api_practice
class Api::V2::User::AuthenticatesController < Api::V2Controller
skip_before_action :authenticate!, :validate_and_transform_json_api_params
skip_after_action :verify_authorized
def create
require_cas_ticket
validate_cas_ticket
update_tracked_fields
queue_imports
render_authenticate
end
private
def require_cas_ticket
raise ActionController::ParameterMissing if cas_ticket_param.blank?
rescue ActionController::ParameterMissing
raise Exceptions::BadRequestError, 'Expected a cas_ticket to be provided in the attributes'
end
def validate_cas_ticket
cas_ticket_validator.validate
end
def cas_ticket_validator
@cas_ticket_validator ||= CasTicketValidatorService.new(ticket: cas_ticket_param, service: service)
end
def load_user
@user ||= UserFromCasService.find_or_create(cas_ticket_validator.attributes)
raise Exceptions::AuthenticationError unless @user
@user
end
def build_authenticate
@authenticate ||= ::User::Authenticate.new(authenticate_params)
end
def authenticate_params
{ user: load_user }
end
def cas_ticket_param
params.require('data').require('attributes')['cas_ticket']
end
def queue_imports
load_user.queue_imports
end
# The service should be a predetermined service URL for the MPDX API.
# It will be used by the API when validating the ticket (and also by clients to request a ticket).
# It's recommended to use the URL that the ticket is sent to on the MPDX API for consistency, which is this controller.
# Expect it to be "https://api.mpdx.org/api/v2/user/authenticate"
def service
[request.base_url, request.path].join
end
def render_authenticate
render json: build_authenticate,
status: :ok
end
def update_tracked_fields
load_user.update_tracked_fields!(request)
end
end
|
chuckmersereau/api_practice
|
spec/services/csv_export_spec.rb
|
require 'rails_helper'
RSpec.describe CsvExport, type: :service do
describe '#self.mailing_addresses' do
it 'does not cause an error or give an empty string' do
contact = create(:contact, name: '<NAME>', send_newsletter: 'Both')
contact.addresses << create(:address)
account_list = create(:account_list)
account_list.contacts << contact
csv_rows =
CSV.parse(described_class.mailing_addresses(ContactFilter.new(newsletter: 'address').filter(account_list.contacts, account_list)))
expect(csv_rows.size).to eq(2)
csv_rows.each_with_index do |row, index|
expect(row[0]).to eq('Contact Name') if index.zero?
expect(row[0]).to eq('<NAME>') if index == 1
expect(row[0]).to be_nil if index == 2
end
end
end
end
|
chuckmersereau/api_practice
|
lib/sidekiq_job_args_logger.rb
|
<filename>lib/sidekiq_job_args_logger.rb
class SidekiqJobArgsLogger
def call(_worker, job, _queue)
# class, jid and enqueued_at are implied by the logger header
Sidekiq.logger.info(job.except('class', 'jid', 'enqueued_at'))
yield
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120314212559_add_balance_to_designation_account.rb
|
<filename>db/migrate/20120314212559_add_balance_to_designation_account.rb
class AddBalanceToDesignationAccount < ActiveRecord::Migration
def change
add_column :designation_accounts, :balance, :decimal, precision: 8, scale: 2
remove_column :designation_accounts, :account_id
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120306213318_create_organizations.rb
|
<reponame>chuckmersereau/api_practice
class CreateOrganizations < ActiveRecord::Migration
def change
create_table :organizations do |t|
t.string :name
t.string :query_ini_url
t.string :iso3166
t.string :minimum_gift_date
t.string :logo, length: 2000
t.string :code
t.boolean :query_authentication
t.string :account_help_url, length: 2000
t.string :abbreviation
t.string :org_help_email
t.string :org_help_url, length: 2000
t.string :org_help_url_description, length: 2000
t.text :org_help_other
t.string :request_profile_url, length: 2000
t.string :staff_portal_url, length: 2000
t.string :default_currency_code
t.boolean :allow_passive_auth
t.string :account_balance_url, length: 2000
t.string :account_balance_params
t.string :donations_url, length: 2000
t.string :donations_params, length: 2000
t.string :addresses_url, length: 2000
t.string :addresses_params, length: 2000
t.string :addresses_by_personids_url, length: 2000
t.string :addresses_by_personids_params, length: 2000
t.string :profiles_url, length: 2000
t.string :profiles_params, length: 2000
t.string :redirect_query_ini, length: 2000
t.timestamps null: false
end
rename_column :designation_accounts, :account_source, :profile
add_column :designation_accounts, :organization_id, :integer
add_index :designation_accounts, :organization_id
add_index :organizations, :query_ini_url, :unique => true
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/stopped_giving_range_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Contact::Filter::StoppedGivingRange do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let!(:designation_account) { create(:designation_account, account_lists: [account_list]) }
describe '#query' do
let!(:first_contact) do
create(
:contact,
account_list: account_list,
donor_accounts: [build(:donor_account)],
last_donation_date: 2.months.ago
)
end
let!(:second_contact) do
create(
:contact,
account_list: account_list,
donor_accounts: [build(:donor_account, account_number: '123')],
pledge_amount: 20.00, last_donation_date: 4.months.ago
)
end
let!(:third_contact) do
create(
:contact,
account_list: account_list,
donor_accounts: [build(:donor_account, account_number: '1234')],
pledge_amount: 40.00, pledge_frequency: 0.5
)
end
let!(:fourth_contact) do
create(
:contact,
account_list: account_list,
donor_accounts: [build(:donor_account, account_number: '12345')],
pledge_amount: 40.00
)
end
let!(:first_donation_from_second_contact) do
create(
:donation,
donation_date: 6.months.ago,
designation_account: account_list.designation_accounts.first,
donor_account: second_contact.donor_accounts.first,
amount: 50.00
)
end
let!(:second_donation_from_second_contact) do
create(
:donation,
donation_date: 5.months.ago,
designation_account: account_list.designation_accounts.first,
donor_account: second_contact.donor_accounts.first,
amount: 50.00
)
end
let!(:third_donation_from_second_contact) do
create(
:donation,
donation_date: 4.months.ago,
designation_account: account_list.designation_accounts.first,
donor_account: second_contact.donor_accounts.first,
amount: 50.00
)
end
let!(:first_donation_from_third_contact) do
create(
:donation,
donation_date: 4.months.ago,
designation_account: account_list.designation_accounts.first,
donor_account: third_contact.donor_accounts.first,
amount: 20.00
)
end
let!(:second_donation_from_third_contact) do
create(
:donation,
donation_date: 2.months.ago,
designation_account: account_list.designation_accounts.first,
donor_account: third_contact.donor_accounts.first,
amount: 20.00
)
end
let(:contacts) { Contact.all }
context 'contacts that have stopped giving within date range' do
it 'returns the correct contacts' do
expect(
described_class.query(
contacts,
{ stopped_giving_range: Range.new(6.months.ago.to_datetime, 1.month.ago.to_datetime) },
[account_list]
)
).to eq([second_contact])
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/application_duplicate_pairs_finder_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe ApplicationDuplicatePairsFinder do
let!(:account_list) { create(:user_with_account).account_lists.order(:created_at).first }
context 'valid type' do
before do
expect_any_instance_of(ApplicationDuplicatePairsFinder).to receive(:record_type).and_return('Contact')
end
it 'initializes' do
duplicate_pairs_finder = ApplicationDuplicatePairsFinder.new(account_list)
expect(duplicate_pairs_finder.account_list).to eq(account_list)
expect(duplicate_pairs_finder.duplicate_ids).to eq(Set.new)
expect(duplicate_pairs_finder.duplicate_record_pairs).to eq([])
end
describe '#find_and_save' do
it 'sends messages to find duplicates and save them' do
duplicate_pairs_finder = ApplicationDuplicatePairsFinder.new(account_list)
expect(duplicate_pairs_finder).to receive(:find_duplicates)
expect(duplicate_pairs_finder).to receive(:delete_pairs_with_missing_records)
duplicate_record_pair_double = double(:duplicate_record_pair, save: true)
expect(duplicate_record_pair_double).to receive(:save)
duplicate_pairs_finder.duplicate_record_pairs << duplicate_record_pair_double
duplicate_pairs_finder.find_and_save
end
end
end
context 'invalid type' do
it 'raises an error on initialization' do
error = nil
begin
ApplicationDuplicatePairsFinder.new(account_list)
rescue StandardError => e
error = e
end
expect(error).to be_present
expect(error.message).to eq('record_type ApplicationDuplicatePairsFinder is not valid!')
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160217173440_allow_longer_church_name.rb
|
class AllowLongerChurchName < ActiveRecord::Migration
def change
change_column :contacts, :church_name, :text
end
end
|
chuckmersereau/api_practice
|
app/mailers/account_list_reset_mailer.rb
|
class AccountListResetMailer < ApplicationMailer
layout 'inky'
def logout(user, reset_log)
@user = user
@reset_log = reset_log
return unless @user.email.present?
mail to: @user.email.email, subject: _('You must log in to MPDX again')
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/wildcard_search_spec.rb
|
<filename>spec/services/contact/filter/wildcard_search_spec.rb
require 'rails_helper'
RSpec.describe Contact::Filter::WildcardSearch do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:person) do
create(:person, first_name: 'PersonFirstName', last_name: 'PersonLastName',
email_addresses: [build(:email_address, email: '<EMAIL>')],
phone_numbers: [build(:phone_number, number: '514 122-4362')])
end
let!(:contact_one) do
create(:contact, account_list: account_list,
notes: 'the random notes',
name: '<NAME>',
donor_accounts: [build(:donor_account, account_number: '1234567890')])
end
let!(:contact_two) do
create(:contact, account_list: account_list, notes: 'this is my favourite person', name: '<NAME>')
end
let!(:contact_three) do
create(:contact, account_list: account_list, notes: 'missing', name: '<NAME>', people: [person])
end
let!(:contact_four) { create(:contact, account_list: account_list, notes: nil, name: '<NAME>') }
describe '#config' do
it 'does not have config' do
expect(described_class.config([account_list])).to eq(nil)
end
end
def wildcard_search(value)
described_class.query(contacts, { wildcard_search: value }, nil).to_a
end
describe '#query' do
let(:contacts) { account_list.contacts }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(contacts, {}, nil)).to eq(nil)
expect(described_class.query(contacts, { wildcard_search: {} }, nil)).to eq nil
expect(described_class.query(contacts, { wildcard_search: [] }, nil)).to eq nil
expect(described_class.query(contacts, { wildcard_search: '' }, nil)).to eq nil
end
end
context 'filter with wildcard search' do
it 'returns only contacts that match the search query' do
expect(wildcard_search('Freddie')).to eq [contact_one]
expect(wildcard_search('1234567890')).to eq [contact_one]
expect(wildcard_search(person.last_name)).to eq [contact_three]
expect(wildcard_search('122')).to eq [contact_three]
expect(wildcard_search('email')).to eq [contact_three]
end
it 'searches contact name regardless of order, case, or commas' do
expect(wildcard_search('<NAME>,')).to eq [contact_one]
expect(wildcard_search('jones, freddie')).to eq [contact_one]
end
it 'searches person first and last name regardless of order, case, or commas' do
expect(wildcard_search('Personfirstname, personlastName')).to eq [contact_three]
expect(wildcard_search(',PERSONLASTNAME personfirstname')).to eq [contact_three]
end
it 'searches names with more than two words' do
contact_one.update(name: '<NAME>')
contact_two.update(name: '<NAME>')
expect(wildcard_search('park min jun')).to eq [contact_one]
expect(wildcard_search('park min-jun')).to eq [contact_one]
expect(wildcard_search('seo yun kim')).to eq [contact_two]
expect(wildcard_search('kim seo-yun')).to eq [contact_two]
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/person/filter/base.rb
|
class Person::Filter::Base < ApplicationFilter
end
|
chuckmersereau/api_practice
|
app/workers/organization_from_query_url_worker.rb
|
<reponame>chuckmersereau/api_practice
class OrganizationFromQueryUrlWorker
include Sidekiq::Worker
sidekiq_options queue: :api_organization_from_query_url_worker, unique: :until_executed
SECTIONS = {
'ACCOUNT_BALANCE' => 'account_balance',
'DONATIONS' => 'donations',
'ADDRESSES' => 'addresses',
'ADDRESSES_BY_PERSONIDS' => 'addresses_by_personids',
'PROFILES' => 'profiles',
'OAuth_GetChallengeStartNum' => 'oauth_get_challenge_start_num',
'OAuth_ConvertToToken' => 'oauth_convert_to_token',
'OAuth_GetTokenInfo' => 'oauth_get_token_info'
}.freeze
attr_accessor :name, :query_ini_url
def perform(name, query_ini_url)
@name = name
@query_ini_url = query_ini_url
load_organization
build_organization
save_organization
rescue StandardError => ex
Rails.logger.debug "\FAILURE: #{@organization.query_ini_url}\n\n"
Rollbar.error(ex)
end
private
def load_organization
@organization ||=
Organization.find_by(
'name = :name OR query_ini_url = :query_ini_url',
name: name,
query_ini_url: query_ini_url
)
end
def build_organization
@organization ||= Organization.new(iso3166: nil, api_class: 'DataServer')
@organization.attributes = organization_attributes
end
def save_organization
@organization.save!
Rails.logger.debug "\nSUCCESS: #{@organization.query_ini_url}\n\n"
rescue StandardError => ex
Rollbar.error(ex, organization_attributes: organization_attributes)
end
def organization_attributes
@organization_attributes ||= {
name: name,
query_ini_url: query_ini_url,
redirect_query_ini: ini['ORGANIZATION']['RedirectQueryIni'],
abbreviation: ini['ORGANIZATION']['Abbreviation'],
logo: ini['ORGANIZATION']['WebLogo-JPEG-470x120'],
account_help_url: ini['ORGANIZATION']['AccountHelpUrl'],
minimum_gift_date: @organization.minimum_gift_date || ini['ORGANIZATION']['MinimumWebGiftDate'],
code: ini['ORGANIZATION']['Code'],
query_authentication: ini['ORGANIZATION']['QueryAuthentication'].to_i == 1,
org_help_email: ini['ORGANIZATION']['OrgHelpEmail'],
org_help_url: ini['ORGANIZATION']['OrgHelpUrl'],
org_help_url_description: ini['ORGANIZATION']['OrgHelpUrlDescription'],
org_help_other: ini['ORGANIZATION']['OrgHelpOther'],
request_profile_url: ini['ORGANIZATION']['RequestProfileUrl'],
staff_portal_url: ini['ORGANIZATION']['StaffPortalUrl'],
default_currency_code: ini['ORGANIZATION']['DefaultCurrencyCode'],
allow_passive_auth: ini['ORGANIZATION']['AllowPassiveAuth'] == 'True',
oauth_url: ini['ORGANIZATION']['OAuthUrl']
}.merge(section_attributes)
end
def section_attributes
section_attributes = {}
SECTIONS.each do |key, section|
next unless ini[key]
# This code will pick up all keys with a .2, etc at the end
keys = ini.map do |k, _v|
k.key.match?(/^#{key}[\.\d]*$/) ? k.key : nil
end.compact.sort
# The last value is saved (.2 is favored over .1)
keys.each do |k|
section_attributes["#{section}_url"] = ini[k]['Url'] if ini[k]['Url']
section_attributes["#{section}_params"] = ini[k]['Post'] if ini[k]['Post']
section_attributes["#{section}_oauth"] = ini[k]['OAuth'] if ini[k]['OAuth']
end
end
section_attributes
end
def ini
return @ini if @ini
uri = URI.parse(query_ini_url)
ini_body = uri.read('r:UTF-8').unpack('C*').pack('U*').force_encoding('UTF-8').encode!
# remove unicode characters if present
ini_body = ini_body[3..-1] if ini_body.first.localize.code_points.first == 239
@ini = IniParse.parse(ini_body)
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_designation_account_id_spec.rb
|
require 'rails_helper'
RSpec.describe Task::Filter::ContactDesignationAccountId do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:designation_account_1) { create(:designation_account) }
let(:designation_account_2) { create(:designation_account) }
before do
account_list.designation_accounts << designation_account_1
account_list.designation_accounts << designation_account_2
end
describe '#query' do
let!(:contact_1) do
donor_account = create(:donor_account, account_number: '1')
create(:donation, donor_account: donor_account, designation_account: designation_account_1)
create(
:contact,
account_list: account_list,
donor_accounts: [donor_account]
)
end
let!(:contact_2) do
donor_account = create(:donor_account, account_number: '2')
create(:donation, donor_account: donor_account, designation_account: designation_account_2)
create(
:contact,
account_list: account_list,
donor_accounts: [donor_account]
)
end
let!(:contact_3) do
donor_account = create(:donor_account, account_number: '3')
create(:donation, donor_account: donor_account, designation_account: designation_account_1)
create(:donation, donor_account: donor_account, designation_account: designation_account_2)
create(
:contact,
account_list: account_list,
donor_accounts: [donor_account]
)
end
let!(:contact_4) { create(:contact, account_list: account_list) }
let!(:task_1) { create(:task, contacts: [contact_1]) }
let!(:task_2) { create(:task, contacts: [contact_2]) }
let!(:task_3) { create(:task, contacts: [contact_3]) }
let!(:task_4) { create(:task, contacts: [contact_4]) }
let(:tasks) { Task.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, nil)).to eq(nil)
expect(described_class.query(tasks, { contact_designation_account_id: {} }, nil)).to eq(nil)
end
end
context 'for single designation_account' do
it 'returns the correct tasks' do
expect(described_class.query(tasks, { contact_designation_account_id: designation_account_1.id }, nil)).to(
contain_exactly(task_1, task_3)
)
expect(described_class.query(tasks, { contact_designation_account_id: designation_account_2.id }, nil)).to(
contain_exactly(task_2, task_3)
)
end
end
context 'for multiple designation_accounts' do
it 'returns the correct tasks' do
expect(
described_class.query(
tasks,
{
contact_designation_account_id: [designation_account_1.id, designation_account_2.id]
},
nil
)
).to(
contain_exactly(task_1, task_2, task_3)
)
end
end
context 'with reverse_FILTER' do
subject { described_class.query(tasks, query, nil) }
let(:query) do
{
contact_designation_account_id: contact_designation_account_id,
reverse_contact_designation_account_id: true
}
end
context 'designation_account_id: designation_account_1' do
let(:contact_designation_account_id) { designation_account_1.id }
it('returns tasks with contacts that have not donated to designation_account_1') do
is_expected.to contain_exactly(task_2, task_4)
end
end
context 'designation_account_id: designation_account_1 & designation_account_2' do
let(:contact_designation_account_id) { [designation_account_1.id, designation_account_2.id] }
it('returns tasks with contacts that have not donated to designation_account_1 & designation_account_2') do
is_expected.to contain_exactly(task_4)
end
end
end
end
describe '#config' do
it 'returns expected config' do
expect(described_class.config([account_list])).to include(
default_selection: '',
multiple: true,
name: :contact_designation_account_id,
options: [{ name: '-- Any --', id: '', placeholder: 'None' },
{
name: DesignationAccountSerializer.new(designation_account_1).display_name,
id: designation_account_1.id
}, {
name: DesignationAccountSerializer.new(designation_account_2).display_name,
id: designation_account_2.id
}],
parent: 'Contact Gift Details',
title: 'Designation Acccount',
type: 'multiselect'
)
end
end
end
|
chuckmersereau/api_practice
|
app/services/task/filter/ids.rb
|
class Task::Filter::Ids < Task::Filter::Base
def execute_query(tasks, filters)
tasks.where(activities: { id: parse_list(filters[:ids]) })
end
end
|
chuckmersereau/api_practice
|
spec/workers/org_donor_accounts_address_cleaner_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe OrgDonorAccountsAddressCleaner, '#perform' do
it 'merges donor account addresses and sets source to DataServer' do
org = create(:organization, api_class: 'DataServer')
donor_account = create(:donor_account, organization: org)
address1 = create(:address, street: '1 Way', source: nil)
address2 = create(:address, street: '1 way', source: nil)
address3 = create(:address, street: '2 Way', source: nil)
donor_account.addresses << [address1, address2, address3]
OrgDonorAccountsAddressCleaner.new.perform(org.id)
expect(donor_account.reload.addresses.count).to eq 2
expect(donor_account.addresses.map(&:source).uniq).to eq ['DataServer']
end
end
|
chuckmersereau/api_practice
|
spec/controllers/monitors_controller_spec.rb
|
require 'rails_helper'
describe MonitorsController do
context '#lb' do
it 'gives success because we have a valid database connection' do
get :lb
expect(response).to be_success
end
end
context '#sidekiq' do
it 'gives success if latency not too high' do
expect(SidekiqMonitor).to receive(:queue_latency_too_high?) { false }
get :sidekiq
expect(response.status).to eq 200
end
it 'gives error status if latency too high' do
expect(SidekiqMonitor).to receive(:queue_latency_too_high?) { true }
get :sidekiq
expect(response.status).to eq 500
end
end
context '#commit' do
it 'renders git GIT_COMMIT env var' do
ENV['GIT_COMMIT'] = '<PASSWORD>'
get :commit
expect(response.body).to eq 'abc<PASSWORD>'
end
end
end
|
chuckmersereau/api_practice
|
dev/util/balance_util.rb
|
def fix_dup_balances(u)
u.account_lists.each(&method(:fix_dup_balance))
end
def fix_dup_balance(a)
balance_to_account = {}
a.designation_accounts.order("CASE WHEN name LIKE '% and %' THEN 0 ELSE 1 END")
.order(created_at: :desc).each do |da|
next unless da.balance.present?
if balance_to_account[da.balance].present?
da.update!(active: false)
else
balance_to_account[da.balance] = da
end
end
a.async(:import_data)
end
|
chuckmersereau/api_practice
|
db/migrate/20141216133726_add_not_duplicated_with_to_people.rb
|
class AddNotDuplicatedWithToPeople < ActiveRecord::Migration
def change
add_column :people, :not_duplicated_with, :string, limit: 2000
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/started_giving_range.rb
|
class Contact::Filter::StartedGivingRange < Contact::Filter::Base
def execute_query(scope, filters)
scope.where('pledge_amount is not null AND pledge_amount > 0')
.where(first_donation_date: filters[:started_giving_range])
end
def valid_filters?(filters)
date_range?(filters[:started_giving_range])
end
end
|
chuckmersereau/api_practice
|
spec/mailers/notification_mailer_spec.rb
|
require 'rails_helper'
describe NotificationMailer do
let!(:user) { create(:user) }
let!(:email_address) { create(:email_address, person: user) }
let(:account_list) { create(:account_list, designation_accounts: [des_account]) }
let(:des_account) { build(:designation_account, name: 'Very Specific Designation Name') }
let(:type_special_gift) { NotificationType::SpecialGift.first_or_create }
let(:notifications_by_type) do
{
type_special_gift => [
build(:notification, notification_type: type_special_gift,
donation: build(:donation, designation_account: des_account),
contact: create(:contact, account_list: account_list))
]
}
end
describe 'notify' do
it 'renders the email correctly' do
email = NotificationMailer.notify(user.reload, notifications_by_type)
expect(email.to).to eq [email_address.email]
end
context 'with account_list_id' do
it 'includes name of account list' do
account_list = user.account_lists.first || create(:account_list)
mail = NotificationMailer.notify(user.reload, notifications_by_type, account_list.id)
expect(mail.body.raw_source).to include(account_list.name)
end
end
context 'without account_list_id' do
it 'does not includes name of account list' do
mail = NotificationMailer.notify(user.reload, notifications_by_type)
expect(mail.body.raw_source).to_not include("Here are today's notifications for")
end
end
context 'with multiple designations' do
let(:account_list) { create(:account_list, designation_accounts: [build(:designation_account), des_account]) }
it 'includes designation name in email' do
mail = NotificationMailer.notify(user.reload, notifications_by_type)
expect(mail.body.raw_source).to include(des_account.name)
end
it 'includes designation number in email if no name' do
des_account.update(name: '', designation_number: '12345678')
mail = NotificationMailer.notify(user.reload, notifications_by_type)
expect(mail.body.raw_source).to include(des_account.designation_number)
end
end
context 'with a single designation' do
it 'does not include designation name in email' do
mail = NotificationMailer.notify(user.reload, notifications_by_type)
expect(mail.body.raw_source).to_not include(des_account.name)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import/gifts_import_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe TntImport::GiftsImport do
before do
stub_smarty_streets
end
context '#import gifts for offline orgs' do
before do
stub_request(:post, 'http://example.com/profiles')
.with(body: { 'Action' => 'Profiles', 'Password' => '<PASSWORD>', 'UserName' => '<EMAIL>' })
.to_return(body: '')
@account_list = create(:account_list)
@offline_org = create(:offline_org)
@user = create(:user)
@user.organization_accounts << create(:organization_account, organization: @offline_org)
@account_list.users << @user
@import = create(:tnt_import_gifts, account_list: @account_list, user: @user)
@tnt_import = TntImport.new(@import)
@import_with_personal_gift = create(:tnt_import_with_personal_gift, account_list: @account_list, user: @user)
@tnt_import_with_personal_gift = TntImport.new(@import_with_personal_gift)
@appeal = create(:appeal, account_list: @account_list, tnt_id: '1')
@second_appeal = create(:appeal, account_list: @account_list, tnt_id: '2')
end
let(:setup_online_org) do
@user.organization_accounts.destroy_all
online_org = create(:organization)
@user.organization_accounts << create(:organization_account, organization: online_org)
end
it 'handles an xml that has no gifts' do
@import = create(:tnt_import_no_gifts, account_list: @account_list, user: @user)
@tnt_import = TntImport.new(@import)
expect { @tnt_import.import }.to_not change(Donation, :count).from(0)
end
it 'does import gifts for an online org when gift is marked as personal' do
setup_online_org
expect { @tnt_import_with_personal_gift.import }.to change(Donation, :count).from(0).to(2)
end
describe 'associating gifts to appeals' do
context 'version 3.1 and lower' do
it 'links gifts to first appeal and adds other gift splits to memo' do
setup_online_org
@tnt_import.import
donation = Appeal.find_by(tnt_id: 2).donations.first
expect(donation.appeal).to eq(@second_appeal)
expect(donation.memo).to eq('This donation was imported from Tnt.')
end
end
context 'version 3.2 and higher' do
it 'links gifts to first appeal and adds other gift splits to memo' do
setup_online_org
@tnt_import_with_personal_gift.import
donation = Appeal.find_by(tnt_id: 2).donations.first
expect(donation.appeal).to eq(@second_appeal)
expect(donation.memo).to eq(
%(This donation was imported from Tnt.\n\n$841 is designated to the "#{@appeal.name}" appeal.)
)
end
end
end
it 'does not import gifts when the user has multiple orgs' do
@user.organization_accounts.destroy_all
@user.organization_accounts << create(:organization_account, organization: @offline_org)
@user.organization_accounts << create(:organization_account, organization: create(:offline_org))
expect { @tnt_import.import }.to_not change(Donation, :count).from(0)
end
it 'imports gifts when account list has other users with org accounts on the same org' do
expect(@user.organization_accounts.count).to eq 1
user2 = create(:user)
@account_list.users << user2
user2.organization_accounts << create(:organization_account, organization: @offline_org)
expect { @tnt_import_with_personal_gift.import }.to change(Donation, :count).from(0).to(2)
end
it 'imports gifts for a single org' do
expect { @tnt_import.import }.to change(Donation, :count).from(0).to(2)
contact = Contact.first
fields = [:donation_date, :amount, :tendered_amount, :tendered_currency, :tnt_id]
donations = Donation.all.map { |d| d.attributes.symbolize_keys.slice(*fields) }
expect(donations).to include(donation_date: Date.new(2013, 11, 20), amount: 50,
tendered_amount: 50, tendered_currency: 'USD', tnt_id: '1-M84S3J')
expect(donations).to include(donation_date: Date.new(2013, 11, 21), amount: 25,
tendered_amount: 25, tendered_currency: 'USD', tnt_id: '1-O73R2P')
expect(contact.last_donation_date).to eq(Date.new(2013, 11, 21))
expect(contact.first_donation_date).to eq(Date.new(2013, 11, 20))
expect(contact.total_donations).to eq(75.0)
expect(contact.donor_accounts.count).to eq(1)
donor_account = contact.donor_accounts.first
expect(donor_account.total_donations).to eq(75.0)
expect(donor_account.name).to eq('<NAME>')
end
it 'finds a unique donor number for new contacts' do
# Make sure it does a numeric search not an alphabetic one to find 10 as the max and not 9.
@offline_org.donor_accounts.create(account_number: '10')
@offline_org.donor_accounts.create(account_number: '9')
expect { @tnt_import.import }.to change(Donation, :count).from(0).to(2)
Donation.all.each do |donation|
expect(donation.donor_account.account_number).to eq('11')
end
end
it 'does not re-import the same gifts multiple times but adds new gifts in existing donor accounts' do
expect { @tnt_import.import }.to change(Donation, :count).from(0).to(2)
expect(DonorAccount.first.account_number).to eq('1')
import2 = create(:tnt_import_gifts_added, account_list: @account_list, user: @import.user)
tnt_import2 = TntImport.new(import2)
expect { tnt_import2.import }.to change(Donation, :count).from(2).to(3)
donations = Donation.all.map { |d| d.attributes.symbolize_keys.slice(:donation_date, :amount, :memo, :tnt_id) }
expect(donations).to include(donation_date: Date.new(2013, 11, 20),
amount: 50, memo: 'This donation was imported from Tnt.',
tnt_id: '1-M84S3J')
expect(donations).to include(donation_date: Date.new(2013, 11, 21),
amount: 25, memo: 'This donation was imported from Tnt.',
tnt_id: '1-O73R2P')
expect(donations).to include(donation_date: Date.new(2013, 11, 22),
amount: 100,
memo: 'This donation was imported from Tnt.',
tnt_id: nil)
contact = Contact.first
expect(contact.last_donation_date).to eq(Date.new(2013, 11, 22))
expect(contact.first_donation_date).to eq(Date.new(2013, 11, 20))
expect(contact.total_donations).to eq(175.0)
expect(contact.donor_accounts.count).to eq(1)
donor_account = contact.donor_accounts.first
expect(donor_account.account_number).to eq('1')
expect(donor_account.total_donations).to eq(175.0)
end
it 'assigns the gift currency code' do
@import = create(:tnt_import_broad, account_list: @account_list, user: @user)
@tnt_import = TntImport.new(@import)
@user.organization_accounts.destroy_all
online_org = create(:organization)
@user.organization_accounts << create(:organization_account, organization: online_org)
@tnt_import.import
expect(Donation.exists?(amount: 50, currency: 'CAD')).to eq true
end
it 'assigns the gift tendered currency code' do
@user.organization_accounts.destroy_all
online_org = create(:organization)
@user.organization_accounts << create(:organization_account, organization: online_org)
@tnt_import_with_personal_gift.import
expect(Donation.exists?(tendered_amount: 50, tendered_currency: 'CAD')).to eq(true)
expect(Donation.exists?(tendered_amount: 25, tendered_currency: 'USD')).to eq(true)
end
it 'assigns a designation account to each donation' do
expect { @tnt_import.import }.to change { Donation.count }.from(0)
Donation.all.each do |donation|
expect(donation.designation_account.present?).to eq(true)
end
end
it 'does not recreate the designation account when re-importing' do
expect { @tnt_import.import }.to change { @account_list.designation_accounts.reload.count }.from(0).to(1)
Donation.destroy_all
expect { @tnt_import.import }.to_not change { @account_list.designation_accounts.reload.count }.from(1)
end
it 'creates a designation account' do
expect { @tnt_import.import }.to change { @account_list.designation_accounts.reload.count }.from(0).to(1)
designation_account = @account_list.designation_accounts.last
expect(designation_account.name).to eq("#{@import.user.to_s.strip} (Imported from TntConnect)")
expect(designation_account.organization).to eq(@offline_org)
end
it 'does not assign a remote_id when creating a donation' do
expect { @tnt_import.import }.to change(Donation, :count).from(0).to(2)
expect(Donation.where(remote_id: nil).count).to eq(2)
end
it 'updates an existing donation by remote_id' do
@import.update(override: true)
expect { @tnt_import.import }.to change(Donation, :count).from(0).to(2)
Donation.where(tnt_id: '1-M84S3J').first.update!(tnt_id: nil, remote_id: '1-M84S3J', amount: 1)
expect { @tnt_import.import }.to_not change(Donation, :count).from(2)
expect(Donation.where(tnt_id: '1-M84S3J', remote_id: '1-M84S3J').first.amount).to eq(50.0)
expect(Donation.where(tnt_id: '1-M84S3J').count).to eq(1)
end
it 'updates an existing donation by tnt_id' do
@import.update(override: true)
expect { @tnt_import.import }.to change(Donation, :count).from(0).to(2)
Donation.where(tnt_id: '1-M84S3J').first.update!(remote_id: nil, amount: 1)
expect { @tnt_import.import }.to_not change(Donation, :count).from(2)
expect(Donation.where(tnt_id: '1-M84S3J').first.amount).to eq(50.0)
expect(Donation.where(tnt_id: '1-M84S3J').count).to eq(1)
end
it 'updates an existing donation by donor, amount, and date, if there is no tnt_id or remote_id' do
expect { @tnt_import.import }.to change(Donation, :count).from(0).to(2)
# Set the tnt_id and remote_id to nil, to force the import to find by donor, amount, and date.
Donation.update_all(tnt_id: nil, remote_id: nil)
expect { @tnt_import.import }.to_not change(Donation, :count).from(2)
end
it 'matches a donation on a different donor account if remote_id matches' do
@tnt_import.import
donation = Donation.last
other_contact = create(:contact, account_list: @account_list)
other_donor_account = create(:donor_account, organization: @offline_org)
other_contact.donor_accounts << other_donor_account
donation.update!(donor_account: other_donor_account)
expect { @tnt_import.import }.to_not change(Donation, :count)
expect(donation.reload.donor_account).to eq other_donor_account
end
it 'creates new donations by donor, amount, and date, if there is no tnt_id or remote_id' do
expect { @tnt_import.import }.to change(Donation, :count).from(0).to(2)
# Set the tnt_id and remote_id to nil, to force the import to find by donor, amount, and date.
# Set the amount to 1, to test that the import doesn't find the donation and creates a new one.
Donation.find_by(tnt_id: '1-M84S3J').update!(tnt_id: nil, remote_id: nil, amount: 1)
expect { @tnt_import.import }.to change(Donation, :count).from(2).to(3)
donation = Donation.find_by(tnt_id: '1-M84S3J')
donation.update!(tnt_id: nil, remote_id: nil, donor_account_id: create(:donor_account).id)
expect { @tnt_import.import }.to change(Donation, :count).from(3).to(4)
Donation.find_by(tnt_id: '1-M84S3J').update!(tnt_id: nil, remote_id: nil, donation_date: Time.current)
expect { @tnt_import.import }.to change(Donation, :count).from(4).to(5)
end
it 'imports multiple donations that were made on the same day, by the same donor, and of the same amount' do
import = create(:tnt_import_gifts_multiple_same_day, account_list: @account_list, user: @import.user)
tnt_import = TntImport.new(import)
expect { tnt_import.import }.to change { Donation.count }.from(0).to(3)
expect { tnt_import.import }.to_not change { Donation.count }.from(3)
end
it 'uses an existing designation_account if it exists' do
expect { @tnt_import.import }.to change { Donation.count }.from(0).to(2)
donation = Donation.first
designation_account = create(:designation_account)
@account_list.designation_accounts << designation_account
donation.update!(designation_account: designation_account)
expect { @tnt_import.import }.to_not change { donation.reload.designation_account }.from(designation_account)
end
describe 'creating pledges' do
it 'creates a pledge if the donation belongs to an appeal' do
setup_online_org
expect { @tnt_import_with_personal_gift.import }.to change { Pledge.count }.from(0).to(1)
.and change { Donation.count }.from(0).to(2)
pledge = Pledge.first
donation = pledge.donations.first
expect(pledge.amount).to eq(841)
expect(pledge.amount_currency).to eq('USD')
expect(pledge.expected_date.to_date).to eq(donation.donation_date.to_date)
expect(pledge.contact).to eq(donation.donor_account.contacts.first)
expect(donation.appeal).to eq(@second_appeal)
end
it 'does not create a pledge if the donation does not belong to an appeal' do
@import = create(:tnt_import_gifts_without_appeal, account_list: @account_list, user: @user)
@tnt_import = TntImport.new(@import)
setup_online_org
expect { @tnt_import.import }.to change { Donation.count }.from(0).to(2)
expect(Pledge.count).to eq(0)
end
it 'does not create a new pledge if one already exists' do
setup_online_org
expect { @tnt_import_with_personal_gift.import }.to change { Pledge.count }.from(0).to(1)
expect { @tnt_import_with_personal_gift.import }.to_not change { Pledge.count }.from(1)
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/account_list_coach_spec.rb
|
require 'rails_helper'
RSpec.describe AccountListCoach, type: :model do
subject { create(:account_list_coach) }
it { is_expected.to belong_to(:coach) }
it { is_expected.to belong_to(:account_list) }
end
|
chuckmersereau/api_practice
|
app/models/google_plus_account.rb
|
class GooglePlusAccount < ApplicationRecord
belongs_to :email_address
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_metro_area_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Task::Filter::ContactMetroArea do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id) }
let!(:contact_three) { create(:contact, account_list_id: account_list.id) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id) }
let!(:contact_five) { create(:contact, account_list_id: account_list.id) }
let!(:task_one) { create(:task, account_list: account_list, contacts: [contact_one]) }
let!(:task_two) { create(:task, account_list: account_list, contacts: [contact_two]) }
let!(:task_three) { create(:task, account_list: account_list, contacts: [contact_three]) }
let!(:task_four) { create(:task, account_list: account_list, contacts: [contact_four]) }
let!(:task_five) { create(:task, account_list: account_list, contacts: [contact_five]) }
let!(:address_one) { create(:address, metro_area: 'My Metro') }
let!(:address_two) { create(:address, metro_area: 'My Metro') }
let!(:address_three) { create(:address, metro_area: nil) }
let!(:address_four) { create(:address, metro_area: nil) }
let!(:address_five) { create(:address, metro_area: 'My Metro', historic: true) }
before do
contact_one.addresses << address_one
contact_two.addresses << address_two
contact_three.addresses << address_three
contact_four.addresses << address_four
contact_five.addresses << address_five
end
describe '#query' do
let(:tasks) { Task.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_metro_area: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_metro_area: [] }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_metro_area: '' }, account_list)).to eq(nil)
end
end
context 'filter by no metro_area' do
it 'returns only tasks with contacts that have no metro_area' do
result = described_class.query(tasks, { contact_metro_area: 'none' }, account_list).to_a
expect(result).to match_array [task_three, task_four]
end
end
context 'filter by metro_area' do
it 'filters multiple metro_areas' do
result = described_class.query(tasks, { contact_metro_area: 'My Metro, My Metro' }, account_list).to_a
expect(result).to match_array [task_one, task_two]
end
it 'filters a single metro_area' do
result = described_class.query(tasks, { contact_metro_area: 'My Metro' }, account_list).to_a
expect(result).to match_array [task_one, task_two]
end
end
context 'multiple filters' do
it 'returns tasks with contacts matching multiple filters' do
result = described_class.query(tasks, { contact_metro_area: 'My Metro, none' }, account_list).to_a
expect(result).to match_array [task_one, task_two, task_three, task_four]
end
end
context 'address historic' do
it 'returns tasks with contacts matching the metro_area with historic addresses' do
query = { contact_metro_area: 'My Metro', address_historic: 'true' }
result = described_class.query(tasks, query, account_list).to_a
expect(result).to eq [task_five]
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20171011173827_add_global_registry_columns.rb
|
<gh_stars>0
class AddGlobalRegistryColumns < ActiveRecord::Migration
def change
add_column :people, :global_registry_id, :uuid, null: true, default: nil
add_column :people, :global_registry_mdm_id, :uuid, null: true, default: nil
add_column :email_addresses, :global_registry_id, :uuid, null: true, default: nil
add_column :phone_numbers, :global_registry_id, :uuid, null: true, default: nil
end
end
|
chuckmersereau/api_practice
|
app/services/account_list/chalkline_mails.rb
|
<reponame>chuckmersereau/api_practice
class AccountList::ChalklineMails < ActiveModelSerializers::Model
attr_accessor :account_list
def initialize(attributes = {})
super
end
def send_later
account_list.async_send_chalkline_list
end
end
|
chuckmersereau/api_practice
|
app/exhibits/coaching/contact_exhibit.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class Coaching::ContactExhibit < PersonExhibit
def self.applicable_to?(object)
object.class.name == 'Contact'
end
end
|
chuckmersereau/api_practice
|
app/workers/currency_rates_fetcher_worker.rb
|
class CurrencyRatesFetcherWorker
include Sidekiq::Worker
sidekiq_options queue: :api_currency_rates_fetcher_worker, unique: :until_executed
MAX_DAYS_TO_FETCH = 30
def perform
num_days_to_fetch.times do |n|
fetch_rates(Date.current - n)
end
CurrencyRate::AliasedRatesFiller.new.fill_aliased_rates
end
private
def num_days_to_fetch
last_date = last_rate_exchanged_date
if last_date.nil?
MAX_DAYS_TO_FETCH
else
[(Date.current - last_date).to_i, MAX_DAYS_TO_FETCH].min
end
end
def last_rate_exchanged_date
CurrencyRate.order(:exchanged_on).last.try(:exchanged_on)
end
def fetch_rates(date)
json = rates(date)
raise 'Currency Layer api call failed' unless json['success']
import_quotes(json['quotes'], date)
end
def import_quotes(quotes, date)
quotes.each do |currencies, rate|
CurrencyRate.create(exchanged_on: date,
code: currencies[3..5], rate: rate,
source: 'currencylayer')
end
end
def rates(time)
return live_currency_rates if time.today?
historical_rates(time)
end
def historical_rates(date)
currency_layer_call('historical', date: date.strftime('%Y-%m-%d'))
end
def live_currency_rates
currency_layer_call('live')
end
def currency_layer_call(action, params = {})
url = 'http://apilayer.net/api/' + action
params = params.merge(access_key: ENV.fetch('CURRENCY_LAYER_KEY'))
JSON.parse(RestClient.get(url, params: params))
end
end
|
chuckmersereau/api_practice
|
spec/support/clear_caches.rb
|
RSpec.configure do |config|
config.after(:each) do |_example|
CurrencyRate.clear_rate_cache
end
end
|
chuckmersereau/api_practice
|
app/serializers/background_batch_serializer.rb
|
class BackgroundBatchSerializer < ApplicationSerializer
attributes :total, :pending
has_many :requests
def total
object.requests.count
end
def pending
object.requests.pending.count
end
end
|
chuckmersereau/api_practice
|
app/models/import.rb
|
require 'async'
require 'charlock_holmes'
require 'csv'
class Import < ApplicationRecord
include Async
include Sidekiq::Worker
sidekiq_options queue: :api_import, retry: 0, backtrace: true, unique: :until_executed
mount_uploader :file, ImportUploader
SOURCES = %w(facebook twitter linkedin tnt google tnt_data_sync csv).freeze
SOURCE_ERROR_MESSAGES = {
tnt: 'You must specify a TntConnect .xml export file to upload to MPDX.'.freeze,
csv: 'You must specify a .csv spreadsheet file from to upload to MPDX.'.freeze,
tnt_data_sync: 'You must specify a TntDataSync (.tntdatasync or .tntmpd) '\
'donor export file from your organization to upload to MPDX.'.freeze
}.freeze
MAX_FILE_SIZE_IN_BYTES = 500_000_000
PERMITTED_ATTRIBUTES = [:created_at,
:file,
:file_constants_mappings,
:file_headers_mappings,
{ groups: [] },
:import_by_group,
:in_preview,
:overwrite,
:override,
:source,
:source_account_id,
:tag_list,
:updated_at,
:updated_in_db_at,
:user_id,
:id].freeze
belongs_to :user
belongs_to :account_list
validates :source, inclusion: { in: SOURCES }
validates :file, file_size: { less_than: MAX_FILE_SIZE_IN_BYTES }
validates :file, upload_extension: { extension: 'xml', message: SOURCE_ERROR_MESSAGES[:tnt] }, if: :source_tnt?
validates :file, upload_extension: { extension: 'csv', message: SOURCE_ERROR_MESSAGES[:csv] }, if: :source_csv?
validates :file, upload_extension: { extension: %w(tntmpd tntdatasync), message: SOURCE_ERROR_MESSAGES[:tnt_data_sync] },
if: :source_tnt_data_sync?
validates :file, :file_headers, :file_headers_mappings, :file_row_samples,
presence: true, if: :source_csv?, unless: :in_preview?
validates :file_headers, :file_constants, :file_headers_mappings, :file_constants_mappings, class: { is_a: Hash }
validates :file_row_samples, :file_row_failures, class: { is_a: Array }
validates :source_account_id, presence: true, if: :source_tnt_data_sync?
validates_with CsvImportMappingsValidator, if: :source_csv?, unless: :in_preview?
validates_with FacebookImportValidator, if: :source_facebook?
serialize :groups, Array
serialize :group_tags, JSON
serialize :file_headers, Hash
serialize :file_constants, Hash
serialize :file_row_samples, Array
serialize :file_headers_mappings, Hash
serialize :file_constants_mappings, Hash
serialize :file_row_failures, Array
after_commit :queue_import, on: [:create, :update]
# Define convenience methods for checking the import source
SOURCES.each do |source_to_check|
define_method("source_#{source_to_check}?") { source == source_to_check }
end
def queue_import
return if in_preview? || queued_for_import_at
update_column(:queued_for_import_at, Time.current) if async_to_queue(sidekiq_queue, :import)
end
def user_friendly_source
case source
when 'csv'
source.upcase
when 'tnt', 'tnt_data_sync'
source.titleize
else
source.humanize
end
end
def file_path
return unless file.present?
file.cache_stored_file! unless file.cached?
file.path
end
def file=(new_file)
reset_file
super
end
# This model handles it's own tags in it's "tags" attribute,
# tags are persisted as a comma delimited list. We've created
# accessor methods tag_list and tags to provide consistency
# with the rest of the app.
def tags
attributes['tags'].try(:split, ',')
end
def tags=(new_tags)
super(Array.wrap(new_tags).join(','))
end
def tag_list
attributes['tags']
end
def tag_list=(new_tag_list)
self.tags = new_tag_list.try(:split, ',')
end
private
def sidekiq_queue
"api_import_#{source}"
end
def reset_file
self.file_headers = {}
self.file_constants = {}
self.file_row_samples = []
self.file_row_failures = []
end
# Delegate the import process to a decorator class, each import source should have it's own decorator.
# The import might happen async in other jobs. If it is async we let the decorator handle the callbacks,
# but if not then we handle the callbacks right here.
def import
ImportCallbackHandler.new(self).handle_start
async = false
begin
async = "#{source.camelize}Import".safe_constantize.new(self).import
rescue StandardError => exception
exception.is_a?(Import::UnsurprisingImportError) ? Rollbar.info(exception) : Rollbar.error(exception)
ImportCallbackHandler.new(self).handle_failure(exception: exception)
false
else
ImportCallbackHandler.new(self).handle_success unless async
true
end
rescue StandardError => exception
Rollbar.error(exception)
ImportCallbackHandler.new(self).handle_failure(exception: exception) unless async
false
ensure
ImportCallbackHandler.new(self).handle_complete unless async
end
class UnsurprisingImportError < StandardError
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/church_names_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'ChurchNames' do
include_context :json_headers
documentation_scope = :church_names_api
let(:factory_type) { :church_names }
# first user
let!(:user) { create(:user_with_account) }
let!(:account_list) { 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: account_list, church_name: third_church_name) }
let(:resource_attributes) do
%w(
church_name
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/contacts/church_names' do
parameter 'church_name_like', 'Church Name Search [OPTIONAL]', scope: :filter
example 'Church Names [LIST]', document: documentation_scope do
explanation 'List Church Names'
do_request
expect(response_status).to eq(200)
end
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/church_names_controller.rb
|
class Api::V2::Contacts::ChurchNamesController < Api::V2Controller
def index
authorize_index
load_churches
render json: @church_names,
include: include_params,
fields: field_params,
each_serializer: Contact::ChurchNamesSerializer
end
private
def load_churches
@church_names = search_church_names.list_church_names
end
def search_church_names
return contact_scope unless params[:filter] && params[:filter][:church_name_like]
contact_scope.search_church_names(params[:filter][:church_name_like])
end
def contact_scope
Contact.where(account_list_id: account_lists.pluck(:id))
end
def authorize_index
account_lists.each { |account_list| authorize(account_list, :show?) }
end
end
|
chuckmersereau/api_practice
|
db/migrate/20150826193355_add_calendar_id_to_google_event.rb
|
class AddCalendarIdToGoogleEvent < ActiveRecord::Migration
def change
add_column :google_events, :calendar_id, :string
GoogleEvent.connection.execute(
'UPDATE google_events
SET calendar_id = google_integrations.calendar_id
FROM google_integrations
WHERE google_events.google_integration_id = google_integrations.id'
)
end
end
|
chuckmersereau/api_practice
|
spec/support/rspec_retry.rb
|
if ENV['CI']
RSpec.configure do |config|
# show retry status in spec process
config.verbose_retry = true
# show exception that triggers a retry if verbose_retry is set to true
config.display_try_failure_messages = true
config.around :each do |ex|
ex.run_with_retry retry: 3
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/pagination.rb
|
<filename>app/controllers/concerns/pagination.rb
module Pagination
private
def page_number_param
params[:page] || 1
end
def per_page_param
params[:per_page] || 25
end
def pagination_meta_params(resources)
{
page: page_number_param,
per_page: per_page_param,
total_count: resources.total_count,
total_pages: resources.total_pages
}
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/coaching/contacts_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Coaching Contacts' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: %i(coaching contacts))
let(:resource_type) { 'contacts' }
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!(:contact) do
create :contact, account_list_id: account_list.id, pledge_received: true
end
let!(:contact_outstanding) do
create :contact, account_list_id: account_list.id, pledge_received: false,
pledge_start_date: 2.days.ago
end
let!(:contact_pending) do
create :contact, account_list_id: account_list.id, pledge_received: false,
pledge_start_date: 2.days.from_now
end
let!(:contact_completed_start_past) do
create :contact, account_list_id: account_list.id, pledge_received: true,
pledge_start_date: 2.days.ago
end
let!(:contact_completed_start_future) do
create :contact, account_list_id: account_list.id, pledge_received: true,
pledge_start_date: 2.days.from_now
end
let(:id) { contact.id }
let(:resource_attributes) do
%w(
created_at
late_at
locale
name
pledge_amount
pledge_currency
pledge_currency_symbol
pledge_frequency
pledge_received
pledge_start_date
updated_at
updated_in_db_at
)
end
context 'authorized user' do
before { api_login(coach) }
get '/api/v2/coaching/contacts' 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 5
expect(response_status).to eq 200
end
end
get '/api/v2/coaching/contacts/:id' do
doc_helper.insert_documentation_for(action: :show, context: self)
example doc_helper.title_for(:show), document: doc_helper.document_scope do
explanation doc_helper.description_for(:show)
do_request
check_resource
expect(resource_object['pledge_amount']).to eq contact.pledge_amount.to_s
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
app/workers/google_email_sync_enqueuer_worker.rb
|
class GoogleEmailSyncEnqueuerWorker
include Sidekiq::Worker
sidekiq_options queue: :api_google_email_sync_enqueuer_worker, unique: :until_executed
def perform
GoogleIntegration.where(email_integration: true).pluck(:id).each do |google_integration_id|
GoogleSyncDataWorker.perform_async(google_integration_id, 'email')
end
end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/syncer.rb
|
<gh_stars>0
# This class is used to manage a two way sync between MailChimp and MPDX.
class MailChimp::Syncer
Gibbon::Request.timeout = 600
attr_reader :mail_chimp_account, :list_id
delegate :interest_categories, to: :mc_list
def initialize(mail_chimp_account, list_id = nil)
@mail_chimp_account = mail_chimp_account
@list_id = list_id || mail_chimp_account.primary_list_id
@use_primary_list = mail_chimp_account.primary_list_id == list_id
end
def two_way_sync_with_primary_list
MailChimp::ConnectionHandler.new(mail_chimp_account)
.call_mail_chimp(self, :two_way_sync_with_primary_list!)
end
def two_way_sync_with_primary_list!
setup_webhooks
delete_mail_chimp_members
# import_mail_chimp_subscribers
export_mpdx_contacts_to_mail_chimp
end
private
def import_mail_chimp_subscribers
MailChimp::Importer.new(mail_chimp_account).import_all_members
end
def export_mpdx_contacts_to_mail_chimp
MailChimp::ExportContactsWorker.perform_async(mail_chimp_account.id, mail_chimp_account.primary_list_id, nil)
end
def delete_mail_chimp_members
wrapper = MailChimp::GibbonWrapper.new(mail_chimp_account)
subscribed_emails = wrapper.list_members(list_id)
.select { |member| member['status'] == 'subscribed' }
.map { |member| member['email_address'].downcase }
mail_chimp_account.mail_chimp_members.where(list_id: list_id).where.not(email: subscribed_emails).delete_all
mail_chimp_account.mail_chimp_members.reload
end
def setup_webhooks
return if does_not_require_webhooks_setup?
generate_token_if_necessary
create_webhooks
end
def create_webhooks
mail_chimp_webhooks.create(
body: {
url: webhook_url,
events: {
campaign: true,
cleaned: true,
profile: true,
subscribe: true,
unsubscribe: true,
upemail: true
},
sources: {
admin: true,
api: false,
user: true
}
}
)
end
def generate_token_if_necessary
mail_chimp_account.update(webhook_token: SecureRandom.hex(32)) if mail_chimp_account.webhook_token.blank?
end
def does_not_require_webhooks_setup?
not_a_production_or_stage_environment? ||
mail_chimp_account.webhook_token.present? &&
mail_chimp_webhooks.retrieve['webhooks'].find { |webhook| webhook['url'] == webhook_url }
end
def not_a_production_or_stage_environment?
!Rails.env.production? && !Rails.env.staging?
end
def appeal_export?
@is_appeal_export
end
def gibbon
@gibbon ||= Gibbon::Request.new(api_key: mail_chimp_account.api_key)
end
def mail_chimp_webhooks
mail_chimp_list.webhooks
end
def mail_chimp_list
gibbon.lists(list_id)
end
def use_primary_list?
@use_primary_list
end
def email_hash(email)
Digest::MD5.hexdigest(email.downcase)
end
def webhook_url
(Rails.env.development? ? 'http://' : 'https://') +
Rails.application.routes.default_url_options[:host] + '/mail_chimp_webhook/' + mail_chimp_account.webhook_token
end
end
|
chuckmersereau/api_practice
|
app/serializers/contact/church_names_serializer.rb
|
class Contact::ChurchNamesSerializer < ActiveModel::Serializer
type 'church_names'
attributes :church_name
end
|
chuckmersereau/api_practice
|
app/services/reports/donor_currency_donations.rb
|
class Reports::DonorCurrencyDonations < ActiveModelSerializers::Model
include Concerns::Reports::DonationSumHelper
include Concerns::Reports::DateRangeFilterable
attr_accessor :account_list, :filter_params
def donor_infos
received_donations_object.donors
end
def currency_groups
Hash.new { |h, k| h[k] = {} }.tap do |grouped|
donations_by_currency(all_received_donations).each do |currency, donations|
grouped[currency] = {
totals: {
year: sum_donations(donations),
year_converted: sum_converted_donations(donations, account_list.salary_currency),
months: sum_donations_by_month(donations, months)
},
donation_infos: contacts_donation_info(donations)
}
end
end
end
protected
def donations(donations)
donations = donations.where('donation_date >= ?', start_date)
if filter_params && filter_params[:designation_account_id]
donations = donations.where(designation_account_id: filter_params[:designation_account_id])
end
if filter_params && filter_params[:donor_account_id]
donations = donations.where(donor_account_id: filter_params[:donor_account_id])
end
donations
end
private
def contacts_donation_info(all_donations)
donor_infos
.map { |donation| create_donation_info(donation, all_donations) }
.reject { |info| info[:months].empty? }
end
def create_donation_info(donor, all_donations)
id = donor.contact_id
contact_donations = all_donations.select { |d| d.contact_id == id }
amounts = contact_donations.map { |d| donation_amount(d) }
total = amounts.inject(:+)
{
contact_id: id,
total: total,
average: (total / amounts.size.to_f if total),
minimum: amounts.min,
maximum: amounts.max,
months: summarize_months(contact_donations)
}
end
def summarize_months(all_donations)
group_donations_by_month(all_donations, months).map do |donations|
{
total: sum_donations(donations),
donations: donations
}
end
end
def received_donations_object
@received_donations_object ||=
DonationReports::ReceivedDonations.new(
account_list: account_list,
donations_scoper: ->(donations) { self.donations(donations) }
)
end
def all_received_donations
@all_received_donations ||= received_donations_object.donations
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120309220159_add_downloading_and_last_downloaded_to_accounts.rb
|
<filename>db/migrate/20120309220159_add_downloading_and_last_downloaded_to_accounts.rb
class AddDownloadingAndLastDownloadedToAccounts < ActiveRecord::Migration
def change
add_column :person_facebook_accounts, :downloading, :boolean, default: false, null: false
add_column :person_facebook_accounts, :last_download, :datetime
add_column :person_google_accounts, :downloading, :boolean, default: false, null: false
add_column :person_google_accounts, :last_download, :datetime
add_column :person_key_accounts, :downloading, :boolean, default: false, null: false
add_column :person_key_accounts, :last_download, :datetime
add_column :person_linkedin_accounts, :downloading, :boolean, default: false, null: false
add_column :person_linkedin_accounts, :last_download, :datetime
add_column :person_organization_accounts, :downloading, :boolean, default: false, null: false
add_column :person_organization_accounts, :last_download, :datetime
add_column :person_relay_accounts, :downloading, :boolean, default: false, null: false
add_column :person_relay_accounts, :last_download, :datetime
add_column :person_twitter_accounts, :downloading, :boolean, default: false, null: false
add_column :person_twitter_accounts, :last_download, :datetime
end
end
|
chuckmersereau/api_practice
|
app/services/contact/dup_contacts_merge.rb
|
class Contact::DupContactsMerge
def initialize(account_list:, contact:)
@account_list = account_list
@contact = contact
end
def find_duplicates
contacts_with_the_same_name_as(contact).select do |contact_with_the_same_name|
contacts_have_a_matching_donor_account?(contact, contact_with_the_same_name) ||
contacts_have_a_matching_address?(contact, contact_with_the_same_name)
end
end
def merge_duplicates
find_duplicates.each do |contact_to_merge|
contact.merge(contact_to_merge)
end
contact.reload
contact.merge_people
contact.merge_addresses
end
private
attr_accessor :account_list, :contact
def contacts_with_the_same_name_as(contact)
account_list.contacts.includes(:addresses, :donor_accounts).where.not(id: contact.id).where(name: contact.name)
end
def contacts_have_a_matching_donor_account?(contact_a, contact_b)
(contact_a.donor_accounts & contact_b.donor_accounts).present?
end
def contacts_have_a_matching_address?(contact_a, contact_b)
contact_a.addresses.any? do |address_a|
contact_b.addresses.any? do |address_b|
address_a.equal_to?(address_b)
end
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/people_controller.rb
|
class Api::V2::Contacts::PeopleController < Api::V2Controller
supports_content_types 'multipart/form-data', 'application/vnd.api+json'
def index
authorize_index
load_people
render json: Api::V2::Contacts::PeoplePreloader.new(include_params, field_params).preload(@people),
meta: meta_hash(@people),
include: include_params,
fields: field_params
end
def show
load_person
authorize_person
render_person
end
def create
persist_person
end
def update
load_person
authorize_person
persist_person
end
def destroy
load_person
authorize_person
destroy_person
end
private
def destroy_person
@person.destroy
head :no_content
end
def person_params
params
.require(:person)
.permit(person_attributes)
end
def person_attributes
Person::PERMITTED_ATTRIBUTES
end
def person_scope
Person.joins(:contact_people)
.where(contact_people: { contact: contact_scope })
end
def contact_scope
return Contact.where(account_list: account_lists) if params[:contact_id].blank?
Contact.find(params[:contact_id])
Contact.where(id: params[:contact_id])
end
def current_contact
@contact ||= Contact.find(params[:contact_id])
end
def authorize_index
return account_lists.each { |account_list| authorize(account_list, :show?) } if params[:contact_id].blank?
authorize(contact_scope, :show?)
end
def authorize_person
authorize(@person)
end
def build_person
@person ||= person_scope.build
@person.assign_attributes(person_params)
end
def load_person
@person ||= Person.find(params[:id])
end
def load_people
@people = Person::Filterer.new(filter_params)
.filter(scope: person_scope, account_lists: account_lists)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def persist_person
build_person
authorize_person
if save_person
render_person
else
render_with_resource_errors(@person)
end
end
def render_person
render json: @person,
status: success_status,
include: include_params,
fields: field_params
end
def save_person
ActiveRecord::Base.transaction do
person_save_result = @person.save(context: persistence_context)
@person.contact_people.create(contact: contact_scope.order(:created_at).first) if action_name == 'create' && person_save_result
person_save_result
end
end
def pundit_user
PunditContext.new(current_user, contact_scope: contact_scope)
end
def permitted_filters
@permitted_filters ||= Person::Filterer.filter_params + [:account_list_id]
end
def default_sort_param
Person.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
spec/requests/api/v2/put_requests_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe 'Patch Requests', type: :request do
let!(:user) { create(:user_with_account) }
let(:contact) { create(:contact) }
let(:headers) do
{
'CONTENT_TYPE' => 'application/vnd.api+json',
'ACCEPT' => 'application/vnd.api+json'
}
end
let(:update_attributes) { { first_name: 'test_first_name' } }
let(:full_update_attributes) do
{
data: {
type: 'users',
attributes: update_attributes.merge(overwrite: true)
}
}
end
before { api_login(user) }
describe 'requests' do
context 'with correct parameters (200)' do
it 'should return a success status (200)' do
put api_v2_user_path, full_update_attributes.to_json, headers
expect(response.status).to eq(200), invalid_status_detail
end
it 'should return a representation of the updated resource' do
put api_v2_user_path, full_update_attributes.to_json, headers
updated_user_first_name = JSON.parse(response.body)['data']['attributes']['first_name']
expect(updated_user_first_name).to eq('test_first_name')
end
end
context 'with unsupported/forbidden parameters (403)' do
let(:account_list) { user.account_lists.order(:created_at).first }
let(:id) { account_list.id }
let(:update_attributes) { attributes_for(:account_list) }
let(:full_update_attributes) do
{
data: {
id: account_list.id,
type: 'account_lists',
attributes: update_attributes.merge(updated_in_db_at: account_list.updated_at)
}
}
end
it 'should return a forbidden status (403)' do
api_login(create(:user))
put api_v2_account_list_path(id), full_update_attributes.to_json, headers
expect(response.status).to eq(403), invalid_status_detail
end
end
context 'against a resource that does not exist (404)' do
let(:mock_id) { SecureRandom.uuid }
let(:missing_resource_attributes) do
{
data: {
id: mock_id,
type: 'contacts',
attributes: {
name: 'foo_bar',
updated_in_db_at: contact.updated_at
}
}
}
end
it 'should return a not found status (404)' do
put api_v2_contact_path(mock_id), missing_resource_attributes.to_json, headers
expect(response.status).to eq(404), invalid_status_detail
end
end
context 'that references a related resource that does not exist (404)' do
let(:organization) { user.organization_accounts.first }
let(:missing_related_resource_attributes) do
{
data: {
type: 'organization_accounts',
relationships: {
data: {
type: 'organizations',
id: 'abc123'
}
}
}
}
end
it 'should return a not found status (404)' do
put api_v2_user_organization_account_path(user.id), missing_related_resource_attributes.to_json, headers
expect(response.status).to eq(404), invalid_status_detail
end
end
context 'in which the resource object’s type does not match the server’s endpoint (409)' do
let(:account_list) { user.account_lists.order(:created_at).first }
let(:task) { create(:task, account_list: account_list) }
let(:constrained_attributes) do
{
data: {
type: 'another_type',
attributes: {
subject: 'This is a task subject',
updated_in_db_at: task.updated_at
}
}
}
end
it 'should return a conflict status (409)' do
put api_v2_task_path(task.id), constrained_attributes.to_json, headers
expect(response.status).to eq(409), invalid_status_detail
end
end
context 'in which the resource object’s id does not match the server’s endpoint (409)' do
let(:mock_id) { SecureRandom.uuid }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:task) { create(:task, account_list: account_list) }
let(:constrained_attributes) do
{
data: {
id: mock_id,
type: 'account_lists',
attributes: {
updated_in_db_at: task.updated_at
}
}
}
end
it 'should return a conflict status (409)' do
put api_v2_task_path(task.id), constrained_attributes.to_json, headers
expect(response.status).to eq(409), invalid_status_detail
end
end
end
context 'in which the resource is expired (409)' do
let(:account_list) { user.account_lists.order(:created_at).first }
let(:task) { create(:task, account_list: account_list) }
let(:expired_attributes) do
{
data: {
id: task.id,
type: 'tasks',
attributes: {
updated_in_db_at: Time.parse('2016-01-26').utc
}
}
}
end
it 'should return a conflict status (409)' do
put api_v2_task_path(task.id), expired_attributes.to_json, headers
expect(response.status).to eq(409), invalid_status_detail
end
end
end
|
chuckmersereau/api_practice
|
app/models/partner_status_log.rb
|
class PartnerStatusLog < ApplicationRecord
belongs_to :contact
def pledge_currency
self[:pledge_currency] || contact.pledge_currency
end
end
|
chuckmersereau/api_practice
|
app/workers/admin/account_list_reset_worker.rb
|
class Admin::AccountListResetWorker
include Sidekiq::Worker
sidekiq_options queue: :api_admin_account_list_reset_worker, retry: 3
def perform(account_list_id, user_id, reset_log_id)
@account_list = AccountList.find_by_id(account_list_id)
@user = User.find(user_id)
@organization_accounts = @account_list&.organization_accounts.presence || @user.organization_accounts
@reset_log = Admin::ResetLog.where(id: reset_log_id, resetted_user: @user).last!
reset
email_user
rescue ActiveRecord::RecordNotFound, Pundit::NotAuthorizedError => exception
Rollbar.error(exception)
false
else
true
end
private
def reset
authorize_reset_log
destroy_account_list
import_profiles
set_default_account_list
queue_import_organization_data
@reset_log.update_column(:completed_at, Time.current)
end
def authorize_reset_log
PunditAuthorizer.new(@reset_log.admin_resetting, @reset_log).authorize_on('create')
end
def destroy_account_list
return if @account_list.blank?
AccountList::Destroyer.new(@account_list.id).destroy!
end
def import_profiles
@organization_accounts.each(&:import_profiles)
end
def set_default_account_list
@user.reload
return if @user.default_account_list.present? && (@user.valid? || @user.errors[:default_account_list].blank?)
@user.update(default_account_list: @user.account_lists&.first&.id)
end
def queue_import_organization_data
Person::OrganizationAccount.where(id: @organization_accounts).update_all(last_download: nil)
@organization_accounts.each(&:queue_import_data)
end
def email_user
AccountListResetMailer.delay.logout(@user, @reset_log)
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/coaches_controller.rb
|
class Api::V2::AccountLists::CoachesController < Api::V2Controller
resource_type :users
def index
authorize load_account_list, :show?
load_coaches
render json: @coaches.preload_valid_associations(include_associations),
meta: meta_hash(@coaches),
include: include_params,
fields: field_params,
each_serializer: AccountListUserSerializer
end
def show
load_coach
authorize_coach
render_coach
end
def destroy
load_coach
authorize_coach
destroy_coach
end
private
def destroy_coach
@coach.remove_coach_access(load_account_list)
head :no_content
end
def load_coaches
@coaches = coach_scope.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def load_coach
@coach ||= User::Coach.find(params[:id])
end
def render_coach
render json: @coach,
status: success_status,
include: include_params,
fields: field_params,
serializer: AccountListUserSerializer
end
def authorize_coach
authorize @coach
end
def coach_scope
load_account_list.coaches
end
def load_account_list
@account_list ||= AccountList.find(params[:account_list_id])
end
def pundit_user
if action_name == 'index'
PunditContext.new(current_user, account_list: load_account_list)
else
current_user
end
end
def default_sort_param
User::Coach.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
spec/support/stub_google_plus_account_fetch.rb
|
<filename>spec/support/stub_google_plus_account_fetch.rb
RSpec.configure do |config|
config.before(:suite) do
$stdout.puts('Stubbing all calls to the #start_google_plus_account_fetcher_job on EmailAddress create')
end
config.before(:each) do
allow_any_instance_of(EmailAddress).to receive(:start_google_plus_account_fetcher_job)
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/people/duplicates_controller_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Api::V2::Contacts::People::DuplicatesController, type: :controller do
let(:factory_type) { :duplicate_people_pair }
let!(:duplicate_record_pair) { create(:duplicate_people_pair) }
let!(:second_duplicate_record_pair) { create(:duplicate_people_pair, account_list: duplicate_record_pair.account_list) }
let(:account_list) { duplicate_record_pair.account_list }
let(:user) { create(:user).tap { |user| account_list.users << user } }
let(:resource) { duplicate_record_pair }
let(:second_resource) { second_duplicate_record_pair }
let(:id) { duplicate_record_pair.id }
let(:correct_attributes) do
{
reason: 'Testing',
updated_in_db_at: resource.updated_at
}
end
let(:correct_relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: account_list.id
}
},
records: {
data: [
{
type: 'person',
id: account_list.people.first.id
},
{
type: 'person',
id: account_list.people.second.id
}
]
}
}
end
let(:unpermitted_relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: create(:account_list).id
}
}
}
end
let(:reference_key) { :reason }
let(:reference_value) { correct_attributes[:reason] }
let(:incorrect_reference_value) { resource.send(reference_key) }
let(:incorrect_attributes) do
{
reason: nil,
updated_in_db_at: resource.updated_at
}
end
include_examples 'index_examples'
include_examples 'show_examples'
include_examples 'update_examples'
end
|
chuckmersereau/api_practice
|
app/services/person/filter/email_address_valid.rb
|
<reponame>chuckmersereau/api_practice
class Person::Filter::EmailAddressValid < Person::Filter::Base
def execute_query(people, filters)
self.people = people
return people unless filters[:email_address_valid] == 'false'
# Fetching a second time to allow loading of both valid and invalid email addresses.
# Without this, it'll return people, but only invalid email addresses will be included.
Person.where(id: people_with_invalid_email_addresses.ids)
end
private
attr_accessor :people
def filter_scope
people.includes(:email_addresses).references(:email_addresses)
end
def people_with_invalid_email_addresses
filter_scope.where('email_addresses.valid_values = :valid OR people.id IN(:people_ids)',
valid: false,
people_ids: select_person_id_with_duplicate_primary_email_addresses)
end
def select_person_id_with_duplicate_primary_email_addresses
EmailAddress.select(:person_id)
.where(person_id: people.ids, primary: true)
.group(:person_id)
.having('count(*) > 1')
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/people/merges/bulk_controller.rb
|
class Api::V2::Contacts::People::Merges::BulkController < Api::V2Controller
skip_before_action :validate_and_transform_json_api_params
before_action :reject_if_in_batch_request
PersonMerge = Struct.new(:winner, :loser)
def create
skip_authorization
load_people
build_merge_structs
process_and_render_merges do |merge|
merge_people(merge)
merge.winner
end
end
private
def person_ids
params[:data].flat_map do |merge_params|
attributes = extract_merge_attributes(merge_params)
[attributes[:winner_id], attributes[:loser_id]]
end
end
def extract_merge_attributes(params)
params
.require(:data)
.require(:attributes)
.permit(merge_attributes)
end
def merge_attributes
[:winner_id, :loser_id]
end
def load_people
@people = people_scope.where(id: person_ids).tap(&:first!).to_a
end
def people_scope
Person.joins(:account_lists).where(account_lists: { id: account_lists })
end
def build_merge_structs
@merges = params[:data].map do |merge_params|
attributes = extract_merge_attributes(merge_params)
build_merge_from_attributes(attributes)
end
@merges.compact!
raise ActiveRecord::RecordNotFound unless @merges.any?
end
def build_merge_from_attributes(attributes)
winner = @people.find { |person| person.id == attributes[:winner_id] }
loser = @people.find { |person| person.id == attributes[:loser_id] }
return nil unless (winner && loser) && (winner.contact_ids & loser.contact_ids).any?
PersonMerge.new(winner, loser)
end
def process_and_render_merges(&process)
winners = @merges.map(&process)
render json: BulkResourceSerializer.new(resources: winners),
include: include_params,
fields: field_params
end
def merge_people(merge)
merge.winner.merge(merge.loser)
end
def permitted_filters
[]
end
def pundit_user
PunditContext.new(current_user)
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::AccountListsController, type: :controller do
let(:factory_type) { :account_list }
let!(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let!(:second_account_list) { create(:account_list, users: [user], created_at: 2.weeks.from_now) }
let(:id) { account_list.id }
let(:resource) { account_list }
let(:unpermitted_attributes) { nil }
let(:correct_attributes) { attributes_for(:account_list) }
let(:incorrect_attributes) { { name: nil } }
let!(:notification_preference) { create(:notification_preference, account_list: account_list) }
let(:correct_relationships) do
{
notification_preferences: {
data: {
type: 'notification_preferences',
id: create(:notification_preference).id
}
}
}
end
include_examples 'index_examples'
include_examples 'show_examples'
include_examples 'update_examples'
context 'User::Coach' do
include_context 'common_variables'
let(:contact) { create(:contact, account_list: account_list) }
let!(:pledge) do
create(:pledge,
account_list: account_list,
contact: contact,
amount: 9.99,
expected_date: 1.month.ago)
end
let!(:second_pledge) do
create(:pledge,
account_list: account_list,
amount: 10.00,
expected_date: 2.months.from_now)
end
let!(:appeal) { create(:appeal, account_list: account_list) }
let(:coach) { create(:user).becomes(User::Coach) }
before do
pledge.update(appeal: appeal)
account_list.coaches << coach
account_list.update(primary_appeal_id: appeal.id)
end
describe '#show' do
it 'shows list of resources to the coach who is signed in' do
api_login(coach)
get :show, full_params
expect(response.status).to eq(200), invalid_status_detail
expect(json_response['data']['attributes']['primary_appeal']).to_not be_nil
%w(balance committed currency monthly_goal primary_appeal progress received total_pledges).each do |key|
expect(json_response['data']['attributes']).to have_key(key)
end
end
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/contacts/analytics_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::V2::Contacts::AnalyticsController, type: :controller do
# This is required!
let(:user) { create(:user_with_account) }
# This MAY be required!
let(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_with_anniversary_with_week) do
person = create(:person, anniversary_month: Date.current.month,
anniversary_day: Date.current.day)
contact = create(:contact, account_list_id: account_list.id,
status: 'Partner - Financial')
contact.people << person
contact
end
let!(:contact_with_birthday_this_week) do
person = create(:person, birthday_month: Date.current.month,
birthday_day: Date.current.day)
contact = create(:contact, account_list_id: account_list.id,
status: 'Partner - Financial')
contact.people << person
contact
end
# This is required!
let!(:resource) do
# Creates the Singular Resource for this spec - change as needed
# Example: create(:contact, account_list: account_list)
Contact::Analytics.new(user.contacts)
end
# If needed, keep this ;)
let(:parent_param) do
# This is a hash of the nested keys needed for the URL,
# If the resource is listed more than once, you can add multiple.
# Ex: /api/v2/:account_list_id/contacts/:contact_id/addresses/:id
# --
# Note: Don't include :id
# Example: { account_list_id: account_list_id }
{}
end
# This is required!
let(:correct_attributes) do
# A hash of correct attributes for creating/updating the resource
# Example: { subject: 'test subject', start_at: Time.now, account_list_id: account_list.id }
{}
end
# These includes can be found in:
# spec/support/shared_controller_examples.rb
include_examples 'show_examples', except: [:sparse_fieldsets]
context '#show' do
context '#birthdays_this_week' do
let(:parent_contact_relationship) { JSON.parse(response.body)['included'].first['relationships']['parent_contact'] }
it 'includes parent_contact relationship when birthdays_this_week is included' do
api_login(user)
get :show, include: :birthdays_this_week
expect(parent_contact_relationship['data']['id']).to eq(contact_with_birthday_this_week.id)
end
end
end
end
|
chuckmersereau/api_practice
|
config/initializers/mime_types.rb
|
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Adds the JSONAPI Spec media type:
# http://jsonapi.org/format/#introduction
# http://jsonapi.org/format/#content-negotiation
#
# Solution: https://github.com/rails-api/active_model_serializers/issues/1027#issuecomment-126543577
api_mime_types = %w(
application/vnd.api+json
text/x-json
application/json
)
Mime::Type.unregister :json
Mime::Type.register 'application/vnd.api+json', :json, api_mime_types
# For csv and xlsx exports
Mime::Type.register "text/csv", :csv unless Mime::Type.lookup_by_extension(:csv)
Mime::Type.register "application/xlsx", :xlsx unless Mime::Type.lookup_by_extension(:xlsx)
|
chuckmersereau/api_practice
|
spec/factories/duplicate_record_pairs.rb
|
<gh_stars>0
FactoryBot.define do
factory :duplicate_contacts_pair, class: 'DuplicateRecordPair' do
association :account_list
reason 'Just testing'
record_one do
create(:contact, account_list: account_list)
end
record_two do
create(:contact, account_list: account_list)
end
end
factory :duplicate_people_pair, class: 'DuplicateRecordPair' do
association :account_list
reason 'Just testing'
record_one do
create(:person).tap do |person|
create(:contact, account_list: account_list)
account_list.reload.contacts.first.people << person
end
end
record_two do
create(:person).tap do |person|
account_list.contacts.first.people << person
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20161007231427_create_admin_reset_logs.rb
|
class CreateAdminResetLogs < ActiveRecord::Migration
def change
create_table :admin_reset_logs do |t|
t.integer :admin_resetting_id
t.integer :resetted_user_id
t.string :reason
t.timestamps null: false
end
end
end
|
chuckmersereau/api_practice
|
spec/services/account_list/pledge_matcher_spec.rb
|
require 'rails_helper'
describe AccountList::PledgeMatcher do
subject { described_class.new(donation) }
let!(:donation) do
build(:donation, donor_account: donor_account, appeal: appeal,
amount: 200.00, appeal_amount: 100.00)
end
let(:donor_account) { build(:donor_account) }
let(:appeal) { create(:appeal, account_list: account_list) }
let(:account_list) { create(:account_list) }
let!(:contact) do
create(:contact, donor_accounts: [donor_account],
account_list: account_list, appeals: [appeal])
end
context 'a Pledge already exists' do
let!(:pledge) do
create(:pledge, appeal: appeal, contact: contact, amount: 250.00)
end
describe '#needs_pledge?' do
it 'cannot assign a Pledge if there already is one' do
donation.update! pledges: [pledge]
expect(subject.needs_pledge?).to be false
end
it 'returns true if there is an Appeal and no existing PledgeDonation' do
expect(subject.needs_pledge?).to be true
end
end
describe '#pledge' do
it 'returns the pre-existing Pledge' do
expect(subject.pledge).to eq pledge
end
end
context 'the donation has no associated Appeal' do
before { donation.appeal = nil }
it 'will not return a Pledge' do
expect(subject.pledge).to be_nil
end
it 'automatically associates with the existing Pledge when an Appeal is added' do
donation.save!
expect(subject.pledge).to be_nil
expect(donation.pledges).to be_empty
donation.update!(appeal: appeal)
expect(donation.pledges).to include pledge
end
end
end
context 'a Pledge does not already exist' do
describe '#needs_pledge?' do
it 'cannot assign a Pledge if there is no associated Appeal' do
donation.update! appeal: nil
expect(subject.needs_pledge?).to be false
end
it 'returns true if there is an Appeal and no existing Pledge' do
expect(subject.needs_pledge?).to be true
end
end
describe '#pledge' do
it 'returns a new Pledge' do
expect(subject.pledge).to be_a Pledge
end
it 'returns a Pledge with the Donation attributes' do
expect(subject.pledge.amount).to eq donation.pledge_amount
expect(subject.pledge.expected_date).to eq donation.donation_date
expect(subject.pledge.account_list).to eq account_list
expect(subject.pledge.contact).to eq contact
expect(subject.pledge.amount_currency).to eq donation.currency
expect(subject.pledge.appeal).to eq donation.appeal
end
it 'fills the Pledge with the #appeal_amount' do
expect(subject.pledge.amount).to eq 100.00
end
it 'uses the #amount if there is no #appeal_amount' do
donation.appeal_amount = nil
expect(subject.pledge.amount).to eq 200.00
end
context 'the donation has no associated Appeal' do
before { donation.appeal = nil }
it 'will not return a Pledge' do
expect(subject.pledge).to be_nil
end
it 'automatically creates a new Pledge when an Appeal is added' do
donation.save!
expect(subject.pledge).to be_nil
expect(donation.pledges).to be_empty
donation.update!(appeal: appeal)
expect(donation.pledges).not_to be_empty
end
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/family_relationship.rb
|
<gh_stars>0
class FamilyRelationship < ApplicationRecord
belongs_to :person
belongs_to :related_person, class_name: 'Person'
validates :related_person_id, :relationship, presence: true
PERMITTED_ATTRIBUTES = [:created_at,
:person_id,
:overwrite,
:relationship,
:related_person_id,
:updated_at,
:updated_in_db_at,
:id].freeze
def self.add_for_person(person, attributes)
fr = person.family_relationships.find_by(related_person_id: attributes[:related_person_id])
return fr if fr
new_or_create = person.new_record? ? :new : :create
attributes = attributes.except(:_destroy)
person.family_relationships.send(new_or_create, attributes)
end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/exporter.rb
|
# This class handles the process of exporting MPDX data to Mail Chimp.
class MailChimp::Exporter
attr_reader :mail_chimp_account, :gibbon_wrapper, :list_id
def initialize(mail_chimp_account, list_id = nil)
@mail_chimp_account = mail_chimp_account
@gibbon_wrapper = MailChimp::GibbonWrapper.new(mail_chimp_account)
@list_id = list_id || mail_chimp_account.primary_list_id
end
def export_contacts(contact_ids = nil, ignore_status = false)
MailChimp::ConnectionHandler.new(mail_chimp_account)
.call_mail_chimp(self, :export_contacts!, contact_ids, ignore_status)
end
def export_contacts!(contact_ids, ignore_status)
contacts_to_export = fetch_contacts_to_export(contact_ids, ignore_status)
# on non-primary lists, all of the subscriptions should be manual, so they shouldn't be auto-cleaned
emails_of_members_to_remove = fetch_emails_of_members_to_remove if primary_list?
export_adds_and_updates(contacts_to_export) if contacts_to_export.present?
export_deletes(emails_of_members_to_remove) if emails_of_members_to_remove.present?
end
private
def primary_list?
@list_id == mail_chimp_account.primary_list_id
end
def appeal_export?
@appeal_id.present?
end
def export_adds_and_updates(contacts)
group_adder.add_status_interests(statuses_from_contacts(contacts))
group_adder.add_tags_interests(tags_from_contacts(contacts))
merge_variables_to_add.each do |merge_variable|
merge_field_adder.add_merge_field(merge_variable)
end
batcher.subscribe_contacts(contacts)
end
def export_deletes(emails_of_members_to_remove)
emails_with_reasons = emails_of_members_to_remove.each_with_object({}) do |email, hash|
reason = unsubscribe_reason(email)
hash[email] = reason
end
batcher.unsubscribe_members(emails_with_reasons)
end
def unsubscribe_reason(email)
# newsletter: none/physical
return 'email on contact with newsletter set to None or Physical' if non_opt_out_people_emails.exists?(email: email)
# opt-out
return "email on person marked as 'Opt-out of Email Newsletter'" if primary_emails.exists?(email: email)
# non-primary
return 'email marked as non-primary' if active_emails.exists?(email: email)
# historic email
return 'email marked as historic' if mpdx_email_addresses.exists?(email: email)
# not in mpdx
'email not in MPDX'
end
def mpdx_email_addresses
EmailAddress.joins(person: [:contacts]).where(contacts: { account_list_id: mail_chimp_account.account_list.id })
end
def active_emails
mpdx_email_addresses.where(historic: false)
end
def primary_emails
active_emails.where(primary: true)
end
def non_opt_out_people_emails
primary_emails.where(people: { optout_enewsletter: false })
end
def group_adder
@group_adder ||= InterestAdder.new(mail_chimp_account, gibbon_wrapper, list_id)
end
def batcher
@batcher ||= Batcher.new(mail_chimp_account, gibbon_wrapper, list_id)
end
def merge_field_adder
@merge_field_adder ||= MergeFieldAdder.new(mail_chimp_account, gibbon_wrapper, list_id)
end
def fetch_emails_of_members_to_remove
relevant_mail_chimp_members.pluck(:email).map(&:downcase).uniq - mail_chimp_account.newsletter_emails
end
def fetch_contacts_to_export(contact_ids, ignore_status)
relevant_contact_scope = mail_chimp_account.relevant_contacts(contact_ids, ignore_status)
.includes(primary_contact_person: :person, people: :primary_email_address)
relevant_contact_scope.find_each.select { |contact| contact_changed_or_new?(contact) }.sort_by(&:created_at)
end
def statuses_from_contacts(contacts)
(contacts.map(&:status).compact + ['Partner - Pray']).uniq
end
def tags_from_contacts(_contacts)
mail_chimp_account.account_list.contact_tags.pluck(:name).uniq
end
def merge_variables_to_add
['GREETING'].concat(appeal_export? ? ['DONATED_TO_APPEAL'] : [])
end
def fetch_members_to_unsubscribe(contacts)
gibbon_wrapper.list_emails(list_id) - primary_email_addresses_scope(contacts).pluck(:email)
end
def primary_email_addresses_scope(contacts)
EmailAddress.joins(person: :contact_people)
.where(contact_people: { contact_id: contacts.ids }, primary: true)
end
def contact_changed_or_new?(contact)
contact.people.any? do |person|
next unless person.primary_email_address
member = members_by_email[person.primary_email_address.email]
contact_person_changed_or_new?(contact, person, member)
end
end
def contact_person_changed_or_new?(contact, person, member)
member.nil? ||
member.status != contact.status ||
member.greeting != contact.greeting ||
member.first_name != person.first_name ||
member.last_name != person.last_name ||
member.contact_locale != contact.locale
end
def members_by_email
@members_by_email ||= relevant_mail_chimp_members.map { |member| { member.email.downcase => member } }.reduce({}, :merge)
end
def relevant_mail_chimp_members
@relevant_mail_chimp_members ||= mail_chimp_account.mail_chimp_members.where(list_id: list_id)
end
def gibbon_list
gibbon_wrapper.gibbon_list_object(list_id)
end
end
|
chuckmersereau/api_practice
|
app/services/siebel.rb
|
# This service as been superseded by DonationImports::Siebel.
# It should be deleted when DonationImports::Siebel is stable.
require_dependency 'data_server'
class Siebel < DataServer
# Donations should sometimes be deleted if they were misclassifed and then
# later correctly re-classified. However, we have had 2 recent occasions when
# the Siebel API incorectly returned no donations (or a lot fewer than
# expected) and it caused MPDX users to unexpectedly lose bunches of
# donations. So as a safety measure for that only remove a few donations per
# import as typically only a couple at most will be misclassified.
MAX_DONATIONS_TO_DELETE_AT_ONCE = 3
def self.requires_credentials?
false
end
def import_profiles
designation_profiles = []
profiles.each do |profile|
designation_profile = Retryable.retryable do
if profile.id
@org.designation_profiles.where(user_id: @org_account.person_id, code: profile.id)
.first_or_create(name: profile.name)
else
@org.designation_profiles.where(user_id: @org_account.person_id, code: nil)
.first_or_create(name: profile.name)
end
end
import_profile_balance(designation_profile)
designation_profiles << designation_profile
# Add included designation accounts
profile.designations.each do |designation|
find_or_create_designation_account(designation.number,
designation_profile,
name: designation.description,
staff_account_id: designation.staff_account_id,
chartfield: designation.chartfield)
end
next if designation_profile.account_list
AccountList::FromProfileLinker.new(designation_profile, @org_account)
.link_account_list!
end
designation_profiles
end
def import_profile_balance(profile)
total = 0
# the profile balance is the sum of the balances from each designation account in that profile
profile.designation_accounts.each do |da|
next unless da.staff_account_id.present?
balance = SiebelDonations::Balance.find(employee_ids: da.staff_account_id).first
balance_amount = da.active? ? balance.primary : 0
da.update(balance: balance_amount, balance_updated_at: Time.now)
total += balance_amount
end
profile.update(balance: total, balance_updated_at: Time.now)
profile
end
def import_donors(profile, date_from = nil)
designation_numbers = profile.designation_accounts.pluck(:designation_number)
return unless designation_numbers.present?
account_list = profile.account_list
SiebelDonations::Donor.find(having_given_to_designations: designation_numbers.join(','),
contact_filter: :all,
account_address_filter: :primary,
contact_email_filter: :all,
contact_phone_filter: :all).each do |siebel_donor|
donor_account = add_or_update_donor_account(account_list, siebel_donor, profile, date_from)
next unless siebel_donor.type == 'Business'
add_or_update_company(account_list, siebel_donor, donor_account)
end
end
def import_donations(profile, start_date = nil, end_date = nil)
# if no date_from was passed in, use min date from query_ini
rails_start_date = start_date
if start_date.blank?
start_date = @org.minimum_gift_date ? @org.minimum_gift_date : '01/01/2004'
rails_start_date = Date.strptime(start_date, '%m/%d/%Y')
start_date = rails_start_date.strftime('%Y-%m-%d')
else
start_date = start_date.strftime('%Y-%m-%d')
end
rails_end_date = end_date ? Date.strptime(end_date, '%m/%d/%Y') : Time.now
end_date = rails_end_date.strftime('%Y-%m-%d')
profile.designation_accounts.each do |da|
donations = SiebelDonations::Donation.find(designations: da.designation_number,
posted_date_start: start_date,
posted_date_end: end_date)
donations.each do |donation|
add_or_update_donation(donation, da, profile)
end
# Sometimes the Siebel API flakes out and doesn't return any donations.
# When that happened before it would cause all MPDX's donation records to
# be destroyed (for Cru USA users). As a sanity check for that flaky API
# condition, don't remove any donations if there are no donations in the
# range we are checking (past 50 days typically).
next if donations.empty?
remove_deleted_siebel_donations(da, rails_start_date, rails_end_date,
start_date, end_date)
end
end
def remove_deleted_siebel_donations(da, rails_start_date, rails_end_date,
start_date, end_date)
# Check for removed donations
all_current_donations_relation = da.donations.where('donation_date >= ? AND donation_date <= ?',
rails_start_date, rails_end_date)
.where.not(remote_id: nil)
all_current_donations_array = all_current_donations_relation.to_a
SiebelDonations::Donation.find(designations: da.designation_number, donation_date_start: start_date,
donation_date_end: end_date).each do |siebel_donation|
donation = all_current_donations_relation.find_by(remote_id: siebel_donation.id)
all_current_donations_array.delete(donation)
end
donations_destroyed = 0
# Double check removed donations straight from Siebel
all_current_donations_array.each do |donation|
next if donation.appeal.present?
donation_date = donation.donation_date.strftime('%Y-%m-%d')
siebel_donations = SiebelDonations::Donation.find(designations: da.designation_number,
donors: donation.donor_account.account_number,
start_date: donation_date,
end_date: donation_date)
# The previous query might return a donation for the same date, so check that the remote_id is equal
next unless siebel_donations.blank? ||
(siebel_donations.size == 1 && siebel_donations.first.id != donation.remote_id)
donation.destroy
donations_destroyed += 1
break if donations_destroyed == MAX_DONATIONS_TO_DELETE_AT_ONCE
end
end
def profiles_with_designation_numbers
@profiles_with_designation_numbers ||= profiles.map do |profile|
{ designation_numbers: profile.designations.map(&:number),
name: profile.name,
code: profile.id }
end
end
def profiles
unless @profiles
if @org_account.user.key_accounts.none?
# This org account is no longer useful
@org_account.destroy
return []
end
Retryable.retryable(on: RestClient::InternalServerError, times: 3) do
@profiles = SiebelDonations::Profile.find(ssoGuid: @org_account.remote_id)
end
end
@profiles
end
protected
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
Retryable.retryable do
profile.designation_accounts << da unless profile.designation_accounts.include?(da)
da.update_attributes(extra_attributes) if extra_attributes.present?
@designation_accounts[number] = da
end
end
@designation_accounts[number]
end
def add_or_update_donation(siebel_donation, designation_account, profile)
default_currency = @org.default_currency_code || 'USD'
donor_account = @org.donor_accounts.find_by(account_number: siebel_donation.donor_id)
# find donor account from siebel if we don't already have this donor
unless donor_account
siebel_donor = SiebelDonations::Donor.find(ids: siebel_donation.donor_id).first
if siebel_donor
account_list = profile.account_list
donor_account = add_or_update_donor_account(account_list, siebel_donor, profile)
end
end
unless donor_account
Rollbar.raise_or_notify(Exception.new("Can't find donor account for #{siebel_donation.inspect}"))
return
end
Retryable.retryable do
date = Date.strptime(siebel_donation.donation_date, '%Y-%m-%d')
attributes = {
amount: siebel_donation.amount,
channel: siebel_donation.channel,
currency: default_currency,
designation_account_id: designation_account.id,
donation_date: date,
donor_account_id: donor_account.id,
motivation: siebel_donation.campaign_code,
payment_method: siebel_donation.payment_method,
payment_type: siebel_donation.payment_type,
remote_id: siebel_donation.id,
tendered_amount: siebel_donation.amount,
tendered_currency: default_currency
}
finder = DonationImports::Base::FindDonation.new(designation_profile: profile, attributes: attributes)
donation = finder.find_and_merge
donation ||= Donation.new
donation.update!(attributes)
donation
end
end
def add_or_update_company(account_list, siebel_donor, donor_account)
master_company = MasterCompany.find_by(name: siebel_donor.account_name)
company = @org_account.user.partner_companies.find_by(master_company_id: master_company.id) if master_company
company ||= account_list.companies.new(master_company: master_company)
contact = siebel_donor.primary_contact || SiebelDonations::Contact.new
address = siebel_donor.primary_address || SiebelDonations::Address.new
street = [address.address1, address.address2, address.address3, address.address4].compact.join("\n")
company.attributes = {
name: siebel_donor.account_name,
phone_number: contact.primary_phone_number.try(:phone),
street: street,
city: address.city,
state: address.state,
postal_code: address.zip
}
company.save!
unless donor_account.master_company_id == company.master_company.id
donor_account.update_attribute(:master_company_id, company.master_company_id)
end
company
end
def add_or_update_donor_account(account_list, donor, _profile, date_from = nil)
Retryable.retryable do
donor_account = @org.donor_accounts.where(account_number: donor.id).first_or_initialize
donor_account.attributes = { name: donor.account_name,
donor_type: donor.type }
donor_account.save!
contact = donor_account.link_to_contact_for(account_list)
raise 'Failed to link to contact' unless contact
# Save addresses
donor.addresses&.each do |address|
next if date_from.present? && DateTime.parse(address.updated_at) < date_from && contact.addresses.present?
add_or_update_address(address, donor_account, donor_account)
# Make sure the contact has the primary address
add_or_update_address(address, contact, donor_account) if address.primary == true
end
# Save people (siebel calls them contacts)
donor.contacts&.each do |person|
next if date_from.present? && DateTime.parse(person.updated_at) < date_from && contact.people.present?
add_or_update_person(person, donor_account, contact, date_from)
end
donor_account
end
end
def add_or_update_person(siebel_person, donor_account, contact, date_from = nil)
master_person_from_source = @org.master_people.find_by('master_person_sources.remote_id' => siebel_person.id)
# If we didn't find someone using the real remote_id, try the "old style"
unless master_person_from_source
remote_id = siebel_person.primary ? "#{donor_account.account_number}-1" : "#{donor_account.account_number}-2"
master_person_from_source = @org.master_people.find_by('master_person_sources.remote_id' => remote_id)
if master_person_from_source
MasterPersonSource.where(organization_id: @org.id, remote_id: remote_id).update_all(remote_id: siebel_person.id)
end
end
person = contact.people.find_by(first_name: siebel_person.first_name, last_name: siebel_person.last_name)
person ||= contact.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)
gender = case siebel_person.sex
when 'F' then 'female'
when 'M' then 'male'
end
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
} if person.new_record?
person.master_person_id ||= MasterPerson.find_or_create_for_person(person, donor_account: donor_account).try(:id)
person.save!
Retryable.retryable do
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
end
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: siebel_person.id)
.first_or_create(master_person_id: person.master_person.id)
end
end
# Phone Numbers
siebel_person.phone_numbers&.each do |pn|
next if date_from.present? && DateTime.parse(pn.updated_at) < date_from && contact_person.phone_numbers.present?
add_or_update_phone_number(pn, person)
# Make sure the contact person has the primary phone number
add_or_update_phone_number(pn, contact_person) if pn.primary == true
end
# Email Addresses
siebel_person.email_addresses&.each do |email|
next if date_from.present? &&
contact_person.email_addresses.present? &&
DateTime.parse(email.updated_at) < date_from
add_or_update_email_address(email, person)
# Make sure the contact person has the primary email address
add_or_update_email_address(email, contact_person) if email.primary == true
end
[person, contact_person]
end
def add_or_update_address(address, object, source_donor_account)
new_address = new_address_from_siebel(address, object, source_donor_account)
place_match = object.addresses_including_deleted.find { |a| a.equal_to?(new_address) }
remote_id_match = object.addresses_including_deleted.find { |a| a.remote_id == new_address.remote_id }
address_to_update = place_match || remote_id_match
# Remove the remote id from the old address if needed in case Siebel reuses address ids
remote_id_match.update(remote_id: nil) if remote_id_match && place_match && place_match != remote_id_match
if address_to_update
address_to_update.assign_attributes(new_address.attributes.select { |_k, v| v.present? })
address_to_update.save!(validate: false)
new_or_updated_address = address_to_update
else
new_or_updated_address = object.addresses.create!(new_address.attributes)
end
if new_or_updated_address.primary_mailing_address?
object.addresses.where.not(id: new_or_updated_address.id).update_all(primary_mailing_address: false)
end
rescue ActiveRecord::RecordInvalid => e
raise e.message + " - #{address.inspect}"
end
def new_address_from_siebel(address, object, source_donor_account)
current_primary = object.addresses.find_by(primary_mailing_address: true)
make_primary = current_primary.blank? || (address.primary && current_primary.source == 'Siebel' &&
source_donor_account.present? && current_primary.source_donor_account == source_donor_account)
street_value = [address.address1, address.address2, address.address3, address.address4].compact.join("\n")
new_address = Address.new(street: street_value,
city: address.city,
state: address.state,
postal_code: address.zip,
primary_mailing_address: make_primary,
seasonal: address.seasonal,
location: address.type,
remote_id: address.id,
source: 'Siebel',
start_date: parse_date(address.updated_at),
source_donor_account: source_donor_account)
# Set the master address so we can match by the same address formatted differently
new_address.find_or_create_master_address
new_address
end
def add_or_update_phone_number(phone_number, person)
attributes = {
number: phone_number.phone,
location: phone_number.type.downcase,
primary: phone_number.primary,
remote_id: phone_number.id
}
existing_phone = person.phone_numbers.find { |pn| pn.remote_id == phone_number.id }
if existing_phone
existing_phone.update_attributes(attributes)
else
PhoneNumber.add_for_person(person, attributes)
end
end
def add_or_update_email_address(email, person)
attributes = {
email: email.email,
primary: email.primary,
location: email.type,
remote_id: email.id
}
Retryable.retryable do
existing_email = person.email_addresses.find { |e| e.remote_id == email.id }
if existing_email
begin
existing_email.update_attributes(attributes)
rescue ActiveRecord::RecordNotUnique
# If they already have the email address we're trying to update
# to, don't do anything
end
else
EmailAddress.add_for_person(person, attributes)
end
end
end
def check_credentials!() end
end
class SiebelError < StandardError
end
|
chuckmersereau/api_practice
|
spec/services/google_calendar_integrator_spec.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
require 'rails_helper'
describe GoogleCalendarIntegrator do
let(:user) { create(:user) }
let(:google_account) { create :google_account, person: user }
let(:google_integration) do
build(:google_integration, google_account: google_account,
calendar_integrations: ['Appointment'],
calendar_name: 'My Calendar')
end
let(:integrator) { google_integration.calendar_integrator }
let(:task) { create(:task, account_list: google_integration.account_list, activity_type: 'Appointment') }
let(:google_event) { create(:google_event, activity: task, google_integration: google_integration) }
let(:missing_event_response) do
errors = [{ 'domain' => 'global', 'reason' => 'notFound', 'message' => 'Not Found' }]
double(data: { 'error' => { 'errors' => errors,
'code' => 404, 'message' => 'Not Found' } },
status: 404)
end
context '#sync_tasks' do
it 'calls #sync_task for each future, uncompleted task that is set to be synced' do
task1 = double(id: 1)
task2 = double(id: 2)
allow(google_integration)
.to receive_message_chain(:account_list, :tasks, :future, :uncompleted, :of_type, :ids)
.and_return([task1.id, task2.id])
expect(integrator).to receive(:sync_task).with(task1.id)
expect(integrator).to receive(:sync_task).with(task2.id)
integrator.sync_tasks
end
end
context '#sync_task' do
it 'calls add_task if no google_event exists' do
expect(integrator).to receive(:add_task).with(task)
integrator.sync_task(task)
end
it 'calls update_task if a google_event exists' do
allow(google_integration).to receive(:calendars).and_return(nil)
expect(integrator).to receive(:update_task).with(task, google_event)
integrator.sync_task(task)
end
it 'calls add_task if google_event is for another calendar' do
allow(google_integration).to receive(:calendars).and_return(nil)
google_event.update(calendar_id: 'other-calendar')
expect(integrator).to receive(:add_task).with(task)
integrator.sync_task(task)
end
it 'calls remove_google_event if task is nil' do
allow(google_integration).to receive(:calendars).and_return(nil)
expect(integrator).to receive(:remove_google_event).with(google_event)
task.destroy
integrator.sync_task(task.id)
end
end
context '#add_task' do
it 'creates a google_event' do
allow(google_integration).to receive_message_chain(:calendar_service, :insert_event)
.and_return(double(id: '1234'))
expect do
integrator.send(:add_task, task)
end.to change(GoogleEvent, :count)
expect(GoogleEvent.last.calendar_id).to eq('cal1')
expect(GoogleEvent.last.google_event_id).to eq('1234')
end
it 'removes the calendar integration if the calendar no longer exists on google' do
allow(google_integration).to receive_message_chain(:calendar_service, :insert_event)
.and_raise(Google::Apis::ClientError.new('error', status_code: 404))
expect(google_integration.calendar_integration?).to be true
expect(google_integration.calendar_id).to be_present
expect(google_integration.calendar_name).to be_present
integrator.send(:add_task, task)
expect(google_integration.calendar_integration?).to be false
expect(google_integration.calendar_id).to be_nil
expect(google_integration.calendar_name).to be_nil
end
end
context '#update_task' do
it 'updates a google_event' do
allow(google_integration).to receive_message_chain(:calendar_service, :patch_event).and_return(double)
expect(integrator).to_not receive(:add_task)
google_event.save
expect do
integrator.send(:update_task, task, google_event)
end.to_not change(GoogleEvent, :count)
end
it 'adds the google event if it is missing from google' do
allow(google_integration).to receive_message_chain(:calendar_service, :patch_event)
.and_raise(Google::Apis::ClientError.new('error', status_code: 404))
allow(google_integration).to receive_message_chain(:calendar_service, :insert_event)
.and_return(double(id: '1234'))
integrator.send(:update_task, task, google_event)
expect(GoogleEvent.exists?(id: google_event.id)).to eq(false)
event_attrs = { google_integration_id: google_integration.id, activity_id: task.id, google_event_id: '1234' }
expect(GoogleEvent.exists?(event_attrs)).to eq(true)
end
end
context '#remove_google_event' do
it 'deletes a google_event' do
allow(google_integration).to receive_message_chain(:calendar_service, :delete_event)
google_event.save
expect do
integrator.send(:remove_google_event, google_event)
end.to change(GoogleEvent, :count).by(-1)
end
end
context '#build_api_event_from_mpdx_task' do
it 'sets start and end times for tasks with default lengths' do
event = integrator.send(:build_api_event_from_mpdx_task, task)
expect(event.start.date_time).to_not be_nil
expect(event.end.date_time).to_not be_nil
expect(event.start.date).to be_nil
expect(event.end.date).to be_nil
end
it 'sets an all day event for tasks without default lengths' do
task.activity_type = 'Thank'
event = integrator.send(:build_api_event_from_mpdx_task, task)
expect(event.start.date_time).to be_nil
expect(event.end.date_time).to be_nil
expect(event.start.date).to_not be_nil
expect(event.end.date).to_not be_nil
end
it 'respects the user time zone on an all day event' do
task.activity_type = 'Thank'
task.start_at = 'Thu, 15 Oct 2015 00:55:00 UTC +00:00'
user.time_zone = 'Central Time (US & Canada)'
user.save
event = integrator.send(:build_api_event_from_mpdx_task, task)
expect(event.start.date).to eql('2015-10-14')
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/find_from_name_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Contact::FindFromName, type: :model do
let!(:contact_one) { create(:contact_with_person, name: '<NAME>').reload }
let!(:contact_two) { create(:contact_with_person, name: '<NAME>').reload }
it 'initializes' do
expect(described_class.new(Contact.all, 'test')).to be_a(described_class)
end
describe '#first' do
it 'finds an exact match on the name' do
Person.delete_all
expect(described_class.new(Contact.all, '<NAME>').first).to eq(contact_one)
end
it 'finds a match on the name by parsing full name' do
Person.delete_all
expect(described_class.new(Contact.all, '<NAME>').first).to eq(contact_one)
end
it 'finds an exact match on the greeting' do
Person.delete_all
contact_one.update(greeting: 'Mr. Man')
expect(described_class.new(Contact.all, contact_one.greeting).first).to eq(contact_one)
end
it 'finds a match on the greeting by parsing full name' do
Person.delete_all
contact_one.update(greeting: 'Mcbilly, Bobby and Janey')
expect(described_class.new(Contact.all, 'Bobby and <NAME>').first).to eq(contact_one)
end
it 'finds a match on the greeting by parsing just first name' do
Person.delete_all
contact_one.update(greeting: 'Bobby and Janey')
expect(described_class.new(Contact.all, 'Doe, Bobby & Janey').first).to eq(contact_one)
end
it 'finds an exact match on the person first and last name' do
contact_one.update(name: 'Something irrelevant')
names = "#{contact_one.people.first.last_name}, #{contact_one.people.first.first_name}"
expect(described_class.new(Contact.all, names).first).to eq(contact_one)
end
it 'scopes the query' do
expect(described_class.new(Contact.where(name: contact_one.name), contact_two.name).first).to be_nil
expect(described_class.new(Contact.where(name: contact_two.name), contact_two.name).first).to eq(contact_two)
end
end
end
|
chuckmersereau/api_practice
|
app/exhibits/donation_exhibit.rb
|
class DonationExhibit < DisplayCase::Exhibit
def self.applicable_to?(object)
object.class.name == 'Donation'
end
def to_s
amount
end
def tendered_amount
precision = self[:tendered_amount] == self[:tendered_amount].to_i ? 0 : 2
@context.number_to_current_currency(
self[:tendered_amount], currency: currency, precision: precision
)
end
end
|
chuckmersereau/api_practice
|
spec/workers/donation_amount_recommendation/remote_worker_spec.rb
|
require 'rails_helper'
describe DonationAmountRecommendation::RemoteWorker do
subject { described_class.new }
describe '#perform' do
let(:organization1) { create(:organization) }
let(:organization2) { create(:organization) }
let(:donor_account1) { create(:donor_account, organization: organization1) }
let(:donor_account2) { create(:donor_account, organization: organization2) }
let(:designation_account1) { create(:designation_account, organization: organization1) }
let(:designation_account2) { create(:designation_account, organization: organization2) }
let!(:remote1) do
create(
:donation_amount_recommendation_remote,
donor_number: donor_account1.account_number,
designation_number: designation_account1.designation_number,
organization: organization1,
ask_at: Time.zone.today + 5.days,
started_at: Time.zone.today - 2.months,
suggested_pledge_amount: 200
)
end
let!(:remote2) do
create(
:donation_amount_recommendation_remote,
donor_number: donor_account2.account_number,
designation_number: designation_account2.designation_number,
organization: organization2,
ask_at: Time.zone.today + 2.days,
started_at: Time.zone.today - 1.month,
suggested_pledge_amount: 30
)
end
it 'should iterate through remote and create donation_amount_recommendations' do
expect { subject.perform }.to change { DonationAmountRecommendation.count }.from(0).to(2)
expect(
DonationAmountRecommendation.where(
designation_account: designation_account1,
donor_account: donor_account1,
ask_at: remote1.ask_at,
started_at: remote1.started_at,
suggested_pledge_amount: remote1.suggested_pledge_amount
)
).to_not be_nil
expect(
DonationAmountRecommendation.where(
designation_account: designation_account2,
donor_account: donor_account2,
ask_at: remote2.ask_at,
started_at: remote2.started_at,
suggested_pledge_amount: remote2.suggested_pledge_amount
)
).to_not be_nil
end
end
context 'unknown organization' do
before do
create(:donation_amount_recommendation_remote, organization_id: SecureRandom.uuid)
end
it 'should not create donation_amount_recommendation' do
expect { subject.perform }.to_not change { DonationAmountRecommendation.count }
end
end
context 'unknown donor_number' do
before do
create(:donation_amount_recommendation_remote, donor_number: '123')
end
it 'should not create donation_amount_recommendation' do
expect { subject.perform }.to_not change { DonationAmountRecommendation.count }
end
end
context 'unknown designation_number' do
before do
create(:donation_amount_recommendation_remote, designation_number: '123')
end
it 'should not create donation_amount_recommendation' do
expect { subject.perform }.to_not change { DonationAmountRecommendation.count }
end
end
context 'donation_amount_recommendation_remote exists' do
let(:organization) { create(:organization) }
let(:donor_account) { create(:donor_account, organization: organization) }
let(:designation_account) { create(:designation_account, organization: organization) }
let!(:remote) do
create(
:donation_amount_recommendation_remote,
donor_number: donor_account.account_number,
designation_number: designation_account.designation_number,
organization: organization,
ask_at: Time.zone.today + 5.days,
started_at: Time.zone.today - 2.months,
suggested_pledge_amount: 200
)
end
it 'should create donation_amount_recommendation' do
expect { subject.perform }.to change { DonationAmountRecommendation.count }.from(0).to(1)
donation_amount_recommendation = DonationAmountRecommendation.first
expect(donation_amount_recommendation.ask_at).to eq(remote.ask_at)
expect(donation_amount_recommendation.started_at).to eq(remote.started_at)
expect(donation_amount_recommendation.suggested_pledge_amount).to eq(remote.suggested_pledge_amount)
end
context 'donation_amount_recommendation exists' do
let!(:donation_amount_recommendation) do
create(
:donation_amount_recommendation,
ask_at: Time.zone.today + 1.year,
started_at: Time.zone.today - 20.days,
suggested_pledge_amount: 20,
donor_account: donor_account,
designation_account: designation_account
)
end
before do
subject.perform
donation_amount_recommendation.reload
end
it 'should update ask_at' do
expect(donation_amount_recommendation.ask_at).to eq(remote.ask_at)
end
it 'should update started_at' do
expect(donation_amount_recommendation.started_at).to eq(remote.started_at)
end
it 'should update suggested_pledge_amount' do
expect(donation_amount_recommendation.suggested_pledge_amount).to eq(remote.suggested_pledge_amount)
end
end
end
context 'donation_amount_recommendation_remote does not exist' do
let(:organization) { create(:organization) }
let(:donor_account) { create(:donor_account, organization: organization) }
let(:designation_account) { create(:designation_account, organization: organization) }
context 'donation_amount_recommendation exists' do
let!(:donation_amount_recommendation) do
create(
:donation_amount_recommendation,
ask_at: Time.zone.today + 1.year,
started_at: Time.zone.today - 20.days,
suggested_pledge_amount: 20,
donor_account: donor_account,
designation_account: designation_account,
updated_at: 1.day.ago
)
end
it 'should delete donation_amount_recommendation' do
subject.perform
expect { donation_amount_recommendation.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.