repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
chuckmersereau/api_practice
db/migrate/20170913013837_drop_recurring_recommendation_results.rb
class DropRecurringRecommendationResults < ActiveRecord::Migration def change drop_table :recurring_recommendation_results end end
chuckmersereau/api_practice
app/models/notification_type.rb
<reponame>chuckmersereau/api_practice class NotificationType < ApplicationRecord # attr_accessible :description, :type def initialize(*args) @contacts ||= {} super end def self.types @@types ||= connection.select_values("select distinct(type) from #{table_name}") end def self.check_all(account_list) contacts = {} types.each do |type| type_instance = type.constantize.first next unless account_list .notification_preferences .where(notification_type_id: type_instance.id) .where('"notification_preferences"."email" = true OR "notification_preferences"."task" = true') .exists? contacts[type] = type_instance.check(account_list) end.compact contacts end # Check to see if this designation_account has donations that should trigger a notification def check(account_list) notifications = [] check_contacts_filter(account_list.contacts).each do |contact| donation = check_for_donation_to_notify(contact) next unless donation && donation.donation_date > 60.days.ago # Don't notify for old gifts next if contact.notifications.active.exists?(notification_type_id: id, donation_id: donation.id) notification = contact.notifications.create!(notification_type_id: id, donation: donation, event_date: Date.today) notifications << notification end notifications end # Create a task that corresponds to this notification def create_task(account_list, notification) contact = notification.contact task = account_list.tasks.create(task_attributes(notification)) task.activity_contacts.create(contact_id: contact.id) task end def task_description(notification) format(_(task_description_template), interpolation_values(notification)) end def email_description(notification, context) values = interpolation_values(notification) # insert %{link} in the place of the contact name so that it can be split out later. localized = format(_(task_description_template(notification)), values.merge(contact_name: '%{link}')) # replace each instance of %{contact_name} with a link # to the contact by splitting and joining in a safe way context.safe_join(localized.split('%{link}'), contact_link(notification, context)) end protected def interpolation_values(notification) { contact_name: notification.contact.name, amount: notification.donation&.localized_amount, date: notification.donation&.localized_date, designation: notification.donation&.designation_account&.descriptor } end def contact_link(notification, context) url = WebRouter.contact_url(notification.contact) name = notification.contact.name context.link_to(name, url) end def task_description_template(_notification = nil) raise 'This method (or create_task and task_description) must be implemented in a subclass' end def task_attributes(notification) { subject: task_description(notification), start_at: Time.now, activity_type: _(task_activity_type), notification_id: notification.id, source: type } end def task_activity_type _('Thank') end def check_contacts_filter(contacts) contacts end def check_for_donation_to_notify(_contact) raise 'This method (or check) must be implemented in a subclass' end end
chuckmersereau/api_practice
app/workers/add_appeal_to_tnt_donations_worker.rb
<filename>app/workers/add_appeal_to_tnt_donations_worker.rb class AddAppealToTntDonationsWorker include Sidekiq::Worker include Concerns::TntImport::AppealHelpers def perform(import_id) load_import(import_id) return unless @import linked_donations = find_gift_rows.map(&method(:link_donation_to_appeal)) ids = linked_donations.compact.collect(&:id) # because the sidekiq config sets the logging level to Fatal, # log to fatal so that we can see these in the logs Rails.logger.fatal("AddAppealToTntDonationsWorker linked the following donations to appeals: #{ids.join(', ')}") end private def find_gift_rows xml.tables['Gift'].select(&method(:attached_appeal_id)).select(&:present?) end def load_import(import_id) @import = Import.joins(:account_list).find_by(id: import_id, source: 'tnt') @import&.file&.cache_stored_file! end def link_donation_to_appeal(gift_row) appeal = find_appeal(gift_row) return unless appeal donation = find_donation(gift_row) return if donation.blank? || donation.appeal_id.present? donation.update(appeal: appeal, appeal_amount: appeal_amount(gift_row)) ensure_summed_pledge_amount(donation) donation end def ensure_summed_pledge_amount(donation) pledge = donation.reload.pledges.first return unless pledge donations = pledge.donations.to_a return unless donations.many? pledge.update(amount: donations.sum(&:appeal_amount)) end def find_appeal(gift_row) tnt_id = attached_appeal_id(gift_row) @appeals ||= {} return @appeals[tnt_id] if @appeals.key? tnt_id @appeals[tnt_id] = account_list.appeals.find_by(tnt_id: tnt_id) end def find_donation(gift_row) exact_donation_match(gift_row) || find_donation_by_contact(gift_row) end def exact_donation_match(gift_row) gift_code = gift_row['OrgGiftCode'] return unless gift_code.present? # in some instances the tnt code is from a different set then what the same donation has in mpdx. # This leads to a chance of collisions, so also make sure we are matching based on amount and date. donations_scope(gift_row).where(remote_id_match(gift_code).or(tnt_id_match(gift_code))).first end def find_donation_by_contact(gift_row) contact = account_list.contacts.find_by(tnt_id: gift_row['ContactID']) if gift_row['ContactID'] contact ||= find_contact_by_donor_id(gift_row) return unless contact matching_donations = donations_scope(gift_row).where(donor_account: contact.donor_accounts).to_a resolve_multiple_donations(matching_donations) end def find_contact_by_donor_id(gift_row) account_number = donor_account_number(gift_row['DonorID']) return unless account_number contacts = account_list.contacts .includes(:donor_accounts) .where(donor_accounts: { account_number: account_number }) .to_a # if there is more than one contact with this donor account, run. return unless contacts.count == 1 contacts.first end def resolve_multiple_donations(donations) # if 0, return nil # if 1, return first # if many, only return if none have an appeal id return if donations.count > 1 && donations.any?(&:appeal_id) donations.first end def donor_account_number(donor_id) return unless donor_id donor = xml.find(:Donor, donor_id) return unless donor && donor['OrgDonorCode'] # also include a version padded with zeros to account for Siebel # account numbers that may have been truncated in tnt [donor['OrgDonorCode'], donor['OrgDonorCode'].to_s.rjust(9, '0')] end def donations_scope(gift_row) @account_list_donations ||= account_list.donations @account_list_donations.where(amount: gift_row['Amount'], donation_date: gift_row['GiftDate']) end def attached_appeal_id(gift_row) # Version 3.2 of Tnt changed the relationship beteween Gifts and Appeals: # In 3.1 a Gift can only belong to one Appeal, through a foreign key on the Gift table. # In 3.2 a Gift can be split and belong to many Appeals, through a new GiftSplit table. return gift_row['AppealID'] if @xml.version < 3.2 split = xml.find(:GiftSplit, 'GiftID' => gift_row['id']) return unless split split['CampaignID'] end def appeal_amount(gift_row) gift_row[appeal_amount_name] end # # Data methods # def tnt_import @tnt_import ||= TntImport.new(@import) end def xml @xml ||= tnt_import.xml end def account_list @account_list ||= @import.account_list end # # Query methods # def donation_table Donation.arel_table end def remote_id_match(code) donation_table[:remote_id].eq(code) end def tnt_id_match(code) donation_table[:tnt_id].eq(code) end end
chuckmersereau/api_practice
spec/factories/donor_accounts.rb
FactoryBot.define do factory :donor_account do association :organization account_number 'MyString' name 'MyString' total_donations 3 last_donation_date Date.today first_donation_date Date.today donor_type 'Type' contact_ids [] end end
chuckmersereau/api_practice
spec/models/activity_contact_spec.rb
<filename>spec/models/activity_contact_spec.rb<gh_stars>0 require 'rails_helper' RSpec.describe ActivityContact, type: :model do end
chuckmersereau/api_practice
app/workers/run_once/account_password_removal_worker.rb
class RunOnce::AccountPasswordRemovalWorker include Sidekiq::Worker sidekiq_options queue: :api_run_once def perform accounts_with_tokens.find_each do |oa| next unless oa.valid? oa.update_columns(username: nil, password: nil) end end private def accounts_with_tokens Person::OrganizationAccount.where.not(password: nil, token: nil) end end
chuckmersereau/api_practice
spec/factories/user_coaches.rb
<filename>spec/factories/user_coaches.rb FactoryBot.define do factory :user_coach, class: 'User::Coach' do first_name { Faker::Name.first_name } last_name { Faker::Name.last_name } end end
chuckmersereau/api_practice
app/models/question.rb
class Question < ApplicationRecord PERMITTED_ATTRIBUTES = [ :id, :question ].freeze end
chuckmersereau/api_practice
spec/support/shared_controller_examples/common_variables.rb
RSpec.shared_examples 'common_variables' do let(:id_param) { defined?(id) ? { id: id } : {} } let(:full_params) { id_param.merge(defined?(parent_param) ? parent_param : {}) } let(:parent_param_if_needed) { defined?(parent_param) ? parent_param : {} } let(:parent_association_if_needed) do defined?(parent_association) ? parent_association : parent_param_if_needed.keys.last.to_s.gsub('_id', '') end let(:full_correct_attributes) do { data: { type: resource_type, attributes: correct_attributes.merge(overwrite: true) }.merge(relationships_params) }.merge(full_params) end let(:full_unpermitted_attributes) do { data: { type: resource_type, attributes: correct_attributes.merge(overwrite: true) }.merge(unpermitted_relationships_params) }.merge(full_params) end let(:full_incorrect_attributes) do { data: { type: resource_type, attributes: incorrect_attributes.merge(overwrite: true) }.merge(incorrect_relationships_params) }.merge(full_params) end let(:relationships_params) do return { relationships: correct_relationships } if defined?(correct_relationships) if defined?(account_list) { relationships: { account_list: { data: { type: 'account_lists', id: account_list.id } } } } else {} end end let(:update_relationships_params) do defined?(update_relationships) ? { relationships: update_relationships } : relationships_params end let(:incorrect_relationships_params) do defined?(incorrect_relationships) ? { relationships: incorrect_relationships } : relationships_params end let(:unpermitted_relationships_params) do return {} unless defined?(unpermitted_relationships) { relationships: unpermitted_relationships } end let(:reference_key) { defined?(given_reference_key) ? given_reference_key : correct_attributes.keys.first } let(:reference_value) { defined?(given_reference_value) ? given_reference_value : correct_attributes.values.first } let(:count_proc) { defined?(count) ? count : -> { resources_count } } let(:resource_not_destroyed_scope) { defined?(not_destroyed_scope) ? not_destroyed_scope : resource.class } let(:serializer_class) do defined?(given_serializer_class) ? given_serializer_class : ActiveModel::Serializer.serializer_for(resource) end let(:serializer) { serializer_class.new(resource) } let(:defined_resource_type) { defined?(given_resource_type) ? given_resource_type : nil } let(:resource_type) do defined_resource_type || serializer._type || resource.class.to_s.underscore.tr('/', '_').pluralize end let(:response_errors) { JSON.parse(response.body)['errors'] } let(:response_error_pointers) do response_errors.map do |error| error['source']['pointer'] if error['source'] end end let(:full_update_attributes) do if defined?(update_attributes) { data: { type: resource_type, attributes: update_attributes }.merge(update_relationships_params) }.merge(full_params) else full_correct_attributes end end let(:update_reference_key) do if defined?(given_update_reference_key) given_update_reference_key else full_update_attributes[:data][:attributes].keys.first end end let(:update_reference_value) do if defined?(given_update_reference_value) given_update_reference_value else full_update_attributes[:data][:attributes].values.first end end let(:attributes_with_incorrect_resource_type) do full_correct_attributes.tap do |params| params[:data][:type] = :gummybear # should definitely fail end end def invalid_status_detail body = response.body.blank? ? '' : JSON.pretty_generate(JSON.parse(response.body)) "\n\nResponse Status: #{response.status}\nResponse Body: #{body}" end def resources_count defined?(reference_scope) ? reference_scope.count : resource_not_destroyed_scope.count end end
chuckmersereau/api_practice
app/services/mail_chimp/importer/matcher.rb
# This class finds MPDX People matching the member_info objects from MailChimp. class MailChimp::Importer class Matcher attr_reader :mail_chimp_account, :account_list def initialize(mail_chimp_account) @mail_chimp_account = mail_chimp_account @account_list = mail_chimp_account.account_list end def find_matching_people(member_infos) people_matching_member_infos = fetch_people_matching_member_infos(member_infos) reject_extra_subscribe_causers(people_matching_member_infos) end private def fetch_people_matching_member_infos(member_infos) member_infos.each_with_object({}.with_indifferent_access) do |member_info, matching_people_hash| person = find_person(member_info[:first_name], member_info[:last_name], member_info[:email]) matching_people_hash[person.id] ||= member_info if person end end def find_person(first_name, last_name, email) person_by_email(email) || person_by_name(first_name, last_name) end def person_by_name(first_name, last_name) account_list.people.find_by(first_name: first_name, last_name: last_name) end def person_by_email(email) account_list.people.joins(:primary_email_address) .find_by(email_addresses: { email: email&.downcase }) end def reject_extra_subscribe_causers(people_matching_member_infos) contacts_associated_to_person_ids = fetch_contacts_associated_to_person_ids(people_matching_member_infos.keys) contacts_that_should_be_imported = contacts_associated_to_person_ids.select do |contact| contact_that_should_be_imported?(contact, people_matching_member_infos) end people_matching_member_infos.slice(*contacts_that_should_be_imported.flat_map(&:people).map(&:id)) end def fetch_contacts_associated_to_person_ids(person_ids) account_list.contacts .joins(:people) .where(people: { id: person_ids }) end def contact_that_should_be_imported?(contact, people_matching_member_infos) return true if contact.send_newsletter.in?(%w(Email Both)) contact.people.all? do |person| person_should_be_imported?(person, people_matching_member_infos) end end def person_should_be_imported?(person, people_matching_member_infos) person.primary_email_address.blank? || person.optout_enewsletter? || people_matching_member_infos.include?(person.id) end end end
chuckmersereau/api_practice
spec/models/user/option_spec.rb
require 'rails_helper' RSpec.describe User::Option, type: :model do let(:user) { create(:user_with_account) } subject { create(:user_option, user: user) } it { is_expected.to belong_to(:user) } it { is_expected.to validate_presence_of(:user) } it { is_expected.to validate_presence_of(:key) } it { is_expected.to validate_uniqueness_of(:key).scoped_to(:user_id) } it { is_expected.to have_db_column(:key).of_type(:string) } it { is_expected.to have_db_column(:value).of_type(:text) } it { is_expected.to have_db_column(:user_id).of_type(:uuid) } it { is_expected.to have_db_column(:id).of_type(:uuid) } it { is_expected.to have_db_index([:key, :user_id]).unique(true) } it { is_expected.to allow_value('snake_case').for(:key) } it { is_expected.to allow_value('camelCase').for(:key) } it { is_expected.to_not allow_value('Title Case').for(:key) } end
chuckmersereau/api_practice
engines/auth/config/initializers/warden.rb
<reponame>chuckmersereau/api_practice<filename>engines/auth/config/initializers/warden.rb require 'warden' Warden::Manager.serialize_into_session(&:id) Warden::Manager.serialize_from_session do |id| User.find(id) end
chuckmersereau/api_practice
app/preloaders/api/v2/contacts/addresses_preloader.rb
<gh_stars>0 class Api::V2::Contacts::AddressesPreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = {}.freeze FIELD_ASSOCIATION_MAPPING = { geo: :master_address }.freeze end
chuckmersereau/api_practice
db/migrate/20120531202725_add_tags_to_import.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 class AddTagsToImport < ActiveRecord::Migration def change add_column :imports, :tags, :text end end
chuckmersereau/api_practice
app/services/contact/find_from_name.rb
<reponame>chuckmersereau/api_practice class Contact::FindFromName def initialize(contact_scope, name) @contact_scope = contact_scope @name = name end def first find_contact_by_name.first.presence || find_contact_by_greeting.first.presence || find_contact_by_primary_person.first.presence || find_contact_by_spouse.first.presence end private attr_accessor :name, :contact_scope def find_contact_by_name contact_scope.where(name: [name, parse_and_rebuild_name].select(&:present?)) end def find_contact_by_greeting contact_scope.where(greeting: [name, parse_and_rebuild_name, parse_and_rebuild_first_name].select(&:present?)) end def find_contact_by_primary_person people_params = { first_name: parsed_name_parts[:first_name], last_name: parsed_name_parts[:last_name] } contact_scope.people.joins(:people).where(people: people_params) end def find_contact_by_spouse people_params = { first_name: parsed_name_parts[:spouse_first_name], last_name: parsed_name_parts[:spouse_last_name] } contact_scope.people.joins(:people).where(people: people_params) end def parsed_name_parts @parsed_name_parts ||= HumanNameParser.new(name).parse end def parse_and_rebuild_name @parse_and_rebuild_name ||= Contact::NameBuilder.new(name).name end def parse_and_rebuild_first_name @parse_and_rebuild_first_name ||= Contact::NameBuilder.new(parsed_name_parts.slice(:first_name, :spouse_first_name)).name end end
chuckmersereau/api_practice
spec/acceptance/api/v2/account_lists/imports/tnt_data_sync_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/acceptance/api/v2/account_lists/imports/tnt_data_sync_spec.rb require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Account Lists > Imports > from TNT Data Sync' do include_context :multipart_form_data_headers include ActionDispatch::TestProcess documentation_scope = :account_lists_api_imports before { stub_smarty_streets } let(:resource_type) { 'imports' } let!(:user) { create(:user_with_account) } let!(:fb_account) { create(:facebook_account, person_id: user.id) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let(:import) do create(:import, account_list: account_list, user: user, source_account_id: fb_account.id) end let(:id) { import.id } let(:new_import) do fixture_file = Rails.root.join('spec', 'fixtures', 'tnt', 'tnt_data_sync_no_org_lowercase_fields.tntmpd') attrs = { file: Rack::Test::UploadedFile.new(fixture_file) } attributes_for(:import) .reject { |attr| attr.to_s.end_with?('_id') } .tap { |attributes| attributes.delete('id') }.merge(attrs) end let(:relationships) do { account_list: { data: { type: 'account_lists', id: account_list.id } }, user: { data: { type: 'users', id: user.id } }, source_account: { data: { type: 'facebook_accounts', id: fb_account.id } } } end let(:resource_attributes) do %w( account_list_id created_at file_constants file_constants_mappings file_headers file_headers_mappings file_url group_tags groups import_by_group in_preview override source tag_list updated_at updated_in_db_at ) end let(:resource_associations) do %w( sample_contacts user ) end let(:form_data) { build_data(new_import, relationships: relationships) } context 'authorized user' do before { api_login(user) } post '/api/v2/account_lists/:account_list_id/imports/tnt_data_sync' do with_options scope: [:data, :attributes] do parameter 'file', 'The file uploaded as form-data', type: 'String' parameter 'groups', 'Groups', type: 'String' parameter 'group_tags', 'Group Tags', type: 'String' parameter 'import_by_group', 'Import by Group', type: 'String' parameter 'in_preview', "The Import will not be performed while it's in preview", type: 'Boolean' parameter 'override', 'Override', type: 'Boolean' parameter 'source_account_id', 'Source Account ID', type: 'String' parameter 'tag_list', 'Comma delimited list of Tags', type: 'String' parameter 'user_id', 'User ID', type: 'String' end with_options scope: [:data, :attributes] do response_field 'account_list_id', 'Account List ID', type: 'Number' response_field 'created_at', 'Created At', type: 'String' response_field 'file_url', 'A URL to download the file', type: 'String' response_field 'file_headers_mappings', 'Not applicable to TNT XML imports.', type: 'Object' response_field 'file_headers', 'Not applicable to TNT XML imports.', type: 'Object' response_field 'file_constants', 'Not applicable to TNT XML imports.', type: 'Object' response_field 'file_constants_mappings', 'Not applicable to TNT XML imports.', type: 'Object' response_field 'group_tags', 'Group Tags', type: 'String' response_field 'groups', 'Groups', type: 'Array[String]' response_field 'import_by_group', 'Import by Group', type: 'String' response_field 'override', 'Override', type: 'Boolean' response_field 'source', 'Source; Defaults to "tnt"', type: 'String' response_field 'tag_list', 'Comma delimited list of Tags', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' response_field 'in_preview', "The Import will not be performed while it's in preview; Defaults to false", type: 'Boolean' end with_options scope: [:data, :relationships] do response_field 'user', 'User that the Import belongs to', type: 'Object' end example 'TNT Data Sync Import [CREATE]', document: documentation_scope do explanation 'Creates a new TNT Data Sync Import associated with the Account List. This ' \ 'endpoint expects a .tntmpd file to be uploaded using Content-Type ' \ '"multipart/form-data", this makes the endpoint unique in that it does not ' \ 'expect JSON content. Unless otherwise specified, the Import will be created ' \ 'with "in_preview" set to false, which will cause the import to begin after ' \ 'being created (the import runs asynchronously as a background job).' do_request data: form_data expect(response_status).to eq(201), invalid_status_detail check_resource(['relationships']) expect(response_headers['Content-Type']).to eq 'application/vnd.api+json; charset=utf-8' expect(resource_data['id']).to be_present expect(resource_data['attributes']['file_url']).to be_present expect(resource_data['attributes']['source']).to eq 'tnt_data_sync' expect(resource_data['attributes']['in_preview']).to eq false end end end end
chuckmersereau/api_practice
app/services/contact/filter/updated_at.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 class Contact::Filter::UpdatedAt < Contact::Filter::Base def execute_query(contacts, filters) contacts.where(updated_at: filters[:updated_at]) end end
chuckmersereau/api_practice
spec/services/mail_chimp/exporter/batcher_spec.rb
require 'rails_helper' RSpec.describe MailChimp::Exporter::Batcher do 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(:list_id) { 'list_one' } let(:email_hash) { '1919bfc4fa95c7f6b231e583da677a17' } subject { described_class.new(mail_chimp_account, mock_gibbon_wrapper, list_id) } let(:mock_gibbon_wrapper) { double(:mock_gibbon_wrapper) } let(:mock_gibbon_list_object) { double(:mock_gibbon_list_object) } let(:mock_gibbon_batches) { double(:mock_gibbon_batches) } let(:mock_interest_categories) { double(:mock_interest_categories) } let(:mock_interests) { double(:mock_interests) } let(:mock_batch_response) { { 'id' => 'a1b2c3', '_links' => [] } } let(:complete_batch_body) do { body: { operations: operations_body } } end before do allow(mock_gibbon_wrapper).to receive(:gibbon_list_object).and_return(mock_gibbon_list_object) allow(mock_gibbon_wrapper).to receive(:batches).and_return(mock_gibbon_batches) allow(mock_gibbon_list_object).to receive(:lists).and_return(list_id) 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) allow(mock_interests).to receive(:retrieve).and_return( 'interests' => [ { 'name' => 'status or tag', 'id' => 'random' } ] ) end context '#subscribe_contacts' do let(:first_email) { '<EMAIL>' } let!(:contact) { create(:contact, account_list: account_list, people: [person, person_opted_out]) } let(:person) do create(:person, primary_email_address: build(:email_address, email: first_email)) end let(:person_opted_out) do create(:person, optout_enewsletter: true, primary_email_address: build(:email_address)) end let(:operations_body) do [ { method: 'PUT', path: "/lists/#{list_id}/members/#{email_hash}", body: person_operation_body.to_json } ] end let(:person_operation_body) do { status: 'subscribed', email_address: '<EMAIL>', merge_fields: { EMAIL: '<EMAIL>', FNAME: person.first_name, LNAME: person.last_name, GREETING: contact.greeting }, language: 'en', interests: { random: false } } end before do # This block of code ensures that MC batches method will trigger each # of the 3 types of errors that are handled by the import. times_called = 0 allow(mock_gibbon_batches).to receive(:create) do times_called += 1 case times_called when 1 raise Gibbon::MailChimpError, 'You have more than 500 pending batches.' when 2 raise Gibbon::MailChimpError, 'nested too deeply' when 3 raise Gibbon::MailChimpError, '<H1>Bad Request</H1>' else mock_batch_response end end end it 'subscribes the contacts and creates the mail_chimp_members handling all 3 MC API intermittent errors' do expect(mock_gibbon_batches).to receive(:create).with(complete_batch_body).exactly(4) expect do subject.subscribe_contacts([contact]) end.to change { mail_chimp_account.mail_chimp_members(true).count }.by(1) end it 'adds tag interests' do contact.tag_list.add('status or tag') subject.subscribe_contacts([contact]) expect(mail_chimp_account.mail_chimp_members(true).last.tags.compact).to_not be_empty end it 'logs request to AudtChangeLog' do expect(AuditChangeWorker).to receive(:perform_async) subject.subscribe_contacts([contact]) end it 'adds worker to watch batch results' do expect do subject.subscribe_contacts([contact]) end.to change(MailChimp::BatchResultsWorker.jobs, :size).by(1) end it "doesn't send null on last name or greeting" do person.update!(last_name: nil) contact.update!(greeting: nil) person_operation_body[:merge_fields][:LNAME] = '' expect(mock_gibbon_batches).to receive(:create).with(complete_batch_body).exactly(4) subject.subscribe_contacts([contact]) end end context '#unsubscribe_contacts' do let!(:mail_chimp_member) do create(:mail_chimp_member, mail_chimp_account: mail_chimp_account, email: '<EMAIL>', list_id: list_id) end let!(:second_mail_chimp_member) do create(:mail_chimp_member, mail_chimp_account: mail_chimp_account, list_id: list_id) end let(:operations_body) do [ { method: 'PATCH', path: "/lists/#{list_id}/members/#{email_hash}", body: { status: 'unsubscribed' }.to_json } ] end it 'unsubscribes the members based on the emails provided' do expect(mock_gibbon_batches).to receive(:create).with(complete_batch_body).and_return(mock_batch_response) subject.unsubscribe_members(mail_chimp_member.email => nil) end it 'sends provided unsubscribe reason to mailchimp' do reason = 'Test Reason' operations_body << { method: 'POST', path: "/lists/#{list_id}/members/#{email_hash}/notes", body: { note: "Unsubscribed by MPDX: #{reason}" }.to_json } expect(mock_gibbon_batches).to receive(:create).with(complete_batch_body).and_return(mock_batch_response) subject.unsubscribe_members(mail_chimp_member.email => reason) end it 'destroys associated mail chimp members' do allow(mock_gibbon_batches).to receive(:create).and_return(mock_batch_response) expect do subject.unsubscribe_members(mail_chimp_member.email => nil) end.to change(MailChimpMember, :count).by(-1) end end end
chuckmersereau/api_practice
db/migrate/20160419135520_add_foreign_key_to_peron_on_master_person.rb
<filename>db/migrate/20160419135520_add_foreign_key_to_peron_on_master_person.rb class AddForeignKeyToPeronOnMasterPerson < ActiveRecord::Migration def change add_foreign_key(:people, :master_people, dependent: :restrict) end end
chuckmersereau/api_practice
app/policies/prayer_letters_account_policy.rb
class PrayerLettersAccountPolicy < AccountListChildrenPolicy def sync? resource_owner? end end
chuckmersereau/api_practice
lib/batch_request_handler/instruments/request_validator.rb
<filename>lib/batch_request_handler/instruments/request_validator.rb module BatchRequestHandler module Instruments class RequestValidator < BatchRequestHandler::Instrument VALID_BATCH_METHODS = %w(GET POST PUT PATCH DELETE).freeze class InvalidBatchRequestError < StandardError DEFAULT_MESSAGE = 'This request is unable to be performed as part of a batch request'.freeze attr_reader :message, :status def initialize(message: DEFAULT_MESSAGE, status: 400) @message = message @status = status end end def around_perform_request(env) rack_request = Rack::Request.new(env) validate_request!(rack_request) yield env rescue InvalidBatchRequestError => error invalid_batch_request_error_response(error, rack_request) end def self.generate_invalid_batch_request_json_payload(error, rack_request) { errors: [ { status: error.status, message: error.message, meta: { method: rack_request.request_method, path: rack_request.path, body: rack_request.body.read } } ] } end private def validate_request!(rack_request) allowed_method?(rack_request) path_present?(rack_request) end def allowed_method?(rack_request) return if rack_request.request_method.in?(VALID_BATCH_METHODS) raise InvalidBatchRequestError, message: "HTTP method `#{rack_request.request_method}` is not allowed in a batch request", status: 405 end def path_present?(rack_request) return if rack_request.path.present? raise InvalidBatchRequestError, message: 'The `path` key must be provided as part of a request object in a batch request' end def invalid_batch_request_error_response(error, rack_request) json_response = self.class.generate_invalid_batch_request_json_payload(error, rack_request) body = JSON.dump(json_response) [error.status, { 'Content-Type' => 'application/json' }, [body]] end end end end
chuckmersereau/api_practice
app/services/concerns/reports/donation_sum_helper.rb
<gh_stars>0 module Concerns::Reports::DonationSumHelper protected def donation_currency(donation) donation.currency end def donation_amount(donation) donation.amount end def donoations_with_currency(donations) donations.currencies.select(&:present?).map do |currency| donos = donations.where(currency: currency) converted = donos.map(&:converted_amount).inject(:+) || 0 { amount: donos.sum(:amount), converted: converted, currency: currency } end end private def donations_by_currency(donations) Hash.new { |hash, key| hash[key] = [] }.tap do |grouped| donations.each do |donation| grouped[donation_currency(donation)].push(donation) end end end def sum_donations(donations) donations.map(&:amount).inject(:+) || 0 end def sum_converted_donations(donations, converted_currency = 'USD') donations.map do |donation| CurrencyRate.convert_on_date( amount: donation.amount, date: donation.donation_date, from: donation.currency, to: converted_currency ) end.inject(:+) || 0 end def sum_donations_by_month(donations, months) group_donations_by_month(donations, months).map { |donation| sum_donations(donation) } end def group_donations_by_month(donations, months) months.map do |month| donations.select { |donation| donation.donation_date.beginning_of_month == month } end end end
chuckmersereau/api_practice
db/migrate/20150714135841_create_mail_chimp_appeal_lists.rb
class CreateMailChimpAppealLists < ActiveRecord::Migration def change create_table :mail_chimp_appeal_lists do |t| t.integer :mail_chimp_account_id, null: false t.string :appeal_list_id, null: false t.integer :appeal_id, null: false t.timestamps null: false end add_index :mail_chimp_appeal_lists, :mail_chimp_account_id add_index :mail_chimp_appeal_lists, :appeal_list_id end end
chuckmersereau/api_practice
app/services/contact/filter/donation_date.rb
<gh_stars>0 class Contact::Filter::DonationDate < Contact::Filter::Base def execute_query(contacts, filters) # Contact::Filter::Donation handles date range if looking for no donations during period return contacts if filters[:donation] == 'none' params = daterange_params(filters[:donation_date]) contacts = contacts.joins(donor_accounts: [:donations]) if params.present? if params[:start] contacts = contacts.where('donations.donation_date >= :date_range_start AND '\ 'donations.designation_account_id IN (:designation_account_ids)', date_range_start: params[:start], designation_account_ids: designation_account_ids) end if params[:end] contacts = contacts.where('donations.donation_date <= :date_range_end AND '\ 'donations.designation_account_id IN (:designation_account_ids)', date_range_end: params[:end], designation_account_ids: designation_account_ids) end contacts end def title _('Gift Date') end def parent _('Gift Details') end def type 'daterange' end def custom_options [ { name: _('Last 30 Days'), start: 30.days.ago.beginning_of_day, end: Time.current }, { name: _('This Month'), start: Time.current.beginning_of_month + 1.hour, end: Time.current.end_of_month }, { name: _('Last Month'), start: 1.month.ago.beginning_of_month + 1.hour, end: 1.month.ago.end_of_month }, { name: _('Last Two Months'), start: 2.months.ago.beginning_of_month + 1.hour, end: Time.current.beginning_of_month }, { name: _('Last Three Months'), start: 3.months.ago.beginning_of_month + 1.hour, end: Time.current.beginning_of_month }, { name: _('This Year'), start: Time.current.beginning_of_year + 1.hour, end: Time.current.end_of_year }, { name: _('Last Year'), start: 1.year.ago.beginning_of_year + 1.hour, end: 1.year.ago.end_of_year } ] end def valid_filters?(filters) super && daterange_params(filters[:donation_date]).present? end end
chuckmersereau/api_practice
db/migrate/20120404163503_change_type_of_remote_id_from_designation_profile.rb
class ChangeTypeOfRemoteIdFromDesignationProfile < ActiveRecord::Migration def up change_column :designation_profiles, :remote_id, :string end def down change_column :designation_profiles, :remote_id, :integer end end
chuckmersereau/api_practice
spec/models/facebook_import_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe FacebookImport do let!(:user) { create(:user) } let!(:account) { create(:facebook_account, person_id: user.id) } let!(:account_list) { create(:account_list, creator: user) } let!(:import) do create(:import, source: 'facebook', source_account_id: account.id, account_list: account_list, user: user) end subject! { described_class.new(import) } describe 'when importing contacts' do let(:contact) { create(:contact, account_list: account_list) } let(:person) { create(:person) } let(:spouse) { create(:person) } before do stub_request(:get, "https://graph.facebook.com/#{account.remote_id}/friends?access_token=#{account.token}") .to_return(body: '{"data": [{"name": "<NAME>","id": "120581"}]}') stub_request(:get, "https://graph.facebook.com/120581?access_token=#{account.token}") .to_return(body: '{"id": "120581", "first_name": "John", "last_name": "Doe", '\ '"relationship_status": "Married", "significant_other":{"id":"120582"}}') stub_request(:get, "https://graph.facebook.com/120582?access_token=#{account.token}") .to_return(body: '{"id": "120582", "first_name": "Jane", "last_name": "Doe"}') end it 'should match an existing person on my list' do contact.people << person expect do expect(subject).to receive(:create_or_update_person).and_return(person) expect(subject).to receive(:create_or_update_person).and_return(create(:person)) # spouse subject.send(:import_contacts) end.to_not change(Contact, :count) end it 'should create a new contact for someone not on my list (or married to someone on my list)' do expect(subject).to receive(:create_or_update_person).and_return(spouse) expect do expect do expect(subject).to receive(:create_or_update_person).and_return(create(:person)) subject.send(:import_contacts) end.to change(Person, :count).by(1) end.to change(Contact, :count).by(1) end it 'should match a person to their spouse if the spouse is on my list' do contact.people << spouse # spouse_account create(:facebook_account, person: spouse, remote_id: '120582') expect do expect do expect(subject).to receive(:create_or_update_person).and_return(create(:person)) expect(subject).to receive(:create_or_update_person).and_return(spouse) subject.send(:import_contacts) end.to change(Person, :count).by(1) end.to_not change(Contact, :count) end it 'should add tags from the import' do import.update_column(:tags, 'hi, mom') subject.send(:import_contacts) expect(Contact.last.tag_list.sort).to eq(%w(hi mom)) end end describe 'create_or_update_person' do let(:friend) do OpenStruct.new(first_name: 'John', identifier: Time.now.to_i.to_s, raw_attributes: { 'birthday' => '01/02' }) end it 'should update the person if they already exist' do contact = create(:contact, account_list: account_list) person = create(:person, first_name: 'Not-John') create(:facebook_account, person: person, remote_id: friend.identifier) contact.people << person expect do subject.send(:create_or_update_person, friend, account_list) expect(person.reload.first_name).to eq('John') end.to_not change(Person, :count) end it 'should create a person with an existing Master Person if a person with this FB accoun already exists' do person = create(:person) create(:facebook_account, person: person, remote_id: friend.identifier, authenticated: true) expect do expect do subject.send(:create_or_update_person, friend, account_list) end.to change(Person, :count) end.to_not change(MasterPerson, :count) end it "should create a person and master peson if we can't find a match" do expect do expect do subject.send(:create_or_update_person, friend, account_list) end.to change(Person, :count) end.to change(MasterPerson, :count) end end end
chuckmersereau/api_practice
config/initializers/siebel_donations.rb
<reponame>chuckmersereau/api_practice SiebelDonations.configure do |config| config.oauth_token = ENV.fetch('WSAPI_KEY') config.default_timeout = 600 config.base_url = 'https://wsapi.cru.org/wsapi/rest' end
chuckmersereau/api_practice
app/controllers/monitors_controller.rb
class MonitorsController < ActionController::API def lb ActiveRecord::Migration.check_pending! ActiveRecord::Base.connection.select_values('select id from people limit 1') render text: File.read(Rails.public_path.join('lb.txt')) rescue ActiveRecord::PendingMigrationError render text: 'PENDING MIGRATIONS', status: :service_unavailable end def sidekiq if SidekiqMonitor.queue_latency_too_high? render text: 'Queue latency too high', status: :internal_server_error else render text: 'OK' end end def commit render text: ENV['GIT_COMMIT'] end end
chuckmersereau/api_practice
spec/models/notification_type/recontinuing_gift_spec.rb
require 'rails_helper' describe NotificationType::RecontinuingGift do let!(:recontinuing_gift) { NotificationType::RecontinuingGift.first_or_initialize } let!(:da) { create(:designation_account) } let!(:account_list) { create(:account_list) } let!(:contact) { create(:contact, account_list: account_list, pledge_amount: 9.99, pledge_received: true) } let!(:donor_account) { create(:donor_account) } let!(:donation) { create(:donation, donor_account: donor_account, designation_account: da) } let!(:old_donation) do create(:donation, donor_account: donor_account, designation_account: da, donation_date: Date.today << 3) end before do account_list.account_list_entries.create!(designation_account: da) contact.donor_accounts << donor_account contact.update_donation_totals(old_donation) contact.update_donation_totals(donation) end context '#check' do it 'adds a notification if a gift comes from a financial partner after a lag of 2 or more months' do expect(recontinuing_gift.check(account_list).size).to eq(1) end it 'does not add a notfication if the lag was just one month or there was no previous gift' do old_donation.update(donation_date: Date.today << 2) expect(recontinuing_gift.check(account_list)).to be_empty old_donation.destroy! expect(recontinuing_gift.check(account_list)).to be_empty end it 'does not add a notification if marked as pledge not received' do contact.update(pledge_received: false) expect(recontinuing_gift.check(account_list)).to be_empty end it 'does not notify if prior gift was a special gift', versioning: true do # First force the status to start as Partner - Special (without callbacks # so it won't trigger a partner status log entry) contact.update_column(:status, 'Partner - Special') # Do an update to Partner - Financial so that Partner - Special is # recorded in the partner status log contact.update(status: 'Partner - Financial') # Now don't consider it a recontinuing gift because the partner # status at the previous gift time was not Partner - Financial expect(recontinuing_gift.check(account_list)).to be_empty end end end
chuckmersereau/api_practice
app/services/deleted_records/filter/types.rb
class DeletedRecords::Filter::Types < ApplicationFilter def execute_query(deleted_records, filters) return deleted_records if filters[:types].blank? deleted_records.where(deletable_type: parse_list(filters[:types])) end end
chuckmersereau/api_practice
app/serializers/account_list/analytics_serializer.rb
class AccountList::AnalyticsSerializer < ServiceSerializer attributes :appointments, :contacts, :correspondence, :electronic, :email, :end_date, :facebook, :phone, :text_message, :start_date delegate :appointments, :contacts, :correspondence, :electronic, :email, :facebook, :text_message, :phone, to: :object end
chuckmersereau/api_practice
spec/factories/notification_types.rb
<reponame>chuckmersereau/api_practice FactoryBot.define do factory :notification_type do type 'NotificationType::CallPartnerOncePerYear' description 'MyText' end end
chuckmersereau/api_practice
app/workers/account_list_import_data_enqueuer_worker.rb
<reponame>chuckmersereau/api_practice class AccountListImportDataEnqueuerWorker include Sidekiq::Worker sidekiq_options queue: :api_account_list_import_data_enqueuer_worker, unique: :until_executed def perform account_list_ids_to_import.each do |account_list_id| Sidekiq::Client.push( 'class' => AccountList, 'args' => [account_list_id, :import_data], 'queue' => :api_account_list_import_data ) end end private def account_list_scope(users:, last_attempt: Time.current) AccountList.with_linked_org_accounts .has_users(users) .where('last_download_attempt_at IS NULL OR last_download_attempt_at <= ?', last_attempt) end def account_list_ids_to_import @account_list_ids_to_import ||= ( account_list_scope(users: active_users).pluck(:id) + account_list_scope(users: inactive_users, last_attempt: 1.week.ago).pluck(:id) ).uniq end def active_users User.where('current_sign_in_at >= ?', active_user_cutoff_time) end def inactive_users User.where('current_sign_in_at IS NULL OR current_sign_in_at < ?', active_user_cutoff_time) end def active_user_cutoff_time @active_user_cutoff_time ||= 2.months.ago end end
chuckmersereau/api_practice
spec/services/person/filter/deceased_spec.rb
require 'rails_helper' RSpec.describe Person::Filter::Deceased 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], deceased: true) } let!(:person_two) { create(:person, contacts: [contact_two], deceased: true) } let!(:person_three) { create(:person, contacts: [contact_one], deceased: false) } let!(:person_four) { create(:person, contacts: [contact_two], deceased: false) } describe '#query' do let(:scope) { account_list.people } context 'no filter params' do it 'returns nil' do expect(described_class.query(scope, {}, nil)).to eq(nil) expect(described_class.query(scope, { deceased: {} }, nil)).to eq(nil) expect(described_class.query(scope, { deceased: [] }, nil)).to eq(nil) expect(described_class.query(scope, { deceased: '' }, nil)).to eq(nil) end end context 'filter by deceased' do it 'returns only people that have deceased' do expect(described_class.query(scope, { deceased: 'true' }, nil).to_a).to match_array [person_one, person_two] end end context 'filter by not deceased' do it 'returns only people that have not deceased' do expect(described_class.query(scope, { deceased: 'false' }, nil).to_a).to match_array [person_three, person_four] end end end end
chuckmersereau/api_practice
spec/controllers/api/v2/account_lists/donor_accounts_controller_spec.rb
<gh_stars>0 require 'rails_helper' describe Api::V2::AccountLists::DonorAccountsController, type: :controller do let(:factory_type) { :donor_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!(:contact) { create(:contact, account_list: account_list) } let!(:contact2) { create(:contact, account_list: account_list) } let!(:donor_accounts) { create_list(:donor_account, 3) } let(:donor_account) { donor_accounts.first } let(:id) { donor_account.id } before do contact.donor_accounts << donor_accounts[0] contact.donor_accounts << donor_accounts[1] contact2.donor_accounts << donor_accounts[2] end let(:resource) { donor_account } let(:parent_param) { { account_list_id: account_list_id } } let(:correct_attributes) { attributes_for(:donor_account) } include_examples 'index_examples' include_examples 'show_examples' describe '#index' do let(:contact_one) { create(:contact, account_list: account_list) } let(:contact_two) { create(:contact) } let(:included_array_in_response) { JSON.parse(response.body)['included'] } before { api_login(user) } it 'shows donor accounts from selected contacts' do create(factory_type) get :index, account_list_id: account_list_id, filter: { contacts: [contact] } expect(response.status).to eq(200) expect(JSON.parse(response.body)['data'].count).to eq(2) end it "doesn't include contacts from different account_list" do create(factory_type, contacts: [contact_one, contact_two]) get :index, account_list_id: account_list_id, include: '*' expect(response.status).to eq(200) expect(included_array_in_response.any? { |resource| resource['id'] == contact_two.id }).to eq(false) end describe 'filter[wildcard_search]' do context 'account_number starts with' do let!(:donor_account) { create(factory_type, account_number: '1234') } before { contact.donor_accounts << donor_account } it 'returns donor_account' do get :index, account_list_id: account_list_id, filter: { wildcard_search: '12' } expect(JSON.parse(response.body)['data'][0]['id']).to eq(donor_account.id) end end context 'account_number does not start with' do let!(:donor_account) { create(factory_type, account_number: '1234') } before { contact.donor_accounts << donor_account } it 'returns donor_accounts' do get :index, account_list_id: account_list_id, filter: { wildcard_search: '34' } expect(JSON.parse(response.body)['data'].count).to eq(1) end end context 'name contains' do let!(:donor_account) { create(factory_type, name: 'abcd') } before { contact.donor_accounts << donor_account } it 'returns dnor_account' do get :index, account_list_id: account_list_id, filter: { wildcard_search: 'bc' } expect(JSON.parse(response.body)['data'][0]['id']).to eq(donor_account.id) end end context 'name does not contain' do let!(:donor_account) { create(factory_type, name: 'abcd') } before { contact.donor_accounts << donor_account } it 'returns no donor_accounts' do get :index, account_list_id: account_list_id, filter: { wildcard_search: 'def' } expect(JSON.parse(response.body)['data'].count).to eq(0) end end end end end
chuckmersereau/api_practice
dev/fixers/spouse_dup_info_fixer.rb
<gh_stars>0 # This is a script I used to help address this HelpScout ticket: # https://secure.helpscout.net/conversation/145083350/25821/?folderId=378967 # # The core issue was that after the user had done a Facebook import, Tnt import, # and done the Google contacts sync, plus maybe find duplicates at some point. # # Somewhere along the way, perhaps due to a bug in MPDX, many of the couples had # thek same phone number (mobile or work) for both spouses, as well as the same # emails for both. # # What I did before I ran it on production was to create a duplicate of his # contact data locally and teset it there to make sure it worked correctly. # # Similar care should be applied if you use this script again, and some of the # logic may be specific to his particular issue. # # This code may be somewhat specific to that user's particular circumstance and # may not always apply in every case. def fix_account_dup_contact_info(account_list, tnt_import) tnt_contacts_by_id = find_tnt_contacts_by_id(tnt_import) dup_info_contacts = account_list.contacts.select(&method(:people_have_dup_numbers?)) dup_info_contacts.each do |dup_info_contact| fix_dup_info_contact(dup_info_contact, tnt_contacts_by_id) end end def find_tnt_contacts_by_id(import) import.file.cache_stored_file! tnt = TntImport.new(import) tnt_contacts = tnt.xml['Contact']['row'] tnt_contacts_by_id = {} tnt_contacts.each do |tnt_contact| tnt_contacts_by_id[tnt_contact['id'].to_i] = tnt_contact end tnt_contacts_by_id end def people_have_dup_numbers?(contact) phones_for_contact = Set.new contact.people.each do |person| phones = person.phone_numbers.select { |p| p.number.present? } numbers = phones.map(&:number) existing_matches = phones_for_contact.select do |existing_phone| existing_phone.number.in?(numbers) end existing_numbers = phones_for_contact.map(&:number) current_matches = phones.select do |phone| phone.number.in?(existing_numbers) end all_home_numbers = existing_matches.all? { |p| p.location == 'home' } && current_matches.all? { |p| p.location == 'home' } if current_matches.any? if all_home_numbers puts "Home phones match for contact #{contact} with id #{contact.id}" else puts "Dup numbers for contact #{contact} with id #{contact.id}" return true end else phones.each { |p| phones_for_contact << p } end end false end def fix_dup_info_contact(dup_info_contact, tnt_contacts_by_id) tnt_fields = tnt_contacts_by_id[dup_info_contact.tnt_id] if tnt_fields.blank? puts "No Tnt fields for #{dup_info_contact}" else fix_non_primary_people_info(dup_info_contact, tnt_fields) end end def fix_non_primary_people_info(dup_info_contact, tnt_fields) primary_person = primary_person_by_first_name(dup_info_contact, tnt_fields) return unless primary_person non_primary_people = dup_info_contact.people.where.not(id: primary_person.id) fix_dup_phone(tnt_fields, 'MobilePhone', primary_person, non_primary_people) fix_dup_phone(tnt_fields, 'BusinessPhone', primary_person, non_primary_people) end def primary_person_by_first_name(dup_info_contact, tnt_fields) primary_people = dup_info_contact.people.where(first_name: tnt_fields['FirstName']) if primary_people.count > 1 puts "Tnt primary person not found for #{dup_info_contact}" nil elsif primary_people.count.zero? puts "Tnt primary person not found for #{dup_info_contact}" nil else primary_people.first end end def fix_dup_phone(tnt_fields, tnt_phone_field, primary_person, non_primary_people) primary_person_number = tnt_fields[tnt_phone_field] return if primary_person_number.blank? primary_person_number = clean_number(primary_person_number) unless primary_person_number.in?(primary_person.phone_numbers.pluck(:number)) puts "Primary person #{primary_person} with id #{primary_person.id}"\ "does not have number #{mobile_phone.number} in MPDX but has it in Tnt" return end non_primary_people.each do |spouse| dup_phones = spouse.phone_numbers.where(number: primary_person_number) dup_phones.each do |dup_phone| puts "Removing number #{dup_phone.number} for person #{spouse} with id #{spouse.id}" puts dup_phone.inspect dup_phone.destroy end end end def clean_number(number) phone = PhoneNumber.new(number: number) phone.clean_up_number phone.number end
chuckmersereau/api_practice
spec/workers/convert_credentials_worker_spec.rb
<filename>spec/workers/convert_credentials_worker_spec.rb require 'rails_helper' RSpec.describe ConvertCredentialsWorker do let(:oauth_convert_to_token_url) { 'https://example.com' } let(:username) { '<EMAIL>' } let(:password) { '<PASSWORD>' } let(:organization) { create(:fake_org, oauth_convert_to_token_url: oauth_convert_to_token_url) } let!(:organization_account) do create( :organization_account, organization: organization, username: username, password: password ) end let(:response) do "IsValidLogin,Token,Scope\n\"True\",\"abc-123\",\"user-123 profile-*\"\n" end before do stub_request(:post, oauth_convert_to_token_url).to_return(body: response) allow(ENV).to receive(:fetch).with('DONORHUB_CLIENT_ID') { 'client_id' } allow(ENV).to receive(:fetch).with('DONORHUB_CLIENT_SECRET') { 'client_secret' } end describe '#perform' do it 'should call RestClient::Request.execute' do expect(RestClient::Request).to( receive(:execute).with( method: :post, url: oauth_convert_to_token_url, payload: { 'UserName' => username, 'Password' => password, 'Action' => 'OAuthConvertToToken', 'client_id' => 'client_id', 'client_secret' => 'client_secret', 'client_instance' => 'app' } ).and_call_original ) subject.perform end end it 'should update organization_account' do subject.perform organization_account.reload expect(organization_account.token).to eq 'abc-123' end end
chuckmersereau/api_practice
app/services/task/filter/updated_at.rb
class Task::Filter::UpdatedAt < Task::Filter::Base def execute_query(tasks, filters) tasks.where(updated_at: filters[:updated_at]) end end
chuckmersereau/api_practice
spec/workers/google_email_sync_enqueuer_worker_spec.rb
<filename>spec/workers/google_email_sync_enqueuer_worker_spec.rb<gh_stars>0 require 'rails_helper' describe GoogleEmailSyncEnqueuerWorker do let!(:first_google_integration_with_email) { create(:google_integration, email_integration: true) } let!(:second_google_integration_with_email) { create(:google_integration, email_integration: true) } let!(:google_integration_without_email) { create(:google_integration, email_integration: false) } it 'queues the jobs' do expect(GoogleSyncDataWorker).to receive(:perform_async).with(first_google_integration_with_email.id, 'email') expect(GoogleSyncDataWorker).to receive(:perform_async).with(second_google_integration_with_email.id, 'email') expect(GoogleSyncDataWorker).to_not receive(:perform_async).with(google_integration_without_email.id, 'email') GoogleEmailSyncEnqueuerWorker.new.perform end end
chuckmersereau/api_practice
spec/services/donation_imports/siebel_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe DonationImports::Siebel do let(:organization_account) { create(:organization_account) } let(:organization) { organization_account.organization } let(:mock_profile_importer) { double(:mock_profile_importer) } let(:mock_donor_importer) { double(:mock_donor_importer) } let(:mock_donation_importer) { double(:mock_donation_importer) } let(:date_from) { 2.years.ago } subject { described_class.new(organization_account) } describe '#import_all' do it 'imports profiles, donors and donations' do expect(described_class::ProfileImporter).to receive(:new).with(subject).and_return(mock_profile_importer) expect(mock_profile_importer).to receive(:import_profiles) expect(described_class::DonorImporter).to receive(:new).with(subject).and_return(mock_donor_importer) expect(mock_donor_importer).to receive(:import_donors) expect(described_class::DonationImporter).to receive(:new).with(subject).and_return(mock_donation_importer) expect(mock_donation_importer).to receive(:import_donations).with(start_date: date_from) subject.import_all(date_from) end end end
chuckmersereau/api_practice
app/services/reports/year_donations.rb
class Reports::YearDonations < ActiveModelSerializers::Model attr_accessor :account_list def donor_infos received_donations.donors end def donation_infos @donations = received_donations.donations DonationReports::DonationsConverter.new(account_list: account_list, donations: @donations).convert_amounts @donations end private def received_donations scoper = ->(donations) { donations.where('donation_date >= ?', 12.months.ago.beginning_of_month) } @received_donations ||= DonationReports::ReceivedDonations.new(account_list: account_list, donations_scoper: scoper) end end
chuckmersereau/api_practice
app/models/mail_chimp_account.rb
require 'async' class MailChimpAccount < ApplicationRecord COUNT_PER_PAGE = 100 audited associated_with: :account_list, except: [:importing] belongs_to :account_list has_one :mail_chimp_appeal_list, dependent: :destroy has_many :mail_chimp_members, dependent: :destroy attr_reader :validation_error delegate :appeal_open_rate, :lists, :lists_available_for_newsletters_formatted, :lists_link, :primary_list, :primary_list_name, :validate_key, :validation_error, to: :gibbon_wrapper validates :account_list_id, :api_key, presence: true validates :api_key, format: /\A\w+-us\d+\z/ serialize :tags_details, Hash serialize :statuses_details, Hash scope :that_belong_to, -> (user) { where(account_list_id: user.account_list_ids) } PERMITTED_ATTRIBUTES = [ :api_key, :auto_log_campaigns, :created_at, :grouping_id, :overwrite, :primary_list_id, :updated_at, :updated_in_db_at, :id ].freeze def newsletter_emails newsletter_contacts_with_emails(nil).pluck('email_addresses.email') end def relevant_contacts(contact_ids = nil, force_sync = false) return contacts_with_email_addresses(contact_ids) if contact_ids && force_sync newsletter_contacts_with_emails(contact_ids) end def newsletter_contacts_with_emails(contact_ids) contacts_with_email_addresses(contact_ids) .where(send_newsletter: %w(Email Both)) .where.not(people: { optout_enewsletter: true }) end def contacts_with_email_addresses(contact_ids) contacts = account_list.contacts contacts = contacts.where(id: contact_ids) if contact_ids contacts.joins(people: :primary_email_address) .where.not(email_addresses: { historic: true }) end def email_hash(email) Digest::MD5.hexdigest(email.downcase) end def statuses_interest_ids_for_list(list_id) get_interest_attribute_for_list(group: :status, attribute: :interest_ids, list_id: list_id) end def tags_interest_ids_for_list(list_id) get_interest_attribute_for_list(group: :tag, attribute: :interest_ids, list_id: list_id) end def get_interest_attribute_for_list(group:, attribute:, list_id:) send("#{group.to_s.pluralize}_details")&.dig(list_id, attribute) end def set_interest_attribute_for_list(group:, attribute:, list_id:, value:) key = "#{group.to_s.pluralize}_details" hash = send(key) || {} hash[list_id] ||= {} hash[list_id][attribute] = value send("#{key}=", hash) end def gibbon_wrapper @gibbon_wrapper ||= MailChimp::GibbonWrapper.new(self) end end
chuckmersereau/api_practice
spec/models/donation_spec.rb
<filename>spec/models/donation_spec.rb<gh_stars>0 require 'rails_helper' describe Donation do let(:designation_account) { create(:designation_account) } let(:donation) { create(:donation, donation_date: Date.new(2015, 4, 5), designation_account: designation_account) } describe '#localized_date' do it 'is just date' do expect(donation.localized_date).to eq 'April 05, 2015' end end describe '#update_contacts' do let(:contact) { create(:contact) } let(:donor_account) { create(:donor_account, contacts: [contact]) } context 'donor_account_id is updated' do let(:donation) { create(:donation, designation_account: designation_account, donor_account: donor_account) } let(:new_contact) { create(:contact) } let(:new_donor_account) { create(:donor_account, contacts: [new_contact]) } it 'updates old donor account contacts and new donor account contacts' do allow(DonorAccount).to receive(:find).with(donor_account.id).and_return(donor_account) expect(contact).to receive(:save).once allow(donation).to receive(:contacts).and_return([new_contact]) expect(new_contact).to receive(:save).once donation.update(donor_account: new_donor_account) end end context 'donor_account_id is added' do let(:donation) { create(:donation, designation_account: designation_account, donor_account: nil) } it 'updates donor account contacts' do expect_any_instance_of(Contact).to receive(:save).once.and_call_original donation.update(donor_account: donor_account) end end end describe '#deletable' do let(:delete_donation) { donation.destroy } it 'should save a reference to the donation that was deleted' do expect { delete_donation }.to change { DeletedRecord.count }.by(1) end it 'should record the deleted objects details' do delete_donation record = DeletedRecord.find_by(deletable_type: 'Donation', deletable_id: donation.id) expect(record.deletable_type).to eq('Donation') expect(record.deletable_id).to eq(donation.id) expect(record.deleted_from_id).to eq(donation.designation_account_id) end end describe '#update_related_pledge' do let(:pledge) { create(:pledge, amount: 100.00) } let(:donation) { build(:donation, appeal: create(:appeal)) } let!(:persisted_donation) { create(:donation) } it 'calls the match service method whenever a new donation is created' do expect_any_instance_of(AccountList::PledgeMatcher).to receive(:needs_pledge?).and_return(true) expect_any_instance_of(AccountList::PledgeMatcher).to receive(:pledge).and_return(pledge) donation.save expect(pledge.donations.count).to eq(1) expect(pledge.donations).to include(donation) end it "doesn't call the match service method whenever a new donation is updated" do expect_any_instance_of(AccountList::PledgeMatcher).not_to receive(:pledge) persisted_donation.update(amount: 200.00) end it 'deletes pledge donation if appeal is removed' do expect_any_instance_of(AccountList::PledgeMatcher).to receive(:needs_pledge?).and_return(true) expect_any_instance_of(AccountList::PledgeMatcher).to receive(:pledge).and_return(pledge) donation.save expect { donation.update(appeal: nil) }.to change(PledgeDonation, :count).by(-1) end end context 'converted_amount and converted_currency' do let(:designation_account) { create(:designation_account) } let(:donation) { create(:donation, currency: 'EUR', designation_account: designation_account) } let!(:currency_rate) { create(:currency_rate, exchanged_on: donation.donation_date) } it 'returns the converted amount to designation_account currency' do expect(donation.converted_amount).to be_within(0.001).of(donation.amount / currency_rate.rate) end it 'returns the converted designation_account currency' do expect(donation.converted_currency).to eq('USD') end end describe '#add_appeal_contacts' do let(:appeal) { create(:appeal) } it 'adds a contact to the appeal if that contacts donation is added' do contact = create(:contact, account_list: appeal.account_list, appeals: [appeal]) contact.donor_accounts << donation.donor_account donation.update(appeal: appeal, appeal_amount: 1) expect(appeal.contacts.reload).to include(contact) end it "doesn't adds a contact to the appeal if that contact is in different donor account" do contact = create(:contact, account_list: appeal.account_list) contact.donor_accounts << create(:donor_account) donation.update(appeal: appeal, appeal_amount: 1) expect(appeal.contacts.reload).to_not include(contact) end it "doesn't adds a contact to the appeal if that contact is in different donor account" do contact = create(:contact, account_list: appeal.account_list, appeals: [appeal]) donor_account = create(:donor_account) contact.donor_accounts << donor_account new_donation = create(:donation, appeal: appeal, appeal_amount: 1, donor_account_id: donor_account.id) expect(new_donation.donor_account).to eq(contact.donor_accounts.first) expect(appeal.contacts.reload).to include(contact) end end context '.all_from_offline_orgs?' do it 'returns true if all donations are from offline orgs' do org = create(:organization, api_class: 'OfflineOrg') donor_account = create(:donor_account, organization: org) create(:donation, donor_account: donor_account) expect(Donation.all_from_offline_orgs?(Donation.all)).to be true end it 'returns false if any donation is from an online org' do offline_org = create(:organization, api_class: 'OfflineOrg') da_offline = create(:donor_account, organization: offline_org) create(:donation, donor_account: da_offline) online_org = create(:organization, api_class: 'Siebel') da_online = create(:donor_account, organization: online_org) create(:donation, donor_account: da_online) expect(Donation.all_from_offline_orgs?(Donation.all)).to be false end end describe 'after_destroy #reset_totals' do let!(:account_list) { create(:account_list) } let!(:donor_account) { create(:donor_account, total_donations: 0) } let!(:designation_account) { create(:designation_account).tap { |da| da.account_lists << account_list } } let!(:contact) do create(:contact, account_list: account_list, total_donations: 0).tap { |c| c.donor_accounts << donor_account } end let!(:donation_one) do create(:donation, amount: 1, donor_account: donor_account, designation_account: designation_account) end let!(:donation_two) do create(:donation, amount: 2, donor_account: donor_account, designation_account: designation_account) end let!(:donation_three) do create(:donation, amount: 3, donor_account: donor_account, designation_account: designation_account) end it 'resets the donor account total_donations' do expect(donor_account.total_donations).to eq(6) donation_one.destroy expect(donor_account.reload.total_donations).to eq(5) donation_two.destroy expect(donor_account.reload.total_donations).to eq(3) donation_three.destroy expect(donor_account.reload.total_donations).to eq(0) end it 'resets the designation account total_donations' do expect(contact.reload.total_donations).to eq(6) donation_one.destroy expect(contact.reload.total_donations).to eq(5) donation_two.destroy expect(contact.reload.total_donations).to eq(3) donation_three.destroy expect(contact.reload.total_donations).to eq(0) end end describe '#pledge' do let(:appeal) { create(:appeal) } let(:pledge1) { create(:pledge, amount: 100.00, appeal: appeal) } let(:pledge2) { create(:pledge, amount: 100.00) } let(:donation) { create(:donation, appeal: appeal) } before do pledge1.donations << donation pledge2.donations << donation end it 'returns first pledge' do expect(donation.pledge).to eq pledge1 end end end
chuckmersereau/api_practice
spec/controllers/api/v2/user/key_accounts_controller_spec.rb
require 'rails_helper' RSpec.describe Api::V2::User::KeyAccountsController, type: :controller do let(:user) { create(:user) } let(:factory_type) { :key_account } let!(:resource) { create(:key_account, person: user) } let!(:second_resource) { create(:key_account, person: user) } let(:id) { resource.id } let(:unpermitted_attributes) { nil } let(:correct_attributes) { { email: '<EMAIL>', remote_id: 200 } } let(:incorrect_attributes) { { remote_id: nil } } include_examples 'show_examples' include_examples 'update_examples' include_examples 'create_examples' include_examples 'destroy_examples' include_examples 'index_examples' end
chuckmersereau/api_practice
db/migrate/20120525132155_remove_unique_index_from_accounts.rb
class RemoveUniqueIndexFromAccounts < ActiveRecord::Migration def up remove_index :person_facebook_accounts, name: 'index_person_facebook_accounts_on_remote_id_and_authenticated' remove_index :person_google_accounts, name: 'index_person_google_accounts_on_remote_id_and_authenticated' remove_index :person_key_accounts, name: 'index_person_key_accounts_on_remote_id_and_authenticated' remove_index :person_linkedin_accounts, name: 'index_person_linkedin_accounts_on_remote_id_and_authenticated' remove_index :person_relay_accounts, name: 'index_person_relay_accounts_on_remote_id_and_authenticated' remove_index :person_twitter_accounts, name: 'index_person_twitter_accounts_on_remote_id_and_authenticated' add_index :person_relay_accounts, :remote_id add_index :person_key_accounts, :remote_id add_index :person_google_accounts, :remote_id end def down add_index :person_twitter_accounts, [:remote_id, :authenticated], unique: true add_index :person_relay_accounts, [:remote_id, :authenticated], unique: true add_index :person_linkedin_accounts, [:remote_id, :authenticated], unique: true add_index :person_key_accounts, [:remote_id, :authenticated], unique: true add_index :person_google_accounts, [:remote_id, :authenticated], unique: true add_index :person_facebook_accounts, [:remote_id, :authenticated], unique: true end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/duplicates_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > Duplicates' do include_context :json_headers doc_helper = DocumentationHelper.new(resource: [:contacts, :duplicates]) # This is the scope in how these endpoints will be organized in the # generated documentation. # # :entities should be used for "top level" resources, and the top level # resources should be used for nested resources. # # Ex: Api > v2 > Contacts - :entities would be the scope # Ex: Api > v2 > Contacts > Email Addresses - :contacts would be the scope # documentation_scope = :contacts_api_duplicates # This is required! # This is the resource's JSONAPI.org `type` attribute to be validated against. let(:resource_type) { 'duplicate_record_pairs' } # Remove this and the authorized context below if not authorizing your requests. let(:duplicate_record_pair) { create(:duplicate_contacts_pair) } let(:resource) { duplicate_record_pair } let(:account_list) { resource.account_list } let(:user) { create(:user).tap { |user| account_list.users << user } } let(:id) { resource.id } # List your expected resource keys vertically here (alphabetical please!) let(:expected_attribute_keys) do %w( created_at ignore reason updated_at updated_in_db_at ) end # List out any additional attribute keys that will be alongside # the attributes of the resources. # # Remove if not needed. let(:additional_attribute_keys) do %w( relationships ) end let(:form_data) do build_data({ ignore: true, updated_in_db_at: resource.updated_at }, relationships: relationships) end let(:relationships) do { account_list: { data: { type: 'account_lists', id: account_list.id } } } end context 'authorized user' do before { api_login(user) } get '/api/v2/contacts/duplicates' do doc_helper.insert_documentation_for(action: :index, context: self) example doc_helper.title_for(:index), document: doc_helper.document_scope do explanation doc_helper.description_for(:index) do_request check_collection_resource(1, additional_attribute_keys) expect(resource_object.keys).to match_array expected_attribute_keys expect(response_status).to eq 200 end end get '/api/v2/contacts/duplicates/:id' do doc_helper.insert_documentation_for(action: :show, context: self) example doc_helper.title_for(:show), document: doc_helper.document_scope do explanation doc_helper.description_for(:show) do_request check_resource(['relationships'], additional_attribute_keys) expect(resource_object['reason']).to eq resource.reason expect(response_status).to eq 200 end end put '/api/v2/contacts/duplicates/:id' do doc_helper.insert_documentation_for(action: :update, context: self) example doc_helper.title_for(:update), document: doc_helper.document_scope do explanation doc_helper.description_for(:update) do_request data: form_data expect(response_status).to eq(200), invalid_status_detail expect(resource_object['ignore']).to eq(true) end end end end
chuckmersereau/api_practice
spec/lib/batch_request_handler/instruments/abort_on_error_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/lib/batch_request_handler/instruments/abort_on_error_spec.rb require 'spec_helper' require 'support/batch_request_helpers' describe BatchRequestHandler::Instruments::AbortOnError do let(:successful_request) { double('success') } let(:successful_response) { Rack::Response.new([], 200).finish } let(:successful_json_response) { { status: 200 } } let(:failing_request) { double('fail') } let(:failing_response) { Rack::Response.new([], 400).finish } let(:failing_json_response) { { status: 400 } } let(:app) do lambda do |env| case env when successful_request then successful_response when failing_request then failing_response end end end let(:around_perform_requests_block) do lambda do |request_envs| request_envs.map { |env| subject.around_perform_request(env, &app) } end end it 'should only be enabled when on_error is set to ABORT' do batch_request = create_empty_batch_request_with_params(on_error: 'ABORT') expect(described_class).to be_enabled_for(batch_request) end let(:params) { {} } subject { described_class.new(params) } describe '#around_perform_requests' do let(:block) { around_perform_requests_block } context 'with all successful requests' do let(:requests) { [successful_request, successful_request] } it 'returns both requests' do responses = subject.around_perform_requests(requests, &block) expect(responses).to eq([successful_response, successful_response]) end end context 'with a failing request' do let(:requests) { [successful_request, failing_request, successful_request] } it 'returns only the requests up to and including the failing request' do responses = subject.around_perform_requests(requests, &block) expect(responses).to eq([successful_response, failing_response]) end end end describe 'around_perform_request' do context 'with a successful request' do it 'should not throw :error' do expect { subject.around_perform_request(successful_request, &app) } .to_not throw_symbol(:error) end end context 'with a failing request' do it 'should throw :error' do expect { subject.around_perform_request(failing_request, &app) } .to throw_symbol(:error) end end end describe 'around_build_response' do let(:block) do -> (_json_responses) { [200, { 'Content-Type' => 'application/json' }, ['']] } end context 'when the batch request did not abort' do let(:json_responses) { [successful_json_response] } before do subject.around_perform_requests([successful_request], &around_perform_requests_block) end it 'should return a rack response with a 200 status' do status, = subject.around_build_response(json_responses, &block) expect(status).to eq(200) end end context 'when the batch request did abort' do let(:json_responses) { [successful_json_response, failing_json_response] } before do subject.around_perform_requests([successful_request, failing_request], &around_perform_requests_block) end it 'should return a rack response with a status equal to the last response\'s status' do status, = subject.around_build_response(json_responses, &block) expect(status).to eq(json_responses.last[:status]) end end end end
chuckmersereau/api_practice
app/workers/employee_csv_group_import_worker.rb
<reponame>chuckmersereau/api_practice<filename>app/workers/employee_csv_group_import_worker.rb<gh_stars>0 class EmployeeCsvGroupImportWorker include Sidekiq::Worker sidekiq_options unique: :until_executed, queue: :api_import, retry: 0 def perform(path, from, to) importer = EmployeeCsvImporter.new(path: path) importer.converted_data[from...to].each do |user_for_import| EmployeeCsvImportWorker.perform_in(1.second, user_for_import.cas_attributes) end end end
chuckmersereau/api_practice
spec/controllers/api/v2/reports/expected_monthly_totals_controller_spec.rb
require 'rails_helper' RSpec.describe Api::V2::Reports::ExpectedMonthlyTotalsController, type: :controller do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:resource) do Reports::ExpectedMonthlyTotals.new(account_list: account_list) end let(:parent_param) do { filter: { account_list_id: account_list.id } } end let(:given_reference_key) { 'expected_donations' } include_examples 'show_examples', except: [:sparse_fieldsets] describe 'Filters' do let!(:donor_account_1) { create(:donor_account) } let!(:designation_account_1) { create(:designation_account) } let!(:contact_1) { create(:contact, account_list: account_list) } let!(:donations_1) do create_list(:donation, 2, donor_account: donor_account_1, designation_account: designation_account_1, amount: 50.00, donation_date: Date.today) end let!(:donor_account_2) { create(:donor_account) } let!(:designation_account_2) { create(:designation_account) } let!(:contact_2) { create(:contact, account_list: account_list) } let!(:donations_2) do create_list(:donation, 2, donor_account: donor_account_2, designation_account: designation_account_2, amount: 100.00, donation_date: 2.months.ago) end let!(:donor_account_3) { create(:donor_account) } let!(:designation_account_3) { create(:designation_account) } let!(:contact_3) { create(:contact, account_list: account_list) } let!(:donations_3) do create_list(:donation, 2, donor_account: donor_account_3, designation_account: designation_account_3, amount: 150.00, donation_date: Date.today) end before do account_list.designation_accounts << designation_account_1 account_list.designation_accounts << designation_account_2 account_list.designation_accounts << designation_account_3 contact_1.donor_accounts << donor_account_1 contact_2.donor_accounts << donor_account_2 contact_3.donor_accounts << donor_account_3 api_login(user) end it 'allows a user to request all data' do get :show, account_list_id: account_list.id expect(response_json['data']['attributes']['expected_donations'].map { |c| c['contact_id'] }.uniq).to( contain_exactly(contact_1.id, contact_2.id, contact_3.id) ) end it 'allows a user to filter by designation_account_id' do get :show, account_list_id: account_list.id, filter: { designation_account_id: designation_account_1.id } expect(response_json['data']['attributes']['expected_donations'].map { |c| c['contact_id'] }.uniq).to( contain_exactly(contact_1.id) ) end it 'allows a user to filter by multiple designation_account_ids' do get :show, account_list_id: account_list.id, filter: { designation_account_id: "#{designation_account_1.id},#{designation_account_2.id}" } expect(response_json['data']['attributes']['expected_donations'].map { |c| c['contact_id'] }.uniq).to( contain_exactly(contact_1.id, contact_2.id) ) end it 'allows a user to filter by donor_account_id' do get :show, account_list_id: account_list.id, filter: { donor_account_id: donor_account_2.id } expect(response_json['data']['attributes']['expected_donations'].map { |c| c['contact_id'] }.uniq).to( contain_exactly(contact_2.id) ) end it 'allows a user to filter by multiple donor_account_ids' do get :show, account_list_id: account_list.id, filter: { donor_account_id: "#{donor_account_1.id},#{donor_account_2.id}" } expect(response_json['data']['attributes']['expected_donations'].map { |c| c['contact_id'] }.uniq).to( contain_exactly(contact_1.id, contact_2.id) ) end end end
chuckmersereau/api_practice
spec/serializers/background_batch/request_serializer_spec.rb
require 'rails_helper' RSpec.describe BackgroundBatch::RequestSerializer, type: :serializer do end
chuckmersereau/api_practice
app/controllers/api/v2/account_lists/analytics_controller.rb
<filename>app/controllers/api/v2/account_lists/analytics_controller.rb<gh_stars>0 class Api::V2::AccountLists::AnalyticsController < Api::V2Controller def show load_analytics authorize_analytics render_analytics end protected def permit_coach? true end private def authorize_analytics authorize(load_account_list, :show?) end def load_analytics @analytics ||= AccountList::Analytics.new(analytics_params) end def load_account_list @account_list ||= account_lists.find(params[:account_list_id]) end def analytics_params { start_date: (filter_params[:date_range].try(:first) || 1.month.ago), end_date: (filter_params[:date_range].try(:last) || Time.current) }.merge(account_list: load_account_list) end def permitted_filters [:date_range] end def render_analytics render json: @analytics, fields: field_params, include: include_params end end
chuckmersereau/api_practice
app/models/notification_type/thank_partner_once_per_year.rb
<filename>app/models/notification_type/thank_partner_once_per_year.rb<gh_stars>0 class NotificationType::ThankPartnerOncePerYear < NotificationType::TaskIfPeriodPast def check_contacts_filter(contacts) super(contacts).where('pledge_frequency < ?', LongTimeFrameGift::LONG_TIME_FRAME_PLEDGE_FREQUENCY) end def task_description_template(_notification = nil) _('%{contact_name} have not had a thank you note logged in the past year. Send them a Thank You note.') end def task_activity_type 'Thank' end end
chuckmersereau/api_practice
app/policies/user/coach_policy.rb
class User::CoachPolicy < ApplicationPolicy def destroy? coaching_one_of_user_account_lists? end def show? resource_owner? || coaching_one_of_user_account_lists? end private def coaching_one_of_user_account_lists? (user.account_lists.ids & resource.coaching_account_lists.ids).present? end def resource_owner? user == resource end end
chuckmersereau/api_practice
app/services/donation_reports/received_donations.rb
<reponame>chuckmersereau/api_practice module DonationReports class ReceivedDonations def initialize(account_list:, donations_scoper:) @account_list = account_list @donations_scoper = donations_scoper end def donations load_donors_and_donations @donations end def donors load_donors_and_donations @donors end private def donations_and_contacts Contact::DonationsEagerLoader.new( account_list: @account_list, donations_scoper: @donations_scoper ).donations_and_contacts end def donor_and_donation_info donations, contacts = donations_and_contacts donations_info = donations.map do |donation| DonationReports::DonationInfo.from_donation(donation, @account_list.salary_currency) end contacts_info = contacts.map do |contact| DonationReports::DonorInfo.from_contact(contact) end [donations_info, contacts_info] end def load_donors_and_donations return if @donations && @donors @donations, @donors = donor_and_donation_info end end end
chuckmersereau/api_practice
app/services/donations_chart/monthly_totaler.rb
<gh_stars>0 class DonationsChart::MonthlyTotaler def initialize(account_list) @account_list = account_list end def months_back @months_back ||= calc_months_back end def totals currencies.map(&method(:totals_for_currency)) .sort_by { |totals| totals[:total_converted] } .reverse end private attr_reader :account_list def calc_months_back first_donation = account_list.donations.select('donation_date').last return 1 unless first_donation first_donation_days_ago = Date.today.end_of_month - first_donation.donation_date approx_months = (first_donation_days_ago.to_f / 30).floor [[approx_months, 12].min, 1].max end def recent_donations account_list.donations.where('donation_date > ?', months_back.months.ago.utc.beginning_of_month) end def currencies # It is possible for some donations to have a `nil` value for their # currency, but that that is a rarer case and something we should fix # earlier in the process than here. What we do to handle that case is to # just ignore donations with no currencies to prevent an invalid call on # `nil` in the chart itself. @currencies ||= recent_donations.currencies.select(&:present?) end def totals_for_currency(currency) month_totals = currency_month_totals(currency) { currency: currency, total_amount: month_totals.map { |t| t[:amount] }.sum, total_converted: month_totals.map { |t| t[:converted] }.sum, month_totals: month_totals } end def currency_month_totals(currency) months_back.downto(0).map do |month_index| start_date = month_index.months.ago.utc.beginning_of_month end_date = start_date.end_of_month amount = account_list.donations .where(currency: currency) .where(donation_date: start_date..end_date) .sum(:amount) mid_month = Date.new(start_date.year, start_date.month, 15) converted = CurrencyRate.convert_on_date(amount: amount, from: currency, to: total_currency, date: mid_month) { amount: amount, converted: converted } end end def total_currency account_list.salary_currency_or_default end end
chuckmersereau/api_practice
spec/controllers/api/v2/contacts/referrers_controller_spec.rb
<filename>spec/controllers/api/v2/contacts/referrers_controller_spec.rb require 'rails_helper' RSpec.describe Api::V2::Contacts::ReferrersController, type: :controller do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:factory_type) { :contact } let(:contact) { create(:contact, account_list: account_list) } let(:parent_param) { { contact_id: contact.id } } let!(:resource) do create(:contact_with_person, account_list: account_list).tap do |referrer| contact.contacts_that_referred_me << referrer end end let!(:second_resource) do create(:contact_with_person, account_list: account_list).tap do |referrer| contact.contacts_that_referred_me << referrer end end let(:correct_attributes) do attributes_for(:contact, account_list: account_list) end include_examples 'index_examples' end
chuckmersereau/api_practice
spec/controllers/api/v2/user/authenticates_controller_spec.rb
require 'rails_helper' RSpec.describe Api::V2::User::AuthenticatesController, type: :controller do let!(:user) { create(:user) } let(:response_body) { JSON.parse(response.body) } let(:valid_cas_ticket) { 'ST-314971-9fjrd0HfOINCehJ5TKXX-cas2a' } let(:service) { 'http://test.host/api/v2/user/authenticate' } let(:request_data) do { id: nil, type: 'authenticate', attributes: { cas_ticket: valid_cas_ticket } } end describe '#create' do context 'valid cas ticket' do let!(:validator) do CasTicketValidatorService.new(ticket: valid_cas_ticket, service: service) end before do stub_request( :get, "#{ENV['CAS_BASE_URL']}/p3/serviceValidate?service=#{service}&ticket=#{valid_cas_ticket}" ).to_return( status: 200, body: File.open( Rails.root.join('spec', 'fixtures', 'cas', 'successful_ticket_validation_response_body.xml') ).read ) user.key_accounts << create(:key_account, relay_remote_id: 'B163530-7372-551R-KO83-1FR05534129F') allow(UserFromCasService) .to receive(:find_or_create) .with(validator.attributes) .and_return(user) travel_to(Time.now.getlocal) end after { travel_back } subject { post :create, data: request_data } it 'returns success' do subject expect(response.status).to eq(200) end it 'responds with a valid json web token' do subject json_web_token = response_body['data']['attributes']['json_web_token'] decoded_web_token = JsonWebToken.decode(json_web_token) expect(json_web_token).to be_present expect(User.find_by(id: decoded_web_token['user_id']).id).to eq user.id expect(decoded_web_token['exp']).to eq 30.days.from_now.utc.to_i end it 'updates the user tracked fields' do user.update_columns(current_sign_in_at: 1.year.ago, last_sign_in_at: 2.years.ago, sign_in_count: 2) expect { subject }.to change { user.current_sign_in_at }.to(Time.now.utc) expect(user.last_sign_in_at).to eq(1.year.ago) expect(user.sign_in_count).to eq(3) end end context 'invalid ticket' do before do user.key_accounts << create(:key_account, relay_remote_id: 'B163530-7372-551R-KO83-1FR05534129F') stub_request( :get, "#{ENV['CAS_BASE_URL']}/p3/serviceValidate?"\ "service=http://test.host/api/v2/user/authenticate&ticket=#{valid_cas_ticket}" ).to_return( status: 200, body: File.open( Rails.root.join('spec', 'fixtures', 'cas', 'invalid_ticket_validation_response_body.xml') ).read ) post :create, data: request_data end it 'returns unauthorized' do expect(response.status).to eq(401) end it 'returns error details in the json body' do expect(response_body['data']).to be_nil expect(response_body['errors'].size).to eq 1 expect(response_body['errors'].first['status']).to eq '401' expect(response_body['errors'].first['detail']).to eq( "INVALID_TICKET: Ticket '#{valid_cas_ticket}' not recognized" ) end end context 'missing ticket' do before do post :create end it 'returns bad request' do expect(response.status).to eq(400) end it 'returns error details in the json body' do expect(response_body['data']).to be_nil expect(response_body['errors'].size).to eq 1 expect(response_body['errors'].first['status']).to eq '400' expect(response_body['errors'].first['detail']).to eq( 'Expected a cas_ticket to be provided in the attributes' ) end end end end
chuckmersereau/api_practice
spec/factories/company_partnerships.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 FactoryBot.define do factory :company_partnership do account_list nil company nil end end
chuckmersereau/api_practice
db/migrate/20120424130756_add_total_donations_and_last_donation_date_to_contact.rb
class AddTotalDonationsAndLastDonationDateToContact < ActiveRecord::Migration def change add_column :donor_accounts, :total_donations, :decimal, precision: 10, scale: 2 add_column :donor_accounts, :last_donation_date, :date add_column :donor_accounts, :first_donation_date, :date add_index :donor_accounts, :total_donations add_index :donor_accounts, :last_donation_date add_column :contacts, :total_donations, :decimal, precision: 10, scale: 2 add_column :contacts, :last_donation_date, :date add_column :contacts, :first_donation_date, :date add_index :contacts, :total_donations add_index :contacts, :last_donation_date # update donor_accounts da set da.total_donations = (select sum(amount) from donations d where d.donor_account_id = da.id) # update donor_accounts da set da.last_donation_date = (select max(donation_date) from donations d where d.donor_account_id = da.id) # update donor_accounts da set da.first_donation_date = (select min(donation_date) from donations d where d.donor_account_id = da.id) AccountList.all.each do |a| a.contacts.each do |c| if c.donor_account_id designation_account_ids = a.designation_accounts.pluck('designation_accounts.id') donations = Donation.where(donor_account_id: c.donor_account_id, designation_account_id: designation_account_ids) c.update_column(:total_donations, donations.sum(:amount)) c.update_column(:last_donation_date, donations.maximum(:donation_date)) c.update_column(:first_donation_date, donations.minimum(:donation_date)) end end end end end
chuckmersereau/api_practice
spec/models/designation_profile_account_spec.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 require 'rails_helper' describe DesignationProfileAccount do end
chuckmersereau/api_practice
lib/tasks/mailchimp.rake
<reponame>chuckmersereau/api_practice<filename>lib/tasks/mailchimp.rake namespace :mailchimp do desc 'Sync MPDX users to mailchimp list' task sync: :environment do MailChimpSyncWorker.new.perform end end
chuckmersereau/api_practice
spec/controllers/api/v2/user/google_accounts/google_integrations_controller_spec.rb
require 'rails_helper' RSpec.describe Api::V2::User::GoogleAccounts::GoogleIntegrationsController, type: :controller do before do allow_any_instance_of(GoogleIntegration).to receive(:calendars).and_return([]) end let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:google_account) { create(:google_account, person: user) } let(:factory_type) do :google_integration end let!(:resource) do create(:google_integration, account_list: account_list, google_account: google_account) end let!(:second_resource) do create(:google_integration, account_list: account_list, google_account: google_account, created_at: 1.hour.from_now) end let(:id) { resource.id } let(:parent_param) { { google_account_id: google_account.id } } before do allow_any_instance_of(Person::GoogleAccount).to receive(:contact_groups).and_return( [ Person::GoogleAccount::ContactGroup.new( id: 'contact_group_id_0', title: 'System Group: My Family', created_at: Date.today, updated_at: Date.today ) ] ) end # This is required! let(:correct_attributes) do { calendar_id: '<EMAIL>', calendar_name: 'test123', calendar_integration: true, calendar_integrations: [], contacts_integration: true, email_integration: true } end let(:unpermitted_attributes) do # A hash of attributes that include unpermitted attributes for the current user to update # Example: { subject: 'test subject', start_at: Time.now, account_list_id: create(:account_list).id } } # -- # If there aren't attributes that are unpermitted, # you need to specifically return `nil` end let(:incorrect_attributes) do nil end include_examples 'index_examples' include_examples 'show_examples' include_examples 'create_examples' include_examples 'update_examples' include_examples 'destroy_examples' describe 'account_list_id filter' do let!(:account_list_two) { create(:account_list).tap { |account_list| user.account_lists << account_list } } let!(:google_integration_two) do create(:google_integration, account_list: account_list_two, google_account: google_account, created_at: 1.hour.ago) end before do expect(user.google_integrations.pluck(:account_list_id).uniq.size).to eq(2) end it 'filters by account_list_id' do api_login(user) get :index, parent_param_if_needed.merge(filter: { account_list_id: account_list_two.id }) expect(JSON.parse(response.body)['data'].map { |hash| hash['id'] }).to eq([google_integration_two.id]) end it 'does not filter by account_list_id' do api_login(user) get :index, parent_param_if_needed.except(:filter) expect(JSON.parse(response.body)['data'].map { |hash| hash['id'] }).to( eq(user.google_integrations.order(:created_at).map(&:id)) ) end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/account_lists/users_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Account Lists > Users' do include_context :json_headers documentation_scope = :account_lists_api_users let(:resource_type) { 'users' } let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:users) { create_list(:user, 2) } let(:user2) { users.last } let(:id) { user2.id } let(:original_user_id) { user.id } let(:resource_attributes) do %w( created_at first_name last_name updated_at updated_in_db_at ) end before do account_list.users += users end context 'authorized user' do before { api_login(user) } get '/api/v2/account_lists/:account_list_id/users' do example 'User [LIST]', document: documentation_scope do explanation 'List of Users associated to the Account List' do_request check_collection_resource(3, []) expect(response_status).to eq 200 end end get '/api/v2/account_lists/:account_list_id/users/:id' do with_options scope: [:data, :attributes] do response_field 'first_name', 'First name', type: 'String' response_field 'last_name', 'Last name', type: 'String' response_field 'created_at', 'Created At', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end example 'User [GET]', document: documentation_scope do explanation 'The Account List User with the given ID' do_request check_resource([]) expect(resource_object['first_name']).to eq user2.first_name expect(resource_object['last_name']).to eq user2.last_name expect(response_status).to eq 200 end end delete '/api/v2/account_lists/:account_list_id/users/:id' do example 'User [DELETE]', document: documentation_scope do explanation 'Destroy the Account List User with the given ID' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
app/policies/notification_preference_policy.rb
class NotificationPreferencePolicy < ApplicationPolicy def initialize(context, resource) @resource = resource @user = context.user end private def resource_owner? resource.user == user && user.account_lists.include?(resource.account_list) end end
chuckmersereau/api_practice
spec/serializers/donor_account_serializer_spec.rb
require 'rails_helper' describe DonorAccountSerializer do let(:account_list) { create(:account_list) } let(:contact_one) { create(:contact) } let(:contact_two) { create(:contact, account_list: account_list) } let(:donor_account) { create(:donor_account, contacts: [contact_one, contact_two]) } let(:serializer) { described_class.new(donor_account) } let(:scoped_serializer) { described_class.new(donor_account, scope: { account_list: account_list }) } describe '#contacts' do context 'account list' do it 'only returns contacts associated to a specific account_list' do expect(scoped_serializer.contacts).to eq([contact_two]) end end context 'no account list' do it 'returns empty array' do expect(serializer.contacts).to eq([]) end end end describe '#display_name' do context 'donor_account has name and number' do let(:donor_account) { create(:donor_account, name: 'Name', account_number: 'Number') } it 'returns donor_account name (number)' do expect(serializer.display_name).to eq 'Name (Number)' end end context 'donor_account has name with number and number' do let(:donor_account) { create(:donor_account, name: '<NAME>', account_number: 'Number') } it 'returns donor_account name' do expect(serializer.display_name).to eq 'Name Number' end end context 'donor_account has no name' do let(:donor_account) { create(:donor_account, name: nil, account_number: 'Number') } it 'returns donor_account number' do expect(serializer.display_name).to eq 'Number' end end context 'donor_account has associated contact' do it 'returns contact name (number)' do expect(scoped_serializer.display_name).to eq "#{contact_two.name} (#{donor_account.account_number})" end end end describe '#name' do context 'donor_account has name and number' do let(:donor_account) { create(:donor_account, name: 'Name', account_number: 'Number') } it 'returns donor_account name (number)' do expect(serializer.send(:name)).to eq 'Name' end end context 'donor_account has no name' do let(:donor_account) { create(:donor_account, name: nil, account_number: 'Number') } it 'returns nil' do expect(serializer.send(:name)).to be_nil end end end end
chuckmersereau/api_practice
app/controllers/api/v2/user/key_accounts_controller.rb
<gh_stars>0 class Api::V2::User::KeyAccountsController < Api::V2Controller def index load_key_accounts render json: @key_accounts.preload_valid_associations(include_associations), meta: meta_hash(@key_accounts), include: include_params, fields: field_params end def show load_key_account authorize_key_account render_key_account end def create persist_key_account end def update load_key_account authorize_key_account persist_key_account end def destroy load_key_account authorize_key_account destroy_key_account end private def destroy_key_account @key_account.destroy head :no_content end def load_key_accounts @key_accounts = key_account_scope.where(filter_params) .reorder(sorting_param) .order(default_sort_param) .page(page_number_param) .per(per_page_param) end def load_key_account @key_account ||= Person::KeyAccount.find(params[:id]) end def render_key_account render json: @key_account, status: success_status, include: include_params, fields: field_params end def persist_key_account build_key_account authorize_key_account if save_key_account render_key_account else render_with_resource_errors(@key_account) end end def build_key_account @key_account ||= key_account_scope.build @key_account.assign_attributes(key_account_params) end def save_key_account @key_account.save(context: persistence_context) end def key_account_params params.require(:key_account).permit(Person::KeyAccount::PERMITTED_ATTRIBUTES) end def authorize_key_account authorize @key_account end def key_account_scope load_user.key_accounts end def load_user @user ||= current_user end def permited_filters [] end def default_sort_param Person::KeyAccount.arel_table[:created_at].asc end end
chuckmersereau/api_practice
spec/services/mail_chimp/connection_handler_spec.rb
require 'rails_helper' RSpec.describe MailChimp::ConnectionHandler do let(:mail_chimp_account) { create(:mail_chimp_account, primary_list_id: 'List1', active: true) } subject { described_class.new(mail_chimp_account) } context '#call_mail_chimp' do let(:status_code) { 400 } let(:error_message) { 'Random Message' } let(:error) { Gibbon::MailChimpError.new(error_message, status_code: status_code, detail: error_message) } let(:mail_chimp_syncer) { MailChimp::Syncer.new(mail_chimp_account) } context 'API key disabled' do context '"API Key Disabled" message' do let(:error_message) { 'API Key Disabled' } it 'sets the mail chimp account to inactive and sends an email' do raise_error_on_two_way_sync expect_invalid_mailchimp_key_email expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to change { mail_chimp_account.reload.active } end end context '"code 104" message' do let(:error_message) { 'code 104' } it 'sets the mail chimp account to inactive and sends an email' do raise_error_on_two_way_sync expect_invalid_mailchimp_key_email expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to change { mail_chimp_account.reload.active } end end context 'Deactivated account' do let(:error_message) { 'This account has been deactivated.' } it 'sets the mail chimp account to inactive and sends an email' do raise_error_on_two_way_sync expect_invalid_mailchimp_key_email expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to change { mail_chimp_account.reload.active } end end end context 'Invalid merge fields' do let(:error_message) { 'Your merge fields were invalid.' } it 'sets the mail chimp account primary_list_id to nil and sends an email' do raise_error_on_two_way_sync expect_email(:mailchimp_required_merge_field) expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to change { mail_chimp_account.reload.primary_list_id } end end context 'Invalid mail chimp list' do let(:error_message) { 'code 200' } it 'removes the primary_list_id from the mail chimp account' do raise_error_on_two_way_sync expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to change { mail_chimp_account.reload.primary_list_id }.to(nil) end end context 'Resource Not Found' do let(:error_message) { 'The requested resource could not be found.' } it 'removes the primary_list_id from the mail chimp account' do raise_error_on_two_way_sync lists_url = 'https://us4.api.mailchimp.com/3.0/lists?count=100' stub_request(:get, lists_url).to_return(body: { lists: [] }.to_json) expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to change { mail_chimp_account.reload.primary_list_id }.to(nil) end end context 'Invalid email' do let(:error_message) { 'looks fake or invalid, please enter a real email' } it 'ignores the error silently' do raise_error_on_two_way_sync expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to_not raise_error end end context 'Email already subscribed' do let(:error_message) { 'code 214' } it 'ignores the error silently' do raise_error_on_two_way_sync expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to_not raise_error end end context 'Mail Chimp Server Errors' do context 'Server temporarily unavailable' do let(:status_code) { '503' } it 'raises an error to silently retry job' do raise_error_on_two_way_sync expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to raise_error(LowerRetryWorker::RetryJobButNoRollbarError) end end context 'Number of connections limit reached' do let(:status_code) { '429' } it 'raises an error to silently retry job' do raise_error_on_two_way_sync expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to raise_error(LowerRetryWorker::RetryJobButNoRollbarError) end end context 'All other cases' do it 'raises the error' do raise_error_on_two_way_sync expect do subject.call_mail_chimp(mail_chimp_syncer, :two_way_sync_with_primary_list) end.to raise_error(error) end end end def expect_invalid_mailchimp_key_email expect_email(:invalid_mailchimp_key) end def raise_error_on_two_way_sync expect(mail_chimp_syncer).to receive(:two_way_sync_with_primary_list!).and_raise(error) end def expect_email(mailer_method) delayed = double expect(AccountMailer).to receive(:delay).and_return(delayed) expect(delayed).to receive(mailer_method) end end end
chuckmersereau/api_practice
lib/batch_request_handler/instrument.rb
<gh_stars>0 module BatchRequestHandler # The Instrument class is used to add features or concerns to the # BatchRequest. It provides three life-cycle hooks that you may use to alter # or inspect the handling of the batch request. # # There is a class method, `enabled_for?`, which takes a BatchRequest as an # object and returns true or false if the instrument should be active for that # batch request. # # If the instrument does match the current BatchRequest, the instrument will # be instantiated with the params from the BatchRequest, and added to the # BatchRequest's list of instruments. # # While the BatchRequest is processing, it will call three different # life-cycle methods on the instrument objects it contains. Each life-cycle # method will receive some arguments and a block. The block is the next # instrument's same life-cycle method, or in the case of the final instrument, # the actual BatchRequest's life-cycle method. The life-cycle methods have the # important responsibility of passing along the arguments it was given, to the # next block. They also have the responsibility of returning a certain value. # The value they must return is the result of calling the block with the # necessary arguments. # # The power of the instrument comes from being able to modify the arguments # given to it, before it passes them along to the block. And likewise, being # able to make changes to the result of calling the block, and returning it's # own changes instead. # # Each life-cycle method has been documented with the arguments it receives, # what the block expects to be called with, what the block returns, and what # the method is supposed to return. # # Also note that instead of needing to explicitly define the block in the list # of arguments, we can simply use `yield` passing it the required arguments, # and that will be the same as calling the block with those arguments. class Instrument # Arguments: # batch_request - the current BatchRequest object # Should return: # a boolean, representing whether or not to use this instrument for the # given batch request def self.enabled_for?(_batch_request) true end # Arguments: # params - the params (all key => value pairs sent in the json body of the # batch request except for `requests`) def initialize(_params) end # Arguments: # requests - the array of request objects from the batch json payload # block - the given block expects to be called with the requests. When # called with an array of requests, it will return an array of # Rack responses # Should return: # an array of Rack response objects def around_perform_requests(requests) yield requests end # Arguments: # env - the environment that will be passed down the middleware to # perform the request. The environment may be mutated # block - the given block expects to be called with the environment. # Calling the block with the environment will continue down the # middleware chain and will return a Rack response object # Should return: # a Rack response object def around_perform_request(env) yield env end # Arguments: # json_responses - an array of responses that have been formatted into a # Hash for JSON serialization # block - the given block expects to be called with an array of # Hash formatted responses. It returns a Rack response # which will be used as the response for the batch request # Should return: # a Rack response object def around_build_response(json_responses) yield json_responses end end end
chuckmersereau/api_practice
app/controllers/api/v2/account_lists/pledges_controller.rb
class Api::V2::AccountLists::PledgesController < Api::V2Controller def index authorize_pledges load_pledges render_pledges end def show load_pledge authorize_pledge render_pledge end def create persist_pledge end def update load_pledge authorize_pledge persist_pledge end def destroy load_pledge authorize_pledge destroy_pledge end protected def permit_coach? %w(index show).include? params[:action] end private def coach? !load_account_list.users.where(id: current_user).exists? && load_account_list.coaches.where(id: current_user).exists? end def pledge_params params .require(:pledge) .permit(pledge_attributes) end def pledge_attributes Pledge::PERMITTED_ATTRIBUTES end def pledge_scope scope = load_account_list.pledges if coach? scope = scope.where('expected_date < ?', Date.today) .where(appeal_id: load_account_list.primary_appeal_id, status: :not_received) end scope end def authorize_pledge authorize @pledge end def authorize_pledges authorize load_account_list, :show? end def build_pledge @pledge ||= pledge_scope.build @pledge.assign_attributes(pledge_params) end def destroy_pledge @pledge.destroy head :no_content end def load_pledge @pledge ||= Pledge.find(params[:id]) end def load_account_list @account_list ||= AccountList.find(params[:account_list_id]) end def load_pledges @pledges = filter_pledges.joins(sorting_join) .reorder(sorting_param) .page(page_number_param) .per(per_page_param) end def filter_pledges filters = if coach? # only allow coach to filter by contact_id filter_params.slice(:contact_id) else filter_params end pledge_scope.where(filters) end def permitted_filters [:contact_id, :appeal_id, :status] end def persist_pledge build_pledge authorize_pledge if save_pledge render_pledge else render_with_resource_errors(@pledge) end end def permitted_sorting_params %w(amount expected_date contact.name) end def render_pledges options = base_render_options.merge(json: @pledges.preload_valid_associations(include_associations), meta: meta_hash(@pledges)) options[:each_serializer] = Coaching::PledgeSerializer if coach? render options end def render_pledge options = base_render_options.merge(json: @pledge, status: success_status) options[:serializer] = Coaching::PledgeSerializer if coach? render options end def base_render_options { include: include_params, fields: field_params } end def save_pledge @pledge.save(context: persistence_context) end end
chuckmersereau/api_practice
spec/models/currency_rate_spec.rb
require 'rails_helper' describe CurrencyRate do before { CurrencyRate.clear_rate_cache } context '.latest_for' do it 'returns the latest exchange rate for currency' do create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 1, 1), rate: 0.8) create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 2, 1), rate: 0.7) expect(CurrencyRate.latest_for('EUR')).to eq 0.7 end it 'logs a missing rate exception to Rollbar and returns 1.0 if rate missing' do expect(Rollbar).to receive(:info) do |error| expect(error).to be_a(CurrencyRate::RateNotFoundError) end expect(CurrencyRate.latest_for('EUR')).to eq 1.0 end it 'returns 1.0 and does not log a Rollbar exception for nil currency' do expect(Rollbar).to_not receive(:error) expect(CurrencyRate.latest_for(nil)).to eq 1.0 end it 'returns 1.0 for USS despite no db entry' do expect(CurrencyRate.exists?(code: 'USS')).to be false expect(Rollbar).to_not receive(:error) expect(CurrencyRate.latest_for('USS')).to eq 1.0 end end context '.latest_for_pair' do it 'retrieves composite rate between currencies' do create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 4, 1), rate: 0.88) create(:currency_rate, code: 'GBP', exchanged_on: Date.new(2016, 4, 1), rate: 0.69) expect(CurrencyRate.latest_for_pair(from: 'EUR', to: 'GBP')) .to be_within(0.01).of(0.78) end it 'returns 1.0 if the currencies are the same' do create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 4, 1), rate: 0.88) expect(CurrencyRate.latest_for_pair(from: 'EUR', to: 'EUR')).to eq 1.0 end end context '.convert_with_latest!' do it 'converts from one currency to other using latest rates' do create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 4, 1), rate: 0.88) create(:currency_rate, code: 'GBP', exchanged_on: Date.new(2016, 4, 1), rate: 0.69) expect(CurrencyRate.convert_with_latest!(amount: 10.0, from: 'EUR', to: 'GBP')) .to be_within(0.1).of(7.8) end end context '.convert_with_latest' do it 'returns 0 in the event of an error' do allow(CurrencyRate).to receive(:convert_with_latest!).and_raise(CurrencyRate::RateNotFoundError) expect(CurrencyRate.convert_with_latest(amount: 10.0, from: 'EUR', to: 'GBP')) .to eq 0 end end context '.convert_on_date' do it 'converts from one currency to other using latest rates' do create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 4, 1), rate: 0.88) create(:currency_rate, code: 'GBP', exchanged_on: Date.new(2016, 4, 1), rate: 0.69) create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 4, 2), rate: 0.5) create(:currency_rate, code: 'GBP', exchanged_on: Date.new(2016, 4, 2), rate: 0.5) expect(CurrencyRate.convert_on_date( amount: 10, from: 'EUR', to: 'GBP', date: Date.new(2016, 4, 1) )) .to be_within(0.1).of(7.8) end it 'uses the oldest currency rate after that date for rates with no dates' do create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 4, 1), rate: 0.88) create(:currency_rate, code: 'GBP', exchanged_on: Date.new(2016, 4, 1), rate: 0.69) expect(CurrencyRate.convert_on_date( amount: 10, from: 'EUR', to: 'GBP', date: Date.new(2016, 3, 1) )) .to be_within(0.1).of(7.8) end it 'still works if you cache the currency rate date range first' do create(:currency_rate, code: 'EUR', exchanged_on: Date.new(2016, 4, 1), rate: 0.88) create(:currency_rate, code: 'GBP', exchanged_on: Date.new(2016, 4, 1), rate: 0.69) CurrencyRate.cache_rates_for_dates( currency_code: 'EUR', from_date: Date.new(2016, 3, 30), to_date: Date.new(2016, 4, 2) ) expect(CurrencyRate.convert_on_date( amount: 10, from: 'EUR', to: 'GBP', date: Date.new(2016, 4, 1) )) .to be_within(0.1).of(7.8) end end end
chuckmersereau/api_practice
spec/factories/admin_reset_logs.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 FactoryBot.define do factory :admin_reset_log, class: 'Admin::ResetLog' do admin_resetting_id { SecureRandom.uuid } resetted_user_id { SecureRandom.uuid } reason 'MyString' end end
chuckmersereau/api_practice
app/serializers/appeal_serializer.rb
<filename>app/serializers/appeal_serializer.rb class AppealSerializer < ApplicationSerializer attributes :amount, :currencies, :description, :end_date, :name, :pledges_amount_not_received_not_processed, :pledges_amount_processed, :pledges_amount_received_not_processed, :pledges_amount_total, :total_currency belongs_to :account_list has_many :contacts has_many :donations def currencies object.donations.currencies end def total_currency object.account_list.salary_currency_or_default end end
chuckmersereau/api_practice
spec/acceptance/api/v2/tasks/tags_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Tasks > Tags' do include_context :json_headers documentation_scope = :tasks_api_tags let(:resource_type) { 'tags' } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:task) { create(:task, account_list: account_list) } let(:task_id) { task.id } let(:tag_name) { 'new_tag' } let(:new_tag_params) { { name: tag_name } } let(:form_data) { build_data(new_tag_params) } before { api_login(user) } get '/api/v2/tasks/tags' do let!(:account_list_two) { create(:account_list) } let!(:task_one) { create(:task, account_list: account_list, tag_list: [tag_name]) } let!(:task_two) { create(:task, account_list: account_list_two, tag_list: [tag_name]) } before { user.account_lists << account_list_two } example 'Tag [LIST]', document: documentation_scope do explanation 'List Task Tags' do_request expect(resource_data.count).to eq 1 expect(first_or_only_item['type']).to eq 'tags' expect(resource_object.keys).to match_array(%w(name)) expect(response_status).to eq 200 end end post '/api/v2/tasks/:task_id/tags' do with_options scope: [:data, :attributes] do parameter 'name', 'Name of Tag' end example 'Tag [CREATE]', document: documentation_scope do explanation 'Create a Tag associated with the Task' do_request data: form_data expect(resource_object['new_tag']).to eq new_tag_params['new_tag'] expect(response_status).to eq 201 end end delete '/api/v2/tasks/:task_id/tags/:tag_name' do parameter 'tag_name', 'The name of the tag' parameter 'task_id', 'The Task ID of the Tag' example 'Tag [DELETE]', document: documentation_scope do explanation 'Delete the Task\'s Tag with the given name' do_request expect(response_status).to eq 204 end end end
chuckmersereau/api_practice
db/migrate/20171102140700_add_interests_details_to_mail_chimp_accounts.rb
class AddInterestsDetailsToMailChimpAccounts < ActiveRecord::Migration def change add_column :mail_chimp_accounts, :tags_details, :text add_column :mail_chimp_accounts, :statuses_details, :text end end
chuckmersereau/api_practice
spec/mailers/previews/account_mailer_preview.rb
class AccountMailerPreview < ApplicationPreview def invalid_mailchimp_key AccountMailer.invalid_mailchimp_key(account_list) end def mailchimp_required_merge_field AccountMailer.mailchimp_required_merge_field(account_list) end def prayer_letters_invalid_token AccountMailer.prayer_letters_invalid_token(account_list) end private def account_list account_list = AccountList.new(name: 'Test Account') user = User.new(first_name: 'Bill', last_name: 'Bright') account_list.users << user user.email_addresses << EmailAddress.new(email: '<EMAIL>') account_list end end
chuckmersereau/api_practice
app/workers/contact_dup_merge_worker.rb
class ContactDupMergeWorker include Sidekiq::Worker sidekiq_options queue: :api_contact_dup_contacts_merge_worker def perform(account_list_id, contact_id) @account_list = AccountList.find_by_id(account_list_id) @contact = Contact.find_by_id(contact_id) return unless @account_list && @contact Contact::DupContactsMerge.new(account_list: @account_list, contact: @contact).merge_duplicates end end
chuckmersereau/api_practice
app/preloaders/application_preloader.rb
# Preloaders allow you to dynamically preload the necessary associations # to avoid N+1 queries on a client request. Preloader files will be used to # determine what associations should be preloaded for a given resource. # To add a preloader, simply create a class that inherits from ApplicationPreloader. # It will be assumed that the preloader path structure follows that of the controllers. # For example, the CommentPreloader will only work if it is under the Api::V2::Tasks namespace. # Eg. # class Api::V2::TasksPreloader < ApplicationPreloader # ASSOCIATION_PRELOADER_MAPPING = { # account_list: Api::V2::AccountListsPreloader, # }.freeze # FIELD_ASSOCIATION_MAPPING = { tag_list: :tags }.freeze # # private # # def serializer_class # TaskSerializer # end # end # 'ASSOCIATION_PRELOADER_MAPPING' expects a hash where associations are mapping to # their corresponding preloader classes. # 'FIELD_ASSOCIATION_MAPPING' expects a hash where dynamic fields are mapping to # associations that will need to be loaded when the field method is called. # 'serializer_class' can optionally be defined to overwrite the ApplicationPreloader # method which will try to infer the serializer based on the preloader class' name. # Once the preloader is defined, call it llike this from the controller: # # Api::V2::TasksPreloader.new(include_params, field_params).preload(@tasks) # # Where 'include_params' and 'field_params' are the controller defined client provided # parameters and '@tasks' is the Task collection object for which the associations are # to be preloaded. class ApplicationPreloader attr_reader :include_params, :field_params, :parent_association def initialize(include_params, field_params, parent_association = nil) @include_params = include_params @field_params = field_params @parent_association = parent_association || fetch_parent_association end def preload(collection) collection.preload_valid_associations(associations_to_preload) end def associations_to_preload(add_field_associations = true) associations_to_preload = fetch_necessary_include_associations associations_to_preload += fetch_necessary_field_associations if add_field_associations associations_to_preload.uniq end private def fetch_necessary_include_associations IncludeAssociationsFetcher.new(self.class::ASSOCIATION_PRELOADER_MAPPING, resource_path) .fetch_include_associations(include_params, field_params) end def fetch_necessary_field_associations FieldAssociationsFetcher.new(self.class::FIELD_ASSOCIATION_MAPPING, serializer_class) .fetch_field_associations(field_params[parent_association.to_sym]) end def fetch_parent_association resource_name.pluralize.underscore.to_sym end def resource_path self.class.to_s.chomp('Preloader') end def resource_name resource_path.split('::').last.singularize end def serializer_class "#{resource_name}Serializer".constantize end end
chuckmersereau/api_practice
app/controllers/api/v2/reports/monthly_losses_graphs_controller.rb
class Api::V2::Reports::MonthlyLossesGraphsController < Api::V2Controller def show load_report authorize_report render_report end protected def permit_coach? true end private def load_report @report ||= ::Reports::MonthlyLossesGraph.new(report_params) end def report_params { account_list: load_account_list, months: params[:months]&.to_i } end def load_account_list @account_list ||= AccountList.find_by(id: params[:id]) end def render_report render json: @report, fields: field_params, include: include_params end def authorize_report authorize(load_account_list, :show?) end end
chuckmersereau/api_practice
lib/encoding_util.rb
require 'nokogiri' require 'csv' module EncodingUtil def normalized_utf8(contents) contents = contents.to_s return '' if contents == '' encoding_info = CharlockHolmes::EncodingDetector.detect(contents) return nil unless encoding_info && encoding_info[:encoding] encoding = encoding_info[:encoding] contents = CharlockHolmes::Converter.convert(contents, encoding, 'UTF-8') # Remove byte order mark contents.sub!("\xEF\xBB\xBF".force_encoding('UTF-8'), '') contents.encode(universal_newline: true) end module_function :normalized_utf8 end
chuckmersereau/api_practice
spec/controllers/api/v2/admin/resets_controller_spec.rb
require 'rails_helper' RSpec.describe Api::V2::Admin::ResetsController do let(:admin_user) { create(:user, admin: true) } let(:reset_user) { create(:user_with_account) } let!(:key_account) { create(:key_account, person: reset_user) } let(:account_list) { reset_user.account_lists.order(:created_at).first } let(:given_resource_type) { :resets } let(:correct_attributes) do { resetted_user_email: key_account.email, reason: 'Resetting User Account', account_list_name: account_list.name } end let(:response_data) { JSON.parse(response.body)['data'] } let(:response_errors) { JSON.parse(response.body)['errors'] } include_context 'common_variables' context 'create' do it 'returns a 401 when someone is not logged in' do post :create, full_correct_attributes expect(response.status).to eq(401) end it 'returns a 403 when someone that is not an admin tries to create an organization' do api_login(create(:user)) post :create, full_correct_attributes expect(response.status).to eq(403) end it 'returns a 400 when the account list name does not exist' do full_correct_attributes[:data][:attributes][:account_list_name] = 'random' api_login(admin_user) post :create, full_correct_attributes expect(response.status).to eq(400) expect(response_errors).to_not be_empty end it 'returns a 400 when the user email does not exist' do full_correct_attributes[:data][:attributes][:resetted_user_email] = '<EMAIL>' api_login(admin_user) post :create, full_correct_attributes expect(response.status).to eq(400) expect(response_errors).to_not be_empty end it 'returns a 200 when an admin provides correct attributes' do api_login(admin_user) post :create, full_correct_attributes expect(response.status).to eq(200) end end end
chuckmersereau/api_practice
app/services/tnt_import/contact_import.rb
class TntImport::ContactImport include Concerns::TntImport::DateHelpers include LocalizationHelper BEGINNING_OF_TIME = '1899-12-30'.freeze def initialize(import, tags, donor_accounts, xml) @import = import @account_list = import.account_list @user = import.user @tags = tags @donor_accounts = donor_accounts || [] @xml = xml @override = import.override? end def import_contact(row) contact = Retryable.retryable do @account_list.contacts.find_by(tnt_id: row['id']) end @donor_accounts.each do |donor_account| contact = donor_account.link_to_contact_for(@account_list, contact) end # Look for more ways to link a contact contact ||= Retryable.retryable do @account_list.contacts.where(name: row['FileAs']).first_or_initialize end # add additional data to contact update_contact(contact, row) primary_contact_person = add_or_update_primary_person(row, contact) # Now the secondary person (persumably spouse) if row['SpouseFirstName'].present? row['SpouseLastName'] = row['LastName'] if row['SpouseLastName'].blank? contact_spouse = add_or_update_spouse(row, contact) # Wed the two peple primary_contact_person.add_spouse(contact_spouse) end merge_dups_by_donor_accts(contact, @donor_accounts) @donor_accounts.each { |donor_account| add_or_update_company(row, donor_account) } if true?(row['IsOrganization']) contact end private def update_contact(contact, row) update_contact_basic_fields(contact, row) update_contact_pledge_fields(contact, row) update_contact_date_fields(contact, row) update_contact_send_newsletter_field(contact, row) update_locale(contact, row) update_contact_tags(contact) Retryable.retryable do contact.save end end def update_contact_basic_fields(contact, row) # we should set value either way if the contact is new because the values are defaulted contact.direct_deposit = true?(row['DirectDeposit']) if @override || !contact.persisted? contact.magazine = true?(row['Magazine']) if @override || !contact.persisted? contact.is_organization = true?(row['IsOrganization']) if @override || !contact.persisted? contact.name = row['FileAs'] if @override || contact.name.blank? contact.full_name = row['FullName'] if @override || contact.full_name.blank? contact.greeting = row['Greeting'] if @override || contact.greeting.blank? if @override || contact.attributes['envelope_greeting'].blank? contact.envelope_greeting = extract_envelope_greeting_from_row(row) end contact.website = row['WebPage'] if @override || contact.website.blank? contact.church_name = row['ChurchName'] if @override || contact.church_name.blank? contact.updated_at = parse_date(row['LastEdit'], @import.user) if @override contact.created_at = parse_date(row['CreatedDate'], @import.user) if @override add_notes(contact, row) contact.tnt_id = row['id'] contact.addresses.build(TntImport::AddressesBuilder.build_address_array(row, contact, @override)) end def update_contact_pledge_fields(contact, row) contact.pledge_amount = row['PledgeAmount'] if @override || contact.pledge_amount.blank? # PledgeFrequencyID: Since TNT 3.2, a negative number indicates a fequency in days. # For example: -11 would be a frequency of 11 days. For now we are ignoring negatives. if (@override || contact.pledge_frequency.blank?) && row['PledgeFrequencyID'].to_i.positive? contact.pledge_frequency = row['PledgeFrequencyID'] end contact.pledge_received = true?(row['PledgeReceived']) if @override || contact.pledge_received.blank? if (@override || contact.status.blank?) && TntImport::TntCodes.mpd_phase(row['MPDPhaseID']).present? contact.status = TntImport::TntCodes.mpd_phase(row['MPDPhaseID']) end if (@override || contact.likely_to_give.blank?) && row['LikelyToGiveID'].to_i.nonzero? contact.likely_to_give = contact.assignable_likely_to_gives[row['LikelyToGiveID'].to_i - 1] end contact.no_appeals = true?(row['NeverAsk']) if @override || contact.no_appeals.nil? if @override || contact.estimated_annual_pledge_amount.nil? contact.estimated_annual_pledge_amount = row['EstimatedAnnualCapacity'] end contact.next_ask_amount = row['NextAskAmount'] if @override || contact.next_ask_amount.nil? contact.pledge_currency = pledge_currency(row) if @override || contact.pledge_currency.nil? end def update_contact_date_fields(contact, row) if (@override || contact.pledge_start_date.blank?) && row['PledgeStartDate'].present? && row['PledgeStartDate'] != BEGINNING_OF_TIME contact.pledge_start_date = parse_date(row['PledgeStartDate'], @import.user) end if (@override || contact.next_ask.blank?) && row['NextAsk'].present? && row['NextAsk'] != BEGINNING_OF_TIME contact.next_ask = parse_date(row['NextAsk'], @import.user) end if (@override || contact.last_activity.blank?) && row['LastActivity'].present? && row['LastActivity'] != BEGINNING_OF_TIME contact.last_activity = parse_date(row['LastActivity'], @import.user) end if (@override || contact.last_appointment.blank?) && row['LastAppointment'].present? && row['LastAppointment'] != BEGINNING_OF_TIME contact.last_appointment = parse_date(row['LastAppointment'], @import.user) end if (@override || contact.last_letter.blank?) && row['LastLetter'].present? && row['LastLetter'] != BEGINNING_OF_TIME contact.last_letter = parse_date(row['LastLetter'], @import.user) end if (@override || contact.last_phone_call.blank?) && row['LastCall'].present? && row['LastCall'] != BEGINNING_OF_TIME contact.last_phone_call = parse_date(row['LastCall'], @import.user) end if (@override || contact.last_pre_call.blank?) && row['LastPreCall'].present? && row['LastPreCall'] != BEGINNING_OF_TIME contact.last_pre_call = parse_date(row['LastPreCall'], @import.user) end if (@override || contact.last_thank.blank?) && row['LastThank'].present? && row['LastThank'] != BEGINNING_OF_TIME contact.last_thank = parse_date(row['LastThank'], @import.user) end end def update_contact_send_newsletter_field(contact, row) return unless contact.send_newsletter.nil? || @override if true?(row['SendNewsletter']) case row['NewsletterMediaPref'] when '+E', '+E-P' contact.send_newsletter = 'Email' when '+P', '+P-E' contact.send_newsletter = 'Physical' else contact.send_newsletter = 'Both' end else contact.send_newsletter = 'None' end end def update_locale(contact, row) newsletter_lang = @xml.find('NewsletterLang', row['NewsletterLangID']).try(:[], 'Description') locale = supported_locales.key(newsletter_lang) if locale contact.locale = locale elsif newsletter_lang.present? && newsletter_lang != 'Unknown' contact.tag_list.add(newsletter_lang) end end def update_contact_tags(contact) @tags.each do |tag| # we replace , with ; to allow for safe tags to be created safe_tag = tag.gsub(ActsAsTaggableOn.delimiter, ';') contact.tag_list.add(safe_tag) end end def add_or_update_primary_person(row, contact) add_or_update_person(row, contact, '') end def add_or_update_spouse(row, contact) add_or_update_person(row, contact, 'Spouse') end def add_or_update_person(row, contact, prefix) TntImport::PersonImport.new(row, contact, prefix, @override).import end # If the user had two donor accounts in the same contact in Tnt, then merge different contacts with those in MPDX. def merge_dups_by_donor_accts(tnt_contact, donor_accounts) dups_by_donor_accts = @account_list.contacts.where.not(id: tnt_contact.id).joins(:donor_accounts) .where(donor_accounts: { id: donor_accounts.map(&:id) }).readonly(false) dups_by_donor_accts.each do |dup_contact_matching_donor_account| tnt_contact.merge(dup_contact_matching_donor_account) end end def add_or_update_company(row, donor_account) master_company = MasterCompany.find_by(name: row['OrganizationName']) company = @user.partner_companies.find_by(master_company_id: master_company.id) if master_company company ||= @account_list.companies.new(master_company: master_company) company.assign_attributes(name: row['OrganizationName'], phone_number: row['Phone'], street: row['MailingStreetAddress'], city: row['MailingCity'], state: row['MailingState'], postal_code: row['MailingPostalCode'], country: row['MailingCountry']) company.save! unless donor_account.master_company_id == company.master_company.id donor_account.update_attribute(:master_company_id, company.master_company_id) end company end def add_notes(contact, row) contact.add_to_notes(row['Notes']) # These fields don't have equivalents in MPDX, so we'll add them to notes: contact.add_to_notes("Children: #{row['Children']}") if row['Children'].present? contact.add_to_notes("User Status: #{row['UserStatus']}") if row['UserStatus'].present? contact.add_to_notes("Categories: #{row['Categories']}") if row['Categories'].present? contact.add_to_notes("Other Social: #{row['SocialWeb4']}") if row['SocialWeb4'].present? contact.add_to_notes("Spouse Other Social: #{row['SpouseSocialWeb4']}") if row['SpouseSocialWeb4'].present? contact.add_to_notes("Voice/Skype: #{row['VoiceSkype']}") if row['VoiceSkype'].present? contact.add_to_notes("Spouse Voice/Skype: #{row['SpouseVoiceSkype']}") if row['SpouseVoiceSkype'].present? contact.add_to_notes("IM Address: #{row['IMAddress']}") if row['IMAddress'].present? contact.add_to_notes("Spouse IM Address: #{row['SpouseIMAddress']}") if row['SpouseIMAddress'].present? contact.add_to_notes("Interests: #{row['Interests']}") if row['Interests'].present? contact.add_to_notes("Spouse Interests: #{row['SpouseInterests']}") if row['SpouseInterests'].present? contact.add_to_notes("Nickname: #{row['Nickname']}") if row['Nickname'].present? contact.add_to_notes("Spouse Nickname: #{row['SpouseNickname']}") if row['SpouseNickname'].present? end def extract_envelope_greeting_from_row(row) # TNT has something called a "MailingAddressBlock", the envelope greeting is the first line of this string. block = row['MailingAddressBlock'] envelope_greeting = block&.split("\n")&.detect(&:present?) # Find the first non-blank line of the string. envelope_greeting.presence || row['FullName'] end def pledge_currency(row) currency_id = row['PledgeCurrencyID'] return unless currency_id @xml.find('Currency', currency_id).try(:[], 'Code') end def true?(val) val.to_s.casecmp('TRUE').zero? end end
chuckmersereau/api_practice
spec/acceptance/api/v2/account_lists/invites_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/acceptance/api/v2/account_lists/invites_spec.rb require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Account Lists > Invites' do include_context :json_headers documentation_scope = :account_lists_api_invites let(:resource_type) { 'account_list_invites' } let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let(:invite_params) { { account_list: account_list, accepted_by_user: nil, cancelled_by_user: nil } } let!(:invite) { create(:account_list_invite, invite_params) } let!(:invite_coach) { create(:account_list_invite, invite_params.merge(invite_user_as: 'coach')) } let(:id) { invite.id } let(:expected_attribute_keys) do %w( accepted_at code created_at invite_user_as recipient_email updated_at updated_in_db_at ) end let(:resource_associations) do %w( accepted_by_user cancelled_by_user invited_by_user ) end context 'authorized user' do before { api_login(user) } get '/api/v2/account_lists/:account_list_id/invites' do parameter 'account_list_id', 'Account List ID', required: true response_field 'data', 'Data', type: 'Array[Object]' example 'Invite [LIST]', document: documentation_scope do explanation 'List of Invites associated with the Account List' do_request check_collection_resource(2, ['relationships']) expect(resource_object.keys).to match_array expected_attribute_keys expect(response_status).to eq 200 end example 'Invite [LIST] Filter User Invites', document: false do explanation 'List of User Invites associated with the Account List' do_request(filter: { invite_user_as: 'user' }) check_collection_resource(1, ['relationships']) expect(resource_object['invite_user_as']).to eq 'user' expect(response_status).to eq 200 end example 'Invite [LIST] Filter Coach Invites', document: false do explanation 'List of Coach Invites associated with the Account List' do_request(filter: { invite_user_as: 'coach' }) check_collection_resource(1, ['relationships']) expect(resource_object['invite_user_as']).to eq 'coach' expect(response_status).to eq 200 end end get '/api/v2/account_lists/:account_list_id/invites/:id' do with_options scope: [:data, :attributes] do response_field 'accepted_at', 'Accepted At', type: 'String' response_field 'accepted_by_user_id', 'Accepted by User ID', type: 'Number' response_field 'account_list_id', 'Account List ID', type: 'Number' response_field 'cancelled_by_user_id', 'Cancelled by user ID', type: 'Number' response_field 'code', 'Code', type: 'String' response_field 'created_at', 'Created At', type: 'String' response_field 'invited_by_user_id', 'Invited by User ID', type: 'Number' response_field 'recipient_email', 'Recipient Email', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end example 'Invite [GET]', document: documentation_scope do explanation 'The Account List Invite with the given ID' do_request check_resource(['relationships']) expect(resource_object.keys).to match_array expected_attribute_keys expect(resource_object['code']).to eq invite.code expect(response_status).to eq 200 end end post '/api/v2/account_lists/:account_list_id/invites' do let!(:new_account_list_invite) { attributes_for :account_list_invite } let!(:recipient_email) { new_account_list_invite[:recipient_email] } let!(:invite_user_as) { 'user' } let!(:form_data) { build_data(recipient_email: recipient_email, invite_user_as: invite_user_as) } parameter 'recipient_email', 'Recipient Email', scope: [:data, :attributes], required: true parameter 'invite_user_as', 'Kind of invite ("user" or "coach")', scope: [:data, :attributes], required: true example 'Invite [CREATE]', document: documentation_scope do explanation 'Creates the invite associated to the given account_list' do_request data: form_data expect(response_status).to eq 201 expect(resource_object['recipient_email']).to eq recipient_email expect(resource_object['invite_user_as']).to eq 'user' end end put '/api/v2/account_lists/:account_list_id/invites/:id/accept' do let(:form_data) { build_data(code: invite.code) } parameter 'code', 'Acceptance code', scope: [:data, :attributes], required: true example 'Invite [ACCEPT]', document: documentation_scope do explanation 'Accepts the invite' do_request data: form_data expect(response_status).to eq 200 expect(resource_object['accepted_at']).to be_present end end delete '/api/v2/account_lists/:account_list_id/invites/:id' do example 'Invite [CANCEL]', document: documentation_scope do explanation 'Cancels the invite' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
config/initializers/smtp.rb
<reponame>chuckmersereau/api_practice ActionMailer::Base.smtp_settings = { :user_name => ENV.fetch('SMTP_USER_NAME'), :password => <PASSWORD>('<PASSWORD>'), :address => ENV.fetch('SMTP_ADDRESS'), :authentication => (ENV.fetch('SMTP_AUTHENTICATION') || :none), :enable_starttls_auto => ENV.fetch('SMTP_ENABLE_STARTTLS_AUTO'), :port => ENV.fetch('SMTP_PORT') || 25 }
chuckmersereau/api_practice
config/initializers/fast_gettext.rb
<filename>config/initializers/fast_gettext.rb require 'gettext_i18n_rails/string_interpolate_fix' text_domain = FastGettext.add_text_domain 'mpdx', path: 'locale', type: :po, report_warning: false FastGettext.default_text_domain = 'mpdx' I18n.config.available_locales = [ 'en', 'en-US','de','fr-FR', 'fr-CA', 'en', 'es-419', 'it', 'ko', 'pt-BR', 'ru', 'id', 'ar', 'zh-HANS-CH', 'tr', 'th', 'hy', 'nl-NL' ] FastGettext.default_available_locales = I18n.config.available_locales.map{ |locale| locale.to_s.tr('-', '_') } GettextI18nRails.translations_are_html_safe = true # Overwrite the find_files_in_locale_folders method to not check the locale with the limiting REGEX # before fetching the file.module FastGettext. # We need this for locales like es-419 which the REGEX check would prevent from being loaded. module FastGettext module TranslationRepository class Base def find_files_in_locale_folders(relative_file_path, path) path ||= "locale" raise "path #{path} could not be found!" unless File.exist?(path) @files = {} Dir[File.join(path,'*')].each do |locale_folder| file = File.join(locale_folder,relative_file_path).untaint next unless File.exist? file locale = File.basename(locale_folder) @files[locale] = yield(locale,file) end end end end end text_domain.reload # We are reloading the locale files here since we want loading to take place using the above code.
chuckmersereau/api_practice
app/services/tnt_import/appeals_import.rb
# In version 3.2, TNT renamed the "Appeal" table to "Campaign". class TntImport::AppealsImport include Concerns::TntImport::AppealHelpers def initialize(account_list, contact_ids_by_tnt_appeal_id, xml) @account_list = account_list @contact_ids_by_tnt_appeal_id = contact_ids_by_tnt_appeal_id @xml = xml @xml_tables = xml.tables end def import appeals_by_tnt_id = find_or_create_appeals_by_tnt_id appeals_by_tnt_id.each do |appeal_tnt_id, appeal| contact_ids = contact_ids_by_tnt_appeal_id[appeal_tnt_id] || [] appeal.bulk_add_contacts(contact_ids: contact_ids) end end private attr_reader :xml_tables, :contact_ids_by_tnt_appeal_id def find_or_create_appeals_by_tnt_id return {} unless xml_tables[appeal_table_name].present? appeals = {} xml_tables[appeal_table_name].each do |row| appeal = @account_list.appeals.find_or_initialize_by(tnt_id: row['id']) appeal.attributes = { created_at: row['LastEdit'], name: row['Description'], active: row['Active'] || true, amount: row['SpecialGoal'], monthly_amount: row['MonthlyGoal'] } appeal.save appeals[row['id']] = appeal end appeals end end
chuckmersereau/api_practice
app/controllers/api/v2/account_lists/notification_preferences_controller.rb
class Api::V2::AccountLists::NotificationPreferencesController < Api::V2Controller def index authorize load_account_list, :show? load_notification_preferences render json: @notification_preferences.preload_valid_associations(include_associations), meta: meta_hash(@notification_preferences), include: include_params, fields: field_params end def show load_notification_preference authorize_notification_preference render_notification_preference end def create persist_notification_preference end def destroy load_notification_preference authorize_notification_preference destroy_notification_preference end private def notification_preference_params params .require(:notification_preference) .permit(notification_preference_attributes) end def notification_preference_attributes NotificationPreference::PERMITTED_ATTRIBUTES end def notification_preference_scope current_user.notification_preferences.where(account_list: load_account_list) end def authorize_notification_preference authorize @notification_preference end def build_notification_preference @notification_preference ||= notification_preference_scope.build @notification_preference.assign_attributes(notification_preference_params) end def destroy_notification_preference @notification_preference.destroy head :no_content end def load_notification_preference @notification_preference ||= NotificationPreference.find(params[:id]) end def load_notification_preferences @notification_preferences ||= notification_preference_scope .where(filter_params) .reorder(:created_at) .page(page_number_param) .per(per_page_param) end def persist_notification_preference build_notification_preference authorize_notification_preference if save_notification_preference render_notification_preference else render_400_with_errors(@notification_preference) end end def render_notification_preference render json: @notification_preference, status: success_status, include: include_params, fields: field_params end def save_notification_preference @notification_preference.save(context: persistence_context) 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/models/nickname_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/models/nickname_spec.rb require 'rails_helper' describe Nickname do describe '#increment_times_merged' do it 'calls find_and_increment_counter' do expect(Nickname).to receive(:find_and_increment_counter).with('John', 'Johnny', :num_merges) Nickname.increment_times_merged('John', 'Johnny') end end describe '#increment_not_duplicates' do it 'calls find_and_increment_counter' do expect(Nickname).to receive(:find_and_increment_counter).with('John', 'Johnny', :num_not_duplicates) Nickname.increment_not_duplicates('John', 'Johnny') end end describe '#find_and_increment_counter' do it 'finds an existing nickname and increments its counter' do nickname = Nickname.create(name: 'john', nickname: 'johnny') expect do Nickname.find_and_increment_counter('John', 'Johnny', :num_merges) nickname.reload end.to change(nickname, :num_merges).from(0).to(1) end it 'creates a new nickname and increments its counter' do expect do Nickname.find_and_increment_counter('John', 'Johnny', :num_merges) end.to change(Nickname, :count).from(0).to(1) expect(Nickname.first.num_merges).to eq(1) end it 'does nothing if the nickname and name are the same or one contains an initial, ., space or -' do non_saved_nickname_pairs = { 'John' => 'john', 'john.' => 'John', 'J' => 'John', '<NAME>' => 'Mary', 'Hoo-tee' => 'Hootee' } expect do non_saved_nickname_pairs.each do |name1, name2| Nickname.find_and_increment_counter(name1, name2, :num_merges) Nickname.find_and_increment_counter(name2, name1, :num_merges) end end.to_not change(Nickname, :count).from(0) end end end
chuckmersereau/api_practice
app/services/contact/analytics.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 class Contact::Analytics alias read_attribute_for_serialization send attr_reader :contacts def initialize(contacts) @contacts = contacts end def first_gift_not_received_count contacts.financial_partners .where(pledge_received: false) .count end def partners_30_days_late_count contacts.late_by(31.days, 60.days).count end def partners_60_days_late_count contacts.late_by(61.days, 90.days).count end def partners_90_days_late_count contacts.late_by(91.days).count end def birthdays_this_week fetch_contact_people_with_birthdays_this_week_who_are_alive_from_active_contacts.map do |contact_person| PersonWithParentContact.new(person: contact_person.person, parent_contact: contact_person.contact) end end def anniversaries_this_week fetch_active_contacts_who_have_people_with_anniversaries_this_week end private def beginning_of_week @beginning_of_week ||= Time.current.beginning_of_week end def fetch_active_contacts_who_have_people_with_anniversaries_this_week person_ids = fetch_people_with_anniversaries_this_week_who_are_alive .select(:id) contacts .active .joins(:contact_people) .where(contact_people: { person_id: person_ids }).uniq end def fetch_contact_people_with_birthdays_this_week_who_are_alive_from_active_contacts contact_ids = contacts.active.select(:id) person_ids = Person.with_birthday_this_week(beginning_of_week) .alive .select(:id) ContactPerson.where(contact_id: contact_ids, person_id: person_ids) .includes(:person, :contact) end def fetch_people_with_anniversaries_this_week_who_are_alive Person.with_anniversary_this_week(beginning_of_week) .by_anniversary .alive end end
chuckmersereau/api_practice
app/serializers/appeal/excluded_appeal_contact_serializer.rb
class Appeal::ExcludedAppealContactSerializer < ApplicationSerializer type :excluded_appeal_contacts attributes :reasons belongs_to :appeal belongs_to :contact end
chuckmersereau/api_practice
app/controllers/api/v2/user/google_accounts_controller.rb
<reponame>chuckmersereau/api_practice class Api::V2::User::GoogleAccountsController < Api::V2Controller def index load_google_accounts render json: @google_accounts.preload_valid_associations(include_associations), meta: meta_hash(@google_accounts), include: include_params, fields: field_params end def show load_google_account authorize_google_account render_google_account end def create persist_google_account end def update load_google_account authorize_google_account persist_google_account end def destroy load_google_account authorize_google_account destroy_key_account end private def destroy_key_account @google_account.destroy head :no_content end def load_google_accounts @google_accounts = google_account_scope.where(filter_params) .reorder(sorting_param) .page(page_number_param) .per(per_page_param) end def load_google_account @google_account ||= Person::GoogleAccount.find(params[:id]) end def render_google_account render json: @google_account, status: success_status, include: include_params, fields: field_params end def persist_google_account build_google_account authorize_google_account if save_google_account render_google_account else render_with_resource_errors(@google_account) end end def build_google_account @google_account ||= google_account_scope.build @google_account.assign_attributes(google_account_params) end def save_google_account @google_account.save(context: persistence_context) end def google_account_params params .require(:google_account) .permit(Person::GoogleAccount::PERMITTED_ATTRIBUTES) end def authorize_google_account authorize @google_account end def google_account_scope load_user.google_accounts end def load_user @user ||= current_user end end
chuckmersereau/api_practice
app/workers/run_once/send_gdpr_unsubscribes_worker.rb
<reponame>chuckmersereau/api_practice<filename>app/workers/run_once/send_gdpr_unsubscribes_worker.rb<gh_stars>0 class RunOnce::SendGDPRUnsubscribesWorker include Sidekiq::Worker sidekiq_options queue: :default, retry: false def perform(email_addresses) emails = EmailAddress.includes(person: :contacts).where(email: email_addresses, primary: true, people: { optout_enewsletter: false }, contacts: { send_newsletter: %w(Email Both) }) AccountList.includes(people: :email_addresses).where(email_addresses: { id: emails.collect(&:id) }) .each { |al| send_mail(al, emails) } end def build_unsubscribes_list(account_list, emails) contact_people = ContactPerson.includes(:contact, :person).where(contacts: { account_list_id: account_list.id }, person_id: emails.collect(&:person_id)) unsubscribes = contact_people.map do |cp| email = emails.find { |e| e.person_id == cp.person_id } { contact_id: cp.contact_id, person_id: cp.person.id, person_name: cp.person.to_s, email: email.email } end unsubscribes.sort_by { |h| h[:email] } end private def send_mail(account_list, emails) to = account_list.users.collect(&:email_address).uniq.compact return unless to.any? unsubscribes = build_unsubscribes_list(account_list, emails) unsubscribes.each { |unsub| RunOnceMailer.delay.gdpr_unsubscribes(to, account_list.name, unsub) } Rails.logger.warn("Account List notified of GDPR unsubscribes: #{account_list.id}") end end
chuckmersereau/api_practice
db/migrate/20170418040007_add_index_on_master_companies_on_name.rb
<filename>db/migrate/20170418040007_add_index_on_master_companies_on_name.rb class AddIndexOnMasterCompaniesOnName < ActiveRecord::Migration disable_ddl_transaction! def change add_index :master_companies, :name, algorithm: :concurrently end end
chuckmersereau/api_practice
app/services/account_list/from_designations_finder.rb
class AccountList::FromDesignationsFinder def initialize(numbers, organization_id) @numbers = numbers @organization_id = organization_id end def account_list AccountList.where(id: account_list_ids_with_designations) .select(&method(:no_other_designations_for_org?)).min_by(&:id) end private # We want to filter out account lists whose designations for a particular # organization are greater than the designation numbers specified for a # specific user so that that user isn't allowed to view the higher-level # account lists for an organization unless they are authorized to view all the # designations for that account. But the comparision should be done on a # per-organization basis so that we can match account lists that have # designations from multiple organizations merged into them (e.g. for staff # with multiple currencies and accounts in different countries) def no_other_designations_for_org?(account_list) comparator = account_list.designation_accounts .where(organization_id: @organization_id) .where("name NOT LIKE '%(Imported from TntConnect)'") .pluck(:id) .sort comparator == designation_ids end # Returns the account lists that contain all of the designations # This could include both personal accounts as well as higher-level ministry # accounts that e.g. contain all the designations for a particular ministry. def account_list_ids_with_designations # By using a count query we can filter for only those account lists that # have all of the designation account ids we are looking for. AccountList.joins(:account_list_entries) .where(account_list_entries: { designation_account_id: designation_ids }) .group(:account_list_id).having('count(*) = ?', designation_ids.count) .count.keys end def designation_ids @designation_ids ||= DesignationAccount.where(designation_number: @numbers) .where(organization_id: @organization_id).pluck(:id).sort end end
chuckmersereau/api_practice
db/migrate/20170322001657_add_file_row_sampes_to_imports.rb
class AddFileRowSampesToImports < ActiveRecord::Migration def change add_column :imports, :file_row_samples, :text end end
chuckmersereau/api_practice
app/services/contact/filter/likely.rb
<gh_stars>0 class Contact::Filter::Likely < Contact::Filter::Base def execute_query(contacts, filters) likely_filters = parse_list(filters[:likely]) likely_filters << nil if likely_filters.delete('none') contacts.where(likely_to_give: likely_filters) end def title _('Likely To Give') end def parent _('Contact Details') end def type 'multiselect' end def custom_options [{ name: _('-- None --'), id: 'none' }] + contact_instance.assignable_likely_to_gives.map { |s| { name: _(s), id: s } } end end
chuckmersereau/api_practice
app/workers/mail_chimp/primary_list_sync_worker.rb
class MailChimp::PrimaryListSyncWorker include Sidekiq::Worker sidekiq_options queue: :api_mail_chimp_sync_worker, unique: :until_executed def perform(mail_chimp_account_id) mail_chimp_account = MailChimpAccount.find_by(id: mail_chimp_account_id) return unless mail_chimp_account MailChimp::Syncer.new(mail_chimp_account).two_way_sync_with_primary_list end end
chuckmersereau/api_practice
db/migrate/20140801103154_add_optout_enewsletter_to_people.rb
class AddOptoutEnewsletterToPeople < ActiveRecord::Migration def change add_column :people, :optout_enewsletter, :boolean, default: false end end
chuckmersereau/api_practice
app/models/master_person.rb
<filename>app/models/master_person.rb class MasterPerson < ApplicationRecord has_many :people, dependent: :destroy has_many :master_person_donor_accounts, dependent: :destroy has_many :master_person_sources, dependent: :destroy has_many :donor_accounts, through: :master_person_donor_accounts def self.find_or_create_for_person(person, extra = {}) master_person = find_for_person(person, extra) return master_person if master_person mp = create! donor_account = extra[:donor_account] if donor_account mp.donor_accounts << donor_account mp.master_person_sources.create(organization_id: donor_account.organization_id, remote_id: extra[:remote_id]) if extra[:remote_id] end mp end def self.find_for_person(person, extra = {}) # Start by looking for a person with the same email address (since that's our one true unique field) person.email_addresses.each do |email_address| other_person = Person.where('people.first_name' => person.first_name, 'people.last_name' => person.last_name, 'people.suffix' => person.suffix, 'email_addresses.email' => email_address.email) .where('people.middle_name = ? OR people.middle_name is null', person.middle_name) .joins(:email_addresses) .first return other_person.master_person if other_person end # if we have an exact match on name and phone number, that's also pretty good person.phone_numbers.each do |phone_number| phone_number.clean_up_number next unless phone_number.number.present? other_person = Person.where('people.first_name' => person.first_name, 'people.last_name' => person.last_name, 'people.suffix' => person.suffix, 'phone_numbers.number' => phone_number.number, 'phone_numbers.country_code' => phone_number.country_code) .where('people.middle_name = ? OR people.middle_name is null', person.middle_name) .joins(:phone_numbers).first return other_person.master_person if other_person end # If we have a donor account to look at, donor account + name is pretty safe if extra[:donor_account] other_person = extra[:donor_account].people.where('people.first_name' => person.first_name, 'people.last_name' => person.last_name, 'people.suffix' => person.suffix) .find_by('people.middle_name = ? OR people.middle_name is null', person.middle_name) return other_person.master_person if other_person end nil end def merge(other) Person.where(master_person_id: other.id).update_all(master_person_id: id) MasterPersonSource.where(master_person_id: other.id).update_all(master_person_id: id) MasterPersonDonorAccount.where(master_person_id: other.id).update_all(master_person_id: id) other.reload other.destroy end end
chuckmersereau/api_practice
spec/controllers/api/v2/account_lists/donations_controller_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/controllers/api/v2/account_lists/donations_controller_spec.rb<gh_stars>0 require 'rails_helper' describe Api::V2::AccountLists::DonationsController, type: :controller do let(:factory_type) { :donation } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:contact) { create(:contact, account_list: account_list) } let!(:donor_account) { create(:donor_account) } let!(:designation_account) { create(:designation_account) } let!(:donations) do create_list(:donation, 2, donor_account: donor_account, designation_account: designation_account, amount: 10.00, donation_date: Date.today) end let(:donation) { donations.first } let(:id) { donation.id } before do donation.update(donation_date: 2.days.ago, amount: 12.00) account_list.designation_accounts << designation_account contact.donor_accounts << donor_account end let(:resource) { donation } let(:parent_param) { { account_list_id: account_list_id } } let(:filter_param) { { donation_date: "#{1.day.ago}..#{1.day.from_now}" } } let(:correct_attributes) { attributes_for(:donation) } let(:incorrect_attributes) { { donation_date: nil } } let(:unpermitted_attributes) { nil } let(:correct_relationships) do { account_list: { data: { type: 'account_lists', id: account_list_id } } } end include_examples 'index_examples' include_examples 'show_examples' include_examples 'update_examples' include_examples 'destroy_examples' describe 'Filters' do let!(:donor_account_1) { create(:donor_account) } let!(:designation_account_1) { create(:designation_account) } let!(:contact_1) { create(:contact, account_list: account_list) } let!(:donations_1) do create_list(:donation, 2, donor_account: donor_account_1, designation_account: designation_account_1, amount: 10.00, donation_date: Date.today) end before do account_list.designation_accounts << designation_account_1 contact_1.donor_accounts << donor_account_1 api_login(user) end it 'allows a user to filter by designation_account_id' do get :index, account_list_id: account_list_id, filter: { designation_account_id: designation_account_1.id } expect(response_json['data'].map { |donation| donation['id'] }).to match_array(donations_1.map(&:id)) expect(response_json['meta']['filter']['designation_account_id']).to eq(designation_account_1.id) end it 'allows a user to filter by donor_account_id' do get :index, account_list_id: account_list_id, filter: { donor_account_id: donor_account_1.id } expect(response_json['data'].map { |donation| donation['id'] }).to match_array(donations_1.map(&:id)) expect(response_json['meta']['filter']['donor_account_id']).to eq(donor_account_1.id) end it 'has donation totals within the meta' do get :index, account_list_id: account_list_id, filter: { donor_account_id: donor_account_1.id } expect(response_json['meta']['totals'].first['amount']).to eq(donor_account_1.donations.sum(:amount).to_s) end end end
chuckmersereau/api_practice
app/validators/file_size_validator.rb
<reponame>chuckmersereau/api_practice<filename>app/validators/file_size_validator.rb class FileSizeValidator < ActiveModel::EachValidator def initialize(options) raise(ArgumentError, 'You must supply a validation value for less_than (in bytes)') unless options[:less_than]&.is_a?(Integer) options[:message] ||= "File size must be less than #{options[:less_than]} bytes" super end def validate_each(record, attribute, value) return unless value&.size return if value.size <= options[:less_than] record.errors[attribute] << options[:message] end end