Fix Layout/LineLength

This commit is contained in:
Neal Chambers
2023-06-22 08:45:36 +09:00
parent bca7813320
commit 1e4034534c
57 changed files with 299 additions and 160 deletions

View File

@@ -34,7 +34,8 @@ module Admin
# and https://www.postgresql.org/docs/current/static/sql-select.html#SQL-FOR-UPDATE-SHARE
order.with_lock do
if order.contents.update_item(@line_item, line_item_params)
render body: nil, status: :no_content # No Content, does not trigger ng resource auto-update
# No Content, does not trigger ng resource auto-update
render body: nil, status: :no_content
else
render json: { errors: @line_item.errors }, status: :precondition_failed
end

View File

@@ -62,9 +62,7 @@ module Admin
when :for_order_cycle
order_cycle = OrderCycle.find_by(id: params[:order_cycle_id]) if params[:order_cycle_id]
coordinator = Enterprise.find_by(id: params[:coordinator_id]) if params[:coordinator_id]
if order_cycle.nil? && coordinator.present?
order_cycle = OrderCycle.new(coordinator: coordinator)
end
order_cycle ||= OrderCycle.new(coordinator: coordinator) if coordinator.present?
enterprises = OpenFoodNetwork::OrderCyclePermissions.new(spree_current_user,
order_cycle).visible_enterprises
EnterpriseFee.for_enterprises(enterprises).order('enterprise_id', 'fee_type', 'name')

View File

@@ -16,7 +16,8 @@ module Admin
@enterprise_relationship = EnterpriseRelationship.new enterprise_relationship_params
if @enterprise_relationship.save
render plain: Api::Admin::EnterpriseRelationshipSerializer.new(@enterprise_relationship).to_json
render plain: Api::Admin::EnterpriseRelationshipSerializer
.new(@enterprise_relationship).to_json
else
render status: :bad_request,
json: { errors: @enterprise_relationship.errors.full_messages.join(', ') }

View File

@@ -122,7 +122,8 @@ module Admin
respond_to do |format|
format.json do
render json: @collection,
each_serializer: Api::Admin::ForOrderCycle::EnterpriseSerializer, order_cycle: @order_cycle, spree_current_user: spree_current_user
each_serializer: Api::Admin::ForOrderCycle::EnterpriseSerializer,
order_cycle: @order_cycle, spree_current_user: spree_current_user
end
end
end
@@ -178,9 +179,7 @@ module Admin
when :for_order_cycle
@order_cycle = OrderCycle.find_by(id: params[:order_cycle_id]) if params[:order_cycle_id]
coordinator = Enterprise.find_by(id: params[:coordinator_id]) if params[:coordinator_id]
if @order_cycle.nil? && coordinator.present?
@order_cycle = OrderCycle.new(coordinator: coordinator)
end
@order_cycle ||= OrderCycle.new(coordinator: coordinator) if coordinator.present?
enterprises = OpenFoodNetwork::OrderCyclePermissions.new(spree_current_user, @order_cycle)
.visible_enterprises

View File

@@ -37,8 +37,14 @@ module Admin
end
def reset_absent_products
@importer = ProductImport::ProductImporter.new(File.new(file_path),
spree_current_user, import_into: params[:import_into], enterprises_to_reset: params[:enterprises_to_reset], updated_ids: params[:updated_ids], settings: params[:settings])
@importer = ProductImport::ProductImporter.new(
File.new(file_path),
spree_current_user,
import_into: params[:import_into],
enterprises_to_reset: params[:enterprises_to_reset],
updated_ids: params[:updated_ids],
settings: params[:settings]
)
if params.key?(:enterprises_to_reset) && params.key?(:updated_ids)
@importer.reset_absent(params[:updated_ids])
@@ -56,8 +62,13 @@ module Admin
end
def process_data(method)
@importer = ProductImport::ProductImporter.new(File.new(file_path),
spree_current_user, start: params[:start], end: params[:end], settings: params[:settings])
@importer = ProductImport::ProductImporter.new(
File.new(file_path),
spree_current_user,
start: params[:start],
end: params[:end],
settings: params[:settings]
)
begin
@importer.public_send("#{method}_entries")

View File

@@ -18,7 +18,8 @@ module Admin
if view_context.subscriptions_setup_complete?(@shops)
@order_cycles = OrderCycle.joins(:schedules).managed_by(spree_current_user)
.includes([:distributors, :cached_incoming_exchanges])
@payment_methods = Spree::PaymentMethod.managed_by(spree_current_user).includes(:taggings)
@payment_methods = Spree::PaymentMethod.managed_by(spree_current_user)
.includes(:taggings)
@payment_method_tags = payment_method_tags_by_id
@shipping_methods = Spree::ShippingMethod.managed_by(spree_current_user)
else
@@ -100,7 +101,8 @@ module Admin
end
def load_shops
@shops = Enterprise.managed_by(spree_current_user).is_distributor.where(enable_subscriptions: true)
@shops = Enterprise.managed_by(spree_current_user)
.is_distributor.where(enable_subscriptions: true)
end
def load_form_data
@@ -139,7 +141,9 @@ module Admin
@open_orders_to_keep = @subscription.proxy_orders.placed_and_open.pluck(:id)
return if @open_orders_to_keep.empty? || params[:open_orders] == 'keep'
render json: { errors: { open_orders: t('admin.subscriptions.confirm_cancel_open_orders_msg') } },
render json: {
errors: { open_orders: t('admin.subscriptions.confirm_cancel_open_orders_msg') }
},
status: :conflict
end
@@ -147,7 +151,9 @@ module Admin
return if params[:canceled_orders] == 'notified'
return if @subscription.proxy_orders.active.canceled.empty?
render json: { errors: { canceled_orders: t('admin.subscriptions.resume_canceled_orders_msg') } },
render json: {
errors: { canceled_orders: t('admin.subscriptions.resume_canceled_orders_msg') }
},
status: :conflict
end

View File

@@ -27,8 +27,11 @@ module PaymentGateways
redirect_to provider.express_checkout_url(pp_response, useraction: 'commit')
else
flash[:error] =
Spree.t('flash.generic_error', scope: 'paypal',
reasons: pp_response.errors.map(&:long_message).join(" "))
Spree.t(
'flash.generic_error',
scope: 'paypal',
reasons: pp_response.errors.map(&:long_message).join(" "),
)
redirect_to main_app.checkout_step_path(:payment)
end
rescue SocketError

View File

