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

Damian Legawiec6c5925145334
diff --git a/.changeset/typed-preferences.md b/.changeset/typed-preferences.md
index b0d9d1a3a0..52da7f9e80 100644
--- a/.changeset/typed-preferences.md
+++ b/.changeset/typed-preferences.md
@@ -5,4 +5,4 @@
"@spree/seller-dashboard": minor
---
-Changed preferences to a typed contract. Every `/…/types` entry returns `schema`, the JSON Schema of the type's `preferences`, instead of `preference_schema`, and rows no longer repeat it; `PreferenceField` and `DeliveryPreferenceField` are replaced by `PreferenceSchema`. Each configurable family's settings are typed per `type` (`PromotionRulePreferencesMap`, `TypedPromotionRule`, …), and an extension adds its own by declaration merging. Store, channel, import and seller profile settings drop the `preferred_` prefix (`guest_checkout`, `timezone`, `delimiter`), the store's decimal settings are strings, and delivery methods read and write `calculator: { type, preferences }`. Preference writes are validated, refused with `invalid_preferences` and a JSON pointer per failing value.
+Changed preferences to a typed contract. Every `/…/types` entry returns `schema`, the JSON Schema of the type's `preferences`, instead of `preference_schema`, and rows no longer repeat it; `PreferenceField` and `DeliveryPreferenceField` are replaced by `PreferenceSchema`. Each configurable family's settings are typed per `type` (`PromotionRulePreferencesMap`, `TypedPromotionRule`, …), and an extension adds its own by declaration merging. Store, channel, import and seller profile settings drop the `preferred_` prefix (`guest_checkout`, `timezone`, `delimiter`), the store's decimal settings are strings, and delivery methods read and write `calculator: { type, preferences }`. Preference writes are validated, refused with `invalid_preferences` and a JSON pointer per failing value. `paymentMethods.types()` lists every provider with `installed` set on those the store already has.
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index f8de56a271..810cbe4f4a 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -541,11 +541,11 @@ Settings no longer reach the Admin and Seller APIs in the shape of Ruby's prefer
| Import (Admin and Seller) | `preferred_delimiter` | `delimiter` |
| Seller profile | `preferred_timezone` | `timezone` |
-`order.preferred_stock_location_id` keeps its name: it is an association, not a setting. Validation errors name the field without the prefix too. `preferred_auto_capture` and `preferred_auto_capture_on_dispatch` are no longer accepted; send `capture_method`. The store's `default_minimum_payout_amount` and `default_commission_tax_rate` are now exact decimal strings (`"0.23"`) instead of numbers.
+`order.preferred_stock_location_id` keeps its name: it is an association, not a setting. Validation errors name the field without the prefix too. Writes still accept the old `preferred_*` names until Spree 6.1, with a deprecation warning in the server log; responses only carry the new names. The store's `storefront_url` is the setting as saved, `null` when unset; `url` is the address customer links use. The store's `default_minimum_payout_amount` and `default_commission_tax_rate` are now exact decimal strings (`"0.23"`) instead of numbers.
-**`preference_schema` is replaced by `schema`.** Rules, actions, payment methods and integrations no longer carry `preference_schema` on every row. Each family's `/types` endpoint (and the delivery-method and promotion-action calculator lists) returns a `schema` per type instead: the JSON Schema of its `preferences`, with `format`, `enum`, `default` and `x-spree-secret`. Read a row's type, then look up its schema there.
+**`preference_schema` is replaced by `schema`.** Rules, actions, payment methods and integrations no longer carry `preference_schema` on every row. Each family's `/types` endpoint (and the delivery-method and promotion-action calculator lists) returns a `schema` per type instead: the JSON Schema of its `preferences`, with `format`, `enum`, `default` and `x-spree-secret`. Read a row's type, then look up its schema there. `/payment_methods/types` now lists every provider, with `installed: true` on those the store already has, instead of leaving them out.
-**Writes are validated.** A `preferences` payload with an unknown key, a value of the wrong type, a value outside the declared choices, or an id of another model or another store is refused with a `422` whose `code` is `invalid_preferences`. `details` names each failing value by its JSON pointer (`/preferences/channel_ids/1`). Before, unknown keys were silently dropped. Send decimals as strings (`"10.0"`) and record ids as prefixed ids (`ch_…`).
+**Writes are validated.** A `preferences` payload with an unknown key, a value of the wrong type, a value outside the declared choices, or an id of another model or another store is refused with a `422` whose `code` is `invalid_preferences`. `details` names each failing value by its JSON pointer (`/preferences/channel_ids/1`, or `/rules/0/preferences/channel_ids/1` inside a list of rules). Before, unknown keys were silently dropped. Send decimals as strings (`"10.0"`) and record ids as prefixed ids (`ch_…`).
**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.
diff --git a/docs/plans/6.0-typed-preferences.md b/docs/plans/6.0-typed-preferences.md
index 92927c1151..473c79c41f 100644
--- a/docs/plans/6.0-typed-preferences.md
+++ b/docs/plans/6.0-typed-preferences.md
@@ -44,7 +44,7 @@ Preferences reach the API in two ways, and both expose the Ruby preferences DSL
- **The `preferences` field name stays.** It is plain English, not a Ruby term. The leaks were the untyped values and the `preferred_` prefix.
- **Breaking in 6.0, for every v3 API.** Consistent with the Ruby-class-name change (#14837). Every renamed field and every removed `preference_schema` is listed in the upgrade guide. Inventory (2026-10-09) found the Store API unaffected: the cart's only `preferred_*` field is `preferred_stock_location_id`, which stays, and the seller `profile` belongs to the Seller API.
- **One pull request, one commit series per phase** (decided 2026-10-09). The three phases below are delivered together so every breaking 6.0 change is reviewed and released at once.
-- **`storefront_url` is the store setting's plain name; its reader keeps the fallback** (decided 2026-10-09). Dropping the prefix collides with `Store#storefront_url`. The setting takes the name on the wire and in the model, no second method is introduced, and the reader still answers the first non-loopback allowed origin and then the store's own URL when nothing is set, so customer emails and the product feed never get an empty base URL. Accepted trade-off: a client cannot tell an unset value from a fallback one.
+- **`storefront_url` is the store setting's plain name; its reader keeps the fallback** (decided 2026-10-09, narrowed the same day in review). Dropping the prefix collides with `Store#storefront_url`. The setting takes the name on the wire and in the model, no second method is introduced, and the model's reader still answers the first non-loopback allowed origin and then the store's own URL when nothing is set, so customer emails and the product feed never get an empty base URL. The API's `storefront_url` field returns the stored setting (`null` when unset), while `url` keeps returning the effective address: review found that serving the fallback made the dashboard show a "View store" link for stores without a storefront, and save the fallback back as if the merchant had typed it.
- **Incomplete declarations warn in 6.0 and raise in 6.1** (decided 2026-10-09). An `:array` without `of:`, a `:hash` without `keys:`/`values:`, or `:any` logs a deprecation naming the missing option, and its schema accepts any value for that key, so an un-updated plugin keeps working. Every declaration Spree ships is complete, and a spec enforces it.
- **`exposes_preferences` does not grant write access to anyone** (decided 2026-10-09). It defines the plain model reader and writer only. Each API keeps its own permitted list, and Seller controllers keep using `additional_seller_permitted_attributes`, so exposing a setting never makes it seller-writable.
@@ -58,6 +58,10 @@ Preferences reach the API in two ways, and both expose the Ruby preferences DSL
- **Internal preferences are refused on write.** They are not in the schema, so sending one is an unknown key (422), not a silent no-op.
- **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.
+- **`/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.
- **Validation errors on an exposed setting use its plain name.** A model validates `preferred_<name>`; the API reports the error as `<name>`.
- **`preference_attributes Model, :name, …` in serializers** types each exposed setting from its declaration, so the generated SDK types follow the model. Store decimal settings are now exact strings.
- **`ItemTotal`'s `operator_min`/`operator_max` declare no `choices:` yet.** Their defaults are `>`/`<` while the code compares against `gt`/`gte`; fixing that needs a data upgrade for stored rules and is left for a follow-up.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 9fb058197a..f2534b738f 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -19,7 +19,7 @@
**Context:** Preferences reached the v3 APIs as the Ruby DSL rather than a contract. Store, channel and import settings were exposed as `preferred_*` fields, and every configurable subtype (promotion rules and actions, calculators, payment methods, integrations, rules of every kind) sent an untyped `preferences` object next to a `preference_schema` written in Ruby type names, repeated on every row. The real rules (prefixed-ID decoding, country normalization, rejecting unknown keys) lived in code no client could read.
-**Decision:** The preference declarations stay the single source and become complete (`of:`, `keys:`/`values:`, `money:`, `choices:`, `format:`, `prefix:`). They compile to JSON Schema, which feeds the OpenAPI components, the SDK unions (one member per built-in subtype plus a fallback for plugins), the `/…/types` endpoints (`schema` replaces `preference_schema`, which leaves resource rows) and the validation of every preferences write (422 `invalid_preferences` with a JSON pointer per failure). `preferred_*` fields are renamed to plain names through `exposes_preferences` on the model; `order.preferred_stock_location_id` is an association and stays. The store's `storefront_url` setting takes the plain name and its reader keeps the fallback to the first allowed origin and the store URL. `exposes_preferences` grants no write access; each API keeps its own permitted list. Incomplete declarations in plugins warn and get a permissive schema in 6.0, and raise in 6.1. Delivery methods move to the nested `calculator: { type, preferences }` shape. All three phases ship in one pull request.
+**Decision:** The preference declarations stay the single source and become complete (`of:`, `keys:`/`values:`, `money:`, `choices:`, `format:`, `prefix:`). They compile to JSON Schema, which feeds the OpenAPI components, the SDK unions (one member per built-in subtype plus a fallback for plugins), the `/…/types` endpoints (`schema` replaces `preference_schema`, which leaves resource rows) and the validation of every preferences write (422 `invalid_preferences` with a JSON pointer per failure). `preferred_*` fields are renamed to plain names through `exposes_preferences` on the model; `order.preferred_stock_location_id` is an association and stays. The store's `storefront_url` setting takes the plain name; the model's reader keeps the fallback to the first allowed origin and the store URL, while the API returns the stored setting and `url` carries the effective address. Old `preferred_*` keys are accepted on write until 6.1 with a deprecation warning. `exposes_preferences` grants no write access; each API keeps its own permitted list. Incomplete declarations in plugins warn and get a permissive schema in 6.0, and raise in 6.1. Delivery methods move to the nested `calculator: { type, preferences }` shape. All three phases ship in one pull request.
**Consequences:** A new preference declares its full type and never uses `:any`; an ID list is `of: :id, prefix:`, never a decoding lambda; no serializer or permitted list gains a `preferred_*` name or a `preference_schema`; a new configurable family publishes a `/…/types` endpoint and a typed union with a fallback member. The Store API is unaffected; the Admin and Seller APIs break, and every rename is listed in the upgrade guide.
diff --git a/packages/dashboard-core/src/components/preferences-form.tsx b/packages/dashboard-core/src/components/preferences-form.tsx
index dd45cec5f8..2d1ca5da69 100644
--- a/packages/dashboard-core/src/components/preferences-form.tsx
+++ b/packages/dashboard-core/src/components/preferences-form.tsx
@@ -356,25 +356,17 @@ export function PreferenceField({
return (
<Field>
<FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
- <Input
+ <NumberPreferenceInput
id={id}
- type="number"
- step={field.type === 'integer' ? 1 : 'any'}
+ integer={field.type === 'integer'}
+ nullable={!!field.nullable}
// An empty optional field means "no limit" — surface that
// rather than leaving it looking like a required blank.
placeholder={
field.nullable ? t('admin.components.preferences_form.unlimited') : undefined
}
- value={value === null || value === undefined ? '' : String(value)}
- onChange={(e) => {
- const raw = e.target.value
- if (raw === '') return onChange(null)
- // A decimal (an amount, a percentage) stays the canonical string
- // the number input yields; the API refuses money sent as a JSON number.
- if (field.type === 'decimal') return onChange(isDecimalString(raw) ? raw : null)
- const parsed = parseInt(raw, 10)
- onChange(Number.isNaN(parsed) ? null : parsed)
- }}
+ value={value}
+ onChange={onChange}
/>
</Field>
)
@@ -467,6 +459,63 @@ export function PreferenceField({
}
}
+/**
+ * A number setting. Keeps what is typed locally and passes on only values the
+ * server accepts: decimals as exact strings (`.5` becomes `0.5`), integers as
+ * numbers, and an empty field as `null` only when the setting may be unset —
+ * a required one keeps its last value until a number is typed.
+ */
+function NumberPreferenceInput({
+ id,
+ integer,
+ nullable,
+ placeholder,
+ value,
+ onChange,
+}: {
+ id: string
+ integer: boolean
+ nullable: boolean
+ placeholder?: string
+ value: unknown
+ onChange: (value: unknown) => void
+}) {
+ const external = value === null || value === undefined ? '' : String(value)
+ const [text, setText] = useState(external)
+ const [lastExternal, setLastExternal] = useState(external)
+ if (external !== lastExternal) {
+ setLastExternal(external)
+ setText(external)
+ }
+
+ function commit(raw: string) {
+ setText(raw)
+ const trimmed = raw.trim()
+ if (trimmed === '') {
+ if (nullable) onChange(null)
+ return
+ }
+ const number = Number(trimmed)
+ if (!Number.isFinite(number)) return
+ if (integer) {
+ if (Number.isInteger(number)) onChange(number)
+ return
+ }
+ onChange(new RegExp(DECIMAL_PATTERN).test(trimmed) ? trimmed : String(number))
+ }
+
+ return (
+ <Input
+ id={id}
+ type="number"
+ step={integer ? 1 : 'any'}
+ placeholder={placeholder}
+ value={text}
+ onChange={(e) => commit(e.target.value)}
+ />
+ )
+}
+
function humanizeKey(key: string): string {
return key
.split('_')
diff --git a/packages/dashboard/src/components/spree/payment-method-editors/payment-method-sheets.tsx b/packages/dashboard/src/components/spree/payment-method-editors/payment-method-sheets.tsx
index 4677405895..676df1e36e 100644
--- a/packages/dashboard/src/components/spree/payment-method-editors/payment-method-sheets.tsx
+++ b/packages/dashboard/src/components/spree/payment-method-editors/payment-method-sheets.tsx
@@ -20,6 +20,7 @@ import {
useUpdatePaymentMethod,
} from '../../../hooks/use-payment-methods'
import {
+ filterPaymentMethodProviderTypes,
PAYMENT_METHOD_BASE_DEFAULTS,
PAYMENT_METHOD_CREATE_DEFAULTS,
paymentMethodBaseFormSchema,
@@ -56,7 +57,7 @@ export function CreatePaymentMethodSheet({
const createMutation = useCreatePaymentMethod()
const { data: typesResponse, isLoading: loadingTypes } = usePaymentMethodTypes()
const providerTypes = useMemo(
- () => (typesResponse?.data ?? []).filter((type) => !type.installed),
+ () => filterPaymentMethodProviderTypes(typesResponse?.data ?? []),
[typesResponse],
)
// Seed `currency`-typed preferences with the store default so the merchant
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx
index 220a73e666..2c8434b9d2 100644
--- a/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx
+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx
@@ -11,6 +11,7 @@ import {
type adminClient,
Can,
currencyParts,
+ defaultPreferences,
PreferencesForm,
ResourceMultiAutocomplete,
Subject,
@@ -1070,7 +1071,18 @@ function PricingCard({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }
<Select
items={calculatorOptions}
value={field.value ?? ''}
- onValueChange={field.onChange}
+ onValueChange={(next) => {
+ field.onChange(next)
+ // Each calculator declares its own settings, and the server
+ // refuses any it does not, so a switch starts from the new
+ // calculator's defaults rather than the old one's values.
+ const schema = (calculators?.data ?? []).find((c) => c.type === next)?.schema
+ form.setValue(
+ 'calculator.preferences',
+ schema ? defaultPreferences(schema, { currency: defaultCurrency }) : {},
+ { shouldDirty: true },
+ )
+ }}
>
<SelectTrigger id="calculator-type">
<SelectValue />
diff --git a/packages/dashboard/src/hooks/use-payment-methods.ts b/packages/dashboard/src/hooks/use-payment-methods.ts
index 94677478fb..46d5fb5dfb 100644
--- a/packages/dashboard/src/hooks/use-payment-methods.ts
+++ b/packages/dashboard/src/hooks/use-payment-methods.ts
@@ -12,18 +12,16 @@ import {
} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import i18n from 'i18next'
-import { filterPaymentMethodProviderTypes } from '../schemas/payment-method'
export function usePaymentMethodTypes({ enabled = true }: { enabled?: boolean } = {}) {
- // Store-scoped because the server filters out providers already installed
- // on the current store. Matches the +['payment-methods', 'types']+ shape
+ // Every provider, with `installed` set for those this store already has:
+ // pickers filter (see `filterPaymentMethodProviderTypes`), while an edit form
+ // reads an installed provider's schema from the same list. Store-scoped
+ // because `installed` is. Matches the +['payment-methods', 'types']+ shape
// that +useResourceMutation+ expands to +['payment-methods', storeId, 'types']+.
return useQuery({
queryKey: useResourceKey('payment-methods', 'types'),
- queryFn: async () => {
- const response = await adminClient.paymentMethods.types()
- return { ...response, data: filterPaymentMethodProviderTypes(response.data) }
- },
+ queryFn: () => adminClient.paymentMethods.types(),
staleTime: Infinity,
enabled,
})
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx
index 2e2595e62d..4d26894495 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx
@@ -39,6 +39,7 @@ import {
usePaymentMethodTypes,
useUpdatePaymentMethod,
} from '../../../../hooks/use-payment-methods'
+import { filterPaymentMethodProviderTypes } from '../../../../schemas/payment-method'
const PAYMENTS_GROUP = 'payments'
const ALL_TAB = 'all'
@@ -98,12 +99,11 @@ function IntegrationsPage() {
: [],
[canReadPayments, paymentMethodsResponse],
)
- // The server already leaves out providers installed on this store, so
- // these are only the ones still to set up.
+ // Only the providers still to set up: not installed on this store yet.
const availablePaymentTypes = useMemo(
() =>
- (paymentTypesResponse?.data ?? []).filter(
- (type) => type.third_party && !type.superseded && !type.installed,
+ filterPaymentMethodProviderTypes(paymentTypesResponse?.data ?? []).filter(
+ (type) => type.third_party && !type.superseded,
),
[paymentTypesResponse],
)
diff --git a/packages/dashboard/src/schemas/payment-method.test.ts b/packages/dashboard/src/schemas/payment-method.test.ts
index 45e595c574..02375c91f5 100644
--- a/packages/dashboard/src/schemas/payment-method.test.ts
+++ b/packages/dashboard/src/schemas/payment-method.test.ts
@@ -23,4 +23,14 @@ describe('filterPaymentMethodProviderTypes', () => {
expect(filterPaymentMethodProviderTypes(types).map((t) => t.type)).toEqual(['stripe', 'check'])
})
+
+ it('removes providers this store already has installed', () => {
+ const schema = { type: 'object' as const, properties: {}, additionalProperties: false as const }
+ const types = [
+ { type: 'stripe', label: 'Stripe', schema, installed: true },
+ { type: 'check', label: 'Check', schema, installed: false },
+ ]
+
+ expect(filterPaymentMethodProviderTypes(types).map((t) => t.type)).toEqual(['check'])
+ })
})
diff --git a/packages/dashboard/src/schemas/payment-method.ts b/packages/dashboard/src/schemas/payment-method.ts
index cbacb339b2..68acb93ddb 100644
--- a/packages/dashboard/src/schemas/payment-method.ts
+++ b/packages/dashboard/src/schemas/payment-method.ts
@@ -41,9 +41,12 @@ export const PAYMENT_METHOD_CREATE_DEFAULTS: PaymentMethodFormValues = {
/** Wire `type` values that must not appear in the add-payment-method provider picker. */
export const PAYMENT_METHOD_TYPES_HIDDEN_FROM_PICKER = ['custom_payment_source_method'] as const
-export function filterPaymentMethodProviderTypes<T extends { type: string }>(types: T[]): T[] {
+/** The providers a merchant may add: not hidden, and not already installed on this store. */
+export function filterPaymentMethodProviderTypes<T extends { type: string; installed?: boolean }>(
+ types: T[],
+): T[] {
const hidden = new Set<string>(PAYMENT_METHOD_TYPES_HIDDEN_FROM_PICKER)
- return types.filter((entry) => !hidden.has(entry.type))
+ return types.filter((entry) => !hidden.has(entry.type) && !entry.installed)
}
export function paymentMethodValuesToCreateParams(
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
new file mode 100644
index 0000000000..a069a4d608
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/legacy_preference_params.rb
@@ -0,0 +1,32 @@
+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.
+ module LegacyPreferenceParams
+ extend ActiveSupport::Concern
+
+ class_methods do
+ # @param model [Class] the model whose exposed preferences the controller writes
+ def accepts_legacy_preference_params(model)
+ before_action(if: -> { request.post? || request.patch? || request.put? }) { translate_legacy_preference_params(model) }
+ end
+ end
+
+ private
+
+ def translate_legacy_preference_params(model)
+ params.keys.each do |key|
+ name = key.to_s.delete_prefix('preferred_')
+ next if name == key.to_s || params.key?(name) || !model.exposed_preference?(name)
+
+ Spree::Deprecation.warn("The `#{key}` parameter is deprecated and will be removed in Spree 6.1. Send `#{name}` instead.")
+ params[name] = params.delete(key)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
index aba29705f4..619fb53236 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
@@ -3,6 +3,10 @@ module Spree
module V3
module Admin
class ChannelsController < ResourceController
+ include Spree::Api::V3::LegacyPreferenceParams
+
+ accepts_legacy_preference_params Spree::Channel
+
scoped_resource :settings
# POST /api/v3/admin/channels/:id/add_products
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 ca9932c352..3bf0c0a28e 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
@@ -228,7 +228,11 @@ module Spree
delivery_method.ensure_calculator
return if delivery_method.calculator.nil?
- delivery_method.calculator.assign_preferences(preferences)
+ begin
+ delivery_method.calculator.assign_preferences(preferences)
+ rescue Spree::Preferences::InvalidPreferences => e
+ raise e.within('/calculator')
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
index 8c0ca22560..c45491b214 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
@@ -11,6 +11,10 @@ module Spree
# Spree::Import.required_scope). The index is filtered to the types
# the key can write.
class ImportsController < ResourceController
+ include Spree::Api::V3::LegacyPreferenceParams
+
+ accepts_legacy_preference_params Spree::Import
+
include ActiveStorage::SetCurrent
# The index spans many import types — `scope` filters it to the
diff --git a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
index 8cc53d8605..deee8628dd 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
@@ -19,7 +19,7 @@ module Spree
# create picker leaves those out so a provider is not installed
# twice, and the edit form still finds an installed one's schema.
def types
- authorize! :create, model_class
+ authorize! :show, model_class
installed_class_names = current_store.payment_methods.pluck(:type)
installed_shorthands = installed_class_names.filter_map do |name|
diff --git a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
index a89bdb070f..53a70aaaba 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
@@ -3,7 +3,10 @@ module Spree
module V3
module Admin
class StoreController < Admin::BaseController
+ include Spree::Api::V3::LegacyPreferenceParams
+
scoped_resource :settings
+ accepts_legacy_preference_params Spree::Store
# Reading the current store is shell data — the dashboard needs the
# name, logo, timezone, currency and locales to render anything at
@@ -85,6 +88,10 @@ module Spree
:address_requires_company,
:address_requires_phone,
:capture_method,
+ # @deprecated Superseded by capture_method; the model maps them
+ # onto it. Removed in 6.1.
+ :preferred_auto_capture,
+ :preferred_auto_capture_on_dispatch,
:track_inventory_levels,
:stock_reservations_enabled,
:low_stock_threshold,
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 f92cf74641..dedc4251aa 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
@@ -251,7 +251,11 @@ module Spree
delivery_method.ensure_calculator
return if delivery_method.calculator.nil?
- delivery_method.calculator.assign_preferences(preferences)
+ begin
+ delivery_method.calculator.assign_preferences(preferences)
+ rescue Spree::Preferences::InvalidPreferences => e
+ raise e.within('/calculator')
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/imports_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/imports_controller.rb
index d363e4f811..a43f160d4d 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/imports_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/imports_controller.rb
@@ -22,6 +22,10 @@ module Spree
# says; a seller reaches `active` only through review
# (docs/plans/6.0-seller-product-submission.md).
class ImportsController < Seller::ResourceController
+ include Spree::Api::V3::LegacyPreferenceParams
+
+ accepts_legacy_preference_params Spree::Import
+
include ActiveStorage::SetCurrent
# The import types a seller may run. An operator's `customers` or
diff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
index aed3c7af70..4bd9bfdc2f 100644
--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
@@ -89,7 +89,8 @@ module Spree
# Declares a model's settings under their plain names (see
# `exposes_preferences`), typed from their declarations so the
- # generated SDK types never drift from the model.
+ # generated SDK types never drift from the model. Each reads the
+ # stored setting, never a reader the model overrides with a fallback.
#
# preference_attributes Spree::Store, :guest_checkout, :timezone
def self.preference_attributes(model, *names)
@@ -97,7 +98,7 @@ module Spree
names.each do |name|
typelize name => preference_type_hint(Spree::PreferenceSchema::JsonSchema.property_schema(definitions.fetch(name)))
attribute(name) do |object|
- value = object.public_send(name)
+ value = object.public_send(:"preferred_#{name}")
value.is_a?(BigDecimal) ? value.to_s('F') : value
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/commission_rates_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/commission_rates_controller_spec.rb
index 6a9f088dae..da0a4a899c 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/commission_rates_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/commission_rates_controller_spec.rb
@@ -150,7 +150,7 @@ RSpec.describe Spree::Api::V3::Admin::CommissionRatesController, type: :controll
expect(response).to have_http_status(:unprocessable_content)
expect(json_response['error']['code']).to eq('invalid_preferences')
- expect(json_response['error']['details']).to have_key('/preferences/seller_ids')
+ expect(json_response['error']['details']).to have_key('/rules/0/preferences/seller_ids')
expect(rate.reload.commission_rules.map(&:class)).to eq([Spree::CommissionRules::SellerRule])
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
index bb03807f41..ecc4d5862d 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
@@ -19,6 +19,17 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
expect(response).to have_http_status(:ok)
end
+ # `url` is where customer links point; `storefront_url` is the setting
+ # itself, so an unset one is null rather than the fallback.
+ it 'returns the storefront url setting as stored, not its fallback' do
+ allow_any_instance_of(Spree::Store).to receive(:preferred_storefront_url).and_return(nil)
+
+ subject
+
+ expect(json_response['storefront_url']).to be_nil
+ expect(json_response['url']).to be_present
+ end
+
# The dashboard shell (store name, logo, timezone, currencies, locales)
# can't render without this, so reading the store is not gated on the
# settings permission — only writing is.
@@ -342,6 +353,21 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
end
end
+ context 'with a pre-6.0 preferred_ key' do
+ let(:params) { { preferred_guest_checkout: false } }
+
+ it 'still saves it for one release, with a deprecation warning' do
+ expect(Spree::Deprecation).to receive(:warn).with(/`preferred_guest_checkout` parameter is deprecated/)
+
+ subject
+
+ expect(response).to have_http_status(:ok)
+ expect(store.reload.preferred_guest_checkout).to eq(false)
+ expect(json_response).to include('guest_checkout' => false)
+ expect(json_response).not_to have_key('preferred_guest_checkout')
+ end
+ end
+
context 'with address params' do
let(:params) { { company_field_enabled: true, address_requires_phone: true } }
diff --git a/spree/core/app/models/concerns/spree/calculated_adjustments.rb b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
index 0655c0e8a2..b57eae51f5 100644
--- a/spree/core/app/models/concerns/spree/calculated_adjustments.rb
+++ b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
@@ -42,7 +42,11 @@ module Spree
return if calculator.nil? || attrs[:preferences].blank?
- calculator.assign_preferences(attrs[:preferences])
+ begin
+ calculator.assign_preferences(attrs[:preferences])
+ rescue Spree::Preferences::InvalidPreferences => e
+ raise e.within('/calculator')
+ end
end
private
diff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rb
index 1555797406..ce6475c8b5 100644
--- a/spree/core/app/models/concerns/spree/preference_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema.rb
@@ -78,8 +78,10 @@ module Spree
# @return [Array<Hash{Symbol => String}>] `{ pointer:, message: }` per failure, empty when it matches
def preference_failures(values)
schema = preference_json_schema
- return [] if schema.nil?
-
+ # Rebuilt whenever the schema is, so a schema computed before the
+ # database was up is not validated against for the life of the process.
+ @preference_schemer = nil unless @preference_schemer_source.equal?(schema)
+ @preference_schemer_source = schema
@preference_schemer ||= JSONSchemer.schema(schema)
@preference_schemer.validate(values).map do |error|
{ pointer: error['data_pointer'], message: error['error'] }
diff --git a/spree/core/app/models/concerns/spree/typed_associations.rb b/spree/core/app/models/concerns/spree/typed_associations.rb
index 7544702f94..010e9e3006 100644
--- a/spree/core/app/models/concerns/spree/typed_associations.rb
+++ b/spree/core/app/models/concerns/spree/typed_associations.rb
@@ -53,7 +53,7 @@ module Spree
def reconcile_typed_association(association, rows)
collection = public_send(association)
- kept_ids = rows.filter_map { |row| save_typed_association_row(collection, row) }
+ kept_ids = rows.each_with_index.filter_map { |row, index| save_typed_association_row(collection, row, "/#{association.to_s.split('_').last}/#{index}") }
if kept_ids.any? || rows.empty?
collection.where.not(id: kept_ids).destroy_all
# `where.not(...).destroy_all` deletes the dropped rows from the DB but
@@ -64,7 +64,8 @@ module Spree
end
end
- def save_typed_association_row(collection, row)
+ # @param pointer [String] where the row sits in the request, e.g. `/rules/1`
+ def save_typed_association_row(collection, row, pointer)
record = find_or_build_typed_association_row(collection, row)
return nil unless record
@@ -78,8 +79,12 @@ module Spree
deferred_ids, scalar_attrs = attrs.partition { |k, _| record.new_record? && k.to_s.end_with?('_ids') }
record.assign_attributes(scalar_attrs.to_h) if scalar_attrs.any?
- record.assign_preferences(preferences) if preferences
- record.assign_calculator_attributes(calculator) if calculator.present? && record.respond_to?(:assign_calculator_attributes)
+ begin
+ record.assign_preferences(preferences) if preferences
+ record.assign_calculator_attributes(calculator) if calculator.present? && record.respond_to?(:assign_calculator_attributes)
+ rescue Spree::Preferences::InvalidPreferences => e
+ raise e.within(pointer)
+ end
# Always save — `record.changed?` doesn't reflect preferences
# (serialized hash) or calculator association changes.
diff --git a/spree/core/lib/spree/core/preferences/invalid_preferences.rb b/spree/core/lib/spree/core/preferences/invalid_preferences.rb
index 2e55c9a4e2..352fc83aac 100644
--- a/spree/core/lib/spree/core/preferences/invalid_preferences.rb
+++ b/spree/core/lib/spree/core/preferences/invalid_preferences.rb
@@ -8,10 +8,20 @@ module Spree
attr_reader :failures
# @param failures [Array<Hash{Symbol => String}>] pointers relative to the preferences object
- def initialize(failures)
- @failures = failures.map { |failure| failure.merge(pointer: "/preferences#{failure[:pointer]}") }
+ # @param prefix [String] where the preferences object sits in the request
+ def initialize(failures, prefix: '/preferences')
+ @failures = failures.map { |failure| failure.merge(pointer: "#{prefix}#{failure[:pointer]}") }
super(@failures.map { |failure| "#{failure[:pointer]}: #{failure[:message]}" }.join('; '))
end
+
+ # The same failures, for preferences nested deeper in the request — a
+ # rule in a list (`/rules/1`) or a calculator (`/calculator`).
+ #
+ # @param prefix [String]
+ # @return [InvalidPreferences]
+ def within(prefix)
+ self.class.new(failures, prefix: prefix)
+ end
end
end
end
diff --git a/spree/core/lib/spree/core/preferences/masking.rb b/spree/core/lib/spree/core/preferences/masking.rb
index 70f94adf71..5fcfe2c90e 100644
--- a/spree/core/lib/spree/core/preferences/masking.rb
+++ b/spree/core/lib/spree/core/preferences/masking.rb
@@ -86,7 +86,13 @@ module Spree
value = preferable.stored_preference(field[:key]) { nil }
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)
+ if definition[:of] == :id
+ prefixed_ids(value, definition)
+ elsif %i[password money].include?(field[:type])
+ wire_value(preferable, field[:type], value)
+ else
+ preferable.wire_preference_value(value, definition)
+ end
end
end
diff --git a/spree/core/lib/spree/core/preferences/preferable.rb b/spree/core/lib/spree/core/preferences/preferable.rb
index d8e2e1060b..7a0b75ce07 100644
--- a/spree/core/lib/spree/core/preferences/preferable.rb
+++ b/spree/core/lib/spree/core/preferences/preferable.rb
@@ -178,6 +178,22 @@ module Spree::Preferences::Preferable
end
end
+ # 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.
+ #
+ # @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 value if value.nil? || definition[:of] == :id
+ return value if definition[:type] == :array && !value.is_a?(Array)
+
+ cast_preference_contents(value, definition)
+ end
+
# Names of the preferences the last save changed, secrets included.
#
# @return [Array<Symbol>]
diff --git a/spree/core/spec/models/spree/commission_rate_spec.rb b/spree/core/spec/models/spree/commission_rate_spec.rb
index 509325105b..768aa447e7 100644
--- a/spree/core/spec/models/spree/commission_rate_spec.rb
+++ b/spree/core/spec/models/spree/commission_rate_spec.rb
@@ -360,7 +360,7 @@ RSpec.describe Spree::CommissionRate, type: :model do
expect {
rate.update!(rules: [{ type: 'seller_rule', preferences: { seller_ids: [foreign_seller.prefixed_id] } }])
- }.to raise_error(Spree::Preferences::InvalidPreferences, %r{/preferences/seller_ids})
+ }.to raise_error(Spree::Preferences::InvalidPreferences, %r{/rules/0/preferences/seller_ids})
end
it 'builds rules on a rate that does not exist yet' do
diff --git a/spree/core/spec/models/spree/preferences/masking_spec.rb b/spree/core/spec/models/spree/preferences/masking_spec.rb
index 2827e9bd72..82ee74274a 100644
--- a/spree/core/spec/models/spree/preferences/masking_spec.rb
+++ b/spree/core/spec/models/spree/preferences/masking_spec.rb
@@ -138,6 +138,16 @@ RSpec.describe Spree::Preferences::Masking do
expect(result.fetch('api_secret')).not_to eq('SECRET456')
end
+ it 'returns amounts stored as numbers before preferences were typed as exact strings' do
+ calculator = Spree::Calculator::Shipping::FlatRate.new
+ calculator.preferences = calculator.preferences.merge('amounts' => { 'EUR' => 12.5 }, 'amount' => 3)
+
+ result = described_class.serialize(calculator)
+
+ expect(result['amounts']).to eq('EUR' => '12.5')
+ expect(result['amount']).to eq('3.0')
+ 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))