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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added typed preference declarations and a JSON Schema generator
Damian Legawiec0efbc8fc723b
diff --git a/spree/core/app/models/concerns/spree/calculator/currency_amounts.rb b/spree/core/app/models/concerns/spree/calculator/currency_amounts.rbindex d299954110..2245dce852 100644--- a/spree/core/app/models/concerns/spree/calculator/currency_amounts.rb+++ b/spree/core/app/models/concerns/spree/calculator/currency_amounts.rb@@ -13,7 +13,7 @@ module Spreeextend ActiveSupport::Concernincluded do- preference :amounts, :hash, default: {}+ preference :amounts, :hash, keys: :currency, values: :money, default: {}end# The amount this calculator quotes for a currency: the per-currencydiff --git a/spree/core/app/models/concerns/spree/calculator/tiers.rb b/spree/core/app/models/concerns/spree/calculator/tiers.rbindex 67bfaea156..1ba9fa694e 100644--- a/spree/core/app/models/concerns/spree/calculator/tiers.rb+++ b/spree/core/app/models/concerns/spree/calculator/tiers.rb@@ -9,24 +9,11 @@ module Spreeextend ActiveSupport::Concernincluded do- preference :tiers, :array, default: [], parse_on_set: ->(value) { Tiers.normalize(value) }+ preference :tiers, :array, of: :object, properties: { threshold: :money, value: :decimal }, default: []validate :preferred_tiers_contentend- # @param value [Object] tiers as an operator or API client sent them- # @return [Object] an array of string-keyed hashes with numbers as exact- # decimal strings — the form JSON stores, so a fresh value compares- # equal to one read back — or the value unchanged when it is not a list- # of hashes, so validation can name the problem- def self.normalize(value)- return value unless value.is_a?(Array) && value.all? { |tier| tier.respond_to?(:to_h) && !tier.is_a?(Array) }-- value.map do |tier|- tier.to_h.stringify_keys.to_h { |key, number| [key, decimal(number)&.as_json || number] }- end- end-# @return [BigDecimal, nil] nil when the value is not a numberdef self.decimal(value)BigDecimal(value.to_s, exception: false)diff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rbindex ddb8eaaf66..a31f5b0881 100644--- a/spree/core/app/models/concerns/spree/preference_schema.rb+++ b/spree/core/app/models/concerns/spree/preference_schema.rb@@ -58,6 +58,23 @@ module Spree@preference_schema || []end+ # Whether the declarations could be read — an empty {#preference_schema}+ # also stands in for one that could not be computed before the database+ # was up.+ def preference_schema_computed?+ preference_schema+ !@preference_schema.nil?+ end++ # The JSON Schema of this class's `preferences` object (see+ # {Spree::PreferenceSchema::JsonSchema}). Memoized like+ # {#preference_schema}, and retried while that one could not be computed.+ #+ # @return [Hash, nil]+ def preference_json_schema+ @preference_json_schema ||= Spree::PreferenceSchema::JsonSchema.for(self)+ end+# Wire-safe variant of `preference_schema` with `:password`# defaults nilled out. A gateway author can set a non-empty# default for a `:password` preference; without this redaction the@@ -154,6 +171,9 @@ module Spree# relation builder; defaults to the unscoped `klass`.# @return [Proc] suitable for the `parse_on_set:` preference option.def normalize_id_preference(klass: nil, scope: nil)+ Spree::Deprecation.warn(+ '`normalize_id_preference` is deprecated. Declare the list as `preference :name, :array, of: :id, model:, scope:`.'+ )lambda do |values, owner = nil|raw = Array(values).flat_map { |v| v.to_s.split(',') }.compact_blank.map(&:strip)next raw unless klassdiff --git a/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb b/spree/core/app/models/concerns/spree/preference_schema/json_schema.rbnew file mode 100644index 0000000000..0406756d41--- /dev/null+++ b/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb@@ -0,0 +1,111 @@+module Spree+ module PreferenceSchema+ # Compiles a class's preference declarations into the JSON Schema of its+ # `preferences` object — the contract the OpenAPI components, the SDK+ # types, the `/…/types` endpoints and write validation all read, so none+ # of them is written by hand.+ module JsonSchema+ DECIMAL_PATTERN = '^-?\d+(\.\d+)?$'.freeze++ # Domain formats, with the pattern that makes each one checkable by any+ # validator, not only those that know the format's name.+ FORMATS = {+ currency: { format: 'currency', pattern: '^[A-Z]{3}$' },+ iso_country: { format: 'iso-country', pattern: '^[A-Z]{2}$' },+ timezone: { format: 'timezone' },+ locale: { format: 'locale' },+ url: { format: 'uri' },+ color: { format: 'color', pattern: '^#[0-9A-Fa-f]{6}$' }+ }.freeze++ # @param klass [Class] a class including {Spree::PreferenceSchema}+ # @return [Hash] a JSON Schema object (string keys), or nil when the+ # declarations could not be read yet (no database connection)+ def self.for(klass)+ fields = klass.preference_schema+ return nil if fields.empty? && !klass.preference_schema_computed?++ definitions = klass.preference_definitions+ properties = fields.to_h { |field| [field[:key].to_s, property(field, definitions.fetch(field[:key]))] }++ { 'type' => 'object', 'properties' => properties, 'additionalProperties' => false }+ end++ def self.property(field, definition)+ schema = value_schema(definition)+ choices = field[:choices]+ schema['enum'] = choices.map { |choice| choice.is_a?(Symbol) ? choice.to_s : choice } if choices.present?+ default = wire_default(field[:default], definition)++ # A value nothing has set reads back as null, so a preference without+ # a default is nullable on the wire whatever its declared type — and so+ # is a secret, whose default is never sent.+ if (definition[:nullable] || default.nil? || definition[:type] == :password) && schema['type']+ schema['type'] = [schema['type'], 'null']+ schema['enum'] += [nil] if schema['enum']+ end+ # A secret's default would leak alongside the masked value.+ schema['default'] = default unless default.nil? || definition[:type] == :password+ schema+ end++ def self.value_schema(definition)+ case definition[:type]+ when :string then string_schema(definition[:format])+ when :text then { 'type' => 'string', 'x-spree-widget' => 'textarea' }+ when :boolean then { 'type' => 'boolean' }+ when :integer then { 'type' => 'integer' }+ when :decimal then item_schema(definition[:money] ? :money : :decimal, definition)+ when :password then { 'type' => 'string', 'x-spree-secret' => true }+ when :date then { 'type' => 'string', 'format' => 'date' }+ when :datetime then { 'type' => 'string', 'format' => 'date-time' }+ when :array+ schema = { 'type' => 'array' }+ schema['items'] = item_schema(definition[:of], definition) if definition[:of]+ schema+ when :hash+ schema = { 'type' => 'object' }+ if definition[:keys] && definition[:values]+ schema['propertyNames'] = definition[:keys] == :currency ? string_schema(:currency) : { 'type' => 'string' }+ schema['additionalProperties'] = item_schema(definition[:values], definition)+ end+ schema+ else+ {}+ end+ end++ def self.item_schema(item_type, definition)+ case item_type+ when :string then string_schema(definition[:format])+ when :integer then { 'type' => 'integer' }+ when :boolean then { 'type' => 'boolean' }+ when :decimal then { 'type' => 'string', 'pattern' => DECIMAL_PATTERN }+ when :money then { 'type' => 'string', 'format' => 'money', 'pattern' => DECIMAL_PATTERN }+ when :id+ prefix = Spree::Preferences::Preferable.preference_model(definition)._prefix_id_prefix+ { 'type' => 'string', 'format' => 'prefixed-id', 'pattern' => "^#{prefix}_[A-Za-z0-9]+$", 'x-spree-prefix' => prefix }+ when :object+ properties = definition[:properties].to_h { |name, type| [name.to_s, item_schema(type, {})] }+ { 'type' => 'object', 'properties' => properties, 'required' => properties.keys, 'additionalProperties' => false }+ else+ {}+ end+ end++ def self.string_schema(format)+ { 'type' => 'string' }.merge(FORMATS.fetch(format, {}).transform_keys(&:to_s))+ end++ # The default in the form the API returns it: decimals as exact strings.+ def self.wire_default(default, definition)+ return default if default.nil?+ return BigDecimal(default.to_s, exception: false)&.as_json if definition[:type] == :decimal++ default.as_json+ end++ private_class_method :property, :value_schema, :item_schema, :string_schema, :wire_default+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/stores/email_branding.rb b/spree/core/app/models/concerns/spree/stores/email_branding.rbindex 2e2a9d3376..7c2cc6828a 100644--- a/spree/core/app/models/concerns/spree/stores/email_branding.rb+++ b/spree/core/app/models/concerns/spree/stores/email_branding.rb@@ -6,7 +6,8 @@ module Spreeextend ActiveSupport::Concernincluded do- Spree::Emails::Branding.attribute_names.each { |name| preference :"email_#{name}", :string }+ Spree::Emails::Branding::COLORS.each { |name| preference :"email_#{name}", :string, format: :color }+ preference :email_font, :string, choices: -> { Spree::Emails::Branding::FONTS.keys }validate :email_branding_validenddiff --git a/spree/core/app/models/concerns/spree/typed_associations.rb b/spree/core/app/models/concerns/spree/typed_associations.rbindex 0600673fc4..57febe3769 100644--- a/spree/core/app/models/concerns/spree/typed_associations.rb+++ b/spree/core/app/models/concerns/spree/typed_associations.rb@@ -81,7 +81,7 @@ module Spreepreferences&.each do |key, value|next unless record.has_preference?(key.to_sym)- record.set_preference(key.to_sym, decode_preference_value(key, value))+ record.set_preference(key.to_sym, value)endrecord.assign_calculator_attributes(calculator) if calculator.present? && record.respond_to?(:assign_calculator_attributes)@@ -101,17 +101,6 @@ module Spreeraiseend- # Decode `*_ids` array preferences (`customer_group_ids`, `user_ids`,- # …) from prefixed strings to raw PKs. Plain-scalar / non-id- # preferences pass through unchanged.- def decode_preference_value(key, value)- return value unless key.to_s.end_with?('_ids') && value.is_a?(Array)-- value.map do |v|- Spree::PrefixedId.prefixed_id?(v) ? Spree::PrefixedId.decode_prefixed_id(v) : v- end- end-def find_or_build_typed_association_row(collection, row)if row[:id].present?id = Spree::PrefixedId.prefixed_id?(row[:id]) ? Spree::PrefixedId.decode_prefixed_id(row[:id]) : row[:id]diff --git a/spree/core/app/models/spree/calculator/flat_rate.rb b/spree/core/app/models/spree/calculator/flat_rate.rbindex 7e3cc812d3..38d46bcd7f 100644--- a/spree/core/app/models/spree/calculator/flat_rate.rb+++ b/spree/core/app/models/spree/calculator/flat_rate.rb@@ -1,7 +1,7 @@module Spreeclass Calculator::FlatRate < Calculatorpreference :amount, :money, default: 0- preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }preference :apply_only_on_full_priced_items, :boolean, default: falsedef self.descriptiondiff --git a/spree/core/app/models/spree/calculator/flexi_rate.rb b/spree/core/app/models/spree/calculator/flexi_rate.rbindex 19107d7f39..e4251f08df 100644--- a/spree/core/app/models/spree/calculator/flexi_rate.rb+++ b/spree/core/app/models/spree/calculator/flexi_rate.rb@@ -3,7 +3,7 @@ module Spreepreference :first_item, :money, default: 0.0preference :additional_item, :money, default: 0.0preference :max_items, :integer, default: 0- preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }preference :apply_only_on_full_priced_items, :boolean, default: falsedef self.descriptiondiff --git a/spree/core/app/models/spree/calculator/price_sack.rb b/spree/core/app/models/spree/calculator/price_sack.rbindex 06a12cdd3f..9beb909116 100644--- a/spree/core/app/models/spree/calculator/price_sack.rb+++ b/spree/core/app/models/spree/calculator/price_sack.rb@@ -3,7 +3,7 @@ module Spreepreference :minimal_amount, :money, default: 0preference :normal_amount, :money, default: 0preference :discount_amount, :money, default: 0- preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }def self.descriptionI18n.t('spree.price_sack')diff --git a/spree/core/app/models/spree/calculator/shipping/digital_delivery.rb b/spree/core/app/models/spree/calculator/shipping/digital_delivery.rbindex 7d8799f5ce..cb9b40bf50 100644--- a/spree/core/app/models/spree/calculator/shipping/digital_delivery.rb+++ b/spree/core/app/models/spree/calculator/shipping/digital_delivery.rb@@ -4,7 +4,7 @@ module Spreeinclude Spree::Calculator::CurrencyAmountspreference :amount, :money, default: 0- preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }def self.descriptionI18n.t('spree.digital.digital_delivery')diff --git a/spree/core/app/models/spree/calculator/shipping/flat_rate.rb b/spree/core/app/models/spree/calculator/shipping/flat_rate.rbindex 61fb68741e..cf358bf17d 100644--- a/spree/core/app/models/spree/calculator/shipping/flat_rate.rb+++ b/spree/core/app/models/spree/calculator/shipping/flat_rate.rb@@ -7,7 +7,7 @@ module Spree# @deprecated Together with the single `amount`, superseded by the# per-currency `amounts` hash; kept as the fallback for its own# currency so upgraded stores quote unchanged.- preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }preference :minimum_item_total, :money, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'preference :maximum_item_total, :money, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'diff --git a/spree/core/app/models/spree/calculator/shipping/flexi_rate.rb b/spree/core/app/models/spree/calculator/shipping/flexi_rate.rbindex eb92a59fab..1d6090fd1d 100644--- a/spree/core/app/models/spree/calculator/shipping/flexi_rate.rb+++ b/spree/core/app/models/spree/calculator/shipping/flexi_rate.rb@@ -4,7 +4,7 @@ module Spreepreference :first_item, :money, default: 0.0preference :additional_item, :money, default: 0.0preference :max_items, :integer, default: 0- preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }# Single-currency amounts: quoting another currency would mislabel# the configured numbers, so the method stays hidden there.diff --git a/spree/core/app/models/spree/calculator/shipping/per_item.rb b/spree/core/app/models/spree/calculator/shipping/per_item.rbindex dfa1a9d4a5..347e2a0bf4 100644--- a/spree/core/app/models/spree/calculator/shipping/per_item.rb+++ b/spree/core/app/models/spree/calculator/shipping/per_item.rb@@ -4,7 +4,7 @@ module Spreeinclude Spree::Calculator::CurrencyAmountspreference :amount, :money, default: 0- preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }def self.descriptionI18n.t('spree.shipping_flat_rate_per_item')diff --git a/spree/core/app/models/spree/calculator/shipping/price_sack.rb b/spree/core/app/models/spree/calculator/shipping/price_sack.rbindex 2ebb4402a7..46b8d94378 100644--- a/spree/core/app/models/spree/calculator/shipping/price_sack.rb+++ b/spree/core/app/models/spree/calculator/shipping/price_sack.rb@@ -4,7 +4,7 @@ module Spreepreference :minimal_amount, :money, default: 0preference :normal_amount, :money, default: 0preference :discount_amount, :money, default: 0- preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }# Single-currency amounts: quoting another currency would mislabel# the configured numbers, so the method stays hidden there.diff --git a/spree/core/app/models/spree/calculator/tiered_flat_rate.rb b/spree/core/app/models/spree/calculator/tiered_flat_rate.rbindex 9042a4b281..3358ba5f03 100644--- a/spree/core/app/models/spree/calculator/tiered_flat_rate.rb+++ b/spree/core/app/models/spree/calculator/tiered_flat_rate.rb@@ -3,7 +3,7 @@ module Spreeinclude Spree::Calculator::Tierspreference :base_amount, :money, default: 0- preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }def self.descriptionI18n.t('spree.tiered_flat_rate')diff --git a/spree/core/app/models/spree/channel/gating.rb b/spree/core/app/models/spree/channel/gating.rbindex a335682f75..49a526dec6 100644--- a/spree/core/app/models/spree/channel/gating.rb+++ b/spree/core/app/models/spree/channel/gating.rb@@ -17,7 +17,7 @@ module Spree# Empty -> falls back to the Store-level preference. Both are `nullable`# so a blank write stays nil (inherit) rather than coercing to "" or# false, while an explicit value remains a channel override.- preference :storefront_access, :string, default: nil, nullable: true+ preference :storefront_access, :string, default: nil, nullable: true, choices: STOREFRONT_ACCESSpreference :guest_checkout, :boolean, default: nil, nullable: truevalidate :storefront_access_must_be_validdiff --git a/spree/core/app/models/spree/commission_rules/category_rule.rb b/spree/core/app/models/spree/commission_rules/category_rule.rbindex 7359465b59..15672d2813 100644--- a/spree/core/app/models/spree/commission_rules/category_rule.rb+++ b/spree/core/app/models/spree/commission_rules/category_rule.rb@@ -9,11 +9,8 @@ module Spree# restate the rule on every new leaf. The walk is done once per order by# Spree::Commissions::Context, not per rule.class CategoryRule < Spree::CommissionRule- preference :category_ids, :array, default: [],- parse_on_set: normalize_id_preference(- klass: Spree::Category,- scope: ->(rule) { rule.store.categories }- )+ preference :category_ids, :array, of: :id, model: 'Spree::Category', default: [],+ scope: ->(rule) { rule.store.categories }# @return [Array<Spree::Category>]def categoriesdiff --git a/spree/core/app/models/spree/commission_rules/seller_rule.rb b/spree/core/app/models/spree/commission_rules/seller_rule.rbindex ecc544d224..f80305927e 100644--- a/spree/core/app/models/spree/commission_rules/seller_rule.rb+++ b/spree/core/app/models/spree/commission_rules/seller_rule.rb@@ -7,11 +7,8 @@ module Spree# Ids are checked against the rate's own store on write, so a rule can# never be pointed at another marketplace's seller — and the client is# told, rather than having the id quietly dropped.- preference :seller_ids, :array, default: [],- parse_on_set: normalize_id_preference(- klass: Spree::Seller,- scope: ->(rule) { rule.store.sellers }- )+ preference :seller_ids, :array, of: :id, model: 'Spree::Seller', default: [],+ scope: ->(rule) { rule.store.sellers }# @return [Array<Spree::Seller>]def sellersdiff --git a/spree/core/app/models/spree/delivery_method_rules/channel_rule.rb b/spree/core/app/models/spree/delivery_method_rules/channel_rule.rbindex 79ce8d991f..012447b73e 100644--- a/spree/core/app/models/spree/delivery_method_rules/channel_rule.rb+++ b/spree/core/app/models/spree/delivery_method_rules/channel_rule.rb@@ -13,11 +13,8 @@ module Spree# decodes them on write, so eligibility compares against raw# `channel_id` rows. The scope confines the existence check to the# method's store, so cross-store channel IDs can't sneak in.- preference :channel_ids, :array, default: [],- parse_on_set: normalize_id_preference(- klass: Spree::Channel,- scope: ->(rule) { rule.store.channels }- )+ preference :channel_ids, :array, of: :id, model: 'Spree::Channel', default: [],+ scope: ->(rule) { rule.store.channels }def channelsreturn [] if preferred_channel_ids.blank?diff --git a/spree/core/app/models/spree/price_rules/channel_rule.rb b/spree/core/app/models/spree/price_rules/channel_rule.rbindex fa00ae2c79..f623de3eec 100644--- a/spree/core/app/models/spree/price_rules/channel_rule.rb+++ b/spree/core/app/models/spree/price_rules/channel_rule.rb@@ -9,11 +9,8 @@ module Spree# against raw `channel_id` rows directly. Scope confines the# existence check to the price-list's store so cross-store channel# IDs can't sneak in.- preference :channel_ids, :array, default: [],- parse_on_set: normalize_id_preference(- klass: Spree::Channel,- scope: ->(rule) { rule.store.channels }- )+ preference :channel_ids, :array, of: :id, model: 'Spree::Channel', default: [],+ scope: ->(rule) { rule.store.channels }def channelsreturn [] if preferred_channel_ids.blank?diff --git a/spree/core/app/models/spree/price_rules/customer_group_rule.rb b/spree/core/app/models/spree/price_rules/customer_group_rule.rbindex a8fe5b2cfc..e50fc7071a 100644--- a/spree/core/app/models/spree/price_rules/customer_group_rule.rb+++ b/spree/core/app/models/spree/price_rules/customer_group_rule.rb@@ -10,11 +10,8 @@ module Spree# callers and decodes them on write so eligibility checks compare# against raw `customer_group_id` rows directly. Scope confines# the existence check to the price-list's store.- preference :customer_group_ids, :array, default: [],- parse_on_set: normalize_id_preference(- klass: Spree::CustomerGroup,- scope: ->(rule) { rule.store.customer_groups }- )+ preference :customer_group_ids, :array, of: :id, model: 'Spree::CustomerGroup', default: [],+ scope: ->(rule) { rule.store.customer_groups }def customer_groupsreturn [] if preferred_customer_group_ids.blank?diff --git a/spree/core/app/models/spree/price_rules/market_rule.rb b/spree/core/app/models/spree/price_rules/market_rule.rbindex 1655245aaf..67897ee51e 100644--- a/spree/core/app/models/spree/price_rules/market_rule.rb+++ b/spree/core/app/models/spree/price_rules/market_rule.rb@@ -6,11 +6,8 @@ module Spree# against raw `market_id` rows directly. Scope confines the# existence check to the price-list's store so cross-store market# IDs can't sneak in.- preference :market_ids, :array, default: [],- parse_on_set: normalize_id_preference(- klass: Spree::Market,- scope: ->(rule) { rule.store.markets }- )+ preference :market_ids, :array, of: :id, model: 'Spree::Market', default: [],+ scope: ->(rule) { rule.store.markets }def marketsreturn [] if preferred_market_ids.blank?diff --git a/spree/core/app/models/spree/price_rules/user_rule.rb b/spree/core/app/models/spree/price_rules/user_rule.rbindex 2deb0beccf..fe9451e105 100644--- a/spree/core/app/models/spree/price_rules/user_rule.rb+++ b/spree/core/app/models/spree/price_rules/user_rule.rb@@ -10,9 +10,7 @@ module Spree# e.g. `usr_…`) from API callers and decodes them on write. Resolves# `Spree.customer_class` lazily — the user class is configured at boot,# and class-body evaluation runs before that on cold loads.- preference :user_ids, :array, default: [], parse_on_set: ->(values) {- normalize_id_preference(klass: Spree.customer_class).call(values)- }+ preference :user_ids, :array, of: :id, model: -> { Spree.customer_class }, default: []def usersreturn [] if preferred_user_ids.blank?diff --git a/spree/core/app/models/spree/promotion/rules/category.rb b/spree/core/app/models/spree/promotion/rules/category.rbindex 3763bdc907..17658f474d 100644--- a/spree/core/app/models/spree/promotion/rules/category.rb+++ b/spree/core/app/models/spree/promotion/rules/category.rb@@ -35,7 +35,7 @@ module Spree# Preferences#MATCH_POLICIES = %w(any all)- preference :match_policy, :string, default: MATCH_POLICIES.first+ preference :match_policy, :string, default: MATCH_POLICIES.first, choices: MATCH_POLICIES## Attributesdiff --git a/spree/core/app/models/spree/promotion/rules/channel.rb b/spree/core/app/models/spree/promotion/rules/channel.rbindex 0eafa94b14..70998f7481 100644--- a/spree/core/app/models/spree/promotion/rules/channel.rb+++ b/spree/core/app/models/spree/promotion/rules/channel.rb@@ -8,11 +8,8 @@ module Spree# against the order's raw `channel_id` directly. Scope confines the# existence check to the promotion's store so cross-store channel# IDs can't sneak in.- preference :channel_ids, :array, default: [],- parse_on_set: normalize_id_preference(- klass: Spree::Channel,- scope: ->(rule) { rule.promotion.store.channels }- )+ preference :channel_ids, :array, of: :id, model: 'Spree::Channel', default: [],+ scope: ->(rule) { rule.promotion.store.channels }def channelsreturn Spree::Channel.none if preferred_channel_ids.blank?diff --git a/spree/core/app/models/spree/promotion/rules/country.rb b/spree/core/app/models/spree/promotion/rules/country.rbindex ec12dc4090..0f153c325b 100644--- a/spree/core/app/models/spree/promotion/rules/country.rb+++ b/spree/core/app/models/spree/promotion/rules/country.rb@@ -9,11 +9,10 @@ module Spreeclass Promotionmodule Rulesclass Country < Spree::PromotionRule- preference :country_codes, :array, default: [], parse_on_set: lambda { |values|- normalize_id_preference.call(values).map(&:upcase)- }+ preference :country_codes, :array, of: :string, format: :iso_country, default: [],+ parse_on_set: ->(values) { Array(values).flat_map { |value| value.to_s.split(',') }.map { |code| code.strip.upcase }.compact_blank }preference :country_id, :integer # legacy single-country shortcut- preference :country_code, :string # legacy ISO-based shortcut+ preference :country_code, :string, format: :iso_country # legacy ISO-based shortcutdef countriesisos = configured_country_codes.presence || [configured_country_code].compact_blankdiff --git a/spree/core/app/models/spree/promotion/rules/currency.rb b/spree/core/app/models/spree/promotion/rules/currency.rbindex 1641e4f94d..54f9a07bd5 100644--- a/spree/core/app/models/spree/promotion/rules/currency.rb+++ b/spree/core/app/models/spree/promotion/rules/currency.rb@@ -3,7 +3,7 @@ module Spreeclass Promotionmodule Rulesclass Currency < Spree::PromotionRule- preference :currency, :string+ preference :currency, :string, format: :currencydef eligible?(order, options = {})return true if order.currency == preferred_currencydiff --git a/spree/core/app/models/spree/promotion/rules/customer_group.rb b/spree/core/app/models/spree/promotion/rules/customer_group.rbindex 5bb768facd..56442780aa 100644--- a/spree/core/app/models/spree/promotion/rules/customer_group.rb+++ b/spree/core/app/models/spree/promotion/rules/customer_group.rb@@ -9,11 +9,8 @@ module Spree# Scoped to the promotion's own store: groups are store-owned, so an# id from elsewhere must raise rather than link a promotion to an# audience its store cannot see.- preference :customer_group_ids, :array, default: [],- parse_on_set: normalize_id_preference(- klass: Spree::CustomerGroup,- scope: ->(rule) { rule.promotion.store.customer_groups }- )+ preference :customer_group_ids, :array, of: :id, model: 'Spree::CustomerGroup', default: [],+ scope: ->(rule) { rule.promotion.store.customer_groups }def customer_groupsreturn Spree::CustomerGroup.none if preferred_customer_group_ids.blank?diff --git a/spree/core/app/models/spree/promotion/rules/market.rb b/spree/core/app/models/spree/promotion/rules/market.rbindex e745ee5d80..7535a2efab 100644--- a/spree/core/app/models/spree/promotion/rules/market.rb+++ b/spree/core/app/models/spree/promotion/rules/market.rb@@ -8,11 +8,8 @@ module Spree# against the order's raw `market_id` directly. Scope confines the# existence check to the promotion's store so cross-store market# IDs can't sneak in.- preference :market_ids, :array, default: [],- parse_on_set: normalize_id_preference(- klass: Spree::Market,- scope: ->(rule) { rule.promotion.store.markets }- )+ preference :market_ids, :array, of: :id, model: 'Spree::Market', default: [],+ scope: ->(rule) { rule.promotion.store.markets }def marketsreturn Spree::Market.none if preferred_market_ids.blank?diff --git a/spree/core/app/models/spree/promotion/rules/option_value.rb b/spree/core/app/models/spree/promotion/rules/option_value.rbindex 060240e9e0..34296234c5 100644--- a/spree/core/app/models/spree/promotion/rules/option_value.rb+++ b/spree/core/app/models/spree/promotion/rules/option_value.rb@@ -3,13 +3,12 @@ module Spreemodule Rulesclass OptionValue < Spree::PromotionRuleMATCH_POLICIES = %w(any)- preference :match_policy, :string, default: MATCH_POLICIES.first+ preference :match_policy, :string, default: MATCH_POLICIES.first, choices: MATCH_POLICIES# Stored as raw Spree::OptionValue ids. Accepts prefixed IDs (`optval_…`)# from API callers and decodes them on write so eligibility checks compare# against stable option-value rows, not join-table ids that shift when# variants are reconfigured.- preference :eligible_values, :array, default: [],- parse_on_set: normalize_id_preference(klass: Spree::OptionValue)+ preference :eligible_values, :array, of: :id, model: 'Spree::OptionValue', default: []# @param promotable [Object]# @return [Boolean]diff --git a/spree/core/app/models/spree/promotion/rules/product.rb b/spree/core/app/models/spree/promotion/rules/product.rbindex ff05967e18..c6d1d018a4 100644--- a/spree/core/app/models/spree/promotion/rules/product.rb+++ b/spree/core/app/models/spree/promotion/rules/product.rb@@ -28,7 +28,7 @@ module Spree# Preferences#MATCH_POLICIES = %w(any all none)- preference :match_policy, :string, default: MATCH_POLICIES.first+ preference :match_policy, :string, default: MATCH_POLICIES.first, choices: MATCH_POLICIES## Attributesdiff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 4df952501f..d3bbf2878c 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -42,9 +42,9 @@ module Spree# Preferences## general preferences- preference :admin_locale, :string- preference :timezone, :string, default: Time.zone.name- preference :weight_unit, :string, default: 'lb'+ preference :admin_locale, :string, format: :locale+ preference :timezone, :string, format: :timezone, default: Time.zone.name+ preference :weight_unit, :string, default: 'lb', choices: -> { Spree::Variant::WEIGHT_UNITS }preference :unit_system, :string, default: 'imperial'# Anonymous identifier of this installation, kept on the default store# (see Spree.install_id). Written by Spree, never by the operator.@@ -83,7 +83,7 @@ module Spree# How often sellers are settled, unless one carries its own schedule.# Monthly by default because it is the interval that needs least of an# operator paying by hand, which is what the built-in provider expects.- preference :default_payouts_schedule_interval, :string, default: 'monthly'+ preference :default_payouts_schedule_interval, :string, default: 'monthly', choices: -> { Spree::Seller::PAYOUT_INTERVALS }validates :preferred_default_payouts_schedule_interval,inclusion: { in: Spree::Seller::PAYOUT_INTERVALS }, allow_blank: true# What a seller's balance must reach before a settlement is worth sending;@@ -95,10 +95,10 @@ module Spree# (see Spree::Channel::Gating). Retained so existing accessors keep working.preference :guest_checkout, :boolean, default: true# Store-level fallback for the channel-owned `storefront_access` posture.- preference :storefront_access, :string, default: 'public'+ preference :storefront_access, :string, default: 'public', choices: -> { Spree::Channel::Gating::STOREFRONT_ACCESS }# Canonical storefront origin used in customer-facing emails and links,# e.g. "https://myshop.com" — see #storefront_url for the fallback chain.- preference :storefront_url, :string+ preference :storefront_url, :string, format: :urlpreference :special_instructions_enabled, :boolean, default: false# Advertises a confirm/review step for every checkout, even when no# payment method asks for one. Payment methods that require confirmation@@ -108,7 +108,8 @@ module Spree# Store-wide default for when a customer is charged rather than only# authorized. A payment method's own capture_method wins when set.# See Spree::CaptureMethod.- preference :capture_method, :string, default: Spree::CaptureMethod::DEFAULT_CAPTURE_METHOD+ preference :capture_method, :string, default: Spree::CaptureMethod::DEFAULT_CAPTURE_METHOD,+ choices: -> { Spree::CaptureMethod::CAPTURE_METHODS }preference :stock_reservations_enabled, :boolean, default: true# Which address a sale's tax is computed against. Stores selling where tax# follows the destination keep this on; billing-address jurisdictions turn@@ -120,9 +121,9 @@ module Spreepreference :inventory_provider, :string, default: 'internal'# What happens when an external source cannot be reached.preference :pricing_provider_failure_policy, :string,- default: Spree::ProviderFailurePolicy::DEFAULT_PRICING_POLICY+ default: Spree::ProviderFailurePolicy::DEFAULT_PRICING_POLICY, choices: -> { Spree::ProviderFailurePolicy::VALUES }preference :inventory_provider_failure_policy, :string,- default: Spree::ProviderFailurePolicy::DEFAULT_INVENTORY_POLICY+ default: Spree::ProviderFailurePolicy::DEFAULT_INVENTORY_POLICY, choices: -> { Spree::ProviderFailurePolicy::VALUES }# Catalog preferencespreference :track_inventory_levels, :boolean, default: true# On-hand quantity at or below which a tracked variant counts as running@@ -163,7 +164,7 @@ module Spree# applies to every numbered document; prefix, suffix and starting value# are order-only — other document types keep their code-level prefixes.# Changes affect future numbers only; existing numbers are permanent.- preference :document_number_format, :string, default: 'sequential'+ preference :document_number_format, :string, default: 'sequential', choices: -> { Spree::NumberGenerators::Registry::FORMATS.keys }preference :order_number_prefix, :string, default: 'R'preference :order_number_suffix, :string, default: ''preference :order_number_sequence_start, :integer, default: 1001diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex c56881967e..585101b9e8 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -17,6 +17,7 @@ require 'awesome_nested_set'require 'cancan'require 'countries/global'require 'friendly_id'+require 'json_schemer'require 'jwt'require 'liquid'require 'spree/core/emails/escaped_output'diff --git a/spree/core/lib/spree/core/preferences/masking.rb b/spree/core/lib/spree/core/preferences/masking.rbindex 2bc1e2ca53..70f94adf71 100644--- a/spree/core/lib/spree/core/preferences/masking.rb+++ b/spree/core/lib/spree/core/preferences/masking.rb@@ -78,14 +78,26 @@ module Spreedef self.serialize(preferable)return {} if preferable.nil?+ definitions = preferable.class.preference_definitionspreferable.preference_schema.each_with_object({}) do |field, hash|# The stored value only, never the default — an unset secret must not# reveal what it would fall back to — read through the record,# because a secret lives in its own column.value = preferable.stored_preference(field[:key]) { nil }- hash[field[:key_string] || field[:key].to_s] = wire_value(preferable, field[:type], value)+ definition = definitions.fetch(field[:key])+ hash[field[:key_string] || field[:key].to_s] =+ definition[:of] == :id ? prefixed_ids(value, definition) : wire_value(preferable, field[:type], value)endend++ # Ids are stored as raw primary keys and leave as prefixed ids, the form+ # every write accepts.+ def self.prefixed_ids(value, definition)+ return value unless value.is_a?(Array)++ model = Spree::Preferences::Preferable.preference_model(definition)+ value.map { |id| Spree::PrefixedId.prefixed_id?(id.to_s) ? id : model.prefixed_id_for(id) }+ endendendenddiff --git a/spree/core/lib/spree/core/preferences/preferable.rb b/spree/core/lib/spree/core/preferences/preferable.rbindex 7bb230734a..9865ea7711 100644--- a/spree/core/lib/spree/core/preferences/preferable.rb+++ b/spree/core/lib/spree/core/preferences/preferable.rb@@ -42,6 +42,17 @@ module Spree::Preferences::Preferablevalueend+ # The record class an `of: :id` preference points at. Declared as a class+ # name or a block, so a declaration never loads another model, nor fixes a+ # configurable class like `Spree.customer_class`, at class load.+ #+ # @param definition [Hash] a preference definition+ # @return [Class]+ def self.preference_model(definition)+ model = definition[:model]+ model.respond_to?(:call) ? model.call : model.to_s.constantize+ end+def get_preference(name)has_preference! namepublic_send(:"preferred_#{name}")@@ -183,6 +194,7 @@ module Spree::Preferences::Preferablevalue = parse_on_set.arity.abs > 1 ? parse_on_set.call(value, self) : parse_on_set.call(value)endvalue = 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# read back from the database and one just written compare equal and# setting the same value is not a change. The reader restores them.@@ -192,6 +204,81 @@ module Spree::Preferences::Preferablevalueend+ # Casts what a typed `:array` or `:hash` holds to its declared item type, in+ # the form JSON stores. A value that does not cast is left as it came, so+ # validation can name it rather than a silent zero hiding it.+ def cast_preference_contents(value, definition)+ case definition[:type]+ when :array+ case definition[:of]+ when nil then value+ when :id then decode_preference_ids(value, definition)+ when :object then value.map { |item| cast_preference_object(item, definition[:properties]) }+ else split_preference_list(value).map { |item| cast_preference_item(item, definition[:of]) }+ end+ when :hash+ return value unless definition[:values] && value.is_a?(Hash)++ value.to_h do |key, item|+ key = definition[:keys] == :currency ? key.to_s.upcase : key.to_s+ [key, cast_preference_item(item, definition[:values])]+ end+ else+ value+ end+ end++ # A comma-separated string is a list too: what a plain text field sends.+ def split_preference_list(values)+ values.flat_map { |item| item.is_a?(String) ? item.split(',') : [item] }+ .map { |item| item.is_a?(String) ? item.strip : item }+ .reject { |item| item.respond_to?(:empty?) && item.empty? }+ end++ def cast_preference_item(value, item_type)+ case item_type+ when :string then value.to_s+ when :integer then Integer(value.to_s, 10, exception: false) || value+ when :decimal, :money then BigDecimal(value.to_s, exception: false)&.as_json || value+ when :boolean then ActiveModel::Type::Boolean.new.cast(value)+ else value+ end+ end++ def cast_preference_object(item, properties)+ return item unless item.respond_to?(:to_h) && !item.is_a?(Array)++ item.to_h.stringify_keys.slice(*properties.keys.map(&:to_s)).to_h do |key, value|+ [key, cast_preference_item(value, properties[key.to_sym])]+ end+ end++ # Turns a list of record ids into the raw primary keys the preference+ # stores. A prefixed id must carry the declared model's prefix — a+ # channel's id never decodes into a market id — and every id must belong to+ # the record's scope, so a rule cannot point at another store's records.+ #+ # @raise [ActiveRecord::RecordNotFound] naming the ids that were not found+ def decode_preference_ids(values, definition)+ model = Spree::Preferences::Preferable.preference_model(definition)+ prefix = "#{model._prefix_id_prefix}_"+ ids = split_preference_list(values).map(&:to_s).map do |id|+ next id unless Spree::PrefixedId.prefixed_id?(id)++ id.start_with?(prefix) ? Spree::PrefixedId.decode_prefixed_id(id).to_s : id+ end+ return ids if ids.empty?++ relation = definition[:scope] ? definition[:scope].call(self) : model+ found = relation.where(id: ids.reject { |id| Spree::PrefixedId.prefixed_id?(id) }).pluck(:id).map(&:to_s).to_set+ missing = ids.reject { |id| found.include?(id) }+ if missing.any?+ raise ActiveRecord::RecordNotFound.new("Couldn't find #{model.name} with id=#{missing.join(',')}", model.name)+ end++ ids+ end+# Assigns a new hash rather than calling the store accessor's writer, which# skips writing nil to a missing key — leaving the default in force when nil# was meant. Rails still sees no change when the value is the one stored.diff --git a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb b/spree/core/lib/spree/core/preferences/preferable_class_methods.rbindex 1f7cdd50c7..ea21b4b1ca 100644--- a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb+++ b/spree/core/lib/spree/core/preferences/preferable_class_methods.rb@@ -37,12 +37,41 @@ module Spree::Preferencespreference_declarations_cache[:secrets] ||= declared_preference_types.filter_map { |name, type| name if type == :password }.freezeend+ # The value types a list item, a hash value or an object property may+ # declare, and the formats a string may carry. They are what+ # {Spree::PreferenceSchema::JsonSchema} compiles to JSON Schema.+ ITEM_TYPES = %i[string integer decimal money boolean id object].freeze+ FORMATS = %i[currency iso_country timezone locale url color].freeze+# Declares a typed preference with a `preferred_<name>` reader and writer# and a `prefers_<name>?` query. On a model, the value lives in the# `preferences` column (`secret_preferences` for a `:password` one) as a# Rails store accessor, which brings the change methods with it:# `preferred_<name>_changed?`, `_change`, `_was`,# `saved_change_to_preferred_<name>?` and `preferred_<name>_before_last_save`.+ #+ # The declaration is the preference's contract on the wire, so it states+ # the full type:+ #+ # preference :amount_min, :decimal, money: true+ # preference :channel_ids, :array, of: :id, model: 'Spree::Channel', scope: ->(rule) { rule.store.channels }+ # preference :country_codes, :array, of: :string, format: :iso_country+ # preference :match_policy, :string, choices: %w[any all none]+ # preference :amounts, :hash, keys: :currency, values: :money+ # preference :tiers, :array, of: :object, properties: { threshold: :money, value: :decimal }+ #+ # @param name [Symbol]+ # @param type [Symbol] `:string`, `:text`, `:boolean`, `:integer`, `:decimal`,+ # `:array`, `:hash`, `:password`, `:date` or `:datetime`+ # @option options [Symbol] :of the type of each item of an `:array`+ # @option options [Symbol] :keys the type of a `:hash`'s keys (`:string` or `:currency`)+ # @option options [Symbol] :values the type of a `:hash`'s values+ # @option options [Hash{Symbol => Symbol}] :properties the fields of each `of: :object` item+ # @option options [Boolean] :money a `:decimal` that is an amount of money+ # @option options [Symbol] :format a string's domain format (see {FORMATS})+ # @option options [String, Proc] :model the record class an `of: :id` list points at+ # @option options [Proc] :scope `->(owner) { relation }` the ids must be found in+ # @option options [Array, Proc] :choices the fixed set a value must come fromdef preference(name, type, *args)name = name.to_symsecret = type == :password@@ -52,7 +81,14 @@ module Spree::Preferencesendoptions = args.extract_options!- options.assert_valid_keys(:default, :deprecated, :in, :internal, :nullable, :parse_on_set)+ options.assert_valid_keys(:default, :deprecated, :in, :choices, :internal, :nullable, :parse_on_set,+ :of, :keys, :values, :properties, :money, :format, :model, :scope)+ if options.key?(:in)+ Spree::Deprecation.warn("`preference :#{name}, in:` is deprecated. Use `choices:` instead.")+ options[:choices] ||= options.delete(:in)+ end+ check_preference_declaration(name, type, options)+default = options[:default]default = -> { options[:default] } unless default.is_a?(Proc)own_preference_definitions[name] = {@@ -63,9 +99,17 @@ module Spree::Preferences# value a provider hands back, kept out of every admin form.internal: options[:internal],# The fixed set a value must come from; turns a text box into a picker.- choices: options[:in],+ choices: options[:choices],nullable: options[:nullable],- parse_on_set: options[:parse_on_set]+ parse_on_set: options[:parse_on_set],+ of: options[:of],+ keys: options[:keys],+ values: options[:values],+ properties: options[:properties],+ money: options[:money],+ format: options[:format],+ model: options[:model],+ scope: options[:scope]}PreferableClassMethods.declarations += 1@@ -86,8 +130,60 @@ module Spree::Preferencesendend+ # Gives each named preference a plain reader and writer, so the API reads+ # and writes `guest_checkout` rather than the DSL's `preferred_guest_checkout`.+ # Grants no write access: each API controller still lists what it permits.+ #+ # exposes_preferences :guest_checkout, :timezone+ #+ # @param names [Array<Symbol>]+ # @return [void]+ def exposes_preferences(*names)+ names.each do |name|+ name = name.to_sym+ raise ArgumentError, "#{self.name} has no preference `#{name}` to expose" unless preference_definitions.key?(name)+ raise ArgumentError, "#{self.name} cannot expose the preference `#{name}`: a method of that name exists" if method_defined?(name)++ define_method(name) { public_send(:"preferred_#{name}") }+ define_method(:"#{name}=") { |value| public_send(:"preferred_#{name}=", value) }+ end+ end+private+ # A declaration is the preference's contract on the wire. One Spree ships+ # is always complete (a spec enforces it); an incomplete one from an+ # extension still works in 6.0, with a schema that accepts any value.+ def check_preference_declaration(name, type, options)+ if options[:of] && type != :array+ raise ArgumentError, "`of:` applies to an :array preference, not `#{name}` (#{type})"+ end+ if (options[:keys] || options[:values]) && type != :hash+ raise ArgumentError, "`keys:` and `values:` apply to a :hash preference, not `#{name}` (#{type})"+ end+ if options[:money] && type != :decimal+ raise ArgumentError, "`money:` applies to a :decimal preference, not `#{name}` (#{type})"+ end+ [options[:of], options[:values], *options[:properties]&.values].compact.each do |item_type|+ raise ArgumentError, "Unknown item type `#{item_type}` on preference `#{name}`" unless ITEM_TYPES.include?(item_type)+ end+ raise ArgumentError, "Unknown format `#{options[:format]}` on preference `#{name}`" if options[:format] && FORMATS.exclude?(options[:format])+ raise ArgumentError, "`of: :id` needs `model:` on preference `#{name}`" if options[:of] == :id && options[:model].blank?+ raise ArgumentError, "`of: :object` needs `properties:` on preference `#{name}`" if options[:of] == :object && options[:properties].blank?++ missing = case type+ when :any then 'a type other than :any'+ when :array then '`of:`' unless options[:of]+ when :hash then '`keys:` and `values:`' unless options[:keys] && options[:values]+ end+ return unless missing++ Spree::Deprecation.warn(+ "#{self.name} preference `#{name}` (#{type}) needs #{missing}; until it has one, its schema accepts any value. " \+ 'Spree 6.1 will raise for an incomplete declaration.'+ )+ end+def own_preference_definitions@own_preference_definitions ||= {}enddiff --git a/spree/core/spec/models/spree/preference_schema/json_schema_spec.rb b/spree/core/spec/models/spree/preference_schema/json_schema_spec.rbnew file mode 100644index 0000000000..872adc2ee0--- /dev/null+++ b/spree/core/spec/models/spree/preference_schema/json_schema_spec.rb@@ -0,0 +1,104 @@+require 'spec_helper'++describe Spree::PreferenceSchema::JsonSchema do+ def property(klass, name)+ klass.preference_json_schema.fetch('properties').fetch(name.to_s)+ end++ describe '.for' do+ it 'describes a closed object, so an unknown key is refused' do+ schema = Spree::Promotion::Rules::Channel.preference_json_schema++ expect(schema).to include('type' => 'object', 'additionalProperties' => false)+ expect(schema['properties'].keys).to eq(%w[channel_ids])+ end++ it 'types an id list with the model prefix' do+ expect(property(Spree::Promotion::Rules::Channel, :channel_ids)).to eq(+ 'type' => 'array',+ 'items' => { 'type' => 'string', 'format' => 'prefixed-id', 'pattern' => '^ch_[A-Za-z0-9]+$', 'x-spree-prefix' => 'ch' },+ 'default' => []+ )+ end++ it 'types money as an exact decimal string, nullable when it has no default' do+ expect(property(Spree::Promotion::Rules::ItemTotal, :amount_min)).to include(+ 'type' => 'string', 'format' => 'money', 'pattern' => described_class::DECIMAL_PATTERN, 'default' => '100.0'+ )+ expect(property(Spree::Promotion::Rules::ItemTotal, :amount_max)['type']).to eq(%w[string null])+ end++ it 'types a keyed hash and a list of objects' do+ expect(property(Spree::Calculator::Shipping::FlatRate, :amounts)).to include(+ 'type' => 'object',+ 'propertyNames' => { 'type' => 'string', 'format' => 'currency', 'pattern' => '^[A-Z]{3}$' },+ 'additionalProperties' => include('format' => 'money')+ )+ expect(property(Spree::Calculator::TieredPercent, :tiers)['items']).to include(+ 'type' => 'object', 'required' => %w[threshold value], 'additionalProperties' => false+ )+ end++ it 'turns choices into an enum' do+ expect(property(Spree::Promotion::Rules::Product, :match_policy)).to include('type' => 'string', 'enum' => %w[any all none])+ end++ it 'marks a secret and never carries its default' do+ secret = property(Spree::Gateway::Bogus, :dummy_secret_key)++ expect(secret).to include('x-spree-secret' => true)+ expect(secret).not_to have_key('default')+ end++ it 'leaves out internal preferences' do+ expect(Spree::Store.preference_json_schema['properties']).not_to have_key('install_id')+ end+ end++ # Every class Spree ships is a contract a client may rely on: its schema+ # compiles, is valid JSON Schema, and states the full type of every value.+ describe 'the declarations Spree ships' do+ let(:classes) do+ Rails.autoloaders.main.eager_load_dir(Spree::Core::Engine.root.join('app/models').to_s)+ ObjectSpace.each_object(Class).select do |klass|+ klass.name.to_s.start_with?('Spree::') && klass.respond_to?(:preference_json_schema) && klass.preference_definitions.any?+ end+ end++ it 'compile to valid JSON Schema' do+ classes.each do |klass|+ schema = klass.preference_json_schema+ expect(schema).to be_present, "#{klass.name} compiled no schema"+ expect(JSONSchemer.valid_schema?(schema)).to be(true), "#{klass.name} compiled an invalid schema"+ end+ end++ it 'state the full type of every value' do+ incomplete = classes.flat_map do |klass|+ klass.preference_definitions.filter_map do |name, definition|+ complete = case definition[:type]+ when :any then false+ when :array then definition[:of].present?+ when :hash then definition[:keys].present? && definition[:values].present?+ else true+ end+ "#{klass.name}##{name}" unless complete || definition[:deprecated]+ end+ end++ expect(incomplete).to be_empty+ end++ it 'validate the values a new record holds' do+ classes.each do |klass|+ next if klass.abstract_class?++ record = klass.new+ schemer = JSONSchemer.schema(klass.preference_json_schema)+ errors = schemer.validate(Spree::Preferences::Masking.serialize(record)).map { |error| error['error'] }++ expect(errors).to be_empty, "#{klass.name}: #{errors.join('; ')}"+ end+ end+ end+enddiff --git a/spree/core/spec/models/spree/preferences/masking_spec.rb b/spree/core/spec/models/spree/preferences/masking_spec.rbindex 0a87515d49..2827e9bd72 100644--- a/spree/core/spec/models/spree/preferences/masking_spec.rb+++ b/spree/core/spec/models/spree/preferences/masking_spec.rb@@ -137,5 +137,14 @@ RSpec.describe Spree::Preferences::Masking do# Sanity check: the unmasked default would have leaked here.expect(result.fetch('api_secret')).not_to eq('SECRET456')end++ it 'returns an id list as prefixed ids, the form a write accepts' do+ channel = create(:channel)+ rule = Spree::PriceRules::ChannelRule.new(price_list: create(:price_list))+ rule.preferred_channel_ids = [channel.prefixed_id]++ expect(rule.preferences[:channel_ids]).to eq([channel.id.to_s])+ expect(described_class.serialize(rule)['channel_ids']).to eq([channel.prefixed_id])+ endendenddiff --git a/spree/core/spec/models/spree/preferences/preferable_spec.rb b/spree/core/spec/models/spree/preferences/preferable_spec.rbindex 1f1b398bbb..23893f0205 100644--- a/spree/core/spec/models/spree/preferences/preferable_spec.rb+++ b/spree/core/spec/models/spree/preferences/preferable_spec.rb@@ -410,6 +410,96 @@ describe Spree::Preferences::Preferable, type: :model doendend+ describe 'typed declarations' do+ let(:preferable_class) do+ Class.new(Spree::Base) do+ self.table_name = 'preferable_spec_records'++ def self.name+ 'TypedPreferable'+ end++ preference :channel_ids, :array, of: :id, model: 'Spree::Channel', default: [],+ scope: ->(_record) { Spree::Store.default.channels }+ preference :quantities, :array, of: :integer, default: []+ preference :amounts, :hash, keys: :currency, values: :money, default: {}+ preference :tiers, :array, of: :object, properties: { threshold: :money, value: :decimal }, default: []+ preference :flavor, :string, default: 'vanilla'+ exposes_preferences :flavor+ end+ end+ let(:record) { preferable_class.new }+ let(:channel) { create(:channel) }++ it 'decodes prefixed ids to the raw primary keys it stores' do+ record.set_preference(:channel_ids, [channel.prefixed_id])+ expect(record.preferences[:channel_ids]).to eq([channel.id.to_s])+ end++ it 'accepts a comma-separated list' do+ record.set_preference(:channel_ids, "#{channel.prefixed_id}, #{channel.id}")+ expect(record.preferences[:channel_ids]).to eq([channel.id.to_s, channel.id.to_s])+ end++ it 'refuses an id carrying another model\'s prefix, even when it decodes to an existing row' do+ market_id = "mkt_#{Spree::PrefixedId::SQIDS.encode([channel.id])}"+ expect { record.set_preference(:channel_ids, [market_id]) }.to raise_error(ActiveRecord::RecordNotFound)+ end++ it 'refuses an id outside the declared scope' do+ other_channel = create(:channel, store: create(:store))+ expect { record.set_preference(:channel_ids, [other_channel.prefixed_id]) }.to raise_error(ActiveRecord::RecordNotFound)+ end++ it 'casts list items to their declared type' do+ record.set_preference(:quantities, ['1', 2])+ expect(record.preferences[:quantities]).to eq([1, 2])+ end++ it 'keeps an item that does not cast, for validation to name' do+ record.set_preference(:quantities, ['many'])+ expect(record.preferences[:quantities]).to eq(['many'])+ end++ it 'stores hash values in their declared type, with currency keys upcased' do+ record.set_preference(:amounts, 'eur' => 15, 'USD' => '9.99')+ expect(record.preferences[:amounts]).to eq('EUR' => '15.0', 'USD' => '9.99')+ end++ it 'keeps only the declared properties of each object, typed' do+ record.set_preference(:tiers, [{ threshold: 100, value: '10', note: 'dropped' }])+ expect(record.preferences[:tiers]).to eq([{ 'threshold' => '100.0', 'value' => '10.0' }])+ end++ it 'exposes a preference under its plain name' do+ expect(record.flavor).to eq('vanilla')+ record.flavor = 'mint'+ expect(record.preferred_flavor).to eq('mint')+ end++ it 'refuses to expose a name that is not a preference or is already a method' do+ expect { preferable_class.exposes_preferences :not_declared }.to raise_error(ArgumentError, /no preference/)+ expect { preferable_class.exposes_preferences :flavor }.to raise_error(ArgumentError, /a method of that name exists/)+ end++ it 'raises for an option that does not fit the type' do+ expect { preferable_class.preference :wrong_of, :string, of: :integer }.to raise_error(ArgumentError, /`of:` applies to an :array/)+ expect { preferable_class.preference :id_without_model, :array, of: :id }.to raise_error(ArgumentError, /needs `model:`/)+ expect { preferable_class.preference :unknown_item, :array, of: :thing }.to raise_error(ArgumentError, /Unknown item type/)+ 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: []+ end++ it 'accepts the legacy `in:` option with a warning' do+ expect(Spree::Deprecation).to receive(:warn).with(/Use `choices:` instead/)+ preferable_class.preference :legacy_choice, :string, in: %w[a b]+ expect(preferable_class.preference_definitions[:legacy_choice][:choices]).to eq(%w[a b])+ end+ end+describe 'persisted preferables' dobefore(:all) doclass CreatePrefTest < ActiveRecord::Migration[4.2]diff --git a/spree/core/spree_core.gemspec b/spree/core/spree_core.gemspecindex 9c9a96d1de..f8d119747f 100644--- a/spree/core/spree_core.gemspec+++ b/spree/core/spree_core.gemspec@@ -49,6 +49,7 @@ Gem::Specification.new do |s|# touching a JSON column raises ArgumentError. Rails' bug, not ours — unpin# once activesupport passes those options as keywords.s.add_dependency 'json', '< 3'+ s.add_dependency 'json_schemer', '~> 2.4's.add_dependency 'jwt', '~> 3.1's.add_dependency 'liquid', '~> 5.14's.add_dependency 'money', '~> 6.13'diff --git a/spree/providers/easypost/app/models/spree_easypost/integration.rb b/spree/providers/easypost/app/models/spree_easypost/integration.rbindex 54b364bfb7..34d031116e 100644--- a/spree/providers/easypost/app/models/spree_easypost/integration.rb+++ b/spree/providers/easypost/app/models/spree_easypost/integration.rb@@ -22,12 +22,12 @@ module SpreeEasyPost# signer takes legal responsibility for the declared contents, so it names# a person at the merchant rather than the store.preference :customs_signer, :string- preference :customs_contents_type, :string, default: 'merchandise', in: CUSTOMS_CONTENTS_TYPES+ preference :customs_contents_type, :string, default: 'merchandise', choices: CUSTOMS_CONTENTS_TYPES# Who pays duties and taxes on arrival. Defaults to DAP — the recipient is# billed by the carrier. DDP bills the merchant instead, so only choose it# once duties are actually collected from the customer at checkout;# otherwise the merchant absorbs them silently.- preference :incoterm, :string, default: 'DAP', in: INCOTERMS+ preference :incoterm, :string, default: 'DAP', choices: INCOTERMSvalidates :preferred_incoterm, inclusion: { in: INCOTERMS }, allow_blank: truevalidates :preferred_customs_contents_type, inclusion: { in: CUSTOMS_CONTENTS_TYPES }, allow_blank: true