repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/notifications_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::AccountLists::NotificationsController, type: :controller do
let(:factory_type) { :notification }
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_id: account_list.id) }
let!(:notifications) { create_list(:notification, 2, contact_id: contact.id) }
let(:notification) { notifications.first }
let(:notification_type) { create(:notification_type) }
let(:id) { notification.id }
let(:resource) { notification }
let(:parent_param) { { account_list_id: account_list.id } }
let(:unpermitted_attributes) { nil }
let(:correct_attributes) do
{
cleared: true,
event_date: Time.now.getlocal
}
end
let(:correct_relationships) do
{
notification_type: {
data: {
type: 'notification_types',
id: notification_type.id
}
},
contact: {
data: {
type: 'contacts',
id: contact.id
}
}
}
end
let(:incorrect_attributes) do
{
event_date: nil
}
end
let(:reference_key) { :event_date }
include_examples 'index_examples'
include_examples 'show_examples'
include_examples 'create_examples'
include_examples 'update_examples'
include_examples 'destroy_examples'
end
|
chuckmersereau/api_practice
|
app/services/account_list/notifications_sender.rb
|
class AccountList::NotificationsSender
def initialize(account_list)
@account_list = account_list
@notifications_to_email = {}
end
def send_notifications
notifications = NotificationType.check_all(account_list)
NotificationType.types.each do |notification_type_string|
notification_type = notification_type_string.constantize.first
next unless notifications[notification_type_string].present?
create_tasks(notifications[notification_type_string], notification_type)
queue_emails(notifications[notification_type_string], notification_type)
end
create_emails
end
private
def create_tasks(notifications_of_type, notification_type)
task_notification_preference =
notification_preferences
.find_by(notification_type_id: notification_type.id, user_id: nil, task: true)
return unless task_notification_preference
notifications_of_type.each do |notification|
notification_type.create_task(account_list, notification)
end
end
def queue_emails(notifications_of_type, notification_type)
email_notification_preferences =
notification_preferences
.where(notification_type_id: notification_type.id, email: true)
.where.not(user_id: nil)
return unless email_notification_preferences.present?
email_notification_preferences.each do |email_notification_preference|
@notifications_to_email[email_notification_preference.user_id] ||=
{ user: email_notification_preference.user, notifications_by_type: {} }
@notifications_to_email[email_notification_preference.user_id][:notifications_by_type][notification_type] =
notifications_of_type
end
end
def create_emails
@notifications_to_email.each do |_key, notifications_by_user|
account_list_id = notifications_by_user[:user].account_lists.many? ? @account_list.id : nil
NotificationMailer.delay.notify(
notifications_by_user[:user],
notifications_by_user[:notifications_by_type],
account_list_id
)
end
end
attr_reader :account_list, :notifications_to_email
delegate :notification_preferences, to: :account_list
end
|
chuckmersereau/api_practice
|
db/migrate/20150804155832_create_account_list_invites.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class CreateAccountListInvites < ActiveRecord::Migration
def change
create_table :account_list_invites do |t|
t.belongs_to :account_list
t.integer :invited_by_user_id, null: false
t.string :code, null: false
t.string :recipient_email, null: false
t.integer :accepted_by_user_id
t.datetime :accepted_at
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/imports/csv_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::AccountLists::Imports::CsvController, type: :controller do
let(:factory_type) { :import }
let(:resource_type) { :imports }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:account_list_id) { account_list.id }
let!(:id) { import.id }
let!(:parent_param) { { account_list_id: account_list_id } }
let!(:imports) do
create_list(
:csv_import,
2,
account_list: account_list,
user: user,
in_preview: true,
file_headers_mappings: file_headers_mappings,
file_constants_mappings: file_constants_mappings
)
end
let!(:import) { imports.first }
let!(:resource) { import }
let(:file_headers_mappings) do
{
'city' => 'city',
'pledge_amount' => 'amount',
'pledge_frequency' => 'frequency',
'contact_name' => 'fname',
'country' => 'country',
'email_1' => 'email-address',
'envelope_greeting' => 'envelope-greeting',
'first_name' => 'fname',
'greeting' => 'greeting',
'last_name' => 'lname',
'newsletter' => 'newsletter',
'notes' => 'extra-notes',
'phone_1' => 'phone',
'spouse_email' => 'Spouse-email-address',
'spouse_first_name' => 'Spouse-fname',
'spouse_last_name' => 'Spouse-lname',
'spouse_phone' => 'Spouse-phone-number',
'state' => 'province',
'status' => 'status',
'street' => 'street',
'zip' => 'zip-code'
}
end
let(:file_constants_mappings) do
{
'status' => [
{ 'id' => 'Partner - Financial', 'values' => ['Praying and giving'] }
],
'pledge_frequency' => [
{ 'id' => 'Monthly', 'values' => ['Monthly'] }
],
'newsletter' => [
{ 'id' => 'Both', 'values' => ['Both'] }
]
}
end
let(:correct_attributes) do
{ file: Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'sample_csv_to_import.csv')) }
end
let(:update_attributes) do
{
tag_list: 'test',
updated_in_db_at: resource.updated_at
}
end
let(:given_reference_key) { :file_url }
let(:correct_relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: account_list.id
}
},
user: {
data: {
type: 'users',
id: user.id
}
}
}
end
let(:incorrect_attributes) do
{ file: Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'tnt', 'tnt_export.xml')) }
end
let(:unpermitted_attributes) { { file_headers: ['test'] } }
context 'file uploading uses content type multipart form-data' do
before(:each) { request.headers['CONTENT_TYPE'] = 'multipart/form-data' }
include_examples 'create_examples'
include_examples 'update_examples'
end
include_examples 'index_examples'
include_examples 'show_examples'
describe '#index' do
it 'only returns imports with source csv' do
create(:tnt_import, account_list: account_list, user: user)
api_login(user)
expect(account_list.imports.count).to eq(3)
get :index, full_correct_attributes
expect(JSON.parse(response.body)['data'].size).to eq(2)
end
it 'returns mappings without transforming their keys' do
api_login(user)
get :index, full_correct_attributes
attributes = JSON.parse(response.body)['data'].first['attributes']
expect(attributes['file_headers_mappings']).to eq file_headers_mappings
expect(attributes['file_constants_mappings']).to eq file_constants_mappings
end
end
describe '#show' do
it 'does not return an import if it does not have source csv' do
tnt_import = create(:tnt_import, account_list: account_list, user: user)
api_login(user)
get :show, parent_param.merge(id: tnt_import.id)
expect(response.status).to eq(404)
end
end
describe '#create' do
it 'creates a file' do
api_login(user)
expect do
post :create, full_correct_attributes
end.to change { resource.class.count }.by(1)
expect(response.status).to eq(201)
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.file).to be_present
expect(import.file.path).to end_with("uploads/import/file/#{import.id}/sample_csv_to_import.csv")
end
it 'defaults source to csv' do
api_login(user)
post :create, full_correct_attributes.tap { |params|
params[:data][:attributes][:source] = 'twitter'
}
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.source).to eq 'csv'
end
it 'defaults in_preview to true' do
api_login(user)
post :create, full_correct_attributes.tap { |params|
params[:data][:attributes].delete([:in_preview, 'in_preview'])
}
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.in_preview?).to eq true
end
it 'defaults user_id to current user' do
api_login(user)
full_correct_attributes[:data][:relationships].delete(:user)
post :create, full_correct_attributes
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.user_id).to eq user.id
end
it 'persists cached file data' do
api_login(user)
post :create, full_correct_attributes.tap { |params|
params[:data][:attributes].delete([:in_preview, 'in_preview'])
}
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.file_headers).to be_present
expect(import.file_headers).to be_a Hash
expect(import.file_constants).to be_present
expect(import.file_constants).to be_a Hash
expect(import.file_row_samples).to be_present
expect(import.file_row_samples).to be_a Array
end
end
describe '#update' do
it 'permits all params under file_headers_mappings' do
api_login(user)
put :update, full_correct_attributes.tap { |params|
params[:data][:attributes][:file_headers_mappings] = { 'testing' => { 'nested' => '1234' } }
}
expect(import.reload.file_headers_mappings).to eq('testing' => { 'nested' => '1234' })
end
it 'permits all params under file_constants_mappings' do
api_login(user)
put :update, full_correct_attributes.tap { |params|
params[:data][:attributes][:file_constants_mappings] =
{ 'testing' => [{ 'id' => 'nested', 'values' => ['1234'] }] }
}
expect(import.reload.file_constants_mappings).to eq(
'testing' => [{ 'id' => 'nested', 'values' => ['1234'] }]
)
end
it 'permits assigning empty hashes to the mappings' do
api_login(user)
import.update(file_constants_mappings: { 'testing' => '1234' }, file_headers_mappings: { 'testing' => '1234' })
expect(import.reload.file_constants_mappings).to eq('testing' => '1234')
expect(import.file_headers_mappings).to eq('testing' => '1234')
put :update, full_correct_attributes.tap { |params|
params[:data][:attributes][:file_constants_mappings] = params[:data][:attributes][:file_headers_mappings] = {}
}
expect(import.reload.file_constants_mappings).to eq({})
expect(import.file_headers_mappings).to eq({})
end
end
end
|
chuckmersereau/api_practice
|
config/initializers/linkedin.rb
|
<reponame>chuckmersereau/api_practice<filename>config/initializers/linkedin.rb<gh_stars>0
LINKEDIN = LinkedIn::Client.new(ENV.fetch('LINKEDIN_KEY'), ENV.fetch('LINKEDIN_SECRET'))
|
chuckmersereau/api_practice
|
app/services/mail_chimp/exporter/batcher/interest_ids_cacher.rb
|
<filename>app/services/mail_chimp/exporter/batcher/interest_ids_cacher.rb<gh_stars>0
# This class will retrieve mail chimp interests and cache them for future calls.
class MailChimp::Exporter
class Batcher
class InterestIdsCacher
attr_reader :mail_chimp_account, :gibbon_wrapper, :list_id
def initialize(mail_chimp_account, gibbon_wrapper, list_id)
@mail_chimp_account = mail_chimp_account
@gibbon_wrapper = gibbon_wrapper
@list_id = list_id
end
def cached_interest_ids(attribute)
cache_interest_ids(attribute) if interests_from_database(attribute).blank?
interests_from_database(attribute)
end
def interests_from_database(attribute)
mail_chimp_account.get_interest_attribute_for_list(group: attribute,
attribute: :interest_ids,
list_id: list_id)
end
private
def cache_interest_ids(attribute)
grouping_id_key = fetch_interest_id_from_attribute(attribute)
interests = gibbon_list.interest_categories(grouping_id_key)
.interests.retrieve(params: { 'count': '100' })['interests']
interests = Hash[interests.map { |interest| [interest['name'], interest['id']] }]
mail_chimp_account.set_interest_attribute_for_list(group: attribute, attribute: :interest_ids, list_id: list_id, value: interests)
mail_chimp_account.save(validate: false)
mail_chimp_account.reload
end
def fetch_interest_id_from_attribute(attribute)
mail_chimp_account.get_interest_attribute_for_list(group: attribute,
attribute: :interest_category_id,
list_id: list_id)
end
def gibbon_list
gibbon_wrapper.gibbon_list_object(list_id)
end
end
end
end
|
chuckmersereau/api_practice
|
app/serializers/account_list_invite_serializer.rb
|
<gh_stars>0
class AccountListInviteSerializer < ApplicationSerializer
attributes :accepted_at,
:code,
:recipient_email,
:invite_user_as
belongs_to :accepted_by_user
belongs_to :cancelled_by_user
belongs_to :invited_by_user
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/contact_info_email.rb
|
class Contact::Filter::ContactInfoEmail < Contact::Filter::Base
def execute_query(contacts, filters)
contacts_with_emails = contacts.where.not(email_addresses: { email: nil })
.where(email_addresses: { historic: false })
.joins(people: :email_addresses)
contacts_with_emails_ids = contacts_with_emails.ids
return contacts.where(id: contacts_with_emails_ids) if filters[:contact_info_email] == 'Yes'
return contacts if contacts_with_emails_ids.empty?
contacts.where.not(id: contacts_with_emails_ids)
end
def title
_('Email')
end
def parent
_('Contact Information')
end
def type
'radio'
end
def custom_options
[{ name: _('Yes'), id: 'Yes' }, { name: _('No'), id: 'No' }]
end
end
|
chuckmersereau/api_practice
|
engines/auth/lib/auth.rb
|
require 'auth/engine'
module Auth
end
|
chuckmersereau/api_practice
|
db/seeds.rb
|
if Rails.env.development?
ApplicationSeeder.new.seed
else
raise "Seeding aborted! You are running Rails in #{ Rails.env } environment. Seeding is not supported."
end
|
chuckmersereau/api_practice
|
spec/support/rspec_api_documentation.rb
|
<filename>spec/support/rspec_api_documentation.rb
API_DOC_LEGEND = {
entities: %i(
account_lists
appeals
background_batches
contacts
constants
people
tasks
user
),
account_lists_api: %i(
analytics
chalkline_mail
designation_accounts
donations
donor_accounts
imports
invites
mailchimp_accounts
merges
notification_preferences
notifications
prayer_letters_accounts
users
),
appeals_api: %i(
contacts
),
contacts_api: %i(
addresses
analytics
duplicates
exports
filter
merges
tags
),
people_api: %i(
duplicates
email_addresses
facebook_accounts
linkedin_accounts
merges
phones
relationships
twitter_accounts
websites
),
tasks_api: %i(
analytics
comments
filter
tags
),
user_api: %i(
authenticate
google_accounts
key_accounts
options
organization_accounts
),
reports_api: %i(
donation_summaries
monthly_totals
goal_progress
monthly_giving
appointment_results
)
}.freeze
RspecApiDocumentation.configure do |config|
config.disable_dsl_status!
config.format = ENV['DOC_FORMAT'] || :slate
config.keep_source_order = false
config.request_body_formatter = :json
config.request_headers_to_include = %w(Authorization Content-Type)
config.response_headers_to_include = %w(Content-Type)
API_DOC_LEGEND.each do |groups_parent, group_names|
config.define_group groups_parent do |group_config|
group_config.api_name = groups_parent.to_s.titleize
group_config.filter = groups_parent
end
group_names.each do |group_name|
group_ref = "#{groups_parent}/#{group_name}"
api_name = group_name.to_s.titleize
filter = "#{groups_parent}_#{group_name}".to_sym
config.define_group group_ref do |group_config|
group_config.api_name = api_name
group_config.filter = filter
end
end
end
config.response_body_formatter = proc do |content_type, response_body|
if content_type == 'application/json' || content_type.include?('application/vnd.api+json')
JSON.pretty_generate(JSON.parse(response_body))
else
response_body
end
end
end
|
chuckmersereau/api_practice
|
spec/support/shared_controller_examples/bulk_destroy_examples.rb
|
RSpec.shared_examples 'bulk_destroy_examples' do
include_context 'common_variables'
describe '#destroy' do
let!(:bulk_destroy_attributes) do
{
data: [
{
data: {
type: resource_type,
id: resource.id
}
},
{
data: {
type: resource_type,
id: second_resource.id
}
}
]
}
end
let(:response_body) { JSON.parse(response.body) }
let(:response_errors) { response_body['errors'] }
it 'destroys resources for users that are signed in' do
expect(resource_not_destroyed_scope.count).to be > 2, 'please define resource, second_resource, and third_resource'
expect(resource.class.exists?(resource.id)).to be_truthy
expect(resource.class.exists?(second_resource.id)).to be_truthy
expect(resource.class.exists?(third_resource.id)).to be_truthy
api_login(user)
expect do
delete :destroy, bulk_destroy_attributes
end.to change { resource_not_destroyed_scope.count }.by(-2)
expect(resource.class.exists?(resource.id)).to be_falsey
expect(resource.class.exists?(second_resource.id)).to be_falsey
expect(resource.class.exists?(third_resource.id)).to be_truthy
end
it 'responds with the deleted resources' do
api_login(user)
expect do
delete :destroy, bulk_destroy_attributes
end.to change { resource_not_destroyed_scope.count }.by(-2)
expect(response.status).to eq(200), invalid_status_detail
expect(response_body.size).to eq(2)
expect(response_body.collect { |hash| hash.dig('data', 'id') }).to match_array([resource.id, second_resource.id])
end
context 'resources forbidden' do
it 'does not destroy the resources for users that do not own the resources' do
api_login(create(:user))
expect do
delete :destroy, bulk_destroy_attributes
end.not_to change { resource.class.count }
expect(response.status).to eq(404), invalid_status_detail
expect(response_errors.size).to eq(1)
end
it 'does not destroy resources for users that are not signed in' do
expect do
delete :destroy
end.not_to change { resource.class.count }
expect(response.status).to eq(401), invalid_status_detail
end
end
context 'resources not found' do
it 'responds correctly if all resources are not found' do
api_login(user)
expect do
delete :destroy, data: [{ data: { type: resource_type, id: SecureRandom.uuid } }]
end.not_to change { resource.class.count }
expect(response.status).to eq(404), invalid_status_detail
expect(response_body['errors']).to be_present
expect(response_body['data']).to be_blank
end
it 'responds correctly if only some resources are not found' do
api_login(user)
bulk_destroy_attributes[:data] << { data: { type: resource_type, id: SecureRandom.uuid } }
expect do
delete :destroy, data: bulk_destroy_attributes[:data]
end.to change { resource_not_destroyed_scope.count }.by(-2)
expect(response.status).to eq(200), invalid_status_detail
expect(response_body.size).to eq(2)
end
end
context 'request mixes resources that do belong to and do not belong to the current user' do
let!(:bulk_destroy_attributes) do
{
data: [
{ data: { id: resource.id, type: resource_type } },
{ data: { id: create(factory_type).id, type: resource_type } }
]
}
end
it 'still destroys some resources' do
api_login(user)
expect do
delete :destroy, bulk_destroy_attributes
end.to change { resource.class.count }.by(-1)
expect(response.status).to eq(200), invalid_status_detail
end
end
end
end
|
chuckmersereau/api_practice
|
spec/support/batch_request_helpers.rb
|
<gh_stars>0
def create_empty_batch_request_with_params(params)
json_body = {
requests: []
}.merge(params)
request_body = JSON.dump(json_body)
env = Rack::MockRequest.env_for('/api/v2/batch', method: 'POST', input: request_body)
BatchRequestHandler::BatchRequest.new(env)
end
|
chuckmersereau/api_practice
|
app/services/tnt_import/group_tags_loader.rb
|
<reponame>chuckmersereau/api_practice
class TntImport::GroupTagsLoader
class << self
def tags_by_tnt_contact_id(xml)
return {} unless xml&.tables&.dig('Group').present?
groups = xml.tables['Group'].map do |row|
{
id: row['id'],
tags: extract_tags_from_group_row(row, xml.version)
}
end
groups_by_id = Hash[
groups.map { |group| [group[:id], group] }.to_a # force array from Enumerable::Lazy
]
tags_by_contact_id = {}
xml.tables['GroupContact'].each do |row|
group = groups_by_id[row['GroupID']]
tags_by_contact_id[row['ContactID']] ||= []
tags_by_contact_id[row['ContactID']] += group[:tags]
tags_by_contact_id[row['ContactID']].uniq!
end
tags_by_contact_id
end
private
def group_to_tag(group_name)
return unless group_name
group_name
.gsub(/\s|,/, '-') # Substitute whitespace and commas with dashes
.gsub(/-{2,}/, '-') # Substitute multiple adjacent dashes with a single dash
end
def extract_tags_from_group_row(row, version)
return extract_tags_from_group_row_version_3_2(row) if version >= 3.2
extract_tags_from_group_row_version_3_1(row)
end
# TNT Version 3.2:
# The Category and Description are replaced by PathName.
# PathName looks like "a\hierarchy\of\tags\separated\by\slashes".
# We want tag list like:
# a
# a\hierarchy
# a\hierarchy\of
# a\hierarchy\of\tags
# a\hierarchy\of\tags\separated
# a\hierarchy\of\tags\separated\by
# a\hierarchy\of\tags\separated\by\slashes
def extract_tags_from_group_row_version_3_2(row)
groups = row['PathName'].split('\\')
(1..groups.size).map do |i|
group_to_tag(groups.first(i).join('\\'))
end
end
# TNT Version 3.1:
# If a group has a Category, then the Description will look like "category\description".
# If not, then the Description will just look like "description".
# We want a tag list like: "category description"
def extract_tags_from_group_row_version_3_1(row)
description_tag = row['Description']
description_tag = description_tag.sub("#{row['Category']}\\", '') if row['Category'].present?
[description_tag, row['Category']].select(&:present?).map do |group|
group_to_tag(group)
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160513173621_add_uses_key_auth_to_organization.rb
|
class AddUsesKeyAuthToOrganization < ActiveRecord::Migration
def change
add_column :organizations, :uses_key_auth, :boolean, default: false
end
end
|
chuckmersereau/api_practice
|
db/migrate/20150605194836_fix_old_dates.rb
|
<reponame>chuckmersereau/api_practice<filename>db/migrate/20150605194836_fix_old_dates.rb
class FixOldDates < ActiveRecord::Migration
def change
Contact.where(next_ask: Date.parse('1899-12-30')).update_all(next_ask: nil)
Contact.where(pledge_start_date: Date.parse('1899-12-30')).update_all(pledge_start_date: nil)
Contact.where(last_activity: Date.parse('1899-12-30')).update_all(last_activity: nil)
Contact.where(last_appointment: Date.parse('1899-12-30')).update_all(last_appointment: nil)
Contact.where(last_letter: Date.parse('1899-12-30')).update_all(last_letter: nil)
Contact.where(last_phone_call: Date.parse('1899-12-30')).update_all(last_phone_call: nil)
Contact.where(last_pre_call: Date.parse('1899-12-30')).update_all(last_pre_call: nil)
Contact.where(last_thank: Date.parse('1899-12-30')).update_all(last_thank: nil)
end
end
|
chuckmersereau/api_practice
|
app/services/account_list/restorer.rb
|
<gh_stars>0
# This class is designed to copy an account_list from an instance
# running against a backup DB to production using Kirby
class AccountList::Restorer
attr_reader :account_list, :store
TABLES_TO_IMPORT = %w(
account_lists
account_list_coaches
account_list_entries
account_list_invites
account_list_users
master_companies
companies
company_partnerships
master_people
master_person_sources
donor_accounts
master_person_donor_accounts
people
company_positions
person_facebook_accounts
person_google_accounts
person_key_accounts
person_linkedin_accounts
person_twitter_accounts
person_websites
phone_numbers
email_addresses
pictures
donor_account_people
family_relationships
contacts
contact_referrals
contact_people
contact_donor_accounts
contact_notes_logs
master_addresses
addresses
partner_status_logs
activities
activity_comments
activity_contacts
designation_profiles
designation_accounts
balances
designation_profile_accounts
donations
appeals
appeal_contacts
appeal_excluded_appeal_contacts
pledges
pledge_donations
duplicate_record_pairs
imports
mail_chimp_accounts
mail_chimp_members
mail_chimp_appeal_lists
pls_accounts
prayer_letters_accounts
notification_preferences
notifications
tags
taggings
google_contacts
google_integrations
google_emails
google_events
google_email_activities
google_plus_accounts
).freeze
def self.restore(id)
store = AccountList::Restorer.new(id).store
TABLES_TO_IMPORT.each do |table_name|
next unless store[table_name]&.present?
RowTransferRequest.transfer(table_name, store[table_name])
end
end
def initialize(account_list_id)
@account_list = AccountList.find(account_list_id)
@store = {}
fetch_records
end
private
def fetch_records
fetch_account_list_records
fetch_company_records
fetch_donor_account_records
fetch_person_records
fetch_contact_records
fetch_activity_records
fetch_designation_profile_records
fetch_appeal_records
fetch_duplicate_record_pair_records
fetch_import_records
fetch_mailchimp_account_records
fetch_pls_account_records
fetch_prayer_letters_account_records
fetch_notification_records
fetch_tag_records
fetch_google_records
end
def add_to_store(klass, *ids)
klass = klass.is_a?(Class) ? klass.table_name : klass
ids = ids.flatten
@store[klass] ||= []
@store[klass] = (@store[klass] + ids).uniq.compact
end
def fetch_account_list_records
add_to_store(
AccountList,
account_list.id
)
add_to_store(
AccountListCoach,
account_list.account_list_coaches.pluck(:id)
)
add_to_store(
AccountListEntry,
account_list.account_list_entries.pluck(:id)
)
add_to_store(
AccountListInvite,
account_list.account_list_invites.pluck(:id)
)
add_to_store(
AccountListUser,
account_list.account_list_users.pluck(:id)
)
end
def fetch_company_records
add_to_store(
MasterCompany,
account_list.people.joins(donor_accounts: [:master_company]).pluck('master_companies.id'),
account_list.contacts.joins(donor_accounts: [:master_company]).pluck('master_companies.id'),
account_list.companies.joins(:master_company).pluck('master_companies.id')
)
add_to_store(
Company,
account_list.companies.pluck(:id),
account_list.people.joins(:companies).pluck('companies.id')
)
add_to_store(
CompanyPartnership,
account_list.company_partnerships.pluck(:id)
)
end
def fetch_donor_account_records
add_to_store(
MasterPerson,
account_list.people.joins(:master_person).pluck('master_people.id')
)
add_to_store(
MasterPersonSource,
account_list.people
.joins(master_person: [:master_person_sources])
.pluck('master_person_sources.id')
)
donor_account_ids = (
account_list.people.joins(:donor_accounts).pluck('donor_accounts.id') +
account_list.contacts.joins(:donor_accounts).pluck('donor_accounts.id') +
account_list.contacts.joins(addresses: [:source_donor_account]).pluck('donor_accounts.id')
).uniq
add_to_store(
DonorAccount,
donor_account_ids
)
add_to_store(
MasterPersonDonorAccount,
DonorAccount.where(id: donor_account_ids)
.joins(:master_person_donor_accounts)
.pluck('master_person_donor_accounts.id')
)
end
def fetch_person_records
add_to_store(
Person,
account_list.people.pluck(:id)
)
add_to_store(
CompanyPosition,
CompanyPosition.where(person: account_list.people).pluck(:id)
)
add_to_store(
Person::FacebookAccount,
account_list.people.joins(:facebook_accounts).pluck('person_facebook_accounts.id')
)
add_to_store(
Person::GoogleAccount,
account_list.people.joins(:google_accounts).pluck('person_google_accounts.id')
)
add_to_store(
Person::KeyAccount,
account_list.people.joins(:key_accounts).pluck('person_key_accounts.id')
)
add_to_store(
Person::LinkedinAccount,
account_list.people.joins(:linkedin_accounts).pluck('person_linkedin_accounts.id')
)
add_to_store(
Person::TwitterAccount,
account_list.people.joins(:twitter_accounts).pluck('person_twitter_accounts.id')
)
add_to_store(
Person::Website,
account_list.people.joins(:websites).pluck('person_websites.id')
)
add_to_store(
PhoneNumber,
account_list.people.joins(:phone_numbers).pluck('phone_numbers.id')
)
add_to_store(
EmailAddress,
account_list.people.joins(:email_addresses).pluck('email_addresses.id')
)
add_to_store(
Picture,
account_list.people.joins(:pictures).pluck('pictures.id')
)
add_to_store(
DonorAccountPerson,
account_list.people.joins(:donor_account_people).pluck('donor_account_people.id')
)
add_to_store(
FamilyRelationship,
account_list.people.joins(:family_relationships).pluck('family_relationships.id')
)
end
def fetch_contact_records
add_to_store(
Contact,
account_list.contacts.pluck(:id)
)
add_to_store(
ContactReferral,
account_list.contacts.joins(:contact_referrals_to_me).pluck('contact_referrals.id'),
account_list.contacts.joins(:contact_referrals_by_me).pluck('contact_referrals.id')
)
add_to_store(
ContactPerson,
account_list.contacts.joins(:contact_people).pluck('contact_people.id')
)
add_to_store(
ContactDonorAccount,
account_list.contacts.joins(:contact_donor_accounts).pluck('contact_donor_accounts.id')
)
add_to_store(
ContactNotesLog,
account_list.contacts.joins(:contact_notes_logs).pluck('contact_notes_logs.id')
)
add_to_store(
MasterAddress,
account_list.contacts.joins(addresses: [:master_address]).pluck('master_addresses.id')
)
add_to_store(
Address,
account_list.contacts.joins(:addresses).pluck('addresses.id')
)
add_to_store(
PartnerStatusLog,
account_list.contacts.joins(:partner_status_logs).pluck('partner_status_logs.id')
)
end
def fetch_activity_records
add_to_store(
Activity,
account_list.activities.pluck(:id)
)
add_to_store(
ActivityComment,
account_list.activities.joins(:comments).pluck('activity_comments.id')
)
add_to_store(
ActivityContact,
account_list.activities.joins(:activity_contacts).pluck('activity_contacts.id')
)
end
def fetch_designation_profile_records
add_to_store(
DesignationProfile,
account_list.designation_profiles.pluck(:id)
)
add_to_store(
DesignationAccount,
account_list.designation_profiles.joins(:designation_accounts).pluck('designation_accounts.id')
)
add_to_store(
Balance,
account_list.designation_profiles.joins(designation_accounts: [:balances]).pluck('balances.id'),
account_list.designation_profiles.joins(:balances).pluck('balances.id')
)
add_to_store(
DesignationProfileAccount,
account_list.designation_profiles.joins(:designation_profile_accounts).pluck('designation_profile_accounts.id')
)
add_to_store(
Donation,
account_list.designation_profiles.joins(designation_accounts: [:donations]).pluck('donations.id')
)
end
def fetch_appeal_records
add_to_store(
Appeal,
account_list.appeals.pluck(:id)
)
add_to_store(
AppealContact,
account_list.appeals.joins(:appeal_contacts).pluck('appeal_contacts.id')
)
add_to_store(
Appeal::ExcludedAppealContact,
account_list.appeals.joins(:excluded_appeal_contacts).pluck('appeal_excluded_appeal_contacts.id')
)
add_to_store(
Pledge,
account_list.pledges.pluck(:id)
)
add_to_store(
PledgeDonation,
account_list.pledges.joins(:pledge_donations).pluck('pledge_donations.id')
)
end
def fetch_duplicate_record_pair_records
add_to_store(
DuplicateRecordPair,
account_list.duplicate_record_pairs.pluck(:id)
)
end
def fetch_import_records
add_to_store(
Import,
account_list.imports.pluck(:id)
)
end
def fetch_mailchimp_account_records
add_to_store(
MailChimpAccount,
account_list.mail_chimp_account&.id
)
add_to_store(
MailChimpMember,
account_list.mail_chimp_account&.mail_chimp_members&.pluck(:id)
)
add_to_store(
MailChimpAppealList,
MailChimpAppealList.where(mail_chimp_account: account_list.mail_chimp_account).pluck(:id)
)
end
def fetch_pls_account_records
add_to_store(
PlsAccount,
account_list.pls_account&.id
)
end
def fetch_prayer_letters_account_records
add_to_store(
PrayerLettersAccount,
account_list.prayer_letters_account&.id
)
end
def fetch_notification_records
add_to_store(
NotificationPreference,
account_list.notification_preferences.pluck(:id)
)
add_to_store(
Notification,
account_list.contacts.joins(:notifications).pluck('notifications.id'),
account_list.activities.joins(:notification).pluck('notifications.id')
)
end
def fetch_tag_records
add_to_store(
ActsAsTaggableOn::Tag,
account_list.contacts.joins(taggings: [:tag]).pluck('tags.id'),
account_list.activities.joins(taggings: [:tag]).pluck('tags.id')
)
add_to_store(
ActsAsTaggableOn::Tagging,
account_list.contacts.joins(:taggings).pluck('taggings.id'),
account_list.activities.joins(:taggings).pluck('taggings.id')
)
end
def fetch_google_records
google_contact_ids =
account_list.people.joins(:google_contacts).pluck('google_contacts.id')
google_email_ids =
account_list.activities.joins(:google_emails).pluck('google_emails.id')
add_to_store(
Person::GoogleAccount,
account_list.google_integrations.pluck(:google_account_id),
GoogleContact.where(id: google_contact_ids).pluck(:google_account_id),
GoogleEmail.where(id: google_email_ids).pluck(:google_account_id)
)
add_to_store(
Picture,
GoogleContact.where(id: google_contact_ids).pluck(:picture_id)
)
add_to_store(
GoogleContact,
google_contact_ids
)
add_to_store(
GoogleIntegration,
account_list.google_integrations.pluck(:id),
account_list.activities.joins(google_events: [:google_integration]).pluck('google_integrations.id')
)
add_to_store(
GoogleEmail,
google_email_ids
)
add_to_store(
GoogleEvent,
account_list.activities.joins(:google_events).pluck('google_events.id')
)
add_to_store(
GoogleEmailActivity,
account_list.activities.joins(:google_email_activities).pluck('google_email_activities.id')
)
add_to_store(
GooglePlusAccount,
account_list.people.joins(email_addresses: [:google_plus_account]).pluck('google_plus_accounts.id')
)
end
end
|
chuckmersereau/api_practice
|
spec/concerns/address_methods_spec.rb
|
<filename>spec/concerns/address_methods_spec.rb
require 'rails_helper'
describe AddressMethods do
let(:contact) { create(:contact) }
let(:donor_account) { create(:donor_account) }
context '#merge_addresses' do
let(:master_address_id_1) { SecureRandom.uuid }
let(:master_address_id_2) { SecureRandom.uuid }
def expect_merge_addresses_works(addressable)
address1 = create(:address, street: '1 Way', master_address_id: master_address_id_1)
address2 = create(:address, street: '1 Way', master_address_id: master_address_id_1)
address3 = create(:address, street: '2 Way', master_address_id: master_address_id_2)
addressable.addresses << address1
addressable.addresses << address2
addressable.addresses << address3
expect do
addressable.merge_addresses
end.to change(Address, :count).from(3).to(2)
expect(Address.find_by(id: address1.id)).to be_nil
expect(Address.find_by(id: address2.id)).to eq(address2)
expect(Address.find_by(id: address3.id)).to eq(address3)
end
it 'works for contact' do
expect_merge_addresses_works(contact)
end
it 'works for donor_account' do
expect_merge_addresses_works(donor_account)
end
end
context '#blank_or_duplicate_address?' do
it 'returns false if an id specified' do
expect(contact.blank_or_duplicate_address?('id' => '1')).to be false
end
it 'returns true if address fields blank' do
expect(contact.blank_or_duplicate_address?({})).to be true
end
it 'returns false if any address field is specified' do
['street', 'city', 'state', 'country', 'postal_code', :street, :city, :state, :country, :postal_code].each do |field|
expect(contact.blank_or_duplicate_address?(field => 'a')).to be false
end
end
it 'returns true for a duplicate address by by matching attributes, false if not matching' do
a = create(:address)
contact.addresses << a
expect(contact.blank_or_duplicate_address?(street: a.street, city: a.city, country: a.country,
postal_code: a.postal_code)).to be true
expect(contact.blank_or_duplicate_address?(street: 'other street')).to be false
end
it 'returns true for a duplicate address by by matching attributes if country set alternate name' do
a = create(:address, country: 'USA')
contact.addresses << a
expect(contact.blank_or_duplicate_address?(street: a.street, city: a.city, country: 'USA',
postal_code: a.postal_code)).to be true
end
end
context '#primary_address' do
it 'gives a consistent non-deleted, non-historic primary address' do
contact = create(:contact)
addr1 = create(:address, street: '1', primary_mailing_address: true, deleted: true)
addr2 = create(:address, street: '2', primary_mailing_address: true, historic: true)
addr3 = create(:address, street: '3', primary_mailing_address: false)
addr4 = create(:address, street: '4', primary_mailing_address: true, city: 'b')
addr5 = create(:address, street: '5', primary_mailing_address: true, city: 'a')
contact.addresses << [addr1, addr2, addr3, addr4, addr5]
# Check that we get the same address even if db record order changes
Address.connection.execute('CLUSTER addresses USING index_addresses_on_lower_city')
expect(contact.primary_address).to eq addr4
Address.connection.execute('CLUSTER addresses USING addresses_pkey')
expect(contact.primary_address).to eq addr4
end
end
context '#addresses' do
let(:contact) { create(:contact) }
let!(:addr1) do
create(:address,
street: '1',
primary_mailing_address: false,
city: 'b',
addressable: contact)
end
let!(:addr2) do
create(:address,
street: '2',
primary_mailing_address: false,
city: 'a',
addressable: contact,
created_at: 1.week.from_now)
end
it 'gives a consistent first if none are primary and record order changes' do
# Check that we get the same address even if db record order changes
Address.connection.execute('CLUSTER addresses USING index_addresses_on_lower_city')
expect(contact.addresses.reorder(:created_at).first).to eq addr1
Address.connection.execute('CLUSTER addresses USING addresses_pkey')
expect(contact.addresses.reorder(:created_at).first).to eq addr1
end
end
context '#copy_address' do
it 'moves over the main address attributes and sets source info' do
donor_account = create(:donor_account)
donor_address = create(:address, street: '1 Rd')
donor_account.addresses << donor_address
contact = create(:contact)
contact.copy_address(address: donor_address, source: 'DataServer', source_donor_account_id: 1)
expect(contact.addresses.size).to eq 1
contact_address = contact.addresses.first
expect(contact_address).to_not eq donor_address
expect(contact.addresses.first.street).to eq '1 Rd'
end
end
end
|
chuckmersereau/api_practice
|
spec/exhibits/donation_exhibit_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe DonationExhibit do
subject { DonationExhibit.new(donation, context) }
let(:donation) { build(:donation, tendered_amount: '1.23', currency: 'USD') }
let(:context) { double }
it 'returns a formatted amount' do
allow(context).to receive(:number_to_current_currency).and_return('$1.23')
expect(subject.tendered_amount).to eq('$1.23')
end
end
|
chuckmersereau/api_practice
|
app/workers/mail_chimp/members_import_worker.rb
|
class MailChimp::MembersImportWorker
include Sidekiq::Worker
sidekiq_options queue: :api_mail_chimp_sync_worker, unique: :until_executed
def perform(mail_chimp_account_id, _member_emails)
mail_chimp_account = MailChimpAccount.find_by(id: mail_chimp_account_id)
return unless mail_chimp_account
# MailChimp::Importer.new(mail_chimp_account)
# .import_members_by_email(member_emails)
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/imports_controller_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe Api::V2::AccountLists::ImportsController, type: :controller do
let(:factory_type) { :import }
let!(:user) { create(:user_with_account) }
let!(:fb_account) { create(:facebook_account, person: user) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:import) { create(:import, account_list: account_list, user: user, source_account_id: fb_account.id) }
let(:id) { import.id }
before do
stub_request(:get, "https://graph.facebook.com/#{fb_account.remote_id}/friends?access_token=#{fb_account.token}")
.to_return(body: '{"data": [{"name": "<NAME>","id": "120581"}]}')
stub_request(:get, "https://graph.facebook.com/120581?access_token=#{fb_account.token}")
.to_return(body: '{"id": "120581", "first_name": "John", "last_name": "Doe", '\
'"relationship_status": "Married", "significant_other":{"id":"120582"}}')
stub_request(:get, "https://graph.facebook.com/120582?access_token=#{fb_account.token}")
.to_return(body: '{"id": "120582", "first_name": "Jane", "last_name": "Doe"}')
end
let(:resource) { import }
let(:parent_param) { { account_list_id: account_list_id } }
let(:correct_attributes) do
attributes_for(:import, account_list_id: account_list.id, user_id: user.id, source_account_id: fb_account)
end
let(:incorrect_attributes) { { source: nil } }
let(:unpermitted_attributes) { nil }
include_examples 'show_examples'
end
|
chuckmersereau/api_practice
|
app/models/account_list.rb
|
<filename>app/models/account_list.rb
# This class provides the flexibility needed for one person to have
# multiple designation accounts in multiple countries. In that scenario
# it didn't make sense to associate a contact with a designation
# account. It also doesn't work to associate the contact with a user
# account because (for example) a husband and wife will both want to see
# the same contacts. So for most users, an AccountList will contain only
# one account, and the notion of an AccountList will be hidden from the
# user. This concept should only be exposed to users who have more than
# one designation account.
require 'async'
require 'mail'
class AccountList < ApplicationRecord
include Async
include Sidekiq::Worker
# Expire the uniqueness for AccountList import after 24 hours because the
# uniqueness locks were staying around incorrectly and causing some people's
# donor import to not go through.
sidekiq_options queue: :api_account_list, retry: false, unique: :until_executed
validates :name, presence: true
validate :active_mpd_start_at_is_before_active_mpd_finish_at
store :settings, accessors: [:monthly_goal, :tester, :owner, :home_country, :ministry_country,
:currency, :salary_currency, :log_debug_info]
belongs_to :creator, class_name: 'User', foreign_key: 'creator_id'
has_many :account_list_entries, dependent: :destroy
has_many :account_list_invites, dependent: :destroy
has_many :account_list_users, dependent: :destroy
has_many :account_list_coaches, dependent: :destroy
has_many :active_contacts, -> { where(Contact.active_conditions) }, class_name: 'Contact'
has_many :active_people, through: :active_contacts, source: :people, class_name: 'Person'
has_many :activities, dependent: :destroy
has_many :activity_tags, through: :activities, source: :base_tags
has_many :addresses, through: :contacts
has_many :appeals
belongs_to :primary_appeal, class_name: 'Appeal'
has_many :balances, through: :designation_accounts, source: :balances
has_many :companies, through: :company_partnerships
has_many :company_partnerships, dependent: :destroy
has_many :contact_tags, through: :contacts, source: :base_tags
has_many :contacts, dependent: :destroy
has_many :partner_status_logs, through: :contacts
has_many :designation_accounts, through: :account_list_entries
has_many :designation_organizations, -> { distinct }, through: :designation_accounts,
source: :organization
has_many :designation_profiles
has_many :donor_accounts, through: :contacts
has_many :google_integrations, dependent: :destroy
has_many :help_requests
has_many :imports, dependent: :destroy
has_many :master_people, through: :people
has_many :messages
has_many :notification_preferences, dependent: :destroy, autosave: true
has_many :notifications, through: :contacts
has_many :organization_accounts, through: :users
has_many :organizations, -> { distinct }, through: :organization_accounts
belongs_to :salary_organization, class_name: 'Organization'
has_many :people, through: :contacts
has_many :pledges, dependent: :destroy
has_many :tasks
has_many :coaches, through: :account_list_coaches
has_many :users, through: :account_list_users
has_many :duplicate_record_pairs, dependent: :delete_all
has_one :mail_chimp_account, dependent: :destroy
has_one :prayer_letters_account, dependent: :destroy, autosave: true
has_one :pls_account, dependent: :destroy, autosave: true
accepts_nested_attributes_for :contacts, reject_if: :all_blank, allow_destroy: true
scope :with_linked_org_accounts, lambda {
joins(:organization_accounts).where('locked_at IS NULL').order('last_download ASC')
}
scope :has_users, -> (users) { joins(:account_list_users).where(account_list_users: { user: users }) }
scope :readable_by, -> (user) { AccountList::ReadableFinder.new(user).relation }
before_validation :set_salary_currency
PERMITTED_ATTRIBUTES = [
:created_at,
:currency,
:home_country,
:monthly_goal,
:name,
:overwrite,
:salary_organization,
:tester,
:primary_appeal_id,
:active_mpd_start_at,
:active_mpd_finish_at,
:active_mpd_monthly_goal,
:updated_at,
:updated_in_db_at
].freeze
audited
alias unsafe_destroy destroy
def destroy
raise "It's not safe to call #destroy on an AccountList record. Because the large amount of dependents " \
'and callbacks causes it to take too long and to consume too much memory. See AccountList::Destroyer class instead.'
end
alias destroy! destroy
def salary_organization=(value)
return super(value) if value.is_a? Organization
value = Organization.where(id: value).limit(1).ids.first unless value.is_a?(Integer)
self.salary_organization_id = value
end
def salary_organization_id=(value)
super(value.is_a?(Organization) ? value.id : value)
end
def salary_organization_id
attributes['salary_organization_id'] || designation_organizations.first&.id || organizations&.first&.id
end
def salary_currency
return @salary_currency unless @salary_currency.blank?
@salary_currency ||= settings[:salary_currency] if settings[:salary_currency].present?
@salary_currency ||= Organization.find(salary_organization_id).default_currency_code if salary_organization_id
@salary_currency = 'USD' if @salary_currency.blank?
@salary_currency
end
def monthly_goal=(val)
settings[:monthly_goal] = val.to_s.gsub(/[^\d\.]/, '').to_i if val
end
def monthly_goal
settings[:monthly_goal].present? && settings[:monthly_goal].to_i.positive? ? settings[:monthly_goal].to_i : nil
end
def salary_currency_or_default
salary_currency || default_currency
end
def default_currency
return @default_currency unless @default_currency.blank?
@default_currency ||= settings[:currency] if settings[:currency].present?
@default_currency ||= designation_profiles.try(:first).try(:organization).try(:default_currency_code)
@default_currency = 'USD' if @default_currency.blank?
@default_currency
end
def multiple_designations
designation_accounts.length > 1
end
def cities
@cities ||= contacts.active.joins(:addresses).order('addresses.city').pluck('DISTINCT addresses.city')
end
def states
@states ||= contacts.active.joins(:addresses).order('addresses.state').pluck('DISTINCT addresses.state')
end
def regions
@regions ||= contacts.active.joins(:addresses).order('addresses.region').pluck('DISTINCT addresses.region')
end
def metro_areas
@metro_areas ||= contacts.active.joins(:addresses).order('addresses.metro_area').pluck('DISTINCT addresses.metro_area')
end
def countries
@countries ||= contacts.active.joins(:addresses).order('addresses.country').pluck('DISTINCT addresses.country')
end
def churches
@churches ||= contacts.order(:church_name).pluck('DISTINCT church_name')
end
def timezones
@timezones ||= contacts.order(:timezone).pluck('DISTINCT timezone')
end
def currencies
@currencies ||=
(contacts.order(:pledge_currency).pluck('DISTINCT pledge_currency') +
organizations.pluck(:default_currency_code) +
[default_currency]).compact.uniq
end
def contact_locales
@locales ||= contacts.pluck('DISTINCT locale')
end
def multi_currency?
currencies.count > 1
end
def valid_mail_chimp_account
mail_chimp_account.try(:active?) && mail_chimp_account.primary_list.present?
end
def valid_prayer_letters_account
prayer_letters_account.try(:valid_token?)
end
def valid_pls_account
pls_account.try(:valid_token?)
end
def top_partners
contacts.order('total_donations desc').where('total_donations > 0').limit(10)
end
def donations
scope_donations_by_designations(
Donation.where(donor_account_id: donor_account_ids)
)
end
def scope_donations_by_designations(donations)
donations.where(designation_account_id: designation_account_ids)
end
def designation_profile(user)
designation_profiles.where(user_id: user.id).last
end
def total_pledges
@total_pledges ||= AccountList::PledgesTotal.new(self, contacts.financial_partners).total
end
def received_pledges
@received_pledges ||= AccountList::PledgesTotal.new(self, contacts.financial_partners.where(pledge_received: true)).total
end
def people_with_birthdays(start_date, end_date)
start_month = start_date.month
end_month = end_date.month
people_with_birthdays = if start_month == end_month
people.where('people.birthday_month = ?', start_month)
.where('people.birthday_day BETWEEN ? AND ?', start_date.day, end_date.day)
else
people.where("(people.birthday_month = ? AND people.birthday_day >= ?)
OR (people.birthday_month = ? AND people.birthday_day <= ?)",
start_month, start_date.day, end_month, end_date.day)
end
people_with_birthdays.alive
.order('people.birthday_month, people.birthday_day')
.merge(contacts.active)
end
def contacts_with_anniversaries(start_date, end_date)
start_month = start_date.month
end_month = end_date.month
contacts_with_anniversaries = active_contacts.includes(:people)
contacts_with_anniversaries = if start_month == end_month
contacts_with_anniversaries
.where('people.anniversary_month = ?', start_month)
.where('people.anniversary_day BETWEEN ? AND ?', start_date.day, end_date.day)
else
contacts_with_anniversaries
.where("(people.anniversary_month = ? AND people.anniversary_day >= ?)
OR (people.anniversary_month = ? AND people.anniversary_day <= ?)",
start_month, start_date.day, end_month, end_date.day)
end
contacts_with_anniversaries
.order('people.anniversary_month, people.anniversary_day')
.reject { |contact| contact.people.where(deceased: true).any? }
end
def top_50_percent
return @top_50_percent if @top_50_percent
financial_partners_count = contacts.where('pledge_amount > 0').count
@top_50_percent = contacts.where('pledge_amount > 0')
.order('(pledge_amount::numeric / (pledge_frequency::numeric)) desc')
.limit(financial_partners_count / 2)
end
def bottom_50_percent
return @button if @bottom_50_percent
@bottom_50_percent = contacts.where('pledge_amount > 0')
.order('(pledge_amount::numeric / (pledge_frequency::numeric))')
.limit(contacts.where('pledge_amount > 0').count / 2)
end
def no_activity_since(date, contacts_scope = nil, activity_type = nil)
no_activity_since = []
contacts_scope ||= contacts
contacts_scope.includes(people: [:primary_phone_number, :primary_email_address]).each do |contact|
activities = contact.tasks.where('completed_at > ?', date)
activities = activities.where('activity_type = ?', activity_type) if activity_type.present?
no_activity_since << contact if activities.empty?
end
no_activity_since
end
def async_merge_contacts(since_time)
QueueContactDupMergeBatchWorker.perform_async(id, since_time.to_i)
end
def merge(other)
AccountList::Merge.new(self, other).merge
end
def all_contacts
@all_contacts ||= contacts.order('contacts.name').select(['contacts.id', 'contacts.name'])
end
def cache_key
super + total_pledges.to_s
end
def update_geocodes
return if Redis.current.get("geocodes:#{id}")
Redis.current.set("geocodes:#{id}", true)
contacts.where(timezone: nil).find_each(&:set_timezone)
end
def async_send_chalkline_list
ChalklineMailer.delay.mailing_list(self)
end
def users_combined_name
user1, user2 = users.order('created_at').limit(2).to_a[0..1]
return name unless user1
return "#{user1.first_name} #{user1.last_name}".strip unless user2
if user2.last_name == user1.last_name
"#{user1.first_name} and #{user2.first_name} #{user1.last_name}".strip
else
"#{user1.first_name} #{user1.last_name} and #{user2.first_name} #{user2.last_name}".strip
end
end
def user_emails_with_names
emails_with_nils = users.map do |user|
next unless user.email
address = Mail::Address.new user.email.email
address.display_name = (user.first_name.to_s + ' ' + user.last_name.to_s).strip
address.format
end
emails_with_nils.compact
end
def queue_sync_with_google_contacts
return if google_integrations.where(contacts_integration: true).empty?
return if organization_accounts.any?(&:downloading)
return if imports.any?(&:importing) || mail_chimp_account.try(&:importing)
google_integrations.where(contacts_integration: true).find_each do |google_integration|
google_integration.queue_sync_data('contacts')
end
end
def organization_accounts
users.map(&:organization_accounts).flatten.uniq
end
def in_hand_percent
return unless monthly_goal
(received_pledges * 100 / monthly_goal).round(1)
end
def pledged_percent
return unless monthly_goal
(total_pledges * 100 / monthly_goal).round(1)
end
# trigger any notifications for this account list
def send_account_notifications
AccountList::NotificationsSender.new(self).send_notifications
end
def import_data
import_donations
if fix_dup_balances
# Import donations again if we fixed any dup balances
import_donations
end
send_account_notifications
queue_sync_with_google_contacts
end
private
def set_salary_currency
return unless salary_organization_id_changed?
# we also need to set the instance var so self.salary_currency doesn't return the cached value
@salary_currency = self.salary_currency = salary_organization&.default_currency_code
end
def import_donations
organization_accounts.reject(&:disable_downloads).each(&:import_all_data)
end
def fix_dup_balances
DesignationAccount::DupByBalanceFix.deactivate_dups(designation_accounts)
end
def tester_or_owner_setting_changed?
changes.keys.include?('settings') &&
(changes['settings'][0]['tester'] != changes['settings'][1]['tester'] ||
changes['settings'][0]['owner'] != changes['settings'][1]['owner'])
end
def active_mpd_start_at_is_before_active_mpd_finish_at
return unless active_mpd_start_at && active_mpd_finish_at
return unless active_mpd_start_at >= active_mpd_finish_at
errors[:active_mpd_start_at] << 'is after or equal to active mpd finish at date'
end
end
|
chuckmersereau/api_practice
|
app/serializers/mail_chimp_account_serializer.rb
|
class MailChimpAccountSerializer < ApplicationSerializer
type :mail_chimp_accounts
attributes :active,
:api_key,
:auto_log_campaigns,
:lists_available_for_newsletters,
:lists_link,
:lists_present,
:primary_list_id,
:primary_list_name,
:valid,
:validate_key,
:validation_error
def valid
object.account_list.valid_mail_chimp_account
end
def lists_present
object.lists.present?
end
def lists_available_for_newsletters
object.lists_available_for_newsletters_formatted
end
end
|
chuckmersereau/api_practice
|
app/services/mail_chimp/exporter/merge_field_adder.rb
|
# This class handles the addition of merge fields to Mail Chimp. Merge fields are basically custom fields
# on the MailChimp side that we use to store statuses and tags that a contact has.
class MailChimp::Exporter
class MergeFieldAdder
MAILCHIMP_MAX_ALLOWED_MERGE_FIELDS = 20
attr_reader :mail_chimp_account, :gibbon_wrapper, :list_id
def initialize(mail_chimp_account, gibbon_wrapper, list_id)
@mail_chimp_account = mail_chimp_account
@gibbon_wrapper = gibbon_wrapper
@list_id = list_id
end
def add_merge_field(field_name)
@field_name = field_name
return if should_not_create_merge_field?
create_merge_field
rescue Gibbon::MailChimpError => error
raise unless error.detail =~ /Merge Field .* already exists/
end
private
def should_not_create_merge_field?
merge_fields.find { |merge_field| merge_field['tag'] == @field_name } ||
merge_fields.size == MAILCHIMP_MAX_ALLOWED_MERGE_FIELDS
end
def create_merge_field
gibbon_list.merge_fields.create(
body: {
tag: @field_name, name: _(cleaned_field_name), type: 'text'
}
)
end
def cleaned_field_name
@field_name.downcase.tr('-', '').capitalize
end
def merge_fields
@merge_fields ||= gibbon_list.merge_fields.retrieve['merge_fields']
end
def gibbon_list
gibbon_wrapper.gibbon_list_object(list_id)
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/pictures.rb
|
<reponame>chuckmersereau/api_practice
FactoryBot.define do
factory :picture do
image nil
association :picture_of
end
end
|
chuckmersereau/api_practice
|
spec/factories/currency_rates.rb
|
<reponame>chuckmersereau/api_practice
FactoryBot.define do
factory :currency_rate do
exchanged_on '2016-11-30 15:26:43 -0500'
code 'EUR'
source 'test'
rate 1.13
end
end
|
chuckmersereau/api_practice
|
spec/support/expectations/collection_types.rb
|
require 'rspec/expectations'
RSpec::Matchers.define :be_a_hash_with_types do |key_type, value_type|
match do |actual|
actual.is_a?(Hash) && actual.all? do |k, v|
k.is_a?(key_type) && v.is_a?(value_type)
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180425180956_add_active_to_export_logs.rb
|
class AddActiveToExportLogs < ActiveRecord::Migration
def change
add_column :export_logs, :active, :boolean, default: true
ExportLog.update_all(active: false)
end
class ExportLog < ActiveRecord::Base; end
end
|
chuckmersereau/api_practice
|
app/workers/google_plus_account_fetcher_worker.rb
|
class GooglePlusAccountFetcherWorker
include Sidekiq::Worker
sidekiq_options queue: :api_google_plus_account_fetcher_worker, unique: :until_executed
def perform(email_address_id)
email_address = EmailAddress.find_by(id: email_address_id)
return unless email_address
google_plus_account = fetch_google_plus_account_from_email_address(email_address)
email_address.update(checked_for_google_plus_account: true)
email_address.google_plus_account = google_plus_account
end
private
def fetch_google_plus_account_from_email_address(email_address)
EmailAddress::GooglePlusAccountFetcher.new(email_address).fetch_google_plus_account
end
end
|
chuckmersereau/api_practice
|
app/services/user_from_cas_service.rb
|
<gh_stars>0
class UserFromCasService
def self.find_or_create(cas_attributes)
new(cas_attributes).find_or_create
end
attr_reader :cas_attributes
def initialize(cas_attributes)
@cas_attributes = cas_attributes
end
def find_or_create
user = find_user || create_user || raise_missing_user
Person::KeyAccount.find_or_create_from_auth(omniauth_attributes_hash, user)
user
end
def guids
[
cas_attributes[:relayGuid],
cas_attributes[:theKeyGuid],
cas_attributes[:ssoGuid]
].uniq
end
# The goal of this method is to return a mirror of how the CAS Omniauth system
# returns the CAS data, that way we can leverage the already existing code
# from the legacy system to create user accounts, etc.
#
# This, however, does not include the `credentials` data as only the CAS
# account attributes are being sent on initialize, and the ticket is not
# needed for user creation
#
def omniauth_attributes_hash
@omniauth_attributes_hash ||= Hashie::Mash.new(
provider: 'key',
uid: cas_attributes[:email],
extra: {
user: cas_attributes[:email],
attributes: [
{
ssoGuid: cas_attributes[:ssoGuid],
firstName: cas_attributes[:firstName],
lastName: cas_attributes[:lastName],
theKeyGuid: cas_attributes[:theKeyGuid],
relayGuid: cas_attributes[:relayGuid],
email: cas_attributes[:email]
}
]
}
)
end
private
# Since the legacy system already knows how to create a new User and their
# associated relationships, queue up imports, etc - via Omniauth Data - we can
# just leverage that old code until the time comes for a refactor
#
# The basic logic here is being pulled from the legacy
# `app/controllers/auth/accounts_controller`.
#
# Specifically, the internals of this: https://github.com/CruGlobal/mpdx/blob/8d2f74a9955ad4eb2c2e3faa3c1caca50a7ce97e/app/controllers/auth/accounts_controller.rb#L23
# and this: https://github.com/CruGlobal/mpdx/blob/8d2f74a9955ad4eb2c2e3faa3c1caca50a7ce97e/app/controllers/auth/accounts_controller.rb#L32
def create_user
Person::KeyAccount.create_user_from_auth(omniauth_attributes_hash)
end
def find_user
User.find_by_guid(guids)
end
def raise_missing_user
message = <<~HEREDOC
Unable to find or create user from cas_attributes: #{cas_attributes}
HEREDOC
raise MissingUserError, message
end
class MissingUserError < StandardError; end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/mail_chimp_accounts_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Account Lists > Mailchimp Accounts' do
include_context :json_headers
documentation_scope = :account_lists_api_mailchimp_accounts
let(:resource_type) { 'mail_chimp_accounts' }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:primary_list_id) { '1e72b58b72' }
let(:primary_list_id_2) { '29a77ba541' }
let!(:mail_chimp_account) do
create(:mail_chimp_account, account_list: account_list, api_key: 'fake-us4', primary_list_id: primary_list_id)
end
let(:appeal) { create(:appeal, account_list: account_list) }
let(:form_data) { build_data(api_key: 'fake-us4', primary_list_id: primary_list_id) }
let(:resource_attributes) do
%w(
active
api_key
auto_log_campaigns
created_at
lists_available_for_newsletters
lists_link
lists_present
primary_list_id
primary_list_name
valid
validate_key
validation_error
updated_at
updated_in_db_at
)
end
before do
allow_any_instance_of(MailChimp::PrimaryListSyncWorker).to receive(:perform)
allow_any_instance_of(MailChimp::GibbonWrapper).to receive(:lists).and_return([])
allow_any_instance_of(MailChimp::GibbonWrapper).to receive(:validate_key)
api_login(user)
end
get '/api/v2/account_lists/:account_list_id/mail_chimp_account' do
with_options scope: [:data, :attributes] do
response_field 'active', 'Active', type: 'Boolean'
response_field 'api_key', 'API Key', type: 'String'
response_field 'auto_log_campaigns', 'Auto Log Campaigns', type: 'Boolean'
response_field 'created_at', 'Created At', type: 'String'
response_field 'lists_available_for_newsletters', 'Lists available for newsletters', type: 'Array[Object]'
response_field 'lists_link', 'Lists Link', type: 'String'
response_field 'lists_present', 'Lists Present', type: 'Boolean'
response_field 'primary_list_id', 'Primary List ID', type: 'Number'
response_field 'primary_list_name', 'Primary List Name', type: 'String'
response_field 'updated_at', 'Updated At', type: 'String'
response_field 'updated_in_db_at', 'Updated In Db At', type: 'String'
response_field 'valid', 'Valid', type: 'Boolean'
response_field 'validation_error', 'Validation Error', type: 'String'
response_field 'validate_key', 'Validate Key', type: 'Boolean'
end
example 'Mailchimp Account [GET]', document: documentation_scope do
explanation 'The MailChimp Account associated with the Account List'
do_request
check_resource
expect(response_status).to eq 200
end
end
delete '/api/v2/account_lists/:account_list_id/mail_chimp_account' do
parameter 'account_list_id', 'Account List ID', required: true
parameter 'id', 'ID', required: true
example 'Mailchimp Account [DELETE]', document: documentation_scope do
explanation 'Deletes the MailChimp Account associated with the Account List'
do_request
expect(response_status).to eq 204
end
end
post '/api/v2/account_lists/:account_list_id/mail_chimp_account' do
parameter 'account_list_id', 'Account List ID', required: true
with_options scope: [:data, :attributes] do
parameter 'active', 'Active Account or Not', type: 'Boolean'
parameter 'api_key', 'API Key', type: 'String', required: true
parameter 'auto_log_campaigns', 'Auto Log Campaigns or Not', type: 'Boolean'
parameter 'lists_available_for_newsletters', 'Lists available for newsletters', type: 'Array[Object]'
parameter 'lists_link', 'Lists Link', type: 'String'
parameter 'lists_present', 'Lists Present or Not', type: 'Boolean'
parameter 'primary_list_id', 'Primary List ID', type: 'String', required: true
parameter 'primary_list_name', 'Primary List Name', type: 'String'
parameter 'valid', 'Valid', type: 'Boolean'
parameter 'validation_error', 'Validation Error', type: 'String'
parameter 'validate_key', 'Validate Key or Not', type: 'Boolean'
end
example 'Mailchimp Account [POST]', document: documentation_scope do
explanation 'Add the MailChimp Account associated with the Account List'
do_request data: form_data
check_resource
expect(response_status).to eq 201
end
end
get '/api/v2/account_lists/:account_list_id/mail_chimp_account/sync' do
parameter 'account_list_id', 'Account List ID', required: true
example 'Mailchimp Account [SYNC]', document: documentation_scope do
explanation "Synchronizes the Account List's contacts to the MailChimp server"
do_request
expect(response_status).to eq 200
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/account_lists/imports/google_controller.rb
|
class Api::V2::AccountLists::Imports::GoogleController < Api::V2Controller
resource_type :imports
def create
persist_import
end
private
def render_import
render json: @import,
status: success_status,
include: include_params,
fields: field_params
end
def persist_import
build_import
authorize_import
if save_import
render_import
else
render_with_resource_errors(@import)
end
end
def build_import
@import ||= import_scope.build
@import.assign_attributes(import_params)
end
def authorize_import
authorize @import
end
def save_import
@import.save(context: persistence_context)
end
def import_params
params
.require(:import)
.permit(Import::PERMITTED_ATTRIBUTES)
.merge(group_tags: params.require(:import).fetch(:group_tags, nil).try(:permit!))
.merge(user_id: current_user.id)
end
def import_scope
load_account_list.imports.where(source: 'google')
end
def load_account_list
@account_list ||= AccountList.find(params[:account_list_id])
end
def pundit_user
PunditContext.new(current_user, account_list: load_account_list)
end
end
|
chuckmersereau/api_practice
|
spec/factories/versions.rb
|
<gh_stars>0
FactoryBot.define do
factory :version do
association :item
association :related_object
event 'event'
whodunnit ':)'
object nil
end
end
|
chuckmersereau/api_practice
|
app/policies/admin/reset_log_policy.rb
|
<filename>app/policies/admin/reset_log_policy.rb
class Admin::ResetLogPolicy < ApplicationPolicy
def create?
resource.valid? &&
resource_owner? &&
user_is_admin? &&
resource.resetted_user.present? &&
!expired? &&
!completed?
end
private
def resource_owner?
user == resource.admin_resetting
end
def user_is_admin?
user.admin == true
end
def expired?
(resource.created_at || Time.current) < 1.day.ago
end
def completed?
resource.completed_at.present?
end
end
|
chuckmersereau/api_practice
|
app/services/task/filter/overdue.rb
|
class Task::Filter::Overdue < Task::Filter::Base
def execute_query(tasks, filters)
return tasks.overdue if filters[:overdue].to_s == 'true'
tasks.where('start_at > ?', Time.current.beginning_of_day)
end
def title
_('Overdue')
end
def type
'single_checkbox'
end
def default_selection
nil
end
end
|
chuckmersereau/api_practice
|
app/serializers/question_serializer.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class QuestionSerializer < ApplicationSerializer
#SERVICE_ATTRIBUTES = [:question_id, :question].freeze
attributes :question
end
|
chuckmersereau/api_practice
|
db/migrate/20170314185145_create_pledges.rb
|
class CreatePledges < ActiveRecord::Migration
def change
create_table :pledges do |t|
t.decimal :amount
t.datetime :expected_date
t.integer :donation_id
t.integer :account_list_id
t.integer :contact_id
t.uuid :uuid, null: false, default: 'uuid_generate_v4()'
t.timestamps null: false
end
add_index :pledges, :account_list_id
add_index :pledges, :uuid
end
end
|
chuckmersereau/api_practice
|
lib/google_contacts_cache.rb
|
class GoogleContactsCache
def initialize(google_account)
@account = google_account
end
def cache_all_g_contacts
GoogleContactsIntegrator.retry_on_api_errs do
cache_g_contacts(@account.contacts_api_user.contacts(showdeleted: false), true)
end
end
def cache_g_contacts(g_contacts, all_cached = false)
@all_g_contacts_cached = all_cached
@g_contact_by_id = Hash[g_contacts.map { |g_contact| [g_contact.id, g_contact] }]
@g_contacts_by_name = {}
g_contacts.each do |g_contact|
name = "#{g_contact.given_name} #{g_contact.family_name}"
name_list = @g_contacts_by_name[name]
if name_list
name_list << g_contact
else
@g_contacts_by_name[name] = [g_contact]
end
end
end
def find_by_id(remote_id)
return unless remote_id.present?
cached_g_contact = @g_contact_by_id[remote_id]
return cached_g_contact if cached_g_contact
return if @all_g_contacts_cached
g_contact = GoogleContactsIntegrator.retry_on_api_errs do
@account.contacts_api_user.get_contact(remote_id)
end
g_contact unless g_contact.deleted?
rescue OAuth2::Error => e
# Just return nil for a 404 Contact Not Found error, otherwise raise the error
raise e unless e.response.status == 404
end
def select_by_name(first_name, last_name)
query_by_full_name("#{first_name} #{last_name}").select do |g_contact|
g_contact.given_name == first_name && g_contact.family_name == last_name
end
end
def query_by_full_name(name)
cached_g_contacts = @g_contacts_by_name[name]
if cached_g_contacts
cached_g_contacts
elsif @all_g_contacts_cached
[]
else
GoogleContactsIntegrator.retry_on_api_errs do
@account.contacts_api_user.query_contacts(name, showdeleted: false)
end
end
end
def remove_g_contact(g_contact)
@g_contact_by_id.delete(g_contact.id)
g_contacts_by_name = @g_contacts_by_name["#{g_contact.given_name} #{g_contact.family_name}"]
g_contacts_by_name&.delete(g_contact)
@all_g_contacts_cached = false
end
end
|
chuckmersereau/api_practice
|
spec/workers/add_appeal_to_tnt_donations_worker_spec.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
require 'rails_helper'
RSpec.describe AddAppealToTntDonationsWorker do
describe '#perform' do
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact, account_list: account_list) }
let(:donor_account) { create(:donor_account, contacts: [contact], account_number: '432294333') }
let(:designation) { create(:designation_account, account_lists: [account_list]) }
let(:import) { create(:tnt_import_3_0_appeals, account_list: account_list) }
let!(:appeal) { create(:appeal, account_list: account_list, tnt_id: '-2079150908') }
let!(:donation) do
create(:donation, remote_id: 'ICWMY', amount: 50, donation_date: '2005-06-10'.to_date,
donor_account: donor_account, designation_account: designation)
end
context 'donation not linked to appeal' do
it 'links donation' do
described_class.new.perform(import.id)
donation.reload
expect(donation.appeal).to eq appeal
expect(donation.appeal_amount).to eq 25
end
it 'created related pledge' do
expect { described_class.new.perform(import.id) }.to change { Pledge.count }.by(1)
pledge = Pledge.last
expect(pledge.amount).to eq donation.reload.appeal_amount
expect(pledge.appeal).to eq appeal
expect(pledge.contact).to eq contact
expect(pledge).to be_processed
end
it 'created related AppealContact' do
expect { described_class.new.perform(import.id) }.to change { AppealContact.count }.by(1)
appeal_contact = AppealContact.last
expect(appeal_contact.appeal).to eq appeal
expect(appeal_contact.contact).to eq contact
end
it 'links based on date/amount/donor' do
donation.update(remote_id: 'DIFFERENT')
described_class.new.perform(import.id)
expect(donation.reload.appeal).to eq appeal
end
end
context 'existing donation' do
it 'increases the pledge' do
appeal.contacts << contact
create(:donation, amount: 20, appeal_amount: 20, donation_date: '2005-06-01'.to_date, appeal: appeal,
donor_account: donor_account, designation_account: designation)
expect { described_class.new.perform(import.id) }.to change { Pledge.count }.by(0)
pledge = Pledge.last
expect(pledge.amount).to eq 45
end
end
context 'donation has been linked to another appeal' do
it "doesn't link donation to appeal" do
donation.update(appeal: create(:appeal, account_list: account_list))
expect { described_class.new.perform(import.id) }.to_not change { donation.reload.appeal_id }
end
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/reports/monthly_losses_graphs_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Reports > Monthly Losses Graphs Report' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:reports, :monthly_losses_graphs])
let(:resource_type) { 'reports_monthly_losses_graphs' }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:resource_attributes) do
%w(
created_at
account_list
losses
month_names
updated_at
updated_in_db_at
)
end
let(:id) { account_list_id }
context 'authorized user' do
before { api_login(user) }
# show
get '/api/v2/reports/monthly_losses_graphs/:id' do
doc_helper.insert_documentation_for(action: :show, context: self)
example doc_helper.title_for(:show), document: doc_helper.document_scope do
explanation doc_helper.description_for(:show)
do_request
check_resource(['relationships'])
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180726135630_add_subject_hidden_index.rb
|
<filename>db/migrate/20180726135630_add_subject_hidden_index.rb
class AddSubjectHiddenIndex < ActiveRecord::Migration
disable_ddl_transaction!
def change
add_index :activities, :subject_hidden, algorithm: :concurrently
end
end
|
chuckmersereau/api_practice
|
spec/services/expected_totals_report/received_donations_spec.rb
|
require 'rails_helper'
describe ExpectedTotalsReport::ReceivedDonations do
subject { described_class.new(account_list: account_list) }
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) }
let!(:donor_account_1) { create(:donor_account) }
let!(:donor_account_2) { create(:donor_account) }
let!(:contact_1) { create(:contact, account_list: account_list) }
let!(:contact_2) { create(:contact, account_list: account_list) }
let!(:donation_1) do
create(:donation, donor_account: donor_account_1,
designation_account: designation_account_1,
amount: 3,
currency: 'CAD',
tendered_amount: 3,
tendered_currency: 'CAD',
donation_date: Date.current)
end
let!(:donation_2) do
create(:donation, donor_account: donor_account_2,
designation_account: designation_account_2,
amount: 2,
currency: 'GBP',
tendered_amount: nil,
tendered_currency: nil,
donation_date: Date.current)
end
before do
account_list.designation_accounts << designation_account_1
account_list.designation_accounts << designation_account_2
contact_1.donor_accounts << donor_account_1
contact_2.donor_accounts << donor_account_2
end
describe '#donation_rows' do
subject { described_class.new(account_list: account_list).donation_rows }
it 'includes received donations with their contact info too' do
expect(subject.size).to eq 2
expect(subject).to contain_exactly(
{
type: 'received',
contact: contact_1,
donation_amount: 3.0,
donation_currency: 'CAD'
},
type: 'received',
contact: contact_2,
donation_amount: 2.0,
donation_currency: 'GBP'
)
end
context 'designation_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { designation_account_id: designation_account_1.id }
).donation_rows
end
it 'includes received donations with their contact info too' do
expect(subject.size).to eq 1
expect(subject).to contain_exactly(
type: 'received',
contact: contact_1,
donation_amount: 3.0,
donation_currency: 'CAD'
)
end
end
context 'donor_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { donor_account_id: donor_account_2.id }
).donation_rows
end
it 'includes received donations with their contact info too' do
expect(subject.size).to eq 1
expect(subject).to contain_exactly(
type: 'received',
contact: contact_2,
donation_amount: 2.0,
donation_currency: 'GBP'
)
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/donor_account_person.rb
|
class DonorAccountPerson < ApplicationRecord
belongs_to :donor_account
belongs_to :person
# attr_accessible :title, :body
end
|
chuckmersereau/api_practice
|
dev/util/sidekiq_util.rb
|
<gh_stars>0
# In addition to the normal work queues that Sidekiq has, Sidekiq Pro has a
# reliability queue for each of the sidekiq processes.
#
# The contents of that queue aren't shown on the Sidekiq web dashboard, but
# typically it will match whatever jobs that sidekiq process is running.
#
# Several of these methods help deal with the reliability queue.
# Removes certain jobs from the reliability queues for a certain sidekiq queue
# This can be useful if you want to cancel a certain type of job. Just
# restarting sidekiq would restart those jobs so you need to yank them from the
# reliability queues first then restart sidekiq.
def remove_from_reliability(q = 'default', &_block)
r = Redis.current
qs = r.keys("resque:queue:#{q}_*")
qs.each do |reliability_q|
list = r.lrange(reliability_q, 0, -1)
list.each do |item|
json = JSON.parse(item)
r.lrem(reliability_q, 1, item) if yield(json)
end
end
end
# Useful for clear out Gmail sync jobs when Sidekiq is too busy
def remove_google_integration
remove_from_reliability do |item|
item['class'] == 'GoogleIntegration'
end
end
# Get items in the reliability queue
def reliability_items(q = 'default')
r = Redis.current
qs = r.keys("resque:queue:#{q}_*")
qs.each do |reliability_q|
puts r.lrange(reliability_q, 0, -1).inspect
end
end
# This can be helpful if e.g. the process index of sidekiq changed or you
# reduced the number of sidekiq processes and you want to capture all of the
# jobs those processes were running.
def enqueue_all_reliability
enqueue_reliability('default')
enqueue_reliability('import')
end
# Move all reliability queues to the default queue
def enqueue_reliability(q)
r = Redis.current
running_hosts = Sidekiq::ProcessSet.new.map { |p| p['hostname'] }
qs = r.keys("resque:queue:#{q}_*")
qs.each do |reliability_q|
next if running_hosts.any? { |h| reliability_q.include?(h) }
len = r.llen(reliability_q)
r.pipelined do
len.times { r.rpoplpush(reliability_q, "resque:queue:#{q}") }
end
end
end
# Be careful with this as it will remove all jobs from the reliability queues
# which means that once you restart sidekiq jobs may never get run. Better to
# yank specific jobs or job types from the reliability queue.
def clear_reliability(q = 'default')
r = Redis.current
qs = r.keys("resque:queue:#{q}_*")
qs.each do |reliability_q|
r.ltrim(reliability_q, -1, 0)
end
end
def remove_enqueued_account_list_imports
q = Sidekiq::Queue.new('import')
q.each do |job|
next unless job.klass == 'AccountList' && (job.args[1] == 'import_data')
puts job.delete
end
end
# Be careful in using this method: it will clear all of the uniqueness
# locks for Sidekiq jobs which can result in duplicate jobs running. It is
# useful in cases though when there are incorrect uniqueness locks set for a
# particular job and you want to clear them all to start over.
# What you should probably do first is make sure the currently running Sidekiq
# jobs finish (or clear the reliability queue, clear out donor imports from the
# import queue and re-promote the build to restart Sidekiq).
def clear_uniqueness_locks
r = Redis.current
uniqueness_locks = r.keys('resque:sidekiq_unique:*')
r.pipelined { uniqueness_locks.each { |k| r.del(k) } }
end
# Removes items from the Sidekiq retry list. For selectively removing large
# numbers of items this is much faster than the Sidekiq::RetrySet.new approach
# since that would involve one Redis call per removed item vs. this method that
# does it pipelined.
# As an example, here's how to remove 40K mailchimp retry jobs with it while
# keeping any other jobs the system is retrying still in the queue:
# 40.times do
# remove_selected_from_retry_set(1000) do |item|
# item[:class] == 'MailChimpAccount'
# end
# end
def remove_selected_from_retry_set(count = 1000)
retry_q = 'resque:retry'
r = Redis.current
items = r.zrange(retry_q, 0, count)
kept = 0
removed = 0
r.pipelined do
items.each do |item_json|
item = JSON.parse(item_json).with_indifferent_access
if yield(item)
r.zrem(retry_q, item_json)
removed += 1
else
kept += 1
end
end
end
puts "Removed #{removed} items, kept #{kept} items"
end
|
chuckmersereau/api_practice
|
spec/validators/credential_validator_spec.rb
|
require 'rails_helper'
describe CredentialValidator do
let(:record) { build(:organization_account) }
let(:validator) { described_class.new({}) }
let(:api) { FakeApi.new }
it 'should not add error if the record is missing an org' do
record.organization = nil
record.valid?
expect(record.errors.full_messages).not_to include(
format(_('Your credentials for %{org} are invalid.'), org: record.organization)
)
end
it 'should not add error if the record is missing a person' do
record.person = nil
record.valid?
expect(record.errors.full_messages).not_to include(
format(_('Your credentials for %{org} are invalid.'), org: record.organization)
)
end
context 'token is nil' do
before do
record.token = nil
end
it 'should add error if the record is missing username' do
record.username = nil
record.valid?
expect(record.errors.full_messages).to include(
format(_('Your credentials for %{org} are invalid.'), org: record.organization)
)
end
it 'should add error if the record is missing password' do
record.password = <PASSWORD>
record.valid?
expect(record.errors.full_messages).to include(
format(_('Your credentials for %{org} are invalid.'), org: record.organization)
)
end
end
context 'token is not nil' do
before do
record.token = '<PASSWORD>'
end
it 'should not add error if the record is missing username' do
record.username = nil
record.valid?
expect(record.errors.full_messages).to_not include(
format(_('Your credentials for %{org} are invalid.'), org: record.organization)
)
end
it 'should not add error if the record is missing password' do
record.password = <PASSWORD>
record.valid?
expect(record.errors.full_messages).to_not include(
format(_('Your credentials for %{org} are invalid.'), org: record.organization)
)
end
end
it 'should add error if the credentials are invalid' do
allow(record.organization).to receive(:api) { api }
allow(api).to receive(:validate_credentials) { false }
validator.validate(record)
expect(record.errors.full_messages).to eq(
[format(_('Your credentials for %{org} are invalid.'), org: record.organization)]
)
end
it 'should not add error if an error already exists' do
record.password = <PASSWORD>
expect do
record.valid?
end.to change { record.errors.full_messages }
expect do
record.valid?
end.not_to change { record.errors.full_messages }
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180202024129_remove_actions_from_notification_preferences.rb
|
class RemoveActionsFromNotificationPreferences < ActiveRecord::Migration
def change
remove_column :notification_preferences, :actions
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/coaching/account_lists_controller.rb
|
class Api::V2::Coaching::AccountListsController < Api::V2Controller
resource_type :account_lists
def index
load_account_lists
render json: @account_lists.preload_valid_associations(include_associations),
meta: meta_hash(@account_lists),
include: include_params,
fields: field_params,
each_serializer: Coaching::AccountListSerializer
end
def show
load_account_list
authorize_account_list
render_account_list
end
private
def load_account_lists
@account_lists = account_lists_scope.where(filter_params)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def account_lists_scope
current_user.becomes(User::Coach).coaching_account_lists
end
def load_account_list
@account_list ||= AccountList.find(params[:id])
end
def authorize_account_list
authorize @account_list
end
def render_account_list
render json: @account_list,
status: success_status,
include: include_params,
fields: field_params,
serializer: Coaching::AccountListSerializer
end
def permitted_sorting_params
%w(name active_mpd_start_at active_mpd_finish_at)
end
def default_sort_param
AccountList.arel_table[:created_at].asc
end
end
|
chuckmersereau/api_practice
|
app/serializers/notification_type_serializer.rb
|
class NotificationTypeSerializer < ApplicationSerializer
type :notification_type
attributes :description,
:type
def notification_type
object.type
end
end
|
chuckmersereau/api_practice
|
app/services/converted_total.rb
|
# takes in an array of arrays [amount, currency]
class ConvertedTotal
attr_accessor :array, :rates, :display_currency
def initialize(array, display_currency)
@array = array
@rates = {}
@display_currency = display_currency
end
def total
array.map do |obj|
convert_on_date(obj[0], obj[1], obj[2])
end.sum.round(2)
end
def convert_on_date(amount, currency, date)
CurrencyRate.convert_on_date(
amount: amount,
from: currency,
to: display_currency,
date: date
)
end
end
|
chuckmersereau/api_practice
|
lib/json_web_token/middleware.rb
|
<reponame>chuckmersereau/api_practice<filename>lib/json_web_token/middleware.rb
module JsonWebToken
class Middleware
API_V2_ENDPOINT ||= '/api/v2/'.freeze
def initialize(app, &block)
@app = app
@after_decode = block
end
def call(env)
add_jwt_payload_to_request_environment(env) if api_v2_request?(env)
@app.call(env)
end
private
def api_v2_request?(env)
env['PATH_INFO']&.starts_with? API_V2_ENDPOINT
end
def add_jwt_payload_to_request_environment(env)
jwt_payload = fetch_jwt_payload(env)
if jwt_payload
env['auth.jwt_payload'] = jwt_payload
@after_decode&.call(env)
end
end
def fetch_auth_header(env)
env['HTTP_AUTHORIZATION']
end
def fetch_auth_param(env)
Rack::Request.new(env).params.dig('access_token')
end
def fetch_http_token(env)
auth_header = fetch_auth_header(env)
return auth_header.split(' ').last if auth_header.present?
fetch_auth_param(env)
end
def fetch_jwt_payload(env)
http_token = fetch_http_token(env)
::JsonWebToken.decode(http_token) if http_token
end
end
end
|
chuckmersereau/api_practice
|
spec/support/fake_api.rb
|
<filename>spec/support/fake_api.rb
class FakeApi
def initialize(*_args)
end
def self.requires_credentials?
true
end
def requires_credentials?
self.class.requires_credentials?
end
def validate_credentials(*_args)
true
end
def profiles
[]
end
def profiles_with_designation_numbers
[]
end
def method_missing(*_args, &_block)
true
end
def import_all(args)
end
end
|
chuckmersereau/api_practice
|
spec/mailers/account_list_reset_mailer_spec.rb
|
require 'rails_helper'
describe AccountListResetMailer do
context '#email' do
let(:email) { create(:email_address) }
let(:user) { create(:user, email: email) }
let(:reset_log) { create(:admin_reset_log) }
context 'invite' do
let!(:mail) { AccountListResetMailer.logout(user, reset_log) }
it 'renders the headers and the body contains the correct link' do
expect(mail.subject).to eq('You must log in to MPDX again')
expect(mail.to).to eq([email.email])
expect(mail.from).to eq(['<EMAIL>'])
expect(mail.body.raw_source).to include(
'You are getting this email because an MPDX administrator has reset your Account.'
)
end
end
end
end
|
chuckmersereau/api_practice
|
app/helpers/preferences_helper.rb
|
<gh_stars>0
module PreferencesHelper
include LocalizationHelper
def salary_organization_select(account_list)
options_for_select(
Hash[account_list.designation_organizations.map(&method(:org_option))],
account_list.salary_organization_id
)
end
private
def org_option(org)
currency = org.default_currency_code
["#{org.name} (#{currency_symbol(currency)} #{currency})", org.id]
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120202215030_create_person_linkedin_accounts.rb
|
<gh_stars>0
class CreatePersonLinkedinAccounts < ActiveRecord::Migration
def change
create_table :person_linkedin_accounts do |t|
t.integer :person_id, null: false
t.string :remote_id, null: false
t.string :token
t.string :secret
t.datetime :token_expires_at
t.timestamps null: false
end
add_index :person_linkedin_accounts, [:person_id, :remote_id], unique: true
add_index :person_linkedin_accounts, :remote_id
end
end
|
chuckmersereau/api_practice
|
app/models/user/option.rb
|
class User::Option < ApplicationRecord
PERMITTED_ATTRIBUTES = [:created_at,
:key,
:overwrite,
:updated_at,
:updated_in_db_at,
:id,
:value].freeze
belongs_to :user
validates :user, :key, presence: true
validates :key,
uniqueness: { scope: :user_id },
format: { with: /\A[A-Za-z0-9_]*\z/ }
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_info_addr_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
RSpec.describe Task::Filter::ContactInfoAddr 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!(: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!(:address_one) { create(:address) }
before do
contact_one.addresses << address_one
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_info_addr: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_info_addr: [] }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_info_addr: '' }, account_list)).to eq(nil)
end
end
context 'filter by no address' do
it 'returns only contacts that have no address' do
expect(described_class.query(tasks, { contact_info_addr: 'No' }, account_list).to_a).to match_array [task_two, task_three]
end
end
context 'filter by address' do
it 'returns only contacts that have a address' do
expect(described_class.query(tasks, { contact_info_addr: 'Yes' }, account_list).to_a).to eq [task_one]
end
end
end
end
|
chuckmersereau/api_practice
|
spec/exhibits/activity_comment_exhibit_spec.rb
|
require 'rails_helper'
describe ActivityCommentExhibit do
subject { ActivityCommentExhibit.new(activity_comment, context) }
let(:person) { create(:person) }
let(:activity_comment) { build(:activity_comment, person: person) }
let(:context) { double }
context '#body' do
it 'returns a message with reply stripped' do
activity_comment.body = "message body\n"\
"On Thu, Jun 4, 2015 at 4:02 PM, tester <<EMAIL>> wrote:\n"\
'> This is long thread test with return message.'
expect(subject.body).to eq('message body')
end
it 'returns an original message' do
activity_comment.body = 'message body'
expect(subject.body).to eq('message body')
end
it 'returns nil if the comment body is nil' do
activity_comment.body = nil
expect(subject.body).to be_nil
end
it 'parse a message with unicode characters' do
activity_comment.body = "message body\n"\
"On Thu, Jun 4, 2015 at 4:02 PM, tester <<EMAIL>> wrote:\n"\
'> Â Â Â This is long thread test with return message.'
expect(subject.body).to eq('message body')
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20140818154803_add_group_import_to_imports.rb
|
class AddGroupImportToImports < ActiveRecord::Migration
def change
add_column :imports, :import_by_group, :boolean, default: false
add_column :imports, :groups, :text
add_column :imports, :group_tags, :text
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/reports/bulk_controller.rb
|
class Api::V2::Reports::BulkController < Api::V2::BulkController
resource_type :weeklies
def create
# binding.pry
@reports = params.require(:data).map { |data| Weekly.new(id: data['weekly']['id']) }
build_weeklies
bulk_authorize(@reports)
@reports.each { |weekly| weekly.save(context: persistence_context) }
render_weeklies(@reports)
end
private
def render_weeklies(weeklies)
render json: BulkResourceSerializer.new(resources: weeklies),
include: include_params,
fields: field_params
end
def session
Weekly.default_value
end
def build_weeklies
@reports.each do |weekly|
weekly_index = data_attribute_index(weekly)
attributes = params.require(:data)[weekly_index][:weekly]
weekly.assign_attributes(
weekly_params(attributes)
)
end
end
def data_attribute_index(weekly)
params
.require(:data)
.find_index { |weekly_data| weekly_data[:weekly][:id] == weekly.id }
end
def weekly_params(attributes)
attributes ||= params.require(:weekly)
attributes.permit(:sid, :question_id, :answer)
end
end
|
chuckmersereau/api_practice
|
spec/serializers/application_serializer_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe ApplicationSerializer, type: :serializer do
describe 'time output' do
let(:timestamp) { 20.minutes.ago }
let(:email_address) { create(:email_address, created_at: timestamp) }
let(:serializer) { ApplicationSerializer.new(email_address) }
let(:parsed_json) { JSON.parse(serializer.to_json) }
it 'ensures that the timezone output is UTC ISO-8601' do
expect(parsed_json['created_at']).to eq timestamp.utc.iso8601
end
it 'includes the updated_in_db_at fied in iso8601' do
expect(parsed_json['updated_in_db_at']).to eq(email_address.updated_at.utc.iso8601)
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/sorting.rb
|
module Sorting
PERMITTED_SORTING_PARAM_DEFAULTS = %w(
created_at
updated_at
).freeze
PERMIT_MULTIPLE_SORTING_PARAMS = false
private
def multiple_sorting_params?
sorting_params_split.length > 1
end
def permitted_sorting_params
[]
end
def permitted_sorting_params_with_defaults
permitted_sorting_params + PERMITTED_SORTING_PARAM_DEFAULTS
end
def raise_error_if_multiple_sorting_params_are_not_permitted
exception = Exceptions::BadRequestError, 'This endpoint does not support multiple sorting parameters.'
raise(*exception) if multiple_sorting_params? && !self.class::PERMIT_MULTIPLE_SORTING_PARAMS
end
def raise_error_unless_sorting_param_allowed
exception = Exceptions::BadRequestError, "Sorting by #{unpermitted_sorting_params.to_sentence} is not supported for this endpoint."
raise(*exception) if unpermitted_sorting_params.present?
end
def sorting_param
return default_sort_param unless params[:sort]
raise_error_if_multiple_sorting_params_are_not_permitted
raise_error_unless_sorting_param_allowed
convert_sorting_params_to_sql
end
def default_sort_param
permitted_sorting_params_with_defaults.include?('created_at') ? 'created_at' : nil
end
def sorting_join
sorting_params_split.collect do |param|
next unless param.include? '.'
resource_name = param.tr('-', '').split('.').first
next if db_resource_name == resource_name
resource_name.to_sym
end.compact
end
def unpermitted_sorting_params
sorting_params = sorting_params_split.collect { |param| db_column_for_permitted_param(param) }
sorting_params - permitted_sorting_params_with_defaults
end
def db_column_for_permitted_param(param)
param.split(' ').first.tr('-', '')
end
def sorting_params_split
params[:sort]&.split(',') || []
end
def sorting_param_applied_to_query
params[:sort] unless unpermitted_sorting_params.present?
end
def convert_sorting_params_to_sql
sorting_params_split.collect do |param|
[
db_table_and_column_for_sorting_param(param),
direction_for_sorting_param(param),
null_order_for_sorting_param(param)
].select(&:present?).join(' ')
end.join(', ')
end
def db_table_and_column_for_sorting_param(param)
"\"#{db_table_for_sorting_param(param)}\".\"#{db_column_for_sorting_param(param)}\""
end
def db_table_for_sorting_param(param)
return db_resource_name unless param.include? '.'
param.split('.').first.tr('-', '').pluralize
end
def db_column_for_sorting_param(param)
param.split('.').last.split(' ').first.tr('-', '')
end
def direction_for_sorting_param(param)
param.starts_with?('-') ? 'DESC' : 'ASC'
end
def null_order_for_sorting_param(param)
split_param = param.split(' ')
return unless split_param.size > 1
null_param = split_param.second
raise Exceptions::BadRequestError, 'Bad format for sort param.' unless null_param.tr('-', '') == 'nulls'
null_param.starts_with?('-') ? 'NULLS LAST' : 'NULLS FIRST'
end
def db_resource_name
RESOURCE_TYPE_TO_DB_TYPE[resource_type] || resource_type.to_s
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/completed_spec.rb
|
require 'rails_helper'
RSpec.describe Task::Filter::Completed do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:task_one) { create(:task, account_list: account_list, completed: true) }
let!(:task_two) { create(:task, account_list: account_list, completed: false) }
describe '#query' do
let(:tasks) { account_list.tasks }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, nil)).to eq(nil)
expect(described_class.query(tasks, { completed: {} }, nil)).to eq(nil)
expect(described_class.query(tasks, { completed: [] }, nil)).to eq(nil)
expect(described_class.query(tasks, { completed: '' }, nil)).to eq(nil)
end
end
context 'filter by activity_type' do
it 'filters completed' do
expect(described_class.query(tasks, { completed: true }, nil).to_a).to include(task_one)
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20140205020709_add_more_indexes.rb
|
class AddMoreIndexes < ActiveRecord::Migration
def change
add_index :versions, [:item_type, :event, :related_object_type, :related_object_id, :created_at, :item_id], name: 'index_versions_on_item_type'
add_index :master_person_sources, :master_person_id
end
end
|
chuckmersereau/api_practice
|
app/serializers/phone_number_serializer.rb
|
<reponame>chuckmersereau/api_practice<filename>app/serializers/phone_number_serializer.rb
class PhoneNumberSerializer < ApplicationSerializer
include DisplayCase::ExhibitsHelper
attributes :country_code,
:historic,
:number,
:location,
:primary,
:source,
:valid_values
delegate :number, to: :phone_number_exhibit
def phone_number_exhibit
exhibit(object)
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/donation_amount_recommendation.rb
|
<filename>app/services/contact/filter/donation_amount_recommendation.rb
class Contact::Filter::DonationAmountRecommendation < Contact::Filter::Base
def execute_query(contacts, filters)
contacts_with_recommendation =
contacts.joins(donor_accounts: :donation_amount_recommendations)
.where('"donation_amount_recommendations"."suggested_pledge_amount" > '\
'"contacts"."pledge_amount" / "contacts"."pledge_frequency"')
return contacts_with_recommendation if filters[:donation_amount_recommendation] == 'Yes'
contacts.where.not(id: contacts_with_recommendation.ids)
end
def title
_('Increase Gift Recommendation')
end
def parent
_('Gift Details')
end
def type
'radio'
end
def custom_options
[{ name: _('Yes'), id: 'Yes' }, { name: _('No'), id: 'No' }]
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/imports/tnt_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::AccountLists::Imports::TntController, type: :controller do
let(:factory_type) { :import }
let(:resource_type) { :imports }
let!(:user) { create(:user_with_account) }
let!(:fb_account) { create(:facebook_account, person: user) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:import) { create(:tnt_import, account_list: account_list, user: user) }
let(:id) { import.id }
let(:resource) { import }
let(:parent_param) { { account_list_id: account_list_id } }
let(:correct_attributes) do
attributes_for(:import, file: Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'tnt', 'tnt_export.xml')))
end
let(:correct_relationships) do
{
account_list: {
data: {
type: 'account_lists',
id: account_list.id
}
},
user: {
data: {
type: 'users',
id: user.id
}
},
source_account: {
data: {
type: 'facebook_accounts',
id: fb_account.id
}
}
}
end
let(:incorrect_attributes) { { source: nil } }
let(:unpermitted_attributes) { nil }
before(:each) do
request.headers['CONTENT_TYPE'] = 'multipart/form-data'
end
include_examples 'create_examples'
describe '#create' do
it 'creates a file' do
api_login(user)
expect do
post :create, full_correct_attributes
end.to change { resource.class.count }.by(1)
expect(response.status).to eq(201)
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.file).to be_present
expect(import.file.path).to end_with("uploads/import/file/#{import.id}/tnt_export.xml")
end
it 'defaults source to tnt' do
api_login(user)
post :create, full_correct_attributes.merge(source: 'bogus')
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.source).to eq 'tnt'
end
it 'defaults user_id to current user' do
api_login(user)
full_correct_attributes[:data][:relationships].delete(:user)
post :create, full_correct_attributes
import = Import.find_by_id(JSON.parse(response.body)['data']['id'])
expect(import.user_id).to eq user.id
end
end
end
|
chuckmersereau/api_practice
|
engines/auth/app/controllers/auth/provider/mail_chimp_accounts_controller.rb
|
module Auth
module Provider
class MailChimpAccountsController < BaseController
protected
def find_or_create_account
mail_chimp_account.attributes = { api_key: auth_hash.extra.api_token_with_dc, active: true }
mail_chimp_account.save
end
def mail_chimp_account
@mail_chimp_account ||= current_account_list.mail_chimp_account || current_account_list.build_mail_chimp_account
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/google_event_spec.rb
|
<filename>spec/models/google_event_spec.rb<gh_stars>0
require 'rails_helper'
RSpec.describe GoogleEvent, type: :model do
end
|
chuckmersereau/api_practice
|
app/serializers/activity_serializer.rb
|
class ActivitySerializer < ApplicationSerializer
attributes :activity_type,
:completed,
:completed_at,
:location,
:next_action,
:notification_time_before,
:notification_time_unit,
:notification_type,
:result,
:starred,
:start_at,
:subject,
:subject_hidden,
:tag_list
attribute :activity_comments_count, key: :comments_count
has_many :comments
has_many :contacts
has_many :people
has_many :email_addresses
has_many :phone_numbers
has_many :activity_contacts
belongs_to :account_list
def tag_list
object.tags.collect(&:name)
end
def subject_hidden
!!object.subject_hidden
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/pledge_received.rb
|
class Contact::Filter::PledgeReceived < Contact::Filter::Base
def execute_query(contacts, filters)
contacts.where(pledge_received: filters[:pledge_received])
end
def title
_('Commitment Received')
end
def parent
_('Commitment Details')
end
def type
'radio'
end
def custom_options
[{ name: _('Received'), id: 'true' }, { name: _('Not Received'), id: 'false' }]
end
end
|
chuckmersereau/api_practice
|
app/services/account_list/analytics.rb
|
class AccountList::Analytics < ActiveModelSerializers::Model
include ActiveModel::Validations
validates :account_list,
:start_date,
:end_date,
presence: true
PERMITTED_ATTRIBUTES = [
:account_list,
:start_date,
:end_date
].freeze
attr_accessor :account_list,
:start_date,
:end_date
def initialize(attributes = {})
super
after_initialize
end
def start_date=(value)
@start_date = value.is_a?(Time) ? value : Time.iso8601(value.to_s).utc
end
def end_date=(value)
@end_date = value.is_a?(Time) ? value : Time.iso8601(value.to_s).utc
end
def appointments
@appointments ||= {
completed: task_count(activity_type: 'Appointment', with_result: %w(Completed Done))
}
end
def contacts
@contacts ||= {
active: account_list.contacts.where(status: ['Never Contacted', 'Contact for Appointment']).count,
referrals: account_list.contacts
.joins(:contact_referrals_to_me).uniq
.where('contact_referrals.created_at BETWEEN ? AND ?', start_date, end_date)
.count,
referrals_on_hand: account_list.contacts.where(status: [nil,
'Never Contacted',
'Ask in Future',
'Cultivate Relationship',
'Contact for Appointment'])
.joins(:contact_referrals_to_me).uniq.count
}
end
def correspondence
@correspondence ||= {
precall: task_count(activity_type: 'Pre Call Letter', with_result: %w(Completed Done)),
reminders: task_count(activity_type: 'Reminder Letter', with_result: %w(Completed Done)),
support_letters: task_count(activity_type: 'Support Letter', with_result: %w(Completed Done)),
thank_yous: task_count(activity_type: 'Thank', with_result: %w(Completed Done))
}
end
def electronic
@electronic ||= {
appointments: task_count(activity_type: ['Email', 'Facebook Message', 'Text Message'], next_action: 'Appointment'),
received: email[:received] + facebook[:received] + text_message[:received],
sent: email[:sent] + facebook[:sent] + text_message[:sent]
}
end
def email
@email ||= {
received: task_count(activity_type: 'Email', with_result: 'Received'),
sent: task_count(activity_type: 'Email', with_result: %w(Completed Done))
}
end
def facebook
@facebook ||= {
received: task_count(activity_type: 'Facebook Message', with_result: 'Received'),
sent: task_count(activity_type: 'Facebook Message', with_result: %w(Completed Done))
}
end
def phone
@phone ||= {
appointments: task_count(activity_type: ['Call', 'Talk to In Person'], next_action: 'Appointment'),
attempted: task_count(activity_type: 'Call', with_result: ['Attempted - Left Message', 'Attempted']),
completed: task_count(activity_type: 'Call', with_result: %w(Completed Done)),
received: task_count(activity_type: 'Call', with_result: 'Received'),
talktoinperson: task_count(activity_type: 'Talk to In Person')
}
end
def text_message
@text_message ||= {
received: task_count(activity_type: 'Text Message', with_result: 'Received'),
sent: task_count(activity_type: 'Text Message', with_result: %w(Completed Done))
}
end
private
def after_initialize
raise ArgumentError, errors.full_messages.join(', ') if invalid?
end
def tasks_scope
@tasks_scope ||= account_list.tasks.completed_between(start_date, end_date)
end
def task_count(activity_type:, with_result: nil, next_action: nil)
task_query = tasks_scope.of_type(activity_type)
task_query = task_query.with_result(with_result) if with_result.present?
task_query = task_query.where(next_action: next_action) if next_action.present?
task_query.count
end
end
|
chuckmersereau/api_practice
|
spec/workers/fix_duplicate_donations_spec.rb
|
require 'rails_helper'
describe FixDuplicateDonations do
let(:account_list) { create(:account_list) }
let(:designation_profile) { create(:designation_profile, account_list: account_list) }
let(:tnt_donor_account) { create(:donor_account, account_number: '1111111') }
let(:remote_donor_account) { create(:donor_account, account_number: '2222222') }
let(:contact) { create(:contact, account_list: account_list) }
let(:designation_account_good) do
create(:designation_account, account_lists: [account_list])
end
let(:designation_account_bad) do
create(:designation_account, account_lists: [account_list],
designation_number: nil)
end
let(:appeal) { create(:appeal, account_list: account_list) }
let!(:donation) do
create(:donation, donation_date: 1.day.ago,
designation_account: designation_account_good,
donor_account: remote_donor_account,
appeal: appeal,
remote_id: '1-abc-001')
end
let!(:donation_dup) do
create(:donation, donation_date: 1.day.ago,
designation_account: designation_account_bad,
donor_account: tnt_donor_account,
created_at: 2.years.ago,
appeal: appeal,
remote_id: '1-abc-010')
end
before do
contact.donor_accounts << tnt_donor_account
contact.donor_accounts << remote_donor_account
account_list.users << designation_profile.user
designation_account_good.designation_profiles << designation_profile
designation_account_bad.designation_profiles << designation_profile
end
def perform_worker
FixDuplicateDonations.new.perform(designation_account_bad.id)
end
def donation_count
account_list.donations.count
end
context 'a duplicate exists' do
it 'removes the duplicate donation' do
expect { perform_worker }.to change { donation_count }.from(2).to(1)
end
it 'saves the donation to a designation_account' do
expect { perform_worker }.to change { donation_dup.reload.designation_account_id }
end
it 'saves the old designation_account_id on the memo' do
perform_worker
expect(donation_dup.reload.memo).to include designation_account_bad.id.to_s
end
it 'saves the old account_list_id on the memo' do
perform_worker
expect(donation_dup.reload.memo).to include account_list.id.to_s
end
it 'saves the old donor account on the memo' do
perform_worker
expect(donation_dup.reload.memo).to include tnt_donor_account.name
expect(donation_dup.memo).to include tnt_donor_account.account_number
end
it 'destroys empty DonorAccount' do
perform_worker
expect(DonorAccount.find_by(id: tnt_donor_account.id)).to be nil
end
it 'transfers appeal_id and appeal amount' do
donation.update(appeal: nil, appeal_amount: nil)
donation_dup.update(appeal_amount: donation.amount / 2)
perform_worker
expect(donation.reload.attributes).to include('appeal_id' => appeal.id,
'appeal_amount' => donation_dup.appeal_amount)
end
it "doesn't match if tendered_currency doesn't match" do
donation_dup.update(tendered_currency: 'USD')
expect { perform_worker }.not_to change { donation_count }
end
it "doesn't match if dup donations was associated with different appeal" do
donation_dup.update(appeal: create(:appeal, account_list: account_list))
expect { perform_worker }.not_to change { donation_count }
end
end
context 'no duplicate exists' do
it "doesn't change donation count" do
donation_dup.destroy
expect { perform_worker }.not_to change { donation_count }
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/coaching/contacts_controller.rb
|
<filename>app/controllers/api/v2/coaching/contacts_controller.rb
class Api::V2::Coaching::ContactsController < Api::V2Controller
resource_type :contacts
def index
load_contacts
render json: @contacts.preload_valid_associations(include_associations),
meta: meta_with_totals_hash(@contacts),
include: include_params,
fields: field_params,
each_serializer: Coaching::ContactSerializer
end
def show
load_contact
authorize_contact
render_contact
end
private
def load_contacts
@contacts =
::Coaching::Contact::Filterer.new(filter_params)
.filter(scope: contacts_scope,
account_lists: account_lists)
.reorder(sorting_param)
.order(default_sort_param)
.page(page_number_param)
.per(per_page_param)
end
def contacts_scope
current_user.becomes(User::Coach).coaching_contacts
end
def load_contact
@contact ||= Contact.find(params[:id])
end
def authorize_contact
authorize @contact
end
def render_contact
render json: @contact,
status: success_status,
include: include_params,
fields: field_params,
serializer: Coaching::ContactSerializer
end
def permitted_sorting_params
%w(name)
end
def default_sort_param
Contact.arel_table[:created_at].asc
end
def permitted_filters
::Coaching::Contact::Filterer::FILTERS_TO_DISPLAY.map(&:underscore)
.map(&:to_sym)
end
def meta_with_totals_hash(scope)
service =
Coaching::Contact::TotalMonthlyPledge.new(
scope, current_user&.default_account_list_record&.default_currency
)
meta = meta_hash(scope)
meta[:total_pledge] = { amount: service.total, currency: service.currency }
meta
end
end
|
chuckmersereau/api_practice
|
lib/batch_request_handler/instruments/logging.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
module BatchRequestHandler
module Instruments
class Logging < BatchRequestHandler::Instrument
def initialize(_params)
@request_index = 0
end
def around_perform_requests(requests)
@request_count = requests.length
yield requests
end
def around_perform_request(env)
rack_request = Rack::Request.new(env)
@request_index += 1
Rails.logger.info("Started #{rack_request.request_method} \"#{rack_request.path}\" as "\
"part of batch (#{@request_index}/#{@request_count}) for "\
"#{rack_request.ip} at #{Time.now.getlocal}")
yield env
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180522114733_add_tagging_index.rb
|
class AddTaggingIndex < ActiveRecord::Migration
def change
add_index :taggings, [:tag_id, :taggable_id], unique: true
end
end
|
chuckmersereau/api_practice
|
spec/factories/nicknames.rb
|
FactoryBot.define do
factory :nickname do
sequence(:name) { |n| "Name#{n}" }
sequence(:nickname) { |n| "NickName#{n}" }
num_merges 1
num_not_duplicates 1
num_times_offered 1
end
end
|
chuckmersereau/api_practice
|
spec/models/company_partnership_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe CompanyPartnership do
end
|
chuckmersereau/api_practice
|
spec/factories/designation_profiles.rb
|
FactoryBot.define do
factory :designation_profile do
remote_id 1
name 'foo'
association :organization
association :user
end
end
|
chuckmersereau/api_practice
|
spec/services/mail_chimp/gibbon_wrapper_spec.rb
|
require 'rails_helper'
RSpec.describe MailChimp::GibbonWrapper do
let(:mail_chimp_account) { build(:mail_chimp_account, active: true) }
let(:api_prefix) { 'https://us4.api.mailchimp.com/3.0' }
subject { described_class.new(mail_chimp_account) }
before do
lists_response = {
lists: [
{ id: 'list_id_one', name: 'Test 1', stats: { open_rate: 30 } },
{ id: 'list_id_two', name: 'Test 2', stats: { open_rate: 20 } }
]
}
stub_request(:get, "#{api_prefix}/lists").to_return(body: lists_response.to_json)
stub_request(:get, "#{api_prefix}/lists?count=100").to_return(body: lists_response.to_json)
end
describe '#lists' do
it 'returns an array of lists associated to the mail_chimp_account' do
expect(subject.lists.map(&:name)).to eq ['Test 1', 'Test 2']
end
it 'deactivates account if api key is invalid' do
error = {
title: 'API Key Invalid', status: 401,
detail: "Your API key may be invalid, or you've attempted to access the wrong datacenter."
}
stub_request(:get, "#{api_prefix}/lists?count=100").to_return(status: 401, body: error.to_json)
mail_chimp_account.primary_list_id = nil
mail_chimp_account.save
expect { subject.lists }.to change { mail_chimp_account.reload.active }.to(false)
end
end
describe '#lists_available_for_appeals' do
it 'returns an available lists for appeal. the primary is excluded' do
# list id from above stub
mail_chimp_account.primary_list_id = 'list_id_one'
expect(subject.lists_available_for_appeals.map(&:id)).to eq(['list_id_two'])
end
end
describe '#lists_available_for_newsletters' do
it 'returns all lists if no appeals list.' do
expect(subject.lists_available_for_newsletters.length).to eq(2)
end
it 'excludes the appeals list if specified' do
create(:mail_chimp_appeal_list, appeal_list_id: 'list_id_one', mail_chimp_account: mail_chimp_account)
expect(subject.lists_available_for_newsletters.map(&:id)).to eq(['list_id_two'])
end
end
context 'validate_key' do
let(:mock_gibbon) { double(:mock_gibbon) }
let(:mock_gibbon_lists) { double(:mock_gibbon_lists) }
it 'activates the account if the api key is valid' do
expect(subject).to receive(:gibbon).and_return(mock_gibbon)
expect(mock_gibbon).to receive(:lists).and_return(mock_gibbon_lists)
expect(mock_gibbon_lists).to receive(:retrieve)
mail_chimp_account.api_key = '<KEY>'
mail_chimp_account.active = false
mail_chimp_account.save
subject.validate_key
expect(mail_chimp_account.active).to eq(true)
end
end
context 'finding a list name' do
it 'finds a list by list_id' do
allow_gibbon_wrapper_to_receive_lists
expect(subject.list('1').name).to eq('foo')
end
it 'finds the primary list' do
allow_gibbon_wrapper_to_receive_lists
mail_chimp_account.primary_list_id = '1'
expect(subject.primary_list.name).to eq('foo')
end
end
context 'fetching member data from MailChimp' do
let(:member1_info) { { 'email_address' => '<EMAIL>' } }
let(:member2_info) { { 'email_address' => '<EMAIL>' } }
let(:member3_info) { { 'email_address' => '<EMAIL>' } }
before do
lists_response = {
members: [
member1_info,
member2_info,
member3_info
]
}
stub_request(:get, "#{api_prefix}/lists/list_id_one/members?count=100&offset=0").to_return(body: lists_response.to_json)
end
describe '#list_members' do
it 'returns an array of lists associated to the mail_chimp_account' do
expect(subject.list_members('list_id_one')).to match_array [
member1_info,
member2_info,
member3_info
]
end
end
describe '#list_emails' do
it 'returns an array of lists associated to the mail_chimp_account' do
emails = %w(<EMAIL> <EMAIL> <EMAIL>)
expect(subject.list_emails('list_id_one')).to match_array emails
end
end
describe '#list_member_info' do
it 'makes a single request if there is only one email' do
stub_request(:get, "#{api_prefix}/lists/list_id_one/members/1919bfc4fa95c7f6b231e583da677a17").to_return(body: member1_info.to_json)
expect(subject.list_member_info('list_id_one', '<EMAIL>')).to eq [member1_info]
end
it 'filters members list for multiple emails' do
emails = %w(<EMAIL> <EMAIL>)
expect(subject.list_member_info('list_id_one', emails)).to match_array [member1_info, member2_info]
end
end
end
def allow_gibbon_wrapper_to_receive_lists
allow(subject).to receive(:lists).and_return([OpenStruct.new(id: '1', name: 'foo')])
end
end
|
chuckmersereau/api_practice
|
app/seeders/notification_types_seeder.rb
|
<filename>app/seeders/notification_types_seeder.rb
class NotificationTypesSeeder < ApplicationSeeder
def seed
Rails.logger.info "#{self.class}... " unless quiet
stopped_giving = NotificationType::StoppedGiving.first_or_create
stopped_giving.update(description: _('Partner missed a gift'), description_for_email: _('Partner missed a gift'))
started_giving = NotificationType::StartedGiving.first_or_create
started_giving.update(description: _('Partner started giving'), description_for_email: _('Partner started giving'))
larger_gift = NotificationType::LargerGift.first_or_create
larger_gift.update(description: _('Partner gave a larger gift than commitment'),
description_for_email: _('Partner gave a larger gift than the commitment recorded in MPDX'))
special_gift = NotificationType::SpecialGift.first_or_create
special_gift.update(description: _('Partner gave a Special Gift'),
description_for_email: _('Partner gave a Special Gift: This notification is triggered anytime '\
"someone who does not have a status of 'Partner - Financial' gives a "\
'gift. If one or more of the people below are financial partners, '\
'please log into MPDX, edit that contact, and set their status to '\
"'Partner - Financial'."))
smaller_gift = NotificationType::SmallerGift.first_or_create
smaller_gift.update(description: _('Partner gave less than commitment'),
description_for_email: _('Partner gave a gift that averages out to less than their commitment'))
recontinued_gift = NotificationType::RecontinuingGift.first_or_create
recontinued_gift.update(description: _('Partner recontinued giving'),
description_for_email: _('Partner gave a gift to recontinue their giving '\
'after being two or more months late'))
long_time_frame_gift = NotificationType::LongTimeFrameGift.first_or_create
long_time_frame_gift.update(description: _('Partner gave with commitment of semi-annual or more'),
description_for_email: _('Partner gave a gift with a long time frame '\
'(semi-annual, annual, or biennial'))
call_partner = NotificationType::CallPartnerOncePerYear.first_or_create
call_partner.update(description: _('Partner have not had an attempted call logged in the past year'),
description_for_email: _('It is so important to connect with our financial partners '\
'personally, but it is easy for time to get away from us. MPDX does '\
'not show a phone call to your financial partner in the past year. '\
'Now would be a great time to connect with them!'))
thank_partner = NotificationType::ThankPartnerOncePerYear.first_or_create
thank_partner.update(description: _('Partner have not had a thank you note logged in the past year'),
description_for_email: _('One of the most important things we can do is thank our partners, '\
'but it is easy for time to get away from us. MPDX does not show a '\
'thank you note for your financial partner in the past year. Now '\
'would be a great time to let them '\
'know how much you appreciate them!'))
remind_partner = NotificationType::RemindPartnerInAdvance.first_or_create
remind_partner.update(description: _('Partner (semiannual, annual, etc) has an expected '\
'donation one month from now. Send them a reminder.'),
description_for_email: _('It is important to remind our financial partners who give on a '\
'less frequent basis of their upcoming gift. MPDX shows financial '\
'partners who have expected donations one month from now. Now would '\
'be a great time to remind them.'))
missing_address = NotificationType::MissingAddressInNewsletter.first_or_create
missing_address.update(description: _('Contact is on the physical newsletter but has no mailing address.'),
description_for_email: _('Contacts missing a mailing address'))
missing_email = NotificationType::MissingEmailInNewsletter.first_or_create
missing_email.update(description: _('Contact is on the email newsletter but has no people with a valid email address.'),
description_for_email: _('Contacts missing an email address'))
end
end
|
chuckmersereau/api_practice
|
app/models/balance.rb
|
<gh_stars>0
class Balance < ApplicationRecord
belongs_to :resource, polymorphic: true
validates :balance, :resource, presence: true
end
|
chuckmersereau/api_practice
|
app/policies/background_batch_policy.rb
|
<reponame>chuckmersereau/api_practice
class BackgroundBatchPolicy < ApplicationPolicy
def initialize(context, resource)
@user = context.user
@resource = resource
end
private
def resource_owner?
resource.user == user
end
end
|
chuckmersereau/api_practice
|
app/policies/pledge_policy.rb
|
class PledgePolicy < ApplicationPolicy
def show?
resource_owner? || resource_coach?
end
private
def resource_owner?
user.account_lists.exists?(id: resource.account_list_id) &&
(resource.contact.nil? || resource.account_list.contacts.exists?(id: resource.contact_id))
end
def resource_coach?
coach.coaching_account_lists.exists?(resource.account_list_id)
end
end
|
chuckmersereau/api_practice
|
app/workers/fix_donations_worker.rb
|
require './dev/migrate/2016_07_14_fix_donations_without_designation_acc.rb'
class FixDonationsWorker
include Sidekiq::Worker
def perform(last_donor_id = 0)
AddAccountsToDonations.new.add_accounts_to_donations(last_donor_id)
end
end
|
chuckmersereau/api_practice
|
app/serializers/constant_list_serializer.rb
|
class ConstantListSerializer < ActiveModel::Serializer
include DisplayCase::ExhibitsHelper
type :constant_list
delegate :activities,
:alert_frequencies,
:assignable_likely_to_give,
:assignable_locations,
:assignable_send_newsletter,
:assignable_statuses,
:codes,
:mobile_alert_frequencies,
:next_actions,
:notifications,
:organizations,
:organizations_attributes,
:pledge_frequencies,
:results,
:statuses,
:csv_import,
:sources,
:tnt_import,
to: :object
delegate :bulk_update_options,
:dates,
:languages,
:locales,
:pledge_currencies,
:pledge_received,
:activity_hashes,
:assignable_likely_to_give_hashes,
:assignable_location_hashes,
:assignable_send_newsletter_hashes,
:assignable_status_hashes,
:bulk_update_option_hashes,
:notification_hashes,
:pledge_currency_hashes,
:pledge_frequency_hashes,
:pledge_received_hashes,
:send_appeals_hashes,
:status_hashes,
to: :constants_exhibit
attributes :activities,
:alert_frequencies,
:assignable_likely_to_give,
:assignable_locations,
:assignable_send_newsletter,
:assignable_statuses,
:codes,
:mobile_alert_frequencies,
:next_actions,
:notifications,
:organizations,
:organizations_attributes,
:pledge_frequencies,
:results,
:statuses,
:csv_import,
:sources,
:tnt_import,
:bulk_update_options,
:dates,
:languages,
:locales,
:pledge_currencies,
:pledge_received,
:activity_hashes,
:assignable_likely_to_give_hashes,
:assignable_location_hashes,
:assignable_send_newsletter_hashes,
:assignable_status_hashes,
:bulk_update_option_hashes,
:notification_hashes,
:notification_translated_hashes,
:pledge_currency_hashes,
:pledge_frequency_hashes,
:pledge_received_hashes,
:send_appeals_hashes,
:status_hashes
# This was mistakenly published on the Public API
# It is here to maintain compatibility with old clients
def notification_translated_hashes
constants_exhibit.notification_hashes
end
private
def constants_exhibit
@constants_exhibit ||= object.to_exhibit
end
end
|
chuckmersereau/api_practice
|
spec/support/shared_controller_examples/destroy_examples.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
RSpec.shared_examples 'destroy_examples' do |_options = {}|
include_context 'common_variables'
describe '#destroy' do
it 'destroys resource object to users that are signed in' do
api_login(user)
expect do
delete :destroy, full_params
end.to change(&count_proc).by(-1)
expect(response.status).to eq(204), invalid_status_detail
end
it 'does not destroy the resource for users that do not own the resource' do
if defined?(id)
api_login(create(:user))
expect do
delete :destroy, full_params
end.not_to change(&count_proc)
expect(response.status).to eq(403), invalid_status_detail
end
end
it 'does not destroy resource object to users that are signed in' do
expect do
delete :destroy, full_params
end.not_to change(&count_proc)
expect(response.status).to eq(401), invalid_status_detail
end
end
end
|
chuckmersereau/api_practice
|
spec/mailers/previews/application_preview.rb
|
<reponame>chuckmersereau/api_practice
class ApplicationPreview < ActionMailer::Preview
def account_list
@account_list ||= AccountList.where(name: 'Email Preview Account List').first_or_create
end
def user
return @user if @user
@user = User.where(first_name: 'Robert', last_name: 'Emailer').first_or_create
@user.email = '<EMAIL>' unless @user.email
AccountListUser.where(user: @user, account_list: account_list).first_or_create
@user
end
end
|
chuckmersereau/api_practice
|
spec/models/notification_spec.rb
|
require 'rails_helper'
describe Notification do
end
|
chuckmersereau/api_practice
|
app/serializers/application_serializer.rb
|
<gh_stars>0
class ApplicationSerializer < ActiveModel::Serializer
attributes :id,
:created_at,
:updated_at,
:updated_in_db_at
def self.collection_serialize(resources)
ActiveModelSerializers::SerializableResource.new(resources, each_serializer: self)
end
def attributes(*args)
attrs = super(*args)
attrs.keys.sort.each_with_object({}) do |key, hash|
value = attrs[key]
value = convert_to_utc_iso8601(value) if value.respond_to?(:utc)
hash[key] = value
end
end
def updated_in_db_at
object.updated_at
end
private
def convert_to_utc_iso8601(value)
value.to_time.utc.iso8601
end
end
|
chuckmersereau/api_practice
|
app/serializers/tools/analytics_serializer.rb
|
class Tools::AnalyticsSerializer < ServiceSerializer
attributes :counts_by_type
delegate :counts_by_type,
to: :object
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/user/options_controller_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Api::V2::User::OptionsController, type: :controller do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:factory_type) { :user_option }
let!(:resource) { create(:user_option, user: user, created_at: 10.minutes.ago) }
let!(:second_resource) { create(:user_option, user: user) }
let(:id) { resource.key }
let(:correct_attributes) { attributes_for(:user_option) }
let(:unpermitted_attributes) { nil }
let(:incorrect_attributes) { nil }
include_context 'common_variables'
include_examples 'index_examples'
options = { except: [] }
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(404), 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
include_examples 'create_examples'
describe '#update' do
include_examples 'including related resources examples', action: :update unless options[:except].include?(:includes)
include_examples 'sparse fieldsets examples', action: :update unless options[:except].include?(:sparse_fieldsets)
it 'updates resource for users that are signed in' do
api_login(user)
put :update, full_update_attributes
expect(response.status).to eq(200), invalid_status_detail
expect(resource.reload.send(update_reference_key)).to eq(update_reference_value)
end
it 'does not update the resource with unpermitted relationships' do
if defined?(unpermitted_relationships)
api_login(user)
put :update, full_unpermitted_attributes
expect(response.status).to eq(403), invalid_status_detail
expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value)
end
end
it 'does not update the resource when there are errors in sent data' do
if can_run_incorrect_update_specs && incorrect_attributes
api_login(user)
put :update, full_incorrect_attributes
expect(response.status).to eq(400), invalid_status_detail
expect(response.body).to include('errors')
expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value)
expect(response_errors).to be_present
if response_error_pointers.present?
expect(
incorrect_attributes.keys.any? do |incorrect_attribute|
pointer_reference = "/data/attributes/#{incorrect_attribute}"
response_error_pointers.include?(pointer_reference)
end
).to be true
end
end
end
it 'does not update resources with outdated updated_at field' do
api_login(user)
full_update_attributes[:data][:attributes][:overwrite] = false
full_update_attributes[:data][:attributes][:updated_in_db_at] = 1.year.ago
put :update, full_update_attributes
expect(response.status).to eq(409), invalid_status_detail
expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value)
expect(response_errors).to be_present
expect(response_errors.first).to have_key('meta')
expect(response_errors.first['meta']).to have_key('updated_in_db_at')
end
it 'does not update resource for users that do not own the resource' do
if defined?(id)
api_login(create(:user))
put :update, full_update_attributes
expect(response.status).to eq(404), invalid_status_detail
expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value)
expect(response_errors).to be_present
end
end
it 'does not updates resource for users that are not signed in' do
put :update, full_update_attributes
expect(response.status).to eq(401), invalid_status_detail
expect(resource.reload.send(update_reference_key)).to_not eq(update_reference_value)
expect(response_errors).to be_present
end
it 'does not update a resource if the resource_type is incorrect' do
api_login(user)
put :update, attributes_with_incorrect_resource_type
expect(response.status).to eq(409), invalid_status_detail
expect(response_errors).to be_present
end
end
def can_run_incorrect_update_specs
!(defined?(dont_run_incorrect_update) && dont_run_incorrect_update)
end
describe '#destroy' do
it 'destroys resource object to users that are signed in' do
api_login(user)
expect do
delete :destroy, full_params
end.to change(&count_proc).by(-1)
expect(response.status).to eq(204), invalid_status_detail
end
it 'does not destroy the resource for users that do not own the resource' do
if defined?(id)
api_login(create(:user))
expect do
delete :destroy, full_params
end.not_to change(&count_proc)
expect(response.status).to eq(404), invalid_status_detail
end
end
it 'does not destroy resource object to users that are signed in' do
expect do
delete :destroy, full_params
end.not_to change(&count_proc)
expect(response.status).to eq(401), invalid_status_detail
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/account_list_users.rb
|
<gh_stars>0
FactoryBot.define do
factory :account_list_user do
user nil
account_list nil
end
end
|
chuckmersereau/api_practice
|
spec/factories/account_list_invites.rb
|
FactoryBot.define do
factory :account_list_invite do
code 'abc'
account_list
association :invited_by_user, factory: :user
recipient_email '<EMAIL>'
accepted_at Date.new
end
end
|
chuckmersereau/api_practice
|
app/mailers/application_mailer.rb
|
class ApplicationMailer < ActionMailer::Base
append_view_path Rails.root.join('app', 'views', 'mailers')
default from: '<EMAIL>'
class << self
alias sidekiq_delay delay
alias sidekiq_delay_until delay_until
# Redefine the delay method with a default queue.
def delay(*args)
args << { queue: :mailers } if args.blank?
sidekiq_delay(*args)
end
def delay_until(timestamp, options = {})
options[:queue] = :mailers if options.with_indifferent_access[:queue].blank?
sidekiq_delay_until(timestamp, options)
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/contact_info_mobile.rb
|
class Contact::Filter::ContactInfoMobile < Contact::Filter::Base
def execute_query(contacts, filters)
filter_mobile = filters[:contact_info_mobile]
contacts_ids_with_mobile = contact_ids_with_phone(contacts, 'mobile')
return contacts.where(id: contacts_ids_with_mobile) if filter_mobile == 'Yes'
contacts.where.not(id: contacts_ids_with_mobile)
end
def title
_('Mobile Phone')
end
def parent
_('Contact Information')
end
def type
'radio'
end
def custom_options
[{ name: _('Yes'), id: 'Yes' }, { name: _('No'), id: 'No' }]
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/user/authenticates_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
require 'json'
resource 'User > Authenticate' do
include_context :json_headers
documentation_scope = :user_api_authenticate
let!(:user) { create(:user) }
let!(:cru_usa_org) { create(:ccc) }
before do
user.key_accounts << create(:key_account, remote_id: 'B163530-7372-551R-KO83-1FR05534129F', authenticated: true)
stub_request(
:get,
"#{ENV['CAS_BASE_URL']}/p3/serviceValidate?"\
'service=http://example.org/api/v2/user/authenticate&ticket=ST-314971-9fjrd0HfOINCehJ5TKXX-cas2a'
).to_return(
status: 200,
body: File.open(
Rails.root.join('spec', 'fixtures', 'cas', 'successful_ticket_validation_response_body.xml')
).read
)
allow(SiebelDonations::Profile).to receive(:find).and_return(nil)
end
post '/api/v2/user/authenticate' do
with_options scope: [:data, :attributes] do
parameter 'cas_ticket', 'A valid CAS Ticket from The Key', type: 'String'
response_field 'json_web_token', 'JSON Web Token', type: 'String'
end
example 'Authenticate [CREATE]', document: documentation_scope do
explanation 'Create a JSON Web Token from a provided valid CAS Ticket'
do_request data: { type: 'authenticate', attributes: { cas_ticket: 'ST-314971-9fjrd0HfOINCehJ5TKXX-cas2a' } }
expect(response_status).to eq(200)
expect(
JsonWebToken.decode(JSON.parse(response_body)['data']['attributes']['json_web_token'])['user_id']
).to eq(user.id)
end
end
end
|
chuckmersereau/api_practice
|
app/policies/mail_chimp_account_policy.rb
|
<reponame>chuckmersereau/api_practice
class MailChimpAccountPolicy < ApplicationPolicy
def sync?
resource_owner?
end
def export?
resource_owner?
end
private
def resource_owner?
user.account_lists.exists?(id: resource.account_list_id)
end
end
|
chuckmersereau/api_practice
|
lib/json_api_service/base_object.rb
|
module JsonApiService
class BaseObject
attr_reader :data,
:parent,
:store
def initialize(data, parent: nil, store:)
@data = data || {}
@parent = parent
@store = store
after_initialize
end
def parent?
parent
end
private
def after_initialize; end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/mail_chimp_accounts_controller_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe Api::V2::AccountLists::MailChimpAccountsController, type: :controller do
let(:factory_type) { :mail_chimp_account }
let!(:user) { create(:user_with_account) }
let(:given_resource_type) { 'mail_chimp_accounts' }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:primary_list_id) { '1e72b58b72' }
let(:primary_list_id_2) { '29a77ba541' }
let(:mail_chimp_account) { MailChimpAccount.new(api_key: 'fake-us4', primary_list_id: primary_list_id) }
let!(:account_list_with_mailchimp) { create(:account_list, mail_chimp_account: mail_chimp_account) }
let(:appeal) { create(:appeal, account_list: account_list) }
before do
allow_any_instance_of(MailChimpAccount).to receive(:lists).and_return([])
allow_any_instance_of(MailChimpAccount).to receive(:lists_available_for_newsletters_formatted).and_return([])
allow_any_instance_of(MailChimpAccount).to receive(:lists_link).and_return([])
allow_any_instance_of(MailChimpAccount).to receive(:primary_list_name)
allow_any_instance_of(MailChimpAccount).to receive(:validate_key)
mail_chimp_account.account_list = account_list
mail_chimp_account.save
end
let!(:resource) { mail_chimp_account }
let(:parent_param) { { account_list_id: account_list_id } }
let(:correct_attributes) do
attributes_for(:mail_chimp_account, primary_list_id: primary_list_id)
end
let(:incorrect_attributes) do
attributes_for(:mail_chimp_account, api_key: nil)
.reject { |attr| attr.to_s.end_with?('_id') }
end
let(:unpermitted_attributes) { nil }
let(:given_reference_key) { :primary_list_id }
include_examples 'show_examples'
include_examples 'destroy_examples'
describe '#create' do
before do
account_list.mail_chimp_account.destroy
end
include_examples 'create_examples'
it 'syncs the mailchimp account after creating' do
api_login(user)
expect(MailChimp::PrimaryListSyncWorker).to receive(:perform_async)
get :create, full_correct_attributes
end
context 'without primary_list_id' do
let(:correct_attributes) do
attributes_for(:mail_chimp_account, primary_list_id: nil)
end
it "doesn't sync the mailchimp account" do
api_login(user)
expect(MailChimp::PrimaryListSyncWorker).to_not receive(:perform_async)
get :create, full_correct_attributes
end
end
end
describe '#sync' do
before do
api_login(user)
end
it 'syncs a mailchimp account' do
expect(MailChimp::PrimaryListSyncWorker).to receive(:perform_async).with(mail_chimp_account.id)
get :sync, account_list_id: account_list_id
expect(response.status).to eq 200
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120423192718_create_contact_referrals.rb
|
class CreateContactReferrals < ActiveRecord::Migration
def change
create_table :contact_referrals do |t|
t.belongs_to :referred_by
t.belongs_to :referred_to
t.timestamps null: false
end
add_index :contact_referrals, [:referred_by_id, :referred_to_id], name: 'referrals'
add_index :contact_referrals, :referred_to_id
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.