repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
chuckmersereau/api_practice
app/serializers/person/linkedin_account_serializer.rb
class Person::LinkedinAccountSerializer < ApplicationSerializer type :linkedin_accounts attributes :created_at, :public_url, :updated_at end
chuckmersereau/api_practice
spec/services/donation_imports/base/find_donation_spec.rb
require 'rails_helper' RSpec.describe DonationImports::Base::FindDonation do let(:designation_profile) { create(:designation_profile) } let(:attributes) { {} } describe 'initialize' do it 'initializes' do new_instance = described_class.new(designation_profile: designation_profile, attributes: attributes) expect(new_instance).to be_a(described_class) end end describe '#find_and_merge' do let(:des_account1) { create(:designation_account) } let(:des_account2) { create(:designation_account) } let(:donor_account) { create(:donor_account) } let(:finder) { described_class.new(designation_profile: designation_profile, attributes: attributes) } before do designation_profile.designation_accounts << des_account1 designation_profile.designation_accounts << des_account2 end it 'finds donations by their remote id or tnt id in multiple designation accounts' do d1 = create(:donation, remote_id: '1234', tnt_id: nil, designation_account: des_account1) d2 = create(:donation, remote_id: nil, tnt_id: '1234', designation_account: des_account2) d3 = create(:donation, remote_id: 'abcd', tnt_id: 'abcd', designation_account: des_account2) attributes[:remote_id] = '1234' found_donation = nil expect { found_donation = finder.find_and_merge }.to change { Donation.count }.from(3).to(2) expect([d1, d2, d3]).to include(found_donation) expect(found_donation.reload.tnt_id).to eq('1234') expect(found_donation.remote_id).to eq('1234') end it 'finds donations by their donor, amount, and date in multiple designation accounts' do base_attributes = { remote_id: nil, tnt_id: '1234', amount: 1.0, donation_date: Date.new, donor_account: donor_account } d1 = create(:donation, base_attributes.merge(designation_account: des_account1)) d2 = create(:donation, base_attributes.merge(designation_account: des_account2)) attributes[:remote_id] = 'abcd' attributes[:donor_account_id] = donor_account.id attributes[:amount] = 1.0 attributes[:donation_date] = Date.new expect do expect([d1, d2]).to include(finder.find_and_merge) end.to change { Donation.count }.from(2).to(1) end it 'also looks on placeholder account' do account_list = create(:account_list) designation_profile.update(account_list: account_list) placeholder_account = account_list.designation_accounts.create!(organization: Organization.first, name: 'User (Imported from TntConnect)') d1 = create(:donation, remote_id: '1234', tnt_id: nil, designation_account: des_account1) d2 = create(:donation, remote_id: nil, tnt_id: '1234', designation_account: placeholder_account) attributes[:remote_id] = '1234' expect do expect([d1, d2]).to include(finder.find_and_merge) end.to change { Donation.count }.from(2).to(1) end it 'looks on the provided designation account' do designation_profile.designation_profile_accounts.where(designation_account: des_account2).first.destroy d1 = create(:donation, remote_id: '1234', tnt_id: nil, designation_account: des_account2) attributes[:remote_id] = '1234' attributes[:designation_account_id] = des_account2.id expect(finder.find_and_merge).to eq d1 end end end
chuckmersereau/api_practice
spec/support/sidekiq.rb
require 'sidekiq/testing' require 'sidekiq_unique_jobs/testing' Sidekiq::Logging.logger = nil RSpec.configure do |config| config.define_derived_metadata do |metadata| metadata[:stub_batches] = false end config.before(:each) do |example| # Clears out the jobs for tests using the fake testing Sidekiq::Worker.clear_all if example.metadata[:sidekiq] == :fake Sidekiq::Testing.fake! elsif example.metadata[:sidekiq] == :testing_disabled Sidekiq::Testing.disable! elsif example.metadata[:sidekiq] == :acceptance Sidekiq::Testing.inline! elsif example.metadata[:type] == :acceptance Sidekiq::Testing.inline! else Sidekiq::Testing.fake! end end end
chuckmersereau/api_practice
spec/factories/activity_contacts.rb
<reponame>chuckmersereau/api_practice FactoryBot.define do factory :activity_contact do activity nil contact nil end end
chuckmersereau/api_practice
app/models/donation_amount_recommendation.rb
<reponame>chuckmersereau/api_practice # This model contains donation amount (recurring & one-off) recommendations for # a donor_account in relation to a designation_account class DonationAmountRecommendation < ApplicationRecord belongs_to :donor_account, inverse_of: :donation_amount_recommendations belongs_to :designation_account, inverse_of: :donation_amount_recommendations validates :donor_account, :designation_account, presence: true end
chuckmersereau/api_practice
app/workers/google_contacts_sync_enqueuer_worker.rb
class GoogleContactsSyncEnqueuerWorker include Sidekiq::Worker sidekiq_options queue: :api_google_contacts_sync_enqueuer_worker, unique: :until_executed def perform AccountList.joins(:google_integrations) .where(google_integrations: { contacts_integration: true }) .find_each(&:queue_sync_with_google_contacts) end end
chuckmersereau/api_practice
app/controllers/api/v2/bulk_controller.rb
<reponame>chuckmersereau/api_practice class Api::V2::BulkController < Api::V2Controller skip_before_action :validate_and_transform_json_api_params before_action :reject_if_in_batch_request before_action :validate_and_transform_bulk_json_api_params private def validate_and_transform_bulk_json_api_params @original_params = params @_params = params.merge( data: bulk_data_from_array_params(data_array_params) ) end def bulk_data_from_array_params(data_array_params) data_array_params.map do |data| missing_id_error unless data['data']['id'] data[:action] = params[:action] data[:controller] = params[:controller] data = ActionController::Parameters.new(data) JsonApiService.consume(params: data, context: self) end end def data_array_params params.dig(:data) || [] end def fetch_account_list_with_filter current_user.account_lists.where(id: account_list_filter) end def missing_id_error raise Exceptions::BadRequestError, 'An `id` is required for every top-level object within the /data array being sent in bulk requests' end def scope_exists!(scope) return scope if scope.exists? # exception pulled from # https://github.com/rails/rails/blob/4-2-stable/activerecord/lib/active_record/relation/finder_methods.rb#L489 raise ActiveRecord::RecordNotFound, "Couldn't find #{scope.klass.name} with [#{scope.arel.where_sql}]" end end
chuckmersereau/api_practice
spec/services/coaching/contact/total_monthly_pledge_spec.rb
require 'rails_helper' describe Coaching::Contact::TotalMonthlyPledge do let(:scope) { Contact.all } let(:account_list) { create(:account_list, settings: { currency: 'GBP' }) } let(:service) { described_class.new(scope, 'GBP') } before do create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 4, 1), rate: 1) create(:currency_rate, code: 'GBP', exchanged_on: Date.new(2016, 4, 1), rate: 2) end it 'no contacts' do expect(service.total).to eq 0 end it 'single contact, monthly' do create_contact amount: 10, frequency: 1, currency: 'EUR' expect(service.total).to eq 20 end it 'single contact, bi-monthly' do create_contact amount: 10, frequency: 0.5, currency: 'EUR' expect(service.total).to eq 40 end it 'single contact, semi-monthly' do create_contact amount: 10, frequency: 2, currency: 'EUR' expect(service.total).to eq 10 end it 'two contacts, monthly' do create_contact amount: 10, frequency: 1, currency: 'EUR' create_contact amount: 20, frequency: 1, currency: 'EUR' expect(service.total).to eq 60 end it 'two contacts, bi-monthly' do create_contact amount: 10, frequency: 0.5, currency: 'EUR' create_contact amount: 20, frequency: 0.5, currency: 'EUR' expect(service.total).to eq 120 end it 'two contacts, semi-monthly' do create_contact amount: 10, frequency: 2, currency: 'EUR' create_contact amount: 20, frequency: 2, currency: 'EUR' expect(service.total).to eq 30 end it 'three contacts, different frequencies' do create_contact amount: 10, frequency: 0.5, currency: 'EUR' create_contact amount: 20, frequency: 1, currency: 'EUR' create_contact amount: 30, frequency: 2, currency: 'EUR' expect(service.total).to eq 110 end it 'returns a result with two digits' do create_contact amount: 10.23456, frequency: 1, currency: 'EUR' expect(service.total).to eq 20.46 end private def create_contact(args = {}) args = Hash[args.map { |k, v| [format('pledge_%s', k), v] }] create(:contact, args.merge(account_list: account_list)) end end
chuckmersereau/api_practice
spec/services/person/filterer_spec.rb
require 'rails_helper' describe Person::Filterer do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } describe '.config' do it 'returns an empty array' do expect(described_class.config([account_list])).to eq [] end end describe '.filter_classes' do it 'returns an empty array' do expect(described_class.filter_classes).to eq [Person::Filter::Deceased, Person::Filter::EmailAddressValid, Person::Filter::PhoneNumberValid, Person::Filter::UpdatedAt, Person::Filter::WildcardSearch] end end describe '.filter_params' do it 'returns an empty array' do expect(described_class.filter_params).to eq [:deceased, :email_address_valid, :phone_number_valid, :updated_at, :wildcard_search] end end describe '#filter' do it 'returns the resource scope' do resource_scope = Person.all expect(described_class.new.filter(scope: resource_scope, account_lists: [account_list])).to eq resource_scope end end end
chuckmersereau/api_practice
spec/services/account_list/merge_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe AccountList::Merge, '#merge' do let!(:loser_user) { create(:user_with_account) } let!(:loser) { loser_user.account_lists.order(:created_at).first } let!(:winner_user) { create(:user_with_account) } let!(:winner) { winner_user.account_lists.order(:created_at).first } before do winner.users << loser_user end it 'deletes old AccountList' do expect { winner.merge(loser) }.to change(AccountList, :count).by(-1) end it 'moves over users' do user = create(:user) loser.users << user winner.merge(loser) expect(winner.reload.users).to include user end it 'merges appeals' do create(:appeal, account_list: loser) expect do winner.merge(loser) end.to change(winner.appeals.reload, :count).by(1) end it 'moves the prayer letters account from the loser if winner lacked one' do create(:prayer_letters_account, account_list: loser) winner.merge(loser) expect(winner.reload.prayer_letters_account).to_not be_nil end it 'leaves the winner prayer letter account if both winner and loser have one' do create(:prayer_letters_account, account_list: loser) winner_pla = create(:prayer_letters_account, account_list: winner) expect { winner.merge(loser) }.to change(PrayerLettersAccount, :count).to(1) expect(winner.reload.prayer_letters_account).to eq(winner_pla) end it 'moves designation accounts if they are missing, runs dup balance fix' do da = create(:designation_account) loser.designation_accounts << da expect(winner).to receive(:async).with(:import_data) expect(DesignationAccount::DupByBalanceFix).to receive(:deactivate_dups) do |designations| expect(designations.to_set).to eq([da].to_set) true end expect do winner.merge(loser) end.to change(winner.designation_accounts, :count).from(0).to(1) end it 'does not create a duplicate if a designation account is in both winner and loser' do da = create(:designation_account) loser.designation_accounts << da winner.designation_accounts << da winner.reload expect(winner.designation_accounts.count).to eq(1) end end
chuckmersereau/api_practice
db/migrate/20120926184516_add_completed_at_to_activity.rb
class AddCompletedAtToActivity < ActiveRecord::Migration def change add_column :activities, :completed_at, :datetime Task.connection.update("UPDATE activities SET completed_at = updated_at WHERE type = 'Task' AND completed = 't'") end end
chuckmersereau/api_practice
spec/services/reports/goal_progress_spec.rb
<filename>spec/services/reports/goal_progress_spec.rb require 'rails_helper' RSpec.describe Reports::GoalProgress, type: :model do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:report) { Reports::GoalProgress.new(account_list: account_list) } let!(:designation_account) do create(:designation_account, organization_id: account_list.salary_organization_id, balance: '9.99') end before do account_list.designation_accounts << designation_account account_list.monthly_goal = 1000.00 end describe 'initializes' do it 'initializes successfully' do expect(report).to be_a(Reports::GoalProgress) expect(report.account_list).to eq account_list end end describe '#salary_balance' do it 'returns the total salary balance' do account_list.designation_accounts << create(:designation_account, organization_id: account_list.salary_organization_id, balance: '0.01') expect(report.salary_balance).to eq 10.00 end it 'converts balance to salary currency' do create(:currency_rate, code: 'USD', rate: 1) create(:currency_rate, code: 'KRW', rate: 10) Organization.find(account_list.salary_organization_id).update(default_currency_code: 'USD') expect(report.salary_balance).to eq 9.99 Organization.find(account_list.salary_organization_id).update(default_currency_code: 'KRW') expect(report.salary_balance).to eq 0.999 end end describe 'delegation' do it 'delegates methods to account list' do expect(report.in_hand_percent).to eq account_list.in_hand_percent expect(report.monthly_goal).to eq account_list.monthly_goal expect(report.pledged_percent).to eq account_list.pledged_percent expect(report.received_pledges).to eq account_list.received_pledges expect(report.salary_currency_or_default).to eq account_list.salary_currency_or_default expect(report.salary_organization_id).to eq account_list.salary_organization_id expect(report.total_pledges).to eq account_list.total_pledges end end end
chuckmersereau/api_practice
db/migrate/20160606160232_add_tags_to_mail_chimp_members.rb
<gh_stars>0 class AddTagsToMailChimpMembers < ActiveRecord::Migration def change add_column :mail_chimp_members, :tags, :string, array: true end end
chuckmersereau/api_practice
db/migrate/20130107135513_add_tnt_id_to_activities.rb
<filename>db/migrate/20130107135513_add_tnt_id_to_activities.rb class AddTntIdToActivities < ActiveRecord::Migration def change add_column :activities, :tnt_id, :string add_index :activities, :tnt_id end end
chuckmersereau/api_practice
spec/rails_helper.rb
<reponame>chuckmersereau/api_practice if ENV['CI'] require 'simplecov' SimpleCov.start 'rails' do add_filter 'dev/' add_filter 'vendor/' end if ENV['COVERALLS_REPO_TOKEN'] require 'coveralls' Coveralls.wear_merged!('rails') end end ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) # Prevent database truncation if the environment is production abort('The Rails environment is not running in test mode!') unless Rails.env.test? require 'spec_helper' require 'rspec/rails' require 'rspec/matchers' require 'rspec/retry' require 'equivalent-xml' require 'ammeter/init' require 'shoulda/matchers' require 'documentation_helper' # Add additional requires below this line. Rails is not loaded until this point! require 'global_registry_bindings/testing' GlobalRegistry::Bindings::Testing.skip_workers! # Include Sidekiq testing helpers and fake sidekiq require 'sidekiq/testing' Sidekiq::Testing.fake! # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } # Checks for pending migration and applies them before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| # Reset seed each time this file is loaded, so that spring won't cache seed # To run a spec with a specific seed, use --order=rand:[seed] config.seed = srand % 0xFFFF unless ARGV.any? { |arg| arg =~ /seed/ } config.order = :random # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, :type => :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Exclude gems from spec backtraces, except a few directly related to our app config.filter_gems_from_backtrace( *(Gem::Specification.map(&:name) - %w(google_contacts_api siebel_donations)) ) # Exclude tests that are deprecated config.filter_run_excluding :deprecated config.include Devise::Test::ControllerHelpers, type: :controller config.include FactoryBot::Syntax::Methods config.include HeaderHelpers, type: :controller config.include JsonApiHelper, type: :acceptance config.include JsonApiHelper, type: :controller config.include JsonApiHelper, type: :request config.include MpdxHelpers config.include AuthHelper, :auth config.include ActiveSupport::Testing::TimeHelpers # Ensure jobs don't linger between tests config.before(:each) do Sidekiq::Worker.clear_all end end def response_json JSON.parse(response.body) end # locks the current time down to the second so we don't hit differences in updated_in_db_at def lock_time_around around(:example) do |example| travel_to Time.zone.now, &example end end
chuckmersereau/api_practice
spec/controllers/api/v2/tools/analytics_controller_spec.rb
<filename>spec/controllers/api/v2/tools/analytics_controller_spec.rb require 'rails_helper' RSpec.describe Api::V2::Tools::AnalyticsController, type: :controller do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:second_account_list) { create(:account_list, users: [user]) } let!(:contact_one) { create(:contact, account_list: account_list, status_valid: false) } let!(:contact_two) { create(:contact, account_list: account_list) } let(:resource) do Tools::Analytics.new( account_lists: [account_list] ) end let(:given_reference_key) { 'counts_by_type' } include_examples 'show_examples', except: [:sparse_fieldsets] context 'filtering by account_list_id' do let(:full_params) do { filter: { account_list_id: second_account_list.id } } end it 'filters out other account_lists' do api_login(user) get :show, full_params expect(response.status).to eq(200) expect(response.body).to_not include(account_list.id) end end end
chuckmersereau/api_practice
app/serializers/application_filter_serializer.rb
class ApplicationFilterSerializer < ActiveModel::Serializer attributes :name, :title, :type, :parent, :default_selection, :multiple, :options end
chuckmersereau/api_practice
spec/services/task/filter/contact_ids_spec.rb
require 'rails_helper' RSpec.describe Task::Filter::ContactIds do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact_one) { create(:contact, account_list: account_list) } let!(:contact_two) { create(:contact, account_list: account_list) } let!(:task_one) { create(:task, account_list: account_list, contacts: [contact_one]) } let!(:task_two) { create(:task, account_list: account_list, contacts: [contact_two]) } describe '#config' do it 'returns expected config' do options = [{ name: '-- Any --', id: '', placeholder: 'None' }] + account_list.contacts.order('name ASC').collect do |contact| { name: contact.to_s, id: contact.id, account_list_id: account_list.id } end expect(described_class.config([account_list])).to include(default_selection: '', multiple: true, name: :contact_ids, options: options, parent: nil, priority: 1, title: 'Contacts', type: 'multiselect') end end 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, { contact_ids: {} }, nil)).to eq(nil) expect(described_class.query(tasks, { contact_ids: [] }, nil)).to eq(nil) expect(described_class.query(tasks, { contact_ids: '' }, nil)).to eq(nil) end end context 'filter by activity_type' do it 'filters single contact' do expect(described_class.query(tasks, { contact_ids: contact_one.id }, nil).to_a).to include(task_one) end it 'filters multiple contacts' do results = described_class.query(tasks, { contact_ids: "#{contact_one.id}, #{contact_two.id}" }, nil).to_a expect(results).to include(task_two) end end end end
chuckmersereau/api_practice
app/controllers/api/v2/account_lists/imports/tnt_controller.rb
# This controller supports Content-Type multipart/form-data for file uploads. An example request in curl could look like: # # curl "http://localhost:3000/api/v2/account_lists/23882dc0-e7d2-4170-8667-f1896e8427fa/imports/tnt" \ # -X POST \ # -H "Authorization: ..." \ # -H 'Content-Type: multipart/form-data' \ # -F 'data[attributes][file]=@/Users/sheldon/Dev/mpdx_api/spec/fixtures/tnt/tnt_export.xml' \ # -F "data[type]=imports" class Api::V2::AccountLists::Imports::TntController < Api::V2Controller resource_type :imports supports_content_types 'multipart/form-data' def create persist_import end private def render_import render json: @import, status: success_status, include: include_params, fields: field_params end def persist_import build_import authorize_import if save_import render_import else render_with_resource_errors(@import) end end def build_import @import ||= import_scope.build @import.assign_attributes(import_params) end def authorize_import authorize @import end def save_import @import.save(context: persistence_context) end def import_params params .require(:import) .permit(Import::PERMITTED_ATTRIBUTES) .merge(source: 'tnt', user_id: current_user.id) end def import_scope load_account_list.imports.where(source: 'tnt') end def load_account_list @account_list ||= AccountList.find(params[:account_list_id]) end def pundit_user PunditContext.new(current_user, account_list: load_account_list) end end
chuckmersereau/api_practice
spec/services/account_list/readable_finder_spec.rb
require 'rails_helper' describe AccountList::ReadableFinder do let(:coach) { create(:user_with_account).becomes(User::Coach) } let(:coach_id) { coach.id } subject { AccountList::ReadableFinder.new(coach) } let(:coached_user) { create :user_with_account } let(:account_list) { coach.account_lists.order(:created_at).first } let(:coached_account_list) { coached_user.account_lists.order(:created_at).first } let(:uncoached_account_list) do create(:account_list).tap do |account_list| coached_user.account_lists << account_list end end it 'generates the correct SQL' do expect(subject.to_sql).to eq( '"account_lists"."id" IN (SELECT "account_lists"."id" FROM ' \ '"account_lists" LEFT OUTER JOIN "account_list_coaches" ON ' \ '"account_lists"."id" = "account_list_coaches"."account_list_id"' \ ' LEFT OUTER JOIN "account_list_users" ON "account_lists"."id" =' \ ' "account_list_users"."account_list_id" WHERE ' \ "(\"account_list_users\".\"user_id\" = '#{coach_id}' OR " \ "\"account_list_coaches\".\"coach_id\" = '#{coach_id}'))" ) end it 'returns owned account_lists' do expect(subject.relation.to_a).to eq [account_list] end it 'returns coached account_lists' do coach.update!(account_lists: [], coaching_account_lists: [coached_account_list]) expect(subject.relation.to_a).to eq [coached_account_list] end it 'returns coached and owned account_lists' do coach.update!(coaching_account_lists: [coached_account_list]) expect(subject.relation.to_a).to include account_list, coached_account_list end it 'returns coached and owned account_lists' do coach.update!(coaching_account_lists: [coached_account_list]) expect(subject.relation.to_a).not_to include uncoached_account_list end end
chuckmersereau/api_practice
app/policies/appeal_policy.rb
<gh_stars>0 class AppealPolicy < ApplicationPolicy def initialize(context, resource) @user = context.user @resource = resource end private def resource_owner? user.account_lists.exists?(id: resource.account_list_id) end end
chuckmersereau/api_practice
app/serializers/designation_account_serializer.rb
<reponame>chuckmersereau/api_practice class DesignationAccountSerializer < ApplicationSerializer include ApplicationHelper delegate :account_list, :account_lists, :currency, :organization, to: :object delegate :name, to: :organization, prefix: true attributes :designation_number, :organization_name, :balance, :name, :currency, :currency_symbol, :converted_balance, :exchange_rate, :balance_updated_at, :active, :display_name belongs_to :organization has_many :balances def display_name return _('Unknown') if object.name.blank? && object.designation_number.blank? return object.designation_number if object.name.blank? return object.name if object.designation_number.blank? || object.name.include?(object.designation_number) "#{object.name} (#{object.designation_number})" end def currency_symbol super(object.currency) end def converted_balance object.converted_balance(total_currency).to_f end def total_currency list&.salary_currency_or_default end def exchange_rate CurrencyRate.latest_for_pair(from: currency, to: total_currency) rescue CurrencyRate::RateNotFoundError => e Rollbar.error(e) 'missing' end def active object.active && object.organization_id == list&.salary_organization_id end private def list scope.is_a?(User) ? account_list(scope) : account_lists.order(:created_at).first end end
chuckmersereau/api_practice
app/models/activity.rb
class Activity < ApplicationRecord acts_as_taggable REPORT_STATES = %w(completed uncompleted).freeze audited associated_with: :account_list, except: [:updated_at, :activity_comments_count, :notification_scheduled] belongs_to :account_list belongs_to :notification, inverse_of: :tasks has_many :comments, dependent: :delete_all, class_name: 'ActivityComment' has_many :activity_contacts, dependent: :destroy has_many :contacts, through: :activity_contacts has_many :email_addresses, through: :people has_many :google_email_activities, dependent: :delete_all has_many :google_emails, through: :google_email_activities has_many :google_events has_many :people, through: :contacts has_many :phone_numbers, through: :people scope :completed, -> { where(completed: true).order('completed_at desc, start_at desc') } scope :uncompleted, -> { where(completed: false).order('start_at') } scope :starred, -> { where(starred: true).order('start_at') } scope :overdue, lambda { where(completed: false) .where('start_at < ?', Time.current.beginning_of_day) .order('start_at DESC') } scope :overdue_and_today, -> { where(completed: false).where('start_at < ?', Time.current.end_of_day) } scope :today, lambda { where('start_at BETWEEN ? AND ?', Time.current.beginning_of_day, Time.current.end_of_day) .order('start_at') } scope :tomorrow, lambda { tomorrow = Date.current + 1.day where('start_at BETWEEN ? AND ?', tomorrow.beginning_of_day, tomorrow.end_of_day) .order('start_at') } scope :future, -> { where('start_at > ?', Time.current).order('start_at') } scope :upcoming, -> { where('start_at > ?', Time.current.end_of_day).order('start_at') } scope :no_date, -> { where('start_at IS NULL') } accepts_nested_attributes_for :activity_contacts, allow_destroy: true accepts_nested_attributes_for :comments, reject_if: :all_blank validates :subject, presence: true def to_s subject end def contacts_attributes=(contacts_array) contacts_array = contacts_array.values if contacts_array.is_a?(Hash) contacts_array.each do |contact_attributes| contact = Contact.find(contact_attributes['id']) if contact_attributes['_destroy'].to_s == 'true' contacts.delete(contact) if contacts.include?(contact) else contacts << contact unless contacts.include?(contact) end end end def activity_comment=(hash) comments.new(hash) if hash.values.any?(&:present?) end def assignable_contacts assigned_contact_ids = activity_contacts.pluck(:contact_id) return account_list.active_contacts if assigned_contact_ids.empty? account_list.contacts .where(Contact.active_conditions + ' OR contacts.id IN (?)', assigned_contact_ids) end end
chuckmersereau/api_practice
app/services/donation_reports/donor_info.rb
class DonationReports::DonorInfo < ActiveModelSerializers::Model ATTRIBUTES = [ :contact_id, :contact_name, :late_by_30_days, :late_by_60_days, :pledge_amount, :pledge_currency, :pledge_frequency, :status ].freeze attr_accessor(*ATTRIBUTES) def self.from_contact(contact) new( contact_id: contact.id, contact_name: contact.name, late_by_30_days: contact.late_by?(31, 60), late_by_60_days: contact.late_by?(60), pledge_amount: contact.pledge_amount, pledge_currency: contact.pledge_currency, pledge_frequency: contact.pledge_frequency, status: contact.status ) end end
chuckmersereau/api_practice
spec/controllers/api/v2/tasks/comments_controller_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/controllers/api/v2/tasks/comments_controller_spec.rb require 'rails_helper' RSpec.describe Api::V2::Tasks::CommentsController, type: :controller do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:person) { create(:contact_with_person, account_list: account_list).reload.people.first } let(:activity) { create(:activity, account_list: account_list) } let!(:resource) { create(:activity_comment, activity: activity, person: user) } let!(:second_resource) { create(:activity_comment, activity: activity, person: person) } let(:id) { resource.id } let(:parent_param) { { task_id: activity.id } } let(:parent_association) { :activity } let(:correct_attributes) { { body: 'My insightful comment' } } let(:unpermitted_attributes) { nil } let(:incorrect_attributes) { nil } let!(:not_destroyed_scope) { ActivityComment } let(:factory_type) { :activity_comment } let(:correct_relationships) do { person: { data: { type: 'people', id: user.id } } } end let(:unpermitted_relationships) do { person: { data: { type: 'people', id: create(:person).id } } } end include_examples 'show_examples' include_examples 'update_examples' include_examples 'create_examples' include_examples 'destroy_examples' include_examples 'index_examples' describe '#index authorization' do it 'does not show resources for contact that user does not own' do api_login(user) activity = create(:activity, account_list: create(:user_with_account).account_lists.order(:created_at).first) get :index, task_id: activity.id expect(response.status).to eq(403) end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/export_to_mailchimp_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > Export to MailChimp' do include_context :json_headers documentation_scope = :contacts_api_exports let(:resource_type) { 'mail-chimp-account' } let!(:user) { create(:user_with_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(:primary_list_id) { '1e72b58b72' } let(:second_list_id) { '1e72b58b44' } let(:mail_chimp_account) { MailChimpAccount.new(api_key: 'fake-us4', primary_list_id: primary_list_id) } before do allow(MailChimp::ExportContactsWorker).to receive(:perform_async) allow_any_instance_of(MailChimpAccount).to receive(:lists).and_return([]) allow_any_instance_of(MailChimpAccount).to receive(:validate_key) mail_chimp_account.account_list = account_list mail_chimp_account.save api_login(user) end context 'authorized user' do post '/api/v2/contacts/export_to_mail_chimp' do parameter 'account_list_id', 'Account List ID', scope: :filter parameter 'contact_ids', 'Account List ID', scope: :filter parameter 'mail_chimp_list_id', 'Mail Chimp List ID', required: true example 'Export to Mail Chimp [POST]', document: documentation_scope do explanation 'Export Contacts with the given ID to the Mail Chimp server' do_request mail_chimp_list_id: second_list_id expect(response_status).to eq 200 end end end end
chuckmersereau/api_practice
app/controllers/api/v2/contacts/referrers_controller.rb
class Api::V2::Contacts::ReferrersController < Api::V2Controller def index authorize_index load_referrers render_referrers end private def current_contact @contact ||= Contact.find(params[:contact_id]) end def referrer_scope current_contact.contacts_that_referred_me end def authorize_index authorize(current_contact, :show?) end def load_referrers @referrers = referrer_scope.where(filter_params) .reorder(sorting_param) .order(default_sort_param) .page(page_number_param) .per(per_page_param) end def render_referrers render json: @referrers.preload_valid_associations(include_associations), meta: meta_hash(@referrers), include: include_params, fields: field_params end def pundit_user PunditContext.new(current_user, contact: current_contact) end def default_sort_param Contact.arel_table[:created_at].asc end end
chuckmersereau/api_practice
spec/services/person/filter/email_address_valid_spec.rb
require 'rails_helper' RSpec.describe Person::Filter::EmailAddressValid do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact_one) { create(:contact, account_list_id: account_list.id) } let!(:contact_two) { create(:contact, account_list_id: account_list.id) } let!(:person_one) { create(:person, contacts: [contact_one]) } let!(:person_two) { create(:person, contacts: [contact_one]) } let!(:person_three) { create(:person, contacts: [contact_two]) } let!(:person_four) { create(:person, contacts: [contact_two]) } let!(:email_address_one) { create(:email_address, person: person_one) } let!(:email_address_two) { create(:email_address, person: person_one) } let!(:email_address_three) { create(:email_address, person: person_one) } let!(:email_address_four) { create(:email_address, person: person_three) } let!(:email_address_five) { create(:email_address, person: person_four) } let!(:email_address_six) { create(:email_address, person: person_two) } before do email_address_one.update_columns(valid_values: true, primary: true) email_address_two.update_columns(valid_values: true, primary: true) email_address_three.update_columns(valid_values: true, primary: false) email_address_four.update_columns(valid_values: false, primary: false) email_address_five.update_columns(valid_values: false, primary: false) email_address_six.update_columns(valid_values: true, primary: true) end describe '#query' do let(:scope) { Person.all } context 'no filter params' do it 'returns nil' do expect(described_class.query(scope, {}, nil)).to eq(nil) expect(described_class.query(scope, { email_address_valid: {} }, nil)).to eq(nil) expect(described_class.query(scope, { email_address_valid: [] }, nil)).to eq(nil) expect(described_class.query(scope, { email_address_valid: '' }, nil)).to eq(nil) end end context 'filter by email address invalid' do it 'returns only people that have an invalid email address' do results = described_class.query(scope, { email_address_valid: 'false' }, nil).to_a expect(results).to match_array [person_one, person_three, person_four] end end end end
chuckmersereau/api_practice
engines/auth/config/environments/development.rb
require 'omniauth' OmniAuth.config.full_host = 'http://auth.lvh.me:3000'
chuckmersereau/api_practice
app/services/admin/user_finder.rb
class Admin::UserFinder class << self def find_users(id_name_or_email) if UUID_REGEX.match?(id_name_or_email) users_by_id(id_name_or_email) elsif id_name_or_email =~ /@/ users_by_login_email(id_name_or_email) else users_by_name(id_name_or_email) end end def find_user_by_email(email) @users = users_by_login_email(email) return false if @users.count > 1 @users.first end private def users_by_id(id) User.where(id: id) end def users_by_login_email(email) User.where(id: user_id_by_email(email)) end def users_by_name(name) if name.include?(',') last_name, first_name = name.split(',') else first_name, last_name = name.split end users_by_first_last(first_name, last_name) end def users_by_first_last(first_name, last_name) User.joins(:account_list_users) .where('lower(people.first_name) = ?', first_name.to_s.downcase.strip) .where('lower(people.last_name) = ?', last_name.to_s.downcase.strip) .uniq end def user_id_by_email(email) Person::KeyAccount.where('lower(email) = ?', email.downcase).pluck(:person_id) end end end
chuckmersereau/api_practice
spec/workers/lower_retry_worker_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe LowerRetryWorker do it 'calls the specified method on the given class' do account = build_stubbed(:account_list, id: SecureRandom.uuid) expect(AccountList).to receive(:find).with(account.id) { account } expect(account).to receive(:import_data) LowerRetryWorker.new.perform('AccountList', account.id, 'import_data') end it 'does nothing if the record is not found' do expect do LowerRetryWorker.new.perform('AccountList', -1, 'import_data') end.to_not raise_error end end
chuckmersereau/api_practice
db/migrate/20170217220712_add_default_mpdx_to_existing_address_source.rb
class AddDefaultMpdxToExistingAddressSource < ActiveRecord::Migration def up Address.where(source: ['manual', nil]).update_all(source: 'MPDX') end def down Address.where(source: 'MPDX').update_all(source: nil) end end
chuckmersereau/api_practice
app/models/nickname.rb
<filename>app/models/nickname.rb class Nickname < ApplicationRecord def self.increment_times_merged(name, nickname) find_and_increment_counter(name, nickname, :num_merges) end def self.increment_not_duplicates(name, nickname) find_and_increment_counter(name, nickname, :num_not_duplicates) end def self.find_and_increment_counter(name, nickname, counter) name = name.downcase nickname = nickname.downcase return if name == nickname || name =~ /[\s\-\.]/ || nickname =~ /[\s\-\.]/ || name.length == 1 || nickname.length == 1 Retryable.retryable do nickname = find_or_create_by(name: name, nickname: nickname) end increment_counter(counter, nickname.id) end end
chuckmersereau/api_practice
app/serializers/user/authenticate_serializer.rb
class User::AuthenticateSerializer < ServiceSerializer type :authenticate attributes :json_web_token delegate :json_web_token, to: :object end
chuckmersereau/api_practice
app/serializers/prayer_letters_account_serializer.rb
class PrayerLettersAccountSerializer < ApplicationSerializer attribute :token end
chuckmersereau/api_practice
db/migrate/20140325143531_create_google_events.rb
<reponame>chuckmersereau/api_practice class CreateGoogleEvents < ActiveRecord::Migration def change create_table :google_events do |t| t.belongs_to :activity, index: true t.belongs_to :google_integration, index: true t.string :google_event_id t.timestamps null: false end remove_column :activities, :google_event_id, :string end end
chuckmersereau/api_practice
spec/services/contact/filter/address_valid_spec.rb
<filename>spec/services/contact/filter/address_valid_spec.rb require 'rails_helper' RSpec.describe Contact::Filter::AddressValid do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact_one) { create(:contact, account_list: account_list) } let!(:contact_two) { create(:contact, account_list: account_list) } let!(:contact_three) { create(:contact, account_list: account_list) } let!(:contact_four) { create(:contact, account_list: account_list) } let!(:contact_five) { create(:contact, account_list: account_list) } let!(:address_one) { create(:address, addressable: contact_one, primary_mailing_address: false) } let!(:address_two) { create(:address, addressable: contact_two, primary_mailing_address: false) } let!(:address_three) { create(:address, addressable: contact_three, primary_mailing_address: false) } let!(:address_four) { create(:address, addressable: contact_four, primary_mailing_address: false) } let!(:address_five) { create(:address, addressable: contact_five, primary_mailing_address: false, deleted: true) } let!(:primary_address_one) { create(:address, addressable: contact_one, primary_mailing_address: true) } let!(:primary_address_two) { create(:address, addressable: contact_one, primary_mailing_address: true) } let!(:primary_address_three) { create(:address, addressable: contact_two, primary_mailing_address: true) } let!(:primary_address_four) { create(:address, addressable: contact_five, primary_mailing_address: true) } let!(:primary_address_five) do create(:address, addressable: contact_five, primary_mailing_address: true, deleted: true) end before do address_one.update(valid_values: true) address_two.update(valid_values: true) address_three.update(valid_values: true) address_four.update(valid_values: false) address_five.update(valid_values: false) primary_address_one.update(valid_values: true) primary_address_two.update(valid_values: true) primary_address_three.update(valid_values: true) primary_address_four.update(valid_values: true) primary_address_five.update(valid_values: true) end describe '#config' do it 'does not support returning config' do expect(described_class.config([account_list])).to eq nil 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, { address_valid: {} }, nil).to_a).to eq([]) expect(described_class.query(contacts, { address_valid: [] }, nil).to_a).to eq([]) expect(described_class.query(contacts, { address_valid: '' }, nil).to_a).to eq([]) expect(described_class.query(contacts, { address_valid: 'wut' }, nil).to_a).to match_array(contacts) end end context 'filter by not address valid' do it 'returns only contacts that have an invalid address' do expect( described_class.query(contacts, { address_valid: 'false' }, nil).to_a ).to match_array [contact_four, contact_one] end it 'returns all of the contacts addresses' do contact_four.addresses.create(valid_values: true) found_contacts = described_class.query(contacts, { address_valid: 'false' }, nil) expect(found_contacts.find(contact_one.id).addresses.size).to eq 3 expect(found_contacts.find(contact_four.id).addresses.size).to eq 2 end end end end
chuckmersereau/api_practice
db/migrate/20140207151457_add_source_account_id_to_import.rb
class AddSourceAccountIdToImport < ActiveRecord::Migration def change add_column :imports, :source_account_id, :integer end end
chuckmersereau/api_practice
db/migrate/20171002211135_convert_pledge_state_fields_to_enum.rb
class ConvertPledgeStateFieldsToEnum < ActiveRecord::Migration class PledgeForMigration < ActiveRecord::Base self.table_name = 'pledges' end def up add_column(:pledges, :status, :string, default: 'not_received') PledgeForMigration.where(received_not_processed: true).update_all(status: 'received_not_processed') PledgeForMigration.where(processed: true).update_all(status: 'processed') remove_column(:pledges, :processed) remove_column(:pledges, :received_not_processed) end def down add_column(:pledges, :processed, :boolean, default: false) add_column(:pledges, :received_not_processed, :boolean, default: false) PledgeForMigration.where(status: 'received_not_processed').update_all(received_not_processed: true) PledgeForMigration.where(status: 'processed').update_all(processed: true) remove_column(:pledges, :status) end end
chuckmersereau/api_practice
app/mailers/task_notification_mailer.rb
class TaskNotificationMailer < ApplicationMailer layout 'inky' def notify(task_id, user_id) @task = Task.find_by(id: task_id) @user = User.find_by(id: user_id) email = @user&.email&.email return unless @task && email I18n.locale = @user.locale || 'en' Time.use_zone(@user.time_zone) do mail to: email, subject: _('Task on MPDX') end end end
chuckmersereau/api_practice
lib/async.rb
module Async # This will be called by a worker when a job needs to be processed def perform(id, method, *args) if id begin self.class.find(id).send(method, *args) rescue ActiveRecord::RecordNotFound # If this instance has been deleted, oh well. end else send(method, *args) end end # We can pass this any Repository instance method that we want to # run later. def async(method, *args) Sidekiq::Client.enqueue(self.class, id, method, *args) end def async_to_queue(queue, method, *args) Sidekiq::Client.enqueue_to(queue, self.class, id, method, *args) end def lower_retry_async(method, *args) LowerRetryWorker.perform_async(self.class.name, id, method, *args) end end
chuckmersereau/api_practice
app/models/organization.rb
<reponame>chuckmersereau/api_practice<filename>app/models/organization.rb<gh_stars>0 require 'async' class Organization < ApplicationRecord include Async # To allow batch processing of address merges include Sidekiq::Worker sidekiq_options queue: :api_organization, retry: false, unique: :until_executed delegate :requires_credentials?, to: :api_class has_many :designation_accounts, dependent: :destroy has_many :designation_profiles, dependent: :destroy has_many :donor_accounts, dependent: :destroy has_many :master_person_sources, dependent: :destroy has_many :master_people, through: :master_person_sources has_many :organization_accounts, class_name: 'Person::OrganizationAccount' validates :name, :query_ini_url, presence: true validates :name, uniqueness: true, case_sensitive: false before_create :guess_country before_create :guess_locale scope :active, -> { where('addresses_url is not null') } scope :using_data_server, -> { where("api_class LIKE 'DataServer%'") } def to_s name end def api_class super.constantize end def api(org_account) api_class.new(org_account) end def self.cru_usa Organization.find_by(code: 'CCC-USA') end def default_currency_code self[:default_currency_code] || 'USD' end def guess_country self.country = country_from_name end def guess_locale return self.locale = 'en' unless country.present? self.locale = ISO3166::Country.find_country_by_name(country)&.languages&.first || 'en' end # We had an organization, DiscipleMakers with a lot of duplicate addresses in its contacts and donor # accounts due to a difference in how their data server donor import worked and a previous iteration of # MPDX accepting duplicate addresses there. This will merge dup addresses in their donor accounts and # contacts. The merging takes a while given the large number of duplicate addressees, so it made # sense to run it as a single background job for the organizaton via Sidekiq/Async. def merge_all_dup_addresses # Use find_each with a small batch size to not use up memory donor_accounts.find_each(batch_size: 5, &:merge_addresses) account_lists = AccountList.joins(:users) .joins('INNER JOIN person_organization_accounts ON person_organization_accounts.person_id = people.id') .where(person_organization_accounts: { organization_id: id }) account_lists.find_each(batch_size: 1) do |account_list| account_list.contacts.find_each(batch_size: 5, &:merge_addresses) end end def oauth? oauth_url.present? end protected def country_from_name country_name = remove_prefixes_from_name return 'Canada' if country_name == 'CAN' ::CountrySelect::COUNTRIES_FOR_SELECT.find do |country| country[:name] == country_name || country[:alternatives].split(' ').include?(country_name) end.try(:[], :name) end def remove_prefixes_from_name country_name = name ['Campus Crusade for Christ - ', 'Cru - ', 'Power To Change - ', 'Gospel For Asia', 'Agape'].each do |prefix| country_name = country_name.gsub(prefix, '') end country_name = country_name.split(' - ').last if country_name.include? ' - ' country_name.strip end end
chuckmersereau/api_practice
db/migrate/20160428125403_create_appeal_excluded_appeal_contact.rb
<filename>db/migrate/20160428125403_create_appeal_excluded_appeal_contact.rb class CreateAppealExcludedAppealContact < ActiveRecord::Migration def change create_table :appeal_excluded_appeal_contacts do |t| t.integer :appeal_id t.integer :contact_id t.text :reasons, array: true end add_index :appeal_excluded_appeal_contacts, [:appeal_id, :contact_id], unique: true, name: 'index_excluded_appeal_contacts_on_appeal_and_contact' add_foreign_key :appeal_excluded_appeal_contacts, :contacts, dependent: :delete add_foreign_key :appeal_excluded_appeal_contacts, :appeals, dependent: :delete end end
chuckmersereau/api_practice
lib/json_api_service/transformer.rb
require 'action_controller' require 'json_api_service/params_object' module JsonApiService class Transformer def self.transform(params:, configuration:) new(params: params, configuration: configuration).transform end attr_reader :configuration, :params def initialize(params:, configuration:) @orig_params = params @params = convert_params(params) @configuration = configuration after_initialize end def create? params.dig(:action).to_s.to_sym == :create end def update? params.dig(:action).to_s.to_sym == :update end def destroy? params.dig(:action).to_s.to_sym == :destroy end def transform ActionController::Parameters.new(transform_params) end private def after_initialize raise ArgumentError, argument_error_message unless @orig_params.is_a? ActionController::Parameters end def argument_error_message 'must provide an ActionController::Parameters object, ie: the params from a controller action' end def attributes_for_object(object) (object.dig(:attributes) || {}).tap do |attributes| id = object.dig(:id) attributes[:id] = id if (create? || update?) && id.present? && id.to_sym != :undefined end end def convert_params(params_object) ParamsObject.new(params: params_object).to_h end def foreign_keys_for_object(object) relationships = object.dig(:relationships) || {} relationships .select { |_type, value| value.dig(:data).is_a? Hash } .each_with_object({}) do |(key, value), hash| hash.merge!(generate_foreign_key_from_relationship(key, value)) end end def generate_foreign_key_from_relationship(key, value) foreign_key = "#{key}_id" id = value.dig(:data, :id) id = id == 'none' ? nil : id configuration.resource_lookup.find(value.dig(:data, :type)).find(id) if id { foreign_key => id } end def id_data_for_object(object, nested) id = object.dig(:id) return {} unless id && id.to_sym != :undefined return { id: id } if !nested || configuration.resource_lookup.find(object.dig(:type)).find_by(id: object.dig(:id)) { _client_id: id } end def nested_attributes_for_object(object) relationships = object.dig(:relationships) || {} relationships .select { |_type, value| value.dig(:data).is_a? Array } .each_with_object({}) do |(type, value), hash| id_key = "#{type}_attributes" objects = value.dig(:data) hash[id_key] = objects_array_to_nested_attributes_hash(objects).map do |attribute_hash| attribute_hash.merge(overwrite: true) end end end def objects_array_to_nested_attributes_hash(objects) objects .each_with_object({}) .map { |object| transform_data_object(object, true) } end def primary_key params.dig(:data, :type)&.singularize end def transform_data_object(object, nested = false) id_data = id_data_for_object(object, nested) attributes = attributes_for_object(object) foreign_keys = foreign_keys_for_object(object) nested_attributes = nested_attributes_for_object(object) attributes.delete(:id) if nested && id_data.key?(:_client_id) attributes .merge!(id_data) .merge!(foreign_keys) .merge!(nested_attributes) end def transformed_non_data_params non_data_params = params.except(:data) filter_object = params.dig(:filter) non_data_params.tap do |params| params[:filter] = transform_filter_object(filter_object) if filter_object end end def transform_filter_object(filter_object) transformed_object = filter_object.each_with_object({}) do |(foreign_key, id), hash| next unless foreign_key.to_s.end_with?('_id') id = id.to_s.split(',').uniq.map(&:strip).select(&:presence) hash[foreign_key] = id.one? ? id.first : id end filter_object.merge!(transformed_object) end def transform_params if create? || update? || destroy? { primary_key => transform_data_object(params.dig(:data)) }.merge!(transformed_non_data_params) else transformed_non_data_params end end end end
chuckmersereau/api_practice
spec/controllers/api/v2/contacts/people/bulk_controller_spec.rb
<filename>spec/controllers/api/v2/contacts/people/bulk_controller_spec.rb require 'rails_helper' describe Api::V2::Contacts::People::BulkController, type: :controller do let(:resource_type) { :people } let!(:factory_type) { :person } let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:account_list_id) { account_list.id } let!(:id) { resource.id } let!(:resource) { create(:person, contacts: [contact]) } let!(:second_resource) { create(:person, contacts: [contact]) } let!(:third_resource) { create(:person, contacts: [contact]) } let!(:contact) { create(:contact, account_list: account_list) } let!(:incorrect_reference_value) { resource.send(reference_key) } let!(:given_reference_key) { :first_name } let!(:given_reference_value) { correct_attributes[:first_name] } let!(:correct_attributes) do attributes_for(:person, first_name: 'Michael', last_name: 'Bluth') end let!(:incorrect_attributes) do attributes_for(:person, first_name: nil) end let(:relationships) do { contacts: { data: [{ type: 'contacts', id: contact.id }] } } end let(:forbidden_relationships) do { contacts: { data: [ { type: 'contacts', id: create(:contact).id } ] } } end include_examples 'bulk_create_examples' # skipping forbidden resources as you can't update a person's contact relationship via bulk include_examples 'bulk_update_examples', except: [:forbidden_resources] include_examples 'bulk_destroy_examples' end
chuckmersereau/api_practice
app/services/google_calendar_integrator.rb
class GoogleCalendarIntegrator attr_accessor :google_integration, :google_account, :calendar_service def initialize(google_integration, calendar_service) @google_integration = google_integration @google_account = google_integration.google_account @calendar_service = calendar_service end def sync_data return unless google_integration.calendar_integration? && calendar_service && google_integration.calendar_id task_ids = google_integration.account_list.tasks.future.uncompleted.of_type(google_integration.calendar_integrations).ids task_ids.map { |task_id| sync_task(task_id) } end alias sync_tasks sync_data def sync_task(task_id) return unless google_integration.calendar_integration? && calendar_service && google_integration.calendar_id task = Task.find_by(id: task_id) google_event = GoogleEvent.find_by(google_integration_id: google_integration.id, calendar_id: google_integration.calendar_id, activity_id: task_id) if !task || !google_integration.calendar_integrations.include?(task.activity_type) remove_google_event(google_event) if google_event elsif google_event update_task(task, google_event) else add_task(task) end end private def remove_google_event(google_event) begin calendar_service.delete_event(google_integration.calendar_id, google_event.google_event_id) rescue Google::Apis::ClientError => error raise error unless status_code_indicates_event_is_no_longer_available?(error.status_code) end google_event.destroy end def update_task(task, google_event) calendar_service.patch_event(google_integration.calendar_id, google_event.google_event_id, build_api_event_from_mpdx_task(task)) rescue Google::Apis::ClientError => error raise error unless status_code_indicates_event_is_no_longer_available?(error.status_code) google_event&.destroy add_task(task) end def add_task(task) result_event = calendar_service.insert_event(google_integration.calendar_id, build_api_event_from_mpdx_task(task)) task.google_events.create!(google_integration_id: google_integration.id, calendar_id: google_integration.calendar_id, google_event_id: result_event.id) rescue Google::Apis::ClientError => error raise error unless error.status_code == 404 # A 404 error here means the calendar being referenced doesn't exist on this Google account google_integration.update_attributes( calendar_id: nil, calendar_name: nil, calendar_integration: false ) end def event_summary_for_task(task) first_part = [task.contacts.map(&:to_s).join(', '), _(task.activity_type)].select(&:present?).join(' - ') [first_part, task.subject].select(&:present?).join(': ') end def build_api_event_from_mpdx_task(task) event = Google::Apis::CalendarV3::Event.new event.summary = event_summary_for_task(task) event.location = task.location&.to_s event.description = task.comments.map(&:body).join("\n\n") event.source = Google::Apis::CalendarV3::Event::Source.new(title: 'MPDX', url: 'https://mpdx.org/tasks') if task.default_length event.start = Google::Apis::CalendarV3::EventDateTime.new(date_time: task.start_at.to_datetime.rfc3339) end_at = task.end_at || task.start_at + task.default_length event.end = Google::Apis::CalendarV3::EventDateTime.new(date_time: end_at.to_datetime.rfc3339) else time_zone = google_account.user.time_zone task_date = task.start_at.to_datetime.in_time_zone(time_zone).to_date.to_s(:db) event.start = Google::Apis::CalendarV3::EventDateTime.new(date: task_date) event.end = Google::Apis::CalendarV3::EventDateTime.new(date: task_date) end event end def status_code_indicates_event_is_no_longer_available?(code) [404, 410].include?(code) end end
chuckmersereau/api_practice
db/migrate/20140807135553_create_person_websites.rb
<reponame>chuckmersereau/api_practice<filename>db/migrate/20140807135553_create_person_websites.rb class CreatePersonWebsites < ActiveRecord::Migration def change create_table :person_websites do |t| t.belongs_to :person t.string :url t.boolean :primary, default: false t.timestamps null: false end add_index :person_websites, :person_id end end
chuckmersereau/api_practice
app/controllers/api/v2/account_lists/designation_accounts_controller.rb
<filename>app/controllers/api/v2/account_lists/designation_accounts_controller.rb class Api::V2::AccountLists::DesignationAccountsController < Api::V2Controller def index authorize load_account_list, :show? load_designation_accounts render json: @designation_accounts.preload_valid_associations(include_associations), meta: meta_hash(@designation_accounts), include: include_params, fields: field_params end def show load_designation_account authorize_designation_account render_designation_account end def update load_designation_account authorize_designation_account persist_designation_account end private def load_designation_accounts @designation_accounts = designation_account_scope.filter(filter_params) .reorder(sorting_param) .order(default_sort_param) .page(page_number_param) .per(per_page_param) end def load_designation_account @designation_account ||= DesignationAccount.find(params[:id]) end def authorize_designation_account authorize @designation_account end def render_designation_account render json: @designation_account, include: include_params, fields: field_params end def persist_designation_account build_designation_account authorize_designation_account if save_designation_account render_designation_account else render_with_resource_errors(@designation_account) end end def build_designation_account @designation_account.assign_attributes(designation_account_params) end def save_designation_account @designation_account.save(context: persistence_context) end def designation_account_params params .require(:designation_account) .permit(DesignationAccount::PERMITTED_ATTRIBUTES) end def designation_account_scope load_account_list.designation_accounts end def load_account_list @account_list ||= AccountList.find(params[:account_list_id]) end def permitted_filters [:wildcard_search] end def pundit_user PunditContext.new(current_user, account_list: load_account_list) end def default_sort_param DesignationAccount.arel_table[:created_at].asc end end
chuckmersereau/api_practice
app/controllers/api/v2/contacts/merges_controller.rb
<filename>app/controllers/api/v2/contacts/merges_controller.rb class Api::V2::Contacts::MergesController < Api::V2Controller resource_type :merges def create load_contacts authorize_merge merge_contacts render_winner end private def field_params params = super[:merges] return {} unless params { contacts: params } end def merge_params params .require(:merge) .permit(merge_attributes) end def merge_attributes [:winner_id, :loser_id] end def authorize_merge authorize(@winner, :update?) authorize(@loser, :destroy?) end def load_contacts @winner = Contact.find(merge_params[:winner_id]) @loser = Contact.find(merge_params[:loser_id]) end def merge_contacts @winner.merge(@loser) end def render_winner render json: @winner, include: include_params, fields: field_params end def pundit_user PunditContext.new(current_user) end end
chuckmersereau/api_practice
app/serializers/activity_comment_serializer.rb
<reponame>chuckmersereau/api_practice class ActivityCommentSerializer < ApplicationSerializer include DisplayCase::ExhibitsHelper type :comments attributes :body belongs_to :person def body activity_comment_exhibit = exhibit(object) activity_comment_exhibit.body end end
chuckmersereau/api_practice
db/migrate/20140926145155_add_appeal_id_to_donations.rb
<gh_stars>0 class AddAppealIdToDonations < ActiveRecord::Migration def change add_column :donations, :appeal_id, :integer end end
chuckmersereau/api_practice
spec/lib/json_api_service/params_object_spec.rb
<filename>spec/lib/json_api_service/params_object_spec.rb<gh_stars>0 require 'spec_helper' require 'json_api_service/params_object' module JsonApiService RSpec.describe ParamsObject do describe '#initialize' do it 'initializes with a params hash' do params = build_params object = ParamsObject.new(params: params) expect(object.params).to eq params end it 'initializes with a store' do object = build_object expect(object.store).to be_kind_of ObjectStore end it 'parses the param data' do object = build_object expect(object.data).to be_kind_of DataObject end it 'parses the included objects into the store' do store = ObjectStore.new params = { included: [ { type: 'users', id: 'id-users-1', attributes: { name: '<NAME>' } }, { type: 'contacts', id: 'id-contacts-1', attributes: { first_name: 'Steve', last_name: 'Rogers' } } ] } expect(store['contacts']).to be_empty expect(store['users']).to be_empty object = build_object(params: params, store: store) store = object.store expect(store['contacts']['id-contacts-1']).not_to be_nil expect(store['users']['id-users-1']).not_to be_nil end end describe 'Sanity Check' do it 'correctly converts the params' do object = build_object(params: sanity_params) expect(object.to_h).to eq expected_sanity_output end end def build_object(params: build_params, store: ObjectStore.new) ParamsObject.new(params: params, store: store) end def build_params { data: { type: 'contacts', id: 'id-contacts-1' }, included: [ { type: 'users', id: 'id-users-1', attributes: { name: '<NAME>' } } ] } end def sanity_params { included: [ { type: 'mock_people', id: '10e9f7f5-b027-4e04-8192-b9b698ac0b18', attributes: { first_name: 'Mike' } }, { type: 'mock_comments', id: '91374910-ef15-11e6-8787-ef17a057947e', attributes: { body: 'I love Orange Soda' }, relationships: { mock_person: { data: { type: 'mock_people', id: '10e9f7f5-b027-4e04-8192-b9b698ac0b18' } } } } ], data: { type: 'mock_tasks', attributes: { activity_type: 'Appointment', start_at: '2017-02-09T22:17:28.854Z', subject: 'An appointment to talk about Orange Soda' }, relationships: { mock_account_list: { data: { type: 'mock_account_lists', id: '144b83e8-b7f6-48c8-9c0e-688785bf6164' } }, mock_comments: { data: [ { type: 'mock_comments', id: '91374910-ef15-11e6-8787-ef17a057947e' } ] } } }, action: 'create' } end def expected_sanity_output { data: { type: 'mock_tasks', attributes: { activity_type: 'Appointment', start_at: '2017-02-09T22:17:28.854Z', subject: 'An appointment to talk about Orange Soda' }, relationships: { mock_account_list: { data: { type: 'mock_account_lists', id: '144b83e8-b7f6-48c8-9c0e-688785bf6164' } }, mock_comments: { data: [ { type: 'mock_comments', id: '91374910-ef15-11e6-8787-ef17a057947e', attributes: { body: 'I love Orange Soda' }, relationships: { mock_person: { data: { type: 'mock_people', id: '10e9f7f5-b027-4e04-8192-b9b698ac0b18', attributes: { first_name: 'Mike' } } } } } ] } } }, action: 'create' } end end end
chuckmersereau/api_practice
app/models/weekly.rb
class Weekly < ApplicationRecord PERMITTED_ATTRIBUTES = [ :answer, :question_id, :sid ].freeze before_save :set_nil def set_nil if self.sid == nil self.sid = 1 end end def serializer_class WeeklySerializer end end
chuckmersereau/api_practice
engines/auth/config/initializers/omniauth.rb
require 'omniauth' require 'omniauth-google-oauth2' require 'omniauth-mailchimp' require 'omniauth-prayer-letters' require 'omniauth-donorhub' Auth::Engine.config.middleware.use OmniAuth::Builder do provider :google_oauth2, ENV.fetch('GOOGLE_KEY'), ENV.fetch('GOOGLE_SECRET'), name: 'google', scope: 'userinfo.email,userinfo.profile,https://www.google.com/m8/feeds,https://mail.google.com/,https://www.googleapis.com/auth/calendar', access_type: 'offline', prompt: 'consent select_account' provider :prayer_letters, ENV.fetch('PRAYER_LETTERS_CLIENT_ID'), ENV.fetch('PRAYER_LETTERS_CLIENT_SECRET'), scope: 'contacts.read contacts.write' provider :mailchimp, ENV.fetch('MAILCHIMP_CLIENT_ID'), ENV.fetch('MAILCHIMP_CLIENT_SECRET') provider :donorhub, ENV.fetch('DONORHUB_CLIENT_ID'), ENV.fetch('DONORHUB_CLIENT_SECRET') end OmniAuth.config.on_failure = proc { |env| OmniAuth::FailureEndpoint.new(env).redirect_to_failure }
chuckmersereau/api_practice
app/models/account_list_invite.rb
class AccountListInvite < ApplicationRecord audited associated_with: :account_list belongs_to :account_list belongs_to :invited_by_user, class_name: 'User' belongs_to :accepted_by_user, class_name: 'User' belongs_to :cancelled_by_user, class_name: 'User' scope :active, -> { where(cancelled_by_user: nil, accepted_by_user: nil) } validates :recipient_email, presence: true validates :invite_user_as, inclusion: { in: %w(user coach) } PERMITTED_ATTRIBUTES = [:created_at, :overwrite, :recipient_email, :invite_user_as, :updated_at, :updated_in_db_at, :id].freeze def accept(accepting_user) return false if cancelled? # Do nothing, but return true if the same user trys to accept again. # If a second user tries to accept an already accepted invite, return false. return accepted_by_user == accepting_user if accepted_by_user.present? if invite_user_as == 'coach' account_list.account_list_coaches.find_or_create_by(coach: accepting_user.becomes(User::Coach)) else account_list.account_list_users.find_or_create_by(user: accepting_user) end update(accepted_by_user: accepting_user, accepted_at: Time.now) end def cancel(canceling_user) update(cancelled_by_user: canceling_user) end def cancelled? cancelled_by_user.present? end def self.send_invite(inviting_user, account_list, email, invite_user_as) code = SecureRandom.hex(32) invite = create(invited_by_user: inviting_user, invite_user_as: invite_user_as, code: code, recipient_email: email, account_list: account_list) AccountListInviteMailer.delay.email(invite) invite end end
chuckmersereau/api_practice
app/services/reports/monthly_losses_graph.rb
<reponame>chuckmersereau/api_practice<filename>app/services/reports/monthly_losses_graph.rb class Reports::MonthlyLossesGraph < ActiveModelSerializers::Model MONTH_FORMAT = '%b %Y'.freeze attr_accessor :account_list, :months, :today def initialize(attributes = {}) super @today = Time.zone.today unless attributes.key?(:today) end # @return [Hash<String, Float>] The same as #losses, but each key is the name # of the month in question def losses_with_month_names Hash[month_names.zip(losses)] end # @return [Array<String>] the month represented by each element in #losses def month_names Array.new(months_count) do |index| (start_month + (index + 1).months).strftime(MONTH_FORMAT) end end # @return [Array<Float>] the month-over-month decrease in balance, over the # last #months_count months. def losses monthly_differences.map { |diff| diff.zero? ? diff : diff * -1 } end private # @return [Array<Float>] the change in balance from the previous month def monthly_differences month_totals.each_cons(2) .map { |prev_total, new_total| new_total - prev_total } .map { |total| total.round(2) } end # @return [Array<Float>] def month_totals month_balances.map { |arr| arr.inject(0) { |a, e| a + e.balance } } end # @return [Array<Array<Balance>>] def month_balances @month_balances ||= Array.new(months_count + 1) { [] }.tap do |months| balances.each do |balance| months[month_index(balance.created_at)] << balance end end end def balances @balances ||= account_list.balances.where('balances.created_at >= ?', start_month) end def month_index(date) (date.year * 12 + date.month) - (start_month.year * 12 + start_month.month) end # Note that the start is one month earlier than the first month in our report, # so we can return the loss from the first element's previous month def start_month @start_month ||= today.beginning_of_month - months_count.months end def months_count @months_count ||= if months.to_i.positive? months.to_i else SHARED_DATE_CONSTANTS['DEFAULT_MONTHLY_LOSSES_COUNT'] end end end
chuckmersereau/api_practice
spec/models/balance_spec.rb
require 'rails_helper' RSpec.describe Balance, type: :model do subject { create(:balance) } it { is_expected.to have_db_index([:resource_id, :resource_type]) } it { is_expected.to belong_to(:resource) } it { is_expected.to validate_presence_of(:resource) } it { is_expected.to validate_presence_of(:balance) } end
chuckmersereau/api_practice
app/models/master_company.rb
class MasterCompany < ApplicationRecord has_many :companies, dependent: :destroy has_many :donor_accounts, dependent: :restrict_with_exception def self.find_or_create_for_company(company) where(name: company.name).first_or_create! end end
chuckmersereau/api_practice
db/migrate/20141006182418_add_appeal_indexes.rb
<reponame>chuckmersereau/api_practice class AddAppealIndexes < ActiveRecord::Migration def change add_index :appeal_contacts, :appeal_id add_index :donations, :appeal_id end end
chuckmersereau/api_practice
app/serializers/import_serializer.rb
class ImportSerializer < ApplicationSerializer attributes :account_list_id, :file_constants, :file_constants_mappings, :file_headers, :file_headers_mappings, :file_url, :group_tags, :groups, :import_by_group, :in_preview, :override, :source, :tag_list belongs_to :user has_many :sample_contacts def file_url object.file.url end def sample_contacts @sample_contacts ||= CsvImport.new(object).sample_contacts end end
chuckmersereau/api_practice
app/services/tnt_import/settings_import.rb
<filename>app/services/tnt_import/settings_import.rb<gh_stars>0 class TntImport::SettingsImport def initialize(account_list, xml, override) @account_list = account_list @xml = xml @xml_tables = xml.tables @override = override end def import return unless @xml_tables['Property'].present? @xml_tables['Property'].each do |row| case row['PropName'] when 'MonthlySupportGoal' @account_list.monthly_goal = row['PropValue'] if @override || @account_list.monthly_goal.blank? when 'MailChimpListId' mail_chimp_list_id = row['PropValue'] when 'MailChimpAPIKey' mail_chimp_key = row['PropValue'] end import_mail_chimp(@account_list, mail_chimp_list_id, mail_chimp_key) if mail_chimp_list_id && mail_chimp_key end @account_list.save end def import_mail_chimp(mail_chimp_list_id, mail_chimp_key, override) if @account_list.mail_chimp_account return unless override @account_list.mail_chimp_account.update(api_key: mail_chimp_key, primary_list_id: mail_chimp_list_id) else @account_list.create_mail_chimp_account(api_key: mail_chimp_key, primary_list_id: mail_chimp_list_id) end end end
chuckmersereau/api_practice
lib/json_api_service/configuration.rb
<reponame>chuckmersereau/api_practice require 'json_api_service/resource_lookup' module JsonApiService class Configuration extend Forwardable attr_reader :ignored_foreign_keys, :resource_lookup def_delegator :resource_lookup, :custom_references def initialize @ignored_foreign_keys = Hash.new([]) @resource_lookup = ResourceLookup.new end def custom_references=(new_custom_references) @resource_lookup = ResourceLookup.new(new_custom_references) end def ignored_foreign_keys=(hash = {}) @ignored_foreign_keys = Hash.new([]).merge!(hash) end end end
chuckmersereau/api_practice
spec/models/application_record_spec.rb
require 'rails_helper' require 'securerandom' describe ApplicationRecord do let(:contact) { create(:contact, id: nil) } describe '#before_save on create' do let(:given_id) { SecureRandom.uuid } let(:contact_with_id) { create(:contact, id: given_id) } it 'generates a new id when the id field is set to nil' do expect(contact.id.length).to eq(36) end it 'does not generate a id when the id field is given' do expect(contact_with_id.id).to eq(given_id) end end describe '#before_save on update_from_controller context' do it 'adds an error and does not save when resource is not given an updated_at field' do contact.assign_attributes(name: '<NAME>') contact.save(context: :update_from_controller) expect(contact.errors[:updated_in_db_at]).to include( 'has to be sent in the list of attributes in order to update resource' ) expect(contact.reload.name).not_to eq('New Name') end it 'adds an error and does not save when resource is outdated' do contact.assign_attributes(name: '<NAME>', updated_in_db_at: 2.weeks.ago) contact.save(context: :update_from_controller) expect(contact.errors[:updated_in_db_at]).to eq( ["is not equal to the current value in the database (#{contact.updated_at.utc.iso8601})"] ) expect(contact.reload.name).not_to eq('New Name') end it 'allows the update to take place when the resource is not outdated' do contact.assign_attributes(name: '<NAME>', updated_in_db_at: contact.updated_at) contact.save(context: :update_from_controller) expect(contact.errors[:updated_in_db_at]).to be_empty expect(contact.reload.name).to eq('New Name') end it 'will ignore the updated_in_db_at requirements if #overwrite is true' do contact.overwrite = true expect(contact.valid?(:update_from_controller)).to be_truthy contact.updated_in_db_at = 2.weeks.ago expect(contact.valid?(:update_from_controller)).to be_truthy end it 'will NOT ignore the updated_in_db_at requirements if #overwrite is something OTHER than true' do contact.overwrite = 'peanut butter' expect(contact.valid?(:update_from_controller)).to eq false contact.updated_in_db_at = 2.weeks.ago expect(contact.valid?(:update_from_controller)).to eq false # correct expectations contact.updated_in_db_at = contact.updated_at expect(contact.valid?(:update_from_controller)).to eq true end end describe '#updated_in_db_at=' do it 'accepts a Time' do new_time = 1.day.ago contact.updated_in_db_at = new_time expect(contact.updated_in_db_at).to be_a(Time) expect(contact.updated_in_db_at.iso8601).to eq(new_time.iso8601) end it 'accepts a String in ISO8601' do new_time = '2016-12-09T17:36:19Z' contact.updated_in_db_at = new_time expect(contact.updated_in_db_at).to be_a(Time) expect(contact.updated_in_db_at.iso8601).to eq(new_time) end end describe '.preload_valid_associations' do it 'does not raise error on invalid associations' do create(:contact_with_person) expect { Contact.preload(:people, :last_six_donations).first }.to raise_error(ActiveRecord::AssociationNotFoundError) expect { Contact.preload_valid_associations(:people, :last_six_donations).first }.to_not raise_error end it 'sets preload_values with valid associations' do expect( Contact.preload_valid_associations(:people, :last_six_donations, contacts_that_referred_me: [:people, :last_six_donations]).preload_values ).to eq([:people, contacts_that_referred_me: [:people]]) end end describe '.fetch_valid_associations' do it 'returns an array of valid associations that can be preloaded for the current model' do expect(Contact.fetch_valid_associations(:people, :last_six_donations)).to eq([:people]) end end end
chuckmersereau/api_practice
spec/lib/pundit_context_spec.rb
<gh_stars>0 require 'rails_helper' require 'pundit_context' describe PunditContext do let(:user) { build :user } let(:contact) { build :contact } let(:person) { build :person } context 'with a user object' do subject { PunditContext.new(user) } it 'assigns the user' do expect(subject.user).to eq user end end context 'without a user object' do it 'raises an ArgumentError' do expect { PunditContext.new(contact) }.to raise_error ArgumentError expect { PunditContext.new(nil) }.to raise_error ArgumentError expect { PunditContext.new }.to raise_error ArgumentError end end context 'with extra context' do subject { PunditContext.new(user, extra_context) } let(:extra_context) do { contact: contact, person: person } end it 'creates getters for the extra contexts' do expect(subject.contact).to eq contact expect(subject.person).to eq person end it 'does not create getters for OpenStruct methods' do expect(subject.extra_context).to respond_to :to_h expect(subject).not_to respond_to :to_h end context 'when the extra context is not a hash' do let(:extra_context) { "I'm not a hash!" } it 'raises an ArgumentError' do expect { subject }.to raise_error(ArgumentError) .with_message 'Extra context (the 2nd param) must be a hash' end end end context 'without extra context' do subject { PunditContext.new(user) } it 'does not create getters' do expect(subject).not_to respond_to :contact expect(subject).not_to respond_to :person end end end
chuckmersereau/api_practice
spec/validators/single_primary_validator_spec.rb
<gh_stars>0 require 'rails_helper' describe SinglePrimaryValidator do let(:email_validator) { SinglePrimaryValidator.new(attributes: [:email_addresses]) } let(:addresses_validator) do SinglePrimaryValidator.new(attributes: [:addresses], primary_field: :primary_mailing_address) end it 'adds an error unless record has single primary non-historic address' do { [{ historic: false, primary_mailing_address: true }] => true, [] => true, [{ historic: true, primary_mailing_address: false }] => true, [{ historic: true, primary_mailing_address: true }, { historic: true, primary_mailing_address: true }] => false, [{ historic: false, primary_mailing_address: true }, { historic: false, primary_mailing_address: true }] => false, [{ historic: true, primary_mailing_address: true }] => false, [{ historic: nil, primary_mailing_address: true }, { historic: nil, primary_mailing_address: true }] => false, [{ historic: nil, primary_mailing_address: false }, { historic: nil, primary_mailing_address: false }] => false, [{ historic: false, primary_mailing_address: false }] => false, [{ historic: nil, primary_mailing_address: false, mark_for_destruction: true }] => true }.each do |address_attrs, valid| contact = build(:contact) contact.addresses = address_attrs.map do |attrs| mark_for_destruction = attrs.delete(:mark_for_destruction) address = build(:address, attrs) address.mark_for_destruction if mark_for_destruction address end addresses_validator.validate(contact) expect(contact.errors.empty?).to eq(valid) end end it 'correctly uses :primary as the default primary_field' do { [{ historic: false, primary: true }] => true, [{ historic: false, primary: false }] => false }.each do |email_attrs, valid| person = build(:person, email_addresses: email_attrs.map { |attrs| build(:email_address, attrs) }) email_validator.validate(person) expect(person.errors.empty?).to eq(valid) end end end
chuckmersereau/api_practice
spec/services/csv_import_batch_callback_handler_spec.rb
<filename>spec/services/csv_import_batch_callback_handler_spec.rb require 'rails_helper' describe CsvImportBatchCallbackHandler do let(:import) { create(:csv_import, file_row_failures: [], in_preview: true) } let(:options) { { 'import_id' => import.id } } let(:status) { double(total: 100) } describe '#on_complete' do context 'no failures' do it 'delegates handling to ImportCallbackHandler' do expect_any_instance_of(ImportCallbackHandler).to receive(:handle_success).once expect_any_instance_of(ImportCallbackHandler).to_not receive(:handle_failure).once expect_any_instance_of(ImportCallbackHandler).to receive(:handle_complete).once CsvImportBatchCallbackHandler.new.on_complete(status, options) end end context 'has failures' do before do import.update_column(:file_row_failures, [1, 2, 3]) end it 'delegates handling to ImportCallbackHandler' do expect_any_instance_of(ImportCallbackHandler).to receive(:handle_failure).once expect_any_instance_of(ImportCallbackHandler).to_not receive(:handle_success).once expect_any_instance_of(ImportCallbackHandler).to receive(:handle_complete).once CsvImportBatchCallbackHandler.new.on_complete(status, options) end end end end
chuckmersereau/api_practice
spec/services/mail_chimp/exporter/interest_adder_spec.rb
<filename>spec/services/mail_chimp/exporter/interest_adder_spec.rb require 'rails_helper' RSpec.describe MailChimp::Exporter::InterestAdder 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(:grouping_one) do { id: 'grouping_one_id', title: 'Partner Status' }.with_indifferent_access end let(:grouping_two) do { id: 'grouping_two_id', title: 'Tags' }.with_indifferent_access end let(:mock_interest_categories) { double(:mock_interest_categories) } let(:mock_interests) { double(:mock_interests) } let(:interest_categories_create_body) { { body: { title: group_type, type: 'hidden' } } } before do allow(mock_gibbon_wrapper).to receive(:gibbon_list_object).and_return(mock_gibbon_list_object) allow(mock_gibbon_list_object).to receive(:interest_categories).and_return(mock_interest_categories) allow(mock_interest_categories).to receive(:interests).and_return(mock_interests) end context '#add_tags_interests' do let(:group_type) { 'Tags' } let(:interests_create_body) { { body: { name: 'Tag_two' } } } it 'creates and updates the appropriate interest_categories and adds the appropriate interests to those' do expect(mock_interest_categories).to receive(:retrieve).and_return( { 'categories' => [grouping_one] }, 'categories' => [grouping_one, grouping_two] ) expect(mock_interest_categories).to receive(:create).with(interest_categories_create_body) expect(mock_interests).to receive(:retrieve).and_return( 'interests' => [{ 'name' => 'Tag_one', 'id' => 'NDZA' }] ) expect(mock_interests).to receive(:create).with(interests_create_body).and_return( 'name' => 'Tag_two', 'id' => '70CFZ' ) subject.add_tags_interests(%w(Tag_one Tag_two)) expect(mail_chimp_account.tags_details[list_id][:interest_ids]).to eq( 'Tag_one' => 'NDZA', 'Tag_two' => '70CFZ' ) expect(mail_chimp_account.tags_details[list_id][:interest_category_id]).to eq 'grouping_two_id' end it 'is fine if there are too many interests' do allow(mock_interest_categories).to receive(:retrieve).and_return( { 'categories' => [grouping_one] }, 'categories' => [grouping_one, grouping_two] ) allow(mock_interest_categories).to receive(:create).with(interest_categories_create_body) allow(mock_interests).to receive(:retrieve).and_return( 'interests' => [{ 'name' => 'Tag_one', 'id' => 'NDZA' }] ) # create a new exception that emulates mailchimp reaching the interest limit exception = Gibbon::MailChimpError.new allow(exception).to receive(:status_code).and_return(400) allow(exception).to receive(:detail).and_return('Cannot have more than 2 interests per list') allow(mock_interests).to receive(:create).with(interests_create_body).and_raise(exception) expect { subject.add_tags_interests(%w(Tag_one Tag_two)) }.to_not raise_exception end end context '#add_status_interests' do let(:group_type) { 'Partner Status' } let(:interests_create_body) { { body: { name: 'Never Contacted' } } } it 'creates and updates the appropriate interest_categories and adds the appropriate interests to those' do expect(mock_interest_categories).to receive(:retrieve).and_return('categories' => [grouping_one]) expect(mock_interests).to receive(:retrieve).and_return( 'interests' => [{ 'name' => '<NAME>', 'id' => '07BW' }] ) expect(mock_interests).to receive(:create).with(interests_create_body).and_return( 'name' => 'Never Contacted', 'id' => 'ABCR' ) subject.add_status_interests(['Partner - Pray', 'Never Contacted']) expect(mail_chimp_account.statuses_details[list_id][:interest_ids]).to eq( 'Partner - Pray' => '07BW', 'Never Contacted' => 'ABCR' ) expect(mail_chimp_account.statuses_details[list_id][:interest_category_id]).to eq 'grouping_one_id' end end end
chuckmersereau/api_practice
app/services/deleted_records/filterer.rb
class DeletedRecords::Filterer < ApplicationFilterer FILTERS_TO_DISPLAY = %w(Types SinceDate).freeze end
chuckmersereau/api_practice
spec/lib/application_spec.rb
require 'rails_helper' describe Mpdx::Application do describe 'middleware' do it 'uses Rack::MethodOverride' do expect(described_class.middleware).to include(Rack::MethodOverride) end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/exports/mailling_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > Exports > Mailing' do include_context :json_headers doc_helper = DocumentationHelper.new(resource: [:contacts, :exports, :mailing]) let(:user) { create(:user_with_account) } let!(:contact) do create(:contact, account_list: user.account_lists.order(:created_at).first, addresses: [build(:address)]) end let(:resource) { create(:export_log, user: user, params: { filter: { status: 'active' } }.to_json) } let(:resource_type) { 'export_logs' } let(:id) { resource.id } let(:new_resource) do { params: { filter: { status: 'active' } } } end let(:form_data) do build_data(new_resource) end let(:additional_keys) { ['relationships'] } let(:additional_attributes) { %w(params) } context 'authorized user' do before { api_login(user) } # the INDEX action has been deprecated in favor of using the CREATE and SHOW method # as this better supports a wider range of browsers as the API now generates # the file for the user to download. # The following test remain to ensure backwards compatibility. get '/api/v2/contacts/exports/mailing.csv' do example doc_helper.title_for(:index_csv), document: false do do_request expect(response_status).to eq 200 expect(response_body).to include(contact.name) expect(response_body).to include(contact.csv_street) expect(response_headers['Content-Type']).to eq('text/csv') end end get '/api/v2/contacts/exports/mailing/:id' do doc_helper.insert_documentation_for(action: :show, context: self) with_options scope: :relationships do response_field :user, 'User Object', 'Type' => 'Object' end example doc_helper.title_for(:show), document: doc_helper.document_scope do explanation doc_helper.description_for(:show) do_request check_resource(additional_keys, additional_attributes) expect(resource_object['params']).to eq JSON.parse(new_resource[:params].to_json) expect(response_status).to eq 200 end end post '/api/v2/contacts/exports/mailing' do doc_helper.insert_documentation_for(action: :create, context: self) example doc_helper.title_for(:create), document: doc_helper.document_scope do explanation doc_helper.description_for(:create) do_request data: form_data expect(response_status).to eq(201), invalid_status_detail expect(resource_object['params']).to eq JSON.parse(new_resource[:params].to_json) end end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/user/google_accounts_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'User > Google Accounts' do include_context :json_headers documentation_scope = :user_api_google_accounts let!(:user) { create(:user_with_full_account) } let(:resource_type) { 'google_accounts' } let!(:google_account) { create(:google_account, person: user) } let(:id) { google_account.id } let(:new_google_account) do attributes_for(:google_account) .merge(updated_in_db_at: google_account.updated_at) .tap { |attrs| attrs.delete(:person_id) } end let(:relationships) do { person: { data: { type: 'people', id: user.id } } } end let(:form_data) { build_data(new_google_account, relationships: relationships) } before { allow_any_instance_of(Person::GoogleAccount).to receive(:contact_groups).and_return([]) } let(:resource_attributes) do %w( created_at email expires_at last_download last_email_sync primary remote_id token_expired updated_at updated_in_db_at ) end let(:resource_associations) do %w( contact_groups ) end context 'authorized user' do before { api_login(user) } get '/api/v2/user/google_accounts' do example 'Google Account [LIST]', document: documentation_scope do do_request explanation 'List of Google Accounts associated to current_user' check_collection_resource(1, ['relationships']) expect(response_status).to eq 200 end end get '/api/v2/user/google_accounts/:id' do with_options scope: [:data, :attributes] do response_field 'created_at', 'Created At', type: 'String' response_field 'expires_at', 'OAuth Access Token Expiration Time', type: 'String' response_field 'last_download', 'Last Download', type: 'String' response_field 'last_email_sync', 'Last Email Sync', type: 'String' response_field 'primary', 'Primary', type: 'Boolean' response_field 'remote_id', 'Remote Id', type: 'Number' response_field 'token_expired', 'OAuth Access Token Expired', type: 'Boolean' response_field 'token_failure', 'OAuth Access Token Failure', type: 'Boolean' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end example 'Google Account [GET]', document: documentation_scope do explanation 'The current_user\'s Google Account with the given ID' do_request check_resource(['relationships']) expect(response_status).to eq 200 end end post '/api/v2/user/google_accounts' do with_options scope: [:data, :attributes] do parameter 'person_id', 'Person Id', required: true parameter 'remote_id', 'Remote Id', required: true end example 'Google Account [CREATE]', document: documentation_scope do explanation 'Create a Google Account associated with the current_user' do_request data: form_data expect(response_status).to eq 201 end end put '/api/v2/user/google_accounts/:id' do with_options scope: [:data, :attributes] do parameter 'person_id', 'Person Id', required: true parameter 'remote_id', 'Remote Id', required: true end example 'Google Account [UPDATE]', document: documentation_scope do explanation 'Update the current_user\'s Google Account with the given ID' do_request data: form_data expect(response_status).to eq 200 end end delete '/api/v2/user/google_accounts/:id' do example 'Google Account [DELETE]', document: documentation_scope do explanation 'Delete the current_user\'s Google Account with the given ID' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
spec/models/donor_account_person_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe DonorAccountPerson, type: :model do end
chuckmersereau/api_practice
spec/factories/appeal_excluded_appeal_contacts.rb
FactoryBot.define do factory :appeal_excluded_appeal_contact, class: 'Appeal::ExcludedAppealContact' do appeal contact do |appeal_excluded_appeal_contact| build(:contact, account_list: appeal_excluded_appeal_contact.appeal.account_list) end end end
chuckmersereau/api_practice
db/migrate/20171024045755_add_tnt_fields_to_appeals.rb
class AddTntFieldsToAppeals < ActiveRecord::Migration def change add_column :appeals, :active, :boolean, default: true add_column :appeals, :monthly_amount, :decimal end end
chuckmersereau/api_practice
spec/services/contact/filter/tags_spec.rb
require 'rails_helper' RSpec.describe Contact::Filter::Tags 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, tag_list: 'tag1,tag2') } let!(:contact_two) { create(:contact, account_list_id: account_list.id, tag_list: 'tag1') } let!(:contact_three) { create(:contact, account_list_id: account_list.id, tag_list: 'tag3') } let!(:contact_four) { create(:contact, account_list_id: account_list.id, tag_list: '') } describe '#config' do it 'does not have config' do expect(described_class.config([account_list])).to eq(nil) 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, { tags: {} }, nil)).to eq nil expect(described_class.query(contacts, { tags: [] }, nil)).to eq nil expect(described_class.query(contacts, { tags: '' }, nil)).to eq nil end end context 'filter with tags' do it 'returns only contacts that have the tag' do expect(described_class.query(contacts, { tags: 'tag1' }, nil).to_a).to match_array [contact_one, contact_two] end it 'returns only contacts that have multiple tags' do expect(described_class.query(contacts, { tags: 'tag1, tag2' }, nil).to_a).to eq [contact_one] end it 'accepts tags as comma separated string' do expect(described_class.query(contacts, { tags: 'tag1, tag2' }, nil).to_a).to eq [contact_one] end it 'accepts tags as an array' do expect(described_class.query(contacts, { tags: 'tag1, tag2' }, nil).to_a).to eq [contact_one] end it 'accepts tags as an array when any_tags is set to true' do result = described_class.query(contacts, { tags: 'tag1, tag3', any_tags: 'true' }, nil).to_a expect(result).to match_array [contact_one, contact_two, contact_three] end end end end
chuckmersereau/api_practice
app/controllers/api/v2/contacts/export_to_mail_chimp_controller.rb
class Api::V2::Contacts::ExportToMailChimpController < Api::V2Controller skip_before_action :validate_and_transform_json_api_params def create require_mail_chimp_list_id load_mail_chimp_account authorize_mail_chimp_account raise_if_selected_list_is_primary_list export_to_mail_chimp render_200 end private def raise_if_selected_list_is_primary_list return unless @mail_chimp_account.primary_list_id == params[:mail_chimp_list_id] raise Exceptions::BadRequestError, 'mail_chimp_list_id cannot be primary_list_id, select different list' end def require_mail_chimp_list_id raise Exceptions::BadRequestError, 'mail_chimp_list_id must be provided' unless params[:mail_chimp_list_id] end def load_mail_chimp_account @mail_chimp_account ||= mail_chimp_scope.mail_chimp_account end def authorize_mail_chimp_account authorize @mail_chimp_account end def export_to_mail_chimp MailChimp::ExportContactsWorker.perform_async(@mail_chimp_account.id, params[:mail_chimp_list_id], contact_ids, true) end def contact_ids @contact_ids = current_user.contacts.where(id: filter_params[:contact_ids]).ids if filter_params[:contact_ids] @contact_ids ||= load_appeal.contacts.ids end def mail_chimp_scope account_lists.order(:created_at).first end def load_appeal @appeal ||= fetch_appeal end def fetch_appeal return account_list.appeals.order(:created_at).first unless filter_params[:appeal_id] account_list.appeals.find(filter_params[:appeal_id]) end def account_list account_lists.order(:created_at).first end def account_lists @account_lists ||= current_user.account_lists.where(id: filter_params[:account_list_id]).presence || current_user.account_lists end def permitted_filters [:account_list_id, :appeal_id, :contact_ids] end end
chuckmersereau/api_practice
spec/controllers/api/v2/contacts/people/twitter_accounts_controller.rb
require 'rails_helper' RSpec.describe Api::V2::Contacts::People::TwitterAccountsController, type: :controller do let(:factory_type) { :twitter_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!(:twitter_accounts) { create_list(:twitter_account, 2, person: person) } let(:twitter_account) { twitter_accounts.first } let(:resource) { twitter_account } let(:id) { twitter_account.id } let(:parent_param) { { contact_id: contact.id, person_id: person.id } } let(:unpermitted_attributes) { nil } let(:correct_attributes) { attributes_for(:twitter_account, person_id: person2.id) } let(:incorrect_attributes) { attributes_for(:twitter_account, screen_name: 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/factories/organization_accounts.rb
<reponame>chuckmersereau/api_practice FactoryBot.define do factory :organization_account, class: 'Person::OrganizationAccount' do association :person association :organization, factory: :fake_org username 'foo' password '<PASSWORD>' authenticated true valid_credentials true remote_id 1 end end
chuckmersereau/api_practice
spec/serializers/organization_serializer_spec.rb
require 'rails_helper' RSpec.describe OrganizationSerializer do let(:organization) { create(:organization, oauth_url: 'https://example.com') } subject { described_class.new(organization).as_json } describe '#oauth' do context 'organization is oauth capable' do it 'returns true' do expect(subject[:oauth]).to eq true end end context 'organization is not oauth capable' do let(:organization) { create(:organization, oauth_url: nil) } it 'returns false' do expect(subject[:oauth]).to eq false end end end end
chuckmersereau/api_practice
db/migrate/20151221154339_create_contact_notes_log.rb
class CreateContactNotesLog < ActiveRecord::Migration def change create_table :contact_notes_logs do |t| t.integer :contact_id t.date :recorded_on t.text :notes t.timestamps null: false end add_index :contact_notes_logs, :contact_id add_index :contact_notes_logs, :recorded_on end end
chuckmersereau/api_practice
spec/services/task/analytics_spec.rb
require 'rails_helper' RSpec.describe Task::Analytics, type: :service do let(:today) { Date.current } let(:account_list) { create(:account_list) } describe '#initialize' do it 'initializes with a tasks collection' do tasks = double(:tasks) analytics = Task::Analytics.new(tasks) expect(analytics.tasks).to eq tasks end end describe 'counts' do let(:account_list) { create(:account_list) } let(:tasks) { account_list.tasks } let(:activity_type_keys) do (Task::TASK_ACTIVITIES + ['no_type']).map { |type| type.parameterize.underscore.to_sym } end before do activity_type_keys.each do |type_key| create(:task, type_key, :complete, :today, account_list: account_list) create(:task, type_key, :complete, :yesterday, account_list: account_list) create(:task, type_key, :incomplete, :tomorrow, account_list: account_list) create(:task, type_key, :incomplete, :today, account_list: account_list) create(:task, type_key, :overdue, account_list: account_list) end end let(:analytics) { Task::Analytics.new(tasks) } describe '#tasks_overdue_or_due_today_counts' do it 'pulls the counts for the tasks that are overdue or due today' do counts_data = analytics.tasks_overdue_or_due_today_counts counts_data.each do |count_data| expect(count_data[:count]).to eq 2 end end context 'without any tasks' do let(:tasks) { create(:account_list).tasks } it 'still returns an array of objects of all the labels' do counts_data = analytics.tasks_overdue_or_due_today_counts labels = counts_data.map { |count_data| count_data[:label] } expect(labels).to match_array(Task::TASK_ACTIVITIES + [nil]) counts_data.each do |count_data| expect(count_data[:count]).to eq 0 end end end it 'counts tasks with no type' do create(:task, activity_type: nil, account_list: account_list) counts_data = analytics.tasks_overdue_or_due_today_counts no_type_report = counts_data.find { |count_data| count_data[:label].nil? } expect(no_type_report[:count]).to eq 3 end end describe '#total_tasks_due_count' do it 'pulls the count for all the tasks that are overdue' do expected_count = activity_type_keys.count * 2 expect(analytics.total_tasks_due_count).to eq expected_count end end end describe 'newsletters' do let(:account_list) { create(:account_list) } let!(:first_complete_email_newsletter) do create(:task, :newsletter_email, :complete, account_list: account_list, completed_at: 1.day.ago) end let!(:second_complete_email_newsletter) do create(:task, :newsletter_email, :complete, account_list: account_list, completed_at: Date.current) end let!(:incomplete_email_newsletter) do create(:task, :newsletter_email, :incomplete, account_list: account_list) end let!(:first_complete_physical_newsletter) do create(:task, :newsletter_physical, :complete, account_list: account_list, completed_at: 1.day.ago) end let!(:second_complete_physical_newsletter) do create(:task, :newsletter_physical, :complete, account_list: account_list, completed_at: Date.current) end let!(:incomplete_physical_newsletter) do create(:task, :newsletter_physical, :incomplete, account_list: account_list) end let(:analytics) { Task::Analytics.new(account_list.tasks) } describe '#last_electronic_newsletter_completed_at' do it "returns the last electronic newsletter's completed_at time" do expect(analytics.last_electronic_newsletter_completed_at) .to eq second_complete_email_newsletter.completed_at end end describe '#last_physical_newsletter_completed_at' do it "returns the last physical newsletter's completed_at time" do expect(analytics.last_physical_newsletter_completed_at) .to eq second_complete_physical_newsletter.completed_at end end end end
chuckmersereau/api_practice
app/models/duplicate_record_pair.rb
<gh_stars>0 class DuplicateRecordPair < ApplicationRecord PERMITTED_ATTRIBUTES = [ :account_list_id, :created_at, :ignore, :overwrite, :reason, :record_one_id, :record_two_id, :updated_at, :updated_in_db_at, :id ].freeze TYPES = %w(Contact Person).freeze belongs_to :record_one, polymorphic: true belongs_to :record_two, polymorphic: true belongs_to :account_list before_save :sort_record_ids validates :account_list_id, :record_one_id, :record_one_type, :record_two_id, :record_two_type, :reason, presence: true validates :record_one_type, :record_two_type, inclusion: { in: TYPES } validate :records_have_the_same_type_validation validate :records_belong_to_the_same_account_list_validation validate :pair_is_unique_validation validate :a_record_cannot_be_in_multiple_pairs_validation scope :type, -> (type) { where(record_one_type: type, record_two_type: type) } def type record_one_type == record_two_type ? record_one_type : nil end def records [record_one, record_two] end def ids [record_one_id, record_two_id] end private # It doesn't matter whether a record is in record_one or record_two. # We sort the record ids so that the db index can enforce uniqueness across both ids. def sort_record_ids self.record_one_id, self.record_two_id = (records.compact.sort_by(&:created_at).map(&:id) + ids).uniq end def records_have_the_same_type_validation return if record_one_type == record_two_type errors.add(:base, 'Records must have the same type!') end def find_account_list_ids_for_record(record) if record.respond_to?(:account_list_id) [record.account_list_id] elsif record.respond_to?(:account_lists) record.account_lists.ids else [] end end def records_belong_to_the_same_account_list_validation return if records.all? do |record| find_account_list_ids_for_record(record).include?(account_list&.id) end errors.add(:base, 'Records must belong to the same AccountList!') end # We don't let a record into multiple pairs because if one of those pairs is # merged then the original record may be deleted, and in that case dealing # with the next pair is challenging because the record no longer exists. def a_record_cannot_be_in_multiple_pairs_validation records_with_multiple_pairs = DuplicateRecordPair.type(type) .where.not(id: id) .where(ignore: false) .where('record_one_id IN (:ids) OR record_two_id IN (:ids)', ids: ids) return unless records_with_multiple_pairs.exists? errors.add(:base, 'A record cannot be in multiple pairs (unless the pair is ignored first)!') end def pair_is_unique_validation existing_pair = DuplicateRecordPair.type(type).where.not(id: id).where(record_one_id: ids, record_two_id: ids) return unless existing_pair.exists? errors.add(:base, 'Each duplicate pair should be unique!') end end
chuckmersereau/api_practice
config/initializers/date_formats_constant.rb
DATE_FORMATS = { 'ar-SA' => 'dd/MM/yy', 'bg-BG' => 'dd.M.yyyy', 'ca-ES' => 'dd/MM/yyyy', 'zh-TW' => 'yyyy/M/d', 'cs-CZ' => 'd.M.yyyy', 'da-DK' => 'dd-MM-yyyy', 'de-DE' => 'dd.MM.yyyy', 'el-GR' => 'd/M/yyyy', 'en-US' => 'M/d/yyyy', 'fi-FI' => 'd.M.yyyy', 'fr-FR' => 'dd/MM/yyyy', 'he-IL' => 'dd/MM/yyyy', 'hu-HU' => 'yyyy. MM. dd.', 'is-IS' => 'd.M.yyyy', 'it-IT' => 'dd/MM/yyyy', 'ja-JP' => 'yyyy/MM/dd', 'ko-KR' => 'yyyy-MM-dd', 'nl-NL' => 'd-M-yyyy', 'nb-NO' => 'dd.MM.yyyy', 'pl-PL' => 'yyyy-MM-dd', 'pt-BR' => 'd/M/yyyy', 'ro-RO' => 'dd.MM.yyyy', 'ru-RU' => 'dd.MM.yyyy', 'hr-HR' => 'd.M.yyyy', 'sk-SK' => 'd. M. yyyy', 'sq-AL' => 'yyyy-MM-dd', 'sv-SE' => 'yyyy-MM-dd', 'th-TH' => 'd/M/yyyy', 'tr-TR' => 'dd.MM.yyyy', 'ur-PK' => 'dd/MM/yyyy', 'id-ID' => 'dd/MM/yyyy', 'uk-UA' => 'dd.MM.yyyy', 'be-BY' => 'dd.MM.yyyy', 'sl-SI' => 'd.M.yyyy', 'et-EE' => 'd.MM.yyyy', 'lv-LV' => 'yyyy.MM.dd.', 'lt-LT' => 'yyyy.MM.dd', 'fa-IR' => 'MM/dd/yyyy', 'vi-VN' => 'dd/MM/yyyy', 'hy-AM' => 'dd.MM.yyyy', 'az-Latn-AZ' => 'dd.MM.yyyy', 'eu-ES' => 'yyyy/MM/dd', 'mk-MK' => 'dd.MM.yyyy', 'af-ZA' => 'yyyy/MM/dd', 'ka-GE' => 'dd.MM.yyyy', 'fo-FO' => 'dd-MM-yyyy', 'hi-IN' => 'dd-MM-yyyy', 'ms-MY' => 'dd/MM/yyyy', 'kk-KZ' => 'dd.MM.yyyy', 'ky-KG' => 'dd.MM.yy', 'sw-KE' => 'M/d/yyyy', 'uz-Latn-UZ' => 'dd/MM yyyy', 'tt-RU' => 'dd.MM.yyyy', 'pa-IN' => 'dd-MM-yy', 'gu-IN' => 'dd-MM-yy', 'ta-IN' => 'dd-MM-yyyy', 'te-IN' => 'dd-MM-yy', 'kn-IN' => 'dd-MM-yy', 'mr-IN' => 'dd-MM-yyyy', 'sa-IN' => 'dd-MM-yyyy', 'mn-MN' => 'yy.MM.dd', 'gl-ES' => 'dd/MM/yy', 'kok-IN' => 'dd-MM-yyyy', 'syr-SY' => 'dd/MM/yyyy', 'dv-MV' => 'dd/MM/yy', 'ar-IQ' => 'dd/MM/yyyy', 'zh-CN' => 'yyyy/M/d', 'de-CH' => 'dd.MM.yyyy', 'en-GB' => 'dd/MM/yyyy', 'es-MX' => 'dd/MM/yyyy', 'fr-BE' => 'd/MM/yyyy', 'it-CH' => 'dd.MM.yyyy', 'nl-BE' => 'd/MM/yyyy', 'nn-NO' => 'dd.MM.yyyy', 'pt-PT' => 'dd-MM-yyyy', 'sr-Latn-CS' => 'd.M.yyyy', 'sv-FI' => 'd.M.yyyy', 'az-Cyrl-AZ' => 'dd.MM.yyyy', 'ms-BN' => 'dd/MM/yyyy', 'uz-Cyrl-UZ' => 'dd.MM.yyyy', 'ar-EG' => 'dd/MM/yyyy', 'zh-HK' => 'd/M/yyyy', 'de-AT' => 'dd.MM.yyyy', 'en-AU' => 'd/MM/yyyy', 'es-ES' => 'dd/MM/yyyy', 'fr-CA' => 'yyyy-MM-dd', 'sr-Cyrl-CS' => 'd.M.yyyy', 'ar-LY' => 'dd/MM/yyyy', 'zh-SG' => 'd/M/yyyy', 'de-LU' => 'dd.MM.yyyy', 'en-CA' => 'dd/MM/yyyy', 'es-GT' => 'dd/MM/yyyy', 'fr-CH' => 'dd.MM.yyyy', 'ar-DZ' => 'dd-MM-yyyy', 'zh-MO' => 'd/M/yyyy', 'de-LI' => 'dd.MM.yyyy', 'en-NZ' => 'd/MM/yyyy', 'es-CR' => 'dd/MM/yyyy', 'fr-LU' => 'dd/MM/yyyy', 'ar-MA' => 'dd-MM-yyyy', 'en-IE' => 'dd/MM/yyyy', 'es-PA' => 'MM/dd/yyyy', 'fr-MC' => 'dd/MM/yyyy', 'ar-TN' => 'dd-MM-yyyy', 'en-ZA' => 'yyyy/MM/dd', 'es-DO' => 'dd/MM/yyyy', 'ar-OM' => 'dd/MM/yyyy', 'en-JM' => 'dd/MM/yyyy', 'es-VE' => 'dd/MM/yyyy', 'ar-YE' => 'dd/MM/yyyy', 'en-029' => 'MM/dd/yyyy', 'es-CO' => 'dd/MM/yyyy', 'ar-SY' => 'dd/MM/yyyy', 'en-BZ' => 'dd/MM/yyyy', 'es-PE' => 'dd/MM/yyyy', 'ar-JO' => 'dd/MM/yyyy', 'en-TT' => 'dd/MM/yyyy', 'es-AR' => 'dd/MM/yyyy', 'ar-LB' => 'dd/MM/yyyy', 'en-ZW' => 'M/d/yyyy', 'es-EC' => 'dd/MM/yyyy', 'ar-KW' => 'dd/MM/yyyy', 'en-PH' => 'M/d/yyyy', 'es-CL' => 'dd-MM-yyyy', 'ar-AE' => 'dd/MM/yyyy', 'es-UY' => 'dd/MM/yyyy', 'ar-BH' => 'dd/MM/yyyy', 'es-PY' => 'dd/MM/yyyy', 'ar-QA' => 'dd/MM/yyyy', 'es-BO' => 'dd/MM/yyyy', 'es-SV' => 'dd/MM/yyyy', 'es-HN' => 'dd/MM/yyyy', 'es-NI' => 'dd/MM/yyyy', 'es-PR' => 'dd/MM/yyyy', 'am-ET' => 'd/M/yyyy', 'tzm-Latn-DZ' => 'dd-MM-yyyy', 'iu-Latn-CA' => 'd/MM/yyyy', 'sma-NO' => 'dd.MM.yyyy', 'mn-Mong-CN' => 'yyyy/M/d', 'gd-GB' => 'dd/MM/yyyy', 'en-MY' => 'd/M/yyyy', 'prs-AF' => 'dd/MM/yy', 'bn-BD' => 'dd-MM-yy', 'wo-SN' => 'dd/MM/yyyy', 'rw-RW' => 'M/d/yyyy', 'qut-GT' => 'dd/MM/yyyy', 'sah-RU' => 'MM.dd.yyyy', 'gsw-FR' => 'dd/MM/yyyy', 'co-FR' => 'dd/MM/yyyy', 'oc-FR' => 'dd/MM/yyyy', 'mi-NZ' => 'dd/MM/yyyy', 'ga-IE' => 'dd/MM/yyyy', 'se-SE' => 'yyyy-MM-dd', 'br-FR' => 'dd/MM/yyyy', 'smn-FI' => 'd.M.yyyy', 'moh-CA' => 'M/d/yyyy', 'arn-CL' => 'dd-MM-yyyy', 'ii-CN' => 'yyyy/M/d', 'dsb-DE' => 'd. M. yyyy', 'ig-NG' => 'd/M/yyyy', 'kl-GL' => 'dd-MM-yyyy', 'lb-LU' => 'dd/MM/yyyy', 'ba-RU' => 'dd.MM.yy', 'nso-ZA' => 'yyyy/MM/dd', 'quz-BO' => 'dd/MM/yyyy', 'yo-NG' => 'd/M/yyyy', 'ha-Latn-NG' => 'd/M/yyyy', 'fil-PH' => 'M/d/yyyy', 'ps-AF' => 'dd/MM/yy', 'fy-NL' => 'd-M-yyyy', 'ne-NP' => 'M/d/yyyy', 'se-NO' => 'dd.MM.yyyy', 'iu-Cans-CA' => 'd/M/yyyy', 'sr-Latn-RS' => 'd.M.yyyy', 'si-LK' => 'yyyy-MM-dd', 'sr-Cyrl-RS' => 'd.M.yyyy', 'lo-LA' => 'dd/MM/yyyy', 'km-KH' => 'yyyy-MM-dd', 'cy-GB' => 'dd/MM/yyyy', 'bo-CN' => 'yyyy/M/d', 'sms-FI' => 'd.M.yyyy', 'as-IN' => 'dd-MM-yyyy', 'ml-IN' => 'dd-MM-yy', 'en-IN' => 'dd-MM-yyyy', 'or-IN' => 'dd-MM-yy', 'bn-IN' => 'dd-MM-yy', 'tk-TM' => 'dd.MM.yy', 'bs-Latn-BA' => 'd.M.yyyy', 'mt-MT' => 'dd/MM/yyyy', 'sr-Cyrl-ME' => 'd.M.yyyy', 'se-FI' => 'd.M.yyyy', 'zu-ZA' => 'yyyy/MM/dd', 'xh-ZA' => 'yyyy/MM/dd', 'tn-ZA' => 'yyyy/MM/dd', 'hsb-DE' => 'd. M. yyyy', 'bs-Cyrl-BA' => 'd.M.yyyy', 'tg-Cyrl-TJ' => 'dd.MM.yy', 'sr-Latn-BA' => 'd.M.yyyy', 'smj-NO' => 'dd.MM.yyyy', 'rm-CH' => 'dd/MM/yyyy', 'smj-SE' => 'yyyy-MM-dd', 'quz-EC' => 'dd/MM/yyyy', 'quz-PE' => 'dd/MM/yyyy', 'hr-BA' => 'd.M.yyyy.', 'sr-Latn-ME' => 'd.M.yyyy', 'sma-SE' => 'yyyy-MM-dd', 'en-SG' => 'd/M/yyyy', 'ug-CN' => 'yyyy-M-d', 'sr-Cyrl-BA' => 'd.M.yyyy', 'es-US' => 'M/d/yyyy' }.freeze
chuckmersereau/api_practice
spec/exhibits/reports/monthly_giving_graph_exhibit_spec.rb
require 'spec_helper' describe Reports::MonthlyGivingGraphExhibit do subject { Reports::MonthlyGivingGraphExhibit.new(report, context) } let(:report) { Reports::MonthlyGivingGraph.new(account_list: account_list) } let(:account_list) { create :account_list, salary_currency: 'EUR' } let(:context) { double } context '#salary_currency_symbol' do it { expect(subject.salary_currency_symbol).to eq '€' } end end
chuckmersereau/api_practice
spec/services/import_callback_handler_spec.rb
require 'rails_helper' describe ImportCallbackHandler do let(:import) { create(:csv_import, in_preview: true) } before do Sidekiq::Testing.inline! import.update_column(:in_preview, false) end describe 'initialize' do it 'initializes' do expect(ImportCallbackHandler.new(import)).to be_a ImportCallbackHandler end end describe '#handle_start' do it 'updates import' do travel_to Time.current do expect do ImportCallbackHandler.new(import).handle_start end.to change { import.reload.importing }.from(false).to(true) .and change { import.import_started_at&.to_i }.from(nil).to(Time.current.to_i) end end end describe '#handle_success' do it 'runs after import success processes' do expect_any_instance_of(AccountList).to receive(:queue_sync_with_google_contacts).once expect_any_instance_of(AccountList).to receive(:valid_mail_chimp_account).and_return(true) expect_any_instance_of(AccountList).to receive(:mail_chimp_account).and_return(MailChimpAccount.new) expect(MailChimp::PrimaryListSyncWorker).to receive(:perform_async).once expect_delayed_email(ImportMailer, :success) ImportCallbackHandler.new(import).handle_success end it 'does not send an email if there is an error in the post import processes' do begin expect_any_instance_of(AccountList).to receive(:queue_sync_with_google_contacts).and_raise(StandardError) expect(ImportMailer).to_not receive(:delay) ImportCallbackHandler.new(import).handle_success rescue StandardError end end it 'sets the Import error to nil' do import.update_column(:error, 'ERROR') expect do ImportCallbackHandler.new(import).handle_success end.to change { import.reload.error }.from('ERROR').to(nil) end end describe '#handle_failure' do it 'sends import failure mail' do expect_delayed_email(ImportMailer, :failed) ImportCallbackHandler.new(import).handle_failure end it 'sets the Import error' do import.update_column(:error, nil) exception = StandardError.new('Just testing!') expect do ImportCallbackHandler.new(import).handle_failure(exception: exception) end.to change { import.reload.error }.from(nil).to('StandardError: Just testing!') end end describe '#handle_complete' do it 'runs after import complete processes' do import.update_column(:importing, true) expect_any_instance_of(AccountList).to receive(:async_merge_contacts).once expect(ContactSuggestedChangesUpdaterWorker).to receive(:perform_async) travel_to Time.current do expect do ImportCallbackHandler.new(import).handle_complete end.to change { import.reload.importing }.from(true).to(false) .and change { import.import_completed_at&.to_i }.from(nil).to(Time.current.to_i) end end it 'updates the record even if there is an error in the import complete processes' do travel_to Time.current do begin expect_any_instance_of(AccountList).to receive(:async_merge_contacts).and_raise(StandardError) expect do ImportCallbackHandler.new(import).handle_complete end.to change { import.reload.importing }.from(true).to(false) .and change { import.import_completed_at&.to_i }.from(nil).to(Time.current.to_i) rescue StandardError end end end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/admin/organizations_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Organizations' do include_context :json_headers let(:admin_user) { create(:user_with_account, admin: true) } let(:request_type) { 'organizations' } let(:form_data) { build_data(name: 'Cru (Offline)', org_help_url: 'https://cru.org', country: 'United States') } context 'authorized user' do before { api_login(admin_user) } post '/api/v2/admin/organizations' do with_options scope: [:data, :attributes] do parameter :name, 'The name of the new organization' parameter :org_help_url, 'The url of the organization' parameter :country, 'The default country that account lists associated with this organization will be set to' end example 'Organization [CREATE]', document: false do explanation 'This endpoint allows an admin to create an organization.' do_request data: form_data expect(response_status).to eq 201 expect(json_response['data']['attributes']['name']).to eq 'Cru (Offline)' end end end end
chuckmersereau/api_practice
db/migrate/20160809235201_add_only_active_contacts_to_mail_chimp_accounts.rb
class AddOnlyActiveContactsToMailChimpAccounts < ActiveRecord::Migration def change add_column :mail_chimp_accounts, :sync_all_active_contacts, :boolean end end
chuckmersereau/api_practice
app/services/task/filter/starred.rb
<gh_stars>0 class Task::Filter::Starred < Task::Filter::Base def execute_query(tasks, filters) tasks.where(starred: filters[:starred]) end def title _('Starred') end def type 'single_checkbox' end def default_selection nil end end
chuckmersereau/api_practice
app/concerns/has_primary.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 module HasPrimary extend ActiveSupport::Concern included do cattr_accessor :primary_scope after_commit :ensure_only_one_primary end private def ensure_only_one_primary self.class.ensure_only_one_primary?(send(primary_scope), self) end module ClassMethods def ensure_only_one_primary?(parent_object, object) rel = to_s.tableize.to_sym return unless parent_object&.send(rel).present? if object.respond_to?(:historic) parent_object.send(rel).where(historic: true).update_all(primary: false) not_historic_where = { historic: false } return unless parent_object.send(rel).where(not_historic_where).present? else not_historic_where = {} end primaries = parent_object.send(rel).where(primary: true).where(not_historic_where) if primaries.blank? parent_object.send(rel).where(not_historic_where).last.update_column(:primary, true) elsif primaries.length > 1 if primaries.include?(object) (primaries - [object]).map { |e| e.update_column(:primary, false) } else primaries[0..-2].map { |e| e.update_column(:primary, false) } end end end end end
chuckmersereau/api_practice
app/models/concerns/adobe_campaignable.rb
# frozen_string_literal: true module AdobeCampaignable extend ActiveSupport::Concern included do after_commit :enqueue_adobe_campaign_subscription, on: :create end module ClassMethods def subscribe_to_adobe_campaign(user_id) find_by(id: user_id)&.find_or_create_adobe_subscription end def adobe_campaign_service ::Adobe::Campaign::Service.find(ENV['ADOBE_SERVICE_NAME']).dig('content', 0) end end def find_or_create_adobe_profile @adobe_profile ||= find_on_adobe_campaign @adobe_profile ||= post_to_adobe_campaign end def find_on_adobe_campaign ::Adobe::Campaign::Profile.by_email(email_address)['content'][0] end def post_to_adobe_campaign ::Adobe::Campaign::Profile.post( "email": email_address, "firstName": first_name, "lastName": last_name ) end def find_or_create_adobe_subscription find_adobe_subscription || subscribe_to_adobe_campaign end def find_adobe_subscription profile = find_or_create_adobe_profile prof_subs_url = profile.fetch('subscriptions', {}).fetch('href', '') subscriptions = ::Adobe::Campaign::Base.get_request(prof_subs_url).fetch('content', [{ serviceName: nil }]) subscriptions.find { |subcription| subcription['serviceName'] == ENV['ADOBE_SERVICE_NAME'] } end def subscribe_to_adobe_campaign profile = find_or_create_adobe_profile service_subs_url = (self.class.adobe_campaign_service || {}).fetch('subscriptions', {}).fetch('href', '') ::Adobe::Campaign::Service.post_subscription(service_subs_url, profile['PKey']) end private def enqueue_adobe_campaign_subscription return unless email_address =~ /@/ && Rails.env.production? UserAdobeCampaignSubscriberWorker.perform_async(id) end end
chuckmersereau/api_practice
app/services/contact/filter/ids.rb
class Contact::Filter::Ids < Contact::Filter::Base def execute_query(contacts, filters) contacts.where(id: parse_list(filters[:ids])) end end
chuckmersereau/api_practice
spec/factories/appeals.rb
FactoryBot.define do factory :appeal do account_list amount 1000.0 description 'The description for my new Appeal' end_date { 1.week.from_now.to_date } sequence(:name) { |num| "Appeal ##{num}" } end end
chuckmersereau/api_practice
app/serializers/person/google_account_serializer.rb
<gh_stars>0 class Person::GoogleAccountSerializer < ApplicationSerializer type :google_accounts has_many :contact_groups attributes :email, :expires_at, :last_download, :last_email_sync, :primary, :remote_id, :token_expired def token_expired object.token_expired? end def token_failure object.token_failure? end end
chuckmersereau/api_practice
spec/validators/csv_import_mappings_validator_spec.rb
require 'rails_helper' describe CsvImportMappingsValidator do INVALID_STATUS = 'has an invalid mapping. For the header "status", we '\ "couldn't find the following values in the CSV".freeze MISSING_STATUS = "is missing mappings. For the header \"status\", we couldn't find the following "\ 'mappings to the CSV values: ["Praying", "Praying and giving"]'.freeze let!(:import) { create(:csv_import_custom_headers, in_preview: true) } before do CsvImport.new(import).update_cached_file_data import.in_preview = false end it 'validates that file_headers_mappings_contains_required_headers' do expected_error = 'should specify a header mapping for at least one of the required headers' expect(CsvImport).to receive(:required_headers).and_return('first_name' => 'First Name').at_least(:once) import.file_headers_mappings = { 'something_invalid' => 'fname' } expect(import.valid?).to eq false expect(import.errors[:file_headers_mappings].any? { |error| error.starts_with?(expected_error) }).to eq true import.file_headers_mappings = { 'first_name' => 'fname' } import.valid? expect(import.errors[:file_headers_mappings].any? { |error| error.starts_with?(expected_error) }).to eq false end it 'validates that file_headers_mappings_contains_only_supported_headers' do expected_error = 'has unsupported headers. One or more of the headers '\ 'specified in file_headers_mappings is not supported' import.file_headers_mappings = { 'something_invalid' => 'fname' } expect(import.valid?).to eq false expect(import.errors[:file_headers_mappings].any? { |error| error.starts_with?(expected_error) }).to eq true import.file_headers_mappings = { 'first_name' => 'fname' } import.valid? expect(import.errors[:file_headers_mappings].any? { |error| error.starts_with?(expected_error) }).to eq false end it 'validates that file_headers_mappings_only_maps_to_headers_in_the_file' do expected_error = 'has unsupported mappings. One or more of the header mappings '\ 'was not found in the headers of the given CSV file' import.file_headers_mappings = { 'first_name' => 'something invalid' } expect(import.valid?).to eq false expect(import.errors[:file_headers_mappings].any? { |error| error.starts_with?(expected_error) }).to eq true import.file_headers_mappings = { 'first_name' => 'fname' } import.valid? expect(import.errors[:file_headers_mappings].any? { |error| error.starts_with?(expected_error) }).to eq false end context 'mappings have the format of key and value pairs' do it 'validates that file_constants_mappings_contains_the_constants_needed_for_import' do expected_error = 'is missing mappings. One or more of the header constants specified in '\ 'file_headers_mappings does not have a mapping specified in file_constants_mappings' import.file_headers_mappings = { 'first_name' => 'fname', 'status' => 'status' } import.file_constants_mappings = {} expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? { |error| error.starts_with?(expected_error) }).to eq true import.file_constants_mappings = { 'status' => [] } import.valid? expect(import.errors[:file_constants_mappings].any? { |error| error.starts_with?(expected_error) }).to eq false end it 'validates that file_constants_mappings_only_maps_constants_that_are_supported' do import.file_headers_mappings = { 'first_name' => 'fname', 'status' => 'status' } import.file_constants_mappings = { 'status' => [{ id: 'Something Invalid', values: ['Praying and giving'] }] } expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?('has an invalid mapping. For the header "status", you cannot map to the constants') end).to eq true import.file_constants_mappings = { 'status' => [{ id: 'Partner - Financial', values: ['Praying and giving'] }] } import.valid? expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?('has an invalid mapping. For the header "status", you cannot map to the constants') end).to eq false end it 'validates that file_constants_mappings_only_maps_constants_that_are_also_in_file_headers_mappings' do expected_error = 'has an invalid mapping. You cannot map to the constants ["status"] '\ 'because they are not found in file_headers_mappings' import.file_headers_mappings = { 'first_name' => 'fname' } import.file_constants_mappings = { 'status' => [{ id: 'Partner - Financial', values: ['Praying and giving'] }] } expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? { |error| error.starts_with?(expected_error) }).to eq true import.file_headers_mappings['Status'] = 'status' import.valid? expect(import.errors[:file_constants_mappings].any? { |error| error.starts_with?(expected_error) }).to eq false end it 'validates that file_constants_mappings_only_maps_constants_to_values_found_in_the_csv' do import.file_headers_mappings = { 'first_name' => 'fname', 'status' => 'status' } import.file_constants_mappings = { 'status' => [{ id: 'Partner - Financial', values: ['something invalid'] }] } expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? { |error| error.starts_with?(INVALID_STATUS) }).to eq true import.file_constants_mappings = { 'status' => [{ id: 'Partner - Financial', values: ['Praying and giving'] }] } import.valid? expect(import.errors[:file_constants_mappings].any? { |error| error.starts_with?(INVALID_STATUS) }).to eq false end it 'validates that file_constants_mappings_maps_all_constants_values_found_in_the_csv' do import.file_headers_mappings = { 'first_name' => 'fname', 'status' => 'status' } import.file_constants_mappings = { 'status' => [] } expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(MISSING_STATUS) end).to eq true import.file_constants_mappings = { 'status' => [ { id: 'Partner - Financial', values: ['Praying and giving'] }, { id: 'Partner - Prayer', values: ['Praying'] } ] } import.valid? expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(MISSING_STATUS) end).to eq false end end context 'mappings have the format of id and values hashes' do it 'validates that file_constants_mappings_contains_the_constants_needed_for_import' do missing_const = 'is missing mappings. One or more of the header constants specified in '\ 'file_headers_mappings does not have a mapping specified in file_constants_mappings' import.file_headers_mappings = { 'first_name' => 'fname', 'status' => 'status' } import.file_constants_mappings = {} expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(missing_const) end).to eq true import.file_constants_mappings = { 'status' => [] } import.valid? expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(missing_const) end).to eq false end it 'validates that file_constants_mappings_only_maps_constants_that_are_supported' do import.file_headers_mappings = { 'first_name' => 'fname', 'status' => 'status' } import.file_constants_mappings = { 'status' => [{ id: 'Something Invalid', values: ['Praying and giving'] }] } expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?('has an invalid mapping. For the header "status", you cannot map to the constants') end).to eq true import.file_constants_mappings = { 'status' => [{ id: 'Partner - Financial', values: ['Praying and giving'] }] } import.valid? expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?('has an invalid mapping. For the header "status", you cannot map to the constants') end).to eq false end it 'validates that file_constants_mappings_only_maps_constants_that_are_also_in_file_headers_mappings' do invalid_const_map = 'has an invalid mapping. You cannot map to the constants '\ '["status"] because they are not found in file_headers_mappings' import.file_headers_mappings = { 'first_name' => 'fname' } import.file_constants_mappings = { 'status' => [{ id: 'Partner - Financial', values: ['Praying and giving'] }] } expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(invalid_const_map) end).to eq true import.file_headers_mappings['Status'] = 'status' import.valid? expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(invalid_const_map) end).to eq false end it 'validates that file_constants_mappings_only_maps_constants_to_values_found_in_the_csv' do import.file_headers_mappings = { 'first_name' => 'fname', 'status' => 'status' } import.file_constants_mappings = { 'status' => [{ id: 'Partner - Financial', values: ['something invalid'] }] } expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(INVALID_STATUS) end).to eq true import.file_constants_mappings = { 'status' => [{ id: 'Partner - Financial', values: ['Praying and giving'] }] } import.valid? expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(INVALID_STATUS) end).to eq false end it 'validates that file_constants_mappings_maps_all_constants_values_found_in_the_csv' do import.file_headers_mappings = { 'first_name' => 'fname', 'status' => 'status' } import.file_constants_mappings = { 'status' => [] } expect(import.valid?).to eq false expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(MISSING_STATUS) end).to eq true import.file_constants_mappings = { 'status' => [ { id: 'Partner - Financial', values: ['Praying and giving'] }, { id: 'Partner - Prayer', values: ['Praying'] } ] } import.valid? expect(import.errors[:file_constants_mappings].any? do |error| error.starts_with?(MISSING_STATUS) end).to eq false end end end
chuckmersereau/api_practice
app/preloaders/api/v2/contacts/people/relationships_preloader.rb
class Api::V2::Contacts::People::RelationshipsPreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = { related_person: Api::V2::Contacts::PeoplePreloader }.freeze FIELD_ASSOCIATION_MAPPING = {}.freeze private def serializer_class FamilyRelationshipSerializer end end
chuckmersereau/api_practice
spec/models/task_spec.rb
require 'rails_helper' describe Task do let(:account_list) { create(:account_list) } it 'updates a related contacts uncompleted tasks count' do task1 = create(:task, account_list: account_list) task2 = create(:task, account_list: account_list) contact = create(:contact, account_list: account_list) contact.tasks << task1 contact.tasks << task2 expect(contact.reload.uncompleted_tasks_count).to eq(2) task1.reload.update_attributes(completed: true) expect(contact.reload.uncompleted_tasks_count).to eq(1) task1.update_attributes(completed: false) expect(contact.reload.uncompleted_tasks_count).to eq(2) task2.destroy expect(contact.reload.uncompleted_tasks_count).to eq(1) end it 'auto generates the subject line when one is missing' do contact = create(:contact, account_list: account_list, name: '<NAME>') task = Task.new(activity_type: 'Call', subject: nil, account_list: account_list) task.contacts << contact task.save expect(task.subject).to eq('Call Holloway, Max') expect(task.subject_hidden).to eq(true) end context 'google calendar integration' do let(:google_integration) { double('GoogleIntegration', async: true, id: 1234) } before do allow_any_instance_of(AccountList).to receive(:google_integrations) { [google_integration] } end it 'does not sync an old task to google after a save call' do expect(google_integration).to_not receive(:lower_retry_async) create(:task, account_list: account_list, activity_type: 'Appointment') end it 'does not sync a completed task to google after a save call' do expect(google_integration).to_not receive(:lower_retry_async) create(:task, result: 'completed', account_list: account_list, activity_type: 'Appointment') end it 'does not sync a task with has been specified as having no date' do expect(google_integration).to_not receive(:lower_retry_async) create(:task, start_at: nil, account_list: account_list, activity_type: 'Appointment') end it 'syncs a task to google after a save call' do task = build(:task, start_at: 1.day.from_now, account_list: account_list, activity_type: 'Appointment') expect { task.save }.to change { GoogleCalendarSyncTaskWorker.jobs.size }.by(1) expect(GoogleCalendarSyncTaskWorker.jobs.last['args']).to eq([1234, task.id]) end it 'syncs a task to google after a destroy call' do expect(GoogleCalendarSyncTaskWorker).to receive(:perform_async).twice create(:task, start_at: 1.day.from_now, account_list: account_list, activity_type: 'Appointment').destroy end end describe '#deletable' do let(:account_list) { create(:account_list) } let(:person) { create(:person) } let(:task) { create(:task, account_list: account_list) } let(:delete_task) { task.destroy } it 'should save a reference to the task that was deleted' do expect { delete_task }.to change { DeletedRecord.count }.by(1) end it 'should record the deleted objects details' do delete_task record = DeletedRecord.find_by(deletable_type: 'Activity', deletable_id: task.id) expect(record.deletable_type).to eq('Activity') expect(record.deletable_id).to eq(task.id) expect(record.deleted_from_id).to eq(task.account_list_id) expect(record.deleted_by_id).to eq(task.account_list.creator_id) end end context '#calculate_location' do let(:contact) { create(:contact, account_list: account_list) } let(:person) { create(:person, first_name: 'John', last_name: 'Smith') } let(:task) { create(:task, account_list: account_list) } before do contact.people << person task.contacts << contact end it 'users numbers if call' do task.update_column(:activity_type, 'Call') person.phone_numbers << create(:phone_number) expect(task.calculated_location).to eq '<NAME> (213) 456-7890 - mobile' end it 'uses address for non-calls' do contact.addresses << create(:address) task.update_column(:activity_type, 'Appointment') address = '123 Somewhere St, Fremont, CA, 94539, United States' expect(task.calculated_location).to eq address end end describe '.alert_frequencies' do subject { Task.alert_frequencies } it 'returns a hash of {String => String}' do is_expected.to be_a_hash_with_types(String, String) end end context 'logging newsletter' do subject { build(:task, account_list: account_list) } let!(:contact_1) { create(:contact, account_list: account_list, send_newsletter: 'Email') } let!(:contact_2) { create(:contact, account_list: account_list, send_newsletter: 'Physical') } let!(:contact_3) { create(:contact, account_list: account_list, send_newsletter: 'Both') } before do subject.comments.build(body: 'test') end context 'physical' do before do subject.activity_type = 'Newsletter - Physical' end it 'creates two seperate log newsletter tasks' do expect { subject.save }.to change { Task.count }.from(0).to(3) end it 'creates two seperate comments' do expect { subject.save }.to change { ActivityComment.count }.from(0).to(3) end it 'creates tasks associated to correct contacts' do subject.save expect(contact_1.tasks.empty?).to be_truthy expect(contact_2.tasks.empty?).to be_falsy expect(contact_3.tasks.empty?).to be_falsy end it 'copies attributes to created tasks' do subject.save created_task = contact_3.tasks.first expect(created_task.subject).to eq(subject.subject) expect(created_task.activity_type).to eq(subject.activity_type) expect(created_task.completed_at).to eq(subject.completed_at) expect(created_task.completed).to eq(subject.completed) end end context 'email' do context 'with source Nil' do before do subject.activity_type = 'Newsletter - Email' subject.source = nil end it 'does not create a seperate log newsletter tasks' do expect { subject.save }.to change { Task.count }.from(0).to(3) end it 'creates two seperate comments' do expect { subject.save }.to change { ActivityComment.count }.from(0).to(3) end it 'creates tasks associated to correct contacts' do subject.save expect(contact_1.tasks.empty?).to be_falsy expect(contact_2.tasks.empty?).to be_truthy expect(contact_3.tasks.empty?).to be_falsy end it 'copies attributes to created tasks' do subject.save created_task = contact_3.tasks.first expect(created_task.subject).to eq(subject.subject) expect(created_task.activity_type).to eq(subject.activity_type) expect(created_task.completed_at).to eq(subject.completed_at) expect(created_task.completed).to eq(subject.completed) end end context 'with source MailChimp' do before do subject.activity_type = 'Newsletter - Email' subject.source = 'MailChimp' end it 'does not create seperate log newsletter tasks' do expect { subject.save }.to change { Task.count }.from(0).to(1) end it 'creates two seperate comments' do expect { subject.save }.to change { ActivityComment.count }.from(0).to(1) end end end it 'does not try to update uncompleted_tasks_count' do expect_any_instance_of(Contact).to_not receive(:update_uncompleted_tasks_count) subject.activity_type = 'Newsletter - Email' subject.completed = true subject.source = nil subject.save end end describe '#update_completed_at' do context 'complete' do it 'sets completed_at, start_at, and result on create' do task = build(:task, completed: true, start_at: nil, result: nil) travel_to Time.current do expect { task.save }.to change { task.completed_at }.from(nil).to(Time.current) .and change { task.start_at }.from(nil).to(Time.current) .and change { task.result }.from(nil).to('Done') end end it 'sets completed_at, start_at, and result on update' do task = create(:task, completed: false, start_at: nil, result: nil) task.completed = true travel_to Time.current do expect { task.save }.to change { task.completed_at }.from(nil).to(Time.current) .and change { task.start_at }.from(nil).to(Time.current) .and change { task.result }.from(nil).to('Done') end end end context 'not complete' do it 'sets completed_at, start_at, and result on create' do task = build(:task, completed: false, start_at: nil, result: nil) travel_to Time.current do expect { task.save }.to_not change { task.completed_at }.from(nil) end expect(task.start_at).to eq(nil) expect(task.result).to eq(nil) end it 'sets completed_at, start_at, and result on update' do original_completed_at = 1.month.ago task = create(:task, completed: true, completed_at: original_completed_at, start_at: nil, result: nil) travel_to Time.current do expect { task.update(completed: false) }.to change { task.completed_at }.from(original_completed_at).to(nil) expect(task.start_at).to eq(original_completed_at) expect(task.result).to eq('') end end end end describe '.all_result_options' do it 'returns all results' do expect(described_class.all_result_options).to eq( 'Appointment' => %w[Completed Attempted], 'Call' => ['Attempted - Left Message', 'Attempted', 'Completed', 'Received'], 'Email' => %w[Completed Received], 'Facebook Message' => %w[Completed Received], 'Letter' => %w[Completed Received], 'Pre Call Letter' => %w[Completed Received], 'Reminder Letter' => %w[Completed Received], 'Support Letter' => %w[Completed Received], 'Talk to In Person' => ['Completed'], 'Text Message' => %w[Completed Received], 'Thank' => %w[Completed Received], 'default' => ['Done'] ) end end describe '.all_next_action_options' do it 'returns next actions' do expect(described_class.all_next_action_options).to eq( 'Appointment' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'Appointment', 'Prayer Request', 'Thank'], 'Call' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'Appointment', 'Prayer Request', 'Thank'], 'Email' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'Appointment', 'Prayer Request', 'Thank'], 'Facebook Message' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'Appointment', 'Prayer Request', 'Thank'], 'Letter' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'None'], 'Prayer Request' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'Appointment', 'Prayer Request', 'Thank'], 'Pre Call Letter' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'None'], 'Reminder Letter' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'None'], 'Support Letter' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'None'], 'Talk to In Person' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'Appointment', 'Prayer Request', 'Thank'], 'Text Message' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'Appointment', 'Prayer Request', 'Thank'], 'Thank' => ['Call', 'Email', 'Text Message', 'Facebook Message', 'Talk to In Person', 'None'], 'default' => ['None'] ) end end end
chuckmersereau/api_practice
spec/serializers/activity_comment_serializer_spec.rb
require 'rails_helper' describe ActivityCommentSerializer do let(:activity_comment) do build(:activity_comment, person: build(:person)) end subject { ActivityCommentSerializer.new(activity_comment).as_json } describe '#body' do it 'returns the body' do expect(subject[:body]).to eq activity_comment.body end end end
chuckmersereau/api_practice
app/serializers/activity_contact_serializer.rb
<filename>app/serializers/activity_contact_serializer.rb class ActivityContactSerializer < ApplicationSerializer include DisplayCase::ExhibitsHelper belongs_to :contact belongs_to :activity end
chuckmersereau/api_practice
spec/services/task/filter/tags_spec.rb
require 'rails_helper' RSpec.describe Task::Filter::Tags do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:task_one) { create(:task, account_list_id: account_list.id, tag_list: 'tag1,tag2') } let!(:task_two) { create(:task, account_list_id: account_list.id, tag_list: 'tag1') } let!(:task_three) { create(:task, account_list_id: account_list.id, tag_list: 'tag3') } let!(:task_four) { create(:task, account_list_id: account_list.id, tag_list: '') } describe '#config' do it 'does not have config' do expect(described_class.config([account_list])).to eq(nil) end end 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, { tags: {} }, nil)).to eq nil expect(described_class.query(tasks, { tags: [] }, nil)).to eq nil expect(described_class.query(tasks, { tags: '' }, nil)).to eq nil end end context 'filter with tags' do it 'returns only tasks that have the tag' do expect(described_class.query(tasks, { tags: 'tag1' }, nil).to_a).to match_array [task_one, task_two] end it 'returns only tasks that have multiple tags' do expect(described_class.query(tasks, { tags: 'tag1,tag2' }, nil).to_a).to eq [task_one] end it 'accepts tags as comma separated string' do expect(described_class.query(tasks, { tags: 'tag1,tag2' }, nil).to_a).to eq [task_one] end it 'accepts tags as an array when any_tags is set to true' do result = described_class.query(tasks, { tags: 'tag1, tag3', any_tags: 'true' }, nil).to_a expect(result).to match_array [task_one, task_two, task_three] end end end end
chuckmersereau/api_practice
db/migrate/20120717195403_add_access_token_to_people.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 class AddAccessTokenToPeople < ActiveRecord::Migration def change add_column :people, :access_token, :string, limit: 32 add_index :people, :access_token, unique: true end end