@@ -7,7 +7,8 @@ module AngularFormHelper
container.map do |element|
html_attributes = option_html_attributes(element)
text, value = option_text_and_value(element).map(&:to_s)
%(<option value="#{ERB::Util.html_escape(value)}"#{html_attributes}>#{ERB::Util.html_escape(text)}</option>)
%(<option value="#{ERB::Util.html_escape(value)}"\
#{html_attributes}>#{ERB::Util.html_escape(text)}</option>)
end.join("\n").html_safe
end

View File

@@ -139,7 +139,7 @@ module CheckoutHelper
def stripe_card_options(cards)
cards.map do |cc|
[
"#{cc.brand} #{cc.last_digits} #{I18n.t(:card_expiry_abbreviation)}:"\
"#{cc.brand} #{cc.last_digits} #{I18n.t(:card_expiry_abbreviation)}:" \
"#{cc.month.to_s.rjust(2, '0')}/#{cc.year}", cc.id
]
end

View File

@@ -77,7 +77,8 @@ module EnterprisesHelper
end
def subscriptions_enabled?
spree_current_user.admin? || spree_current_user.enterprises.where(enable_subscriptions: true).any?
spree_current_user.admin? ||
spree_current_user.enterprises.where(enable_subscriptions: true).any?
end
def enterprise_url_selector(enterprise)

View File

@@ -18,9 +18,8 @@ module Spree
def changeable_orders
# Only returns open order for the current user + shop + oc combo
return @changeable_orders unless @changeable_orders.nil?
unless spree_current_user && current_distributor && current_order_cycle
return @changeable_orders = []
end
return @changeable_orders = [] unless spree_current_user &&
current_distributor && current_order_cycle
return @changeable_orders = [] unless current_distributor.allow_order_changes?
@changeable_orders = Spree::Order.complete.where(

View File

@@ -41,7 +41,9 @@ class SubscriptionConfirmJob < ApplicationJob
def recently_closed_order_cycles
OrderCycle.closed.where(
'order_cycles.orders_close_at BETWEEN (?) AND (?) OR order_cycles.updated_at BETWEEN (?) AND (?)', 1.hour.ago, Time.zone.now, 1.hour.ago, Time.zone.now
'order_cycles.orders_close_at BETWEEN (?) AND (?) ' \
'OR order_cycles.updated_at BETWEEN (?) AND (?)',
1.hour.ago, Time.zone.now, 1.hour.ago, Time.zone.now
)
end

View File

@@ -13,7 +13,7 @@ module Spree
@edit_password_reset_url = spree.
edit_spree_user_password_url(reset_password_token: token)
subject = "#{Spree::Config[:site_name]} " \
"#{I18n.t('spree.user_mailer.reset_password_instructions.subject')}"
"#{I18n.t('spree.user_mailer.reset_password_instructions.subject')}"
I18n.with_locale valid_locale(user) do
mail(to: user.email, subject: subject)

View File

@@ -38,14 +38,16 @@ class SubscriptionMailer < ApplicationMailer
@shop = Enterprise.find(summary.shop_id)
@summary = summary
mail(to: @shop.contact.email,
subject: "#{Spree::Config[:site_name]} #{t('subscription_mailer.placement_summary_email.subject')}")
subject: "#{Spree::Config[:site_name]} " \
"#{t('subscription_mailer.placement_summary_email.subject')}")
end
def confirmation_summary_email(summary)
@shop = Enterprise.find(summary.shop_id)
@summary = summary
mail(to: @shop.contact.email,
subject: "#{Spree::Config[:site_name]} #{t('subscription_mailer.confirmation_summary_email.subject')}")
subject: "#{Spree::Config[:site_name]} " \
"#{t('subscription_mailer.confirmation_summary_email.subject')}")
end
private

View File

@@ -4,7 +4,7 @@ require 'active_support/concern'
# This module is an adapter for OFN to work with Spree 2 code.
#
# Although Spree 2 supports multiple shipments per order, in OFN we have only one shipment per order.
# Although Spree 2 supports multiple shipments per order, in OFN we have only 1 shipment per order.
# A shipment is associated to a shipping_method through a selected shipping_rate.
# See https://github.com/openfoodfoundation/openfoodnetwork/wiki/Spree-Upgrade:-Migration-to-multiple-shipments
# for details.
@@ -30,7 +30,8 @@ module OrderShipment
shipments.first.shipping_method
end
# Finds the shipment's shipping_rate for the given shipping_method_id and selects that shipping_rate.
# Finds the shipment's shipping_rate for the given shipping_method_id
# and selects that shipping_rate.
# If the selection is successful, it persists it in the database by saving the shipment.
# If it fails, it does not clear the current shipping_method selection.
#

View File

@@ -6,7 +6,8 @@ module ProductStock
extend ActiveSupport::Concern
def on_demand
raise 'Cannot determine product on_demand value of product with multiple variants' if variants.size > 1
raise 'Cannot determine product on_demand value of product with multiple variants' if
variants.size > 1
variants.first.on_demand
end

View File

@@ -42,7 +42,8 @@ module VariantStock
# Checks whether this variant is produced on demand.
def on_demand
# A variant that has not been saved yet or has been soft-deleted doesn't have a stock item
# This provides a default value for variant.on_demand using Spree::StockLocation.backorderable_default
# This provides a default value for variant.on_demand
# using Spree::StockLocation.backorderable_default
return Spree::StockLocation.first.backorderable_default if new_record? || deleted?
# This can be removed unless we have seen this error in Bugsnag recently
@@ -76,8 +77,10 @@ module VariantStock
end
end
# Moving Spree::Stock::Quantifier.can_supply? to the variant enables us to override this behaviour for variant overrides
# We can have this responsibility here in the variant because there is only one stock item per variant
# Moving Spree::Stock::Quantifier.can_supply? to the variant enables us
# to override this behaviour for variant overrides
# We can have this responsibility here in the variant because there is
# only one stock item per variant
#
# Here we depend only on variant.total_on_hand and variant.on_demand.
# This way, variant_overrides only need to override variant.total_on_hand and variant.on_demand.
@@ -85,8 +88,10 @@ module VariantStock
on_demand || total_on_hand >= quantity
end
# Moving Spree::StockLocation.fill_status to the variant enables us to override this behaviour for variant overrides
# We can have this responsibility here in the variant because there is only one stock item per variant
# Moving Spree::StockLocation.fill_status to the variant enables us
# to override this behaviour for variant overrides
# We can have this responsibility here in the variant because there is
# only one stock item per variant
#
# Here we depend only on variant.total_on_hand and variant.on_demand.
# This way, variant_overrides only need to override variant.total_on_hand and variant.on_demand.
@@ -102,7 +107,8 @@ module VariantStock
[on_hand, backordered]
end
# We can have this responsibility here in the variant because there is only one stock item per variant
# We can have this responsibility here in the variant because there is
# only one stock item per variant
#
# This enables us to override this behaviour for variant overrides
def move(quantity, originator = nil)
@@ -138,7 +144,8 @@ module VariantStock
# Overwrites stock_item.count_on_hand
#
# Calling stock_item.adjust_count_on_hand will bypass filling backorders and creating stock movements
# Calling stock_item.adjust_count_on_hand will bypass filling backorders
# and creating stock movements
# If that was required we could call self.move
def overwrite_stock_levels(new_level)
stock_item.adjust_count_on_hand(new_level.to_i - stock_item.count_on_hand)

View File

@@ -34,7 +34,10 @@ class Customer < ApplicationRecord
validates :code, uniqueness: { scope: :enterprise_id, allow_nil: true }
validates :email, presence: true, 'valid_email_2/email': true,
uniqueness: { scope: :enterprise_id, message: I18n.t('validation_msg_is_associated_with_an_exising_customer') }
uniqueness: {
scope: :enterprise_id,
message: I18n.t('validation_msg_is_associated_with_an_exising_customer')
}
scope :of, ->(enterprise) { where(enterprise_id: enterprise) }
scope :managed_by, ->(user) { user&.persisted? ? where(user: user).or(of(Enterprise.managed_by(user))) : none }

View File

@@ -506,7 +506,10 @@ class Enterprise < ApplicationRecord
end
def set_unused_address_fields
address.firstname = address.lastname = address.phone = address.company = 'unused' if address.present?
if address.present?
address.firstname = address.lastname = address.phone =
address.company = 'unused'
end
business_address.first_name = business_address.last_name = 'unused' if business_address.present?
end

View File

@@ -11,7 +11,12 @@ module ProductImport
include ActiveModel::Validations
attr_accessor :line_number, :valid, :validates_as, :product_object, :product_validations,
:on_hand_nil, :has_overrides, :units, :unscaled_units, :unit_type, :tax_category, :shipping_category, :id, :product_id, :producer, :producer_id, :distributor, :distributor_id, :name, :display_name, :sku, :unit_value, :unit_description, :variant_unit, :variant_unit_scale, :variant_unit_name, :display_as, :category, :primary_taxon_id, :price, :on_hand, :on_demand, :tax_category_id, :shipping_category_id, :description, :import_date, :enterprise, :enterprise_id
:on_hand_nil, :has_overrides, :units, :unscaled_units, :unit_type, :tax_category,
:shipping_category, :id, :product_id, :producer, :producer_id, :distributor,
:distributor_id, :name, :display_name, :sku, :unit_value, :unit_description,
:variant_unit, :variant_unit_scale, :variant_unit_name, :display_as, :category,
:primary_taxon_id, :price, :on_hand, :on_demand, :tax_category_id,
:shipping_category_id, :description, :import_date, :enterprise, :enterprise_id
NON_DISPLAY_ATTRIBUTES = ['id', 'product_id', 'unscaled_units', 'variant_id', 'enterprise',
'enterprise_id', 'producer_id', 'distributor_id', 'primary_taxon',
@@ -68,7 +73,11 @@ module ProductImport
def invalid_attributes
invalid_attrs = {}
errors = @product_validations ? @product_validations.messages.merge(self.errors.messages) : self.errors.messages
errors = if @product_validations
@product_validations.messages.merge(self.errors.messages)
else
self.errors.messages
end
errors.each do |attr, message|
invalid_attrs[attr.to_s] = "#{attr.to_s.capitalize} #{message.first}"
end

View File

@@ -73,11 +73,13 @@ module ProductImport
end
def units_and_unit_type_present?
@attrs.key?('units') && @attrs.key?('unit_type') && @attrs['units'].present? && @attrs['unit_type'].present?
@attrs.key?('units') && @attrs.key?('unit_type') && @attrs['units'].present? &&
@attrs['unit_type'].present?
end
def units_and_variant_unit_name_present?
@attrs.key?('units') && @attrs.key?('variant_unit_name') && @attrs['units'].present? && @attrs['variant_unit_name'].present?
@attrs.key?('units') && @attrs.key?('variant_unit_name') && @attrs['units'].present? &&
@attrs['variant_unit_name'].present?
end
def valid_unit_type?(unit_type)

View File

@@ -17,7 +17,8 @@ class ProxyOrder < ApplicationRecord
scope :canceled, -> { where('proxy_orders.canceled_at IS NOT NULL') }
scope :not_canceled, -> { where('proxy_orders.canceled_at IS NULL') }
scope :placed_and_open, -> {
joins(:order).not_closed.where(spree_orders: { state: ['complete', 'resumed'] })
joins(:order).not_closed
.where(spree_orders: { state: ['complete', 'resumed'] })
}
def state

View File

@@ -8,7 +8,8 @@ class Schedule < ApplicationRecord
has_many :coordinators, -> { distinct }, through: :order_cycles
scope :with_coordinator, lambda { |enterprise|
joins(:order_cycles).where('coordinator_id = ?', enterprise.id).select('DISTINCT schedules.*')
joins(:order_cycles).where('coordinator_id = ?', enterprise.id)
.select('DISTINCT schedules.*')
}
def current_or_next_order_cycle

View File

@@ -75,7 +75,8 @@ module Spree
preference :attachment_url, :string,
default: '/spree/products/:id/:style/:basename.:extension'
preference :attachment_styles, :string,
default: "{\"mini\":\"48x48>\",\"small\":\"100x100>\",\"product\":\"240x240>\",\"large\":\"600x600>\"}"
default: "{\"mini\":\"48x48>\",\"small\":\"100x100>\"," \
"\"product\":\"240x240>\",\"large\":\"600x600>\"}"
preference :attachment_default_style, :string, default: 'product'
preference :s3_access_key, :string
preference :s3_bucket, :string

View File

@@ -91,7 +91,7 @@ module Spree
stripe_account: stripe_account_id)
gateway_options[:stripe_account] = stripe_account_id
# If a payment has been confirmed it cannot be voided by Stripe, and must be refunded instead
# If a payment has been confirmed it can't be voided by Stripe, and must be refunded instead
if voidable?(payment_intent_response)
provider.void(response_code, gateway_options)
else

View File

@@ -146,9 +146,7 @@ module Spree
}
scope :with_line_items_variants_and_products_outer, lambda {
joins('LEFT OUTER JOIN spree_line_items ON (spree_line_items.order_id = spree_orders.id)').
joins('LEFT OUTER JOIN spree_variants ON (spree_variants.id = spree_line_items.variant_id)').
joins('LEFT OUTER JOIN spree_products ON (spree_products.id = spree_variants.product_id)')
left_joins(:line_items, line_items: :variant, variant: :product)
}
# All the states an order can be in after completing the checkout

