repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
vicki29644/Super_hero_cli
|
lib/shc.rb
|
# application enviroment
require 'bundler/setup'
Bundler.require(:default)
require_relative './super_hero_cli/cli.rb'
require_relative './super_hero_cli/api.rb'
require_relative './super_hero_cli/shc.rb'
|
vicki29644/Super_hero_cli
|
lib/api.rb
|
class Api
def Api
puts "Api class loaded"
end
end
|
adamsanderson/cesspit_rails
|
lib/cesspit_rails.rb
|
require 'cesspit'
require 'cesspit_rails/asset_helpers'
module CesspitRails
end
|
adamsanderson/cesspit_rails
|
lib/cesspit_rails/asset_helpers.rb
|
<reponame>adamsanderson/cesspit_rails
module CesspitRails
module AssetHelpers
# Raised when an asset is not found.
class AssetNotFound < StandardError
attr_accessor :path
def initialize(path)
@path = path
super "Asset not found #{path.inspect}"
end
end
def add_asset(path)
asset = assets[path]
raise AssetNotFound, path unless asset
add_css(asset.to_s, path)
end
# Override the default read_html method.
def read_css(path)
add_asset(path)
rescue AssetNotFound => ex
super(path)
end
def assets
Rails.application.assets
end
end
end
Cesspit.send :prepend, CesspitRails::AssetHelpers
|
adamsanderson/cesspit_rails
|
test/dummy/app/controllers/demo_controller.rb
|
<filename>test/dummy/app/controllers/demo_controller.rb
class DemoController < ApplicationController
def show
@css_classes = params[:id]
end
end
|
adamsanderson/cesspit_rails
|
test/cesspit_rails_test.rb
|
require 'sass-rails'
require_relative './test_helper'
class CesspitRailsTest < ActiveSupport::TestCase
attr_accessor :cesspit
setup do
@cesspit = Cesspit.new
@cesspit.io = StringIO.new
end
test "adding assets" do
cesspit.add_asset "red.css"
assert_equal 1, cesspit.unmatched_selectors.length
assert_equal [".red"], cesspit.unmatched_selectors
end
test "adding processed assets" do
cesspit.add_asset "application.css"
assert_equal 2, cesspit.unmatched_selectors.length
assert_equal [".red", ".blue"], cesspit.unmatched_selectors
end
test "raises when asset is missing" do
assert_raises CesspitRails::AssetHelpers::AssetNotFound do
cesspit.add_asset "does_not_exist.css"
end
end
test "adding assets by path" do
cesspit.read_css "application.css"
assert_equal 2, cesspit.unmatched_selectors.length
assert_equal [".red", ".blue"], cesspit.unmatched_selectors
end
test "adding files by path" do
# Verify that we can still load without going through sprockets
cesspit.read_css(Rails.root + "app/assets/stylesheets/red.css")
assert_equal 1, cesspit.unmatched_selectors.length
assert_equal [".red"], cesspit.unmatched_selectors
end
end
|
adamsanderson/cesspit_rails
|
test/dummy/config/routes.rb
|
Rails.application.routes.draw do
get 'demo/:id' => 'demo#show'
end
|
moneroist/jekyll-paginate-v2
|
lib/jekyll-paginate-v2/autopages/autoPages.rb
|
<reponame>moneroist/jekyll-paginate-v2<filename>lib/jekyll-paginate-v2/autopages/autoPages.rb
module Jekyll
module PaginateV2::AutoPages
#
# This function is called right after the main generator is triggered by Jekyll
# This code is adapted from <NAME>'s code https://github.com/stevecrozz
def self.create_autopages(site)
# Get the configuration for the auto pages
autopage_config = Jekyll::Utils.deep_merge_hashes(DEFAULT, site.config['autopages'] || {})
pagination_config = Jekyll::Utils.deep_merge_hashes(Jekyll::PaginateV2::Generator::DEFAULT, site.config['pagination'] || {})
autolog_resources = []
['tags', 'collections', 'categories'].each do |resource|
unless site.config.dig('autopages', resource)
autopage_config.delete(resource)
else
autolog_resources << resource
end
end
# If disabled then don't do anything
if !autopage_config['enabled'] || autopage_config['enabled'].nil?
Jekyll.logger.info "AutoPages:","Disabled/Not configured in site.config."
return
end
autopages_log(autopage_config, autolog_resources)
# TODO: Should I detect here and disable if we're running the legacy paginate code???!
# Simply gather all documents across all pages/posts/collections that we have
# we could be generating quite a few empty pages but the logic is just vastly simpler than trying to
# figure out what tag/category belong to which collection.
posts_to_use = Utils.collect_all_docs(site.collections)
###############################################
# Generate the Tag pages if enabled
createtagpage_lambda = lambda do | autopage_tag_config, pagination_config, layout_name, tag, tag_original_name |
site.pages << TagAutoPage.new(site, site.dest, autopage_tag_config, pagination_config, layout_name, tag, tag_original_name)
end
autopage_create(autopage_config, pagination_config, posts_to_use, 'tags', 'tags', createtagpage_lambda) # Call the actual function
###############################################
# Generate the category pages if enabled
createcatpage_lambda = lambda do | autopage_cat_config, pagination_config, layout_name, category, category_original_name |
site.pages << CategoryAutoPage.new(site, site.dest, autopage_cat_config, pagination_config, layout_name, category, category_original_name)
end
autopage_create(autopage_config, pagination_config,posts_to_use, 'categories', 'categories', createcatpage_lambda) # Call the actual function
###############################################
# Generate the Collection pages if enabled
createcolpage_lambda = lambda do | autopage_col_config, pagination_config, layout_name, coll_name, coll_original_name |
site.pages << CollectionAutoPage.new(site, site.dest, autopage_col_config, pagination_config, layout_name, coll_name, coll_original_name)
end
autopage_create(autopage_config, pagination_config,posts_to_use, 'collections', '__coll', createcolpage_lambda) # Call the actual function
end # create_autopages
# STATIC: this function actually performs the steps to generate the autopages. It uses a lambda function to delegate the creation of the individual
# page types to the calling code (this way all features can reuse the logic).
#
def self.autopage_create(autopage_config, pagination_config, posts_to_use, configkey_name, indexkey_name, createpage_lambda )
if !autopage_config[configkey_name].nil?
ap_sub_config = autopage_config[configkey_name]
if ap_sub_config ['enabled']
# Roll through all documents in the posts collection and extract the tags
index_keys = Utils.ap_index_posts_by(posts_to_use, indexkey_name) # Cannot use just the posts here, must use all things.. posts, collections...
index_keys.each do |index_key, value|
# Iterate over each layout specified in the config
ap_sub_config ['layouts'].each do | layout_name |
# Use site.dest here as these pages are never created in the actual source but only inside the _site folder
createpage_lambda.call(ap_sub_config, pagination_config, layout_name, index_key, value[-1]) # the last item in the value array will be the display name
end
end
end
end
end
def self.autopages_log(config, config_keys)
enabled, disabled = [], []
config_keys.each do |key|
key_config = config[key] # config for key
next if config.nil? || key_config['silent']
(key_config['enabled'] ? enabled : disabled) << key
end
Jekyll.logger.info("AutoPages:","Generating pages for #{_to_sentence(enabled)}") unless enabled.empty?
Jekyll.logger.info("AutoPages:","#{_to_sentence(disabled)} pages are disabled/not configured in site.config") unless disabled.empty?
end
def self._to_sentence(array)
if array.empty?
""
elsif array.length == 1
array[0].to_s
else
array[0..-2].join(", ") + " & " + array.last
end
end
end # module PaginateV2
end # module Jekyll
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/relationship/many_to_many.rb
|
require 'data_mapper/constraints/relationship/one_to_many'
module DataMapper
module Constraints
module Relationship
module ManyToMany
private
def one_to_many_options
super.merge(:constraint => @constraint)
end
# Checks that the constraint type is appropriate to the relationship
#
# @param [Fixnum] cardinality
# cardinality of relationship
# @param [Symbol] name
# name of relationship to evaluate constraint of
# @param [Hash] options
# options hash
#
# @option *args :constraint[Symbol]
# one of VALID_CONSTRAINT_VALUES
#
# @raise ArgumentError
# if @option :constraint is not one of VALID_CONSTRAINT_TYPES
#
# @return [Undefined]
#
# @api private
def assert_valid_constraint
super
# TODO: is any constraint valid for a m:m relationship?
if @constraint == :set_nil
raise ArgumentError, "#{@constraint} is not a valid constraint type for #{self.class}"
end
end
end # module ManyToMany
end # module Relationship
end # module Constraints
Associations::ManyToMany::Relationship::OPTIONS << :constraint
Associations::ManyToMany::Relationship.class_eval do
include Constraints::Relationship::ManyToMany
end
end # module DataMapper
|
meadmaker/dm-constraints
|
spec/isolated/require_spec.rb
|
shared_examples_for "require 'dm-constraints'" do
it "extends Model descendants with the constraint API" do
DataMapper::Model.descendants.should_not be_empty
DataMapper::Model.descendants.all? do |model|
model.respond_to?(:auto_migrate_constraints_down, true).should be(true)
model.respond_to?(:auto_migrate_constraints_up, true).should be(true)
end
end
it "includes the constraint API into the adapter" do
@adapter.respond_to?(:constraint_exists? ).should be(true)
@adapter.respond_to?(:create_relationship_constraint ).should be(true)
@adapter.respond_to?(:destroy_relationship_constraint).should be(true)
end
end
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/adapters/postgres_adapter.rb
|
require 'data_mapper/constraints/adapters/do_adapter'
module DataMapper
module Constraints
module Adapters
module PostgresAdapter
include DataObjectsAdapter
end
end
end
end
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/relationship/one_to_many.rb
|
<reponame>meadmaker/dm-constraints<filename>lib/data_mapper/constraints/relationship/one_to_many.rb<gh_stars>0
module DataMapper
module Constraints
module Relationship
module OneToMany
attr_reader :constraint
# @api private
def enforce_destroy_constraint(resource)
return true unless association = get(resource)
constraint = self.constraint
case constraint
when :protect
Array(association).empty?
when :destroy, :destroy!
association.__send__(constraint)
when :set_nil
if resource.instance_variable_get('@_constraint_destroy_process')
true
else
Array(association).all? do |resource|
resource.update(inverse => nil)
end
end
when :skip
true # do nothing
end
end
private
##
# Adds the delete constraint options to a relationship
#
# @param params [*ARGS] Arguments passed to Relationship#initialize
#
# @return [nil]
#
# @api private
def initialize(*args)
super
set_constraint
assert_valid_constraint
end
def set_constraint
@constraint = @options.fetch(:constraint, :protect) || :skip
end
# Checks that the constraint type is appropriate to the relationship
#
# @param [Fixnum] cardinality
# cardinality of relationship
# @param [Symbol] name
# name of relationship to evaluate constraint of
# @param [Hash] options
# options hash
#
# @option *args :constraint[Symbol]
# one of VALID_CONSTRAINT_VALUES
#
# @raise ArgumentError
# if @option :constraint is not one of VALID_CONSTRAINT_VALUES
#
# @return [Undefined]
#
# @api semipublic
def assert_valid_constraint
return unless @constraint
unless VALID_CONSTRAINT_VALUES.include?(@constraint)
raise ArgumentError, ":constraint option must be one of #{VALID_CONSTRAINT_VALUES.to_a.join(', ')}"
end
end
end # module OneToMany
end # module Relationship
end # module Constraints
Associations::OneToMany::Relationship::OPTIONS << :constraint
Associations::OneToMany::Relationship.class_eval do
include Constraints::Relationship::OneToMany
end
end # module DataMapper
|
meadmaker/dm-constraints
|
lib/dm-constraints.rb
|
require 'dm-core'
require 'data_mapper/constraints/resource'
require 'data_mapper/constraints/migrations/model'
require 'data_mapper/constraints/migrations/relationship'
require 'data_mapper/constraints/migrations/singleton_methods'
require 'data_mapper/constraints/relationship/one_to_many'
require 'data_mapper/constraints/relationship/many_to_many'
require 'data_mapper/constraints/adapters/extension'
require 'data_mapper/constraints/adapters/abstract_adapter'
module DataMapper
module Constraints
VALID_CONSTRAINT_VALUES = [ :protect, :destroy, :destroy!, :set_nil, :skip ].to_set.freeze
end
end
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/adapters/sqlite_adapter.rb
|
<reponame>meadmaker/dm-constraints<filename>lib/data_mapper/constraints/adapters/sqlite_adapter.rb
module DataMapper
module Constraints
module Adapters
module SqliteAdapter
# @api private
def constraint_exists?(*)
false
end
# @api private
def create_relationship_constraint(*)
false
end
# @api private
def destroy_relationship_constraint(*)
false
end
end
end
end
end
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/adapters/extension.rb
|
module DataMapper
module Constraints
module Adapters
module Extension
# Include the corresponding Constraints module into a adapter class
#
# @param [Symbol] const_name
# demodulized name of the adapter class to include corresponding
# constraints module into
#
# TODO: come up with a better way to include modules
# into all currently loaded and subsequently loaded Adapters
#
# @api private
def include_constraint_api(const_name)
require constraint_extensions(const_name)
if Constraints::Adapters.const_defined?(const_name)
adapter = const_get(const_name)
constraint_module = Constraints::Adapters.const_get(const_name)
adapter.class_eval { include constraint_module }
end
rescue LoadError
# Silently ignore the fact that no adapter extensions could be required
# This means that the adapter in use doesn't support constraints
end
private
# @api private
def constraint_extensions(const_name)
name = adapter_name(const_name)
name = 'do' if name == 'dataobjects'
"data_mapper/constraints/adapters/#{name}_adapter"
end
# @api private
def const_added(const_name)
include_constraint_api(const_name)
super
end
end # module Extension
end # module Adapters
end # module Constraints
Adapters.extend Constraints::Adapters::Extension
end # module DataMapper
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/adapters/abstract_adapter.rb
|
require "data_mapper/constraints/adapters/extension"
module DataMapper
module Constraints
module Adapters
module AbstractAdapter
# @api private
def constraint_exists?(*)
false
end
# @api private
def create_relationship_constraint(*)
false
end
# @api private
def destroy_relationship_constraint(*)
false
end
end # module AbstractAdapter
end # module Adapters
end # module Constraints
Adapters::AbstractAdapter.class_eval do
include Constraints::Adapters::AbstractAdapter
end
Adapters::AbstractAdapter.descendants.each do |adapter_class|
const_name = DataMapper::Inflector.demodulize(adapter_class.name)
Adapters.include_constraint_api(const_name)
end
end # module DataMapper
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/resource.rb
|
<gh_stars>0
module DataMapper
module Constraints
module Resource
def before_destroy_hook
instance_variable_set('@_constraint_destroy_process', true)
enforce_destroy_constraints
super
end
def after_destroy_hook
remove_instance_variable('@_constraint_destroy_process')
end
private
# Check delete constraints prior to destroying a dm resource or collection
#
# @note
# - It only considers a relationship's constraints if this is the parent model (ie a child shouldn't delete a parent)
# - Many to Many Relationships are skipped, as they are evaluated by their underlying 1:M relationships
#
# @return [nil]
#
# @api semi-public
def enforce_destroy_constraints
relationships.each do |relationship|
next unless relationship.respond_to?(:enforce_destroy_constraint)
constraint_satisfied = relationship.enforce_destroy_constraint(self)
throw(:halt, false) unless constraint_satisfied
end
end
end # module Resource
end # module Constraints
Model.append_inclusions Constraints::Resource
end # module DataMapper
|
meadmaker/dm-constraints
|
spec/integration/constraints_spec.rb
|
require 'spec_helper'
describe 'DataMapper::Constraints', "(with #{DataMapper::Spec.adapter_name})" do
supported_by :all do
before :all do
@in_memory = defined?(DataMapper::Adapters::InMemoryAdapter) && @adapter.kind_of?(DataMapper::Adapters::InMemoryAdapter)
@yaml = defined?(DataMapper::Adapters::YamlAdapter) && @adapter.kind_of?(DataMapper::Adapters::YamlAdapter)
@skip = @in_memory || @yaml
end
before :all do
class ::Article
include DataMapper::Resource
property :id, Serial
property :title, String, :required => true
property :content, Text
has 1, :revision
has n, :comments
has n, :authors, :through => Resource
end
class ::Author
include DataMapper::Resource
property :first_name, String, :key => true
property :last_name, String, :key => true
has n, :comments
has n, :articles, :through => Resource
end
class ::Comment
include DataMapper::Resource
property :id, Serial
property :body, Text
belongs_to :article
belongs_to :author
end
# Used to test a belongs_to association with no has() association
# on the other end
class ::Revision
include DataMapper::Resource
property :id, Serial
property :text, String
belongs_to :article
end
end
describe 'create related objects' do
before :all do
class ::Comment
belongs_to :article, :required => false
belongs_to :author, :required => false
end
class ::Revision
belongs_to :article, :required => false
end
end
it 'should be able to create related objects with a foreign key constraint' do
@article = Article.create(:title => 'Man on the Moon')
@comment = @article.comments.create(:body => 'So true!')
end
it 'should be able to create related objects with a composite foreign key constraint' do
@author = Author.create(:first_name => 'John', :last_name => 'Doe')
@comment = @author.comments.create(:body => 'So true!')
end
supported_by :postgres, :mysql do
it 'should not be able to create related objects with a failing foreign key constraint' do
jruby = defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby'
pending_if 'JRuby throws a DataObjects::SQLError for integrity errors, which is wrong', jruby do
article = Article.create(:title => 'Man on the Moon')
lambda {
Comment.create(:body => 'So true!', :article_id => article.id + 1)
}.should raise_error(DataObjects::IntegrityError)
end
end
end
end
describe 'belongs_to without matching has association' do
before do
@article = Article.create(:title => 'Man on the Moon')
@other_article = Article.create(:title => 'Dolly cloned')
@revision = Revision.create(:text => 'Riveting!', :article => @other_article)
end
it 'should destroy the parent if there are no children in the association' do
@article.destroy.should be(true)
@article.model.get(*@article.key).should be_nil
end
it 'the child should be destroyable' do
@revision.destroy.should be(true)
@revision.model.get(*@revision.key).should be_nil
end
end
describe 'constraint options' do
describe 'when no constraint options are given' do
before do
@article = Article.create(:title => 'Man on the Moon')
@author = Author.create(:first_name => 'John', :last_name => 'Doe')
@other_author = Author.create(:first_name => 'Joe', :last_name => 'Smith')
@comment = @other_author.comments.create(:body => 'So true!', :article => @article)
end
it 'should destroy the parent if there are no children in the association' do
@author.destroy.should be(true)
@author.model.get(*@author.key).should be_nil
end
it 'should not destroy the parent if there are children in the association' do
@other_author.destroy.should be(false)
@other_author.model.get(*@other_author.key).should_not be_nil
end
end
describe 'when :constraint => :protect is given' do
before :all do
class ::Article
has 1, :revision, :constraint => :protect
has n, :comments, :constraint => :protect
has n, :authors, :constraint => :protect, :through => Resource
end
class ::Author
has n, :comments, :constraint => :protect
has n, :articles, :constraint => :protect, :through => Resource
end
class ::Comment
belongs_to :article
belongs_to :author
end
class ::Revision
belongs_to :article
end
end
describe 'one-to-one associations' do
before do
@article = Article.create(:title => 'Man on the Moon')
@revision = Revision.create(:text => 'Riveting!', :article => @article)
end
it 'should not destroy the parent if there are children in the association' do
@article.destroy.should be(false)
@article.model.get(*@article.key).should_not be_nil
end
it 'the child should be destroyable' do
@revision.destroy.should be(true)
@revision.model.get(*@revision.key).should be_nil
end
end
describe 'one-to-many associations' do
before do
@article = Article.create(:title => 'Man on the Moon')
@author = Author.create(:first_name => 'John', :last_name => 'Doe')
@another_author = Author.create(:first_name => 'Joe', :last_name => 'Smith')
@comment = @another_author.comments.create(:body => 'So true!', :article => @article)
end
it 'should destroy the parent if there are no children in the association' do
@author.destroy.should be(true)
@author.model.get(*@author.key).should be_nil
end
it 'should not destroy the parent if there are children in the association' do
@another_author.destroy.should be(false)
end
it 'the child should be destroyable' do
@comment.destroy.should be(true)
@comment.model.get(*@comment.key).should be_nil
end
end
describe 'many-to-many associations' do
before do
pending 'The adapter does not support m:m associations yet' if @skip
end
before do
@author = Author.create(:first_name => 'John', :last_name => 'Doe')
@another_author = Author.create(:first_name => 'Joe', :last_name => 'Smith')
@article = Article.create(:title => 'Man on the Moon', :authors => [ @author ])
end
it 'should destroy the parent if there are no children in the association' do
@another_author.destroy.should be(true)
@another_author.model.get(*@another_author.key).should be_nil
end
it 'should not destroy the parent if there are children in the association' do
@author.articles.should_not == []
@author.destroy.should be(false)
end
it 'the child should be destroyable' do
@article.authors.clear
@article.save.should be(true)
@article.authors.should be_empty
end
end
end
describe 'when :constraint => :destroy! is given' do
before :all do
class ::Article
has 1, :revision, :constraint => :destroy!
has n, :comments, :constraint => :destroy!
has n, :authors, :constraint => :destroy!, :through => Resource
end
class ::Author
has n, :comments, :constraint => :destroy!
has n, :articles, :constraint => :destroy!, :through => Resource
end
class ::Comment
belongs_to :article
belongs_to :author
end
class ::Revision
belongs_to :article
end
end
describe 'one-to-one associations' do
before do
@article = Article.create(:title => 'Man on the Moon')
@revision = Revision.create(:text => 'Riveting!', :article => @article)
end
it 'should let the parent to be destroyed' do
@article.destroy.should be(true)
@article.model.get(*@article.key).should be_nil
end
it 'should destroy the children' do
revision = @article.revision
@article.destroy.should be(true)
revision.model.get(*revision.key).should be_nil
end
it 'the child should be destroyable' do
@revision.destroy.should be(true)
@revision.model.get(*@revision.key).should be_nil
end
end
describe 'one-to-many associations' do
before do
@article = Article.create(:title => 'Man on the Moon')
@author = Author.create(:first_name => 'John', :last_name => 'Doe')
@comment = @author.comments.create(:body => 'So true!', :article => @article)
@another_comment = @author.comments.create(:body => 'Nice comment', :article => @article)
end
it 'should let the parent to be destroyed' do
@author.destroy.should be(true)
@author.model.get(*@author.key).should be_nil
end
it 'should destroy the children' do
@author.destroy.should be(true)
@author.comments.all? { |comment| comment.should be_new }
end
it 'the child should be destroyable' do
@comment.destroy.should be(true)
@comment.model.get(*@comment.key).should be_nil
end
end
describe 'many-to-many associations' do
before do
pending 'The adapter does not support m:m associations yet' if @skip
end
before do
@article = Article.create(:title => 'Man on the Moon')
@other_article = Article.create(:title => 'Dolly cloned')
@author = Author.create(:first_name => 'John', :last_name => 'Doe', :articles => [ @article, @other_article ])
end
it 'should let the parent to be destroyed' do
@author.destroy.should be(true)
@author.model.get(*@author.key).should be_nil
end
it 'should destroy the children' do
@author.destroy.should be(true)
@article.model.get(*@article.key).should be_nil
@other_article.model.get(*@other_article.key).should be_nil
end
it 'the child should be destroyable' do
@article.destroy.should be(true)
@article.model.get(*@article.key).should be_nil
end
end
end
describe 'when :constraint => :destroy is given' do
before :all do
class ::Article
has 1, :revision, :constraint => :destroy
has n, :comments, :constraint => :destroy
has n, :authors, :constraint => :destroy, :through => Resource
end
class ::Author
has n, :comments, :constraint => :destroy
has n, :articles, :constraint => :destroy, :through => Resource
end
class ::Comment
belongs_to :article
belongs_to :author
end
class ::Revision
belongs_to :article
end
end
describe 'one-to-one associations' do
before do
@article = Article.create(:title => 'Man on the Moon')
@revision = Revision.create(:text => 'Riveting!', :article => @article)
end
it 'should let the parent to be destroyed' do
@article.destroy.should be(true)
@article.model.get(*@article.key).should be_nil
end
it 'should destroy the children' do
revision = @article.revision
@article.destroy.should be(true)
revision.model.get(*revision.key).should be_nil
end
it 'the child should be destroyable' do
@revision.destroy.should be(true)
@revision.model.get(*@revision.key).should be_nil
end
end
describe 'one-to-many associations' do
before do
@article = Article.create(:title => 'Man on the Moon')
@author = Author.create(:first_name => 'John', :last_name => 'Doe')
@comment = @author.comments.create(:body => 'So true!', :article => @article)
@other_comment = @author.comments.create(:body => "That's nonsense", :article => @article)
end
it 'should let the parent to be destroyed' do
@author.destroy.should be(true)
@author.model.get(*@author.key).should be_nil
end
it 'should destroy the children' do
@author.destroy.should be(true)
@author.comments.all? { |comment| comment.should be_new }
end
it 'the child should be destroyable' do
@comment.destroy.should be(true)
@comment.model.get(*@comment.key).should be_nil
end
end
describe 'many-to-many associations' do
before do
pending 'The adapter does not support m:m associations yet' if @skip
end
before do
@article = Article.create(:title => 'Man on the Moon')
@other_article = Article.create(:title => 'Dolly cloned')
@author = Author.create(:first_name => 'John', :last_name => 'Doe', :articles => [ @article, @other_article ])
end
it 'should destroy the parent and the children, too' do
@author.destroy.should be(true)
@author.model.get(*@author.key).should be_nil
@article.model.get(*@article.key).should be_nil
@other_article.model.get(*@other_article.key).should be_nil
end
it 'the child should be destroyable' do
@article.destroy.should be(true)
@article.model.get(*@article.key).should be_nil
end
end
end
describe 'when :constraint => :set_nil is given' do
before :all do
# NOTE: M:M Relationships are not supported by :set_nil,
# see 'when checking constraint types' tests at bottom
class ::Article
has 1, :revision, :constraint => :set_nil
has n, :comments, :constraint => :set_nil
end
class ::Author
has n, :comments, :constraint => :set_nil
end
class ::Comment
belongs_to :article, :required => false
belongs_to :author, :required => false
end
class ::Revision
belongs_to :article, :required => false
end
end
describe 'one-to-one associations' do
before do
@article = Article.create(:title => 'Man on the Moon')
@revision = Revision.create(:text => 'Riveting!', :article => @article)
end
it 'should let the parent to be destroyed' do
@article.destroy.should be(true)
@article.model.get(*@article.key).should be_nil
end
it "should set the child's foreign_key id to nil" do
revision = @article.revision
@article.destroy.should be(true)
revision.article.should be_nil
revision.model.get(*revision.key).article.should be_nil
end
it 'the child should be destroyable' do
@revision.destroy.should be(true)
@revision.model.get(*@revision.key).should be_nil
end
end
describe 'one-to-many associations' do
before do
@author = Author.create(:first_name => 'John', :last_name => 'Doe')
@comment = @author.comments.create(:body => 'So true!')
@other_comment = @author.comments.create(:body => "That's nonsense")
end
it 'should let the parent to be destroyed' do
@author.destroy.should be(true)
@author.model.get(*@author.key).should be_nil
end
it 'should set the foreign_key ids of children to nil' do
@author.destroy.should be(true)
@author.comments.all? { |comment| comment.author.should be_nil }
end
it 'the children should be destroyable' do
@comment.destroy.should be(true)
@comment.model.get(*@comment.key).should be_nil
@other_comment.destroy.should be(true)
@other_comment.model.get(*@other_comment.key).should be_nil
end
end
end
describe 'when :constraint => :skip is given' do
before :all do
class ::Article
has 1, :revision, :constraint => :skip
has n, :comments, :constraint => :skip
has n, :authors, :constraint => :skip, :through => Resource
end
class ::Author
has n, :comments, :constraint => :skip
has n, :articles, :constraint => :skip, :through => Resource
end
class ::Comment
belongs_to :article
belongs_to :author
end
class ::Revision
belongs_to :article
end
end
describe 'one-to-one associations' do
before do
@article = Article.create(:title => 'Man on the Moon')
@revision = Revision.create(:text => 'Riveting!', :article => @article)
end
it 'should let the parent be destroyed' do
@article.destroy.should be(true)
@article.model.get(*@article.key).should be_nil
end
it 'should let the children become orphan records' do
@article.destroy.should be(true)
@revision.model.get(*@revision.key).article.should be_nil
end
it 'the child should be destroyable' do
@revision.destroy.should be(true)
@revision.model.get(*@revision.key).should be_nil
end
end
describe 'one-to-many associations' do
before do
@article = Article.create(:title => 'Man on the Moon')
@author = Author.create(:first_name => 'John', :last_name => 'Doe')
@comment = @author.comments.create(:body => 'So true!', :article => @article)
@other_comment = @author.comments.create(:body => "That's nonsense", :article => @article)
end
it 'should let the parent to be destroyed' do
@author.destroy.should be(true)
@author.model.get(*@author.key).should be_nil
end
it 'should let the children become orphan records' do
@author.destroy.should be(true)
@comment.model.get(*@comment.key).author.should be_nil
@other_comment.model.get(*@other_comment.key).author.should be_nil
end
it 'the children should be destroyable' do
@comment.destroy.should be(true)
@other_comment.destroy.should be(true)
@other_comment.model.get(*@other_comment.key).should be_nil
end
end
describe 'many-to-many associations' do
before do
pending 'The adapter does not support m:m associations yet' if @skip
end
before do
@article = Article.create(:title => 'Man on the Moon')
@other_article = Article.create(:title => 'Dolly cloned')
@author = Author.create(:first_name => 'John', :last_name => 'Doe', :articles => [ @article, @other_article ])
end
it 'the children should be destroyable' do
@article.destroy.should be(true)
@article.model.get(*@article.key).should be_nil
end
end
end
describe 'when checking constraint types' do
# M:M relationships results in a join table composed of composite (composed of two parts)
# primary key.
# Setting a portion of this primary key is not possible for two reasons:
# 1. the columns are defined as :required => true
# 2. there could be duplicate rows if more than one of either of the types
# was deleted while being associated to the same type on the other side of the relationshp
# Given
# Author(name: <NAME>, ID: 1) =>
# Articles[Article(title: Man on the Moon, ID: 1), Article(title: Dolly cloned, ID: 2)]
# Author(Name: <NAME>, ID: 2) =>
# Articles[Article(title: Man on the Moon, ID: 1), Article(title: The end is nigh, ID: 3)]
#
# Table authors_articles would look like (author_id, article_id)
# (1, 1)
# (1, 2)
# (2, 1)
# (2, 3)
#
# If both articles were deleted and the primary key was set to null
# (null, 1)
# (null, 2)
# (null, 1) # duplicate error!
# (null, 3)
#
# I would suggest setting :constraint to :skip in this scenario which will leave
# you with orphaned rows.
it 'should raise an error if :set_nil is given for a M:M relationship' do
lambda {
class ::Article
has n, :authors, :through => Resource, :constraint => :set_nil
end
class ::Author
has n, :articles, :through => Resource, :constraint => :set_nil
end
}.should raise_error(ArgumentError)
end
it 'should raise an error if an unknown type is given' do
lambda do
class ::Author
has n, :articles, :constraint => :chocolate
end
end.should raise_error(ArgumentError)
end
end
end
end
end
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/adapters/mysql_adapter.rb
|
require 'data_mapper/constraints/adapters/do_adapter'
module DataMapper
module Constraints
module Adapters
module MysqlAdapter
include DataObjectsAdapter
module SQL
private
##
# MySQL specific query to drop a foreign key
#
# @see DataMapper::Constraints::Adapters::DataObjectsAdapter#destroy_constraints_statement
#
# @api private
def destroy_constraints_statement(storage_name, constraint_name)
DataMapper::Ext::String.compress_lines(<<-SQL)
ALTER TABLE #{quote_name(storage_name)}
DROP FOREIGN KEY #{quote_name(constraint_name)}
SQL
end
end
include SQL
end # module MysqlAdapter
end # module Adapters
end # module Constraints
end # module DataMapper
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/adapters/oracle_adapter.rb
|
require 'data_mapper/constraints/adapters/do_adapter'
module DataMapper
module Constraints
module Adapters
module OracleAdapter
include DataObjectsAdapter
# oracle does not provide the information_schema table
# To question internal state like postgres or mysql
#
# @see DataMapper::Constraints::Adapters::DataObjectsAdapter
#
# @api private
def constraint_exists?(storage_name, constraint_name)
statement = DataMapper::Ext::String.compress_lines(<<-SQL)
SELECT COUNT(*)
FROM USER_CONSTRAINTS
WHERE table_name = ?
AND constraint_name = ?
SQL
select(statement, oracle_upcase(storage_name)[0, self.class::IDENTIFIER_MAX_LENGTH].gsub('"', '_'), oracle_upcase(constraint_name)[0, self.class::IDENTIFIER_MAX_LENGTH].gsub('"', '_')).first > 0
end
# @see DataMapper::Constraints::Adapters::DataObjectsAdapter#create_constraints_statement
#
# @api private
#
# TODO: is it desirable to always set `INITIALLY DEFERRED DEFERRABLE`?
def create_constraints_statement(constraint_name, constraint_type, source_storage_name, source_keys, target_storage_name, target_keys)
DataMapper::Ext::String.compress_lines(<<-SQL)
ALTER TABLE #{quote_name(source_storage_name)}
ADD CONSTRAINT #{quote_name(constraint_name)}
FOREIGN KEY (#{source_keys.join(', ')})
REFERENCES #{quote_name(target_storage_name)} (#{target_keys.join(', ')})
#{"ON DELETE " + constraint_type if constraint_type && constraint_type != "NO ACTION"}
INITIALLY DEFERRED DEFERRABLE
SQL
end
# @api private
def destroy_constraints_statement(storage_name, constraint_name)
DataMapper::Ext::String.compress_lines(<<-SQL)
ALTER TABLE #{quote_name(storage_name)}
DROP CONSTRAINT #{quote_name(constraint_name)}
CASCADE
SQL
end
end
end
end
end
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/adapters/do_adapter.rb
|
<gh_stars>1-10
module DataMapper
module Constraints
module Adapters
module DataObjectsAdapter
##
# Determine if a constraint exists for a table
#
# @param storage_name [Symbol]
# name of table to check constraint on
# @param constraint_name [~String]
# name of constraint to check for
#
# @return [Boolean]
#
# @api private
def constraint_exists?(storage_name, constraint_name)
statement = DataMapper::Ext::String.compress_lines(<<-SQL)
SELECT COUNT(*)
FROM #{quote_name('information_schema')}.#{quote_name('table_constraints')}
WHERE #{quote_name('constraint_type')} = 'FOREIGN KEY'
AND #{quote_name('table_schema')} = ?
AND #{quote_name('table_name')} = ?
AND #{quote_name('constraint_name')} = ?
SQL
select(statement, schema_name, storage_name, constraint_name).first > 0
end
##
# Create the constraint for a relationship
#
# @param relationship [Relationship]
# the relationship to create the constraint for
#
# @return [true, false]
# true if creating the constraints was successful
#
# @api semipublic
def create_relationship_constraint(relationship)
return false unless valid_relationship_for_constraint?(relationship)
source_storage_name = relationship.source_model.storage_name(name)
target_storage_name = relationship.target_model.storage_name(name)
constraint_name = constraint_name(source_storage_name, relationship.name)
return false if constraint_exists?(source_storage_name, constraint_name)
constraint_type =
case relationship.inverse.constraint
when :protect then 'NO ACTION'
# TODO: support :cascade as an option:
# (destroy doesn't communicate the UPDATE constraint)
when :destroy, :destroy! then 'CASCADE'
when :set_nil then 'SET NULL'
end
return false if constraint_type.nil?
source_keys = relationship.source_key.map { |p| property_to_column_name(p, false) }
target_keys = relationship.target_key.map { |p| property_to_column_name(p, false) }
create_constraints_statement = create_constraints_statement(
constraint_name,
constraint_type,
source_storage_name,
source_keys,
target_storage_name,
target_keys)
execute(create_constraints_statement)
end
##
# Remove the constraint for a relationship
#
# @param relationship [Relationship]
# the relationship to remove the constraint for
#
# @return [true, false]
# true if destroying the constraint was successful
#
# @api semipublic
def destroy_relationship_constraint(relationship)
return false unless valid_relationship_for_constraint?(relationship)
storage_name = relationship.source_model.storage_name(name)
constraint_name = constraint_name(storage_name, relationship.name)
return false unless constraint_exists?(storage_name, constraint_name)
destroy_constraints_statement =
destroy_constraints_statement(storage_name, constraint_name)
execute(destroy_constraints_statement)
end
private
##
# Check to see if the relationship's constraints can be used
#
# Only one-to-one, one-to-many, and many-to-many relationships
# can be used for constraints. They must also be in the same
# repository as the adapter is connected to.
#
# @param relationship [Relationship]
# the relationship to check
#
# @return [true, false]
# true if a constraint can be established for relationship
#
# @api private
def valid_relationship_for_constraint?(relationship)
return false unless relationship.source_repository_name == name || relationship.source_repository_name.nil?
return false unless relationship.target_repository_name == name || relationship.target_repository_name.nil?
return false unless relationship.kind_of?(Associations::ManyToOne::Relationship)
true
end
module SQL
private
# Generates the SQL statement to create a constraint
#
# @param [String] constraint_name
# name of the foreign key constraint
# @param [String] constraint_type
# type of constraint to ALTER source_storage_name with
# @param [String] source_storage_name
# name of table to ALTER with constraint
# @param [Array(String)] source_keys
# columns in source_storage_name that refer to foreign table
# @param [String] target_storage_name
# target table of the constraint
# @param [Array(String)] target_keys
# columns the target table that are referred to
#
# @return [String]
# SQL DDL Statement to create a constraint
#
# @api private
def create_constraints_statement(constraint_name, constraint_type, source_storage_name, source_keys, target_storage_name, target_keys)
DataMapper::Ext::String.compress_lines(<<-SQL)
ALTER TABLE #{quote_name(source_storage_name)}
ADD CONSTRAINT #{quote_name(constraint_name)}
FOREIGN KEY (#{source_keys.join(', ')})
REFERENCES #{quote_name(target_storage_name)} (#{target_keys.join(', ')})
ON DELETE #{constraint_type}
ON UPDATE #{constraint_type}
SQL
end
##
# Generates the SQL statement to destroy a constraint
#
# @param [String] storage_name
# name of table to constrain
# @param [String] constraint_name
# name of foreign key constraint
#
# @return [String]
# SQL DDL Statement to destroy a constraint
#
# @api private
def destroy_constraints_statement(storage_name, constraint_name)
DataMapper::Ext::String.compress_lines(<<-SQL)
ALTER TABLE #{quote_name(storage_name)}
DROP CONSTRAINT #{quote_name(constraint_name)}
SQL
end
##
# generates a unique constraint name given a table and a relationships
#
# @param [String] storage_name
# name of table to constrain
# @param [String] relationship_name
# name of the relationship to constrain
#
# @return [String]
# name of the constraint
#
# @api private
def constraint_name(storage_name, relationship_name)
identifier = "#{storage_name}_#{relationship_name}"[0, self.class::IDENTIFIER_MAX_LENGTH - 3]
"#{identifier}_fk"
end
end
include SQL
end # module DataObjectsAdapter
end # module Adapters
end # module Constraints
end # module DataMapper
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/migrations/model.rb
|
# TODO: figure out some other (less tightly coupled) way to ensure that
# dm-migrations' method implementations are loaded before this file
require "dm-migrations/auto_migration"
module DataMapper
module Constraints
module Migrations
module Model
# @api private
def auto_migrate_constraints_up(repository_name = self.repository_name)
# TODO: this check should not be here
return if self.respond_to?(:is_remixable?) && self.is_remixable?
relationships(repository_name).each do |relationship|
relationship.auto_migrate_constraints_up(repository_name)
end
end
# @api private
def auto_migrate_constraints_down(repository_name = self.repository_name)
return unless storage_exists?(repository_name)
# TODO: this check should not be here
return if self.respond_to?(:is_remixable?) && self.is_remixable?
relationships(repository_name).each do |relationship|
relationship.auto_migrate_constraints_down(repository_name)
end
end
end # module Model
end # module Migrations
end # module Constraints
Model.append_extensions Constraints::Migrations::Model
end # module DataMapper
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/migrations/relationship.rb
|
<filename>lib/data_mapper/constraints/migrations/relationship.rb<gh_stars>1-10
module DataMapper
module Constraints
module Migrations
module Relationship
# @api private
def auto_migrate_constraints_up(repository_name)
# no-op
end
# @api private
def auto_migrate_constraints_down(repository_name)
# no-op
end
module ManyToOne
# @api private
def auto_migrate_constraints_up(repository_name)
adapter = DataMapper.repository(repository_name).adapter
adapter.create_relationship_constraint(self)
self
end
# @api private
def auto_migrate_constraints_down(repository_name)
adapter = DataMapper.repository(repository_name).adapter
adapter.destroy_relationship_constraint(self)
self
end
end
end # module Relationship
end # module Migrations
end # module Constraints
Associations::Relationship.class_eval do
include Constraints::Migrations::Relationship
end
Associations::ManyToOne::Relationship.class_eval do
include Constraints::Migrations::Relationship::ManyToOne
end
end # module DataMapper
|
meadmaker/dm-constraints
|
lib/data_mapper/constraints/migrations/singleton_methods.rb
|
<reponame>meadmaker/dm-constraints<gh_stars>1-10
module DataMapper
module Constraints
module Migrations
module SingletonMethods
def auto_migrate!(repository_name = nil)
auto_migrate_constraints_down(repository_name)
# TODO: Model#auto_migrate! drops and adds constraints, as well.
# is that an avoidable duplication?
super
auto_migrate_constraints_up(repository_name)
self
end
private
def auto_migrate_down!(repository_name = nil)
auto_migrate_constraints_down(repository_name)
super
self
end
def auto_migrate_up!(repository_name = nil)
super
auto_migrate_constraints_up(repository_name)
self
end
# @api private
def auto_migrate_constraints_up(repository_name = nil)
DataMapper::Model.descendants.each do |model|
model.auto_migrate_constraints_up(repository_name || model.default_repository_name)
end
end
# @api private
def auto_migrate_constraints_down(repository_name = nil)
DataMapper::Model.descendants.each do |model|
model.auto_migrate_constraints_down(repository_name || model.default_repository_name)
end
end
end # module SingletonMethods
end # module Migrations
end # module Constraints
extend Constraints::Migrations::SingletonMethods
end # module DataMapper
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/reports/donation_monthly_totals_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Reports > Donation Monthly Totals Report' do
include_context :json_headers
documentation_scope = :reports_api_donation_summaries
let(:resource_type) { 'reports_donation_monthly_totals' }
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let(:resource_attributes) do
%w(
created_at
donation_totals_by_month
updated_at
updated_in_db_at
)
end
context 'authorized user' do
before { api_login(user) }
# show
get '/api/v2/reports/donation_monthly_totals' do
parameter 'filter[account_list_id]', 'Account List ID', required: true
parameter 'filter[month_range]', 'Month Range', required: true
with_options scope: [:data, :attributes] do
response_field 'donation_totals_by_month', 'The donations amount for each currency by month.', type: 'Array[Object]'
end
example 'Donation Summary [LIST]', document: documentation_scope do
explanation 'Lists donors who donated in the past 12 months, separated by into currency groups'
do_request(filter: { account_list_id: account_list_id, month_range: (4.months.ago..2.months.ago).to_s })
check_resource([])
expect(json_response['data']['attributes']['donation_totals_by_month']).to be_an(Array)
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20150514012021_add_disable_downloads_to_person_organization_accounts.rb
|
class AddDisableDownloadsToPersonOrganizationAccounts < ActiveRecord::Migration
def change
add_column :person_organization_accounts, :disable_downloads, :boolean, null: false, default: false
end
end
|
chuckmersereau/api_practice
|
db/migrate/20180913185651_add_age_to_person.rb
|
<reponame>chuckmersereau/api_practice<filename>db/migrate/20180913185651_add_age_to_person.rb
class AddAgeToPerson < ActiveRecord::Migration
def change
add_column :people, :age, :integer
end
end
|
chuckmersereau/api_practice
|
spec/factories/access_tokens.rb
|
<filename>spec/factories/access_tokens.rb<gh_stars>0
FactoryBot.define do
factory :access_token, class: 'Doorkeeper::AccessToken' do
resource_owner_id
application_id
token { double acceptable?: true }
end
end
|
chuckmersereau/api_practice
|
spec/controllers/concerns/filtering_spec.rb
|
require 'spec_helper'
describe Api::V2Controller do
describe '#DATE_REGEX' do
it 'matches date string' do
expect('2017-12-13').to match Filtering::DATE_REGEX
end
it 'does not match blank' do
expect('').to_not match Filtering::DATE_REGEX
expect(nil).to_not match Filtering::DATE_REGEX
end
it 'does not match not-date string' do
expect('last week').to_not match Filtering::DATE_REGEX
expect('2001').to_not match Filtering::DATE_REGEX
end
end
describe '#DATE_TIME_REGEX' do
it 'matches 00:00 timezone datetime string' do
expect('2001-02-03T04:05:06+00:00').to match Filtering::DATE_TIME_REGEX
end
it 'matches Z timezone datetime string' do
expect('2001-02-03T04:05:06Z').to match Filtering::DATE_TIME_REGEX
end
it 'does not match blank' do
expect('').to_not match Filtering::DATE_TIME_REGEX
expect(nil).to_not match Filtering::DATE_TIME_REGEX
end
it 'does not match not-datetime string' do
expect('last week').to_not match Filtering::DATE_TIME_REGEX
expect('2017-12-13').to_not match Filtering::DATE_TIME_REGEX
end
end
describe '#DATE_RANGE_REGEX' do
it 'matches date range string' do
expect('2017-12-13..2018-01-13').to match Filtering::DATE_RANGE_REGEX
expect('2017-12-13...2018-01-13').to match Filtering::DATE_RANGE_REGEX
end
it 'does not match blank' do
expect('').to_not match Filtering::DATE_RANGE_REGEX
expect(nil).to_not match Filtering::DATE_RANGE_REGEX
end
it 'does not match not-date range string' do
expect('last week').to_not match Filtering::DATE_RANGE_REGEX
expect('2017-12-13').to_not match Filtering::DATE_RANGE_REGEX
end
end
describe '#DATE_TIME_RANGE_REGEX' do
it 'matches datetime range string' do
expect('2001-02-03T04:05:06+00:00..2001-02-03T04:05:06+00:00').to match Filtering::DATE_TIME_RANGE_REGEX
expect('2001-02-03T04:05:06Z...2001-02-03T04:05:06Z').to match Filtering::DATE_TIME_RANGE_REGEX
end
it 'does not match blank' do
expect('').to_not match Filtering::DATE_TIME_RANGE_REGEX
expect(nil).to_not match Filtering::DATE_TIME_RANGE_REGEX
end
it 'does not match not-datetime range string' do
expect('last week').to_not match Filtering::DATE_TIME_RANGE_REGEX
expect('2017-12-13..2018-01-13').to_not match Filtering::DATE_TIME_RANGE_REGEX
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120509144947_add_public_url_to_person_linkedin_accounts.rb
|
<reponame>chuckmersereau/api_practice
class AddPublicUrlToPersonLinkedinAccounts < ActiveRecord::Migration
def change
add_column :person_linkedin_accounts, :public_url, :string
end
end
|
chuckmersereau/api_practice
|
app/policies/notification_policy.rb
|
<filename>app/policies/notification_policy.rb
class NotificationPolicy < AccountListChildrenPolicy
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/tasks/filters_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Tasks > Filters' do
include_context :json_headers
documentation_scope = :tasks_api_filters
let!(:user) { create(:user_with_account) }
context 'authorized user' do
before { api_login(user) }
get '/api/v2/tasks/filters' do
example 'Filter [LIST]', document: documentation_scope do
explanation 'List of Task Filters'
do_request
filters_displayed = json_response['data'].map do |filter|
filter['type'].gsub('task_filter_', '').camelize
end
expect(Task::Filterer::FILTERS_TO_DISPLAY.map(&:pluralize)).to include(*filters_displayed)
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
app/workers/run_once/fix_newsletter_status_worker.rb
|
class RunOnce::FixNewsletterStatusWorker
include Sidekiq::Worker
List = Struct.new(:id, :name, :web_id)
MAIL_CHIMP_REFACTOR_DATE = '2017-07-12'.freeze
NEW_LIST_NAME = 'List created by MPDX'.freeze
TAG_NAME = 'MailChimp Updated'.freeze
sidekiq_options queue: :run_nowhere, unique: :until_executed
def perform(mail_chimp_account_uuid)
log('Starting work on ' + mail_chimp_account_uuid)
@account = MailChimpAccount.find_by(uuid: mail_chimp_account_uuid)
return if @account.api_key.blank? || @account.primary_list_id.blank?
return unless @account.account_list
@gibbon_wrapper = MailChimp::GibbonWrapper.new(@account)
@list_id = @account.primary_list_id
@current_subscribers = []
@people = {}
@contacts = {}
members_to_resubscribe = find_members_to_resubscribe
if @current_subscribers.to_set != members_to_resubscribe.to_set
# If the current and new list of emails aren't the same, rather than mark all these people as subscribed on
# someone's current mailchimp list, we're going to create a new list for them just to be safe. We'll add all these
# emails to the new list, and attach that list to their
# MPDX account.
@new_list_id = create_new_list
populate_new_list(@new_list_id, members_to_resubscribe)
# We now want to point the mailchimp account at the new list. Otherwise when we automatically update mpdx
# fields below it will pass through to updating the old list
connect_mpdx_to_new_list(@new_list_id)
end
# Then update mpdx optout and send_newsletter values, which will trigger updates to the list we just pointed to
# (all of those updates should be noops)
update_mpdx_fields(members_to_resubscribe)
@account.update(active: true) if @new_list_id
log('-- running full sync on list')
MailChimp::ExportContactsWorker.new.perform(@account.id, @new_list_id, nil)
fix_count = FixCount.find_or_initialize_by(account_list_id: @account.account_list_id)
fix_count.old_members = @current_subscribers.count
fix_count.new_members = members_to_resubscribe.count
fix_count.contacts_tagged = @account.account_list.contacts.tagged_with(TAG_NAME).count
fix_count.people_changed = @people.keys.count
fix_count.contacts_changed = @contacts.keys.count
fix_count.save
emails = @account.account_list.users.collect(&:email_address).uniq.compact
return unless emails.any?
log("-- emailing #{emails}")
mail = if @new_list
RunOnceMailer.new_mailchimp_list(emails,
fix_count.contacts_tagged,
@account.account_list.name,
link_for_list)
elsif fix_count.contacts_tagged.positive?
RunOnceMailer.fix_newsletter_status(emails, fix_count.contacts_tagged, @account.account_list.name)
end
mail&.deliver_later
rescue Gibbon::MailChimpError => e
log("-- failing with #{e.status_code} #{e.detail}")
case e.status_code
when 401, 403
@account.update(api_key: nil)
when 404
@account.update(primary_list_id: nil)
else
raise e
end
end
# Returns a list of email addresses that received a newsletter since the refactor
def find_members_to_resubscribe
log('-- Finding people to resubscribe')
members = @gibbon_wrapper.list_members(@list_id)
members_to_resubscribe = []
members.each do |member|
if member['status'] == 'subscribed'
@current_subscribers << member
members_to_resubscribe << member
next
end
# if they manually unsubscribed, they will have a reason other than Unsubscribed by an admin
# we should not resubscribe them if that is the case
mpdx_unsubscribe = member['unsubscribe_reason'] == 'N/A (Unsubscribed by an admin)'
# if the email isn't a primary, it doesn't belong on the list anyway
next unless primary_email_exists?(member['email_address'])
unless mpdx_unsubscribe
# if they have an unsubscribe reason other than via admin and are unsubscribed, ensure
# optout_enewsletter is true
ensure_optout(member['email_address']) if member['status'] == 'unsubscribed'
# if the member is not currently unsubscribed and not unsubscribed by MPDX, leave them off
# the new list
next
end
activity_search_params = { params: {
action: 'sent', fields: 'activity.timestamp'
} }
activity = @gibbon_wrapper.gibbon.lists(@list_id).members(member['id']).activity.retrieve(activity_search_params)['activity'].first
members_to_resubscribe << member if activity && activity['timestamp'] >= MAIL_CHIMP_REFACTOR_DATE
end
members_to_resubscribe
end
def primary_email_exists?(email)
email_address_scope = EmailAddress.joins(person: [:contacts])
.where(contacts: {
account_list_id: @account.account_list_id,
status: Contact::ACTIVE_STATUSES + [nil]
})
email_address_scope.exists?(email: email, primary: true)
end
def emails_to_resubscribe(members_to_resubscribe)
members_to_resubscribe.collect { |member| member['email_address'] }
end
def ensure_optout(email)
people = @account.account_list
.people
.joins(:email_addresses)
.where(email_addresses: { email: email, primary: true })
people.each { |person| person.update(optout_enewsletter: true) }
end
# resets the optout_newsletter and send_newsletter fields based on the fact that people are getting the letter
def update_mpdx_fields(members_to_resubscribe)
log('-- Updating MPDX fields')
emails = emails_to_resubscribe(members_to_resubscribe)
account_list = @account.account_list
# Remove optout from people with this email address
people = account_list.active_people.joins(:email_addresses).where('email_addresses.email' => emails.map(&:downcase))
people.each do |person|
next unless person.optout_enewsletter?
person.update(optout_enewsletter: false)
@people[person] ||= true
add_tag(person.contacts.first)
end
# Update contacts on the list to get Email
contact_scope = account_list.active_contacts.joins(:contact_people).where('contact_people.person_id' => people.pluck(:id))
contact_scope.each do |contact|
if contact.send_newsletter == 'Physical'
contact.update(send_newsletter: 'Both')
@contacts[contact] ||= true
add_tag(contact)
end
next unless [nil, '', 'None'].include?(contact.send_newsletter)
contact.update(send_newsletter: 'Email')
@contacts[contact] ||= true
add_tag(contact)
end
# Update contacts not on the list to not get email
# no_email_contact_scope = account_list.active_contacts.where('id NOT IN(?)', contact_scope.pluck(:id))
# no_email_contact_scope.where(send_newsletter: 'Both').update_all(send_newsletter: 'Physical')
# no_email_contact_scope.where(send_newsletter: 'Email').update_all(send_newsletter: 'None')
end
def create_new_list
log('-- creating a new mailchimp list')
primary_list = @gibbon_wrapper.gibbon.lists(@list_id).retrieve
# See if we already created the list
@new_list = @gibbon_wrapper.lists.detect { |l| l.name == NEW_LIST_NAME }
unless @new_list
list_config_keys = %w[contact permission_reminder use_archive_bar campaign_defaults notify_on_subscribe
notify_on_unsubscribe email_type_option visibility]
list_attributes = primary_list.slice(*list_config_keys).merge('name' => NEW_LIST_NAME)
response = @gibbon_wrapper.gibbon.lists.create(body: list_attributes)
@new_list = List.new(response['id'], response['name'], response['web_id'])
end
@new_list.id
end
def populate_new_list(list_id, members_to_resubscribe)
log('-- populating new mailchimp list')
emails = emails_to_resubscribe(members_to_resubscribe)
gibbon = @gibbon_wrapper.gibbon
# Since this list is fully managed by MPDX, it's safe to delete people before re-populating as part of this
# one-off process
existing_members = @gibbon_wrapper.list_members(list_id)
existing_members.each do |member|
gibbon.lists(list_id).members(member['id']).delete unless emails.include?(member['email_address'])
end
# Subscribe people to this new list
operations = []
member_attributes = %w[email_address email_type merge_fields language vip]
members_to_resubscribe.each do |member|
operations << {
method: 'PUT',
path: "lists/#{list_id}/members/#{@account.email_hash(member['email_address'])}",
body: member.slice(*member_attributes).merge(status: 'subscribed').to_json
}
end
gibbon.batches.create(body: { operations: operations }) if operations.present?
end
def connect_mpdx_to_new_list(list_id)
@account.update(primary_list_id: list_id)
end
def add_tag(contact)
contact.tag_list.add(TAG_NAME)
contact.save
end
def link_for_list
"#{@gibbon_wrapper.lists_link}members/?id=#{@new_list.web_id}"
end
def log(message)
# Because the sidekiq config sets the logging level to Fatal, log to fatal
# so that we can see these in the logs
Rails.logger.fatal("FixNewsletterStatus[worker]: #{message}")
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170911035021_add_timestamps_to_excluded_appeal_contacts.rb
|
class AddTimestampsToExcludedAppealContacts < ActiveRecord::Migration
def change
add_timestamps :appeal_excluded_appeal_contacts, default: DateTime.now
change_column_default :appeal_excluded_appeal_contacts, :created_at, nil
change_column_default :appeal_excluded_appeal_contacts, :updated_at, nil
end
end
|
chuckmersereau/api_practice
|
engines/auth/app/controllers/auth/application_controller.rb
|
<reponame>chuckmersereau/api_practice<filename>engines/auth/app/controllers/auth/application_controller.rb
module Auth
class ApplicationController < ActionController::Base
class AuthenticationError < StandardError; end
rescue_from AuthenticationError, with: :render_401
protect_from_forgery with: :exception
protected
def current_user
@current_user ||= warden.user(:user)
raise AuthenticationError unless @current_user
@current_user
end
def render_401
render '401', status: 401
end
end
end
|
chuckmersereau/api_practice
|
spec/controllers/auth/user_accounts_controller_spec.rb
|
require 'rails_helper'
describe Auth::UserAccountsController, :auth, type: :controller do
routes { Auth::Engine.routes }
let(:user) { create(:user_with_account) }
let(:provider) { :google }
context 'with a logged in user' do
before(:each) do
end
it 'should redirect the user to the requested provider' do
auth_login(user)
get :create, provider: provider
expect(response.status).to be(302)
expect(response.location).to include(provider.to_s)
end
it 'should add the current user to the session' do
auth_login(user)
get :create, provider: provider
expect(session['warden.user.user.key']).to be(user.id)
end
it 'should store an account_list_id param in the session' do
auth_login(user)
get :create, provider: provider, account_list_id: '4'
expect(session['account_list_id']).to eq('4')
end
context 'provider is donorhub' do
let(:provider) { :donorhub }
let!(:organization) do
create(
:organization,
oauth_url: 'https://www.mytntware.com/dataserver/toontown/staffportal/oauth/authorize.aspx'
)
end
it 'should redirect the user to the requested provider' do
auth_login(user)
get :create, provider: provider, organization_id: organization.id
expect(response.status).to be(302)
expect(response.location).to include("#{provider}?oauth_url=#{URI.encode(organization.oauth_url)}")
end
context 'organization does not exist' do
it 'should return an unauthorized response' do
get :create, provider: provider, organization_id: '123'
expect(response.status).to be(401)
end
end
end
context 'provider is sidekiq' do
let(:provider) { :sidekiq }
let(:user) { create(:user_with_account, developer: true) }
it 'should redirect user to sidekiq' do
auth_login(user)
get :create, provider: provider
expect(response.status).to be(302)
expect(response.location).to include('sidekiq')
end
context 'user is not developer' do
let(:user) { create(:user_with_account, developer: false) }
it 'should return an unauthorized response' do
get :create, provider: provider
expect(response.status).to be(401)
end
end
end
end
context 'with no logged in user' do
it 'should return an unauthorized response' do
get :create, provider: provider
expect(response.status).to be(401)
end
end
end
|
chuckmersereau/api_practice
|
app/services/currency_rate/aliased_rates_filler.rb
|
class CurrencyRate
class AliasedRatesFiller
def fill_aliased_rates
CurrencyAlias.all.find_each(&method(:fill_rates_for_alias))
end
private
def fill_rates_for_alias(currency_alias)
missing_dates(currency_alias).each do |missing_date|
base_rate = CurrencyRate.find_by(code: currency_alias.rate_api_code,
exchanged_on: missing_date).rate
CurrencyRate.create(code: currency_alias.alias_code, source: 'alias',
rate: base_rate * currency_alias.ratio,
exchanged_on: missing_date)
end
end
def missing_dates(currency_alias)
CurrencyRate.connection.execute(missing_dates_sql(currency_alias))
.values.map(&:first)
end
def missing_dates_sql(currency_alias)
quoted_alias_code = CurrencyRate.connection.quote(currency_alias.alias_code)
quoted_rate_api_code = CurrencyRate.connection.quote(currency_alias.rate_api_code)
<<-EOS
SELECT primary_rates.exchanged_on
FROM currency_rates primary_rates
LEFT JOIN currency_rates aliased_rates
ON aliased_rates.exchanged_on = primary_rates.exchanged_on
AND aliased_rates.code = #{quoted_alias_code}
WHERE primary_rates.code = #{quoted_rate_api_code}
AND aliased_rates.id IS NULL
EOS
end
end
end
|
chuckmersereau/api_practice
|
config/environments/development.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
Rails.application.configure do
# Make it easy to turn on http logger when you want it
if ENV['HTTP_LOGGER']
HttpLogger.log_headers = true
HttpLogger.logger = Logger.new(STDOUT)
HttpLogger.collapse_body_limit = 10_000
HttpLogger.ignore = [/newrelic\.com/]
else
HttpLogger.logger = Logger.new('/dev/null')
end
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Prefer responses to be sent in JSON, so disable Rails error reports by considering requests as remote.
# (consider reverting this when upgrading to Rails 5)
config.consider_all_requests_local = false
# Disable caching.
config.action_controller.perform_caching = false
# config.action_controller.perform_caching = true
config.i18n.fallbacks = true
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
config.assets.digest = false
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.assets.logger = false
config.assets.prefix = '/dev-assets'
# The ngrok utility to tunnel connections to localhost is useful for testing
# the MailChimp webhooks feature
config.action_mailer.default_url_options = {
host: ENV['DEV_NGROK_HOST'].present? ? ENV['DEV_NGROK_HOST'] : 'localhost:3000',
protocol: 'http'
}
config.debug_exception_response_format = :default
config.action_mailer.asset_host = 'http://localhost:3000'
config.action_mailer.delivery_method = :letter_opener
config.action_mailer.preview_path = Rails.root.join('spec', 'mailers', 'previews')
Rails.application.routes.default_url_options[:host] = config.action_mailer.default_url_options[:host]
Rails.application.routes.default_url_options[:protocol] = config.action_mailer.default_url_options[:protocol]
config.middleware.insert_before 0, 'Rack::Cors' do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :delete, :put, :options]
end
end
end
|
chuckmersereau/api_practice
|
app/services/concerns/tnt_import/date_helpers.rb
|
module Concerns
module TntImport
module DateHelpers
private
def parse_date(date_as_string, user)
zone = user&.time_zone ? Time.find_zone(user.time_zone) || Time.zone : Time.zone
zone.parse(date_as_string)
end
end
end
end
|
chuckmersereau/api_practice
|
config/initializers/public_exceptions.rb
|
<reponame>chuckmersereau/api_practice<filename>config/initializers/public_exceptions.rb<gh_stars>0
# This is a monkey patch that changes the format of the Rails default error response body.
#
# When responding to a JSON format request, Rails will by default send errors formatted like:
#
# {
# "status": "404",
# "error": "Not Found"
# }
#
# We want Rails to conform to JSON:API spec, so the error response should look like this:
#
# {
# "errors": [
# {
# "status": "404",
# "title": "Not Found"
# }
# ]
# }
#
# This monkey patch achieves this by altering the behaviour of the ActionDispatch middleware
# to format the body using our ErrorSerializer.
#
# This is handled at the middleware level so that all exceptions will return the correct format,
# not just those inside the Rails app.
#
# (This could also be handled by creating a custom exceptions_app, but the patch was simpler)
module ActionDispatch
class PublicExceptions
private
alias_method :original_render, :render
def render(status, content_type, body)
error_serializer = ErrorSerializer.new(
title: body[:error],
status: status
)
original_render(status, content_type, error_serializer.as_json)
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/contact_referrals.rb
|
<reponame>chuckmersereau/api_practice
FactoryBot.define do
factory :contact_referral do
referred_by { FactoryBot.create(:contact) }
referred_to { FactoryBot.create(:contact) }
end
end
|
chuckmersereau/api_practice
|
app/serializers/person/twitter_account_serializer.rb
|
<gh_stars>0
class Person::TwitterAccountSerializer < ApplicationSerializer
type :twitter_accounts
attributes :created_at,
:primary,
:remote_id,
:screen_name,
:updated_at
end
|
chuckmersereau/api_practice
|
app/services/task/filter/activity_type.rb
|
class Task::Filter::ActivityType < Task::Filter::Base
def execute_query(tasks, filters)
parsed_filters = parse_list(filters[:activity_type])
if parsed_filters.include?('none')
parsed_filters.delete('none')
parsed_filters << ''
return tasks.where('activity_type IS NULL OR activity_type in (?)', parsed_filters)
end
tasks.where(activity_type: parsed_filters)
end
def title
_('Action')
end
def type
'multiselect'
end
def custom_options
[{ name: _('-- None --'), id: 'none' }] +
Task::TASK_ACTIVITIES.collect { |activity_type| { name: _(activity_type), id: activity_type } }
end
end
|
chuckmersereau/api_practice
|
db/migrate/20150212133202_add_source_donor_account_id_to_addresses.rb
|
<filename>db/migrate/20150212133202_add_source_donor_account_id_to_addresses.rb
class AddSourceDonorAccountIdToAddresses < ActiveRecord::Migration
def change
add_column :addresses, :source_donor_account_id, :integer
end
end
|
chuckmersereau/api_practice
|
db/migrate/20121224123025_add_seasonal_to_address.rb
|
<filename>db/migrate/20121224123025_add_seasonal_to_address.rb
class AddSeasonalToAddress < ActiveRecord::Migration
def change
add_column :addresses, :seasonal, :boolean, default: false
add_column :email_addresses, :location, :string, limit: 50
add_column :donor_accounts, :donor_type, :string, limit: 20
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/exports/mailing_controller.rb
|
<reponame>chuckmersereau/api_practice
require 'csv'
class Api::V2::Contacts::Exports::MailingController < Api::V2::Contacts::ExportsController
supports_accept_header_content_types :any
supports_content_types :any
resource_type 'export_logs'
protected
def export_log_type
'Contacts Mailing'
end
def render_csv(filename)
headers['Content-Type'] ||= 'text/csv'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
render text: CsvExport.mailing_addresses(@contacts), filename: filename
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/analytics_spec.rb
|
<filename>spec/acceptance/api/v2/contacts/analytics_spec.rb
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts > Analytics' do
include_context :json_headers
doc_helper = DocumentationHelper.new(resource: [:contacts, :analytics])
# This is required!
# This is the resource's JSONAPI.org `type` attribute to be validated against.
let(:resource_type) { 'contact_analytics' }
# 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(:alternate_account_list) do
create(:account_list).tap do |account_list|
user.account_lists << account_list
end
end
let(:contact_with_anniversary_with_week) do
create(:contact, account_list_id: account_list.id,
status: 'Partner - Financial')
end
let(:person_with_anniversary_this_week) do
create(:person, anniversary_month: Date.current.month,
anniversary_day: Date.current.day)
end
let(:contact_with_birthday_this_week) do
create(:contact, account_list_id: account_list.id,
status: 'Partner - Financial')
end
let(:contact_with_birthday_this_week_but_different_account_list) do
create(:contact, account_list_id: alternate_account_list.id,
status: 'Partner - Financial')
end
let(:person_with_birthday_this_week) do
create(:person, birthday_month: Date.current.month,
birthday_day: Date.current.day)
end
let(:person_with_birthday_this_week_from_different_account_list) do
create(:person, birthday_month: Date.current.month,
birthday_day: Date.current.day)
end
let(:birthday_relationship_data) do
json_response['data']['relationships']['birthdays_this_week']['data']
end
let(:anniversary_relationship_data) do
json_response['data']['relationships']['anniversaries_this_week']['data']
end
before do
contact_with_birthday_this_week
.people << person_with_birthday_this_week
contact_with_birthday_this_week_but_different_account_list
.people << person_with_birthday_this_week_from_different_account_list
contact_with_anniversary_with_week
.people << person_with_anniversary_this_week
end
let(:expected_attribute_keys) do
# list your expected resource keys vertically here (alphabetical please!)
%w(
created_at
first_gift_not_received_count
partners_30_days_late_count
partners_60_days_late_count
partners_90_days_late_count
updated_at
updated_in_db_at
)
end
let(:additional_attribute_keys) do
%w(
relationships
)
end
context 'authorized user' do
before { api_login(user) }
context 'without specifying an `account_list_id`' do
# show
get '/api/v2/contacts/analytics' do
doc_helper.insert_documentation_for(action: :show, context: self)
example doc_helper.title_for(:show), document: doc_helper.document_scope do
explanation doc_helper.description_for(:show)
do_request
check_resource(additional_attribute_keys)
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 200
expect(birthday_relationship_data.count).to eq(2)
expect(anniversary_relationship_data.count).to eq(1)
end
end
end
context 'when specifying an `account_list_id`' do
# show
get '/api/v2/contacts/analytics' do
doc_helper.insert_documentation_for(action: :show, context: self)
example doc_helper.title_for(:show), document: doc_helper.document_scope do
explanation doc_helper.description_for(:show)
do_request filter: { account_list_id: alternate_account_list.id }
check_resource(additional_attribute_keys)
expect(resource_object.keys).to match_array expected_attribute_keys
expect(response_status).to eq 200
expect(birthday_relationship_data.count).to eq(1)
expect(anniversary_relationship_data.count).to eq(0)
end
end
end
end
end
|
chuckmersereau/api_practice
|
app/mailers/account_list_invite_mailer.rb
|
class AccountListInviteMailer < ApplicationMailer
layout 'inky'
def email(invite)
@invite = invite
@message_values = { inviter: @invite.invited_by_user, account: @invite.account_list.name }
if invite.invite_user_as == 'coach'
mail to: invite.recipient_email,
subject: _('You\'ve been invited to be a coach for an account on MPDX'),
template_name: 'coach'
else
mail to: invite.recipient_email,
subject: _('You\'ve been invited to access an account on MPDX'),
template_name: 'user'
end
end
end
|
chuckmersereau/api_practice
|
app/exhibits/address_exhibit.rb
|
<filename>app/exhibits/address_exhibit.rb<gh_stars>0
class AddressExhibit < DisplayCase::Exhibit
def self.applicable_to?(object)
object.class.name == 'Address'
end
def to_s
to_google
end
def to_google
[street, city, state, postal_code, country].select(&:present?).join(', ')
end
def user_friendly_source
case source
when 'DataServer', 'Siebel' then _('Donor system')
when 'GoogleImport' then _('Google import')
when 'GoogleContactsSync' then _('Google sync')
when TntImport::Source then _('Tnt import')
when Address::MANUAL_SOURCE then _('Manual entry')
else source
end
end
def address_change_email_body
donor_info = if source_donor_account.present?
details = { name: source_donor_account.name, account_number: source_donor_account.account_number }
format(_('"%{name}" (donor #%{account_number})'), details)
else
"\"#{addressable.name}\""
end
[
_('Dear Donation Services') + ",\n\n",
format(_('One of my donors, %{donor} has a new current address.'), donor: donor_info) + "\n\n",
_('Please update their address to') + ":\n\n",
_('REPLACE WITH NEW STREET') + "\n",
_('REPLACE WITH NEW CITY, STATE, ZIP') + "\n\n",
_('Thanks!') + "\n\n"
].join
end
end
|
chuckmersereau/api_practice
|
engines/auth/config/routes.rb
|
<reponame>chuckmersereau/api_practice<filename>engines/auth/config/routes.rb
Auth::Engine.routes.draw do
get '/auth/donorhub/callback', to: 'provider/donorhub_accounts#create'
get '/auth/google/callback', to: 'provider/google_accounts#create'
get '/auth/mailchimp/callback', to: 'provider/mail_chimp_accounts#create'
get '/auth/prayer_letters/callback', to: 'provider/prayer_letters_accounts#create'
get '/auth/user/:provider', to: 'user_accounts#create'
get '/auth/failure', to: 'user_accounts#failure'
end
|
chuckmersereau/api_practice
|
spec/services/person/gmail_account_spec.rb
|
require 'rails_helper'
describe Person::GmailAccount do
let(:google_account) { create(:google_account, last_email_sync: Date.today) }
let(:gmail_account) { Person::GmailAccount.new(google_account) }
let(:account_list) { create(:account_list) }
let(:contact) { create(:contact, account_list: account_list) }
let(:person) { create(:person) }
let(:user) { create(:user) }
context '#gmail' do
it 'refreshes the google account token if expired' do
google_account.expires_at = 1.hour.ago
expect(google_account).to receive(:refresh_token!).once
gmail_account.gmail_connection {}
end
end
context '#import_emails' do
let(:recipient_data) { double('recipient', mailbox: 'recipient', host: 'example.com') }
let(:sender_data) { double('sender', mailbox: 'sender', host: 'example.com') }
let(:envelope) { double('envelope', to: [recipient_data], sender: [sender_data]) }
let(:gmail_uid) { double('gmail_uid') }
let(:gmail_imap_struct) { double('gmail_imap_struct', attr: { 'ENVELOPE' => envelope }) }
let(:sent_mailbox) { double }
let(:all_mailbox) { double }
let(:client_conn) { double('client_connection') }
let!(:recipient_email) { create(:email_address, email: '<EMAIL>', person: person) }
let!(:sender_email) { create(:email_address, email: '<EMAIL>', person: person) }
before do
contact.people << person
google_account.person = user
google_account.save
account_list.users << user
allow_any_instance_of(Gmail::Client::XOAuth2).to receive(:mailbox).with('[Gmail]/Sent Mail').and_return(sent_mailbox)
allow_any_instance_of(Gmail::Client::XOAuth2).to receive(:mailbox).with('[Gmail]/All Mail').and_return(all_mailbox)
allow_any_instance_of(Gmail::Client::XOAuth2).to receive(:conn).and_return(client_conn)
allow(client_conn).to receive(:uid_fetch).with([gmail_uid], kind_of(Array)).and_return([gmail_imap_struct])
allow(client_conn).to receive(:uid_fetch).with([], kind_of(Array)).and_return([])
end
it 'records a sent email' do
expect(sent_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([gmail_uid])
expect(all_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([])
expect(gmail_account).to receive(:record_email).once
gmail_account.import_emails(account_list)
end
it 'records a received email' do
expect(sent_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([])
expect(all_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([gmail_uid])
expect(gmail_account).to receive(:record_email).once
gmail_account.import_emails(account_list)
end
it 'does not record a blacklisted received email' do
expect(sent_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([])
expect(all_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([gmail_uid])
expect(gmail_account).to_not receive(:record_email)
gmail_account.import_emails(account_list, [sender_email.email])
end
it 'does not record a blacklisted sent email' do
expect(sent_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([gmail_uid])
expect(all_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([])
expect(gmail_account).to_not receive(:record_email)
gmail_account.import_emails(account_list, [recipient_email.email])
end
it 'does not record blacklisted email from a specific domain' do
expect(sent_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([])
expect(all_mailbox).to receive(:fetch_uids).with(on: google_account.last_email_sync.to_date).and_return([gmail_uid])
expect(gmail_account).to_not receive(:record_email)
gmail_account.import_emails(account_list, ['*<EMAIL>'])
end
end
context '#record_email' do
let(:gmail_message) { mock_gmail_message('message body') }
let(:google_email) { build(:google_email, google_email_id: gmail_message.msg_id, google_account: google_account) }
def mock_gmail_message(body)
double(message: double(multipart?: false, body: double(decoded: body)),
envelope: double(date: Time.zone.now, message_id: '1'),
subject: 'subject', msg_id: 1)
end
it 'creates a completed task' do
expect do
expect do
gmail_account.record_email(gmail_message, account_list.id, contact.id, person.id, 'Done')
end.to change(Task, :count).by(1)
end.to change(ActivityComment, :count).by(1)
task = Task.last
expect(task.subject).to eq('subject')
expect(task.completed).to eq(true)
expect(task.completed_at.to_s(:db)).to eq(gmail_message.envelope.date.to_s(:db))
expect(task.result).to eq('Done')
end
it "creates a task even if the email doesn't have a subject" do
expect(gmail_message).to receive(:subject).and_return('')
task = gmail_account.record_email(gmail_message, account_list.id, contact.id, person.id, 'Done')
expect(task.subject).to eq('No Subject')
end
it 'truncates the subject if the subject is more than 2000 chars' do
expect(gmail_message).to receive(:subject).once.and_return('x' * 2001)
task = gmail_account.record_email(gmail_message, account_list.id, contact.id, person.id, 'Done')
expect(task.subject).to eq('x' * 2000)
end
it "doesn't create a duplicate task" do
google_email.save
task = create(:task, account_list: account_list, remote_id: gmail_message.envelope.message_id, source: 'gmail')
contact.tasks << task
create(:google_email_activity, google_email: google_email, activity: task)
expect do
gmail_account.record_email(gmail_message, account_list.id, contact.id, person.id, 'Done')
end.not_to change(Task, :count)
end
it 'creates a google_email' do
expect do
gmail_account.record_email(gmail_message, account_list.id, contact.id, person.id, 'Done')
end.to change(GoogleEmail, :count).by(1)
task = GoogleEmail.last
expect(task.google_email_id).to eq(gmail_message.msg_id)
end
it "doesn't create a duplicate google_email" do
google_email.save
expect do
gmail_account.record_email(gmail_message, account_list.id, contact.id, person.id, 'Done')
end.not_to change(GoogleEmail, :count)
end
it 'handles messages with null bytes' do
expect do
gmail_account.record_email(mock_gmail_message("\0null\0!"), account_list.id, contact.id, person.id, 'Done')
end.to change(Task, :count).by(1)
expect(Task.last.comments.first.body).to eq 'null!'
end
end
end
|
chuckmersereau/api_practice
|
app/services/contact/suggested_changes_updater.rb
|
class Contact::SuggestedChangesUpdater
attr_reader :contact
def initialize(contact:)
@contact = contact
end
def update_status_suggestions
return if status_confirmed_recently?
build_suggested_changes
contact.update_columns(updates)
end
private
attr_accessor :suggested_changes
private(*delegate(:suggested_pledge_frequency,
:suggested_pledge_amount,
:suggested_pledge_currency,
:suggested_status,
:contact_has_stopped_giving?,
to: :status_suggester))
def status_suggester
@status_suggester ||= Contact::StatusSuggester.new(contact: contact)
end
def updates
{
suggested_changes: suggested_changes,
status_valid: suggested_changes.blank?
}
end
def status_confirmed_recently?
contact.status_confirmed_at && contact.status_confirmed_at > 1.year.ago
end
def build_suggested_changes
self.suggested_changes = contact.suggested_changes || {}
if contact_has_stopped_giving?
load_suggested_attribute(:pledge_frequency, nil)
load_suggested_attribute(:pledge_amount, nil)
load_suggested_attribute(:pledge_currency, nil)
else
load_suggested_attribute(:pledge_frequency, suggested_pledge_frequency)
load_suggested_attribute(:pledge_amount, suggested_pledge_amount)
load_suggested_attribute(:pledge_currency, suggested_pledge_currency)
end
load_suggested_attribute(:status, suggested_status)
# Don't suggest nil for certain attributes.
[:status, :pledge_currency].each do |attribute|
suggested_changes.delete(attribute) if suggested_changes[attribute].blank?
end
# nil and 0 are equivalent for certain attributes.
[:pledge_frequency, :pledge_amount].each do |attribute|
suggested_changes.delete(attribute) if [0, nil].include?(suggested_changes[attribute]) && [0, nil].include?(@contact.send(attribute))
end
end
def load_suggested_attribute(suggested_change_attribute, suggested_change_value)
if contact.send(suggested_change_attribute) != suggested_change_value
suggested_changes[suggested_change_attribute] = suggested_change_value
else
suggested_changes.delete(suggested_change_attribute)
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/account_lists/notifications_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Account Lists > Notifications' do
include_context :json_headers
documentation_scope = :account_lists_api_notifications
let(:resource_type) { 'notifications' }
let!(:user) { create(:user_with_full_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:contact) { create(:contact, account_list: account_list) }
let!(:notifications) { create_list(:notification, 2, contact: contact) }
let(:notification) { notifications.first }
let(:id) { notification.id }
let(:donation) { create(:donation) }
let(:new_notification) do
attributes_for(:notification)
.reject { |attr| attr.to_s.end_with?('_id') }
.merge(updated_in_db_at: notification.updated_at)
end
let(:form_data) do
build_data(new_notification, relationships: relationships)
end
let(:relationships) do
{
contact: {
data: {
type: 'contacts',
id: contact.id
}
},
donation: {
data: {
type: 'donations',
id: donation.id
}
},
notification_type: {
data: {
type: 'notification_types',
id: notification.notification_type.id
}
}
}
end
let(:resource_attributes) do
%w(
cleared
created_at
event_date
updated_at
updated_in_db_at
)
end
let(:resource_associations) do
%w(
contact
donation
notification_type
)
end
context 'authorized user' do
before { api_login(user) }
get '/api/v2/account_lists/:account_list_id/notifications' do
parameter 'account_list_id', 'Account List ID', required: true
response_field 'data', 'Data', type: 'Array[Object]'
example 'Notification [LIST]', document: documentation_scope do
explanation 'List of Notifications associated with the Account List'
do_request
check_collection_resource(2, ['relationships'])
expect(response_status).to eq 200
end
end
get '/api/v2/account_lists/:account_list_id/notifications/:id' do
with_options scope: [:data, :attributes] do
response_field 'cleared', 'Cleared', type: 'Boolean'
response_field 'contact_id', 'Contact ID', type: 'Number'
response_field 'created_at', 'Created At', type: 'String'
response_field 'donation_id', 'Donation ID', type: 'Number'
response_field 'event_date', 'Event Date', type: 'String'
response_field 'notification_type_id', 'Notification Type 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 'Notification [GET]', document: documentation_scope do
explanation 'The Account List Notification with the given ID'
do_request
check_resource(['relationships'])
expect(response_status).to eq 200
end
end
post '/api/v2/account_lists/:account_list_id/notifications' do
with_options scope: [:data, :attributes] do
parameter 'cleared', 'Cleared'
parameter 'contact_id', 'Contact ID'
parameter 'donation_id', 'Donation ID'
parameter 'event_date', 'Event Date'
parameter 'notification_type_id', 'Notification Type ID'
end
example 'Notification [CREATE]', document: documentation_scope do
explanation 'Creates a new Notification associated with the Account List'
do_request data: form_data
expect(response_status).to eq 201
end
end
put '/api/v2/account_lists/:account_list_id/notifications/:id' do
with_options scope: [:data, :attributes] do
parameter 'cleared', 'Cleared'
parameter 'contact_id', 'Contact ID'
parameter 'donation_id', 'Donation ID'
parameter 'event_date', 'Event Date'
parameter 'notification_type_id', 'Notification Type ID'
end
example 'Notification [UPDATE]', document: documentation_scope do
explanation 'Updates the Account List Notification with the given ID'
do_request data: form_data
expect(response_status).to eq 200
end
end
delete '/api/v2/account_lists/:account_list_id/notifications/:id' do
parameter 'account_list_id', 'Account List ID', required: true
parameter 'id', 'ID', required: true
example 'Notification [DELETE]', document: documentation_scope do
explanation 'Deletes the Account List Notification with the given ID'
do_request
expect(response_status).to eq 204
end
end
end
end
|
chuckmersereau/api_practice
|
spec/services/expected_totals_report/possible_donations_spec.rb
|
require 'rails_helper'
describe ExpectedTotalsReport::PossibleDonations do
subject { described_class.new(account_list: account_list) }
let(:account_list) { create(:account_list) }
let(:designation_account_1) { create(:designation_account) }
let(:designation_account_2) { create(:designation_account) }
let(:donor_account_1) { create(:donor_account) }
let(:donor_account_2) { create(:donor_account) }
let(:contact_1) do
create(:contact, account_list: account_list, pledge_amount: 2,
pledge_currency: 'EUR')
end
let(:contact_2) do
create(:contact, account_list: account_list, pledge_amount: 4,
pledge_currency: 'CAD')
end
let!(:donation_1) do
create(:donation, donor_account: donor_account_1,
designation_account: designation_account_1)
end
let!(:donation_2) do
create(:donation, donor_account: donor_account_2,
designation_account: designation_account_2)
end
before do
account_list.designation_accounts << designation_account_1
account_list.designation_accounts << designation_account_2
contact_1.donor_accounts << donor_account_1
contact_2.donor_accounts << donor_account_2
end
describe '#donation_rows' do
subject { described_class.new(account_list: account_list).donation_rows }
let(:likely_donation) do
instance_double(
ExpectedTotalsReport::LikelyDonation,
likely_more: likely_more,
received_this_month: received_this_month
)
end
before do
allow(ExpectedTotalsReport::LikelyDonation).to receive(:new) { likely_donation }
end
context 'likely amount is more than zero' do
let(:likely_more) { 0 }
let(:received_this_month) { 0 }
it 'reports unlikely donations' do
expect(subject.size).to eq 2
expect(subject).to contain_exactly(
{
type: 'unlikely',
contact: contact_1,
donation_amount: 2.0,
donation_currency: contact_1.pledge_currency
},
type: 'unlikely',
contact: contact_2,
donation_amount: 4.0,
donation_currency: contact_2.pledge_currency
)
end
context 'designation_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { designation_account_id: designation_account_1.id }
).donation_rows
end
it 'reports unlikely donations' do
expect(subject.size).to eq 1
expect(subject).to contain_exactly(
type: 'unlikely',
contact: contact_1,
donation_amount: 2.0,
donation_currency: contact_1.pledge_currency
)
end
end
context 'donor_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { donor_account_id: donor_account_2.id }
).donation_rows
end
it 'reports unlikely donations' do
expect(subject.size).to eq 1
expect(subject).to contain_exactly(
type: 'unlikely',
contact: contact_2,
donation_amount: 4.0,
donation_currency: contact_2.pledge_currency
)
end
end
end
context 'likely amount is more than zero' do
let(:likely_more) { 1 }
let(:received_this_month) { 0 }
it 'reports likely donations' do
expect(subject.size).to eq 2
expect(subject).to contain_exactly(
{
type: 'likely',
contact: contact_1,
donation_amount: 1.0,
donation_currency: contact_1.pledge_currency
},
type: 'likely',
contact: contact_2,
donation_amount: 1.0,
donation_currency: contact_2.pledge_currency
)
end
context 'designation_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { designation_account_id: designation_account_1.id }
).donation_rows
end
it 'reports likely donations' do
expect(subject.size).to eq 1
expect(subject).to contain_exactly(
type: 'likely',
contact: contact_1,
donation_amount: 1.0,
donation_currency: contact_1.pledge_currency
)
end
end
context 'donor_account_id present in filter_params' do
subject do
described_class.new(
account_list: account_list,
filter_params: { donor_account_id: donor_account_2.id }
).donation_rows
end
it 'reports unlikely donations' do
expect(subject.size).to eq 1
expect(subject).to contain_exactly(
type: 'likely',
contact: contact_2,
donation_amount: 1.0,
donation_currency: contact_2.pledge_currency
)
end
end
end
context 'donation already received this month' do
let(:likely_more) { 0 }
let(:received_this_month) { 2 }
it 'reports nothing' do
expect(subject).to be_empty
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/reports/activity_results.rb
|
class Reports::ActivityResults < ActiveModelSerializers::Model
FIELDS = ::Task::TASK_ACTIVITIES.map do |activity_type|
scope = activity_type.parameterize.underscore.to_sym
::Activity::REPORT_STATES.map { |state| "#{state}_#{scope}".to_sym }
end.flatten.freeze
attr_accessor :account_list
attr_writer :filter_params
DEFAULT_RANGE = '4w'.freeze
def periods_data
@periods_data ||= periods.map do |period|
Reports::ActivityResultsPeriod.new(account_list: account_list,
start_date: period[:start_date],
end_date: period[:end_date])
end
end
def meta(fields = {})
results_period_fields = fields['reports_activity_results_periods']
size = periods_data.count
FIELDS.each_with_object({}) do |key, hash|
next unless results_period_fields.nil? || results_period_fields.include?(key.to_s)
hash["average_#{key}"] = (periods_data.sum(&key) / size.to_d).round
end
end
def filter_params
@filter_params || {}
end
def end_date
filter_params[:end_date].presence || Date.today
end
def range
filter_params[:range].presence || DEFAULT_RANGE
end
private
def periods
Array.new(times) do |i|
period_end_date = end_date - i.send(time_unit)
{
start_date: period_end_date.send("beginning_of_#{time_unit}").beginning_of_day,
end_date: period_end_date.send("end_of_#{time_unit}").end_of_day
}
end
end
def times
range.to_i
end
def time_unit
case range[-1]
when 'd'
:day
when 'w'
:week
when 'm'
:month
when 'y'
:year
end
end
def valid_range
range =~ /^\d+[dwmy]$/
end
end
|
chuckmersereau/api_practice
|
app/mailers/mail_chimp_mailer.rb
|
class MailChimpMailer < ApplicationMailer
layout 'inky'
def invalid_email_addresses(account_list, user, emails_with_person_ids)
@account_list = account_list
@user = user
@emails_with_people = emails_with_person_ids.transform_values do |person_ids|
@account_list.people.where(id: person_ids)
end
mail to: user.email_address,
subject: _('MPDX was unable to sync some email addresses to MailChimp')
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/metro_area.rb
|
<reponame>chuckmersereau/api_practice<filename>app/services/contact/filter/metro_area.rb
class Contact::Filter::MetroArea < Contact::Filter::Base
def execute_query(contacts, filters)
metro_area_filters = parse_list(filters[:metro_area])
metro_area_filters << nil if metro_area_filters.delete('none')
contacts.where('addresses.metro_area' => metro_area_filters,
'addresses.historic' => filters[:address_historic] == 'true')
.joins(:addresses)
end
def title
_('Metro Area')
end
def parent
_('Contact Location')
end
def type
'multiselect'
end
def custom_options
account_list_areas = account_lists.collect(&:metro_areas)
.flatten
.uniq
.reject(&:blank?)
.map { |s| { name: _(s), id: s } }
[{ name: _('-- None --'), id: 'none' }] + account_list_areas
end
end
|
chuckmersereau/api_practice
|
spec/services/csv_file_constants_reader_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe CsvFileConstantsReader do
let(:file_path) { Rails.root.join('spec/fixtures/sample_csv_with_custom_headers.csv') }
let(:service) { CsvFileConstantsReader.new(file_path) }
it 'initializes' do
expect(service).to be_a CsvFileConstantsReader
end
describe '#constants' do
it 'returns a correct hash of sets' do
expect(service.constants).to eq(
'greeting' => Set.new(['Hi <NAME> Jane', 'Hello!', '']),
'status' => Set.new(['Praying', 'Praying and giving']),
'amount' => Set.new(['50', '10', '']),
'frequency' => Set.new(['Monthly', '']),
'newsletter' => Set.new(['Both']),
'currency' => Set.new(['CAD', '']),
'skip' => Set.new(['No', 'Yes', '']),
'appeals' => Set.new(%w(Yes No)),
'likely_giver' => Set.new(%w(Yes No))
)
end
end
end
|
chuckmersereau/api_practice
|
spec/services/csv_row_contact_builder_spec.rb
|
require 'rails_helper'
describe CsvRowContactBuilder do
let!(:import) { create(:csv_import_custom_headers, tags: 'csv, test', in_preview: true) }
let!(:csv_row) { CSV.new(File.open(import.file_path).read, headers: :first_row).first }
let!(:existing_contact) { create(:contact, name: '<NAME>', account_list: import.account_list) }
let(:file_headers_mappings) do
{
'church' => 'church',
'city' => 'city',
'pledge_amount' => 'amount',
'pledge_currency' => 'currency',
'pledge_frequency' => 'frequency',
'contact_name' => 'fname',
'country' => 'country',
'email_1' => 'email_address',
'first_name' => 'fname',
'full_name' => 'fullname',
'greeting' => 'greeting',
'envelope_greeting' => 'mailing_greeting',
'last_name' => 'lname',
'likely_to_give' => 'likely_giver',
'metro_area' => 'metro',
'newsletter' => 'newsletter',
'notes' => 'extra_notes',
'phone_1' => 'phone',
'referred_by' => 'referred_by',
'region' => 'region',
'send_appeals' => 'appeals',
'spouse_email' => 'spouse_email_address',
'spouse_first_name' => 'spouse_fname',
'spouse_last_name' => 'spouse_lname',
'spouse_phone' => 'spouse_phone_number',
'state' => 'province',
'status' => 'status',
'street' => 'street',
'tags' => 'tags',
'website' => 'website',
'zip' => 'zip_code'
}
end
let(:file_constants_mappings) do
{
'pledge_currency' => [
{ 'id' => 'CAD', 'values' => ['CAD'] },
{ 'id' => 'USD', 'values' => [''] }
],
'pledge_frequency' => [
{ 'id' => 'Monthly', 'values' => ['Monthly'] },
{ 'id' => '', 'values' => [''] }
],
'likely_to_give' => [
{ 'id' => 'Most Likely', 'values' => ['Yes'] },
{ 'id' => 'Least Likely', 'values' => ['No'] }
],
'newsletter' => [
{ 'id' => 'Both', 'values' => ['Both'] }
],
'send_appeals' => [
{ 'id' => true, 'values' => ['Yes'] },
{ 'id' => false, 'values' => ['No'] }
],
'status' => [
{ 'id' => 'Partner - Financial', 'values' => ['Praying and giving'] },
{ 'id' => 'Partner - Pray', 'values' => ['Praying'] }
]
}
end
subject { CsvRowContactBuilder.new(import: import, csv_row: csv_row) }
before do
CsvImport.new(import).update_cached_file_data
import.file_headers_mappings = file_headers_mappings
import.file_constants_mappings = file_constants_mappings
stub_smarty_streets
end
describe '#build' do
it 'builds a contact with expected attributes' do
contact = subject.build
expect(contact).to be_a Contact
expect(contact.account_list).to eq(import.account_list)
expect(contact.name).to eq('<NAME>')
expect(contact.church_name).to eq('Westside Baptist Church')
expect(contact.greeting).to eq('Hi John and Jane')
expect(contact.envelope_greeting).to eq('Doe family')
expect(contact.status).to eq('Partner - Pray')
expect(contact.pledge_amount).to eq(50)
expect(contact.pledge_currency).to eq('CAD')
expect(contact.notes).to eq('test notes')
expect(contact.pledge_frequency).to eq(1)
expect(contact.send_newsletter).to eq('Both')
expect(contact.tag_list.sort).to eq(%w(christmas-card csv family test))
expect(contact.likely_to_give).to eq('Most Likely')
expect(contact.no_appeals).to be(false)
expect(contact.website).to eq('http://www.john.doe')
address = contact.mailing_address
expect(address.street).to eq('1 Example Ave, Apt 6')
expect(address.city).to eq('Sample City')
expect(address.state).to eq('IL')
expect(address.postal_code).to eq('60201')
expect(address.country).to eq('United States')
expect(address.metro_area).to eq('metro')
expect(address.region).to eq('region')
expect(address.primary_mailing_address).to be(true)
person = contact.primary_person
expect(person.first_name).to eq('John')
expect(person.last_name).to eq('Doe')
expect(person.email_addresses.size).to eq(1)
expect(person.email_addresses.first.email).to eq('<EMAIL>')
expect(person.phone_numbers.size).to eq(1)
expect(person.phone_numbers.first.number.in?(['(213) 222-3333', '+12132223333'])).to be(true)
spouse = contact.spouse
expect(spouse.first_name).to eq('Jane')
expect(spouse.last_name).to eq('Doe')
expect(spouse.email_addresses.size).to eq(1)
expect(spouse.email_addresses.first.email).to eq('<EMAIL>')
expect(spouse.phone_numbers.size).to eq(1)
expect(spouse.phone_numbers.first.number.in?(['(407) 555-6666', '+14075556666'])).to be(true)
end
context 'referred_by cannot be found' do
it 'adds referred_by to contact notes and tag' do
Contact.delete_all
contact = subject.build
expect(contact.contact_referrals_to_me.size).to eq(0)
expect(contact.notes).to include('Referred by: <NAME>')
expect(contact.tag_list).to include('missing csv referred by')
end
end
end
describe 'name parsing' do
context 'all name fields are specified' do
before do
%w(full_name first_name last_name spouse_first_name spouse_last_name).each do |required_key|
raise unless import.file_headers_mappings.keys.include?(required_key)
end
end
it 'builds names' do
contact = subject.build
expect(contact.name).to eq('<NAME>')
person = contact.primary_person
expect(person.first_name).to eq('John')
expect(person.last_name).to eq('Doe')
spouse = contact.spouse
expect(spouse.first_name).to eq('Jane')
expect(spouse.last_name).to eq('Doe')
end
end
context 'full_name field is not specified, but other name fields are' do
before do
import.file_headers_mappings.delete('full_name')
end
it 'builds names' do
contact = subject.build
expect(contact.name).to eq('<NAME>')
person = contact.primary_person
expect(person.first_name).to eq('John')
expect(person.last_name).to eq('Doe')
spouse = contact.spouse
expect(spouse.first_name).to eq('Jane')
expect(spouse.last_name).to eq('Doe')
end
end
context 'full_name field is specified, but other name fields are not' do
before do
import.file_headers_mappings.delete('first_name')
import.file_headers_mappings.delete('last_name')
import.file_headers_mappings.delete('spouse_first_name')
import.file_headers_mappings.delete('spouse_last_name')
end
it 'builds names' do
contact = subject.build
expect(contact.name).to eq('<NAME> and Janey')
person = contact.primary_person
expect(person.first_name).to eq('Johnny')
expect(person.last_name).to eq('Doey')
spouse = contact.spouse
expect(spouse.first_name).to eq('Janey')
expect(spouse.last_name).to eq('Doey')
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170824151005_add_last_download_attempt_at_to_person_organization_accounts.rb
|
<reponame>chuckmersereau/api_practice<filename>db/migrate/20170824151005_add_last_download_attempt_at_to_person_organization_accounts.rb
class AddLastDownloadAttemptAtToPersonOrganizationAccounts < ActiveRecord::Migration
def change
add_column :person_organization_accounts, :last_download_attempt_at, :datetime
add_index :person_organization_accounts, :last_download_attempt_at
end
end
|
chuckmersereau/api_practice
|
spec/services/tnt_import_spec.rb
|
<filename>spec/services/tnt_import_spec.rb
require 'rails_helper'
describe TntImport do
let(:xml) { TntImport::XmlReader.new(tnt_import).parsed_xml }
let(:user) { create(:user) }
let(:tnt_import) { create(:tnt_import, override: true, user: user) }
let(:import) { TntImport.new(tnt_import) }
let(:contact) { create(:contact) }
let(:contact_rows) { xml.tables['Contact'] }
let(:task_rows) { xml.tables['Task'] }
let(:task_contact_rows) { xml.tables['TaskContact'] }
let(:history_rows) { xml.tables['History'] }
let(:history_contact_rows) { xml.tables['HistoryContact'] }
let(:property_rows) { xml.tables['Property'] }
before do
stub_smarty_streets
user.preferences['time_zone'] = ActiveSupport::TimeZone.all.last
user.save
end
describe '#xml' do
it 'returns an Xml object' do
import = TntImport.new(create(:tnt_import))
expect(import.xml).to be_a TntImport::Xml
expect(import.xml.tables.keys).to eq %w(Appeal Contact Designation Group GroupContact History HistoryContact
HistoryResult LikelyToGive Login LoginProfile
LoginProfileDesignation PendingAction Picture Property Region
RegionLocation Task TaskContact TaskReason TaskType Currency)
expect(import.xml.version).to eq 3.0
end
end
context '#import contacts with multiple donor accounts in multiple existing contacts' do
before do
account_list = create(:account_list)
designation_profile = create(:designation_profile)
organization = org_for_code('CCC-USA')
designation_profile.organization = organization
account_list.designation_profiles << designation_profile
john = create(:contact, name: '<NAME>')
john_donor = create(:donor_account, account_number: '444444444')
john.donor_accounts << john_donor
organization.donor_accounts << john_donor
account_list.contacts << john
john_and_jane = create(:contact, name: '<NAME> and Jane')
john_and_jane_donor = create(:donor_account, account_number: '555555555')
john_and_jane.donor_accounts << john_and_jane_donor
organization.donor_accounts << john_and_jane_donor
account_list.contacts << john_and_jane
@import = create(:tnt_import_multi_donor_accounts, account_list: account_list)
@tnt_import = TntImport.new(@import)
end
it 'imports and merges existing contacts by donor accounts if set to override' do
@import.update_column(:override, true)
@tnt_import.send(:import_contacts)
expect(Contact.all.count).to eq(1)
end
it 'imports and merges existing contacts by donor accounts if not set to override' do
@import.update_column(:override, false)
@tnt_import.send(:import_contacts)
expect(Contact.all.count).to eq(1)
end
end
context '#import_contacts' do
it 'creates a new contact from a non-donor' do
import = TntImport.new(create(:tnt_import_non_donor))
expect do
import.send(:import_contacts)
end.to change(Contact, :count).by(1)
end
it "doesn't create duplicate people when importing the same list twice" do
import = TntImport.new(create(:tnt_import_non_donor))
import.send(:import_contacts)
expect do
import.send(:import_contacts)
end.not_to change(Person, :count)
end
it 'associates referrals and imports no_appeals field' do
expect do
import.import
end.to change(ContactReferral, :count).by(1)
expect(Contact.order(:created_at).first.no_appeals).to be true
end
context 'referred by contact cannot be found' do
it 'adds the referred by name into the contact notes' do
expected_note = "call for amount \n \nReferred by: Steve and <NAME>"
expect do
import.import
end.to change { Contact.order(:created_at).last&.notes }.from(nil).to(expected_note)
end
it 'adds a tag so that the contact can be found' do
expect do
import.import
end.to change { Contact.order(:created_at).last&.tag_list }.from(nil).to(['missing tnt referred by'])
end
end
context 'updating an existing contact' do
before do
@account_list = create(:account_list)
tnt_import.account_list = @account_list
tnt_import.save
TntImport.new(tnt_import)
contact.tnt_id = 1_620_699_916
contact.status = 'Ask in Future'
contact.account_list = @account_list
contact.save
end
it 'updates an existing contact' do
expect do
import.send(:import_contacts)
end.to change { contact.reload.status }.from('Ask in Future').to('Partner - Pray')
end
describe 'primary address behavior' do
def import_with_addresses
@address = create(:address, primary_mailing_address: true)
contact.addresses << @address
contact.save
expect(contact.addresses.where(primary_mailing_address: true).count).to eq(1)
expect do
import.send(:import_contacts)
end.not_to change { contact.addresses.where(primary_mailing_address: true).count }
expect do # make sure it survives a second import
import.send(:import_contacts)
end.not_to change { contact.addresses.where(primary_mailing_address: true).count }
end
it 'changes the primary address of an existing contact' do
import_with_addresses
expect(@address.reload.primary_mailing_address).to be false
end
it 'does not change the primary address of an existing contact if not override' do
tnt_import.update_column(:override, false)
import_with_addresses
expect(@address.reload.primary_mailing_address).to be true
end
end
describe 'primary email behavior' do
before do
@person = create(:person, first_name: 'Bob', last_name: 'Doe')
@person.email_address = { email: '<EMAIL>', primary: true }
@person.save
@contact = create(:contact, account_list: @account_list, name: 'Doe, Bob and Dawn')
@contact.people << @person
@email_before_import = @person.email_addresses.first
tnt_import.update_column(:override, false)
end
it 'changes the primary email of an existing contact if override' do
tnt_import.update_column(:override, true)
import.send(:import_contacts)
expect(@email_before_import.reload.primary).to be false
end
it 'does not change the primary email of an existing contact if not override' do
import.send(:import_contacts)
expect(@email_before_import.reload.primary).to be true
end
it 'sets the primary email if override not set and no primary was set for the person' do
@email_before_import.update_column(:primary, false)
import.send(:import_contacts)
expect(@person.email_addresses.where(primary: true).count).to eq(1)
expect(@person.email_addresses.where(primary: true).first.email).to eq('<EMAIL>')
end
it 'sets the primary email if override not set and no person existed' do
@contact.destroy
import.send(:import_contacts)
person = Person.find_by(first_name: 'Bob')
expect(person.email_addresses.where(primary: true).count).to eq(1)
expect(person.email_addresses.where(primary: true).first.email).to eq('<EMAIL>')
end
end
describe 'primary phone behavior' do
before do
@person = create(:person, first_name: 'Bob', last_name: 'Doe')
@person.phone_number = { number: '212-456-7890', primary: true }
@person.save
@contact = create(:contact, account_list: @account_list, name: 'Doe, Bob and Dawn')
@contact.people << @person
@phone_before_import = @person.phone_numbers.first
tnt_import.update_column(:override, false)
end
it 'changes the primary phone of an existing contact if override' do
tnt_import.update_column(:override, true)
import.send(:import_contacts)
expect(@phone_before_import.reload.primary).to be false
end
it 'does not change the primary phone of an existing contact if not override' do
import.send(:import_contacts)
expect(@phone_before_import.reload.primary).to be true
end
it 'sets the primary phone if override not set and no primary was set for the person' do
@phone_before_import.update_column(:primary, false)
import.send(:import_contacts)
expect(@person.phone_numbers.where(primary: true).count).to eq(1)
expect(@person.phone_numbers.where(primary: true).first.number).to eq('+12123337890')
end
it 'sets the primary phone if override not set and no person existed' do
@contact.destroy
import.send(:import_contacts)
person = Person.find_by(first_name: 'Bob')
expect(person.phone_numbers.where(primary: true).count).to eq(1)
expect(person.phone_numbers.where(primary: true).first.number).to eq('+12123337890')
end
end
describe 'spouse/primary person phone import' do
it 'puts home phone in both, but only primary or spouse phones in individual people' do
john = create(:person, first_name: 'John', last_name: 'Smith')
jane = create(:person, first_name: 'Jane', last_name: 'Smith')
contact.people << john
contact.people << jane
import.send(:import_contacts)
john_numbers = john.reload.phone_numbers.pluck(:number)
jane_numbers = jane.reload.phone_numbers.pluck(:number)
expect(john_numbers.size).to eq(3)
expect(john_numbers).to include('+15155551234') # home
expect(john_numbers).to include('+12132111111')
expect(john_numbers).to include('+15155559771;301')
expect(jane_numbers.size).to eq(2)
expect(jane_numbers).to include('+15155551234') # home
expect(jane_numbers).to include('+12122222222')
end
end
end
it 'does not import very old dates' do
import.send(:import_contacts)
contact = Contact.first
expect(contact.next_ask).not_to eq Date.parse('1899-12-30')
expect(contact.pledge_start_date).not_to eq Date.parse('1899-12-30')
expect(contact.last_activity).not_to eq Date.parse('1899-12-30')
expect(contact.last_appointment).not_to eq Date.parse('1899-12-30')
expect(contact.last_letter).not_to eq Date.parse('1899-12-30')
expect(contact.last_phone_call).not_to eq Date.parse('1899-12-30')
expect(contact.last_pre_call).not_to eq Date.parse('1899-12-30')
expect(contact.last_thank).not_to eq Date.parse('1899-12-30')
end
it 'imports a contact even if their donor account had no name' do
org = create(:organization)
create(:donor_account, account_number: '413518908', organization: org, name: nil)
create(:designation_profile, account_list: tnt_import.account_list, organization: org)
expect do
import.send(:import_contacts)
end.to change(Contact, :count).by(2)
end
it 'imports a contact people details even if the contact is not a donor' do
import = TntImport.new(create(:tnt_import_non_donor))
expect do
import.send(:import_contacts)
end.to change(Person, :count).by(1)
end
it 'matches an existing contact with leading zeros in their donor account' do
donor_account = create(:donor_account, account_number: '000139111', name: nil)
organization = org_for_code('CCC-USA')
organization.donor_accounts << donor_account
organization.save
contact.donor_accounts << donor_account
contact.save
account_list = build(:account_list)
account_list.designation_profiles << create(:designation_profile, organization: organization)
account_list.contacts << contact
account_list.save
import = TntImport.new(create(:tnt_import_short_donor_code, account_list: account_list))
import.send(:import_contacts)
# Should match existing contact based on the donor account with leading zeros
expect(DonorAccount.all.count).to eq(1)
expect(Contact.all.count).to eq(1)
# The donor account name should get set to the contact name if it was nil
expect(donor_account.reload.name).to eq '<NAME> and Jane'
end
end
context '#import_tasks' do
let(:contacts) do
xml.tables['TaskContact'].map do |row|
create(:contact, tnt_id: row['ContactID'])
end
end
let(:contact_ids) { Hash[contacts.map { |c| [c.tnt_id.to_s, c.id] }] }
it 'creates a new task' do
expect do
new_tasks = import.send(:import_tasks, contact_ids)
expect(new_tasks.first.remote_id).to eq('-1918558789')
end.to change(Task, :count).by(1)
end
it 'sets start_at' do
new_tasks = import.send(:import_tasks, contact_ids)
expect(new_tasks.first.start_at).to eq(tnt_import.user.time_zone.parse('2006-09-09 16:30:00'))
end
it 'updates an existing task' do
create(:task, source: 'tnt', remote_id: task_rows.first['id'], account_list: tnt_import.account_list)
expect do
import.send(:import_tasks)
end.not_to change(Task, :count)
end
it 'associates a contact with the task' do
expect do
import.send(:import_tasks, task_contact_rows.first['ContactID'] => contact.id)
end.to change(ActivityContact, :count).by(1)
end
it 'adds notes as a task comment' do
task = create(:task, source: 'tnt', remote_id: task_rows.first['id'], account_list: tnt_import.account_list)
import.send(:import_tasks, contact_ids)
expect(task.comments.first.body).to eq('Notes')
end
it 'does not add duplicate comments' do
task = create(:task, source: 'tnt', remote_id: task_rows.first['id'], account_list: tnt_import.account_list)
task.comments.create!(body: 'Notes')
import.send(:import_tasks)
expect(task.comments.count).to eq(1)
end
it 'sets the task as complete' do
expect(TntImport::TntCodes).to receive(:task_status_completed?).and_return(true)
new_tasks = import.send(:import_tasks, contact_ids)
expect(new_tasks.first.completed).to eq(true)
end
end
context '#import groups' do
it 'imports groups as tags' do
account_list = build(:account_list)
import = TntImport.new(create(:tnt_import_groups, account_list: account_list))
import.send(:import_contacts)
expect(Contact.all.count).to eq(1)
contact = Contact.all.first
expect(contact.tag_list.sort).to eq(%w(category-1-comma group-with-dave-comma testers))
end
end
context '#import_appeals' do
def test_appeal_import(import)
account_list = import.account_list
account_list.users << create(:user)
@offline_org = create(:offline_org)
account_list.users.first.organization_accounts << create(:organization_account, organization: @offline_org)
tnt_import = TntImport.new(import)
expect do
tnt_import.import
end.to change(Appeal, :count).from(0).to(1)
appeal = Appeal.first
expect(appeal.name).to eq('CSU')
expect(appeal.created_at).to eq(Time.zone.local(2005, 5, 21, 12, 56, 40))
expect(appeal.contacts.pluck(:name)).to eq(['Smith, John and Jane'])
donation = appeal.donations.first
expect(donation.tnt_id).to eq('ICWMY')
expect(donation.appeal).to eq(appeal)
expect(donation.appeal_amount).to eq(25)
# Survies the second import even if you rename the appeal
# Also check that it updates created_at to match tnt
appeal.update(name: 'Test new name', created_at: Time.zone.now)
expect do
tnt_import.import
end.to_not change(Appeal, :count).from(1)
expect(donation.appeal_amount).to eq(25)
appeal.reload
expect(appeal.created_at).to eq(Time.zone.local(2005, 5, 21, 12, 56, 40))
expect(appeal.contacts.pluck(:name)).to eq(['Smith, John and Jane'])
end
context 'version 3.1 and lower, appeals are called "Appeal"' do
it 'imports an appeal as well as its contacts and donations' do
test_appeal_import(create(:tnt_import_3_0_appeals))
end
end
context 'version 3.2 and higher, appeals are called "Campaign"' do
it 'imports an appeal as well as its contacts and donations' do
test_appeal_import(create(:tnt_import_3_2_campaigns))
end
end
it 'does not error if an appeal has no contacts' do
create(:appeal, tnt_id: -723_622_290, account_list: tnt_import.account_list)
contacts_by_tnt_appeal_id = {}
expect { import.send(:import_appeals, contacts_by_tnt_appeal_id) }.to_not raise_error
expect(Appeal.count).to eq(1)
expect(AppealContact.count).to eq(0)
end
it 'imports appeals before it imports gifts' do
expect(import).to receive(:import_appeals).ordered
expect(import).to receive(:import_offline_org_gifts).ordered
import.import
end
end
context '#import_history' do
it 'creates a new completed task' do
expect do
import.send(:import_history, import.send(:import_contacts))
end.to change(Task, :count).by(1)
end
it 'marks an existing task as completed' do
task = create(:task, source: 'tnt',
remote_id: history_rows.first['id'],
account_list: tnt_import.account_list,
completed: false)
expect { import.send(:import_history, import.send(:import_contacts)) }.not_to change(Task, :count)
task.reload
expect(task.completed).to eq(true)
expect(task.completed_at.utc).to eq(tnt_import.user.time_zone.parse('2004-08-26 19:00:00').utc)
end
it 'accociates a contact with the task' do
expect do
import.send(:import_history, history_contact_rows.first['ContactID'] => contact)
end.to change(ActivityContact, :count).by(1)
end
it 'associates contacts with tnt appeal ids' do
tnt_import = TntImport.new(create(:tnt_import_3_0_appeals))
contact_ids_by_tnt_appeal_id = tnt_import.send(:import_history, import.send(:import_contacts))
expect(contact_ids_by_tnt_appeal_id.size).to eq(1)
contact_ids = contact_ids_by_tnt_appeal_id['-2079150908']
expect(contact_ids.size).to eq(1)
expect(contact_ids[0]).to_not be_nil
expect(Contact.find(contact_ids[0]).name).to eq('<NAME> and Jane')
end
end
context 'importing designations from multiple orgs' do
it 'assigns correct organization to import designation numbers' do
ptc = org_for_code('PTC-CAN')
cru = org_for_code('CCC-USA')
expect do
create(:tnt_import_multi_org).send(:import)
end.to change(Contact, :count).by(2)
contacts = Contact.order(:name).to_a
expect(contacts.size).to eq 2
jane = contacts.first
expect(jane.donor_accounts.count).to eq 2
jane.donor_accounts.all? { |da| expect(da.organization).to eq ptc }
john = contacts.second
expect(john.donor_accounts.count).to eq 1
expect(john.donor_accounts.first.organization).to eq cru
expect(john.donor_accounts.first.name).to eq '<NAME>'
john_donor_address = john.donor_accounts.first.addresses.first
expect(john_donor_address.street).to eq '12345 Crescent'
expect(john_donor_address.country).to eq 'Canada'
end
end
context 'version support' do
context 'version 3.2 and higher' do
before { tnt_import.file = File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml')) }
it 'imports' do
expect { import.import }.to change { Contact.all.count }.from(0).to(3)
end
end
end
context 'with OrgContactPerson' do
before { tnt_import.file = File.new(Rails.root.join('spec/fixtures/tnt/tnt_3_2_broad.xml')) }
it 'add name to person' do
import.import
contact = Contact.find_by(tnt_id: 748_459_735)
expect(contact.people.collect(&:to_s)).to eq ['OrgContactPerson ']
# expect for phone numbers and email addresses to be associated with that person
expect(contact.people.first.email_addresses).to be_present
expect(contact.people.first.phone_numbers).to be_present
end
end
end
|
chuckmersereau/api_practice
|
spec/models/notification_type/missing_address_in_newsletter_spec.rb
|
<filename>spec/models/notification_type/missing_address_in_newsletter_spec.rb
require 'rails_helper'
describe NotificationType::MissingAddressInNewsletter do
subject { NotificationType::MissingAddressInNewsletter.first_or_initialize }
let(:account_list) { create(:account_list) }
context '#missing_info_filter' do
it 'excludes contacts not on the physical newsletter' do
account_list.contacts << create(:contact, send_newsletter: nil)
account_list.contacts << create(:contact, send_newsletter: 'Email')
expect_filtered_contacts([])
end
it 'excludes contacts on the newsletter with a valid address' do
contact = create(:contact, send_newsletter: 'Physical')
contact.addresses << create(:address, historic: nil)
account_list.contacts << contact
expect_filtered_contacts([])
end
it 'includes contacts on the newsletter without an address' do
contact = create(:contact, send_newsletter: 'Both')
account_list.contacts << contact
expect(contact.addresses.count).to eq(0)
expect_filtered_contacts([contact])
end
it 'includes contacts on the newsletter with a historic/deleted address' do
contact1 = create(:contact, send_newsletter: 'Physical')
contact1.addresses << create(:address, historic: true)
account_list.contacts << contact1
contact2 = create(:contact, send_newsletter: 'Both')
contact2.addresses << create(:address, deleted: true)
account_list.contacts << contact2
expect_filtered_contacts([contact1, contact2])
end
end
def expect_filtered_contacts(expected)
actual = subject.missing_info_filter(account_list.contacts).to_a
expect(actual.size).to eq(expected.size)
expected.each { |c| expect(actual).to include(c) }
end
end
|
chuckmersereau/api_practice
|
app/controllers/concerns/resource_type.rb
|
<filename>app/controllers/concerns/resource_type.rb
module ResourceType
extend ActiveSupport::Concern
def resource_type
self.class.custom_resource_type || resource_type_from_class_name
end
private
def invalid_resource_type_detail
if resource_type_from_params.to_s.empty?
"MUST supply a resource type for POST and PATCH requests. Expected type for this endpoint is '#{resource_type}'"
else
"'#{resource_type_from_params}' is not a valid resource type for this endpoint. Expected '#{resource_type}' instead"
end
end
def resource_type_from_class_name
self.class
.name
.split('::')
.last
.underscore
.sub('_controller', '')
.to_sym
end
def resource_type_from_params
params.dig(:data, :type).to_s.to_sym
end
def verify_resource_type
return if resource_type_from_params == resource_type
render_409(detail: invalid_resource_type_detail)
end
module ClassMethods
def custom_resource_type
@resource_type&.to_sym
end
def resource_type(type)
@resource_type = type
end
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/donation_amount_recommendation_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::DonationAmountRecommendation do
subject { described_class.new }
describe '#execute_query' do
let(:organization) { create(:organization) }
let(:designation_account) { create(:designation_account, organization: organization) }
let!(:account_list) { create(:account_list, designation_accounts: [designation_account]) }
let(:contacts) { account_list.contacts }
let(:donor_account1) { create(:donor_account, organization: organization, account_number: '123') }
let(:donor_account2) { create(:donor_account, organization: organization, account_number: '456') }
let(:donor_account3) { create(:donor_account, organization: organization, account_number: '789') }
let!(:contact1) do
create(
:contact,
account_list: account_list,
pledge_amount: 10,
pledge_frequency: 1,
donor_accounts: [donor_account1]
)
end
let!(:contact2) do
create(
:contact,
account_list: account_list,
pledge_amount: 10,
pledge_frequency: 1,
donor_accounts: [donor_account2]
)
end
let!(:contact3) do
create(
:contact,
account_list: account_list,
pledge_amount: 20,
pledge_frequency: 1,
donor_accounts: [donor_account3]
)
end
let!(:contact4) { create(:contact, account_list: account_list) }
let!(:donation_amount_recommendation1) do
create(
:donation_amount_recommendation,
suggested_pledge_amount: 20,
donor_account: donor_account1,
designation_account: designation_account
)
end
let!(:donation_amount_recommendation2) do
create(
:donation_amount_recommendation,
suggested_pledge_amount: 20,
donor_account: donor_account2,
designation_account: designation_account
)
end
let!(:donation_amount_recommendation3) do
create(
:donation_amount_recommendation,
suggested_pledge_amount: 20,
donor_account: donor_account3,
designation_account: designation_account
)
end
context 'filter is Yes' do
it 'should return contacts with recommendations' do
expect(subject.execute_query(contacts, donation_amount_recommendation: 'Yes')).to match_array(
[contact1, contact2]
)
end
end
context 'filter is No' do
it 'should return contacts without recommendations' do
expect(subject.execute_query(contacts, donation_amount_recommendation: 'No')).to match_array(
[contact3, contact4]
)
end
end
end
describe '#title' do
it 'should return "Increase Gift Recommendation"' do
expect(subject.title).to eq 'Increase Gift Recommendation'
end
end
describe '#parent' do
it 'should return "Gift Details"' do
expect(subject.parent).to eq 'Gift Details'
end
end
describe '#type' do
it 'should return "radio"' do
expect(subject.type).to eq 'radio'
end
end
describe '#custom_options' do
it 'should return array of options' do
expect(subject.custom_options).to eq(
[{ name: _('Yes'), id: 'Yes' }, { name: _('No'), id: 'No' }]
)
end
end
end
|
chuckmersereau/api_practice
|
app/workers/convert_credentials_worker.rb
|
# The purpose of this worker is to help transition DataSever user credentials from username/password to access tokens.
# This worker will not work after August 1, 2018. This worker is for transitional use only.
require 'csv'
class ConvertCredentialsWorker
include Sidekiq::Worker
sidekiq_options queue: :api_convert_credentials_worker
def perform
people_with_convertible_passwords.find_each(&method(:convert))
end
protected
def people_with_convertible_passwords
Person::OrganizationAccount
.joins(:organization)
.where(token: nil)
.where.not(organizations: { oauth_convert_to_token_url: nil })
end
def convert(organization_account)
url = organization_account.organization.oauth_convert_to_token_url
params = params(organization_account)
response = get_response(url, params)
CSV.new(response, headers: :first_row).each do |line|
organization_account.update(token: line['Token']) if line['Token']
end
rescue StandardError => ex
Rollbar.error(ex, organization_account_id: organization_account.id)
end
def params(organization_account, params = {})
params['UserName'] = organization_account.username
params['Password'] = <PASSWORD>
params['Action'] = 'OAuthConvertToToken'
params['client_id'] = ENV.fetch('DONORHUB_CLIENT_ID')
params['client_secret'] = ENV.fetch('DONORHUB_CLIENT_SECRET')
params['client_instance'] = 'app'
params
end
def get_response(url, params)
RestClient::Request.execute(method: :post, url: url, payload: params) do |response|
EncodingUtil.normalized_utf8(response.to_str)
end
end
end
|
chuckmersereau/api_practice
|
app/models/deleted_record.rb
|
class DeletedRecord < ApplicationRecord
TYPES = %w(Contact Activity Donation).freeze
DELETED_FROM_TYPES = %w(AccountList DesignationAccount).freeze
belongs_to :deletable, polymorphic: true
belongs_to :deleted_from, polymorphic: true
belongs_to :deleted_by, class_name: 'Person', foreign_key: 'deleted_by_id'
validates :deleted_from_id, :deleted_from_type, :deletable_id, :deletable_type, presence: true
validates :deletable_type, inclusion: { in: TYPES }
validates :deleted_from_type, inclusion: { in: DELETED_FROM_TYPES }
scope :account_list_ids, ->(ids) { where(deleted_from_id: ids) }
scope :since_date, ->(date) { where('deleted_at >= ?', date) }
scope :between_dates, ->(date_range) { where(deleted_at: date_range) }
scope :types, ->(types) { where(deletable_type: types.to_s.gsub('Task', 'Activity').split(',')) }
end
|
chuckmersereau/api_practice
|
spec/services/reports/monthly_losses_graph_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Reports::MonthlyLossesGraph, type: :model do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:organization) { create(:organization) }
let(:designation_account) do
create(:designation_account, organization: organization)
end
let(:contact) { create(:contact, account_list: account_list) }
let(:donor_account) { create(:donor_account, organization: organization) }
let!(:donation) do
create(:donation, donor_account: donor_account,
designation_account: designation_account,
donation_date: Date.parse('2099-03-04'),
amount: '1200')
end
let(:today) { Time.zone.parse('2099-06-22 12:34:56') }
subject do
Reports::MonthlyLossesGraph.new(account_list: account_list, months: 3,
today: today)
end
before do
contact.donor_accounts << donor_account
account_list.designation_accounts << designation_account
end
describe 'initializes' do
it 'initializes successfully' do
expect(subject).to be_a(Reports::MonthlyLossesGraph)
expect(subject.account_list).to eq(account_list)
end
end
describe '#losses with no balances' do
it { expect(subject.losses.size).to eq 3 }
it { expect(subject.losses).to eq Array.new(3, 0.0) }
end
describe '#losses' do
before do
create_balance balance: 100, created_at: today - 1.month
create_balance balance: 50, created_at: today - 5.days
end
it { expect(subject.losses.size).to eq 3 }
it { expect(subject.losses).to eq [0.00, -100.00, 50.00] }
end
describe '#month_names' do
it { expect(subject.month_names.size).to eq 3 }
it { expect(subject.month_names).to eq ['Apr 2099', 'May 2099', 'Jun 2099'] }
end
describe '#losses_with_month_names with no balances' do
it { expect(subject.losses.size).to eq 3 }
it { expect(subject.losses).to eq Array.new(3, 0.0) }
end
describe '#losses_with_month_names' do
before do
create_balance balance: 100, created_at: today - 1.month
create_balance balance: 50, created_at: today - 5.days
end
it { expect(subject.losses_with_month_names.size).to eq 3 }
it do
expect(subject.losses_with_month_names).to eq 'Apr 2099' => 0.00,
'May 2099' => -100.00,
'Jun 2099' => 50.00
end
end
private
def create_balance(args = {})
create :balance, args.merge(resource: designation_account)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20160811145356_add_deleted_to_email_addresses.rb
|
<filename>db/migrate/20160811145356_add_deleted_to_email_addresses.rb
class AddDeletedToEmailAddresses < ActiveRecord::Migration
def change
add_column :email_addresses, :deleted, :boolean, :default => false
end
end
|
chuckmersereau/api_practice
|
spec/models/designation_profile_spec.rb
|
require 'rails_helper'
describe DesignationProfile do
let!(:designation_profile) { create(:designation_profile) }
let!(:designation_account) { create(:designation_account) }
it 'should return name for to_s' do
expect(DesignationProfile.new(name: 'foo').to_s).to eq('foo')
end
it 'should return the first account when asked' do
designation_profile.designation_accounts << designation_account
expect(designation_profile.designation_account).to eq(designation_account)
end
it 'should create associated balance record when balance is updated' do
expect { create(:designation_profile, balance: 10.0) }.to change { Balance.count }.by(1)
expect { designation_profile.update(balance: 20.0) }.to change { Balance.count }.by(1)
expect { designation_profile.update(balance: 20.0) }.to change { Balance.count }.by(0)
end
it 'should not create associated balance record when balance is updated to nil' do
expect { designation_profile.update(balance: nil) }.to change { Balance.count }.by(0)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20120201225214_create_email_addresses.rb
|
<gh_stars>0
class CreateEmailAddresses < ActiveRecord::Migration
def change
create_table :email_addresses do |t|
t.belongs_to :person
t.string :email, null: false
t.boolean :primary, default: false
t.timestamps null: false
end
add_index :email_addresses, :person_id
end
end
|
chuckmersereau/api_practice
|
app/services/tools/analytics.rb
|
class Tools::Analytics < ActiveModelSerializers::Model
include ActiveModel::Validations
validates :account_lists, presence: true
attr_accessor :account_lists
def initialize(attributes = {})
super
after_initialize
end
def counts_by_type
account_lists.map do |account_list|
{
id: account_list.id,
counts: counts_by_type_for_account_list(account_list)
}
end
end
private
def counts_by_type_for_account_list(account_list)
[
{ type: 'fix-commitment-info', count: fix_commitment_info_count(account_list) },
{ type: 'fix-phone-numbers', count: fix_phone_number_count(account_list) },
{ type: 'fix-email-addresses', count: fix_email_addresses_count(account_list) },
{ type: 'fix-addresses', count: fix_addresses_count(account_list) },
{ type: 'fix-send-newsletter', count: fix_send_newsletter_count(account_list) },
{ type: 'duplicate-contacts', count: duplicate_contacts_count(account_list) },
{ type: 'duplicate-people', count: duplicate_people_count(account_list) }
]
end
def filter_contacts(account_list, filter_params)
Contact::Filterer.new(filter_params).filter(scope: account_list.contacts, account_lists: [account_list])
end
def filter_people(account_list, filter_params)
person_scope = Person.joins(:contact_people).where(contact_people: { contact: account_list.contacts.active })
Person::Filterer.new(filter_params).filter(scope: person_scope, account_lists: [account_list])
end
def fix_commitment_info_count(account_list)
filter_contacts(account_list, status_valid: 'false').count
end
def fix_phone_number_count(account_list)
filter_people(account_list, phone_number_valid: 'false').count
end
def fix_email_addresses_count(account_list)
filter_people(account_list, email_address_valid: 'false').count
end
def fix_addresses_count(account_list)
filter_contacts(account_list, address_valid: 'false').count
end
def fix_send_newsletter_count(account_list)
filter_contacts(account_list,
newsletter: 'no_value',
status: 'Partner - Financial,Partner - Special,Partner - Pray').count
end
def duplicate_contacts_count(account_list)
Contact::DuplicatePairsFinder.new(account_list).find_and_save
DuplicateRecordPair.type('Contact').where(account_list: account_list, ignore: false).count
end
def duplicate_people_count(account_list)
Person::DuplicatePairsFinder.new(account_list).find_and_save
DuplicateRecordPair.type('Person').where(account_list: account_list, ignore: false).count
end
def after_initialize
raise ArgumentError, errors.full_messages.join(', ') if invalid?
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/contact_pledge_frequency_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe Task::Filter::ContactPledgeFrequency do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let!(:frequent_contact) { create(:contact, account_list: account_list, pledge_frequency: 1) }
let!(:infrequent_contact) { create(:contact, account_list: account_list, pledge_frequency: nil) }
let!(:task_one) { create(:task, account_list: account_list, contacts: [frequent_contact]) }
let!(:task_two) { create(:task, account_list: account_list, contacts: [infrequent_contact]) }
describe '#query' do
let(:tasks) { account_list.tasks }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_pledge_frequency: {} }, account_list)).to eq(nil)
expect(described_class.query(tasks, { contact_pledge_frequency: [] }, account_list)).to eq(nil)
end
end
context 'filter by contact with a pledge frequecy' do
it 'returns the tasks with contacts that have a pledge frequency set' do
expect(described_class.query(tasks, { contact_pledge_frequency: '1' }, account_list).to_a).to eq [task_one]
expect(described_class.query(tasks, { contact_pledge_frequency: '1' }, account_list).to_a).not_to match_array [task_one, task_two]
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/contact.rb
|
<filename>app/models/contact.rb
class Contact < ApplicationRecord
include AddressMethods
acts_as_taggable
extend ApplicationHelper
include Deletable
PAPER_TRAIL_IGNORED_FIELDS = [
:account_list_id, :updated_at, :notes_saved_at, :status_confirmed_at,
:total_donations, :last_donation_date, :first_donation_date,
:last_activity, :last_appointment, :last_letter, :last_phone_call, :last_pre_call, :last_thank,
:uncompleted_tasks_count, :notes, :deprecated_not_duplicated_with, :status_valid
].freeze
audited associated_with: :account_list, except: PAPER_TRAIL_IGNORED_FIELDS
# Track status and pledge details at most once per day in separate table
has_attributes_history for: [:status, :pledge_amount, :pledge_frequency,
:pledge_received, :pledge_start_date, :pledge_currency],
with_model: PartnerStatusLog
# Also track notes at most once per day in separate table
has_attributes_history for: [:notes], with_model: ContactNotesLog
has_many :contact_donor_accounts, dependent: :delete_all, inverse_of: :contact
has_many :donor_accounts, through: :contact_donor_accounts, inverse_of: :contacts
has_many :donation_amount_recommendations, through: :donor_accounts
belongs_to :account_list
has_many :contact_people, dependent: :destroy
has_many :people, through: :contact_people
has_one :primary_contact_person, -> { where(primary: true) }, class_name: 'ContactPerson', dependent: :destroy
has_one :primary_person, through: :primary_contact_person, source: :person, autosave: true
has_one :spouse_contact_person, -> { where(primary: [false, nil]) }, class_name: 'ContactPerson', dependent: :destroy
has_one :spouse, through: :spouse_contact_person, source: :person, autosave: true
has_many :contact_referrals_to_me, foreign_key: :referred_to_id, class_name: 'ContactReferral', dependent: :delete_all
has_many :contact_referrals_by_me, foreign_key: :referred_by_id, class_name: 'ContactReferral', dependent: :delete_all
has_many :contacts_that_referred_me, through: :contact_referrals_to_me, source: :referred_by
has_many :contacts_referred_by_me, through: :contact_referrals_by_me, source: :referred_to
has_many :activity_contacts, dependent: :destroy
has_many :activities, through: :activity_contacts
has_many :tasks, through: :activity_contacts, source: :task
has_many :notifications, inverse_of: :contact, dependent: :destroy
has_many :messages
has_many :appeal_contacts
has_many :appeals, through: :appeal_contacts
has_many :excluded_appeal_contacts, class_name: 'Appeal::ExcludedAppealContact', dependent: :delete_all
has_many :pledges
serialize :prayer_letters_params, Hash
serialize :suggested_changes, Hash
scope :people, lambda {
where('donor_accounts.master_company_id is null').includes(:donor_accounts).references('donor_accounts')
}
scope :companies, lambda {
where('donor_accounts.master_company_id is not null').includes(:donor_accounts).references('donor_accounts')
}
scope :with_person, -> (person) { includes(:people).where('people.id' => person.id) }
scope :for_donor_account, lambda { |donor_account|
where('donor_accounts.id' => donor_account.id).includes(:donor_accounts).references('donor_accounts')
}
scope :for_account_list, -> (account_list) { where(account_list_id: account_list.id) }
scope :financial_partners, -> { where(status: 'Partner - Financial') }
scope :non_financial_partners, -> { where("status <> 'Partner - Financial' OR status is NULL") }
scope :with_referrals, -> { joins(:contact_referrals_by_me).uniq }
scope :active, -> { where(active_conditions) }
scope :inactive, -> { where(inactive_conditions) }
scope :active_or_unassigned, -> { where(active_or_unassigned_conditions) }
scope :late_by, lambda { |min_days, max_days = 100.years|
financial_partners.where(late_at: (max_days || 100.years).ago..min_days.ago)
}
scope :created_between, lambda { |start_date, end_date|
where('contacts.created_at BETWEEN ? and ?', start_date.in_time_zone, (end_date + 1.day).in_time_zone)
}
scope :search_donor_account_numbers, lambda { |search_term|
joins(:donor_accounts)
.where('donor_accounts.account_number ilike ?', "%#{search_term}%")
}
scope :primary_addresses, -> { joins(:addresses).where(addresses: { primary_mailing_address: true }) }
scope :non_primary_addresses, -> { joins(:addresses).where(addresses: { primary_mailing_address: false }) }
scope :non_historical_addresses, -> { joins(:addresses).where(addresses: { historic: false }) }
scope :historical_addresses, -> { joins(:addresses).where(addresses: { historic: true }) }
scope :distinct_church_names, -> { select('DISTINCT on (church_name) church_name, id') }
scope :list_church_names, -> { distinct_church_names.where.not(church_name: nil).order('church_name asc') }
scope :search_church_names, ->(term) { where('church_name iLIKE ?', "%#{term}%") }
PERMITTED_ATTRIBUTES = [
:account_list_id,
:church_name,
:created_at,
:direct_deposit,
:envelope_greeting,
:full_name,
:greeting,
:likely_to_give,
:locale,
:magazine,
:name,
:next_ask,
:no_appeals,
:no_gift_aid,
:notes,
:overwrite,
:pledge_amount,
:pledge_currency,
:pledge_frequency,
:pledge_received,
:pledge_start_date,
:primary_person_id,
:send_newsletter,
:status,
:status_valid,
:tag_list,
:timezone,
:updated_at,
:updated_in_db_at,
:id,
:website,
{
addresses_attributes: [
:_destroy,
:city,
:country,
:historic,
:id,
:_client_id,
:location,
:master_address_id,
:metro_area,
:overwrite,
:postal_code,
:primary_mailing_address,
:region,
:remote_id,
:state,
:street,
:source,
:user_changed,
:valid_values
],
contact_referrals_to_me_attributes: [
:_destroy,
:id,
:_client_id,
:overwrite,
:referred_by_id
],
contact_referrals_by_me_attributes: [
:_destroy,
:id,
:_client_id,
:overwrite,
:referred_to_id
],
donor_accounts_attributes: [
:_destroy,
:account_number,
:id,
:_client_id,
:organization_id,
:overwrite
],
people_attributes: Person::PERMITTED_ATTRIBUTES + [:overwrite],
contacts_referred_by_me_attributes: [
:_destroy,
:account_list_id,
:id,
:_client_id,
:name,
:notes,
:overwrite,
:primary_address_city,
:primary_address_postal_code,
:primary_address_state,
:primary_address_street,
:primary_person_email,
:primary_person_first_name,
:primary_person_last_name,
:primary_person_phone,
:spouse_email,
:spouse_first_name,
:spouse_last_name,
:spouse_phone
],
tag_list: []
}
].freeze
MERGE_COPY_ATTRIBUTES = [
:name, :pledge_amount, :status, :full_name, :greeting, :envelope_greeting, :website, :pledge_frequency,
:pledge_start_date, :next_ask, :likely_to_give, :church_name, :no_appeals, :pls_id,
:direct_deposit, :magazine, :pledge_received, :timezone, :last_activity, :last_appointment, :last_letter,
:last_phone_call, :last_pre_call, :last_thank, :prayer_letters_id, :last_donation_date, :first_donation_date, :tnt_id
].freeze
validates :account_list_id, presence: true
validates :addresses, single_primary: { primary_field: :primary_mailing_address }, if: :user_changed
validates :name, presence: true
validates :pledge_amount, numericality: true, allow_nil: true
accepts_nested_attributes_for :people, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :donor_accounts, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :contact_people, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :contact_referrals_to_me, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :contacts_referred_by_me, reject_if: :all_blank, allow_destroy: false
before_save :set_notes_saved_at, :update_late_at, :check_state_for_mail_chimp_sync, :set_status_confirmed_at
after_create :create_people_from_contact, if: :prefill_attributes_on_create
after_commit :sync_with_mail_chimp, if: :sync_with_mail_chimp_required?
after_commit :sync_with_letter_services, :sync_with_google_contacts
before_destroy :delete_from_letter_services, :delete_people
LETTER_SERVICES = [:pls, :prayer_letters].freeze
# loaded_donations is used by Contact::DonationsEagerLoader
attr_accessor :user_changed, :loaded_donations, :prefill_attributes_on_create
# Don't change these willy-nilly, they break the mobile app
ASSIGNABLE_STATUSES = [
'Never Contacted', 'Ask in Future', 'Cultivate Relationship', 'Contact for Appointment',
'Appointment Scheduled', 'Call for Decision', 'Partner - Financial', 'Partner - Special',
'Partner - Pray', 'Not Interested', 'Unresponsive', 'Never Ask', 'Research Abandoned',
'Expired Referral'
].freeze
assignable_values_for :status, allow_blank: true do
ASSIGNABLE_STATUSES
end
INACTIVE_STATUSES = [
'Not Interested', 'Unresponsive', 'Never Ask', 'Research Abandoned',
'Expired Referral'
].freeze
ACTIVE_STATUSES = ASSIGNABLE_STATUSES - INACTIVE_STATUSES
IN_PROGRESS_STATUSES = [
'Never Contacted', 'Ask in Future', 'Contact for Appointment',
'Appointment Scheduled',
'Call for Decision'
].freeze
def status=(val)
# handle deprecated values
self[:status] = case val
when 'Call for Appointment'
'Contact for Appointment'
else
val
end
end
ASSIGNABLE_LIKELY_TO_GIVE = ['Least Likely', 'Likely', 'Most Likely'].freeze
assignable_values_for :likely_to_give, allow_blank: true do
ASSIGNABLE_LIKELY_TO_GIVE
end
ASSIGNABLE_SEND_NEWSLETTER = %w(Physical Email Both None).freeze
assignable_values_for :send_newsletter, allow_blank: true do
ASSIGNABLE_SEND_NEWSLETTER
end
delegate :first_name, :last_name, :phone, :email, to: :primary_or_first_person
delegate :street, :city, :csv_street, :state, :postal_code, to: :mailing_address
# These delegations exist to facilitate creating referrals (as new contact records) with nested attributes
delegate :street, :city, :state, :postal_code, to: :primary_address, prefix: :primary_address, allow_nil: true
delegate 'street=', 'city=', 'state=', 'postal_code=', to: :find_or_build_primary_address, prefix: :primary_address
delegate :first_name, :last_name, :phone, :email, to: :primary_person, prefix: :primary_person, allow_nil: true
delegate 'first_name=', 'last_name=', 'phone=', 'email=', to: :find_or_build_primary_person, prefix: :primary_person
delegate :first_name, :last_name, :phone, :email, to: :spouse, prefix: :spouse, allow_nil: true
delegate 'first_name=', 'last_name=', 'phone=', 'email=', to: :find_or_build_spouse, prefix: :spouse
def to_s
name
end
def deleted_from
account_list
end
def add_person(person, donor_account = nil)
# Nothing to do if this person is already on the contact
new_person = people.find_by(master_person_id: person.master_person_id)
unless new_person
new_person = Person.clone(person)
people << new_person
donor_account&.donor_account_people&.create(person: new_person)
end
new_person
end
def add_to_notes(new_note)
return if notes.to_s.include?(new_note.to_s)
self.notes = if notes.present?
"#{notes} \n \n#{new_note}"
else
new_note
end
save
end
def mailing_address
# Use .reject(&:historic) and not .where.not(historic: true) because the
# CSV import uses mailing_address for checking the addresses for contacts
# before saving them to the database.
@mailing_address ||= primary_address ||
addresses.reject(&:historic).first || Address.new
end
def reload_mailing_address
@mailing_address = nil
mailing_address.reload unless mailing_address.new_record?
mailing_address
end
def hide
update_attributes(status: 'Never Ask')
end
def active?
!Contact.inactive_statuses.include?(status)
end
def late_by?(min_days, max_days = nil)
return false unless status == 'Partner - Financial' && pledge_frequency.present? && late_at
min_late_date = Date.today - min_days
max_late_date = max_days ? Date.today - max_days : Date.new(1951, 1, 1)
late_at > max_late_date && late_at < min_late_date
end
def update_late_at
initial_date = last_donation_date || pledge_start_date
return self.late_at = nil unless late_at_should_be_set?(initial_date)
self.late_at = if pledge_frequency >= 1.0
initial_date + pledge_frequency.to_i.months
elsif pledge_frequency >= 0.4
initial_date + 2.weeks
else
initial_date + 1.week
end
end
def late_at_should_be_set?(initial_date)
status == 'Partner - Financial' && pledge_frequency.present? && initial_date.present?
end
def self.active_conditions
"status IN('#{active_statuses.join("','")}') or status is null"
end
def self.inactive_conditions
"status IN('#{inactive_statuses.join("','")}')"
end
def self.active_or_unassigned_conditions
active_or_unassigned_statuses = active_statuses + ['']
"status IN('#{active_or_unassigned_statuses.join("','")}')"
end
def self.active_statuses
ACTIVE_STATUSES
end
def self.inactive_statuses
INACTIVE_STATUSES
end
def self.create_from_donor_account(donor_account, account_list)
contact = account_list.contacts.new(name: donor_account.name,
locale: donor_account.organization&.locale)
contact.addresses_attributes = donor_account.addresses_attributes
contact.addresses.each { |a| a.source_donor_account = donor_account }
contact.save!
contact.donor_accounts << donor_account
contact
end
def primary_or_first_person
@primary_or_first_person ||= primary_person
return @primary_or_first_person if @primary_or_first_person
return Person.new if people.blank?
@primary_or_first_person = if people.count == 1
people.first
else
people.alive.find_by(gender: 'male') || people.alive.order('created_at').first
end
self.primary_person_id = @primary_or_first_person.id if @primary_or_first_person&.new_record? && !new_record?
@primary_or_first_person || Person.new
end
def clear_primary_person
@primary_or_first_person = nil
self.primary_person_id = nil
end
def primary_person_id
primary_or_first_person.id
end
def primary_person_id=(person_id)
if person_id
cp = contact_people.find_by(person_id: person_id)
cp&.update_attributes(primary: true)
@primary_or_first_person = nil
end
person_id
end
def greeting
self[:greeting].presence || generated_greeting
end
def generated_greeting
return name if siebel_organization?
return first_name if spouse.try(:deceased)
return spouse_first_name if primary_or_first_person.deceased && spouse
[first_name, spouse_first_name].compact.join(" #{_('and')} ")
end
def envelope_greeting
self[:envelope_greeting].presence || generated_envelope_greeting
end
def generated_envelope_greeting
return name if siebel_organization?
working_name = name.to_s.strip
working_name.chomp!(',') if working_name.ends_with?(',')
return working_name unless working_name.include?(',')
last_name = working_name.split(',')[0].strip
first_names = working_name.split(',')[1].strip
return first_names + ' ' + last_name unless first_names =~ /\((\w|\W)*\)/
first_names = first_names.split(/ & | #{_('and')} | and /)
if first_names[0] =~ /\((\w|\W)*\)/
first_names.each { |first_name| first_name.sub!(/\((\w|\W)*\)/, '') }
first_names.each(&:strip!)
env_greeting = if first_names[1].present?
"#{first_names[0]} #{_('and')} #{first_names[1]} #{last_name}"
else
"#{first_names[0]} #{last_name}"
end
return env_greeting
end
if donor_accounts.where(name: name).any? && first_names[1] =~ /\((\w|\W)*\)/
# Contacts from the donor system usually have nicknames, not a different
# last name in paren, i.e. "<NAME> and Janet (Jane)" not "<NAME> and Janet (Smith)"
nickname_stripped = first_names[1].gsub!(/\(.*?\)/, '').gsub(/\s\s+/, ' ').strip
return "#{first_names[0]} #{_('and')} #{nickname_stripped} #{last_name}"
end
first_names[1].delete!('()')
"#{first_names[0]} #{last_name} #{_('and')} #{first_names[1]}"
end
def siebel_organization?
last_name == 'of the Ministry'
end
def update_donation_totals(donation, reset: false)
self.first_donation_date = donation.donation_date if first_donation_date.nil? || donation.donation_date < first_donation_date
self.last_donation_date = donation.donation_date if last_donation_date.nil? || donation.donation_date > last_donation_date
self.total_donations = reset ? total_donations_query : (total_donations.to_f + donation.amount)
save(validate: false)
end
def update_all_donation_totals
update(total_donations: total_donations_query)
end
def total_donations_query
@total_donations_query ||= donations.sum(:amount)
end
def monthly_pledge
amount = pledge_amount_for_monthly_pledge_calculation
frequency = pledge_frequency_for_monthly_pledge_calculation
(amount / frequency).round(2)
end
def send_email_letter?
%w(Email Both).include?(send_newsletter)
end
def send_physical_letter?
%w(Physical Both).include?(send_newsletter)
end
def pledge_currency
self[:pledge_currency].presence || account_list.try(:default_currency)
end
def pledge_currency_symbol
cldr_currency = TwitterCldr::Shared::Currencies.for_code(pledge_currency.upcase)
cldr_currency.present? ? cldr_currency[:symbol] : pledge_currency
end
def donor_accounts_attributes=(attribute_collection)
attribute_collection = Hash[(0...attribute_collection.size).zip attribute_collection] if attribute_collection.is_a?(Array)
attribute_collection = attribute_collection.with_indifferent_access.values
attribute_collection.each do |attrs|
donor_account = DonorAccount.find_by(account_number: attrs[:account_number], organization_id: attrs[:organization_id])
if attrs[:id].present? && (attrs[:account_number].blank? || attrs[:_destroy] == '1')
ContactDonorAccount.where(donor_account_id: attrs[:id], contact_id: id).destroy_all
elsif attrs[:account_number].blank?
next
elsif donor_account
contact_donor_accounts.new(donor_account: donor_account) unless donor_account.contacts.include?(self)
else
assign_nested_attributes_for_collection_association(:donor_accounts, [attrs])
end
end
end
def deceased
people.any? && people.all?(&:deceased)
end
alias deceased? deceased
def self.pledge_frequencies
{
0.23076923076923.to_d => _('Weekly'),
0.46153846153846.to_d => _('Every 2 Weeks'),
1.0.to_d => _('Monthly'),
2.0.to_d => _('Every 2 Months'),
3.0.to_d => _('Quarterly'),
4.0.to_d => _('Every 4 Months'),
6.0.to_d => _('Every 6 Months'),
12.0.to_d => _('Annual'),
24.0.to_d => _('Every 2 Years')
}
end
def merge(other)
ContactMerge.new(self, other).merge
end
def merge_people
# Merge people that have the same name
merged_people = []
people.reload.each do |person|
next if merged_people.include?(person)
other_people = people.select do |p|
p.first_name.to_s.strip.casecmp(person.first_name.to_s.strip.downcase).zero? &&
p.last_name.to_s.strip.casecmp(person.last_name.to_s.strip.downcase).zero? &&
p.id != person.id
end
next unless other_people
other_people.each do |other_person|
person.merge(other_person)
merged_people << other_person
end
end
people.reload
people.map(&:merge_phone_numbers)
end
def merge_donor_accounts
# Merge donor accounts that have the same number
donor_accounts.reload.each do |account|
other = donor_accounts.find do |da|
da.id != account.id &&
da.account_number == account.account_number
end
next unless other
account.merge(other)
merge_donor_accounts
break
end
end
def update_uncompleted_tasks_count
update_column(:uncompleted_tasks_count, tasks.uncompleted.count)
end
def find_timezone
return unless primary_or_first_address
primary_or_first_address.master_address.find_timezone
rescue StandardError
end
def primary_or_first_address
@primary_or_first_address ||=
addresses.find(&:primary_mailing_address?) || addresses.first
end
def set_timezone
timezone = find_timezone
update_column(:timezone, find_timezone) unless timezone == self.timezone
end
def should_be_in_prayer_letters?
send_physical_letter? && name.present? && envelope_greeting.present? &&
mailing_address.present? && mailing_address.valid_mailing_address?
end
def donations
Donation.where(donor_account: donor_accounts)
.for_accounts(account_list.designation_accounts)
end
def last_six_donations
donations.order(:created_at).limit(6)
end
def last_donation
donations.order(:created_at).first
end
def last_monthly_total(except_payment_method: nil)
scoped_donations = donations
scoped_donations = scoped_donations.where.not(payment_method: except_payment_method) if except_payment_method
scoped_donations.where('donation_date >= ?',
last_donation_month_end.beginning_of_month).sum(:amount)
end
def prev_month_donation_date
donations.where('donation_date <= ?', (last_donation_month_end << 1).end_of_month)
.pluck(:donation_date).first
end
def monthly_avg_current(except_payment_method: nil)
monthly_avg_over_range(current_pledge_interval_start, last_donation_month_end, except_payment_method: except_payment_method)
end
def monthly_avg_with_prev_gift(except_payment_method: nil)
monthly_avg_over_range(prev_donation_month_start, last_donation_month_end, except_payment_method: except_payment_method)
end
def monthly_avg_from(date, except_payment_method: nil)
return unless date
monthly_avg_over_range(start_of_pledge_interval(date), last_donation_month_end, except_payment_method: except_payment_method)
end
def months_from_prev_to_last_donation
return unless last_donation && prev_month_donation_date
month_diff(prev_month_donation_date, last_donation.donation_date)
end
def current_pledge_interval_donations
interval_donations(current_pledge_interval_start, last_donation_month_end)
end
def current_pledge_interval_start
prev_months_to_include = [(pledge_frequency || 1) - 1, 0].max
(last_donation_month_end << prev_months_to_include).beginning_of_month
end
def self.bulk_update_options(current_account_list)
options = {}
options['likely_to_give'] = ASSIGNABLE_LIKELY_TO_GIVE
options['status'] = ASSIGNABLE_STATUSES
options['send_newsletter'] = ASSIGNABLE_SEND_NEWSLETTER
options['pledge_received'] = %w(Yes No)
options['pledge_currency'] = currency_select(current_account_list)
options
end
def amount_with_gift_aid(amount)
amount ||= 0
(amount * gift_aid_coefficient).round(2)
end
def pledge_amount=(pledge_amount)
pledge_amount = if pledge_amount.to_s.index(',').to_i < pledge_amount.to_s.index('.').to_i
pledge_amount.to_s.delete(',')
else
pledge_amount.to_s.delete('.')
end
self[:pledge_amount] = pledge_amount.blank? ? nil : pledge_amount.to_f
end
def mail_chimp_open_rate
return nil unless email
mail_chimp_member_request
end
def create_people_from_contact
name_parts = name.split(',')
if name_parts.length > 1
last_name = name_parts[0]
name_parts[1].split(/\sand\s|\s&\s/).map { |i| i.strip if i.strip != '' }.uniq.compact.map do |first_name|
people << Person.new(first_name: first_name, last_name: last_name)
end
else
people << Person.new(first_name: name)
end
save
end
def sync_with_mail_chimp
return unless account_list.mail_chimp_account
if account_list.mail_chimp_account.relevant_contacts([id]).exists?
send_update_to_mailchimp
else
send_check_removal_mailchimp
end
end
private
def send_update_to_mailchimp
MailChimp::ExportContactsWorker.perform_async(
account_list.mail_chimp_account.id, account_list.mail_chimp_account.primary_list_id, [id]
)
end
def send_check_removal_mailchimp
MailChimp::ExportContactsWorker.perform_async(
account_list.mail_chimp_account.id, account_list.mail_chimp_account.primary_list_id, []
)
end
def sync_with_mail_chimp_required?
@sync_mail_chimp
end
def mail_chimp_member_request
return unless mail_chimp_account&.primary_list_id
gibbon_wrapper = MailChimp::GibbonWrapper.new(mail_chimp_account)
gibbon_wrapper.gibbon_list_object(mail_chimp_account.primary_list_id)
.members(email_hash(email)).retrieve['stats']['avg_open_rate']
rescue Gibbon::MailChimpError => error
return nil if error.title =~ /Resource Not Found/
raise error
end
def mail_chimp_account
account_list.mail_chimp_account
end
def email_hash(email)
Digest::MD5.hexdigest(email.email.downcase)
end
def gift_aid_coefficient
(1 + (gift_aid_percentage.to_f / 100))
end
def gift_aid_percentage
return 0 if no_gift_aid?
donor_accounts.first.try(:organization).try(:gift_aid_percentage) || 0
end
def monthly_avg_over_range(start_date, end_date, except_payment_method: nil)
scoped_donations = interval_donations(start_date, end_date)
scoped_donations = scoped_donations.where.not(payment_method: except_payment_method) if except_payment_method
scoped_donations.sum(:amount) / months_in_range(start_date, end_date)
end
def interval_donations(start_date, end_date)
donations
.where('donation_date >= ?', start_date)
.where('donation_date <= ?', end_date)
end
def last_donation_month_end
@last_donation_month_end ||=
if last_donation_date && month_diff(last_donation_date, Date.today).positive?
Date.today.prev_month.end_of_month
else
Date.today.end_of_month
end
end
def prev_donation_month_start
@prev_donation_month_start ||=
start_of_pledge_interval([first_donation_date, Date.today << 12,
prev_month_donation_date].compact.max)
end
def start_of_pledge_interval(date)
months_in_range_mod_freq = months_in_range(date, last_donation_month_end) % pledge_frequency
months_to_subtract = months_in_range_mod_freq.zero? ? 0 : pledge_frequency - months_in_range_mod_freq
(date << months_to_subtract).beginning_of_month
end
def month_diff(start_date, end_date)
(end_date.year * 12 + end_date.month) - (start_date.year * 12 + start_date.month)
end
def months_in_range(start_date, end_date)
month_diff(start_date, end_date) + 1
end
def delete_people
people.each do |person|
# If this person isn't linked to any other contact, delete them
next if account_list.people.where('people.id = ? AND contact_people.contact_id <> ?', person.id, id).any?
person.destroy
end
contact_people.destroy_all
end
def set_notes_saved_at
self.notes_saved_at = DateTime.now if changed.include?('notes')
end
def check_state_for_mail_chimp_sync
@sync_mail_chimp = (relevant_nested_attribute_changed? || relevant_contact_attribute_changed?)
true
end
def relevant_contact_attribute_changed?
(changed & %w(locale status tag_list send_newsletter)).present?
end
def relevant_nested_attribute_changed?
any_tags_change? ||
people.any? do |person|
person.primary_email_address&.email_changed? ||
person.first_name_changed? ||
person.last_name_changed? ||
person.optout_enewsletter_changed?
end
end
def any_tags_change?
taggings.count != tag_list.count
end
def sync_with_google_contacts
account_list.queue_sync_with_google_contacts
end
def sync_with_letter_services
LETTER_SERVICES.each { |service| sync_with_letter_service(service) }
end
def delete_from_letter_services
LETTER_SERVICES.each { |service| delete_from_letter_service(service) }
end
def sync_with_letter_service(service)
return unless account_list && account_list.send("valid_#{service}_account")
# in case an association change triggered this
reload_mailing_address
pl = account_list.send("#{service}_account")
if should_be_in_prayer_letters?
pl.add_or_update_contact(self)
else
delete_from_letter_service(service)
end
end
def delete_from_letter_service(service)
# If this contact was at prayerletters.com and no other contact on this list has the
# same prayer_letters_id, remove this contact from prayerletters.com
return if send("#{service}_id").blank?
return unless account_list && account_list.send("valid_#{service}_account")
return if account_list.contacts.where("#{service}_id" => send("#{service}_id")).where.not(id: id).present?
account_list.send("#{service}_account").delete_contact(self)
end
def find_or_build_spouse
@find_or_build_spouse ||= (spouse || build_spouse_contact_person.build_person)
end
def find_or_build_primary_person
@find_or_build_primary_person ||= (primary_person || build_primary_contact_person.build_person)
end
def find_or_build_primary_address
@find_or_build_primary_address ||= (primary_address || build_primary_address)
end
def pledge_amount_for_monthly_pledge_calculation
if pledge_amount&.positive?
pledge_amount.to_f
else
0
end
end
def pledge_frequency_for_monthly_pledge_calculation
if pledge_frequency&.positive?
pledge_frequency
else
1 # default
end
end
def set_status_confirmed_at
return unless status_valid_changed? && status_valid_was == false && status_valid == true
self.status_confirmed_at = Time.current
end
end
|
chuckmersereau/api_practice
|
spec/lib/batch_request_handler/instruments/request_validator_spec.rb
|
<gh_stars>0
require 'spec_helper'
describe BatchRequestHandler::Instruments::RequestValidator do
let(:params) { {} }
subject { described_class.new(params) }
describe '#around_perform_request' do
context 'with a valid request' do
let(:env) { Rack::MockRequest.env_for('/api/v2/users') }
it 'yields the request environment' do
expect { |block| subject.around_perform_request(env, &block) }
.to yield_with_args(env)
end
end
context 'with an invalid request method' do
let(:env) { Rack::MockRequest.env_for('/api/v2/users', method: 'OPTIONS') }
it 'does not yield the request environment' do
expect { |block| subject.around_perform_request(env, &block) }
.to_not yield_control
end
it 'returns an error response' do
status, headers, body = subject.around_perform_request(env) {}
json = JSON.parse(body.first)
expect(status).to be(405)
expect(headers).to include('Content-Type' => 'application/json')
expect(json).to have_key('errors')
expect(json['errors'].length).to eq(1)
expect(json['errors'][0]).to include('status', 'message', 'meta')
expect(json['errors'][0]['meta']).to include('path', 'method', 'body')
end
end
context 'with a valid request that is rejected for being batched at the controller level' do
let(:env) { Rack::MockRequest.env_for('/api/v2/users') }
let(:error_message) { 'You cannot access this endpoint from within a batch request' }
let(:block) do
lambda do |_env|
raise BatchRequestHandler::Instruments::RequestValidator::InvalidBatchRequestError,
status: 403,
message: error_message
end
end
it 'yields the request environment' do
expect { |block| subject.around_perform_request(env, &block) }
.to yield_with_args(env)
end
it 'returns an error response' do
status, headers, body = subject.around_perform_request(env, &block)
json = JSON.parse(body.first)
expect(status).to be(403)
expect(headers).to include('Content-Type' => 'application/json')
expect(json).to have_key('errors')
expect(json['errors'].length).to eq(1)
expect(json['errors'][0]).to include('status', 'message', 'meta')
expect(json['errors'][0]['message']).to eq(error_message)
expect(json['errors'][0]['meta']).to include('path', 'method', 'body')
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/deleted_records/filter/since_date.rb
|
class DeletedRecords::Filter::SinceDate < ApplicationFilter
def execute_query(deleted_records, filters)
return deleted_records if filters[:since_date].blank?
deleted_records.between_dates(filters[:since_date])
end
end
|
chuckmersereau/api_practice
|
lib/generators/graip/controller/controller_generator.rb
|
require 'generators/rspec'
module Graip
module Generators
class ControllerGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
def generate_controller
return if name.blank?
full_file_name = "#{file_name}_controller.rb"
file_path = File.join('app/controllers', class_path, full_file_name)
template 'controller.rb.erb', file_path
end
def generate_controller_spec
full_file_name = "#{file_name}_controller_spec.rb"
file_path = File.join('spec/controllers', class_path, full_file_name)
template 'controller_spec.rb.erb', file_path
end
def generate_acceptance_spec
full_file_name = "#{file_name}_spec.rb"
file_path = File.join('spec/acceptance', class_path, full_file_name)
template 'acceptance_spec.rb.erb', file_path
end
private
def build_parent_namespacing
return if class_path.empty?
class_path.map(&:camelize).join('::').concat('::')
end
def underscored_resource_name
@underscored_resource_name ||= resource_name.underscore
end
def underscored_resources_name
@underscored_resources_name ||= resources_name.underscore
end
def parent_namespacing
@parent_namespaces ||= build_parent_namespacing
end
def resource_class_name
@resource_class_name ||= resource_name.camelize
end
def resource_instance
@resource_instance ||= "@#{resource_name}"
end
def resource_name
@resource_name ||= file_name.singularize
end
def resources_instance
@resources_instance ||= "@#{resources_name}"
end
def resources_name
@resources_name ||= file_name.pluralize
end
def resource_human_name
@resource_human_name ||= resource_name.humanize(capitalize: false)
end
def resources_human_name
@resources_human_name ||= resource_human_name.pluralize
end
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/balances.rb
|
FactoryBot.define do
factory :balance do
balance { rand(0.0...100.0) }
association :resource, factory: :designation_account
end
end
|
chuckmersereau/api_practice
|
spec/services/mail_chimp/exporter_spec.rb
|
require 'rails_helper'
describe MailChimp::Exporter do
let(:list_id) { 'list_one_id' }
let(:mail_chimp_account) do
create(
:mail_chimp_account,
active: true,
primary_list_id: list_id
)
end
let(:account_list) { mail_chimp_account.account_list }
subject { described_class.new(mail_chimp_account, list_id) }
let(:mock_connection_handler) { double(:mock_connection_handler) }
let(:mock_gibbon_wrapper) { double(:mock_gibbon_wrapper) }
let(:mock_batcher) { double(:mock_batcher) }
let(:mock_group_adder) { double(:mock_group_adder) }
let(:mock_interest_ids_cacher) { double(:mock_interest_ids_cacher) }
let(:mock_merge_field_adder) { double(:mock_merge_field_adder) }
let(:mock_gibbon_list) { double(:mock_gibbon_list) }
let!(:contacts) do
(1..3).map do |count|
create(
:contact,
account_list: account_list,
tag_list: 'tag',
people: [
build(:person, primary_email_address: build(:email_address))
],
created_at: count.weeks.from_now
)
end
end
let(:appeal) { create(:appeal, account_list: account_list) }
context '#export_contacts' do
it 'uses the connection handler and export_contacts! 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, :export_contacts!, nil, false)
subject.export_contacts
end
end
context '#export_contacts!' do
let(:contact) { Contact.order(:created_at).first }
let!(:mail_chimp_member) do
create(
:mail_chimp_member,
mail_chimp_account: mail_chimp_account,
list_id: list_id,
email: contact.people.first.primary_email_address.email
)
end
let(:unsubscribed_email) { contact.people.first.primary_email_address.email }
before do
allow_any_instance_of(MailChimp::GibbonWrapper).to receive(:list_emails).and_return(['<EMAIL>'])
allow_any_instance_of(MailChimp::GibbonWrapper).to receive(:gibbon_list_object).and_return(mock_gibbon_list)
allow(described_class::InterestAdder).to receive(:new).and_return(mock_group_adder)
allow(described_class::Batcher).to receive(:new).and_return(mock_batcher)
allow(described_class::MergeFieldAdder).to receive(:new).and_return(mock_merge_field_adder)
end
it 'calls InterestAdder, MergeFieldAdder and Batcher instances with correct arguments' do
expect(mock_group_adder).to receive(:add_status_interests).with(['Partner - Financial', 'Partner - Pray'])
expect(mock_group_adder).to receive(:add_tags_interests).with(['tag'])
expect(mock_merge_field_adder).to receive(:add_merge_field).with('GREETING')
expect(mock_batcher).to receive(:subscribe_contacts).with(contacts)
unsubscribe_reason = 'email on contact with newsletter set to None or Physical'
expect(mock_batcher).to receive(:unsubscribe_members).with(unsubscribed_email => unsubscribe_reason)
subject.export_contacts!(contacts.map(&:id), true)
end
context 'unsubscribe reason' do
before do
allow(mock_group_adder).to receive(:add_status_interests).with(['Partner - Financial', 'Partner - Pray'])
allow(mock_group_adder).to receive(:add_tags_interests).with(['tag'])
allow(mock_merge_field_adder).to receive(:add_merge_field).with('GREETING')
allow(mock_batcher).to receive(:subscribe_contacts).with([contact])
end
it 'generates reason when send_newsletter is nil' do
contact.update(send_newsletter: nil)
unsubscribe_reason = 'email on contact with newsletter set to None or Physical'
expect(mock_batcher).to receive(:unsubscribe_members).with(unsubscribed_email => unsubscribe_reason)
subject.export_contacts!([contact.id], false)
end
it 'generates reason when person is opted out' do
contact.people.first.update(optout_enewsletter: true)
unsubscribe_reason = "email on person marked as 'Opt-out of Email Newsletter'"
expect(mock_batcher).to receive(:unsubscribe_members).with(unsubscribed_email => unsubscribe_reason)
subject.export_contacts!([contact.id], false)
end
it 'generates reason when email is not primary' do
old_email = unsubscribed_email
contact.people.first.email_addresses.create(email: '<EMAIL>', primary: true)
unsubscribe_reason = 'email marked as non-primary'
expect(mock_batcher).to receive(:unsubscribe_members).with(old_email => unsubscribe_reason)
subject.export_contacts!([contact.id], false)
end
it 'generates reason when email is historic' do
old_email = unsubscribed_email
contact.people.first.primary_email_address.update(historic: true)
unsubscribe_reason = 'email marked as historic'
expect(mock_batcher).to receive(:unsubscribe_members).with(old_email => unsubscribe_reason)
subject.export_contacts!([contact.id], false)
end
it 'generates reason when email no longer on account' do
old_email = unsubscribed_email
contact.people.first.primary_email_address.destroy!
unsubscribe_reason = 'email not in MPDX'
expect(mock_batcher).to receive(:unsubscribe_members).with(old_email => unsubscribe_reason)
subject.export_contacts!([contact.id], false)
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/company.rb
|
class Company < ApplicationRecord
has_many :company_positions, dependent: :destroy
has_many :people, through: :company_positions
has_many :company_partnerships, dependent: :destroy
has_many :account_lists, through: :company_partnerships
belongs_to :master_company
before_create :find_master_company
after_destroy :clean_up_master_company
def to_s
name
end
private
def find_master_company
self.master_company_id = MasterCompany.find_or_create_for_company(self).id unless master_company_id
end
def clean_up_master_company
master_company.destroy if master_company.companies.blank?
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170907182701_add_remote_id_index_to_activities.rb
|
<gh_stars>0
class AddRemoteIdIndexToActivities < ActiveRecord::Migration
disable_ddl_transaction!
def change
add_index :activities, :remote_id, algorithm: :concurrently
end
end
|
chuckmersereau/api_practice
|
app/services/offline_org.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
# This class stubs out data server stuff for orgs that don't have anything for us to download
require_dependency 'data_server'
class OfflineOrg < DataServer
def import_all(_date_from = nil)
# Do nothing
end
def import_profiles
profile = create_designation_profile
create_designation_account(profile)
AccountList::FromProfileLinker.new(profile, org_account).link_account_list!
end
def self.requires_credentials?
false
end
private
def create_designation_profile
dps = org.designation_profiles.where(user_id: org_account.person_id)
if dps.empty?
dp = org.designation_profiles.create!(
user_id: org_account.person_id,
code: org_account.id.to_s,
name: org_account.user.to_s
)
else
dp = dps.find_by(code: org_account.id.to_s)
if dp.nil?
dp = dps.first
dp.update(code: org_account.id.to_s, name: org_account.user.to_s)
else
dp.update(name: org_account.user.to_s)
end
end
dp
end
def create_designation_account(profile)
da = org.designation_accounts.where(
designation_number: org_account.id.to_s,
active: true
).first_or_create
da.update(name: org.name.to_s)
profile.designation_accounts << da unless profile.designation_accounts.include?(da)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20130109160332_add_pledge_received_to_contact.rb
|
<filename>db/migrate/20130109160332_add_pledge_received_to_contact.rb
class AddPledgeReceivedToContact < ActiveRecord::Migration
def change
add_column :contacts, :pledge_received, :boolean, default: false, null: false
add_column :people, :profession, :string
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/people/merges_controller.rb
|
<gh_stars>0
class Api::V2::Contacts::People::MergesController < Api::V2Controller
resource_type :merges
def create
load_records
authorize_merge
merge_people
render_winner
end
private
def merge_params
params
.require(:merge)
.permit(merge_attributes)
end
def merge_attributes
[:winner_id, :loser_id]
end
def authorize_merge
authorize(@winner, :update?)
authorize(@loser, :destroy?)
end
def load_records
load_contact
load_people
end
def load_contact
@current_contact = Contact.find(params[:contact_id])
end
def load_people
@winner = Person.find(merge_params[:winner_id])
@loser = Person.find(merge_params[:loser_id])
end
def merge_people
@winner.merge(@loser)
end
def render_winner
render json: @winner,
include: include_params,
fields: field_params
end
def field_params
fields = super[:merges]
return {} unless fields
{
people: fields
}
end
def pundit_user
PunditContext.new(current_user, contact: @current_contact)
end
end
|
chuckmersereau/api_practice
|
app/services/social_item.rb
|
<reponame>chuckmersereau/api_practice
class SocialItem
From = Struct.new(:id, :name)
To = Struct.new(:id, :name)
Comment = Struct.new(:id, :from, :message, :created_time)
Like = Struct.new(:id, :name)
Action = Struct.new(:name, :link)
StoryTag = Struct.new(:id, :name, :offset, :length, :type)
FbApplication = Struct.new(:id, :name, :namespace)
attr_accessor :id, :from, :to, :message, :picture, :link, :name, :caption, :description, :icon, :story, :story_tags, :type,
:status_type, :created_time, :updated_time, :likes, :likes_count, :comments, :comments_count, :application,
:object_id
def initialize(json, names)
%w(id message picture object_id type status_type link name caption description icon story).each do |field|
send("#{field}=".to_sym, json[field]) if json[field].present?
end
@created_time = Time.at(json['created_time'])
@from = From.new(json['actor_id'], names[json['actor_id']])
@to = To.new(json['target_id'], names[json['target_id']]) if json['target_id'].present?
# if json['actions']
# @actions = []
# json['actions'].each do |action|
# @actions << Action.new(action['name'], action['link'])
# end
# end
# if json['application']
# @application = FbApplication.new(json['application']['id'], json['application']['name'], json['application']['namespace'])
# end
# if json['comments']
# @comments_count = json['comments']['count']
# if json['comments']['data']
# @comments = []
# json['comments']['data'].each do |comment|
# @comments << Comment.new(comment['id'], From.new(comment['from']['id'], comment['from']['name']),
# comment['message'], DateTime.parse(comment['created_time']))
# end
# end
# end
# if json['likes']
# @likes_count = json['likes']['count']
# if json['likes']['data']
# @likes = []
# json['likes']['data'].each do |like|
# @likes << Like.new(like['id'], like['name'])
# end
# end
# end
# if json['story_tags']
# @story_tags = []
# json['story_tags'].values.flatten.each do |tag|
# @story_tags << StoryTag.new(tag['id'], tag['name'], tag['offset'], tag['length'], tag['type'])
# end
# end
end
def body
message || story || description
end
def <=>(other)
other.created_time <=> created_time
end
end
|
chuckmersereau/api_practice
|
lib/batch_request_handler/instruments/request_limiter.rb
|
<gh_stars>0
module BatchRequestHandler
module Instruments
class RequestLimiter < BatchRequestHandler::Instrument
def initialize(_params)
@is_bad_request = false
end
def around_perform_requests(requests)
if requests.length <= 100
yield requests
else
@is_bad_request = true
[] # returning that there are no requests being processed
end
end
def around_build_response(json_responses)
if @is_bad_request
bad_request_response
else
yield json_responses
end
end
private
def bad_request_response
[
429,
{
'Content-Type' => 'application/json'
},
[
{
errors: [
{
status: 429,
title: 'Too Many Requests',
detail: 'You only able to send up to 100 requests in a batch request'
}
]
}.to_json
]
]
end
end
end
end
|
chuckmersereau/api_practice
|
app/validators/facebook_import_validator.rb
|
class FacebookImportValidator < ActiveModel::Validator
def validate(import)
# To import from facebook we need to have a valid token
if !import.user.facebook_account ||
import.user.facebook_account.token_missing_or_expired?
import.errors[:base] << _('The link to your facebook account needs to be refreshed. '\
'<a href="/auth/facebook">Click here to re-connect to facebook</a> '\
'then try your import again.')
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/contacts/tags_controller.rb
|
<gh_stars>0
class Api::V2::Contacts::TagsController < Api::V2Controller
def index
authorize_index
load_tags
render json: @tags,
status: success_status,
include: include_params,
fields: field_params
end
def create
load_contact
authorize_contact
persist_resource(contact_params[:name]) do |tag_name|
@contact.tag_list.add(tag_name)
end
end
def destroy
load_contact
authorize_contact
destroy_tag
end
private
def load_tags
@tags ||= account_lists.map(&:contact_tags).flatten.uniq.sort_by(&:name)
end
def authorize_index
account_lists.each { |account_list| authorize(account_list, :show?) }
end
def destroy_tag
persist_resource(params[:tag_name]) do |tag_name|
@contact.tag_list.remove(tag_name)
end
head :no_content
end
def persist_resource(tag_name)
tag_error = TagValidator.new.validate(tag_name)
if tag_error
render_with_resource_errors(tag_error)
else
yield(tag_name)
@contact.save(context: persistence_context)
render json: @contact,
status: success_status,
include: include_params,
fields: field_params
end
end
def load_contact
@contact ||= Contact.find(params[:contact_id])
end
def authorize_contact
authorize @contact
end
def contact_params
params.require(:tag).permit(:name)
end
def permitted_filters
[:account_list_id]
end
def pundit_user
PunditContext.new(current_user, contact: @contact)
end
end
|
chuckmersereau/api_practice
|
app/workers/google_calendar_sync_task_worker.rb
|
<filename>app/workers/google_calendar_sync_task_worker.rb
class GoogleCalendarSyncTaskWorker
include Sidekiq::Worker
sidekiq_options queue: :api_google_sync_data_worker, unique: :until_executed
def perform(google_integration_id, task_id)
GoogleIntegration.find(google_integration_id).calendar_integrator.sync_task(task_id)
end
end
|
chuckmersereau/api_practice
|
app/serializers/coaching/account_list_serializer.rb
|
<gh_stars>0
class Coaching::AccountListSerializer < AccountListSerializer
include DisplayCase::ExhibitsHelper
include LocalizationHelper
delegate :last_prayer_letter_at,
:staff_account_ids,
:weeks_on_mpd,
to: :account_list_exhibit
attributes :balance,
:committed,
:last_prayer_letter_at,
:progress,
:received,
:staff_account_ids,
:weeks_on_mpd,
:primary_appeal
has_many :users, serializer: Coaching::PersonSerializer
def account_list_exhibit
@exhibit ||= exhibit(object)
end
def balance
locale = current_user&.locale if respond_to?(:current_user)
account_list_exhibit.formatted_balance(locale: locale || 'en')
end
def committed
account_list_exhibit.total_pledges
end
def received
account_list_exhibit.received_pledges
end
def progress
Reports::GoalProgressSerializer.new(goal_progress)
.to_h
.except(:account_list) # redundant
end
private
def goal_progress
Reports::GoalProgress.new(account_list: object)
end
end
|
chuckmersereau/api_practice
|
spec/controllers/api/v2/account_lists/designation_accounts_controller_spec.rb
|
require 'rails_helper'
describe Api::V2::AccountLists::DesignationAccountsController, type: :controller do
let(:factory_type) { :designation_account }
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let(:account_list_id) { account_list.id }
let!(:designation_account) { create(:designation_account, account_lists: [account_list]) }
let!(:second_designation_account) do
create(:designation_account, account_lists: [account_list], created_at: 1.day.from_now)
end
let(:id) { designation_account.id }
let(:resource) { designation_account }
let(:parent_param) { { account_list_id: account_list_id } }
let(:correct_attributes) { attributes_for(:designation_account) }
let(:given_update_reference_key) { :active }
let(:given_update_reference_value) { false }
let(:correct_attributes) { attributes_for(:designation_account, active: false) }
let(:unpermitted_attributes) { attributes_for(:designation_account, name: 'Appeal 3') }
let(:dont_run_incorrect_update) { true }
include_examples 'index_examples'
include_examples 'show_examples'
include_examples 'update_examples'
describe '#index' do
before { api_login(user) }
describe 'filter[wildcard_search]' do
context 'designation_number starts with' do
let!(:designation_account) { create(factory_type, designation_number: '1234', account_lists: [account_list]) }
it 'returns designation_account' do
get :index, account_list_id: account_list_id, filter: { wildcard_search: '12' }
expect(JSON.parse(response.body)['data'][0]['id']).to eq(designation_account.id)
end
end
context 'designation_number does not start with' do
let!(:designation_account) { create(factory_type, designation_number: '1234', account_lists: [account_list]) }
it 'returns no designation_accounts' do
get :index, account_list_id: account_list_id, filter: { wildcard_search: '34' }
expect(JSON.parse(response.body)['data'].count).to eq(0)
end
end
context 'name contains' do
let!(:donor_account) { create(factory_type, name: 'abcd', account_lists: [account_list]) }
it 'returns designation_account' do
get :index, account_list_id: account_list_id, filter: { wildcard_search: 'bc' }
expect(JSON.parse(response.body)['data'][0]['id']).to eq(donor_account.id)
end
end
context 'name does not contain' do
let!(:donor_account) { create(factory_type, name: 'abcd', account_lists: [account_list]) }
it 'returns no designation_accounts' do
get :index, account_list_id: account_list_id, filter: { wildcard_search: 'def' }
expect(JSON.parse(response.body)['data'].count).to eq(0)
end
end
end
end
end
|
chuckmersereau/api_practice
|
app/services/person/google_account/contact_group.rb
|
class Person::GoogleAccount::ContactGroup < ActiveModelSerializers::Model
attr_accessor :id, :title, :created_at, :updated_at
def self.from_groups(groups, collection = [])
groups.each do |group|
collection.push(
new(
id: group.id,
title: group.title,
created_at: group.updated,
updated_at: group.updated
)
)
end
collection
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/contact_info_work_phone.rb
|
<gh_stars>0
class Contact::Filter::ContactInfoWorkPhone < Contact::Filter::Base
def execute_query(contacts, filters)
filter_work_phone = filters[:contact_info_work_phone]
contacts_ids_with_home = contact_ids_with_phone(contacts, 'work')
return contacts.where(id: contacts_ids_with_home) if filter_work_phone == 'Yes'
contacts.where.not(id: contacts_ids_with_home)
end
def title
_('Work Phone')
end
def parent
_('Contact Information')
end
def type
'radio'
end
def custom_options
[{ name: _('Yes'), id: 'Yes' }, { name: _('No'), id: 'No' }]
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170829220006_add_processed_to_pledge_donations.rb
|
class AddProcessedToPledgeDonations < ActiveRecord::Migration
def change
add_column :pledges, :processed, :boolean, default: false
end
end
|
chuckmersereau/api_practice
|
spec/services/contact_multi_add_spec.rb
|
<gh_stars>0
require 'rails_helper'
describe ContactMultiAdd do
let(:account_list) { create(:account_list) }
subject { ContactMultiAdd.new(account_list) }
let(:contact_attrs) do
{ first_name: 'John', last_name: 'Doe', spouse_first_name: 'Jane',
notes: 'Notes', email: '<EMAIL>', phone: '213-222-3333',
spouse_email: '<EMAIL>', spouse_phone: '407-555-6666',
street: '1 Way', city: 'Somewhere', state: 'IL', postal_code: '60660' }
end
before { stub_smarty_streets }
context '#add_contacts' do
it 'adds contacts with correct fields' do
expect do
@contacts, @bad_count = subject.add_contacts(0 => contact_attrs)
end.to change(Contact, :count).by(1)
expect(@bad_count).to eq(0)
expect(@contacts.count).to eq(1)
contact = @contacts.first
expect(contact.account_list).to eq(account_list)
expect(contact.notes).to eq('Notes')
expect(contact.greeting).to eq('John & Jane')
expect(contact.name).to eq('Doe, John & Jane')
expect(contact.addresses.count).to eq(1)
address = contact.addresses.first
expect(address.street).to eq('1 Way')
expect(address.city).to eq('Somewhere')
expect(address.state).to eq('IL')
expect(address.primary_mailing_address).to be_truthy
expect(address.postal_code).to eq('60660')
expect(contact.people.count).to eq(2)
john = contact.people.first
expect(john.first_name).to eq('John')
expect(john.last_name).to eq('Doe')
expect(john.phone_numbers.count).to eq(1)
expect(john.phone_numbers.first.number).to eq('+12132223333')
expect(john.email_addresses.count).to eq(1)
expect(john.email_addresses.first.email).to eq('<EMAIL>')
jane = contact.people.second
expect(jane.first_name).to eq('Jane')
expect(jane.last_name).to eq('Doe')
expect(jane.phone_numbers.count).to eq(1)
expect(jane.phone_numbers.first.number).to eq('+14075556666')
expect(jane.email_addresses.count).to eq(1)
expect(jane.email_addresses.first.email).to eq('<EMAIL>')
end
it 'ignores fully blank rows' do
attrs = {
0 => contact_attrs,
1 => { first_name: '', last_name: ' ' }
}
expect do
@contacts, @bad_count = subject.add_contacts(attrs)
end.to change(Contact, :count).by(1)
expect(@bad_count).to eq(0)
end
it 'counts rows with no first or last name as a bad row' do
contacts, bad_count = subject.add_contacts(0 => { street: 'some data' })
expect(bad_count).to eq(1)
expect(contacts).to be_empty
end
it 'counts a row with a bad email as bad' do
contacts, bad_count = subject.add_contacts(0 => { last_name: 'Doe', email: 'bad' })
expect(bad_count).to eq(1)
expect(contacts).to be_empty
end
it 'defaults one unspecified first or last name to Unknown' do
attrs = { 0 => { first_name: 'John' }, 1 => { last_name: 'Doe' } }
expect do
@contacts, @bad_count = subject.add_contacts(attrs)
end.to change(Contact, :count).by(2)
expect(@bad_count).to eq(0)
expect(@contacts.first.last_name).to eq('Unknown')
expect(@contacts.second.first_name).to eq('Unknown')
end
it 'sets the referrer if specified' do
referrer = create(:contact)
ContactMultiAdd.new(account_list, referrer).add_contacts(0 => contact_attrs)
expect(account_list.contacts.last.contacts_that_referred_me.to_a).to eq([referrer])
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/reports/questions_controller.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
class Api::V2::Reports::QuestionsController < ApplicationController
def index
@questions = Question.all
render json: @questions
end
end
|
chuckmersereau/api_practice
|
spec/preloaders/application_preloader/include_associations_fetcher_spec.rb
|
require 'rails_helper'
RSpec.describe ApplicationPreloader::IncludeAssociationsFetcher do
context '#fetch_include_associations' do
let(:association_preloader_mapping) { { contacts_that_referred_me: Api::V2::ContactsPreloader } }
let(:resource_path) { 'Api::V2::Contacts' }
let(:include_params) { ['contacts_that_referred_me', 'people.email_addresses'] }
let(:field_params) { { people: 'email' } }
subject { described_class.new(association_preloader_mapping, resource_path) }
it 'includes all included resources and the appropriate associations for each of those' do
expect(Api::V2::ContactsPreloader).to receive(:new).with([], field_params, 'contacts_that_referred_me')
.and_call_original
expect_any_instance_of(Api::V2::ContactsPreloader).to receive(:associations_to_preload).and_return([])
expect(Api::V2::Contacts::PeoplePreloader).to receive(:new).with(['email_addresses'], field_params, 'people')
.and_call_original
expect_any_instance_of(Api::V2::Contacts::PeoplePreloader).to receive(:associations_to_preload)
.and_return([:email_addresses])
result = subject.fetch_include_associations(include_params, field_params)
expect(result).to match_array([:contacts_that_referred_me, people: [:email_addresses]])
end
end
end
|
chuckmersereau/api_practice
|
spec/acceptance/api/v2/contacts/people/merges_spec.rb
|
require 'rails_helper'
require 'rspec_api_documentation/dsl'
resource 'Contacts > People > Merges' do
include_context :json_headers
documentation_scope = :people_api_merges
# This is required!
# This is the resource's JSONAPI.org `type` attribute to be validated against.
let(:resource_type) { 'people' }
let(:request_type) { 'merges' }
# 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, name: '<NAME>', account_list: account_list) }
let(:contact_id) { contact.id }
let!(:winner) { create(:person, first_name: 'John', last_name: 'Doe') }
let!(:loser) { create(:person, first_name: 'John', last_name: '<NAME>') }
before do
contact.people << winner
contact.people << loser
end
# This is the reference data used to create/update a resource.
# specify the `attributes` specifically in your request actions below.
let(:form_data) { build_data(attributes, relationships: relationships) }
# List your expected resource keys vertically here (alphabetical please!)
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
# List out any additional attribute keys that will be alongside
# the attributes of the resources.
#
# Remove if not needed.
let(:additional_attribute_keys) do
%w(
relationships
)
end
# This is the scope in how these endpoints will be organized in the
# generated documentation.
#
# :entities should be used for "top level" resources, and the top level
# resources should be used for nested resources.
#
# Ex: Api > v2 > Contacts - :entities would be the scope
# Ex: Api > v2 > Contacts > Email Addresses - :contacts would be the scope
documentation_scope = :people
context 'authorized user' do
before { api_login(user) }
# create
post '/api/v2/contacts/:contact_id/people/merges' do
with_options scope: [:data, :attributes] do
parameter 'winner_id', 'The ID of the person that should win the merge'
parameter 'loser_id', 'The ID of the person that should lose the merge'
end
let(:attributes) { {} }
let(:relationships) do
{
winner: {
data: {
type: 'people',
id: winner.id
}
},
loser: {
data: {
type: 'people',
id: loser.id
}
}
}
end
example 'Merge [CREATE]', document: documentation_scope do
explanation 'Create Merge'
do_request data: form_data
check_resource(additional_attribute_keys)
expect(response_status).to eq 200
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/picture.rb
|
class Picture < ApplicationRecord
include HasPrimary
@@primary_scope = :picture_of
mount_uploader :image, ImageUploader
belongs_to :picture_of, polymorphic: true, touch: true
end
|
chuckmersereau/api_practice
|
spec/support/stub_googleapi.rb
|
<filename>spec/support/stub_googleapi.rb
RSpec.configure do |config|
config.before(:each) do |_example|
stub_google_geocoder
end
end
|
chuckmersereau/api_practice
|
app/services/concerns/filter/searchable_in_parts.rb
|
module Concerns::Filter::SearchableInParts
private
def sql_condition_to_search_columns_in_parts(*columns)
search_term_parts_hash.keys.collect do |part_key|
columns.collect do |column|
"#{column} ilike :#{part_key}"
end.join(' OR ').prepend('(') + ')'
end.flatten.join(' AND ').prepend('(') + ')'
end
def search_term_parts_hash
@search_term_parts_hash ||= @search_term.gsub(/[,-]/, ' ').split(' ').each_with_object({}) do |search_term_part, hash|
hash["search_part_#{hash.size}".to_sym] = "%#{search_term_part}%"
hash
end
end
def query_params(extra_params = {})
{ search: "%#{@search_term}%" }.merge(extra_params)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.