diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 3eeab7c74..dfce00758 100755 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -19,15 +19,17 @@ def set_locale end end + # rubocop:disable Style/UnlessLogicalOperators def redirect_to_maintenance if Settings&.maintenance&.maintenance_mode && !current_user - unless self.class == Users::SessionsController && + unless instance_of?(Users::SessionsController) && ((Settings.maintenance.maintenance_token && params[:maintenance_token] == Settings.maintenance.maintenance_token) || params[:format] == "json") redirect_to Settings.maintenance.maintenance_page, allow_other_host: true end end end + # rubocop:enable Style/UnlessLogicalOperators protected @@ -62,7 +64,7 @@ def render_json(&block) rescue ExpiredTokenError => e logger.info "422: #{e}".red.bold result = {status: 422, json: {error: e.message}} - rescue Exception => e # a non-validation related exception + rescue => e # a non-validation related exception logger.error "500: #{e}".red.bold logger.error e.backtrace.take(5).map { |l| ">>".red.bold + " #{l}" }.join("\n").red result = {status: 500, json: {error: e.message, backtrace: e.backtrace}} @@ -147,7 +149,7 @@ def after_inactive_sign_up_path_for(resource) private def current_user_id - current_user && current_user.id + current_user&.id end # Overload handle_unverified_request to ensure that diff --git a/app/controllers/campaigns/donations_controller.rb b/app/controllers/campaigns/donations_controller.rb index beb20ebdf..aa31a0b73 100644 --- a/app/controllers/campaigns/donations_controller.rb +++ b/app/controllers/campaigns/donations_controller.rb @@ -8,7 +8,7 @@ class DonationsController < ApplicationController def index respond_to do |format| format.csv do - file_date = Date.today.strftime("%m-%d-%Y") + file_date = Time.zone.today.strftime("%m-%d-%Y") donations = QueryDonations.campaign_export(current_campaign.id) send_data(Format::Csv.from_vectors(donations), filename: "campaign-donations-#{file_date}.csv") end diff --git a/app/controllers/campaigns_controller.rb b/app/controllers/campaigns_controller.rb index 7126b5e22..e077a2786 100644 --- a/app/controllers/campaigns_controller.rb +++ b/app/controllers/campaigns_controller.rb @@ -67,7 +67,7 @@ def create json_saved campaign, "Campaign created! Well done." else profile_id = params[:campaign][:profile_id] - Profile.find(profile_id).update_attributes params[:profile] + Profile.find(profile_id).update params[:profile] render json: CreatePeerToPeerCampaign.create(params[:campaign], profile_id) end end @@ -76,7 +76,7 @@ def update Time.use_zone(current_nonprofit.timezone || "UTC") do params[:campaign][:end_datetime] = Chronic.parse(params[:campaign][:end_datetime]) if params[:campaign][:end_datetime].present? end - current_campaign.update_attributes params[:campaign] + current_campaign.update params[:campaign] json_saved current_campaign, "Successfully updated!" end diff --git a/app/controllers/concerns/controllers/api_new/jbuilder_expansions.rb b/app/controllers/concerns/controllers/api_new/jbuilder_expansions.rb index c6ec0f1a9..7c52b89f4 100644 --- a/app/controllers/concerns/controllers/api_new/jbuilder_expansions.rb +++ b/app/controllers/concerns/controllers/api_new/jbuilder_expansions.rb @@ -403,6 +403,12 @@ def leaf? end end + def self.create_from(root_tree_node) + er = ExpansionTree.new + er.root_node = root_tree_node + er + end + private # given a set of SPaths, build a tree to describe @@ -415,11 +421,5 @@ def parse_paths(paths = []) end end end - - def self.create_from(root_tree_node) - er = ExpansionTree.new - er.root_node = root_tree_node - er - end end end diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb index 37abc7fba..304fd4f88 100644 --- a/app/controllers/events_controller.rb +++ b/app/controllers/events_controller.rb @@ -43,7 +43,7 @@ def update params[:event][:start_datetime] = Chronic.parse(params[:event][:start_datetime]) if params[:event][:start_datetime].present? params[:event][:end_datetime] = Chronic.parse(params[:event][:end_datetime]) if params[:event][:end_datetime].present? end - current_event.update_attributes(params[:event]) + current_event.update(params[:event]) json_saved current_event, "Successfully updated" end diff --git a/app/controllers/image_attachments_controller.rb b/app/controllers/image_attachments_controller.rb index ab48f4a90..1139150a5 100644 --- a/app/controllers/image_attachments_controller.rb +++ b/app/controllers/image_attachments_controller.rb @@ -13,7 +13,7 @@ def create end def remove - @image = ImageAttachment.select { |img| img.file_url == params[:src] }.first + @image = ImageAttachment.find { |img| img.file_url == params[:src] } if @image @image.destroy render json: @image diff --git a/app/controllers/nonprofits/custom_field_joins_controller.rb b/app/controllers/nonprofits/custom_field_joins_controller.rb index 1376abbab..4f3f7248e 100644 --- a/app/controllers/nonprofits/custom_field_joins_controller.rb +++ b/app/controllers/nonprofits/custom_field_joins_controller.rb @@ -20,7 +20,7 @@ def modify end supporter_ids = if params[:selecting_all] - QuerySupporters.full_filter_expr(current_nonprofit.id, params[:query]).select("supporters.id").execute.map { |h| h["id"] } + QuerySupporters.full_filter_expr(current_nonprofit.id, params[:query]).select("supporters.id").execute.pluck("id") else params[:supporter_ids].map(&:to_i) end diff --git a/app/controllers/nonprofits/nonprofit_keys_controller.rb b/app/controllers/nonprofits/nonprofit_keys_controller.rb index b903a45bb..972d22df0 100644 --- a/app/controllers/nonprofits/nonprofit_keys_controller.rb +++ b/app/controllers/nonprofits/nonprofit_keys_controller.rb @@ -27,7 +27,7 @@ def mailchimp_landing session.delete(:current_mailchimp_nonprofit_id) begin session[:mailchimp_access_token] = InsertNonprofitKeys.insert_mailchimp_access_token(@nonprofit.id, params[:code]) - rescue Exception => e + rescue => e flash[:notice] = "Unable to connect to your Mailchimp account, please try again. (Error: #{e})" redirect_to "/settings" return diff --git a/app/controllers/nonprofits/payments_controller.rb b/app/controllers/nonprofits/payments_controller.rb index aeb850b53..ed6c9bd66 100644 --- a/app/controllers/nonprofits/payments_controller.rb +++ b/app/controllers/nonprofits/payments_controller.rb @@ -43,7 +43,7 @@ def show def update @payment = current_nonprofit.payments.find(params[:id]) - @payment.update_attributes(params[:payment]) + @payment.update(params[:payment]) json_saved @payment end diff --git a/app/controllers/nonprofits/stripe_accounts_controller.rb b/app/controllers/nonprofits/stripe_accounts_controller.rb index 56a0f63e6..9aeaeba50 100644 --- a/app/controllers/nonprofits/stripe_accounts_controller.rb +++ b/app/controllers/nonprofits/stripe_accounts_controller.rb @@ -29,7 +29,7 @@ def begin_verification StripeAccountUtils.find_or_create(current_nonprofit.id) current_nonprofit.reload - status = NonprofitVerificationProcessStatus.where("stripe_account_id = ?", current_nonprofit.stripe_account_id).first + status = NonprofitVerificationProcessStatus.where(stripe_account_id: current_nonprofit.stripe_account_id).first status ||= NonprofitVerificationProcessStatus.new(stripe_account_id: current_nonprofit.stripe_account_id) unless status.started_at diff --git a/app/controllers/nonprofits/supporter_notes_controller.rb b/app/controllers/nonprofits/supporter_notes_controller.rb index 4703aa5b8..a3ffbdbff 100644 --- a/app/controllers/nonprofits/supporter_notes_controller.rb +++ b/app/controllers/nonprofits/supporter_notes_controller.rb @@ -12,7 +12,7 @@ def create # put /nonprofits/:nonprofit_id/supporters/:supporter_id/supporter_notes/:id def update - params[:supporter_note][:user_id] ||= current_user && current_user.id + params[:supporter_note][:user_id] ||= current_user&.id params[:supporter_note][:id] = params[:id] render_json { UpdateSupporterNotes.update(params[:supporter_note]) } end diff --git a/app/controllers/nonprofits/supporters_controller.rb b/app/controllers/nonprofits/supporters_controller.rb index 3d52855e1..85249752c 100644 --- a/app/controllers/nonprofits/supporters_controller.rb +++ b/app/controllers/nonprofits/supporters_controller.rb @@ -3,7 +3,7 @@ module Nonprofits class SupportersController < ApplicationController include Controllers::NonprofitHelper - before_action :authenticate_nonprofit_user!, except: [:new, :create] + before_action :authenticate_nonprofit_user!, except: [:create] before_action :validate_allowed!, only: [:create] rescue_from ::TempBlockError, with: :handle_temp_block_error @@ -19,7 +19,7 @@ def index end format.csv do - file_date = Date.today.strftime("%m-%d-%Y") + file_date = Time.zone.today.strftime("%m-%d-%Y") supporters = QuerySupporters.for_export(params[:nonprofit_id], params) send_data(Format::Csv.from_vectors(supporters), filename: "supporters-#{file_date}.csv") end @@ -82,7 +82,7 @@ def update def bulk_delete supporter_ids = if params[:selecting_all] - QuerySupporters.full_filter_expr(current_nonprofit.id, params[:query]).select("supporters.id").execute.map { |h| h["id"] } + QuerySupporters.full_filter_expr(current_nonprofit.id, params[:query]).select("supporters.id").execute.pluck("id") else params[:supporter_ids].map(&:to_i) end diff --git a/app/controllers/nonprofits/tag_joins_controller.rb b/app/controllers/nonprofits/tag_joins_controller.rb index 15f28caf9..5a34fe478 100644 --- a/app/controllers/nonprofits/tag_joins_controller.rb +++ b/app/controllers/nonprofits/tag_joins_controller.rb @@ -14,7 +14,7 @@ def index # selected supporters' tags or all supporters' tags def modify supporter_ids = if params[:selecting_all] - QuerySupporters.full_filter_expr(current_nonprofit.id, params[:query]).select("supporters.id").execute.map { |h| h["id"] } + QuerySupporters.full_filter_expr(current_nonprofit.id, params[:query]).select("supporters.id").execute.pluck("id") else params[:supporter_ids].map(&:to_i) end diff --git a/app/controllers/nonprofits_controller.rb b/app/controllers/nonprofits_controller.rb index 7becb6322..5c5a8cd5f 100755 --- a/app/controllers/nonprofits_controller.rb +++ b/app/controllers/nonprofits_controller.rb @@ -56,7 +56,7 @@ def create def update flash[:notice] = "Update successful!" - current_nonprofit.update_attributes params[:nonprofit].except(:verification_status) + current_nonprofit.update params[:nonprofit].except(:verification_status) current_nonprofit.clear_cache json_saved current_nonprofit end @@ -129,7 +129,7 @@ def countries_list(locale) all_countries = ISO3166::Country.translations(locale) if Settings.intntl.all_countries - countries = all_countries.select { |code, name| Settings.intntl.all_countries.include? code } + countries = all_countries.slice(*Settings.intntl.all_countries) countries = countries.map { |code, name| [code.upcase, name] }.sort_by { |a| a[1] } countries.push([Settings.intntl.other_country.upcase, I18n.t("nonprofits.donate.info.supporter.other_country")]) if Settings.intntl.other_country countries diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index 6998de843..d3f07b64f 100755 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -45,7 +45,7 @@ def update else current_user.profile end - @profile.update_attributes(params[:profile]) + @profile.update(params[:profile]) json_saved @profile, "Profile updated" end diff --git a/app/controllers/recurring_donations_controller.rb b/app/controllers/recurring_donations_controller.rb index 44ce1e09d..970778706 100644 --- a/app/controllers/recurring_donations_controller.rb +++ b/app/controllers/recurring_donations_controller.rb @@ -43,7 +43,7 @@ def update end def update_amount - rd = RecurringDonation.where("id = ?", params[:id]).first + rd = RecurringDonation.where(id: params[:id]).first if rd && params[:edit_token] == rd["edit_token"] begin amount_response = UpdateRecurringDonations.update_amount(rd, params[:token], params[:amount], params[:fee_covered]) @@ -61,8 +61,8 @@ def update_amount def print_currency(cents, unit = "EUR", sign = true) dollars = cents.to_f / 100.0 - dollars = view_context.number_to_currency(dollars, unit: "#{unit}", precision: (dollars.round == dollars) ? 0 : 2) - dollars = dollars[1..-1] if !sign + dollars = view_context.number_to_currency(dollars, unit: unit.to_s, precision: (dollars.round == dollars) ? 0 : 2) + dollars = dollars[1..] if !sign dollars end end diff --git a/app/controllers/static_controller.rb b/app/controllers/static_controller.rb index 521a568e8..bb3f190be 100644 --- a/app/controllers/static_controller.rb +++ b/app/controllers/static_controller.rb @@ -7,19 +7,27 @@ def terms_and_privacy end def ccs - ccs_method = (!Settings.ccs) ? "local_tar_gz" : Settings.ccs.ccs_method - if ccs_method == "local_tar_gz" - temp_file = "#{Rails.root.join("tmp/#{Time.current.to_i}.tar.gz")}" - result = Kernel.system("git archive --format=tar.gz -o #{temp_file} HEAD") - if result - send_file(temp_file, type: "application/gzip") - else - head 500 - end - elsif ccs_method == "github" - git_hash = File.read("#{Rails.root.join("CCS_HASH")}") + if Settings.ccs&.ccs_method.presence == "github" redirect_to "https://github.com/#{Settings.ccs.options.account}/#{Settings.ccs.options.repo}/tree/#{git_hash}", allow_other_host: true + elsif create_archive + send_file(temp_file, type: "application/gzip") + else + head 500 end end + + private + + def git_hash + @git_hash ||= File.read(Rails.root.join("CCS_HASH").to_s) + end + + def temp_file + @temp_file ||= Rails.root.join("tmp/#{Time.current.to_i}.tar.gz").to_s + end + + def create_archive + Kernel.system("git archive --format=tar.gz -o #{temp_file} HEAD") + end end diff --git a/app/controllers/super_admins_controller.rb b/app/controllers/super_admins_controller.rb index f77323b74..ae88c9cdf 100644 --- a/app/controllers/super_admins_controller.rb +++ b/app/controllers/super_admins_controller.rb @@ -18,7 +18,7 @@ def search_profiles def search_fullcontact begin result = FullContact.person(email: params[:search]) - rescue Exception + rescue result = "" end render json: [result] @@ -29,7 +29,7 @@ def resend_user_confirmation profile_id: {required: true, is_integer: true} }) - profile = Profile.includes(:user).where("id = ?", params[:profile_id]).first + profile = Profile.includes(:user).where(id: params[:profile_id]).first unless profile.user raise ArgumentError.new("#{params[:profile_id]} is a profile without a valid user") end @@ -56,7 +56,7 @@ def recurring_donations_without_cards } } - send_data(csv_out, filename: "recurring_donations_without_cards-#{Time.now.to_date}.csv") + send_data(csv_out, filename: "recurring_donations_without_cards-#{Time.zone.now.to_date}.csv") end end end diff --git a/app/controllers/ticket_levels_controller.rb b/app/controllers/ticket_levels_controller.rb index 3fe7a29eb..dd67e64ac 100644 --- a/app/controllers/ticket_levels_controller.rb +++ b/app/controllers/ticket_levels_controller.rb @@ -19,7 +19,7 @@ def create end def update - current_ticket_level.update_attributes params[:ticket_level] + current_ticket_level.update params[:ticket_level] json_saved current_ticket_level, "Ticket level updated" end diff --git a/app/controllers/tickets_controller.rb b/app/controllers/tickets_controller.rb index 4ff2c69c1..283dab7b7 100644 --- a/app/controllers/tickets_controller.rb +++ b/app/controllers/tickets_controller.rb @@ -30,7 +30,7 @@ def index respond_to do |format| format.html format.csv do - file_date = Date.today.strftime("%m-%d-%Y") + file_date = Time.zone.today.strftime("%m-%d-%Y") filename = "tickets-#{file_date}" @tickets = QueryTickets.for_export(@event.id, params) send_data(Format::Csv.from_vectors(@tickets), filename: "#{filename}.csv") @@ -44,7 +44,7 @@ def index # PUT nonprofits/:nonprofit_id/events/:event_id/tickets/:id/add_note def add_note - current_nonprofit.tickets.find(params[:id]).update_attributes(note: params[:ticket][:note]) + current_nonprofit.tickets.find(params[:id]).update(note: params[:ticket][:note]) render json: {} end diff --git a/app/controllers/users/confirmations_controller.rb b/app/controllers/users/confirmations_controller.rb index 85848014f..66c2ca388 100644 --- a/app/controllers/users/confirmations_controller.rb +++ b/app/controllers/users/confirmations_controller.rb @@ -23,7 +23,7 @@ def exists def confirm @user = User.find(params[:id]) - if @user.valid? && @user.update_attributes(params[:user].except(:confirmation_token)) + if @user.valid? && @user.update(params[:user].except(:confirmation_token)) flash[:notice] = "Your account is all set!" sign_in @user redirect_to session[:donor_signup_url] || root_url diff --git a/app/controllers/users/registrations_controller.rb b/app/controllers/users/registrations_controller.rb index 00bbb6293..31ed59801 100644 --- a/app/controllers/users/registrations_controller.rb +++ b/app/controllers/users/registrations_controller.rb @@ -32,7 +32,7 @@ def update if current_user.pending_password && params[:user][:password] && params[:user][:password_confirmation] params[:user][:pending_password] = false end - success = current_user.update_attributes(params[:user]) + success = current_user.update(params[:user]) errs = current_user.errors.full_messages else success = false diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 37b17aa2c..262c88e0e 100755 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -14,8 +14,8 @@ def devise_mapping def print_currency(cents, unit = "EUR", sign = true) dollars = cents.to_f / 100.0 - dollars = number_to_currency(dollars, unit: "#{unit}", precision: (dollars.round == dollars) ? 0 : 2) - dollars = dollars[1..-1] if !sign + dollars = number_to_currency(dollars, unit: unit.to_s, precision: (dollars.round == dollars) ? 0 : 2) + dollars = dollars[1..] if !sign dollars end diff --git a/app/helpers/card_helper.rb b/app/helpers/card_helper.rb index 57bd37932..bc60476be 100644 --- a/app/helpers/card_helper.rb +++ b/app/helpers/card_helper.rb @@ -1,6 +1,6 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module CardHelper def expiration_years - (0..15).map { |n| (Date.today + n.years).year } + (0..15).map { |n| (Time.zone.today + n.years).year } end end diff --git a/app/jobs/inline_job.rb b/app/jobs/inline_job.rb index 34652aa66..13c18b0c1 100644 --- a/app/jobs/inline_job.rb +++ b/app/jobs/inline_job.rb @@ -1,5 +1,5 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later # newer versions of Rails use an ApplicationJob so let's be cool like them -class InlineJob < ActiveJob::Base +class InlineJob < ApplicationJob :inline end diff --git a/app/jobs/mailchimp_nonprofit_user_add_job.rb b/app/jobs/mailchimp_nonprofit_user_add_job.rb index c55c28365..d9a1204cd 100644 --- a/app/jobs/mailchimp_nonprofit_user_add_job.rb +++ b/app/jobs/mailchimp_nonprofit_user_add_job.rb @@ -1,6 +1,6 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later -class MailchimpNonprofitUserAddJob < ActiveJob::Base +class MailchimpNonprofitUserAddJob < ApplicationJob queue_as :default def perform(user, nonprofit) diff --git a/app/legacy_lib/audit.rb b/app/legacy_lib/audit.rb index e8fa075e4..7e4912743 100644 --- a/app/legacy_lib/audit.rb +++ b/app/legacy_lib/audit.rb @@ -21,7 +21,7 @@ def self.payout_check(id) gross = p.payments.sum(:gross_amount) fees = p.payments.sum(:fee_total) net = p.payments.sum(:net_amount) - puts [ + Rails.logger.debug [ [p.gross_amount, p.fee_total, p.net_amount].join(", ") + " -- payout columns", [gross, fees, net].join(", ") + " -- summed from payments", [p.gross_amount - gross, p.fee_total - fees, p.net_amount - net].join(", ") + " -- differences" @@ -55,18 +55,18 @@ def self.find_missing_charges(transfers) # Audit some basic balances for a nonprofit with those on Stripe def self.audit_balances(id) np = Nonprofit.find(id) - puts "Stripe Dashboard: https://dashboard.stripe.com/#{np.stripe_account_id}" - puts "CC Payments: https://commitchange.com/nonprofits/#{id}/payments" - puts "CC Payouts: https://commitchange.com/nonprofits/#{id}/payouts" + Rails.logger.debug { "Stripe Dashboard: https://dashboard.stripe.com/#{np.stripe_account_id}" } + Rails.logger.debug { "CC Payments: https://commitchange.com/nonprofits/#{id}/payments" } + Rails.logger.debug { "CC Payouts: https://commitchange.com/nonprofits/#{id}/payouts" } begin stripe_balances = Stripe::Balance.retrieve(stripe_account: np.stripe_account_id) available = stripe_balances["available"].first["amount"] pending = stripe_balances["pending"].first["amount"] - rescue Exception + rescue available = 0 pending = 0 - puts "UNRECOGNIZED STRIPE ACCOUNT ID: #{np.stripe_account_id}" + Rails.logger.debug { "UNRECOGNIZED STRIPE ACCOUNT ID: #{np.stripe_account_id}" } end bal = np_balances(id) { diff --git a/app/legacy_lib/cancel_billing_subscription.rb b/app/legacy_lib/cancel_billing_subscription.rb index 6ab6001d0..7e91ea642 100644 --- a/app/legacy_lib/cancel_billing_subscription.rb +++ b/app/legacy_lib/cancel_billing_subscription.rb @@ -25,7 +25,7 @@ def self.with_stripe(nonprofit) end billing_plan_id = Settings.default_bp.id - billing_subscription.update_attributes({ + billing_subscription.update({ billing_plan_id: billing_plan_id, status: "active" }) diff --git a/app/legacy_lib/create_campaign_gift.rb b/app/legacy_lib/create_campaign_gift.rb index 89641710b..7623d6fd5 100644 --- a/app/legacy_lib/create_campaign_gift.rb +++ b/app/legacy_lib/create_campaign_gift.rb @@ -15,12 +15,12 @@ def self.create(params) } }) - donation = Donation.includes(:nonprofit).includes(:supporter).includes(:recurring_donation).includes(:campaign_gifts).where("id = ?", params[:donation_id]).first + donation = Donation.includes(:nonprofit).includes(:supporter).includes(:recurring_donation).includes(:campaign_gifts).where(id: params[:donation_id]).first unless donation raise ParamValidation::ValidationError.new("#{params[:donation_id]} is not a valid donation id.", {key: :donation_id}) end - campaign_gift_option = CampaignGiftOption.includes(:campaign).where("id = ?", params[:campaign_gift_option_id]).first + campaign_gift_option = CampaignGiftOption.includes(:campaign).where(id: params[:campaign_gift_option_id]).first unless campaign_gift_option raise ParamValidation::ValidationError.new("#{params[:campaign_gift_option_id]} is not a valid campaign gift option", {key: :campaign_gift_option_id}) end diff --git a/app/legacy_lib/create_custom_field_join.rb b/app/legacy_lib/create_custom_field_join.rb index fcbc9b24c..0852992a8 100644 --- a/app/legacy_lib/create_custom_field_join.rb +++ b/app/legacy_lib/create_custom_field_join.rb @@ -11,14 +11,14 @@ def self.create(supporter, profile_id, params) # * value [Object] the expected value of the field. If this key is an empty string, we remove the custom_field def self.modify(np, user, supporter_ids, custom_fields) - return if supporter_ids.nil? || supporter_ids.empty? - return if custom_fields.nil? || custom_fields.empty? + return if supporter_ids.blank? + return if custom_fields.blank? supporter_ids.each do |sid| supporter = np.supporters.find(sid) custom_fields.each do |custom_field| existing = supporter.custom_field_joins.find_by_custom_field_master_id(custom_field[:custom_field_master_id]) if existing - existing.update_attributes({ + existing.update({ custom_field_master_id: custom_field[:custom_field_master_id], value: custom_field[:value] }) diff --git a/app/legacy_lib/create_peer_to_peer_campaign.rb b/app/legacy_lib/create_peer_to_peer_campaign.rb index c4df427a5..cbc5296c3 100644 --- a/app/legacy_lib/create_peer_to_peer_campaign.rb +++ b/app/legacy_lib/create_peer_to_peer_campaign.rb @@ -18,24 +18,23 @@ def self.create(campaign_params, profile_id) # child campaigns are always in dollars, not supporters p2p_params[:goal_is_in_supporters] = false - campaign = Campaign.create(p2p_params) - + campaign = Campaign.new(p2p_params) campaign.published = true campaign.profile = profile campaign.save begin - campaign.update_attribute(:main_image, parent_campaign.main_image) unless !parent_campaign.main_image + campaign.update_attribute(:main_image, parent_campaign.main_image) if parent_campaign.main_image.present? rescue Aws::S3::Errors::NoSuchKey end begin - campaign.update_attribute(:background_image, parent_campaign.background_image) unless !parent_campaign.background_image + campaign.update_attribute(:background_image, parent_campaign.background_image) if parent_campaign.background_image.present? rescue Aws::S3::Errors::NoSuchKey end begin - campaign.update_attribute(:banner_image, parent_campaign.banner_image) unless !parent_campaign.banner_image + campaign.update_attribute(:banner_image, parent_campaign.banner_image) if parent_campaign.banner_image.present? rescue Aws::S3::Errors::NoSuchKey end diff --git a/app/legacy_lib/cypher.rb b/app/legacy_lib/cypher.rb index c8c8e87ff..0c9f256f5 100644 --- a/app/legacy_lib/cypher.rb +++ b/app/legacy_lib/cypher.rb @@ -28,7 +28,7 @@ def self.decrypt(hash) decipher.update(encrypted) + decipher.final end - private + private_class_method def self.create_cipher OpenSSL::Cipher.new("aes-256-cbc") diff --git a/app/legacy_lib/delete_custom_field_joins.rb b/app/legacy_lib/delete_custom_field_joins.rb index b778cba52..4cbb59085 100644 --- a/app/legacy_lib/delete_custom_field_joins.rb +++ b/app/legacy_lib/delete_custom_field_joins.rb @@ -24,7 +24,7 @@ def self.find_multiple_custom_field_joins def self.copy_and_delete(ids_to_delete) if ids_to_delete.any? Qx.insert_into(:custom_field_joins_backup, @columns).select(@columns).from(:custom_field_joins).where("id IN ($ids)", ids: ids_to_delete).execute - CustomFieldJoin.where("id IN (?)", ids_to_delete).delete_all + CustomFieldJoin.where(id: ids_to_delete).delete_all end end diff --git a/app/legacy_lib/email.rb b/app/legacy_lib/email.rb index a7e8c2b28..38554fd4f 100644 --- a/app/legacy_lib/email.rb +++ b/app/legacy_lib/email.rb @@ -1,5 +1,5 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module Email - Regex ||= /\A[^ ]+@[^ ]+\.[^ ]+\z/i + REGEX = /\A[^ ]+@[^ ]+\.[^ ]+\z/i # PsqlRegex ||= '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$' end diff --git a/app/legacy_lib/export_payments.rb b/app/legacy_lib/export_payments.rb index 561308293..a98ec9e26 100644 --- a/app/legacy_lib/export_payments.rb +++ b/app/legacy_lib/export_payments.rb @@ -6,11 +6,11 @@ def self.initiate_export(npo_id, params, user_id) npo_id: {required: true, is_integer: true}, params: {required: true, is_hash: true}, user_id: {required: true, is_integer: true}) - npo = Nonprofit.where("id = ?", npo_id).first + npo = Nonprofit.where(id: npo_id).first unless npo raise ParamValidation::ValidationError.new("Nonprofit #{npo_id} doesn't exist!", key: :npo_id) end - user = User.where("id = ?", user_id).first + user = User.where(id: user_id).first unless user raise ParamValidation::ValidationError.new("User #{user_id} doesn't exist!", key: :user_id) end @@ -43,18 +43,21 @@ def self.run_export(npo_id, params, user_id, export_id) unless Nonprofit.exists?(npo_id) raise ParamValidation::ValidationError.new("Nonprofit #{npo_id} doesn't exist!", key: :npo_id) end - user = User.where("id = ?", user_id).first + user = User.where(id: user_id).first unless user raise ParamValidation::ValidationError.new("User #{user_id} doesn't exist!", key: :user_id) end - file_date = Time.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") + file_date = Time.zone.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") filename = "tmp/csv-exports/payments-#{export.id}-#{file_date}.csv" - url = CHUNKED_UPLOADER.upload(filename, for_export_enumerable(npo_id, params, 15000).map { |i| i.to_csv }, content_type: "text/csv", content_disposition: "attachment") + url = CHUNKED_UPLOADER.upload(filename, + for_export_enumerable(npo_id, params, 15000).map { |i| i.to_csv }, + content_type: "text/csv", + content_disposition: "attachment") export.url = url export.status = :completed - export.ended = Time.now + export.ended = Time.zone.now export.save! ExportMailer.delay.export_payments_completed_notification(export) @@ -62,11 +65,11 @@ def self.run_export(npo_id, params, user_id, export_id) if export export.status = :failed export.exception = e.to_s - export.ended = Time.now + export.ended = Time.zone.now export.save! begin - user ||= User.where("id = ?", user_id).first + user ||= User.where(id: user_id).first if user ExportMailer.delay.export_payments_failed_notification(export) end @@ -77,7 +80,7 @@ def self.run_export(npo_id, params, user_id, export_id) raise e end - private + private_class_method def self.for_export_enumerable(npo_id, query, chunk_limit = 15000) ParamValidation.new({npo_id: npo_id, query: query}, {npo_id: {required: true, is_int: true}, @@ -197,7 +200,7 @@ def self.build_donations_and_campaigns_select(export_format) end def self.build_custom_value_clause(column_name, custom_columns_and_values, custom_column_name, column_treatment = column_name) - custom_values = custom_columns_and_values&.dig(column_name)&.dig("custom_values") + custom_values = custom_columns_and_values&.dig(column_name, "custom_values") if custom_values.present? return build_custom_values_switch_case(custom_values, column_treatment, custom_column_name) end @@ -214,32 +217,32 @@ def self.build_custom_values_switch_case(custom_values, column_name, custom_colu def self.build_custom_names_for_payments(custom_names) { - "payments.date" => custom_names&.dig("payments.date")&.dig("custom_name") || "date", - "payments.gross_amount" => custom_names&.dig("payments.gross_amount")&.dig("custom_name") || "gross_amount", - "payments.fee_total" => custom_names&.dig("payments.fee_total")&.dig("custom_name") || "fee_total", - "payments.net_amount" => custom_names&.dig("payments.net_amount")&.dig("custom_name") || "net_amount", - "payments.kind" => custom_names&.dig("payments.kind")&.dig("custom_name") || "type" + "payments.date" => custom_names&.dig("payments.date", "custom_name") || "date", + "payments.gross_amount" => custom_names&.dig("payments.gross_amount", "custom_name") || "gross_amount", + "payments.fee_total" => custom_names&.dig("payments.fee_total", "custom_name") || "fee_total", + "payments.net_amount" => custom_names&.dig("payments.net_amount", "custom_name") || "net_amount", + "payments.kind" => custom_names&.dig("payments.kind", "custom_name") || "type" } end def self.build_custom_names_for_donations_and_campaigns(custom_names) { - "donations.designation" => custom_names&.dig("donations.designation")&.dig("custom_name") || "designation", + "donations.designation" => custom_names&.dig("donations.designation", "custom_name") || "designation", "donations.anonymous OR supporters.anonymous" => ( custom_names&.dig("donations.anonymous OR supporters.anonymous") || custom_names&.dig("donations.anonymous") || custom_names&.dig("supporters.anonymous") )&.dig("custom_name") || '"Anonymous?"', - "campaigns_for_export.name" => custom_names&.dig("campaigns_for_export.name")&.dig("custom_name") || "campaign", - "campaigns_for_export.id" => custom_names&.dig("campaigns_for_export.id")&.dig("custom_name") || '"Campaign Id"', - "campaigns_for_export.creator_email" => custom_names&.dig("campaigns_for_export.creator_email")&.dig("custom_name") || "campaign_creator_email", - "campaign_gift_options.name" => custom_names&.dig("campaign_gift_options.name")&.dig("custom_name") || "campaign_gift_level", - "events_for_export.name" => custom_names&.dig("events_for_export.name")&.dig("custom_name") || "event_name", - "payments.id" => custom_names&.dig("payments.id")&.dig("custom_name") || "payment_id", - "offsite_payments.check_number" => custom_names&.dig("offsite_payments.check_number")&.dig("custom_name") || "check_number", - "donations.comment" => custom_names&.dig("donations.comment")&.dig("custom_name") || "donation_note", - "donations.created_at" => custom_names&.dig("donations.created_at")&.dig("custom_name") || '"Recurring Donation Started At"', - "misc_payment_infos.fee_covered" => custom_names&.dig("misc_payment_infos.fee_covered")&.dig("custom_name") || '"Fee Covered by Supporter"' + "campaigns_for_export.name" => custom_names&.dig("campaigns_for_export.name", "custom_name") || "campaign", + "campaigns_for_export.id" => custom_names&.dig("campaigns_for_export.id", "custom_name") || '"Campaign Id"', + "campaigns_for_export.creator_email" => custom_names&.dig("campaigns_for_export.creator_email", "custom_name") || "campaign_creator_email", + "campaign_gift_options.name" => custom_names&.dig("campaign_gift_options.name", "custom_name") || "campaign_gift_level", + "events_for_export.name" => custom_names&.dig("events_for_export.name", "custom_name") || "event_name", + "payments.id" => custom_names&.dig("payments.id", "custom_name") || "payment_id", + "offsite_payments.check_number" => custom_names&.dig("offsite_payments.check_number", "custom_name") || "check_number", + "donations.comment" => custom_names&.dig("donations.comment", "custom_name") || "donation_note", + "donations.created_at" => custom_names&.dig("donations.created_at", "custom_name") || '"Recurring Donation Started At"', + "misc_payment_infos.fee_covered" => custom_names&.dig("misc_payment_infos.fee_covered", "custom_name") || '"Fee Covered by Supporter"' } end diff --git a/app/legacy_lib/export_recurring_donations.rb b/app/legacy_lib/export_recurring_donations.rb index 2bb4e2651..3ffa27af0 100644 --- a/app/legacy_lib/export_recurring_donations.rb +++ b/app/legacy_lib/export_recurring_donations.rb @@ -6,13 +6,13 @@ def self.initiate_export(npo_id, params, user_ids, export_type = :requested_by_u npo_id: {required: true, is_integer: true}, params: {required: true, is_hash: true}, user_ids: {required: true, is_array: true}) - npo = Nonprofit.where("id = ?", npo_id).first + npo = Nonprofit.where(id: npo_id).first unless npo raise ParamValidation::ValidationError.new("Nonprofit #{npo_id} doesn't exist!", key: :npo_id) end user_ids.each do |user_id| - user = User.where("id = ?", user_id).first + user = User.where(id: user_id).first unless user raise ParamValidation::ValidationError.new("User #{user_id} doesn't exist!", key: :user_id) end @@ -44,18 +44,18 @@ def self.run_export(npo_id, params, user_id, export_id, export_type = :requested unless Nonprofit.exists?(npo_id) raise ParamValidation::ValidationError.new("Nonprofit #{npo_id} doesn't exist!", key: :npo_id) end - user = User.where("id = ?", user_id).first + user = User.where(id: user_id).first unless user raise ParamValidation::ValidationError.new("User #{user_id} doesn't exist!", key: :user_id) end - file_date = Time.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") + file_date = Time.zone.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") filename = "tmp/csv-exports/recurring_donations-#{export.id}-#{file_date}.csv" url = CHUNKED_UPLOADER.upload(filename, QueryRecurringDonations.for_export_enumerable(npo_id, params, 15000).map { |i| i.to_csv }, content_type: "text/csv", content_disposition: "attachment") export.url = url export.status = :completed - export.ended = Time.now + export.ended = Time.zone.now export.save! notify_about_export_completion(export, export_type) @@ -63,7 +63,7 @@ def self.run_export(npo_id, params, user_id, export_id, export_type = :requested if export export.status = :failed export.exception = e.to_s - export.ended = Time.now + export.ended = Time.zone.now export.save! if user notify_about_export_failure(export, export_type) @@ -75,7 +75,7 @@ def self.run_export(npo_id, params, user_id, export_id, export_type = :requested def self.run_export_for_active_recurring_donations_to_csv(nonprofit_s3_key, filename, export) if filename.blank? - file_date = Time.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") + file_date = Time.zone.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") filename = "tmp/json-exports/recurring_donations-#{export.id}-#{file_date}.csv" end @@ -90,7 +90,7 @@ def self.run_export_for_active_recurring_donations_to_csv(nonprofit_s3_key, file def self.run_export_for_started_recurring_donations_to_csv(nonprofit_s3_key, filename, export) if filename.blank? - file_date = Time.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") + file_date = Time.zone.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") filename = "tmp/json-exports/recurring_donations-#{export.id}-#{file_date}.csv" end @@ -112,7 +112,7 @@ def self.get_bucket(nonprofit_s3_key) end end - private + private_class_method def self.notify_about_export_completion(export, export_type) case export_type diff --git a/app/legacy_lib/export_supporter_notes.rb b/app/legacy_lib/export_supporter_notes.rb index 46ba40407..a7def7c89 100644 --- a/app/legacy_lib/export_supporter_notes.rb +++ b/app/legacy_lib/export_supporter_notes.rb @@ -5,11 +5,11 @@ def self.initiate_export(npo_id, params, user_id) npo_id: {required: true, is_integer: true}, params: {required: true, is_hash: true}, user_id: {required: true, is_integer: true}) - npo = Nonprofit.where("id = ?", npo_id).first + npo = Nonprofit.where(id: npo_id).first unless npo raise ParamValidation::ValidationError.new("Nonprofit #{npo_id} doesn't exist!", key: :npo_id) end - user = User.where("id = ?", user_id).first + user = User.where(id: user_id).first unless user raise ParamValidation::ValidationError.new("User #{user_id} doesn't exist!", key: :user_id) end @@ -42,18 +42,18 @@ def self.run_export(npo_id, params, user_id, export_id) unless Nonprofit.exists?(npo_id) raise ParamValidation::ValidationError.new("Nonprofit #{npo_id} doesn't exist!", key: :npo_id) end - user = User.where("id = ?", user_id).first + user = User.where(id: user_id).first unless user raise ParamValidation::ValidationError.new("User #{user_id} doesn't exist!", key: :user_id) end - file_date = Time.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") + file_date = Time.zone.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") filename = "tmp/csv-exports/supporters-notes-#{export.id}-#{file_date}.csv" url = CHUNKED_UPLOADER.upload(filename, QuerySupporters.supporter_note_export_enumerable(npo_id, params, 15000).map { |i| i.to_csv }, content_type: "text/csv", content_disposition: "attachment") export.url = url export.status = :completed - export.ended = Time.now + export.ended = Time.zone.now export.save! JobQueue.queue(JobTypes::ExportSupporterNotesCompletedJob, export) @@ -61,7 +61,7 @@ def self.run_export(npo_id, params, user_id, export_id) if export export.status = :failed export.exception = e.to_s - export.ended = Time.now + export.ended = Time.zone.now export.save! if user JobQueue.queue(JobTypes::ExportSupporterNotesFailedJob, export) diff --git a/app/legacy_lib/export_supporters.rb b/app/legacy_lib/export_supporters.rb index 0cc94c632..d6af3975e 100644 --- a/app/legacy_lib/export_supporters.rb +++ b/app/legacy_lib/export_supporters.rb @@ -4,11 +4,11 @@ def self.initiate_export(npo_id, params, user_id) npo_id: {required: true, is_integer: true}, params: {required: true, is_hash: true}, user_id: {required: true, is_integer: true}) - npo = Nonprofit.where("id = ?", npo_id).first + npo = Nonprofit.where(id: npo_id).first unless npo raise ParamValidation::ValidationError.new("Nonprofit #{npo_id} doesn't exist!", key: :npo_id) end - user = User.where("id = ?", user_id).first + user = User.where(id: user_id).first unless user raise ParamValidation::ValidationError.new("User #{user_id} doesn't exist!", key: :user_id) end @@ -41,17 +41,17 @@ def self.run_export(npo_id, params, user_id, export_id) unless Nonprofit.exists?(npo_id) raise ParamValidation::ValidationError.new("Nonprofit #{npo_id} doesn't exist!", key: :npo_id) end - user = User.where("id = ?", user_id).first + user = User.where(id: user_id).first unless user raise ParamValidation::ValidationError.new("User #{user_id} doesn't exist!", key: :user_id) end - file_date = Time.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") + file_date = Time.zone.now.getutc.strftime("%m-%d-%Y--%H-%M-%S") filename = "tmp/csv-exports/supporters-#{export.id}-#{file_date}.csv" url = CHUNKED_UPLOADER.upload(filename, QuerySupporters.for_export_enumerable(npo_id, params, 15000).map { |i| i.to_csv }, content_type: "text/csv", content_disposition: "attachment") export.url = url export.status = :completed - export.ended = Time.now + export.ended = Time.zone.now export.save! ExportMailer.delay.export_supporters_completed_notification(export) @@ -59,7 +59,7 @@ def self.run_export(npo_id, params, user_id, export_id) if export export.status = :failed export.exception = e.to_s - export.ended = Time.now + export.ended = Time.zone.now export.save! if user ExportMailer.delay.export_supporters_failed_notification(export) diff --git a/app/legacy_lib/fetch_miscellaneous_np_info.rb b/app/legacy_lib/fetch_miscellaneous_np_info.rb index 50064011a..509a023d7 100644 --- a/app/legacy_lib/fetch_miscellaneous_np_info.rb +++ b/app/legacy_lib/fetch_miscellaneous_np_info.rb @@ -3,6 +3,6 @@ module FetchMiscellaneousNpInfo def self.fetch(np_id) ParamValidation.new({np_id: np_id}, np_id: {required: true, is_integer: true}) raise ParamValidation::ValidationError.new("Nonprofit #{np_id} does not exist", {key: :np_id}) unless Nonprofit.exists?(np_id) - MiscellaneousNpInfo.where("nonprofit_id = ?", np_id).first_or_initialize + MiscellaneousNpInfo.where(nonprofit_id: np_id).first_or_initialize end end diff --git a/app/legacy_lib/format/address.rb b/app/legacy_lib/format/address.rb index 3ede6a560..9664b3a89 100644 --- a/app/legacy_lib/format/address.rb +++ b/app/legacy_lib/format/address.rb @@ -16,7 +16,7 @@ def self.city_or_state(city, state) def self.with_supporter(s) return "" if s.nil? - [[s.address, s.city, s.state_code].reject(&:blank?).join(", "), s.zip_code].reject(&:blank?).join(" ") + [[s.address, s.city, s.state_code].compact_blank.join(", "), s.zip_code].compact_blank.join(" ") end end end diff --git a/app/legacy_lib/format/geography.rb b/app/legacy_lib/format/geography.rb index 92e210cf8..c55c0f102 100644 --- a/app/legacy_lib/format/geography.rb +++ b/app/legacy_lib/format/geography.rb @@ -1,9 +1,9 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module Format module Geography - StateCodes = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"] + STATE_CODES = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"] - StateMappings = { + STATE_MAPPINGS = { "alabama" => "AL", "alaska" => "AK", "arizona" => "AZ", @@ -58,7 +58,7 @@ module Geography "wyoming" => "WY" } - Countries = [ + COUNTRIES = [ "Afghanistan", "Albania", "Algeria", @@ -298,8 +298,8 @@ module Geography # Will leave strings that are already state codes alone def self.full_state_to_code(str) str = str.strip - return str if StateCodes.include?(str.upcase) - StateMappings[str.downcase] + return str if STATE_CODES.include?(str.upcase) + STATE_MAPPINGS[str.downcase] end end end diff --git a/app/legacy_lib/format/remove_diacritics.rb b/app/legacy_lib/format/remove_diacritics.rb index 4d9459648..0e5ed197b 100644 --- a/app/legacy_lib/format/remove_diacritics.rb +++ b/app/legacy_lib/format/remove_diacritics.rb @@ -7,7 +7,7 @@ def self.from_hash(hash, keys) # returns a new hash with any diacritics replaced with a plain character # only from values corresponding to specified keys: # {"city" => "São Paulo"} ["city"] will return {"city" => "Sao Paulo"} - Hash[hash.map { |k, v| [k, keys.include?(k) ? I18n.transliterate(v) : v] }] + hash.map { |k, v| [k, keys.include?(k) ? I18n.transliterate(v) : v] }.to_h end end end diff --git a/app/legacy_lib/get_data.rb b/app/legacy_lib/get_data.rb index aeb514014..7a86ae5be 100644 --- a/app/legacy_lib/get_data.rb +++ b/app/legacy_lib/get_data.rb @@ -3,7 +3,7 @@ module GetData def self.chain(obj, *methods) methods.each do |m| if m.is_a?(Array) - params = m[1..-1] + params = m[1..] m = m[0] end diff --git a/app/legacy_lib/image.rb b/app/legacy_lib/image.rb index 8df83324a..2e1921321 100644 --- a/app/legacy_lib/image.rb +++ b/app/legacy_lib/image.rb @@ -1,6 +1,6 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module Image - AssetPath = "https://dmnsmycmdpaix.cloudfront.net/uploads" + ASSET_PATH = "https://dmnsmycmdpaix.cloudfront.net/uploads" DefaultProfileUrl = Settings.default.image.profile DefaultNonprofitUrl = Settings.default.image.nonprofit @@ -8,7 +8,7 @@ module Image def self._url(resource_name, image_name, version = "normal") %( - concat(#{Qexpr.quote AssetPath} + concat(#{Qexpr.quote ASSET_PATH} , '/', #{Qexpr.quote resource_name} , '/', #{Qexpr.quote image_name} , '/', #{resource_name + ".id"} diff --git a/app/legacy_lib/import_civicrm_payments.rb b/app/legacy_lib/import_civicrm_payments.rb index e796c2a53..fa76330ee 100644 --- a/app/legacy_lib/import_civicrm_payments.rb +++ b/app/legacy_lib/import_civicrm_payments.rb @@ -20,7 +20,7 @@ def self.import_from_csv(csv_body, nonprofit, field_of_supporter_id) supporters_with_fields = Supporter.includes(:custom_field_joins).where("supporters.nonprofit_id = ? AND custom_field_joins.custom_field_master_id = ?", nonprofit.id, supporter_id_custom_field.id) questionable_records = [] contrib_records.each { |r| - our_supporter = supporters_with_fields.where("custom_field_joins.value = ?", r[field_of_supporter_id].to_s).first + our_supporter = supporters_with_fields.where(custom_field_joins: {value: r[field_of_supporter_id].to_s}).first unless our_supporter questionable_records.push(r) next @@ -38,12 +38,12 @@ def self.import_from_csv(csv_body, nonprofit, field_of_supporter_id) offsite = {kind: "check", check_number: r["Check Number"]} end - puts r["Date Received"] + Rails.logger.debug r["Date Received"] date_received = nil Time.use_zone("Pacific Time (US & Canada)") do date_received = Time.zone.parse(r["Date Received"]) - puts date_received + Rails.logger.debug date_received end d = InsertDonation.offsite( @@ -56,7 +56,7 @@ def self.import_from_csv(csv_body, nonprofit, field_of_supporter_id) offsite_payment: offsite }.with_indifferent_access ) - puts d + Rails.logger.debug d pay_imp.donations.push(Donation.find(d[:json]["donation"]["id"])) } questionable_records @@ -70,9 +70,7 @@ def self.undo(import_id) d.payments.each { |p| p.destroy } - if d.offsite_payment - d.offsite_payment.destroy - end + d.offsite_payment&.destroy d.destroy } diff --git a/app/legacy_lib/import_onecause_event_donations.rb b/app/legacy_lib/import_onecause_event_donations.rb index 9f7bf2df7..27526fbaa 100644 --- a/app/legacy_lib/import_onecause_event_donations.rb +++ b/app/legacy_lib/import_onecause_event_donations.rb @@ -15,7 +15,7 @@ def self.import(event, ticket_level, csv) bidder_groups.keys.each do |i| payment_row, non_payment = bidder_groups[i].partition { |row| row["Action"] == "Payment" } - payment_row = payment_row.select { |i| i["Payment Status"] == "Approved" }.first + payment_row = payment_row.find { |i| i["Payment Status"] == "Approved" } supporter_info_row = payment_row || non_payment.first @@ -70,7 +70,7 @@ def self.winnow_to_supporter(event, np, name, email = nil) possible_supporters = if email np.supporters.not_deleted.where("email = ? ", email) else - np.supporters.not_deleted.where("name = ?", name) + np.supporters.not_deleted.where(name: name) end if possible_supporters.none? @@ -79,7 +79,7 @@ def self.winnow_to_supporter(event, np, name, email = nil) return possible_supporters.first end - tickets_for_supporters = event.tickets.where("supporter_id IN (?)", possible_supporters.map { |i| i.id }) + tickets_for_supporters = event.tickets.where(supporter_id: possible_supporters.map { |i| i.id }) if tickets_for_supporters.none? possible_supporters.first @@ -91,7 +91,7 @@ def self.winnow_to_supporter(event, np, name, email = nil) end def self.winnow_tickets(event, supporter) - event.tickets.where("supporter_id = ?", supporter.id).first + event.tickets.where(supporter_id: supporter.id).first end def self.create_notes(p_row, np_rows) diff --git a/app/legacy_lib/include_asset.rb b/app/legacy_lib/include_asset.rb index d59cfd177..59579ba09 100644 --- a/app/legacy_lib/include_asset.rb +++ b/app/legacy_lib/include_asset.rb @@ -10,7 +10,7 @@ def self.css(path) %().html_safe end - private + private_class_method def self.asset_version ENV["ASSET_VERSION"] diff --git a/app/legacy_lib/insert_bank_account.rb b/app/legacy_lib/insert_bank_account.rb index 1ac550360..c208e3769 100644 --- a/app/legacy_lib/insert_bank_account.rb +++ b/app/legacy_lib/insert_bank_account.rb @@ -37,7 +37,7 @@ def self.with_stripe(nonprofit, user, params = {}) ba.default_for_currency = true ba.save - BankAccount.where("nonprofit_id = ?", nonprofit.id).update_all(deleted: true) + BankAccount.where(nonprofit_id: nonprofit.id).update_all(deleted: true) bank_account = BankAccount.create( stripe_bank_account_id: ba.id, diff --git a/app/legacy_lib/insert_card.rb b/app/legacy_lib/insert_card.rb index 5dc54119d..41cb52e06 100644 --- a/app/legacy_lib/insert_card.rb +++ b/app/legacy_lib/insert_card.rb @@ -47,7 +47,7 @@ def self.with_stripe(card_data, stripe_account_id = nil, event_id = nil, current begin if holder_type == :supporter && event_id - event = Event.where("id = ?", event_id).first + event = Event.where(id: event_id).first unless event raise ParamValidation::ValidationError.new("#{event_id} is not a valid event", {key: :event_id}) end @@ -105,9 +105,6 @@ def self.with_stripe(card_data, stripe_account_id = nil, event_id = nil, current rescue e Airbrake.notify(e) return {json: {error: "Oops! There was an error saving your card, and it did not complete. Please try again in a moment. Error: #{e}"}, status: :unprocessable_entity} - rescue e - Airbrake.notify(e) - return {json: {error: "Oops! There was an error saving your card, and it did not complete. Please try again in a moment. Error: #{e}"}, status: :unprocessable_entity} end {status: :ok, json: card.attributes.to_deprecated_h.with_indifferent_access.merge(token: source_token)} diff --git a/app/legacy_lib/insert_charge.rb b/app/legacy_lib/insert_charge.rb index 155f86391..765dde4d0 100644 --- a/app/legacy_lib/insert_charge.rb +++ b/app/legacy_lib/insert_charge.rb @@ -38,19 +38,19 @@ def self.with_stripe(data) } }) - np = Nonprofit.where("id = ?", data[:nonprofit_id]).first + np = Nonprofit.where(id: data[:nonprofit_id]).first unless np raise ParamValidation::ValidationError.new("#{data[:nonprofit_id]} is not a valid Nonprofit", {key: :nonprofit_id}) end - supporter = Supporter.where("id = ?", data[:supporter_id]).first + supporter = Supporter.where(id: data[:supporter_id]).first unless supporter raise ParamValidation::ValidationError.new("#{data[:supporter_id]} is not a valid Supporter", {key: :supporter_id}) end - card = Card.where("id = ?", data[:card_id]).first + card = Card.where(id: data[:card_id]).first unless card raise ParamValidation::ValidationError.new("#{data[:card_id]} is not a valid card", {key: :card_id}) @@ -134,7 +134,7 @@ def self.with_stripe(data) charge.failure_message = failure_message charge.status = stripe_charge&.paid ? "pending" : "failed" charge.card = card - charge.donation = Donation.where("id = ?", data[:donation_id]).first + charge.donation = Donation.where(id: data[:donation_id]).first charge.supporter = supporter charge.nonprofit = np charge.save! @@ -147,7 +147,7 @@ def self.with_stripe(data) payment.net_amount = data[:amount] - fee payment.towards = data[:towards] payment.kind = data[:kind] - payment.donation = Donation.where("id = ?", data[:donation_id]).first + payment.donation = Donation.where(id: data[:donation_id]).first payment.nonprofit = np payment.supporter = supporter payment.refund_total = 0 diff --git a/app/legacy_lib/insert_custom_field_joins.rb b/app/legacy_lib/insert_custom_field_joins.rb index d70d4f23e..f3bee5933 100644 --- a/app/legacy_lib/insert_custom_field_joins.rb +++ b/app/legacy_lib/insert_custom_field_joins.rb @@ -32,7 +32,7 @@ def self.find_or_create(np_id, supporter_ids, field_data) # make sure the supporters_ids exist supporter_ids.each { |id| - unless np.supporters.where("id = ?", id).exists? + unless np.supporters.where(id: id).exists? raise ParamValidation::ValidationError.new("#{id} is not a valid supporter for nonprofit #{np_id}", {key: :supporter_ids}) end } @@ -86,7 +86,7 @@ def self.in_bulk(np_id, supporter_ids, field_data) end # filtering the tag_data to this nonprofit - valid_ids = CustomFieldMaster.where("nonprofit_id = ? and id IN (?)", np_id, field_data.map { |fd| fd[:custom_field_master_id] }).pluck(:id).to_a + valid_ids = CustomFieldMaster.where("nonprofit_id = ? and id IN (?)", np_id, field_data.pluck(:custom_field_master_id)).pluck(:id).to_a filtered_field_data = field_data.select { |i| valid_ids.include? i[:custom_field_master_id].to_i } # first, delete the items which should be removed @@ -97,7 +97,7 @@ def self.in_bulk(np_id, supporter_ids, field_data) if to_remove.any? deleted = Qx.delete_from(:custom_field_joins) .where("supporter_id IN ($ids)", ids: supporter_ids) - .and_where("custom_field_master_id in ($fields)", fields: to_remove.map { |t| t[:custom_field_master_id] }) + .and_where("custom_field_master_id in ($fields)", fields: to_remove.pluck(:custom_field_master_id)) .returning("*") .execute end diff --git a/app/legacy_lib/insert_donation.rb b/app/legacy_lib/insert_donation.rb index fe1cb092c..06ce6d836 100644 --- a/app/legacy_lib/insert_donation.rb +++ b/app/legacy_lib/insert_donation.rb @@ -9,7 +9,7 @@ def self.with_stripe(data, current_user = nil) data = data.to_deprecated_h.with_indifferent_access ParamValidation.new(data, common_param_validations - .merge(token: {required: true, format: UUID::Regex})) + .merge(token: {required: true, format: UUID::REGEX})) source_token = QuerySourceToken.get_and_increment_source_token(data[:token], current_user) tokenizable = source_token.tokenizable @@ -30,7 +30,7 @@ def self.with_stripe(data, current_user = nil) result = {} - data[:date] = Time.now + data[:date] = Time.zone.now data = amount_from_data(data) data = data.except(:old_donation).except("old_donation") result = result.merge(insert_charge(data)) @@ -142,7 +142,7 @@ def self.with_sepa(data) result = {} - data[:date] = Time.now + data[:date] = Time.zone.now result = result.merge(insert_charge(data)) result["donation"] = insert_donation(data, entities) update_donation_keys(result) @@ -154,7 +154,7 @@ def self.with_sepa(data) result end - private + private_class_method def self.get_nonprofit_data(nonprofit_id) Nonprofit.find(nonprofit_id) @@ -278,11 +278,11 @@ def self.validate_all_entities(entities) raise ParamValidation::ValidationError.new("Supporter #{entities[:supporter_id].id} is deleted", key: :supporter_id) end - if entities[:event_id] && entities[:event_id].deleted + if entities[:event_id]&.deleted raise ParamValidation::ValidationError.new("Event #{entities[:event_id].id} is deleted", key: :event_id) end - if entities[:campaign_id] && entities[:campaign_id].deleted + if entities[:campaign_id]&.deleted raise ParamValidation::ValidationError.new("Campaign #{entities[:campaign_id].id} is deleted", key: :campaign_id) end diff --git a/app/legacy_lib/insert_duplicate.rb b/app/legacy_lib/insert_duplicate.rb index c0388af77..76cad63d8 100644 --- a/app/legacy_lib/insert_duplicate.rb +++ b/app/legacy_lib/insert_duplicate.rb @@ -6,12 +6,12 @@ def self.campaign(campaign_id, profile_id, new_nonprofit = nil) campaign_id: {required: true, is_integer: true}, profile_id: {required: true, is_integer: true} }) - campaign = Campaign.where("id = ?", campaign_id).first + campaign = Campaign.where(id: campaign_id).first unless campaign raise ParamValidation::ValidationError.new("#{campaign_id} is not a valid campaign", {key: :campaign_id}) end - profile = Profile.where("id = ?", profile_id).first + profile = Profile.where(id: profile_id).first unless profile raise ParamValidation::ValidationError.new("#{profile_id} is not a valid profile", {key: :profile_id}) end @@ -55,12 +55,12 @@ def self.event(event_id, profile_id, new_nonprofit = nil) event_id: {required: true, is_integer: true}, profile_id: {required: true, is_integer: true} }) - event = Event.where("id = ?", event_id).first + event = Event.where(id: event_id).first unless event raise ParamValidation::ValidationError.new("#{event_id} is not a valid event", {key: :event_id}) end - profile = Profile.where("id = ?", profile_id).first + profile = Profile.where(id: profile_id).first unless profile raise ParamValidation::ValidationError.new("#{profile_id} is not a valid profile", {key: :profile_id}) end @@ -112,7 +112,7 @@ def self.event(event_id, profile_id, new_nonprofit = nil) def self.misc_event_info(event, dupe) original_custom_get_tickets_button_label = event&.misc_event_info&.custom_get_tickets_button_label - return unless original_custom_get_tickets_button_label.present? + return if original_custom_get_tickets_button_label.blank? dupe.create_misc_event_info dupe.misc_event_info.custom_get_tickets_button_label = original_custom_get_tickets_button_label diff --git a/app/legacy_lib/insert_email_lists.rb b/app/legacy_lib/insert_email_lists.rb index 9714b386e..7be59b9de 100644 --- a/app/legacy_lib/insert_email_lists.rb +++ b/app/legacy_lib/insert_email_lists.rb @@ -5,26 +5,25 @@ module InsertEmailLists def self.for_mailchimp(npo_id, tag_master_ids) # Partial SQL expression for deleting deselected tags tags_for_nonprofit = Nonprofit.includes(tag_masters: :email_list).find(npo_id).tag_masters.not_deleted - tag_master_ids = tags_for_nonprofit.where("id in (?)", tag_master_ids).pluck(:id) - if tag_master_ids.empty? # no tags were selected; remove all email lists - deleted = tags_for_nonprofit.includes(:email_list).where.not(email_lists: {id: nil}).references(:email_lists).map { |i| i.email_list } - EmailList.where("id IN (?)", deleted.map { |i| i.id }).delete_all + tag_master_ids = tags_for_nonprofit.where(id: tag_master_ids).pluck(:id) + deleted = if tag_master_ids.empty? # no tags were selected; remove all email lists + tags_for_nonprofit.includes(:email_list).where.not(email_lists: {id: nil}).references(:email_lists).map { |i| i.email_list } else # Remove all email lists that exist in the db that are not included in tag_master_ids - deleted = tags_for_nonprofit.includes(:email_list).where.not(email_lists: {tag_master_id: tag_master_ids}).references(:email_lists).map { |i| i.email_list } - EmailList.where("id IN (?)", deleted.map { |i| i.id }).delete_all + tags_for_nonprofit.includes(:email_list).where.not(email_lists: {tag_master_id: tag_master_ids}).references(:email_lists).map { |i| i.email_list } end + EmailList.where(id: deleted.map { |i| i.id }).delete_all mailchimp_lists_to_delete = deleted.map { |i| i.mailchimp_list_id } result = Mailchimp.delete_mailchimp_lists(npo_id, mailchimp_lists_to_delete) return {deleted: deleted.map { |i| {"mailchimp_list_id" => i.mailchimp_list_id} }, deleted_result: result} if tag_master_ids.empty? - existing = tags_for_nonprofit.includes(:email_list).where("email_lists.tag_master_id IN (?)", tag_master_ids).references(:email_lists) + existing = tags_for_nonprofit.includes(:email_list).where(email_lists: {tag_master_id: tag_master_ids}).references(:email_lists) tag_master_ids -= existing.map { |i| i.id } lists = Mailchimp.create_mailchimp_lists(npo_id, tag_master_ids) if !lists || !lists.any? || !lists.first[:name] - raise Exception.new("Unable to create mailchimp lists. Response was: #{lists}") + raise StandardError.new("Unable to create mailchimp lists. Response was: #{lists}") end inserted_lists = Qx.insert_into(:email_lists) diff --git a/app/legacy_lib/insert_import.rb b/app/legacy_lib/insert_import.rb index dac4c95bc..e2154a720 100644 --- a/app/legacy_lib/insert_import.rb +++ b/app/legacy_lib/insert_import.rb @@ -14,7 +14,7 @@ def self.from_csv_safe(data) Qx.transaction do InsertImport.from_csv(data) end - rescue Exception => e + rescue => e body = "Import failed. Error: #{e}" GenericMailer.generic_mail( "support@commitchange.com", "Jay Bot", # FROM @@ -55,7 +55,7 @@ def self.from_csv(data) # no spaces are allowed by open(). We could URI.encode, but spaces seem to be the only problem and we want to avoid double-encoding a URL data[:file_uri] = data[:file_uri].gsub(/ /, "%20") - CSV.new(open(data[:file_uri]), headers: :first_row).each do |row| + CSV.new(open(data[:file_uri]), headers: :first_row).each do |row| # rubocop:disable Security/Open row_count += 1 # triplet of [header_name, value, import_key] matches = row.map { |key, val| [key, val, data[:header_matches][key]] } @@ -98,7 +98,7 @@ def self.from_csv(data) # Create new tags if table_data["supporter"]["id"] && table_data["tags"] && table_data["tags"].any? # Split tags by semicolons - tags = table_data["tags"].select { |t| t.present? }.map { |t| t.split(/[;,]/).map(&:strip) }.flatten + tags = table_data["tags"].compact_blank.map { |t| t.split(/[;,]/).map(&:strip) }.flatten InsertTagJoins.find_or_create(data[:nonprofit_id], [table_data["supporter"]["id"]], tags) end diff --git a/app/legacy_lib/insert_nonprofit_keys.rb b/app/legacy_lib/insert_nonprofit_keys.rb index 25b2a847c..cf5c0df3d 100644 --- a/app/legacy_lib/insert_nonprofit_keys.rb +++ b/app/legacy_lib/insert_nonprofit_keys.rb @@ -6,11 +6,11 @@ module InsertNonprofitKeys include HTTParty def self.insert_mailchimp_access_token(npo_id, code) - form_data = "grant_type=authorization_code&client_id=#{URI.escape ENV["MAILCHIMP_OAUTH_CLIENT_ID"]}&client_secret=#{ENV["MAILCHIMP_OAUTH_CLIENT_SECRET"]}&redirect_uri=#{ENV["MAILCHIMP_REDIRECT_URL"]}%2Fmailchimp-landing&code=#{URI.escape code}" + form_data = "grant_type=authorization_code&client_id=#{CGI.escape ENV["MAILCHIMP_OAUTH_CLIENT_ID"]}&client_secret=#{ENV["MAILCHIMP_OAUTH_CLIENT_SECRET"]}&redirect_uri=#{ENV["MAILCHIMP_REDIRECT_URL"]}%2Fmailchimp-landing&code=#{CGI.escape code}" response = post("https://login.mailchimp.com/oauth2/token", {body: form_data}) if response["error"] - raise Exception.new(response["error"]) + raise StandardError.new(response["error"]) end nonprofit_key = Nonprofit.find(npo_id).nonprofit_key diff --git a/app/legacy_lib/insert_recurring_donation.rb b/app/legacy_lib/insert_recurring_donation.rb index 7800b4588..f6e7dfe3e 100644 --- a/app/legacy_lib/insert_recurring_donation.rb +++ b/app/legacy_lib/insert_recurring_donation.rb @@ -6,7 +6,7 @@ def self.with_stripe(data) data = data.to_deprecated_h.with_indifferent_access ParamValidation.new(data, InsertDonation.common_param_validations - .merge(token: {required: true, format: UUID::Regex})) + .merge(token: {required: true, format: UUID::REGEX})) if data[:recurring_donation].nil? data[:recurring_donation] = {} @@ -46,7 +46,7 @@ def self.with_stripe(data) data["card_id"] = tokenizable.id result = {} - data[:date] = Time.now + data[:date] = Time.zone.now data = data.merge(payment_provider: payment_provider(data)) data = data.except(:old_donation).except("old_donation") # if start date is today, make initial charge first @@ -144,13 +144,13 @@ def self.import_with_stripe(data) data["card_id"] = card.id result = {} - data[:date] = Time.now + data[:date] = Time.zone.now data = data.merge(payment_provider: payment_provider(data)) data = data.except(:old_donation).except("old_donation") # if start date is today, make initial charge first test_start_date = get_test_start_date(data) if test_start_date.nil? || Time.current >= test_start_date - puts "we would have charged on #{data}" + Rails.logger.debug { "we would have charged on #{data}" } # result = result.merge(InsertDonation.insert_charge(data)) # if result['charge']['status'] == 'failed' diff --git a/app/legacy_lib/insert_refunds.rb b/app/legacy_lib/insert_refunds.rb index eb0fadfb1..335650717 100644 --- a/app/legacy_lib/insert_refunds.rb +++ b/app/legacy_lib/insert_refunds.rb @@ -38,7 +38,7 @@ def self.modern_refund(charge, h) refund.create_misc_refund_info(is_modern: true, stripe_application_fee_refund_id: results[:stripe_app_fee_refund]&.id) gross = -h["amount"] - fees = (results[:stripe_app_fee_refund] && results[:stripe_app_fee_refund].amount) || 0 + fees = results[:stripe_app_fee_refund]&.amount || 0 net = gross + fees # Create a corresponding./run negative payment record diff --git a/app/legacy_lib/insert_source_token.rb b/app/legacy_lib/insert_source_token.rb index 2779eb8e4..5468ad20d 100644 --- a/app/legacy_lib/insert_source_token.rb +++ b/app/legacy_lib/insert_source_token.rb @@ -14,7 +14,7 @@ def self.create_record(tokenizable, params = {}) else max_uses = params[:max_uses] || Settings.source_tokens.max_uses expiration_diff = params[:expiration_time] || Settings.source_tokens.expiration_time - expiration = Time.now + expiration_diff.to_i + expiration = Time.zone.now + expiration_diff.to_i end c = SourceToken.new c.tokenizable = tokenizable diff --git a/app/legacy_lib/insert_tag_joins.rb b/app/legacy_lib/insert_tag_joins.rb index a7c1f3640..f27c90be1 100644 --- a/app/legacy_lib/insert_tag_joins.rb +++ b/app/legacy_lib/insert_tag_joins.rb @@ -38,13 +38,13 @@ def self.in_bulk(np_id, profile_id, supporter_ids, tag_data) nonprofit = Nonprofit.find(np_id) # verify that the supporters belong to the nonprofit - supporter_ids = nonprofit.supporters.where("id IN (?)", supporter_ids).pluck(:id) + supporter_ids = nonprofit.supporters.where(id: supporter_ids).pluck(:id) unless supporter_ids.any? return {json: {inserted_count: 0, removed_count: 0}, status: :ok} end # filtering the tag_data to this nonprofit - valid_ids = nonprofit.tag_masters.where("id IN (?)", tag_data.to_tag_master_ids).pluck(:id).to_a + valid_ids = nonprofit.tag_masters.where(id: tag_data.to_tag_master_ids).pluck(:id).to_a filtered_tag_data = tag_data.for_given_tags(valid_ids) # first, delete the items which should be removed diff --git a/app/legacy_lib/insert_tickets.rb b/app/legacy_lib/insert_tickets.rb index c3476010e..dd236de69 100644 --- a/app/legacy_lib/insert_tickets.rb +++ b/app/legacy_lib/insert_tickets.rb @@ -24,7 +24,7 @@ def self.create(data, skip_notifications = false) event_id: {required: true, is_reference: true}, event_discount_id: {is_reference: true}, kind: {included_in: ["free", "charge", "offsite"]}, - token: {format: UUID::Regex}, + token: {format: UUID::REGEX}, offsite_payment: {is_hash: true}, amount: {required: true, is_integer: true} }) @@ -154,7 +154,7 @@ def self.create(data, skip_notifications = false) InsertActivities.for_tickets(result["tickets"].map { |t| t.id }) ticket_ids = result["tickets"].map { |t| t.id } - charge_id = result["charge"] ? result["charge"].id : nil + charge_id = result["charge"]&.id unless skip_notifications JobQueue.queue(JobTypes::TicketMailerReceiptAdminJob, ticket_ids) diff --git a/app/legacy_lib/json_resp.rb b/app/legacy_lib/json_resp.rb index ef362a8ca..b4eed6c51 100644 --- a/app/legacy_lib/json_resp.rb +++ b/app/legacy_lib/json_resp.rb @@ -22,10 +22,10 @@ def when_valid(&block) return {status: 422, json: {errors: @errors}} if @errors.any? begin @response = block.call(@params) - rescue Exception => e + rescue => e @response = {status: 500, json: {error: "We're sorry, but something went wrong. We've been notified about this issue."}} - puts e - puts e.backtrace.first(10) + Rails.logger.debug e + Rails.logger.debug e.backtrace.first(10) end @response end diff --git a/app/legacy_lib/mailchimp.rb b/app/legacy_lib/mailchimp.rb index d887edd2e..ab69f6082 100644 --- a/app/legacy_lib/mailchimp.rb +++ b/app/legacy_lib/mailchimp.rb @@ -65,8 +65,8 @@ def self.get_mailchimp_token(npo_id) # Get all lists owned by the nonprofit represented by the mailchimp token def get_all_lists(mailchimp_token) uri = base_uri(mailchimp_token) - puts "URI #{uri}" - puts "KEY #{mailchimp_token}" + Rails.logger.debug { "URI #{uri}" } + Rails.logger.debug { "KEY #{mailchimp_token}" } get(uri + "/lists", { basic_auth: {username: "", password: mailchimp_token}, headers: {"Content-Type" => "application/json"} @@ -78,8 +78,8 @@ def get_all_lists(mailchimp_token) def self.create_mailchimp_lists(npo_id, tag_master_ids) mailchimp_token = get_mailchimp_token(npo_id) uri = base_uri(mailchimp_token) - puts "URI #{uri}" - puts "KEY #{mailchimp_token}" + Rails.logger.debug { "URI #{uri}" } + Rails.logger.debug { "KEY #{mailchimp_token}" } npo = Qx.fetch(:nonprofits, npo_id).first tags = Qx.select("DISTINCT(tag_masters.name) AS tag_name, tag_masters.id") @@ -116,7 +116,7 @@ def self.create_mailchimp_lists(npo_id, tag_master_ids) }.to_json }) if list.code != 200 - raise Exception.new("Failed to create list: #{list}") + raise StandardError.new("Failed to create list: #{list}") end {id: list["id"], name: list["name"], tag_master_id: h["id"]} end @@ -126,7 +126,7 @@ def self.create_mailchimp_lists(npo_id, tag_master_ids) # See here: http://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-batch-operations/ # Perform all the batch operations and return a status report def self.perform_batch_operations(npo_id, post_data) - post_data = post_data.map(&:to_h).select(&:present?) # the select removes any nil items + post_data = post_data.map(&:to_h).compact_blank # the select removes any nil items return if post_data.empty? mailchimp_token = get_mailchimp_token(npo_id) uri = base_uri(mailchimp_token) @@ -168,7 +168,7 @@ def self.sync_supporters_to_list_from_tag_joins(npo_id, supporter_ids, tag_data) end def self.get_emails_for_supporter_ids(npo_id, supporters_ids = []) - Nonprofit.find(npo_id).supporters.where("id in (?)", supporters_ids).pluck(:email).select(&:present?) + Nonprofit.find(npo_id).supporters.where(id: supporters_ids).pluck(:email).compact_blank end def self.get_mailchimp_list_ids(tag_master_ids) @@ -177,7 +177,7 @@ def self.get_mailchimp_list_ids(tag_master_ids) .from(:tag_masters) .where("tag_masters.id IN ($ids)", ids: tag_master_ids) .join("email_lists", "email_lists.tag_master_id=tag_masters.id") - .execute.map { |h| h["mailchimp_list_id"] } + .execute.pluck("mailchimp_list_id") end # @param [Nonprofit] nonprofit diff --git a/app/legacy_lib/maintain_donation_validity.rb b/app/legacy_lib/maintain_donation_validity.rb index 40a9290ed..786044a11 100644 --- a/app/legacy_lib/maintain_donation_validity.rb +++ b/app/legacy_lib/maintain_donation_validity.rb @@ -130,9 +130,7 @@ def self.cleanup_for_no_supporter(donation) def self.cleanup_for_no_nonprofit(donation) if !donation.nonprofit && !donation.supporter && !donation.recurring_donation && !donation.campaign && (!donation.payment || !donation.payment.nonprofit) && donation.campaign_gifts.none? && donation.activities.none? - if donation.payment - donation.payment.destroy - end + donation.payment&.destroy donation.destroy end end diff --git a/app/legacy_lib/maintain_payment_records.rb b/app/legacy_lib/maintain_payment_records.rb index 5a61fab77..2ef1a8d00 100644 --- a/app/legacy_lib/maintain_payment_records.rb +++ b/app/legacy_lib/maintain_payment_records.rb @@ -16,9 +16,7 @@ def self.set_payment_supporter_and_nonprofit_though_charge_refund(i) def self.delete_payment_and_offsite_payment_record(id) p = Payment.includes(:offsite_payment).find(id) - if p.offsite_payment - p.offsite_payment.destroy - end + p.offsite_payment&.destroy p.destroy end end diff --git a/app/legacy_lib/maintain_payments_where_supporter_is_gone.rb b/app/legacy_lib/maintain_payments_where_supporter_is_gone.rb index e715a26d2..0319e2cd8 100644 --- a/app/legacy_lib/maintain_payments_where_supporter_is_gone.rb +++ b/app/legacy_lib/maintain_payments_where_supporter_is_gone.rb @@ -21,7 +21,7 @@ def self.sorted_by_kind(records) def self.nonprofit_by_kind(urgency) nonprofit_by_kind = urgency.map { |k, v| [k, v.group_by { |i| i.kind }.sort_by { |i, x| x.count }.reverse.map { |i, x| [i, x.count] }] } nonprofit_by_kind.each { |id, group| - puts id + Rails.logger.debug id group.each { |kind, num| puts " #{kind}: #{num}" } } nonprofit_by_kind @@ -31,15 +31,15 @@ def self.cleanup(sorted_by_kind, api_key) Qx.transaction do manual_payments = [] - recurring_donations_from_stripe = sorted_by_kind[1][1].select { |i| i.charge && i.charge.stripe_charge_id && !i.charge.stripe_charge_id.start_with?("legacy") } - donations_from_stripe = sorted_by_kind[2][1].select { |i| i.charge && i.charge.stripe_charge_id && !i.charge.stripe_charge_id.start_with?("legacy") } - ticket_from_stripe = sorted_by_kind[3][1].select { |i| i.charge && i.charge.stripe_charge_id && !i.charge.stripe_charge_id.start_with?("legacy") } + recurring_donations_from_stripe = sorted_by_kind[1][1].select { |i| i.charge&.stripe_charge_id && !i.charge.stripe_charge_id.start_with?("legacy") } + donations_from_stripe = sorted_by_kind[2][1].select { |i| i.charge&.stripe_charge_id && !i.charge.stripe_charge_id.start_with?("legacy") } + ticket_from_stripe = sorted_by_kind[3][1].select { |i| i.charge&.stripe_charge_id && !i.charge.stripe_charge_id.start_with?("legacy") } payments = recurring_donations_from_stripe.concat(donations_from_stripe).concat(ticket_from_stripe) payments.each do |i| if Supporter.exists?(i.supporter_id) || i.nonprofit_id == 4500 - puts "#{i.supporter_id} was already saved" + Rails.logger.debug { "#{i.supporter_id} was already saved" } else ch = Stripe::Charge.retrieve(i.charge.stripe_charge_id, {api_key: api_key}) billing_name = ch.billing_details["name"] @@ -49,17 +49,17 @@ def self.cleanup(sorted_by_kind, api_key) # where we save the Supporter s = Supporter.create(id: i.supporter_id, name: billing_name, email: email, created_at: i.created_at, nonprofit_id: i.nonprofit_id) s.save! - puts "#{i.supporter_id} is saved" + Rails.logger.debug { "#{i.supporter_id} is saved" } end rescue => e - puts e + Rails.logger.debug e - puts "we failed on #{i.id}" + Rails.logger.debug { "we failed on #{i.id}" } manual_payments.push(i) end manual_refunds = [] # we have to manually track down these refunds on the connected accounts - refunds = sorted_by_kind[4][1].select { |i| i.refund && i.refund.stripe_refund_id } + refunds = sorted_by_kind[4][1].select { |i| i.refund&.stripe_refund_id } refunds.each do |i| unless Supporter.exists?(i.supporter_id) @@ -75,7 +75,7 @@ def self.cleanup(sorted_by_kind, api_key) manual_refunds.push(i) end - disputes = sorted_by_kind[5][1].select { |i| i.dispute && i.dispute.stripe_dispute_id } + disputes = sorted_by_kind[5][1].select { |i| i.dispute&.stripe_dispute_id } manual_disputes = [] # ditto disputes.each do |i| diff --git a/app/legacy_lib/maintain_stripe_records.rb b/app/legacy_lib/maintain_stripe_records.rb index 6a2ccffa7..a57f08150 100644 --- a/app/legacy_lib/maintain_stripe_records.rb +++ b/app/legacy_lib/maintain_stripe_records.rb @@ -1,7 +1,7 @@ module MaintainStripeRecords def self.safely_fill_stripe_charge_object(stripe_charge_id) LockManager.with_transaction_lock(stripe_charge_id) do - unless StripeCharge.where("stripe_charge_id = ?", stripe_charge_id).any? + unless StripeCharge.where(stripe_charge_id: stripe_charge_id).any? object = Stripe::Charge.retrieve(stripe_charge_id) StripeCharge.create!(object: object) end diff --git a/app/legacy_lib/merge_supporters.rb b/app/legacy_lib/merge_supporters.rb index 922688aca..4a8514edc 100644 --- a/app/legacy_lib/merge_supporters.rb +++ b/app/legacy_lib/merge_supporters.rb @@ -13,7 +13,7 @@ def self.update_associations(old_supporters, new_supporter, np_id, profile_id) .where("supporter_id IN ($ids)", ids: old_supporter_ids).timestamps.execute end - old_supporters.joins(:cards).each do |supp| + old_supporters.joins(:cards).find_each do |supp| supp.cards.each do |card| card.holder = new_supporter card.save! @@ -31,19 +31,19 @@ def self.update_associations(old_supporters, new_supporter, np_id, profile_id) all_custom_field_joins = old_supporters.map { |i| i.custom_field_joins }.flatten group_joins_by_custom_field_master = all_custom_field_joins.group_by { |i| i.custom_field_master.id } - one_custom_field_join_per_user = group_joins_by_custom_field_master.map { |k, v| - v.sort_by { |i| + one_custom_field_join_per_user = group_joins_by_custom_field_master.map do |k, v| + v.sort_by do |i| i.created_at - }.last - } + end.reverse.first # rubocop:disable Performance/ReverseFirst + end # delete old supporter custom_field - InsertCustomFieldJoins.in_bulk(np_id, old_supporter_ids, one_custom_field_join_per_user.map { |i| + InsertCustomFieldJoins.in_bulk(np_id, old_supporter_ids, one_custom_field_join_per_user.map do |i| { custom_field_master_id: i.custom_field_master_id, value: "" } - }) + end) # insert new supporter custom field InsertCustomFieldJoins.in_bulk(np_id, [new_supporter_id], one_custom_field_join_per_user.map { |i| @@ -59,7 +59,7 @@ def self.update_associations(old_supporters, new_supporter, np_id, profile_id) end def self.selected(merged_data, supporter_ids, np_id, profile_id, skip_conflicting_custom_fields = false) - old_supporters = Nonprofit.find(np_id).supporters.where("supporters.id IN (?)", supporter_ids) + old_supporters = Nonprofit.find(np_id).supporters.where(supporters: {id: supporter_ids}) if skip_conflicting_custom_fields && conflicting_custom_fields?(old_supporters) return {json: supporter_ids, status: :failure} diff --git a/app/legacy_lib/migrate/migrate_cover_fees.rb b/app/legacy_lib/migrate/migrate_cover_fees.rb index 5438d46a5..9a0e3b86a 100644 --- a/app/legacy_lib/migrate/migrate_cover_fees.rb +++ b/app/legacy_lib/migrate/migrate_cover_fees.rb @@ -1,7 +1,7 @@ module Migrate class MigrateCoverFees def self.for_nonprofits - MiscellaneousNpInfo.all.each do |mni| + MiscellaneousNpInfo.all.find_each do |mni| mni.fee_coverage_option_config = if mni.hide_cover_fees "none" end @@ -10,7 +10,7 @@ def self.for_nonprofits end def self.for_campaigns - MiscCampaignInfo.all.each do |mci| + MiscCampaignInfo.all.find_each do |mci| mci.fee_coverage_option_config = if mci.campaign.nonprofit.hide_cover_fees? nil elsif mci.hide_cover_fees_option? diff --git a/app/legacy_lib/name_copy_naming_algorithm.rb b/app/legacy_lib/name_copy_naming_algorithm.rb index 95d932e1d..2daed50b7 100644 --- a/app/legacy_lib/name_copy_naming_algorithm.rb +++ b/app/legacy_lib/name_copy_naming_algorithm.rb @@ -8,7 +8,7 @@ def initialize(klass, nonprofit_id) end def copy_addition - " (#{Time.now.strftime("%F")} copy)" + " (#{Time.zone.now.strftime("%F")} copy)" end def separator_before_copy_number diff --git a/app/legacy_lib/notify_user.rb b/app/legacy_lib/notify_user.rb index 1eec28265..c69717919 100644 --- a/app/legacy_lib/notify_user.rb +++ b/app/legacy_lib/notify_user.rb @@ -2,7 +2,7 @@ module NotifyUser def self.send_confirmation_email(user_id) ParamValidation.new({user_id: user_id}, user_id: {required: true, is_integer: true}) - user = User.where("id = ?", user_id).first + user = User.where(id: user_id).first if !user raise ParamValidation::ValidationError.new("#{user_id} is not a valid user id", {key: :user_id, val: user_id}) end diff --git a/app/legacy_lib/pay_recurring_donation.rb b/app/legacy_lib/pay_recurring_donation.rb index 066ec94ce..2f62c4e96 100644 --- a/app/legacy_lib/pay_recurring_donation.rb +++ b/app/legacy_lib/pay_recurring_donation.rb @@ -10,7 +10,7 @@ def self.pay_all_due_with_stripe # Bulk insert the delayed jobs with a single expression ids = Psql.execute_vectors( QueryRecurringDonations._all_that_are_due - )[1..-1].flatten + )[1..].flatten jobs = ids.map do |id| {handler: DelayedJobHelper.create_handler(PayRecurringDonation, :with_stripe, [id])} @@ -64,7 +64,7 @@ def self.with_stripe(rd_id, force_run = false) } }) - rd = RecurringDonation.includes(:misc_recurring_donation_info).where("id = ?", rd_id).first + rd = RecurringDonation.includes(:misc_recurring_donation_info).where(id: rd_id).first unless rd raise ParamValidation::ValidationError.new("#{rd_id} is not a valid recurring donation", {key: :rd_id}) @@ -72,7 +72,7 @@ def self.with_stripe(rd_id, force_run = false) return false if !force_run && !QueryRecurringDonations.is_due?(rd_id) - donation = Donation.where("id = ?", rd["donation_id"]).first + donation = Donation.where(id: rd["donation_id"]).first unless donation raise ParamValidation::ValidationError.new("#{rd["donation_id"]} is not a valid donation", {}) end diff --git a/app/legacy_lib/payment_dupes.rb b/app/legacy_lib/payment_dupes.rb index 14b36d901..d81b06d1d 100644 --- a/app/legacy_lib/payment_dupes.rb +++ b/app/legacy_lib/payment_dupes.rb @@ -90,9 +90,7 @@ def self.remove_payment_dupes(np_id, designations_to_become_comments) deleted_payments = [] nonprofit = Nonprofit.find(np_id) etap_id_cf = CustomFieldMaster.find_by(name: "E-Tapestry Id #").id - supp = nonprofit.supporters.not_deleted.joins(:custom_field_joins).where( - "custom_field_joins.custom_field_master_id = ?", etap_id_cf - ).references(:custom_field_joins) + supp = nonprofit.supporters.not_deleted.joins(:custom_field_joins).where(custom_field_joins: {custom_field_master_id: etap_id_cf}).references(:custom_field_joins) supp.find_each do |s| offsite_payments = s.payments.includes(:donation).where("kind = 'OffsitePayment'").joins(:journal_entries_to_item) diff --git a/app/legacy_lib/psql.rb b/app/legacy_lib/psql.rb index 496ac8c75..1b2227080 100644 --- a/app/legacy_lib/psql.rb +++ b/app/legacy_lib/psql.rb @@ -3,7 +3,6 @@ # combine usage of this library with Qexpr require "colorize" - require "qx" # Initialize the database connection @@ -11,14 +10,14 @@ module Psql # Execute a sql statement (string) def self.execute(statement) - puts statement if ENV["RAILS_ENV"] != "production" && ENV["RAILS_LOG_LEVEL"] == "debug" # log to STDOUT on dev/staging + Rails.logger.debug statement if ENV["RAILS_ENV"] != "production" && ENV["RAILS_LOG_LEVEL"] == "debug" # log to STDOUT on dev/staging Qx.execute_raw(raw_expr_str(statement)) end # A variation of execute that returns a vector of vectors rather than a vector of hashes # Useful and faster for creating CSV's def self.execute_vectors(statement) - puts statement if ENV["RAILS_ENV"] != "production" && ENV["RAILS_LOG_LEVEL"] == "debug" # log to STDOUT on dev/staging + Rails.logger.debug statement if ENV["RAILS_ENV"] != "production" && ENV["RAILS_LOG_LEVEL"] == "debug" # log to STDOUT on dev/staging statement.to_s.uncolorize.encode("UTF-8", "binary", invalid: :replace, undef: :replace, replace: "") Qx.execute_raw(raw_expr_str(statement), format: "csv") end @@ -29,7 +28,7 @@ def self.transaction(&block) end end - private + private_class_method # Raw expression string def self.raw_expr_str(statement) diff --git a/app/legacy_lib/qexpr.rb b/app/legacy_lib/qexpr.rb index c5957c1a5..ec971f196 100644 --- a/app/legacy_lib/qexpr.rb +++ b/app/legacy_lib/qexpr.rb @@ -37,7 +37,7 @@ def parse query_based_expression = @tree[:update] || @tree[:delete_from] || @tree[:select] # Query-based expessions - if query_based_expression.nil? || query_based_expression.empty? + if query_based_expression.blank? raise ArgumentError.new("Must have a select, update, or delete clause") end @@ -103,7 +103,7 @@ def select(*cols) else "\n #{cols.join("\n, ")}" end - Qexpr.new @tree.put(:select, "\nSELECT".bold.light_blue + "#{cols}".blue) + Qexpr.new @tree.put(:select, "\nSELECT".bold.light_blue + cols.to_s.blue) end end @@ -266,7 +266,7 @@ def self.interpolate_expr(expr, data) end end - private + private_class_method # Given some kind of expr object (might be just a string or another whole Qexpr expr), and an 'as' value # then give back either a hash for the sub-Qexpr expression, or just a string. diff --git a/app/legacy_lib/query_email_settings.rb b/app/legacy_lib/query_email_settings.rb index b980bedcb..90723ee1c 100644 --- a/app/legacy_lib/query_email_settings.rb +++ b/app/legacy_lib/query_email_settings.rb @@ -1,6 +1,6 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module QueryEmailSettings - Settings = ["notify_payments", "notify_campaigns", "notify_events", "notify_payouts", "notify_recurring_donations"] + SETTINGS = ["notify_payments", "notify_campaigns", "notify_events", "notify_payouts", "notify_recurring_donations"] def self.fetch(np_id, user_id) es = Psql.execute(%( diff --git a/app/legacy_lib/query_event_metrics.rb b/app/legacy_lib/query_event_metrics.rb index f4da6aabd..b30f34212 100644 --- a/app/legacy_lib/query_event_metrics.rb +++ b/app/legacy_lib/query_event_metrics.rb @@ -67,12 +67,12 @@ def self.for_listings(id_type, id, params) end if params["active"].present? exp = exp - .and_where(["events.end_datetime >= $date", date: Time.now]) + .and_where(["events.end_datetime >= $date", date: Time.zone.now]) .and_where(["events.published = TRUE AND coalesce(events.deleted, FALSE) = FALSE"]) end if params["past"].present? exp = exp - .and_where(["events.end_datetime < $date", date: Time.now]) + .and_where(["events.end_datetime < $date", date: Time.zone.now]) .and_where(["events.published = TRUE AND coalesce(events.deleted, FALSE) = FALSE"]) end if params["unpublished"].present? diff --git a/app/legacy_lib/query_nonprofits.rb b/app/legacy_lib/query_nonprofits.rb index 395218dde..6d017907a 100644 --- a/app/legacy_lib/query_nonprofits.rb +++ b/app/legacy_lib/query_nonprofits.rb @@ -11,7 +11,7 @@ def self.by_search_string(string) .where("nonprofits.published='t'") .order_by("nonprofits.name ASC") .limit(10) - )[1..-1] + )[1..] if results results = results.map { |id, name| {id: id, name: name} } end diff --git a/app/legacy_lib/query_payments.rb b/app/legacy_lib/query_payments.rb index 86a5d2c6e..ca2ea9dd0 100644 --- a/app/legacy_lib/query_payments.rb +++ b/app/legacy_lib/query_payments.rb @@ -38,7 +38,7 @@ def self.ids_for_payout(npo_id, options = {}) OR (NOT manual_balance_adjustments.disbursed)) )) .and_where("payments.date <= $date", date: options[:date] || end_of_day) - .execute.map { |h| h["id"] } + .execute.pluck("id") end # the amount to payout calculates the total payout based upon the payments it's provided, likely provided from ids_to_payout @@ -201,10 +201,10 @@ def self.select_to_filter_search(npo_id, query) ) end if query[:designation].present? - expr = expr.where("donations.designation @@ $s", s: "#{query[:designation]}") + expr = expr.where("donations.designation @@ $s", s: query[:designation].to_s) end if query[:dedication].present? - expr = expr.where("donations.dedication @@ $s", s: "#{query[:dedication]}") + expr = expr.where("donations.dedication @@ $s", s: query[:dedication].to_s) end if query[:donation_type].present? expr = expr.where("payments.kind IN ($kinds)", kinds: query[:donation_type].split(",")) @@ -334,10 +334,10 @@ def self.create_reverse_select(npo_id, query) expr = expr.where("to_char(payments.date, 'YYYY')=$year", year: query[:year]) end if query[:designation].present? - expr = expr.where("donations.designation @@ $s", s: "#{query[:designation]}") + expr = expr.where("donations.designation @@ $s", s: query[:designation].to_s) end if query[:dedication].present? - expr = expr.where("donations.dedication @@ $s", s: "#{query[:dedication]}") + expr = expr.where("donations.dedication @@ $s", s: query[:dedication].to_s) end if query[:donation_type].present? expr = expr.where("payments.kind IN ($kinds)", kinds: query[:donation_type].split(",")) @@ -429,12 +429,12 @@ def self.for_payout(npo_id, payout_id) def self.find_payments_where_too_far_from_charge_date(id = nil) pay = Payment.includes(:donation).includes(:offsite_payment) if id - pay = pay.where("id = ?", id) + pay = pay.where(id: id) end pay = pay.where.not(date: nil).order("id ASC") - pay.all.each { |p| + pay.all.find_each { |p| next if !p.offsite_payment.nil? - lowest_charge_for_payment = Charge.where("payment_id = ?", p.id).order("created_at ASC").limit(1).first + lowest_charge_for_payment = Charge.where(payment_id: p.id).order("created_at ASC").limit(1).first if lowest_charge_for_payment diff = p.date - lowest_charge_for_payment.created_at diff --git a/app/legacy_lib/query_recurring_donations.rb b/app/legacy_lib/query_recurring_donations.rb index 1dafc4c37..388bd09ad 100644 --- a/app/legacy_lib/query_recurring_donations.rb +++ b/app/legacy_lib/query_recurring_donations.rb @@ -81,7 +81,7 @@ def self.full_search_expr(np_id, query) end if failed_or_active_clauses.any? - expr = expr.where("#{failed_or_active_clauses.join(" OR ")}") + expr = expr.where(failed_or_active_clauses.join(" OR ").to_s) end if query.key?(:end_date_gt_or_equal) @@ -210,14 +210,14 @@ def self.get_chunk_of_export(npo_id, query, offset = nil, limit = nil, skip_head end def self.recurring_donations_without_cards - RecurringDonation.active.includes(:card).includes(:charges).includes(:donation).includes(:nonprofit).includes(:supporter).where("cards.id IS NULL").order("recurring_donations.created_at DESC") + RecurringDonation.active.includes(:card).includes(:charges).includes(:donation).includes(:nonprofit).includes(:supporter).where(cards: {id: nil}).order("recurring_donations.created_at DESC") end # @param [Supporter] supporter def self.find_recurring_donation_with_a_card(supporter) - supporter.recurring_donations.select { |rd| + supporter.recurring_donations.find { |rd| !rd.donation.nil? && !rd.donation.card.nil? - }.first + } end # Check if a single recdon is due -- used in PayRecurringDonation.with_stripe @@ -348,7 +348,7 @@ def self.last_charge end def self.export_for_transfer(nonprofit_id) - items = RecurringDonation.where("nonprofit_id = ?", nonprofit_id).active.includes("supporter").includes("card").to_a + items = RecurringDonation.where(nonprofit_id: nonprofit_id).active.includes("supporter").includes("card").to_a output = items.map { |i| {supporter: i.supporter.id, supporter_name: i.supporter.name, diff --git a/app/legacy_lib/query_roles.rb b/app/legacy_lib/query_roles.rb index 540c76d30..ba68e9afc 100644 --- a/app/legacy_lib/query_roles.rb +++ b/app/legacy_lib/query_roles.rb @@ -13,7 +13,7 @@ def self.host_ids(user_id, role_names) Qx.select("host_id").from(:roles) .where(user_id: user_id) .and_where("roles.name IN ($names)", names: role_names) - .execute.map { |h| h["host_id"] } + .execute.pluck("host_id") end def self.is_nonprofit_user?(user_id, np_id) diff --git a/app/legacy_lib/query_source_token.rb b/app/legacy_lib/query_source_token.rb index b8dfe9835..79a5baada 100644 --- a/app/legacy_lib/query_source_token.rb +++ b/app/legacy_lib/query_source_token.rb @@ -12,9 +12,9 @@ module QuerySourceToken # or we're past the expiration date def self.get_and_increment_source_token(token, user = nil) ParamValidation.new({token: token}, { - token: {required: true, format: UUID::Regex} + token: {required: true, format: UUID::REGEX} }) - source_token = SourceToken.where("token = ?", token).first + source_token = SourceToken.where(token: token).first if source_token source_token.with_lock { unless source_token_unexpired?(source_token) @@ -44,7 +44,7 @@ def self.source_token_unexpired?(source_token) if source_token.max_uses <= source_token.total_uses return false end - if source_token.expiration < Time.now + if source_token.expiration < Time.zone.now return false end true diff --git a/app/legacy_lib/query_supporters.rb b/app/legacy_lib/query_supporters.rb index 1553f7d1c..368ec3040 100644 --- a/app/legacy_lib/query_supporters.rb +++ b/app/legacy_lib/query_supporters.rb @@ -238,7 +238,7 @@ def self.full_filter_expr(np_id, query) expr = expr.and_where("payments.count = 0 OR payments.max_date <= timezone(COALESCE(nonprofits.timezone, 'UTC'), timezone('UTC', $d))", d: d) end if query[:MAX_payment_before].present? - date_ago = Timespan::TimeUnits[query[:MAX_payment_before]].utc + date_ago = Timespan::TIME_UNITS[query[:MAX_payment_before]].utc expr = expr.and_where("payments.max_date < timezone(COALESCE(nonprofits.timezone, 'UTC'), timezone('UTC', $date)) OR payments.count = 0", date: date_ago) end if query[:search].present? @@ -310,19 +310,19 @@ def self.full_filter_expr(np_id, query) if query[:event_id].present? select_tickets_supporters = Qx.select("event_ticket_supporters.supporter_id") .from( - "#{Qx.select("MAX(tickets.event_id) AS event_id", "tickets.supporter_id") + Qx.select("MAX(tickets.event_id) AS event_id", "tickets.supporter_id") .from(:tickets) .where("event_id = $event_id", event_id: query[:event_id]) - .group_by(:supporter_id).as("event_ticket_supporters").parse}" + .group_by(:supporter_id).as("event_ticket_supporters").parse.to_s ) select_donation_supporters = Qx.select("event_donation_supporters.supporter_id") .from( - "#{Qx.select("MAX(donations.event_id) AS event_id", "donations.supporter_id") + Qx.select("MAX(donations.event_id) AS event_id", "donations.supporter_id") .from(:donations) .where("event_id = $event_id", event_id: query[:event_id]) - .group_by(:supporter_id).as("event_donation_supporters").parse}" + .group_by(:supporter_id).as("event_donation_supporters").parse.to_s ) union_expr = "( @@ -522,7 +522,7 @@ def self.dupes_on_email(np_id, strict_mode = true) .and_where("email IS NOT NULL") .and_where("email != ''") .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -532,7 +532,7 @@ def self.dupes_on_name(np_id, strict_mode = true) dupes_expr(np_id) .and_where("name IS NOT NULL") .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -543,7 +543,7 @@ def self.dupes_on_name_and_email(np_id, strict_mode = true) dupes_expr(np_id) .and_where("name IS NOT NULL AND name != '' AND email IS NOT NULL AND email != ''") .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -557,7 +557,7 @@ def self.dupes_on_name_and_phone(np_id, strict_mode = true) AND phone_index != ''" ) .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -573,7 +573,7 @@ def self.dupes_on_name_and_phone_and_address(np_id, strict_mode = true) AND address != ''" ) .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -589,7 +589,7 @@ def self.dupes_on_phone_and_email_and_address(np_id, strict_mode = true) AND address != ''" ) .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -601,7 +601,7 @@ def self.dupes_on_address(np_id, strict_mode = true) AND address != ''" ) .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -615,7 +615,7 @@ def self.dupes_on_name_and_address(np_id, strict_mode = true) AND address != ''" ) .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -628,7 +628,7 @@ def self.dupes_on_last_name_and_address(np_id) AND address != ''" ) .group_by(calculated_last_name + " || '_____' || address") - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -641,7 +641,7 @@ def self.dupes_on_last_name_and_address_and_email(np_id) AND address != ''" ) .group_by(calculated_last_name + " || '_____' || address || '_____' || COALESCE(email, '')") - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -655,7 +655,7 @@ def self.dupes_on_phone_and_email(np_id, strict_mode = true) AND email != ''" ) .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -667,7 +667,7 @@ def self.dupes_on_address_without_zip_code(np_id, strict_mode = true) AND address != ''" ) .group_by(group_by_clause) - .execute(format: "csv")[1..-1] + .execute(format: "csv")[1..] .map { |arr_group| arr_group.flatten.sort } end @@ -898,14 +898,14 @@ def self.tag_joins(nonprofit_id, supporter_id) # this is inefficient, don't use in live code def self.find_supporters_with_multiple_recurring_donations_evil_way(npo_id) - supporters = Supporter.where("supporters.nonprofit_id = ?", npo_id).includes(:recurring_donations) + supporters = Supporter.where(supporters: {nonprofit_id: npo_id}).includes(:recurring_donations) supporters.select { |s| s.recurring_donations.length > 1 } end # this is inefficient, don't use in live code def self.find_supporters_with_multiple_active_recurring_donations_evil_way(npo_id) - supporters = Supporter.where("supporters.nonprofit_id = ?", npo_id).includes(:recurring_donations) - supporters.select { |s| s.recurring_donations.select { |rd| rd.active }.length > 1 } + supporters = Supporter.where(supporters: {nonprofit_id: npo_id}).includes(:recurring_donations) + supporters.select { |s| s.recurring_donations.count { |rd| rd.active } > 1 } end def self.parse_convert_datetime(date) diff --git a/app/legacy_lib/query_ticket_levels.rb b/app/legacy_lib/query_ticket_levels.rb index a710cfb4e..4c0ada68b 100644 --- a/app/legacy_lib/query_ticket_levels.rb +++ b/app/legacy_lib/query_ticket_levels.rb @@ -3,7 +3,7 @@ module QueryTicketLevels def self.gross_amount_from_tickets(tickets, discount_id) - amounts = TicketLevel.where("id IN (?)", tickets.map { |h| h["ticket_level_id"] }).map { |i| [i.id, i.amount] }.to_h + amounts = TicketLevel.where(id: tickets.map { |h| h["ticket_level_id"] }).map { |i| [i.id, i.amount] }.to_h total = tickets.map { |t| amounts[t["ticket_level_id"].to_i].to_i * t["quantity"].to_i }.sum if discount_id @@ -33,7 +33,7 @@ def self.verify_tickets_available(tickets) if data[:quantity] != 0 tl = TicketLevel.find(data[:ticket_level_id]) if tl.limit && tl.limit > 0 - already_sold = Ticket.where("ticket_level_id = ?", data[:ticket_level_id]).sum("tickets.quantity") + already_sold = Ticket.where(ticket_level_id: data[:ticket_level_id]).sum("tickets.quantity") unless (already_sold + data[:quantity]) <= tl.limit raise NotEnoughQuantityError.new(TicketLevel, data[:ticket_level_id], data[:quantity], "Oops! We sold out some of the tickets you wanted before ordering. Please refresh to see what tickets are still available.") end diff --git a/app/legacy_lib/query_users.rb b/app/legacy_lib/query_users.rb index ae28c6fc7..17a3e9014 100644 --- a/app/legacy_lib/query_users.rb +++ b/app/legacy_lib/query_users.rb @@ -4,7 +4,7 @@ module QueryUsers # Return all the nonprofit user emails for a given email notification setting # for notification_type in ['payments', 'campaigns', 'events', 'payouts', 'recurring_donations'] def self.nonprofit_user_emails(np_id, notification_type) - raise ArgumentError.new("Invalid notification type") unless QueryEmailSettings::Settings.include?(notification_type) + raise ArgumentError.new("Invalid notification type") unless QueryEmailSettings::SETTINGS.include?(notification_type) Qx.select("users.email") .from("users") .join("roles", "roles.user_id=users.id") @@ -13,7 +13,7 @@ def self.nonprofit_user_emails(np_id, notification_type) .where("email_settings.user_id IS NULL OR email_settings.#{notification_type}=TRUE") .and_where("nonprofits.id=$id", id: np_id) .group_by("users.email") - .execute.map { |h| h["email"] } + .execute.pluck("email") end # Return all nonprofit emails regardless of email settings @@ -23,13 +23,13 @@ def self.all_nonprofit_user_emails(np_id, roles = [:nonprofit_admin, :nonprofit_ .add_join("nonprofits", "nonprofits.id = roles.host_id AND roles.host_type='Nonprofit'") .where("nonprofits.id=$id", id: np_id) .and_where("roles.name IN ($names)", names: roles) - .execute.map { |h| h["email"] } + .execute.pluck("email") end # Return an array of email address strings for all users with role of 'super_admin' def self.super_admin_emails Qx.select("users.email").from("users") .join("roles", "roles.user_id=users.id AND roles.name='super_admin'") - .ex.map { |h| h["email"] } + .ex.pluck("email") end end diff --git a/app/legacy_lib/retrieve_active_record_items.rb b/app/legacy_lib/retrieve_active_record_items.rb index 520cfa072..6f27654f8 100644 --- a/app/legacy_lib/retrieve_active_record_items.rb +++ b/app/legacy_lib/retrieve_active_record_items.rb @@ -1,15 +1,14 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module RetrieveActiveRecordItems def self.retrieve(data, optional = false) - data.map { |k, v| - our_integer = begin - Integer(v) - rescue - nil - end + data.map do |k, v| + our_integer = Integer(v, exception: false) + + # rubocop:disable Style/UnlessLogicalOperators unless (optional && v.nil?) || (our_integer && our_integer > 0) raise ArgumentError.new("Value '#{v}' for Key '#{k}' is not valid") end + # rubocop:enable Style/UnlessLogicalOperators unless k.is_a? Class raise ArgumentError.new("Key '#{k}' is not a class") @@ -18,17 +17,17 @@ def self.retrieve(data, optional = false) if optional && v.nil? ret = [k, nil] else - ret = [k, k.where("id = ?", our_integer).first] + ret = [k, k.where(id: our_integer).first] if ret[1].nil? raise ParamValidation::ValidationError.new("ID #{v} is not a valid #{k}", {key: k}) end end ret - }.to_h + end.to_h end def self.retrieve_from_keys(input, class_to_key_hash, optional = false) - class_to_key_hash.map { |k, v| + class_to_key_hash.map do |k, v| unless k.is_a? Class raise ArgumentError.new("Key '#{k}' is not a class") end @@ -44,6 +43,6 @@ def self.retrieve_from_keys(input, class_to_key_hash, optional = false) raise ParamValidation::ValidationError.new("#{input[v]} is not a valid ID for Key '#{v}'", {key: v}) end ret - }.to_h + end.to_h end end diff --git a/app/legacy_lib/scheduled_jobs.rb b/app/legacy_lib/scheduled_jobs.rb index eeb057899..5d1e2b744 100644 --- a/app/legacy_lib/scheduled_jobs.rb +++ b/app/legacy_lib/scheduled_jobs.rb @@ -19,14 +19,14 @@ def self.delete_junk_data ids: Qx.select("custom_field_joins.id") .from(:custom_field_joins) .left_join("supporters", "custom_field_joins.supporter_id=supporters.id") - .where("supporters.id IS NULL") + .where(supporters: {id: nil}) }) # Delete orphaned tag joins del_tags_orphaned = Qx.delete_from(:tag_joins).where("id IN ($ids)", { ids: Qx.select("tag_joins.id") .from(:tag_joins) .left_join(:supporters, "tag_joins.supporter_id=supporters.id") - .where("supporters.id IS NULL") + .where(supporters: {id: nil}) }) Enumerator.new do |yielder| @@ -72,7 +72,7 @@ def self.update_verification_statuses def self.update_np_balances Enumerator.new do |yielder| - nps = Nonprofit.where("id IN (?)", Charge.pending.uniq.pluck(:nonprofit_id)) + nps = Nonprofit.where(id: Charge.pending.uniq.select(:nonprofit_id)) nps.each do |np| yielder << lambda do UpdateNonprofit.mark_available_charges(np.id) @@ -84,7 +84,7 @@ def self.update_np_balances def self.update_pending_payouts Enumerator.new do |yielder| - Payout.pending.includes(:nonprofit).each do |p| + Payout.pending.includes(:nonprofit).find_each do |p| yielder << lambda do if p.transfer_type == :transfer p.status = Stripe::Transfer.retrieve(p.stripe_transfer_id, { diff --git a/app/legacy_lib/search_vector.rb b/app/legacy_lib/search_vector.rb index 37beb6b39..b3df649af 100644 --- a/app/legacy_lib/search_vector.rb +++ b/app/legacy_lib/search_vector.rb @@ -1,7 +1,7 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module SearchVector - AcceptedTables = ["supporters", "payments"] + ACCEPTED_TABLES = ["supporters", "payments"] def self.query(query_string, expr = nil) query = if (query_string.is_a?(Integer) || query_string.is_int?) && SearchVector.within_postgres_integer_limit(query_string) diff --git a/app/legacy_lib/timespan.rb b/app/legacy_lib/timespan.rb index 3b2a4fdf3..cccfd1ef2 100644 --- a/app/legacy_lib/timespan.rb +++ b/app/legacy_lib/timespan.rb @@ -3,14 +3,16 @@ # Relies on activesupport Timespan = Struct.new(:interval, :time_unit) do - self::Units = ["week", "day", "month", "year"] - self::TimeUnits = { - "1_week" => 1.week.ago, - "2_weeks" => 2.weeks.ago, - "1_month" => 1.month.ago, - "3_months" => 3.months.ago, - "6_months" => 6.months.ago, - "1_year" => 1.year.ago, - "2_years" => 2.years.ago - } + self::UNITS = ["week", "day", "month", "year"] + self::TIME_UNITS = proc do + { + "1_week" => 1.week.ago, + "2_weeks" => 2.weeks.ago, + "1_month" => 1.month.ago, + "3_months" => 3.months.ago, + "6_months" => 6.months.ago, + "1_year" => 1.year.ago, + "2_years" => 2.years.ago + } + end end diff --git a/app/legacy_lib/update_activities.rb b/app/legacy_lib/update_activities.rb index ee6813014..165cd7538 100644 --- a/app/legacy_lib/update_activities.rb +++ b/app/legacy_lib/update_activities.rb @@ -18,7 +18,7 @@ def self.for_supporter_notes(note) def self.for_one_time_donation(payment) activity = generate_for_one_time_donation(payment) - activity.save! if activity + activity&.save! end def self.generate_for_one_time_donation(payment) diff --git a/app/legacy_lib/update_campaign_gift_option.rb b/app/legacy_lib/update_campaign_gift_option.rb index 8a9ee4213..2a03b26a1 100644 --- a/app/legacy_lib/update_campaign_gift_option.rb +++ b/app/legacy_lib/update_campaign_gift_option.rb @@ -1,7 +1,7 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module UpdateCampaignGiftOption def self.update gift_option, params - gift_option.update_attributes params + gift_option.update params gift_option end end diff --git a/app/legacy_lib/update_charges.rb b/app/legacy_lib/update_charges.rb index fe2ea3660..440469935 100644 --- a/app/legacy_lib/update_charges.rb +++ b/app/legacy_lib/update_charges.rb @@ -5,6 +5,6 @@ def self.disburse_all_with_payments(payment_ids) end def self.reverse_disburse_all_with_payments(payment_ids) - Charge.where("payment_id IN (?)", payment_ids).update_all(status: "available") + Charge.where(payment_id: payment_ids).update_all(status: "available") end end diff --git a/app/legacy_lib/update_custom_field_joins.rb b/app/legacy_lib/update_custom_field_joins.rb index f7baff2f0..92d8df89e 100644 --- a/app/legacy_lib/update_custom_field_joins.rb +++ b/app/legacy_lib/update_custom_field_joins.rb @@ -12,7 +12,7 @@ def self.delete_dupes(supporter_ids) .join("custom_field_masters cfms", "cfms.id = custom_field_joins.custom_field_master_id") .group_by("cfms.name") .having("COUNT(custom_field_joins) > 1") - .execute.map { |h| h["ids"][1..-1] }.flatten + .execute.map { |h| h["ids"][1..] }.flatten return unless ids.any? Qx.delete_from(:custom_field_joins) .where("id IN ($ids)", ids: ids) diff --git a/app/legacy_lib/update_disputes.rb b/app/legacy_lib/update_disputes.rb index 8840b3ef9..4ff772782 100644 --- a/app/legacy_lib/update_disputes.rb +++ b/app/legacy_lib/update_disputes.rb @@ -2,14 +2,14 @@ module UpdateDisputes def self.disburse_all_with_payments(payment_ids) - DisputeTransaction.where("payment_id IN (?)", payment_ids).update_all( + DisputeTransaction.where(payment_id: payment_ids).update_all( disbursed: true, updated_at: Time.current ) end def self.reverse_disburse_all_with_payments(payment_ids) - DisputeTransaction.where("payment_id IN (?)", payment_ids).update_all( + DisputeTransaction.where(payment_id: payment_ids).update_all( disbursed: false, updated_at: Time.current ) diff --git a/app/legacy_lib/update_donation.rb b/app/legacy_lib/update_donation.rb index 1288642d4..4c752290b 100644 --- a/app/legacy_lib/update_donation.rb +++ b/app/legacy_lib/update_donation.rb @@ -15,7 +15,7 @@ def self.update_payment(donation_id, data) id: {required: true, is_reference: true}, data: {required: true, is_hash: true} }) - existing_payment = Payment.where("donation_id = ?", donation_id).last + existing_payment = Payment.where(donation_id: donation_id).last unless existing_payment raise ParamValidation::ValidationError.new("#{donation_id} is does not correspond to a valid donation", @@ -48,7 +48,7 @@ def self.update_payment(donation_id, data) if set_to_nil[:campaign] campaign = nil else - campaign = Campaign.where("id = ?", data[:campaign_id]).first + campaign = Campaign.where(id: data[:campaign_id]).first unless campaign raise ParamValidation::ValidationError.new("#{data[:campaign_id]} is not a valid campaign", {key: :campaign_id}) end @@ -60,7 +60,7 @@ def self.update_payment(donation_id, data) if set_to_nil[:event] event = nil else - event = Event.where("id = ?", data[:event_id]).first + event = Event.where(id: data[:event_id]).first unless event raise ParamValidation::ValidationError.new("#{data[:event_id]} is not a valid event", {key: :event_id}) end @@ -100,7 +100,7 @@ def self.update_payment(donation_id, data) existing_payment.save! end elsif donation.designation - Payment.where("donation_id = ?", donation.id).update_all(towards: donation.designation, updated_at: Time.now) + Payment.where(donation_id: donation.id).update_all(towards: donation.designation, updated_at: Time.zone.now) end # if offsite, set check_number, date, gross_amount @@ -158,7 +158,7 @@ def self.correct_donations_when_date_and_payments_are_off(id) donation.date = donation.created_at donation.save! - payments = Payment.where("donation_id = ?", id).includes(:charge) + payments = Payment.where(donation_id: id).includes(:charge) payments.each { |p| @payments_corrected.push(p.id) diff --git a/app/legacy_lib/update_manual_balance_adjustments.rb b/app/legacy_lib/update_manual_balance_adjustments.rb index 7a28911e4..051712fcd 100644 --- a/app/legacy_lib/update_manual_balance_adjustments.rb +++ b/app/legacy_lib/update_manual_balance_adjustments.rb @@ -2,7 +2,7 @@ module UpdateManualBalanceAdjustments def self.disburse_all_with_payments(payment_ids) - ManualBalanceAdjustment.where("payment_id IN (?)", payment_ids).update_all( + ManualBalanceAdjustment.where(payment_id: payment_ids).update_all( disbursed: true, updated_at: Time.current ) diff --git a/app/legacy_lib/update_miscellaneous_np_info.rb b/app/legacy_lib/update_miscellaneous_np_info.rb index 97e4675ca..34cf49759 100644 --- a/app/legacy_lib/update_miscellaneous_np_info.rb +++ b/app/legacy_lib/update_miscellaneous_np_info.rb @@ -4,9 +4,9 @@ def self.update(np_id, misc_settings) ParamValidation.new({np_id: np_id, misc_settings: misc_settings}, np_id: {required: true, is_integer: true}, misc_settings: {required: true, is_hash: true}) - np = Nonprofit.where("id = ?", np_id).first + np = Nonprofit.where(id: np_id).first raise ParamValidation::ValidationError.new("Nonprofit #{np_id} does not exist", {key: :np_id}) unless np - misc = MiscellaneousNpInfo.where("nonprofit_id = ?", np_id).first + misc = MiscellaneousNpInfo.where(nonprofit_id: np_id).first unless misc misc = MiscellaneousNpInfo.new misc.nonprofit = np diff --git a/app/legacy_lib/update_nonprofit.rb b/app/legacy_lib/update_nonprofit.rb index e68768e07..781b6e4e2 100644 --- a/app/legacy_lib/update_nonprofit.rb +++ b/app/legacy_lib/update_nonprofit.rb @@ -25,7 +25,7 @@ def self.mark_available_charges(npo_id) remaining_balance -= payment["net_amount"] true end - end.map { |h| h["charge_id"] } + end.pluck("charge_id") Qx.update(:charges).set(status: "available").where("id IN ($ids)", ids: charge_ids).execute if charge_ids.any? end diff --git a/app/legacy_lib/update_order.rb b/app/legacy_lib/update_order.rb index aa351d1d8..d1e439c48 100644 --- a/app/legacy_lib/update_order.rb +++ b/app/legacy_lib/update_order.rb @@ -8,7 +8,7 @@ module UpdateOrder def self.with_data(table_name, data) vals = data.map { |h| "(#{h[:id].to_i}, #{h[:order].to_i})" }.join(", ") from_str = "(VALUES #{vals}) AS data(id, \"order\")" - Qx.update("#{table_name}") + Qx.update(table_name.to_s) .set('"order"="data"."order"') .timestamps .from(from_str) diff --git a/app/legacy_lib/update_payouts.rb b/app/legacy_lib/update_payouts.rb index 1827c3001..a02456738 100644 --- a/app/legacy_lib/update_payouts.rb +++ b/app/legacy_lib/update_payouts.rb @@ -6,7 +6,7 @@ def self.reverse_with_stripe(payout_id, status, failure_message) status: {included_in: ["pending", "paid", "canceled", "failed"], required: true}, failure_message: {not_blank: true, required: true} }) - payout = Payout.where("id = ?", payout_id).first + payout = Payout.where(id: payout_id).first unless payout raise ParamValidation::ValidationError.new("No payout with id number: #{payout_id} ", [{key: :payout_id}]) end diff --git a/app/legacy_lib/update_recurring_donations.rb b/app/legacy_lib/update_recurring_donations.rb index 8593adcb8..1f69cfbdd 100644 --- a/app/legacy_lib/update_recurring_donations.rb +++ b/app/legacy_lib/update_recurring_donations.rb @@ -14,7 +14,7 @@ def self.update_card_id(rd, token) ParamValidation.new({rd: rd, token: token}, { rd: {is_hash: true, required: true}, - token: {format: UUID::Regex, required: true} + token: {format: UUID::REGEX, required: true} }) ParamValidation.new(rd, @@ -46,7 +46,7 @@ def self.update_card_id(rd, token) # Update the paydate for a given recurring donation (provide rd['id']) def self.update_paydate(rd, paydate) - return ValidationError.new(["Invalid paydate"]) unless (1..28).include?(paydate.to_i) + return ValidationError.new(["Invalid paydate"]) unless (1..28).cover?(paydate.to_i) Psql.execute(Qexpr.new.update(:recurring_donations, paydate: paydate).where("id=$id", id: rd["id"])) rd["paydate"] = paydate rd @@ -60,7 +60,7 @@ def self.update_amount(rd, token, amount, fee_covered = false) ParamValidation.new({amount: amount, rd: rd, token: token}, {amount: {is_integer: true, min: 50, required: true}, rd: {required: true, is_a: RecurringDonation}, - token: {required: true, format: UUID::Regex}}) + token: {required: true, format: UUID::REGEX}}) source_token = QuerySourceToken.get_and_increment_source_token(token, nil) tokenizable = source_token.tokenizable @@ -87,11 +87,11 @@ def self.update_amount(rd, token, amount, fee_covered = false) end def self.update_from_start_dates - RecurringDonation.inactive.where("start_date >= ?", Date.today).update_all(active: true) + RecurringDonation.inactive.where("start_date >= ?", Time.zone.today).update_all(active: true) end def self.update_from_end_dates - RecurringDonation.active.where("end_date < ?", Date.today).update_all(active: false) + RecurringDonation.active.where("end_date < ?", Time.zone.today).update_all(active: false) end # Cancel a recurring donation (set active='f') and record the supporter/user email who did it @@ -120,7 +120,7 @@ def self.update(rd, params) params = set_defaults(params) if params[:donation] - rd.donation.update_attributes(params[:donation]) + rd.donation.update(params[:donation]) return rd.donation unless rd.donation.valid? params = params.except(:donation) end @@ -131,7 +131,7 @@ def self.update(rd, params) misc.save! params = params.except(:fee_covered) - rd.update_attributes(params) + rd.update(params) rd end diff --git a/app/legacy_lib/update_refunds.rb b/app/legacy_lib/update_refunds.rb index e0668b2c7..142a46ffc 100644 --- a/app/legacy_lib/update_refunds.rb +++ b/app/legacy_lib/update_refunds.rb @@ -10,6 +10,6 @@ def self.disburse_all_with_payments(payment_ids) end def self.reverse_disburse_all_with_payments(payment_ids) - Refund.where("payment_id IN (?)", payment_ids).update_all(disbursed: false) + Refund.where(payment_id: payment_ids).update_all(disbursed: false) end end diff --git a/app/legacy_lib/update_supporter.rb b/app/legacy_lib/update_supporter.rb index 9d559fd95..da410f551 100644 --- a/app/legacy_lib/update_supporter.rb +++ b/app/legacy_lib/update_supporter.rb @@ -1,7 +1,7 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module UpdateSupporter def self.from_info(supporter, params) - supporter.update_attributes(params) + supporter.update(params) supporter end diff --git a/app/legacy_lib/update_tickets.rb b/app/legacy_lib/update_tickets.rb index 5ae8e0f01..7dcf70100 100644 --- a/app/legacy_lib/update_tickets.rb +++ b/app/legacy_lib/update_tickets.rb @@ -4,7 +4,7 @@ def self.update(data, current_user = nil) ParamValidation.new(data, { event_id: {required: true, is_reference: true}, ticket_id: {required: true, is_reference: true}, - token: {format: UUID::Regex}, + token: {format: UUID::REGEX}, bid_id: {is_integer: true}, # note: nothing to check? diff --git a/app/legacy_lib/uuid.rb b/app/legacy_lib/uuid.rb index da1e2535b..ab4dd0db2 100644 --- a/app/legacy_lib/uuid.rb +++ b/app/legacy_lib/uuid.rb @@ -1,4 +1,4 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later module UUID - Regex = /\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?/ + REGEX = /\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?/ end diff --git a/app/mailers/base_mailer.rb b/app/mailers/base_mailer.rb index faf95c7c0..635d5498c 100644 --- a/app/mailers/base_mailer.rb +++ b/app/mailers/base_mailer.rb @@ -1,5 +1,6 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later -class BaseMailer < ActionMailer::Base + +class BaseMailer < ActionMailer::Base # rubocop:disable Rails/ApplicationMailer include Devise::Controllers::UrlHelpers helper ApplicationHelper default :from => Settings.mailer.default_from, "X-SES-CONFIGURATION-SET" => "Admin" diff --git a/app/mailers/dispute_mailer.rb b/app/mailers/dispute_mailer.rb index acf2ed2eb..bd13aa994 100644 --- a/app/mailers/dispute_mailer.rb +++ b/app/mailers/dispute_mailer.rb @@ -112,8 +112,8 @@ def updated(dispute) ## from application_helper. I don't have time to mess with this. def print_currency(cents, unit = "EUR", sign = true) dollars = cents.to_f / 100.0 - dollars = number_to_currency(dollars, unit: "#{unit}", precision: (dollars.round == dollars) ? 0 : 2) - dollars = dollars[1..-1] if !sign + dollars = number_to_currency(dollars, unit: unit.to_s, precision: (dollars.round == dollars) ? 0 : 2) + dollars = dollars[1..] if !sign dollars end end diff --git a/app/mailers/donation_mailer.rb b/app/mailers/donation_mailer.rb index ad9e99ddb..8c74e1f35 100644 --- a/app/mailers/donation_mailer.rb +++ b/app/mailers/donation_mailer.rb @@ -98,16 +98,6 @@ def nonprofit_recurring_donation_cancellation(donation_id) end end - def nonprofit_recurring_donation_change_amount(donation_id, previous_amount = nil) - @donation = RecurringDonation.find(donation_id).donation - @nonprofit = @donation.nonprofit - @emails = QueryUsers.nonprofit_user_emails(@nonprofit.id, "notify_recurring_donations") - @previous_amount = previous_amount - if @emails.any? - mail(to: @emails, subject: "Recurring donation amount changed for #{@donation.supporter.name || @donation.supporter.email}") - end - end - def donor_recurring_donation_change_amount(donation_id, previous_amount = nil) @donation = RecurringDonation.find(donation_id).donation @nonprofit = @donation.nonprofit diff --git a/app/mailers/export_mailer.rb b/app/mailers/export_mailer.rb index 25d12ba42..6b44050e9 100644 --- a/app/mailers/export_mailer.rb +++ b/app/mailers/export_mailer.rb @@ -54,24 +54,24 @@ def export_supporter_notes_failed_notification(export) def export_failed_recurring_donations_monthly_completed_notification(export) @export = export - mail(to: @export.user.email, subject: "Your report of failed recurring donations from #{Time.now.strftime("%B %Y")} is available!") + mail(to: @export.user.email, subject: "Your report of failed recurring donations from #{Time.zone.now.strftime("%B %Y")} is available!") end def export_failed_recurring_donations_monthly_failed_notification(export) @export = export - mail(to: @export.user.email, subject: "Your report of failed recurring donations from #{Time.now.strftime("%B %Y")} has failed.") + mail(to: @export.user.email, subject: "Your report of failed recurring donations from #{Time.zone.now.strftime("%B %Y")} has failed.") end def export_cancelled_recurring_donations_monthly_completed_notification(export) @export = export - mail(to: @export.user.email, subject: "Your report of cancelled recurring donations from #{Time.now.strftime("%B %Y")} is available!") + mail(to: @export.user.email, subject: "Your report of cancelled recurring donations from #{Time.zone.now.strftime("%B %Y")} is available!") end def export_cancelled_recurring_donations_monthly_cancelled_notification(export) @export = export - mail(to: @export.user.email, subject: "Your report of cancelled recurring donations from #{Time.now.strftime("%B %Y")} has failed.") + mail(to: @export.user.email, subject: "Your report of cancelled recurring donations from #{Time.zone.now.strftime("%B %Y")} has failed.") end end diff --git a/app/mailers/generic_mailer.rb b/app/mailers/generic_mailer.rb index d393ea026..4db7cd499 100644 --- a/app/mailers/generic_mailer.rb +++ b/app/mailers/generic_mailer.rb @@ -4,7 +4,7 @@ def generic_mail(from_email, from_name, message, subject, to_email, to_name) @from_email = from_email @from_name = from_name @message = message - mail(to: to_email, from: "#{from_name} <#{Settings.mailer.email}>", reply_to: from_email, subject: "#{subject}") + mail(to: to_email, from: "#{from_name} <#{Settings.mailer.email}>", reply_to: from_email, subject: subject.to_s) end # For sending a system notice to super admins diff --git a/app/mailers/ticket_mailer.rb b/app/mailers/ticket_mailer.rb index f5bb81a34..83e960bbd 100644 --- a/app/mailers/ticket_mailer.rb +++ b/app/mailers/ticket_mailer.rb @@ -17,7 +17,7 @@ def followup(ticket_ids, charge_id = nil) end def receipt_admin(ticket_ids, user_id = nil) - @tickets = Ticket.where("id IN (?)", ticket_ids) + @tickets = Ticket.where(id: ticket_ids) @charge = @tickets.last.charge @supporter = @tickets.last.supporter @event = @tickets.last.event diff --git a/app/models/bank_account.rb b/app/models/bank_account.rb index 2d3f2b5de..e33be29ac 100644 --- a/app/models/bank_account.rb +++ b/app/models/bank_account.rb @@ -16,7 +16,7 @@ class BankAccount < ApplicationRecord # validates :stripe_bank_account_token, presence: true, uniqueness: true # validates :stripe_bank_account_id, presence: true, uniqueness: true # validates :nonprofit, presence: true - # validates :email, presence: true, format: {with: Email::Regex} + # validates :email, presence: true, format: {with: Email::REGEX} # validate :nonprofit_must_be_vetted, on: :create # validate :nonprofit_has_stripe_account @@ -24,7 +24,7 @@ class BankAccount < ApplicationRecord belongs_to :nonprofit def nonprofit_must_be_vetted - errors.add(:nonprofit, "must be vetted") unless nonprofit && nonprofit.vetted + errors.add(:nonprofit, "must be vetted") unless nonprofit&.vetted end def nonprofit_has_stripe_account diff --git a/app/models/billing_plan.rb b/app/models/billing_plan.rb index 13e8de772..9b1d0fa3c 100644 --- a/app/models/billing_plan.rb +++ b/app/models/billing_plan.rb @@ -1,6 +1,6 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later class BillingPlan < ApplicationRecord - Names = ["Starter", "Fundraising", "Supporter Management"] + NAMES = ["Starter", "Fundraising", "Supporter Management"] attr_accessible \ :name, # str: readable name diff --git a/app/models/billing_subscription.rb b/app/models/billing_subscription.rb index bc0cf6e00..ad579d845 100644 --- a/app/models/billing_subscription.rb +++ b/app/models/billing_subscription.rb @@ -10,9 +10,6 @@ class BillingSubscription < ApplicationRecord belongs_to :nonprofit belongs_to :billing_plan - validates :nonprofit, presence: true - validates :billing_plan, presence: true - def as_json(options = {}) h = super h[:plan_name] = billing_plan.name diff --git a/app/models/campaign.rb b/app/models/campaign.rb index ac230f2cb..4ce3aa9a0 100644 --- a/app/models/campaign.rb +++ b/app/models/campaign.rb @@ -36,17 +36,14 @@ class Campaign < ApplicationRecord :default_reason_for_supporting validate :end_datetime_cannot_be_in_past, on: :create - validates :profile, presence: true - validates :nonprofit, presence: true - validates :goal_amount, - presence: true, numericality: { - only_integer: true - } + validates :goal_amount, presence: true, numericality: {only_integer: true} validate :validate_goal_amount - validates :name, - presence: true, - length: {maximum: 60} - validates :slug, uniqueness: {scope: :nonprofit_id, message: "You already have a campaign with that URL."}, presence: true + validates :name, presence: true, length: {maximum: 60} + + # rubocop:disable Rails/UniqueValidationWithoutIndex + validates :slug, presence: true, + uniqueness: {scope: :nonprofit_id, message: "You already have a campaign with that URL."} + # rubocop:enable Rails/UniqueValidationWithoutIndex validates :starting_point, presence: true, numericality: {only_integer: true, greater_than_or_equal_to: 0} @@ -80,8 +77,8 @@ class Campaign < ApplicationRecord has_many :children_campaigns, class_name: "Campaign", foreign_key: "parent_campaign_id" scope :published, -> { where(published: true) } - scope :active, -> { where(published: true).where("end_datetime IS NULL OR end_datetime >= ?", Date.today) } - scope :past, -> { where(published: true).where("end_datetime < ?", Date.today) } + scope :active, -> { where(published: true).where("end_datetime IS NULL OR end_datetime >= ?", Time.zone.today) } + scope :past, -> { where(published: true).where("end_datetime < ?", Time.zone.today) } scope :unpublished, -> { where(published: [nil, false]) } scope :not_deleted, -> { where(deleted: [nil, false]) } scope :deleted, -> { where(deleted: true) } @@ -165,7 +162,7 @@ def average_donation # Validations def end_datetime_cannot_be_in_past - if end_datetime.present? && end_datetime < Time.now + if end_datetime.present? && end_datetime < Time.zone.now errors.add(:end_datetime, "can't be in the past") end end @@ -180,11 +177,11 @@ def url def days_left return 0 if end_datetime.nil? - (end_datetime.to_date - Date.today).to_i + (end_datetime.to_date - Time.zone.today).to_i end def finished? - end_datetime && end_datetime < Time.now + end_datetime && end_datetime < Time.zone.now end def validate_goal_amount diff --git a/app/models/campaign_gift.rb b/app/models/campaign_gift.rb index 0e3e36ac5..ea62ff85f 100644 --- a/app/models/campaign_gift.rb +++ b/app/models/campaign_gift.rb @@ -8,7 +8,4 @@ class CampaignGift < ApplicationRecord belongs_to :donation belongs_to :campaign_gift_option - - validates :donation, presence: true - validates :campaign_gift_option, presence: true end diff --git a/app/models/comment.rb b/app/models/comment.rb index 13d262ede..c382d6305 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -5,7 +5,6 @@ class Comment < ApplicationRecord :profile_id, :body - validates :profile, presence: true validates :body, presence: true, length: {maximum: 200} has_one :activity, as: :attachment, dependent: :destroy diff --git a/app/models/concerns/model/calculated_names.rb b/app/models/concerns/model/calculated_names.rb index 5efdf371c..e10be0b9a 100644 --- a/app/models/concerns/model/calculated_names.rb +++ b/app/models/concerns/model/calculated_names.rb @@ -5,6 +5,7 @@ module Model::CalculatedNames extend ActiveSupport::Concern included do + # rubocop:disable Lint/LiteralAsCondition def calculated_first_name name_parts = name&.strip&.split(" ")&.map(&:strip) case name_parts&.count || 0 @@ -28,5 +29,6 @@ def calculated_last_name name_parts[-1] end end + # rubocop:enable Lint/LiteralAsCondition end end diff --git a/app/models/concerns/model/houidable.rb b/app/models/concerns/model/houidable.rb index 8d86ea56d..6499180e6 100644 --- a/app/models/concerns/model/houidable.rb +++ b/app/models/concerns/model/houidable.rb @@ -3,12 +3,11 @@ # License: AGPL-3.0-or-later WITH WTO-AP-3.0-or-later # Full license explanation at https://github.com/houdiniproject/houdini/blob/main/LICENSE -# rubocop:disable Layout/TrailingWhitespace # we do this becuase rubocop is bizarrely crashing on this file module Model::Houidable extend ActiveSupport::Concern class_methods do ### - # @description: Simplifies using HouIDs for an ActiveRecord class. A Houid (pronounced "Hoo-id") is a unique + # @description: Simplifies using HouIDs for an ActiveRecord class. A Houid (pronounced "Hoo-id") is a unique # identifier for an object. Houids have the format of: prefix_{22 random alphanumeric characters}. A prefix # consists of lowercase alphabetical characters. Each class must have its own unique prefix. All of the Houids # generated for that class will use that prefix. @@ -29,65 +28,59 @@ module Model::Houidable # @param houid_attribute {string|Symbol}: the attribute on this model to assign the Houid to. Defaults to :id. ### def setup_houid(prefix, houid_attribute = :id) - ###### # define_model_callbacks :houid_set # after_initialize :add_houid - # # The HouID prefix as a symbol # def houid_prefix # :supp # end - # # Generates a HouID using the provided houid_prefix # def generate_houid # houid_prefix.to_s + "_" + SecureRandom.alphanumeric(22) # end - - # private + # private # def add_houid # run_callbacks(:houid_set) do # write_attribute(:id, self.generate_houid) unless read_attribute(:id) # end # end ##### - class_eval <<-RUBY, __FILE__, __LINE__ + 1 # rubocop:disable Style/DocumentDynamicEvalDefinition - define_model_callbacks :houid_set - after_initialize :add_houid - - delegate :houid_prefix, :houid_attribute, :generate_houid, to: :class + class_eval <<-RUBY, __FILE__, __LINE__ + 1 # rubocop:disable Style/DocumentDynamicEvalDefinition + define_model_callbacks :houid_set + after_initialize :add_houid - # The HouID prefix as a symbol - # def self.houid_prefix - # :supp - # end + delegate :houid_prefix, :houid_attribute, :generate_houid, to: :class - def self.houid_prefix - :#{prefix} - end + # The HouID prefix as a symbol + # def self.houid_prefix + # :supp + # end - def self.houid_attribute - :#{houid_attribute} - end - - # Generates a HouID using the provided houid_prefix - def self.generate_houid - houid_prefix.to_s + "_" + SecureRandom.alphanumeric(22) - end + def self.houid_prefix + :#{prefix} + end - def to_houid - self.send(houid_attribute) - end - - private - def add_houid - run_callbacks(:houid_set) do - write_attribute(self.houid_attribute, self.generate_houid) unless read_attribute(self.houid_attribute) - end - end + def self.houid_attribute + :#{houid_attribute} + end + + # Generates a HouID using the provided houid_prefix + def self.generate_houid + houid_prefix.to_s + "_" + SecureRandom.alphanumeric(22) + end + + def to_houid + self.send(houid_attribute) + end + + private + def add_houid + run_callbacks(:houid_set) do + write_attribute(self.houid_attribute, self.generate_houid) unless read_attribute(self.houid_attribute) + end + end RUBY end end end - -# rubocop:enable Layout/TrailingWhitespace diff --git a/app/models/custom_field_join.rb b/app/models/custom_field_join.rb index a397460e1..a32c8db27 100644 --- a/app/models/custom_field_join.rb +++ b/app/models/custom_field_join.rb @@ -5,8 +5,6 @@ class CustomFieldJoin < ApplicationRecord :custom_field_master, :custom_field_master_id, :value - validates :custom_field_master, presence: true - belongs_to :custom_field_master belongs_to :supporter diff --git a/app/models/dispute.rb b/app/models/dispute.rb index e7d9f7262..1edaed4bf 100644 --- a/app/models/dispute.rb +++ b/app/models/dispute.rb @@ -1,8 +1,8 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later class Dispute < ApplicationRecord - Reasons = [:unrecognized, :duplicate, :fraudulent, :subscription_canceled, :product_unacceptable, :product_not_received, :unrecognized, :credit_not_processed, :goods_services_returned_or_refused, :goods_services_cancelled, :incorrect_account_details, :insufficient_funds, :bank_cannot_process, :debit_not_authorized, :general] + REASONS = [:unrecognized, :duplicate, :fraudulent, :subscription_canceled, :product_unacceptable, :product_not_received, :unrecognized, :credit_not_processed, :goods_services_returned_or_refused, :goods_services_cancelled, :incorrect_account_details, :insufficient_funds, :bank_cannot_process, :debit_not_authorized, :general] - Statuses = [:needs_response, :under_review, :won, :lost] + STATUSES = [:needs_response, :under_review, :won, :lost] attr_accessible \ :gross_amount, # int diff --git a/app/models/donation.rb b/app/models/donation.rb index 1827c916c..744ca4058 100644 --- a/app/models/donation.rb +++ b/app/models/donation.rb @@ -26,8 +26,6 @@ class Donation < ApplicationRecord attr_readonly :fts validates :amount, presence: true, numericality: {only_integer: true} - validates :supporter, presence: true - validates :nonprofit, presence: true validates_associated :charges validates :payment_provider, inclusion: {in: ["credit_card", "sepa"]}, allow_blank: true @@ -62,6 +60,6 @@ def actual_donation? private def set_anonymous - update_attributes(anonymous: false) if anonymous.nil? + update(anonymous: false) if anonymous.nil? end end diff --git a/app/models/e_tap_import_contact.rb b/app/models/e_tap_import_contact.rb index cba0d6ee8..8eb30ad2c 100644 --- a/app/models/e_tap_import_contact.rb +++ b/app/models/e_tap_import_contact.rb @@ -5,8 +5,8 @@ class ETapImportContact < ApplicationRecord def supporters nonprofit.supporters.not_deleted.includes(custom_field_joins: :custom_field_master) - .where("custom_field_masters.name = ?", "E-Tapestry Id #") - .where("custom_field_joins.value = ?", account_id.to_s).references(:custom_field_joins, :custom_field_masters) + .where(custom_field_masters: {name: "E-Tapestry Id #"}) + .where(custom_field_joins: {value: account_id.to_s}).references(:custom_field_joins, :custom_field_masters) end def supporter @@ -31,9 +31,9 @@ def self.find_by_account_id(account_id) where("row @> '{\"Account Number\": \"#{account_id}\"}'").first end - def journal_entries - e_tap_import.e_tap_import_journal_entries.by_account(row["Account Number"]) - end + # def journal_entries + # e_tap_import.e_tap_import_journal_entries.by_account(row["Account Number"]) + # end def self.find_by_account_name(account_name, account_email, original_account_id) query = where("row @> '{\"Account Name\": \"#{account_name}\"}' OR row @> '{\"Email\": \"#{account_email}\"}' OR row @> '{\"Email Address 2\": \"#{account_email}\"}' OR row @> '{\"Email Address 3\": \"#{account_email}\"}'") @@ -61,22 +61,21 @@ def create_or_update_CUSTOM(known_supporter = nil) # is this also relate to the latest payment if supporter - if (latest_journal_entry&.to_wrapper&.date || Time.at(0)) >= (supporter.payments.order("date DESC").first&.date || Time.at(0)) - puts "update the supporter info" + if (latest_journal_entry&.to_wrapper&.date || Time.zone.at(0)) >= (supporter.payments.order("date DESC").first&.date || Time.zone.at(0)) + Rails.logger.debug "update the supporter info" begin # did we overwrite the email? if supporter.persisted? && supporter.email && to_supporter_args[:email] && supporter.email.downcase != to_supporter_args[:email].downcase - cfj = supporter.custom_field_joins.joins(:custom_field_master).where("custom_field_masters.name = ?", "Overwrote previous email").references(:custom_field_masters).first + cfj = supporter.custom_field_joins.joins(:custom_field_master).where(custom_field_masters: {name: "Overwrote previous email"}).references(:custom_field_masters).first val = (cfj&.split(",") || []) + [supporter.email] custom_fields_to_save += [["Overwrote previous email", val.join(",")]] end supporter.update(to_supporter_args) - rescue PG::NotNullViolation => e - byebug + rescue PG::NotNullViolation => e # rubocop:disable Lint/UselessRescue raise e end else - puts "do nothing!" + Rails.logger.debug "do nothing!" end else supporter = e_tap_import.nonprofit.supporters.create(to_supporter_args) @@ -235,12 +234,12 @@ def to_custom_fields end def emails - [row["Email Address 1"], row["Email Address 2"], row["Email Address 3"]].select { |i| i.present? } + [row["Email Address 1"], row["Email Address 2"], row["Email Address 3"]].compact_blank end private def phone_numbers - [row["Phone - Voice"], row["Phone - Mobile"], row["Phone - Cell"]].select { |i| i.present? } + [row["Phone - Voice"], row["Phone - Mobile"], row["Phone - Cell"]].compact_blank end end diff --git a/app/models/e_tap_import_journal_entry.rb b/app/models/e_tap_import_journal_entry.rb index 4b82eb478..2acca2743 100644 --- a/app/models/e_tap_import_journal_entry.rb +++ b/app/models/e_tap_import_journal_entry.rb @@ -73,7 +73,7 @@ def create_or_update_payment if corresponding_payment && corresponding_matches? unless corresponding_payment.tickets.any? - byebug unless corresponding_payment.donation + # byebug unless corresponding_payment.donation UpdateDonation.update_payment(corresponding_payment.donation.id, { designation: designation, campaign_id: "", diff --git a/app/models/email_list.rb b/app/models/email_list.rb index be35a0b6b..7d5a8ff89 100644 --- a/app/models/email_list.rb +++ b/app/models/email_list.rb @@ -4,12 +4,9 @@ class EmailList < ApplicationRecord belongs_to :tag_master has_many :tag_joins, through: :tag_master - has_many :supporters, through: :tag_joins - # you can set this manually for testing but generally, it should be - # generated from the api key - attr_accessor :base_uri + attr_writer :base_uri # the path on the Mailchimp api for the list def list_path diff --git a/app/models/event.rb b/app/models/event.rb index a979d8156..57ce5d4fd 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -40,9 +40,11 @@ class Event < ApplicationRecord validates :address, presence: true validates :city, presence: true validates :state_code, presence: true - validates :slug, presence: true, uniqueness: {scope: :nonprofit_id, message: "You already have an event with that URL"} - validates :nonprofit_id, presence: true - validates :profile_id, presence: true + + # rubocop:disable Rails/UniqueValidationWithoutIndex + validates :slug, presence: true, + uniqueness: {scope: :nonprofit_id, message: "You already have an event with that URL"} + # rubocop:enable Rails/UniqueValidationWithoutIndex belongs_to :nonprofit belongs_to :profile @@ -69,12 +71,10 @@ class Event < ApplicationRecord scope :not_deleted, -> { where(deleted: [nil, false]) } scope :deleted, -> { where(deleted: true) } scope :published, -> { where(published: true) } - scope :upcoming, -> { where("start_datetime >= ?", Date.today).published } - scope :past, -> { where("end_datetime < ?", Date.today).published } + scope :upcoming, -> { where("start_datetime >= ?", Time.zone.today).published } + scope :past, -> { where("end_datetime < ?", Time.zone.today).published } scope :unpublished, -> { where.not(published: true) } - validates :slug, uniqueness: {scope: :nonprofit_id, message: "You already have a campaign with that name."} - before_validation(on: :create) do unless slug self.slug = Format::Url.convert_to_slug(name) diff --git a/app/models/export.rb b/app/models/export.rb index 19abd1794..2d9b12977 100644 --- a/app/models/export.rb +++ b/app/models/export.rb @@ -5,6 +5,4 @@ class Export < ApplicationRecord belongs_to :nonprofit belongs_to :user - - validates :user, presence: true end diff --git a/app/models/export_format.rb b/app/models/export_format.rb index 3b153b632..0808eb9b5 100644 --- a/app/models/export_format.rb +++ b/app/models/export_format.rb @@ -8,7 +8,6 @@ class ExportFormat < ApplicationRecord belongs_to :nonprofit validates :name, presence: true - validates :nonprofit_id, presence: true validates_with PostgresqlDateFormatValidator, {attribute_name: :date_format} diff --git a/app/models/fee_era.rb b/app/models/fee_era.rb index e7364e363..f8766b2fb 100644 --- a/app/models/fee_era.rb +++ b/app/models/fee_era.rb @@ -17,14 +17,14 @@ class FeeEra < ApplicationRecord has_many :fee_structures do def find_by_source(source) - unless source.respond_to?(:brand) and source.respond_to?(:country) + unless source.respond_to?(:brand) && source.respond_to?(:country) raise ArgumentError, "source must be a valid Stripe::Source, Stripe::Card or similar" end - brand_found = select { |i| i.brand == source.brand }.first + brand_found = find { |i| i.brand == source.brand } return brand_found if brand_found - blank_source = select { |i| i.brand.blank? }.first + blank_source = find { |i| i.brand.blank? } if blank_source.nil? raise ArgumentError, "source must be a valid Stripe::Source, Stripe::Card or similar" @@ -56,8 +56,8 @@ def charge_international_fee?(source) # @param at [DateTime,nil] def in_era?(at = nil) at ||= Time.current - test_start_time = start_time || Time.at(0) - test_end_time = end_time || Time.new(9999, 1) + test_start_time = start_time || Time.zone.at(0) + test_end_time = end_time || Time.zone.local(9999, 1) (test_start_time...test_end_time).cover? at end diff --git a/app/models/fee_structure.rb b/app/models/fee_structure.rb index dfd7d87e8..9b57c05d0 100644 --- a/app/models/fee_structure.rb +++ b/app/models/fee_structure.rb @@ -26,7 +26,7 @@ class FeeStructure < ApplicationRecord numericality: {greater_than_or_equal_to: 0, less_than: 1}, presence: true - validates :fee_era, presence: true + validates :fee_era, presence: true # rubocop:disable Rails/RedundantPresenceValidationOnBelongsTo delegate :charge_international_fee?, :international_surcharge_fee, to: :fee_era diff --git a/app/models/full_contact_photo.rb b/app/models/full_contact_photo.rb index 1326d07fb..036f5f843 100644 --- a/app/models/full_contact_photo.rb +++ b/app/models/full_contact_photo.rb @@ -7,7 +7,5 @@ class FullContactPhoto < ApplicationRecord :is_primary, # bool :url # string - belongs_to :full_contact_info - - validates :full_contact_info, presence: true + belongs_to :full_contact_info, optional: false end diff --git a/app/models/full_contact_social_profile.rb b/app/models/full_contact_social_profile.rb index f9a00dc0b..fbae73940 100644 --- a/app/models/full_contact_social_profile.rb +++ b/app/models/full_contact_social_profile.rb @@ -9,7 +9,5 @@ class FullContactSocialProfile < ApplicationRecord :bio, # string :url # string - belongs_to :full_contact_info - - validates :full_contact_info, presence: true + belongs_to :full_contact_info, optional: false end diff --git a/app/models/import.rb b/app/models/import.rb index ad8fc33b1..c49b4b858 100644 --- a/app/models/import.rb +++ b/app/models/import.rb @@ -11,6 +11,4 @@ class Import < ApplicationRecord has_many :supporters belongs_to :nonprofit belongs_to :user - - validates :user, presence: true end diff --git a/app/models/model_extensions/transaction_assignment/refund_extension.rb b/app/models/model_extensions/transaction_assignment/refund_extension.rb index d5f2bcb6e..b9860b2fd 100644 --- a/app/models/model_extensions/transaction_assignment/refund_extension.rb +++ b/app/models/model_extensions/transaction_assignment/refund_extension.rb @@ -13,7 +13,7 @@ def assignments # Handle a completed refund from a legacy Refund object def process_refund(refund) - donation = assignments.select { |i| i.assignable.is_a? ModernDonation }.first.assignable + donation = assignments.find { |i| i.assignable.is_a? ModernDonation }.assignable donation.amount = trx.amount donation.save! end diff --git a/app/models/nonprofit.rb b/app/models/nonprofit.rb index 325410fa3..1529f41d9 100755 --- a/app/models/nonprofit.rb +++ b/app/models/nonprofit.rb @@ -3,7 +3,7 @@ class Nonprofit < ApplicationRecord include Model::Houidable setup_houid :np, :houid - Categories = ["Public Benefit", "Human Services", "Education", "Civic Duty", "Human Rights", "Animals", "Environment", "Health", "Arts, Culture, Humanities", "International", "Children", "Religion", "LGBTQ", "Women's Rights", "Disaster Relief", "Veterans"] + CATEGORIES = ["Public Benefit", "Human Services", "Education", "Civic Duty", "Human Rights", "Animals", "Environment", "Health", "Arts, Culture, Humanities", "International", "Children", "Religion", "LGBTQ", "Women's Rights", "Disaster Relief", "Veterans"] attr_accessible \ :name, # str @@ -60,11 +60,11 @@ class Nonprofit < ApplicationRecord has_many :recurring_donations has_many :payments do def pending - joins(:charges).where("charges.status = ?", "pending") + joins(:charges).where(charges: {status: "pending"}) end def pending_totals - net, gross = pending.pluck(Arel.sql('SUM("payments"."net_amount") AS net, SUM("payments"."gross_amount") AS gross')).first + net, gross = pending.pick(Arel.sql('SUM("payments"."net_amount") AS net, SUM("payments"."gross_amount") AS gross')) {"net" => net, "gross" => gross} end @@ -166,9 +166,9 @@ def for_export_enumerable(query, chunk_limit = 15000) validates :name, presence: true validates :city, presence: true validates :state_code, presence: true - validates :email, format: {with: Email::Regex}, allow_blank: true + validates :email, format: {with: Email::REGEX}, allow_blank: true validate :timezone_is_valid - validates :slug, uniqueness: {scope: [:city_slug, :state_code_slug]} + validates :slug, uniqueness: {scope: [:city_slug, :state_code_slug]} # rubocop:disable Rails/UniqueValidationWithoutIndex validates :slug, presence: true scope :vetted, -> { where(vetted: true) } @@ -185,6 +185,7 @@ def for_export_enumerable(query, chunk_limit = 15000) self end + # rubocop:disable Lint/ConstantDefinitionInBlock concerning :Path do class_methods do ModernParams = Struct.new(:to_param) @@ -199,6 +200,7 @@ def to_modern_param end end end + # rubocop:enable Lint/ConstantDefinitionInBlock # Register (create) a nonprofit with an initial admin def self.register(user, params) @@ -275,13 +277,14 @@ def active_cards # @param [Card] card the new active_card def active_card=(card) - unless card.class == Card + unless card.instance_of?(Card) raise ArgumentError.new "Pass a card to active_card or else" end Card.transaction do active_cards.update_all inactive: true - return cards << card + cards << card end + cards end def active_card @@ -310,7 +313,7 @@ def steps_to_payout pending_bank_account = bank_account&.pending_verification - bank_account && bank_account.pending_verification + bank_account&.pending_verification bank_status = if no_bank_account :no_bank_account diff --git a/app/models/nonprofit_account.rb b/app/models/nonprofit_account.rb index 14a3846d5..1d24af10f 100644 --- a/app/models/nonprofit_account.rb +++ b/app/models/nonprofit_account.rb @@ -6,6 +6,5 @@ class NonprofitAccount < ApplicationRecord belongs_to :nonprofit - validates :nonprofit, presence: true validates :stripe_account_id, presence: true end diff --git a/app/models/object_event.rb b/app/models/object_event.rb index 6210c7181..e14bb7420 100644 --- a/app/models/object_event.rb +++ b/app/models/object_event.rb @@ -82,7 +82,7 @@ def event_entity(event_entity_houid) # Queries the database to find every ObjectEvent of a particular type def event_types(types) - where("event_type IN (?)", types) + where(event_type: types) end end end diff --git a/app/models/payment.rb b/app/models/payment.rb index d912fef9a..ce99c3142 100644 --- a/app/models/payment.rb +++ b/app/models/payment.rb @@ -68,7 +68,7 @@ def from_donation? elsif kind == "Dispute" || kind == "DisputeReversal" !!dispute_transaction&.from_donation? elsif kind == "OffsitePayment" - !!donation.present? + !donation.blank? else kind == "Donation" || kind == "RecurringDonation" end diff --git a/app/models/payment_import.rb b/app/models/payment_import.rb index 8a66c4a4a..e73920123 100644 --- a/app/models/payment_import.rb +++ b/app/models/payment_import.rb @@ -1,7 +1,7 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later class PaymentImport < ApplicationRecord attr_accessible :nonprofit, :user - has_and_belongs_to_many :donations, join_table: "donations_payment_imports" + has_and_belongs_to_many :donations, join_table: "donations_payment_imports" # rubocop:disable Rails/HasAndBelongsToMany belongs_to :nonprofit belongs_to :user end diff --git a/app/models/payment_payout.rb b/app/models/payment_payout.rb index 72bbbcb72..472071bc4 100644 --- a/app/models/payment_payout.rb +++ b/app/models/payment_payout.rb @@ -21,7 +21,4 @@ class PaymentPayout < ApplicationRecord belongs_to :charge # deprecated belongs_to :payment belongs_to :payout - - validates :payment, presence: true - validates :payout, presence: true end diff --git a/app/models/payout.rb b/app/models/payout.rb index 3b1abe6f4..8b2f49794 100644 --- a/app/models/payout.rb +++ b/app/models/payout.rb @@ -29,8 +29,8 @@ class Payout < ApplicationRecord has_many :payments, through: :payment_payouts has_many :object_events, as: :event_entity - validates :stripe_transfer_id, presence: true, uniqueness: true - validates :nonprofit, presence: true + validates :stripe_transfer_id, presence: true, uniqueness: true # rubocop:disable Rails/UniqueValidationWithoutIndex + validates :nonprofit, presence: true # rubocop:disable Rails/RedundantPresenceValidationOnBelongsTo validates :bank_account, presence: true validates :email, presence: true validates :net_amount, presence: true, numericality: {greater_than: 0} @@ -55,17 +55,17 @@ def transfer_type end def bank_account_must_be_confirmed - if bank_account && bank_account.pending_verification + if bank_account&.pending_verification errors.add(:bank_account, "must be confirmed via email") end end def nonprofit_must_have_identity_verified - errors.add(:nonprofit, "must be verified") unless nonprofit && nonprofit&.stripe_account&.payouts_enabled + errors.add(:nonprofit, "must be verified") unless nonprofit&.stripe_account&.payouts_enabled end def nonprofit_must_be_vetted - errors.add(:nonprofit, "must be vetted") unless nonprofit && nonprofit.vetted + errors.add(:nonprofit, "must be vetted") unless nonprofit&.vetted end def publish_created diff --git a/app/models/periodic_report.rb b/app/models/periodic_report.rb index 28ffe9964..e1049d337 100644 --- a/app/models/periodic_report.rb +++ b/app/models/periodic_report.rb @@ -7,7 +7,7 @@ class PeriodicReport < ApplicationRecord # nonprofit_id belongs_to :nonprofit, optional: false - has_and_belongs_to_many :users + has_and_belongs_to_many :users # rubocop:disable Rails/HasAndBelongsToMany belongs_to :nonprofit_s3_key validate :valid_report_type? diff --git a/app/models/profile.rb b/app/models/profile.rb index d5168d048..b54b8f4d4 100755 --- a/app/models/profile.rb +++ b/app/models/profile.rb @@ -17,14 +17,13 @@ class Profile < ApplicationRecord :city_state, :user_id - validates :email, format: {with: Email::Regex}, allow_blank: true + validates :email, format: {with: Email::REGEX}, allow_blank: true attr_accessor :email, :city_state mount_uploader :picture, ProfileUploader belongs_to :user - has_many :activities # Activities this profile has created has_many :supporters has_many :donations has_many :campaigns diff --git a/app/models/recurring_donation.rb b/app/models/recurring_donation.rb index 5955176c1..c714aee37 100644 --- a/app/models/recurring_donation.rb +++ b/app/models/recurring_donation.rb @@ -42,7 +42,7 @@ class RecurringDonation < ApplicationRecord scope :active, -> { where(active: true) } scope :inactive, -> { where(active: [false, nil]) } - scope :cancelled, -> { where(active: [false, nil]) } + scope :cancelled, -> { inactive } scope :monthly, -> { where(time_unit: "month", interval: 1) } scope :annual, -> { where(time_unit: "year", interval: 1) } scope :failed, -> { where("n_failures >= 3") } @@ -62,29 +62,21 @@ class RecurringDonation < ApplicationRecord has_many :activities, as: :attachment validates :paydate, numericality: {less_than: 29}, allow_blank: true - validates :donation_id, presence: true - validates :nonprofit_id, presence: true validates :start_date, presence: true validates :interval, presence: true, numericality: {greater_than: 0} - validates :time_unit, presence: true, inclusion: {in: Timespan::Units} + validates :time_unit, presence: true, inclusion: {in: Timespan::UNITS} validates_associated :donation def most_recent_charge - if charges - charges.sort_by { |c| c.created_at }.last - end + charges&.max_by { |c| c.created_at } end def most_recent_paid_charge - if charges - charges.find_all { |c| c.paid? }.sort_by { |c| c.created_at }.last - end + charges&.find_all { |c| c.paid? }&.max_by { |c| c.created_at } end def total_given - if charges - charges.find_all(&:paid?).sum(&:amount) - end + charges&.find_all(&:paid?)&.sum(&:amount) end def failed? @@ -129,7 +121,7 @@ def monthly_total private def set_anonymous - update_attributes(anonymous: false) if anonymous.nil? + update(anonymous: false) if anonymous.nil? end def fire_recurring_donation_created diff --git a/app/models/refund.rb b/app/models/refund.rb index b6bd67336..8ea697c3c 100644 --- a/app/models/refund.rb +++ b/app/models/refund.rb @@ -1,6 +1,6 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later class Refund < ApplicationRecord - Reasons = [:duplicate, :fraudulent, :requested_by_customer] + REASONS = [:duplicate, :fraudulent, :requested_by_customer] attr_accessible \ :amount, # int diff --git a/app/models/role.rb b/app/models/role.rb index 8803fb9ba..f297f49d1 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -1,6 +1,6 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later class Role < ApplicationRecord - Names = [ + NAMES = [ :super_admin, # global access :super_associate, # global access to everything except bank acct info :nonprofit_admin, # npo scoped access to everything @@ -24,8 +24,7 @@ class Role < ApplicationRecord scope :campaign_editors, -> { where(name: :campaign_editor) } scope :event_editors, -> { where(name: :event_editor) } - validates :user, presence: true - validates :name, inclusion: {in: Names} + validates :name, inclusion: {in: NAMES} validates :host, presence: true, unless: [:super_admin?, :super_associate?] def name diff --git a/app/models/source_token.rb b/app/models/source_token.rb index b95b24909..a6d995ac4 100644 --- a/app/models/source_token.rb +++ b/app/models/source_token.rb @@ -6,13 +6,13 @@ class SourceToken < ApplicationRecord belongs_to :tokenizable, polymorphic: true belongs_to :event - scope :expired, -> { where("max_uses <= total_uses OR expiration < ?", Time.now) } - scope :unexpired, -> { where(" NOT (max_uses <= total_uses OR expiration < ?)", Time.now) } + scope :expired, -> { where("max_uses <= total_uses OR expiration < ?", Time.zone.now) } + scope :unexpired, -> { where(" NOT (max_uses <= total_uses OR expiration < ?)", Time.zone.now) } scope :last_used_more_than_a_month_ago, -> { where("source_tokens.updated_at < ? ", 1.month.ago) } def expired? - max_uses <= total_uses || source_token.expiration < Time.now + max_uses <= total_uses || source_token.expiration < Time.zone.now end def unexpired? diff --git a/app/models/stripe_account.rb b/app/models/stripe_account.rb index a57007f57..db4244957 100644 --- a/app/models/stripe_account.rb +++ b/app/models/stripe_account.rb @@ -81,7 +81,7 @@ def serialize_on_update(input) when Stripe::Account self[:object] = input.to_hash object_json = object - puts object + Rails.logger.debug object when String self[:object] = input object_json = object @@ -110,7 +110,7 @@ def initialize(requirements) def current_deadline if @requirements["current_deadline"] && @requirements["current_deadline"].to_i != 0 - Time.at(@requirements["current_deadline"].to_i) + Time.zone.at(@requirements["current_deadline"].to_i) end end diff --git a/app/models/stripe_dispute.rb b/app/models/stripe_dispute.rb index cb3ffbf9e..da9b52aa4 100644 --- a/app/models/stripe_dispute.rb +++ b/app/models/stripe_dispute.rb @@ -16,7 +16,7 @@ def balance_transactions_state end def funds_withdrawn_balance_transaction - balance_transactions.any? ? balance_transactions.sort_by { |i| i["created"] }[0] : nil + balance_transactions.any? ? balance_transactions.min_by { |i| i["created"] } : nil end def funds_reinstated_balance_transaction @@ -41,14 +41,14 @@ def serialize_on_update(input) self.reason = object_json["reason"] self.status = object_json["status"] - self.net_change = object_json["balance_transactions"].map { |i| i["net"] }.sum + self.net_change = object_json["balance_transactions"].pluck("net").sum self.amount = object_json["amount"] self.stripe_dispute_id = object_json["id"] self.stripe_charge_id = object_json["charge"] self.evidence_due_date = (object_json["evidence_details"] && object_json["evidence_details"]["due_by"]) ? - Time.at(object_json["evidence_details"]["due_by"]) : + Time.zone.at(object_json["evidence_details"]["due_by"]) : nil - self.started_at = Time.at(object_json["created"]) + self.started_at = Time.zone.at(object_json["created"]) object end @@ -66,21 +66,20 @@ def fire_change_events if old_state != balance_transactions_state if old_state == :none + dispute_funds_withdrawn_event if balance_transactions_state == :funds_withdrawn - dispute_funds_withdrawn_event else - dispute_funds_withdrawn_event dispute_funds_reinstated_event end elsif old_state == :funds_withdrawn if balance_transactions_state == :funds_reinstated dispute_funds_reinstated_event else - raise RuntimeError("Dispute #{dispute.id} previously had a balance_transaction_state of #{old_state} but is now #{balance_transactions_state}. " + + raise RuntimeError("Dispute #{dispute.id} previously had a balance_transaction_state of #{old_state} but is now #{balance_transactions_state}. " \ "This shouldn't be possible.") end elsif balance_transactions_state != :funds_reinstated - raise RuntimeError("Dispute #{dispute.id} previously had a balance_transaction_state of #{old_state} but is now #{balance_transactions_state}. " + + raise RuntimeError("Dispute #{dispute.id} previously had a balance_transaction_state of #{old_state} but is now #{balance_transactions_state}. " \ "This shouldn't be possible.") end end @@ -89,7 +88,7 @@ def fire_change_events if saved_change_to_attribute?(:status) if TERMINAL_DISPUTE_STATUSES.include?(after_save_changed_attributes["status"]) && !TERMINAL_DISPUTE_STATUSES.include?(status) # if previous status was won or lost and the new one isn't - raise RuntimeError("Dispute #{dispute.id} was previously #{after_save_changed_attributes["status"]} but is now #{status}. " + + raise RuntimeError("Dispute #{dispute.id} was previously #{after_save_changed_attributes["status"]} but is now #{status}. " \ "This shouldn't be possible") elsif !TERMINAL_DISPUTE_STATUSES.include?(after_save_changed_attributes["status"]) && TERMINAL_DISPUTE_STATUSES.include?(status) # previous status was not won or lost but the new one is @@ -122,9 +121,9 @@ def dispute_funds_withdrawn_event fee_total: fee_total, net_amount: gross_amount + fee_total, kind: "Dispute", - date: Time.at(funds_withdrawn_balance_transaction["created"])), + date: Time.zone.at(funds_withdrawn_balance_transaction["created"])), stripe_transaction_id: funds_withdrawn_balance_transaction["id"], - date: Time.at(funds_withdrawn_balance_transaction["created"])) + date: Time.zone.at(funds_withdrawn_balance_transaction["created"])) # add dispute payment activity transaction.payment.activities.create @@ -144,9 +143,9 @@ def dispute_funds_reinstated_event fee_total: fee_total, net_amount: gross_amount + fee_total, kind: "DisputeReversed", - date: Time.at(funds_reinstated_balance_transaction["created"])), + date: Time.zone.at(funds_reinstated_balance_transaction["created"])), stripe_transaction_id: funds_reinstated_balance_transaction["id"], - date: Time.at(funds_reinstated_balance_transaction["created"])) + date: Time.zone.at(funds_reinstated_balance_transaction["created"])) transaction.dispute.original_payment.refund_total += gross_amount * -1 transaction.dispute.original_payment.save! @@ -159,35 +158,35 @@ def dispute_closed_event dispute.status = status dispute.save! if dispute.status == "won" - dispute.activities.create("DisputeWon", Time.now) + dispute.activities.create("DisputeWon", Time.zone.now) JobQueue.queue(JobTypes::DisputeWonJob, dispute) elsif dispute.status == "lost" - dispute.activities.create("DisputeLost", Time.now) + dispute.activities.create("DisputeLost", Time.zone.now) JobQueue.queue(JobTypes::DisputeLostJob, dispute) else - raise RuntimeError("Dispute #{dispute.id} was closed " + + raise RuntimeError("Dispute #{dispute.id} was closed " \ "but had status of #{dispute.status}") end end def dispute_updated_event - dispute.activities.create("DisputeUpdated", Time.now) + dispute.activities.create("DisputeUpdated", Time.zone.now) JobQueue.queue(JobTypes::DisputeUpdatedJob, dispute) end + def after_save_changed_attributes + saved_changes.transform_values(&:first) + end + + private_class_method + + # rubocop:disable Lint/IneffectiveAccessModifier def self.calc_balance_transaction_state(balance_transactions) if !balance_transactions || balance_transactions.count == 0 :none else - (balance_transactions.count == 1) ? - :funds_withdrawn : - :funds_reinstated + (balance_transactions.count == 1) ? :funds_withdrawn : :funds_reinstated end end - - private - - def after_save_changed_attributes - saved_changes.transform_values(&:first) - end + # rubocop:enable Lint/IneffectiveAccessModifier end diff --git a/app/models/stripe_event.rb b/app/models/stripe_event.rb index 0e26dd65a..773815e24 100644 --- a/app/models/stripe_event.rb +++ b/app/models/stripe_event.rb @@ -5,23 +5,23 @@ class StripeEvent < ApplicationRecord def self.process_dispute(event) StripeEvent.transaction do object = event.data.object - events_for_object_id = StripeEvent.where("object_id = ?", object.id).lock(true) + events_for_object_id = StripeEvent.where(object_id: object.id).lock(true) - event_record = events_for_object_id.where("event_id = ?", event.id).first + event_record = events_for_object_id.where(event_id: event.id).first # if event_record found, we've recorded this event so no processing necessary unless event_record # we record this event! - stripe_event = StripeEvent.new(event_id: event.id, event_time: Time.at(event.created).to_datetime, object_id: event.data.object.id) + stripe_event = StripeEvent.new(event_id: event.id, event_time: Time.zone.at(event.created).to_datetime, object_id: event.data.object.id) stripe_event.save! - later_event = events_for_object_id.where("event_time > ?", Time.at(event.created).to_datetime).first + later_event = events_for_object_id.where("event_time > ?", Time.zone.at(event.created).to_datetime).first # we have a later event so we don't need to process this anymore unless later_event LockManager.with_transaction_lock(object.id) do object = Stripe::Dispute.retrieve(object.id) - dispute = StripeDispute.where("stripe_dispute_id = ?", object.id).first + dispute = StripeDispute.where(stripe_dispute_id: object.id).first dispute ||= StripeDispute.new(stripe_dispute_id: object.id) dispute.object = object dispute.save! @@ -34,23 +34,23 @@ def self.process_dispute(event) def self.process_charge(event) StripeEvent.transaction do object = event.data.object - events_for_object_id = StripeEvent.where("object_id = ?", object.id).lock(true) + events_for_object_id = StripeEvent.where(object_id: object.id).lock(true) - event_record = events_for_object_id.where("event_id = ?", event.id).first + event_record = events_for_object_id.where(event_id: event.id).first # if event_record found, we've recorded this event so no processing necessary unless event_record # we record this event! - stripe_event = StripeEvent.new(event_id: event.id, event_time: Time.at(event.created).to_datetime, object_id: event.data.object.id) + stripe_event = StripeEvent.new(event_id: event.id, event_time: Time.zone.at(event.created).to_datetime, object_id: event.data.object.id) stripe_event.save! - later_event = events_for_object_id.where("event_time > ?", Time.at(event.created).to_datetime).first + later_event = events_for_object_id.where("event_time > ?", Time.zone.at(event.created).to_datetime).first # we have a later event so we don't need to process this anymore unless later_event LockManager.with_transaction_lock(object.id) do object = Stripe::Charge.retrieve(object.id) - charge = StripeCharge.where("stripe_charge_id = ?", object.id).first + charge = StripeCharge.where(stripe_charge_id: object.id).first charge ||= StripeCharge.new(stripe_charge_id: object.id) charge.object = object charge.save! @@ -65,22 +65,22 @@ def self.handle(event) when "account.updated" StripeEvent.transaction do object = event.data.object - events_for_object_id = StripeEvent.where("object_id = ?", object.id).lock(true) + events_for_object_id = StripeEvent.where(object_id: object.id).lock(true) - event_record = events_for_object_id.where("event_id = ?", event.id).first + event_record = events_for_object_id.where(event_id: event.id).first # if event_record found, we've recorded this event so no processing necessary unless event_record # we record this event! - stripe_event = StripeEvent.new(event_id: event.id, event_time: Time.at(event.created).to_datetime, object_id: event.data.object.id) + stripe_event = StripeEvent.new(event_id: event.id, event_time: Time.zone.at(event.created).to_datetime, object_id: event.data.object.id) stripe_event.save! - later_event = events_for_object_id.where("event_time > ?", Time.at(event.created).to_datetime).first + later_event = events_for_object_id.where("event_time > ?", Time.zone.at(event.created).to_datetime).first # we have a later event so we don't need to process this anymore unless later_event previous_verification_status = nil - account = StripeAccount.where("stripe_account_id = ?", object.id).first + account = StripeAccount.where(stripe_account_id: object.id).first if account account.lock!("FOR UPDATE") previous_verification_status = account.verification_status diff --git a/app/models/subtransaction.rb b/app/models/subtransaction.rb index 785fc01b3..be7da4d6f 100644 --- a/app/models/subtransaction.rb +++ b/app/models/subtransaction.rb @@ -24,6 +24,5 @@ def ordered_payments delegate :to_houid, :process_refund, :publish_updated, to: :subtransactable as_money :amount - - validates :subtransactable, presence: true + validates :subtransactable, presence: true # rubocop:disable Rails/RedundantPresenceValidationOnBelongsTo end diff --git a/app/models/supporter.rb b/app/models/supporter.rb index 9ff373045..842bbce55 100644 --- a/app/models/supporter.rb +++ b/app/models/supporter.rb @@ -59,19 +59,19 @@ def during_np_year(year) end def donation_payments - where("kind IN (?)", ["Donation", "RecurringDonation"]) + where(kind: ["Donation", "RecurringDonation"]) end def refund_payments - where("kind IN (?)", ["Refund"]) + where(kind: ["Refund"]) end def dispute_payments - where("kind IN (?)", ["Dispute"]) + where(kind: ["Dispute"]) end def dispute_reversal_payments - where("kind IN (?)", ["DisputeReversed"]) + where(kind: ["DisputeReversed"]) end end has_many :offsite_payments @@ -142,11 +142,10 @@ def update_member_on_all_lists has_many :addresses, class_name: "SupporterAddress", after_add: :set_address_to_primary_if_needed belongs_to :primary_address, class_name: "SupporterAddress" - validates :nonprofit, presence: true scope :not_deleted, -> { where(deleted: false) } scope :deleted, -> { where(deleted: true) } scope :merged, -> { where.not(merged_at: nil) } - scope :not_merged, -> { where("merged_at IS NULL") } + scope :not_merged, -> { where(merged_at: nil) } geocoded_by :full_address reverse_geocoded_by :latitude, :longitude do |obj, results| @@ -165,6 +164,7 @@ def profile_picture size = :normal profile.get_profile_picture(size) end + # rubocop:disable Lint/ConstantDefinitionInBlock concerning :Path do class_methods do ModernParams = Struct.new(:to_param) @@ -179,6 +179,7 @@ def to_modern_param end end end + # rubocop:enable Lint/ConstantDefinitionInBlock # Supporters can be merged many times. This finds the last # supporter after following merged_into until it gets a nil @@ -215,7 +216,7 @@ def cleanup_address def cleanup_name if first_name.present? || last_name.present? - assign_attributes(name: [first_name&.strip, last_name&.strip].select { |i| i.present? }.join(" ")) + assign_attributes(name: [first_name&.strip, last_name&.strip].compact_blank.join(" ")) assign_attributes(first_name: nil, last_name: nil) end end diff --git a/app/models/supporter_note.rb b/app/models/supporter_note.rb index 4fc96a850..1f818cfbb 100644 --- a/app/models/supporter_note.rb +++ b/app/models/supporter_note.rb @@ -10,7 +10,6 @@ class SupporterNote < ApplicationRecord belongs_to :user validates :content, length: {minimum: 1} - validates :supporter, presence: true after_create :create_activity diff --git a/app/models/tag_join.rb b/app/models/tag_join.rb index 2e3bb9c88..1699c2a8d 100644 --- a/app/models/tag_join.rb +++ b/app/models/tag_join.rb @@ -4,8 +4,6 @@ class TagJoin < ApplicationRecord :supporter, :supporter_id, :tag_master, :tag_master_id - validates :tag_master, presence: true - belongs_to :tag_master belongs_to :supporter diff --git a/app/models/ticket_level.rb b/app/models/ticket_level.rb index f598c3eb4..508a8ebf7 100644 --- a/app/models/ticket_level.rb +++ b/app/models/ticket_level.rb @@ -18,7 +18,6 @@ class TicketLevel < ApplicationRecord belongs_to :event validates :name, presence: true - validates :event_id, presence: true scope :not_deleted, -> { where(deleted: [false, nil]) } diff --git a/app/models/user.rb b/app/models/user.rb index f61a815bf..e14a08a10 100755 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,4 +1,5 @@ # License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later + class User < ApplicationRecord include Model::CalculatedNames @@ -40,14 +41,14 @@ class User < ApplicationRecord validates :email, presence: true, uniqueness: {case_sensitive: false}, - format: {with: Email::Regex} + format: {with: Email::REGEX} has_many :donations, through: :profile has_many :roles, dependent: :destroy has_one :profile, dependent: :destroy has_many :imports has_many :email_settings - has_and_belongs_to_many :periodic_reports + has_and_belongs_to_many :periodic_reports # rubocop:disable Rails/HasAndBelongsToMany accepts_nested_attributes_for :profile @@ -78,7 +79,7 @@ def profile_picture(size) # https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview def self.new_with_session(params, session) super.tap do |user| - if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"] + if (data = session["devise.facebook_data"]) && session["devise.facebook_data"]["extra"]["raw_info"] user.email = data["email"] if user.email.blank? end end @@ -111,7 +112,7 @@ def as_json(options = {}) def make_confirmation_token! raw, db = Devise.token_generator.generate(User, :confirmation_token) self.confirmation_token = db - self.confirmation_sent_at = Time.now + self.confirmation_sent_at = Time.zone.now save! raw end @@ -125,7 +126,7 @@ def send_devise_notification(notification, *args) def self.send_reset_password_instructions(attributes = {}) recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found) if recoverable.persisted? - if recoverable.reset_password_sent_at.nil? || Time.now > recoverable.reset_password_sent_at + 5.minutes + if recoverable.reset_password_sent_at.nil? || Time.zone.now > recoverable.reset_password_sent_at + 5.minutes recoverable.send_reset_password_instructions return recoverable else diff --git a/app/models/widget_description.rb b/app/models/widget_description.rb index c244893f0..c6e7c69e4 100644 --- a/app/models/widget_description.rb +++ b/app/models/widget_description.rb @@ -20,16 +20,14 @@ def to_json_safe_keys private def are_custom_amounts_correct - unless custom_amounts.nil? - custom_amounts.each_with_index do |amount, index| - if amount.is_a? Hash - unless amount.has_key?("amount") && amount["amount"].is_a?(Integer) - errors.add(:custom_amounts, "has an invalid amount #{amount} at index #{index}") - end - - elsif !amount.is_a? Integer + custom_amounts&.each_with_index do |amount, index| + if amount.is_a? Hash + unless amount.has_key?("amount") && amount["amount"].is_a?(Integer) errors.add(:custom_amounts, "has an invalid amount #{amount} at index #{index}") end + + elsif !amount.is_a? Integer + errors.add(:custom_amounts, "has an invalid amount #{amount} at index #{index}") end end end diff --git a/app/uploaders/article_background_uploader.rb b/app/uploaders/article_background_uploader.rb index 66796469b..a3474da35 100644 --- a/app/uploaders/article_background_uploader.rb +++ b/app/uploaders/article_background_uploader.rb @@ -47,6 +47,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/article_uploader.rb b/app/uploaders/article_uploader.rb index bf288b50e..bf40cedb4 100644 --- a/app/uploaders/article_uploader.rb +++ b/app/uploaders/article_uploader.rb @@ -47,6 +47,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/campaign_background_image_uploader.rb b/app/uploaders/campaign_background_image_uploader.rb index 00adc73a0..20be1030e 100644 --- a/app/uploaders/campaign_background_image_uploader.rb +++ b/app/uploaders/campaign_background_image_uploader.rb @@ -18,6 +18,6 @@ def extension_white_list end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/campaign_banner_image_uploader.rb b/app/uploaders/campaign_banner_image_uploader.rb index 0b6444752..ea7885f9b 100644 --- a/app/uploaders/campaign_banner_image_uploader.rb +++ b/app/uploaders/campaign_banner_image_uploader.rb @@ -11,6 +11,6 @@ def extension_white_list end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/campaign_main_image_uploader.rb b/app/uploaders/campaign_main_image_uploader.rb index 687549ca2..e71e44892 100644 --- a/app/uploaders/campaign_main_image_uploader.rb +++ b/app/uploaders/campaign_main_image_uploader.rb @@ -49,6 +49,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/event_background_image_uploader.rb b/app/uploaders/event_background_image_uploader.rb index 9373f7e70..c612155d8 100644 --- a/app/uploaders/event_background_image_uploader.rb +++ b/app/uploaders/event_background_image_uploader.rb @@ -45,6 +45,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/event_main_image_uploader.rb b/app/uploaders/event_main_image_uploader.rb index b515556be..763dea6c3 100644 --- a/app/uploaders/event_main_image_uploader.rb +++ b/app/uploaders/event_main_image_uploader.rb @@ -49,6 +49,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/image_attachment_uploader.rb b/app/uploaders/image_attachment_uploader.rb index da05bc92b..96c75e7c6 100644 --- a/app/uploaders/image_attachment_uploader.rb +++ b/app/uploaders/image_attachment_uploader.rb @@ -57,6 +57,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/nonprofit_background_uploader.rb b/app/uploaders/nonprofit_background_uploader.rb index 5f4327bc4..606277a55 100644 --- a/app/uploaders/nonprofit_background_uploader.rb +++ b/app/uploaders/nonprofit_background_uploader.rb @@ -48,6 +48,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/nonprofit_logo_uploader.rb b/app/uploaders/nonprofit_logo_uploader.rb index 78fdeae77..b0184fc64 100644 --- a/app/uploaders/nonprofit_logo_uploader.rb +++ b/app/uploaders/nonprofit_logo_uploader.rb @@ -44,6 +44,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/nonprofit_uploader.rb b/app/uploaders/nonprofit_uploader.rb index 3d8408253..61c9e83d5 100755 --- a/app/uploaders/nonprofit_uploader.rb +++ b/app/uploaders/nonprofit_uploader.rb @@ -54,6 +54,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/uploaders/profile_uploader.rb b/app/uploaders/profile_uploader.rb index e1e5b8e8c..413002089 100644 --- a/app/uploaders/profile_uploader.rb +++ b/app/uploaders/profile_uploader.rb @@ -53,6 +53,6 @@ def extension_white_list # end def cache_dir - "#{Rails.root.join("tmp/uploads")}" + Rails.root.join("tmp/uploads").to_s end end diff --git a/app/views/nonprofits/_edit.html.erb b/app/views/nonprofits/_edit.html.erb index 7a4406397..ebe40fb4f 100644 --- a/app/views/nonprofits/_edit.html.erb +++ b/app/views/nonprofits/_edit.html.erb @@ -46,7 +46,7 @@ <%= render :partial => "common/states_dropdown", :locals => {:name => 'nonprofit[state_code]', :default => @nonprofit.state_code} %> - +