View File

@@ -36,15 +36,17 @@ module Spree
return val
end
# If it's not in the cache, maybe it's in the database, but
# has been cleared from the cache
# If it's not in the cache, maybe it's in the database, but has been cleared from the cache
# does it exist in the database?
if should_persist? && (Spree::Preference.table_exists? && preference = Spree::Preference.find_by(key: key))
# it does exist, so let's put it back into the cache
@cache.write(preference.key, preference.value)
if should_persist? && Spree::Preference.table_exists?
preference = Spree::Preference.find_by(key: key)
if preference
# it does exist, so let's put it back into the cache
@cache.write(preference.key, preference.value)
# and return the value
return preference.value
# and return the value
return preference.value
end
end
unless fallback.nil?

View File

@@ -29,12 +29,14 @@ class Subscription < ApplicationRecord
accepts_nested_attributes_for :bill_address, :ship_address
scope :not_ended, -> {
where('subscriptions.ends_at > (?) OR subscriptions.ends_at IS NULL', Time.zone.now)
where('subscriptions.ends_at > (?) OR subscriptions.ends_at IS NULL',
Time.zone.now)
}
scope :not_canceled, -> { where('subscriptions.canceled_at IS NULL') }
scope :not_paused, -> { where('subscriptions.paused_at IS NULL') }
scope :active, -> {
not_canceled.not_ended.not_paused.where('subscriptions.begins_at <= (?)', Time.zone.now)
not_canceled.not_ended.not_paused.where('subscriptions.begins_at <= (?)',
Time.zone.now)
}
def closed_proxy_orders

View File

@@ -13,7 +13,8 @@ class VariantOverride < ApplicationRecord
validates :hub, presence: true
validates :variant, presence: true
# Default stock can be nil, indicating stock should not be reset or zero, meaning reset to zero. Need to ensure this can be set by the user.
# Default stock can be nil, indicating stock should not be reset or zero, meaning reset to zero.
# Need to ensure this can be set by the user.
validates :default_stock, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
validates :price, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
validates :count_on_hand, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
@@ -48,7 +49,8 @@ class VariantOverride < ApplicationRecord
def move_stock!(quantity)
unless stock_overridden?
Bugsnag.notify RuntimeError.new "Attempting to move stock of a VariantOverride without a count_on_hand specified."
Bugsnag.notify RuntimeError.new "Attempting to move stock of a VariantOverride " \
"without a count_on_hand specified."
return
end
@@ -69,7 +71,8 @@ class VariantOverride < ApplicationRecord
self.attributes = { on_demand: false, count_on_hand: default_stock }
save
else
Bugsnag.notify RuntimeError.new "Attempting to reset stock level for a variant with no default stock level."
Bugsnag.notify RuntimeError.new "Attempting to reset stock level for a variant " \
"with no default stock level."
end
end
self

