repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
chuckmersereau/api_practice
db/migrate/20120308211617_add_primary_to_some_accounts.rb
class AddPrimaryToSomeAccounts < ActiveRecord::Migration def change add_column :person_twitter_accounts, :primary, :boolean, default: false add_column :person_google_accounts, :primary, :boolean, default: false add_column :person_relay_accounts, :primary, :boolean, default: false add_column :person_key_accounts, :primary, :boolean, default: false end end
chuckmersereau/api_practice
app/models/name_male_ratio.rb
<gh_stars>0 class NameMaleRatio < ApplicationRecord end
chuckmersereau/api_practice
app/serializers/notification_serializer.rb
<filename>app/serializers/notification_serializer.rb class NotificationSerializer < ApplicationSerializer attributes :cleared, :event_date has_one :contact has_one :notification_type belongs_to :donation belongs_to :notification_type end
chuckmersereau/api_practice
app/policies/activity_comment_policy.rb
class ActivityCommentPolicy < ApplicationPolicy private def resource_owner? person_authorized? && user.account_lists.exists?(id: resource.activity.account_list_id) end def person_authorized? resource.person_id.blank? || resource.person_id == user.id end end
chuckmersereau/api_practice
db/migrate/20170817184253_add_email_blacklist_to_google_integrations.rb
<gh_stars>0 class AddEmailBlacklistToGoogleIntegrations < ActiveRecord::Migration def change add_column :google_integrations, :email_blacklist, :text end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/people/linkedin_accounts_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > People > Linkedin Accounts' do include_context :json_headers doc_helper = DocumentationHelper.new(resource: [:people, :linkedin_accounts]) let(:resource_type) { 'linkedin_accounts' } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:contact) { create(:contact, account_list: account_list) } let(:contact_id) { contact.id } let!(:person) { create(:person) } let(:person_id) { person.id } let!(:linkedin_accounts) { create_list(:linkedin_account, 2, person: person) } let(:linkedin_account) { linkedin_accounts.first } let(:id) { linkedin_account.id } let(:new_linked_in_account) do attributes_for(:linkedin_account) .select { |key| key.to_s.in? %w(public_url) } .merge(updated_in_db_at: linkedin_account.updated_at) end let(:form_data) { build_data(new_linked_in_account) } let(:expected_attribute_keys) do %w( created_at public_url updated_at updated_in_db_at ) end context 'authorized user' do before do contact.people << person api_login(user) end get '/api/v2/contacts/:contact_id/people/:person_id/linkedin_accounts' do doc_helper.insert_documentation_for(action: :index, context: self) example doc_helper.title_for(:index), document: doc_helper.document_scope do explanation doc_helper.description_for(:index) do_request expect(response_status).to eq(200), invalid_status_detail check_collection_resource(2) expect(resource_object.keys).to match_array expected_attribute_keys end end get '/api/v2/contacts/:contact_id/people/:person_id/linkedin_accounts/:id' do doc_helper.insert_documentation_for(action: :show, context: self) example doc_helper.title_for(:show), document: doc_helper.document_scope do explanation doc_helper.description_for(:show) do_request expect(response_status).to eq(200), invalid_status_detail expect(resource_object.keys).to match_array expected_attribute_keys end end post '/api/v2/contacts/:contact_id/people/:person_id/linkedin_accounts' do doc_helper.insert_documentation_for(action: :create, context: self) example doc_helper.title_for(:create), document: doc_helper.document_scope do explanation doc_helper.description_for(:create) do_request data: form_data expect(response_status).to eq(201), invalid_status_detail end end put '/api/v2/contacts/:contact_id/people/:person_id/linkedin_accounts/:id' do doc_helper.insert_documentation_for(action: :update, context: self) example doc_helper.title_for(:update), document: doc_helper.document_scope do explanation doc_helper.description_for(:update) do_request data: form_data expect(response_status).to eq(200), invalid_status_detail end end delete '/api/v2/contacts/:contact_id/people/:person_id/linkedin_accounts/:id' do doc_helper.insert_documentation_for(action: :delete, context: self) example doc_helper.title_for(:delete), document: doc_helper.document_scope do explanation doc_helper.description_for(:delete) do_request expect(response_status).to eq(204), invalid_status_detail end end end end
chuckmersereau/api_practice
app/services/account_list/destroyer.rb
# . . . # _ . . ( # (_) . . . # . ____.--^. # . /: / | + . . # /: `--=--' . . # LS /: __[\==`-.___ * . # /__|\ _~~~~~~ ~~--..__ . . # \ \|::::|-----.....___|~--. . # \ _\_~~~~~-----:|:::______//---...___ # . [\ \ __ -- \ ~ \_ ~~~===------==-...____ # [============================================================- # / __/__ -- /__ -- /____....----''''~~~~ . # * / / == ____....=---='''~~~~ . # /____....--=-''':~~~~ . . # . ~--~ # . . . # . . + # . + . <=> # . . . # . * . * ` - class AccountList::Destroyer def initialize(account_list_id) @account_list = AccountList.find(account_list_id) end def destroy! destroy_sync_associations # Destroy the sync associations first to prevent syncing to external services. @account_list.account_list_coaches.destroy_all @account_list.account_list_users.destroy_all @account_list.designation_accounts.each(&:destroy) @account_list.designation_profiles.destroy_all @account_list.imports.destroy_all @account_list.appeals.destroy_all @account_list.account_list_entries.delete_all @account_list.account_list_invites.delete_all @account_list.company_partnerships.delete_all @account_list.notification_preferences.delete_all delete_activities delete_people delete_contacts @account_list.reload @account_list.unsafe_destroy end private def destroy_sync_associations @account_list.google_integrations.each(&:destroy!) @account_list.mail_chimp_account&.destroy! @account_list.pls_account&.destroy! @account_list.prayer_letters_account&.destroy! end def delete_activities activities = @account_list.activities.to_a ActsAsTaggableOn::Tagging.where(taggable: activities).delete_all ActivityContact.where(activity: activities).delete_all ActivityComment.where(activity: activities).delete_all GoogleEmailActivity.where(activity: activities).delete_all Activity.where(id: activities.collect(&:id)).delete_all end def delete_people people = @account_list.people.to_a Person::GoogleAccount.where(person: people).destroy_all Person::OrganizationAccount.where(person: people).destroy_all Picture.where(picture_of: people).destroy_all ActivityComment.where(person: people).destroy_all EmailAddress.where(person: people).delete_all PhoneNumber.where(person: people).delete_all FamilyRelationship.where(person: people).delete_all CompanyPosition.where(person: people).delete_all Person::TwitterAccount.where(person: people).delete_all Person::FacebookAccount.where(person: people).delete_all Person::LinkedinAccount.where(person: people).delete_all Person::Website.where(person: people).delete_all Person::KeyAccount.where(person: people).delete_all ContactPerson.where(person: people).delete_all Message.where(from_id: people).delete_all Message.where(to_id: people).delete_all Person.where(id: people.collect(&:id)).delete_all end def delete_contacts contacts = @account_list.contacts Address.where(addressable: contacts).delete_all ActsAsTaggableOn::Tagging.where(taggable: contacts).delete_all # TODO: delete has_attributes_history ContactDonorAccount.where(contact: contacts).delete_all ContactPerson.where(contact: contacts).delete_all ContactReferral.where(referred_by: contacts).delete_all ContactReferral.where(referred_to: contacts).delete_all ActivityContact.where(contact: contacts).delete_all Notification.where(contact: contacts).delete_all Appeal::ExcludedAppealContact.where(contact: contacts).delete_all Contact.where(id: contacts.collect(&:id)).delete_all end end
chuckmersereau/api_practice
spec/factories/tasks.rb
<filename>spec/factories/tasks.rb FactoryBot.define do factory :task do association :account_list starred false location 'MyString' subject { "#{activity_type} #{Faker::Name.name}" } start_at '2012-03-08 14:59:46' activity_type 'Call' result nil completed_at nil trait :complete do completed true completed_at { Time.current } end trait :incomplete do completed false end trait :overdue do incomplete yesterday end trait :today do start_at { Time.current.beginning_of_day } end trait :tomorrow do start_at { (Date.current + 1.day).beginning_of_day } end trait :yesterday do start_at { (Time.current - 1.day).end_of_day } end Task::TASK_ACTIVITIES.each do |activity_type| trait_type = activity_type.parameterize.underscore.to_sym trait trait_type do activity_type activity_type end end trait :no_type do activity_type nil end end end
chuckmersereau/api_practice
app/models/notification_type/missing_address_in_newsletter.rb
<filename>app/models/notification_type/missing_address_in_newsletter.rb<gh_stars>0 class NotificationType::MissingAddressInNewsletter < NotificationType::MissingContactInfo def missing_info_filter(contacts) contacts.where(send_newsletter: %w(Both Physical)) .joins('LEFT JOIN addresses '\ "ON addresses.addressable_type = 'Contact' "\ 'AND addresses.addressable_id = contacts.id '\ "AND (addresses.historic = 'f' OR addresses.historic IS NULL)"\ "AND addresses.deleted = 'f'") .where(addresses: { id: nil }) end def task_description_template(_notification = nil) _('%{contact_name} is on the physical newsletter but lacks a current mailing address.') end end
chuckmersereau/api_practice
app/services/tnt_import/contacts_import.rb
class TntImport::ContactsImport def initialize(import, designation_profile, xml) @import = import @account_list = import.account_list @override = import.override? @tags_for_all = Array.wrap(import.tags) @designation_profile = designation_profile @xml = xml @xml_tables = xml.tables end def import_contacts donors_by_tnt_id = donor_accounts_by_tnt_contact_id contact_id_by_tnt_contact_id = {} @xml_tables['Contact'].each do |row| tnt_id = row['id'] tags = all_tags_for_tnt_contact_id(tnt_id) donor_accounts = donors_by_tnt_id[tnt_id] contact = import_contact(row, tags.compact, donor_accounts) contact_id_by_tnt_contact_id[tnt_id] = contact.id if contact.id end contact_id_by_tnt_contact_id end private def all_tags_for_tnt_contact_id(tnt_id) (@tags_for_all + group_tags_for_tnt_contact_id(tnt_id) + contact_tags_for_tnt_contact_id(tnt_id)).uniq end def group_tags_for_tnt_contact_id(tnt_id) @group_tags_by_tnt_contact_id ||= TntImport::GroupTagsLoader.tags_by_tnt_contact_id(@xml) Array.wrap(@group_tags_by_tnt_contact_id[tnt_id]) end def contact_tags_for_tnt_contact_id(tnt_id) @contact_tags_for_tnt_contact_id ||= TntImport::ContactTagsLoader.new(@xml).tags_by_tnt_contact_id Array.wrap(@contact_tags_for_tnt_contact_id[tnt_id]) end def import_contact(row, tags, donor_accounts) TntImport::ContactImport.new(@import, tags, donor_accounts, @xml) .import_contact(row) end def donor_accounts_by_tnt_contact_id @donor_accounts_by_contact_id ||= TntImport::DonorAccountsImport.new(@xml, orgs_by_tnt_id).import end def orgs_by_tnt_id TntImport::OrgsFinder .orgs_by_tnt_id(@xml, @designation_profile.try(:organization)) end end
chuckmersereau/api_practice
db/migrate/20150226131119_make_appeal_contacts_unique.rb
class MakeAppealContactsUnique < ActiveRecord::Migration def change Appeal.find_each do |appeal| contact_ids_so_far = Set.new appeal.appeal_contacts.each do |appeal_contact| if contact_ids_so_far.include?(appeal_contact.contact_id) appeal_contact.destroy else contact_ids_so_far << appeal_contact.contact_id end end end remove_index :appeal_contacts, [:appeal_id, :contact_id] add_index :appeal_contacts, [:appeal_id, :contact_id], :unique => true end end
chuckmersereau/api_practice
app/mailers/run_once_mailer.rb
<gh_stars>0 # here's a great place class RunOnceMailer < ApplicationMailer layout 'inky', except: :gdpr_unsubscribes def fix_newsletter_status(emails, fixed_count, account_list_name) @fixed_count = fixed_count @account_list_name = account_list_name mail to: emails, subject: 'MPDX - Mailchimp Bug Update' end def new_mailchimp_list(emails, fixed_count, account_list_name, mc_list_url) @fixed_count = fixed_count @account_list_name = account_list_name @mc_list_url = mc_list_url mail to: emails, subject: 'MPDX - Mailchimp Bug Update' end def gdpr_unsubscribes(to, account_list_name, unsubscribe_details) @account_list_name = account_list_name @unsubscribe = unsubscribe_details @url = WebRouter.person_url(Person.find(@unsubscribe[:person_id]), Contact.find(@unsubscribe[:contact_id])) mail to: to, from: '<NAME> <<EMAIL>>', reply_to: '<EMAIL>', subject: '[Action Required] Important Message About Some Of Your MPDX Contacts' end end
chuckmersereau/api_practice
db/migrate/20160429175451_create_currency_aliases.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 class CreateCurrencyAliases < ActiveRecord::Migration def change create_table :currency_aliases do |t| t.string :alias_code, null: false t.string :rate_api_code, null: false t.decimal :ratio, null: false t.timestamps null: false end end end
chuckmersereau/api_practice
spec/factories/questions.rb
FactoryBot.define do factory :question do id 1 question "MyText" end end
chuckmersereau/api_practice
app/services/contact/filter/primary_address.rb
class Contact::Filter::PrimaryAddress < Contact::Filter::Base def execute_query(contacts, filters) case filters[:primary_address].to_s when 'primary' contacts.primary_addresses when 'active' contacts.non_historical_addresses when 'inactive' contacts.historical_addresses else contacts end end def title _('Address Type') end def parent _('Contact Location') end def type 'multiselect' end def default_options [] end def default_selection 'primary, null' end def custom_options [ { name: _('Primary'), id: 'primary' }, { name: _('Active'), id: 'active' }, { name: _('Inactive'), id: 'inactive' }, { name: _('All'), id: 'null' } ] end def valid_filters?(filters) %w(primary active inactive).include?(filters[:primary_address]) end end
chuckmersereau/api_practice
spec/acceptance/api/v2/account_lists/imports_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Account Lists > Imports' do include_context :json_headers documentation_scope = :account_lists_api_imports 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 attrs = { account_list_id: account_list.id, user_id: user.id, source_account_id: fb_account.id } attributes_for(:import).merge(attrs) end let(:form_data) { build_data(new_import) } 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 before do stub_request(:get, "https://graph.facebook.com/#{fb_account.remote_id}/friends?access_token=#{fb_account.token}") .to_return(body: '{"data": [{"name": "<NAME>","id": "120581"}]}') spouse_expected_response = '{"id": "120581", "first_name": "John", "last_name": "Doe", '\ '"relationship_status": "Married", "significant_other":{"id":"120582"}}' stub_request(:get, "https://graph.facebook.com/120581?access_token=#{fb_account.token}") .to_return(body: spouse_expected_response) stub_request(:get, "https://graph.facebook.com/120582?access_token=#{fb_account.token}") .to_return(body: '{"id": "120582", "first_name": "Jane", "last_name": "Doe"}') end context 'authorized user' do before { api_login(user) } get '/api/v2/account_lists/:account_list_id/imports/:id' do with_options scope: [:data, :attributes] do 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', 'Only applicable to CSV Imports', type: 'Object' response_field 'file_headers', 'Only applicable to CSV Imports', type: 'Object' response_field 'file_constants', 'Only applicable to CSV Imports', type: 'Object' response_field 'file_constants_mappings', 'Only applicable to CSV Imports', type: 'Object' response_field 'groups', 'Groups', type: 'String' response_field 'group_tags', 'Group Tags', type: 'String' response_field 'import_by_group', 'Import by Group', type: 'Boolean' response_field 'override', 'Override', type: 'Boolean' response_field 'source', 'Source', type: 'String' response_field 'source_account_id', 'Source Account ID', type: 'Number' response_field 'tag_list', 'Comma delimited list of Tags', type: 'String' response_field 'user_id', 'User ID', type: 'Number' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end example 'Import [GET]', document: documentation_scope do explanation 'Creates a new Import associated with the Account List. This endpoint accepts ' \ 'a file to be uploaded using Content-Type "multipart/form-data", this makes ' \ 'the endpoint unique in that it does not only accept 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 check_resource(['relationships']) expect(response_status).to eq 200 end end end end
chuckmersereau/api_practice
db/migrate/20150814142759_create_mail_chimp_members.rb
<filename>db/migrate/20150814142759_create_mail_chimp_members.rb class CreateMailChimpMembers < ActiveRecord::Migration def change create_table :mail_chimp_members do |t| t.integer :mail_chimp_account_id, null: false t.string :list_id, null: false t.string :email, null: false t.string :status t.string :greeting t.string :first_name t.string :last_name t.timestamps null: false end add_index :mail_chimp_members, :mail_chimp_account_id add_index :mail_chimp_members, :list_id add_index :mail_chimp_members, :email add_index :mail_chimp_members, [:mail_chimp_account_id, :list_id, :email], unique: true, name: :mail_chimp_members_email_list_account_uniq end end
chuckmersereau/api_practice
spec/models/help_request_spec.rb
require 'rails_helper' RSpec.describe HelpRequest, type: :model do end
chuckmersereau/api_practice
app/controllers/api/v2/contacts/people/linkedin_accounts_controller.rb
class Api::V2::Contacts::People::LinkedinAccountsController < Api::V2Controller def index authorize load_person, :show? load_linkedin_accounts render json: @linkedin_accounts.preload_valid_associations(include_associations), meta: meta_hash(@linkedin_accounts), include: include_params, fields: field_params end def show load_linkedin_account authorize_linkedin_account render_linkedin_account end def create persist_linkedin_account end def update load_linkedin_account authorize_linkedin_account persist_linkedin_account end def destroy load_linkedin_account authorize_linkedin_account destroy_linkedin_account end private def destroy_linkedin_account @linkedin_account.destroy head :no_content end def load_linkedin_accounts @linkedin_accounts = linkedin_account_scope.where(filter_params) .reorder(sorting_param) .page(page_number_param) .per(per_page_param) end def load_linkedin_account @linkedin_account ||= linkedin_account_scope.find(params[:id]) end def authorize_linkedin_account authorize @linkedin_account end def render_linkedin_account render json: @linkedin_account, status: success_status, include: include_params, fields: field_params end def persist_linkedin_account build_linkedin_account authorize_linkedin_account if save_linkedin_account render_linkedin_account else render_with_resource_errors(@linkedin_account) end end def build_linkedin_account @linkedin_account ||= linkedin_account_scope.build @linkedin_account.assign_attributes(linkedin_account_params) end def save_linkedin_account @linkedin_account.save(context: persistence_context) end def linkedin_account_params params.require(:linkedin_account) .permit(Person::LinkedinAccount::PERMITTED_ATTRIBUTES) end def linkedin_account_scope load_person.linkedin_accounts end def load_person @person ||= load_contact.people.find(params[:person_id]) end def load_contact @contact ||= Contact.find(params[:contact_id]) end def pundit_user action_name == 'index' ? PunditContext.new(current_user, contact: load_contact) : current_user end end
chuckmersereau/api_practice
spec/factories/person_websites.rb
FactoryBot.define do factory :website, class: 'Person::Website' do association :person url { Faker::Internet.url } primary true end end
chuckmersereau/api_practice
db/migrate/20140821112305_create_appeal_contacts.rb
class CreateAppealContacts < ActiveRecord::Migration def change create_table :appeal_contacts do |t| t.belongs_to :appeal t.belongs_to :contact t.timestamps null: false end add_index :appeal_contacts, [:appeal_id, :contact_id] add_index :appeal_contacts, :contact_id end end
chuckmersereau/api_practice
spec/requests/api/v2/batch_request_spec.rb
<filename>spec/requests/api/v2/batch_request_spec.rb require 'rails_helper' RSpec.describe 'Batch Requests', type: :request do before { api_login(user) } let(:batch_endpoint) { '/api/v2/batch' } let(:headers) { { 'CONTENT_TYPE' => 'application/vnd.api+json', 'ACCEPT' => '' } } let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:get_current_user) { { method: 'GET', path: api_v2_user_path } } let(:get_constants) { { method: 'GET', path: api_v2_constants_path } } let(:contact_post_data) do { data: { type: :contacts, id: SecureRandom.uuid, attributes: attributes_for(:contact, name: '<NAME>'), relationships: { account_list: { data: { type: 'account_lists', id: account_list.id } } } } }.to_json end let(:create_contact) { { method: 'POST', path: api_v2_contacts_path, body: contact_post_data } } let(:failing_contact_post_data) do { data: { type: :contacts, id: SecureRandom.uuid, attributes: attributes_for(:contact, name: '<NAME>'), relationships: { account_list: { data: { type: 'account_lists', id: create(:account_list).id } } } } }.to_json end let(:failing_create_contact) { { method: 'POST', path: api_v2_contacts_path, body: failing_contact_post_data } } context 'with all passing requests' do let(:requests) { [get_current_user, get_constants, create_contact] } let(:batch_request) { { requests: requests }.to_json } it 'returns 200 ok' do post batch_endpoint, batch_request, headers expect(response.status).to eq(200), invalid_status_detail end it 'returns a json array with all the responses' do post batch_endpoint, batch_request, headers expect(json_response).to be_an(Array) expect(json_response.length).to eq(requests.length) expect(json_response[0]).to include('status', 'headers', 'body') end end context 'with a failing request' do let(:requests) { [get_current_user, failing_create_contact, get_constants] } let(:batch_request) { { requests: requests }.to_json } it 'returns a 200 ok' do post batch_endpoint, batch_request, headers expect(response.status).to eq(200), invalid_status_detail end it 'returns all the responses' do post batch_endpoint, batch_request, headers expect(json_response.length).to eq(requests.length) end end context 'with a failing request, with on_error set to ABORT' do let(:requests) { [get_current_user, failing_create_contact, get_constants] } let(:batch_request) { { requests: requests, on_error: 'ABORT' }.to_json } it 'returns an error status of whatever the failing request failed with' do post batch_endpoint, batch_request, headers expect(response.status).to_not eq(200), invalid_status_detail expect(response.status).to eq(json_response.last['status'].to_i) end it 'returns the responses up to and including the failed request, but no more' do post batch_endpoint, batch_request, headers expect(json_response.length).to eq(2) end end context 'with over 100 requests' do let(:requests) { [get_current_user] * 101 } let(:batch_request) { { requests: requests }.to_json } it 'returns a rate limit error' do post batch_endpoint, batch_request, headers expect(response.status).to eq(429), invalid_status_detail end end context 'with a malformed request inside the batch request' do let(:bad_request) { { method: 'OPTIONS', path: '/api/v2/user' } } let(:batch_request) { { requests: [get_current_user, bad_request] }.to_json } it 'returns a 200 ok' do post batch_endpoint, batch_request, headers expect(response.status).to eq(200), invalid_status_detail end it 'returns an error for that specific request' do post batch_endpoint, batch_request, headers expect(json_response[1]['status']).to eq(405), invalid_status_detail end end context 'with a request to a bulk endpoint inside the batch request' do let(:bulk_request) { { method: 'POST', path: '/api/v2/contacts/bulk' } } let(:batch_request) { { requests: [get_current_user, bulk_request] }.to_json } it 'returns a 200 ok' do post batch_endpoint, batch_request, headers expect(response.status).to eq(200), invalid_status_detail end it 'returns an error for that specific request' do post batch_endpoint, batch_request, headers expect(json_response[1]['status']).to eq(403), invalid_status_detail end end context 'with a malformed batch request' do it 'returns an error explaining how to use the batch endpoint' do post batch_endpoint, '', headers expect(response.status).to eq(400), invalid_status_detail expect(json_response).to include('errors') end end end
chuckmersereau/api_practice
spec/factories/weeklies.rb
FactoryBot.define do factory :weekly do end end
chuckmersereau/api_practice
spec/models/person/google_account_spec.rb
require 'rails_helper' describe Person::GoogleAccount do describe 'create from auth' do it 'should create an account linked to a person' do auth_hash = Hashie::Mash.new(uid: '1', info: { email: '<EMAIL>' }, credentials: { token: 'a', refresh_token: 'b', expires: true, expires_at: Time.now.to_i + 100 }) person = FactoryBot.create(:person) expect do @account = Person::GoogleAccount.find_or_create_from_auth(auth_hash, person) end.to change(Person::GoogleAccount, :count).from(0).to(1) expect(person.google_accounts).to include(@account) end end describe 'update from auth' do it 'should update an account that already exists' do auth_hash = Hashie::Mash.new(uid: '1', info: { email: '<EMAIL>' }, credentials: { token: 'a', refresh_token: 'b', expires: true, expires_at: Time.now.to_i + 100 }) person = FactoryBot.create(:person) Person::GoogleAccount.find_or_create_from_auth(auth_hash, person) expect do @account = Person::GoogleAccount.find_or_create_from_auth(auth_hash.merge!(credentials: { refresh_token: 'c' }), person) end.to_not change(Person::GoogleAccount, :count) expect(@account.refresh_token).to eq('c') end end it 'should return email for to_s' do account = Person::GoogleAccount.new(email: '<EMAIL>') expect(account.to_s).to eq('<EMAIL>') end describe '#contact_groups' do subject { create(:google_account) } it 'calls Person::GoogleAccount::ContactGroup' do expect(subject).to receive(:contacts_api_user).and_return(OpenStruct.new(groups: [])) expect(Person::GoogleAccount::ContactGroup).to receive(:from_groups) subject.contact_groups end it 'returns an empty array if the refresh token is invalid' do expect(subject).to receive(:contacts_api_user).and_raise(Person::GoogleAccount::MissingRefreshToken) expect(Person::GoogleAccount::ContactGroup).to_not receive(:from_groups) expect(subject.contact_groups).to eq([]) end end describe '#token_expired?' do context 'expires_at is in the future' do subject { build(:google_account, expires_at: 1.minute.from_now) } it 'does not attempt to refresh token' do expect(subject).to_not receive(:refresh_token!) expect(subject.token_expired?).to eq false end it 'returns false' do expect(subject.token_expired?).to eq false end end context 'expires_at is in the past' do subject { build(:google_account, expires_at: 1.minute.ago) } it 'attempts to refresh token' do expect(subject).to receive(:refresh_token!).and_return(true) expect(subject.token_expired?).to eq false end it 'returns true' do expect(subject).to receive(:refresh_token!).and_return(false) expect(subject.token_expired?).to eq true end end context 'expires_at is nil' do subject { build(:google_account, expires_at: nil) } it 'attempts to refresh token' do expect(subject).to receive(:refresh_token!).and_return(true) expect(subject.token_expired?).to eq false end it 'returns true' do expect(subject).to receive(:refresh_token!).and_return(false) expect(subject.token_expired?).to eq true end end end describe '#token_failure?' do it 'returns true if notified_failure' do expect(build(:google_account, notified_failure: true).token_failure?).to eq(true) end it 'returns false if not notified_failure' do expect(build(:google_account, notified_failure: false).token_failure?).to eq(false) expect(build(:google_account, notified_failure: nil).token_failure?).to eq(false) end end describe '#refresh_token!' do subject { build(:google_account) } before do ENV['GOOGLE_KEY'] = 'key' ENV['GOOGLE_SECRET'] = 'secret' end it 'returns false and alerts to a refresh needed if refresh token blank' do subject.refresh_token = nil expect(subject).to receive(:needs_refresh) expect(subject.refresh_token!).to be false end it 'updates the token and expiration on success' do stub_refresh_request('{"access_token":"NewToken"}') expect(subject.refresh_token!).to be_truthy expect(subject.new_record?).to be_falsey subject.reload expect(subject.token).to eq 'NewToken' expect(subject.expires_at).to be > 58.minutes.from_now end it 'returns false and alerts refresh needed on invalid_grant error' do stub_refresh_request('{"error":"invalid_grant"}', 403) expect(subject).to receive(:needs_refresh) expect(Rollbar).to_not receive(:error) expect(subject.refresh_token!).to be_falsey end it 'returns false and alerts refresh needed on invalid_client error' do stub_refresh_request('{"error":"invalid_client"}', 403) expect(subject).to receive(:needs_refresh) expect(Rollbar).to_not receive(:error) expect(subject.refresh_token!).to be_falsey end it 'returns false and does not alert refresh needed on an unknown error' do stub_refresh_request('{"error":"internal err"}', 500) expect(subject).to_not receive(:needs_refresh) expect(Rollbar).to receive(:error) expect(subject.refresh_token!).to be_falsey end def stub_refresh_request(body, status = 200) stub_request(:post, 'https://accounts.google.com/o/oauth2/token') .with(body: { 'client_id' => 'key', 'client_secret' => 'secret', 'grant_type' => 'refresh_token', 'refresh_token' => '<PASSWORD>' }) .to_return(body: body, status: status) end end end
chuckmersereau/api_practice
spec/lib/json_api_service/resource_lookup_spec.rb
<reponame>chuckmersereau/api_practice require 'spec_helper' require 'json_api_service/resource_lookup' require 'support/json_api_service_helper' module JsonApiService RSpec.describe ResourceLookup, type: :service do include JsonApiServiceHelpers let(:custom_references) do { mock_facebook_accounts: 'MockPerson::FacebookAccount' } end describe '#custom_references' do context 'by default' do let(:lookup) { ResourceLookup.new } it 'is empty' do expect(lookup.custom_references).to be_empty end end context 'when initialized with references' do let(:lookup) { ResourceLookup.new(custom_references) } it 'uses those references' do expect(lookup.custom_references).to eq custom_references end end end describe '#find' do let(:lookup) { ResourceLookup.new(custom_references) } context 'with a singular type' do let(:type) { 'mock_contact' } it 'returns the correct Resource' do expect(lookup.find(type)).to eq MockContact end end context 'with a pluralized type' do let(:type) { 'mock_contacts' } it 'returns the correct Resource' do expect(lookup.find(type)).to eq MockContact end end context 'with a type that requires a custom reference' do let(:type) { 'mock_facebook_accounts' } it 'returns the correct Resource' do expect(lookup.find(type)).to eq MockPerson::FacebookAccount end end end describe '#find_type_by_class' do let(:lookup) { ResourceLookup.new(custom_references) } context 'nil argument' do it 'returns nil' do expect(lookup.find_type_by_class(nil)).to eq nil end end context 'with a type that is not a custom reference' do it 'returns the correct Resource' do expect(lookup.find_type_by_class(MockContact)).to eq :mock_contacts end end context 'with a type that requires a custom reference' do it 'returns the correct Resource' do expect(lookup.find_type_by_class(MockPerson::FacebookAccount)).to eq :mock_facebook_accounts end end end end end
chuckmersereau/api_practice
spec/services/contact/duplicate_pairs_finder_spec.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 require 'rails_helper' describe Contact::DuplicatePairsFinder do let!(:account_list) { create(:user_with_account).account_lists.order(:created_at).first } let!(:unique_contact_one) do create(:contact, name: 'This contact should have no duplicates whatsoever', account_list: account_list).tap do |contact| contact.donor_accounts << create(:donor_account, account_number: '12134908719187349182374165192734283') end end let!(:unique_contact_two) do create(:contact, name: 'Another contact that is totally a special snow flake', account_list: account_list).tap do |contact| contact.donor_accounts << create(:donor_account, account_number: '08762912346125073571094871239487123') end end def build_finder Contact::DuplicatePairsFinder.new(account_list) end it 'deletes pairs with missing records' do valid_pair = DuplicateRecordPair.create!( account_list: account_list, reason: 'Test', record_one: create(:contact, name: '<NAME>', account_list: account_list), record_two: create(:contact, name: '<NAME>', account_list: account_list) ) contact = create(:contact, name: '<NAME>', account_list: account_list) pair_missing_record_one = DuplicateRecordPair.new( account_list: account_list, reason: 'Test', record_one_id: SecureRandom.uuid, record_one_type: 'Contact', record_two_id: contact.id, record_two_type: 'Contact' ) pair_missing_record_one.save(validate: false) pair_missing_record_two = DuplicateRecordPair.new( account_list: account_list, reason: 'Test', record_one_id: contact.id, record_one_type: 'Contact', record_two_id: SecureRandom.uuid, record_two_type: 'Contact' ) pair_missing_record_two.save(validate: false) expect { build_finder.find_and_save }.to change { DuplicateRecordPair.count }.by(-2) expect(DuplicateRecordPair.exists?(pair_missing_record_one.id)).to eq(false) expect(DuplicateRecordPair.exists?(pair_missing_record_two.id)).to eq(false) expect(DuplicateRecordPair.exists?(valid_pair.id)).to eq(true) end it 'does not find duplicates from a different account list' do create(:contact, name: '<NAME>') create(:contact, name: '<NAME>', account_list: account_list) expect do expect(build_finder.find_and_save).to eq([]) end.to_not change { DuplicateRecordPair.count }.from(0) end context 'contacts with the same original name' do let!(:contact_one) { create(:contact, name: '<NAME>', account_list: account_list) } let!(:contact_two) { create(:contact, name: '<NAME>', account_list: account_list) } it 'finds and saves the DuplicateRecordPair' do expect { build_finder.find_and_save }.to change { DuplicateRecordPair.type('Contact').where(reason: 'Similar names', record_one_id: contact_one.id, record_two_id: contact_two.id).count }.from(0).to(1) expect(DuplicateRecordPair.count).to eq(1) end end context 'contacts with the same rebuilt name' do let!(:contact_one) { create(:contact, name: '<NAME>', account_list: account_list) } let!(:contact_two) { create(:contact, name: '<NAME>', account_list: account_list) } it 'finds and saves the DuplicateRecordPair' do expect { build_finder.find_and_save }.to change { DuplicateRecordPair.where(reason: 'Similar names', record_one_id: contact_one.id, record_two_id: contact_two.id).count }.from(0).to(1) expect(DuplicateRecordPair.count).to eq(1) end end context 'contacts with the same rebuilt name that appear to be unhuman' do let!(:contact_one) { create(:contact, name: "big\n church", account_list: account_list) } let!(:contact_two) { create(:contact, name: 'BIG Church ', account_list: account_list) } it 'finds and saves the DuplicateRecordPair' do expect { build_finder.find_and_save }.to change { DuplicateRecordPair.where(reason: 'Similar names', record_one_id: contact_one.id, record_two_id: contact_two.id).count }.from(0).to(1) expect(DuplicateRecordPair.count).to eq(1) end end context 'contacts where a single name and a couple primary name match' do let!(:contact_one) { create(:contact, name: '<NAME> and Jane', account_list: account_list) } let!(:contact_two) { create(:contact, name: '<NAME>', account_list: account_list) } it 'finds and saves the DuplicateRecordPair' do expect { build_finder.find_and_save }.to change { DuplicateRecordPair.where(reason: 'Similar names', record_one_id: contact_one.id, record_two_id: contact_two.id).count }.from(0).to(1) expect(DuplicateRecordPair.count).to eq(1) end end context 'contacts couple primary name match but spouse does not' do let!(:contact_one) { create(:contact, name: '<NAME> and Jane', account_list: account_list) } let!(:contact_two) { create(:contact, name: '<NAME> and Sarah', account_list: account_list) } it 'does not find any pairs' do expect do expect(build_finder.find_and_save).to eq([]) end.to_not change { DuplicateRecordPair.count }.from(0) end end context 'contacts where a single name and a couple spouse name match' do let!(:contact_one) { create(:contact, name: '<NAME> and Jane', account_list: account_list) } let!(:contact_two) { create(:contact, name: '<NAME>', account_list: account_list) } it 'finds and saves the DuplicateRecordPair' do expect { build_finder.find_and_save }.to change { DuplicateRecordPair.where(reason: 'Similar names', record_one_id: contact_one.id, record_two_id: contact_two.id).count }.from(0).to(1) expect(DuplicateRecordPair.count).to eq(1) end end context 'contacts couple spouse name match but primary does not' do let!(:contact_one) { create(:contact, name: '<NAME> and Jane', account_list: account_list) } let!(:contact_two) { create(:contact, name: '<NAME> and Jane', account_list: account_list) } it 'does not find any pairs' do expect do expect(build_finder.find_and_save).to eq([]) end.to_not change { DuplicateRecordPair.count }.from(0) end end context 'contacts with the same donor account number' do let!(:contact_one) do create( :contact, name: 'John', account_list: account_list ).tap { |contact| contact.donor_accounts << create(:donor_account, account_number: '1234') } end let!(:contact_two) do create( :contact, name: 'Jane', account_list: account_list ).tap { |contact| contact.donor_accounts << create(:donor_account, account_number: '1234') } end it 'finds and saves the DuplicateRecordPair' do expect { build_finder.find_and_save }.to change { DuplicateRecordPair.where(reason: 'Same donor account number', record_one_id: contact_one.id, record_two_id: contact_two.id).count }.from(0).to(1) expect(DuplicateRecordPair.count).to eq(1) end end context 'contacts names contain bad whitespace' do let!(:contact_one) { create(:contact, name: "\n<NAME>\r", account_list: account_list) } let!(:contact_two) { create(:contact, name: 'Doe, John', account_list: account_list) } it 'finds and saves the DuplicateRecordPair' do expect { build_finder.find_and_save }.to change { DuplicateRecordPair.where(reason: 'Similar names', record_one_id: contact_one.id, record_two_id: contact_two.id).count }.from(0).to(1) expect(DuplicateRecordPair.count).to eq(1) end end it 'only returns new pairs' do create(:contact, name: '<NAME>', account_list: account_list) create(:contact, name: '<NAME>', account_list: account_list) create(:contact, name: '<NAME>', account_list: account_list) create(:contact, name: '<NAME>', account_list: account_list) expect do expect(build_finder.find_and_save.size).to eq(2) end.to change { DuplicateRecordPair.count }.from(0).to(2) expect do expect(build_finder.find_and_save.size).to eq(0) end.to_not change { DuplicateRecordPair.count }.from(2) DuplicateRecordPair.first.update!(ignore: true) expect do expect(build_finder.find_and_save.size).to eq(0) end.to_not change { DuplicateRecordPair.count }.from(2) create(:contact, name: '<NAME>', account_list: account_list) create(:contact, name: '<NAME>', account_list: account_list) expect do expect(build_finder.find_and_save.size).to eq(1) end.to change { DuplicateRecordPair.count }.from(2).to(3) end end
chuckmersereau/api_practice
app/models/notification_type/started_giving.rb
<reponame>chuckmersereau/api_practice<filename>app/models/notification_type/started_giving.rb<gh_stars>0 class NotificationType::StartedGiving < NotificationType def check(account_list) notifications = [] account_list.contacts.where(account_list_id: account_list.id).financial_partners.each do |contact| next if Notification.active.exists?(contact_id: contact.id, notification_type_id: id) # update pledge received in case there are past donations orig_pledge_received = contact.pledge_received? donation = last_donation_within_pledge_freq(contact) contact.pledge_received = true if donation.present? && contact.pledge_amount == donation.amount contact.save # If they just gave their first gift, note it as such next unless !orig_pledge_received && donation && !contact.donations.where('donation_date < ?', 2.weeks.ago).exists? # update pledge amount contact.pledge_amount = donation.amount if contact.pledge_amount.blank? contact.pledge_currency = donation.currency if contact.pledge_currency != donation.currency # recheck pledge_received in case pledge_amount was blank before contact.pledge_received = true if contact.pledge_amount == donation.amount contact.pledge_frequency ||= 1 # default to monthly pledge if nil contact.save notification = contact.notifications.create!(notification_type_id: id, event_date: Date.today) notifications << notification end notifications end def task_description_template(_notification = nil) _('%{contact_name} just gave their first gift. Send them a Thank You.') end private def last_donation_within_pledge_freq(contact) # Default past period to 2 weeks so we can set the pledge info above when # the first gift comes for a partner with no pledge info set. past_pledge_period_start = pledge_freq_months_ago(contact) || 2.weeks.ago # Donation sort order is by donation_date descending by default contact.donations.find_by('donation_date > ?', past_pledge_period_start) end def pledge_freq_months_ago(contact) return unless contact.pledge_frequency.present? if contact.pledge_frequency < 1 (contact.pledge_frequency * 30).days.ago else contact.pledge_frequency.to_i.months.ago end end end
chuckmersereau/api_practice
app/workers/organizations_from_csv_url_worker.rb
class OrganizationsFromCsvUrlWorker include Sidekiq::Worker sidekiq_options queue: :api_organizations_from_csv_url_worker, unique: :until_executed def perform(url) organizations_csv = open(url).read.unpack('C*').pack('U*') CSV.new(organizations_csv, headers: :first_row).each do |line| name, url = line[0..1] next unless url.present? OrganizationFromQueryUrlWorker.perform_async(name, url) end end end
chuckmersereau/api_practice
spec/models/person/twitter_account_spec.rb
<gh_stars>0 require 'rails_helper' describe Person::TwitterAccount do let(:auth_hash) do Hashie::Mash.new(extra: { access_token: { params: { user_id: 5, screen_name: 'foo', oauth_token: 'a', oauth_token_secret: 'b' } } }) end describe 'create from auth' do it 'should create an account linked to a person' do person = FactoryBot.create(:person) expect do @account = Person::TwitterAccount.find_or_create_from_auth(auth_hash, person) end.to change(Person::TwitterAccount, :count).from(0).to(1) expect(person.twitter_accounts).to include(@account) end end describe 'update from auth' do it 'should update an account that already exists' do person = FactoryBot.create(:person) Person::TwitterAccount.find_or_create_from_auth(auth_hash, person) expect do @account = Person::TwitterAccount.find_or_create_from_auth(auth_hash, person) end.to_not change(Person::TwitterAccount, :count) end end it 'should return screen name for to_s' do account = Person::TwitterAccount.new(screen_name: 'Doe') expect(account.to_s).to eq('Doe') end end
chuckmersereau/api_practice
app/policies/user_policy.rb
<filename>app/policies/user_policy.rb class UserPolicy < ApplicationPolicy def destroy? resource != user && belongs_to_same_account_list? end def show? resource_owner? || belongs_to_same_account_list? end private def belongs_to_same_account_list? (user.account_lists.ids & resource.account_lists.ids).present? end def resource_owner? user == resource end end
chuckmersereau/api_practice
db/migrate/20170330210159_add_appeal_id_to_pledges.rb
<reponame>chuckmersereau/api_practice class AddAppealIdToPledges < ActiveRecord::Migration def change add_column :pledges, :appeal_id, :integer add_index :pledges, :appeal_id end end
chuckmersereau/api_practice
spec/workers/mail_chimp/campaign_logger_worker_spec.rb
require 'rails_helper' RSpec.describe MailChimp::CampaignLoggerWorker do let(:mail_chimp_account) { create(:mail_chimp_account) } it 'logs the campaign' do expect_any_instance_of(MailChimp::CampaignLogger).to receive(:log_sent_campaign).with(1, 'Subject') MailChimp::CampaignLoggerWorker.new.perform(mail_chimp_account.id, 1, 'Subject') end end
chuckmersereau/api_practice
app/workers/sidekiq_cron_worker.rb
<filename>app/workers/sidekiq_cron_worker.rb<gh_stars>0 class SidekiqCronWorker include Sidekiq::Worker sidekiq_options queue: :api_sidekiq_cron_worker, unique: :until_executed def perform(action) klass, method = action.split('.') klass.constantize.send(method.to_sym) end end
chuckmersereau/api_practice
db/migrate/20120312174302_remove_guid_from_person.rb
class RemoveGuidFromPerson < ActiveRecord::Migration def up remove_column :people, :guid add_column :people, :middle_name, :string end def down remove_column :people, :middle_name add_column :people, :guid, :string end end
chuckmersereau/api_practice
spec/services/contact/filter/name_like_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe Contact::Filter::NameLike do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact_one) { create(:contact, name: '<NAME>') } let!(:contact_two) { create(:contact, name: 'Name') } let!(:contact_three) { create(:contact) } describe '#config' do it 'does not support returning config' do expect(described_class.config([account_list])).to eq nil end end describe '#query' do let(:contacts) { Contact.all } context 'no filter params' do it 'returns nil' do expect(described_class.query(contacts, {}, nil)).to eq(nil) expect(described_class.query(contacts, { name_like: {} }, nil)).to eq(nil) expect(described_class.query(contacts, { name_like: [] }, nil)).to eq(nil) expect(described_class.query(contacts, { name_like: '' }, nil)).to eq(nil) end end context 'filter by contact name' do it 'returns only contacts that start with the search query' do expect(described_class.query(contacts, { name_like: 'First' }, nil).to_a).to eq [contact_one] expect(described_class.query(contacts, { name_like: 'Name' }, nil).to_a).to eq [contact_two] end end end end
chuckmersereau/api_practice
db/migrate/20170307220854_update_all_timestamp_columns_to_be_non_null.rb
<gh_stars>0 class UpdateAllTimestampColumnsToBeNonNull < ActiveRecord::Migration def up tables.each do |table| next unless model = model_for_table(table) columns(table).each do |column| next unless timestamp_column?(column) next unless allows_null_values?(column) say_with_time "Updating #{column.name} on #{table} to be NOT NULL" do affected_rows = set_null_values_to_current_timestamp!(model, column) change_column table, column.name, :datetime, null: false affected_rows end end end end def down raise ActiveRecord::IrreversibleMigration end private TIMESTAMP_COLUMN_NAMES = %w(created_at updated_at).freeze def model_for_table(table_name) models_by_table[table_name] end def timestamp_column?(column) column.name.in? TIMESTAMP_COLUMN_NAMES end def allows_null_values?(column) column.null end def models_by_table @models_by_table ||= fetch_and_build_models_by_table_name end def fetch_and_build_models_by_table_name Rails.application.eager_load! ActiveRecord::Base.descendants.each_with_object({}) do |klass, hash| hash[klass.table_name] = klass end end def set_null_values_to_current_timestamp!(model, column) query = column_is_null_query(column) # Ex: { created_at: nil } changeset = timestamp_changeset_for_column(column) # Ex: { created_at: DateTime.current } model.where(query).update_all(changeset) end def column_is_null_query(column) { "#{column.name}": nil } end def timestamp_changeset_for_column(column) { "#{column.name}": DateTime.current } end end
chuckmersereau/api_practice
spec/generators/graip/controller_generator_spec.rb
require 'rails_helper' require 'generators/graip/controller/controller_generator' RSpec.describe Graip::Generators::ControllerGenerator, type: :generator do destination Rails.root.join('tmp/generator_specs') before { prepare_destination } describe 'generated files' do before { run_generator ['Api/v2/EmailAddresses'] } describe 'the controller' do subject { file('app/controllers/api/v2/email_addresses_controller.rb') } it { is_expected.to exist } it { is_expected.to have_correct_syntax } it 'correctly generates the code' do example_code = fetch_example_controller spec_code = File.read(subject) expect(spec_code).to eq example_code end end describe 'the controller spec' do subject do filename = 'spec/controllers/api/v2/email_addresses_controller_spec.rb' file(filename) end it { is_expected.to exist } it { is_expected.to have_correct_syntax } it 'correctly generates the code' do example_code = fetch_example_controller_spec spec_code = File.read(subject) expect(spec_code).to eq example_code end end describe 'the acceptance spec' do subject { file('spec/acceptance/api/v2/email_addresses_spec.rb') } it { is_expected.to exist } it { is_expected.to have_correct_syntax } it 'correctly generates the code' do example_code = fetch_example_acceptance_spec spec_code = File.read(subject) expect(spec_code).to eq example_code end end end private def fetch_example_acceptance_spec File.read("#{support_files_root}/acceptance_spec.rb.example") end def fetch_example_controller File.read("#{support_files_root}/controller.rb.example") end def fetch_example_controller_spec File.read("#{support_files_root}/controller_spec.rb.example") end def support_files_root 'spec/support/generators/graip/controller' end end
chuckmersereau/api_practice
spec/workers/mail_chimp/members_import_worker_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe MailChimp::MembersImportWorker do let(:mail_chimp_account) { create(:mail_chimp_account) } let(:email) { '<EMAIL>' } # it 'starts the sync with primary list' do # expect_any_instance_of(MailChimp::Importer).to receive(:import_members_by_email).with([email]) # # MailChimp::MembersImportWorker.new.perform(mail_chimp_account.id, [email]) # end end
chuckmersereau/api_practice
spec/controllers/auth/provider/prayer_letters_accounts_controller_spec.rb
require 'rails_helper' describe Auth::Provider::PrayerLettersAccountsController, :auth, type: :controller do routes { Auth::Engine.routes } let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } before(:each) do auth_login(user) request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:prayer_letters] end context 'with no preexisting PrayerLettersAccount' do it 'should create a PrayerLettersAccount' do expect do get :create, nil, account_list_id: account_list_id end.to change(PrayerLettersAccount, :count).by(1) end end context 'with a preexisting PrayerLettersAccount' do let!(:prayer_letters_account) { create(:prayer_letters_account, account_list: account_list) } it 'should not create a PrayerLettersAccount' do expect do get :create, nil, account_list_id: account_list_id end.to_not change(PrayerLettersAccount, :count) end it 'should update the existing PrayerLettersAccount' do expect do get :create, nil, account_list_id: account_list_id prayer_letters_account.reload end.to change { prayer_letters_account.oauth2_token } end end end
chuckmersereau/api_practice
db/migrate/20140707182714_add_email_integration.rb
class AddEmailIntegration < ActiveRecord::Migration def change add_column :google_integrations, :email_integration, :boolean, null: false, default: false create_table :google_emails do |t| t.integer :google_account_id t.integer :google_email_id, limit: 8 t.timestamps null: false end create_table :google_email_activities do |t| t.integer :google_email_id t.integer :activity_id t.timestamps null: false end end end
chuckmersereau/api_practice
app/services/contact/filter/appeal.rb
<filename>app/services/contact/filter/appeal.rb<gh_stars>0 class Contact::Filter::Appeal < Contact::Filter::Base def execute_query(contacts, filters) appeal_filters = parse_list(filters[:appeal]) contacts = contacts.where(no_appeals: true) if appeal_filters.delete('no_appeals') contacts = contacts.joins(:appeals).where(appeals: { id: appeal_filters }).uniq if appeal_filters.present? contacts end def title _('Appeal') end def type 'multiselect' end def custom_options [{ name: _('-- Do not ask --'), id: 'no_appeals' }] + ::Appeal.select(:name, :id).where(account_list: account_lists).map do |appeal| { name: appeal.name, id: appeal.id } end end end
chuckmersereau/api_practice
app/services/tnt_import/tasks_import.rb
class TntImport::TasksImport include Concerns::TntImport::DateHelpers include Concerns::TntImport::AppealHelpers def initialize(import, contact_ids_by_tnt_contact_id, xml) @import = import @user = import.user @account_list = import.account_list @contact_ids_by_tnt_contact_id = contact_ids_by_tnt_contact_id @xml = xml @xml_tables = xml.tables end def import return unless xml_tables[xml_table_name].present? && xml_tables['TaskContact'].present? new_tasks = [] all_tasks = build_tasks contact_ids_with_new_tasks = xml_tables['TaskContact'].map do |contact_row| begin task, contact_id = create_task_for_contact!(contact_row, all_tasks) new_tasks << task contact_id rescue ActiveRecord::RecordInvalid nil end end update_contacts_task_counters!(contact_ids_with_new_tasks.compact) new_tasks end private attr_reader :xml_tables, :contact_ids_by_tnt_contact_id def subject(row) row['Description'] || TntImport::TntCodes.task_type(row['TaskTypeID']) end def build_tasks task_rows = xml_tables[xml_table_name].select { |row| TntImport::TntCodes.import_task_type?(row['TaskTypeID']) } task_rows.map { |r| build_task_from_row(r) } end def build_task_from_row(row) task = Retryable.retryable { @account_list.tasks.where(remote_id: row['id'], source: 'tnt').first_or_initialize } task.attributes = { activity_type: TntImport::TntCodes.task_type(row['TaskTypeID']), subject: subject(row), start_at: parse_date("#{row['TaskDate']} #{row['TaskTime'].split(' ').second}", @user) } add_assigned_to_as_tag(task, row) add_campaign_as_tag(task, row) add_categories_as_tags(task, row) task.completed = TntImport::TntCodes.task_status_completed?(row['Status']) task.completed_at = parse_date(row['LastEdit'], @user) if task.completed task end def add_categories_as_tags(task, row) task.tag_list.add(row['Categories'], parse: true) if row['Categories'].present? end def add_assigned_to_as_tag(task, row) assigned_to_id = row['AssignedToUserID'] return unless assigned_to_id username = @xml.find('User', assigned_to_id).try(:[], 'UserName') task.tag_list.add username end def add_campaign_as_tag(task, row) campaign_id = row[appeal_id_name] return unless campaign_id campaign_name = @xml.find(appeal_table_name, campaign_id).try(:[], 'Description') task.tag_list.add campaign_name end def create_task_for_contact!(contact_row, tasks) task_prototype = find_task_prototype(contact_row, tasks) contact_id = contact_ids_by_tnt_contact_id[contact_row['ContactID']] return unless task_prototype && contact_id task = create_task_from_prototype!(task_prototype, contact_id) task.reload [task, contact_id] end def find_task_prototype(contact_row, tasks) tasks.find { |t| t.remote_id == contact_row[xml_foreign_key] } end def create_task_from_prototype!(prototype, contact_id) dup_task(prototype, contact_id).tap do |task| task.skip_contact_task_counter_update = true task.activity_contacts.where(contact_id: contact_id).first_or_initialize do |activity_contact| activity_contact.skip_contact_task_counter_update = true end task.save! row = @xml.find(xml_table_name, task.remote_id) import_comments_for_task(task: task, row: row) end end def dup_task(task, contact_id) dupped_task = if task.id.blank? task.dup elsif task.contacts.empty? || task.contacts.any? { |c| c.id == contact_id } task else task.dup.tap { |t| t.id = nil } end task.comments.each { |c| dupped_task.comments << c.dup } if dupped_task != task dupped_task end def update_contacts_task_counters!(contact_ids) Contact.where(id: contact_ids).find_each(&:update_uncompleted_tasks_count) end def import_comments_for_task(task:, row: nil) notes = row.try(:[], 'Notes') tnt_task_type_id = row.try(:[], 'TaskTypeID') task.comments.where(body: notes.strip).first_or_create if notes.present? unsupported_type_name = ::TntImport::TntCodes.unsupported_task_type(tnt_task_type_id) if unsupported_type_name comment_body = _(%(This task was given the type "#{unsupported_type_name}" in TntConnect.)) task.comments.where(body: comment_body).first_or_create end add_completed_by_as_comment(task, row) if task.completed task.comments end def add_completed_by_as_comment(task, row) completed_by_id = row['LoggedByUserID'] return unless completed_by_id username = @xml.find('User', completed_by_id).try(:[], 'UserName') task.comments.where(body: "Completed By: #{username}").first_or_create if username end def xml_table_name 'Task' end def xml_foreign_key 'TaskID' end end
chuckmersereau/api_practice
spec/factories/partner_status_logs.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 FactoryBot.define do factory :partner_status_log do association :contact recorded_on '2016-11-30 14:20:20 -0500' status 'MyString' pledge_amount 100.00 pledge_frequency 1.0 pledge_received true pledge_start_date '2016-01-01 14:20:20 -0500' end end
chuckmersereau/api_practice
app/services/tnt_import/orgs_finder.rb
class TntImport::OrgsFinder class << self def orgs_by_tnt_id(xml, default_org) xml = xml.tables return unless xml && xml['Organization'].present? orgs_by_tnt_id = {} xml['Organization'].each do |org_row| orgs_by_tnt_id[org_row['id']] = Organization.find_by(code: org_row['Code']) || default_org end orgs_by_tnt_id end end end
chuckmersereau/api_practice
spec/services/contact/filter/related_task_action_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe Contact::Filter::RelatedTaskAction do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:task_one) { create(:task, account_list: account_list, activity_type: 'Email') } let(:task_two) { create(:task, account_list: account_list, activity_type: 'Call') } let!(:contact_one) { create(:contact, status: 'Partner - Financial', account_list: account_list, tasks: [task_one]) } let!(:contact_two) { create(:contact, status: 'Partner - Financial', account_list: account_list, tasks: [task_one]) } let!(:contact_three) { create(:contact, status: 'Partner - Financial', account_list: account_list, tasks: [task_two]) } let!(:contact_four) { create(:contact, status: 'Partner - Financial', account_list: account_list) } describe '#config' do it 'returns expected config' do expect(described_class.config([account_list])).to include(multiple: true, name: :related_task_action, options: [ { name: '-- Any --', id: '', placeholder: 'None' }, { name: '-- None --', id: 'none' }, { name: 'Call', id: 'Call' }, { name: 'Email', id: 'Email' } ], parent: 'Tasks', title: 'Action', type: 'multiselect', default_selection: '') end end describe '#query' do let(:contacts) { Contact.all } context 'no filter params' do it 'returns nil' do expect(described_class.query(contacts, {}, nil)).to eq(nil) expect(described_class.query(contacts, { related_task_action: {} }, nil)).to eq(nil) expect(described_class.query(contacts, { related_task_action: [] }, nil)).to eq(nil) expect(described_class.query(contacts, { related_task_action: '' }, nil)).to eq(nil) end end context 'filter by Related Task Action Type' do it 'returns only contacts that have no related tasks when "none" is passed' do expect(described_class.query(contacts, { related_task_action: 'none' }, nil).to_a).to eq [contact_four] expect(described_class.query(contacts, { related_task_action: 'null' }, nil).to_a).to eq [contact_four] end it 'returns only contacts with tasks of the specified activity type when specified' do expect(described_class.query(contacts, { related_task_action: 'Email' }, nil).to_a).to match_array [contact_one, contact_two] expect(described_class.query(contacts, { related_task_action: 'Call' }, nil).to_a).to eq [contact_three] end end context 'filter by Related Task Action Type, with non-task Activities' do before do contact_four.activities << create(:activity) end it 'returns contacts no no related tasks, but with other non-task activities' do expect(described_class.query(contacts, { related_task_action: 'none' }, nil).to_a).to include contact_four expect(described_class.query(contacts, { related_task_action: 'null' }, nil).to_a).to include contact_four end end end end
chuckmersereau/api_practice
db/migrate/20160204190113_add_index_to_tags_lower_name.rb
<gh_stars>0 class AddIndexToTagsLowerName < ActiveRecord::Migration self.disable_ddl_transaction! def change execute "create index concurrently tags_on_lower_name on tags(lower(name));" end end
chuckmersereau/api_practice
db/migrate/20150220141300_add_tnt_id_to_appeals.rb
class AddTntIdToAppeals < ActiveRecord::Migration def change add_column :appeals, :tnt_id, :integer end end
chuckmersereau/api_practice
app/serializers/reports/monthly_losses_graph_serializer.rb
<gh_stars>0 class Reports::MonthlyLossesGraphSerializer < ServiceSerializer include DisplayCase::ExhibitsHelper delegate :account_list, :month_names, :losses, to: :object belongs_to :account_list attributes :account_list, :month_names, :losses end
chuckmersereau/api_practice
spec/support/authorization.rb
require 'rails_helper' shared_context :authorization do let(:authorization) { "Bearer #{JsonWebToken.encode(user_id: user.id)}" } header 'Authorization', :authorization end
chuckmersereau/api_practice
spec/acceptance/api/v2/reports/donor_currency_donations_spec.rb
<filename>spec/acceptance/api/v2/reports/donor_currency_donations_spec.rb<gh_stars>0 require 'spec_helper' require 'rspec_api_documentation/dsl' resource 'Reports > Donor Currency Donations Report' do include_context :json_headers documentation_scope = :reports_api_donation_summaries let(:resource_type) { 'reports_donor_currency_donations' } let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let(:resource_attributes) do %w( created_at donor_infos months currency_groups salary_currency updated_at updated_in_db_at ) end context 'authorized user' do before { api_login(user) } # show get '/api/v2/reports/donor_currency_donations' do parameter 'filter[account_list_id]', 'Account List ID', required: true parameter 'filter[donor_account_id]', 'List of Donor Account Ids', 'Type' => 'Array[String]' parameter 'filter[designation_account_id]', 'List of Designation Account Ids', 'Type' => 'Array[String]' response_field 'data', 'Data object', type: 'Object' with_options scope: [:data, :attributes] do response_field 'created_at', 'Time when report was observed', type: 'String' response_field 'donor_infos', 'Info on donors', type: 'Array[Object]' response_field 'months', 'The months represented in the data', type: 'Array[Object]' response_field 'currency_groups', 'The donations made each month, per contact, grouped by currencies', type: 'Array[Object]' end with_options scope: [:data, :attributes, :currency_groups, :currency_code] do response_field 'totals', 'The total donations for the year, and each individual month', type: 'Object' response_field 'donation_infos', 'Info on each contact\'s donations each month of the year', type: 'Array[Object]' end with_options scope: [:data, :relationships] do response_field 'account_list', 'Account List', type: 'Object' end example 'Donation Summary [LIST]', document: documentation_scope do explanation 'Lists donors who donated in the past 12 months, separated by into currency groups' do_request(filter: { account_list_id: account_list_id }) check_resource(['relationships']) expect(response_status).to eq 200 end end end end
chuckmersereau/api_practice
app/services/constant_list.rb
class ConstantList < ActiveModelSerializers::Model include DisplayCase::ExhibitsHelper include LocalizationHelper CURRENCY_CODES_NOT_NEEDED = %w(ADP AFA).freeze delegate :alert_frequencies, :mobile_alert_frequencies, to: :Task delegate :pledge_frequencies, to: :Contact delegate :assignable_locations, to: :address delegate :assignable_statuses, to: :contact def activities @activities ||= ::Task::TASK_ACTIVITIES.dup end def assignable_likely_to_give contact.assignable_likely_to_gives end def assignable_send_newsletter contact.assignable_send_newsletters end def statuses contact.assignable_statuses end def codes @codes ||= TwitterCldr::Shared::Currencies.currency_codes - CURRENCY_CODES_NOT_NEEDED end def locales @locales ||= supported_locales.invert.sort_by(&:first) end def notifications @notifications ||= notifications_hash end def organizations @organizations ||= organizations_hash end def organizations_attributes @organizations_attributes ||= organizations_attributes_hash end def next_actions @next_actions ||= dup_hash_of_arrays(Task.all_next_action_options.dup) end def results @results ||= dup_hash_of_arrays(Task.all_result_options.dup) end def csv_import @csv_import ||= { constants: CsvImport.constants, max_file_size_in_bytes: Import::MAX_FILE_SIZE_IN_BYTES, required_headers: CsvImport.required_headers, supported_headers: CsvImport.supported_headers } end def tnt_import { max_file_size_in_bytes: Import::MAX_FILE_SIZE_IN_BYTES } end def sources { addresses: %w(DataServer GoogleContactSync GoogleImport MPDX Siebel TntImport), email_addresses: ['MPDX'], phone_numbers: ['MPDX'] } end def send_appeals { true => 'Yes', false => 'No' } end def to_exhibit @exhibit ||= exhibit(self) end private def address @address ||= Address.new end def contact @contact ||= Contact.new end def notifications_hash NotificationType.all.inject({}) do |hash, notification_type| hash.merge!(notification_type.id => notification_type.description) end end def organizations_hash Organization.active.order(name: :asc).inject({}) do |hash, organization| hash.merge!(organization.id => organization.name) end end def organizations_attributes_hash Organization.active.order(name: :asc).inject({}) do |hash, organization| hash.merge!(organization.id => organization_attributes_hash(organization)) end end def organization_attributes_hash(organization) { name: organization.name, api_class: organization.api_class.to_s, help_email: organization.org_help_email, oauth: organization.oauth? } end # For some reason, ActiveModelSerializer tries to somehow modify the elements # that it serializes. If an array being serialized has been frozen, a "can't # modify frozen Array" error will be raised. def dup_hash_of_arrays(hash) Hash[hash.map { |k, v| [k, v.dup] }] end end
chuckmersereau/api_practice
db/migrate/20120202200843_create_person_twitter_accounts.rb
class CreatePersonTwitterAccounts < ActiveRecord::Migration def change create_table :person_twitter_accounts do |t| t.integer :person_id, null: false t.column :remote_id, :bigint, null: false t.string :screen_name t.string :token t.string :secret t.timestamps null: false end add_index :person_twitter_accounts, [:person_id, :remote_id], unique: true add_index :person_twitter_accounts, :remote_id end end
chuckmersereau/api_practice
app/serializers/donation_amount_recommendation_serializer.rb
<filename>app/serializers/donation_amount_recommendation_serializer.rb<gh_stars>0 class DonationAmountRecommendationSerializer < ApplicationSerializer belongs_to :designation_account belongs_to :donor_account attributes :ask_at, :started_at, :suggested_pledge_amount, :suggested_special_amount end
chuckmersereau/api_practice
db/migrate/20151210152844_remove_bad_from_email_addresses.rb
<filename>db/migrate/20151210152844_remove_bad_from_email_addresses.rb class RemoveBadFromEmailAddresses < ActiveRecord::Migration def change return unless column_exists?(:email_addresses, :bad) remove_column :email_addresses, :bad, :boolean end end
chuckmersereau/api_practice
dev/fixers/wrong_org_donor_accounts_fixer.rb
<reponame>chuckmersereau/api_practice # There was a bug in the Tnt import that would make it so when someone # imported from Tnt and they had multiple organizations, MPDX could # incorrectly associate some of their donor accounts with the wrong # organization. # Because of the way the contact merge logic works (just considering # donor account numbers not organizations), when people merged contacts # together, donations would disappear. # # These functions allow you to correct a user's account by going through # their donor accounts and setting those that were incorrectly labeled. # # The first two methods donor_accounts_counts_by_org and empty_donor_accounts # allow you to look up what donor accounts an account list has to diagnose which # organization was incorrectly assigned to some of their donor accounts. # # Then to correct the problem, call fix_all_donor_accounts with the account # list, the org that was wrongly set and the correct org. # # For instance, if someone is from Canada and they imported from TntMPD but a # lot of their donor accounts got marked as as Cru USA incorrectly, then you # would call the method like this: # # ptc = Organization.find_by(name: 'Power to Change - Canada') # fix_all_donor_accounts(account_list, Organization.cru_usa, ptc) # Gives an overview of the organizations that are in an account's donors to help # diagnose which organization might have been wrongly added by the Tnt import. def donor_accounts_counts_by_org(account_list) account_list.donor_accounts.group(:organization_id).count end # Shows the empty donor accounts for an account list, helpful for diagnosing # which organization was incorrectly set onto their account lists. def empty_donor_accounts(account_list) account_list.donor_accounts.select do |da| da.donations.count.zero? end end # Main fixer method to use on an account list def fix_all_donor_accounts(account_list, wrong_org, right_org) account_list.contacts.each do |contact| fix_donor_accounts(contact, wrong_org, right_org) end nil end ############################################## # Helper methods for fix_all_donor_accounts above ############################################## def fix_donor_accounts(contact, _wrong_org, right_org) contact.donor_accounts.each do |da| next if da.organization == right_org || da.donations.any? remove_donor_account(contact, da) add_right_donor_account(contact, da.account_number, right_org) end end def remove_donor_account(contact, donor_account) contact.contact_donor_accounts.where(donor_account: donor_account).each do |_cda| puts "Removing wrong org donor #{donor_account.id} from contact #{contact.id}" end puts "Deleting wrong org donor account #{donor_account.inspect}" donor_account.destroy end def add_right_donor_account(contact, account_number, right_org) right_da = right_org.donor_accounts.find_by(account_number: account_number) if right_da.nil? puts "Could not find right org donor for ##{account_number} for conact #{contact.id}" elsif already_has_donor_account?(contact, account_number, right_org) puts "Contact #{contact.id} already has right org donor #{right_da.id}" else puts "Adding right org donor #{right_da.id} to contact #{contact.id}" contact.donor_accounts << right_da end end def already_has_donor_account?(contact, account_number, right_org) numbers = contact.donor_accounts.where(organization: right_org).pluck(:account_number) numbers.include?(account_number) end
chuckmersereau/api_practice
app/serializers/preferences_set_serializer.rb
class PreferencesSetSerializer < ApplicationSerializer attributes :account_list_name, :currency, :default_account_list, :email, :first_name, :home_country, :last_name, :locale, :ministry_country, :monthly_goal, :tester, :time_zone belongs_to :salary_organization end
chuckmersereau/api_practice
spec/services/account_list/chalkline_mails_spec.rb
<filename>spec/services/account_list/chalkline_mails_spec.rb require 'rails_helper' RSpec.describe AccountList::ChalklineMails, type: :model do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:service) { AccountList::ChalklineMails.new(account_list: account_list) } describe 'initialize' do subject { service } it 'initializes successfully' do expect(subject).to be_a AccountList::ChalklineMails expect(subject.account_list).to eq account_list end end describe '#send_later' do before do Sidekiq::Testing.fake! end subject { service.send_later } it 'enqueues a new background job' do expect(ChalklineMailer).to receive_message_chain(:delay, :mailing_list).with(account_list) subject end end end
chuckmersereau/api_practice
spec/support/mpdx_helpers.rb
<reponame>chuckmersereau/api_practice module MpdxHelpers def api_login(user) allow_any_instance_of(Api::V2Controller).to receive(:authenticate!) allow_any_instance_of(Api::V2Controller).to receive(:current_user).and_return(user) end def api_logout allow_any_instance_of(Api::V2Controller).to receive(:authenticate!).and_raise(Exceptions::AuthenticationError) allow_any_instance_of(Api::V2Controller).to receive(:current_user).and_return(nil) end def login(user) # rubocop:disable Style/GlobalVars $request_test = true $user = user # rubocop:enable Style/GlobalVars end def stub_google_geocoder stub_request(:get, %r{maps\.googleapis\.com/maps/api.*}).to_return(body: '{}') end def stub_smarty_streets stub_request(:get, %r{https://api\.smartystreets\.com/street-address/.*}) .to_return(body: '[]') end # Clear out unique job locks. They can get into Redis if you interrupt a test # run or don't call Worker.clear after queuing jobs in a spec. def clear_uniqueness_locks Sidekiq.redis do |redis| redis.keys('*unique*').each { |k| redis.del(k) } end end # locally, the orgs are seeded if you run rake db:test:prepare, but in # Travis the database is fully empty since it just loads structure.sql def org_for_code(code) Organization.find_by(code: code) || create(:organization, name: code, code: code) end def stub_auth stub_request(:get, 'http://oauth.ccci.us/users/' + user.access_token) .to_return(status: 200) end def expect_delayed_email(mailer, mailing_method) delayed = double expect(mailer).to receive(:delay).and_return(delayed) expect(delayed).to receive(mailing_method) end end
chuckmersereau/api_practice
app/controllers/api/v2/reports/pledge_histories_controller.rb
<filename>app/controllers/api/v2/reports/pledge_histories_controller.rb class Api::V2::Reports::PledgeHistoriesController < Api::V2Controller include Filtering def index load_report authorize_report render_report end private def permit_coach? true end def load_report @report ||= ::Reports::PledgeHistories.new(report_params) end def report_params { account_list: load_account_list }.merge(filter_params.except(:account_list_id)) end def load_account_list @account_list ||= account_lists.order(:created_at).first end def render_report render json: @report.periods_data, fields: field_params, include: include_params, meta: meta_hash end def meta_hash { filter: permitted_filter_params_with_ids } end def permitted_filters [:account_list_id, :period, :end_date] end def authorize_report authorize(load_account_list, :show?) end end
chuckmersereau/api_practice
spec/models/partner_status_log_spec.rb
<filename>spec/models/partner_status_log_spec.rb require 'rails_helper' describe PartnerStatusLog, versioning: true do subject { create(:partner_status_log) } it 'gets added to track status and pledge details at most once per day' do contact = nil travel_to Date.new(2015, 12, 18) do contact = create(:contact, status: 'Ask in Future', pledge_amount: nil) end travel_to Date.new(2015, 12, 19) do expect do contact.update(status: 'Partner - Financial') contact.update(pledge_amount: 200) end.to change(PartnerStatusLog, :count).by(1) end expect(contact.status_on_date(Date.new(2015, 12, 18))).to eq 'Ask in Future' end describe '#pledge_currency' do before { subject.pledge_currency = 'USD' } it 'returns pledge_currency' do expect(subject.pledge_currency).to eq 'USD' end context 'pledge_currency is nil' do before do subject.pledge_currency = nil subject.contact.update_attribute(:pledge_currency, 'USD') end it 'returns pledge_currency' do expect(subject.pledge_currency).to eq 'USD' end end end end
chuckmersereau/api_practice
lib/pundit_context.rb
class PunditContext attr_reader :user attr_reader :extra_context def initialize(user, extra_context = nil) @user = validate_user(user) @extra_context = validate_extra_context(extra_context) end def method_missing(method_name, *args, &block) if extra_context_item_keys.include?(method_name) extra_context.public_send(method_name, *args, &block) else super end end def respond_to_missing?(method_name, include_private = false) extra_context_item_keys.include?(method_name) || super end private def extra_context_item_keys @context_item_keys ||= extra_context.to_h.keys end def validate_user(user_candidate) return user_candidate if user_candidate.class.name == 'User' raise ArgumentError, 'expected an instance of User' end def validate_extra_context(context_candidate) context_candidate ||= {} return OpenStruct.new(context_candidate) if context_candidate.is_a?(Hash) raise ArgumentError, 'Extra context (the 2nd param) must be a hash' end end
chuckmersereau/api_practice
spec/policies/admin/reset_log_policy_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/policies/admin/reset_log_policy_spec.rb require 'rails_helper' RSpec.describe Admin::ResetLogPolicy do let!(:resetted_user) { create(:user) } let!(:admin_resetting) { create(:admin_user) } let!(:reason) { 'Just testing this out :)' } let!(:reset_log) do Admin::ResetLog.create(resetted_user: resetted_user, admin_resetting: admin_resetting, reason: reason) end describe 'authorize create' do subject { PunditAuthorizer.new(admin_resetting, reset_log).authorize_on('create') } it 'does raise any errors when authorized' do expect { subject }.to_not raise_error end it 'is raises error when the record is invalid' do reset_log.reason = nil expect(reset_log.valid?).to eq false expect { subject }.to raise_error Pundit::NotAuthorizedError end it 'is raises error when admin_resetting is not an admin' do reset_log.admin_resetting = create(:user) expect(reset_log.valid?).to eq true expect { subject }.to raise_error Pundit::NotAuthorizedError end it 'is raises error when resetted_user is no longer in the database' do reset_log.resetted_user = nil reset_log.resetted_user_id = SecureRandom.uuid expect(reset_log.valid?).to eq true expect { subject }.to raise_error Pundit::NotAuthorizedError end it 'is raises error if it is too old' do reset_log.update_column(:created_at, 1.month.ago) expect(reset_log.valid?).to eq true expect { subject }.to raise_error Pundit::NotAuthorizedError end it 'is raises error if the reset already happened' do reset_log.update_column(:completed_at, 1.month.ago) expect(reset_log.valid?).to eq true expect { subject }.to raise_error Pundit::NotAuthorizedError end end end
chuckmersereau/api_practice
spec/support/geocoder.rb
<filename>spec/support/geocoder.rb # Suppress debug-level "Geocoder: HTTP request being made ..." in spec output Geocoder.configure(lookup: :test) Geocoder::Lookup::Test.set_default_stub( [ { 'latitude' => 40.7, 'longitude' => -74.0, 'address' => 'New York, NY, USA', 'state' => 'New York', 'state_code' => 'NY', 'country' => 'United States', 'country_code' => 'US' } ] )
chuckmersereau/api_practice
spec/services/person/google_account/contact_group_spec.rb
<filename>spec/services/person/google_account/contact_group_spec.rb require 'rails_helper' RSpec.describe Person::GoogleAccount::ContactGroup do let(:api_contact_groups) do [ OpenStruct.new( id: 'contact_group_id_0', title: 'contact_group_title_0', updated: Date.today ), OpenStruct.new( id: 'contact_group_id_1', title: 'contact_group_title_1', updated: Date.today ) ] end let(:contact_groups) do [ described_class.new( id: 'contact_group_id_0', title: 'contact_group_title_0', created_at: Date.today, updated_at: Date.today ), described_class.new( id: 'contact_group_id_1', title: 'contact_group_title_1', created_at: Date.today, updated_at: Date.today ) ] end describe '.from_groups' do it 'should create collection of instances' do expect(described_class.from_groups(api_contact_groups)[0].to_json).to eq(contact_groups[0].to_json) expect(described_class.from_groups(api_contact_groups)[1].to_json).to eq(contact_groups[1].to_json) end end end
chuckmersereau/api_practice
app/services/tnt_import/pledges_import.rb
<reponame>chuckmersereau/api_practice # In TNT a Pledge is called a "Promise". class TntImport::PledgesImport include Concerns::TntImport::AppealHelpers include Concerns::TntImport::DateHelpers DEFAULT_CURRENCY_CODE = 'USD'.freeze def initialize(account_list, import, xml) @account_list = account_list @import = import @xml = xml end def import return {} unless @xml.tables['Promise'] Array.wrap(@xml.tables['Promise']).each do |row| import_pledge(row) end end private def import_pledge(row) @account_list.pledges.find_or_create_by(amount: row['Amount'], amount_currency: find_tnt_currency_code_for_row(row), appeal: find_mpdx_appeal_for_row(row), contact: find_mpdx_contact_for_row(row), expected_date: parse_date(row['DateDue'], @import.user)) end def find_mpdx_contact_for_row(row) return unless row['ContactID'].present? @account_list.contacts.where(tnt_id: row['ContactID']).first end def find_mpdx_appeal_for_row(row) return unless row[appeal_id_name].present? @account_list.appeals.where(tnt_id: row[appeal_id_name]).first end def find_tnt_currency_code_for_row(row) currency_id = row['CurrencyID'] return DEFAULT_CURRENCY_CODE unless currency_id && @xml.tables['Currency'] found_currency_row = @xml.tables['Currency'].detect { |currency_row| currency_row['id'] == currency_id } found_currency_row.try(:[], 'Code').presence || DEFAULT_CURRENCY_CODE end end
chuckmersereau/api_practice
db/migrate/20140128153112_add_index_to_taggings.rb
class AddIndexToTaggings < ActiveRecord::Migration def change add_index :taggings, :taggable_id, name: 'INDEX_TAGGINGS_ON_TAGGABLE_ID' end end
chuckmersereau/api_practice
spec/services/contact/filter/metro_area_spec.rb
require 'rails_helper' RSpec.describe Contact::Filter::MetroArea do let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact_one) { create(:contact, account_list_id: account_list.id) } let!(:contact_two) { create(:contact, account_list_id: account_list.id) } let!(:contact_three) { create(:contact, account_list_id: account_list.id) } let!(:contact_four) { create(:contact, account_list_id: account_list.id) } let!(:contact_five) { create(:contact, account_list_id: account_list.id) } let!(:address_one) { create(:address, metro_area: 'My Metro') } let!(:address_two) { create(:address, metro_area: 'My Metro') } let!(:address_three) { create(:address, metro_area: nil) } let!(:address_four) { create(:address, metro_area: nil) } let!(:address_five) { create(:address, metro_area: 'My Metro', historic: true) } before do contact_one.addresses << address_one contact_two.addresses << address_two contact_three.addresses << address_three contact_four.addresses << address_four contact_five.addresses << address_five end describe '#config' do it 'returns expected config' do options = [{ name: '-- Any --', id: '', placeholder: 'None' }, { name: '-- None --', id: 'none' }, { name: 'My Metro', id: 'My Metro' }] expect(described_class.config([account_list])).to include(multiple: true, name: :metro_area, options: options, parent: 'Contact Location', title: 'Metro Area', type: 'multiselect', default_selection: '') end end describe '#query' do let(:contacts) { Contact.all } context 'no filter params' do it 'returns nil' do expect(described_class.query(contacts, {}, nil)).to eq(nil) expect(described_class.query(contacts, { metro_area: {} }, nil)).to eq(nil) expect(described_class.query(contacts, { metro_area: [] }, nil)).to eq(nil) expect(described_class.query(contacts, { metro_area: '' }, nil)).to eq(nil) end end context 'filter by no metro_area' do it 'returns only contacts that have no metro_area' do result = described_class.query(contacts, { metro_area: 'none' }, nil).to_a expect(result).to match_array [contact_three, contact_four] end end context 'filter by metro_area' do it 'filters multiple metro_areas' do result = described_class.query(contacts, { metro_area: 'My Metro, My Metro' }, nil).to_a expect(result).to match_array [contact_one, contact_two] end it 'filters a single metro_area' do result = described_class.query(contacts, { metro_area: 'My Metro' }, nil).to_a expect(result).to match_array [contact_one, contact_two] end end context 'multiple filters' do it 'returns contacts matching multiple filters' do result = described_class.query(contacts, { metro_area: 'My Metro, none' }, nil).to_a expect(result).to match_array [contact_one, contact_two, contact_three, contact_four] end end context 'address historic' do it 'returns contacts matching the metro_area with historic addresses' do result = described_class.query(contacts, { metro_area: 'My Metro', address_historic: 'true' }, nil).to_a expect(result).to eq [contact_five] end end end end
chuckmersereau/api_practice
db/migrate/20170831194616_deprecate_people_not_duplicated_with.rb
<gh_stars>0 class DeprecatePeopleNotDuplicatedWith < ActiveRecord::Migration def change rename_column :people, :not_duplicated_with, :deprecated_not_duplicated_with end end
chuckmersereau/api_practice
app/policies/donation_policy.rb
<reponame>chuckmersereau/api_practice class DonationPolicy < AccountListChildrenPolicy end
chuckmersereau/api_practice
dev/util/account_util.rb
def find_u(id_name_or_email) users = Admin::UserFinder.find_users(id_name_or_email) if users.count <= 1 users.first elsif users.count > 1 puts 'multiple users' users end end def find_a(name) first, last = name.split(' ') alus = AccountListUser.joins(:user).where(people: { first_name: first, last_name: last }) puts alus.count if alus.count == 1 alus.first.account_list else alus.map(&:account_list) end end def find_a_by_e(email) alus = AccountListUser.joins(:user) \ .joins('inner join email_addresses on email_addresses.person_id = people.id') \ .where(email_addresses: { email: email }) puts alus.count if alus.count == 1 alus.first.account_list else alus.map(&:account_list) end end def remove_account_list(user, account_list) account_list.account_list_users.find_by(user: user).destroy account_list.account_list_users.find_by(user: user) end
chuckmersereau/api_practice
db/migrate/20150410120313_add_prayer_letters_params_to_contacts.rb
class AddPrayerLettersParamsToContacts < ActiveRecord::Migration def change add_column :contacts, :prayer_letters_params, :text end end
chuckmersereau/api_practice
spec/factories/google_plus_accounts.rb
<filename>spec/factories/google_plus_accounts.rb FactoryBot.define do factory :google_plus_account do account_id 'GooglePlusAccountId' end end
chuckmersereau/api_practice
spec/controllers/api/v2/tasks/bulk_controller_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe Api::V2::Tasks::BulkController, type: :controller do let!(:account_list) { user.account_lists.order(:created_at).first } let!(:account_list_id) { account_list.id } let!(:factory_type) { :task } let!(:id) { resource.id } let!(:incorrect_reference_value) { resource.send(reference_key) } let!(:given_reference_key) { :subject } let!(:given_reference_value) { correct_attributes[:subject] } let!(:resource) { create(:task, account_list: account_list) } let!(:second_resource) { create(:task, account_list: account_list) } let!(:third_resource) { create(:task, account_list: account_list) } let!(:user) { create(:user_with_account) } let!(:resource_type) { :tasks } let!(:correct_attributes) do attributes_for(:task, subject: '<NAME>', tag_list: 'tag1') end let!(:incorrect_attributes) do attributes_for(:task, subject: nil) end let(:relationships) do { account_list: { data: { type: 'account_lists', id: account_list_id } } } end include_examples 'bulk_create_examples' include_examples 'bulk_update_examples' include_examples 'bulk_destroy_examples' describe '#post' do before { api_login(user) } let(:bulk_create_form_data) do [{ data: { type: resource_type, id: SecureRandom.uuid, attributes: correct_attributes, relationships: relationships } }] end context 'with specified fields' do it 'only returns specific fields' do post :create, data: bulk_create_form_data, fields: { tasks: 'subject' } expect(JSON.parse(response.body)[0]['data']['attributes'].keys).to eq ['subject'] end it 'will leave subject_hidden as false' do post :create, data: bulk_create_form_data, fields: { tasks: 'subject,subject_hidden' } attributes = JSON.parse(response.body)[0]['data']['attributes'] expect(attributes['subject_hidden']).to eq(false) end end context 'with a missing subject' do let!(:contact) { create(:contact, account_list: account_list) } let(:contact_relationship) do { account_list: { data: { type: 'account_lists', id: account_list_id } }, contacts: { data: [ { id: contact.id, type: 'contacts' } ] } } end let!(:contact_attributes) { attributes_for(:task, subject: nil, activity_type: 'Call') } let(:bulk_create_form_data_with_missing_subject) do [{ data: { type: resource_type, id: SecureRandom.uuid, attributes: contact_attributes, relationships: contact_relationship } }] end it 'will set the subject_hidden to true' do post :create, data: bulk_create_form_data_with_missing_subject, fields: { tasks: 'subject,subject_hidden' } attributes = JSON.parse(response.body)[0]['data']['attributes'] expect(attributes['subject_hidden']).to eq(true) expect(attributes['subject']).to eq("Call #{contact.name}") end end end end
chuckmersereau/api_practice
spec/support/time_travelling.rb
<reponame>chuckmersereau/api_practice RSpec.configure do |config| config.after(:each) do |_example| travel_back Timecop.return if defined?(Timecop) # Just in case someone tries to add Timecop again in the future :) end end
chuckmersereau/api_practice
spec/services/account_list/from_profile_linker_spec.rb
require 'rails_helper' describe AccountList::FromProfileLinker do context '#link_account_list' do let(:org_account) { create(:organization_account) } let(:profile) do create(:designation_profile, user_id: org_account.person_id, organization: org_account.organization) end it 'creates a new account list if none is found' do da = create(:designation_account, organization: org_account.organization) profile.designation_accounts << da expect do AccountList::FromProfileLinker.new(profile, org_account).link_account_list! end.to change(AccountList, :count).by(1) end it 'does not create a new account list if one is found' do da = create(:designation_account, organization: org_account.organization) profile.designation_accounts << da account_list = create(:account_list) profile2 = create(:designation_profile, account_list: account_list) profile2.designation_accounts << da expect do AccountList::FromProfileLinker.new(profile, org_account).link_account_list! end.to_not change(AccountList, :count) end end end
chuckmersereau/api_practice
db/migrate/20171219033014_change_actions_to_booleans_on_notification_preferences.rb
class ChangeActionsToBooleansOnNotificationPreferences < ActiveRecord::Migration def change add_column :notification_preferences, :email, :boolean, default: true add_column :notification_preferences, :task, :boolean, default: true end end
chuckmersereau/api_practice
spec/models/offline_org_spec.rb
require 'rails_helper' describe OfflineOrg do let(:account_list) { create(:account_list) } let(:profile) { create(:designation_profile, organization: @org, user: @person.to_user, account_list: account_list) } before(:each) do @org = create(:organization, name: 'MyString', api_class: 'OfflineOrg') @person = create(:person) @org_account = build(:organization_account, person: @person, organization: @org) end context '.import_profiles' do let(:offline_org) { OfflineOrg.new(@org_account) } it 'creates designation account' do expect do offline_org.import_profiles end.to change(DesignationAccount, :count).from(0).to(1) designation_account = DesignationAccount.first expect(designation_account.designation_number).to eq(@org_account.id.to_s) expect(designation_account.active).to eq(true) expect(designation_account.name).to eq(@org.name) end end end
chuckmersereau/api_practice
spec/support/multipart_form_data_headers.rb
<reponame>chuckmersereau/api_practice shared_context :multipart_form_data_headers do header 'Content-Type', 'multipart/form-data' let(:raw_post) { params } end
chuckmersereau/api_practice
app/controllers/api/v2/account_lists/donor_accounts_controller.rb
class Api::V2::AccountLists::DonorAccountsController < Api::V2Controller serialization_scope :serializer_context def index authorize load_account_list, :show? load_donor_accounts render json: @donor_accounts.preload_valid_associations(include_associations), meta: meta_hash(@donor_accounts), include: include_params, fields: field_params end def show load_donor_account authorize_donor_account render_donor_account end private def load_donor_accounts @donor_accounts ||= filter_params[:contacts] ? filtered_donor_accounts : all_donor_accounts @donor_accounts = @donor_accounts.filter(load_account_list, filter_params_without_contacts) .reorder(sorting_param) .order(default_sort_param) .page(page_number_param) .per(per_page_param) end def load_donor_account @donor_account ||= DonorAccount.find(params[:id]) end def render_donor_account render json: @donor_account, include: include_params, fields: field_params end def authorize_donor_account authorize @donor_account end def donor_account_scope load_account_list.donor_accounts end def load_account_list @account_list ||= AccountList.find(params[:account_list_id]) end def permitted_filters [:contacts, :wildcard_search] end def pundit_user PunditContext.new(current_user, account_list: load_account_list) end def all_donor_accounts donor_account_scope end def filter_params_without_contacts filter_params.except(:contacts) end def filtered_donor_accounts donor_account_scope.where(contact_donor_accounts: { contact_id: filter_params[:contacts] }) end def serializer_context { account_list: load_account_list, current_user: current_user } end def default_sort_param DonorAccount.arel_table[:created_at].asc end end
chuckmersereau/api_practice
spec/services/admin/user_finder_spec.rb
require 'rails_helper' describe Admin::UserFinder do describe '.find_users' do it 'finds user by id' do user = create(:user) expect(Admin::UserFinder.find_users(user.id)).to eq [user] end it 'finds users by name' do # Shouldn't find this non-user person with name create(:person, first_name: 'John', last_name: 'Doe') john1 = create(:user_with_account, first_name: 'John', last_name: 'Doe') john2 = create(:user_with_account, first_name: 'John', last_name: 'Doe') create(:user_with_account, first_name: 'Jane', last_name: 'Doe') found_users = Admin::UserFinder.find_users('<NAME>') expect(found_users.to_set).to eq [john1, john2].to_set end it 'finds user by key account' do account = create(:key_account, email: '<EMAIL>') found_user = Admin::UserFinder.find_users('<EMAIL>').first expect(found_user).to be_a User expect(found_user.id).to eq account.person.id end it 'returns only use result for a user with multiple account lists' do john = create(:user_with_account, first_name: 'John', last_name: 'Doe') john.account_lists << create(:account_list) found_users = Admin::UserFinder.find_users('<NAME>') expect(found_users).to eq [john] end it 'can look up by "Last Name, First Name"' do john = create(:user_with_account, first_name: '<NAME>', last_name: '<NAME>') john.account_lists << create(:account_list) found_users = Admin::UserFinder.find_users('<NAME>, <NAME>') expect(found_users).to eq [john] end it 'does not error if given a non-email string without a space or comma' do expect do result = Admin::UserFinder.find_users('joe') expect(result).to be_empty end.to_not raise_error end end describe '.find_user_by_email' do it 'should find users with the email' do account = create(:key_account, email: '<EMAIL>') found_user = Admin::UserFinder.find_user_by_email('<EMAIL>') expect(found_user).to be_a User expect(found_user.id).to eq account.person.id end end end
chuckmersereau/api_practice
spec/support/header_helpers.rb
module HeaderHelpers extend ActiveSupport::Concern included do before(:each) do request.headers['CONTENT_TYPE'] = 'application/vnd.api+json' end end end
chuckmersereau/api_practice
app/controllers/api/v2/appeals_controller.rb
class Api::V2::AppealsController < Api::V2Controller def index load_appeals render json: @appeals.preload_valid_associations(include_associations), scope: { account_list: load_account_list_scope }, meta: meta_hash(@appeals), include: include_params, fields: field_params end def show load_appeal authorize_appeal render_appeal end def create persist_appeal end def update load_appeal authorize_appeal persist_appeal end def destroy load_appeal authorize_appeal destroy_appeal end private def destroy_appeal @appeal.destroy head :no_content end def load_appeals @appeals = appeal_scope.filter(filter_params) .reorder(sorting_param) .order(default_sort_param) .page(page_number_param) .per(per_page_param) end def load_appeal @appeal ||= Appeal.find(params[:id]) end def render_appeal render json: @appeal, scope: { account_list: load_account_list_scope }, status: success_status, include: include_params, fields: field_params end def persist_appeal build_appeal authorize_appeal if save_appeal render_appeal else render_with_resource_errors(@appeal) end end def build_appeal @appeal ||= appeal_scope.build @appeal.assign_attributes(appeal_params) @appeal.exclusion_filter = params[:appeal][:exclusion_filter] @appeal.inclusion_filter = params[:appeal][:inclusion_filter] end def save_appeal @appeal.save(context: persistence_context) end def appeal_params params .require(:appeal) .permit(Appeal::PERMITTED_ATTRIBUTES) end def appeal_scope Appeal.that_belong_to(current_user) end def authorize_appeal authorize(@appeal) end def load_account_list_scope return unless filter_params[:account_list_id] @account_list ||= AccountList.find(filter_params[:account_list_id]).tap do |account_list| authorize(account_list, :show?) end end def permitted_filters [:account_list_id, :wildcard_search, :appeal_id] end def pundit_user PunditContext.new(current_user) end def default_sort_param Appeal.arel_table[:created_at].asc end end
chuckmersereau/api_practice
spec/lib/sidekiq_audited_user_spec.rb
<reponame>chuckmersereau/api_practice require 'spec_helper' describe SidekiqAuditedUser do class Worker end it 'tracks the sidekiq job info to be accessed later in the job' do job = { 'class' => 'Worker', 'enqueued_at' => 1, 'args' => [1, :a, { c: 'hi' }], 'jid' => '1', 'x' => 2 } expect do |block| SidekiqAuditedUser.new.call(double, job, double, &block) end.to yield_control expect(::Audited.store[:audited_user]).to be_a(Worker) end end
chuckmersereau/api_practice
spec/services/account_list/pledges_total_spec.rb
<gh_stars>0 require 'rails_helper' describe AccountList::PledgesTotal do let(:account_list) { create(:account_list, salary_organization_id: create(:organization).id) } it 'defaults unknown currency rates to 1' do rate = described_class.new(account_list, account_list.contacts).latest_rate('ANY') expect(rate).to eq(1) end let!(:contact1) do create(:contact, account_list: account_list, pledge_amount: 15, pledge_currency: 'USD', status: 'Partner - Financial') end let!(:contact2) do create(:contact, account_list: account_list, pledge_amount: 10, pledge_currency: 'USD', status: 'Partner - Financial') end it 'calculates total pledges with no Financial Partners' do contact1.update(status: 'Partner - Special') contact2.update(status: '') expect(account_list.total_pledges).to eq(0) end it 'calculates total pledges' do expect(account_list.total_pledges).to eq(25) end context 'multi-currency' do before do account_list.update(currency: 'EUR') contact2.update(pledge_amount: 95, pledge_currency: 'RUB') create(:currency_rate, rate: 0.8, exchanged_on: '2016-02-15', code: 'EUR') create(:currency_rate, rate: 0.75, exchanged_on: '2016-01-15', code: 'EUR') create(:currency_rate, rate: 75.20, exchanged_on: '2016-02-15', code: 'RUB') end it 'calculates total pledges with currency conversion' do expect(account_list.total_pledges).to eq(16.26) end end end
chuckmersereau/api_practice
spec/services/tnt_import/xml_spec.rb
require 'spec_helper' describe TntImport::Xml do let(:tnt_import) { FactoryBot.build_stubbed(:tnt_import, override: true) } let(:xml) { TntImport::XmlReader.new(tnt_import).parsed_xml } describe 'initialize' do it 'initializes' do expect(xml).to be_a TntImport::Xml end end describe '#tables' do it 'returns parsed xml as a hash' do expect(xml.tables).to be_a Hash expect(xml.tables.keys).to eq %w(Appeal Contact Designation Group GroupContact History HistoryContact HistoryResult LikelyToGive Login LoginProfile LoginProfileDesignation PendingAction Picture Property Region RegionLocation Task TaskContact TaskReason TaskType Currency) end end describe '#version' do it 'returns parsed version as a float' do expect(xml.version).to be_a Float expect(xml.version).to eq 3.0 end end describe '#find' do it 'finds row by id' do appeal_id = xml.tables['Contact'].last['id'] expect(xml.find('Contact', appeal_id)).to eq xml.tables['Contact'].last end it 'finds row by attributes' do attributes = { 'FullName' => '<NAME> and <NAME>', 'Phone' => '(555) 999-9999' } row = xml.tables['Contact'].last row['FullName'] = attributes['FullName'] row['Phone'] = attributes['Phone'] expect(xml.find('Contact', attributes)).to eq row end it 'does not raise if table does not exist' do expect(xml.find('SuperHero', '1')).to eq(nil) end end end
chuckmersereau/api_practice
app/helpers/application_helper.rb
<filename>app/helpers/application_helper.rb module ApplicationHelper include DisplayCase::ExhibitsHelper include LocalizationHelper def auth_link(provider) if current_user.send("#{provider}_accounts".to_sym).empty? prompt = _('Add an Account') else prompt = _('Add another Account') unless "Person::#{provider.camelcase}Account".constantize.one_per_user? end button_class = 'btn btn-secondary btn-xs' return unless prompt if provider == 'organization' link_to(prompt, '#', class: button_class, data: { behavior: 'add_org_account' }) else link_to(prompt, "/auth/#{provider}", class: button_class) end end def link_to_clear_contact_filters(f) link_to(f, contacts_path(clear_filter: true)) end def tip(tip, options = {}) tag('span', class: 'qtip', title: tip, style: options[:style]) end def spinner(options = {}) id = options[:extra] ? "spinner_#{options[:extra]}" : 'spinner' style = options[:visible] ? '' : 'display:none' image_tag('spinner.gif', id: id, style: style, class: 'spinner') end def l(date, options = {}) options[:format] ||= :date_time date = date.to_datetime unless date.class == Date || date.class == DateTime if date.class == Date date = date.to_datetime.localize(FastGettext.locale).to_date else date = Time.zone.utc_to_local(date) date = date.to_datetime.localize(FastGettext.locale) end if [:full, :long, :medium, :short].include?(options[:format]) date.send("to_#{options[:format]}_s".to_sym) else case options[:format] when :month_abbrv date.to_s(format: 'MMM') when :date_time date.to_short_s else date.to_s(format: options[:format]) end end end def calendar_date_select_tag(name, value = nil, options = {}) options['data-calendar-jquery'] = true options['id'] = '' options['style'] = 'width:100px;' # options.merge!('readonly' => '') value = if value.is_a?(Time) || value.is_a?(DateTime) value.to_date.to_s(:db) elsif value.is_a?(Date) value.to_s(:db) else value end text_field_tag(name, value, options) end def currency_select hash = {} # show account default currency first default = current_account_list.default_currency hash[currency_code_and_symbol(default)] = default TwitterCldr::Shared::Currencies.currency_codes.each do |code| hash[currency_code_and_symbol(code)] = code end hash end def currency_code_and_symbol(code) code + ' (' + currency_symbol(code) + ')' end end
chuckmersereau/api_practice
spec/services/contact/filter/donation_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/services/contact/filter/donation_spec.rb require 'rails_helper' RSpec.describe Contact::Filter::Donation 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, name: 'Contact 1') } let!(:donor_account_one) { create(:donor_account) } let!(:designation_account_one) { create(:designation_account) } let!(:donation_one) do create(:donation, donor_account: donor_account_one, designation_account: designation_account_one) end let!(:contact_two) { create(:contact, account_list_id: account_list.id, name: 'Contact 2') } let!(:donor_account_two) { create(:donor_account) } let!(:designation_account_two) { create(:designation_account) } let!(:donation_two) do create(:donation, donor_account: donor_account_two, designation_account: designation_account_two) end let!(:donation_three) do create(:donation, donor_account: donor_account_two, designation_account: designation_account_two) end let!(:contact_three) { create(:contact, account_list_id: account_list.id, name: 'Contact 3') } let!(:contact_four) { create(:contact, account_list_id: account_list.id, name: 'Contact 4') } before do account_list.designation_accounts << designation_account_one account_list.designation_accounts << designation_account_two contact_one.donor_accounts << donor_account_one contact_two.donor_accounts << donor_account_two donation_one.update(donation_date: 1.year.ago) donation_two.update(donation_date: 1.month.ago) donation_three.update(donation_date: 1.week.ago) end describe '#config' do it 'returns expected config' do expect(described_class.config([account_list])).to include(default_selection: '', multiple: true, name: :donation, options: [ { name: '-- Any --', id: '', placeholder: 'None' }, { name: 'No Gifts', id: 'none' }, { name: 'One or More Gifts', id: 'one' }, { name: 'First Gift', id: 'first' }, { name: 'Last Gift', id: 'last' } ], parent: 'Gift Details', title: 'Gift Options', type: 'multiselect') end end describe '#query' do let(:contacts) { Contact.all } context 'no filter params' do it 'returns nil' do expect(described_class.query(contacts, {}, nil)).to eq(nil) expect(described_class.query(contacts, { donation: {} }, nil)).to eq(nil) expect(described_class.query(contacts, { donation: [] }, nil)).to eq(nil) expect(described_class.query(contacts, { donation: [''] }, nil)).to eq(nil) end end context 'filter by no gifts' do it 'returns only contacts that have never given a donation' do expect( described_class.query(contacts, { donation: 'none' }, [account_list]).to_a ).to match_array [contact_three, contact_four] end end context 'filter by one or more gifts' do it 'returns only contacts that have given at least one gift' do expect( described_class.query(contacts, { donation: 'one' }, [account_list]).to_a ).to match_array [contact_one, contact_two] end end context 'filter by first gift' do it 'returns only contacts that have given a first gift' do expect( described_class.query(contacts, { donation: 'first' }, [account_list]).to_a ).to match_array [contact_one, contact_two] end end context 'filter by last gift' do it 'returns only contacts that have given a last gift' do expect( described_class.query(contacts, { donation: 'last' }, [account_list]).to_a ).to match_array [contact_one, contact_two] end end context 'filter by no gift and gift date' do it 'currently is expected to return no contacts' do expect( Contact::Filterer.new( donation: 'none', donation_date: Range.new(2.years.ago.to_datetime, 6.months.ago.to_datetime) ).filter(scope: contacts, account_lists: [account_list]).to_a ).to match_array [contact_two, contact_three, contact_four] expect( Contact::Filterer.new( donation: 'none', donation_date: Range.new(2.weeks.ago.to_datetime, 1.day.ago.to_datetime) ).filter(scope: contacts, account_lists: [account_list]).to_a ).to match_array [contact_one, contact_three, contact_four] end end context 'filter by one gift and gift date' do it 'returns only contacts that have given at least one gift within the dates specified' do expect( Contact::Filterer.new( donation: 'one', donation_date: Range.new(2.years.ago, 6.months.ago) ).filter(scope: contacts, account_lists: [account_list]).to_a ).to eq [contact_one] expect( Contact::Filterer.new( donation: ['one'], donation_date: Range.new(2.weeks.ago, 1.day.ago) ).filter(scope: contacts, account_lists: [account_list]).to_a ).to eq [contact_two] end end context 'filter by first gift and gift date' do it 'returns only contacts that have given a first gift within the dates specified' do expect( Contact::Filterer.new( donation: 'first', donation_date: Range.new(2.years.ago, 6.months.ago) ).filter(scope: contacts, account_lists: [account_list]).to_a ).to eq [contact_one] expect( Contact::Filterer.new( donation: 'first', donation_date: Range.new(2.weeks.ago, 1.day.ago) ).filter(scope: contacts, account_lists: [account_list]).to_a ).to eq [] end end context 'filter by last gift and gift date' do it 'returns only contacts that have given a last gift within the dates specified' do expect( Contact::Filterer.new( donation: 'last', donation_date: Range.new(2.years.ago, 6.months.ago) ).filter(scope: contacts, account_lists: [account_list]).to_a ).to eq [contact_one] expect( Contact::Filterer.new( donation: 'last', donation_date: Range.new(2.weeks.ago, 1.day.ago) ).filter(scope: contacts, account_lists: [account_list]).to_a ).to eq [contact_two] end end context 'donations to designations outside of the specified account_list' do let!(:account_list_two) { create(:account_list) } let!(:donor_account_three) { create(:donor_account) } let!(:designation_account_three) { create(:designation_account) } let!(:donation_three) do create(:donation, donor_account: donor_account_three, designation_account: designation_account_three) end before do account_list_two.designation_accounts << designation_account_three contact_three.donor_accounts << donor_account_three end context 'filter by no gifts' do it 'returns only contacts that have never given a donation' do expect( described_class.query(contacts, { donation: 'none' }, [account_list]).to_a ).to match_array [contact_three, contact_four] end end end context 'contact has donor_account with donations and donor_account with no donations' do before do contact_three.donor_accounts << donor_account_one contact_three.donor_accounts << create(:donor_account) end context 'filter by no gifts' do it 'returns only contacts that have never given a donation' do expect( described_class.query(contacts, { donation: 'none' }, [account_list]).to_a ).to match_array [contact_four] end end end end end
chuckmersereau/api_practice
app/services/reports/appointment_results.rb
# this class is responsible for building the periods and meta for the report class Reports::AppointmentResults < Reports::Base def meta(fields = {}) results_period_fields = fields['reports_appointment_results_periods'] size = periods_data.count available_fields = [:individual_appointments, :group_appointments, :new_monthly_partners, :new_special_pledges, :monthly_increase, :pledge_increase] available_fields.each_with_object({}) do |key, hash| next unless results_period_fields.nil? || results_period_fields.include?(key.to_s) hash["average_#{key}"] = (periods_data.sum(&key) / size.to_d).round end end protected def generate_report_for_period(start_date:, end_date:) Reports::AppointmentResultsPeriod.new(account_list: account_list, start_date: start_date, end_date: end_date) end end
chuckmersereau/api_practice
app/models/activity_comment.rb
<gh_stars>0 class ActivityComment < ApplicationRecord audited associated_with: :activity, on: [:destroy] belongs_to :activity, counter_cache: true, touch: true belongs_to :person validates :body, presence: true PERMITTED_ATTRIBUTES = [:body, :created_at, :overwrite, :person_id, :updated_at, :updated_in_db_at, :id].freeze end
chuckmersereau/api_practice
spec/factories/pledge_donations.rb
<gh_stars>0 FactoryBot.define do factory :pledge_donation do pledge donation end end
chuckmersereau/api_practice
app/models/notification.rb
class Notification < ApplicationRecord belongs_to :contact, inverse_of: :notifications belongs_to :notification_type belongs_to :donation has_one :account_list, through: :contact has_many :tasks, inverse_of: :notification, dependent: :destroy scope :active, -> { where(cleared: false) } validates :event_date, presence: true PERMITTED_ATTRIBUTES = [:cleared, :contact_id, :created_at, :donation_id, :event_date, :notification_type_id, :overwrite, :updated_at, :updated_in_db_at, :id].freeze end
chuckmersereau/api_practice
spec/controllers/api/v2/contacts/bulk_controller_spec.rb
require 'rails_helper' describe Api::V2::Contacts::BulkController, type: :controller do let!(:account_list) { user.account_lists.order(:created_at).first } let!(:account_list_id) { account_list.id } let!(:factory_type) { :contact } let!(:id) { resource.id } let!(:incorrect_reference_value) { resource.send(reference_key) } let!(:given_reference_key) { :name } let!(:given_reference_value) { correct_attributes[:name] } let!(:resource) { create(:contact_with_person, account_list: account_list) } let!(:second_resource) { create(:contact, account_list: account_list) } let!(:third_resource) { create(:contact, account_list: account_list) } let!(:user) { create(:user_with_account) } let(:resource_type) { :contacts } let!(:correct_attributes) do attributes_for(:contact, name: '<NAME>', tag_list: 'tag1') end let!(:incorrect_attributes) do attributes_for(:contact, name: nil) end let(:relationships) do { account_list: { data: { type: 'account_lists', id: account_list_id } } } end include_examples 'bulk_create_examples' include_examples 'bulk_update_examples' include_examples 'bulk_destroy_examples' end
chuckmersereau/api_practice
spec/controllers/api/v2/contacts/people/relationships_controller_spec.rb
<filename>spec/controllers/api/v2/contacts/people/relationships_controller_spec.rb require 'rails_helper' RSpec.describe Api::V2::Contacts::People::RelationshipsController, type: :controller do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:factory_type) { :family_relationship } let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) } let(:person) { create(:person, contacts: [contact]) } let!(:resource) { create(:family_relationship, person: person) } let!(:second_resource) { create(:family_relationship, person: person) } let(:id) { resource.id } let(:parent_param) { { contact_id: contact.id, person_id: person.id } } let(:correct_attributes) { { relationship: 'Father' } } let(:correct_relationships) do { related_person: { data: { type: 'people', id: create(:person, contacts: [contact]).id } } } end let(:incorrect_attributes) { { relationship: nil } } let(:incorrect_relationships) { {} } include_examples 'show_examples' include_examples 'update_examples' include_examples 'create_examples' include_examples 'destroy_examples' include_examples 'index_examples' end
chuckmersereau/api_practice
app/models/mail_chimp_member.rb
<filename>app/models/mail_chimp_member.rb class MailChimpMember < ApplicationRecord belongs_to :mail_chimp_account audited associated_with: :mail_chimp_account def email=(email) super(email&.downcase) end def self.mpdx_unsubscribe?(member) reason = member.is_a?(Hash) ? member['unsubscribe_reason'] : member return false unless reason # if MPDX removed the contact from the list it will be something like this # we have seen two different values: N/A (Unsubscribed by an admin) and N/A (Unsubscribed by admin) (reason =~ %r(N/A \(Unsubscribed by( an)? admin\))).present? end end
chuckmersereau/api_practice
app/controllers/api/v2/tasks/tags_controller.rb
<reponame>chuckmersereau/api_practice<filename>app/controllers/api/v2/tasks/tags_controller.rb class Api::V2::Tasks::TagsController < Api::V2Controller def index authorize_index load_tags render json: @tags, status: success_status, include: include_params, fields: field_params end def create load_task authorize_task persist_tag(tag_params[:name]) do |tag_name| @task.tag_list.add(tag_name) end end def destroy load_task authorize_task destroy_tag end private def load_tags @tags ||= account_lists.map(&:activity_tags).flatten.uniq.sort_by(&:name) end def authorize_index account_lists.each { |account_list| authorize(account_list, :show?) } end def destroy_tag persist_tag(params[:tag_name]) do |tag_name| @task.tag_list.remove(tag_name) end head :no_content end def persist_tag(tag_name) tag_error = TagValidator.new.validate(tag_name) if tag_error render_with_resource_errors(tag_error) else yield(tag_name) @task.save(context: persistence_context) render json: @task, status: success_status, include: include_params, fields: field_params end end def load_task @task ||= Task.find(params[:task_id]) end def authorize_task authorize @task end def permitted_filters [:account_list_id] end def tag_params params.require(:tag).permit(:name) end end
chuckmersereau/api_practice
db/migrate/20170707013656_add_indexes_to_activities_and_donor_accounts.rb
class AddIndexesToActivitiesAndDonorAccounts < ActiveRecord::Migration disable_ddl_transaction! def change remove_index :activities, column: :account_list_id, name: :index_activities_on_account_list_id, algorithm: :concurrently add_index :donor_accounts, :account_number, name: 'index_donor_accounts_on_account_number', algorithm: :concurrently add_index :activities, [:account_list_id, :completed], name: 'activities_on_list_id_completed', algorithm: :concurrently end end
chuckmersereau/api_practice
spec/services/contact/filter/pledge_amount_increased_range_spec.rb
<filename>spec/services/contact/filter/pledge_amount_increased_range_spec.rb require 'rails_helper' RSpec.describe Contact::Filter::PledgeAmountIncreasedRange do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } describe '#query' do let!(:increasing_contact) do create( :contact, account_list: account_list, pledge_amount: 150, pledge_frequency: 1, first_donation_date: 4.months.ago ) end let!(:second_contact) do create( :contact, account_list: account_list, pledge_amount: 20.00, first_donation_date: 3.months.ago ) end let!(:third_contact) do create( :contact, account_list: account_list, pledge_amount: 40.00, first_donation_date: 7.months.ago ) end let!(:first_partner_status_log) do create( :partner_status_log, contact: increasing_contact, pledge_amount: 50.00, pledge_frequency: 1, recorded_on: 2.months.ago ) end let!(:second_partner_status_log) do create( :partner_status_log, contact: increasing_contact, pledge_amount: 50.00, pledge_frequency: 0.5, recorded_on: 1.month.ago ) end let!(:third_partner_status_log) do create( :partner_status_log, contact: second_contact, pledge_amount: 60.00, pledge_frequency: 0.5, recorded_on: 2.months.ago ) end let!(:fourth_partner_status_log) do create( :partner_status_log, contact: second_contact, pledge_amount: 40.00, pledge_frequency: 0.5, recorded_on: 1.month.ago ) end let!(:fifth_partner_status_log) do create( :partner_status_log, contact: third_contact, pledge_amount: 50.00, pledge_frequency: 1, recorded_on: 5.months.ago ) end let!(:sixth_partner_status_log) do create( :partner_status_log, contact: third_contact, pledge_amount: 50.00, pledge_frequency: 0.5, recorded_on: 3.months.ago ) end let(:contacts) { Contact.all } context 'contacts that have increased their pledge amount and or frequency' do it 'returns the correct contacts' do expect( described_class.query( contacts, { pledge_amount_increased_range: Range.new(3.months.ago.to_datetime, DateTime.now.getlocal) }, nil ) ).to eq([increasing_contact]) end end end end
chuckmersereau/api_practice
app/services/contact/filter/donation_amount.rb
<filename>app/services/contact/filter/donation_amount.rb class Contact::Filter::DonationAmount < Contact::Filter::Base def execute_query(contacts, filters) contacts = contacts.joins(donor_accounts: [:donations]) contacts = contacts.where('donations.amount IN (:amounts) AND donations.designation_account_id IN (:designation_account_ids)', amounts: parse_list(filters[:donation_amount]), designation_account_ids: designation_account_ids) contacts end def title _('Exact Gift Amount') end def parent _('Gift Details') end def type 'multiselect' end def custom_options account_lists.collect { |account_list| account_list.donations.where.not(amount: nil).pluck(:amount) } .flatten .uniq .sort .collect { |amount| { name: amount, id: amount } } end end
chuckmersereau/api_practice
db/migrate/20120330150711_create_partners.rb
class CreatePartners < ActiveRecord::Migration def change create_table :contacts do |t| t.string :name t.belongs_to :donor_account t.belongs_to :account_list t.timestamps null: false end add_index :contacts, [:donor_account_id, :account_list_id], unique: true add_index :contacts, :account_list_id remove_column :people, :account_list_id # Make address polymorphic add_column :addresses, :addressable_type, :string rename_column :addresses, :person_id, :addressable_id ActiveRecord::Base.connection.update("update addresses set addressable_type = 'Person'") end end
chuckmersereau/api_practice
spec/serializers/google_integration_serializer_spec.rb
require 'rails_helper' describe GoogleIntegrationSerializer do let(:cru_cal_id) { 'cru.<EMAIL>' } let(:google_integration) { create(:google_integration) } let(:calendar_list_entry_one) do double(id: cru_cal_id, summary: 'MPDX Scrum', access_role: 'owner') end let(:calendar_list_entry_two) do double(id: '<EMAIL>', summary: '<EMAIL>', access_role: 'owner') end subject { GoogleIntegrationSerializer.new(google_integration).as_json } describe '#calendars' do before do allow(google_integration).to(receive(:calendars) .and_return([calendar_list_entry_one, calendar_list_entry_two])) end it 'returns a list of calendars with id and name' do expect(subject[:calendars]).to eq [{ id: cru_cal_id, name: 'MPDX Scrum' }, { id: '<EMAIL>', name: '<EMAIL>' }] end end end