repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
chuckmersereau/api_practice
db/migrate/20140730113153_add_historic_to_email_addresses.rb
<reponame>chuckmersereau/api_practice<filename>db/migrate/20140730113153_add_historic_to_email_addresses.rb class AddHistoricToEmailAddresses < ActiveRecord::Migration def change add_column :email_addresses, :historic, :boolean, default: false end end
chuckmersereau/api_practice
app/models/audited/audit_elastic.rb
require 'elasticsearch/persistence/model' module Audited class AuditElastic include Elasticsearch::Persistence::Model INDEX_BASE = ['mpdx', 'uuid', Rails.env].join('-').freeze index_name [INDEX_BASE, Date.today.to_s.tr('-', '.')].join('-') attribute :auditable_id, String attribute :auditable_type, String attribute :associated_id, String attribute :associated_type, String attribute :user_id, String attribute :user_type, String attribute :action, String attribute :audited_changes, String attribute :comment, String attribute :remote_address, String attribute :request_uuid, String attribute :created_at, DateTime def parsed_audited_changes JSON.parse audited_changes.gsub('=>', ':').gsub('nil', 'null') end def undo(comment = nil) object = audited_object object.audit_comment = comment if action == 'create' # destroys a newly created record object.destroy! elsif action == 'destroy' # creates a new record with the destroyed record attributes object.save else # changes back attributes parsed_audited_changes.each { |attrs, changes| object[attrs] = changes[0] } object.save end end def audited_object model = auditable_type.constantize return model.find(auditable_id) unless action == 'destroy' auditable_type.constantize.new(parsed_audited_changes) end def user return user_type unless user_id user_type.constantize.find(user_id) end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/people_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'People' do include_context :json_headers documentation_scope = :entities_people let!(:user) { create(:user_with_full_account) } let(:resource_type) { 'people' } let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) } let(:contact_id) { contact.id } let!(:resource) { create(:person).tap { |person| create(:contact_person, contact: contact, person: person) } } let(:id) { resource.id } let(:new_resource) do attributes_for(:person, first_name: 'Mpdx') .reject { |key| key.to_s.end_with?('_id') } .merge(overwrite: true) end let(:relationship_person) { create(:person) } let(:form_data) { build_data(new_resource) } let(:resource_attributes) do %w( anniversary_day anniversary_month anniversary_year avatar birthday_day birthday_month birthday_year created_at deceased employer first_name gender last_name legal_first_name marital_status middle_name occupation optout_enewsletter parent_contacts suffix title updated_at updated_in_db_at ) end let(:resource_associations) do %w( email_addresses facebook_accounts family_relationships linkedin_accounts phone_numbers twitter_accounts websites ) end let(:nested_family_relationship_data) do { included: [ { attributes: { relationship: 'Nephew' }, relationships: { related_person: { data: { type: 'people', id: relationship_person.id } } }, type: 'family_relationships', id: 'ce1e9746-2b34-4d3d-9357-292a950e681a' } ], data: { relationships: { linkedin_accounts: { data: nil }, facebook_accounts: { data: nil }, family_relationships: { data: [ { type: 'family_relationships', id: 'ce1e9746-2b34-4d3d-9357-292a950e681a' } ] }, websites: { data: nil }, email_addresses: { data: nil } }, attributes: { birthday_year: nil, first_name: 'new', last_name: 'person', middle_name: nil, suffix: nil, title: nil, gender: 'female', created_at: resource.created_at, marital_status: 'Married', updated_at: resource.updated_at, anniversary_day: nil, anniversary_month: nil, birthday_day: nil, overwrite: true, anniversary_year: nil, birthday_month: nil, deceased: false }, type: 'people', id: resource.id } } end documentation_scope = :entities_people context 'authorized user' do before { api_login(user) } get '/api/v2/contacts/people' do parameter 'filter[deceased]', 'Filter by deceased; Accepts values "true" and "false"', required: false parameter 'filter[email_address_valid]', %(Filter by Email Address Invalid; A Person's Email \ Address is invalid if the Email Address's valid_values \ attribute is set to false, or if the Person has \ multiple Email Addresses marked as primary; \ Accepts value "false"), required: false parameter 'filter[phone_number_valid]', %(Filter by Phone Number Invalid; A Person's Phone \ Number is invalid if the Phone Number's valid_values \ attribute is set to false, or if the Person has \ multiple Phone Numbers marked as primary; \ Accepts value "false"), required: false parameter 'filter[updated_at]', %(Filter by Updated At Date range; Accepts date range \ with text value like"MM/DD/YYYY - MM/DD/YYYY"), required: false parameter 'filter[wildcard_search]', %(Filter by keyword, searches through \ name, email_addresses and phone_numbers), required: false parameter 'filter[any_filters]', 'If set to true any result where at least one '\ 'of the filters apply will be returned', required: false parameter 'filter[reverse_FILTER_NAME]', 'If set to true, the filter defined as FILTER_NAME '\ "will return results that don't apply", required: false example 'List people', document: documentation_scope do explanation 'List of People' do_request check_collection_resource(1, ['relationships']) expect(response_status).to eq(200) end end get '/api/v2/contacts/people/:id' do with_options scope: :data do with_options scope: :attributes do response_field 'anniversary_day', 'Anniversary Day', type: 'Number' response_field 'anniversary_month', 'Anniversary Month', type: 'Number' response_field 'anniversary_year', 'Anniversary Year', type: 'Number' response_field 'avatar', 'Avatar', type: 'String' response_field 'birthday_day', 'Birthday Day', type: 'Number' response_field 'birthday_month', 'Birthday Month', type: 'Number' response_field 'birthday_year', 'Birthday Year', type: 'Number' response_field 'created_at', 'Created At', type: 'String' response_field 'deceased', 'Deceased', type: 'Boolean' response_field 'employer', 'Employer', type: 'String' response_field 'first_name', 'First Name', type: 'String' response_field 'gender', 'Gender', type: 'String' response_field 'last_name', 'Last Name', type: 'String' response_field 'legal_first_name', 'Legal First Name', type: 'String' response_field 'marital_status', 'Marital Status', type: 'String' response_field 'master_person_id', 'Master Person ID', type: 'Number' response_field 'middle_name', 'Middle Name', type: 'String' response_field 'occupation', 'Occupation', type: 'String' response_field 'optout_enewsletter', 'Optout of Enewsletter or not', type: 'Boolean' response_field 'parent_contacts', 'Array of Parent Contact Ids', type: 'Array' response_field 'suffix', 'Suffix', type: 'String' response_field 'title', 'Title', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end with_options scope: :relationships do response_field 'email_addresses', 'Email Addresses', type: 'Object' response_field 'facebook_accounts', 'Facebook Account', type: 'Object' response_field 'phone_numbers', 'Phone Number', type: 'Object' end end example 'Retrieve a person', document: documentation_scope do explanation 'The Contact\'s Person with the given ID' do_request expect(response_status).to eq(200), invalid_status_detail check_resource(['relationships']) end end put '/api/v2/contacts/people/:id' do example 'Update a person', document: documentation_scope do explanation 'Update the Person with the given ID' do_request data: form_data expect(response_status).to eq(200), invalid_status_detail expect(resource_object['first_name']).to(be_present) && eq(new_resource['first_name']) end end delete '/api/v2/contacts/people/:id' do example 'Delete a person', document: documentation_scope do explanation 'Delete the Contact\'s Person with the given ID' do_request expect(response_status).to eq(204), invalid_status_detail end end get '/api/v2/contacts/:contact_id/people' do example 'List people for a contact', document: documentation_scope do explanation 'List of People associated to the Contact' do_request expect(response_status).to eq(200), invalid_status_detail check_collection_resource(1, ['relationships']) end end get '/api/v2/contacts/:contact_id/people/:id' do with_options scope: :data do with_options scope: :attributes do response_field 'anniversary_day', 'Anniversary Day', type: 'Number' response_field 'anniversary_month', 'Anniversary Month', type: 'Number' response_field 'anniversary_year', 'Anniversary Year', type: 'Number' response_field 'avatar', 'Avatar', type: 'String' response_field 'birthday_day', 'Birthday Day', type: 'Number' response_field 'birthday_month', 'Birthday Month', type: 'Number' response_field 'birthday_year', 'Birthday Year', type: 'Number' response_field 'created_at', 'Created At', type: 'String' response_field 'deceased', 'Deceased', type: 'Boolean' response_field 'employer', 'Employer', type: 'String' response_field 'first_name', 'First Name', type: 'String' response_field 'gender', 'Gender', type: 'String' response_field 'last_name', 'Last Name', type: 'String' response_field 'legal_first_name', 'Legal First Name', type: 'String' response_field 'marital_status', 'Marital Status', type: 'String' response_field 'master_person_id', 'Master Person ID', type: 'Number' response_field 'middle_name', 'Middle Name', type: 'String' response_field 'occupation', 'Occupation', type: 'String' response_field 'optout_enewsletter', 'Optout of Enewsletter or not', type: 'Boolean' response_field 'parent_contacts', 'Array of Parent Contact Ids', type: 'Array' response_field 'suffix', 'Suffix', type: 'String' response_field 'title', 'Title', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end with_options scope: :relationships do response_field 'email_addresses', 'Email Addresses', type: 'Object' response_field 'facebook_accounts', 'Facebook Account', type: 'Object' response_field 'phone_numbers', 'Phone Number', type: 'Object' end end example 'Retrieve a person', document: documentation_scope do explanation 'The Contact\'s Person with the given ID and Contact ID' do_request expect(response_status).to eq(200), invalid_status_detail check_resource(['relationships']) end end post '/api/v2/contacts/:contact_id/people' do with_options scope: [:data, :attributes] do with_options required: true do parameter 'first_name', '<NAME>', type: 'String' end # rubocop:disable Metrics/LineLength parameter 'anniversary_day', 'Anniversary Day', type: 'Number' parameter 'anniversary_month', 'Anniversary Month', type: 'Number' parameter 'anniversary_year', 'Anniversary Year', type: 'Number' parameter 'birthday_day', 'Birthday Day', type: 'Number' parameter 'birthday_month', 'Birthday Month', type: 'Number' parameter 'birthday_year', 'Birthday Year', type: 'Number' parameter 'deceased', 'Deceased', type: 'Boolean' parameter 'email_address[email]', 'Email Address', type: 'String' parameter 'employer', 'Employer', type: 'String' parameter 'employer', 'Employer', type: 'String' parameter 'gender', 'Gender', type: 'String' parameter 'last_name', 'Last Name', type: 'String' parameter 'legal_first_name', 'Legal First Name', type: 'String' parameter 'legal_first_name', 'Legal First Name', type: 'String' parameter 'marital_status', 'Marital Status', type: 'String' parameter 'middle_name', 'Middle Name', type: 'String' parameter 'occupation', 'Occupation', type: 'String' parameter 'occupation', 'Occupation', type: 'String' parameter 'optout_enewsletter', 'Optout Enewsletter', type: 'Boolean' parameter 'optout_enewsletter', 'Optout of Enewsletter or not', type: 'Boolean' parameter 'phone_number[number]', 'Phone Number', type: 'String' parameter 'suffix', 'Suffix', type: 'String' parameter 'title', 'Title', type: 'String' parameter 'email_addresses_attributes[:key][_destroy]', 'Destroy Email Address if set to 1, where :key is an integer', type: 'Number' parameter 'email_addresses_attributes[:key][email]', 'Email Address Email, where :key is an integer', type: 'String' parameter 'email_addresses_attributes[:key][historic]', 'Email Address Historic, where :key is an integer', type: 'Boolean' parameter 'email_addresses_attributes[:key][id]', 'Email Address ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'email_addresses_attributes[:key][primary]', 'Email Address Primary, where :key is an integer', type: 'String' parameter 'family_relationships_attributes[:key][_destroy]', 'Destroy Family Relationship if set to 1, where :key is an integer', type: 'Number' parameter 'family_relationships_attributes[:key][id]', 'Family Relationship ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'family_relationships_attributes[:key][related_person_id]', 'Family Relationship Related Persion ID, where :key is an integer', type: 'String' parameter 'family_relationships_attributes[:key][relationship]', 'Family Relationship Relationship, where :key is an integer', type: 'String' parameter 'linkedin_accounts_attributes[:key][_destroy]', 'Destroy LinkedIn Account if set to 1, where :key is an integer', type: 'Number' parameter 'linkedin_accounts_attributes[:key][id]', 'LinkedIn Account ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'linkedin_accounts_attributes[:key][url]', 'LinkedIn Account URL, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][_destroy]', 'Destroy Phone Number if set to 1, where :key is an integer', type: 'Number' parameter 'phone_numbers_attributes[:key][historic]', 'Phone Number Historic, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][id]', 'Phone Number ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][location]', 'Phone Number Location, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][number]', 'Phone Number, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][primary]', 'Phone Number Primary, where :key is an integer', type: 'Boolean' parameter 'pictures_attributes[:key][_destroy]', 'Destroy Picture if set to 1, where :key is an integer', type: 'Number' parameter 'pictures_attributes[:key][id]', 'Picture ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'pictures_attributes[:key][image_cache]', 'Picture Image Cache, where :key is an integer', type: 'String' parameter 'pictures_attributes[:key][image]', 'Picture Image, where :key is an integer', type: 'String' parameter 'pictures_attributes[:key][primary]', 'Picture Primary, where :key is an integer', type: 'Boolean' parameter 'twitter_accounts_attributes[:key][_destroy]', 'Destroy Twitter Account if set to 1, where :key is an integer', type: 'Number' parameter 'twitter_accounts_attributes[:key][id]', 'Twitter Account ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'twitter_accounts_attributes[:key][screen_name]', 'Twitter Account Screen Name, where :key is an integer', type: 'String' parameter 'websites_attributes[:key][_destroy]', 'Destroy Website if set to 1, where :key is an integer', type: 'Number' parameter 'websites_attributes[:key][id]', 'Website ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'websites_attributes[:key][primary]', 'Website Primary, where :key is an integer', type: 'Boolean' parameter 'websites_attributes[:key][url]', 'Website URL, where :key is an integer', type: 'String' end example 'Create a person', document: documentation_scope do explanation 'Create a Person associated with the Contact' do_request data: form_data expect(response_status).to eq(201), invalid_status_detail expect(resource_object['first_name']).to(be_present) && eq(new_resource['first_name']) end end put '/api/v2/contacts/:contact_id/people/:id' do with_options scope: [:data, :attributes] do with_options required: true do parameter 'first_name', '<NAME>', type: 'String' end parameter 'anniversary_day', 'Anniversary Day', type: 'Number' parameter 'anniversary_month', 'Anniversary Month', type: 'Number' parameter 'anniversary_year', 'Anniversary Year', type: 'Number' parameter 'birthday_day', 'Birthday Day', type: 'Number' parameter 'birthday_month', 'Birthday Month', type: 'Number' parameter 'birthday_year', 'Birthday Year', type: 'Number' parameter 'deceased', 'Deceased', type: 'Boolean' parameter 'employer', 'Employer', type: 'String' parameter 'gender', 'Gender', type: 'String' parameter 'last_name', 'Last Name', type: 'String' parameter 'legal_first_name', 'Legal First Name', type: 'String' parameter 'marital_status', 'Marital Status', type: 'String' parameter 'middle_name', 'Middle Name', type: 'String' parameter 'occupation', 'Occupation', type: 'String' parameter 'optout_enewsletter', 'Optout Enewsletter', type: 'Boolean' parameter 'suffix', 'Suffix', type: 'String' parameter 'title', 'Title', type: 'String' parameter 'email_address[email]', 'Email Address', type: 'String' parameter 'phone_number[number]', 'Phone Number', type: 'String' parameter 'email_addresses_attributes[:key][_destroy]', 'Destroy Email Address if set to 1, where :key is an integer', type: 'Number' parameter 'email_addresses_attributes[:key][email]', 'Email Address Email, where :key is an integer', type: 'String' parameter 'email_addresses_attributes[:key][historic]', 'Email Address Historic, where :key is an integer', type: 'Boolean' parameter 'email_addresses_attributes[:key][id]', 'Email Address ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'email_addresses_attributes[:key][primary]', 'Email Address Primary, where :key is an integer', type: 'String' parameter 'family_relationships_attributes[:key][_destroy]', 'Destroy Family Relationship if set to 1, where :key is an integer', type: 'Number' parameter 'family_relationships_attributes[:key][id]', 'Family Relationship ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'family_relationships_attributes[:key][related_person_id]', 'Family Relationship Related Persion ID, where :key is an integer', type: 'String' parameter 'family_relationships_attributes[:key][relationship]', 'Family Relationship Relationship, where :key is an integer', type: 'String' parameter 'linkedin_accounts_attributes[:key][_destroy]', 'Destroy LinkedIn Account if set to 1, where :key is an integer', type: 'Number' parameter 'linkedin_accounts_attributes[:key][id]', 'LinkedIn Account ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'linkedin_accounts_attributes[:key][url]', 'LinkedIn Account URL, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][_destroy]', 'Destroy Phone Number if set to 1, where :key is an integer', type: 'Number' parameter 'phone_numbers_attributes[:key][historic]', 'Phone Number Historic, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][id]', 'Phone Number ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][location]', 'Phone Number Location, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][number]', 'Phone Number, where :key is an integer', type: 'String' parameter 'phone_numbers_attributes[:key][primary]', 'Phone Number Primary, where :key is an integer', type: 'Boolean' parameter 'pictures_attributes[:key][_destroy]', 'Destroy Picture if set to 1, where :key is an integer', type: 'Number' parameter 'pictures_attributes[:key][id]', 'Picture ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'pictures_attributes[:key][image_cache]', 'Picture Image Cache, where :key is an integer', type: 'String' parameter 'pictures_attributes[:key][image]', 'Picture Image, where :key is an integer', type: 'String' parameter 'pictures_attributes[:key][primary]', 'Picture Primary, where :key is an integer', type: 'Boolean' parameter 'twitter_accounts_attributes[:key][_destroy]', 'Destroy Twitter Account if set to 1, where :key is an integer', type: 'Number' parameter 'twitter_accounts_attributes[:key][id]', 'Twitter Account ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'twitter_accounts_attributes[:key][screen_name]', 'Twitter Account Screen Name, where :key is an integer', type: 'String' parameter 'websites_attributes[:key][_destroy]', 'Destroy Website if set to 1, where :key is an integer', type: 'Number' parameter 'websites_attributes[:key][id]', 'Website ID, omit to create a new record, where :key is an integer', type: 'String' parameter 'websites_attributes[:key][primary]', 'Website Primary, where :key is an integer', type: 'Boolean' parameter 'websites_attributes[:key][url]', 'Website URL, where :key is an integer', type: 'String' # rubocop:enabled Metrics/LineLength end example 'Update a person', document: documentation_scope do explanation 'Update the Contact\'s Person with the given ID and Contact ID' do_request data: form_data expect(response_status).to eq(200), invalid_status_detail expect(resource_object['first_name']).to(be_present) && eq(new_resource['first_name']) end end put '/api/v2/contacts/:contact_id/people/:id' do example 'Person Nested Family Relationships', document: :private do explanation 'Create a family relationship for the person' expect(resource.family_relationships).to be_empty do_request nested_family_relationship_data expect(response_status).to eq(200), invalid_status_detail expect(resource.reload.family_relationships).not_to be_empty end end delete '/api/v2/contacts/:contact_id/people/:id' do example 'Delete a person', document: documentation_scope do explanation 'Delete the Contact\'s Person with the given ID and Contact ID' do_request expect(response_status).to eq(204), invalid_status_detail end end end end
chuckmersereau/api_practice
spec/lib/google_contacts_cache_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' require 'google_contacts_cache' describe GoogleContactsCache do let(:john1) { double(id: 'john1', given_name: 'John', family_name: 'Doe') } let(:john2) { double(id: 'john2', given_name: 'John', family_name: 'Doe') } let(:jane1) { double(id: 'jane1', given_name: 'Jane', family_name: 'Doe') } let(:jane2) { double(id: 'jane2', given_name: '<NAME>', family_name: '') } let(:account) { build(:google_account) } let(:cache) { GoogleContactsCache.new(account) } describe 'find_by_id' do it 'handles a missing id' do expect(cache.find_by_id(nil)).to eq(nil) expect(cache.find_by_id('')).to eq(nil) expect(cache.find_by_id(' ')).to eq(nil) end end describe 'cache_all_g_contacts' do it 'calls the api and caches all retrieved contacts' do api_user = double expect(account).to receive(:contacts_api_user).and_return(api_user) expect(api_user).to receive(:contacts).and_return([john1]) expect(cache).to receive(:cache_g_contacts).with([john1], true) cache.cache_all_g_contacts end end describe 'cache_g_contacts' do it 'retrieves cached g_contacts; when set to cache all returns nil and not in cache' do cache.cache_g_contacts([john1, john2], true) expect(cache.find_by_id('john1')).to eq(john1) expect(cache.find_by_id('john2')).to eq(john2) expect(cache.find_by_id('not-john')).to be_nil expect(cache.query_by_full_name('<NAME>')).to eq([john1, john2]) expect(cache.query_by_full_name('Not-John')).to eq([]) end it 'retrieves cached g_contacts; when not set to cache all, calls the api when not in cache' do cache.cache_g_contacts([john1, john2], false) expect(cache.find_by_id('john1')).to eq(john1) expect(cache.find_by_id('john2')).to eq(john2) api_user = double expect(account).to receive(:contacts_api_user).and_return(api_user) api_john = double expect(api_user).to receive(:get_contact).with('api_john').and_return(api_john) expect(api_john).to receive(:deleted?).and_return(false) expect(cache.find_by_id('api_john')).to eq(api_john) expect(account).to receive(:contacts_api_user).and_return(api_user) api_john_query = double expect(api_user).to receive(:query_contacts).with('Api John', showdeleted: false).and_return([api_john_query]) expect(cache.query_by_full_name('Api John')).to eq([api_john_query]) end end describe 'remove a contact from cache' do it 'allows you to remove a contact from the cache and then will call the api for get contact after that' do cache.cache_g_contacts([john1, john2], true) expect(cache.find_by_id('john1')).to eq(john1) expect(cache.find_by_id('john2')).to eq(john2) expect(cache.query_by_full_name('<NAME>')).to eq([john1, john2]) expect(cache.find_by_id('not-john')).to be_nil expect(cache.query_by_full_name('Not-John')).to eq([]) cache.remove_g_contact(john1) expect(cache.find_by_id('john2')).to eq(john2) expect(cache.query_by_full_name('<NAME>')).to eq([john2]) api_user = double expect(account).to receive(:contacts_api_user).and_return(api_user) api_john1 = double expect(api_user).to receive(:get_contact).with('john1').and_return(api_john1) expect(api_john1).to receive(:deleted?).and_return(false) expect(cache.find_by_id('john1')).to eq(api_john1) end end end
chuckmersereau/api_practice
app/controllers/api/v2/contacts/people/duplicates_controller.rb
<filename>app/controllers/api/v2/contacts/people/duplicates_controller.rb class Api::V2::Contacts::People::DuplicatesController < Api::V2Controller resource_type :duplicate_record_pairs def index authorize_index find_more_duplicates load_duplicates render_duplicates end def show load_duplicate authorize_duplicate render_duplicate end def update load_duplicate authorize_duplicate persist_duplicate end private def authorize_index account_lists.each { |account_list| authorize(account_list, :show?) } end def authorize_duplicate @duplicate.records.each { |person| authorize(person, :update?) } authorize(@duplicate.account_list, :update?) end def duplicates_scope DuplicateRecordPair.type('Person').where(account_list: account_lists) end def find_more_duplicates account_lists.each do |account_list| Person::DuplicatePairsFinder.new(account_list).find_and_save end end def load_duplicates @duplicates = duplicates_scope.where(filter_params) .reorder(sorting_param) .order(default_sort_param) .page(page_number_param) .per(per_page_param) end def load_duplicate @duplicate = DuplicateRecordPair.type('Person').find(params[:id]) end def build_duplicate @duplicate ||= DuplicateRecordPair.new(type: 'Person') @duplicate.assign_attributes(duplicate_params) end def save_duplicate @duplicate.save(context: persistence_context) end def persist_duplicate build_duplicate authorize_duplicate if save_duplicate render_duplicate else render_with_resource_errors(@duplicate) end end def duplicate_params params.require(:duplicate_record_pair) .permit(DuplicateRecordPair::PERMITTED_ATTRIBUTES) end def render_duplicate render json: @duplicate, status: success_status, include: include_params, fields: field_params end def render_duplicates render json: @duplicates, meta: meta_hash(@duplicates), include: include_params, fields: field_params end def permitted_filters [:account_list_id, :ignore] end def pundit_user PunditContext.new(current_user) end def default_sort_param DuplicateRecordPair.arel_table[:created_at].asc end end
chuckmersereau/api_practice
app/serializers/task_serializer.rb
class TaskSerializer < ActivitySerializer end
chuckmersereau/api_practice
spec/factories/master_person_sources.rb
FactoryBot.define do factory :master_person_source do association :master_person association :organization remote_id 'MyString' end end
chuckmersereau/api_practice
app/serializers/notification_preference_serializer.rb
<filename>app/serializers/notification_preference_serializer.rb class NotificationPreferenceSerializer < ApplicationSerializer attributes :email, :task belongs_to :notification_type end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/tags_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > Tags' do include_context :json_headers documentation_scope = :contacts_api_tags let(:resource_type) { :tags } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let!(:contact) { create(:contact, account_list: account_list) } let(:contact_id) { contact.id } let(:tag_name) { 'new_tag' } let(:new_tag_params) { { name: tag_name } } let(:form_data) { build_data(new_tag_params) } context 'authorized user' do before { api_login(user) } get '/api/v2/contacts/tags' do let!(:account_list_two) { create(:account_list) } let!(:contact_one) { create(:contact, account_list: account_list, tag_list: [tag_name]) } let!(:contact_two) { create(:contact, account_list: account_list_two, tag_list: [tag_name]) } before { user.account_lists << account_list_two } example 'Tag [LIST]', document: documentation_scope do explanation 'List Contact Tags' do_request expect(resource_data.count).to eq 1 expect(first_or_only_item['type']).to eq 'tags' expect(resource_object.keys).to match_array(%w(name)) expect(response_status).to eq 200 end end post '/api/v2/contacts/:contact_id/tags' do with_options scope: [:data, :attributes] do parameter 'name', 'name of Tag' end example 'Tag [CREATE]', document: documentation_scope do explanation 'Create a Tag associated with the Contact' do_request data: form_data expect(resource_object['tag_list'].first).to eq new_tag_params[:name] expect(response_status).to eq 201 end end delete '/api/v2/contacts/:contact_id/tags/:tag_name' do parameter 'contact_id', 'the Contact id of the Tag' parameter 'tag_name', 'the Id of the Tag' example 'Tag [DELETE]', document: documentation_scope do explanation 'Delete the Contact\'s Tag with the given name' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
app/models/master_address.rb
<filename>app/models/master_address.rb class MasterAddress < ApplicationRecord has_many :addresses serialize :smarty_response, JSON scope :requires_geocode, lambda { where(latitude: [nil, '']) .where('updated_at::timestamp(0) > last_geocoded_at::timestamp(0) OR last_geocoded_at IS NULL') } def geo return unless latitude.present? && longitude.present? latitude + ',' + longitude end def self.populate_lat_long requires_geocode.find_each do |master_address| next unless master_address.geocode sleep 0.1 end end def find_timezone geocode return unless latitude.present? && longitude.present? timezone = GoogleTimezone.fetch(latitude, longitude).time_zone_id return ActiveSupport::TimeZone::MAPPING.invert[timezone] if ActiveSupport::TimeZone::MAPPING.invert[timezone] timezone if Time.now.in_time_zone(timezone) rescue ArgumentError nil end def geocode return false unless requires_geocode? assign_lat_long_from_smarty_response assign_lat_long_from_geocoder if longitude.blank? || latitude.blank? self.last_geocoded_at = Time.current save true end private def requires_geocode? return false if latitude.present? && longitude.present? return true if last_geocoded_at.blank? updated_at.to_i > last_geocoded_at.to_i end def assign_lat_long_from_smarty_response return unless smarty_response && smarty_response[0] && smarty_response[0]['metadata'] meta = smarty_response[0]['metadata'] self.latitude = meta['latitude'].to_s self.longitude = meta['longitude'].to_s end def assign_lat_long_from_geocoder lat, long = Geocoder.coordinates([street, city, state, country].join(',')) self.latitude = lat.to_s self.longitude = long.to_s end end
chuckmersereau/api_practice
spec/models/donor_account_spec.rb
<filename>spec/models/donor_account_spec.rb<gh_stars>0 require 'rails_helper' describe DonorAccount do before(:each) do @donor_account = create(:donor_account) end it 'should have one primary_master_person' do @mp1 = create(:master_person) @donor_account.master_people << @mp1 expect(@donor_account.primary_master_person).to eq(@mp1) expect do @donor_account.master_people << create(:master_person) expect(@donor_account.primary_master_person).to eq(@mp1) end.to_not change(MasterPersonDonorAccount.primary, :count) end describe '#link_to_contact_for' do before do @account_list = create(:account_list) end it 'returns an already linked contact' do contact = create(:contact, account_list: @account_list) contact.donor_accounts << @donor_account expect(@donor_account.link_to_contact_for(@account_list)).to eq(contact) end it 'links a contact based on a matching name' do contact = create(:contact, account_list: @account_list, name: @donor_account.name) new_contact = @donor_account.link_to_contact_for(@account_list) expect(new_contact).to eq(contact) expect(new_contact.donor_account_ids).to include(@donor_account.id) end it 'creates a new contact if no match is found' do expect do @donor_account.link_to_contact_for(@account_list) end.to change(Contact, :count) end it 'does not match to a contact with no addresses' do create(:contact, account_list: @account_list) create(:address, addressable: @donor_account) expect do @donor_account.link_to_contact_for(@account_list) end.to change(Contact, :count) end context 'with a blank name' do before { @donor_account.update!(name: '') } it 'does not raise an ActiveRecord::RecordInvalid error' do expect do @donor_account.link_to_contact_for(@account_list) end.not_to raise_error end it 'creates a contact with a fallback name' do contact = @donor_account.link_to_contact_for(@account_list) expect(contact.name).to eq 'Donor' end end end describe '#name' do context 'with a name present' do before { @donor_account.update!(name: 'Bob') } it 'creates a contact with a fallback name' do expect(@donor_account.name).to eq 'Bob' end end context 'with a blank name' do before { @donor_account.update!(name: '') } it 'creates a contact with a fallback name' do expect(@donor_account.name).to eq 'Donor' end end end describe '#merge' do let(:winner) { create(:donor_account) } let(:loser) { create(:donor_account) } let(:donation1) { create(:donation, donation_date: Date.today) } let(:donation2) { create(:donation, donation_date: Date.yesterday) } let(:donor_account) { create(:donor_account) } let(:mpda) do create(:master_person_donor_account, donor_account: donor_account) end let(:contact_donor_account) do create(:contact_donor_account, contact: create(:contact), donor_account: donor_account) end before do winner.donations << donation1 winner.update_donation_totals(donation1) loser.donations << donation2 loser.update_donation_totals(donation2) loser.master_person_donor_accounts << mpda loser.contact_donor_accounts << contact_donor_account end it 'returns false and does nothing if account numbers differ' do loser.update(account_number: 'different number') expect do expect(winner.merge(loser)).to be false end.to_not change(DonorAccount, :count) end it 'combines donor account data' do expect do winner.merge(loser) end.to change(DonorAccount, :count).by(-1) winner.reload expect(winner.total_donations).to eq(12.99 * 2) expect(winner.last_donation_date).to eq Date.today expect(winner.first_donation_date).to eq Date.yesterday expect(winner.donations.to_set).to eq([donation1, donation2].to_set) expect(winner.master_person_donor_accounts.to_a).to eq [mpda] expect(winner.contact_donor_accounts.to_a).to eq [contact_donor_account] end end describe '.filter' do let!(:account_list) { create(:account_list) } context 'wildcard_search' do let!(:random_account) { create(:donor_account) } context 'account_number starts with' do let!(:donor_account) { create(:donor_account, account_number: '1234') } it 'returns donor_account' do expect(described_class.filter(account_list, wildcard_search: '12')).to eq([donor_account]) end end context 'account_number does not start with' do let!(:donor_account) { create(:donor_account, account_number: '1234') } it 'returns donor_accounts' do expect(described_class.filter(account_list, wildcard_search: '34')).to eq([donor_account]) end end context 'donor account name contains' do let!(:donor_account) { create(:donor_account, name: 'abcd') } it 'returns donor_account' do expect(described_class.filter(account_list, wildcard_search: 'bc')).to eq([donor_account]) end end context 'donor account name does not contain' do let!(:donor_account) { create(:donor_account, name: 'abcd') } it 'returns no donor_accounts' do expect(described_class.filter(account_list, wildcard_search: 'def')).to be_empty end end context 'contact name contains case insensitively' do let!(:contact) { create(:contact, name: '<NAME>', account_list: account_list) } let!(:donor_account) { create(:donor_account, account_number: '1234', contacts: [contact]) } it 'returns donor_account' do expect(described_class.filter(account_list, wildcard_search: 'Dom Nam')).to eq([donor_account]) end end context "name on contact belonging to another user's account list" do let!(:contact) { create(:contact, name: '<NAME>', account_list: create(:account_list)) } let!(:donor_account) { create(:donor_account, account_number: '1234', contacts: [contact]) } it 'returns no donor_accounts' do expect(described_class.filter(account_list, wildcard_search: 'Dom Nam')).to eq([]) end end end context 'not wildcard_search' do let!(:donor_account) { create(:donor_account, account_number: '1234') } it 'returns donor_account' do expect(described_class.filter(account_list, account_number: donor_account.account_number)).to eq([donor_account]) end end end context 'by_wildcard_search' do let(:account_list) { create(:account_list) } let!(:donor_account) { create(:donor_account, account_number: '1234') } it 'can be called directly' do expect(described_class.by_wildcard_search(account_list, '12')).to eq([donor_account]) end end end
chuckmersereau/api_practice
spec/models/currency_alias_spec.rb
require 'rails_helper' describe CurrencyAlias do end
chuckmersereau/api_practice
db/migrate/20130222192624_add_tnt_id_to_contact.rb
class AddTntIdToContact < ActiveRecord::Migration def change add_column :contacts, :tnt_id, :integer add_index :contacts, :tnt_id end end
chuckmersereau/api_practice
db/migrate/20130821201443_associate_prayer_letters_account_with_account_list.rb
<filename>db/migrate/20130821201443_associate_prayer_letters_account_with_account_list.rb class AssociatePrayerLettersAccountWithAccountList < ActiveRecord::Migration def up rename_table :person_prayer_letters_accounts, :prayer_letters_accounts add_column :prayer_letters_accounts, :account_list_id, :integer PrayerLettersAccount.find_each do |pl| al = User.find(pl.person_id).account_lists.order(:created_at).first pl.update_column(:account_list_id, al.id) end remove_column :prayer_letters_accounts, :person_id add_index :prayer_letters_accounts, :account_list_id end def down add_column :prayer_letters_accounts, :person_id, :integer PrayerLettersAccount.find_each do |pl| u = AccountList.find(pl.account_list_id).users.first pl.update_column(:account_list_id, u.id) end remove_column :prayer_letters_accounts, :account_list_id rename_table :prayer_letters_accounts, :person_prayer_letters_accounts end end
chuckmersereau/api_practice
app/workers/task_notifications_worker.rb
<reponame>chuckmersereau/api_practice require 'async' class TaskNotificationsWorker include Async include Sidekiq::Worker sidekiq_options queue: :api_task_notifications_worker, unique: :until_executed def perform tasks_ready_for_notification.find_each do |task| send_notification_to_all_account_users(task) task.update_column(:notification_scheduled, true) end end def tasks_ready_for_notification Task.unscheduled .starting_between(::Time.current..24.hours.from_now) .with_notification_time .notify_by([Task.notification_types[:email], Task.notification_types[:both]]) end def send_notification_to_all_account_users(task) delayed_until = determine_start_time(task) task.account_list.users.each { |user| send_notification(task.id, user.id, delayed_until) } end def determine_start_time(task) time_unit = task.notification_time_unit || 'minutes' task.start_at - task.notification_time_before.send(time_unit) end def send_notification(task_id, user_id, delayed_until) TaskNotificationMailer.delay_until(delayed_until).notify(task_id, user_id) end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/referrals_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > Referrals' do include_context :json_headers documentation_scope = :contacts_api_referrals # This is required! # This is the resource's JSONAPI.org `type` attribute to be validated against. let(:resource_type) { 'contact_referrals' } # Remove this and the authorized context below if not authorizing your requests. let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:contact) { create(:contact, account_list: account_list) } let(:contact_id) { contact.id } let(:referral) { create(:contact, account_list: account_list) } let(:referral_id) { referral.id } let(:contact_referral) do create(:contact_referral, referred_by: contact, referred_to: referral) end let(:id) { contact_referral.id } # This is the reference data used to create/update a resource. # specify the `attributes` specifically in your request actions below. let(:form_data) { build_data(attributes, relationships: relationships) } let(:resource_attributes) do # list your expected resource keys vertically here (alphabetical please!) %w( created_at updated_at updated_in_db_at ) end let(:additional_attribute_keys) do %w( relationships ) end context 'authorized user' do before { api_login(user) } # index get '/api/v2/contacts/:contact_id/referrals' do before { contact_referral } example_request 'list referrals' do check_collection_resource(1, additional_attribute_keys) creation_time = Time.zone.parse(resource_object['created_at']) expect(creation_time.to_s).to eq contact_referral.created_at.to_s expect(response_status).to eq 200 end end # show get '/api/v2/contacts/:contact_id/referrals/:id' do with_options scope: [:data, :attributes] do response_field 'created_at', 'Created At', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' end example_request 'show referral' do check_resource(additional_attribute_keys) creation_time = Time.zone.parse(resource_object['created_at']) expect(creation_time.to_s).to eq contact_referral.created_at.to_s expect(response_status).to eq 200 end end # create post '/api/v2/contacts/:contact_id/referrals/' do with_options scope: [:data, :attributes] do parameter 'referred_by_id', 'ID of the Contact making the Referral', type: 'Number' parameter 'referred_to_id', 'ID of the Contact being Referred', type: 'Number' end let(:attributes) do {} end let(:relationships) do { referred_to: { data: { type: 'contacts', id: referral.id } }, referred_by: { data: { type: 'contacts', id: contact.id } } } end example 'create referral', document: documentation_scope do do_request data: form_data check_resource(additional_attribute_keys) expect(response_status).to eq 201 contact_referrals_by_me_ids = contact.contact_referrals_by_me.map(&:id) created_id = json_response['data']['id'] expect(contact_referrals_by_me_ids).to include created_id end end # update put '/api/v2/contacts/:contact_id/referrals/:id' do with_options scope: [:data, :attributes] do parameter 'referred_by_id', 'ID of the Contact making the Referral', type: 'Number' parameter 'referred_to_id', 'ID of the Contact being Referred', type: 'Number' end let(:alternate) { create(:contact, account_list: account_list) } let(:attributes) do { updated_in_db_at: contact_referral.updated_at } end let(:relationships) do { referred_to: { data: { type: 'contacts', id: alternate.id } }, referred_by: { data: { type: 'contacts', id: contact.id } } } end example 'update referral', document: documentation_scope do expect(contact_referral.referred_to_id).to eq referral.id do_request data: form_data check_resource(additional_attribute_keys) expect(response_status).to eq 200 expect(contact_referral.reload.referred_to_id).to eq alternate.id end end # destroy delete '/api/v2/contacts/:contact_id/referrals/:id' do example 'delete referral', document: documentation_scope do explanation 'Delete a Referral' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
spec/services/data_server_stumo_spec.rb
<filename>spec/services/data_server_stumo_spec.rb require 'rails_helper' describe DataServerStumo do let!(:organization) { create(:organization, name: 'Student Mobilization') } let!(:person) { create(:person) } let!(:organization_account) do build(:organization_account, person: person, organization: organization) end context '.import_profiles' do let(:data_server) { described_class.new(organization_account) } it 'in US format' do stub_request(:post, /.*profiles/).to_return( body: 'ROLE_CODE,ROLE_DESCRIPTION'\ "\n"\ ',"Staff Account (0559826)"' ) stub_request(:post, /.*accounts/).to_return( body: '"EMPLID","EFFDT","BALANCE","ACCT_NAME"'\ "\n"\ '"0000000","2012-03-23 16:01:39.0","123.45","Test Account"'\ "\n" ) expect(data_server).to receive(:import_profile_balance) expect do data_server.import_profiles end.to change(DesignationProfile, :count).by(1) end it 'in DataServer format' do stub_request(:post, /.*profiles/).to_return( body: "\xEF\xBB\xBF"\ '"PROFILE_CODE","PROFILE_DESCRIPTION"'\ "\r\n"\ '"1769360689","MPD Coach (All Staff Donations)"'\ "\r\n"\ '"1769360688","My Campus Accounts"'\ "\r\n"\ '"","My Staff Account"'\ "\r\n" ) stub_request(:post, /.*accounts/).to_return( body: '"EMPLID","EFFDT","BALANCE","ACCT_NAME"'\ "\n"\ '"0000000","2012-03-23 16:01:39.0","123.45","Test Account"'\ "\n" ) expect do data_server.import_profiles end.to change(DesignationProfile, :count).by(3) end context 'when the code or name of a profile has changed' do before do organization.designation_profiles.create!( [ { user_id: person.id, code: '1769360689', name: 'MPD Coach (All Staff Donations)' }, { user_id: person.id, code: '1769360688', name: 'My Campus Accounts' }, { user_id: person.id, code: '', name: 'My Staff Account' }, { user_id: person.id, code: '1769360680', name: 'My Missions Account' } ] ) stub_request(:post, /.*profiles/).to_return( body: "\xEF\xBB\xBF"\ '"PROFILE_CODE","PROFILE_DESCRIPTION"'\ "\r\n"\ '"1769360689","MY NEW PROFILE NAME"'\ "\r\n"\ '"NEW-PROFILE-CODE","My Campus Accounts"'\ "\r\n"\ '"","My Staff Account"'\ "\r\n"\ '"1769360680",""'\ "\r\n" ) stub_request(:post, /.*accounts/).to_return( body: '"EMPLID","EFFDT","BALANCE","ACCT_NAME"'\ "\n"\ '"0000000","2012-03-23 16:01:39.0","123.45","Test Account"'\ "\n" ) end let(:coach_profile) do organization.designation_profiles.find_by(code: '1769360689') end let(:campus_profile) do organization.designation_profiles.find_by(code: '1769360688') end let(:missions_profile) do organization.designation_profiles.find_by(code: '1769360680') end it 'only makes a new profile if the code has changed' do expect do data_server.import_profiles end.to change(DesignationProfile, :count).by(1) end it "updates a profile's name if code exists AND name is provided" do expect(coach_profile.name).to eq 'MPD Coach (All Staff Donations)' expect(campus_profile.name).to eq 'My Campus Accounts' expect(missions_profile.name).to eq 'My Missions Account' data_server.import_profiles # gave new name expect(coach_profile.reload.name).to eq 'MY NEW PROFILE NAME' # gave diff code but same name - # made a new profile & didn't change existing one expect(campus_profile.reload.name).to eq 'My Campus Accounts' # same code but missing name - # doesn't change name of existing profile expect(missions_profile.reload.name).to eq 'My Missions Account' end end end end
chuckmersereau/api_practice
spec/factories/pls_accounts.rb
<gh_stars>0 FactoryBot.define do factory :pls_account do association :account_list oauth2_token '<PASSWORD>' end end
chuckmersereau/api_practice
spec/support/omniauth.rb
OmniAuth.config.test_mode = true google_mock_response = { provider: 'google_oauth2', uid: '123456789', info: { name: '<NAME>', email: '<EMAIL>', first_name: 'John', last_name: 'Doe', image: 'https://lh3.googleusercontent.com/url/photo.jpg' }, credentials: { token: 'token', refresh_token: 'another_<PASSWORD>', expires_at: (Time.current + 1.day).to_i, expires: true }, extra: { raw_info: { id: '123456789', email: '<EMAIL>', email_verified: true, name: '<NAME>', given_name: 'John', family_name: 'Doe', link: 'https://plus.google.com/123456789', picture: 'https://lh3.googleusercontent.com/url/photo.jpg', gender: 'male', birthday: '0000-06-25', locale: 'en', hd: 'company_name.com' } } } prayer_letters_mock_response = { credentials: { token: 'token' } } donorhub_mock_response = { credentials: { token: 'token' } } mail_chimp_mock_response = { extra: { api_token_with_dc: 'token-us5' } } OmniAuth.config.add_mock(:google, google_mock_response) OmniAuth.config.add_mock(:prayer_letters, prayer_letters_mock_response) OmniAuth.config.add_mock(:mailchimp, mail_chimp_mock_response) OmniAuth.config.add_mock(:donorhub, donorhub_mock_response)
chuckmersereau/api_practice
app/preloaders/api/v2/contacts/people/facebook_accounts_preloader.rb
<filename>app/preloaders/api/v2/contacts/people/facebook_accounts_preloader.rb class Api::V2::Contacts::People::FacebookAccountsPreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = {}.freeze FIELD_ASSOCIATION_MAPPING = {}.freeze private def serializer_class Person::FacebookAccountSerializer end end
chuckmersereau/api_practice
db/migrate/20170829192854_create_balances.rb
<reponame>chuckmersereau/api_practice<filename>db/migrate/20170829192854_create_balances.rb class CreateBalances < ActiveRecord::Migration def change create_table :balances do |t| t.decimal :balance t.integer :resource_id t.string :resource_type t.uuid :uuid, default: 'uuid_generate_v4()' t.timestamps null: false end add_index :balances, [:resource_id, :resource_type] end end
chuckmersereau/api_practice
spec/services/contact/filter/donation_date_spec.rb
require 'rails_helper' RSpec.describe Contact::Filter::DonationDate 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!(: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) } 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!(:contact_three) { create(:contact, account_list_id: account_list.id) } let!(:donor_account_three) { create(:donor_account) } let!(:donation_three) do create(:donation, donor_account: donor_account_three, designation_account_id: nil) end 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.month.ago) donation_two.update(donation_date: 1.month.from_now) donation_three.update(donation_date: 1.month.from_now) end describe '#config' do it 'returns expected config' do expect(described_class.config([account_list]).except(:options)).to include( default_selection: '', multiple: false, name: :donation_date, parent: 'Gift Details', title: 'Gift Date', type: 'daterange' ) 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_date: {} }, nil)).to eq(nil) expect(described_class.query(contacts, { donation_date: { wut: '???', hey: 'yo' } }, nil)).to eq(nil) expect(described_class.query(contacts, { donation_date: '' }, nil)).to eq(nil) end end context 'filter by end and start date' do it 'returns only contacts with a donation after the start date and before the end date' do options = { donation_date: Range.new(1.year.ago, 1.year.from_now) } result = described_class.query(contacts, options, [account_list]).to_a expect(result).to match_array [contact_one, contact_two] options = { donation_date: Range.new(1.day.ago, 2.months.from_now) } result = described_class.query(contacts, options, [account_list]).to_a expect(result).to eq [contact_two] end end end end
chuckmersereau/api_practice
app/services/data_server/contact_address_update.rb
DataServer::ContactAddressUpdate = Struct.new(:contact, :donor_account) do def update_from_donor_account return if contact_already_has_latest? Contact.transaction do contact.primary_address.update!(primary_mailing_address: false) if contact.primary_address&.source == 'DataServer' if latest_donor_address contact.copy_address(address: latest_donor_address, source: 'DataServer', source_donor_account_id: latest_donor_address.addressable_id) end end end private def contact_already_has_latest? contact.addresses_including_deleted.any? { |a| a.equal_to?(latest_donor_address) } end def latest_donor_address @latest_donor_address ||= donor_account.addresses.reorder(created_at: :desc).first end end
chuckmersereau/api_practice
spec/services/admin/primary_address_fix_spec.rb
require 'rails_helper' describe Admin::PrimaryAddressFix, '#fix' do let(:contact) { create(:contact) } it 'sets non-primary address to primary' do address1 = create(:address, primary_mailing_address: false) contact.addresses << address1 Admin::PrimaryAddressFix.new(contact).fix expect(address1.reload).to be_primary_mailing_address end it 'does not create a new address if there are none' do Admin::PrimaryAddressFix.new(contact).fix expect(contact.addresses.count).to eq 0 end it 'sets mailing address to primary in case with two non-primary addresses' do address1 = create(:address, primary_mailing_address: false) address2 = create(:address, primary_mailing_address: false) allow(contact).to receive(:addresses) .and_return(Address.where(id: [address1.id, address2.id])) allow(contact).to receive(:mailing_address) { address1 } Admin::PrimaryAddressFix.new(contact).fix expect(address1.reload).to be_primary_mailing_address expect(address2.reload).to_not be_primary_mailing_address end it 'does not set historic address to primary' do address = create(:address, primary_mailing_address: false, historic: true) contact.addresses << address Admin::PrimaryAddressFix.new(contact).fix expect(address.reload).to_not be_primary_mailing_address end it 'sets mailing address as the only primary if had two primary addresses' do address1 = create(:address, primary_mailing_address: true) address2 = create(:address, primary_mailing_address: true) allow(contact).to receive(:addresses) .and_return(Address.where(id: [address1.id, address2.id])) allow(contact).to receive(:mailing_address) { address1 } Admin::PrimaryAddressFix.new(contact).fix expect(address1.reload).to be_primary_mailing_address end it 'set historic addresses to non-primary' do address = create(:address, primary_mailing_address: true, historic: true) contact.addresses << address Admin::PrimaryAddressFix.new(contact).fix expect(address.reload).to_not be_primary_mailing_address end end
chuckmersereau/api_practice
spec/workers/organizations_from_csv_url_worker_spec.rb
require 'rails_helper' RSpec.describe OrganizationsFromCsvUrlWorker do let!(:csv_url) { 'https://download.tntware.com/donorhub/donorhub_api_organizations.csv' } let!(:request) do stub_request(:get, csv_url) .to_return(body: "Name,QueryIni\n<NAME>,http://dataserver1.com\nToonTown,\nTandem Ministries,http://dataserver2.com") end describe '#perform' do it 'creates OrganizationFromQueryUrlWorker jobs' do expect(OrganizationFromQueryUrlWorker).to( receive(:perform_async).with('Agape Iceland', 'http://dataserver1.com') ) expect(OrganizationFromQueryUrlWorker).to( receive(:perform_async).with('Tandem Ministries', 'http://dataserver2.com') ) described_class.new.perform(csv_url) expect(request).to have_been_requested end end end
chuckmersereau/api_practice
app/policies/person/website_policy.rb
<reponame>chuckmersereau/api_practice<filename>app/policies/person/website_policy.rb<gh_stars>0 class Person::WebsitePolicy < ApplicationPolicy private def resource_owner? resource.person.account_lists.exists?(id: user.account_lists.ids) end end
chuckmersereau/api_practice
app/controllers/api/v2/tasks/analytics_controller.rb
<gh_stars>0 class Api::V2::Tasks::AnalyticsController < Api::V2Controller def show load_analytics authorize_analytics render_analytics end private def authorize_analytics account_lists.each { |account_list| authorize account_list, :show? } end def load_analytics @analytics ||= Task::Analytics.new(load_tasks) end def load_tasks Task.where(account_list_id: account_lists.map(&:id)) end def permitted_filters [:account_list_id] end def render_analytics render json: @analytics, include: include_params, fields: field_params, serializer: Task::AnalyticsSerializer end end
chuckmersereau/api_practice
app/services/tnt_import/person_import.rb
<filename>app/services/tnt_import/person_import.rb class TntImport::PersonImport include YearCompletable def initialize(row, contact, prefix, override) @row = row @contact = contact @prefix = prefix @override = override end def import add_or_update_person(@row, @contact, @prefix) end private def add_or_update_person(row, contact, prefix = '') add_org_contact_person_name(row) row[prefix + 'FirstName'] = 'Unknown' if row[prefix + 'FirstName'].blank? # See if there's already a person by this name on this contact (This is a contact with multiple donation accounts) person = contact.people.where(first_name: row[prefix + 'FirstName'], last_name: row[prefix + 'LastName']) .find_by("middle_name = ? OR middle_name = '' OR middle_name is NULL", row[prefix + 'MiddleName']) person ||= Person.new update_person_attributes(person, row, prefix) person.master_person_id ||= MasterPerson.find_or_create_for_person(person).id person.save(validate: false) begin contact.people << person unless contact.people.include?(person) rescue ActiveRecord::RecordNotUnique end person end def add_org_contact_person_name(row) return unless true?(row['IsOrganization']) && row['OrgContactPerson'].present? parsed = HumanNameParser.new(row['OrgContactPerson']).parse row['FirstName'] = parsed[:first_name] row['LastName'] = parsed[:last_name] end def update_person_attributes(person, row, prefix = '') new_attributes = { first_name: row[prefix + 'FirstName'], last_name: row[prefix + 'LastName'], middle_name: row[prefix + 'MiddleName'], title: row[prefix + 'Title'], suffix: row[prefix + 'Suffix'], gender: prefix.present? ? 'female' : 'male', occupation: row[prefix + 'Profession'], employer: row[prefix + 'BusinessName'], birthday_month: row[prefix + 'BirthdayMonth'], birthday_day: row[prefix + 'BirthdayDay'], birthday_year: get_four_digit_year_from_value(row[prefix + 'BirthdayYear']), anniversary_month: row[prefix + 'AnniversaryMonth'], anniversary_day: row[prefix + 'AnniversaryDay'], anniversary_year: get_four_digit_year_from_value(row[prefix + 'AnniversaryYear']), deceased: (row['Deceased'] == 'true') } person.attributes = if !person.persisted? new_attributes elsif @override person.attributes.symbolize_keys.merge(new_attributes) else new_attributes.merge(person.attributes.symbolize_keys) end update_person_phones(person, row, prefix) update_person_emails(person, row, prefix) update_person_social_media_accounts(person, row, prefix) update_contact_primary_person(person, prefix) person end def update_person_phones(person, row, prefix) person_sym = prefix == '' ? :primary : :spouse is_valid_mask = row['PhoneIsValidMask'].to_i # Bit vector indexed corresponding to TNT_PHONES had_no_primary = person.phone_numbers.where(primary: true).empty? TntImport::TntCodes::TNT_PHONES.each_with_index do |tnt_phone, i| number = row[tnt_phone[:field]] next unless number.present? && (tnt_phone[:person] == :both || tnt_phone[:person] == person_sym) phone_attrs = { number: number, location: tnt_phone[:location], historic: (is_valid_mask[i]).zero? } if (@override || had_no_primary) && row['PreferredPhoneType'].to_i == i phone_attrs[:primary] = true person.phone_numbers.each { |phone| phone.update(primary: false) } end person.phone_number = phone_attrs end end def update_person_emails(person, row, prefix) changed_primary = false had_no_primary = person.email_addresses.where(primary: true).empty? # If there is just a single email in Tnt, it leaves the suffix off, so start with a blank then do the numbers # up to three as Tnt allows a maximum of 3 email addresses for a person/spouse. (1..3).each do |i| email = row[prefix + "Email#{i}"] next unless email.present? email_valid = row["#{prefix}Email#{i}IsValid"] historic = email_valid.present? && !true?(email_valid) email_attrs = { email: email, historic: historic } # For MPDX, we set the primary email to be the first "preferred" email listed in Tnt. if (@override || had_no_primary) && !changed_primary && !historic && tnt_email_preferred?(row, i, prefix) person.email_addresses.each { |e| e.update(primary: false) } email_attrs[:primary] = true changed_primary = true end EmailAddress.expand_and_clean_emails(email_attrs).each do |cleaned_attrs| person.email_address = cleaned_attrs end end end def update_person_social_media_accounts(person, row, prefix) import_social_column(person.facebook_accounts, row, prefix, 'SocialWeb1', :username) import_social_column(person.linkedin_accounts, row, prefix, 'SocialWeb2', :public_url) import_social_column(person.twitter_accounts, row, prefix, 'SocialWeb3', :screen_name) import_social_column(person.websites, row, prefix, 'WebPage1', :url) import_social_column(person.websites, row, prefix, 'WebPage2', :url) end def import_social_column(relationship, row, prefix, col_name, remote_field) remote_value = row["#{prefix}#{col_name}"] new_account = relationship.find_or_initialize_by(remote_field => remote_value) if remote_value # if the record is invalid, don't try to initialize it relationship.delete(new_account) if new_account&.invalid? end def true?(val) val&.casecmp('TRUE')&.zero? end # TntMPD allows multiple emails to be marked as preferred and expresses that array of booleans as a # bit vector in the PreferredEmailTypes. Bit 0 is ignored, then 3 for primary person emails, then 3 for spouse def tnt_email_preferred?(row, email_num, person_prefix) preferred_bit_index = (person_prefix == 'Spouse' ? 3 : 0) + email_num row['PreferredEmailTypes'].present? && row['PreferredEmailTypes'].to_i[preferred_bit_index] == 1 end def update_contact_primary_person(person, prefix) @contact.primary_person_id = person.id if @override && prefix == '' end end
chuckmersereau/api_practice
spec/serializers/donation_reports/donor_info_serializer_spec.rb
require 'rails_helper' describe DonationReports::DonorInfoSerializer do let(:account_list) { create(:account_list) } let(:donor_info) { DonationReports::DonorInfo.from_contact(build(:contact)) } subject { DonationReports::DonorInfoSerializer.new(donor_info).as_json } it 'serializes status' do expect(subject[:status]).to eq('Partner - Financial') end it 'serializes pledge_frequency' do expect(subject[:pledge_frequency]).to eq('Monthly') end it 'serializes pledge_amount' do expect(subject[:pledge_amount]).to eq(100.0) end end
chuckmersereau/api_practice
app/services/tnt_import/history_import.rb
class TntImport::HistoryImport < TntImport::TasksImport def import return {} unless xml_tables[xml_table_name].present? && xml_tables['HistoryContact'].present? @tnt_appeal_id_by_tnt_history_id = {} all_tasks = build_tasks xml_tables['HistoryContact'].map do |contact_row| process_history_contact_row(contact_row, all_tasks) end contact_ids_by_tnt_appeal_id end private def build_tasks task_rows = xml_tables[xml_table_name].select { |row| TntImport::TntCodes.import_task_type?(row['TaskTypeID']) } task_rows.map do |row| tnt_history_id = row['id'] @tnt_appeal_id_by_tnt_history_id[tnt_history_id] = row[appeal_id_name] if row[appeal_id_name].present? build_task_from_row(row) end end def process_history_contact_row(contact_row, all_tasks) create_task_for_contact!(contact_row, all_tasks) rescue ActiveRecord::RecordInvalid nil end def contact_ids_by_tnt_appeal_id # set default value of keys to an empty array so they can be pushed into later contact_ids_by_tnt_appeal_id = Hash.new { |hash, key| hash[key] = [] } xml_tables['HistoryContact'].each do |row| tnt_contact_id = row['ContactID'] contact_id = @contact_ids_by_tnt_contact_id[tnt_contact_id] next unless contact_id tnt_appeal_id = @tnt_appeal_id_by_tnt_history_id[row[xml_foreign_key]] contact_ids_by_tnt_appeal_id[tnt_appeal_id] << contact_id if tnt_appeal_id end contact_ids_by_tnt_appeal_id end def build_task_from_row(row) task = Retryable.retryable do @account_list.tasks.where(remote_id: row['id'], source: 'tnt').first_or_initialize end task.attributes = { activity_type: TntImport::TntCodes.task_type(row['TaskTypeID']), subject: subject(row), completed_at: parse_date(row['HistoryDate'], @user), completed: true, result: TntImport::TntCodes.history_result(row['HistoryResultID']) } add_assigned_to_as_tag(task, row) add_campaign_as_tag(task, row) add_categories_as_tags(task, row) task.start_at ||= parse_date(row['HistoryDate'], @user) task end def xml_table_name 'History' end def xml_foreign_key 'HistoryID' end end
chuckmersereau/api_practice
spec/factories/currency_aliases.rb
<filename>spec/factories/currency_aliases.rb FactoryBot.define do factory :currency_alias do sequence(:alias_code) { |n| (65 + n).chr } sequence(:rate_api_code) { |n| (65 + n).chr } ratio 1 end end
chuckmersereau/api_practice
spec/lib/encoding_util_spec.rb
require 'encoding_util' describe EncodingUtil do context '.normalized_utf8' do it 'normalizes to uft8 without byte-order-mark, and with universal line endings' do [ ['', ''], [1, '1'], [nil, ''], %w(USA USA), ["a\r\nb", "a\nb"], %W(a\nb a\nb), %w(Agapé Agapé), %w(Agapé Agapé), %w(Agapé Agapé), # ISO-8859-1 ["Lan\xE9", 'Lané'], # ISO-8859-2 ["\xEF\xBB\xBFAgapé".force_encoding('UTF-8'), 'Agapé'] # byte-order-mark ].each do |str, normalized| expect(EncodingUtil.normalized_utf8(str)).to eq(normalized) end end end end
chuckmersereau/api_practice
spec/services/data_server_ptc_spec.rb
require 'rails_helper' describe DataServerPtc do let(:account_list) { create(:account_list) } let(:profile) do create(:designation_profile, organization: @org, user: @person.to_user, account_list: account_list) end before(:each) do @org = create(:nav) @person = create(:person) @org_account = build(:organization_account, person: @person, organization: @org) @data_server = DataServerPtc.new(@org_account) end describe 'import account balances' do it 'should update a profile balance' do stub_resp = "\"EMPLID\",\"EFFDT\",\"BALANCE\",\"ACCT_NAME\"\n"\ "\"\",\"2/10/15 10:13:38\",\"123.45\",\"Test Account\"\n" stub_request(:post, /.*accounts/).to_return(body: stub_resp) expect(@data_server).to receive(:check_credentials!) expect do @data_server.import_profile_balance(profile) end.to change(profile, :balance).to(123.45) end it 'should update a designation account balance' do stub_resp = "\"EMPLID\",\"EFFDT\",\"BALANCE\",\"ACCT_NAME\"\n"\ "\"#{@org_account.username}\",\"2/10/15 10:13:38\",\"123.45\",\"Test Account\"\n" stub_request(:post, /.*accounts/).to_return(body: stub_resp) @designation_account = create(:designation_account, organization: @org, designation_number: @org_account.username) @data_server.import_profile_balance(profile) expect(@designation_account.reload.balance).to eq(123.45) end end end
chuckmersereau/api_practice
spec/services/contact/filter/designation_account_id_spec.rb
require 'rails_helper' RSpec.describe Contact::Filter::DesignationAccountId do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:designation_account_1) { create(:designation_account) } let(:designation_account_2) { create(:designation_account) } before do account_list.designation_accounts << designation_account_1 account_list.designation_accounts << designation_account_2 end describe '#query' do let!(:contact_1) do donor_account = create(:donor_account, account_number: '1') create(:donation, donor_account: donor_account, designation_account: designation_account_1) create( :contact, account_list: account_list, donor_accounts: [donor_account] ) end let!(:contact_2) do donor_account = create(:donor_account, account_number: '2') create(:donation, donor_account: donor_account, designation_account: designation_account_2) create( :contact, account_list: account_list, donor_accounts: [donor_account] ) end let!(:contact_3) do donor_account = create(:donor_account, account_number: '3') create(:donation, donor_account: donor_account, designation_account: designation_account_1) create(:donation, donor_account: donor_account, designation_account: designation_account_2) create( :contact, account_list: account_list, donor_accounts: [donor_account] ) end let!(:contact_4) { create(:contact, account_list: account_list) } 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, { designation_account_id: {} }, nil)).to eq(nil) end end context 'for single designation_account' do it 'returns the correct contacts' do expect(described_class.query(contacts, { designation_account_id: designation_account_1.id }, nil)).to( contain_exactly(contact_1, contact_3) ) expect(described_class.query(contacts, { designation_account_id: designation_account_2.id }, nil)).to( contain_exactly(contact_2, contact_3) ) end end context 'for multiple designation_accounts' do it 'returns the correct contacts' do expect( described_class.query( contacts, { designation_account_id: [designation_account_1.id, designation_account_2.id] }, nil ) ).to( contain_exactly(contact_1, contact_2, contact_3) ) end end context 'with reverse_FILTER' do subject { described_class.query(contacts, query, nil) } let(:query) { { designation_account_id: designation_account_id, reverse_designation_account_id: true } } context 'designation_account_id: designation_account_1' do let(:designation_account_id) { designation_account_1.id } it 'returns contacts that have not donated to designation_account_1' do is_expected.to contain_exactly(contact_2, contact_4) end end context 'designation_account_id: designation_account_1 & designation_account_2' do let(:designation_account_id) { [designation_account_1.id, designation_account_2.id] } it 'returns contacts that have not donated to designation_account_1 & designation_account_2' do is_expected.to contain_exactly(contact_4) end end end end describe '#config' do it 'returns expected config' do expect(described_class.config([account_list])).to include( default_selection: '', multiple: true, name: :designation_account_id, options: [{ name: '-- Any --', id: '', placeholder: 'None' }, { name: DesignationAccountSerializer.new(designation_account_1).display_name, id: designation_account_1.id }, { name: DesignationAccountSerializer.new(designation_account_2).display_name, id: designation_account_2.id }], parent: 'Gift Details', title: 'Designation Acccount', type: 'multiselect' ) end end end
chuckmersereau/api_practice
spec/models/notification_type/started_giving_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe NotificationType::StartedGiving do let!(:started_giving) { NotificationType::StartedGiving.first_or_initialize } let!(:da) { create(:designation_account_with_donor) } let(:contact) { da.contacts.financial_partners.first } let(:donation) do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 5.days.ago, currency: '') end context '#check' do before { contact.update_column(:direct_deposit, true) } it 'adds a notification if first gift came within past 2 weeks' do donation # create donation object from let above notifications = started_giving.check(contact.account_list) expect(notifications.length).to eq(1) end it 'adds a notification if first gift came within past 2 weeks even if donor has given to another da' do other_da = create(:designation_account_with_special_donor) create(:donation, donor_account: contact.donor_accounts.first, designation_account: other_da, donation_date: 20.days.ago) donation # create donation object from let above notifications = started_giving.check(contact.account_list) expect(notifications.length).to eq(1) end it "doesn't add a notification if not first gift" do 2.times do |i| create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: (i * 30).days.ago) end notifications = started_giving.check(contact.account_list) expect(notifications.length).to eq(0) end it "doesn't add a notification if first gift came more than 2 weeks ago" do create(:donation, donor_account: contact.donor_accounts.first, designation_account: da, donation_date: 37.days.ago) notifications = started_giving.check(contact.account_list) expect(notifications.length).to eq(0) end describe 'sets pledge_received if first gift came in the past pledge_frequency period' do before { contact.update(pledge_amount: 9.99) } it 'marks pledge received if monthly and donation within one month' do contact.update(pledge_frequency: 1) donation = create_donation(6.months.ago) expect_pledge_received(false) donation.update(donation_date: 15.days.ago) expect_pledge_received(true) end it 'marks pledge received if annual and donation within one year' do contact.update(pledge_frequency: 12) donation = create_donation(2.years.ago) expect_pledge_received(false) donation.update(donation_date: 6.months.ago) expect_pledge_received(true) end it 'works if pledge frequency is a fraction' do contact.update(pledge_frequency: 0.5) create_donation(1.day.ago) expect_pledge_received(true) end def create_donation(donation_date) create(:donation, donor_account: contact.donor_accounts.first, currency: '', designation_account: da, donation_date: donation_date) end def expect_pledge_received(expected_val) started_giving.check(contact.account_list) expect(contact.reload.pledge_received).to be expected_val end end it "doesn't add a notification if the contact is on a different account list with a shared designation account" do donation # create donation object from let above account_list2 = create(:account_list) account_list2.account_list_entries.create!(designation_account: da) notifications = started_giving.check(account_list2) expect(notifications.length).to eq(0) end it 'sets pledge received and defaults to a monthly pledge when first gift given for financial partner' do contact.update(pledge_amount: nil, pledge_currency: nil, pledge_frequency: nil, pledge_received: false) donation started_giving.check(contact.account_list) contact.reload expect(contact.pledge_amount).to eq(9.99) expect(contact.pledge_frequency).to eq(1) expect(contact.pledge_received).to be true end it 'sets pledge received and defaults to monthly pledge and currency when first gift given for financial partner' do contact.update(pledge_amount: nil, pledge_currency: nil, pledge_frequency: nil, pledge_received: false) donation.update(currency: 'EUR', amount: 21.50) started_giving.check(contact.account_list) contact.reload expect(contact.pledge_amount).to eq(21.50) expect(contact.pledge_currency).to eq('EUR') expect(contact.pledge_frequency).to eq(1) expect(contact.pledge_received).to be true end end describe '.create_task' do let(:account_list) { create(:account_list) } it 'creates a task for the activity list' do expect do started_giving.create_task(account_list, contact.notifications.new) end.to change(Activity, :count).by(1) end it 'associates the contact with the task created' do task = started_giving.create_task(account_list, contact.notifications.new) expect(task.contacts.reload).to include contact end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/admin/impersonation_spec.rb
<filename>spec/acceptance/api/v2/admin/impersonation_spec.rb<gh_stars>0 require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Impersonation' do include_context :json_headers let(:admin_user) { create(:user_with_account, admin: true) } let(:impersonated_user) { create(:user) } let(:request_type) { 'impersonation' } let(:form_data) { build_data(reason: 'Reason', user: impersonated_user.id) } context 'authorized user' do before { api_login(admin_user) } post '/api/v2/admin/impersonation' do with_options scope: [:data, :attributes] do parameter :reason, 'The reason for the impersonation' parameter :user, 'The User Name, ID or Key/Relay Email of the user to impersonate' end example 'Impersonation', document: false do explanation 'This endpoint allows an admin to impersonate any user by receiving a jwt that can ' \ 'be used to access any resources on the API on behalf of the impersonated user.' do_request data: form_data expect(response_status).to eq 200 expect(json_response['data']['attributes']['json_web_token']).to be_present end end end end
chuckmersereau/api_practice
app/models/google_integration.rb
<reponame>chuckmersereau/api_practice<filename>app/models/google_integration.rb require 'google/apis/calendar_v3' class GoogleIntegration < ApplicationRecord belongs_to :google_account, class_name: 'Person::GoogleAccount', inverse_of: :google_integrations belongs_to :account_list, inverse_of: :google_integrations serialize :calendar_integrations, Array serialize :email_blacklist, Array before_save :toggle_calendar_integration_for_appointments, :set_default_calendar, if: :calendar_integration_changed? after_save :toggle_email_integration, if: :email_integration_changed? delegate :sync_task, to: :calendar_integrator validates :calendar_integrations, :email_blacklist, class: { is_a: Array } PERMITTED_ATTRIBUTES = [ :account_list_id, :calendar_id, :calendar_integration, :calendar_name, :contacts_integration, :email_integration, :overwrite, :updated_in_db_at, :id, { calendar_integrations: [], email_blacklist: [] } ].freeze PERMITTED_INTEGRATIONS = %w(calendar email contacts).freeze def queue_sync_data(integration) validate_integration!(integration) raise 'Cannot queue sync on an unpersisted record!' unless persisted? GoogleSyncDataWorker.perform_async(id, integration) end def sync_data(integration) validate_integration!(integration) send("#{integration}_integrator").sync_data end def calendar_integrator @calendar_integrator ||= GoogleCalendarIntegrator.new(self, calendar_service) end def email_integrator @email_integrator ||= GoogleEmailIntegrator.new(self) end def contacts_integrator @contacts_integrator ||= GoogleContactsIntegrator.new(self) end def calendars return @calendars if @calendars calendar_list_entries = calendar_service&.list_calendar_lists&.items || [] @calendars = calendar_list_entries.select do |calendar_list_entry| calendar_list_entry.access_role == 'owner' end end private def calendar_service return unless google_account.authorization @calendar_service ||= Google::Apis::CalendarV3::CalendarService.new.tap do |calendar_service| calendar_service.authorization = google_account.authorization end end def validate_integration!(integration) raise "Invalid integration '#{integration}'!" unless PERMITTED_INTEGRATIONS.include?(integration) end def toggle_calendar_integration_for_appointments if calendar_integration? self.calendar_integrations = ['Appointment'] if calendar_integrations.blank? else self.calendar_integrations = [] end end def set_default_calendar return unless calendar_integration? && calendar_id.blank? && calendars.length == 1 calendar = calendars.first self.calendar_id = calendar.id self.calendar_name = calendar.summary end def toggle_email_integration queue_sync_data('email') if email_integration? end end
chuckmersereau/api_practice
db/migrate/20160518122049_make_person_relay_accounts_remote_id_uniq.rb
<filename>db/migrate/20160518122049_make_person_relay_accounts_remote_id_uniq.rb class MakePersonRelayAccountsRemoteIdUniq < ActiveRecord::Migration disable_ddl_transaction! def change execute 'create unique index concurrently person_relay_accounts_on_lower_remote_id on person_relay_accounts(lower(remote_id));' end end
chuckmersereau/api_practice
app/services/csv_import.rb
# This service class is a decorator for the Import model, # it handles additional behaviour regarding importing from CSV files. require 'csv' class CsvImport delegate :account_list, to: :@import def self.supported_headers { church: _('Church'), city: _('City'), pledge_amount: _('Commitment Amount'), pledge_currency: _('Commitment Currency'), pledge_frequency: _('Commitment Frequency'), country: _('Country'), email_1: _('Email 1'), email_2: _('Email 2'), envelope_greeting: _('Envelope Greeting'), first_name: _('First Name'), full_name: _('Full Name'), greeting: _('Greeting'), last_name: _('Last Name'), likely_to_give: _('Likely To Give'), metro_area: _('Metro Area'), newsletter: _('Newsletter'), notes: _('Notes'), phone_1: _('Phone 1'), phone_2: _('Phone 2'), phone_3: _('Phone 3'), referred_by: _('Referred By'), region: _('Region'), send_appeals: _('Send Appeals?'), spouse_email: _('Spouse Email'), spouse_first_name: _('Spouse First Name'), spouse_last_name: _('Spouse Last Name'), spouse_phone: _('Spouse Phone'), state: _('State'), status: _('Status'), street: _('Street'), tags: _('Tags'), website: _('Website'), zip: _('Zip') } end def self.required_headers {} end def self.constants constants_exhibit = ConstantList.new.to_exhibit { pledge_currency: constants_exhibit.pledge_currency_hashes, pledge_frequency: constants_exhibit.pledge_frequency_hashes, likely_to_give: constants_exhibit.assignable_likely_to_give_hashes, newsletter: constants_exhibit.assignable_send_newsletter_hashes, send_appeals: constants_exhibit.send_appeals_hashes, status: constants_exhibit.status_hashes } end def self.transform_array_to_hash_with_underscored_keys(array) array.each_with_object({}.with_indifferent_access) do |value, hash| hash[value&.parameterize&.underscore] = value hash end end def initialize(import) @import = import end def each_row CsvFileReader.new(@import.file_path).each_row do |csv_row| yield(csv_row) end end def import raise 'Attempted an invalid import! Aborting.' if @import.invalid? raise 'Attempted an import that is in preview! Aborting.' if @import.in_preview? batch = Sidekiq::Batch.new batch.description = "CsvImport #{@import.id} #import" batch.on(:complete, 'CsvImportBatchCallbackHandler', import_id: @import.id) batch.jobs do each_row do |csv_row| CsvImportContactWorker.perform_async(@import.id, csv_row.headers, csv_row.fields) end end # If there are no jobs the Batch callbacks won't fire, # in that case treat this as a synchronous job by returning false. !batch.jids.empty? ? true : false end def file_constants_for_mpdx_header(mpdx_header) @import.file_constants[@import.file_headers_mappings[mpdx_header]]&.to_a end def sample_contacts sample_contacts = @import.file_row_samples.collect do |sample_row| contact_from_file_line(sample_row) end.compact generate_ids_for_contacts(sample_contacts) end def update_cached_file_data assign_cached_file_data @import.save end def generate_csv_from_file_row_failures csv = CSV.generate_line(['Error Message'] + @import.file_headers.values) @import.file_row_failures.each_with_object(csv) { |failure, string| string << CSV.generate_line(failure) } csv end private def assign_cached_file_data @import.file_headers = read_file_headers_from_file_contents if @import.file_headers.blank? @import.file_constants = read_file_constants_from_file_contents if @import.file_constants.blank? @import.file_row_samples = read_file_row_samples_from_file_contents if @import.file_row_samples.blank? end def read_file_headers_from_file_contents header_row = nil each_row do |csv_row| header_row = csv_row.headers break end self.class.transform_array_to_hash_with_underscored_keys(header_row) end def read_file_constants_from_file_contents CsvFileConstantsReader.new(@import.file_path).constants end def read_file_row_samples_from_file_contents samples = [] each_row do |csv_row| row_fields = csv_row.fields samples << row_fields break if samples.size >= 4 end samples end def contact_from_file_line(line) line = CSV.new(line).first unless line.is_a?(Array) csv_row = CSV::Row.new(@import.file_headers.values, line) CsvRowContactBuilder.new(csv_row: csv_row, import: @import).build end def generate_ids_for_contacts(contacts) objects_needing_ids = contacts.collect do |contact| [ contact, contact.primary_person, contact.spouse, contact.addresses, contact.primary_person&.email_addresses, contact.spouse&.email_addresses, contact.primary_person&.phone_numbers, contact.spouse&.phone_numbers ] end.flatten.compact objects_needing_ids.each { |record| record.id ||= SecureRandom.uuid } contacts end end
chuckmersereau/api_practice
spec/services/donation_imports/siebel/profile_importer_spec.rb
require 'rails_helper' RSpec.describe DonationImports::Siebel::ProfileImporter do let!(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:organization_account) { user.organization_accounts.first } let(:organization) { organization_account.organization } let(:key_account) { user.key_accounts.first } let(:designation_profile) { organization_account.designation_profiles.first } let(:designation_account) do create(:designation_account, designation_profiles: [designation_profile], designation_number: 'designation_number', organization: organization) end let(:mock_siebel_import) { double(:mock_siebel_import) } let(:mock_profile_linker) { double(:mock_profile_linker) } before do organization_account.update(remote_id: nil) key_account.update(relay_remote_id: 'random_guid') allow(mock_siebel_import).to receive(:organization).and_return(organization) allow(mock_siebel_import).to receive(:organization_account).and_return(organization_account) end subject { described_class.new(mock_siebel_import) } ProfileStructure = Struct.new(:id, :name, :designations) DesignationStructure = Struct.new(:number, :description, :staff_account_id, :chartfield) BalanceStructure = Struct.new(:primary) let(:siebel_profiles) do [ ProfileStructure.new( designation_profile.code, designation_profile.name, [DesignationStructure.new('second_designation_number', 'Joshua and <NAME> (0559826)')] ), ProfileStructure.new( 'profile_id_one', 'Staff Account (0559826)', [DesignationStructure.new('designation_number', 'Joshua and <NAME> (0559826)', 'employee_id')] ) ] end context '#import_profiles' do it 'imports or updates designation_profiles from Siebel' do expect(SiebelDonations::Profile).to receive(:find) .with(ssoGuid: key_account.relay_remote_id) .and_return(siebel_profiles) expect(SiebelDonations::Balance).to receive(:find) .with(employee_ids: 'employee_id') .and_return([BalanceStructure.new(2000.00)]) expect(AccountList::FromProfileLinker).to receive(:new) .with(instance_of(DesignationProfile), organization_account) .and_return(mock_profile_linker) expect(mock_profile_linker).to receive(:link_account_list!) expect do expect(subject.import_profiles).to be_truthy end.to change { organization.designation_profiles.count }.by(1) .and change { organization.designation_accounts.count }.by(1) .and change { designation_account.reload.staff_account_id } .and change { designation_account.reload.balance_updated_at } .and change { designation_profile.reload.balance_updated_at } expect(designation_account.balance).to eq(2000.00) expect(DesignationProfile.order(:created_at).last.balance).to eq(2000.00) end end end
chuckmersereau/api_practice
db/migrate/20141226170459_create_name_male_ratios.rb
<reponame>chuckmersereau/api_practice<filename>db/migrate/20141226170459_create_name_male_ratios.rb class CreateNameMaleRatios < ActiveRecord::Migration def change create_table :name_male_ratios do |t| t.string "name", null: false t.float "male_ratio", null: false t.timestamps null: false end add_index :name_male_ratios, :name end end
chuckmersereau/api_practice
app/services/cas_ticket_validator_service.rb
<filename>app/services/cas_ticket_validator_service.rb class CasTicketValidatorService attr_reader :ticket, :service def initialize(ticket:, service:) @ticket = ticket @service = service end def validate return true if authentication_success? raise Exceptions::AuthenticationError, error_message end def attribute(attribute_name) response.dig('serviceResponse', 'authenticationSuccess', 'attributes', attribute_name, '__content__')&.strip end def attributes { authenticationDate: attribute('authenticationDate'), email: attribute('email'), firstName: attribute('firstName'), isFromNewLogin: attribute('isFromNewLogin'), lastName: attribute('lastName'), longTermAuthenticationRequestTokenUsed: attribute('longTermAuthenticationRequestTokenUsed'), relayGuid: attribute('relayGuid'), ssoGuid: attribute('ssoGuid'), theKeyGuid: attribute('theKeyGuid') } end private def authentication_success? return true if response.dig('serviceResponse', 'authenticationSuccess').present? return false if response.dig('serviceResponse', 'authenticationFailure').present? raise 'Unknown response from /cas/serviceValidate' end def error_code return nil if authentication_success? response.dig('serviceResponse', 'authenticationFailure', 'code') end def error_content return nil if authentication_success? response.dig('serviceResponse', 'authenticationFailure', '__content__')&.strip end def error_message [error_code, error_content].join(': ') end def response @response ||= ActiveSupport::XmlMini.parse(open_xml) end def url base_url = ENV['CAS_BASE_URL'] https = base_url.present? && base_url.starts_with?('https://') raise('expected CAS_BASE_URL environment variable to be present and using https') unless https "#{base_url}/p3/serviceValidate?ticket=#{ticket}&service=#{service}" end def open_xml open(url) end end
chuckmersereau/api_practice
spec/models/contact_donor_account_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe ContactDonorAccount do end
chuckmersereau/api_practice
spec/services/contact/filter/started_giving_range_spec.rb
require 'rails_helper' RSpec.describe Contact::Filter::StartedGivingRange do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } describe '#query' do let!(:first_contact) do create(:contact, account_list: account_list, pledge_amount: 0.0, 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!(:fourth_contact) do create(:contact, account_list: account_list, pledge_amount: 40.00, first_donation_date: nil) end let(:contacts) { Contact.all } context 'contacts that have started giving within date range' do it 'returns the correct contacts' do expect( described_class.query( contacts, { started_giving_range: Range.new(5.months.ago.to_datetime, 2.months.ago) }, [account_list] ) ).to eq([second_contact]) end end end end
chuckmersereau/api_practice
app/serializers/account_list/chalkline_mails_serializer.rb
class AccountList::ChalklineMailsSerializer < ServiceSerializer type 'chalkline_mails' end
chuckmersereau/api_practice
spec/factories/activity_comments.rb
<reponame>chuckmersereau/api_practice FactoryBot.define do factory :activity_comment do activity nil person nil body 'MyText' end end
chuckmersereau/api_practice
db/migrate/20160210153943_add_index_to_master_addresses_country.rb
class AddIndexToMasterAddressesCountry < ActiveRecord::Migration self.disable_ddl_transaction! def change add_index :master_addresses, :country, algorithm: :concurrently end end
chuckmersereau/api_practice
app/validators/casted_value_validator.rb
# rubocop:disable Style/ModuleFunction module CastedValueValidator extend self DATE_FIELD_ENDINGS ||= %w(_at _date _range).freeze def validate!(attribute:, value:) ensure_date_formatting(value) if DATE_FIELD_ENDINGS.any? { |ending| attribute.to_s.end_with?(ending) } end private def ensure_date_formatting(value) case value when Date, DateTime true when Range ensure_date_formatting(value.begin) ensure_date_formatting(value.end) else raise DateTimeCastingError end end class DateTimeCastingError < StandardError; end end
chuckmersereau/api_practice
spec/models/pls_account_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' describe PlsAccount do end
chuckmersereau/api_practice
app/models/event.rb
class Event < Activity end
chuckmersereau/api_practice
db/migrate/20120522184324_remove_user_columns.rb
class RemoveUserColumns < ActiveRecord::Migration def change remove_column :people, :time_zone remove_column :people, :locale end end
chuckmersereau/api_practice
spec/factories/email_addresses.rb
FactoryBot.define do factory :email_address do association :person historic false location 'home' primary false sequence(:email) { |n| "<EMAIL>" } end end
chuckmersereau/api_practice
spec/serializers/reports/pledge_histories_period_serializer_spec.rb
require 'rails_helper' describe Reports::PledgeHistoriesPeriodSerializer do let(:account_list) { create(:account_list) } let(:object) do Reports::PledgeHistoriesPeriod.new(account_list: account_list, start_date: 1.week.ago, end_date: DateTime.current) end subject { described_class.new(object) } it 'serializes attributes' do expect(subject.as_json.keys).to match_array [ :start_date, :end_date, :pledged, :received, :created_at, :id, :updated_at, :updated_in_db_at ] end describe '#id' do it 'returns a custom id' do expect(subject.id).to eq subject.start_date.strftime('%F') end end end
chuckmersereau/api_practice
spec/lib/json_web_token_spec.rb
<gh_stars>0 require 'rails_helper' describe JsonWebToken do let(:payload) { { 'user_id' => SecureRandom.uuid } } let(:token) { JsonWebToken.encode(payload) } context '.encode' do it 'returns encoded token' do expect(token.length).to be > 15 end end context '.decode' do it 'decodes' do expect(JsonWebToken.decode(token)).to eq(payload) end it 'escapes any JWT::Decode errors and returns nil' do expect(JWT).to receive(:decode).and_raise(JWT::DecodeError) expect(JsonWebToken.decode(token)).to eq(nil) end end end
chuckmersereau/api_practice
app/services/google_email_integrator.rb
<gh_stars>0 class GoogleEmailIntegrator attr_accessor :client def initialize(google_integration) @google_integration = google_integration @google_account = google_integration.google_account end def sync_data return unless @google_integration.email_integration? gmail_account = Person::GmailAccount.new(@google_account) gmail_account.import_emails(@google_integration.account_list, @google_integration.email_blacklist) end alias sync_mail sync_data end
chuckmersereau/api_practice
app/models/appeal/excluded_appeal_contact.rb
<reponame>chuckmersereau/api_practice class Appeal::ExcludedAppealContact < ApplicationRecord belongs_to :appeal belongs_to :contact validates :appeal, :contact, presence: true validates :contact_id, uniqueness: { scope: :appeal_id } validate :associations_have_same_account_list protected def associations_have_same_account_list return unless appeal && contact return if contact.account_list_id == appeal.account_list_id errors[:contact] << 'does not have the same account list as appeal' end end
chuckmersereau/api_practice
spec/models/activity_comment_spec.rb
<filename>spec/models/activity_comment_spec.rb require 'rails_helper' RSpec.describe ActivityComment, type: :model do end
chuckmersereau/api_practice
app/services/tnt_import/gifts_import.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 class TntImport::GiftsImport include Concerns::TntImport::DateHelpers include Concerns::TntImport::AppealHelpers include LocalizationHelper attr_reader :contact_ids_by_tnt_contact_id, :xml_tables, :account_list, :organization, :user, :contact def initialize(account_list, contact_ids_by_tnt_contact_id, xml, import) @account_list = account_list @contact_ids_by_tnt_contact_id = contact_ids_by_tnt_contact_id @xml = xml @xml_tables = xml.tables @import = import @user = import&.user @organization = organizations.first end def import return {} unless organizations.count == 1 && xml_tables['Gift'].present? xml_tables['Gift'].each do |row| tnt_contact_id = row['ContactID'] @contact = account_list.contacts.find_by(id: contact_ids_by_tnt_contact_id[tnt_contact_id]) next unless contact donor_account = donor_account_for_contact add_or_update_donation_and_link_to_appeal(row, donor_account) end end private delegate :designation_accounts, to: :account_list def tnt_designation_account account_name = "#{user.to_s.strip} (Imported from TntConnect)" @tnt_designation_account ||= designation_accounts.where(organization: organization, name: account_name) .first_or_create! end def designation_account_for_donation(donation) if donation.designation_account && designation_accounts.include?(donation.designation_account) # If the donation already has a designation account then assume it is the correct one. donation.designation_account else tnt_designation_account end end def add_or_update_donation_and_link_to_appeal(row, donor_account) donation_date = parse_date(row['GiftDate'], @import.user).to_date currency = currency_code_for_id(row['CurrencyID']) donation = account_list.donations.find_by(tnt_id: row['OrgGiftCode']) if row['OrgGiftCode'] donation ||= account_list.donations.find_by(remote_id: row['OrgGiftCode']) if row['OrgGiftCode'] found_exact_match = donation.present? donation ||= donor_account.donations.find_or_initialize_by(tnt_id: nil, donor_account_id: donor_account.id, amount: row['Amount'], donation_date: donation_date) updated_attributes = { amount: row['Amount'], designation_account: designation_account_for_donation(donation), donation_date: donation_date, donor_account_id: donor_account.id, tendered_amount: row['Amount'], currency: currency_code_for_id(row['BaseCurrencyID']), tendered_currency: currency } donation.assign_attributes(updated_attributes) if !found_exact_match || @import.override? donation.tnt_id = row['OrgGiftCode'] donation.save add_donation_to_first_appeal_and_add_other_appeals_to_memo(donation, row, donor_account) create_pledge_for_donation(donation) donation end def add_donation_to_first_appeal_and_add_other_appeals_to_memo(mpdx_donation, tnt_gift, donor_account) # Version 3.2 of Tnt changed the relationship beteween Gifts and Appeals: # In 3.1 a Gift can only belong to one Appeal, through a foreign key on the Gift table. # In 3.2 a Gift can be split and belong to many Appeals, through a new GiftSplit table. if @xml.version < 3.2 add_donation_to_first_appeal_and_add_other_appeals_to_memo_version_3_1(mpdx_donation, tnt_gift) else add_donation_to_first_appeal_and_add_other_appeals_to_memo_version_3_2(mpdx_donation, tnt_gift) end add_donor_account_contacts_to_appeal(donor_account, mpdx_donation.reload.appeal) end def add_donor_account_contacts_to_appeal(donor_account, appeal) return unless donor_account && appeal contact_ids = donor_account.contacts.where(account_list: account_list).ids appeal.bulk_add_contacts(contact_ids: contact_ids) end def add_donation_to_first_appeal_and_add_other_appeals_to_memo_version_3_1(mpdx_donation, tnt_gift) appeal = account_list_appeal_by_tnt_id(tnt_gift['AppealID']) new_memo = generate_new_donation_memo(mpdx_donation) mpdx_donation.update(appeal: appeal, memo: new_memo, appeal_amount: tnt_gift[appeal_amount_name]) end def add_donation_to_first_appeal_and_add_other_appeals_to_memo_version_3_2(mpdx_donation, tnt_gift) gift_splits = account_list_appeals.map do |appeal| gift_splits_by_gift_and_campaign(tnt_gift['id'], appeal.tnt_id.to_s) end.flatten.compact gift_split_with_appeal = gift_splits.find do |gift_split| account_list_appeal_by_tnt_id(gift_split['CampaignID']).present? end appeal = gift_split_with_appeal ? account_list_appeal_by_tnt_id(gift_split_with_appeal['CampaignID']) : nil appeal_amount = appeal ? gift_split_with_appeal['Amount'] : nil new_memo = generate_new_donation_memo(mpdx_donation, (gift_splits - [gift_split_with_appeal])) mpdx_donation.update(appeal: appeal, memo: new_memo, appeal_amount: appeal_amount) end # If the Donation has an Appeal then we need to make sure there is also a # matching Pledge. Otherwise MPDX won't assign the Donation to the Appeal. def create_pledge_for_donation(mpdx_donation) return unless mpdx_donation&.appeal pledge = account_list.pledges.find_or_create_by(amount: mpdx_donation.amount, appeal: mpdx_donation.appeal, contact: contact) pledge.amount_currency ||= mpdx_donation.currency pledge.expected_date ||= mpdx_donation.donation_date pledge.donations << mpdx_donation unless pledge.donations.include?(mpdx_donation) pledge.save end def generate_new_donation_memo(donation, gift_splits = []) new_memo_items = [_('This donation was imported from Tnt.')] new_memo_items += generate_gift_splits_memos(gift_splits) new_memo_items.each { |memo_item| memo_item.gsub!('&quot;', '"') } new_memo_items.reject! do |memo_item| memo_item.blank? || (donation.memo || '').include?(memo_item) end new_memo_items.prepend(donation.memo) if donation.memo.present? new_memo_items.join("\n\n") end def generate_gift_splits_memos(gift_splits) gift_splits.map do |gift_split| current_appeal = account_list_appeal_by_tnt_id(gift_split['CampaignID']) current_currency_symbol = currency_symbol(currency_code_for_id(gift_split['CurrencyID'])) "#{current_currency_symbol}#{gift_split['Amount']}" + format(_(' is designated to the "%{appeal_name}" appeal.'), appeal_name: current_appeal.name) end end def gift_splits_by_gift_and_campaign(gift_id, campaign_id) @gift_splits ||= xml_tables['GiftSplit'] return unless @gift_splits @gift_splits.select do |gift_split| gift_split['GiftID'] == gift_id && gift_split['CampaignID'] == campaign_id end end def account_list_appeals @account_list_appeals ||= account_list.appeals end def account_list_appeal_by_tnt_id(tnt_id) account_list_appeals.find { |appeal| appeal.tnt_id == tnt_id.to_i } end def donor_account_for_contact donor_account = contact.donor_accounts.first return donor_account if donor_account donor_account = Retryable.retryable(tries: 3) do # The donor accounts are importer earlier in the process (TntImport::DonorAccountsImport), # but in case the contact didn't receive one: # Find a unique donor account_number for this contact. Try the current max numeric account number # plus one. If that is a collision due to a race condition, an exception will be raised as there is a # unique constraint on (organization_id, account_number) for donor_accounts. Just wait and try # again in that case. max = organization.donor_accounts.where("account_number ~ '^[0-9]+$'").maximum('CAST(account_number AS bigint)') organization.donor_accounts.create!(account_number: (max.to_i + 1).to_s, name: contact.name) end contact.donor_accounts << donor_account donor_account end def currency_code_for_id(tnt_currency_id) found_currency_row = xml_tables['Currency']&.detect do |currency_row| currency_row['id'] == tnt_currency_id end found_currency_row&.[]('Code').presence || account_list.default_currency end def organizations return [] unless account_list Organization.includes(:organization_accounts) .where(person_organization_accounts: { person_id: account_list.users }) end end
chuckmersereau/api_practice
config/initializers/languages_constant.rb
LANGUAGES_CONSTANT = { 'en-us' => 'US English', 'ar' => 'Arabic', 'hy' => 'Armenian', 'zh-hans-cn' => 'Chinese (Simplified)', 'nl-nl' => 'Dutch (Netherlands)', 'fr-fr' => 'French (France)', 'fr-ca' => 'French (Canadian)', 'de' => 'German', 'id' => 'Indonesian', 'it' => 'Italian', 'ko' => 'Korean', 'pl' => 'Polish', 'pt-BR' => 'Portuguese (Brasil)', 'ru' => 'Russian', 'es-419' => 'Spanish (Latin America)', 'th' => 'Thai', 'tr' => 'Turkish', 'uk' => 'Ukranian' }.freeze
chuckmersereau/api_practice
spec/acceptance/api/v2/account_lists/imports/google_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Account Lists > Imports > from Google' do include_context :json_headers documentation_scope = :account_lists_api_imports before do stub_smarty_streets stub_request(:get, 'https://www.google.com/m8/feeds/contacts/default/full'\ '?alt=json&'\ 'group=http://www.google.com/m8/feeds/groups/test%2540gmail.com/base/d&'\ 'max-results=100000&v=3') end let(:resource_type) { 'imports' } let!(:user) { create(:user_with_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:google_account) { create(:google_account, person_id: user.id) } let(:new_import) do { 'in_preview' => false, 'tag_list' => 'test,poster', 'groups' => [ 'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/d', 'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/f' ], 'import_by_group' => 'true', 'override' => 'true', 'source' => 'google', 'group_tags' => { 'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/6' => 'my-contacts', 'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/d' => 'friends' } } end let(:relationships) do { source_account: { data: { type: 'google_accounts', id: google_account.id } } } end let(:resource_attributes) do %w( file_constants file_constants_mappings file_headers file_headers_mappings file_url account_list_id created_at group_tags groups import_by_group in_preview override source tag_list updated_at updated_in_db_at ) end let(:resource_associations) do %w( sample_contacts user ) end let(:form_data) { build_data(new_import, relationships: relationships) } context 'authorized user' do before { api_login(user) } post '/api/v2/account_lists/:account_list_id/imports/google' do with_options scope: [:data, :attributes] do parameter 'groups', 'Array of Groups (items are group_id)', type: 'String' parameter 'group_tags', 'Group Tags (key: group_id, value: Comma delimited list of tags', type: 'Object' parameter 'import_by_group', 'Import by Group', type: 'String' parameter 'in_preview', "The Import will not be performed while it's in preview", type: 'Boolean' parameter 'override', 'Override', type: 'Boolean' parameter 'source_account_id', 'Source Account ID', type: 'String' parameter 'tag_list', 'Comma delimited list of Tags', type: 'String' end with_options scope: [:data, :attributes] do response_field 'account_list_id', 'Account List ID', type: 'Number' response_field 'created_at', 'Created At', type: 'String' response_field 'file_url', 'Not applicable to Google imports.', type: 'String' response_field 'file_headers_mappings', 'Not applicable to Google imports.', type: 'Object' response_field 'file_headers', 'Not applicable to Google imports.', type: 'Object' response_field 'file_constants', 'Not applicable to Google imports.', type: 'Object' response_field 'file_constants_mappings', 'Not applicable to Google imports.', type: 'Object' response_field 'group_tags', 'Group Tags', type: 'Object' response_field 'groups', 'Groups', type: 'Array[String]' response_field 'import_by_group', 'Import by Group', type: 'String' response_field 'in_preview', 'The Import will not be performed while '\ "it's in preview; Defaults to false", type: 'Boolean' response_field 'override', 'Override', type: 'Boolean' response_field 'source', 'Source; Defaults to "google"', type: 'String' response_field 'tag_list', 'Comma delimited list of Tags', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' end with_options scope: [:data, :relationships] do response_field 'user', 'User that the Import belongs to', type: 'Object' end example 'Google Import [CREATE]', document: documentation_scope do explanation 'Creates a new Google Import associated with the Account List. Unless otherwise '\ 'specified, the Import will be created with "in_preview" set to false, which '\ 'will cause the import to begin after being created '\ '(the import runs asynchronously as a background job).' do_request data: form_data expect(response_status).to eq(201), invalid_status_detail check_resource(['relationships']) expect(response_headers['Content-Type']).to eq 'application/vnd.api+json; charset=utf-8' expect(resource_data['id']).to be_present expect(resource_data['attributes']['source']).to eq 'google' expect(resource_data['attributes']['in_preview']).to eq false expect(resource_data['attributes']['tag_list']).to eq 'test,poster' expect(resource_data['attributes']['import_by_group']).to eq true expect(resource_data['attributes']['groups']).to eq %w( http://www.google.com/m8/feeds/groups/test%40gmail.com/base/d http://www.google.com/m8/feeds/groups/test%40gmail.com/base/f ) expect(resource_data['attributes']['group_tags']).to eq( 'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/6' => 'my-contacts', 'http://www.google.com/m8/feeds/groups/test%40gmail.com/base/d' => 'friends' ) end end end end
chuckmersereau/api_practice
app/services/north_star_report.rb
<gh_stars>0 class NorthStarReport include ActiveRecord::Sanitization def initialize(end_date: Time.zone.today, weeks: 20) @end_date = end_date @weeks = weeks end def weeks start_date = (@end_date - @weeks.weeks).beginning_of_week end_date = (@end_date - 1.week).end_of_week inner_query = AccountList.select("date_trunc('week', activities.completed_at) AS week, "\ 'count(DISTINCT account_lists.id) AS users') .where(activities: { completed_at: start_date..end_date }) .group('week') .joins(:activities).to_sql format AccountList.connection.execute(inner_query).to_a end def months start_date = (@end_date - @weeks.months).beginning_of_month inner_query = AccountList.select("date_trunc('month', activities.completed_at) AS month, "\ 'count(DISTINCT account_lists.id) AS users') .where(activities: { completed_at: start_date..@end_date }) .group('month') .joins(:activities).to_sql format AccountList.connection.execute(inner_query).to_a end def weeks_with_history current = weeks old_end_date = @end_date @end_date -= 52.weeks historic = weeks @end_date = old_end_date current.each_with_index { |row, i| row['old'] = historic.dig(i, 'users') } end private def format(data_array) data_array.each do |row| row['week'] = DateTime.parse(row['week']).strftime('%m-%d-%y') if row['week'] row['month'] = DateTime.parse(row['month']).strftime('%m-%Y') if row['month'] end end end
chuckmersereau/api_practice
spec/acceptance/api/v2/contacts/people/phones_spec.rb
<reponame>chuckmersereau/api_practice<gh_stars>0 require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Contacts > People > Phones' do include_context :json_headers documentation_scope = :people_api_phones let(:resource_type) { 'phone_numbers' } let!(:user) { create(:user_with_full_account) } let(:contact) { create(:contact, account_list: user.account_lists.order(:created_at).first) } let(:contact_id) { contact.id } let(:person) { create(:person, contacts: [contact]) } let(:person_id) { person.id } let!(:phone) { create(:phone_number, person: person) } let(:id) { phone.id } let(:new_phone) do attributes_for(:phone_number, number: '3561987123') .reject { |key| key.to_s.end_with?('_id') } .merge(updated_in_db_at: phone.updated_at) end let(:form_data) { build_data(new_phone) } let(:expected_attribute_keys) do %w( country_code created_at historic location number primary source updated_at updated_in_db_at valid_values ) end context 'authorized user' do before { api_login(user) } get '/api/v2/contacts/:contact_id/people/:person_id/phones' do example 'Phone [LIST]', document: documentation_scope do explanation 'List of Phone Numbers associated to the Person' do_request check_collection_resource(1) expect(response_status).to eq(200) end end get '/api/v2/contacts/:contact_id/people/:person_id/phones/:id' do with_options scope: [:data, :attributes] do response_field 'country_code', 'Country Code', type: 'String' response_field 'created_at', 'Created At', type: 'String' response_field 'historic', 'Historic', type: 'Boolean' response_field 'location', 'Location', type: 'String' response_field 'number', 'Number', type: 'String' response_field 'primary', 'Primary', type: 'Boolean' response_field 'source', 'Source', type: 'String' response_field 'updated_at', 'Updated At', type: 'String' response_field 'updated_in_db_at', 'Updated In Db At', type: 'String' response_field 'valid_values', 'Valid', type: 'Boolean' end example 'Phone [GET]', document: documentation_scope do explanation 'The Person\'s Phone Number with the given ID' do_request expect(resource_object.keys).to match_array expected_attribute_keys check_resource expect(response_status).to eq(200) end end post '/api/v2/contacts/:contact_id/people/:person_id/phones' do with_options required: true, scope: [:data, :attributes] do parameter 'country-code', 'Country Code' parameter 'location', 'Location' parameter 'number', 'Number' parameter 'primary', 'Primary' parameter 'remote_id', 'Remote ID' parameter 'source', 'Source' parameter 'valid_values', 'Valid Values' end example 'Phone [CREATE]', document: documentation_scope do explanation 'Create a Phone Number associated with the Person' do_request data: form_data expect(resource_object['number']).to eq new_phone[:number] expect(response_status).to eq 201 end end put '/api/v2/contacts/:contact_id/people/:person_id/phones/:id' do with_options required: true, scope: [:data, :attributes] do parameter 'country-code', 'Country Code' parameter 'location', 'Location' parameter 'number', 'Number' parameter 'primary', 'Primary' parameter 'remote_id', 'Remote ID' parameter 'source', 'Source' parameter 'valid_values', 'Valid Values' end example 'Phone [UPDATE]', document: documentation_scope do explanation 'Update Person\'s Phone Number with the given ID' do_request data: form_data expect(resource_object['number']).to eq new_phone[:number] expect(response_status).to eq(200) end end delete '/api/v2/contacts/:contact_id/people/:person_id/phones/:id' do example 'Phone [DELETE]', document: documentation_scope do explanation 'Delete Person\'s Phone Number with the given ID' do_request expect(response_status).to eq 204 end end end end
chuckmersereau/api_practice
spec/factories/master_addresses.rb
FactoryBot.define do factory :master_address do street 'MyText' city 'MyString' state 'MyString' country 'MyString' postal_code 'MyString' latitude '0' longitude '0' end end
chuckmersereau/api_practice
spec/controllers/api/v2/account_lists/pledges_controller_spec.rb
require 'rails_helper' RSpec.describe Api::V2::AccountLists::PledgesController, type: :controller do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let(:contact) { create(:contact, account_list: account_list) } let(:factory_type) { :pledge } let!(:resource) do create(:pledge, account_list: account_list, contact: contact, amount: 9.99, expected_date: 1.month.ago) end let!(:second_resource) do create(:pledge, account_list: account_list, amount: 10.00, expected_date: 2.months.from_now) end let(:id) { resource.id } let(:parent_param) do { account_list_id: account_list.id } end let(:correct_attributes) do { amount: 200.00, amount_currency: 'USD', expected_date: Date.today } end let(:correct_relationships) do { contact: { data: { id: contact.id, type: 'contacts' } } } end let(:unpermitted_relationships) do { contact: { data: { id: create(:contact).id, type: 'contacts' } } } end let(:incorrect_attributes) do { amount: 200.00, expected_date: nil } end include_examples 'index_examples' include_examples 'show_examples' include_examples 'update_examples' include_examples 'destroy_examples' describe 'sort' do before { api_login(user) } let(:contact_2) { create(:contact, account_list: account_list, name: 'zzzzz') } let!(:pledge_3) { create(:pledge, account_list: account_list, contact: contact_2, amount: 10.00) } it 'sorts results by contact.name desc' do get :index, parent_param.merge(sort: 'contact.name') json = JSON.parse(response.body) ids = json['data'].collect { |pledge| pledge['id'] } expect(ids.last).to eq pledge_3.id end it 'sorts results by contact.name asc' do get :index, parent_param.merge(sort: '-contact.name') json = JSON.parse(response.body) ids = json['data'].collect { |pledge| pledge['id'] } expect(ids.first).to eq pledge_3.id end end describe 'filtering' do before { api_login(user) } context 'status filter' do let(:contact_2) { create(:contact, account_list: account_list) } let!(:pledge_3) do create(:pledge, account_list: account_list, contact: contact_2, amount: 10.00, status: :processed) end it 'filters results' do get :index, parent_param.merge(filter: { status: 'processed' }) expect(response.status).to eq(200) expect(response_json['data'].length).to eq(1) expect(response_json['data'][0]['id']).to eq(pledge_3.id) end end end context 'with no existing Pledges' do before { Pledge.destroy_all } include_examples 'create_examples' end context 'User::Coach' do include_context 'common_variables' let(:coach) { create(:user).becomes(User::Coach) } before do account_list.coaches << coach full_params[:include] = 'contact' end describe '#index' do it 'shows list of resources to coach that are signed in' do api_login(coach) get :index, full_params expect(response.status).to eq(200), invalid_status_detail expect(json_response['data'].count).to eq 1 expect(json_response['data'][0]['id']).to eq resource.id expect(json_response['data'][0]['attributes'].keys).to eq( %w(amount created_at expected_date updated_at updated_in_db_at) ) expect(json_response['data'][0]['relationships'].keys).to eq( %w(contact) ) expect(json_response['included'].count).to eq 1 expect(json_response['included'][0]['id']).to eq resource.contact.id expect(json_response['included'][0]['attributes'].keys).to eq( %w(created_at late_at locale name pledge_amount pledge_currency pledge_currency_symbol pledge_frequency pledge_received pledge_start_date updated_at updated_in_db_at) ) end it 'only shows records that are on primary appeal' do resource.update(appeal: create(:appeal, account_list: account_list)) api_login(coach) get :index, full_params expect(response.status).to eq(200), invalid_status_detail expect(json_response['data'].count).to eq 0 end it 'does not show list of resources to users that are not signed in' do get :index, full_params expect(response.status).to eq(401), invalid_status_detail end end describe '#create' do it 'does not create resource for users that are only coaches' do post :create, full_correct_attributes expect(response.status).to eq(401), invalid_status_detail end end describe '#update' do it 'does not create resource for users that are only coaches' do put :update, full_correct_attributes expect(response.status).to eq(401), invalid_status_detail end end describe '#destroy' do it 'does not create resource for users that are only coaches' do delete :destroy, full_correct_attributes expect(response.status).to eq(401), invalid_status_detail end end end end
chuckmersereau/api_practice
spec/preloaders/application_preloader_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe ApplicationPreloader do context 'methods' do let(:include_params) { ['addresses', 'primary_person', 'people.facebook_accounts'] } let(:field_params) do { addresses: ['region'], contacts: [], facebook_accounts: ['remote_id'], primary_person: %w(first_name avatar email) } end let!(:contact_one) { create(:contact) } let!(:contact_two) { create(:contact) } let!(:person_one) { create(:person, contacts: [contact_one]) } let!(:person_two) { create(:person, contacts: [contact_two]) } let!(:contacts) { Contact.all } let(:expected_associations) do [ :addresses, :primary_person, { primary_person: [:primary_picture, :primary_email_address] }, { people: [:facebook_accounts] } ] end subject { ContactsPreloader.new(include_params, field_params) } describe '#preload' do it 'preloads the correct association' do expect(contacts).to receive(:preload).with(*expected_associations) subject.preload(contacts) end end describe '#associations_to_preload' do describe 'if specific associations are included' do it 'preloads the correct association' do expect(subject.associations_to_preload).to eq(expected_associations) end end end module Contacts class AddressesPreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = {}.freeze FIELD_ASSOCIATION_MAPPING = {}.freeze end class PeoplePreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = {}.freeze FIELD_ASSOCIATION_MAPPING = { avatar: :primary_picture, email: :primary_email_address }.freeze end module People class FacebookAccountsPreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = {}.freeze FIELD_ASSOCIATION_MAPPING = {}.freeze def serializer_class Person::FacebookAccountSerializer end end end end class ContactsPreloader < ApplicationPreloader ASSOCIATION_PRELOADER_MAPPING = { primary_person: Contacts::PeoplePreloader }.freeze FIELD_ASSOCIATION_MAPPING = {}.freeze end end end
chuckmersereau/api_practice
spec/services/mail_chimp/importer_spec.rb
require 'rails_helper' describe MailChimp::Importer do let(:mail_chimp_account) { create(:mail_chimp_account, active: true) } let(:account_list) { mail_chimp_account.account_list } subject { described_class.new(mail_chimp_account) } let(:mock_connection_handler) { double(:mock_connection_handler) } let(:mock_gibbon_wrapper) { double(:mock_gibbon_wrapper) } let(:mock_matcher) { double(:mock_matcher) } let(:mock_gibbon_list) { double(:mock_gibbon_list) } let(:email) { '<EMAIL>' } context '#import_all_members' do it 'uses the connection handler and import_all_members! is called' do expect(MailChimp::ConnectionHandler).to receive(:new).and_return(mock_connection_handler) expect(mock_connection_handler).to receive(:call_mail_chimp).with(subject, :import_all_members!) subject.import_all_members end end context '#import_members_by_email' do it 'uses the connection handler and import_members_by_email! is called' do expect(MailChimp::ConnectionHandler).to receive(:new).and_return(mock_connection_handler) expect(mock_connection_handler).to receive(:call_mail_chimp).with(subject, :import_members_by_email!, [email]) subject.import_members_by_email([email]) end end context '#import_all_members & import_members_by_email' do let(:mail_chimp_member) { create(:mail_chimp_member, mail_chimp_account: mail_chimp_account) } let(:member_infos) do [ { 'merge_fields' => { 'FNAME' => 'First Name', 'LNAME' => 'Last Name', 'GREETING' => 'Greeting', 'GROUPINGS' => 'Random Grouping' }, 'email_address' => '<EMAIL>', 'status' => 'subscribed' }, { 'merge_fields' => { 'FNAME' => '<NAME> Name', 'LNAME' => 'Second Last Name', 'GREETING' => 'Second Greeting', 'GROUPINGS' => 'Second Random Grouping' }, 'email_address' => '<EMAIL>', 'status' => 'subscribed' }, { 'merge_fields' => { 'GREETING' => 'Third Greeting', 'GROUPINGS' => 'Third Random Grouping' }, 'email_address' => '<EMAIL>', 'status' => 'subscribed' }, { 'merge_fields' => { 'FNAME' => 'Fourth First Name', 'LNAME' => 'Fourth Last Name', 'GREETING' => 'Fourth Greeting', 'GROUPINGS' => 'Fourth Random Grouping' }, 'email_address' => '<EMAIL>', 'status' => 'cleaned' }, { 'merge_fields' => { 'FNAME' => 'Fifth First Name', 'LNAME' => 'Fifth Last Name', 'GREETING' => 'Fifth Greeting', 'GROUPINGS' => 'Fifth Random Grouping' }, 'email_address' => '<EMAIL>', 'status' => 'unsubscribed', 'unsubscribe_reason' => 'Not Interested' } ] end let(:formatted_member_infos) do [ { email: '<EMAIL>', first_name: '<NAME>', last_name: '<NAME>', greeting: 'Greeting', groupings: 'Random Grouping', status: 'subscribed', unsubscribe_reason: nil }, { email: '<EMAIL>', first_name: '<NAME>', last_name: '<NAME>', greeting: 'Second Greeting', groupings: 'Second Random Grouping', status: 'subscribed', unsubscribe_reason: nil }, { email: '<EMAIL>', first_name: nil, last_name: nil, greeting: 'Third Greeting', groupings: 'Third Random Grouping', status: 'subscribed', unsubscribe_reason: nil }, { email: '<EMAIL>', first_name: '<NAME>', last_name: '<NAME>', greeting: 'Fourth Greeting', groupings: 'Fourth Random Grouping', status: 'cleaned', unsubscribe_reason: nil }, { email: '<EMAIL>', first_name: '<NAME>', last_name: '<NAME>', greeting: 'Fifth Greeting', groupings: 'Fifth Random Grouping', status: 'unsubscribed', unsubscribe_reason: 'Not Interested' } ] end let(:matching_people_hash) do { person.id => { email: '<EMAIL>', first_name: '<NAME>', last_name: '<NAME>', greeting: 'Greeting', groupings: 'Random Grouping', status: 'subscribed', unsubscribe_reason: nil }, second_person.id => { email: '<EMAIL>', first_name: '<NAME>', last_name: '<NAME>', greeting: 'Greeting', groupings: 'Random Grouping', status: 'subscribed', unsubscribe_reason: nil } }.with_indifferent_access end let!(:person) { create(:person, primary_email_address: build(:email_address, email: '<EMAIL>')) } let!(:contact) { create(:contact, primary_person: person, send_newsletter: 'None') } let!(:second_person) { create(:person, primary_email_address: nil, first_name: '<NAME>', last_name: '<NAME>') } let!(:second_contact) { create(:contact, primary_person: second_person, send_newsletter: 'None') } let(:new_contacts) { Contact.order(:created_at).last(4) } before do allow(MailChimp::GibbonWrapper).to receive(:new).and_return(mock_gibbon_wrapper) allow(mock_gibbon_wrapper).to receive(:list_emails).and_return(['<EMAIL>', '<EMAIL>']) allow(mock_gibbon_wrapper).to receive(:gibbon_list_object).and_return(mock_gibbon_list) allow(mock_gibbon_wrapper).to receive(:list_member_info).and_return(member_infos) allow(described_class::Matcher).to receive(:new).and_return(mock_matcher) end # context '#import_all_members!' do # it 'calls Matcher instance with correct arguments and updates/creates the contact/people records' do # expect(mock_matcher).to receive(:find_matching_people).with(formatted_member_infos).and_return(matching_people_hash) # expect do # subject.import_all_members! # end.to change { Person.count }.by(4) # expect(second_person.primary_email_address).to be_nil # expect(new_contacts.first.send_newsletter).to eq('Email') # expect(new_contacts.first.primary_person.primary_email_address.email).to eq('<EMAIL>') # expect(new_contacts.second.name).to eq('Third Email') # expect(new_contacts.second.primary_person.first_name).to eq('Third Email') # expect(new_contacts.third.primary_person.email_addresses.first.historic).to be_truthy # expect(new_contacts.fourth.send_newsletter).to be_nil # expect(new_contacts.fourth.primary_person.optout_enewsletter).to be_truthy # expect(contact.reload.send_newsletter).to eq('None') # end # end # context '#import_members_by_email!' do # it 'calls Matcher instance with correct arguments and updates/creates the contact/people records' do # expect(mock_matcher).to receive(:find_matching_people).with(formatted_member_infos).and_return(matching_people_hash) # expect do # subject.import_members_by_email!(formatted_member_infos.map { |member| member[:email] }) # end.to change { Person.count }.by(4) # expect(new_contacts.first.send_newsletter).to eq('Email') # expect(new_contacts.first.primary_person.primary_email_address.email).to eq('<EMAIL>') # expect(new_contacts.second.name).to eq('Third Email') # expect(new_contacts.second.primary_person.first_name).to eq('Third Email') # expect(new_contacts.third.primary_person.email_addresses.first.historic).to be_truthy # expect(new_contacts.fourth.send_newsletter).to be_nil # expect(new_contacts.fourth.primary_person.optout_enewsletter).to be_truthy # expect(contact.reload.send_newsletter).to eq('None') # end # end end end
chuckmersereau/api_practice
app/concerns/tags_eager_loading.rb
<reponame>chuckmersereau/api_practice # Hacky monkey patch because the acts_as_taggable gem doesn't work well with eager loading # See https://github.com/mbleigh/acts-as-taggable-on/issues/9 module TagsEagerLoading extend ActiveSupport::Concern included do original_tag_list = instance_method(:tag_list) define_method(:tag_list) do # acts_as_taggable caches with this variable using a TagList @tag_list ||= ActsAsTaggableOn::TagList.new(*tags.map(&:name)) if tags.loaded? original_tag_list.bind(self).call end end end
chuckmersereau/api_practice
spec/factories/master_person_donor_accounts.rb
FactoryBot.define do factory :master_person_donor_account do association :master_person association :donor_account primary false end end
chuckmersereau/api_practice
app/services/task/filter/exclude_tags.rb
class Task::Filter::ExcludeTags < Task::Filter::Base def execute_query(tasks, filters) tasks.tagged_with(parse_list(filters[:exclude_tags]), exclude: true) end end
chuckmersereau/api_practice
spec/requests/api/v2/post_requests_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe 'Post Requests', type: :request do let(:headers) do { 'CONTENT_TYPE' => 'application/vnd.api+json', 'Accept' => 'application/vnd.api+json' } end let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.first } describe 'with a related resource' do before { api_login(user) } context "when the related resource doesn't exist" do let!(:new_task_attributes) { attributes_for(:task) } let!(:data) do { data: { type: :tasks, attributes: new_task_attributes, relationships: { account_list: { data: { id: SecureRandom.uuid, type: 'account_lists' } } } } }.to_json end it 'returns a 404' do post api_v2_tasks_path, data, headers expect(response.status).to eq(404), invalid_status_detail end end end describe 'with a Client Generated UUID' do let(:desired_id) { SecureRandom.uuid } let(:contact_attributes) { attributes_for(:contact, name: '<NAME>').except!(:id) } before { api_login(user) } context 'with the UUID in the correct placement: /data/id' do let(:post_attributes) do { data: { type: :contacts, id: desired_id, attributes: contact_attributes, relationships: { account_list: { data: { type: 'account_lists', id: account_list.id } } } } }.to_json end it 'creates a resource with the Client Generated UUID' do post api_v2_contacts_path, post_attributes, headers expect(response.status).to eq(201), invalid_status_detail expect(json_response['data']['id']).to eq desired_id end end context 'with the id in: /data/attributes' do let(:post_attributes) do { data: { type: :contacts, attributes: contact_attributes.merge!( id: desired_id ), relationships: { account_list: { data: { type: 'account_lists', id: account_list.id } } } } }.to_json end let(:error_message) do 'A primary key, if sent in a request, CANNOT be referenced in the #attributes of a JSONAPI '\ "resource object. It must instead be sent as a top level member of the resource's `data` "\ 'object. Reference: `/data/attributes/id`. Expected `/data/id`' end it 'returns an error' do post api_v2_contacts_path, post_attributes, headers expect(response.status).to eq(409), invalid_status_detail expect(json_response['errors'].first['detail']).to eq(error_message) end end context 'with a id that already exists' do let!(:pre_existing_task) { create(:task, account_list: account_list) } let!(:new_task_attributes) { attributes_for(:task) } let!(:data) do { data: { id: pre_existing_task.id, type: :tasks, attributes: new_task_attributes, relationships: { account_list: { data: { type: 'account_lists', id: account_list.id } } } } }.to_json end it 'returns a 409' do post api_v2_tasks_path, data, headers expect(response.status).to eq(409), invalid_status_detail end end end describe 'creating a resource with a specified type' do before { api_login(user) } context 'when the resource type is correct' do let!(:new_task_attributes) { attributes_for(:task) } let!(:valid_type) { :tasks } let!(:data) do { data: { type: valid_type, attributes: new_task_attributes, relationships: { account_list: { data: { type: 'account_lists', id: account_list.id } } } } }.to_json end it 'returns a 201' do post api_v2_tasks_path, data, headers expect(response.status).to eq(201), invalid_status_detail expect(json_response['errors']).to be_nil end end context 'when the resource type is incorrect' do let!(:new_task_attributes) { attributes_for(:task) } let!(:invalid_type) { :gummybear } let!(:data) do { data: { type: invalid_type, attributes: new_task_attributes.merge!( account_list_id: account_list.id ) } }.to_json end let(:error_message) do "'gummybear' is not a valid resource type for this endpoint. Expected 'tasks' instead" end it 'returns a 409' do post api_v2_tasks_path, data, headers expect(response.status).to eq(409), invalid_status_detail expect(json_response['errors'].first['title']).to eq('Conflict') expect(json_response['errors'].first['detail']).to eq(error_message) end end context 'when the resource type is missing' do let!(:new_task_attributes) { attributes_for(:task) } let!(:data) do { data: { type: nil, # missing type attributes: new_task_attributes, relationships: { account_list: { data: { type: 'account_lists', id: account_list.id } } } } }.to_json end let(:error_message) do 'JSONAPI resource objects MUST contain a `type` top-level member of its hash for POST '\ 'and PATCH requests. Expected to find a `type` member at /data/type' end it 'returns a 409' do post api_v2_tasks_path, data, headers expect(response.status).to eq(409), invalid_status_detail expect(json_response['errors'].first['title']).to eq('Conflict') expect(json_response['errors'].first['detail']).to eq(error_message) end end end end
chuckmersereau/api_practice
dev/fixers/default_pledges_from_donations.rb
# I used this to set some basic default pledge info for a global user who had # some trouble with MPDX. The logic it uses is very basic and likely wrong in # many cases, but the goal was just to do a quick thing to help him out. This # general idea could be a cool feature to add for someone who is moving to MPDX # as a senior staff if they don't have TntMPD and want to get a general handle # on people's commitments based on their giving history def default_pledges!(account_list) puts 'defaulting pledges..' account_list.contacts.where(pledge_amount: nil).each(&method(:default_pledge!)) nil end def default_pledge!(contact) if contact.pledge_amount.present? puts "Pledge for #{contact} ##{contact.id} already set to "\ "#{contact.pledge_amount} "\ "#{Contact.pledge_frequencies[contact.pledge_frequency]}" return end frequencies = [1, 3, 12] frequencies.each do |frequency| return true if try_frequency!(contact, frequency) end puts "Pledge for #{contact} ##{contact.id} not changed" end def try_frequency!(contact, frequency) look_back_period = (frequency * 3).to_i.months.ago.beginning_of_month.to_date donations = contact.donations.where('donation_date >= ?', look_back_period) # If the person gave between 3 and 4 times in the past 3 complete periods + # partial current period then assuming they give at this frequency. return false unless (3..4).cover?(donations.count) && contact.pledge_frequency.nil? amount = donations.first.amount puts "Pledge for #{contact} ##{contact.id} set to #{amount} "\ "#{Contact.pledge_frequencies[frequency.to_d]}" contact.update!( status: 'Partner - Financial', pledge_frequency: frequency, pledge_amount: amount, pledge_received: true ) true end
chuckmersereau/api_practice
spec/factories/companies.rb
<filename>spec/factories/companies.rb<gh_stars>0 FactoryBot.define do factory :company do name 'MyString' end end
chuckmersereau/api_practice
db/migrate/20120328193356_add_token_to_person_organization_account.rb
<reponame>chuckmersereau/api_practice class AddTokenToPersonOrganizationAccount < ActiveRecord::Migration def change add_column :person_organization_accounts, :token, :string end end
chuckmersereau/api_practice
spec/models/duplicate_record_pair_spec.rb
require 'rails_helper' describe DuplicateRecordPair, type: :model do let!(:account_list) { create(:account_list) } let!(:record_one) { create(:contact).tap { |c| account_list.contacts << c } } let!(:record_two) { create(:contact).tap { |c| account_list.contacts << c } } let!(:record_three) { create(:contact).tap { |c| account_list.contacts << c } } it 'sorts the record ids' do drp = DuplicateRecordPair.create!(account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing') expect(drp.record_one_id).to eq(record_one.id) expect(drp.record_two_id).to eq(record_two.id) expect(drp.record_two.created_at > drp.record_one.created_at).to eq(true) drp.update!(record_one_id: record_two.id, record_two_id: record_one.id) expect(drp.record_one_id).to eq(record_one.id) expect(drp.record_two_id).to eq(record_two.id) DuplicateRecordPair.delete_all drp = DuplicateRecordPair.create!(account_list: account_list, record_one: record_two, record_two: record_one, reason: 'Testing') expect(drp.record_one_id).to eq(record_one.id) expect(drp.record_two_id).to eq(record_two.id) end it 'validates presence of both ids' do drp = DuplicateRecordPair.new(account_list: account_list, record_one: record_one, record_two: nil, reason: 'Testing') expect(drp.valid?).to eq(false) drp = DuplicateRecordPair.new(account_list: account_list, record_one: nil, record_two: record_two, reason: 'Testing') expect(drp.valid?).to eq(false) drp = DuplicateRecordPair.new(account_list: account_list, record_one: nil, record_two: nil, reason: 'Testing') expect(drp.valid?).to eq(false) drp = DuplicateRecordPair.new(account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing') expect(drp.valid?).to eq(true) end it 'validates that both records have the same type' do drp = DuplicateRecordPair.create!(account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing') expect(drp.valid?).to eq(true) drp.record_one_type = 'Person' expect(drp.valid?).to eq(false) drp.record_one_type = 'Contact' expect(drp.valid?).to eq(true) end it 'validates that both records belong to the same AccountList' do other_account_list = create(:account_list) other_contact = create(:contact).tap { |c| other_account_list.contacts << c } expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing' ) end.to_not raise_error expect do DuplicateRecordPair.create!( account_list: other_account_list, record_one: record_one, record_two: record_two, reason: 'Testing' ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: other_contact, record_two: record_two, reason: 'Testing' ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: other_contact, reason: 'Testing' ) end.to raise_error(ActiveRecord::RecordInvalid) end it 'validates that the pair is unique' do expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing 1', ignore: true ) end.to_not raise_error expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing 2', ignore: true ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_two, record_two: record_one, reason: 'Testing 3', ignore: true ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing 4', ignore: false ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_two, record_two: record_one, reason: 'Testing 5', ignore: false ) end.to raise_error(ActiveRecord::RecordInvalid) expect(DuplicateRecordPair.count).to eq(1) DuplicateRecordPair.first.update!(ignore: false) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing 2', ignore: true ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_two, record_two: record_one, reason: 'Testing 3', ignore: true ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing 4', ignore: false ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_two, record_two: record_one, reason: 'Testing 5', ignore: false ) end.to raise_error(ActiveRecord::RecordInvalid) end it 'validates that a record cannot be in multiple pairs' do expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing' ) end.to_not raise_error expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing' ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_two, record_two: record_one, reason: 'Testing' ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_two, record_two: record_three, reason: 'Testing' ) end.to raise_error(ActiveRecord::RecordInvalid) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_three, record_two: record_two, reason: 'Testing' ) end.to raise_error(ActiveRecord::RecordInvalid) DuplicateRecordPair.first.update!(ignore: true) expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_one, record_two: record_three, reason: 'Testing' ) end.to_not raise_error expect do DuplicateRecordPair.create!( account_list: account_list, record_one: record_three, record_two: record_two, reason: 'Testing' ) end.to raise_error(ActiveRecord::RecordInvalid) expect(DuplicateRecordPair.count).to eq(2) end describe 'scope type' do let!(:drp1) do DuplicateRecordPair.create!(account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing') end let!(:drp2) do DuplicateRecordPair.create!(account_list: account_list, record_one: create(:contact, account_list: account_list), record_two: create(:contact, account_list: account_list), reason: 'Testing') end it "returns DuplicateRecordPair's with the expected type" do expect(DuplicateRecordPair.type('Contact').to_a).to contain_exactly(drp1, drp2) expect(DuplicateRecordPair.type('Person').to_a).to eq([]) end end describe '#type' do let(:duplicate_record_pair) do DuplicateRecordPair.create!(account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing') end it 'returns the type if they are the same' do expect(duplicate_record_pair.type).to eq('Contact') duplicate_record_pair.record_one_type = 'Asdf' expect(duplicate_record_pair.type).to eq(nil) duplicate_record_pair.record_two_type = 'Asdf' expect(duplicate_record_pair.type).to eq('Asdf') end end describe '#records' do let(:duplicate_record_pair) do DuplicateRecordPair.create!(account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing') end it 'returns the record pair as an array' do expect(duplicate_record_pair.records).to eq([record_one, record_two]) end end describe '#ids' do let(:duplicate_record_pair) do DuplicateRecordPair.create!(account_list: account_list, record_one: record_one, record_two: record_two, reason: 'Testing') end it 'returns the record ids as an array' do expect(duplicate_record_pair.ids).to eq([record_one.id, record_two.id]) end end end
chuckmersereau/api_practice
spec/lib/json_api_service/transformer_spec.rb
<filename>spec/lib/json_api_service/transformer_spec.rb require 'spec_helper' require 'json_api_service/transformer' require 'json_api_service/configuration' require 'support/json_api_service_helper' module JsonApiService RSpec.describe Transformer, type: :service do include JsonApiServiceHelpers UUID_REGEX = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i unless defined? UUID_REGEX before do allow(UUID_REGEX).to receive(:match).and_return(true) end describe '.transform' do let(:params) { double(:params) } let(:configuration) { double(:configuration) } let(:transformer) do double(:transformer, transform: 'Autobots, transform and ROLL OUT!') end before do allow(Transformer) .to receive(:new) .with(params: params, configuration: configuration) .and_return(transformer) end it 'delegates the arguments to a new instance and calls `.transform`' do result = Transformer.transform( params: params, configuration: configuration ) expect(result).to eq 'Autobots, transform and ROLL OUT!' end end describe '#initialize' do context 'with an ActionController::Parameters object' do let(:params) { build_params_with({}) } let(:transformer) { build_transformer(params: params) } it 'initializes with a params object' do expect(transformer.params).to eq params end end context 'WITHOUT an ActionController::Parameters object' do let(:params) { { hi: "I'm not an ActionController::Parameters object" } } it 'raises an ArgumentError' do expect { build_transformer(params: params) } .to raise_error(ArgumentError) .with_message('must provide an ActionController::Parameters object, ie: the params from a controller action') end end end describe '#create?' do context 'when the controller action is "create"' do let(:params) do params = { action: 'create' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } it 'is true' do expect(transformer).to be_create end end context "when the controller action isn't 'create'" do let(:params) do params = { action: 'update' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } it 'is false' do expect(transformer).not_to be_create end end end describe '#update?' do context "when the controller action is 'update'" do let(:params) do params = { action: 'update' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } it 'is true' do expect(transformer).to be_update end end context "when the controller action isn't 'create'" do let(:params) do params = { action: 'create' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } it 'is false' do expect(transformer).not_to be_update end end end describe '#transform' do describe 'with no relationships' do let(:params) do params = { data: { type: 'mock_contacts', attributes: { name: '<NAME>' } }, action: 'create', controller: 'users' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } it 'correctly transforms the values' do expected_hash = { mock_contact: { name: '<NAME>' }, action: 'create', controller: 'users' } expect(transformer.transform).to eq build_params_with(expected_hash) end end describe 'during an INDEX' do context 'with filter params' do let(:params) do params = { action: 'index', controller: 'mock_contacts', filter: { mock_account_list_id: 'qwe123' } } build_params_with(params) end let(:transformer) { build_transformer(params: params) } before do mock_id_reference( from: 'qwe123', to: 'qwe123', resource: MockAccountList ) end it 'correctly transforms the filter params' do expected_hash = { action: 'index', controller: 'mock_contacts', filter: { mock_account_list_id: 'qwe123' } } expect(transformer.transform).to eq build_params_with(expected_hash) end end context 'with filter params that have comma delimited IDs and empty IDs' do let(:params) do params = { action: 'index', controller: 'mock_contacts', filter: { mock_account_list_id: 'qwe123, rty890, ,' } } build_params_with(params) end let(:transformer) { build_transformer(params: params) } before do mock_id_reference( from: %w(qwe123 rty890), to: %w(qwe123 rty890), resource: MockAccountList ) end it 'correctly transforms the filter params' do expected_hash = { action: 'index', controller: 'mock_contacts', filter: { mock_account_list_id: %w(qwe123 rty890) } } expect(transformer.transform).to eq build_params_with(expected_hash) end end end describe 'with a id as the primary id' do context 'during a POST' do let(:params) do params = { data: { type: 'mock_contacts', id: 'abc123', attributes: { name: '<NAME>' } }, action: 'create', controller: 'mock_contacts' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } before do mock_empty_id_reference( from: ['abc123'], resource: MockContact ) end it "moves the id into the resource's attributes" do expected_hash = { mock_contact: { name: '<NAME>', id: 'abc123' }, action: 'create', controller: 'mock_contacts' } expect(transformer.transform).to eq build_params_with(expected_hash) end end context 'during a PATCH' do let(:params) do params = { data: { type: 'mock_contacts', id: 'abc123', attributes: { name: '<NAME>' } }, action: 'update', controller: 'mock_contacts' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } before { mock_id_reference(from: 'abc123', to: 55, resource: MockContact) } it "moves the id into the resource's attributes and finds the ID" do expected_hash = { mock_contact: { id: 'abc123', name: '<NAME>' }, action: 'update', controller: 'mock_contacts' } expect(transformer.transform).to eq build_params_with(expected_hash) end end end describe 'with a foreign_key relationship' do context 'with indirectly named relationships' do let(:params) do params = { data: { type: 'mock_contact_referrals', relationships: { referred_by: { data: { type: 'mock_contacts', id: 'abc123' } }, referred_to: { data: { type: 'mock_contacts', id: 'none' } } } }, action: 'create' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } before do mock_id_reference( from: %w(abc123 none), to: ['abc123', nil], resource: MockContact ) end it 'correctly transforms the values' do expected_hash = { mock_contact_referral: { referred_by_id: 'abc123', referred_to_id: nil }, action: 'create' } expect(transformer.transform).to eq build_params_with(expected_hash) end end context 'with a directly named relationship' do let(:params) do params = { data: { type: 'mock_contacts', attributes: { name: '<NAME>' }, relationships: { mock_account_list: { data: { type: 'mock_account_lists', id: 'abc123' } } } }, action: 'create' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } before { mock_id_reference(from: 'abc123', to: 'abc123', resource: MockAccountList) } it 'correctly transforms the values' do expected_hash = { mock_contact: { mock_account_list_id: 'abc123', name: '<NAME>' }, action: 'create' } expect(transformer.transform).to eq build_params_with(expected_hash) end end end describe 'with a nested relationships' do let(:params) do params = { data: { type: 'mock_contacts', attributes: { name: '<NAME>' }, relationships: { mock_addresses: { data: [ { id: 'addresses-id-abc123', type: 'mock_addresses', attributes: { location: 'Home', city: 'Fremont', street: '123 Somewhere St', state: 'CA', country: 'United States' } }, { id: 'addresses-id-def456', type: 'mock_addresses', attributes: { location: 'Work', city: 'Orlando', street: '100 Lake Hart Drive', state: 'FL', country: 'United States' } } ] } } }, action: 'create' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } before do mock_empty_id_reference( from: ['addresses-id-abc123', 'addresses-id-def456'], resource: MockAddress ) end it 'correctly transforms the values' do expected_hash = { mock_contact: { name: '<NAME>', mock_addresses_attributes: [ { location: 'Home', city: 'Fremont', street: '123 Somewhere St', state: 'CA', country: 'United States', _client_id: 'addresses-id-abc123', overwrite: true }, { location: 'Work', city: 'Orlando', street: '100 Lake Hart Drive', state: 'FL', country: 'United States', _client_id: 'addresses-id-def456', overwrite: true } ] }, action: 'create' } expect(transformer.transform).to eq build_params_with(expected_hash) end end describe 'with nested > nested relationships' do let(:params) do params = { data: { type: 'mock_contacts', attributes: { name: '<NAME>' }, relationships: { mock_people: { data: [ { type: 'mock_people', attributes: { first_name: 'Steve', last_name: 'Rogers' }, relationships: { mock_email_addresses: { data: [ { type: 'mock_emails', attributes: { email: '<EMAIL>' } } ] } } } ] } } }, action: 'create' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } it 'correctly transforms the values' do expected_hash = { mock_contact: { name: '<NAME>', mock_people_attributes: [ { first_name: 'Steve', last_name: 'Rogers', overwrite: true, mock_email_addresses_attributes: [ { email: '<EMAIL>', overwrite: true } ] } ] }, action: 'create' } expect(transformer.transform).to eq build_params_with(expected_hash) end end end describe 'with includes and relationships' do let(:params) do params = { included: [ { type: 'mock_people', id: '10e9f7f5-b027-4e04-8192-b9b698ac0b18', attributes: { first_name: 'Mike' } }, { type: 'mock_comments', id: '91374910-ef15-11e6-8787-ef17a057947e', attributes: { body: 'I love Orange Soda' }, relationships: { mock_person: { data: { type: 'mock_people', id: '10e9f7f5-b027-4e04-8192-b9b698ac0b18' } } } } ], data: { type: 'mock_tasks', attributes: { activity_type: 'Appointment', start_at: '2017-02-09T22:17:28.854Z', subject: 'An appointment to talk about Orange Soda' }, relationships: { mock_account_list: { data: { type: 'mock_account_lists', id: '144b83e8-b7f6-48c8-9c0e-688785bf6164' } }, mock_comments: { data: [ { type: 'mock_comments', id: '91374910-ef15-11e6-8787-ef17a057947e' } ] } } }, action: 'create' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } before do mock_id_reference( from: '10e9f7f5-b027-4e04-8192-b9b698ac0b18', to: '10e9f7f5-b027-4e04-8192-b9b698ac0b18', resource: MockPerson ) mock_id_reference( from: '144b83e8-b7f6-48c8-9c0e-688785bf6164', to: '144b83e8-b7f6-48c8-9c0e-688785bf6164', resource: MockAccountList ) mock_id_reference( from: '91374910-ef15-11e6-8787-ef17a057947e', to: '91374910-ef15-11e6-8787-ef17a057947e', resource: MockComment ) end it 'correctly transforms the values' do expected_hash = { mock_task: { activity_type: 'Appointment', start_at: '2017-02-09T22:17:28.854Z', subject: 'An appointment to talk about Orange Soda', mock_account_list_id: '144b83e8-b7f6-48c8-9c0e-688785bf6164', mock_comments_attributes: [ { _client_id: '91374910-ef15-11e6-8787-ef17a057947e', body: 'I love Orange Soda', mock_person_id: '10e9f7f5-b027-4e04-8192-b9b698ac0b18', overwrite: true } ] }, action: 'create' } expect(transformer.transform).to eq build_params_with(expected_hash) end end describe 'Transforming when the ID is "undefined"' do let(:params) do params = { data: { type: 'mock_tasks', id: 'undefined', attributes: { activity_type: 'Appointment' } }, action: 'create' } build_params_with(params) end let(:transformer) { build_transformer(params: params) } it "doesn't return #id in the hash" do expected_hash = { mock_task: { activity_type: 'Appointment' }, action: 'create' } expect(transformer.transform).to eq build_params_with(expected_hash) end end def build_transformer(params:, configuration: Configuration.new) Transformer.new(params: params, configuration: configuration) end end end
chuckmersereau/api_practice
app/models/appeal.rb
<filename>app/models/appeal.rb class Appeal < ApplicationRecord include Filtering include Filtering::Contacts audited associated_with: :account_list, except: [:updated_at] attr_accessor :inclusion_filter, :exclusion_filter belongs_to :account_list has_one :mail_chimp_account, through: :account_list has_many :appeal_contacts, dependent: :delete_all has_many :contacts, through: :appeal_contacts, source: :contact has_many :excluded_appeal_contacts, dependent: :delete_all has_many :excluded_contacts, through: :excluded_appeal_contacts, source: :contact has_many :donations, dependent: :nullify has_many :pledges, dependent: :delete_all validates :name, :account_list_id, presence: true after_create :create_contact_associations default_scope { order(created_at: :desc) } scope :that_belong_to, -> (user) { where(account_list_id: user.account_list_ids) } PERMITTED_ATTRIBUTES = [:account_list_id, :amount, :description, :end_date, :exclusion_filter, :inclusion_filter, :name, :overwrite, :created_at, :updated_at, :updated_in_db_at, :id].freeze def self.filter(filter_params) chain = where(filter_params.except(:wildcard_search)) return chain unless filter_params.key?(:wildcard_search) chain.where('LOWER("appeals"."name") LIKE :name', name: "%#{filter_params[:wildcard_search].downcase}%") end def bulk_add_contacts(contacts: [], contact_ids: contacts.map(&:id)) contact_ids_to_add = contact_ids.uniq - self.contact_ids appeal_contacts_to_import = contact_ids_to_add.map do |contact_id| AppealContact.new(contact_id: contact_id, appeal: self) end AppealContact.import(appeal_contacts_to_import) end def donated?(contact) donations.joins(donor_account: :contact_donor_accounts).exists?(contact_donor_accounts: { contact_id: contact.id }) end def pledges_amount_total ConvertedTotal.new( pledges.joins(:contact).pluck('pledges.amount, contacts.pledge_currency, pledges.created_at'), account_list.salary_currency_or_default ).total end def pledges_amount_not_received_not_processed ConvertedTotal.new( pledges_by_status(:not_received), account_list.salary_currency_or_default ).total end def pledges_amount_received_not_processed ConvertedTotal.new( pledges_by_status(:received_not_processed), account_list.salary_currency_or_default ).total end def pledges_amount_processed ConvertedTotal.new( donations_from_pledges, account_list.salary_currency_or_default ).total end protected def donations_from_pledges donations.reorder(:created_at) .joins(:pledges) .where(pledges: { status: 'processed' }) .pluck(:appeal_amount, :amount, :currency, :donation_date) .map do |donation| [donation[0]&.positive? ? donation[0] : donation[1], donation[2], donation[3]] end end def pledges_by_status(status) pledges.where(status: status).joins(:contact).pluck('pledges.amount, contacts.pledge_currency, pledges.created_at') end def create_contact_associations create_excluded_appeal_contacts_from_filter create_appeal_contacts_from_filter end def create_excluded_appeal_contacts_from_filter return unless exclusion_filter exclusions = {} exclusion_filter.each do |key, value| excluded_contacts_from_filter(key => value).pluck(:id).each do |id| exclusions[id] ||= [] exclusions[id].append(key) end end bulk_add_excluded_appeal_contacts(exclusions) end def bulk_add_excluded_appeal_contacts(exclusions) excluded_appeal_contacts_to_import = [] exclusions.each do |id, reasons| excluded_appeal_contacts_to_import << excluded_appeal_contacts.build(contact_id: id, reasons: reasons) end Appeal::ExcludedAppealContact.import(excluded_appeal_contacts_to_import) end def create_appeal_contacts_from_filter bulk_add_contacts( contact_ids: contacts_from_filter.where.not(id: excluded_appeal_contacts.select(:contact_id)).pluck(:id) ) end def contacts_from_filter(filter = inclusion_filter) params = filter_params(filter) return Contact.none if params.empty? Contact::Filterer.new(params).filter( scope: Contact.where(account_list: account_list), account_lists: [account_list] ) end def excluded_contacts_from_filter(filter = exclusion_filter) params = filter_params(filter) return Contact.none if params.empty? Contact::Filterer.new(params).filter( scope: contacts_from_filter, account_lists: [account_list] ) end end
chuckmersereau/api_practice
db/migrate/20120326194920_add_designation_profile_id_to_account_list.rb
<gh_stars>0 class AddDesignationProfileIdToAccountList < ActiveRecord::Migration def change add_column :account_lists, :designation_profile_id, :integer add_index :account_lists, [:designation_profile_id], :unique => true add_column :designation_accounts, :name, :string end end
chuckmersereau/api_practice
app/services/user/authenticate.rb
<reponame>chuckmersereau/api_practice<filename>app/services/user/authenticate.rb class User::Authenticate < ActiveModelSerializers::Model attr_accessor :user def initialize(attributes = {}) super end def json_web_token @json_web_token ||= ::JsonWebToken.encode( user_id: user.id, exp: 30.days.from_now.utc.to_i ) end end
chuckmersereau/api_practice
spec/services/task/filter/contact_status_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/services/task/filter/contact_status_spec.rb<gh_stars>0 require 'rails_helper' RSpec.describe Task::Filter::ContactStatus do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } let!(:active_contact) { create(:contact, account_list: account_list, status: 'Ask in Future') } let!(:inactive_contact) { create(:contact, account_list: account_list, status: 'Not Interested') } let!(:contact_with_no_status) { create(:contact, account_list: account_list, status: nil) } let!(:task_one) { create(:task, account_list: account_list, contacts: [active_contact]) } let!(:task_two) { create(:task, account_list: account_list, contacts: [inactive_contact]) } let!(:task_three) { create(:task, account_list: account_list, contacts: [contact_with_no_status]) } describe '#query' do let(:tasks) { account_list.tasks } context 'for single status' do it 'returns the correct tasks for corresponding contact status filter' do expect(described_class.query(tasks, { contact_status: 'active' }, account_list).to_a).to( contain_exactly(task_one, task_three) ) expect(described_class.query(tasks, { contact_status: 'hidden' }, account_list).to_a).to( contain_exactly(task_two) ) expect(described_class.query(tasks, { contact_status: 'null' }, account_list).to_a).to( contain_exactly(task_three) ) expect(described_class.query(tasks, { contact_status: 'null' }, account_list).to_a).not_to( contain_exactly(task_one, task_two, task_three) ) end end context 'for multiple statuses' do it 'returns the correct contacts' do expect(described_class.query(tasks, { contact_status: 'active, hidden' }, account_list).to_a).to( contain_exactly(task_one, task_two, task_three) ) expect(described_class.query(tasks, { contact_status: 'hidden, null' }, account_list).to_a).to( contain_exactly(task_two, task_three) ) expect(described_class.query(tasks, { contact_status: 'null, hidden' }, account_list).to_a).not_to( contain_exactly(task_one, task_two, task_three) ) end end context 'with reverse_FILTER' do subject { described_class.query(tasks, query, account_list) } let(:query) { { contact_status: contact_status, reverse_contact_status: true } } context 'contact_status: "active"' do let(:contact_status) { 'active' } it('returns tasks owned by hidden contacts') { is_expected.to match_array([task_two]) } end context 'contact_status: "null"' do let(:contact_status) { 'null' } it('returns tasks owned by hidden contacts') { is_expected.to match_array([task_two]) } end context 'contact_status: "hidden"' do let(:contact_status) { 'hidden' } it('returnstasks owned by null/blank contacts') { is_expected.to match_array([task_three]) } end end end end
chuckmersereau/api_practice
app/models/person/organization_account.rb
require_dependency 'data_server' require_dependency 'credential_validator' require 'async' class Person::OrganizationAccount < ApplicationRecord class MissingCredentialsError < StandardError; end class InvalidCredentialsError < StandardError; end include Person::Account include Async include Sidekiq::Worker audited associated_with: :person, except: [:password, :locked_at] sidekiq_options queue: :api_person_organization_account, retry: false, unique: :until_executed delegate :requires_credentials?, to: :organization, allow_nil: true serialize :password, Encryptor.new after_create :set_up_account_list, :queue_import_data validates :organization_id, :person_id, presence: true validates_with CredentialValidator, if: :requires_credentials? after_validation :set_valid_credentials after_destroy :destroy_designation_profiles belongs_to :organization PERMITTED_ATTRIBUTES = [:created_at, :organization_id, :overwrite, :password, :person_id, :updated_at, :updated_in_db_at, :username, :id].freeze def self.find_or_create_from_auth(token, oauth_url, user) organization = Organization.find_by!(oauth_url: oauth_url) organization_account = user.organization_accounts.find_or_initialize_by(organization: organization) organization_account.token = token organization_account.save! organization_account end def to_s str = organization.to_s employee_id = user.key_accounts.where(remote_id: remote_id).pluck(:employee_id).first postfix = username || employee_id || remote_id str += ': ' + postfix if postfix str end def user @user ||= person.to_user end def self.one_per_user? false end def self.clear_stalled_downloads where('locked_at is not null and locked_at < ?', 2.days.ago).update_all(downloading: false, locked_at: nil) end def queue_import_data async(:import_all_data) end def account_list user.designation_profiles.first.try(:account_list) end def designation_profiles DesignationProfile.where(organization_id: organization_id, user_id: person_id) end def import_all_data return if locked_at || new_record? || !valid_rechecked_credentials update_columns(downloading: true, last_download_attempt_at: Time.current) import_donations rescue InvalidCredentialsError, MissingCredentialsError update_column(:valid_credentials, false) ImportMailer.delay.credentials_error(self) ensure clear_lock_fields end def import_profiles organization.api(self).import_profiles rescue DataServerError => e Rollbar.error(e) end private def valid_rechecked_credentials # Trigger validation to check if the credentials are actually valid in case # they were previously incorrectly indicated by a data server as invalid. valid_credentials || valid? end def import_donations starting_time = Time.current starting_donation_count = user.donations.count import_donations_from_api # The last_download date is the date of the last donation that was imported. # We only want to set the last_download date if at least one donation was downloaded. return unless user.donations.count > starting_donation_count process_new_donations_downloaded(import_started_at: starting_time) end def import_donations_from_api update(downloading: true, locked_at: Time.now) date_from = last_download ? (last_download - 50.days) : '' organization.api(self).import_all(date_from) end def process_new_donations_downloaded(import_started_at:) ContactSuggestedChangesUpdaterWorker.perform_async(user.id, import_started_at) # Set the last download date to whenever the last donation was received last_donation_date = user.donations .where.not(remote_id: nil).order('donation_date desc').first.donation_date update_column(:last_download, last_donation_date) end def clear_lock_fields update_columns(downloading: false, locked_at: nil) rescue ActiveRecord::ActiveRecordError end def set_valid_credentials self.valid_credentials = true end # The purpose of this method is to transparently share one account list between two spouses. # In general any time two people have access to a designation profile containing only one # designation account, the second person will be given access to the first person's account list def set_up_account_list import_profiles # If this org account doesn't have any profiles, create a default account list and profile for them if user.account_lists.reload.empty? || organization.designation_profiles.where(user_id: person_id).blank? account_list = user.account_lists.create!(name: user.to_s, creator_id: user.id) organization.designation_profiles.create!(name: user.to_s, user_id: user.id, account_list_id: account_list.id) end end def destroy_designation_profiles designation_profiles.destroy_all end end
chuckmersereau/api_practice
db/migrate/20120209221107_add_email_to_person_google_account.rb
class AddEmailToPersonGoogleAccount < ActiveRecord::Migration def change add_column :person_google_accounts, :email, :string, null: false end end
chuckmersereau/api_practice
app/services/task/filter/contact_state.rb
class Task::Filter::ContactState < Task::Filter::Base def execute_query(tasks, filters) filters = clean_contact_filter(filters) # We are plucking ids here because the contact filter already generates an sql statement with several nested subqueries # and sending too many of those to postgres can cause unexpected errors and is often slower than breaking things up. # Do not change this unless you test the results before pushing to production. tasks.joins(:contacts) .where(contacts: { id: Contact::Filter::State.query(contact_scope(tasks), filters, account_lists).ids }) end delegate :custom_options, :parent, :type, :title, to: 'Contact::Filter::State.new(account_lists)' end
chuckmersereau/api_practice
db/migrate/20161128055225_add_late_at_to_contacts.rb
class AddLateAtToContacts < ActiveRecord::Migration class Contact < ActiveRecord::Base before_save :update_late_at scope :financial_partners, -> { where(status: 'Partner - Financial') } def update_late_at initial_date = last_donation_date || pledge_start_date return unless status == 'Partner - Financial' && pledge_frequency.present? && initial_date.present? self.late_at = case when pledge_frequency >= 1.0 initial_date + pledge_frequency.to_i.months when pledge_frequency >= 0.4 initial_date + 2.weeks else initial_date + 1.week end end end def up add_column :contacts, :late_at, :date Contact.financial_partners.map(&:save) end def down remove_column :contacts, :late_at end end
chuckmersereau/api_practice
config/initializers/geocoder.rb
<reponame>chuckmersereau/api_practice<filename>config/initializers/geocoder.rb Geocoder.configure( timeout: 2, lookup: :google_premier, google_premier: { use_https: true, api_key: [ ENV.fetch('GOOGLE_GEOCODER_KEY'), ENV.fetch('GOOGLE_GEOCODER_CLIENT'), ENV.fetch('GOOGLE_GEOCODER_CHANNEL') ] } )
chuckmersereau/api_practice
dev/util/http_logger_util.rb
<reponame>chuckmersereau/api_practice def enable_http_logger # This will work in a prod_console even though the http_logger gem is in # the development group. require 'http_logger' HttpLogger.log_headers = true HttpLogger.logger = Logger.new(STDOUT) HttpLogger.collapse_body_limit = 10_000 HttpLogger.ignore = [/newrelic\.com/] end
chuckmersereau/api_practice
app/policies/application_policy.rb
class ApplicationPolicy attr_reader :resource, :user, :coach def initialize(context, resource) @resource = resource @user = context.is_a?(User) ? context : context.user @coach = @user.becomes(User::Coach) end def show? resource_owner? end def create? resource_owner? end def update? resource_owner? end def destroy? resource_owner? end protected def resource_owner? raise 'Must Override' end def resource_coach? raise 'Must Override' end end
chuckmersereau/api_practice
spec/services/contact/filter/no_appeals_spec.rb
require 'rails_helper' RSpec.describe Contact::Filter::NoAppeals do let(:user) { create(:user_with_account) } let(:account_list) { user.account_lists.order(:created_at).first } describe '#query' do let!(:first_contact) { create(:contact, account_list: account_list, no_appeals: true) } let!(:second_contact) { create(:contact, account_list: account_list, no_appeals: nil) } let(:contacts) { Contact.all } context 'contacts that are marked as no_appeal' do it 'returns the correct contacts' do expect(described_class.query(contacts, { no_appeals: 'true' }, [account_list])).to eq([first_contact]) end end context 'integrated with Contact::Filterer' do it 'returns the correct contacts' do contacts = Contact::Filterer.new(no_appeals: true) .filter(scope: account_list.contacts, account_lists: [account_list]) expect(contacts).to eq [first_contact] end end end end
chuckmersereau/api_practice
db/migrate/20170925223827_add_status_confirmed_at_to_contacts.rb
class AddStatusConfirmedAtToContacts < ActiveRecord::Migration def change add_column :contacts, :status_confirmed_at, :datetime end end
chuckmersereau/api_practice
spec/acceptance/api/v2/user/key_accounts_spec.rb
require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'User > Key Accounts' do include_context :json_headers documentation_scope = :user_api_key_accounts let!(:user) { create(:user_with_full_account) } let(:resource_type) { 'key_accounts' } let!(:key_account) { create(:key_account, person: user) } let(:id) { key_account.id } let(:new_key_account_params) do attributes_for(:key_account) .merge(updated_in_db_at: key_account.updated_at) .select { |(key, _)| Person::KeyAccount::PERMITTED_ATTRIBUTES.include?(key.to_sym) } .tap { |attrs| attrs.delete(:person_id) } end let(:form_data) { build_data(new_key_account_params, relationships: relationships) } let(:relationships) do { person: { data: { type: 'persons', id: user.id } } } end let(:resource_attributes) do %w( created_at email first_name last_download last_name primary remote_id updated_at updated_in_db_at ) end context 'authorized user' do before { api_login(user) } get '/api/v2/user/key_accounts' do example 'Key Account [LIST]', document: documentation_scope do do_request explanation 'List of Key Accounts associated to current_user' check_collection_resource(2) expect(response_status).to eq 200 end end get '/api/v2/user/key_accounts/:id' do with_options scope: [:data, :attributes] do response_field 'created_at', 'Created At', type: 'String' response_field 'email', 'Email', type: 'String' response_field 'first_name', 'First Name', type: 'String' response_field 'last_download', 'Last Download', type: 'String' response_field 'last_name', '<NAME>', type: 'String' response_field 'primary', 'Primary', type: 'Boolean' response_field 'remote_id', 'Remote 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 'Key Account [GET]', document: documentation_scope do explanation 'The current_user\'s Key Account with the given ID' do_request check_resource expect(response_status).to eq 200 end end post '/api/v2/user/key_accounts' do with_options scope: [:data, :attributes] do parameter 'email', 'Email', required: true parameter 'first_name', '<NAME>' parameter 'last_name', '<NAME>' parameter 'person_id', 'Person Id', required: true parameter 'remote_id', 'Remote Id', required: true end example 'Key Account [CREATE]', document: documentation_scope do explanation 'Create a Key Account associated with the current_user' do_request data: form_data expect(resource_object['email']).to eq new_key_account_params[:email] expect(response_status).to eq 201 end end put '/api/v2/user/key_accounts/:id' do with_options scope: [:data, :attributes] do parameter 'email', 'Email', required: true parameter 'first_name', '<NAME>' parameter 'last_name', '<NAME>' parameter 'person_id', 'Person Id', required: true parameter 'remote_id', 'Remote Id', required: true end example 'Key Account [UPDATE]', document: documentation_scope do explanation 'Update the current_user\'s Key Account with the given ID' do_request data: form_data expect(resource_object['email']).to eq new_key_account_params[:email] expect(response_status).to eq 200 end end delete '/api/v2/user/key_accounts/:id' do example 'Key Account [DELETE]', document: documentation_scope do explanation 'Delete the current_user\'s Key Account with the given ID' do_request expect(response_status).to eq(204), invalid_status_detail end end end end
chuckmersereau/api_practice
spec/services/user_from_cas_service_spec.rb
<reponame>chuckmersereau/api_practice require 'rails_helper' RSpec.describe UserFromCasService, type: :service do before do stub_cas_requests stub_siebel create_cru_organization end let(:validator) { build_validator_service } let(:service) { UserFromCasService.new(validator.attributes) } describe '#initialize' do it 'initializes with attributes from the CasTicketValidatorService' do expect(service.cas_attributes).to eq validator.attributes end end describe '#guids' do it 'returns the ssoGuid' do expected_guids = ['B163530-7372-551R-KO83-1FR05534129F'] expect(service.guids).to match expected_guids end end describe '#omniauth_attributes_hash' do it 'returns cas_attributes in the same format omniauth would return them' do expected_attributes = { provider: 'key', uid: '<EMAIL>', extra: { user: '<EMAIL>', attributes: [ { ssoGuid: 'B163530-7372-551R-KO83-1FR05534129F', firstName: 'Cas', lastName: 'User', theKeyGuid: 'B163530-7372-551R-KO83-1FR05534129F', relayGuid: 'B163530-7372-551R-KO83-1FR05534129F', email: '<EMAIL>' } ] } } expect(service.omniauth_attributes_hash) .to eq Hashie::Mash.new(expected_attributes) end end describe '#find_or_create' do context 'When a User with the GUID already exists' do let!(:user) do create(:user_with_account).tap do |user| key_account = user.key_accounts.first key_account.update(remote_id: service.guids.first, authenticated: true) end end it 'returns the User' do expect(service.find_or_create).to eq user end end context "When a User with the GUID DOESN'T exist" do let(:user) { double('user') } before do allow(Person::KeyAccount) .to receive(:create_user_from_auth) .with(service.omniauth_attributes_hash) .and_return(user) expect(Person::KeyAccount) .to receive(:find_or_create_from_auth) .with(service.omniauth_attributes_hash, user) end it 'delegates to the KeyAccount to make the user' do expect(service.find_or_create).to eq user end end context "When a user can't be found or created" do before do allow(User) .to receive(:find_by_guid) .and_return(nil) allow(Person::KeyAccount) .to receive(:create_user_from_auth) .with(service.omniauth_attributes_hash) .and_return(nil) end it 'raises an error' do expect { service.find_or_create } .to raise_error(UserFromCasService::MissingUserError) end end end private def build_validator_service CasTicketValidatorService.new(ticket: mock_ticket, service: mock_service) end def create_cru_organization create(:ccc) end def mock_service 'http://my.service' end def mock_ticket 'ST-314971-9fjrd0HfOINCehJ5TKXX-cas2a' end def stub_siebel allow(SiebelDonations::Profile) .to receive(:find) .and_return(nil) end def stub_cas_requests url = "#{ENV['CAS_BASE_URL']}/p3/serviceValidate?service=#{mock_service}&ticket=#{mock_ticket}" data_filepath = Rails.root.join('spec', 'fixtures', 'cas', 'successful_ticket_validation_response_body.xml') response_body = File.read(data_filepath) stub_request(:get, url).to_return(status: 200, body: response_body) end end
chuckmersereau/api_practice
app/serializers/error_serializer.rb
<gh_stars>0 class ErrorSerializer extend ActiveModel::Translation attr_reader :detail, :hash, :resource, :status, :title def initialize(detail: nil, hash: nil, resource: nil, status: nil, title: nil) @detail = detail @hash = hash @resource = resource @status = status @title = title after_initialize end def as_json(*args) @as_json ||= { errors: errors_data }.as_json(*args) end private def add_conflict_info_to_metadata(metadata, key, _error) metadata[:updated_in_db_at] = resource.updated_at&.utc&.iso8601 if key == :updated_in_db_at && resource.present? end def after_initialize unless status.present? raise ArgumentError, 'must provide a status for the title response' end raise ArgumentError, error_data_validation_message unless resource.present? || title.present? || hash.present? end def error_data_validation_message 'must provide at least an error title, resource instance, or hash of errors' end def errors_data @errors_data ||= formatted_hash_errors || formatted_resource_errors || formatted_title_error end def format_active_model_errors_object(errors_object) full_messages = errors_object.full_messages errors_object.map.with_index do |(key, error), index| full_message = full_messages[index] { status: status, source: { pointer: "/data/attributes/#{key}" }, title: error, detail: full_message }.merge(generate_metadata(key, error)) end end def formatted_hash_errors return unless hash.present? && hash.keys.any? mock_resource = OpenStruct.new(errors: ActiveModel::Errors.new(self)) hash.each do |key, value| mock_resource.errors.add(key, value) end format_active_model_errors_object(mock_resource.errors) end def formatted_resource_errors return unless resource&.errors.present? format_active_model_errors_object(resource.errors) end def formatted_title_error return unless title detail_hash = detail.present? ? { detail: detail.to_s } : {} [ { status: status, title: title }.merge!(detail_hash) ] end def generate_metadata(key, error) metadata = {} add_conflict_info_to_metadata(metadata, key, error) if metadata.any? { meta: metadata } else {} end end end
chuckmersereau/api_practice
app/serializers/reports/donor_currency_donations_serializer.rb
<filename>app/serializers/reports/donor_currency_donations_serializer.rb class Reports::DonorCurrencyDonationsSerializer < ServiceSerializer delegate :account_list, :donor_infos, :months, :currency_groups, to: :object delegate :salary_currency, to: :account_list belongs_to :account_list attributes :donor_infos, :months, :currency_groups, :salary_currency end
chuckmersereau/api_practice
spec/models/person_spec.rb
<filename>spec/models/person_spec.rb<gh_stars>0 require 'rails_helper' describe Person do let(:person) { create(:person) } describe 'creating a person' do it 'should set master_person_id' do person = Person.create!(build(:person, master_person: nil).attributes.slice('first_name')) expect(person.master_person_id).not_to be_nil end end describe 'saving family relationships' do it 'should create a family relationship' do family_relationship = build(:family_relationship, person: nil, related_person: create(:person)) family_relationship_attributes = family_relationship.attributes .with_indifferent_access .except(:id, :person_id, :created_at, :updated_at) expect do person.family_relationships_attributes = { '0' => family_relationship_attributes } end.to change(FamilyRelationship, :count).by(1) end it 'should destroy a family relationship' do family_relationship = create(:family_relationship, person: person, related_person: create(:person)) expect do family_relationship_attributes = family_relationship.attributes.merge(_destroy: '1').with_indifferent_access person.family_relationships_attributes = { '0' => family_relationship_attributes } end.to change(FamilyRelationship, :count).from(1).to(0) end it 'should update a family relationship' do family_relationship = create(:family_relationship, person: person) family_relationship_attributes = family_relationship .attributes .merge!(relationship: family_relationship.relationship + 'boo') .with_indifferent_access .except(:person_id, :updated_at, :created_at) person.family_relationships_attributes = { '0' => family_relationship_attributes } expect(person.family_relationships.first.relationship).to eq(family_relationship.relationship + 'boo') end end describe '.save' do it 'gracefully handles having the same FB account assigned twice by id' do fb_account = create(:facebook_account, person: person) person.update_attributes('facebook_accounts_attributes' => { '0' => { '_destroy' => 'false', 'username' => 'random_username' }, '1' => { '_destroy' => 'false', 'url' => 'http://facebook.com/profile.php?id=500015648' }, '1354203866590' => { '_destroy' => 'false', 'id' => fb_account.id, 'url' => fb_account.url } }) expect(person.facebook_accounts.length).to eq(2) end it 'gracefully handles having the same FB account assigned twice a hash of usernames' do fb_account = create(:facebook_account, person: person) attributes = { facebook_accounts_attributes: { '0' => { '_destroy' => 'false', 'username' => 'same_username' }, '1' => { '_destroy' => 'false', 'username' => 'same_username' }, '1354203866590' => { '_destroy' => 'false', 'id' => fb_account.id, 'url' => fb_account.url } } } person.update(attributes) expect(person.reload.facebook_accounts.length).to eq(2) end it 'gracefully handles having the same FB account assigned twice an array of usernames' do fb_account = create(:facebook_account, person: person) attributes = { facebook_accounts_attributes: [ { '_destroy' => 'false', 'username' => 'same_username' }, { '_destroy' => 'false', 'username' => 'same_username' }, { '_destroy' => 'false', 'id' => fb_account.id, 'url' => fb_account.url } ] } person.update(attributes) expect(person.reload.facebook_accounts.length).to eq(2) end it 'gracefully handles having an fb account with a blank username' do person.update_attributes('facebook_accounts_attributes' => { '0' => { '_destroy' => 'false', 'username' => '' } }) expect(person.facebook_accounts.length).to eq(0) end describe 'saving deceased person' do it 'should remove persons name from greeting' do contact = create(:contact) person.first_name = 'Jack' contact.people << person contact.people << create(:person, first_name: 'Jill') contact.name = '<NAME> and Jill' contact.save! person.reload person.deceased = true person.save! contact.reload expect(contact.name).to_not include('Jack') end it "keeps a single deceased person's greeting and name" do contact = create(:contact) person.first_name = 'Jack' person.last_name = 'Smith' contact.people << person contact.name = '<NAME>' contact.save person.reload person.deceased = true person.save! contact.reload expect(contact.name).to eq('<NAME>') expect(contact.greeting).to eq('Jack') end it 'has no stack overflow if deceased person modified, and keeps single deceased person in greeting, etc.' do contact = create(:contact) person.first_name = 'Jack' contact.people << person contact.name = '<NAME>' contact.save! person.reload person.deceased = true person.save! contact.reload expect(contact.name).to eq('<NAME>') expect(contact.greeting).to eq('Jack') expect(contact.primary_person).to eq(person) person.reload person.occupation = 'random change' person.save # Used to cause a stack overflow end it 'has no stack overflow if person in deceased couple is modified' do person.first_name = 'Jack' person.last_name = 'Smith' person.deceased = true person.save! contact = create(:contact) contact.people << person contact.people << create(:person, deceased: true, first_name: 'Jill', last_name: 'Smith') contact.name = 'Smith, Jack and Jill' contact.save contact.update_column(:greeting, '') person.reload person.occupation = 'random change' contact.save # Used to cause a stack overflow end end context 'when all people of the contact are deceased' do let!(:contact) { create(:contact, name: '<NAME>', status: 'Not Interested', no_appeals: false, send_newsletter: 'Email') } before do contact.people << person contact.save person.update(deceased: true, first_name: 'Jack', last_name: 'Smith') contact.reload end it 'should set the partner status to Never Ask' do expect(contact.status).to eq 'Never Ask' end it 'should set the no appeals to true' do expect(contact.no_appeals).to be true end it 'should set the send newsletter to none' do expect(contact.send_newsletter).to eq 'None' end end context 'when only some people of a contact are deceased' do let!(:contact) { create(:contact, name: '<NAME>', status: 'Not Interested', no_appeals: false, send_newsletter: 'Email') } let!(:bob) { create(:person) } before do contact.people << bob contact.people << person contact.save person.update(deceased: true, first_name: 'Jack', last_name: 'Smith') contact.reload end it 'should not set the partner status to Never Ask' do expect(contact.status).to eq 'Not Interested' end it 'should not set the no appeals to true' do expect(contact.no_appeals).to be false end it 'should not set the send newsletter to none' do expect(contact.send_newsletter).to eq 'Email' end end end context '#email=' do let(:email) { '<EMAIL>' } it 'creates an email' do expect do person.email = email expect(person.email_addresses.first.email).to eq(email) end.to change(EmailAddress, :count).from(0).to(1) end end context '#email_address=' do it "doesn't barf when someone puts in the same email address twice" do person = build(:person) email_addresses_attributes = { '1378494030167' => { '_destroy' => 'false', 'email' => '<EMAIL>', 'primary' => '0' }, '1378494031857' => { '_destroy' => 'false', 'email' => '<EMAIL>', 'primary' => '0' } } person.email_addresses_attributes = email_addresses_attributes person.save end end context '#email_addresses_attributes=' do let(:person) { create(:person) } let(:email) { create(:email_address, person: person) } it 'deletes nested email address' do email_addresses_attributes = { '0' => { '_destroy' => '1', 'email' => '<EMAIL>', 'primary' => '0', 'id' => email.id.to_s } } expect do person.email_addresses_attributes = email_addresses_attributes person.save end.to change(person.email_addresses, :count).by(-1) end it 'updates an existing email address' do email_addresses_attributes = { '0' => { '_destroy' => '0', 'email' => 'asdf' + email.email, 'primary' => '1', 'id' => email.id.to_s } } expect do person.email_addresses_attributes = email_addresses_attributes person.save end.to_not change(person.email_addresses, :count) end it "doesn't create a duplicate if updating to an address that already exists" do email2 = create(:email_address) person.email_addresses << email2 email_addresses_attributes = { '0' => { '_destroy' => '0', 'email' => email.email, 'primary' => '0', 'id' => email2.id.to_s } } expect do person.email_addresses_attributes = email_addresses_attributes person.save end.to change(person.email_addresses, :count).by(-1) end end context '#merge' do let(:winner) { create(:person) } let(:loser) { create(:person) } it "shouldn't fail if the winner has the same facebook account as the loser" do fb_account = create(:facebook_account, person: winner) create(:facebook_account, person: loser, remote_id: fb_account.remote_id) # this shouldn't blow up expect do winner.merge(loser) end.to change(Person::FacebookAccount, :count) end it "should move loser's facebook over" do loser = create(:person) fb = create(:facebook_account, person: loser) winner.merge(loser) expect(winner.facebook_accounts).to eq([fb]) end it "should move loser's twitter over" do loser = create(:person) create(:twitter_account, person: loser) winner.merge(loser) expect(winner.twitter_accounts).not_to be_empty end it 'moves pictures over' do picture = create(:picture, picture_of: loser) winner.merge(loser) expect(winner.pictures).to include(picture) end it 'copies over master person sources' do loser.master_person.master_person_sources.create(organization_id: 1, remote_id: 2) expect do winner.merge(loser) end.to change(winner.master_person.master_person_sources, :count).from(0).to(1) end it 'merges the master people of unrelated people so master person source stays unique per org' do loser.master_person.master_person_sources.create(organization_id: 1, remote_id: 2) loser_master_person_id = loser.master_person.id other_person_loser_master = create(:person, master_person: loser.master_person) expect { winner.merge(loser) }.to_not raise_error expect(other_person_loser_master.reload.master_person).to eq(winner.master_person) expect(MasterPerson.find_by(id: loser_master_person_id)).to be_nil end it 'merges two people correctly if they have the same master person' do loser.update(master_person: winner.master_person) expect(loser.master_person).to_not be_nil orig_winner_master_person_id = winner.master_person_id expect { winner.merge(loser) }.to_not raise_error expect(winner.master_person_id).to eq(orig_winner_master_person_id) expect(winner.master_person).to_not be_nil end it 'deletes a DuplicateRecordPair if it exists' do winner.contacts << create(:contact) loser.contacts << winner.contacts.first expect(winner.account_lists).to eq(loser.account_lists) dup_pair_id = DuplicateRecordPair.create!(account_list: winner.account_lists.order(:created_at).first, record_one: winner, record_two: loser, reason: 'Testing').id expect { winner.merge(loser) }.to change { DuplicateRecordPair.exists?(dup_pair_id) }.from(true).to(false) end it 'does not override primary email_address' do loser = create(:person_with_email) primary_email = winner.create_primary_email_address(email: '<EMAIL>') expect { winner.merge(loser) }.to_not change { winner.primary_email_address(true) }.from(primary_email) end end context '#anniversary_year' do it 'outputs a 4 digits year' do person.anniversary_year = 76 expect(person.anniversary_year).to eq(1976) person.anniversary_year = 3 expect(person.anniversary_year).to eq(2003) person.anniversary_year = 15 expect(person.anniversary_year).to eq(2015) person.anniversary_year = 1988 expect(person.anniversary_year).to eq(1988) end it 'returns a placeholder for a missing year' do person.anniversary_day = 1 person.anniversary_month = 1 person.anniversary_year = nil expect(person.anniversary_year).to eq(1900) end it 'does not return a placeholder year if day and month are also missing' do person.anniversary_day = nil person.anniversary_month = nil person.anniversary_year = nil expect(person.anniversary_year).to eq(nil) person.anniversary_day = 1 expect(person.anniversary_year).to eq(nil) person.anniversary_day = nil person.anniversary_month = 1 expect(person.anniversary_year).to eq(nil) end end context '#birthday_year' do it 'outputs a 4 digits year' do person.birthday_year = 76 expect(person.birthday_year).to eq(1976) person.birthday_year = 3 expect(person.birthday_year).to eq(2003) person.birthday_year = 15 expect(person.birthday_year).to eq(2015) person.birthday_year = 1988 expect(person.birthday_year).to eq(1988) end it 'returns a placeholder for a missing year' do person.birthday_day = 1 person.birthday_month = 1 person.birthday_year = nil expect(person.birthday_year).to eq(1900) end it 'does not return a placeholder year if day and month are also missing' do person.birthday_day = nil person.birthday_month = nil person.birthday_year = nil expect(person.birthday_year).to eq(nil) person.birthday_day = 1 expect(person.birthday_year).to eq(nil) person.birthday_day = nil person.birthday_month = 1 expect(person.birthday_year).to eq(nil) end end describe '#sync_with_mail_chimp_account' do let!(:person) { create(:person, primary_email_address: build(:email_address), optout_enewsletter: false) } it 'syncs the contact when a person optout_enewsletter changes' do expect(person).to receive(:trigger_mail_chimp_syncs_to_relevant_contacts) person.update(optout_enewsletter: true) end it 'does not sync the contact another field is changed' do expect(person).not_to receive(:trigger_mail_chimp_syncs_to_relevant_contacts) person.update(last_name: 'Boykin') end end describe 'title=' do context 'blank title' do it 'clears title' do expect { person.title = '' }.to change { person.title }.to('') expect { person.title = nil }.to change { person.title }.to(nil) end end context 'title with period' do it 'saves as-is' do expect { person.title = 'Ms.' }.to change { person.title }.to('Ms.') end end context 'title missing period' do it 'adds trailing period' do expect { person.title = 'Mr' }.to change { person.title }.to('Mr.') end end context 'title not matching pre-defined' do it 'saves as-is' do expect { person.title = 'Pastor' }.to change { person.title }.to('Pastor') end end end describe 'suffix=' do context 'blank suffix' do it 'clears suffix' do expect { person.suffix = '' }.to change { person.suffix }.to('') expect { person.suffix = nil }.to change { person.suffix }.to(nil) end end context 'suffix with period' do it 'saves as-is' do expect { person.suffix = 'Jr.' }.to change { person.suffix }.to('Jr.') end end context 'suffix missing period' do it 'adds trailing period' do expect { person.suffix = 'Sr' }.to change { person.suffix }.to('Sr.') end end context 'suffix not matching pre-defined' do it 'saves as-is' do expect { person.suffix = 'III' }.to change { person.suffix }.to('III') end end end describe 'profession=' do context 'blank occupation' do before { person.occupation = nil } it 'updates occupation field' do expect { person.profession = 'qwer' }.to change { person.occupation } end end context 'occupation is set' do before { person.occupation = 'asdf' } it 'does not update occupation field' do expect { person.profession = 'qwer' }.to_not change { person.occupation } end end end end
chuckmersereau/api_practice
app/policies/person_policy.rb
class PersonPolicy < ApplicationPolicy def initialize(context, resource) @user = context.user @contact_scope = context.respond_to?(:contact_scope) ? context.contact_scope : nil @contacts = resource.contacts @resource = resource end def create? # We trust that the created Person will be associated to a Contact in the contact_scope @contacts = @contact_scope contacts_belongs_to_user? end def bulk_create? contacts_belongs_to_user? end private def resource_owner? resource_is_user? || resource_belongs_to_user? end def resource_is_user? resource.id == user.id end def resource_belongs_to_user? contacts_belongs_to_user? && Person.exists?(id: resource.id) && ContactPerson.exists?(contact_id: @contacts.ids, person_id: resource.id) end def contacts_belongs_to_user? @contacts.present? && (contacts_account_list_ids & user.account_lists.ids == contacts_account_list_ids) end def contacts_account_list_ids @contacts_account_list_ids ||= @contacts.collect(&:account_list_id).uniq end end
chuckmersereau/api_practice
app/services/contact/filter/related_task_action.rb
class Contact::Filter::RelatedTaskAction < Contact::Filter::Base def execute_query(contacts, filters) related_task_action_filters = parse_list(filters[:related_task_action]) if includes_none?(related_task_action_filters) contacts_with_tasks = contacts.joins(:activities) .where('activities.completed' => false, 'activities.type' => Task.sti_name) .ids contacts.where('contacts.id not in (?)', contacts_with_tasks) else contacts.where('activities.activity_type' => related_task_action_filters) .where('activities.completed' => false) .joins(:activities) end end def title _('Action') end def parent _('Tasks') end def type 'multiselect' end def custom_options [{ name: _('-- None --'), id: 'none' }] + related_tasks.collect { |a| { name: _(a), id: a } } end private def includes_none?(filter_list) filter_list.include?('none') || filter_list.include?('null') end def related_tasks Task.new.assignable_activity_types & Task.where(account_list: account_lists).distinct.pluck(:activity_type) end end
chuckmersereau/api_practice
config/initializers/active_model_serializers.rb
ActiveModelSerializers.config.key_transform = :underscore ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonApi ActiveModelSerializers.config.jsonapi_pagination_links_enabled = false class ActiveModelSerializers::Adapter::JsonApi Relationship.class_eval do def data_for(association) serializer = association.serializer if serializer.respond_to?(:each) serializer.map { |s| ResourceIdentifier.new(s, serializable_resource_options).as_json } elsif (virtual_value = association.options[:virtual_value]) { id: virtual_value.id, type: virtual_value.class.to_s.underscore }.as_json elsif serializer && serializer.object ResourceIdentifier.new(serializer, serializable_resource_options).as_json end end end end
chuckmersereau/api_practice
spec/models/background_batch_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe BackgroundBatch, type: :model do subject { build :background_batch } describe '#create_batch' do it 'creates a sidekiq batch and stores the batch_id' do subject.save expect(subject.batch_id).to_not be_nil expect(subject.status).to be_a(Sidekiq::Batch::Status) end end describe '#create_workers' do it 'creates workers in batch' do requests_attributes = [] # background_batch factory already creates request requests_attributes.push(path: 'api/v2/user') requests_attributes.push(path: 'api/v2/constants') subject.requests_attributes = requests_attributes expect(BackgroundBatch::RequestWorker).to receive(:perform_async).exactly(3).times subject.save end end end
chuckmersereau/api_practice
app/models/notification_type/stopped_giving.rb
<reponame>chuckmersereau/api_practice<filename>app/models/notification_type/stopped_giving.rb class NotificationType::StoppedGiving < NotificationType def check(account_list) notifications = [] contact_scope = account_list.contacts .financial_partners .where('pledge_start_date is NULL OR pledge_start_date < ?', 30.days.ago) contact_scope.find_each do |contact| next unless contact.pledge_received? late = contact.late_by?(30.days) prior_notification = Notification.active.find_by(contact_id: contact.id, notification_type_id: id) if late unless prior_notification # If they've never given, they haven't missed a gift if contact.donations.first notification = contact.notifications.create!(notification_type_id: id, event_date: Date.today) notifications << notification end end elsif prior_notification # Clear a prior notification if there was one prior_notification.update_attributes(cleared: true) # Remove any tasks associated with this notification prior_notification.tasks.destroy_all end end notifications end def task_description_template(_notification = nil) _('%{contact_name} seems to have missed a gift. Call to follow up.') end protected def task_activity_type _('Call') end end
chuckmersereau/api_practice
spec/support/json_api_service_helper.rb
require 'action_controller' module JsonApiServiceHelpers def mock_id_reference(from:, to:, resource:) ids = Array[from].flatten ids = Array[to].flatten return_values = ids.map.with_index do |id, index| id = ids[index] [id, id] end return_collection = MockCollection.new(return_values) allow(resource) .to receive(:where) .with(id: ids) .and_return(return_collection) end def mock_empty_id_reference(from:, resource:) ids = Array[from].flatten return_collection = MockCollection.new([]) allow(resource) .to receive(:where) .with(id: ids) .and_return(return_collection) end def build_params_with(hash) ActionController::Parameters.new(hash) end end class MockCollection include Enumerable attr_reader :values def initialize(values) @values = values end def pluck(*) values end end class MockResource def self.where(_args); end def self.find(_args); end def self.find_by(_args); end def self.find_by!(_args); end end class MockAccountList < MockResource; end class MockComment < MockResource; end class MockAddress < MockResource; end class MockContact < MockResource; end class MockEmail < MockResource; end class MockPerson < MockResource; end class MockPerson::FacebookAccount < MockResource; end class MockTask < MockResource end
chuckmersereau/api_practice
app/services/csv_file_reader.rb
<reponame>chuckmersereau/api_practice require 'csv' class CsvFileReader def initialize(file_path) @file_path = file_path end def each_row csv_contents = File.read(@file_path) csv_contents = EncodingUtil.normalized_utf8(csv_contents) CSV.new(csv_contents, headers: true).each do |csv_row| next if csv_row.fields.compact.blank? # Skip this row if it's blank. yield(csv_row) end end end