View File

@@ -131,7 +131,8 @@ class CartService
li_added = li.nil? && (variant_data[:quantity].to_i > 0 || variant_data[:max_quantity].to_i > 0)
li_quantity_changed = li.present? && li.quantity != variant_data[:quantity].to_i
li_max_quantity_changed = li.present? && li.max_quantity.to_i != variant_data[:max_quantity].to_i
li_max_quantity_changed = li.present? &&
li.max_quantity.to_i != variant_data[:max_quantity].to_i
li_added || li_quantity_changed || li_max_quantity_changed
end
@@ -153,8 +154,8 @@ class CartService
end
def check_variant_available_under_distribution(variant)
return true if OrderCycleDistributedVariants.new(@order_cycle,
@distributor).available_variants.include? variant
return true if OrderCycleDistributedVariants.new(@order_cycle, @distributor)
.available_variants.include? variant
errors.add(:base, I18n.t(:spree_order_populator_availability_error))
false

View File

@@ -35,7 +35,8 @@ class EmbeddedPageService
end
def embedding_without_https?
@request.referer && URI(@request.referer).scheme != 'https' && !Rails.env.test? && !Rails.env.development?
@request.referer && URI(@request.referer).scheme != 'https' &&
!Rails.env.test? && !Rails.env.development?
end
def process_embedded_request
@@ -62,7 +63,8 @@ class EmbeddedPageService
end
def enterprise_slug
return false unless @params[:controller] == 'enterprises' && @params[:action] == 'shop' && @params[:id]
return false unless @params[:controller] == 'enterprises' &&
@params[:action] == 'shop' && @params[:id]
@params[:id]
end

View File

@@ -87,18 +87,21 @@ class OrderCycleForm
shipping_method_ids += user_only_selected_distributor_shipping_method_ids
order_cycle.selected_distributor_shipping_method_ids = shipping_method_ids
else
order_cycle.selected_distributor_shipping_method_ids = selected_distributor_shipping_method_ids
order_cycle.selected_distributor_shipping_method_ids =
selected_distributor_shipping_method_ids
end
order_cycle.save!
end
def attachable_distributor_payment_method_ids
@attachable_distributor_payment_method_ids ||= order_cycle.attachable_distributor_payment_methods.map(&:id)
@attachable_distributor_payment_method_ids ||=
order_cycle.attachable_distributor_payment_methods.map(&:id)
end
def attachable_distributor_shipping_method_ids
@attachable_distributor_shipping_method_ids ||= order_cycle.attachable_distributor_shipping_methods.map(&:id)
@attachable_distributor_shipping_method_ids ||=
order_cycle.attachable_distributor_shipping_methods.map(&:id)
end
def exchanges_unchanged?
@@ -113,7 +116,8 @@ class OrderCycleForm
@selected_distributor_payment_method_ids.reject(&:blank?).map(&:to_i)
)
if attachable_distributor_payment_method_ids.sort == @selected_distributor_payment_method_ids.sort
if attachable_distributor_payment_method_ids.sort ==
@selected_distributor_payment_method_ids.sort
@selected_distributor_payment_method_ids = []
end
@@ -130,7 +134,8 @@ class OrderCycleForm
@selected_distributor_shipping_method_ids.reject(&:blank?).map(&:to_i)
)
if attachable_distributor_shipping_method_ids.sort == @selected_distributor_shipping_method_ids.sort
if attachable_distributor_shipping_method_ids.sort ==
@selected_distributor_shipping_method_ids.sort
@selected_distributor_shipping_method_ids = []
end
@@ -146,7 +151,8 @@ class OrderCycleForm
result = existing_schedule_ids
result |= (requested_schedule_ids & permitted_schedule_ids) # Add permitted and requested
result -= ((result & permitted_schedule_ids) - requested_schedule_ids) # Remove permitted but not requested
# Remove permitted but not requested
result -= ((result & permitted_schedule_ids) - requested_schedule_ids)
result
end

View File

@@ -83,7 +83,8 @@ class OrderSyncer
# switching from pick-up to delivery affects whether simultaneous changes to shipping address
# are ignored or not.
pickup_to_delivery = force_ship_address_required?(order)
if (!pickup_to_delivery || order.shipment.present?) && (ship_address.changes.keys & relevant_address_attrs).any?
if (!pickup_to_delivery || order.shipment.present?) &&
(ship_address.changes.keys & relevant_address_attrs).any?
save_ship_address_in_order(order)
end
if !pickup_to_delivery || order.shipment.blank?

View File

@@ -33,7 +33,8 @@ module VariantUnits
# Bread - 1kg # if display_name blank
# Bread - Spelt Sourdough, 1kg # if display_name is "Spelt Sourdough, 1kg"
# Bread - 1kg Spelt Sourdough # if unit_to_display is "1kg Spelt Sourdough"
# Bread - Spelt Sourdough (1kg) # if display_name is "Spelt Sourdough" and unit_to_display is "1kg"
# if display_name is "Spelt Sourdough" and unit_to_display is "1kg"
# Bread - Spelt Sourdough (1kg)
def full_name
return unit_to_display if display_name.blank?
return display_name if display_name.downcase.include? unit_to_display.downcase

View File

@@ -15,7 +15,7 @@ module OrderManagement
@subscriptions = subscriptions.not_ended.not_canceled
else
raise "ProxyOrderSyncer must be initialized with " \
"an instance of Subscription or ActiveRecord::Relation"
"an instance of Subscription or ActiveRecord::Relation"
end
end
@@ -39,7 +39,7 @@ module OrderManagement
def initialise_proxy_orders!
uninitialised_order_cycle_ids.each do |order_cycle_id|
Rails.logger.info "Initializing Proxy Order " \
"of subscription #{@subscription.id} in order cycle #{order_cycle_id}"
"of subscription #{@subscription.id} in order cycle #{order_cycle_id}"
proxy_orders << ProxyOrder.new(subscription: subscription, order_cycle_id: order_cycle_id)
end
end

View File

@@ -123,8 +123,8 @@ module OrderManagement
return @available_variant_ids if @available_variant_ids.present?
subscription_variant_ids = subscription_line_items.map(&:variant_id)
@available_variant_ids = OrderManagement::Subscriptions::VariantsList.eligible_variants(shop)
.where(id: subscription_variant_ids).pluck(:id)
@available_variant_ids = OrderManagement::Subscriptions::VariantsList
.eligible_variants(shop).where(id: subscription_variant_ids).pluck(:id)
end
def build_msg_from(key, msg)

View File

