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 second review findings in the typed preferences contract

Damian Legawiec51d66b9bb67e
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index 810cbe4f4a..2c2a77e569 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -549,7 +549,9 @@ Settings no longer reach the Admin and Seller APIs in the shape of Ruby's prefer
**Id lists read as prefixed ids.** Preferences listing records, such as a rule's `channel_ids` or `customer_group_ids`, now return prefixed ids rather than database ids, the same form a write accepts.
-**Delivery methods nest their calculator.** `calculator_type` and `calculator_preferences` are replaced by `calculator: { type, preferences }` on read and write, the shape promotion actions already use.
+**Delivery methods nest their calculator.** `calculator_type` and `calculator_preferences` are replaced by `calculator: { type, preferences }` on read and write, the shape promotion actions already use. Writes still accept the old two parameters until Spree 6.1, with a deprecation warning.
+
+A preference marked deprecated, such as a flat rate calculator's `minimum_item_total`, is still accepted on write until its removal, with its deprecation warning, but is not read back.
**For extension authors:** declare every preference's full type (`of:` on arrays, `keys:` and `values:` on hashes, `money: true`, `choices:`, `format:`). An incomplete declaration still works in 6.0 with a deprecation warning, and its schema accepts any value. Replace `normalize_id_preference` with `preference :ids, :array, of: :id, model:, scope:`, and `in:` with `choices:`. See [Model preferences](/developer/customization/model-preferences#declaring-the-full-type).
diff --git a/docs/plans/6.0-typed-preferences.md b/docs/plans/6.0-typed-preferences.md
index 473c79c41f..c5476ab906 100644
--- a/docs/plans/6.0-typed-preferences.md
+++ b/docs/plans/6.0-typed-preferences.md
@@ -59,6 +59,10 @@ Preferences reach the API in two ways, and both expose the Ruby preferences DSL
- **An id that is well formed but outside the store, or missing, is a 422 `invalid_preferences`,** with the pointer of the list, rather than a 404.
- **`normalize_params` leaves `preferences` alone.** It decoded every `*_ids` value inside nested hashes, which would have turned valid prefixed ids into integers before the schema saw them.
- **Old `preferred_*` keys are still accepted on write for one release** (found in review), with a deprecation warning, on the store, channel and import endpoints; responses use only the plain names. Without it a 5.x client's change was silently dropped with a 200. `preferred_auto_capture` and `preferred_auto_capture_on_dispatch` stay accepted until 6.1, as already promised.
+- **Deprecated preferences stay writable until their removal** (found in review). They are in the schema with `deprecated: true`, so a write is accepted with the existing deprecation warning; forms and reads leave them out.
+- **The old delivery-method calculator parameters are bridged too** (found in review): `calculator_type` and `calculator_preferences` are still accepted on write until 6.1, with a deprecation warning.
+- **An id list declared without `of:` still has its prefixed ids decoded in 6.0,** as the API did for every `*_ids` key before, so an extension that has not completed its declarations keeps working until 6.1.
+- **A calculator is attached only after its settings are accepted** (found in review). On a saved delivery method, assigning a new calculator replaces the stored one at once, so a refused update used to leave a free rate behind.
- **`/payment_methods/types` lists every provider, with `installed`.** An installed provider's edit form reads its schema from that list now that rows no longer carry one, so the list may not leave it out; pickers filter on `installed`. Reading it needs read access, not create.
- **A failure inside a nested payload names its row:** `/rules/1/preferences/channel_ids/0`, `/actions/0/calculator/preferences/amount`, `/calculator/preferences/amount`.
- **Values stored before the declarations were typed read back in the declared form,** so a delivery method saved with numeric `amounts` can be re-saved unchanged.
diff --git a/packages/dashboard-core/src/components/preferences-form.tsx b/packages/dashboard-core/src/components/preferences-form.tsx
index a57e6b1040..f448c6ca0e 100644
--- a/packages/dashboard-core/src/components/preferences-form.tsx
+++ b/packages/dashboard-core/src/components/preferences-form.tsx
@@ -94,15 +94,18 @@ function fieldType(property: PreferencePropertySchema): string {
export function preferenceFields(
schema: PreferenceSchema | null | undefined,
): PreferenceFieldDef[] {
- return Object.entries(schema?.properties ?? {}).map(([key, property]) => ({
- key,
- type: fieldType(property),
- format: property.format ?? property.items?.format,
- default: property.default ?? null,
- choices: property.enum?.filter((choice): choice is string => typeof choice === 'string'),
- nullable: Array.isArray(property.type) && property.type.includes('null'),
- schema: property,
- }))
+ // A deprecated setting is still accepted on write, but no form offers it.
+ return Object.entries(schema?.properties ?? {})
+ .filter(([, property]) => !property.deprecated)
+ .map(([key, property]) => ({
+ key,
+ type: fieldType(property),
+ format: property.format ?? property.items?.format,
+ default: property.default ?? null,
+ choices: property.enum?.filter((choice): choice is string => typeof choice === 'string'),
+ nullable: Array.isArray(property.type) && property.type.includes('null'),
+ schema: property,
+ }))
}
/**
diff --git a/packages/sdk-core/src/types.ts b/packages/sdk-core/src/types.ts
index 38eff7dfd9..aef101082d 100644
--- a/packages/sdk-core/src/types.ts
+++ b/packages/sdk-core/src/types.ts
@@ -144,6 +144,8 @@ export interface PreferencePropertySchema {
'x-spree-prefix'?: string
/** A longer text, best edited in a multi-line field. */
'x-spree-widget'?: 'textarea'
+ /** Still accepted on write until its removal, but never read back; don't offer it. */
+ deprecated?: boolean
}
/**
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/legacy_preference_params.rb b/spree/api/app/controllers/concerns/spree/api/v3/legacy_preference_params.rb
index 4d044a35b1..fc81339751 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/legacy_preference_params.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/legacy_preference_params.rb
@@ -1,10 +1,12 @@
module Spree
module Api
module V3
- # Accepts a setting under its pre-6.0 `preferred_<name>` key for one
- # release, with a deprecation warning, so a client written for 5.x keeps
- # saving instead of having its change silently dropped. Responses use
- # only the plain name. Removed in Spree 6.1.
+ # Accepts the pre-6.0 shapes of a write for one release, with a
+ # deprecation warning, so a client written for 5.x keeps saving instead
+ # of having its change silently dropped: a setting under its
+ # `preferred_<name>` key, and a calculator as `calculator_type` plus
+ # `calculator_preferences`. Responses use only the new shapes. Removed
+ # in Spree 6.1.
module LegacyPreferenceParams
extend ActiveSupport::Concern
@@ -13,6 +15,10 @@ module Spree
def accepts_legacy_preference_params(model)
before_action(if: -> { request.post? || request.patch? || request.put? }) { translate_legacy_preference_params(model) }
end
+
+ def accepts_legacy_calculator_params
+ before_action(if: -> { request.post? || request.patch? || request.put? }) { translate_legacy_calculator_params }
+ end
end
private
@@ -26,6 +32,16 @@ module Spree
params[name] = params.delete(key)
end
end
+
+ def translate_legacy_calculator_params
+ return if params.key?(:calculator) || !(params.key?(:calculator_type) || params.key?(:calculator_preferences))
+
+ Spree::Deprecation.warn(
+ 'The `calculator_type` and `calculator_preferences` parameters are deprecated and will be removed in Spree 6.1. ' \
+ 'Send `calculator: { type, preferences }` instead.'
+ )
+ params[:calculator] = { type: params.delete(:calculator_type), preferences: params.delete(:calculator_preferences) }.compact
+ end
end
end
end
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 25d4bca70f..4b8b7e43a1 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
@@ -3,6 +3,10 @@ module Spree
module V3
module Admin
class DeliveryMethodsController < ResourceController
+ include Spree::Api::V3::LegacyPreferenceParams
+
+ accepts_legacy_calculator_params
+
scoped_resource :delivery_methods
# GET /api/v3/admin/delivery_methods/calculators
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 e621062774..f55d9a741e 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
@@ -17,6 +17,10 @@ module Spree
# `Spree::DeliveryMethod` validates and why neither provider is
# writable here.
class DeliveryMethodsController < Seller::ResourceController
+ include Spree::Api::V3::LegacyPreferenceParams
+
+ accepts_legacy_calculator_params
+
scoped_resource :delivery_methods
# GET /api/v3/seller/delivery_methods/calculators
diff --git a/spree/api/lib/spree/api/preference_types.rb b/spree/api/lib/spree/api/preference_types.rb
index f85acdb646..b93554a463 100644
--- a/spree/api/lib/spree/api/preference_types.rb
+++ b/spree/api/lib/spree/api/preference_types.rb
@@ -63,7 +63,8 @@ module Spree
label = family.titleize.downcase
parts = members.map do |type, schema|
name = PreferenceFamilies.member_name(family, type)
- properties = schema['properties']
+ # Deprecated settings are still accepted on write but never read back.
+ properties = schema['properties'].reject { |_key, property| property['deprecated'] }
next "/** Settings of the `#{type}` #{label}: none. */\nexport type #{name} = Record<string, never>\n" if properties.empty?
fields = properties.map { |key, property| "#{field_comment(property)} #{key}: #{ts_type(property)}\n" }.join
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
index a4ade7e4be..3971eef92b 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
@@ -235,6 +235,28 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
expect(delivery_method.calculator.preferred_amount).to eq(99)
end
+ it 'keeps the current calculator when the new one\'s settings are refused' do
+ calculator = delivery_method.calculator
+
+ patch :update, params: {
+ id: delivery_method.prefixed_id,
+ calculator: { type: 'flexi_rate', preferences: { first_item: 5 } }
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']).to have_key('/calculator/preferences/first_item')
+ expect(delivery_method.reload.calculator).to eq(calculator)
+ end
+
+ it 'still accepts the pre-6.0 calculator parameters for one release' do
+ expect(Spree::Deprecation).to receive(:warn).with(/`calculator_type` and `calculator_preferences` parameters are deprecated/)
+
+ patch :update, params: { id: delivery_method.prefixed_id, calculator_preferences: { amount: '42' } }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(delivery_method.reload.calculator.preferred_amount).to eq(42)
+ end
+
it 'stores per-currency amounts' do
patch :update, params: {
id: delivery_method.prefixed_id,
diff --git a/spree/core/app/models/concerns/spree/calculated_adjustments.rb b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
index 668b30f05b..55961a2cae 100644
--- a/spree/core/app/models/concerns/spree/calculated_adjustments.rb
+++ b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
@@ -26,8 +26,7 @@ module Spree
def calculator_type=(calculator_type)
return if calculator_type.blank?
- registry = self.class.respond_to?(:calculators) ? self.class.calculators : []
- klass = registry.find { |k| k.api_type == calculator_type.to_s }
+ klass = registered_calculator_class(calculator_type)
self.calculator = klass.new if klass && !calculator.instance_of?(klass)
end
@@ -44,26 +43,37 @@ module Spree
attrs = attrs.to_h.with_indifferent_access
type = attrs[:type].to_s
+ target = calculator
if type.present? && calculator&.class&.api_type != type
- registry = self.class.respond_to?(:calculators) ? self.class.calculators : []
- registered = registry.find { |klass| klass.api_type == type }
- return errors.add(:calculator, :invalid) unless registered
+ klass = registered_calculator_class(type)
+ return errors.add(:calculator, :invalid) unless klass
+
+ target = klass.new
+ end
- # Resolved from the registry entry's own name, never the request's:
- # in development the registry can hold a class from an earlier
- # reload, whose instances fail the association's type check.
- self.calculator = registered.to_s.constantize.new
+ if attrs[:preferences].present?
+ # Preferences sent without a type land on the default calculator
+ # rather than on nothing, for a model that has one.
+ target ||= default_calculator if respond_to?(:default_calculator, true)
+ target&.assign_preferences(attrs[:preferences], pointer: "#{pointer}/preferences")
end
- return if attrs[:preferences].blank?
- # Preferences sent without a type land on the default calculator
- # rather than on nothing, where the model builds one.
- ensure_calculator if respond_to?(:ensure_calculator, true)
- calculator&.assign_preferences(attrs[:preferences], pointer: "#{pointer}/preferences")
+ # Attached only once its settings are accepted: on a saved owner,
+ # assigning a has_one replaces the stored calculator immediately.
+ self.calculator = target unless target.equal?(calculator)
end
private
+ # The registered calculator for an API shorthand, resolved from the
+ # registry entry's own name: nothing user-supplied reaches
+ # `constantize`, and in development the registry can hold a class from
+ # an earlier reload whose instances fail the association's type check.
+ def registered_calculator_class(type)
+ registry = self.class.respond_to?(:calculators) ? self.class.calculators : []
+ registry.find { |klass| klass.api_type == type.to_s }&.to_s&.constantize
+ end
+
def self.model_name_without_spree_namespace
to_s.tableize.tr('/', '_').sub('spree_', '')
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 68a0219623..3eb30d2160 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
@@ -26,6 +26,14 @@ module Spree
properties = fields.to_h do |field|
[field[:key].to_s, property_schema(definitions.fetch(field[:key]), default: field[:default])]
end
+ # A deprecated preference is still written until its removal, so it
+ # stays in the schema, marked, though no form offers it and no read
+ # returns it.
+ definitions.each do |name, definition|
+ next unless definition[:deprecated] && !definition[:internal]
+
+ properties[name.to_s] = property_schema(definition).merge('deprecated' => true)
+ end
{ 'type' => 'object', 'properties' => properties, 'additionalProperties' => false }
end
diff --git a/spree/core/app/models/concerns/spree/typed_associations.rb b/spree/core/app/models/concerns/spree/typed_associations.rb
index dc94c832ca..edb8402dda 100644
--- a/spree/core/app/models/concerns/spree/typed_associations.rb
+++ b/spree/core/app/models/concerns/spree/typed_associations.rb
@@ -82,6 +82,8 @@ module Spree
record.assign_preferences(preferences, pointer: "#{pointer}/preferences") if preferences
if calculator.present? && record.respond_to?(:assign_calculator_attributes)
record.assign_calculator_attributes(calculator, pointer: "#{pointer}/calculator")
+ # Saving runs validation, which would clear an unknown-type error.
+ raise ActiveRecord::RecordInvalid, record if record.errors.any?
end
# Always save — `record.changed?` doesn't reflect preferences
diff --git a/spree/core/app/models/spree/delivery_method.rb b/spree/core/app/models/spree/delivery_method.rb
index f4eaa8dfa2..29a5a21099 100644
--- a/spree/core/app/models/spree/delivery_method.rb
+++ b/spree/core/app/models/spree/delivery_method.rb
@@ -227,7 +227,11 @@ module Spree
end
def ensure_calculator
- self.calculator ||= Spree::Calculator::Shipping::FlatRate.new(preferred_amount: 0)
+ self.calculator ||= default_calculator
+ end
+
+ def default_calculator
+ Spree::Calculator::Shipping::FlatRate.new(preferred_amount: 0)
end
def assign_default_delivery_profile
diff --git a/spree/core/lib/spree/core/preferences/preferable.rb b/spree/core/lib/spree/core/preferences/preferable.rb
index 859f56e43f..79df977fa3 100644
--- a/spree/core/lib/spree/core/preferences/preferable.rb
+++ b/spree/core/lib/spree/core/preferences/preferable.rb
@@ -187,14 +187,16 @@ module Spree::Preferences::Preferable
# A stored value in the form the schema describes. Rows written before the
# declarations were typed can hold a number where an exact decimal string
- # is declared (an `amounts` hash, a decimal default from YAML); read back
- # as they are, a client sending them unchanged would be refused.
+ # is declared (an `amounts` hash, a decimal default from YAML), or a string
+ # where a number or boolean is; read back as they are, a client sending
+ # them unchanged would be refused.
#
# @param value [Object] the stored value
# @param definition [Hash] its preference definition
# @return [Object]
def wire_preference_value(value, definition)
return BigDecimal(value.to_s).as_json if definition[:type] == :decimal && value.is_a?(Numeric)
+ return cast_preference_item(value, definition[:type]) if %i[integer boolean].include?(definition[:type]) && value.is_a?(String)
return value if value.nil? || (definition[:type] == :array && !value.is_a?(Array))
cast_preference_contents(value, definition)
@@ -240,6 +242,12 @@ module Spree::Preferences::Preferable
# `(value, owner = nil)` shapes.
value = parse_on_set.arity.abs > 1 ? parse_on_set.call(value, self) : parse_on_set.call(value)
end
+ # Spree 6.0 bridge, removed with incomplete declarations in 6.1: an id list
+ # an extension declared without `of: :id` still has its prefixed ids
+ # decoded, as the API did for every `*_ids` key before.
+ if definition[:type] == :array && definition[:of].nil? && name.to_s.end_with?('_ids')
+ value = Array.wrap(value).map { |id| Spree::PrefixedId.prefixed_id?(id) ? Spree::PrefixedId.decode_prefixed_id(id) : id }
+ end
value = convert_preference_value(value, definition[:type], nullable: definition[:nullable])
value = cast_preference_contents(value, definition)
# Decimals and times are kept in the string form JSON stores, so a record
diff --git a/spree/core/spec/models/spree/preference_schema/json_schema_spec.rb b/spree/core/spec/models/spree/preference_schema/json_schema_spec.rb
index 872adc2ee0..fc1eea55bf 100644
--- a/spree/core/spec/models/spree/preference_schema/json_schema_spec.rb
+++ b/spree/core/spec/models/spree/preference_schema/json_schema_spec.rb
@@ -50,6 +50,14 @@ describe Spree::PreferenceSchema::JsonSchema do
expect(secret).not_to have_key('default')
end
+ it 'keeps a deprecated preference writable until its removal, marked deprecated' do
+ expect(property(Spree::Calculator::Shipping::FlatRate, :minimum_item_total)).to include('deprecated' => true)
+
+ calculator = Spree::Calculator::Shipping::FlatRate.new
+ Spree::Deprecation.silence { calculator.assign_preferences({ 'minimum_item_total' => '10' }) }
+ expect(calculator.preferred_minimum_item_total).to eq(10)
+ end
+
it 'leaves out internal preferences' do
expect(Spree::Store.preference_json_schema['properties']).not_to have_key('install_id')
end
diff --git a/spree/core/spec/models/spree/preferences/preferable_spec.rb b/spree/core/spec/models/spree/preferences/preferable_spec.rb
index 8c2f169594..c74cf48ce9 100644
--- a/spree/core/spec/models/spree/preferences/preferable_spec.rb
+++ b/spree/core/spec/models/spree/preferences/preferable_spec.rb
@@ -516,6 +516,19 @@ describe Spree::Preferences::Preferable, type: :model do
end
end
+ it 'still decodes prefixed ids in an id list declared without `of:`, for one release' do
+ Spree::Deprecation.silence { preferable_class.preference :warehouse_ids, :array, default: [] }
+
+ record.set_preference(:warehouse_ids, [channel.prefixed_id])
+
+ expect(record.preferences[:warehouse_ids]).to eq([channel.id])
+ end
+
+ it 'reads back an integer or boolean stored as a string by older code as its type' do
+ expect(record.wire_preference_value('5', type: :integer)).to eq(5)
+ expect(record.wire_preference_value('true', type: :boolean)).to be(true)
+ end
+
it 'warns about a declaration that does not state its full type' do
expect(Spree::Deprecation).to receive(:warn).with(/needs `of:`/)
preferable_class.preference :untyped_list, :array, default: []
diff --git a/spree/core/spec/models/spree/promotion_spec.rb b/spree/core/spec/models/spree/promotion_spec.rb
index 1569c9d842..2704c14ab6 100644
--- a/spree/core/spec/models/spree/promotion_spec.rb
+++ b/spree/core/spec/models/spree/promotion_spec.rb
@@ -1125,6 +1125,12 @@ describe Spree::Promotion, type: :model do
expect(reloaded.calculator.preferred_flat_percent).to eq(15)
end
+ 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/)
+ end
+
it 'builds a FreeShipping action without a calculator' do
promotion.actions = [{ type: 'free_shipping' }]
promotion.reload