repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
chuckmersereau/api_practice
db/migrate/20150225181123_add_references_master_person_to_sources.rb
class AddReferencesMasterPersonToSources < ActiveRecord::Migration def change MasterPersonSource .joins('LEFT JOIN master_people ON master_people.id = master_person_sources.master_person_id') .where('master_people.id is null') .each { |orphaned_m_p_s| orphaned_m_p_s.destroy } add_foreign_key :master_person_sources, :master_people end end
chuckmersereau/api_practice
spec/acceptance/api/v2/user/google_accounts/google_integrations_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Google Integrations' do before do allow_any_instance_of(GoogleIntegration).to receive(:calendars).and_return([]) end include_context :json_headers let(:resource_type) { 'google_integrations' } let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:form_data) { build_data(attributes) } let(:google_account) { create(:google_account, person: user) } let(:google_account_id) { google_account.id } let!(:google_integration) { create(:google_integration, account_list: account_list, google_account: google_account) } let(:id) { google_integration.id } let(:resource_attributes) do %w( created_at updated_at updated_in_db_at calendar_integration calendar_integrations calendar_id calendar_name email_integration email_blacklist contacts_integration calendars ) end let(:additional_attribute_keys) do %w( relationships ) end let(:relationships) do { account_list: { data: { type: 'account_lists', id: account_list.id } }, google_account: { data: { type: 'google_accounts', id: google_account.id } } } end let(:new_google_integration) do { calendar_id: '<EMAIL>', calendar_name: 'test123', calendar_integration: false, calendar_integrations: [], contacts_integration: false, email_integration: false, updated_in_db_at: google_integration.updated_at } end let(:form_data) { build_data(new_google_integration, relationships: relationships) } documentation_scope = :user_api_google_integrations context 'authorized user' do before { api_login(user) } # index get '/api/v2/user/google_accounts/:google_account_id/google_integrations' do example 'Google Integration [LIST]', document: documentation_scope do explanation 'List of Google Integrations' do_request check_collection_resource(1, additional_attribute_keys) expect(response_status).to eq 200 end end # show get '/api/v2/user/google_accounts/:google_account_id/google_integrations/:id' do with_options scope: [:data, :attributes] do # list out the attributes here response_field 'name_of_attribute', 'Name of Attribute', type: 'The Attribute Type (String, Boolean, etc)' end example 'Google Integration [GET]', document: documentation_scope do explanation 'The Google Integration for the given ID' do_request check_resource(additional_attribute_keys) expect(response_status).to eq 200 end end # create post '/api/v2/user/google_accounts/:google_account_id/google_integrations' do with_options scope: [:data, :attributes] do # list out the POST params here parameter 'attribute_name', 'Description of the Attribute' end example 'Google Integration [CREATE]', document: documentation_scope do explanation 'Create Google Integration' do_request data: form_data check_resource(additional_attribute_keys) expect(response_status).to eq 201 end end describe 'update' do put '/api/v2/user/google_accounts/:google_account_id/google_integrations/:id' do with_options scope: [:data, :attributes] do # list out the PUT params here parameter 'attribute_name', 'Description of the Attribute' end example 'Google Integration [UPDATE]', document: documentation_scope do explanation 'Update Google Integration' # Merge with the updated_in_db_at value provided by the server. # Ex: updated_in_db_at: email_address.updated_at do_request data: form_data check_resource(additional_attribute_keys) expect(response_status).to eq 200 end [:calendar_integrations, :email_blacklist].each do |attribute_name| example "It updates the #{attribute_name} array", document: false do google_integration.update!(calendar_integration: true, attribute_name => ['Test']) data = form_data data[:attributes][:calendar_integration] = true data[:attributes][attribute_name] = %w(Test 1234) do_request data: data check_resource(additional_attribute_keys) expect(response_status).to eq 200 expect(json_response['data']['attributes'][attribute_name.to_s]).to eq(%w(Test 1234)) end example "It updates the #{attribute_name} array to be empty", document: false do google_integration.update!(calendar_integration: true, attribute_name => ['Test']) data = form_data data[:attributes][:calendar_integration] = true data[:attributes][attribute_name] = [] do_request data: data check_resource(additional_attribute_keys) expect(response_status).to eq 200 expect(json_response['data']['attributes'][attribute_name.to_s]).to eq([]) end example "It does not set the #{attribute_name} array if the param is not sent", document: false do google_integration.update!(calendar_integration: true, attribute_name => ['Test']) data = form_data data[:attributes][:calendar_integration] = true data[:attributes].delete(attribute_name) do_request data: data check_resource(additional_attribute_keys) expect(response_status).to eq 200 expect(json_response['data']['attributes'][attribute_name.to_s]).to eq(['Test']) end end end patch '/api/v2/user/google_accounts/:google_account_id/google_integrations/:id' do with_options scope: [:data, :attributes] do # list out the PATCH params here parameter 'attribute_name', 'Description of the Attribute' end example 'Google Integration [UPDATE]', document: documentation_scope do explanation 'Update Google Integration' # Merge with the updated_in_db_at value provided by the server. # Ex: updated_in_db_at: email_address.updated_at do_request data: form_data check_resource(additional_attribute_keys) expect(response_status).to eq 200 end end end # destroy delete '/api/v2/user/google_accounts/:google_account_id/google_integrations/:id' do example 'Google Integration [DELETE]', document: documentation_scope do explanation 'Delete Google Integration' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
app/services/task/filter/contact_ids.rb
class Task::Filter::ContactIds < Task::Filter::Base def execute_query(tasks, filters) tasks.joins(:contacts).where(contacts: { id: parse_list(filters[:contact_ids]) }) end def title _('Contacts') end def type 'multiselect' end def custom_options contact_attributes_from_account_lists.collect do |contact| { name: contact.name, id: contact.id, account_list_id: contact.account_list_id } end end def contact_attributes_from_account_lists Contact.joins(:account_list).where(account_list: account_lists) .order('contacts.name ASC').distinct.select('contacts.id, contacts.name, account_lists.id AS account_list_id') end end
chuckmersereau/api_practice
db/migrate/20120424191516_add_completed_to_activity.rb
class AddCompletedToActivity < ActiveRecord::Migration def change add_column :activities, :completed, :boolean, null: false, default: false remove_column :activities, :description end end
chuckmersereau/api_practice
spec/services/contact/filter/pledge_late_by_spec.rb
require 'rails_helper' RSpec.describe Contact::Filter::PledgeLateBy do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } def contact_params(days) { status: 'Partner - Financial', pledge_frequency: 1, account_list_id: account_list.id, pledge_start_date: (1.month + days.days).ago } end let!(:contact_one) { create(:contact, contact_params(15)) } let!(:contact_two) { create(:contact, contact_params(45)) } let!(:contact_three) { create(:contact, contact_params(75)) } let!(:contact_four) { create(:contact, contact_params(105)) } describe '#config' do it 'returns expected config' do expect(described_class.config([account_list])).to include(multiple: false, name: :pledge_late_by, options: [ { name: '-- Any --', id: '', placeholder: 'None' }, { name: _('Less than 30 days late'), id: '0_30' }, { name: _('More than 30 days late'), id: '30_60' }, { name: _('More than 60 days late'), id: '60_90' }, { name: _('More than 90 days late'), id: '90' } ], parent: 'Commitment Details', title: 'Late By', type: 'radio', default_selection: '') end end describe '#query' do let(:contacts) { Contact.all } context 'no filter params' do it 'returns nil' do expect(described_class.query(contacts, {}, nil)).to eq(nil) expect(described_class.query(contacts, { pledge_late_by: {} }, nil)).to eq(nil) expect(described_class.query(contacts, { pledge_late_by: [] }, nil)).to eq(nil) expect(described_class.query(contacts, { pledge_late_by: '' }, nil)).to eq(nil) end end context 'filter by days late' do it 'returns only contacts that are less than 30 days late' do expect(described_class.query(contacts, { pledge_late_by: '0_30' }, nil).to_a).to eq [contact_one] end it 'returns only contacts that are between 30 to 60 days late' do expect(described_class.query(contacts, { pledge_late_by: '30_60' }, nil).to_a).to eq [contact_two] end it 'returns only contacts that are between 60 to 90 days late' do expect(described_class.query(contacts, { pledge_late_by: '60_90' }, nil).to_a).to eq [contact_three] end it 'returns only contacts that are more than 90 days late' do expect(described_class.query(contacts, { pledge_late_by: '90' }, nil).to_a).to eq [contact_four] end end end end
chuckmersereau/api_practice
spec/services/tnt_import/contact_tags_loader_spec.rb
require 'rails_helper' describe TntImport::ContactTagsLoader do let(:import) { create(:tnt_import, override: true) } let(:tnt_import) { TntImport.new(import) } let(:xml) { tnt_import.xml } before { import.file = File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml')) } describe '.tags_by_tnt_contact_id' do it 'returns a hash of expected tags grouped by contat id' do expect(TntImport::ContactTagsLoader.new(xml).tags_by_tnt_contact_id).to eq('1' => ['Fund Rep - Clark'], '748459734' => ['UserLabel1 - ParrUser1', 'UserLabel2 - ParrUser2', 'UserLabel3 - ParrUser3', 'UserLabel4 - ParrUser4', 'Fund Rep - Clark'], '748459735' => ['Fund Rep - Clark']) end end end
chuckmersereau/api_practice
db/migrate/20150127184809_create_recurring_recommendation_results.rb
class CreateRecurringRecommendationResults < ActiveRecord::Migration def change create_table :recurring_recommendation_results do |t| t.belongs_to :account_list t.belongs_to :contact t.string :result, null: false t.timestamps null: false end end end
chuckmersereau/api_practice
app/models/notification_type/missing_email_in_newsletter.rb
class NotificationType::MissingEmailInNewsletter < NotificationType::MissingContactInfo def missing_info_filter(contacts) contacts.where(send_newsletter: %w(Both Email)).scoping do Contact.where.not(id: contacts_with_email.pluck(:id)) end end def contacts_with_email Contact.joins(:contact_people) .joins('INNER JOIN email_addresses '\ 'ON email_addresses.person_id = contact_people.person_id') .where(email_addresses: { historic: [nil, false] }) end def task_description_template(_notification = nil) _('%{contact_name} is on the email newsletter but lacks a valid email address.') end end
chuckmersereau/api_practice
app/services/contact/filter/timezone.rb
class Contact::Filter::Timezone < Contact::Filter::Base def execute_query(contacts, filters) contacts.where('contacts.timezone' => timezone_filters(filters)) end def title _('Timezone') end def type 'multiselect' end def custom_options account_lists.map(&:timezones).flatten.uniq.select(&:present?).map { |timezone| { name: timezone, id: timezone } } end private def timezone_filters(filters) @timezone_filters ||= parse_list(filters[:timezone]) end end
chuckmersereau/api_practice
db/migrate/20120229195155_create_account_list_entries.rb
class CreateAccountListEntries < ActiveRecord::Migration def change create_table :account_list_entries do |t| t.belongs_to :account_list t.belongs_to :designation_account t.timestamps null: false end add_index :account_list_entries, [:account_list_id, :designation_account_id], name: 'unique_account', unique: true add_index :account_list_entries, :designation_account_id end end
chuckmersereau/api_practice
lib/csv_util.rb
require 'nokogiri' require 'csv' module CSVUtil def html_table_to_csv(html_table) CSV.generate do |csv| Nokogiri::HTML(html_table).xpath('//table//tr').each do |row| csv << (row.xpath('th') + row.xpath('td')).map { |cell| cell.text.strip } end end end module_function :html_table_to_csv end
chuckmersereau/api_practice
app/policies/contact_referral_policy.rb
class ContactReferralPolicy < ApplicationPolicy attr_reader :contact, :resource, :user def initialize(context, resource) @user = context.user @contact = context.contact @resource = resource end private def resource_owner? user_has_ownership_of_contact? && referral_referred_by_contact? end def referral_referred_by_contact? resource.referred_by_id == contact.id end def user_has_ownership_of_contact? user.account_lists.exists?(id: contact.account_list_id) end end
chuckmersereau/api_practice
app/policies/import_policy.rb
class ImportPolicy < AccountListChildrenPolicy end
chuckmersereau/api_practice
spec/controllers/api/v2/reports/pledge_histories_controller_spec.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 require 'rails_helper' RSpec.describe Api::V2::Reports::PledgeHistoriesController, type: :controller do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:given_serializer_class) { Reports::PledgeHistoriesPeriodSerializer } let(:given_resource_type) { 'reports_pledge_histories_periods' } let(:factory_type) { :account_list } let(:resource) do Reports::PledgeHistoriesPeriod.new( account_list: account_list, start_date: 1.week.ago, end_date: DateTime.current ) end let(:correct_attributes) { {} } include_examples 'index_examples', except: [:sorting, :pagination] describe 'Filters' do it 'allows a user to request from their account_list' do api_login(user) get :index, filter: { account_list_id: account_list.id } expect(response.status).to eq 200 end it 'blocks a user from accessing others account lists' do api_login(create(:user)) get :index, filter: { account_list_id: account_list.id } expect(response.status).to eq 404 end end end
chuckmersereau/api_practice
dev/util/view_cache_util.rb
# Helpful for expiring an account's donations chart if there has been a recent # update in their donations and they don't know why the chart isn't updating. # (Or if you did a change to a test account for purpose of training videos.) def expire_donations_chart(account_list) r = view_cache_redis prefix = 'cache:views/donations_summary_chart/account_lists' # the full key has some extra numbers after the id wildcard_key = "#{prefix}/#{account_list.id}*" full_key = r.keys(wildcard_key).first r.del(full_key) end def view_cache_redis view_cache_db = 1 client = Redis.new(host: Redis.current.client.host, port: Redis.current.client.port, db: view_cache_db) Redis::Namespace.new(Redis.current.namespace, redis: client) end
chuckmersereau/api_practice
app/models/designation_account.rb
class DesignationAccount < ApplicationRecord belongs_to :organization has_many :designation_profile_accounts, dependent: :delete_all has_many :designation_profiles, through: :designation_profile_accounts has_many :account_list_entries, dependent: :delete_all has_many :account_lists, through: :account_list_entries has_many :contacts, through: :account_lists has_many :donations, dependent: :destroy has_many :balances, dependent: :delete_all, as: :resource has_many :donation_amount_recommendations, dependent: :destroy, inverse_of: :designation_account after_save :create_balance, if: :balance_changed? validates :organization_id, presence: true audited except: [:updated_at, :balance, :balance_updated_at] PERMITTED_ATTRIBUTES = [ :active, :overwrite, :updated_at, :updated_in_db_at, :id ].freeze def to_s designation_number end def descriptor name.presence || designation_number.presence || _('Unnamed Designation') end # A given user should only have a designation account in one list def account_list(user) (user.account_lists & account_lists).first end def update_donation_totals(donation, reset: false) contacts.includes(:donor_accounts).where('donor_accounts.id' => donation.donor_account_id).find_each do |contact| contact.update_donation_totals(donation, reset: reset) end end def currency @currency ||= organization.default_currency_code || 'USD' end def converted_balance(convert_to_currency) # Log the error in rollbar, but then return a zero balance to prevent future # errors and prevent this balance form adding to the total. CurrencyRate.convert_with_latest(amount: balance, from: currency, to: convert_to_currency) end def self.filter(filter_params) chain = where(filter_params.except(:wildcard_search)) return chain unless filter_params.key?(:wildcard_search) chain.where('LOWER("designation_accounts"."name") LIKE :name OR '\ '"designation_accounts"."designation_number" LIKE :account_number', name: "%#{filter_params[:wildcard_search].downcase}%", account_number: "#{filter_params[:wildcard_search]}%") end protected def create_balance balances.create(balance: balance) if balance end end
chuckmersereau/api_practice
spec/models/donation_amount_recommendation_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe DonationAmountRecommendation, type: :model do subject { create(:donation_amount_recommendation) } it { is_expected.to belong_to(:designation_account) } it { is_expected.to belong_to(:donor_account) } it { is_expected.to validate_presence_of(:designation_account) } it { is_expected.to validate_presence_of(:donor_account) } end
chuckmersereau/api_practice
db/migrate/20120309152420_move_organization_account_under_person.rb
<reponame>chuckmersereau/api_practice class MoveOrganizationAccountUnderPerson < ActiveRecord::Migration def up rename_table :organization_accounts, :person_organization_accounts rename_column :person_organization_accounts, :user_id, :person_id add_column :person_organization_accounts, :remote_id, :string add_column :person_organization_accounts, :authenticated, :boolean, default: false, null: false add_column :person_organization_accounts, :valid_credentials, :boolean, default: false, null: false add_column :organizations, :api_class, :string end def down remove_column :organizations, :api_class remove_column :person_organization_accounts, :valid_credentials remove_column :person_organization_accounts, :authenticated remove_column :person_organization_accounts, :remote_id rename_column :person_organization_accounts, :person_id, :user_id rename_table :person_organization_accounts, :organization_accounts end end
chuckmersereau/api_practice
app/serializers/person/network_serializer.rb
class Person::NetworkSerializer < ApplicationSerializer attributes :facebook_accounts, :linkedin_accounts, :twitter_accounts, :websites end
chuckmersereau/api_practice
spec/factories/export_logs.rb
<reponame>chuckmersereau/api_practice FactoryBot.define do factory :export_log do type 'Contacts Export' params 'filter[account_list_id]=1' user { User.first || create(:user) } export_at '2017-07-28 15:19:32' end end
chuckmersereau/api_practice
app/controllers/api/v2/account_lists/imports_controller.rb
<reponame>chuckmersereau/api_practice class Api::V2::AccountLists::ImportsController < Api::V2Controller def show load_import authorize_import render_import end private def load_import @import ||= Import.find(params[:id]) end def render_import render json: @import, status: success_status, include: include_params, fields: field_params end def authorize_import authorize @import 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
app/services/person/duplicate_pairs_finder.rb
<filename>app/services/person/duplicate_pairs_finder.rb # This class finds and saves DuplicateRecordPair records by looking through all People in the given AccountList. # Duplicates are found primarily by comparing the People names, phone numbers, and emails. class Person::DuplicatePairsFinder < ApplicationDuplicatePairsFinder private def find_duplicates find_duplicates_by_full_name find_duplicates_by_first_name find_duplicates_by_email find_duplicates_by_phone_number end def people_scope account_list.people end def people_hashes @people_hashes ||= build_people_hashes end def build_people_hashes contact_people = ContactPerson.where(person: people_scope).select(:person_id, :contact_id).group_by(&:person_id) phone_numbers = PhoneNumber.where(person: people_scope).select(:person_id, :number).group_by(&:person_id) email_addresses = EmailAddress.where(person: people_scope).select(:person_id, :email).group_by(&:person_id) people_scope.select(:id, :first_name, :last_name, :gender).collect do |person| { id: person.id, contact_ids: contact_people[person.id].collect(&:contact_id), first_name: normalize_names([person.first_name]), last_name: normalize_names([person.last_name]), full_name: normalize_names([person.first_name, person.last_name]), email_addresses: normalize_email_addresses(email_addresses[person.id]), phone_numbers: normalize_phone_numbers(phone_numbers[person.id]), gender: normalize_gender(person.gender) } end end def normalize_names(names) names = names.collect { |name| name&.squish } (names - [nil, '']).sort.join(' ').downcase.gsub(/[^[:word:]]/, ' ').squish end def normalize_email_addresses(email_addresses) return [] unless email_addresses email_addresses.collect { |email_address| email_address.email.squish.downcase } end def normalize_phone_numbers(phone_numbers) return [] unless phone_numbers phone_numbers.collect { |phone_number| phone_number.number&.gsub(/\D/, '') } .compact end def normalize_gender(gender) gender&.split(' ')&.first&.downcase end def people_hashes_grouped_by_contact_id @people_hashes_grouped_by_contact_id ||= group_people_hashes_by_contact_id end def group_people_hashes_by_contact_id people_hashes.each_with_object({}) do |person_hash, people_hashes_grouped_by_contact_id| person_hash[:contact_ids].each do |contact_id| people_hashes_grouped_by_contact_id[contact_id] ||= [] people_hashes_grouped_by_contact_id[contact_id] << person_hash end end end def find_duplicates_by_full_name people_hashes_grouped_by_contact_id.each do |_contact_id, people_hashes| find_duplicate_hashes_by_value(people_hashes, :full_name).each do |duplicate_hashes| add_duplicate_pair_from_hashes(duplicate_hashes, 'Similar names') end end end # If people have the same first name consider them duplicates only if one or both of them are missing a last name. def find_duplicates_by_first_name people_hashes_grouped_by_contact_id.each do |_contact_id, people_hashes| find_duplicate_hashes_by_value(people_hashes, :first_name).each do |duplicate_hashes| next unless duplicate_hashes.first[:last_name].blank? || duplicate_hashes.second[:last_name].blank? add_duplicate_pair_from_hashes(duplicate_hashes, 'Similar names') end end end def find_duplicates_by_email people_hashes_grouped_by_contact_id.each do |_contact_id, people_hashes| find_duplicate_hashes_by_value(people_hashes, :email_addresses, :values_present_and_intersecting?).each do |duplicate_hashes| add_duplicate_pair_from_hashes(duplicate_hashes, 'Similar email addresses') end end end def find_duplicates_by_phone_number people_hashes_grouped_by_contact_id.each do |_contact_id, people_hashes| find_duplicate_hashes_by_value(people_hashes, :phone_numbers, :values_present_and_intersecting?).each do |duplicate_hashes| add_duplicate_pair_from_hashes(duplicate_hashes, 'Similar phone numbers') end end end # Many couples have the same email or phone number, try to exclude spouses from duplicates by looking at the gender. def add_duplicate_pair_from_hashes(duplicate_hashes, reason) unless reason.include?('name') return if duplicate_hashes.first[:gender] != duplicate_hashes.second[:gender] return if duplicate_hashes.first[:gender].blank? && duplicate_hashes.second[:gender].blank? end super end end
chuckmersereau/api_practice
app/controllers/api/v2/user/google_accounts/google_integrations_controller.rb
class Api::V2::User::GoogleAccounts::GoogleIntegrationsController < Api::V2Controller def index authorize load_google_account, :show? load_google_integrations render json: @google_integrations, meta: meta_hash(@google_integrations), include: include_params, fields: field_params end def show load_google_integration authorize_google_integration render_google_integration end def create persist_google_integration end def update load_google_integration authorize_google_integration persist_google_integration end def destroy load_google_integration authorize_google_integration destroy_google_integration end def sync load_google_integration authorize_google_integration @google_integration.queue_sync_data(params[:integration]) render_200 end private def destroy_google_integration @google_integration.destroy head :no_content end def load_google_integrations @google_integrations = google_integration_scope .reorder(sorting_param) .order(default_sort_param) .page(page_number_param) .per(per_page_param) end def load_google_integration @google_integration ||= GoogleIntegration.find(params[:id]) end def render_google_integration render json: @google_integration, status: success_status, include: include_params, fields: field_params end def persist_google_integration build_google_integration authorize_google_integration if save_google_integration render_google_integration else render_with_resource_errors(@google_integration) end end def build_google_integration @google_integration ||= google_integration_scope.build @google_integration.assign_attributes(google_integration_params) end def authorize_google_integration authorize load_google_account, :show? authorize @google_integration end def save_google_integration @google_integration.save(context: persistence_context) end def google_integration_params params .require(:google_integration) .permit(GoogleIntegration::PERMITTED_ATTRIBUTES) .tap do |permit_params| # Permit the Array attributes to be set to anything, # including nil (so that the client can empty the Array). if params[:google_integration].keys.include?('email_blacklist') permit_params[:email_blacklist] = params[:google_integration][:email_blacklist] end if params[:google_integration].keys.include?('calendar_integrations') permit_params[:calendar_integrations] = params[:google_integration][:calendar_integrations] end end end def google_integration_scope current_user.google_integrations.where(account_list: account_lists, google_account: load_google_account) end def load_google_account @google_account ||= Person::GoogleAccount.find(params[:google_account_id]) end def permitted_filters [:account_list_id] end def default_sort_param GoogleIntegration.arel_table[:created_at].asc end end
chuckmersereau/api_practice
db/migrate/20140901145600_add_fields_to_google_contacts.rb
class AddFieldsToGoogleContacts < ActiveRecord::Migration def change add_column :google_contacts, :picture_etag, :string add_column :google_contacts, :picture_id, :integer add_column :google_contacts, :google_account_id, :integer add_index :google_contacts, :google_account_id end end
chuckmersereau/api_practice
app/exhibits/person_exhibit.rb
<reponame>chuckmersereau/api_practice class PersonExhibit < DisplayCase::Exhibit include DisplayCase::ExhibitsHelper def self.applicable_to?(object) object.class.name == 'Person' end def age(now = Time.now.utc.to_date) return nil unless [birthday_day, birthday_month, birthday_year].all?(&:present?) now.year - birthday_year - (now.month > birthday_month || (now.month == birthday_month && now.day >= birthday_day) ? 0 : 1) end def avatar(size = :square) if primary_picture size_to_load = size size_to_load = :large if size == :large_square begin url = primary_picture.image.url(size_to_load) return url if url rescue StandardError end end if facebook_account&.remote_id.present? return "https://graph.facebook.com/#{facebook_account.remote_id}/picture?height=120&width=120" if size == :large_square return "https://graph.facebook.com/#{facebook_account.remote_id}/picture?type=#{size}" end url = if gender == 'female' ActionController::Base.helpers.image_url('avatar_f.png') else ActionController::Base.helpers.image_url('avatar.png') end if url.start_with?('/') root_url = 'https://mpdx.org' url = URI.join(root_url, url).to_s end url end def to_s [first_name, last_name].compact.join(' ') end def social? facebook_account || twitter_account || linkedin_account end def facebook_link return unless facebook_account @context.link_to('', facebook_account.url, target: '_blank', class: 'fa fa-facebook-square') end def twitter_link return unless twitter_account @context.link_to('', twitter_account.url, target: '_blank', class: 'fa fa-twitter-square') end def email_link return unless primary_email_address @context.mail_to(primary_email_address.to_s, '', class: 'fa fa-envelope') end end
chuckmersereau/api_practice
spec/models/account_list_invite_spec.rb
<gh_stars>0 require 'rails_helper' describe AccountListInvite do let(:invite) { create(:account_list_invite, accepted_by_user: nil) } let(:user) { create(:user) } let(:account_list) { create(:account_list) } context '#accept' do it 'returns false and does nothing if a second user tries to accept' do invite.accept(user) user2 = create(:user) expect do expect(invite.accept(user2)).to be_falsey end.to_not change(AccountListUser, :count) end it 'returns false and does nothing if the invite was canceled' do invite.cancel(user) user2 = create(:user) expect do expect(invite.accept(user2)).to be_falsey end.to_not change(AccountListUser, :count) end context 'user' do it 'creates an account list entry for recipient and updates the accepting info' do expect(invite.accept(user)).to be_truthy expect(user.account_lists.to_a).to eq([invite.account_list]) invite.reload expect(invite.accepted_by_user).to eq(user) expect(invite.accepted_at).to be_present end it 'does not create a second account list entry if the user already has access' do user.account_lists << invite.account_list expect do invite.accept(user) end.to_not change(AccountListUser, :count) end it 'returns true if same user accepts again, but does not create new entry' do invite.accept(user) expect do expect(invite.accept(user)).to be_truthy end.to_not change(AccountListUser, :count) end end context 'coach' do let(:coach) { user.becomes(User::Coach) } before do invite.update(invite_user_as: 'coach') end it 'creates an account list entry for recipient and updates the accepting info' do expect(invite.accept(user)).to be_truthy expect(coach.coaching_account_lists.to_a).to eq([invite.account_list]) invite.reload expect(invite.accepted_by_user).to eq(user) expect(invite.accepted_at).to be_present end it 'does not create a second account list entry if the user already has access' do coach.coaching_account_lists << invite.account_list expect do invite.accept(user) end.to_not change(AccountListCoach, :count) end it 'returns true if same user accepts again, but does not create new entry' do invite.accept(user) expect do expect(invite.accept(user)).to be_truthy end.to_not change(AccountListCoach, :count) end end end context '.send_invite' do context 'user' do it 'creates an invite with a random code and sends the invite email' do expect(SecureRandom).to receive(:hex).with(32) { 'code' } expect_delayed_email(AccountListInviteMailer, :email) invite = AccountListInvite.send_invite(user, account_list, '<EMAIL>', 'user') expect(invite.invited_by_user).to eq(user) expect(invite.invite_user_as).to eq('user') expect(invite.code).to eq('code') expect(invite.recipient_email).to eq('<EMAIL>') expect(invite.account_list).to eq(account_list) end end context 'coach' do it 'creates an invite with a random code and sends the invite email' do expect(SecureRandom).to receive(:hex).with(32) { 'code' } expect_delayed_email(AccountListInviteMailer, :email) invite = AccountListInvite.send_invite(user, account_list, '<EMAIL>', 'coach') expect(invite.invited_by_user).to eq(user) expect(invite.invite_user_as).to eq('coach') expect(invite.code).to eq('code') expect(invite.recipient_email).to eq('<EMAIL>') expect(invite.account_list).to eq(account_list) end end end context '#cancel' do it 'sets the canceling user and is then considered cancelled', versioning: true do expect(invite.cancelled?).to be false user2 = create(:user) invite.cancel(user2) expect(invite.cancelled?).to be true expect(invite.cancelled_by_user).to eq user2 end end end
chuckmersereau/api_practice
app/services/account_list/pledge_matcher.rb
<filename>app/services/account_list/pledge_matcher.rb class AccountList::PledgeMatcher attr_accessor :donation delegate :appeal, to: :donation def initialize(donation) @donation = donation end def needs_pledge? appeal.present? && contact.present? && donation.pledges.empty? end def pledge @pledge ||= existing_pledge || create_pledge if needs_pledge? end private def existing_pledge pledge_scope.find_by(contact_id: contact) end def pledge_scope appeal.pledges end def contact @contact ||= contact_scope.find_by( contact_donor_accounts: { donor_account: donation.donor_account } ) end def contact_scope appeal.contacts.joins(:contact_donor_accounts) end def create_pledge Pledge.create( account_list: appeal.account_list, amount: donation.pledge_amount, amount_currency: donation.currency, appeal: appeal, contact: contact, expected_date: donation.donation_date ) end end
chuckmersereau/api_practice
db/migrate/20120329145102_add_unique_index_to_email_addresses.rb
class AddUniqueIndexToEmailAddresses < ActiveRecord::Migration def change add_index :email_addresses, [:email, :person_id], :unique => true end end
chuckmersereau/api_practice
spec/acceptance/api/v2/appeals/appeal_contacts_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/acceptance/api/v2/appeals/appeal_contacts_spec.rb require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Appeals > AppealContacts' do include_context :json_headers documentation_scope = :appeals_api_appeal_contacts let(:resource_type) { 'appeal_contacts' } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:appeal) { create(:appeal, account_list: account_list) } let(:appeal_id) { appeal.id } let!(:contact) { create(:contact, account_list: account_list) } let!(:new_contact) { create(:contact, account_list: account_list) } let!(:appeal_contact) { create(:appeal_contact, appeal: appeal, contact: contact) } let(:id) { appeal_contact.id } let(:resource_attributes) do %w( created_at updated_at updated_in_db_at ) end let(:resource_associations) do %w( contact appeal ) end context 'authorized user' do before do api_login(user) end get '/api/v2/appeals/:appeal_id/appeal_contacts' do with_options scope: :filter do parameter 'account_list_id', 'Account List ID', type: 'String' parameter 'pledged_to_appeal', 'has contact has pledged to appeal? Accepts value "true" or "false"', required: false, type: 'String' end with_options scope: :sort do parameter 'contact.name', 'Sort by Contact Name', type: 'String' end response_field 'data', 'Data', type: 'Array[Object]' example 'AppealContact [LIST]', document: documentation_scope do explanation 'List of Contacts associated to the Appeal' do_request check_collection_resource(1, %w(relationships)) expect(response_status).to eq 200 end end post 'api/v2/appeals/:appeal_id/appeal_contacts' do let(:relationships) do { contact: { data: { type: 'contacts', id: new_contact.id } } } end let!(:form_data) { build_data(attributes_for(:appeal_contact, appeal: appeal), relationships: relationships) } example 'AppealContact [POST]', document: documentation_scope do explanation 'Add a contact to an Appeal' do_request data: form_data check_resource(%w(relationships)) expect(response_status).to eq 200 end end get '/api/v2/appeals/:appeal_id/appeal_contacts/:id' do with_options scope: [:data, :attributes] do end example 'AppealContact [GET]', document: documentation_scope do explanation 'The Appeal Contact with the given ID' do_request check_resource(%w(relationships)) expect(response_status).to eq 200 end end delete '/api/v2/appeals/:appeal_id/appeal_contacts/:id' do parameter 'id', 'ID', required: true example 'AppealContact [DELETE]', document: documentation_scope do explanation 'Remove the Contact with the given ID from the Appeal' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
config/initializers/strong_migrations.rb
StrongMigrations.start_after = 20180710220521
chuckmersereau/api_practice
spec/workers/admin/account_list_reset_worker_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe Admin::AccountListResetWorker do let!(:user) { create(:user_with_account) } let!(:admin_user) { create(:admin_user) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:reset_log) { Admin::ResetLog.create!(resetted_user: user, admin_resetting: admin_user, reason: "Because I'm writing a spec!") } before do create(:user_with_account) user.update(default_account_list: account_list.id) end subject do Admin::AccountListResetWorker.new.perform(account_list.id, user.id, reset_log.id) end context 'user has multiple account lists' do before do create(:organization_account, person: user) user.reload expect(user.account_lists.size).to eq(2) end describe '#perform' do it 'authorizes the reset' do expect_any_instance_of(PunditAuthorizer).to receive(:authorize_on).with('create') expect do expect(subject).to eq(true) end.to change { AccountList.count }.by(-1) end it 'does not destroy the account_list if the admin is not an admin' do reset_log.update(admin_resetting: create(:user)) reset_log.reload expect(AccountList::Destroyer).to_not receive(:new).with('create') expect do expect(subject).to eq(false) end.to_not change { AccountList.count } end it 'continues with the reset if the account_list was already destroyed' do account_list.unsafe_destroy expect do expect(subject).to eq(true) end.to_not change { AccountList.count } end it 'does not reset if the user is not found' do user.delete expect do expect(subject).to eq(false) end.to_not change { AccountList.count } end it 'does not reset if the reset_log is not found' do reset_log.delete expect do expect(subject).to eq(false) end.to_not change { AccountList.count } end it 'deletes the account_list' do account_list_id = account_list.id expect do expect(subject).to eq(true) end.to change { AccountList.where(id: account_list_id).count }.from(1).to(0) .and change { AccountList.count }.from(4).to(3) end it 'imports the profiles' do organization_account_double = instance_double('Person::OrganizationAccount', queue_import_data: nil, import_profiles: nil) expect_any_instance_of(User).to receive(:organization_accounts).once.and_return([organization_account_double]) expect_any_instance_of(Admin::AccountListResetWorker).to receive(:queue_import_organization_data).once expect(organization_account_double).to receive(:import_profiles) subject end it 'queues a data sync' do number_of_times_called = 0 allow_any_instance_of(Person::OrganizationAccount).to( receive(:queue_import_data) { number_of_times_called += 1 } ) subject expect(number_of_times_called).to eq(user.organization_accounts.size) expect(user.organization_accounts.size).to eq(2) end it 'logs the complete time' do time = Time.current travel_to time do expect { subject }.to change { reset_log.reload.completed_at&.to_i }.from(nil).to(time.to_i) end end it 'updates the default_account_list' do expect { subject }.to change { user.reload.default_account_list }.from(account_list.id) expect(user.account_lists.ids).to include(user.default_account_list) end it 'resets the organization account last_download so that all donations are reimported' do organization_accounts = account_list.organization_accounts organization_accounts.first.update(last_download: 1.day.ago) original_time = organization_accounts.first.reload.last_download organization_accounts.second.update(last_download: original_time) expect { subject }.to change { organization_accounts.first.reload.last_download }.from(original_time).to(nil) .and change { organization_accounts.second.reload.last_download }.from(original_time).to(nil) end end end context 'user has only one account list' do before do expect(user.account_lists.size).to eq(1) end context 'user has no organization account' do before do user.organization_accounts.delete_all user.reload expect(user.organization_accounts.size).to eq(0) end it 'updates the default_account_list' do expect { subject }.to change { user.reload.default_account_list }.from(account_list.id).to(nil) end end context 'user has an organization account' do let(:org_account_double_class) do Class.new do def initialize(user) @user = user end def new_account_list @new_account_list = FactoryBot.create(:account_list) end def import_profiles @user.account_lists << @new_account_list end def queue_import_data end end end let(:org_account_double) { org_account_double_class.new(user) } let(:new_account_list) { org_account_double.new_account_list } before do expect(user.organization_accounts.size).to eq(1) expect_any_instance_of(Admin::AccountListResetWorker).to receive(:queue_import_organization_data) expect_any_instance_of(User).to receive(:organization_accounts).once.and_return([org_account_double]) end it 'updates the default_account_list' do expect { subject }.to change { user.reload.default_account_list }.from(account_list.id).to(new_account_list.id) end end end end
chuckmersereau/api_practice
app/services/tnt_import/contact_tags_loader.rb
class TntImport::ContactTagsLoader def initialize(xml) @xml = xml end def tags_by_tnt_contact_id return {} if @xml&.tables&.dig('Contact').blank? tags_grouped_by_id = {} @xml.tables['Contact'].each do |row| tags_grouped_by_id[row['id']] = extract_tags_from_contact_row(row) end tags_grouped_by_id end private def user_names_grouped_by_id @user_names_grouped_by_id ||= @xml.tables['User']&.each_with_object({}) do |row, group| group[row['id']] = row['UserName'] end || {} end def extract_tags_from_contact_row(row) extract_userfield_tags_from_contact_row(row) + extract_fundrep_tags_from_contact_row(row) end # In TNT a user can assign another user with shared access to an account as the "responsible" fund developer for a contact. # Convert the FundRepId to a user name and apply that as a tag. def extract_fundrep_tags_from_contact_row(row) user_id = row['FundRepID'] user_name = user_names_grouped_by_id[user_id] return [] if user_name.blank? ["#{_('Fund Rep')} - #{user_name}"] end # Convert User Fields into tags. User Fields are custom fields inside TNT, they consist of a custom label and a custom value. # Version 3.2 supports up to 8 User Fields: User1, User2, User3, etc. def extract_userfield_tags_from_contact_row(row) userfield_labels_and_values = (1..8).collect do |number| [display_label_for_userfield_number(number), row["User#{number}"]] end userfield_labels_and_values.reject! { |label_and_value| label_and_value[1].blank? } userfield_labels_and_values.collect { |label_and_value| label_and_value.select(&:present?).join(' - ') } end def display_label_for_userfield_number(number) return unless @xml.tables['Property'] @xml.tables['Property'].detect do |property| property['PropName'] == "User#{number}DisplayLabel" end&.[]('PropValue') end end
chuckmersereau/api_practice
config/initializers/shared_date_constants.rb
SHARED_DATE_CONSTANTS = { 'DEFAULT_MONTHLY_LOSSES_COUNT' => 13 }.freeze
chuckmersereau/api_practice
spec/mailers/mail_chimp_mailer_spec.rb
<gh_stars>0 require 'rails_helper' describe MailChimpMailer do let(:user) { create(:user_with_account, email: '<EMAIL>') } let(:account_list) { user.account_lists.first } describe '#invalid_email_addresses' do let(:email) { '<EMAIL>' } let(:contact1) { create(:contact_with_person, account_list: account_list) } let(:contact2) { create(:contact_with_person, account_list: account_list) } let(:emails_with_person_ids) { { email => [contact1.primary_person.id, contact2.primary_person.id] } } subject { described_class.invalid_email_addresses(account_list, user, emails_with_person_ids) } before do contact1.primary_person.update(email: email) contact2.primary_person.update(email: email) end it 'renders the mail' do expect(subject.to).to eq([user.email_address]) expect(subject.body.raw_source).to include("https://mpdx.org/contacts/#{contact1.id}") expect(subject.body.raw_source).to include("https://mpdx.org/contacts/#{contact2.id}") end end end
chuckmersereau/api_practice
db/migrate/20150327115920_create_pls_accounts.rb
class CreatePlsAccounts < ActiveRecord::Migration def change create_table :pls_accounts do |t| t.integer :account_list_id t.string :oauth2_token t.boolean :valid_token, default: true, nil: false t.timestamps null: false end add_index :pls_accounts, :account_list_id add_column :contacts, :pls_id, :string end end
chuckmersereau/api_practice
spec/acceptance/api/v2/account_lists/notification_preferences_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Account Lists > Notification Preferences' do include_context :json_headers documentation_scope = :account_lists_api_notification_preferences let(:resource_type) { 'notification_preferences' } let(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:notification_preferences) do [ create(:notification_preference, account_list_id: account_list.id, email: true, task: true, notification_type_id: notification_type.id, user_id: user.id), create(:notification_preference, account_list_id: account_list.id, email: true, task: true, notification_type_id: notification_type_1.id, user_id: user.id) ] end let(:notification_preference) { notification_preferences.first } let(:id) { notification_preference.id } let(:notification_type) { create(:notification_type) } let(:notification_type_1) { create(:notification_type) } let(:notification_type_2) { create(:notification_type) } let(:form_data) do build_data(attributes, relationships: relationships) end let(:relationships) do { notification_type: { data: { type: 'notification_types', id: notification_type_2.id } } } end # This is the reference data used to create/update a resource. # specify the `attributes` specifically in your request actions below. # let(:form_data) { build_data(attributes) } # List your expected resource keys vertically here (alphabetical please!) let(:resource_attributes) do %w( email task created_at type updated_at updated_in_db_at ) end let(:additional_attribute_keys) do %w( relationships ) end let(:resource_associations) do %w( account_list notification_type ) end context 'authorized user' do before { api_login(user) } get '/api/v2/account_lists/:account_list_id/notification_preferences' do parameter 'account_list_id', 'Account List ID', required: true response_field 'data', 'List of Notification Preferences', type: 'Array[Object]' example 'Notification Preference [LIST]', document: documentation_scope do explanation 'List of Notification Preferences' do_request expect(response_status).to eq 200 end end get '/api/v2/account_lists/:account_list_id/notification_preferences/:id' do with_options scope: [:data, :attributes] do response_field 'task', 'Create Task', type: 'Boolean' response_field 'email', 'Send an Email', type: 'Boolean' response_field 'created_at', 'Created At', type: 'String' response_field 'type', 'Notification Type', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end example 'Notification Preference [GET]', document: documentation_scope do explanation 'The Notification Preference for the given ID' do_request expect(response_status).to eq 200 end end post '/api/v2/account_lists/:account_list_id/notification_preferences' do with_options scope: [:data, :attributes] do parameter 'task', 'Create Task', type: 'String' parameter 'email', 'Send an Email', type: 'String' parameter 'updated_in_db_at', 'Updated In Db At', type: 'String' end let(:attributes) do { task: true, email: true } end example 'Notification Preference [CREATE]', document: documentation_scope do explanation 'Create Notification Preference' do_request data: form_data expect(response_status).to eq 201 end end delete '/api/v2/account_lists/:account_list_id/notification_preferences/:id' do parameter 'account_list_id', 'Account List ID', required: true parameter 'id', 'ID', required: true example 'Notification Preference [DELETE]', document: documentation_scope do explanation 'Delete Notification Preference' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
spec/workers/sidekiq_cron_worker_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/workers/sidekiq_cron_worker_spec.rb require 'rails_helper' describe SidekiqCronWorker do class TestJob end it 'calls the specified static method' do expect(TestJob).to receive(:test) SidekiqCronWorker.new.perform('TestJob.test') end end
chuckmersereau/api_practice
db/migrate/20150309205439_add_lat_long_master_address.rb
class AddLatLongMasterAddress < ActiveRecord::Migration def change add_column :master_addresses, :latitude, :string add_column :master_addresses, :longitude, :string end end
chuckmersereau/api_practice
spec/services/contact/filter/referrer_spec.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 require 'rails_helper' RSpec.describe Contact::Filter::Referrer do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact_one) { create(:contact, account_list_id: account_list.id) } let!(:contact_two) { create(:contact, account_list_id: account_list.id) } let!(:contact_three) { create(:contact, account_list_id: account_list.id) } let!(:contact_four) { create(:contact, account_list_id: account_list.id) } before do ContactReferral.create! referred_by: contact_one, referred_to: contact_two end describe '#config' do it 'returns expected config' do options = [{ name: '-- Any --', id: '', placeholder: 'None' }, { name: '-- None --', id: 'none' }, { name: '-- Has referrer --', id: 'any' }, { name: contact_one.name, id: contact_one.id }] expect(described_class.config([account_list])).to include(multiple: true, name: :referrer, options: options, parent: nil, title: 'Referrer', type: 'multiselect', default_selection: '') end end describe '#query' do let(:contacts) { Contact.all } context 'no filter params' do it 'returns nil' do expect(described_class.query(contacts, {}, nil)).to eq(nil) expect(described_class.query(contacts, { referrer: {} }, nil)).to eq(nil) expect(described_class.query(contacts, { referrer: [] }, nil)).to eq(nil) end end context 'filter by no referrer' do it 'returns only contacts that have no referrer' do result = described_class.query(contacts, { referrer: 'none' }, nil).to_a expect(result).to match_array [contact_one, contact_three, contact_four] end end context 'filter by any referrer' do it 'returns only contacts that have a referrer' do result = described_class.query(contacts, { referrer: 'any' }, nil).to_a expect(result).to eq [contact_two] end end context 'filter by referrer' do it 'filters multiple referrers' do result = described_class.query(contacts, { referrer: "#{contact_one.id}, #{contact_one.id}" }, nil).to_a expect(result).to eq [contact_two] end it 'filters a single referrer' do result = described_class.query(contacts, { referrer: contact_one.id.to_s }, nil).to_a expect(result).to eq [contact_two] end end context 'multiple filters' do it 'returns contacts matching multiple filters' do result = described_class.query(contacts, { referrer: "#{contact_one.id}, none" }, nil).to_a expect(result).to match_array [contact_one, contact_two, contact_three, contact_four] end end end end
chuckmersereau/api_practice
app/services/mail_chimp/batch_results.rb
<reponame>chuckmersereau/api_practice<filename>app/services/mail_chimp/batch_results.rb<gh_stars>0 require 'rubygems/package' # This class is used to check if there were any sync failures and email the user about them class MailChimp::BatchResults attr_reader :mail_chimp_account, :account_list def initialize(mail_chimp_account) @mail_chimp_account = mail_chimp_account @account_list = mail_chimp_account.account_list end def check_batch(batch_id) MailChimp::ConnectionHandler.new(mail_chimp_account) .call_mail_chimp(self, :check_batch!, batch_id, require_primary: false) end private def check_batch!(batch_id) batch_details = load_batch(batch_id) batch_has_finished?(batch_details) return if batch_details['errored_operations'].to_i.zero? operations = load_batch_json(batch_details['response_body_url']) # we currently only know how to respond to 400 responses errored_operations = operations.select { |op| op['status_code'] == 400 } emails_with_person_ids = errored_operations.each_with_object({}) do |operation, hash| email, people = process_failed_op(operation) hash[email] = people if people&.any? end send_email(emails_with_person_ids) end def batch_has_finished?(batch_details) raise LowerRetryWorker::RetryJobButNoRollbarError, 'batch not finished' unless batch_details['status'] == 'finished' end def load_batch(batch_id) gibbon.batches(batch_id).retrieve end def gibbon wrapper.gibbon end def wrapper @wrapper ||= MailChimp::GibbonWrapper.new(mail_chimp_account) end def load_batch_json(url) file = read_first_file_from_tar(url) JSON.parse(file) if file end def zip_reader(url) Zlib::GzipReader.new(Kernel.open(url)) end def read_first_file_from_tar(url) gz = zip_reader(url) Gem::Package::TarReader.new(gz) do |tar| tar.each { |entry| return entry.read if entry.file? } end end def process_failed_op(operation) detail = JSON.parse(operation['response'])['detail'] return invalid_email(detail) if matches_invalid(detail) || matches_cleaned(detail) unknown_failure(detail) end def matches_invalid(detail) detail.match?(/ looks fake or invalid, please enter a real email address.$/) end def matches_cleaned(detail) compliance_message = ' is in a compliance state due to unsubscribe, bounce, '\ 'or compliance review and cannot be subscribed.' return false unless detail.match?(/#{compliance_message}$/) status = wrapper.list_member_info(@mail_chimp_account.primary_list_id, extract_email(detail)).dig(0, 'status') status == 'cleaned' rescue Gibbon::MailChimpError false end def extract_email(detail) detail.split(' ', 2)[0] end def unknown_failure(detail) email, message = detail.split(' ', 2) Rollbar.info(UncaughtMailchimpSubFailure.new(message), email: email, mail_chimp_account_id: @mail_chimp_account.id) end def invalid_email(detail) email = extract_email(detail) person_ids = account_list.people.joins(:primary_email_address).where(email_addresses: { email: email }).ids EmailAddress.where(person_id: person_ids, email: email).find_each { |e| e.update(historic: true) } [email, person_ids] end def send_email(emails_with_person_ids) return unless emails_with_person_ids.any? account_list.users.each do |user| MailChimpMailer.delay.invalid_email_addresses(account_list, user, emails_with_person_ids) end end class UncaughtMailchimpSubFailure < StandardError; end end
chuckmersereau/api_practice
db/migrate/20170529000340_update_person_websites_url_length.rb
class UpdatePersonWebsitesUrlLength < ActiveRecord::Migration def change change_column :person_websites, :url, :text end end
chuckmersereau/api_practice
db/migrate/20120309135317_create_company_positions.rb
class CreateCompanyPositions < ActiveRecord::Migration def change create_table :company_positions do |t| t.belongs_to :person, null: false t.belongs_to :company, null: false t.date :start_date t.date :end_date t.string :position t.timestamps null: false end add_index :company_positions, :person_id add_index :company_positions, :company_id add_index :company_positions, :start_date end end
chuckmersereau/api_practice
spec/lib/json_api_service/validator_spec.rb
<gh_stars>0 require 'spec_helper' require 'json_api_service/validator' require 'json_api_service/errors' require 'json_api_service/configuration' require 'support/json_api_service_helper' module JsonApiService RSpec.describe Validator, type: :service do include JsonApiServiceHelpers let(:configuration) do Configuration.new.tap do |config| config.ignored_foreign_keys = { users: [:remote_id] } end end let(:validator) do Validator.new( params: params, configuration: configuration, context: controller ) end describe '#initialize' do let(:params) { double(:params) } let(:controller) { double(:controller) } it 'initializes with params and with a controller instance for context' do expect(validator.params).to eq params expect(validator.context).to eq controller end end describe '#validate!' do context 'with a primary id in #attributes' do let(:controller) { double(:controller, resource_type: 'users') } context 'on a POST' do let(:params) do params = { data: { type: 'users', attributes: { id: 'abc123' } }, action: 'create' } build_params_with(params) end it 'raises an error' do message = invalid_primary_key_placement('/data/attributes/id', '/data/id') expect { validator.validate! } .to raise_error(InvalidPrimaryKeyPlacementError) .with_message(message) end end end context 'with a primary id in nested #attributes' do let(:controller) { double(:controller, resource_type: 'users') } context 'on a POST' do let(:params) do params = { data: { type: 'users', relationships: { people: { data: [ { type: 'people', relationships: { email_addresses: { data: [ { type: 'email_addresses', attributes: { id: 'abc123', # invalid placement email: '<EMAIL>' } } ] } } } ] } } }, action: 'create' } build_params_with(params) end it 'raises an error' do message = invalid_primary_key_placement( '/data/relationships/people/data/0/relationships/email_addresses/data/0/attributes/id', '/data/relationships/people/data/0/relationships/email_addresses/data/0/id' ) expect { validator.validate! } .to raise_error(InvalidPrimaryKeyPlacementError) .with_message(message) end end end context 'with an invalid resource_type' do let(:controller) { double(:controller, resource_type: 'users') } context 'on a POST' do let(:params) do params = { data: { type: 'contacts' }, action: 'create' } build_params_with(params) end it 'raises an error' do expect { validator.validate! } .to raise_error(InvalidTypeError) .with_message("'contacts' is not a valid resource type for this endpoint. Expected 'users' instead") end end context 'on a PATCH' do let(:params) do params = { data: { type: 'contacts' }, action: 'update' } build_params_with(params) end it 'raises an error' do expect { validator.validate! } .to raise_error(InvalidTypeError) .with_message("'contacts' is not a valid resource type for this endpoint. Expected 'users' instead") end end end context 'with an missing resource_type' do let(:controller) { double(:controller, resource_type: 'users') } context 'on an INDEX' do let(:params) do params = { data: { type: nil # missing }, action: 'index' } build_params_with(params) end it "doesn't raise an error" do expect { validator.validate! }.not_to raise_error end end context 'on a POST' do let(:params) do params = { data: { type: nil # missing }, action: 'create' } build_params_with(params) end it 'raises an error' do message = missing_type_error('/data/type') expect { validator.validate! } .to raise_error(MissingTypeError) .with_message(message) end end context 'on a PATCH' do let(:params) do params = { data: { type: nil # missing }, action: 'update' } build_params_with(params) end it 'raises an error' do message = missing_type_error('/data/type') expect { validator.validate! } .to raise_error(MissingTypeError) .with_message(message) end end end context 'with an missing resource_type in a relationship object' do let(:controller) { double(:controller, resource_type: 'users') } context 'on an INDEX' do let(:params) do params = { data: { type: 'users', relationships: { account_list: { data: { type: nil # missing } }, addresses: { data: [ { type: nil # missing } ] } } }, action: 'index' } build_params_with(params) end it "doesn't raise an error" do expect { validator.validate! }.not_to raise_error end end context 'with a foreign_key relationship' do context 'on a POST' do let(:params) do params = { data: { type: 'users', relationships: { account_list: { data: { type: nil # missing } } } }, action: 'create' } build_params_with(params) end it 'raises an error' do message = missing_type_error('/data/relationships/account_list/data/type') expect { validator.validate! } .to raise_error(MissingTypeError) .with_message(message) end end context 'on a PATCH' do let(:params) do params = { data: { type: 'users', relationships: { account_list: { data: { type: nil # missing } } } }, action: 'update' } build_params_with(params) end it 'raises an error' do message = missing_type_error('/data/relationships/account_list/data/type') expect { validator.validate! } .to raise_error(MissingTypeError) .with_message(message) end end end context 'with a nested relationship' do context 'on a POST' do let(:params) do params = { data: { type: 'users', relationships: { people: { data: [ { type: 'people', relationships: { email_addresses: { data: [ { type: nil, # missing email: '<EMAIL>' } ] } } } ] } } }, action: 'create' } build_params_with(params) end it 'raises an error' do message = missing_type_error('/data/relationships/people/data/0/'\ 'relationships/email_addresses/data/0/type') expect { validator.validate! } .to raise_error(MissingTypeError) .with_message(message) end end context 'on a PATCH' do let(:params) do params = { data: { type: 'users', relationships: { people: { data: [ { type: 'people', relationships: { email_addresses: { data: [ { type: nil, # missing attributes: { email: '<EMAIL>' } } ] } } } ] } } }, action: 'update' } build_params_with(params) end it 'raises an error' do message = missing_type_error('/data/relationships/people/data/0/'\ 'relationships/email_addresses/data/0/type') expect { validator.validate! } .to raise_error(MissingTypeError) .with_message(message) end end end context "with a foreign_key in the object's #attributes" do context 'on a POST (and with nested resources)' do let(:params) do params = { data: { type: 'users', relationships: { people: { data: [ { type: 'people', relationships: { email_addresses: { data: [ { type: 'email-addresses', attributes: { email: '<EMAIL>', account_list_id: 10 } } ] } } } ] } } }, action: 'create' } build_params_with(params) end it 'raises an error' do message = foreign_key_error('/data/relationships/people/data/0/relationships/'\ 'email_addresses/data/0/attributes/account_list_id') expect { validator.validate! } .to raise_error(ForeignKeyPresentError) .with_message(message) end end context 'on a PATCH' do let(:params) do params = { data: { type: 'users', attributes: { account_list_id: 5 } }, action: 'update' } build_params_with(params) end it 'raises an error' do message = foreign_key_error('/data/attributes/account_list_id') expect { validator.validate! } .to raise_error(ForeignKeyPresentError) .with_message(message) end end context 'when a foreign_key attribute is configured to be ignored' do let(:params) do params = { data: { type: 'users', attributes: { remote_id: 'abc123' } }, action: 'update' } build_params_with(params) end it 'raises an error' do expect { validator.validate! }.not_to raise_error end end end end end context 'with invalid includes' do let(:controller) { double(:controller, resource_type: 'contacts') } context 'with a missing type' do let(:params) do params = { included: [ { type: 'comments', id: 'id-comments-1' }, { type: nil, # missing id: 'id-missing-type' } ], data: { type: 'contacts', id: 'id-contacts-1' }, action: 'create' } build_params_with(params) end it 'raises an error' do message = missing_type_error('/included/1/type') expect { validator.validate! } .to raise_error(MissingTypeError) .with_message(message) end end context 'with a foreign key' do let(:params) do params = { included: [ { type: 'comments', id: 'id-comments-1' }, { type: 'addresses', id: 'id-addresses-1', attributes: { contact_id: 'id-contacts-1' } } ], data: { type: 'contacts', id: 'id-contacts-1' }, action: 'create' } build_params_with(params) end it 'raises an error' do message = foreign_key_error('/included/1/attributes/contact_id') expect { validator.validate! } .to raise_error(ForeignKeyPresentError) .with_message(message) end end end def foreign_key_error(pointer_ref) 'Foreign keys SHOULD NOT be referenced in the #attributes '\ "of a JSONAPI resource object. Reference: #{pointer_ref}" end def missing_type_error(pointer_ref) 'JSONAPI resource objects MUST contain a `type` top-level member of its hash for POST and '\ "PATCH requests. Expected to find a `type` member at #{pointer_ref}" end def invalid_primary_key_placement(actual_pointer_ref, expected_pointer_ref) [ 'A primary key, if sent in a request, CANNOT be referenced', 'in the #attributes of a JSONAPI resource object.', "It must instead be sent as a top level member of the resource's `data` object.", "Reference: `#{actual_pointer_ref}`. Expected `#{expected_pointer_ref}`" ].join(' ') end end end
chuckmersereau/api_practice
config/initializers/cloudinary.rb
<gh_stars>0 Cloudinary.config do |config| config.cloud_name = ENV.fetch('CLOUDINARY_CLOUD_NAME') config.api_key = ENV.fetch('CLOUDINARY_API_KEY') config.api_secret = ENV.fetch('CLOUDINARY_API_SECRET') config.secure = true end
chuckmersereau/api_practice
app/models/notification_type/special_gift.rb
<gh_stars>0 class NotificationType::SpecialGift < NotificationType def check_contacts_filter(contacts) contacts.non_financial_partners end def check_for_donation_to_notify(contact) contact.donations.where('donation_date > ?', 1.month.ago).last end def task_description_template(notification = nil) if notification&.account_list&.designation_accounts&.many? _('%{contact_name} gave a Special Gift of %{amount} on %{date} to %{designation}. Send them a Thank You.') else _('%{contact_name} gave a Special Gift of %{amount} on %{date}. Send them a Thank You.') end end end
chuckmersereau/api_practice
spec/workers/currency_rates_fetcher_worker_spec.rb
require 'rails_helper' describe CurrencyRatesFetcherWorker do before { ENV['CURRENCY_LAYER_KEY'] = 'asdf' } around do |example| travel_to Date.new(2015, 9, 15) do example.run end end it 'imports todays rates if they are missing' do create(:currency_rate, exchanged_on: Date.new(2015, 9, 14)) stub_live_rates_success expect do subject.perform end.to change(CurrencyRate, :count).by(2) eur = CurrencyRate.find_by(code: 'CHF') expect(eur.exchanged_on).to eq Date.new(2015, 9, 15) expect(eur.source).to eq 'currencylayer' expect(eur.rate.to_f).to eq(0.97535) jpy = CurrencyRate.find_by(code: 'JPY') expect(jpy.rate.to_f).to eq(120.445007) end it 'imports multiple previous days rates if missing' do create(:currency_rate, exchanged_on: Date.new(2015, 9, 13)) stub_live_rates_success stub_historical_rates(Date.new(2015, 9, 14)) expect { subject.perform }.to change(CurrencyRate, :count).by(4) chf1 = CurrencyRate.find_by(exchanged_on: Date.new(2015, 9, 15), code: 'CHF') chf2 = CurrencyRate.find_by(exchanged_on: Date.new(2015, 9, 14), code: 'CHF') expect(chf1.rate.to_f).to eq(0.97535) expect(chf2.rate.to_f).to eq(0.96782) end it 'fails if currency layer api call fails' do create(:currency_rate, exchanged_on: Date.current - 1) stub_live_rates(body: { success: false }.to_json) expect { subject.perform }.to raise_error(/failed/) end it 'loads a maximium of the 30 previous days' do stub_live_rates_success create(:currency_rate, exchanged_on: Date.current - 31) 31.times { |i| stub_historical_rates(Date.current - i) } expect { subject.perform }.to change(CurrencyRate, :count).by(60) end it 'imports the past 30 days if there are no rates stored' do stub_live_rates_success 30.times { |i| stub_historical_rates(Date.current - i) } expect { subject.perform }.to change(CurrencyRate, :count).by(60) end def stub_live_rates_success stub_live_rates(body: { success: true, source: 'USD', quotes: { 'USDCHF' => 0.97535, 'USDJPY' => 120.445007 } }.to_json) end def stub_live_rates(stub_to_return) stub_request(:get, 'http://apilayer.net/api/live?access_key=asdf') .to_return(stub_to_return) end def stub_historical_rates(date) historical_rates = { success: true, source: 'USD', quotes: { 'USDCHF' => 0.96782, 'USDJPY' => 119.962502 } } url = "http://apilayer.net/api/historical?access_key=asdf&date=#{date.strftime('%Y-%m-%d')}" stub_request(:get, url).to_return(body: historical_rates.to_json) end end
chuckmersereau/api_practice
app/services/appeal_contact/filter/base.rb
class AppealContact::Filter::Base < ApplicationFilter end
chuckmersereau/api_practice
app/controllers/api/v2/contacts/people/twitter_accounts_controller.rb
<filename>app/controllers/api/v2/contacts/people/twitter_accounts_controller.rb class Api::V2::Contacts::People::TwitterAccountsController < Api::V2Controller def index authorize load_person, :show? load_twitter_accounts render json: @twitter_accounts.preload_valid_associations(include_associations), meta: meta_hash(@twitter_accounts), include: include_params, fields: field_params end def show load_twitter_account authorize_twitter_account render_twitter_account end def create persist_twitter_account end def update load_twitter_account authorize_twitter_account persist_twitter_account end def destroy load_twitter_account authorize_twitter_account destroy_twitter_account end private def destroy_twitter_account @twitter_account.destroy head :no_content end def load_twitter_accounts @twitter_accounts = twitter_account_scope.where(filter_params) .reorder(sorting_param) .page(page_number_param) .per(per_page_param) end def load_twitter_account @twitter_account ||= twitter_account_scope.find(params[:id]) end def authorize_twitter_account authorize @twitter_account end def render_twitter_account render json: @twitter_account, status: success_status, include: include_params, fields: field_params end def persist_twitter_account build_twitter_account authorize_twitter_account if save_twitter_account render_twitter_account else render_with_resource_errors(@twitter_account) end end def build_twitter_account @twitter_account ||= twitter_account_scope.build @twitter_account.assign_attributes(twitter_account_params) end def save_twitter_account @twitter_account.save(context: persistence_context) end def twitter_account_params params.require(:twitter_account).permit(Person::TwitterAccount::PERMITTED_ATTRIBUTES) end def twitter_account_scope load_person.twitter_accounts end def load_person @person ||= load_contact.people.find(params[:person_id]) end def load_contact @contact ||= Contact.find(params[:contact_id]) end def pundit_user action_name == 'index' ? PunditContext.new(current_user, contact: load_contact) : current_user end end
chuckmersereau/api_practice
app/policies/export_log_policy.rb
class ExportLogPolicy < ApplicationPolicy def resource_owner? resource.user == user && resource.active end end
chuckmersereau/api_practice
db/migrate/20160204190056_add_index_to_google_emails_ids.rb
class AddIndexToGoogleEmailsIds < ActiveRecord::Migration self.disable_ddl_transaction! def change add_index :google_emails, [:google_account_id, :google_email_id], algorithm: :concurrently end end
chuckmersereau/api_practice
spec/workers/mail_chimp/export_contacts_worker_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/workers/mail_chimp/export_contacts_worker_spec.rb require 'rails_helper' RSpec.describe MailChimp::ExportContactsWorker do let(:mail_chimp_account) { create(:mail_chimp_account, primary_list_id: 'list_one') } it 'starts the export if the list used is not the primary list' do expect_any_instance_of(MailChimp::Exporter).to receive(:export_contacts).with([1], true) MailChimp::ExportContactsWorker.new.perform(mail_chimp_account.id, 'list_two', [1], true) end end
chuckmersereau/api_practice
app/mailers/import_mailer.rb
<reponame>chuckmersereau/api_practice<filename>app/mailers/import_mailer.rb class ImportMailer < ApplicationMailer layout 'inky' def success(import, successes = nil) user = import.user return unless user&.email @import = import @successes = successes I18n.locale = user.locale || 'en' subject = _('[MPDX] Importing your %{source} contacts completed') mail(to: user.email, subject: format(subject, source: import.user_friendly_source)) end def failed(import, successes = nil, failures = nil) user = import.user return unless user&.email @import = import @successes = successes @failures = failures I18n.locale = user.locale || 'en' @explanation = failure_explanation attachments[failure_attachment_filename] = failure_attachment if failure_attachment.present? subject = _('[MPDX] Importing your %{source} contacts failed') mail(to: user.email, subject: format(subject, source: import.user_friendly_source)) end def credentials_error(account) user = account.person return unless user&.email @account = account subject = _('[MPDX] Your credentials for %{source} are invalid') mail(to: user.email, subject: format(subject, source: account.organization.name)) end private def failure_explanation case @import.source when 'tnt', 'tnt_data_sync' _('There are a number of reasons an import can fail. The most common reason is a temporary '\ 'server issue. Please try your import again. If it fails again, send an email to <EMAIL> '\ "with your Tnt export attached. Having the file you're trying to import will greatly "\ 'help us in trying to determine why the import failed.') when 'csv' _('There are a number of reasons an import can fail. The most likely reason for a CSV import '\ 'to fail is due to First Name. First Name is a required field on CSV import. We have attached '\ 'a CSV file to this email containing the rows that failed to import. The first column in this '\ 'CSV contains an error message about that row. Please download this CSV, fix the issues '\ 'inside it, and then try to import it again. You do not need to reimport the contacts that '\ 'were successfully imported previously. If it fails again, send us an email at <EMAIL> '\ 'and we will investigate what went wrong.') when 'facebook' _('There are a number of reasons an import can fail. Often the failure is a temporary issue '\ 'with Facebook that is outside of our control. Please try your import again. '\ 'If it fails again, send us an email at <EMAIL> and we will investigate what went wrong.') else _('There are a number of reasons an import can fail. Often the failure '\ 'can be a temporary network issue. Please try your import again. '\ 'If it fails again, send us an email at <EMAIL> and we will investigate what went wrong.') end end def failure_attachment return unless @import.source_csv? && @import.file_row_failures.present? @failure_attachment ||= CsvImport.new(@import).generate_csv_from_file_row_failures end def failure_attachment_filename return unless @import.source_csv? 'MPDX Import Failures.csv' end end
chuckmersereau/api_practice
spec/models/notification_type/long_time_frame_gift_spec.rb
<gh_stars>0 require 'rails_helper' describe NotificationType::LongTimeFrameGift do let!(:long_time_frame_gift) { NotificationType::LongTimeFrameGift.first_or_initialize } let!(:da) { create(:designation_account) } let!(:account_list) { create(:account_list) } let!(:contact) { create(:contact, name: '<NAME>', account_list: account_list, pledge_amount: 9.99, pledge_frequency: 12) } let!(:donor_account) { create(:donor_account) } let!(:donation) { create(:donation, donor_account: donor_account, designation_account: da) } let!(:old_donation) do create(:donation, donor_account: donor_account, designation_account: da, donation_date: Date.today << 12) end before do account_list.account_list_entries.create!(designation_account: da) contact.donor_accounts << donor_account contact.update_donation_totals(old_donation) contact.update_donation_totals(donation) end context '#check' do it 'adds a notification if a gift comes in for a long time frame partner' do expect(long_time_frame_gift.check(account_list).size).to eq(1) end it 'does not add a notification if it was the first gift' do old_donation.destroy! expect(long_time_frame_gift.check(account_list)).to be_empty end it 'does not add a notfication if donation was not equal to the pledge' do donation.update(amount: 5) expect(long_time_frame_gift.check(account_list)).to be_empty end end context '#task_description' do it 'adds the gift frequency in correctly' do donation.update(donation_date: Date.new(2015, 3, 18)) notification = contact.notifications.new(donation: donation) description = '<NAME> gave their Annual gift of R9.99 on March 18, 2015. Send them a Thank You.' expect(long_time_frame_gift.task_description(notification)).to eq(description) end end end
chuckmersereau/api_practice
spec/models/import_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe Import do before(:each) do @tnt_import = double('tnt_import', import: false, xml: { 'Database' => { 'Tables' => [] } }) allow(TntImport).to receive(:new).and_return(@tnt_import) end Import::SOURCES.each do |source| describe "#source_#{source}?" do it "returns true if source is #{source} and false otherwise" do import = build(:import, source: nil) expect { import.source = source }.to change { import.send("source_#{source}?") }.from(false).to(true) end end end describe '#user_friendly_source' do let(:import) { build(:import, in_preview: true) } it 'returns a human readable version of the source for each source' do (Import::SOURCES - %w(csv tnt tnt_data_sync)).each do |source| import.source = source expect(import.user_friendly_source).to eq source.humanize end %w(csv).each do |source| import.source = source expect(import.user_friendly_source).to eq source.upcase end %w(tnt tnt_data_sync).each do |source| import.source = source expect(import.user_friendly_source).to eq source.titleize end end end describe '#file=' do it 'resets local attributes related to the file' do import = create(:csv_import, in_preview: true) import.file_headers = { test: 'test' } import.file_constants = { test: 'test' } import.file_row_samples = [:test] import.file_row_failures = [:test] expect { import.file = File.new(Rails.root.join('spec/fixtures/sample_csv_with_custom_headers.csv')) } .to change { import.file_headers }.to({}) .and change { import.file_constants }.to({}) .and change { import.file_row_samples }.to([]) .and change { import.file_row_failures }.to([]) end end context 'tags' do let(:import) { build(:import, tags: 'a,b,c,d') } describe '#tags' do it 'returns tags as an Array' do expect(import.tags).to be_a Array expect(import.tags).to eq %w(a b c d) end end describe '#tags=' do it 'sets tags from an Array' do import.tags = %w(1 2 3) expect(import.tags).to eq %w(1 2 3) import.save! import.reload expect(import.tags).to eq %w(1 2 3) end it 'accepts nil' do import.tags = nil expect(import.tags).to eq [] end end describe '#tag_list' do it 'returns tags as a comma delimited String' do expect(import.tag_list).to be_a String expect(import.tag_list).to eq 'a,b,c,d' end end describe '#tag_list=' do it 'sets tags from a comma delimited String' do import.tag_list = '1,2,3' expect(import.tag_list).to eq '1,2,3' import.save! import.reload expect(import.tag_list).to eq '1,2,3' end it 'accepts nil' do import.tag_list = nil expect(import.tag_list).to eq '' end end end it "should set 'importing' to false after an import" do import = create(:tnt_import, importing: true) import.send(:import) expect(import.importing).to eq(false) end it 'should send an success email when importing completes then merge contacts and queue google sync' do expect_delayed_email(ImportMailer, :success) import = create(:tnt_import) expect(import.account_list).to receive(:async_merge_contacts) expect(import.account_list).to receive(:queue_sync_with_google_contacts) import.send(:import) end it "should send a failure email if there's an error and not re-raise it" do import = create(:tnt_import) expect(@tnt_import).to receive(:import).and_raise('foo') expect_delayed_email(ImportMailer, :failed) expect(Rollbar).to receive(:error) expect do import.send(:import) end.to_not raise_error end it 'should send a failure error but not re-raise the error if the error is UnsurprisingImportError' do Sidekiq::Testing.inline! import = create(:tnt_import) expect(@tnt_import).to receive(:import).and_raise(Import::UnsurprisingImportError) expect_delayed_email(ImportMailer, :failed) expect(Rollbar).to receive(:info) expect do import.send(:import) end.to_not raise_error end it 'passes an exception on to the callback handler on failure' do Sidekiq::Testing.inline! import = create(:tnt_import) error = StandardError.new expect(@tnt_import).to receive(:import).and_raise(error) expect_any_instance_of(ImportCallbackHandler).to receive(:handle_failure).with(exception: error) import.send(:import) end describe '#queue_import' do it 'queues an import when saved' do expect { create(:import) }.to change(Import.jobs, :size).from(0).to(1) end it 'does not requeue an import that was already queued' do import = build(:import) expect { import.save }.to change(Import.jobs, :size).from(0).to(1) Import.clear expect { import.reload.save }.to_not change(Import.jobs, :size).from(0) end it 'sets queued_for_import_at after queueing the import' do travel_to Time.current do import = build(:import) expect { import.save }.to change { import.queued_for_import_at }.from(nil).to(Time.current) end end it 'does not queue import on destroy' do import = create(:import, in_preview: true) import.update_columns(queued_for_import_at: nil, in_preview: false) expect { import.destroy }.to_not change(Import.jobs, :size) end end it 'should finish import if sending mail fails' do expect(ImportMailer).to receive(:delay).and_raise(StandardError) import = create(:tnt_import) expect(import.account_list).to receive(:async_merge_contacts) expect(import.account_list).to receive(:queue_sync_with_google_contacts) import.send(:import) end context 'in_preview' do it 'does not queue an import' do expect { create(:csv_import, in_preview: true) }.to_not change(Import.jobs, :size).from(0) end it 'does not validate csv headers' do import = build(:csv_import_custom_headers, in_preview: true) expect(import.valid?).to eq true import.in_preview = false expect(import.valid?).to eq false end end it 'validates size of file' do import = build(:import) allow(import.file).to receive(:size).and_return(Import::MAX_FILE_SIZE_IN_BYTES + 1) expect(import.valid?).to eq false expect(import.errors[:file]).to eq ["File size must be less than #{Import::MAX_FILE_SIZE_IN_BYTES} bytes"] end describe '#file_path' do it 'returns the file_path' do import = create(:csv_import, in_preview: true) expect(import.file_path).to eq(import.file.file.file) expect(import.file_path).to end_with('sample_csv_to_import.csv') end it 'returns the file path as a cached file, not a stored file' do import = create(:csv_import, in_preview: true) expect(import.file_path).to_not include(import.file.store_path) expect(import.file_path).to end_with(import.file.cache_name) end it 'caches the stored file' do import = create(:csv_import, in_preview: true) expect_any_instance_of(CarrierWave::Uploader::Base).to receive(:cache_stored_file!) import.file_path end it 'it does not recache file on subsequent calls' do import = create(:csv_import, in_preview: true) import.file_path expect_any_instance_of(CarrierWave::Uploader::Base).to_not receive(:cache_stored_file!) import.file_path end it 'returns nil if there is no file' do expect(Import.new.file_path).to eq nil end end it 'allows no file_constants' do import = create(:csv_import, in_preview: true) import.file_constants = nil import.in_preview = false import.valid? expect(import.errors[:file_constants].present?).to eq(false) end end
chuckmersereau/api_practice
app/serializers/person/organization_account_serializer.rb
class Person::OrganizationAccountSerializer < ApplicationSerializer type :organization_accounts attributes :disable_downloads, :last_download, :locked_at, :remote_id, :username belongs_to :organization belongs_to :person end
chuckmersereau/api_practice
app/serializers/export_log_serializer.rb
class ExportLogSerializer < ApplicationSerializer attributes :export_at, :type, :params belongs_to :user def params JSON.parse(object.params) rescue JSON::ParserError object.params end end
chuckmersereau/api_practice
spec/exhibits/account_list_exhibit_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe AccountListExhibit do subject { AccountListExhibit.new(account_list, context) } let(:account_list) { build(:account_list) } let(:context) do context_double = double(reports_balances_path: '/reports/balances', locale: :en) context_double.extend(LocalizationHelper) context_double.extend(ActionView::Helpers) context_double end let(:user) { create(:user) } context '#to_s' do before do 2.times do account_list.designation_accounts << build(:designation_account) end account_list.users << user end it 'returns a designation account names for to_s' do expect(subject.to_s).to eq(account_list.designation_accounts.map(&:name).join(', ')) end end context '#weeks_on_mpd' do it 'is nil without a start' do account_list.update! active_mpd_start_at: nil expect(subject.weeks_on_mpd).to be_nil end it 'is nil without a finish' do account_list.update! active_mpd_finish_at: nil expect(subject.weeks_on_mpd).to be_nil end it 'is a number' do account_list.update! active_mpd_start_at: 1.week.ago, active_mpd_finish_at: 1.week.from_now expect(subject.weeks_on_mpd).to be_a Numeric end it 'returns the difference in weeks' do account_list.update! active_mpd_start_at: 6.weeks.ago, active_mpd_finish_at: 5.weeks.from_now expect(subject.weeks_on_mpd).to eq 11 end it 'can return fractions of a week' do account_list.update! active_mpd_start_at: 6.weeks.ago, active_mpd_finish_at: 3.days.from_now expect(subject.weeks_on_mpd).to eq(6 + 3.0 / 7) end end context '#last_prayer_letter_at' do let(:date) { 5.weeks.ago } let(:mail_chimp_account) { create(:mail_chimp_account, prayer_letter_last_sent: date) } it 'is nil without a #mail_chimp_account' do account_list.update! mail_chimp_account: nil expect(subject.last_prayer_letter_at).to be_nil end it 'is a date' do account_list.update! mail_chimp_account: mail_chimp_account expect(subject.last_prayer_letter_at).to eq date end end context '#formatted_balance' do let(:org) { create(:organization) } let(:act_1) { create(:designation_account, active: true, balance: 10, organization: org) } let(:act_2) { create(:designation_account, active: true, balance: 99, organization: org) } let(:inact_1) { create(:designation_account, active: false, balance: 50, organization: org) } it 'defaults to $0 with no designation_accounts' do account_list.update! designation_accounts: [] expect(subject.formatted_balance).to eq '$0' end it "is the sum of each active account's balance" do account_list.update! designation_accounts: [act_1, act_2, inact_1], salary_organization: org.id expect(subject.formatted_balance).to eq '$109' end it 'accepts an optional locale' do account_list.update! designation_accounts: [act_1, act_2, inact_1], salary_organization: org.id expect(subject.formatted_balance(locale: :fr)).to eq '109 $' end end end
chuckmersereau/api_practice
spec/controllers/api/v2/reports/monthly_giving_graphs_controller_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe Api::V2::Reports::MonthlyGivingGraphsController, type: :controller do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:response_json) { JSON.parse(response.body).deep_symbolize_keys } let(:resource) do Reports::MonthlyGivingGraph.new(account_list: account_list, locale: 'en') end let(:parent_param) do { filter: { account_list_id: account_list.id, month_range: "#{DateTime.new(2017, 1, 3).utc.iso8601}...#{DateTime.new(2017, 3, 3).utc.iso8601}" } } end let(:correct_attributes) { {} } include_examples 'show_examples', except: [:sparse_fieldsets] describe '#show (for a User::Coach)' do include_context 'common_variables' let(:coach) { create(:user).becomes(User::Coach) } before do account_list.coaches << coach end it 'shows resource to users that are signed in' do api_login(coach) get :show, full_params expect(response.status).to eq(200), invalid_status_detail expect(response_json[:data][:relationships][:account_list][:data][:id]) .to eq account_list.id expect(response.body) .to include(resource.send(reference_key).to_json) if reference_key end it 'does not show resource to users that are not signed in' do get :show, full_params expect(response.status).to eq(401), invalid_status_detail end end describe 'Filters' do let!(:donor_account_1) { create(:donor_account) } let!(:designation_account_1) { create(:designation_account) } let!(:contact_1) { create(:contact, account_list: account_list) } let!(:donations_1) do create_list(:donation, 2, donor_account: donor_account_1, designation_account: designation_account_1, amount: 50.00, donation_date: Date.today) end let!(:donor_account_2) { create(:donor_account) } let!(:designation_account_2) { create(:designation_account) } let!(:contact_2) { create(:contact, account_list: account_list) } let!(:donations_2) do create_list(:donation, 2, donor_account: donor_account_2, designation_account: designation_account_2, amount: 100.00, donation_date: Date.today) end let!(:donor_account_3) { create(:donor_account) } let!(:designation_account_3) { create(:designation_account) } let!(:contact_3) { create(:contact, account_list: account_list) } let!(:donations_3) do create_list(:donation, 2, donor_account: donor_account_3, designation_account: designation_account_3, amount: 150.00, donation_date: Date.today) end before do account_list.designation_accounts << designation_account_1 account_list.designation_accounts << designation_account_2 account_list.designation_accounts << designation_account_3 contact_1.donor_accounts << donor_account_1 contact_2.donor_accounts << donor_account_2 contact_3.donor_accounts << donor_account_3 end it 'allows a user to request all data' do api_login(user) get :show, account_list_id: account_list.id expect(response_json[:data][:attributes][:totals][0][:total_amount]).to eq '600.0' end it 'allows a user to filter by designation_account_id' do api_login(user) get :show, account_list_id: account_list.id, filter: { designation_account_id: designation_account_1.id } expect(response_json[:data][:attributes][:totals][0][:total_amount]).to eq '100.0' end it 'allows a user to filter by multiple designation_account_ids' do api_login(user) get :show, account_list_id: account_list.id, filter: { designation_account_id: "#{designation_account_1.id},#{designation_account_2.id}" } expect(response_json[:data][:attributes][:totals][0][:total_amount]).to eq '300.0' end it 'allows a user to filter by donor_account_id' do api_login(user) get :show, account_list_id: account_list.id, filter: { donor_account_id: donor_account_2.id } expect(response_json[:data][:attributes][:totals][0][:total_amount]).to eq '200.0' end it 'allows a user to filter by multiple donor_account_ids' do api_login(user) get :show, account_list_id: account_list.id, filter: { donor_account_id: "#{donor_account_1.id},#{donor_account_2.id}" } expect(response_json[:data][:attributes][:totals][0][:total_amount]).to eq '300.0' end end end
chuckmersereau/api_practice
db/migrate/20170829212715_add_invite_user_as_to_account_list_invites.rb
class AddInviteUserAsToAccountListInvites < ActiveRecord::Migration def change add_column :account_list_invites, :invite_user_as, :string, default: 'user' end end
chuckmersereau/api_practice
spec/controllers/api/v2/user/google_accounts_controller_spec.rb
<filename>spec/controllers/api/v2/user/google_accounts_controller_spec.rb require 'rails_helper' RSpec.describe Api::V2::User::GoogleAccountsController, type: :controller do let(:user) { create(:user) } let(:factory_type) { :google_account } let!(:resource) { create(:google_account, person: user) } let!(:second_resource) { create(:google_account, person: user) } let(:id) { resource.id } let(:unpermitted_attributes) { nil } let(:correct_attributes) { { email: '<EMAIL>' } } let(:incorrect_attributes) { nil } before do allow_any_instance_of(Person::GoogleAccount).to receive(:contact_groups).and_return( [ Person::GoogleAccount::ContactGroup.new( id: 'contact_group_id_0', title: 'System Group: My Family', created_at: Date.today, updated_at: Date.today ) ] ) end include_examples 'show_examples' include_examples 'update_examples' include_examples 'create_examples' include_examples 'destroy_examples' include_examples 'index_examples' end
chuckmersereau/api_practice
lib/tasks/adobe_campaigns.rake
<reponame>chuckmersereau/api_practice<filename>lib/tasks/adobe_campaigns.rake namespace :adobe_campaigns do task signup: :environment do User.where(current_sign_in_at: 1.year.ago..Time.now.utc).find_each { |u| u.send(:enqueue_adobe_campaign_subscription) } end end
chuckmersereau/api_practice
app/serializers/user_serializer.rb
class UserSerializer < PersonSerializer attributes :preferences has_many :account_lists belongs_to :master_person def person_exhibit exhibit(object.becomes(Person)) end def preferences object.preferences.merge( default_account_list: object.default_account_list_record.try(:id), setup: object.setup ) end end
chuckmersereau/api_practice
spec/models/person/linkedin_account_spec.rb
require 'rails_helper' describe Person::LinkedinAccount do let(:people_url) do 'https://api.linkedin.com/v1/people/url=http:%2F%2Fwww.linkedin.com%2F'\ 'pub%2Fchris-cardiff%2F6%2Fa2%2F62a:(id,first-name,last-name,public-profile-url)' end let(:people_response) do '{"first_name":"Chris","id":"F_ZUsSGtL7","last_name":"Cardiff",'\ '"public_profile_url":"http://www.linkedin.com/pub/chris-cardiff/6/a2/62a"}' end describe 'create from auth' do it 'should create an account linked to a person' do auth_hash = Hashie::Mash.new(uid: '5', credentials: { token: 'a', secret: 'b' }, extra: { access_token: { params: { oauth_expires_in: 2, oauth_authorization_expires_in: 5 } } }, info: { first_name: 'John', last_name: 'Doe' }) person = FactoryBot.create(:person) expect do @account = Person::LinkedinAccount.find_or_create_from_auth(auth_hash, person) end.to change(Person::LinkedinAccount, :count).from(0).to(1) expect(person.linkedin_accounts).to include(@account) end end it 'should return name for to_s' do account = Person::LinkedinAccount.new(first_name: 'John', last_name: 'Doe') expect(account.to_s).to eq('<NAME>') end it 'adds http:// to url if necessary' do account = build(:linkedin_account) expect(Person::LinkedinAccount).to receive(:valid_token).and_return([account]) stub_request(:get, people_url).to_return(status: 200, body: people_response, headers: {}) url = 'www.linkedin.com/pub/chris-cardiff/6/a2/62a' l = Person::LinkedinAccount.new(url: url) expect(l.url).to eq('http://' + url) end it 'supports a really long public_url' do account = build(:linkedin_account) account.public_url = 'http://www.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com' expect { account.save! }.to_not raise_error end context '#url=' do it "doesn't contact linkedin.com if the url han't changed" do account = create(:linkedin_account) expect(Person::LinkedinAccount).to_not receive(:valid_token) account.update_attributes(url: account.public_url) end it 'raises LinkedIn::Errors::UnauthorizedError if there are no accounts with a valid token' do account = create(:linkedin_account, valid_token: false) expect do account.update_attributes(url: 'http://bar.com') end.to raise_error(LinkedIn::Errors::UnauthorizedError) end it 'looks for a second valid account if the first one it finds raises an error' do account1 = create(:linkedin_account) account2 = create(:linkedin_account) expect(Person::LinkedinAccount).to receive(:valid_token).once.and_return([account1]) expect(Person::LinkedinAccount).to receive(:valid_token).once.and_return([account2]) expect(LINKEDIN).to receive(:authorize_from_access).once.and_raise(LinkedIn::Errors::UnauthorizedError, 'asdf') expect(LINKEDIN).to receive(:authorize_from_access).once.and_return(true) stub_request(:get, people_url).to_return(status: 200, body: people_response, headers: {}) expect do account2.update_attributes(url: 'www.linkedin.com/pub/chris-cardiff/6/a2/62a') end.to change(account1, :valid_token).from(true).to(false) end end end
chuckmersereau/api_practice
spec/controllers/api_controller_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/controllers/api_controller_spec.rb require 'rails_helper' describe ApiController do let!(:user) { create(:user_with_account) } let(:default_type) { ApiController::DEFAULT_SUPPORTED_CONTENT_TYPE } controller(ApiController) do def show head :no_content end end before do routes.draw { get 'show' => 'api#show' } api_login(user) end context '#supports_content_types' do after(:each) do ApiController.supports_content_types(nil) raise 'State was not properly reset!' if ApiController.supported_content_types != [default_type] end it 'supports additional content types' do ApiController.supports_content_types('my-special-type', 'my-other-content-type') expect(ApiController.supported_content_types).to eq ['my-special-type', 'my-other-content-type'] end it 'supports a default content type' do expect(ApiController.supported_content_types).to include default_type end end context '#supports_accept_header_content_types' do after(:each) do ApiController.supports_accept_header_content_types(nil) raise 'State was not properly reset!' if ApiController.supported_accept_header_content_types != [default_type] end it 'supports additional content types in accept header' do ApiController.supports_accept_header_content_types('my-special-type', 'my-other-content-type') expect(ApiController.supported_accept_header_content_types).to eq %w(my-special-type my-other-content-type) end it 'supports a default content type in accept header' do expect(ApiController.supported_accept_header_content_types).to include default_type end end it 'successfully handles a request with nil content type' do request.headers['CONTENT_TYPE'] = nil get :show end end
chuckmersereau/api_practice
spec/models/notification_type/stopped_giving_spec.rb
<filename>spec/models/notification_type/stopped_giving_spec.rb require 'rails_helper' describe NotificationType::StoppedGiving do let!(:stopped_giving) { NotificationType::StoppedGiving.first_or_initialize } let!(:da) { create(:designation_account_with_donor) } let(:contact) { da.contacts.financial_partners.first } describe '.check' do context 'direct deposit donor' do before do contact.update_attributes(direct_deposit: true, pledge_received: true) end it 'adds a notification if late' do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 63.days.ago) notifications = stopped_giving.check(contact.account_list) expect(notifications.length).to eq(1) end it 'skips people with future pledge_start_date' do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 60.days.ago) contact.update_attributes(pledge_start_date: 1.day.from_now) notifications = stopped_giving.check(contact.account_list) expect(notifications.length).to eq(0) end it "doesn't add a notification if not late" do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 37.days.ago) notifications = stopped_giving.check(contact.account_list) expect(notifications.length).to eq(0) end it "doesn't add a notification if the contact is on a different account list with a shared designation account" do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 60.days.ago) account_list2 = create(:account_list) account_list2.account_list_entries.create!(designation_account: da) notifications = stopped_giving.check(account_list2) expect(notifications.length).to eq(0) end end context 'non-direct deposit donor' do before do contact.update_attributes(pledge_frequency: 1, pledge_received: true) end it 'adds a notification if late' do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 65.days.ago) notifications = stopped_giving.check(contact.account_list) expect(notifications.length).to eq(1) end it "doesn't add a notification if not late" do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 37.days.ago) notifications = stopped_giving.check(contact.account_list) expect(notifications.length).to eq(0) end end context 'has never given' do it "doesn't add a notification" do notifications = stopped_giving.check(contact.account_list) expect(notifications.length).to eq(0) end end end describe '.create_task' do let(:account_list) { create(:account_list) } it 'creates a task for the activity list' do expect do stopped_giving.create_task(account_list, contact.notifications.new) end.to change(Activity, :count).by(1) end it 'associates the contact with the task created' do task = stopped_giving.create_task(account_list, contact.notifications.new) expect(task.contacts.reload).to include contact end end end
chuckmersereau/api_practice
db/migrate/20120315201646_add_balance_to_designation_profile.rb
<reponame>chuckmersereau/api_practice class AddBalanceToDesignationProfile < ActiveRecord::Migration def change add_column :designation_profiles, :balance, :decimal, precision: 8, scale: 2 add_column :designation_profiles, :balance_updated_at, :datetime add_column :designation_accounts, :balance_updated_at, :datetime remove_index :designation_accounts, :organization_id add_index :designation_accounts, [:organization_id, :designation_number], name: 'unique_designation_org', unique: true add_index :donations, :donation_date end end
chuckmersereau/api_practice
app/exhibits/account_list_exhibit.rb
<filename>app/exhibits/account_list_exhibit.rb class AccountListExhibit < DisplayCase::Exhibit include LocalizationHelper def self.applicable_to?(object) object.class.name == 'AccountList' end def to_s designation_accounts.map(&:name).join(', ') end def multi_currencies_for_same_symbol? @multi_currencies_for_same_symbol ||= begin symbols = currencies.map { |c| currency_symbol(c) }.uniq symbols.size < currencies.size end end def weeks_on_mpd if active_mpd_start_at.present? && active_mpd_finish_at.present? seconds = (active_mpd_finish_at - active_mpd_start_at).days seconds / 1.week end end def last_prayer_letter_at mail_chimp_account&.prayer_letter_last_sent end def formatted_balance(locale: nil) balance = designation_accounts.where(organization_id: salary_organization_id) .where(active: true).sum(:balance) @context.number_to_current_currency(balance, currency: salary_currency, locale: locale) end def staff_account_ids designation_accounts.map(&:staff_account_id).compact end end
chuckmersereau/api_practice
spec/controllers/weekly_controller_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe WeeklyController, type: :controller do end
chuckmersereau/api_practice
app/services/contact/filter/designation_account_id.rb
class Contact::Filter::DesignationAccountId < Contact::Filter::Base def execute_query(contacts, filters) contact_ids = contacts.includes(donor_accounts: :donations) .where(donations: { designation_account_id: filters[:designation_account_id] }) .where.not(donations: { id: nil }) .pluck(:id) contacts.where(id: contact_ids) end def title _('Designation Acccount') end def parent _('Gift Details') end def type 'multiselect' end def custom_options account_lists.collect(&:designation_accounts).flatten.compact.map do |designation_account| { id: designation_account.id, name: DesignationAccountSerializer.new(designation_account).display_name } end end def valid_filters?(filters) filters[name].present? && !filters[name].is_a?(Hash) end end
chuckmersereau/api_practice
spec/services/mail_chimp/exporter/merge_field_adder_spec.rb
require 'rails_helper' RSpec.describe MailChimp::Exporter::MergeFieldAdder do let(:list_id) { 'list_one' } let(:mail_chimp_account) { build(:mail_chimp_account) } let(:account_list) { mail_chimp_account.account_list } let(:mock_gibbon_wrapper) { double(:mock_gibbon_wrapper) } let(:mock_gibbon_list_object) { double(:mock_gibbon_list_object) } subject { described_class.new(mail_chimp_account, mock_gibbon_wrapper, list_id) } let(:mock_merge_fields) { double(:mock_merge_fields) } let(:merge_field_create_body) do { body: { tag: 'RANDOM_FIELD', name: 'Random_field', type: 'text' } } end before do allow(mock_gibbon_wrapper).to receive(:gibbon_list_object).and_return(mock_gibbon_list_object) allow(mock_gibbon_list_object).to receive(:merge_fields).and_return(mock_merge_fields) end context '#add_merge_field' do let(:group_type) { 'Tags' } let(:interests_create_body) { { body: { name: 'Tag_two' } } } it 'creates and updates the appropriate tag group names and adds the appropriate groups to those' do expect(mock_merge_fields).to receive(:retrieve).and_return('merge_fields' => [{ 'tag' => 'field_one' }]) expect(mock_merge_fields).to receive(:create).with(merge_field_create_body) subject.add_merge_field('RANDOM_FIELD') end end end
chuckmersereau/api_practice
spec/factories/phone_numbers.rb
FactoryBot.define do factory :phone_number do association :person number '+12134567890' country_code 'MyString' location 'mobile' primary false valid_values true end end
chuckmersereau/api_practice
config/routes.rb
<reponame>chuckmersereau/api_practice<filename>config/routes.rb<gh_stars>0 require 'sidekiq/pro/web' require 'sidekiq/cron/web' Rails.application.routes.draw do mount Auth::Engine, at: '/', constraints: { subdomain: 'auth' } if Rails.env.development? mount Sidekiq::Web => '/sidekiq' else authenticated :user, ->(u) { u.developer } do mount Sidekiq::Web => '/sidekiq' end end namespace :api do api_version(module: 'V2', path: { value: 'v2' }) do constraints(id: UUID_REGEX) do namespace :admin do resources :impersonation, only: :create resources :organizations, only: :create resources :resets, only: :create end resources :account_lists, only: [:index, :show, :update] do scope module: :account_lists do resource :analytics, only: [:show] resources :designation_accounts, only: [:index, :show, :update] resources :donations, only: [:index, :show, :create, :update, :destroy] resources :donor_accounts, only: [:index, :show] resources :invites, only: [:index, :show, :create, :destroy] do put :accept, on: :member, action: :update end resources :imports, only: :show do scope module: :imports do collection do resources :tnt, only: :create resources :google, only: :create resources :tnt_data_sync, only: :create resources :csv, only: [:index, :show, :create, :update] end end end resource :mail_chimp_account, only: [:show, :create, :destroy] do get :sync, on: :member end resources :merge, only: [:create] resources :notification_preferences, only: [:index, :show, :create, :destroy] namespace :notification_preferences do resource :bulk, only: [:create], controller: :bulk end resources :notifications, only: [:index, :show, :create, :update, :destroy] resources :pledges, only: [:index, :show, :create, :update, :destroy] resource :prayer_letters_account, only: [:show, :create, :destroy] do get :sync, on: :member end resources :users, only: [:index, :show, :destroy] resources :coaches, only: [:index, :show, :destroy] resource :chalkline_mail, only: :create end end resources :appeals, only: [:index, :show, :create, :update, :destroy] do scope module: :appeals do resources :appeal_contacts, only: [:index, :show, :create, :destroy] resources :excluded_appeal_contacts, only: [:index, :show, :destroy] end end resources :background_batches, except: [:update] namespace :coaching do resources :account_lists, only: [:index, :show] resources :contacts, only: [:index, :show] end resources :constants, only: [:index] resources :contacts, only: [:index, :show, :create, :update, :destroy] do scope module: :contacts do collection do post :export_to_mail_chimp, to: 'export_to_mail_chimp#create' resource :analytics, only: :show resources :filters, only: :index resources :merges, only: :create namespace :merges do resource :bulk, only: [:create], controller: :bulk end resources :tags, only: :index namespace :tags do resource :bulk, only: [:create, :destroy], controller: :bulk end resources :church_names, only: :index constraints(id: /.+/) do resources :duplicates, only: [:index, :show, :update] namespace :people do resources :duplicates, only: [:index, :show, :update] end end namespace :people do resource :bulk, only: [:create, :update, :destroy], controller: :bulk namespace :merges do resource :bulk, only: [:create], controller: :bulk end end end resources :addresses, only: [:index, :show, :create, :update, :destroy] resources :donation_amount_recommendations, only: [:index, :show, :create, :update, :destroy] resources :people, only: [:show, :index, :create, :update, :destroy] do scope module: :people do collection do resources :merges, only: :create end resources :email_addresses, only: [:index, :show, :create, :update, :destroy] resources :facebook_accounts, only: [:index, :show, :create, :update, :destroy] resources :linkedin_accounts, only: [:index, :show, :create, :update, :destroy] resources :phones, only: [:index, :show, :create, :update, :destroy] resources :relationships, only: [:index, :show, :create, :update, :destroy] resources :twitter_accounts, only: [:index, :show, :create, :update, :destroy] resources :websites, only: [:index, :show, :create, :update, :destroy] end end resources :referrals, only: [:index, :show, :create, :update, :destroy] resources :referrers, only: [:index] resources :tags, only: [:create, :destroy], param: :tag_name collection do get :analytics, to: 'analytics#show' resources :exports, only: [:index, :show, :create] do collection do scope module: :exports do resources :mailing, only: [:index, :show, :create] end end end resource :bulk, only: [:create, :update, :destroy], controller: :bulk resources :filters, only: :index resources :people, only: [:index, :show, :update, :destroy] end end end resources :tasks do scope module: :tasks do resources :tags, only: [:create, :destroy], param: :tag_name resources :comments, only: [:index, :show, :create, :update, :destroy] end collection do scope module: :tasks do resource :analytics, only: :show resource :bulk, only: [:create, :update, :destroy], controller: :bulk resources :filters, only: :index resources :tags, only: :index namespace :tags do resource :bulk, only: [:create, :destroy], controller: :bulk end end end end resource :user, only: [:show, :update] do scope module: :user do resource :authenticate, only: :create resources :google_accounts do scope module: :google_accounts do resources :google_integrations do get :sync, on: :member end end end resources :key_accounts resources :organization_accounts end end namespace :reports do resource :balances, only: :show resource :donation_monthly_totals, only: :show resource :donor_currency_donations, only: :show resource :expected_monthly_totals, only: :show resource :goal_progress, only: :show resource :monthly_giving_graph, only: :show resource :salary_currency_donations, only: :show resource :year_donations, only: :show resources :questions, only: :index resources :weeklies, only: [:index, :show, :create] resources :sessions, only: [:show, :create] resource :bulk, only: :create, controller: :bulk resources :monthly_losses_graphs, only: :show resources :pledge_histories, only: :index resources :appointment_results, only: :index resources :activity_results, only: :index end resources :deleted_records, only: [:index] namespace :tools do get :analytics, to: 'analytics#show' end end resource :user, only: [] do scope module: :user do resources :options end end end end get 'monitors/commit', to: 'monitors#commit' get 'monitors/lb', to: 'monitors#lb' get 'monitors/sidekiq', to: 'monitors#sidekiq' get 'mail_chimp_webhook/:token', to: 'mail_chimp_webhook#index' post 'mail_chimp_webhook/:token', to: 'mail_chimp_webhook#hook' end
chuckmersereau/api_practice
app/models/appeal_contact.rb
<reponame>chuckmersereau/api_practice class AppealContact < ApplicationRecord audited associated_with: :appeal, on: [:destroy] belongs_to :appeal, foreign_key: 'appeal_id' belongs_to :contact validates :appeal, :contact, presence: true validates :contact_id, uniqueness: { scope: :appeal_id } validate :associations_have_same_account_list attr_accessor :force_list_deletion validate :contact_on_exclusion_list, if: :contact_on_exclusion_list? after_create :remove_from_exclusion_list, if: :contact_on_exclusion_list? PERMITTED_ATTRIBUTES = [:overwrite, :contact_id, :updated_at, :updated_in_db_at, :force_list_deletion, :id].freeze def destroy_related_excluded_appeal_contact Appeal::ExcludedAppealContact.find_by(appeal: appeal, contact: contact)&.destroy true end protected def associations_have_same_account_list return unless appeal && contact return if contact.account_list_id == appeal.account_list_id errors[:contact] << 'does not have the same account list as appeal' end def contact_on_exclusion_list? Appeal::ExcludedAppealContact.exists?(appeal: appeal, contact: contact) end def contact_on_exclusion_list return true if ActiveRecord::Type::Boolean.new.type_cast_from_user(force_list_deletion) errors[:contact] << 'is on the Excluded List.' end def remove_from_exclusion_list Appeal::ExcludedAppealContact.find_by(appeal: appeal, contact: contact)&.destroy end end
chuckmersereau/api_practice
spec/models/notification_type/special_gift_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe NotificationType::SpecialGift do let!(:special_gift) { NotificationType::SpecialGift.first_or_initialize } let!(:da) { create(:designation_account_with_special_donor) } let(:contact) { da.contacts.non_financial_partners.first } let(:donation) { create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 5.days.ago) } context '#check' do it 'adds a notification if a gift comes from a non financial partner' do donation # create donation object from let above notifications = special_gift.check(contact.account_list) expect(notifications.length).to eq(1) end it "doesn't add a notification if first gift came more than 1 month ago" do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 37.days.ago) notifications = special_gift.check(contact.account_list) expect(notifications.length).to eq(0) end it "doesn't add a notification if the contact is on a different account list with a shared designation account" do donation # create donation object from let above account_list2 = create(:account_list) account_list2.account_list_entries.create!(designation_account: da) notifications = special_gift.check(account_list2) expect(notifications.length).to eq(0) end end describe '.create_task' do let(:account_list) { create(:account_list) } it 'creates a task for the activity list' do expect do special_gift.create_task(account_list, contact.notifications.new(donation_id: donation.id)) end.to change(Activity, :count).by(1) end it 'associates the contact with the task created' do task = special_gift.create_task(account_list, contact.notifications.new(donation_id: donation.id)) expect(task.contacts.reload).to include contact end end end
chuckmersereau/api_practice
db/migrate/20170221212815_add_validation_columns_to_phone_numbers.rb
class AddValidationColumnsToPhoneNumbers < ActiveRecord::Migration def change add_column :phone_numbers, :valid_values, :boolean, default: true add_column :phone_numbers, :source, :string, default: 'MPDX' end end
chuckmersereau/api_practice
spec/services/task/filter/starred_spec.rb
require 'rails_helper' RSpec.describe Task::Filter::Starred 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, starred: false) } let!(:task_two) { create(:task, account_list: account_list, starred: true) } 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, { overdue: {} }, nil)).to eq(nil) expect(described_class.query(tasks, { overdue: [] }, nil)).to eq(nil) expect(described_class.query(tasks, { overdue: '' }, nil)).to eq(nil) end end context 'filter by starred' do it 'filters where starred is true' do expect(described_class.query(tasks, { starred: true }, nil).to_a).to include(task_two) end end end end
chuckmersereau/api_practice
spec/support/shared_controller_examples/sorting_examples.rb
RSpec.shared_examples 'sorting examples' do |options| UNSUPPORTED_SORT_MESSAGE ||= 'Sorting by id is not supported for this endpoint.'.freeze let(:sorting_param) do described_class.new.send(:permitted_sorting_params).first || described_class::PERMITTED_SORTING_PARAM_DEFAULTS.second end let(:permit_multiple_sorting_params?) { described_class::PERMIT_MULTIPLE_SORTING_PARAMS } def sorting_param_nullable? !%w(created_at updated_at).include?(sorting_param) end before do resource.update_column(sorting_param, 1.day.ago) if sorting_param.ends_with?('_at') unless sorting_param.include?('.') || resource.class.where.not(sorting_param => resource.send(sorting_param)).exists? raise 'To test sorting, there should be a resource with '\ "attribute #{sorting_param} NOT equal to #{resource.send(sorting_param)}" end end it 'sorts resources if sorting_param is in list of permitted sorts' do api_login(user) get options[:action], parent_param_if_needed.merge(sort: "-#{sorting_param}") expect do get options[:action], parent_param_if_needed.merge(sort: sorting_param.to_s) end.to change { JSON.parse(response.body)['data'].first['id'] } expect(JSON.parse(response.body)['meta']['sort']).to eq(sorting_param.to_s) end it 'raises a 400 if sort param is not in list of permitted sorts' do api_login(user) get options[:action], parent_param_if_needed.merge(sort: 'id') expect(response.status).to eq(400) expect(JSON.parse(response.body)['errors'].first['detail']).to eq(UNSUPPORTED_SORT_MESSAGE) end context 'sorting nulls' do before do next if sorting_param.include?('.') || !sorting_param_nullable? resource.update_column(sorting_param, nil) message = "To test sorting by null values, there should be a resource with attribute #{sorting_param} as null" raise message unless resource.class.where(sorting_param => nil).exists? message = "To test sorting by null values, there should be a resource with attribute #{sorting_param} as NOT null" raise message unless resource.class.where.not(sorting_param => nil).exists? end it 'sorts resources based on null values first or last' do next if sorting_param.include?('.') || !sorting_param_nullable? api_login(user) get options[:action], parent_param_if_needed.merge(sort: "#{sorting_param} nulls") expect(JSON.parse(response.body)['meta']['sort']).to eq("#{sorting_param} nulls") expect do get options[:action], parent_param_if_needed.merge(sort: "#{sorting_param} -nulls") end.to change { JSON.parse(response.body)['data'].first['id'] } expect(JSON.parse(response.body)['meta']['sort']).to eq("#{sorting_param} -nulls") end it 'raises an error if the nulls argument is not formatted as expected' do next if sorting_param.include?('.') || !sorting_param_nullable? api_login(user) get options[:action], parent_param_if_needed.merge(sort: "#{sorting_param} nil") expect(response.status).to eq(400) expect(JSON.parse(response.body)['errors'].first['detail']).to eq('Bad format for sort param.') end end context 'sorting by only one parameter' do it 'raises a 400 if sort param includes several sorting parameters' do next if permit_multiple_sorting_params? api_login(user) get options[:action], parent_param_if_needed.merge(sort: 'id,id') expect(response.status).to eq(400) expected_error = 'This endpoint does not support multiple sorting parameters.' expect(JSON.parse(response.body)['errors'].first['detail']).to eq expected_error end end context 'sorting by multiple parameters' do it 'allows sorting by multiple sorting parameters' do next unless permit_multiple_sorting_params? api_login(user) get options[:action], parent_param_if_needed.merge(sort: '-created_at,updated_at') expect do get options[:action], parent_param_if_needed.merge(sort: 'created_at,-updated_at') end.to change { JSON.parse(response.body)['data'].first['id'] } expect(response.status).to eq(200) end it 'raises a 400 if one of the sorting params is not in list of permitted sorts' do next unless permit_multiple_sorting_params? api_login(user) get options[:action], parent_param_if_needed.merge(sort: 'created_at,id') expect(response.status).to eq(400) expect(JSON.parse(response.body)['errors'].first['detail']).to eq(UNSUPPORTED_SORT_MESSAGE) end end end
chuckmersereau/api_practice
app/models/mail_chimp_appeal_list.rb
class MailChimpAppealList < ApplicationRecord validates :mail_chimp_account, :appeal_list_id, :appeal, presence: true belongs_to :mail_chimp_account belongs_to :appeal end
chuckmersereau/api_practice
spec/models/notification_type/smaller_gift_spec.rb
<gh_stars>0 require 'rails_helper' describe NotificationType::SmallerGift do subject { NotificationType::SmallerGift.first_or_initialize } let!(:da) { create(:designation_account) } let!(:account_list) { create(:account_list) } let!(:contact) { create(:contact, account_list: account_list, pledge_amount: 15) } let!(:donor_account) { create(:donor_account) } let!(:donation) { create(:donation, donor_account: donor_account, designation_account: da) } before do account_list.account_list_entries.create!(designation_account: da) contact.donor_accounts << donor_account contact.update_donation_totals(donation) end context '#check' do context 'gift comes from a financial partner and is less than the pledge' do it 'adds a notification' do expect(subject.check(account_list).size).to eq(1) end end context 'two small gifts add up to at least pledge come in at same time' do before do create(:donation, donor_account: donor_account, designation_account: da, donation_date: Date.today, payment_method: Donation::GIFT_AID) end it 'does not add a notfication' do expect(subject.check(account_list)).to be_empty end end it 'does not experience rounding errors' do contact.update(pledge_amount: 250, pledge_frequency: 3.0) donation.update(amount: 250.0, tendered_amount: 250.0) expect(subject.check(account_list)).to be_empty end context 'pledge annually and correct size gift comes in' do before do contact.update(pledge_amount: 1200.0, pledge_frequency: 12.0) donation.update(amount: 1200.0, tendered_amount: 1200.0) contact.update_donation_totals(donation) contact.update(first_donation_date: nil, last_donation_date: nil) # sometimes these aren't set end it 'does not add a notification' do expect(subject.check(account_list)).to be_empty end context 'first donation was before period' do before do create(:donation, donor_account: donor_account, designation_account: da, amount: 20.0, tendered_amount: 20.0, donation_date: 4.years.ago) end it 'does not add a notification' do expect(subject.check(account_list)).to be_empty end end end context 'pledge weekly and correct size gift comes in' do before do contact.update(pledge_amount: 1200.0, pledge_frequency: 0.23076923076923.to_d) donation.update(amount: 1200.0, tendered_amount: 1200.0, donation_date: 1.week.ago) contact.update_donation_totals(donation) contact.update(first_donation_date: nil, last_donation_date: nil) # sometimes these aren't set end it 'does not add a notification' do expect(subject.check(account_list)).to be_empty end context 'first donation was before period' do before do create(:donation, donor_account: donor_account, designation_account: da, amount: 20.0, tendered_amount: 20.0, donation_date: 4.weeks.ago) end it 'does not add a notification' do expect(subject.check(account_list)).to be_empty end end end context 'recontinuing gift notification being sent' do it 'does not add a notification' do allow(NotificationType::RecontinuingGift).to receive(:had_recontinuing_gift?).with(contact).and_return(true) expect(subject.check(account_list)).to be_empty end end end end
chuckmersereau/api_practice
app/mailers/subscriber_cleaned_mailer.rb
<reponame>chuckmersereau/api_practice class SubscriberCleanedMailer < ApplicationMailer def subscriber_cleaned(account_list, cleaned_email) return unless account_list.users.order(:created_at).first @email = cleaned_email @person = @email.person @contact = @person.contact user_emails = account_list.user_emails_with_names I18n.locale = account_list.users.order(:created_at).first.locale || 'en' mail subject: _('MailChimp subscriber email bounced'), to: user_emails end end
chuckmersereau/api_practice
spec/lib/documentation_helper_spec.rb
require 'spec_helper' require 'rails' require 'documentation_helper' RSpec.describe DocumentationHelper, type: :service do before do path = Pathname.new('/mock/project-name') allow(Rails).to receive(:root) .and_return(path) end describe '#initialize' do context 'with a single resource' do it 'returns a resource array' do helper = build_helper(resource: :emails) expect(helper.resource).to match [:emails] end end context 'with multiple references' do it 'returns the references in an array' do helper = build_helper(resource: [:contacts, :people, :emails]) expect(helper.resource).to match [:contacts, :people, :emails] end end end describe '#insert_documentation_for' do it 'delegates to the other document_for methods' do action = :create context = build_mock_context helper = build_helper expect(helper) .to receive(:document_parameters_for) .with(action: action, context: context) expect(helper) .to receive(:document_response_fields_for) .with(action: action, context: context) helper.insert_documentation_for(action: action, context: context) end end describe '#document_parameters_for' do let(:helper) do filepath = 'spec/support/documentation/test/contacts.yml' build_helper(filepath: filepath) end it 'sends :parameter to context with non-ignored fields' do context = build_mock_context data = helper.data_for(type: :parameters, action: :create).deep_dup data.each do |name, attributes| description = attributes.delete(:description) if attributes.key?(:ignore) expect(context) .not_to receive(:parameter) .with(name, description, attributes) else expect(context) .to receive(:parameter) .with(name, description, attributes) end end helper.document_parameters_for(action: :create, context: context) end end describe '#document_response_fields_for' do let(:helper) do filepath = 'spec/support/documentation/test/contacts.yml' build_helper(filepath: filepath) end it 'sends :response_field to context with non-ignored fields' do context = build_mock_context data = helper.data_for(type: :response_fields, action: :create).deep_dup data.each do |name, attributes| description = attributes.delete(:description) if attributes.key?(:ignore) expect(context) .not_to receive(:response_field) .with(name, description, attributes) else expect(context) .to receive(:response_field) .with(name, description, attributes) end end helper.document_response_fields_for(action: :create, context: context) end end describe '#document_scope' do context 'for an entity (single resource passed)' do it 'returns the scope for organizing the documentation' do helper = build_helper(resource: :contacts) expect(helper.document_scope).to eq :entities_contacts helper = build_helper(resource: :people) expect(helper.document_scope).to eq :entities_people end end context 'for an api (multiple resource passed)' do it 'returns the scope for organizing the documentation' do helper = build_helper(resource: [:people, :emails]) expect(helper.document_scope).to eq :people_api_emails helper = build_helper(resource: [:contacts, :addresses]) expect(helper.document_scope).to eq :contacts_api_addresses end end end describe '#filename' do it 'returns the filename expected based on the resource' do helper = build_helper(resource: [:contacts, :people, :emails]) expect(helper.filename).to eq 'emails.yml' end end describe '#filepath' do it 'returns the filepath based on the resource' do base_path = Rails.root.to_s path_of_file = 'spec/support/documentation/test/contacts/people/emails.yml' resource = [:test, :contacts, :people, :emails] helper = DocumentationHelper.new(resource: resource) expect(helper.filepath).to eq "#{base_path}/#{path_of_file}" end end describe '#title_for' do let(:helper) { build_helper(resource: :email_addresses) } it 'returns the title for index' do expect(helper.title_for(:index)).to eq 'Email Address [LIST]' end it 'returns the title for show' do expect(helper.title_for(:show)).to eq 'Email Address [GET]' end it 'returns the title for create' do expect(helper.title_for(:create)).to eq 'Email Address [POST]' end it 'returns the title for update' do expect(helper.title_for(:update)).to eq 'Email Address [PUT]' end it 'returns the title for delete' do expect(helper.title_for(:delete)).to eq 'Email Address [DELETE]' end it 'returns the title for bulk create' do expect(helper.title_for(:bulk_create)).to eq 'Email Addresses [BULK POST]' end it 'returns the title for bulk update' do expect(helper.title_for(:bulk_update)).to eq 'Email Addresses [BULK PUT]' end it 'returns the title for bulk delete' do expect(helper.title_for(:bulk_delete)).to eq 'Email Addresses [BULK DELETE]' end it 'will return a custom title defined in the yml' do expect(helper.title_for(:custom_action)).to eq 'My Custom Title' end end describe '#description_for' do let(:helper) { build_helper } context 'without a custom description' do it 'returns the title for the action' do expect(helper.description_for(:delete)).to eq helper.title_for(:delete) end end context 'with a custom description' do it 'returns the title for the action' do expected_desc = 'This is the endpoint for Creating an Email Address' expect(helper.description_for(:create)).to eq expected_desc end end end describe '#raw_data' do let(:expected_data) { YAML.load_file(test_filepath).deep_symbolize_keys } it 'returns the raw hash data found in the yaml doc file' do helper = build_helper expect(helper.raw_data).to eq expected_data end end describe '#data_for' do context "when the YAML data doesn't have a data key" do let(:expected_data) do { 'attributes.created_at': { description: 'The timestamp of when this resource was created', type: 'ISO8601 timestamp' }, 'attributes.email': { description: 'The actual email address that this Email Address resource represents', required: true, type: 'string' }, 'attributes.primary': { description: "Whether or not the `email` is the owner's primary email address", type: 'boolean' }, 'attributes.updated_at': { description: 'The timestamp of when this resource was last updated', type: 'ISO8601 timestamp' }, 'attributes.updated_in_db_at': { description: 'This is to be used as a reference for the last time the resource was '\ 'updated in the remote database - specifically for when data is '\ 'updated while the client is offline.', type: 'ISO8601 timestamp', required: true }, 'relationships.account_list.data.id': { description: 'The `id` of the Account List needed for creating', type: 'number', required: true }, 'relationships.emails.data': { description: 'An array of Emails sent by this Email Address', type: '[Email]' } } end it 'returns the transformed data with additional field data' do helper = build_helper expect(helper.data_for(type: :response_fields, action: :create)) .to eq expected_data end end context 'when the YAML data has a data key' do let(:expected_data) do { 'data': { description: 'An array of Email Address objects', type: '[Email Address]' } } end it 'returns the transformed data sans ignored attributes' do helper = build_helper expect(helper.data_for(type: :response_fields, action: :index)) .to eq expected_data end end end def build_helper(resource: nil, filepath: test_filepath) resource ||= [:test, :contacts, :people, :emails] DocumentationHelper.new(resource: resource, filepath: filepath) end def build_mock_context double('context', parameter: nil, response_field: nil) end def test_filepath 'spec/support/documentation/test/contacts/people/emails.yml' end end
chuckmersereau/api_practice
db/migrate/20170518165122_add_completed_at_to_admin_reset_log.rb
<reponame>chuckmersereau/api_practice class AddCompletedAtToAdminResetLog < ActiveRecord::Migration def change add_column :admin_reset_logs, :completed_at, :datetime end end
chuckmersereau/api_practice
db/migrate/20120427165336_change_profile_index.rb
<filename>db/migrate/20120427165336_change_profile_index.rb class ChangeProfileIndex < ActiveRecord::Migration def up remove_index :designation_profiles, name: :unique_name add_index :designation_profiles, [:user_id, :organization_id, :remote_id], name: :unique_remote_id, unique: true end def down end end
chuckmersereau/api_practice
spec/requests/api/v2/error_request_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe 'Error Response Format', type: :request do let!(:user) { create(:user_with_account) } let!(:headers) do { 'ACCEPT' => 'application/vnd.api+json', 'CONTENT_TYPE' => 'application/vnd.api+json' } end let(:parsed_response_body) { JSON.parse(response.body) } before do api_login(user) end context 'StandardError' do subject { get api_v2_contacts_path, nil, headers } before { allow(Contact).to receive(:where).and_raise(StandardError) } it 'has a response body that contains error objects in json api format' do subject expect(response.body).to eq '{"errors":[{"status":"500","title":"Internal Server Error"}]}' end end context 'ActiveRecord::RecordNotFound' do let(:id) { SecureRandom.uuid } let(:expected_error_data) do { errors: [ { status: '404', title: 'Not Found', detail: "Couldn't find Contact with 'id'=#{id}" } ] }.deep_stringify_keys end subject { get api_v2_contact_path(id: id), nil, headers } it 'has a response body that contains error objects in json api format' do subject expect(JSON.parse(response.body)).to eq expected_error_data end end context 'ActionController::RoutingError' do describe 'with complete headers' do subject { get '/this_route_does_not_exist', nil, headers } it 'has a response body that contains error objects in json api format' do subject expect(response.body).to eq '{"errors":[{"status":"404","title":"Not Found","detail":"Route not found"}]}' end end describe 'without an ACCEPT header' do let(:headers) { { 'ACCEPT' => '', 'CONTENT_TYPE' => 'application/vnd.api+json' } } subject { get '/this_route_does_not_exist', nil, headers } it 'has a response body that contains error objects in json api format' do subject expect(response.body).to eq '{"errors":[{"status":"404","title":"Not Found","detail":"Route not found"}]}' end end end end
chuckmersereau/api_practice
spec/services/donation_imports/siebel/donation_importer_spec.rb
require 'rails_helper' RSpec.describe DonationImports::Siebel::DonationImporter do let!(:user) { create(:user_with_account) } let(:organization_account) { user.organization_accounts.order(:created_at).first } let(:organization) { organization_account.organization } let!(:donor_account) { create(:donor_account, account_number: 'donor_id_one', organization: organization) } let(:designation_profile) { organization_account.designation_profiles.order(:created_at).first } let!(:designation_account) do create(:designation_account, designation_profiles: [designation_profile], designation_number: 'the_designation_number') end let(:mock_siebel_import) { double(:mock_siebel_import) } let(:donor_account) { create(:donor_account, organization: organization, account_number: 'donor_id_one') } let!(:first_donation) do create(:donation, remote_id: 'id_one', donor_account: donor_account, designation_account: designation_account, amount: 400.00, donation_date: 1.week.ago) end let!(:second_donation) do create(:donation, remote_id: 'id_five', donor_account: donor_account, designation_account: designation_account, amount: 500.00, donation_date: 1.week.ago) end let!(:third_donation) do create(:donation, remote_id: 'id_seven', donor_account: donor_account, designation_account: designation_account, amount: 500.00, donation_date: 3.weeks.ago) end let!(:fourth_donation) do create(:donation, remote_id: 'random_id_one', donor_account: donor_account, designation_account: designation_account, donation_date: 1.week.ago) end let!(:fifth_donation) do create(:donation, remote_id: 'random_id_two', donor_account: donor_account, designation_account: designation_account, donation_date: 1.week.ago) end let!(:sixth_donation) do create(:donation, remote_id: 'random_id_three', donor_account: donor_account, designation_account: designation_account, donation_date: 1.week.ago) end let(:mock_profile) { double(:mock_profile) } before do allow(mock_siebel_import).to receive(:organization).and_return(organization) allow(mock_siebel_import).to receive(:organization_account).and_return(organization_account) allow(mock_siebel_import).to receive(:profiles).and_return([designation_profile]) end subject { described_class.new(mock_siebel_import) } donation_structure_array = [ :id, :donor_id, :amount, :donation_date, :designation, :campaign_code, :payment_method, :payment_type, :channel ] DonationStructure = Struct.new(*donation_structure_array) let(:siebel_donations) do [ DonationStructure.new('id_one', 'donor_id_one', 200.00, 1.week.ago, 'the_designation_number'), DonationStructure.new('id_two', 'donor_id_one', 300.00, 1.week.ago, 'the_designation_number') ] end context '#import_donations' do before do expect(SiebelDonations::Donation).to receive(:find) .with(posted_date_start: 2.weeks.ago.strftime('%Y-%m-%d'), posted_date_end: Time.now.getlocal.strftime('%Y-%m-%d'), designations: 'the_designation_number') .and_return(siebel_donations) end it 'imports donations and deletes up to 3 donations that were removed on siebel (in the date range provided)' do expect do expect(subject.import_donations(start_date: 2.weeks.ago)).to be_truthy end.to change { Donation.count }.by(-2) expect(first_donation.reload.amount).to eq(200.00) expect(Donation.find_by(id: second_donation)).to be_nil expect(third_donation.reload).to be_present end end end
chuckmersereau/api_practice
app/services/person_with_parent_contact.rb
class PersonWithParentContact < ActiveModelSerializers::Model attr_accessor :person, :parent_contact delegate :anniversary_day, :anniversary_month, :anniversary_year, :birthday_day, :birthday_month, :birthday_year, :created_at, :deceased, :email_addresses, :employer, :facebook_accounts, :family_relationships, :first_name, :gender, :last_name, :legal_first_name, :linkedin_accounts, :marital_status, :middle_name, :occupation, :optout_enewsletter, :phone_numbers, :suffix, :title, :twitter_accounts, :updated_at, :updated_in_db_at, :id, :websites, to: :person def initialize(person:, parent_contact:) @person = person @parent_contact = parent_contact end end
chuckmersereau/api_practice
app/preloaders/api/v2/contacts/people_preloader.rb
<reponame>chuckmersereau/api_practice class Api::V2::Contacts::PeoplePreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = { family_relationships: Api::V2::Contacts::People::RelationshipsPreloader }.freeze FIELD_ASSOCIATION_MAPPING = { avatar: [:primary_picture, :facebook_account], parent_contacts: :contacts }.freeze end
chuckmersereau/api_practice
spec/acceptance/api/v2/tasks/bulk_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Tasks Bulk' do include_context :json_headers doc_helper = DocumentationHelper.new(resource: :tasks) let!(:account_list) { user.account_lists.order(:created_at).first } let!(:task_one) { create(:task, account_list: account_list) } let!(:task_two) { create(:task, account_list: account_list) } let!(:resource_type) { 'tasks' } let!(:user) { create(:user_with_account) } let(:new_task) do attributes_for(:task) .reject { |key| key.to_s.end_with?('_id') } .except(:id, :completed, :notification_sent) .merge(updated_in_db_at: task_one.updated_at) end let(:account_list_relationship) do { account_list: { data: { id: account_list.id, type: 'account_lists' } } } end let(:bulk_create_form_data) do [{ data: { type: resource_type, id: SecureRandom.uuid, attributes: new_task, relationships: account_list_relationship } }] end let(:bulk_update_form_data) do [{ data: { type: resource_type, id: task_one.id, attributes: new_task } }] end context 'authorized user' do post '/api/v2/tasks/bulk' do doc_helper.insert_documentation_for(action: :bulk_create, context: self) example doc_helper.title_for(:bulk_create), document: doc_helper.document_scope do explanation doc_helper.description_for(:bulk_create) do_request data: bulk_create_form_data expect(response_status).to eq(200) expect(json_response.first['data']['attributes']['subject']).to eq new_task[:subject] end end put '/api/v2/tasks/bulk' do doc_helper.insert_documentation_for(action: :bulk_update, context: self) example doc_helper.title_for(:bulk_update), document: doc_helper.document_scope do explanation doc_helper.description_for(:bulk_update) do_request data: bulk_update_form_data expect(response_status).to eq(200) expect(json_response.first['data']['attributes']['subject']).to eq new_task[:subject] end end before { api_login(user) } delete '/api/v2/tasks/bulk' do with_options scope: :data do parameter :id, 'Each member of the array must contain the id of the task being deleted' end doc_helper.insert_documentation_for(action: :bulk_delete, context: self) example doc_helper.title_for(:bulk_delete), document: doc_helper.document_scope do explanation doc_helper.description_for(:bulk_delete) do_request data: [ { data: { type: resource_type, id: task_one.id } }, { data: { type: resource_type, id: task_two.id } } ] expect(response_status).to eq(200) expect(json_response.size).to eq(2) expect(json_response.collect { |hash| hash.dig('data', 'id') }).to match_array([task_one.id, task_two.id]) end end end end
chuckmersereau/api_practice
app/services/import_callback_handler.rb
<reponame>chuckmersereau/api_practice class ImportCallbackHandler def initialize(import) @import = import @account_list = @import.account_list @started_at = @import.import_started_at end def handle_start @import.update_columns(importing: true, import_started_at: Time.current) end def handle_success(successes: nil) @account_list.queue_sync_with_google_contacts MailChimp::PrimaryListSyncWorker.perform_async(@account_list.mail_chimp_account.id) if @account_list.valid_mail_chimp_account begin ImportMailer.delay.success(@import, successes) @import.update_column(:error, nil) rescue StandardError => exception Rollbar.error(exception) end end def handle_failure(exception: nil, failures: nil, successes: nil) ImportMailer.delay.failed(@import, successes, failures) @import.update_column(:error, exception_to_text(exception)) rescue StandardError => exception Rollbar.error(exception) end def handle_complete @account_list.async_merge_contacts(@import.import_started_at) ContactSuggestedChangesUpdaterWorker.perform_async(@import.user_id, @import.import_started_at) ensure @import.update_columns(importing: false, import_completed_at: Time.current) end private def exception_to_text(exception) return unless exception text = [exception.class, exception.message].compact.join(': ') [text, exception.backtrace&.join("\n")].compact.join("\n") end end
chuckmersereau/api_practice
db/migrate/20140120124850_add_index_on_address.rb
<reponame>chuckmersereau/api_practice class AddIndexOnAddress < ActiveRecord::Migration def change Address.connection.execute( 'CREATE INDEX index_addresses_on_lower_street ON addresses (lower(street));' ) end end
chuckmersereau/api_practice
app/models/master_person_source.rb
class MasterPersonSource < ApplicationRecord belongs_to :master_person belongs_to :organization # attr_accessible :master_person_id end
chuckmersereau/api_practice
spec/models/google_email_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe GoogleEmail, type: :model do end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/people/websites_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > People > Websites' do include_context :json_headers documentation_scope = :people_api_websites let(:resource_type) { 'websites' } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:contact) { create(:contact, account_list: account_list) } let(:contact_id) { contact.id } let!(:person) { create(:person) } let(:person_id) { person.id } let!(:websites) { create_list(:website, 2, person: person) } let(:website) { websites.first } let(:id) { website.id } let(:new_website) do attributes_for(:website) .reject { |key| key.to_s.end_with?('_id') } .merge(updated_in_db_at: website.updated_at) end let(:form_data) { build_data(new_website) } let(:expected_attribute_keys) do %w( created_at primary updated_at updated_in_db_at url ) end context 'authorized user' do before do contact.people << person api_login(user) end get '/api/v2/contacts/:contact_id/people/:person_id/websites' do parameter 'contact_id', 'Contact ID', required: true parameter 'person_id', 'Person ID', required: true response_field 'data', 'Data', type: 'Array[Object]' example 'Website [LIST]', document: documentation_scope do explanation 'List of Websites associated to the Person' do_request check_collection_resource(2) expect(resource_object.keys).to match_array expected_attribute_keys expect(response_status).to eq 200 end end get '/api/v2/contacts/:contact_id/people/:person_id/websites/:id' do with_options scope: [:data, :attributes] do response_field 'created_at', 'Created At', type: 'String' response_field 'primary', 'Primary', type: 'Boolean' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' response_field 'url', 'Url', type: 'String' end example 'Website [GET]', document: documentation_scope do explanation 'The Person\'s Website with the given ID' do_request expect(resource_object.keys).to match_array expected_attribute_keys expect(response_status).to eq 200 end end post '/api/v2/contacts/:contact_id/people/:person_id/websites' do with_options scope: [:data, :attributes] do parameter 'primary', 'Primary' parameter 'url', 'Url' end example 'Website [CREATE]', document: documentation_scope do explanation 'Create a Website associated with the Person' do_request data: form_data expect(response_status).to eq 201 end end put '/api/v2/contacts/:contact_id/people/:person_id/websites/:id' do with_options scope: [:data, :attributes] do parameter 'primary', 'Primary' parameter 'url', 'Url' end example 'Website [UPDATE]', document: documentation_scope do explanation 'Update the Person\'s Website with the given ID' do_request data: form_data expect(response_status).to eq 200 end end delete '/api/v2/contacts/:contact_id/people/:person_id/websites/:id' do parameter 'contact_id', 'Contact ID', required: true parameter 'person_id', 'Person ID', required: true example 'Website [DELETE]', document: documentation_scope do explanation 'Delete the Person\'s Website with the given ID' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
spec/services/constant_list_spec.rb
require 'rails_helper' RSpec.describe ConstantList, type: :model do subject { ConstantList.new } describe '#currencies' do it { expect(subject.codes).to be_a Array } it 'should consist of ISO 4217 currency codes' do subject.codes.each do |currency| expect(currency).to match(/\A\w{3}\z/) end end it 'should not include currencies no longer in use (eg. AFA and ADP)' do subject.codes.each do |currency| expect(currency).not_to include('ADP', 'AFA') end end end describe '#locales' do it { expect(subject.locales).to be_an Array } it 'should consist of string/symbol pairs' do subject.locales.each do |locale| expect(locale.size).to eq 2 expect(locale.first).to be_a(String) expect(locale.second).to be_a(Symbol) end end it 'should contain a locale code' do subject.locales.each do |locale| expect(locale.second).to match(/\A\w+(?:-\w+)?\z/) end end end describe '#notifications' do before { create :notification_type } it { expect(subject.notifications).to be_a_hash_with_types String, String } end describe '#organizations' do before { 5.times { create(:organization) } } it { expect(subject.organizations).to be_a_hash_with_types String, String } end describe '#organizations_attributes' do before { 5.times { create(:organization) } } it { expect(subject.organizations_attributes).to be_a_hash_with_types String, Hash } it 'keys matches array' do expect(subject.organizations_attributes.first[1].keys).to match_array %i(name api_class help_email oauth) end end describe '#assignable_locations' do it { expect(subject.assignable_locations).to be_an Array } it { subject.assignable_locations.each { |loc| expect(loc).to be_a String } } end describe '#csv_import' do it { expect(subject.csv_import).to be_an Hash } it { expect(subject.csv_import[:supported_headers]).to be_an Hash } it { expect(subject.csv_import[:required_headers]).to be_an Hash } it { expect(subject.csv_import[:constants]).to be_an Hash } it do interception = subject.csv_import[:constants].keys & subject.csv_import[:supported_headers].keys expect(interception).to eq subject.csv_import[:constants].keys end it { expect(subject.csv_import[:constants].keys).to eq CsvImport.constants.keys } it { expect(subject.csv_import[:max_file_size_in_bytes]).to eq Import::MAX_FILE_SIZE_IN_BYTES } end describe '#tnt_import' do it { expect(subject.tnt_import[:max_file_size_in_bytes]).to eq Import::MAX_FILE_SIZE_IN_BYTES } end context '#sources' do it { expect(subject.sources).to be_a_hash_with_types Symbol, Array } end context '#send_appeals' do it { expect(subject.send_appeals).to be_a Hash } end end
chuckmersereau/api_practice
db/migrate/20171023022515_change_pledges_expected_date_to_date.rb
<filename>db/migrate/20171023022515_change_pledges_expected_date_to_date.rb class ChangePledgesExpectedDateToDate < ActiveRecord::Migration def change reversible do |dir| dir.up { change_column :pledges, :expected_date, :date } dir.down { change_column :pledges, :expected_date, :datetime } end end end
chuckmersereau/api_practice
spec/controllers/api/v2/contacts/people/facebook_accounts_controller_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe Api::V2::Contacts::People::FacebookAccountsController, type: :controller do let(:factory_type) { :facebook_account } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact) { create(:contact, account_list: account_list) } let!(:person) { create(:person) } let!(:person2) { create(:person) } let!(:facebook_accounts) { create_list(:facebook_account, 2, person: person) } let(:facebook_account) { facebook_accounts.first } let(:resource) { facebook_account } let(:id) { facebook_account.id } let(:parent_param) { { contact_id: contact.id, person_id: person.id } } let(:unpermitted_attributes) { nil } let(:correct_attributes) { attributes_for(:facebook_account, first_name: 'Albert').except(:person_id) } let(:incorrect_attributes) { { username: nil } } before do contact.people << person end include_examples 'index_examples' include_examples 'show_examples' include_examples 'create_examples' include_examples 'update_examples' include_examples 'destroy_examples' end
chuckmersereau/api_practice
spec/workers/task_notifications_worker_spec.rb
require 'rails_helper' describe TaskNotificationsWorker, sidekiq: :testing_disabled do context 'Create jobs for upcoming tasks' do let(:user) { create(:user, email: create(:email_address)) } let(:account_list) { create(:account_list, users: [user]) } let!(:task) do create(:task, account_list: account_list, start_at: 55.minutes.from_now, notification_time_before: 3, notification_time_unit: 1, notification_type: 'both') end before do clear_uniqueness_locks Sidekiq::ScheduledSet.new.clear end it 'queues the job' do expect { subject.perform }.to change(Sidekiq::ScheduledSet.new, :size).by(1) end it 'queues the job into the mailer queue' do subject.perform expect(Sidekiq::ScheduledSet.new.to_a.last.queue).to eq 'mailers' end it 'does not query a job if mobile only' do task.update(notification_type: 'mobile') expect { subject.perform }.to_not change(Sidekiq::ScheduledSet.new, :size) end it 'will queue a task and use the default time unit if it is missing' do task.update(notification_time_unit: nil, notification_scheduled: nil) notifier = TaskNotificationsWorker.new start_time = task.start_at - task.notification_time_before.send('minutes') expect(notifier.determine_start_time(task)).to eq(start_time) end end end
chuckmersereau/api_practice
db/migrate/20120913194222_add_action_to_tasks.rb
<filename>db/migrate/20120913194222_add_action_to_tasks.rb<gh_stars>0 class AddActionToTasks < ActiveRecord::Migration def change add_column :activities, :activity_type, :string add_index :activities, :activity_type end end
chuckmersereau/api_practice
db/migrate/20150807145306_add_username_to_person_facebook_accounts.rb
<reponame>chuckmersereau/api_practice class AddUsernameToPersonFacebookAccounts < ActiveRecord::Migration def change add_column :person_facebook_accounts, :username, :string change_column :person_facebook_accounts, :remote_id, :bigint, null: true add_index :person_facebook_accounts, [:person_id, :username], unique: true end end
chuckmersereau/api_practice
spec/models/google_contacts_spec.rb
require 'rails_helper' describe GoogleContact do end