@@ -160,7 +160,7 @@ module OrderManagement
end
end
context "when the order has a payment that requires authorization and a completed payment" do
context "when order has a payment that requires authorization and a completed payment" do
let!(:payment) { create(:payment, order: order, state: "requires_authorization") }
let!(:completed_payment) { create(:payment, :completed, order: order) }
@@ -359,7 +359,7 @@ module OrderManagement
end
end
context "when unused payments records exist which require authorization, "\
context "when unused payments records exist which require authorization, " \
"but the order is fully paid" do
let!(:cash_payment) {
build(:payment, state: "completed", amount: order.new_outstanding_balance)

View File

@@ -56,8 +56,8 @@ module OrderManagement
expect(payment).to_not receive(:update)
expect(payment_setup.call!).to eq payment
expect(order.errors[:base].first).to eq "There are no authorised "\
"credit cards available to charge"
expect(order.errors[:base].first).to eq "There are no authorised " \
"credit cards available to charge"
end
end
@@ -82,8 +82,8 @@ module OrderManagement
expect(payment).to_not receive(:update)
expect(payment_setup.call!).to eq payment
expect(order.errors[:base].first).to eq "There are no authorised "\
"credit cards available to charge"
expect(order.errors[:base].first).to eq "There are no authorised " \
"credit cards available to charge"
end
end

View File

@@ -10,10 +10,11 @@ module Web
end
def matomo_iframe_src
"#{Spree::Config.matomo_url}"\
"/index.php?module=CoreAdminHome&action=optOut"\
"&language=#{locale_language}"\
"&backgroundColor=&fontColor=222222&fontSize=16px&fontFamily=%22Roboto%22%2C%20Arial%2C%20sans-serif"
"#{Spree::Config.matomo_url}" \
"/index.php?module=CoreAdminHome&action=optOut" \
"&language=#{locale_language}" \
"&backgroundColor=&fontColor=222222&fontSize=16px&" \
"fontFamily=%22Roboto%22%2C%20Arial%2C%20sans-serif"
end
# removes country from locale if needed

View File

@@ -4,8 +4,9 @@
module Discourse
class SingleSignOn
ACCESSORS = [:nonce, :name, :username, :email, :avatar_url, :avatar_force_update, :require_activation,
:about_me, :external_id, :return_sso_url, :admin, :moderator, :suppress_welcome_message].freeze
ACCESSORS = [:nonce, :name, :username, :email, :avatar_url, :avatar_force_update,
:require_activation, :about_me, :external_id, :return_sso_url, :admin, :moderator,
:suppress_welcome_message].freeze
FIXNUMS = [].freeze
BOOLS = [:avatar_force_update, :admin, :moderator, :require_activation,
:suppress_welcome_message].freeze
@@ -27,9 +28,12 @@ module Discourse
parsed = Rack::Utils.parse_query(payload)
if sso.sign(parsed["sso"]) != parsed["sig"]
diags = "\n\nsso: #{parsed['sso']}\n\nsig: #{parsed['sig']}\n\nexpected sig: #{sso.sign(parsed['sso'])}"
diags = "\n\nsso: #{parsed['sso']}\n\nsig: #{parsed['sig']}\n\n" \
"expected sig: #{sso.sign(parsed['sso'])}"
if parsed["sso"] =~ %r{[^a-zA-Z0-9=\r\n/+]}m
raise "The SSO field should be Base64 encoded, using only A-Z, a-z, 0-9, +, /, and = characters. Your input contains characters we don't understand as Base64, see http://en.wikipedia.org/wiki/Base64 #{diags}"
raise "The SSO field should be Base64 encoded, using only A-Z, a-z, 0-9, +, /, " \
"and = characters. Your input contains characters we don't understand as Base64, " \
"see http://en.wikipedia.org/wiki/Base64 #{diags}"
else
raise "Bad signature for payload #{diags}"
end

View File

@@ -18,7 +18,8 @@ module OpenFoodNetwork
)
AdjustmentMetadata.create! adjustment: adjustment, enterprise: enterprise_fee.enterprise,
fee_name: enterprise_fee.name, fee_type: enterprise_fee.fee_type, enterprise_role: role
fee_name: enterprise_fee.name, fee_type: enterprise_fee.fee_type,
enterprise_role: role
end
def line_item_adjustment_label

View File

@@ -35,8 +35,8 @@ module OpenFoodNetwork
def fees_by_type_for(variant)
per_item_enterprise_fee_applicators_for(variant).each_with_object({}) do |applicator, fees|
fees[applicator.enterprise_fee.fee_type.to_sym] ||= 0
fees[applicator.enterprise_fee.fee_type.to_sym] += calculate_fee_for variant,
applicator.enterprise_fee
fees[applicator.enterprise_fee.fee_type.to_sym] +=
calculate_fee_for variant, applicator.enterprise_fee
end.select { |_fee_type, amount| amount > 0 }
end

View File

@@ -15,7 +15,9 @@ module OpenFoodNetwork
issues << {
description: I18n.t('admin.enterprise_issues.has_no_shipping_methods',
enterprise: @enterprise.name),
link: "<a class='button fullwidth' href='#{spree_routes_helper.new_admin_shipping_method_path}'>#{I18n.t('admin.enterprise_issues.create_new')}</a>"
link: "<a class='button fullwidth' " \
"href='#{spree_routes_helper.new_admin_shipping_method_path}'>" \
"#{I18n.t('admin.enterprise_issues.create_new')}</a>"
}
end
@@ -23,7 +25,9 @@ module OpenFoodNetwork
issues << {
description: I18n.t('admin.enterprise_issues.has_no_payment_methods',
enterprise: @enterprise.name),
link: "<a class='button fullwidth' href='#{spree_routes_helper.new_admin_payment_method_path}'>#{I18n.t('admin.enterprise_issues.create_new')}</a>"
link: "<a class='button fullwidth' " \
"href='#{spree_routes_helper.new_admin_payment_method_path}'>" \
"#{I18n.t('admin.enterprise_issues.create_new')}</a>"
}
end
@@ -46,7 +50,8 @@ module OpenFoodNetwork
unless @enterprise.public?
warnings << {
description: I18n.t('admin.enterprise_issues.not_visible', enterprise: @enterprise.name),
link: "<a class='button fullwidth' href='#{edit_admin_enterprise_path(@enterprise)}'>#{I18n.t(:edit)}</a>"
link: "<a class='button fullwidth' " \
"href='#{edit_admin_enterprise_path(@enterprise)}'>#{I18n.t(:edit)}</a>"
}
end

View File

