Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fixed fourth review findings in the typed preferences contract

Damian Legawiec6c6d6ee7a317
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb
index e353bac64f..2f1644191e 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb
@@ -44,9 +44,9 @@ module Spree
attrs, preferences, calculator = extract_subclass_params(permitted)
@resource = build_subclassed_resource(klass, attrs)
+ authorize_resource!(@resource, :create)
apply_preferences(@resource, preferences) if preferences.present?
apply_calculator(@resource, calculator) if calculator.present?
- authorize_resource!(@resource, :create)
if @resource.save
render json: serialize_resource(@resource), status: :created
@@ -62,13 +62,10 @@ module Spree
permitted = permitted_params_for(@resource.class)
attrs, preferences, calculator = extract_subclass_params(permitted)
- # A new calculator replaces the stored one as soon as it is
- # assigned, so the whole update rolls back if anything is refused.
- saved = model_class.transaction do
+ saved = save_atomically do
@resource.assign_attributes(attrs)
apply_preferences(@resource, preferences) if preferences.present?
apply_calculator(@resource, calculator) if calculator.present?
- @resource.save || raise(ActiveRecord::Rollback)
end
if saved
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
index 3c06b5820c..7c68c597f2 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
@@ -104,6 +104,7 @@ module Spree
rescue_from ActionController::ParameterMissing, with: :handle_parameter_missing
rescue_from ActiveRecord::RecordInvalid, with: :handle_record_invalid
rescue_from Spree::Preferences::InvalidPreferences, with: :handle_invalid_preferences
+ rescue_from ActiveRecord::RecordNotSaved, with: :handle_record_not_saved
rescue_from ArgumentError, with: :handle_argument_error
rescue_from ActionDispatch::Http::Parameters::ParseError, with: :handle_parse_error
end
@@ -258,6 +259,15 @@ module Spree
)
end
+ # Replacing a has_one on a saved record saves the new one at once, and
+ # raises when that one fails its own validations.
+ def handle_record_not_saved(exception)
+ errors = exception.record&.errors
+ return render_validation_error(errors) if errors.present?
+
+ render_error(code: ERROR_CODES[:validation_error], message: exception.message, status: :unprocessable_content)
+ end
+
def handle_argument_error(exception)
Rails.error.report(exception, context: error_context, source: 'spree.api.v3')
render_error(
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb
index 02d03caf75..5276aa703f 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb
@@ -94,12 +94,9 @@ module Spree
end
def update
- # A new calculator replaces the stored one as soon as it is
- # assigned, so the whole update rolls back if anything is refused.
- saved = model_class.transaction do
+ saved = save_atomically do
@resource.assign_attributes(assignable_params)
@resource.assign_calculator_attributes(permitted_params[:calculator])
- @resource.save || raise(ActiveRecord::Rollback)
end
if saved
diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
index 9bb723ebf5..0644f93caf 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -96,6 +96,18 @@ module Spree
protected
+ # Runs the block's assignments and saves the resource as one unit:
+ # assigning a has_one (a calculator, say) on a saved record writes it
+ # at once, so anything refused afterwards rolls that back too.
+ #
+ # @return [Boolean] whether the resource was saved
+ def save_atomically
+ model_class.transaction do
+ yield
+ @resource.save || raise(ActiveRecord::Rollback)
+ end || false
+ end
+
def authenticate_request!
raise NotImplementedError, "#{self.class} must implement authenticate_request!"
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/delivery_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/delivery_methods_controller.rb
index 588f7848c6..4ad234e130 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/delivery_methods_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/delivery_methods_controller.rb
@@ -78,13 +78,10 @@ module Spree
end
def update
- # A new calculator replaces the stored one as soon as it is
- # assigned, so the whole update rolls back if anything is refused.
- saved = model_class.transaction do
+ saved = save_atomically do
@resource.assign_attributes(assignable_params)
rederive_origin_group(@resource)
@resource.assign_calculator_attributes(permitted_params[:calculator])
- @resource.save || raise(ActiveRecord::Rollback)
end
if saved
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/delivery_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/delivery_methods_controller_spec.rb
index 7aa9be8953..ce912790aa 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/delivery_methods_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/delivery_methods_controller_spec.rb
@@ -120,7 +120,7 @@ RSpec.describe Spree::Api::V3::Seller::DeliveryMethodsController, type: :control
post :create, params: valid_params.merge(calculator: { type: 'NoSuchCalculator' }), as: :json
expect(response).to have_http_status(:unprocessable_content)
- expect(json_response['error']['details']).to have_key('calculator')
+ expect(json_response['error']).to include('code' => 'invalid_preferences', 'details' => have_key('/calculator/type'))
end
it 'refuses to share the seller’s own method with the marketplace' do
diff --git a/spree/core/app/models/concerns/spree/calculated_adjustments.rb b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
index 27638abfc9..ada0f5983a 100644
--- a/spree/core/app/models/concerns/spree/calculated_adjustments.rb
+++ b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
@@ -31,14 +31,14 @@ module Spree
end
# API v3 writer for the `calculator: { type:, preferences: {} }`
- # payload. A type the registry does not list raises a validation error
- # on `calculator`; preferences are checked against the calculator's
- # schema and written through its typed writers.
+ # payload. A type the registry does not list is refused like a setting
+ # that does not match (`/calculator/type`); preferences are checked
+ # against the calculator's schema and written through its typed writers.
#
# @param attrs [Hash, ActionController::Parameters, nil]
# @param pointer [String] where the calculator sits in the request
- # @raise [ActiveRecord::RecordInvalid] for a calculator type the registry does not list
- # @raise [Spree::Preferences::InvalidPreferences] for preferences that do not match its schema
+ # @raise [Spree::Preferences::InvalidPreferences] for a type the registry does not list, or
+ # preferences that do not match its schema
# @return [void]
def assign_calculator_attributes(attrs, pointer: '/calculator')
return if attrs.nil?
@@ -49,9 +49,9 @@ module Spree
if type.present? && calculator&.class&.api_type != type
klass = registered_calculator_class(type)
unless klass
- # Raised rather than only recorded: saving would clear the error.
- errors.add(:calculator, :invalid)
- raise ActiveRecord::RecordInvalid, self
+ raise Spree::Preferences::InvalidPreferences.new(
+ [{ pointer: '/type', message: I18n.t('spree.errors.messages.unknown_calculator_type', type: type) }], prefix: pointer
+ )
end
target = klass.new
diff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rb
index 315a69f1aa..7c60926ef2 100644
--- a/spree/core/app/models/concerns/spree/preference_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema.rb
@@ -80,8 +80,8 @@ module Spree
def preference_failures(values)
# The published schema plus deprecated preferences, which a write
# still accepts until their removal. Memoized like the published one.
- schemer = @preference_schemer || JSONSchemer.schema(Spree::PreferenceSchema::JsonSchema.for(self, writable: true))
- @preference_schemer = schemer if @preference_schema
+ schemer = @preference_schemer || JSONSchemer.schema(Spree::PreferenceSchema::JsonSchema.writable(self))
+ @preference_schemer ||= schemer if @preference_schema
schemer.validate(values).map do |error|
{ pointer: error['data_pointer'], message: error['error'] }
end
diff --git a/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb b/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb
index 918fe42a65..3640230fef 100644
--- a/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb
@@ -19,24 +19,30 @@ module Spree
}.freeze
# @param klass [Class] a class including {Spree::PreferenceSchema}
- # @param writable [Boolean] also list deprecated preferences, which a
- # write still accepts until their removal but no read returns
# @return [Hash] a JSON Schema object (string keys)
- def self.for(klass, writable: false)
+ def self.for(klass)
fields = klass.preference_schema
definitions = klass.preference_definitions
properties = fields.to_h do |field|
[field[:key].to_s, property_schema(definitions.fetch(field[:key]), default: field[:default])]
end
- definitions.each do |name, definition|
- next unless writable && definition[:deprecated] && !definition[:internal]
-
- properties[name.to_s] = property_schema(definition).merge('deprecated' => true)
- end
{ 'type' => 'object', 'properties' => properties, 'additionalProperties' => false }
end
+ # The published schema plus the deprecated preferences, which a write
+ # still accepts until their removal although no read returns them.
+ #
+ # @param klass [Class]
+ # @return [Hash]
+ def self.writable(klass)
+ deprecated = klass.preference_definitions.filter_map do |name, definition|
+ [name.to_s, property_schema(definition)] if definition[:deprecated] && !definition[:internal]
+ end
+ schema = klass.preference_json_schema
+ schema.merge('properties' => schema['properties'].merge(deprecated.to_h))
+ end
+
# The schema of one declared preference.
#
# @param definition [Hash] an entry of `preference_definitions`
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index a6366ff99e..4106b26001 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -896,6 +896,7 @@ en:
stock_level_immutable: cannot be changed after the hold is taken — release the hold and take it again
store_association_can_not_be_changed: The store association can not be changed
store_is_already_set: Store is already set
+ unknown_calculator_type: "%{type} is not a calculator offered here"
unknown_custom_field_type: 'is not a known custom field type (expected one of: %{types})'
unknown_scopes: 'contains unknown scopes: %{scopes}'
unregistered_actor: is not a registered actor class
diff --git a/spree/core/lib/spree/core/preferences/preferable.rb b/spree/core/lib/spree/core/preferences/preferable.rb
index 6869671827..2728263d63 100644
--- a/spree/core/lib/spree/core/preferences/preferable.rb
+++ b/spree/core/lib/spree/core/preferences/preferable.rb
@@ -196,9 +196,8 @@ module Spree::Preferences::Preferable
# @return [Object]
def wire_preference_value(value, definition)
return BigDecimal(value.to_s).as_json if definition[:type] == :decimal && value.is_a?(Numeric)
- if %i[integer boolean].include?(definition[:type]) && value.is_a?(String)
- return convert_preference_value(value, definition[:type], nullable: definition[:nullable])
- end
+ return cast_preference_item(value, :integer) if definition[:type] == :integer && value.is_a?(String)
+ return convert_preference_value(value, :boolean, nullable: definition[:nullable]) if definition[:type] == :boolean && value.is_a?(String)
return value if value.nil? || (definition[:type] == :array && !value.is_a?(Array))
cast_preference_contents(value, definition)
diff --git a/spree/core/spec/models/spree/promotion_spec.rb b/spree/core/spec/models/spree/promotion_spec.rb
index 2704c14ab6..6203354eca 100644
--- a/spree/core/spec/models/spree/promotion_spec.rb
+++ b/spree/core/spec/models/spree/promotion_spec.rb
@@ -1128,7 +1128,7 @@ describe Spree::Promotion, type: :model do
it 'refuses a calculator type the action does not offer' do
expect {
promotion.actions = [{ type: 'create_adjustment', calculator: { type: 'not_a_calculator' } }]
- }.to raise_error(ActiveRecord::RecordInvalid, /Calculator/)
+ }.to raise_error(Spree::Preferences::InvalidPreferences, %r{/actions/0/calculator/type})
end
it 'builds a FreeShipping action without a calculator' do