@@ -5,8 +5,8 @@ require 'open_food_network/order_cycle_permissions'
module OpenFoodNetwork
# There are two translator classes on the boundary between Angular and Rails: On the Angular side,
# there is the OrderCycle#dataForSubmit method, and on the Rails side is this class. I think data
# translation is more a responsibility of Angular, so I'd be inclined to refactor this class to move
# as much as possible (if not all) of its logic into Angular.
# translation is more a responsibility of Angular, so I'd be inclined to refactor this class to
# move as much as possible (if not all) of its logic into Angular.
class OrderCycleFormApplicator
# The applicator will only touch exchanges where a permitted enterprise is the participant
def initialize(order_cycle, spree_current_user)
@@ -132,7 +132,8 @@ module OpenFoodNetwork
def manages_coordinator?
return @manages_coordinator unless @manages_coordinator.nil?
@manages_coordinator = Enterprise.managed_by(@spree_current_user).include? @order_cycle.coordinator
@manages_coordinator =
Enterprise.managed_by(@spree_current_user).include? @order_cycle.coordinator
end
def editable_variant_ids_for_incoming_exchange_between(sender, _receiver)
@@ -156,13 +157,17 @@ module OpenFoodNetwork
exchange = find_exchange(sender.id, receiver.id, true)
requested_ids = variants_to_a(attrs[:variants]) # Only the ids the user has requested
existing_ids = exchange.present? ? exchange.variants.pluck(:id) : [] # The ids that already exist
editable_ids = editable_variant_ids_for_incoming_exchange_between(sender, receiver) # The ids we are allowed to add/remove
# The ids that already exist
existing_ids = exchange.present? ? exchange.variants.pluck(:id) : []
# The ids we are allowed to add/remove
editable_ids = editable_variant_ids_for_incoming_exchange_between(sender, receiver)
result = existing_ids
result |= (requested_ids & editable_ids) # add any requested & editable ids that are not yet in the exchange
result -= ((result & editable_ids) - requested_ids) # remove any editable ids that were not specifically mentioned in the request
# add any requested & editable ids that are not yet in the exchange
result |= (requested_ids & editable_ids)
# remove any editable ids that were not specifically mentioned in the request
result -= ((result & editable_ids) - requested_ids)
result
end
@@ -173,14 +178,18 @@ module OpenFoodNetwork
exchange = find_exchange(sender.id, receiver.id, false)
requested_ids = variants_to_a(attrs[:variants]) # Only the ids the user has requested
existing_ids = exchange.present? ? exchange.variants.pluck(:id) : [] # The ids that already exist
editable_ids = editable_variant_ids_for_outgoing_exchange_between(sender, receiver) # The ids we are allowed to add/remove
# The ids that already exist
existing_ids = exchange.present? ? exchange.variants.pluck(:id) : []
# The ids we are allowed to add/remove
editable_ids = editable_variant_ids_for_outgoing_exchange_between(sender, receiver)
result = existing_ids
result |= (requested_ids & editable_ids) # add any requested & editable ids that are not yet in the exchange
# add any requested & editable ids that are not yet in the exchange
result |= (requested_ids & editable_ids)
result -= (result - incoming_variant_ids) # remove any ids not in incoming exchanges
result -= ((result & editable_ids) - requested_ids) # remove any editable ids that were not specifically mentioned in the request
# remove any editable ids that were not specifically mentioned in the request
result -= ((result & editable_ids) - requested_ids)
result
end

View File

@@ -242,7 +242,8 @@ module OpenFoodNetwork
end
def active_outgoing_variants(hub)
@active_outgoing_variants ||= @order_cycle.exchanges.outgoing.where(receiver_id: hub).first&.variants || []
@active_outgoing_variants ||=
@order_cycle.exchanges.outgoing.where(receiver_id: hub).first&.variants || []
end
def user_manages_coordinator_or(enterprise)

View File

@@ -67,7 +67,8 @@ module OpenFoodNetwork
end
def scope_to_eligible_for_subscriptions_in_distributor
eligible_variants_scope = OrderManagement::Subscriptions::VariantsList.eligible_variants(distributor)
eligible_variants_scope =
OrderManagement::Subscriptions::VariantsList.eligible_variants(distributor)
@variants = @variants.merge(eligible_variants_scope)
scope_variants_to_distributor(@variants, distributor)
end

View File

@@ -6,7 +6,8 @@ module Reporting
def initialize(order_permissions, params, orders_relation = nil)
@order_permissions = order_permissions
@params = params
complete_not_canceled_visible_orders = CompleteVisibleOrders.new(order_permissions).query.not_state(:canceled)
complete_not_canceled_visible_orders =
CompleteVisibleOrders.new(order_permissions).query.not_state(:canceled)
@orders_relation = orders_relation || complete_not_canceled_visible_orders
end

View File

@@ -4,7 +4,8 @@ module Reporting
module Reports
module EnterpriseFeeSummary
module ReportData
class EnterpriseFeeTypeTotal < Reporting::Reports::EnterpriseFeeSummary::Reports::ReportData::Base
class EnterpriseFeeTypeTotal <
Reporting::Reports::EnterpriseFeeSummary::Reports::ReportData::Base
attr_accessor :fee_type, :enterprise_name, :fee_name, :customer_name, :fee_placement,
:fee_calculated_on_transfer_through_name, :tax_category_name, :total_amount

View File

@@ -16,7 +16,8 @@ module Spree
old_setter = instance_method(setter) if non_activerecord_attribute?(attribute)
define_method(setter) do |number|
if Spree::Config.enable_localized_number? && Spree::LocalizedNumber.valid_localizable_number?(number)
if Spree::Config.enable_localized_number? &&
Spree::LocalizedNumber.valid_localizable_number?(number)
number = Spree::LocalizedNumber.parse(number)
elsif Spree::Config.enable_localized_number?
@invalid_localized_number ||= []
@@ -54,16 +55,19 @@ module Spree
return nil if number.blank?
return number.to_d unless number.is_a?(String)
number = number.gsub(/[^\d.,-]/, '') # Replace all Currency Symbols, Letters and -- from the string
# Replace all Currency Symbols, Letters and -- from the string
number = number.gsub(/[^\d.,-]/, '')
add_trailing_zeros(number)
number = number.gsub(/[.,]/, '') # Replace all (.) and (,) so the string result becomes in "cents"
# Replace all (.) and (,) so the string result becomes in "cents"
number = number.gsub(/[.,]/, '')
number.to_d / 100 # Let to_decimal do the rest
end
def self.add_trailing_zeros(number)
# If string ends in a single digit (e.g. ,2), make it ,20 in order for the result to be in "cents"
# If string ends in a single digit (e.g. ,2), make it
# ,20 in order for the result to be in "cents"
number << "0" if number =~ /^.*[.,]\d{1}$/
# If does not end in ,00 / .00 then add trailing 00 to turn it into cents

View File

@@ -74,7 +74,8 @@ namespace :ofn do
def request_months
# Ask how many months back we want to search for
puts "This task will search order cycle edited within (n) months of today's date.\nPlease enter a value for (n), or hit ENTER to use the default of three (3) months."
puts "This task will search order cycle edited within (n) months of today's date.\n" \
"Please enter a value for (n), or hit ENTER to use the default of three (3) months."
input = check_default(STDIN.gets.chomp)
while !is_integer?(input)

View File

@@ -31,12 +31,20 @@ namespace :ofn do
def enterprise_header
['name', 'description', 'long_description', 'is_primary_producer', 'is_distributor',
'contact_name', 'phone', 'email', 'website', 'twitter', 'abn', 'acn', 'pickup_times', 'next_collection_at', 'distributor_info', 'visible', 'facebook', 'instagram', 'linkedin', 'address1', 'address2', 'city', 'zipcode', 'state', 'country']
'contact_name', 'phone', 'email', 'website', 'twitter', 'abn', 'acn', 'pickup_times',
'next_collection_at', 'distributor_info', 'visible', 'facebook', 'instagram', 'linkedin',
'address1', 'address2', 'city', 'zipcode', 'state', 'country']
end
def enterprise_row(enterprise)
[enterprise.name, enterprise.description, enterprise.long_description,
enterprise.is_primary_producer, enterprise.is_distributor, enterprise.contact_name, enterprise.phone, enterprise.email, enterprise.website, enterprise.twitter, enterprise.abn, enterprise.acn, enterprise.pickup_times, enterprise.next_collection_at, enterprise.distributor_info, enterprise.visible, enterprise.facebook, enterprise.instagram, enterprise.linkedin, enterprise.address.address1, enterprise.address.address2, enterprise.address.city, enterprise.address.zipcode, enterprise.address.state_name, enterprise.address.country&.name]
enterprise.is_primary_producer, enterprise.is_distributor, enterprise.contact_name,
enterprise.phone, enterprise.email, enterprise.website, enterprise.twitter, enterprise.abn,
enterprise.acn, enterprise.pickup_times, enterprise.next_collection_at,
enterprise.distributor_info, enterprise.visible, enterprise.facebook, enterprise.instagram,
enterprise.linkedin, enterprise.address.address1, enterprise.address.address2,
enterprise.address.city, enterprise.address.zipcode, enterprise.address.state_name,
enterprise.address.country&.name]
end
end
end

View File

@@ -6,7 +6,8 @@ namespace :ofn do
task :product_images, [:filename] => [:environment] do |_task, args|
COLUMNS = [:producer, :name, :image_url].freeze
puts "Warning: use only with trusted URLs. This script will download whatever it can, including local secrets, and expose the file as an image file."
puts "Warning: use only with trusted URLs. This script will download whatever it can, " \
"including local secrets, and expose the file as an image file."
raise "Filename required" if args[:filename].blank?

View File

@@ -47,7 +47,8 @@ describe Admin::BulkLineItemsController, type: :controller do
get :index, format: :json
end
it "retrieves a list of line_items with appropriate attributes, including line items with appropriate attributes" do
it "retrieves a list of line_items with appropriate attributes, " \
"including line items with appropriate attributes" do
keys = json_response['line_items'].first.keys.map(&:to_sym)
expect(line_item_attributes.all?{ |attr| keys.include? attr }).to eq(true)
end
@@ -99,23 +100,28 @@ describe Admin::BulkLineItemsController, type: :controller do
let(:order_cycle) { create(:simple_order_cycle, coordinator: coordinator) }
let!(:order1) {
FactoryBot.create(:order, order_cycle: order_cycle, state: 'complete',
completed_at: Time.zone.now, distributor: distributor1, billing_address: FactoryBot.create(:address) )
completed_at: Time.zone.now, distributor: distributor1,
billing_address: FactoryBot.create(:address) )
}
let!(:line_item1) {
FactoryBot.create(:line_item_with_shipment, order: order1,
product: FactoryBot.create(:product, supplier: supplier))
product: FactoryBot.create(:product,
supplier: supplier))
}
let!(:line_item2) {
FactoryBot.create(:line_item_with_shipment, order: order1,
product: FactoryBot.create(:product, supplier: supplier))
product: FactoryBot.create(:product,
supplier: supplier))
}
let!(:order2) {
FactoryBot.create(:order, order_cycle: order_cycle, state: 'complete',
completed_at: Time.zone.now, distributor: distributor2, billing_address: FactoryBot.create(:address) )
completed_at: Time.zone.now, distributor: distributor2,
billing_address: FactoryBot.create(:address) )
}
let!(:line_item3) {
FactoryBot.create(:line_item_with_shipment, order: order2,
product: FactoryBot.create(:product, supplier: supplier))
product: FactoryBot.create(:product,
supplier: supplier))
}
context "producer enterprise" do
@@ -188,11 +194,14 @@ describe Admin::BulkLineItemsController, type: :controller do
let(:order_cycle) { create(:simple_order_cycle, coordinator: coordinator) }
let!(:order1) {
FactoryBot.create(:order, order_cycle: order_cycle, state: 'complete',
completed_at: Time.zone.now, distributor: distributor1, billing_address: FactoryBot.create(:address) )
completed_at: Time.zone.now,
distributor: distributor1,
billing_address: FactoryBot.create(:address) )
}
let!(:line_item1) {
line_item1 = FactoryBot.create(:line_item_with_shipment, order: order1,
product: FactoryBot.create(:product, supplier: supplier))
line_item1 = FactoryBot.create(:line_item_with_shipment,
order: order1,
product: FactoryBot.create(:product, supplier: supplier))
# make sure shipment is available through db reloads of this line_item
line_item1.tap(&:save!)
}
@@ -294,11 +303,13 @@ describe Admin::BulkLineItemsController, type: :controller do
let(:order_cycle) { create(:simple_order_cycle, coordinator: coordinator) }
let!(:order1) {
FactoryBot.create(:order, order_cycle: order_cycle, state: 'complete',
completed_at: Time.zone.now, distributor: distributor1, billing_address: FactoryBot.create(:address) )
completed_at: Time.zone.now, distributor: distributor1,
billing_address: FactoryBot.create(:address) )
}
let!(:line_item1) {
FactoryBot.create(:line_item_with_shipment, order: order1,
product: FactoryBot.create(:product, supplier: supplier))
product: FactoryBot.create(:product,
supplier: supplier))
}
let(:params) { { id: line_item1.id, order_id: order1.number } }

View File

@@ -12,8 +12,8 @@ describe Admin::ColumnPreferencesController, type: :controller do
context "json" do
let!(:column_preference) {
ColumnPreference.create(user_id: user1.id, action_name: 'enterprises_index', column_name: "name",
visible: true)
ColumnPreference.create(user_id: user1.id, action_name: 'enterprises_index',
column_name: "name", visible: true)
}
let(:column_preference_params) {

View File

@@ -398,7 +398,8 @@ describe Admin::EnterprisesController, type: :controller do
it "is allowed" do
spree_post :register, id: enterprise, sells: 'none'
expect(response).to redirect_to spree.admin_dashboard_path
expect(flash[:success]).to eq "Congratulations! Registration for #{enterprise.name} is complete!"
expect(flash[:success])
.to eq "Congratulations! Registration for #{enterprise.name} is complete!"
expect(enterprise.reload.sells).to eq 'none'
end
end
@@ -420,7 +421,8 @@ describe Admin::EnterprisesController, type: :controller do
it "is allowed" do
spree_post :register, id: enterprise, sells: 'own'
expect(response).to redirect_to spree.admin_dashboard_path
expect(flash[:success]).to eq "Congratulations! Registration for #{enterprise.name} is complete!"
expect(flash[:success])
.to eq "Congratulations! Registration for #{enterprise.name} is complete!"
expect(enterprise.reload.sells).to eq 'own'
end
end
@@ -429,7 +431,8 @@ describe Admin::EnterprisesController, type: :controller do
it "is allowed" do
spree_post :register, id: enterprise, sells: 'any'
expect(response).to redirect_to spree.admin_dashboard_path
expect(flash[:success]).to eq "Congratulations! Registration for #{enterprise.name} is complete!"
expect(flash[:success])
.to eq "Congratulations! Registration for #{enterprise.name} is complete!"
expect(enterprise.reload.sells).to eq 'any'
end
end
@@ -457,7 +460,9 @@ describe Admin::EnterprisesController, type: :controller do
allow(controller).to receive_messages spree_current_user: new_owner
bulk_enterprise_params = { sets_enterprise_set: { collection_attributes: {
'0' => { id: profile_enterprise1.id, sells: 'any',
owner_id: new_owner.id }, '1' => { id: profile_enterprise2.id, sells: 'any', owner_id: new_owner.id }
owner_id: new_owner.id }, '1' => { id: profile_enterprise2.id,
sells: 'any',
owner_id: new_owner.id }
} } }
spree_put :bulk_update, bulk_enterprise_params
@@ -486,7 +491,9 @@ describe Admin::EnterprisesController, type: :controller do
allow(controller).to receive_messages spree_current_user: original_owner
bulk_enterprise_params = { sets_enterprise_set: { collection_attributes: {
'0' => { id: profile_enterprise1.id, sells: 'any',
owner_id: new_owner.id }, '1' => { id: profile_enterprise2.id, sells: 'any', owner_id: new_owner.id }
owner_id: new_owner.id }, '1' => { id: profile_enterprise2.id,
sells: 'any',
owner_id: new_owner.id }
} } }
spree_put :bulk_update, bulk_enterprise_params
@@ -506,7 +513,9 @@ describe Admin::EnterprisesController, type: :controller do
allow(controller).to receive_messages spree_current_user: admin_user
bulk_enterprise_params = { sets_enterprise_set: { collection_attributes: {
'0' => { id: profile_enterprise1.id, sells: 'any',
owner_id: new_owner.id }, '1' => { id: profile_enterprise2.id, sells: 'any', owner_id: new_owner.id }
owner_id: new_owner.id }, '1' => { id: profile_enterprise2.id,
sells: 'any',
owner_id: new_owner.id }
} } }
spree_put :bulk_update, bulk_enterprise_params
@@ -547,8 +556,8 @@ describe Admin::EnterprisesController, type: :controller do
context "when an order_cycle_id is provided in params" do
before { get :for_order_cycle, as: :json, params: { order_cycle_id: 1 } }
it "initializes permissions with the existing OrderCycle" do
expect(OpenFoodNetwork::OrderCyclePermissions).to have_received(:new).with(user,
"existing OrderCycle")
expect(OpenFoodNetwork::OrderCyclePermissions).to have_received(:new)
.with(user, "existing OrderCycle")
end
end
@@ -563,8 +572,8 @@ describe Admin::EnterprisesController, type: :controller do
context "when both an order cycle and a coordinator are provided in params" do
before { get :for_order_cycle, as: :json, params: { order_cycle_id: 1, coordinator_id: 1 } }
it "initializes permissions with the existing OrderCycle" do
expect(OpenFoodNetwork::OrderCyclePermissions).to have_received(:new).with(user,
"existing OrderCycle")
expect(OpenFoodNetwork::OrderCyclePermissions).to have_received(:new)
.with(user, "existing OrderCycle")
end
end
end
@@ -584,8 +593,8 @@ describe Admin::EnterprisesController, type: :controller do
end
it "uses permissions to determine which enterprises are visible and should be rendered" do
expect(controller).to receive(:render_as_json).with([visible_enterprise],
ams_prefix: 'basic', spree_current_user: user).and_call_original
expect(controller).to receive(:render_as_json)
.with([visible_enterprise], ams_prefix: 'basic', spree_current_user: user).and_call_original
get :visible, format: :json
end
end

View File

@@ -20,7 +20,8 @@ describe Admin::SchedulesController, type: :controller do
let(:params) { { format: :json } }
it "scopes @collection to schedules containing order_cycles coordinated by enterprises I manage" do
it "scopes @collection to schedules containing order_cycles " \
"coordinated by enterprises I manage" do
get :index, params: params
expect(assigns(:collection)).to eq [coordinated_schedule]
end
@@ -30,7 +31,8 @@ describe Admin::SchedulesController, type: :controller do
get :index, params: params
end
context "and there is a schedule of an OC coordinated by _another_ enterprise I manage and the first enterprise is given" do
context "and there is a schedule of an OC coordinated by _another_ enterprise " \
"I manage and the first enterprise is given" do
let!(:other_managed_coordinator) {
create(:distributor_enterprise, owner: managed_coordinator.owner)
}
@@ -42,7 +44,8 @@ describe Admin::SchedulesController, type: :controller do
}
let(:params) { { format: :json, enterprise_id: managed_coordinator.id } }
it "scopes @collection to schedules containing order_cycles coordinated by the first enterprise" do
it "scopes @collection to schedules containing order_cycles " \
"coordinated by the first enterprise" do
get :index, params: params
expect(assigns(:collection)).to eq [coordinated_schedule]
end
@@ -109,7 +112,8 @@ describe Admin::SchedulesController, type: :controller do
expect(assigns(:schedule)).to eq coordinated_schedule
# coordinated_order_cycle2 is added, uncoordinated_order_cycle is NOT removed
expect(coordinated_schedule.reload.order_cycles).to include coordinated_order_cycle2,
uncoordinated_order_cycle, uncoordinated_order_cycle3
uncoordinated_order_cycle,
uncoordinated_order_cycle3
# coordinated_order_cycle is removed, uncoordinated_order_cycle2 is NOT added
expect(coordinated_schedule.reload.order_cycles).to_not include coordinated_order_cycle,
uncoordinated_order_cycle2
@@ -121,7 +125,8 @@ describe Admin::SchedulesController, type: :controller do
expect(syncer_mock).to receive(:sync!).exactly(2).times
spree_put :update, format: :json, id: coordinated_schedule.id,
order_cycle_ids: [coordinated_order_cycle.id, coordinated_order_cycle2.id]
order_cycle_ids: [coordinated_order_cycle.id,
coordinated_order_cycle2.id]
spree_put :update, format: :json, id: coordinated_schedule.id,
order_cycle_ids: [coordinated_order_cycle.id]
spree_put :update, format: :json, id: coordinated_schedule.id,
@@ -131,7 +136,8 @@ describe Admin::SchedulesController, type: :controller do
context "where I don't manage any of the schedule's coordinators" do
before do
allow(controller).to receive_messages spree_current_user: uncoordinated_order_cycle2.coordinator.owner
allow(controller)
.to receive_messages spree_current_user: uncoordinated_order_cycle2.coordinator.owner
end
it "prevents me from updating the schedule" do
@@ -253,7 +259,9 @@ describe Admin::SchedulesController, type: :controller do
it "returns an error message and prevents me from deleting the schedule" do
expect { spree_delete :destroy, params }.to_not change(Schedule, :count)
json_response = JSON.parse(response.body)
expect(json_response["errors"]).to include 'This schedule cannot be deleted because it has associated subscriptions'
expect(json_response["errors"])
.to include 'This schedule cannot be deleted ' \
'because it has associated subscriptions'
end
end
end

View File

@@ -15,9 +15,13 @@ describe Admin::StripeAccountsController, type: :controller do
end
it "redirects to Stripe Authorization url constructed OAuth" do
get :connect, params: { enterprise_id: 1 } # A deterministic id results in a deterministic state JWT token
# A deterministic id results in a deterministic state JWT token
get :connect, params: { enterprise_id: 1 }
expect(response).to redirect_to("https://connect.stripe.com/oauth/authorize?state=eyJhbGciOiJIUzI1NiJ9.eyJlbnRlcnByaXNlX2lkIjoiMSJ9.jSSFGn0bLhwuiQYK5ORmHWW7aay1l030bcfGwn1JbFg&scope=read_write&client_id=some_id&response_type=code")
expect(response).to redirect_to("https://connect.stripe.com/oauth/authorize?" \
"state=eyJhbGciOiJIUzI1NiJ9.eyJlbnRlcnByaXNlX2lkIjoiMSJ9" \
".jSSFGn0bLhwuiQYK5ORmHWW7aay1l030bcfGwn1JbFg&" \
"scope=read_write&client_id=some_id&response_type=code")
end
end
@@ -150,8 +154,8 @@ describe Admin::StripeAccountsController, type: :controller do
end
before do
stub_request(:get,
"https://api.stripe.com/v1/accounts/acc_123").to_return(body: JSON.generate(stripe_account_mock))
stub_request(:get, "https://api.stripe.com/v1/accounts/acc_123")
.to_return(body: JSON.generate(stripe_account_mock))
end
it "returns with a status of 'connected'" do