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.

Changed preferences to a typed contract in the Admin and Seller APIs

Damian Legawiec3001ebf19fa8
diff --git a/.changeset/typed-preferences.md b/.changeset/typed-preferences.md
new file mode 100644
index 0000000000..b0d9d1a3a0
--- /dev/null
+++ b/.changeset/typed-preferences.md
@@ -0,0 +1,8 @@
+---
+"@spree/admin-sdk": minor
+"@spree/seller-sdk": minor
+"@spree/dashboard": minor
+"@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.
diff --git a/docs/changelog.mdx b/docs/changelog.mdx
index 95fb6836ef..af10e822d3 100644
--- a/docs/changelog.mdx
+++ b/docs/changelog.mdx
@@ -39,6 +39,17 @@ Keep up with the latest features and improvements in Spree Commerce!
**Learn more:** [Upgrade guide](/developer/upgrades/5.6-to-6.0#money)
</Update>
+<Update label="Typed settings in the Admin API" description="October 9, 2026" tags={["Developers", "API"]}>
+ Every configurable part of Spree — promotion rules and actions, calculators, payment methods, integrations, and price, delivery, commission and order routing rules — now publishes exactly what its settings look like, and the API checks every change against it.
+
+ - Each type's `/types` entry carries a JSON Schema of its settings, so a dashboard, an integration or an AI agent can build a form or a payload for any type, including ones your extensions add.
+ - The TypeScript SDKs type the settings of every type Spree ships, narrowed by `type`.
+ - A setting with an unknown name, a wrong type or another store's record is refused with a message naming the exact value, instead of being silently dropped.
+ - Store, channel and import settings are read and written under plain names (`guest_checkout` instead of `preferred_guest_checkout`).
+
+ This is a breaking change for Admin and Seller API clients. **Learn more:** [Upgrade guide](/developer/upgrades/5.6-to-6.0#preferences-are-typed-in-the-api) · [Model preferences](/developer/customization/model-preferences#preferences-in-the-api)
+</Update>
+
<Update label="Email template editor" description="October 6, 2026" tags={["Emails", "Dashboard"]}>
Merchants can now change what their customer emails say and how they look, right in the dashboard, without asking a developer. Order confirmations, shipping notifications, refunds, password resets, the layout around every email and the shared blocks such as item rows are all editable under **Settings → Emails → Templates**.
diff --git a/docs/developer/core-concepts/calculators.mdx b/docs/developer/core-concepts/calculators.mdx
index ece0cc53af..d5946417fb 100644
--- a/docs/developer/core-concepts/calculators.mdx
+++ b/docs/developer/core-concepts/calculators.mdx
@@ -83,8 +83,8 @@ const calculators = await adminClient.deliveryMethods.calculators()
await adminClient.deliveryMethods.create({
name: 'Standard shipping',
delivery_zone_id: 'dz_xxx',
- calculator_type: 'flat_rate',
- calculator_attributes: {
+ calculator: {
+ type: 'flat_rate',
preferences: { amount: '7.00', currency: 'USD' },
},
})
diff --git a/docs/developer/core-concepts/channels.mdx b/docs/developer/core-concepts/channels.mdx
index 38298994b8..91ce5b8971 100644
--- a/docs/developer/core-concepts/channels.mdx
+++ b/docs/developer/core-concepts/channels.mdx
@@ -38,7 +38,7 @@ erDiagram
| `default` | Exactly one channel per store is the default. Used as a fallback when no channel header is present and as the auto-publish target for new products | `true` |
| `storefront_access` | Controls what an anonymous visitor may see: `public`, `prices_hidden`, or `login_required`. Unset inherits the store's setting. See [Storefront Access Gating](#storefront-access-gating) | `login_required` |
| `guest_checkout` | Whether an order may be placed without an account on this channel. Unset inherits the store's setting | `false` |
-| `preferred_order_routing_strategy` | Optional per-channel override of the store's [Order Routing](/developer/how-to/custom-order-routing) strategy | `rules` |
+| `order_routing_strategy` | Optional per-channel override of the store's [Order Routing](/developer/how-to/custom-order-routing) strategy | `rules` |
`code` is normalized to a URL-safe slug on save — `POS` becomes `pos`, `Point of Sale!` becomes `point-of-sale`. Leaving `code` blank derives it from `name`.
@@ -135,13 +135,13 @@ Both controls fall back to the owning [Store](/developer/core-concepts/stores) w
```typescript Admin SDK
// Gate a channel behind sign-in, and require accounts at checkout
await adminClient.channels.update('ch_wholesale', {
- preferred_storefront_access: 'login_required',
- preferred_guest_checkout: false,
+ storefront_access: 'login_required',
+ guest_checkout: false,
})
// Clear the channel value to inherit the store's default
await adminClient.channels.update('ch_wholesale', {
- preferred_storefront_access: null,
+ storefront_access: null,
})
```
@@ -149,7 +149,7 @@ await adminClient.channels.update('ch_wholesale', {
curl -X PATCH 'https://api.mystore.com/api/v3/admin/channels/ch_wholesale' \
-H 'X-Spree-API-Key: sk_xxx' \
-H 'Content-Type: application/json' \
- -d '{ "preferred_storefront_access": "login_required", "preferred_guest_checkout": false }'
+ -d '{ "storefront_access": "login_required", "guest_checkout": false }'
```
</CodeGroup>
diff --git a/docs/developer/core-concepts/pricing.mdx b/docs/developer/core-concepts/pricing.mdx
index 77741c0ab3..d124038784 100644
--- a/docs/developer/core-concepts/pricing.mdx
+++ b/docs/developer/core-concepts/pricing.mdx
@@ -312,14 +312,14 @@ Price history tracking is enabled by default. To disable it (e.g., for non-EU st
<CodeGroup>
```typescript Admin SDK
-await client.store.update({ preferred_track_price_history: false })
+await client.store.update({ track_price_history: false })
```
```bash cURL
curl -X PATCH 'https://api.mystore.com/api/v3/admin/store' \
-H 'X-Spree-API-Key: sk_xxx' \
-H 'Content-Type: application/json' \
- -d '{ "preferred_track_price_history": false }'
+ -d '{ "track_price_history": false }'
```
</CodeGroup>
diff --git a/docs/developer/customization/model-preferences.mdx b/docs/developer/customization/model-preferences.mdx
index 4ec5d5bafc..45621bd259 100644
--- a/docs/developer/customization/model-preferences.mdx
+++ b/docs/developer/customization/model-preferences.mdx
@@ -39,6 +39,64 @@ end
Any model inheriting from `Spree.base_class` can declare preferences — the reader and writer methods come with it, so there is nothing to include. The values live in that model's `preferences` column.
+### Declaring the full type
+
+A declaration is also the preference's contract in the API: Spree turns it into a JSON Schema that the API publishes, the SDKs type and every write is checked against. So a declaration states everything a client needs to know about the value:
+
+```ruby server/app/models/my_app/promotion/rules/loyalty_tier.rb
+module MyApp
+ module Promotion
+ module Rules
+ class LoyaltyTier < Spree::PromotionRule
+ preference :minimum_spend, :decimal, money: true, default: 0
+ preference :tier, :string, choices: %w[silver gold platinum], default: 'silver'
+ preference :channel_ids, :array, of: :id, model: 'Spree::Channel', default: [],
+ scope: ->(rule) { rule.promotion.store.channels }
+ preference :country_codes, :array, of: :string, format: :iso_country, default: []
+ preference :bonus_amounts, :hash, keys: :currency, values: :money, default: {}
+ end
+ end
+ end
+end
+```
+
+| Option | Applies to | What it says |
+|---|---|---|
+| `of:` | `:array` | The type of each item: `:string`, `:integer`, `:decimal`, `:money`, `:boolean`, `:id` or `:object` |
+| `properties:` | `of: :object` | The fields of each item, e.g. `{ threshold: :money, value: :decimal }` |
+| `keys:` / `values:` | `:hash` | The type of the keys (`:string` or `:currency`) and of the values |
+| `model:` / `scope:` | `of: :id` | The records the ids point at, and the records they must be found in. The API accepts and returns their prefixed ids (`ch_…`); an id of another model, or one outside the scope, is refused |
+| `money:` | `:decimal` | The value is an amount of money |
+| `format:` | `:string`, list items | `:currency`, `:iso_country`, `:timezone`, `:locale`, `:url` or `:color` |
+| `choices:` | any | The fixed set the value must come from; admin forms show a picker |
+
+Decimals and amounts travel as exact strings (`"9.99"`), never as numbers. An `:array` without `of:`, a `:hash` without `keys:` and `values:`, or the `:any` type still works in Spree 6.0, with a deprecation warning and a schema that accepts any value. Spree 6.1 refuses them.
+
+### Preferences in the API
+
+Configurable types — promotion rules and actions, calculators, payment methods, integrations, and price, delivery, commission and order routing rules — send their settings as a `preferences` object next to their `type`. Each family's `/types` endpoint returns the JSON Schema of every registered type's preferences, extensions included, so a client can render a form for a type it has never seen:
+
+<CodeGroup>
+
+```typescript Admin SDK
+const { data } = await adminClient.promotionRules.types()
+const itemTotal = data.find((entry) => entry.type === 'item_total')
+itemTotal.schema.properties.amount_min // { type: 'string', format: 'money', default: '100.0', … }
+```
+
+```bash cURL
+curl 'https://api.mystore.com/api/v3/admin/promotion_rules/types' \
+ -H 'X-Spree-API-Key: sk_xxx'
+```
+
+</CodeGroup>
+
+The SDKs also type the settings of every type Spree ships. `TypedPromotionRule` narrows `preferences` by `type`, and an extension adds its own types to `PromotionRulePreferencesMap` by declaration merging.
+
+A write is checked against the schema before anything is saved. An unknown key, a value of the wrong type, a value outside `choices`, or an id of the wrong model or another store is refused with a `422` whose `code` is `invalid_preferences`; `details` names each failing value by its JSON pointer, such as `/preferences/channel_ids/1`. A secret reads back masked; sending the masked value back keeps the stored secret, and `null` clears it.
+
+Settings of a single resource, such as the store's, are read and written under their plain names (`guest_checkout`, `timezone`), never the `preferred_` methods. A model gives a preference that name with `exposes_preferences :guest_checkout, :timezone`; the API controller still lists what it accepts.
+
## Accessing Model Preferences
Once preferences have been defined for a model, they can be accessed either using the shortcut methods that are generated for each preference or the generic methods that are not specific to a particular preference.
@@ -147,5 +205,4 @@ Around fifty models use preferences, and the pattern is always the same: a famil
| `Spree::PriceRules` and `Spree::DeliveryMethodRules` | When a price list or a delivery method applies |
| `Spree::Store`, `Spree::Channel` and `Spree::Market` | Merchant settings — timezone, units, currency behaviour |
-This is why preferences exist rather than columns: `Spree::Calculator::FlatRate` and `Spree::Calculator::TieredPercent` are rows in one table with entirely different settings, and neither wants a column the other leaves null.
-* `Spree::Theme`
\ No newline at end of file
+This is why preferences exist rather than columns: `Spree::Calculator::FlatRate` and `Spree::Calculator::TieredPercent` are rows in one table with entirely different settings, and neither wants a column the other leaves null.
\ No newline at end of file
diff --git a/docs/developer/customization/validations.mdx b/docs/developer/customization/validations.mdx
index 7e396f7cdd..db50c8011d 100644
--- a/docs/developer/customization/validations.mdx
+++ b/docs/developer/customization/validations.mdx
@@ -74,7 +74,7 @@ dashboard under **Settings → Store**, or through the Admin API:
```typescript Admin SDK
await adminClient.store.update({
- preferred_address_requires_phone: false,
+ address_requires_phone: false,
})
```
@@ -82,7 +82,7 @@ await adminClient.store.update({
curl -X PATCH 'https://api.mystore.com/api/v3/admin/store' \
-H 'X-Spree-API-Key: sk_xxx' \
-H 'Content-Type: application/json' \
- -d '{ "preferred_address_requires_phone": false }'
+ -d '{ "address_requires_phone": false }'
```
</CodeGroup>
diff --git a/docs/developer/how-to/build-a-b2b-store.mdx b/docs/developer/how-to/build-a-b2b-store.mdx
index 45f126f292..333d122c95 100644
--- a/docs/developer/how-to/build-a-b2b-store.mdx
+++ b/docs/developer/how-to/build-a-b2b-store.mdx
@@ -499,14 +499,14 @@ The gate is enforced by the Store API, not by the storefront, so a storefront ap
```typescript Admin SDK
// Gate the wholesale channel, and give its shoppers a default agreement
await adminClient.channels.update('ch_xxx', {
- preferred_storefront_access: 'login_required',
- preferred_guest_checkout: false,
+ storefront_access: 'login_required',
+ guest_checkout: false,
default_catalog_id: 'cat_xxx',
})
// Or set the fallback for every channel that does not set its own
await adminClient.store.update({
- preferred_storefront_access: 'prices_hidden',
+ storefront_access: 'prices_hidden',
})
```
@@ -515,8 +515,8 @@ curl -X PATCH 'https://api.mystore.com/api/v3/admin/channels/ch_xxx' \
-H 'X-Spree-API-Key: sk_xxx' \
-H 'Content-Type: application/json' \
-d '{
- "preferred_storefront_access": "login_required",
- "preferred_guest_checkout": false,
+ "storefront_access": "login_required",
+ "guest_checkout": false,
"default_catalog_id": "cat_xxx"
}'
```
diff --git a/docs/developer/how-to/build-a-marketplace.mdx b/docs/developer/how-to/build-a-marketplace.mdx
index ae335c9cda..247136fe01 100644
--- a/docs/developer/how-to/build-a-marketplace.mdx
+++ b/docs/developer/how-to/build-a-marketplace.mdx
@@ -52,16 +52,16 @@ Three store preferences decide how sellers get paid. All three are writable thro
| Preference | Default | What it decides |
|---|---|---|
-| `preferred_payout_provider` | blank | Who moves the money. Blank means core's record-only provider: the ledger is kept correctly and the operator settles by hand. |
-| `preferred_default_payouts_schedule_interval` | `monthly` | How often sellers are settled. One of `daily`, `weekly`, `biweekly`, `monthly`, `manual`. A seller can carry its own interval, which wins. |
-| `preferred_default_minimum_payout_amount` | `0` | What a seller's balance must reach before a settlement is worth sending. Below it the balance carries to the next period. |
+| `payout_provider` | blank | Who moves the money. Blank means core's record-only provider: the ledger is kept correctly and the operator settles by hand. |
+| `default_payouts_schedule_interval` | `monthly` | How often sellers are settled. One of `daily`, `weekly`, `biweekly`, `monthly`, `manual`. A seller can carry its own interval, which wins. |
+| `default_minimum_payout_amount` | `0` | What a seller's balance must reach before a settlement is worth sending. Below it the balance carries to the next period. |
<CodeGroup>
```typescript Admin SDK
await adminClient.store.update({
- preferred_default_payouts_schedule_interval: 'weekly',
- preferred_default_minimum_payout_amount: 25,
+ default_payouts_schedule_interval: 'weekly',
+ default_minimum_payout_amount: '25.00',
})
```
@@ -70,8 +70,8 @@ curl -X PATCH 'https://api.mystore.com/api/v3/admin/store' \
-H 'X-Spree-API-Key: sk_xxx' \
-H 'Content-Type: application/json' \
-d '{
- "preferred_default_payouts_schedule_interval": "weekly",
- "preferred_default_minimum_payout_amount": 25
+ "default_payouts_schedule_interval": "weekly",
+ "default_minimum_payout_amount": "25.00"
}'
```
@@ -92,19 +92,19 @@ Admin API like the payout ones.
| Preference | Default | What it decides |
|---|---|---|
-| `preferred_auto_approve_sellers` | `false` | Admit a seller the moment they finish the checklist, with nobody looking at them. |
-| `preferred_auto_approve_seller_products` | `false` | Put a seller's product on sale the moment they submit it. |
-| `preferred_send_seller_transactional_emails` | `true` | Whether Spree emails sellers. Turn it off if you front seller communications yourself. |
-| `preferred_default_commission_tax_rate` | `0` | Tax on your commission when neither the rate nor the tax provider names one. |
+| `auto_approve_sellers` | `false` | Admit a seller the moment they finish the checklist, with nobody looking at them. |
+| `auto_approve_seller_products` | `false` | Put a seller's product on sale the moment they submit it. |
+| `send_seller_transactional_emails` | `true` | Whether Spree emails sellers. Turn it off if you front seller communications yourself. |
+| `default_commission_tax_rate` | `0` | Tax on your commission when neither the rate nor the tax provider names one. |
<CodeGroup>
```typescript Admin SDK
await adminClient.store.update({
- preferred_auto_approve_sellers: false,
- preferred_auto_approve_seller_products: false,
- preferred_send_seller_transactional_emails: true,
- preferred_default_commission_tax_rate: 0.23,
+ auto_approve_sellers: false,
+ auto_approve_seller_products: false,
+ send_seller_transactional_emails: true,
+ default_commission_tax_rate: '0.23',
})
```
@@ -113,10 +113,10 @@ curl -X PATCH 'https://api.mystore.com/api/v3/admin/store' \
-H 'X-Spree-API-Key: sk_xxx' \
-H 'Content-Type: application/json' \
-d '{
- "preferred_auto_approve_sellers": false,
- "preferred_auto_approve_seller_products": false,
- "preferred_send_seller_transactional_emails": true,
- "preferred_default_commission_tax_rate": 0.23
+ "auto_approve_sellers": false,
+ "auto_approve_seller_products": false,
+ "send_seller_transactional_emails": true,
+ "default_commission_tax_rate": "0.23"
}'
```
@@ -426,7 +426,7 @@ curl -X PATCH 'https://api.mystore.com/api/v3/admin/products/prod_xxx/reject' \
Filter the review queue with a Ransack query on status: `adminClient.products.list({ status_eq: 'proposed' })`.
-With `preferred_auto_approve_seller_products` on, submitting chains straight into approval. The submission row still gets written and carries an `auto_approved` marker, so a blank reviewer reads as "this store does not review listings" rather than as a lost name.
+With `auto_approve_seller_products` on, submitting chains straight into approval. The submission row still gets written and carries an `auto_approved` marker, so a blank reviewer reads as "this store does not review listings" rather than as a lost name.
There is no bulk route onto `active` for sellers, and that is deliberate: reaching it is the operator's decision on one listing at a time.
@@ -495,7 +495,7 @@ curl 'https://api.mystore.com/api/v3/admin/commission_lines?q[seller_id_eq]=sel_
There is no write path. Correcting a charge is a reversal, not an edit.
-In the EU the fee is a separate supply from the sale, so it is taxed separately — that is what `preferred_default_commission_tax_rate` from step 1 is for, and a rate or a tax provider can name its own.
+In the EU the fee is a separate supply from the sale, so it is taxed separately — that is what `default_commission_tax_rate` from step 1 is for, and a rate or a tax provider can name its own.
**Read more:** [Commissions](/developer/core-concepts/commissions) covers the four rule types, gross-versus-net, how delivery is treated, currency floors and caps, and commission tax in full. [Commission rates](/user/sellers/commission-rates) is the operator's screen.
@@ -620,7 +620,7 @@ curl -X POST 'https://api.mystore.com/api/v3/admin/sellers/sel_xxx/payouts' \
### Payout providers
-A provider is a stateless class registered in `Spree.payout_providers` and chosen per store with `preferred_payout_provider`.
+A provider is a stateless class registered in `Spree.payout_providers` and chosen per store with `payout_provider`.
| Provider | Moves money? | Completion |
|---|---|---|
diff --git a/docs/developer/how-to/custom-order-routing.mdx b/docs/developer/how-to/custom-order-routing.mdx
index fbfd36a232..ef2e0be876 100644
--- a/docs/developer/how-to/custom-order-routing.mdx
+++ b/docs/developer/how-to/custom-order-routing.mdx
@@ -247,7 +247,7 @@ Activate on the whole store:
```ruby
Spree::Store.default.update!(
- preferred_order_routing_strategy: 'Acme::Oms::Strategy'
+ order_routing_strategy: 'Acme::Oms::Strategy'
)
```
@@ -256,11 +256,11 @@ Override on one channel only:
```ruby
store = Spree::Store.default
store.channels.find_by(code: 'pos').update!(
- preferred_order_routing_strategy: 'Acme::Oms::Strategy'
+ order_routing_strategy: 'Acme::Oms::Strategy'
)
```
-Resolution order: `channel.preferred_order_routing_strategy` → `store.preferred_order_routing_strategy` → the default `Strategy::Rules`. Only a value pointing to a **registered** `Strategy::Base` subclass is used; anything unset, unregistered, or invalid is skipped, so a misconfiguration (or a strategy you've since unregistered) falls back to the default instead of breaking checkout.
+Resolution order: the channel's `order_routing_strategy` → the store's `order_routing_strategy` → the default `Strategy::Rules`. Only a value pointing to a **registered** `Strategy::Base` subclass is used; anything unset, unregistered, or invalid is skipped, so a misconfiguration (or a strategy you've since unregistered) falls back to the default instead of breaking checkout.
### Step 3: Test the Strategy
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index ecb4dacf15..f8de56a271 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -526,7 +526,32 @@ If your storefront or webhook receiver reads any of these fields, compare agains
| `payment_source_type` | Store API payment setup sessions, `payment_setup_session.*` webhooks | `Spree::CreditCard` | `credit_card` |
| `type` | Custom fields on products, variants, categories and collections | `Spree::CustomFields::ShortText` | removed — read `field_type` (`short_text`) |
-The Admin API follows the same rule everywhere: providers and strategies (`fulfillment_provider: 'manual'`, `preferred_order_routing_strategy: 'rules'`), custom field definition `resource_type` (`product`, `category`), tag `taggable_type`, the owner and originator types on records, the permission subjects `/me` returns (`product`, `category`), and filters such as `q[type_eq]=orders`. An integration written against the Admin API preview sends and expects these short names; the [Admin SDK](/developer/sdk/admin/resources) types list them.
+The Admin API follows the same rule everywhere: providers and strategies (`fulfillment_provider: 'manual'`, `order_routing_strategy: 'rules'`), custom field definition `resource_type` (`product`, `category`), tag `taggable_type`, the owner and originator types on records, the permission subjects `/me` returns (`product`, `category`), and filters such as `q[type_eq]=orders`. An integration written against the Admin API preview sends and expects these short names; the [Admin SDK](/developer/sdk/admin/resources) types list them.
+
+## Preferences are typed in the API
+
+Settings no longer reach the Admin and Seller APIs in the shape of Ruby's preference methods. The Store API is not affected.
+
+**Settings use plain names.** Every `preferred_*` field is renamed, on read and on write:
+
+| Resource | Before | After |
+|---|---|---|
+| Store (`/admin/store`) | `preferred_timezone`, `preferred_guest_checkout`, `preferred_storefront_url`, … every `preferred_*` field | `timezone`, `guest_checkout`, `storefront_url`, … the same name without the prefix |
+| Channel | `preferred_storefront_access`, `preferred_guest_checkout`, `preferred_order_routing_strategy` | `storefront_access`, `guest_checkout`, `order_routing_strategy` |
+| 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.
+
+**`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.
+
+**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_…`).
+
+**Id lists read as prefixed ids.** Preferences listing records, such as a rule's `channel_ids` or `customer_group_ids`, now return prefixed ids rather than database ids, the same form a write accepts.
+
+**Delivery methods nest their calculator.** `calculator_type` and `calculator_preferences` are replaced by `calculator: { type, preferences }` on read and write, the shape promotion actions already use.
+
+**For extension authors:** declare every preference's full type (`of:` on arrays, `keys:` and `values:` on hashes, `money: true`, `choices:`, `format:`). An incomplete declaration still works in 6.0 with a deprecation warning, and its schema accepts any value. Replace `normalize_id_preference` with `preference :ids, :array, of: :id, model:, scope:`, and `in:` with `choices:`. See [Model preferences](/developer/customization/model-preferences#declaring-the-full-type).
## Every event is declared
@@ -602,7 +627,7 @@ Saving or touching a product used to bump the `updated_at` of each of its catego
`Spree::OrderRouting::Strategy::Legacy` — the pre-5.5 escape hatch that delegated straight to `Spree::Stock::Coordinator` and consulted no routing rules — is removed and no longer registered in `Spree.order_routing.strategies`.
-A store or channel still carrying `preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Legacy'` **keeps working**: `Order#order_routing_strategy` ignores unregistered classes, logs a warning, and falls back to `Strategy::Rules`. Clear the stale preference to silence the warning — note that saving such a record now fails validation, since the value is no longer in the registry.
+A store or channel still carrying `order_routing_strategy: 'Spree::OrderRouting::Strategy::Legacy'` **keeps working**: `Order#order_routing_strategy` ignores unregistered classes, logs a warning, and falls back to `Strategy::Rules`. Clear the stale preference to silence the warning — note that saving such a record now fails validation, since the value is no longer in the registry.
`Spree::Stock::Coordinator` itself stays — cart fulfillment building, exchanges, and claims still use it.
@@ -875,6 +900,9 @@ Before 6.0 a cart was an incomplete order, so extensions written for 5.x (paymen
| `Address#firstname`, `#lastname`, `#zipcode` | `#first_name`, `#last_name`, `#postal_code` (columns renamed) |
| `Address.normalize_zipcode`, `#normalized_zipcode` | `.normalize_postal_code`, `#normalized_postal_code` |
| `Order#bill_address_firstname`, `#bill_address_lastname` | `#bill_address_first_name`, `#bill_address_last_name` |
+| `preference … parse_on_set: normalize_id_preference(klass:, scope:)` | `preference …, :array, of: :id, model:, scope:` |
+| `preference …, in: [...]` | `preference …, choices: [...]` |
+| `:array` without `of:`, `:hash` without `keys:`/`values:`, the `:any` type | A complete declaration (see [Model preferences](/developer/customization/model-preferences#declaring-the-full-type)) |
| `OptionType#presentation`, `OptionValue#presentation` | `#label` (column renamed, translations included). Reads and writes on an instance only — `where(presentation:)` and `find_by(presentation:)` raise, because Mobility owns `label` so the bridge cannot be an attribute alias. Query by `label`. |
| `OptionValue#option_type_presentation` | `#option_type_label` |
| `q[presentation_cont]` (option type / value filters) | `q[label_cont]` — the Ransack whitelist publishes the column, so the filter key moves with it |
diff --git a/docs/integrations/payments/stripe-connect.mdx b/docs/integrations/payments/stripe-connect.mdx
index 00d5736cd4..e4d9b809c0 100644
--- a/docs/integrations/payments/stripe-connect.mdx
+++ b/docs/integrations/payments/stripe-connect.mdx
@@ -25,9 +25,9 @@ const { data: providers } = await adminClient.payoutProviders.list()
// find the row with id 'stripe' — `available` says whether this store can use it
await adminClient.store.update({
- preferred_payout_provider: 'stripe',
- preferred_default_payouts_schedule_interval: 'weekly',
- preferred_default_minimum_payout_amount: 50,
+ payout_provider: 'stripe',
+ default_payouts_schedule_interval: 'weekly',
+ default_minimum_payout_amount: '50.00',
})
```
@@ -35,7 +35,7 @@ await adminClient.store.update({
curl -X PATCH https://your-store.com/api/v3/admin/store \
-H "X-Spree-API-Key: sk_xxx" \
-H "Content-Type: application/json" \
- -d '{"preferred_payout_provider": "stripe", "preferred_default_payouts_schedule_interval": "weekly", "preferred_default_minimum_payout_amount": 50}'
+ -d '{"payout_provider": "stripe", "default_payouts_schedule_interval": "weekly", "default_minimum_payout_amount": "50.00"}'
```
</CodeGroup>
diff --git a/docs/plans/6.0-payment-method-rules.md b/docs/plans/6.0-payment-method-rules.md
index f5db0f37bc..179d0acdc2 100644
--- a/docs/plans/6.0-payment-method-rules.md
+++ b/docs/plans/6.0-payment-method-rules.md
@@ -21,6 +21,8 @@ This **supersedes half of a key decision** in `5.6-6.0-single-store-promotions-p
## Key Decisions (do not deviate without discussion)
+> **Superseded in part (2026-10-09, `6.0-typed-preferences.md`):** id-list preferences are declared `preference :name, :array, of: :id, model:, scope:` rather than with a `normalize_id_preference` lambda, and the `/types` endpoint returns `schema` (JSON Schema) instead of `preference_schema`. Read the snippets below with that substitution.
+
- **Mirror `Spree::PromotionRule`, don't invent a framework.** STI base `Spree::PaymentMethodRule` on a new `spree_payment_method_rules` table, subclasses under `app/models/spree/payment_method_rules/`, preference-schema-driven config (same `preference … parse_on_set: normalize_id_preference(…)` idiom as promotion/price rules), registry-validated `type`. This is the fourth instance of an established house pattern (PromotionRule, PriceRule, OrderRoutingRule) — deviating from it needs a reason.
- **No rules = available everywhere.** A payment method with zero rules behaves exactly as today. No backfill, no behavior change on upgrade.
- **AND semantics.** All active rules on a payment method must pass. No `match_policy` — "any" composition is a future addition if a real merchant needs it (none of the surveyed platforms offer OR at this layer).
diff --git a/docs/plans/6.0-typed-preferences.md b/docs/plans/6.0-typed-preferences.md
index d296fcd3b0..92927c1151 100644
--- a/docs/plans/6.0-typed-preferences.md
+++ b/docs/plans/6.0-typed-preferences.md
@@ -48,6 +48,20 @@ Preferences reach the API in two ways, and both expose the Ruby preferences DSL
- **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.
+### Settled during implementation (2026-10-09)
+
+- **An id list names its model, not its prefix.** `of: :id, model: 'Spree::Channel', scope: ->(rule) { … }`. The prefix (`x-spree-prefix`) is read from the model, and the model is needed anyway to check that every id exists inside `scope`. `model:` takes a class name or a block (`-> { Spree.customer_class }`), so a declaration never loads another class. `normalize_id_preference` stays one release as a deprecated bridge.
+- **The SDK narrows through a map, not a union with a catch-all member.** TypeScript does not narrow on `type` when one member's `type` is `string`, so the plan's `ItemTotalRule | … | UnknownPromotionRule` would type nothing. Each family ships `<Family>PreferencesMap` (an interface, so an extension adds its types by declaration merging, as with `WebhookEventMap`) and `Typed<Family>`, the resource narrowed by `type`. The generated resource type keeps `preferences: Record<string, unknown>`, which is what a plugin type reads as.
+- **OpenAPI carries the family union on `preferences`, without a `discriminator`.** The specs are OpenAPI 3.0.3, and `type` sits outside the `preferences` object, so a discriminator cannot apply. Each family is an `anyOf` of its subtypes plus a plain object, with `x-spree-preferences-by-type` mapping each `type` to its component. Nullable types use `nullable: true`; `propertyNames` becomes `x-spree-property-names`.
+- **Secrets are not `writeOnly`.** They read back masked, so the property is in responses; `x-spree-secret` marks them. A secret is always nullable, because an unset one reads as `null`.
+- **Defaults computed at read time are not in the schema.** A default given as a block (the default store's currency) differs per store and needs the database, so it is left out and does not make the value nullable. The schema can then be generated without a database.
+- **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.
+- **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.
+
## Design Details
### Declaration additions
diff --git a/packages/admin-sdk/examples/delivery-methods/create.ts b/packages/admin-sdk/examples/delivery-methods/create.ts
index 6a3631ac08..77af99d39c 100644
--- a/packages/admin-sdk/examples/delivery-methods/create.ts
+++ b/packages/admin-sdk/examples/delivery-methods/create.ts
@@ -9,8 +9,7 @@ const client = createAdminClient({
const deliveryMethod = await client.deliveryMethods.create({
name: 'Express',
storefront_visible: true,
- calculator_type: 'flat_rate',
- calculator_preferences: { amount: '12.50' },
+ calculator: { type: 'flat_rate', preferences: { amount: '12.50' } },
})
// endregion:example
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index ea5a0b73cd..1b4ff06135 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -4,6 +4,7 @@ import type {
LoginCredentials,
PaginatedResponse,
PaginationMeta,
+ PreferenceSchema,
ProviderLogin,
RequestFn,
RequestOptions,
@@ -318,7 +319,6 @@ import type {
PaymentMethodUpdateParams,
PolicyCreateParams,
PolicyUpdateParams,
- PreferenceField,
PriceBulkUpsertRow,
PriceCreateParams,
PriceListCreateParams,
@@ -2363,11 +2363,11 @@ export class AdminClient {
delete: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/delivery_methods/${id}`, options),
- /** Registered delivery calculator classes with preference schemas. */
+ /** Registered delivery calculator classes, each with the JSON Schema of its preferences. */
calculators: (
options?: RequestOptions,
- ): Promise<{ data: Array<{ type: string; name: string; preference_schema: unknown[] }> }> =>
- this.request<{ data: Array<{ type: string; name: string; preference_schema: unknown[] }> }>(
+ ): Promise<{ data: Array<{ type: string; name: string; schema: PreferenceSchema }> }> =>
+ this.request<{ data: Array<{ type: string; name: string; schema: PreferenceSchema }> }>(
'GET',
'/delivery_methods/calculators',
options,
@@ -2454,7 +2454,7 @@ export class AdminClient {
type: string
name: string
description: string
- preference_schema: PreferenceField[]
+ schema: PreferenceSchema
/** Association-backed config the rule accepts, e.g. `['product_ids']`. */
association_fields: string[]
}>
@@ -2464,7 +2464,7 @@ export class AdminClient {
type: string
name: string
description: string
- preference_schema: PreferenceField[]
+ schema: PreferenceSchema
association_fields: string[]
}>
}>('GET', '/delivery_method_rules/types', options),
@@ -2775,7 +2775,7 @@ export class AdminClient {
this.request<PriceList>('PATCH', `/price_lists/${id}/deactivate`, options),
/**
- * Returns `[{ type, label, description, preference_schema }]` for
+ * Returns `[{ type, label, description, schema }]` for
* every registered subclass in `Spree.pricing.rules`. Used to build
* the "Add rule" picker + render a generic preferences form per
* subclass. Rules themselves are not a separate REST resource —
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 34efe84e60..2cf2cd47b2 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -1,7 +1,7 @@
// Request parameter types for Admin API endpoints
// Based on the Admin API OpenAPI specification
-import type { PaginationMeta } from '@spree/sdk-core'
+import type { PaginationMeta, PreferenceSchema } from '@spree/sdk-core'
import type { ReportingQuery } from './admin-client'
import type { SellerRequirementStatus, StoreCredit } from './types'
@@ -23,7 +23,7 @@ export interface StoreDataSourceProvider {
* sellers to hold an account with it.
*/
export interface StorePayoutProvider {
- /** The provider's shorthand (`system`, `stripe`) — what `preferred_payout_provider` takes. */
+ /** The provider's shorthand (`system`, `stripe`) — what `payout_provider` takes. */
id: string
name: string
/** False when the store has not connected what this provider needs. */
@@ -42,61 +42,57 @@ export interface StoreDataSources {
export interface StoreUpdateParams {
name?: string
- preferred_admin_locale?: string
- preferred_timezone?: string
- preferred_weight_unit?: string
- preferred_unit_system?: string
+ admin_locale?: string
+ timezone?: string
+ weight_unit?: string
+ unit_system?: string
/**
* Store-wide default storefront posture: `public`, `prices_hidden`, or
* `login_required`. Channels fall back to this when they don't set their own.
*/
- preferred_storefront_access?: string
+ storefront_access?: string
/** The storefront's public URL — base for customer-email links; saving it also completes the storefront setup task. */
- preferred_storefront_url?: string | null
+ storefront_url?: string | null
/** Store-wide default for guest checkout. Channels fall back to this. */
- preferred_guest_checkout?: boolean
+ guest_checkout?: boolean
/** Always advertise a confirmation step in checkout, even when no payment method requires one. */
- preferred_always_include_confirm_step?: boolean
+ always_include_confirm_step?: boolean
/** Shows a company field on address forms. */
- preferred_company_field_enabled?: boolean
+ company_field_enabled?: boolean
/** Makes a phone number mandatory on customer addresses. */
- preferred_address_requires_phone?: boolean
+ address_requires_phone?: boolean
/** Store-wide default for when a customer is charged rather than only authorized. A payment method's own setting wins when set. */
- preferred_capture_method?: 'checkout' | 'on_dispatch' | 'manual'
- /** @deprecated Use `preferred_capture_method`; removed in 6.1. */
- preferred_auto_capture?: boolean
- /** @deprecated Use `preferred_capture_method`; removed in 6.1. */
- preferred_auto_capture_on_dispatch?: boolean
+ capture_method?: 'checkout' | 'on_dispatch' | 'manual'
/** Calculates tax from the shipping address. When false, calculates tax from the billing address. */
- preferred_tax_using_ship_address?: boolean
+ tax_using_ship_address?: boolean
/** Counts on-hand quantities. Off means everything is treated as always available. */
- preferred_track_inventory_levels?: boolean
+ track_inventory_levels?: boolean
/** Holds stock for shoppers while they check out, so the same item can't be sold twice. */
- preferred_stock_reservations_enabled?: boolean
+ stock_reservations_enabled?: boolean
/** On-hand units at or below which a tracked variant counts as low stock on the home screen; 0 turns the warning off. */
- preferred_low_stock_threshold?: number
+ low_stock_threshold?: number
/** Records price changes for the EU Omnibus lowest-price-in-30-days display. */
- preferred_track_price_history?: boolean
+ track_price_history?: boolean
/** Whether products with no price in the shopper's currency still appear in listings. */
- preferred_show_products_without_price?: boolean
+ show_products_without_price?: boolean
/** Lets more than one variant share the same SKU. */
- preferred_disable_sku_validation?: boolean
+ disable_sku_validation?: boolean
/** How document numbers are produced: `sequential` or `random`. Applies to every numbered document. */
- preferred_document_number_format?: string
+ document_number_format?: string
/** Leads every order number, e.g. `R`. Uppercase letters, digits, dashes and # only. */
- preferred_order_number_prefix?: string
+ order_number_prefix?: string
/** Ends every order number. Uppercase letters, digits, dashes and # only. */
- preferred_order_number_suffix?: string
+ order_number_suffix?: string
/** First sequential order number. Only applies before the store's first order. */
- preferred_order_number_sequence_start?: number
+ order_number_sequence_start?: number
/** When false, buyers can download their files as often as they like. */
- preferred_limit_digital_download_count?: boolean
+ limit_digital_download_count?: boolean
/** Downloads allowed per purchased file, unless the file overrides it. */
- preferred_digital_asset_authorized_clicks?: number
+ digital_asset_authorized_clicks?: number
/** When false, download links never expire. */
- preferred_limit_digital_download_days?: boolean
+ limit_digital_download_days?: boolean
/** Days a download link stays valid, unless the file overrides it. */
- preferred_digital_asset_authorized_days?: number
+ digital_asset_authorized_days?: number
/** Sender address used on all transactional emails (required by the model). */
mail_from_address?: string
/** Customer-facing reply-to address shown in the storefront/email footer. */
@@ -104,42 +100,42 @@ export interface StoreUpdateParams {
/** Recipient of "new order placed" admin notifications. */
new_order_notifications_email?: string | null
/** When false, transactional consumer emails (order confirmation, etc.) are suppressed. */
- preferred_send_consumer_transactional_emails?: boolean
+ send_consumer_transactional_emails?: boolean
/** Customer email buttons and links, as `#RRGGBB`. Blank keeps the outlined buttons emails ship with. */
- preferred_email_accent_color?: string | null
+ email_accent_color?: string | null
/** Customer email page background, as `#RRGGBB`. */
- preferred_email_background_color?: string | null
+ email_background_color?: string | null
/** Customer email card behind the content, as `#RRGGBB`. */
- preferred_email_card_color?: string | null
+ email_card_color?: string | null
/** Customer email body text, as `#RRGGBB`. */
- preferred_email_text_color?: string | null
+ email_text_color?: string | null
/** Customer email headings and emphasized text, as `#RRGGBB`. */
- preferred_email_heading_color?: string | null
+ email_heading_color?: string | null
/** Customer email font: `inter`, `system`, `helvetica`, `georgia`, `roboto`, `lato` or `merriweather`. */
- preferred_email_font?: string | null
+ email_font?: string | null
/** Active Storage signed_id from a direct upload — the logo embedded in transactional emails. */
mailer_logo?: string | null
/** Where prices come from: a registered provider key, or `internal`. */
- preferred_pricing_provider?: string
+ pricing_provider?: string
/** Where stock levels come from: a registered provider key, or `internal`. */
- preferred_inventory_provider?: string
+ inventory_provider?: string
/** `strict` refuses to price when the provider cannot answer; `fallback` uses the catalog. */
- preferred_pricing_provider_failure_policy?: 'strict' | 'fallback'
+ pricing_provider_failure_policy?: 'strict' | 'fallback'
/** `fallback` sells on the local snapshot when the provider cannot answer; `strict` refuses. */
- preferred_inventory_provider_failure_policy?: 'strict' | 'fallback'
+ inventory_provider_failure_policy?: 'strict' | 'fallback'
/** Blank means the built-in provider: the marketplace settles by hand. */
- preferred_payout_provider?: string
- preferred_default_payouts_schedule_interval?: string
+ payout_provider?: string
+ default_payouts_schedule_interval?: string
/** A decimal string in the store's currency, e.g. `"50.00"`. */
- preferred_default_minimum_payout_amount?: string
+ default_minimum_payout_amount?: string
/** Admits a seller as soon as they finish onboarding, with no operator review. */
- preferred_auto_approve_sellers?: boolean
+ auto_approve_sellers?: boolean
/** Puts a seller's product on sale the moment they submit it, with no review. */
- preferred_auto_approve_seller_products?: boolean
+ auto_approve_seller_products?: boolean
/** When false, transactional seller emails (approval, payouts, etc.) are suppressed. */
- preferred_send_seller_transactional_emails?: boolean
+ send_seller_transactional_emails?: boolean
/** Tax charged on commission as a fraction (`"0.23"` is 23%), when neither the rate nor the tax provider names one. */
- preferred_default_commission_tax_rate?: string
+ default_commission_tax_rate?: string
}
export interface OptionValueParams {
@@ -1854,17 +1850,17 @@ export interface ChannelCreateParams {
* Order routing strategy shorthand (built-in: `rules`), or `null` to
* inherit the store-level preference.
*/
- preferred_order_routing_strategy?: string | null
+ order_routing_strategy?: string | null
/**
* Storefront access posture: `public`, `prices_hidden`, or `login_required`.
* `null` (or an empty string) inherits the store-level preference.
*/
- preferred_storefront_access?: string | null
+ storefront_access?: string | null
/**
* Whether guest checkout is allowed on this channel. `null` inherits the
* store-level preference.
*/
- preferred_guest_checkout?: boolean | null
+ guest_checkout?: boolean | null
/**
* Catalog (cat_...) shown to shoppers not covered by a company or customer
* group catalog. `null` means every product published on the channel.
@@ -1879,17 +1875,17 @@ export interface ChannelUpdateParams {
code?: string
active?: boolean
default?: boolean
- preferred_order_routing_strategy?: string | null
+ order_routing_strategy?: string | null
/**
* Storefront access posture: `public`, `prices_hidden`, or `login_required`.
* `null` (or an empty string) inherits the store-level preference.
*/
- preferred_storefront_access?: string | null
+ storefront_access?: string | null
/**
* Whether guest checkout is allowed on this channel. `null` inherits the
* store-level preference.
*/
- preferred_guest_checkout?: boolean | null
+ guest_checkout?: boolean | null
/**
* Catalog (cat_...) shown to shoppers not covered by a company or customer
* group catalog. `null` means every product published on the channel.
@@ -2040,7 +2036,8 @@ export interface SellerRequirementType {
accepted_content_types: string[]
/** Association-backed config this kind takes beyond its preferences. */
association_fields: string[]
- preference_schema: Array<Record<string, unknown>>
+ /** JSON Schema of the kind's `preferences`. */
+ schema: PreferenceSchema
}
/** Excusing one seller from one requirement. */
@@ -2143,28 +2140,6 @@ export interface CommissionRateCreateParams {
export type CommissionRateUpdateParams = Partial<CommissionRateCreateParams>
-/**
- * One entry in `preference_schema`, describing a single tunable knob on
- * a STI subclass (payment provider, promotion action, promotion rule).
- *
- * The `type` mirrors Spree's preference type system — `string`, `text`,
- * `integer`, `decimal`, `money`, `boolean`, `array`, `password` — so admin UIs
- * can switch on it to render the right input widget. A `money` value is a
- * decimal string in the currency of the record's `currency` preference, when
- * it has one; a `decimal` is a rate or measure, such as a percentage or a weight.
- */
-export interface PreferenceField {
- key: string
- type: string
- default: unknown
- /**
- * The fixed set this value must come from, when the preference declares
- * one. Present only for constrained preferences; an admin form renders a
- * picker for these rather than a free-text box.
- */
- choices?: string[]
-}
-
/**
* Mask token the server applies to `:password`-typed preferences before
* returning them. The value `••••` followed by the original secret's
@@ -2187,12 +2162,12 @@ export function isMaskedSecret(value: unknown): value is string {
/**
* The shape returned by `/<resource>/types` endpoints — one entry per
- * registered subclass with its preference schema. Used to build "Add
+ * registered subclass with the JSON Schema of its preferences. Used to build "Add
* provider / action / rule" pickers and render generic preferences forms.
*/
/**
* One rule kind a commission rate can be narrowed by, as the marketplace
- * reports it. `preference_schema` describes the configuration the kind takes,
+ * reports it. `schema` describes the configuration the kind takes,
* and `association_fields` names any catalog-scale reference it keeps outside
* that — so a client can render the right editor without knowing the kind.
*/
@@ -2200,7 +2175,8 @@ export interface CommissionRuleType {
type: string
name: string
description: string | null
- preference_schema: PreferenceField[]
+ /** JSON Schema of the type's `preferences`. */
+ schema: PreferenceSchema
association_fields: string[]
}
@@ -2208,7 +2184,8 @@ export interface ResourceTypeDefinition {
type: string
label: string
description: string | null
- preference_schema: PreferenceField[]
+ /** JSON Schema of the type's `preferences`. */
+ schema: PreferenceSchema
/**
* Present (true) only on kinds a better mechanism has replaced: existing
* records keep working and rendering, but pickers must stop offering the
@@ -2426,6 +2403,8 @@ export interface PaymentMethodType extends ResourceTypeDefinition {
docs_url: string | null
/** Backed by an external payment provider rather than handled by the store itself. */
third_party: boolean
+ /** The store already has a payment method of this type; leave it out of a create picker. */
+ installed: boolean
}
/**
@@ -2449,7 +2428,8 @@ export interface IntegrationTypeDefinition {
logo_url: string | null
/** Absolute URL of the integration's setup guide. */
docs_url: string | null
- preference_schema: { key: string; type: string; default: unknown }[]
+ /** JSON Schema of the type's `preferences`. */
+ schema: PreferenceSchema
}
export interface IntegrationCreateParams {
@@ -2530,7 +2510,7 @@ export interface ImportCreateParams {
*/
attachment: string
/** CSV column separator. Defaults to a comma on the server. */
- preferred_delimiter?: ',' | ';' | '|' | '\t'
+ delimiter?: ',' | ';' | '|' | '\t'
/**
* For `price_list_prices` imports: the price list the rows are merged
* into. Must belong to the current store (404 otherwise); ignored by
@@ -2695,7 +2675,8 @@ export interface PromotionActionLineItemParams {
export interface PromotionActionCalculator {
type: string
label: string
- preference_schema: PreferenceField[]
+ /** JSON Schema of the type's `preferences`. */
+ schema: PreferenceSchema
}
export interface PromotionActionCreateParams {
@@ -2806,9 +2787,12 @@ export interface DeliveryMethodParams {
estimated_transit_business_days_max?: number | null
/** Prefixed tax category ID (`taxcat_...`), or null to clear. */
tax_category_id?: string | null
- /** Wire shorthand for the calculator, e.g. `'flat_rate'` (see `deliveryMethods.calculators()`). */
- calculator_type?: string
- calculator_preferences?: Record<string, unknown>
+ /**
+ * How the method prices a shipment: the calculator's wire shorthand, e.g.
+ * `'flat_rate'` (see `deliveryMethods.calculators()`), and its preferences,
+ * which must match the `schema` that list carries.
+ */
+ calculator?: { type?: string; preferences?: Record<string, unknown> }
/** Prefixed delivery zone ID (`dz_...`) narrowing destinations, or null for no restriction. Must belong to the method's profile. */
delivery_zone_id?: string | null
/**
@@ -3174,7 +3158,7 @@ export interface EmailTemplatePreviewParams extends EmailTemplateLanguageParams
record_id?: string
/** For the layout or a partial, the email to show it in. */
email_key?: string
- /** Unsaved colors and font to preview, named like the store's `preferred_email_*` settings without the prefix. */
+ /** Unsaved colors and font to preview, named like the store's `email_*` settings. */
branding?: {
accent_color?: string | null
background_color?: string | null
diff --git a/packages/admin-sdk/src/types/generated/Channel.ts b/packages/admin-sdk/src/types/generated/Channel.ts
index d3c6fed733..8a0c46d5c6 100644
--- a/packages/admin-sdk/src/types/generated/Channel.ts
+++ b/packages/admin-sdk/src/types/generated/Channel.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 735c116663be039b5579f691fa117672
+// Typelizer digest 1e3c6c4c2fb1f69409903640da00d4de
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -8,14 +8,12 @@ interface Channel {
code: string;
active: boolean;
default: boolean;
- storefront_access: string;
- guest_checkout: boolean;
- preferred_storefront_access: string | null;
- preferred_guest_checkout: boolean | null;
+ storefront_access: 'public' | 'prices_hidden' | 'login_required' | null;
+ guest_checkout: boolean | null;
created_at: string;
updated_at: string;
/** Order routing strategy; null inherits the store setting. Built-in: rules. Extensions may register more. */
- preferred_order_routing_strategy: string | null;
+ order_routing_strategy: string | null;
stock_location_ids: Array<string>;
default_catalog_id: string | null;
}
diff --git a/packages/admin-sdk/src/types/generated/CommissionRule.ts b/packages/admin-sdk/src/types/generated/CommissionRule.ts
index 3a0053808c..c68f2f6d31 100644
--- a/packages/admin-sdk/src/types/generated/CommissionRule.ts
+++ b/packages/admin-sdk/src/types/generated/CommissionRule.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 98f5e3659ab172d56f253aca2a9368a2
+// Typelizer digest 5ca4b0e28a038f8890c805b46a01faa4
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Seller, Category} from '@/types'
@@ -11,7 +11,6 @@ interface CommissionRule {
type: string;
commission_rate_id: string;
preferences: Record<string, unknown>;
- preference_schema: Array<{ key: string; type: string; default: unknown }>;
product_ids: Array<string> | null;
seller_ids: Array<string> | null;
category_ids: Array<string> | null;
diff --git a/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts b/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts
index ba2f1b1043..5ac243b155 100644
--- a/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts
+++ b/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts
@@ -1,4 +1,4 @@
-// Typelizer digest e7c419105a41d7a43aa7def49ff8989a
+// Typelizer digest 6ab6c0d8401dabaa4660ec68cde64984
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -10,7 +10,6 @@ interface DeliveryMethodRule {
/** Rule type. Built-in: item_total_rule, weight_rule, excluded_products_rule, channel_rule, volume_rule, company_rule. Extensions may register more. */
type: string;
preferences: Record<string, unknown>;
- preference_schema: Array<{ key: string; type: string; default: unknown; choices?: string[] }>;
product_ids: Array<string>;
}
diff --git a/packages/admin-sdk/src/types/generated/Import.ts b/packages/admin-sdk/src/types/generated/Import.ts
index 03e563abbc..5f7805d594 100644
--- a/packages/admin-sdk/src/types/generated/Import.ts
+++ b/packages/admin-sdk/src/types/generated/Import.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 820c94c73561166a1592de21cbde88d6
+// Typelizer digest e8a7267047e6941ee685e3a21f206d0a
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {ImportMapping, ImportStatus} from '@/types'
@@ -18,7 +18,7 @@ interface Import {
owner_id: string | null;
user_id: string | null;
processing_errors: string | null;
- preferred_delimiter: string;
+ delimiter: string;
price_list_id: string | null;
seller_name: string | null;
original_filename: string | null;
diff --git a/packages/admin-sdk/src/types/generated/Integration.ts b/packages/admin-sdk/src/types/generated/Integration.ts
index 1f4fc379f5..de50f45b6a 100644
--- a/packages/admin-sdk/src/types/generated/Integration.ts
+++ b/packages/admin-sdk/src/types/generated/Integration.ts
@@ -1,4 +1,4 @@
-// Typelizer digest eff1530d7d0c217d91b61d9d8940a38b
+// Typelizer digest 7c98857be0680da8bafcd58b84a69d31
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -12,7 +12,6 @@ interface Integration {
type: string;
group: string | null;
preferences: Record<string, unknown>;
- preference_schema: Array<{ key: string; type: string; default: unknown; choices?: string[] }>;
}
export default Integration;
diff --git a/packages/admin-sdk/src/types/generated/OrderRoutingRule.ts b/packages/admin-sdk/src/types/generated/OrderRoutingRule.ts
index 16ea26c05f..165b4ce7c7 100644
--- a/packages/admin-sdk/src/types/generated/OrderRoutingRule.ts
+++ b/packages/admin-sdk/src/types/generated/OrderRoutingRule.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 1bfabab686a2e75046c9cb7f5148822a
+// Typelizer digest 008f3dabedc68fe61944a6f5dd170aaf
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -12,7 +12,6 @@ interface OrderRoutingRule {
type: string;
channel_id: string;
preferences: Record<string, unknown>;
- preference_schema: Array<{ key: string; type: string; default: unknown; choices?: string[] }>;
}
export default OrderRoutingRule;
diff --git a/packages/admin-sdk/src/types/generated/PaymentMethod.ts b/packages/admin-sdk/src/types/generated/PaymentMethod.ts
index a7f1b466d3..90ee4eaf70 100644
--- a/packages/admin-sdk/src/types/generated/PaymentMethod.ts
+++ b/packages/admin-sdk/src/types/generated/PaymentMethod.ts
@@ -1,4 +1,4 @@
-// Typelizer digest c025e1be7880524db5ffd127b7c975c2
+// Typelizer digest 177a1ae2803dbd7e23cb8450d56e9bed
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -20,7 +20,6 @@ interface PaymentMethod {
created_at: string;
updated_at: string;
preferences: Record<string, unknown>;
- preference_schema: Array<{ key: string; type: string; default: unknown; choices?: string[] }>;
logo_url: string | null;
docs_url: string | null;
third_party: boolean;
diff --git a/packages/admin-sdk/src/types/generated/PriceRule.ts b/packages/admin-sdk/src/types/generated/PriceRule.ts
index f4ea0f9ff7..3d8217316d 100644
--- a/packages/admin-sdk/src/types/generated/PriceRule.ts
+++ b/packages/admin-sdk/src/types/generated/PriceRule.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 8eedb3856126fd4d3cdf6816aa61c3d7
+// Typelizer digest 50cd00a9bec2f367470c4152a9eb549d
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Market, CustomerGroup, Channel, Customer} from '@/types'
@@ -11,7 +11,6 @@ interface PriceRule {
type: string;
price_list_id: string;
preferences: Record<string, unknown>;
- preference_schema: Array<{ key: string; type: string; default: unknown }>;
markets?: Array<Market>;
customer_groups?: Array<CustomerGroup>;
channels?: Array<Channel>;
diff --git a/packages/admin-sdk/src/types/generated/PromotionAction.ts b/packages/admin-sdk/src/types/generated/PromotionAction.ts
index c399335440..8a9da5e755 100644
--- a/packages/admin-sdk/src/types/generated/PromotionAction.ts
+++ b/packages/admin-sdk/src/types/generated/PromotionAction.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 8fc25b31bc313caee63e6fd4fe652786
+// Typelizer digest 8d0072956ba947daf41d4eabb1263560
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -10,8 +10,7 @@ interface PromotionAction {
type: string;
promotion_id: string;
preferences: Record<string, unknown>;
- preference_schema: Array<{ key: string; type: string; default: unknown; choices?: string[] }>;
- calculator: { type: string; preferences: Record<string, unknown>; preference_schema: Array<{ key: string; type: string; default: unknown }> } | null;
+ calculator: { type: string; preferences: Record<string, unknown> } | null;
line_items: Array<{ variant_id: string; quantity: number }> | null;
}
diff --git a/packages/admin-sdk/src/types/generated/PromotionRule.ts b/packages/admin-sdk/src/types/generated/PromotionRule.ts
index 74dd7c9989..d2cf47053b 100644
--- a/packages/admin-sdk/src/types/generated/PromotionRule.ts
+++ b/packages/admin-sdk/src/types/generated/PromotionRule.ts
@@ -1,4 +1,4 @@
-// Typelizer digest f72a7c56c3b81bb76c1b80163064d7c5
+// Typelizer digest 99c67ebbf47ab2d5f3c4af7cb8599c19
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Product, Category, Customer, CustomerGroup, Country, Channel, Market, OptionValue} from '@/types'
@@ -11,7 +11,6 @@ interface PromotionRule {
type: string;
promotion_id: string;
preferences: Record<string, unknown>;
- preference_schema: Array<{ key: string; type: string; default: unknown; choices?: string[] }>;
product_ids: Array<string> | null;
category_ids: Array<string> | null;
customer_ids: Array<string> | null;
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 6cc5d65ba8..132418b3bd 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -6,6 +6,8 @@ export type {
LocaleDefaults,
PaginatedResponse,
PaginationMeta,
+ PreferencePropertySchema,
+ PreferenceSchema,
} from '@spree/sdk-core'
// Hand-written discovery-endpoint types (controller-shaped, not generated):
// entries returned by the delivery-method provider discovery endpoints.
@@ -174,6 +176,8 @@ export type { default as Variant } from './generated/Variant'
export type { default as WebhookDelivery } from './generated/WebhookDelivery'
export type { default as WebhookEndpoint } from './generated/WebhookEndpoint'
export type { default as WebhookEvent } from './generated/WebhookEvent'
+// Each configurable family's `preferences`, typed by `type` (generated by `rake typelizer:generate`).
+export type * from './preferences'
// Hand-written translation-management types (controller-shaped, not generated)
export type {
Locale,
diff --git a/packages/admin-sdk/src/types/preferences.ts b/packages/admin-sdk/src/types/preferences.ts
new file mode 100644
index 0000000000..9e2c5453ed
--- /dev/null
+++ b/packages/admin-sdk/src/types/preferences.ts
@@ -0,0 +1,507 @@
+// This file is auto-generated from Spree's preference declarations by `rake typelizer:generate`. Do not edit directly.
+import type CommissionRule from './generated/CommissionRule'
+import type DeliveryMethodRule from './generated/DeliveryMethodRule'
+import type Integration from './generated/Integration'
+import type OrderRoutingRule from './generated/OrderRoutingRule'
+import type PaymentMethod from './generated/PaymentMethod'
+import type PriceRule from './generated/PriceRule'
+import type PromotionRule from './generated/PromotionRule'
+import type SellerRequirement from './generated/SellerRequirement'
+
+/** `Resource` with its `preferences` typed by its `type`, one member per entry of `Map`. */
+type Narrowed<Resource, Map> = {
+ [Type in keyof Map]: Omit<Resource, 'type' | 'preferences'> & {
+ type: Type
+ preferences: Map[Type]
+ }
+}[keyof Map]
+
+/** Settings of the `category_rule` commission rule. */
+export interface CommissionRuleCategoryRulePreferences {
+ /** Prefixed `ctg_` ids. */
+ category_ids: Array<string>
+}
+
+/** Settings of the `item_total_rule` commission rule. */
+export interface CommissionRuleItemTotalRulePreferences {
+ /** An amount, as an exact decimal string. */
+ min_amount: string | null
+ /** An amount, as an exact decimal string. */
+ max_amount: string | null
+}
+
+/** Settings of the `product_rule` commission rule: none. */
+export type CommissionRuleProductRulePreferences = Record<string, never>
+
+/** Settings of the `seller_rule` commission rule. */
+export interface CommissionRuleSellerRulePreferences {
+ /** Prefixed `sel_` ids. */
+ seller_ids: Array<string>
+}
+
+/**
+ * The settings of each commission rule type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface CommissionRulePreferencesMap {
+ category_rule: CommissionRuleCategoryRulePreferences
+ item_total_rule: CommissionRuleItemTotalRulePreferences
+ product_rule: CommissionRuleProductRulePreferences
+ seller_rule: CommissionRuleSellerRulePreferences
+}
+
+/** A commission rule whose `preferences` are typed by its `type`. */
+export type TypedCommissionRule = Narrowed<CommissionRule, CommissionRulePreferencesMap>
+
+/** Settings of the `digital_delivery` delivery calculator. */
+export interface DeliveryCalculatorDigitalDeliveryPreferences {
+ amounts: Record<string, string>
+ /** An amount, as an exact decimal string. */
+ amount: string
+ /** Format: `currency`. */
+ currency: string
+}
+
+/** Settings of the `flat_percent_item_total` delivery calculator. */
+export interface DeliveryCalculatorFlatPercentItemTotalPreferences {
+ flat_percent: string
+}
+
+/** Settings of the `flat_rate` delivery calculator. */
+export interface DeliveryCalculatorFlatRatePreferences {
+ amounts: Record<string, string>
+ /** An amount, as an exact decimal string. */
+ amount: string
+ /** Format: `currency`. */
+ currency: string
+}
+
+/** Settings of the `flexi_rate` delivery calculator. */
+export interface DeliveryCalculatorFlexiRatePreferences {
+ /** An amount, as an exact decimal string. */
+ first_item: string
+ /** An amount, as an exact decimal string. */
+ additional_item: string
+ max_items: number
+ /** Format: `currency`. */
+ currency: string
+}
+
+/** Settings of the `per_item` delivery calculator. */
+export interface DeliveryCalculatorPerItemPreferences {
+ amounts: Record<string, string>
+ /** An amount, as an exact decimal string. */
+ amount: string
+ /** Format: `currency`. */
+ currency: string
+}
+
+/** Settings of the `price_sack` delivery calculator. */
+export interface DeliveryCalculatorPriceSackPreferences {
+ /** An amount, as an exact decimal string. */
+ minimal_amount: string
+ /** An amount, as an exact decimal string. */
+ normal_amount: string
+ /** An amount, as an exact decimal string. */
+ discount_amount: string
+ /** Format: `currency`. */
+ currency: string
+}
+
+/**
+ * The settings of each delivery calculator type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface DeliveryCalculatorPreferencesMap {
+ digital_delivery: DeliveryCalculatorDigitalDeliveryPreferences
+ flat_percent_item_total: DeliveryCalculatorFlatPercentItemTotalPreferences
+ flat_rate: DeliveryCalculatorFlatRatePreferences
+ flexi_rate: DeliveryCalculatorFlexiRatePreferences
+ per_item: DeliveryCalculatorPerItemPreferences
+ price_sack: DeliveryCalculatorPriceSackPreferences
+}
+
+/** Settings of the `channel_rule` delivery method rule. */
+export interface DeliveryMethodRuleChannelRulePreferences {
+ /** Prefixed `ch_` ids. */
+ channel_ids: Array<string>
+}
+
+/** Settings of the `company_rule` delivery method rule. */
+export interface DeliveryMethodRuleCompanyRulePreferences {
+ company_orders_only: boolean
+}
+
+/** Settings of the `excluded_products_rule` delivery method rule: none. */
+export type DeliveryMethodRuleExcludedProductsRulePreferences = Record<string, never>
+
+/** Settings of the `item_total_rule` delivery method rule. */
+export interface DeliveryMethodRuleItemTotalRulePreferences {
+ /** An amount, as an exact decimal string. */
+ minimum_amount: string | null
+ /** An amount, as an exact decimal string. */
+ maximum_amount: string | null
+}
+
+/** Settings of the `volume_rule` delivery method rule. */
+export interface DeliveryMethodRuleVolumeRulePreferences {
+ minimum_volume: string | null
+ maximum_volume: string | null
+}
+
+/** Settings of the `weight_rule` delivery method rule. */
+export interface DeliveryMethodRuleWeightRulePreferences {
+ minimum_weight: string | null
+ maximum_weight: string | null
+}
+
+/**
+ * The settings of each delivery method rule type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface DeliveryMethodRulePreferencesMap {
+ channel_rule: DeliveryMethodRuleChannelRulePreferences
+ company_rule: DeliveryMethodRuleCompanyRulePreferences
+ excluded_products_rule: DeliveryMethodRuleExcludedProductsRulePreferences
+ item_total_rule: DeliveryMethodRuleItemTotalRulePreferences
+ volume_rule: DeliveryMethodRuleVolumeRulePreferences
+ weight_rule: DeliveryMethodRuleWeightRulePreferences
+}
+
+/** A delivery method rule whose `preferences` are typed by its `type`. */
+export type TypedDeliveryMethodRule = Narrowed<DeliveryMethodRule, DeliveryMethodRulePreferencesMap>
+
+/**
+ * The settings of each integration type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+// biome-ignore lint/suspicious/noEmptyInterface: extensions add their types by declaration merging
+export interface IntegrationPreferencesMap {}
+
+/** An integration whose `preferences` are typed by its `type`. */
+export type TypedIntegration = Narrowed<Integration, IntegrationPreferencesMap>
+
+/** Settings of the `default_location` order routing rule: none. */
+export type OrderRoutingRuleDefaultLocationPreferences = Record<string, never>
+
+/** Settings of the `minimize_splits` order routing rule: none. */
+export type OrderRoutingRuleMinimizeSplitsPreferences = Record<string, never>
+
+/** Settings of the `preferred_location` order routing rule: none. */
+export type OrderRoutingRulePreferredLocationPreferences = Record<string, never>
+
+/**
+ * The settings of each order routing rule type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface OrderRoutingRulePreferencesMap {
+ default_location: OrderRoutingRuleDefaultLocationPreferences
+ minimize_splits: OrderRoutingRuleMinimizeSplitsPreferences
+ preferred_location: OrderRoutingRulePreferredLocationPreferences
+}
+
+/** An order routing rule whose `preferences` are typed by its `type`. */
+export type TypedOrderRoutingRule = Narrowed<OrderRoutingRule, OrderRoutingRulePreferencesMap>
+
+/** Settings of the `bogus` payment method. */
+export interface PaymentMethodBogusPreferences {
+ dummy_key: string
+ /** Masked when read (`••••1234`); send it back unchanged to keep it, `null` to clear it. */
+ dummy_secret_key: string | null
+}
+
+/** Settings of the `check` payment method: none. */
+export type PaymentMethodCheckPreferences = Record<string, never>
+
+/** Settings of the `custom_payment_source_method` payment method: none. */
+export type PaymentMethodCustomPaymentSourceMethodPreferences = Record<string, never>
+
+/** Settings of the `store_credit` payment method: none. */
+export type PaymentMethodStoreCreditPreferences = Record<string, never>
+
+/**
+ * The settings of each payment method type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface PaymentMethodPreferencesMap {
+ bogus: PaymentMethodBogusPreferences
+ check: PaymentMethodCheckPreferences
+ custom_payment_source_method: PaymentMethodCustomPaymentSourceMethodPreferences
+ store_credit: PaymentMethodStoreCreditPreferences
+}
+
+/** A payment method whose `preferences` are typed by its `type`. */
+export type TypedPaymentMethod = Narrowed<PaymentMethod, PaymentMethodPreferencesMap>
+
+/** Settings of the `channel_rule` price rule. */
+export interface PriceRuleChannelRulePreferences {
+ /** Prefixed `ch_` ids. */
+ channel_ids: Array<string>
+}
+
+/** Settings of the `customer_group_rule` price rule. */
+export interface PriceRuleCustomerGroupRulePreferences {
+ /** Prefixed `cg_` ids. */
+ customer_group_ids: Array<string>
+}
+
+/** Settings of the `market_rule` price rule. */
+export interface PriceRuleMarketRulePreferences {
+ /** Prefixed `mkt_` ids. */
+ market_ids: Array<string>
+}
+
+/** Settings of the `user_rule` price rule. */
+export interface PriceRuleUserRulePreferences {
+ /** Prefixed `cust_` ids. */
+ user_ids: Array<string>
+}
+
+/** Settings of the `volume_rule` price rule. */
+export interface PriceRuleVolumeRulePreferences {
+ min_quantity: number
+ max_quantity: number | null
+}
+
+/**
+ * The settings of each price rule type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface PriceRulePreferencesMap {
+ channel_rule: PriceRuleChannelRulePreferences
+ customer_group_rule: PriceRuleCustomerGroupRulePreferences
+ market_rule: PriceRuleMarketRulePreferences
+ user_rule: PriceRuleUserRulePreferences
+ volume_rule: PriceRuleVolumeRulePreferences
+}
+
+/** A price rule whose `preferences` are typed by its `type`. */
+export type TypedPriceRule = Narrowed<PriceRule, PriceRulePreferencesMap>
+
+/** Settings of the `flat_percent_item_total` promotion calculator. */
+export interface PromotionCalculatorFlatPercentItemTotalPreferences {
+ flat_percent: string
+}
+
+/** Settings of the `flat_rate` promotion calculator. */
+export interface PromotionCalculatorFlatRatePreferences {
+ /** An amount, as an exact decimal string. */
+ amount: string
+ /** Format: `currency`. */
+ currency: string
+ apply_only_on_full_priced_items: boolean
+}
+
+/** Settings of the `flexi_rate` promotion calculator. */
+export interface PromotionCalculatorFlexiRatePreferences {
+ /** An amount, as an exact decimal string. */
+ first_item: string
+ /** An amount, as an exact decimal string. */
+ additional_item: string
+ max_items: number
+ /** Format: `currency`. */
+ currency: string
+ apply_only_on_full_priced_items: boolean
+}
+
+/** Settings of the `percent_on_line_item` promotion calculator. */
+export interface PromotionCalculatorPercentOnLineItemPreferences {
+ percent: string
+ apply_only_on_full_priced_items: boolean
+}
+
+/** Settings of the `tiered_flat_rate` promotion calculator. */
+export interface PromotionCalculatorTieredFlatRatePreferences {
+ tiers: Array<{ threshold: string; value: string }>
+ /** An amount, as an exact decimal string. */
+ base_amount: string
+ /** Format: `currency`. */
+ currency: string
+}
+
+/** Settings of the `tiered_percent` promotion calculator. */
+export interface PromotionCalculatorTieredPercentPreferences {
+ tiers: Array<{ threshold: string; value: string }>
+ base_percent: string
+}
+
+/**
+ * The settings of each promotion calculator type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface PromotionCalculatorPreferencesMap {
+ flat_percent_item_total: PromotionCalculatorFlatPercentItemTotalPreferences
+ flat_rate: PromotionCalculatorFlatRatePreferences
+ flexi_rate: PromotionCalculatorFlexiRatePreferences
+ percent_on_line_item: PromotionCalculatorPercentOnLineItemPreferences
+ tiered_flat_rate: PromotionCalculatorTieredFlatRatePreferences
+ tiered_percent: PromotionCalculatorTieredPercentPreferences
+}
+
+/** Settings of the `category` promotion rule. */
+export interface PromotionRuleCategoryPreferences {
+ match_policy: 'any' | 'all'
+}
+
+/** Settings of the `channel` promotion rule. */
+export interface PromotionRuleChannelPreferences {
+ /** Prefixed `ch_` ids. */
+ channel_ids: Array<string>
+}
+
+/** Settings of the `country` promotion rule. */
+export interface PromotionRuleCountryPreferences {
+ country_codes: Array<string>
+ country_id: number | null
+ /** Format: `iso-country`. */
+ country_code: string | null
+}
+
+/** Settings of the `currency` promotion rule. */
+export interface PromotionRuleCurrencyPreferences {
+ /** Format: `currency`. */
+ currency: string | null
+}
+
+/** Settings of the `customer` promotion rule: none. */
+export type PromotionRuleCustomerPreferences = Record<string, never>
+
+/** Settings of the `customer_group` promotion rule. */
+export interface PromotionRuleCustomerGroupPreferences {
+ /** Prefixed `cg_` ids. */
+ customer_group_ids: Array<string>
+}
+
+/** Settings of the `customer_logged_in` promotion rule: none. */
+export type PromotionRuleCustomerLoggedInPreferences = Record<string, never>
+
+/** Settings of the `first_order` promotion rule: none. */
+export type PromotionRuleFirstOrderPreferences = Record<string, never>
+
+/** Settings of the `item_total` promotion rule. */
+export interface PromotionRuleItemTotalPreferences {
+ /** An amount, as an exact decimal string. */
+ amount_min: string
+ operator_min: string
+ /** An amount, as an exact decimal string. */
+ amount_max: string | null
+ operator_max: string
+}
+
+/** Settings of the `market` promotion rule. */
+export interface PromotionRuleMarketPreferences {
+ /** Prefixed `mkt_` ids. */
+ market_ids: Array<string>
+}
+
+/** Settings of the `one_use_per_user` promotion rule: none. */
+export type PromotionRuleOneUsePerUserPreferences = Record<string, never>
+
+/** Settings of the `option_value` promotion rule. */
+export interface PromotionRuleOptionValuePreferences {
+ match_policy: 'any'
+ /** Prefixed `optval_` ids. */
+ eligible_values: Array<string>
+}
+
+/** Settings of the `product` promotion rule. */
+export interface PromotionRuleProductPreferences {
+ match_policy: 'any' | 'all' | 'none'
+}
+
+/**
+ * The settings of each promotion rule type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface PromotionRulePreferencesMap {
+ category: PromotionRuleCategoryPreferences
+ channel: PromotionRuleChannelPreferences
+ country: PromotionRuleCountryPreferences
+ currency: PromotionRuleCurrencyPreferences
+ customer: PromotionRuleCustomerPreferences
+ customer_group: PromotionRuleCustomerGroupPreferences
+ customer_logged_in: PromotionRuleCustomerLoggedInPreferences
+ first_order: PromotionRuleFirstOrderPreferences
+ item_total: PromotionRuleItemTotalPreferences
+ market: PromotionRuleMarketPreferences
+ one_use_per_user: PromotionRuleOneUsePerUserPreferences
+ option_value: PromotionRuleOptionValuePreferences
+ product: PromotionRuleProductPreferences
+}
+
+/** A promotion rule whose `preferences` are typed by its `type`. */
+export type TypedPromotionRule = Narrowed<PromotionRule, PromotionRulePreferencesMap>
+
+/** Settings of the `accept_terms` seller requirement. */
+export interface SellerRequirementAcceptTermsPreferences {
+ terms_body: string | null
+ /** Format: `date`. */
+ terms_effective_from: string | null
+ terms_url: string | null
+}
+
+/** Settings of the `attestation` seller requirement: none. */
+export type SellerRequirementAttestationPreferences = Record<string, never>
+
+/** Settings of the `billing_address` seller requirement: none. */
+export type SellerRequirementBillingAddressPreferences = Record<string, never>
+
+/** Settings of the `complete_profile` seller requirement. */
+export interface SellerRequirementCompleteProfilePreferences {
+ require_about: boolean
+ require_logo: boolean
+ require_cover_photo: boolean
+ require_contact_email: boolean
+}
+
+/** Settings of the `delivery_method` seller requirement: none. */
+export type SellerRequirementDeliveryMethodPreferences = Record<string, never>
+
+/** Settings of the `document` seller requirement: none. */
+export type SellerRequirementDocumentPreferences = Record<string, never>
+
+/** Settings of the `minimum_products` seller requirement. */
+export interface SellerRequirementMinimumProductsPreferences {
+ minimum_count: number
+}
+
+/** Settings of the `operator_review` seller requirement: none. */
+export type SellerRequirementOperatorReviewPreferences = Record<string, never>
+
+/** Settings of the `package_type` seller requirement: none. */
+export type SellerRequirementPackageTypePreferences = Record<string, never>
+
+/** Settings of the `payout_account` seller requirement: none. */
+export type SellerRequirementPayoutAccountPreferences = Record<string, never>
+
+/** Settings of the `policy` seller requirement: none. */
+export type SellerRequirementPolicyPreferences = Record<string, never>
+
+/** Settings of the `required_custom_fields` seller requirement: none. */
+export type SellerRequirementRequiredCustomFieldsPreferences = Record<string, never>
+
+/** Settings of the `returns_address` seller requirement: none. */
+export type SellerRequirementReturnsAddressPreferences = Record<string, never>
+
+/**
+ * The settings of each seller requirement type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface SellerRequirementPreferencesMap {
+ accept_terms: SellerRequirementAcceptTermsPreferences
+ attestation: SellerRequirementAttestationPreferences
+ billing_address: SellerRequirementBillingAddressPreferences
+ complete_profile: SellerRequirementCompleteProfilePreferences
+ delivery_method: SellerRequirementDeliveryMethodPreferences
+ document: SellerRequirementDocumentPreferences
+ minimum_products: SellerRequirementMinimumProductsPreferences
+ operator_review: SellerRequirementOperatorReviewPreferences
+ package_type: SellerRequirementPackageTypePreferences
+ payout_account: SellerRequirementPayoutAccountPreferences
+ policy: SellerRequirementPolicyPreferences
+ required_custom_fields: SellerRequirementRequiredCustomFieldsPreferences
+ returns_address: SellerRequirementReturnsAddressPreferences
+}
+
+/** A seller requirement whose `preferences` are typed by its `type`. */
+export type TypedSellerRequirement = Narrowed<SellerRequirement, SellerRequirementPreferencesMap>
diff --git a/packages/admin-sdk/src/zod/generated/Channel.ts b/packages/admin-sdk/src/zod/generated/Channel.ts
index c0771d39ee..c93524499f 100644
--- a/packages/admin-sdk/src/zod/generated/Channel.ts
+++ b/packages/admin-sdk/src/zod/generated/Channel.ts
@@ -7,13 +7,11 @@ export const ChannelSchema = z.object({
code: z.string(),
active: z.boolean(),
default: z.boolean(),
- storefront_access: z.string(),
- guest_checkout: z.boolean(),
- preferred_storefront_access: z.string().nullable(),
- preferred_guest_checkout: z.boolean().nullable(),
+ storefront_access: z.string().nullable(),
+ guest_checkout: z.boolean().nullable(),
created_at: z.string(),
updated_at: z.string(),
- preferred_order_routing_strategy: z.string().nullable(),
+ order_routing_strategy: z.string().nullable(),
stock_location_ids: z.array(z.string()),
default_catalog_id: z.string().nullable(),
});
diff --git a/packages/admin-sdk/src/zod/generated/CommissionRule.ts b/packages/admin-sdk/src/zod/generated/CommissionRule.ts
index c82273426c..d5b8f70b44 100644
--- a/packages/admin-sdk/src/zod/generated/CommissionRule.ts
+++ b/packages/admin-sdk/src/zod/generated/CommissionRule.ts
@@ -10,7 +10,6 @@ export const CommissionRuleSchema = z.object({
type: z.string(),
commission_rate_id: z.string(),
preferences: z.record(z.string(), z.unknown()),
- preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown() })),
product_ids: z.array(z.string()).nullable(),
seller_ids: z.array(z.string()).nullable(),
category_ids: z.array(z.string()).nullable(),
diff --git a/packages/admin-sdk/src/zod/generated/DeliveryMethod.ts b/packages/admin-sdk/src/zod/generated/DeliveryMethod.ts
index 5754302c48..7a3afe3b24 100644
--- a/packages/admin-sdk/src/zod/generated/DeliveryMethod.ts
+++ b/packages/admin-sdk/src/zod/generated/DeliveryMethod.ts
@@ -33,8 +33,7 @@ export const DeliveryMethodSchema = z.object({
fulfillment_provider: z.string(),
pickup_point_provider: z.string().nullable(),
rate_provider: z.string().nullable(),
- calculator_type: z.string().nullable(),
- calculator_preferences: z.record(z.string(), z.unknown()).nullable(),
+ calculator: z.object({ type: z.string(), preferences: z.record(z.string(), z.unknown()) }).nullable(),
});
export type DeliveryMethod = z.infer<typeof DeliveryMethodSchema>;
diff --git a/packages/admin-sdk/src/zod/generated/DeliveryMethodRule.ts b/packages/admin-sdk/src/zod/generated/DeliveryMethodRule.ts
index f2bd1c4d89..78187f7371 100644
--- a/packages/admin-sdk/src/zod/generated/DeliveryMethodRule.ts
+++ b/packages/admin-sdk/src/zod/generated/DeliveryMethodRule.ts
@@ -8,7 +8,6 @@ export const DeliveryMethodRuleSchema = z.object({
updated_at: z.string(),
type: z.string(),
preferences: z.record(z.string(), z.unknown()),
- preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown(), choices: z.array(z.string()).optional() })),
product_ids: z.array(z.string()),
});
diff --git a/packages/admin-sdk/src/zod/generated/Import.ts b/packages/admin-sdk/src/zod/generated/Import.ts
index b785be4222..4e2505d9c8 100644
--- a/packages/admin-sdk/src/zod/generated/Import.ts
+++ b/packages/admin-sdk/src/zod/generated/Import.ts
@@ -16,7 +16,7 @@ export const ImportSchema = z.object({
owner_id: z.string().nullable(),
user_id: z.string().nullable(),
processing_errors: z.string().nullable(),
- preferred_delimiter: z.string(),
+ delimiter: z.string(),
price_list_id: z.string().nullable(),
seller_name: z.string().nullable(),
original_filename: z.string().nullable(),
diff --git a/packages/admin-sdk/src/zod/generated/Integration.ts b/packages/admin-sdk/src/zod/generated/Integration.ts
index b9a38157f3..e30fd73fef 100644
--- a/packages/admin-sdk/src/zod/generated/Integration.ts
+++ b/packages/admin-sdk/src/zod/generated/Integration.ts
@@ -10,7 +10,6 @@ export const IntegrationSchema = z.object({
type: z.string(),
group: z.string().nullable(),
preferences: z.record(z.string(), z.unknown()),
- preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown(), choices: z.array(z.string()).optional() })),
});
export type Integration = z.infer<typeof IntegrationSchema>;
diff --git a/packages/admin-sdk/src/zod/generated/OrderRoutingRule.ts b/packages/admin-sdk/src/zod/generated/OrderRoutingRule.ts
index cc627dc8a0..baa9e2dd96 100644
--- a/packages/admin-sdk/src/zod/generated/OrderRoutingRule.ts
+++ b/packages/admin-sdk/src/zod/generated/OrderRoutingRule.ts
@@ -10,7 +10,6 @@ export const OrderRoutingRuleSchema = z.object({
type: z.string(),
channel_id: z.string(),
preferences: z.record(z.string(), z.unknown()),
- preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown(), choices: z.array(z.string()).optional() })),
});
export type OrderRoutingRule = z.infer<typeof OrderRoutingRuleSchema>;
diff --git a/packages/admin-sdk/src/zod/generated/PaymentMethod.ts b/packages/admin-sdk/src/zod/generated/PaymentMethod.ts
index 2cb2b23dc2..419db9e39c 100644
--- a/packages/admin-sdk/src/zod/generated/PaymentMethod.ts
+++ b/packages/admin-sdk/src/zod/generated/PaymentMethod.ts
@@ -18,7 +18,6 @@ export const PaymentMethodSchema = z.object({
created_at: z.string(),
updated_at: z.string(),
preferences: z.record(z.string(), z.unknown()),
- preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown(), choices: z.array(z.string()).optional() })),
logo_url: z.string().nullable(),
docs_url: z.string().nullable(),
third_party: z.boolean(),
diff --git a/packages/admin-sdk/src/zod/generated/PriceRule.ts b/packages/admin-sdk/src/zod/generated/PriceRule.ts
index 033b4ee86a..691485e51c 100644
--- a/packages/admin-sdk/src/zod/generated/PriceRule.ts
+++ b/packages/admin-sdk/src/zod/generated/PriceRule.ts
@@ -12,7 +12,6 @@ export const PriceRuleSchema = z.object({
type: z.string(),
price_list_id: z.string(),
preferences: z.record(z.string(), z.unknown()),
- preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown() })),
get markets() { return z.array(MarketSchema).optional(); },
get customer_groups() { return z.array(CustomerGroupSchema).optional(); },
channels: z.array(ChannelSchema).optional(),
diff --git a/packages/admin-sdk/src/zod/generated/PromotionAction.ts b/packages/admin-sdk/src/zod/generated/PromotionAction.ts
index d70b89b35d..4f2a325aa6 100644
--- a/packages/admin-sdk/src/zod/generated/PromotionAction.ts
+++ b/packages/admin-sdk/src/zod/generated/PromotionAction.ts
@@ -8,8 +8,7 @@ export const PromotionActionSchema = z.object({
type: z.string(),
promotion_id: z.string(),
preferences: z.record(z.string(), z.unknown()),
- preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown(), choices: z.array(z.string()).optional() })),
- calculator: z.object({ type: z.string(), preferences: z.record(z.string(), z.unknown()), preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown() })) }).nullable(),
+ calculator: z.object({ type: z.string(), preferences: z.record(z.string(), z.unknown()) }).nullable(),
line_items: z.array(z.object({ variant_id: z.string(), quantity: z.number() })).nullable(),
});
diff --git a/packages/admin-sdk/src/zod/generated/PromotionRule.ts b/packages/admin-sdk/src/zod/generated/PromotionRule.ts
index 5551904d37..3345bce79e 100644
--- a/packages/admin-sdk/src/zod/generated/PromotionRule.ts
+++ b/packages/admin-sdk/src/zod/generated/PromotionRule.ts
@@ -16,7 +16,6 @@ export const PromotionRuleSchema = z.object({
type: z.string(),
promotion_id: z.string(),
preferences: z.record(z.string(), z.unknown()),
- preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown(), choices: z.array(z.string()).optional() })),
product_ids: z.array(z.string()).nullable(),
category_ids: z.array(z.string()).nullable(),
customer_ids: z.array(z.string()).nullable(),
diff --git a/packages/admin-sdk/tests/imports.test.ts b/packages/admin-sdk/tests/imports.test.ts
index 7cb913d968..a9c0e71886 100644
--- a/packages/admin-sdk/tests/imports.test.ts
+++ b/packages/admin-sdk/tests/imports.test.ts
@@ -15,7 +15,7 @@ const sampleImport = {
owner_id: 'store_1',
user_id: 'usr_admin',
processing_errors: null,
- preferred_delimiter: ',',
+ delimiter: ',',
schema_fields: [
{ name: 'slug', label: 'Slug', required: true },
{ name: 'price', label: 'Price', required: true },
@@ -95,13 +95,13 @@ describe('imports', () => {
const res = await client.imports.create({
type: 'products',
attachment: 'signed-blob-id',
- preferred_delimiter: ';',
+ delimiter: ';',
})
expect(body).toEqual({
type: 'products',
attachment: 'signed-blob-id',
- preferred_delimiter: ';',
+ delimiter: ';',
})
expect(res.status).toBe('mapping')
expect(res.mappings).toHaveLength(2)
diff --git a/packages/admin-sdk/tests/order-routing-rules.test.ts b/packages/admin-sdk/tests/order-routing-rules.test.ts
index 0a4b3b65e4..17eaeec1fa 100644
--- a/packages/admin-sdk/tests/order-routing-rules.test.ts
+++ b/packages/admin-sdk/tests/order-routing-rules.test.ts
@@ -12,7 +12,6 @@ const sampleRule = {
label: 'Preferred location',
description: 'Fulfill from the location pinned on the order, when one is set',
preferences: {},
- preference_schema: [],
created_at: '2026-07-01T00:00:00Z',
updated_at: '2026-07-01T00:00:00Z',
}
@@ -94,7 +93,7 @@ describe('orderRoutingRules', () => {
type: 'preferred_location',
label: 'Preferred location',
description: null,
- preference_schema: [],
+ schema: { type: 'object', properties: {}, additionalProperties: false },
},
],
}),
diff --git a/packages/admin-sdk/tests/payment-methods.test.ts b/packages/admin-sdk/tests/payment-methods.test.ts
index 34d1eef30e..f0c45edb64 100644
--- a/packages/admin-sdk/tests/payment-methods.test.ts
+++ b/packages/admin-sdk/tests/payment-methods.test.ts
@@ -123,7 +123,11 @@ describe('paymentMethods', () => {
type: 'bogus',
label: 'Bogus Gateway',
description: 'Test gateway for development',
- preference_schema: [{ key: 'server', type: 'string', default: 'test' }],
+ schema: {
+ type: 'object',
+ properties: { server: { type: 'string', default: 'test' } },
+ additionalProperties: false,
+ },
},
],
})
diff --git a/packages/admin-sdk/tests/price-lists.test.ts b/packages/admin-sdk/tests/price-lists.test.ts
index d87f84851f..65b52fac71 100644
--- a/packages/admin-sdk/tests/price-lists.test.ts
+++ b/packages/admin-sdk/tests/price-lists.test.ts
@@ -173,7 +173,11 @@ describe('priceLists', () => {
type: 'volume_rule',
label: 'Volume Rule',
description: 'Apply pricing based on quantity purchased',
- preference_schema: [{ key: 'min_quantity', type: 'integer', default: 1 }],
+ schema: {
+ type: 'object',
+ properties: { min_quantity: { type: 'integer', default: 1 } },
+ additionalProperties: false,
+ },
},
],
}),
diff --git a/packages/dashboard-core/src/api-client.ts b/packages/dashboard-core/src/api-client.ts
index b268650fec..0cb0f4b204 100644
--- a/packages/dashboard-core/src/api-client.ts
+++ b/packages/dashboard-core/src/api-client.ts
@@ -417,7 +417,7 @@ export interface PanelImport {
completed_rows_count: number
failed_rows_count: number
processing_errors?: string | null
- preferred_delimiter?: string
+ delimiter?: string
schema_fields: Array<{ name: string; label: string; required: boolean }>
csv_headers: string[]
sample_row: Record<string, string | null>
@@ -458,7 +458,7 @@ export interface PanelImportCreateParams {
/** Signed blob id of the already direct-uploaded CSV. */
attachment: string
/** CSV column separator — the four both APIs accept. */
- preferred_delimiter?: PanelImportDelimiter
+ delimiter?: PanelImportDelimiter
/** The price list a `price_list_prices` import merges into. */
price_list_id?: string
results_url?: string
diff --git a/packages/dashboard-core/src/components/preferences-form.tsx b/packages/dashboard-core/src/components/preferences-form.tsx
index 5a5e4dfdb6..dd45cec5f8 100644
--- a/packages/dashboard-core/src/components/preferences-form.tsx
+++ b/packages/dashboard-core/src/components/preferences-form.tsx
@@ -1,7 +1,8 @@
import {
compareMoney,
isDecimalString,
- type PreferenceField as PreferenceFieldDef,
+ type PreferencePropertySchema,
+ type PreferenceSchema,
} from '@spree/admin-sdk'
import {
Button,
@@ -28,26 +29,81 @@ import { useId, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useMoneyLocale } from '../hooks/use-money-locale'
import { currencyParts } from '../lib/currency-parts'
+import { CountryCombobox, CountryMultiCombobox } from './country-combobox'
import { CurrencySelect } from './currency-select'
import { StoreDatePicker } from './store-date-picker'
+/**
+ * One setting of a {@link PreferenceSchema}, flattened into what a form
+ * needs to pick its widget.
+ */
+export interface PreferenceFieldDef {
+ key: string
+ /** `string`, `text`, `password`, `boolean`, `integer`, `decimal`, `date`, `datetime`, `array`, `hash` or `object`. */
+ type: string
+ /** The schema's `format` (`money`, `currency`, `iso-country`, …), on the value or, for a list, on its items. */
+ format?: string
+ default: unknown
+ choices?: string[]
+ /** Whether the setting may be left empty (it reads back as null). */
+ nullable: boolean
+ /** The property's own JSON Schema, for widgets that need more (list items, object properties). */
+ schema: PreferencePropertySchema
+}
+
+const DECIMAL_PATTERN = '^-?\\d+(\\.\\d+)?$'
+
+function fieldType(property: PreferencePropertySchema): string {
+ if (property['x-spree-secret']) return 'password'
+ const type = (Array.isArray(property.type) ? property.type : [property.type]).find(
+ (t) => t && t !== 'null',
+ )
+ if (type === 'string') {
+ if (property.format === 'date') return 'date'
+ if (property.format === 'date-time') return 'datetime'
+ if (property.format === 'money') return 'money'
+ if (property.pattern === DECIMAL_PATTERN) return 'decimal'
+ if (property['x-spree-widget'] === 'textarea') return 'text'
+ return 'string'
+ }
+ if (type === 'object') return property.properties ? 'object' : 'hash'
+ return type ?? 'string'
+}
+
+/**
+ * Flattens a preference schema into the fields a form renders, in the order
+ * the type declares them.
+ */
+export function preferenceFields(
+ schema: PreferenceSchema | null | undefined,
+): PreferenceFieldDef[] {
+ return Object.entries(schema?.properties ?? {}).map(([key, property]) => ({
+ key,
+ type: fieldType(property),
+ format: property.format ?? property.items?.format,
+ default: property.default ?? null,
+ choices: property.enum?.filter((choice): choice is string => typeof choice === 'string'),
+ nullable: Array.isArray(property.type) && property.type.includes('null'),
+ schema: property,
+ }))
+}
+
/**
* Hydrates a `preferences` hash with each field's default. Used to seed
* create-mode forms when the user picks a provider/calculator so the
* `<PreferencesForm>` shows sensible starting values instead of blanks.
*
- * `:password` fields are always skipped — the server returns their
- * defaults as `null`, and even when it doesn't, autofilling a password
- * field is hostile UX. `contextDefaults` fills schema-declared keys whose
- * own default is null/undefined — used by callers that know about runtime
+ * Secrets are always skipped — the schema never carries their defaults, and
+ * autofilling a password field is hostile UX. `contextDefaults` fills keys
+ * whose own default is absent — used by callers that know about runtime
* context the schema can't express (e.g. the store's default currency).
*/
export function defaultPreferences(
- schema: PreferenceFieldDef[],
+ schema: PreferenceSchema | null | undefined,
contextDefaults: Record<string, unknown> = {},
): Record<string, unknown> {
const out: Record<string, unknown> = {}
- for (const field of schema) {
+ for (const field of preferenceFields(schema)) {
if (field.type === 'password') continue
if (field.default !== null && field.default !== undefined) {
// A decimal default declared as a Ruby integer arrives as a JSON number,
@@ -65,7 +121,7 @@ export function defaultPreferences(
}
interface PreferencesFormProps {
- schema: PreferenceFieldDef[]
+ schema: PreferenceSchema | null | undefined
values: Record<string, unknown>
onChange: (next: Record<string, unknown>) => void
/** When true, replaces sensitive `password`-typed fields with a stub label. */
@@ -89,16 +145,16 @@ interface PreferencesFormProps {
}
/**
- * Renders a generic configuration form from a `preference_schema` payload.
+ * Renders a generic configuration form from a type's preference schema.
* Used by the Payment Methods edit sheet and the Promotion editor's action
* and rule cards — anywhere we let admins tune a STI subclass's settings
* without hard-coding a per-subclass form.
*
* The schema itself is the source of truth; this component intentionally
* stays "dumb" — server-side validation surfaces errors back via the
- * mutation hook's error handling. Booleans are switches, strings are
- * inputs, integers/decimals get number inputs, and unknown types fall
- * back to a plain text input.
+ * mutation hook's error handling. The widget follows the schema: booleans
+ * are switches, currencies and countries pickers, amounts number inputs
+ * that send the exact decimal string, and anything else a text input.
*/
export function PreferencesForm({
schema,
@@ -109,7 +165,8 @@ export function PreferencesForm({
currencyOptions,
inlineDatePickers,
}: PreferencesFormProps) {
- if (!schema?.length) return null
+ const fields = useMemo(() => preferenceFields(schema), [schema])
+ if (!fields.length) return null
function setValue(key: string, value: unknown) {
if (Object.is(values[key], value)) return
@@ -118,7 +175,7 @@ export function PreferencesForm({
return (
<FieldGroup>
- {schema.map((field) => (
+ {fields.map((field) => (
<PreferenceField
key={field.key}
field={field}
@@ -172,10 +229,9 @@ export function PreferenceField({
const descriptionKey = `${preferenceKey}_description`
const description = i18n.exists(descriptionKey) ? t(descriptionKey) : undefined
- // Currency-typed preferences (`currency`, `default_currency`,
- // `display_currency`, …) get the store's CurrencySelect — same
- // localized `CODE — Full Name` rendering as the rest of admin.
- if (isCurrencyKey(field.key)) {
+ // Currencies get the store's CurrencySelect — same localized
+ // `CODE — Full Name` rendering as the rest of admin.
+ if (field.type === 'string' && field.format === 'currency') {
return (
<Field>
<FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
@@ -189,11 +245,33 @@ export function PreferenceField({
)
}
- // `tiers` preference (Spree::Calculator::TieredPercent /
- // TieredFlatRate) — a list of `{ threshold, value }` objects that the
- // default array input would render as `[object Object]`. Render a row
- // editor so the merchant can add tier breakpoints directly.
- if (field.key === 'tiers') {
+ if (field.type === 'string' && field.format === 'iso-country') {
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
+ <CountryCombobox id={id} value={(value as string) ?? null} onValueChange={onChange} />
+ </Field>
+ )
+ }
+
+ if (field.type === 'array' && field.format === 'iso-country') {
+ return (
+ <Field>
+ <FieldLabel>{displayLabel}</FieldLabel>
+ <CountryMultiCombobox
+ value={Array.isArray(value) ? (value as string[]) : []}
+ onValueChange={onChange}
+ />
+ </Field>
+ )
+ }
+
+ // A tier ladder (the tiered calculators) — a list of
+ // `{ threshold, value }` objects that the default array input would render
+ // as `[object Object]`. Render a row editor so the merchant can add tier
+ // breakpoints directly.
+ const itemProperties = field.schema.items?.properties
+ if (field.type === 'array' && itemProperties?.threshold && itemProperties?.value) {
return <TiersEditor value={value} onChange={onChange} />
}
@@ -258,7 +336,7 @@ export function PreferenceField({
type="number"
step="any"
placeholder={
- isMaxKey(field.key) ? t('admin.components.preferences_form.unlimited') : undefined
+ field.nullable ? t('admin.components.preferences_form.unlimited') : undefined
}
value={value === null || value === undefined ? '' : String(value)}
onChange={(e) => {
@@ -282,10 +360,10 @@ export function PreferenceField({
id={id}
type="number"
step={field.type === 'integer' ? 1 : 'any'}
- // An empty upper-bound field means "no limit" — surface that
+ // An empty optional field means "no limit" — surface that
// rather than leaving it looking like a required blank.
placeholder={
- isMaxKey(field.key) ? t('admin.components.preferences_form.unlimited') : undefined
+ field.nullable ? t('admin.components.preferences_form.unlimited') : undefined
}
value={value === null || value === undefined ? '' : String(value)}
onChange={(e) => {
@@ -396,19 +474,6 @@ function humanizeKey(key: string): string {
.join(' ')
}
-function isCurrencyKey(key: string): boolean {
- return key === 'currency' || key.endsWith('_currency')
-}
-
-// Upper-bound preferences (`max_quantity`, `max_uses`, `usage_max`,
-// `maximum_amount`, …) read "Unlimited" when left blank. Matched on the key
-// name because the wire schema doesn't carry a nullable flag — safe since the
-// placeholder only shows for an empty value, and an empty max legitimately
-// means no ceiling.
-function isMaxKey(key: string): boolean {
- return /(?:^|_)max(?:imum)?(?:_|$)/.test(key)
-}
-
interface TierValue {
threshold: string
value: string
diff --git a/packages/dashboard-core/src/hooks/use-import.ts b/packages/dashboard-core/src/hooks/use-import.ts
index bd8e59b229..6f44cd4dee 100644
--- a/packages/dashboard-core/src/hooks/use-import.ts
+++ b/packages/dashboard-core/src/hooks/use-import.ts
@@ -90,7 +90,7 @@ function imports() {
/** Create-time parameters beyond the ones every import shares. */
export type ImportCreateExtras = Omit<
PanelImportCreateParams,
- 'type' | 'attachment' | 'preferred_delimiter' | 'results_url'
+ 'type' | 'attachment' | 'delimiter' | 'results_url'
>
export interface CreateImportInput {
@@ -129,7 +129,7 @@ export function useCreateImport() {
...params,
type,
attachment: signedId,
- preferred_delimiter: preferredDelimiter,
+ delimiter: preferredDelimiter,
// The import-done email deep-links back to the wizard (`?import=<id>`
// appended server-side). Only honored when this origin is on the
// store's allowed-origins list.
diff --git a/packages/dashboard-core/src/lib/i18n.ts b/packages/dashboard-core/src/lib/i18n.ts
index bf702e4d9b..cca20f347d 100644
--- a/packages/dashboard-core/src/lib/i18n.ts
+++ b/packages/dashboard-core/src/lib/i18n.ts
@@ -10,7 +10,7 @@ import en from '../locales/en.json'
// made anywhere is honored on the next paint.
export const ADMIN_LOCALE_STORAGE_KEY = 'spree-admin-locale'
-// Marks the locale key as auto-applied from a store's `preferred_admin_locale`
+// Marks the locale key as auto-applied from a store's `admin_locale`
// (vs an explicit choice). Holds the storeId whose default is currently in
// effect, so crossing into a different store can re-apply that store's default
// while a genuine choice (switcher/profile/login) still wins everywhere. Mirrors
@@ -69,10 +69,10 @@ function readStoredLocale(): string {
}
/**
- * Reconcile the admin UI language against a store's `preferred_admin_locale`
+ * Reconcile the admin UI language against a store's `admin_locale`
* fallback (legacy `base_controller` parity), for an admin with no genuine
* personal choice. Encodes the precedence:
- * account selected_locale > genuine stored choice > store preferred_admin_locale > 'en'
+ * account selected_locale > genuine stored choice > store admin_locale > 'en'
*
* No-op when a higher tier owns the language (an account locale, or a genuine
* stored choice — locale key set without an auto-marker). Otherwise drives the
@@ -83,7 +83,7 @@ function readStoredLocale(): string {
* - already matching → nothing changes.
* Reloads (via the boot path) only when the displayed language actually changes.
*
- * @param code the store's current `preferred_admin_locale`
+ * @param code the store's current `admin_locale`
* @param storeId the store being entered
* @param accountLocale the account's `selected_locale` (null when unset)
* @param supported locale codes the dashboard ships a bundle for
diff --git a/packages/dashboard-core/src/lib/storefront.ts b/packages/dashboard-core/src/lib/storefront.ts
index 45affbd3a6..1d942a17c2 100644
--- a/packages/dashboard-core/src/lib/storefront.ts
+++ b/packages/dashboard-core/src/lib/storefront.ts
@@ -5,14 +5,14 @@ import type { Store } from '@spree/admin-sdk'
* or `null` when no storefront URL is configured.
*
* The serialized `store.url` always resolves — the backend falls back to the
- * store's formatted URL — so gate on the explicit `preferred_storefront_url`
+ * store's formatted URL — so gate on the explicit `storefront_url`
* preference: only return a link once a real storefront has been set.
*
* @param store the current store, or null/undefined while it loads
* @returns an absolute URL, or null when the store has no configured storefront
*/
export function storefrontHref(store: Store | null | undefined): string | null {
- if (!store?.preferred_storefront_url) return null
+ if (!store?.storefront_url) return null
// Best-effort: prefix with https if the URL is just a hostname.
return /^https?:\/\//.test(store.url) ? store.url : `https://${store.url}`
diff --git a/packages/dashboard-core/src/providers/store-provider.tsx b/packages/dashboard-core/src/providers/store-provider.tsx
index 54376cf299..31d6318f11 100644
--- a/packages/dashboard-core/src/providers/store-provider.tsx
+++ b/packages/dashboard-core/src/providers/store-provider.tsx
@@ -64,7 +64,7 @@ export function StoreProvider({ storeId, children }: { storeId: string; children
// that path already owns the locale via `switchAdminLocale`, and re-applying
// would race that PATCH and could reload before it lands. Tracking the
// storeId it last ran for re-arms it per store, so a multi-store admin still
- // inherits each store's preferred_admin_locale.
+ // inherits each store's admin_locale.
const localeFallbackStoreRef = useRef<string | null>(null)
const query = useQuery({
@@ -83,7 +83,7 @@ export function StoreProvider({ storeId, children }: { storeId: string; children
localeFallbackStoreRef.current = storeId
reconcileStoreDefaultLocale(
- store.preferred_admin_locale,
+ store.admin_locale,
storeId,
accountLocaleRef.current,
coreLocaleCodes(),
@@ -99,7 +99,7 @@ export function StoreProvider({ storeId, children }: { storeId: string; children
// A store's zone preference defaults to the host app's `Time.zone.name`,
// which may be a Rails name ("Eastern Time (US & Canada)") that Intl and
// date-fns-tz reject — falling back keeps every date control working.
- const timezone = resolveTimezone(store?.preferred_timezone)
+ const timezone = resolveTimezone(store?.timezone)
return (
<StoreContext.Provider
diff --git a/packages/dashboard-ui/src/spree/calculator-summary.tsx b/packages/dashboard-ui/src/spree/calculator-summary.tsx
index 30de118c9e..904a646b93 100644
--- a/packages/dashboard-ui/src/spree/calculator-summary.tsx
+++ b/packages/dashboard-ui/src/spree/calculator-summary.tsx
@@ -5,7 +5,8 @@
* model (delivery methods, tax rates, …).
*
* The expected payload mirrors the admin API's calculator embed: a
- * `{ label, preferences, preference_schema }` triple. The component is
+ * `{ label, preferences, schema }` triple, `schema` being the JSON Schema of
+ * the calculator's preferences. The component is
* tolerant of partial input — missing schema or preferences just fall
* back to the label alone.
*
@@ -22,7 +23,14 @@ export interface CalculatorPayload {
/** STI class name (e.g. "Spree::Calculator::FlatRate"). Used as a label fallback. */
type?: string | null
preferences?: Record<string, unknown> | null
- preference_schema?: ReadonlyArray<{ key: string; type: string }> | null
+ schema?: { properties?: Record<string, CalculatorPropertySchema> } | null
+}
+
+/** The part of a preference's JSON Schema the summary reads. */
+interface CalculatorPropertySchema {
+ type?: string | string[]
+ format?: string
+ pattern?: string
}
interface CalculatorSummaryProps {
@@ -60,14 +68,14 @@ export function formatCalculatorSummary(
calculator.label?.trim() ||
(calculator.type ? (calculator.type.split('::').pop() ?? calculator.type) : '')
- const schema = calculator.preference_schema
+ const properties = Object.entries(calculator.schema?.properties ?? {})
const prefs = calculator.preferences
- if (!schema?.length || !prefs) return label || null
+ if (!properties.length || !prefs) return label || null
const currency = (typeof prefs.currency === 'string' && prefs.currency) || 'USD'
- const details = schema
- .map((field) => formatField(field, prefs[field.key], currency))
+ const details = properties
+ .map(([key, property]) => formatField(key, property, prefs[key], currency))
.filter((s): s is string => s !== null)
.join(', ')
@@ -76,39 +84,35 @@ export function formatCalculatorSummary(
}
/**
- * Formats one preference value by naming convention. Calculators don't
- * carry richer field metadata (no `display_format`, no `unit`), so we
- * fall back to key-name heuristics that match the Ruby preference
- * declarations in `Spree::Calculator::*`.
+ * Formats one preference value from its schema.
*
- * - `amount` / `*_amount` decimals → currency-formatted.
- * - `*_percent` decimals → `N%`.
- * - `currency` strings → omitted (folded into the money formatting).
+ * - money → currency-formatted.
+ * - `*_percent` values → `N%`.
+ * - currencies → omitted (folded into the money formatting).
* - booleans → humanized key when true; skipped when false.
- * - lists (tiers) → their length; other objects → omitted.
+ * - lists (tiers) → their length; objects → omitted.
* - everything else → `key: value`.
*/
function formatField(
- field: { key: string; type: string },
+ key: string,
+ property: CalculatorPropertySchema,
value: unknown,
currency: string,
): string | null {
if (value === null || value === undefined || value === '') return null
- if (field.key === 'currency') return null
+ if (property.format === 'currency') return null
+ if (property.format === 'money') return formatMoney(value, currency)
+ if (/(?:^|_)percent$/.test(key)) return `${value}%`
- if (field.type === 'money') return formatMoney(value, currency)
- if (field.type === 'decimal') {
- if (/(?:^|_)percent$/.test(field.key)) return `${value}%`
- return `${humanize(field.key)}: ${value}`
- }
- if (field.type === 'boolean') {
- return value ? humanize(field.key) : null
- }
- if (field.type === 'array') {
- return Array.isArray(value) && value.length ? `${humanize(field.key)}: ${value.length}` : null
+ const type = (Array.isArray(property.type) ? property.type : [property.type]).find(
+ (t) => t !== 'null',
+ )
+ if (type === 'boolean') return value ? humanize(key) : null
+ if (type === 'array') {
+ return Array.isArray(value) && value.length ? `${humanize(key)}: ${value.length}` : null
}
- if (field.type === 'hash') return null
- return `${humanize(field.key)}: ${value}`
+ if (type === 'object') return null
+ return `${humanize(key)}: ${value}`
}
function formatMoney(value: unknown, currency: string): string {
diff --git a/packages/dashboard/e2e/channels-settings.spec.ts b/packages/dashboard/e2e/channels-settings.spec.ts
index b57bf630f0..8ab2cbf6f2 100644
--- a/packages/dashboard/e2e/channels-settings.spec.ts
+++ b/packages/dashboard/e2e/channels-settings.spec.ts
@@ -82,7 +82,7 @@ test.describe('settings / channels', () => {
// Pick the routing strategy by its human label — the dropdown must surface
// readable option labels, never the raw strategy class name.
- await page.locator('#preferred_order_routing_strategy').click()
+ await page.locator('#order_routing_strategy').click()
await page.getByRole('option', { name: /^rules \(ordered\)$/i }).click()
await page.getByRole('button', { name: /^save$/i }).click()
@@ -92,9 +92,7 @@ test.describe('settings / channels', () => {
// Reopening reads the saved strategy back into the same readable option.
await rowButton(page, updated).click()
await expect(page.getByRole('heading', { name: updated })).toBeVisible({ timeout: 15_000 })
- await expect(page.locator('#preferred_order_routing_strategy')).toContainText(
- /^rules \(ordered\)$/i,
- )
+ await expect(page.locator('#order_routing_strategy')).toContainText(/^rules \(ordered\)$/i)
})
test('names the default catalog picker for assistive technology', async ({ page }) => {
@@ -137,7 +135,7 @@ test.describe('settings / channels', () => {
// Wait for the select popup to fully close after the pick so a lingering
// overlay can't intercept the next click. (No Escape here — the popup
// closes on selection, and a stray Escape would close the sheet instead.)
- await page.locator('#preferred_order_routing_strategy').click()
+ await page.locator('#order_routing_strategy').click()
await page.getByRole('option', { name: /^rules \(ordered\)$/i }).click()
await expect(page.getByRole('listbox')).toBeHidden()
await expect(ruleRow(/preferred location/i)).toBeVisible()
diff --git a/packages/dashboard/e2e/store-settings.spec.ts b/packages/dashboard/e2e/store-settings.spec.ts
index 9f91a7b5ca..b4a4bbfab7 100644
--- a/packages/dashboard/e2e/store-settings.spec.ts
+++ b/packages/dashboard/e2e/store-settings.spec.ts
@@ -92,7 +92,7 @@ test.describe('store settings — general', () => {
// Pick Polish (endonym shown in the picker) and save. The page is currently
// in German (the precondition above), so the Save button reads "Speichern".
- // Saving persists preferred_admin_locale AND switches the dashboard into
+ // Saving persists admin_locale AND switches the dashboard into
// Polish, reloading so every module-load `i18n.t(...)` label re-resolves.
await page.locator('#store-admin-locale').click()
await page.getByRole('option', { name: /polski/i }).click()
diff --git a/packages/dashboard/src/components/spree/integrations/configure-integration-sheet.tsx b/packages/dashboard/src/components/spree/integrations/configure-integration-sheet.tsx
index aac1b954e0..cd7f3e9021 100644
--- a/packages/dashboard/src/components/spree/integrations/configure-integration-sheet.tsx
+++ b/packages/dashboard/src/components/spree/integrations/configure-integration-sheet.tsx
@@ -53,7 +53,7 @@ export function ConfigureIntegrationSheet({
const [preferences, setPreferences] = useState<Record<string, unknown>>(() =>
integration
? ((integration.preferences as Record<string, unknown>) ?? {})
- : defaultPreferences(type.preference_schema),
+ : defaultPreferences(type.schema),
)
const [active, setActive] = useState(integration?.active ?? defaultActive)
const [submitError, setSubmitError] = useState<string | null>(null)
@@ -109,11 +109,7 @@ export function ConfigureIntegrationSheet({
</p>
)}
- <PreferencesForm
- schema={type.preference_schema}
- values={preferences}
- onChange={setPreferences}
- />
+ <PreferencesForm schema={type.schema} values={preferences} onChange={setPreferences} />
<div className="flex items-center justify-between gap-3">
<div className="flex flex-col">
diff --git a/packages/dashboard/src/components/spree/order-routing-rules-section.tsx b/packages/dashboard/src/components/spree/order-routing-rules-section.tsx
index 639dc5ceae..0d4df9382a 100644
--- a/packages/dashboard/src/components/spree/order-routing-rules-section.tsx
+++ b/packages/dashboard/src/components/spree/order-routing-rules-section.tsx
@@ -15,7 +15,12 @@ import {
verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
-import type { OrderRoutingRule, PaginatedResponse, ResourceTypeDefinition } from '@spree/admin-sdk'
+import type {
+ OrderRoutingRule,
+ PaginatedResponse,
+ PreferenceSchema,
+ ResourceTypeDefinition,
+} from '@spree/admin-sdk'
import {
Can,
PreferencesForm,
@@ -217,7 +222,7 @@ function SortableRuleRow({
disabled: !canUpdate,
})
const style: CSSProperties = { transform: CSS.Transform.toString(transform), transition }
- const hasPreferences = rule.preference_schema.length > 0
+ const hasPreferences = Object.keys(definition?.schema?.properties ?? {}).length > 0
const label = typeLabel('order_routing_rule', rule.type, definition?.label)
const description = typeDescription('order_routing_rule', rule.type, definition?.description)
@@ -268,7 +273,12 @@ function SortableRuleRow({
)}
</div>
{editing && hasPreferences && (
- <RulePreferencesEditor rule={rule} onSave={onSavePreferences} onCancel={onToggleEdit} />
+ <RulePreferencesEditor
+ rule={rule}
+ schema={definition?.schema}
+ onSave={onSavePreferences}
+ onCancel={onToggleEdit}
+ />
)}
</li>
)
@@ -276,10 +286,12 @@ function SortableRuleRow({
function RulePreferencesEditor({
rule,
+ schema,
onSave,
onCancel,
}: {
rule: OrderRoutingRule
+ schema: PreferenceSchema | undefined
onSave: (preferences: Record<string, unknown>) => void
onCancel: () => void
}) {
@@ -288,7 +300,7 @@ function RulePreferencesEditor({
return (
<div className="flex flex-col gap-3 border-t p-3">
- <PreferencesForm schema={rule.preference_schema} values={values} onChange={setValues} />
+ <PreferencesForm schema={schema} values={values} onChange={setValues} />
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" size="sm" onClick={onCancel}>
{t('admin.actions.cancel')}
diff --git a/packages/dashboard/src/components/spree/payment-method-editors/payment-method-form.tsx b/packages/dashboard/src/components/spree/payment-method-editors/payment-method-form.tsx
index bc73eec246..d3e9214718 100644
--- a/packages/dashboard/src/components/spree/payment-method-editors/payment-method-form.tsx
+++ b/packages/dashboard/src/components/spree/payment-method-editors/payment-method-form.tsx
@@ -1,4 +1,4 @@
-import type { PaymentMethod, PreferenceField } from '@spree/admin-sdk'
+import type { PaymentMethod, PreferenceSchema } from '@spree/admin-sdk'
import { PreferencesForm, Slot, useSlotEntries } from '@spree/dashboard-core'
import {
Field,
@@ -30,7 +30,7 @@ import {
interface ProviderOption {
type: string
label: string
- preference_schema: PreferenceField[]
+ schema: PreferenceSchema
}
interface PaymentMethodFormProps {
@@ -44,7 +44,7 @@ interface PaymentMethodFormProps {
* `providerTypes` against the selected `type` (the parent does this so
* it can also seed `preferences` with defaults on type change).
*/
- preferenceSchema: PreferenceField[]
+ preferenceSchema: PreferenceSchema | undefined
/** Current provider's STI shorthand — drives slot lookups. */
providerType: string
/** Loaded server record in edit mode; null while creating. */
@@ -147,7 +147,8 @@ export function PaymentMethodForm({
{providerType && <Slot name={paymentMethodGuideSlot(providerType)} context={slotContext} />}
- {providerType && (customFormRegistered || preferenceSchema.length > 0) ? (
+ {providerType &&
+ (customFormRegistered || Object.keys(preferenceSchema?.properties ?? {}).length > 0) ? (
<div className="rounded-md border bg-muted/30 p-3">
<h3 className="mb-2 text-sm font-medium">
{t('admin.fields.payment_method.provider_configuration')}
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 6838488c18..4677405895 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
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import type { PaymentMethodType, PreferenceField } from '@spree/admin-sdk'
+import type { PaymentMethodType, PreferenceSchema } from '@spree/admin-sdk'
import { defaultPreferences, mapSpreeErrorsToForm, useStore } from '@spree/dashboard-core'
import {
Button,
@@ -55,7 +55,10 @@ export function CreatePaymentMethodSheet({
const { t } = useTranslation()
const createMutation = useCreatePaymentMethod()
const { data: typesResponse, isLoading: loadingTypes } = usePaymentMethodTypes()
- const providerTypes = useMemo(() => typesResponse?.data ?? [], [typesResponse])
+ const providerTypes = useMemo(
+ () => (typesResponse?.data ?? []).filter((type) => !type.installed),
+ [typesResponse],
+ )
// Seed `currency`-typed preferences with the store default so the merchant
// sees and submits a real value — `CurrencySelect` only displays the
// fallback now (it no longer commits via onChange).
@@ -65,9 +68,7 @@ export function CreatePaymentMethodSheet({
? { ...PAYMENT_METHOD_CREATE_DEFAULTS, type: initialType.type, name: initialType.label }
: PAYMENT_METHOD_CREATE_DEFAULTS
const initialPreferences = () =>
- initialType
- ? defaultPreferences(initialType.preference_schema, { currency: defaultCurrency })
- : {}
+ initialType ? defaultPreferences(initialType.schema, { currency: defaultCurrency }) : {}
const form = useForm<PaymentMethodFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -77,13 +78,13 @@ export function CreatePaymentMethodSheet({
const [preferences, setPreferences] = useState<Record<string, unknown>>(initialPreferences)
const providerType = form.watch('type') ?? ''
- const preferenceSchema: PreferenceField[] = useMemo(
- () => providerTypes.find((t) => t.type === providerType)?.preference_schema ?? [],
+ const preferenceSchema: PreferenceSchema | undefined = useMemo(
+ () => providerTypes.find((t) => t.type === providerType)?.schema,
[providerTypes, providerType],
)
function handleProviderTypeChange(next: string) {
- const nextSchema = providerTypes.find((t) => t.type === next)?.preference_schema ?? []
+ const nextSchema = providerTypes.find((t) => t.type === next)?.schema
setPreferences(defaultPreferences(nextSchema, { currency: defaultCurrency }))
}
@@ -175,6 +176,12 @@ export function EditPaymentMethodSheet({
const { t } = useTranslation()
const { data: paymentMethod, isLoading } = usePaymentMethod(id)
const updateMutation = useUpdatePaymentMethod(id)
+ // The provider's preference schema comes from its `/types` entry, matched
+ // by the record's `type`.
+ const { data: typesData } = usePaymentMethodTypes({ enabled: open })
+ const preferenceSchema = typesData?.data.find(
+ (entry) => entry.type === paymentMethod?.type,
+ )?.schema
const form = useForm<PaymentMethodFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -255,7 +262,7 @@ export function EditPaymentMethodSheet({
<PaymentMethodForm
mode="edit"
form={form}
- preferenceSchema={paymentMethod?.preference_schema ?? []}
+ preferenceSchema={preferenceSchema}
providerType={providerType}
paymentMethod={paymentMethod ?? null}
preferences={preferences}
diff --git a/packages/dashboard/src/components/spree/payment-method-editors/types.ts b/packages/dashboard/src/components/spree/payment-method-editors/types.ts
index 2b7af2728f..f94d33976e 100644
--- a/packages/dashboard/src/components/spree/payment-method-editors/types.ts
+++ b/packages/dashboard/src/components/spree/payment-method-editors/types.ts
@@ -1,4 +1,4 @@
-import type { PaymentMethod, PreferenceField } from '@spree/admin-sdk'
+import type { PaymentMethod, PreferenceSchema } from '@spree/admin-sdk'
import type { UseFormReturn } from 'react-hook-form'
import type { PaymentMethodFormValues } from '../../../schemas/payment-method'
@@ -32,7 +32,7 @@ export interface PaymentMethodEditorContext {
type: string
/** Loaded server record in `edit` mode; `null` in `create` mode. */
paymentMethod: PaymentMethod | null
- preferenceSchema: PreferenceField[]
+ preferenceSchema: PreferenceSchema | undefined
preferences: Record<string, unknown>
onPreferencesChange: (next: Record<string, unknown>) => void
/** react-hook-form instance for the top-level fields. */
diff --git a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
index a83fdc48a4..984c476207 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
@@ -818,12 +818,11 @@ function RuleSummary({
// Fall back to the generic preferences dump for everything else
// (Volume Rule's min_quantity, etc.). Skip keys already covered above.
- for (const field of draft.preference_schema ?? []) {
- if (PREFS_SHOWN_VIA_EMBED.has(field.key)) continue
- const value = draft.preferences?.[field.key]
+ for (const [key, value] of Object.entries(draft.preferences ?? {})) {
+ if (PREFS_SHOWN_VIA_EMBED.has(key)) continue
if (value === null || value === undefined || value === '') continue
if (Array.isArray(value) && value.length === 0) continue
- parts.push(`${humanize(field.key)}: ${formatPreferenceValue(value, t)}`)
+ parts.push(`${humanize(key)}: ${formatPreferenceValue(value, t)}`)
}
if (parts.length === 0) {
@@ -977,7 +976,9 @@ function DefaultRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {
setValues(draft.preferences ?? {})
}, [draft])
- const hasPreferences = !!draft.preference_schema?.length
+ const { data: typesData } = usePriceRuleTypes()
+ const schema = typesData?.data.find((type) => type.type === draft.type)?.schema
+ const hasPreferences = Object.keys(schema?.properties ?? {}).length > 0
function handleSave() {
onSave({ ...draft, preferences: values })
@@ -992,7 +993,7 @@ function DefaultRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {
saveDisabled={!hasPreferences && draft.preferences == null}
>
{hasPreferences ? (
- <PreferencesForm schema={draft.preference_schema} values={values} onChange={setValues} />
+ <PreferencesForm schema={schema} values={values} onChange={setValues} />
) : (
<p className="text-sm text-muted-foreground">
{t('admin.pages.products.price_lists.rule_no_options')}
diff --git a/packages/dashboard/src/components/spree/price-list-editors/rule-channel.tsx b/packages/dashboard/src/components/spree/price-list-editors/rule-channel.tsx
index 5c894b8806..c176c37bc4 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/rule-channel.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/rule-channel.tsx
@@ -8,22 +8,17 @@ import { EditorShell } from '../promotion-editors/editor-shell'
import type { PriceRuleEditorContext } from './types'
/**
- * Multi-select channel picker for the Channel price rule. Seeds from
- * `draft.channels` (the serializer embed, prefixed `ch_…` IDs) because
- * `preferences.channel_ids` holds raw integer IDs server-side. Writes the
- * selected ids back to `preferences.channel_ids` and the resolved records to
- * `draft.channels` for the rule summary.
+ * Multi-select channel picker for the Channel price rule. Reads and writes
+ * the prefixed ids in `preferences.channel_ids`, and keeps the resolved
+ * records in `draft.channels` for the rule summary.
*/
export function ChannelRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {
const { t } = useTranslation()
// Preload the full channel list so the picker surfaces options on open
// without the merchant having to type — the list is small and cached.
const { data: channelsData } = useChannels()
- // Seed from `draft.channels` (the embed) — `preferences.channel_ids`
- // holds raw integer IDs server-side while the embed carries the prefixed
- // `ch_…` IDs the picker round-trips.
- const [channelIds, setChannelIds] = useState<string[]>(() =>
- (draft.channels ?? []).map((c) => c.id),
+ const [channelIds, setChannelIds] = useState<string[]>(
+ () => (draft.preferences?.channel_ids ?? []) as string[],
)
const [channels, setChannels] = useState<RuleEmbedRecord[]>(draft.channels ?? [])
diff --git a/packages/dashboard/src/components/spree/price-list-editors/rule-customer-group.tsx b/packages/dashboard/src/components/spree/price-list-editors/rule-customer-group.tsx
index c9d5a0888a..83bfbdda91 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/rule-customer-group.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/rule-customer-group.tsx
@@ -15,11 +15,8 @@ export function CustomerGroupRuleEditor({ draft, onSave, onClose }: PriceRuleEdi
// Preload the full customer-group list so the picker surfaces options on
// open without the merchant having to type — the list is small and cached.
const { data: customerGroupsData } = useCustomerGroups()
- // Seed from `draft.customer_groups` (the embed) — `preferences.customer_group_ids`
- // holds raw integer IDs server-side while the embed carries the prefixed `cg_…`
- // IDs the picker round-trips.
- const [groupIds, setGroupIds] = useState<string[]>(() =>
- (draft.customer_groups ?? []).map((g) => g.id),
+ const [groupIds, setGroupIds] = useState<string[]>(
+ () => (draft.preferences?.customer_group_ids ?? []) as string[],
)
const [customerGroups, setCustomerGroups] = useState<RuleEmbedRecord[]>(
draft.customer_groups ?? [],
diff --git a/packages/dashboard/src/components/spree/price-list-editors/rule-customer.tsx b/packages/dashboard/src/components/spree/price-list-editors/rule-customer.tsx
index 93bef6f0de..64dc6b48a0 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/rule-customer.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/rule-customer.tsx
@@ -14,11 +14,8 @@ import type { PriceRuleEditorContext } from './types'
*/
export function CustomerRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {
const { t } = useTranslation()
- // Seed from `draft.customers` (the embed) — `preferences.user_ids` holds raw
- // integer IDs server-side while the embed carries the prefixed customer IDs
- // the picker round-trips.
- const [customerIds, setCustomerIds] = useState<string[]>(() =>
- (draft.customers ?? []).map((c) => c.id),
+ const [customerIds, setCustomerIds] = useState<string[]>(
+ () => (draft.preferences?.user_ids ?? []) as string[],
)
// RuleEmbedRecord, not Customer — the draft's embed fields are opaque to
// keep the SDK object graph out of the form type (see RuleEmbedRecord).
diff --git a/packages/dashboard/src/components/spree/price-list-editors/rule-market.tsx b/packages/dashboard/src/components/spree/price-list-editors/rule-market.tsx
index 2705d1e096..3dd53a0d7a 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/rule-market.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/rule-market.tsx
@@ -8,16 +8,16 @@ import { EditorShell } from '../promotion-editors/editor-shell'
import type { PriceRuleEditorContext } from './types'
/**
- * Multi-select market picker for the Market price rule. Seeds from
- * `draft.markets` (the serializer embed) because `preferences.market_ids`
- * holds raw integer IDs server-side while the embed exposes the prefixed
- * `mkt_…` form the picker round-trips.
+ * Multi-select market picker for the Market price rule. Reads and writes
+ * the prefixed ids in `preferences.market_ids`.
*/
export function MarketRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {
const { t } = useTranslation()
const { markets } = useAllMarkets()
- const [marketIds, setMarketIds] = useState<string[]>(() => (draft.markets ?? []).map((m) => m.id))
+ const [marketIds, setMarketIds] = useState<string[]>(
+ () => (draft.preferences?.market_ids ?? []) as string[],
+ )
const selectedMarkets = useMemo<Market[]>(
() =>
diff --git a/packages/dashboard/src/components/spree/promotion-editors/action-adjustment.tsx b/packages/dashboard/src/components/spree/promotion-editors/action-adjustment.tsx
index ee06de88c6..7ad68c22ce 100644
--- a/packages/dashboard/src/components/spree/promotion-editors/action-adjustment.tsx
+++ b/packages/dashboard/src/components/spree/promotion-editors/action-adjustment.tsx
@@ -1,5 +1,5 @@
import type { PromotionActionCalculator } from '@spree/admin-sdk'
-import { adminClient, PreferencesForm, typeLabel } from '@spree/dashboard-core'
+import { defaultPreferences, PreferencesForm, typeLabel } from '@spree/dashboard-core'
import {
Field,
FieldGroup,
@@ -10,10 +10,10 @@ import {
SelectTrigger,
SelectValue,
} from '@spree/dashboard-ui'
-import { useQuery } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { usePromotionActionCalculators } from '../../../hooks/use-promotions'
import { resolveCalculatorType } from '../../../lib/promotion-calculator-type'
import { EditorShell } from './editor-shell'
@@ -26,10 +26,9 @@ import type { PromotionActionEditorContext } from './types'
*/
export function AdjustmentActionEditor({ draft, onSave, onClose }: PromotionActionEditorContext) {
const { t } = useTranslation()
- const { data: calculatorsData, isLoading: calculatorsLoading } = useQuery({
- queryKey: ['promotion-action-calculators', draft.type],
- queryFn: () => adminClient.promotionActions.calculators(draft.type),
- })
+ const { data: calculatorsData, isLoading: calculatorsLoading } = usePromotionActionCalculators(
+ draft.type,
+ )
const calculators = calculatorsData?.data ?? []
@@ -61,11 +60,7 @@ export function AdjustmentActionEditor({ draft, onSave, onClose }: PromotionActi
if (nextType === calculatorType) return
const next = calculators.find((c) => c.type === nextType)
setCalculatorType(nextType)
- setPreferences(
- Object.fromEntries(
- (next?.preference_schema ?? []).map((field) => [field.key, field.default ?? '']),
- ),
- )
+ setPreferences(defaultPreferences(next?.schema))
}
function handleSave() {
@@ -75,13 +70,11 @@ export function AdjustmentActionEditor({ draft, onSave, onClose }: PromotionActi
calculator: {
type: calculatorType,
preferences,
- // Display-only — lets `<ActionSummary>` render the row preview
- // without fetching `/calculators` again. Stripped at payload time.
- // The summary resolves the name from `type`; the catalog's English
- // name rides along as the fallback for a calculator shipped by an
- // extension that carries no dashboard translation.
+ // Display-only, stripped at payload time. The summary resolves the
+ // name from `type`; the catalog's English name rides along as the
+ // fallback for a calculator shipped by an extension that carries no
+ // dashboard translation.
label: selectedCalculator?.label,
- preference_schema: selectedCalculator?.preference_schema,
},
})
onClose()
@@ -151,7 +144,7 @@ function CalculatorPreferences({
}) {
const { t } = useTranslation()
- if (!calculator.preference_schema?.length) {
+ if (!Object.keys(calculator.schema?.properties ?? {}).length) {
return (
<p className="text-sm text-muted-foreground">
{t('admin.components.adjustment_action_editor.no_extra_settings')}
@@ -162,7 +155,7 @@ function CalculatorPreferences({
return (
<FieldGroup>
<FieldLabel>{t('admin.components.adjustment_action_editor.settings_label')}</FieldLabel>
- <PreferencesForm schema={calculator.preference_schema} values={values} onChange={onChange} />
+ <PreferencesForm schema={calculator.schema} values={values} onChange={onChange} />
</FieldGroup>
)
}
diff --git a/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx b/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx
index a25f5d6e17..47f709fd9b 100644
--- a/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx
+++ b/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx
@@ -73,6 +73,7 @@ import {
} from '@spree/dashboard-ui'
import { optionValueLabel } from '../../../hooks/use-option-types'
import {
+ usePromotionActionCalculators,
usePromotionActionTypes,
usePromotionCouponCodes,
usePromotionRuleTypes,
@@ -888,9 +889,8 @@ function RuleSummary({ draft }: { draft: PromotionRuleFormDraft }) {
// Fallback for preference-only rules (Currency, ItemTotal, FirstOrder,
// OneUsePerUser, UserLoggedIn, OptionValue, …) — these don't carry
- // embedded records, just a `preferences` hash. Walk the rule's
- // preference schema and format each value so drafts that haven't been
- // saved yet still get a useful row preview.
+ // embedded records, just a `preferences` hash. Format each value so
+ // drafts that haven't been saved yet still get a useful row preview.
const prefSummary = formatPreferencesSummary(draft)
if (prefSummary) parts.push(prefSummary)
@@ -912,15 +912,13 @@ const RULE_PREFS_SHOWN_ELSEWHERE = new Set([
function formatPreferencesSummary(draft: PromotionRuleFormDraft): string | null {
const prefs = draft.preferences
if (!prefs) return null
- const schema = draft.preference_schema ?? []
const pairs: string[] = []
- for (const field of schema) {
- if (RULE_PREFS_SHOWN_ELSEWHERE.has(field.key)) continue
- const value = prefs[field.key]
+ for (const [key, value] of Object.entries(prefs)) {
+ if (RULE_PREFS_SHOWN_ELSEWHERE.has(key)) continue
if (value === null || value === undefined || value === '') continue
if (Array.isArray(value) && value.length === 0) continue
- pairs.push(`${humanize(field.key)}: ${formatPreferenceValue(value)}`)
+ pairs.push(`${humanize(key)}: ${formatPreferenceValue(value)}`)
}
return pairs.length > 0 ? pairs.join(', ') : null
}
@@ -1073,7 +1071,9 @@ function RuleEditSheet({
function DefaultRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
const { t } = useTranslation()
const [values, setValues] = useState<Record<string, unknown>>(draft.preferences ?? {})
- const hasPreferences = !!draft.preference_schema?.length
+ const { data: typesData } = usePromotionRuleTypes()
+ const schema = typesData?.data.find((type) => type.type === draft.type)?.schema
+ const hasPreferences = Object.keys(schema?.properties ?? {}).length > 0
function handleSave() {
onSave({ ...draft, preferences: values })
@@ -1088,7 +1088,7 @@ function DefaultRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContex
saveLabel={hasPreferences ? undefined : t('admin.actions.add')}
>
{hasPreferences ? (
- <PreferencesForm schema={draft.preference_schema} values={values} onChange={setValues} />
+ <PreferencesForm schema={schema} values={values} onChange={setValues} />
) : (
<p className="text-sm text-muted-foreground">
{t('admin.promotions.rule_edit.no_options')}
@@ -1253,13 +1253,19 @@ function ActionRow({
function ActionSummary({ draft }: { draft: PromotionActionFormDraft }) {
const { t } = useTranslation()
const parts: string[] = []
- // dashboard-ui is headless, so the localized calculator name is resolved
- // here and handed to the formatter rather than looked up inside it.
+ const { data: calculatorsData } = usePromotionActionCalculators(
+ draft.calculator ? draft.type : undefined,
+ )
+ // dashboard-ui is headless, so the localized calculator name and the
+ // calculator's schema are resolved here and handed to the formatter.
+ const calculatorType = draft.calculator?.type
const calc = formatCalculatorSummary(
- draft.calculator?.type
+ calculatorType
? {
...draft.calculator,
- label: typeLabel('calculator', draft.calculator.type, draft.calculator.label),
+ label: typeLabel('calculator', calculatorType, draft.calculator?.label),
+ schema: calculatorsData?.data.find((calculator) => calculator.type === calculatorType)
+ ?.schema,
}
: draft.calculator,
)
@@ -1364,7 +1370,9 @@ function ActionEditSheet({
function DefaultActionEditor({ draft, onSave, onClose }: PromotionActionEditorContext) {
const { t } = useTranslation()
const [values, setValues] = useState<Record<string, unknown>>(draft.preferences ?? {})
- const hasPreferences = !!draft.preference_schema?.length
+ const { data: typesData } = usePromotionActionTypes()
+ const schema = typesData?.data.find((type) => type.type === draft.type)?.schema
+ const hasPreferences = Object.keys(schema?.properties ?? {}).length > 0
function handleSave() {
onSave({ ...draft, preferences: values })
@@ -1379,7 +1387,7 @@ function DefaultActionEditor({ draft, onSave, onClose }: PromotionActionEditorCo
saveLabel={hasPreferences ? undefined : t('admin.actions.add')}
>
{hasPreferences ? (
- <PreferencesForm schema={draft.preference_schema} values={values} onChange={setValues} />
+ <PreferencesForm schema={schema} values={values} onChange={setValues} />
) : (
<p className="text-sm text-muted-foreground">
{t('admin.promotions.action_edit.no_options')}
diff --git a/packages/dashboard/src/components/spree/promotion-editors/rule-channel.tsx b/packages/dashboard/src/components/spree/promotion-editors/rule-channel.tsx
index fc24eaa98e..cb77fe24ee 100644
--- a/packages/dashboard/src/components/spree/promotion-editors/rule-channel.tsx
+++ b/packages/dashboard/src/components/spree/promotion-editors/rule-channel.tsx
@@ -7,19 +7,17 @@ import { EditorShell } from './editor-shell'
import type { PromotionRuleEditorContext } from './types'
/**
- * Multi-select channel picker for the promotion Channel rule. Seeds from
- * `draft.channels` (the serializer embed, prefixed `ch_…` IDs) because
- * `preferences.channel_ids` holds raw integer IDs server-side. Writes the
- * selected ids back to `preferences.channel_ids` and the resolved records to
- * `draft.channels` for the rule summary.
+ * Multi-select channel picker for the promotion Channel rule. Reads and
+ * writes the prefixed ids in `preferences.channel_ids`, and keeps the resolved
+ * records in `draft.channels` for the rule summary.
*/
export function ChannelRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
const { t } = useTranslation()
// Preload the full channel list so the picker surfaces options on open
// without the merchant having to type — the list is small and cached.
const { data: channelsData } = useChannels()
- const [channelIds, setChannelIds] = useState<string[]>(() =>
- (draft.channels ?? []).map((c) => c.id),
+ const [channelIds, setChannelIds] = useState<string[]>(
+ () => (draft.preferences?.channel_ids ?? []) as string[],
)
const [channels, setChannels] = useState<Channel[]>(draft.channels ?? [])
diff --git a/packages/dashboard/src/components/spree/promotion-editors/rule-market.tsx b/packages/dashboard/src/components/spree/promotion-editors/rule-market.tsx
index d0e3378e44..faa12bd2b8 100644
--- a/packages/dashboard/src/components/spree/promotion-editors/rule-market.tsx
+++ b/packages/dashboard/src/components/spree/promotion-editors/rule-market.tsx
@@ -7,16 +7,16 @@ import { EditorShell } from './editor-shell'
import type { PromotionRuleEditorContext } from './types'
/**
- * Multi-select market picker for the promotion Market rule. Seeds from
- * `draft.markets` (the serializer embed) because `preferences.market_ids`
- * holds raw integer IDs server-side while the embed exposes the prefixed
- * `mkt_…` form the picker round-trips.
+ * Multi-select market picker for the promotion Market rule. Reads and writes
+ * the prefixed ids in `preferences.market_ids`.
*/
export function MarketRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
const { t } = useTranslation()
const { markets } = useAllMarkets()
- const [marketIds, setMarketIds] = useState<string[]>(() => (draft.markets ?? []).map((m) => m.id))
+ const [marketIds, setMarketIds] = useState<string[]>(
+ () => (draft.preferences?.market_ids ?? []) as string[],
+ )
const selectedMarkets = useMemo<Market[]>(
() =>
diff --git a/packages/dashboard/src/components/spree/promotion-editors/types.ts b/packages/dashboard/src/components/spree/promotion-editors/types.ts
index 88659626a8..98c5b88aa5 100644
--- a/packages/dashboard/src/components/spree/promotion-editors/types.ts
+++ b/packages/dashboard/src/components/spree/promotion-editors/types.ts
@@ -6,7 +6,7 @@ import type {
CustomerGroup,
Market,
OptionValue,
- PreferenceField,
+ PreferenceSchema,
Product,
PromotionAction,
PromotionActionCalculatorParams,
@@ -18,16 +18,15 @@ import type {
import { defaultPreferences } from '@spree/dashboard-core'
/**
- * Form-state row for a promotion rule. Carries everything the editor
- * needs to render (`key`, `preference_schema`) plus the payload fields
- * the SDK ships on save (extends `PromotionRuleDraft`). The rule's name
- * is resolved from `type` at render time, so no copy is stored here.
+ * Form-state row for a promotion rule: the payload fields the SDK ships on
+ * save (extends `PromotionRuleDraft`) plus display-only embeds. The rule's
+ * name and preference schema are resolved from `type` at render time, so no
+ * copy is stored here.
*
* Drafts seeded from existing rules carry the server's `id`; drafts
* created via the picker have no id until the parent form saves.
*/
export interface PromotionRuleFormDraft extends PromotionRuleDraft {
- preference_schema: PreferenceField[]
/** Client-side row id, used for React keys when the row has no server id yet. */
_localId: string
/**
@@ -49,19 +48,16 @@ export interface PromotionRuleFormDraft extends PromotionRuleDraft {
/** Mirrors `PromotionRuleFormDraft` for actions. */
export interface PromotionActionFormDraft extends Omit<PromotionActionDraft, 'calculator'> {
- preference_schema: PreferenceField[]
_localId: string
/**
* Form-only calculator shape — extends the API's `{ type, preferences }`
- * payload with `preference_schema` so the action-row summary can render
- * the calculator preview without round-tripping. Stripped at payload
- * time by `actionDraftToPayload`.
+ * payload with the catalog's display name. Stripped at payload time by
+ * `actionDraftToPayload`.
*/
calculator?: PromotionActionCalculatorFormDraft
}
export interface PromotionActionCalculatorFormDraft extends PromotionActionCalculatorParams {
- preference_schema?: PreferenceField[]
/**
* The catalog's English name, carried only as the fallback for a
* calculator this dashboard has no translation for. Display resolves from
@@ -145,32 +141,24 @@ export function newLocalId(): string {
* `:currency`-typed prefs). Schema defaults still take precedence.
*/
export function ruleDraftFromType(
- type: {
- type: string
- preference_schema: PreferenceField[]
- },
+ type: { type: string; schema: PreferenceSchema },
contextDefaults: Record<string, unknown> = {},
): PromotionRuleFormDraft {
return {
_localId: newLocalId(),
type: type.type,
- preference_schema: type.preference_schema,
- preferences: defaultPreferences(type.preference_schema, contextDefaults),
+ preferences: defaultPreferences(type.schema, contextDefaults),
}
}
export function actionDraftFromType(
- type: {
- type: string
- preference_schema: PreferenceField[]
- },
+ type: { type: string; schema: PreferenceSchema },
contextDefaults: Record<string, unknown> = {},
): PromotionActionFormDraft {
return {
_localId: newLocalId(),
type: type.type,
- preference_schema: type.preference_schema,
- preferences: defaultPreferences(type.preference_schema, contextDefaults),
+ preferences: defaultPreferences(type.schema, contextDefaults),
}
}
@@ -180,7 +168,6 @@ export function ruleDraftFromRule(rule: PromotionRule): PromotionRuleFormDraft {
_localId: rule.id,
id: rule.id,
type: rule.type,
- preference_schema: rule.preference_schema,
preferences: rule.preferences,
product_ids: rule.product_ids ?? undefined,
category_ids: rule.category_ids ?? undefined,
@@ -201,7 +188,6 @@ export function actionDraftFromAction(action: PromotionAction): PromotionActionF
_localId: action.id,
id: action.id,
type: action.type,
- preference_schema: action.preference_schema,
preferences: action.preferences,
calculator: calculatorFromAction(action.calculator),
line_items: action.line_items ?? undefined,
@@ -215,7 +201,6 @@ function calculatorFromAction(
return {
type: c.type,
preferences: c.preferences,
- preference_schema: c.preference_schema,
}
}
@@ -223,22 +208,21 @@ function calculatorFromAction(
export function ruleDraftToPayload(draft: PromotionRuleFormDraft): PromotionRuleDraft {
const {
_localId: _,
- preference_schema: __,
- products: ___,
- categories: ____,
- customers: _____,
- customer_groups: ______,
- countries: _______,
- channels: ________,
- markets: _________,
- option_values: __________,
+ products: __,
+ categories: ___,
+ customers: ____,
+ customer_groups: _____,
+ countries: ______,
+ channels: _______,
+ markets: ________,
+ option_values: _________,
...rest
} = draft
return rest
}
export function actionDraftToPayload(draft: PromotionActionFormDraft): PromotionActionDraft {
- const { _localId: _, preference_schema: __, calculator, ...rest } = draft
+ const { _localId: _, calculator, ...rest } = draft
return {
...rest,
calculator: calculator
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 34afc31cca..220a73e666 100644
--- a/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx
+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx
@@ -5,7 +5,6 @@ import type {
DeliveryRateProviderOption,
DeliveryZone,
IntegrationTypeDefinition,
- PreferenceField,
Product,
} from '@spree/admin-sdk'
import {
@@ -1020,7 +1019,7 @@ function PricingCard({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }
const { data: calculators } = useDeliveryCalculators()
const { data: taxCategories } = useTaxCategories()
const selectedRateProvider = useSelectedRateProvider(form)
- const calculatorType = form.watch('calculator_type')
+ const calculatorType = form.watch('calculator.type')
// Carrier providers quote live rates, so the calculator's amount is never
// read — the field is hidden rather than offering pricing that does nothing.
@@ -1033,15 +1032,23 @@ function PricingCard({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }
label: typeLabel('calculator', calculator.type, calculator.name),
}))
const selectedCalculator = (calculators?.data ?? []).find((c) => c.type === calculatorType)
- const preferenceSchema = (selectedCalculator?.preference_schema ?? []) as PreferenceField[]
+ const preferenceSchema = selectedCalculator?.schema
// An amount-based calculator prices per currency, so its amount fields are
// rendered by the editor below rather than one-by-one from the schema. The
// rest of its preferences (weight and total bounds) still render generically.
const amountBased = AMOUNT_BASED_CALCULATORS.includes(calculatorType ?? '')
- const genericSchema = amountBased
- ? preferenceSchema.filter((field) => !CURRENCY_AMOUNT_KEYS.includes(field.key))
- : preferenceSchema
+ const genericSchema =
+ amountBased && preferenceSchema
+ ? {
+ ...preferenceSchema,
+ properties: Object.fromEntries(
+ Object.entries(preferenceSchema.properties).filter(
+ ([key]) => !CURRENCY_AMOUNT_KEYS.includes(key),
+ ),
+ ),
+ }
+ : preferenceSchema
const taxCategoryOptions = [
{ value: '', label: t('admin.common.none') },
@@ -1057,7 +1064,7 @@ function PricingCard({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }
{t('admin.fields.delivery_method.calculator.label')}
</FieldLabel>
<Controller
- name="calculator_type"
+ name="calculator.type"
control={form.control}
render={({ field }) => (
<Select
@@ -1081,7 +1088,7 @@ function PricingCard({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }
</Field>
<Controller
- name="calculator_preferences"
+ name="calculator.preferences"
control={form.control}
render={({ field }) => (
<>
@@ -1312,13 +1319,11 @@ function ConditionRuleRow({
const productBacked = ruleType?.association_fields?.includes('product_ids') ?? false
// Channel ids ride in preferences rather than an association field, but a
// bare id array is unusable as a text input — it needs the same picker.
- const channelBacked = (ruleType?.preference_schema ?? []).some(
- (preference) => preference.key === 'channel_ids',
- )
+ const channelBacked = Boolean(ruleType?.schema?.properties?.channel_ids)
const label = ruleType
? typeLabel('delivery_method_rule', ruleType.type, ruleType.name)
: fallbackLabel
- const schema = ruleType?.preference_schema ?? []
+ const schema = ruleType?.schema
return (
<div className="flex flex-col gap-2 rounded-md border p-3">
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx
index abb9d990e4..006c38856f 100644
--- a/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx
+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx
@@ -72,7 +72,7 @@ export function DeliveryMethodList({
const price = carrierPriced
? t('admin.delivery_methods.carrier_rates')
: formatListedPrice(
- method.calculator_preferences,
+ method.calculator?.preferences,
defaultCurrency,
i18n.language,
t('admin.delivery_methods.free'),
@@ -82,7 +82,7 @@ export function DeliveryMethodList({
const ruleSummary = summarizeRules(method.rules, {
t,
currency: defaultCurrency,
- weightUnit: store?.preferred_weight_unit ?? 'lb',
+ weightUnit: store?.weight_unit ?? 'lb',
locale: i18n.language,
})
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx
index b27fc9f12a..88b2844627 100644
--- a/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx
+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx
@@ -132,8 +132,10 @@ export function DeliveryMethodSheet({
estimated_transit_business_days_max:
method.estimated_transit_business_days_max?.toString() ?? '',
tax_category_id: method.tax_category_id ?? '',
- calculator_type: method.calculator_type ?? '',
- calculator_preferences: (method.calculator_preferences as Record<string, unknown>) ?? {},
+ calculator: {
+ type: method.calculator?.type ?? '',
+ preferences: method.calculator?.preferences ?? {},
+ },
delivery_zone_id: method.delivery_zone_id ?? '',
stock_location_ids: method.stock_location_ids ?? [],
markup_flat: decimalToForm(method.markup_flat),
diff --git a/packages/dashboard/src/components/spree/storefront-connect-sheet.tsx b/packages/dashboard/src/components/spree/storefront-connect-sheet.tsx
index 53c1a8d677..76619dcaed 100644
--- a/packages/dashboard/src/components/spree/storefront-connect-sheet.tsx
+++ b/packages/dashboard/src/components/spree/storefront-connect-sheet.tsx
@@ -82,7 +82,7 @@ export function StorefrontConnectSheet({
initialUrl,
}: StorefrontConnectSheetProps) {
const { t } = useTranslation()
- const [url, setUrl] = useState(() => initialUrl ?? store.preferred_storefront_url ?? '')
+ const [url, setUrl] = useState(() => initialUrl ?? store.storefront_url ?? '')
const [showKey, setShowKey] = useState(false)
const {
diff --git a/packages/dashboard/src/hooks/use-promotions.ts b/packages/dashboard/src/hooks/use-promotions.ts
index 087400d8f4..9c2048f878 100644
--- a/packages/dashboard/src/hooks/use-promotions.ts
+++ b/packages/dashboard/src/hooks/use-promotions.ts
@@ -199,3 +199,13 @@ export function usePromotionRuleTypes() {
staleTime: Infinity,
})
}
+
+/** The calculators a calculator-backed action may use, each with its preference schema. */
+export function usePromotionActionCalculators(actionType: string | undefined) {
+ return useQuery({
+ queryKey: ['promotion-action-calculators', actionType],
+ queryFn: () => adminClient.promotionActions.calculators(actionType as string),
+ enabled: !!actionType,
+ staleTime: Infinity,
+ })
+}
diff --git a/packages/dashboard/src/hooks/use-store-settings.ts b/packages/dashboard/src/hooks/use-store-settings.ts
index 40883a2a64..11291e19e1 100644
--- a/packages/dashboard/src/hooks/use-store-settings.ts
+++ b/packages/dashboard/src/hooks/use-store-settings.ts
@@ -69,7 +69,7 @@ export function useConnectStorefront() {
} catch (error) {
if (!(error instanceof SpreeError) || error.status !== 422) throw error
}
- await adminClient.store.update({ preferred_storefront_url: origin })
+ await adminClient.store.update({ storefront_url: origin })
return origin
},
invalidate: [[STORE_QUERY_RESOURCE], ['allowed-origins']],
diff --git a/packages/dashboard/src/lib/delivery-method-summary.test.ts b/packages/dashboard/src/lib/delivery-method-summary.test.ts
index 9d1574799e..8092e4e1c0 100644
--- a/packages/dashboard/src/lib/delivery-method-summary.test.ts
+++ b/packages/dashboard/src/lib/delivery-method-summary.test.ts
@@ -160,4 +160,11 @@ describe('applyCurrencyAmount', () => {
amounts: {},
})
})
+
+ it('sends the amount as the exact string typed, and a cleared default amount as zero', () => {
+ expect(applyCurrencyAmount({ amount: '5.0' }, 'USD', '9.99', 'USD')).toMatchObject({
+ amount: '9.99',
+ })
+ expect(applyCurrencyAmount({ amount: '5.0' }, 'USD', '', 'USD')).toMatchObject({ amount: '0' })
+ })
})
diff --git a/packages/dashboard/src/lib/delivery-method-summary.ts b/packages/dashboard/src/lib/delivery-method-summary.ts
index ccb3a86c4f..c3673ac382 100644
--- a/packages/dashboard/src/lib/delivery-method-summary.ts
+++ b/packages/dashboard/src/lib/delivery-method-summary.ts
@@ -90,6 +90,10 @@ export function amountForCurrency(
* that pair still names a different currency (a pre-6.0 EUR price), the
* existing figure is copied into the `amounts` hash first so typing in the
* dollar row cannot overwrite the euro price.
+ *
+ * Amounts are written as the exact decimal string typed, which is what the
+ * API accepts; a cleared default-currency amount is zero, as the server
+ * stores it.
*/
export function applyCurrencyAmount(
preferences: Record<string, unknown>,
@@ -106,7 +110,7 @@ export function applyCurrencyAmount(
if (namedCurrency !== code && namedCurrency !== defaultCode) {
const existing = amountForCurrency(preferences, namedCurrency, defaultCurrency)
if (existing !== null && hashEntry(nextAmounts, namedCurrency) === undefined) {
- nextAmounts[namedCurrency] = existing
+ nextAmounts[namedCurrency] = String(existing)
}
}
@@ -116,7 +120,7 @@ export function applyCurrencyAmount(
}
return {
...preferences,
- amount: parsed,
+ amount: parsed ?? '0',
currency: defaultCurrency,
amounts: nextAmounts,
}
@@ -125,7 +129,7 @@ export function applyCurrencyAmount(
writeHashAmount(nextAmounts, code, parsed)
if (namedCurrency === code) {
- return { ...preferences, amount: parsed, amounts: nextAmounts }
+ return { ...preferences, amount: parsed ?? '0', amounts: nextAmounts }
}
return { ...preferences, amounts: nextAmounts }
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 9c282fe295..4ec984d91d 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2040,22 +2040,22 @@
"invalid": "استخدم الأحرف الكبيرة والأرقام والشرطات و# فقط.",
"label": "اللاحقة"
},
- "preferred_admin_locale": {
+ "admin_locale": {
"label": "لغة لوحة الإدارة",
"placeholder": "استخدام اللغة الافتراضية"
},
- "preferred_send_consumer_transactional_emails": {
+ "send_consumer_transactional_emails": {
"help": "عند الإيقاف، لا تُرسل رسائل تأكيد الطلب أو الشحن أو الاسترداد.",
"label": "إرسال رسائل المعاملات للعملاء"
},
- "preferred_timezone": {
+ "timezone": {
"label": "Timezone",
"placeholder": "اختر منطقة زمنية"
},
- "preferred_unit_system": {
+ "unit_system": {
"label": "نظام الوحدات"
},
- "preferred_weight_unit": {
+ "weight_unit": {
"label": "وحدة الوزن"
},
"show_products_without_price": {
@@ -2133,14 +2133,14 @@
"digital_asset_authorized_days": {
"label": "الأيام المتاحة"
},
- "preferred_default_package_dimensions": {
+ "default_package_dimensions": {
"height": "الارتفاع",
"help": "الصندوق المعتاد للشحن، تستخدمه شركات النقل لتسعير الوزن الحجمي — بوصات للنظام الإمبراطوري وسنتيمترات للمتري. تلزم القيم الثلاث ليصبح ساريًا.",
"label": "أبعاد الطرد الافتراضية",
"length": "الطول",
"width": "العرض"
},
- "preferred_default_package_weight": {
+ "default_package_weight": {
"help": "وزن التغليف (الصندوق والحشو) الذي يُضاف إلى محتويات كل طرد عند حساب أسعار التوصيل. اضبطه على 0 للتعطيل.",
"label": "الوزن الافتراضي للطرد"
},
@@ -2161,22 +2161,22 @@
"help": "تُحتسب على عمولتك عندما لا تحدد نسبة العمولة ولا مزود الضرائب نسبة خاصة. اتركها 0 إذا كانت عمولتك غير خاضعة للضريبة.",
"suffix": "٪"
},
- "preferred_email_accent_color": {
+ "email_accent_color": {
"label": "لون التمييز"
},
- "preferred_email_background_color": {
+ "email_background_color": {
"label": "لون الخلفية"
},
- "preferred_email_card_color": {
+ "email_card_color": {
"label": "لون البطاقة"
},
- "preferred_email_text_color": {
+ "email_text_color": {
"label": "لون النص"
},
- "preferred_email_heading_color": {
+ "email_heading_color": {
"label": "لون العناوين"
},
- "preferred_email_font": {
+ "email_font": {
"label": "الخط",
"help": "تستخدم تطبيقات البريد التي لا يمكنها تحميله خطًا مشابهًا."
}
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index e9f148fa07..264eb96a3d 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2022,22 +2022,22 @@
"invalid": "Nur Großbuchstaben, Ziffern, Bindestriche und # verwenden.",
"label": "Suffix"
},
- "preferred_admin_locale": {
+ "admin_locale": {
"label": "Admin-Sprache",
"placeholder": "Standardsprache verwenden"
},
- "preferred_send_consumer_transactional_emails": {
+ "send_consumer_transactional_emails": {
"help": "Wenn deaktiviert, werden keine Bestellbestätigungen, Versand- oder Erstattungs-E-Mails gesendet.",
"label": "Transaktionale E-Mails an Kunden senden"
},
- "preferred_timezone": {
+ "timezone": {
"label": "Zeitzone",
"placeholder": "Zeitzone auswählen"
},
- "preferred_unit_system": {
+ "unit_system": {
"label": "Einheitensystem"
},
- "preferred_weight_unit": {
+ "weight_unit": {
"label": "Gewichtseinheit"
},
"show_products_without_price": {
@@ -2115,14 +2115,14 @@
"digital_asset_authorized_days": {
"label": "Verfügbare Tage"
},
- "preferred_default_package_dimensions": {
+ "default_package_dimensions": {
"height": "Höhe",
"help": "Der übliche Versandkarton, von Carrier-Tarifanbietern für Volumengewicht-Preise genutzt — Zoll bei imperial, Zentimeter bei metrisch. Wirksam nur mit allen drei Werten.",
"label": "Standard-Paketabmessungen",
"length": "Länge",
"width": "Breite"
},
- "preferred_default_package_weight": {
+ "default_package_weight": {
"help": "Verpackungsgewicht (Karton und Füllmaterial), das bei der Berechnung von Versandtarifen zum Inhalt jedes Pakets addiert wird. 0 deaktiviert es.",
"label": "Standard-Paketgewicht"
},
@@ -2143,22 +2143,22 @@
"help": "Wird auf Ihre Provision berechnet, wenn weder der Provisionssatz noch Ihr Steueranbieter einen eigenen Satz nennt. Bei 0 belassen, wenn auf Ihre Gebühr keine Steuer anfällt.",
"suffix": "%"
},
- "preferred_email_accent_color": {
+ "email_accent_color": {
"label": "Akzentfarbe"
},
- "preferred_email_background_color": {
+ "email_background_color": {
"label": "Hintergrundfarbe"
},
- "preferred_email_card_color": {
+ "email_card_color": {
"label": "Kartenfarbe"
},
- "preferred_email_text_color": {
+ "email_text_color": {
"label": "Textfarbe"
},
- "preferred_email_heading_color": {
+ "email_heading_color": {
"label": "Überschriftenfarbe"
},
- "preferred_email_font": {
+ "email_font": {
"label": "Schrift",
"help": "E-Mail-Programme, die sie nicht laden können, verwenden eine ähnliche Schrift."
}
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index d4fb63bf29..da5d2001b2 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2022,22 +2022,22 @@
"invalid": "Use only uppercase letters, digits, dashes and #.",
"label": "Suffix"
},
- "preferred_admin_locale": {
+ "admin_locale": {
"label": "Admin language",
"placeholder": "Use the default language"
},
- "preferred_send_consumer_transactional_emails": {
+ "send_consumer_transactional_emails": {
"help": "When off, no order confirmation, shipping, or refund emails are sent.",
"label": "Send transactional emails to customers"
},
- "preferred_timezone": {
+ "timezone": {
"label": "Timezone",
"placeholder": "Select a timezone"
},
- "preferred_unit_system": {
+ "unit_system": {
"label": "Unit system"
},
- "preferred_weight_unit": {
+ "weight_unit": {
"label": "Weight unit"
},
"show_products_without_price": {
@@ -2115,14 +2115,14 @@
"digital_asset_authorized_days": {
"label": "Days available"
},
- "preferred_default_package_dimensions": {
+ "default_package_dimensions": {
"height": "Height",
"help": "The box you usually ship in, used by carrier rate providers for dimensional-weight pricing — inches for imperial, centimeters for metric. All three are needed to take effect.",
"label": "Default package dimensions",
"length": "Length",
"width": "Width"
},
- "preferred_default_package_weight": {
+ "default_package_weight": {
"help": "Packaging weight (box and filler) added to every package's contents when calculating delivery rates. Set to 0 to disable.",
"label": "Default package weight"
},
@@ -2143,22 +2143,22 @@
"help": "Charged on your commission when neither the commission rate nor your tax provider gives a rate of its own. Leave at 0 if you charge no tax on your fee.",
"suffix": "%"
},
- "preferred_email_accent_color": {
+ "email_accent_color": {
"label": "Accent color"
},
- "preferred_email_background_color": {
+ "email_background_color": {
"label": "Background color"
},
- "preferred_email_card_color": {
+ "email_card_color": {
"label": "Card color"
},
- "preferred_email_text_color": {
+ "email_text_color": {
"label": "Text color"
},
- "preferred_email_heading_color": {
+ "email_heading_color": {
"label": "Heading color"
},
- "preferred_email_font": {
+ "email_font": {
"label": "Font",
"help": "Email apps that can't load it fall back to a similar font."
}
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index 5b339eaa6b..2a187ac692 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -2062,22 +2062,22 @@
"invalid": "Usá solo letras mayúsculas, dígitos, guiones y #.",
"label": "Sufijo"
},
- "preferred_admin_locale": {
+ "admin_locale": {
"label": "Idioma del admin",
"placeholder": "Usar el idioma predeterminado"
},
- "preferred_send_consumer_transactional_emails": {
+ "send_consumer_transactional_emails": {
"help": "Desactivado, no se envían emails de confirmación de pedido, envío ni reembolso.",
"label": "Enviar emails transaccionales a los clientes"
},
- "preferred_timezone": {
+ "timezone": {
"label": "Zona horaria",
"placeholder": "Seleccionar una zona horaria"
},
- "preferred_unit_system": {
+ "unit_system": {
"label": "Sistema de unidades"
},
- "preferred_weight_unit": {
+ "weight_unit": {
"label": "Unidad de peso"
},
"show_products_without_price": {
@@ -2155,14 +2155,14 @@
"digital_asset_authorized_days": {
"label": "Días disponibles"
},
- "preferred_default_package_dimensions": {
+ "default_package_dimensions": {
"height": "Alto",
"help": "La caja en la que sueles enviar, usada por los proveedores de tarifas de transporte para el precio por peso dimensional: pulgadas en imperial, centímetros en métrico. Se necesitan los tres para que surta efecto.",
"label": "Dimensiones del paquete predeterminado",
"length": "Largo",
"width": "Ancho"
},
- "preferred_default_package_weight": {
+ "default_package_weight": {
"help": "Peso del empaque (caja y relleno) sumado al contenido de cada paquete al calcular las tarifas de entrega. Poniendo 0 lo deshabilitás.",
"label": "Peso del paquete predeterminado"
},
@@ -2183,22 +2183,22 @@
"help": "Se aplica a tu comisión cuando ni la tarifa de comisión ni tu proveedor de impuestos indican una propia. Déjalo en 0 si tu comisión no lleva impuesto.",
"suffix": "%"
},
- "preferred_email_accent_color": {
+ "email_accent_color": {
"label": "Color de acento"
},
- "preferred_email_background_color": {
+ "email_background_color": {
"label": "Color de fondo"
},
- "preferred_email_card_color": {
+ "email_card_color": {
"label": "Color de la tarjeta"
},
- "preferred_email_text_color": {
+ "email_text_color": {
"label": "Color del texto"
},
- "preferred_email_heading_color": {
+ "email_heading_color": {
"label": "Color de los títulos"
},
- "preferred_email_font": {
+ "email_font": {
"label": "Fuente",
"help": "Las aplicaciones de correo que no puedan cargarla usarán una fuente similar."
}
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index ad5b9b8c40..11df56d1ef 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2022,22 +2022,22 @@
"invalid": "Utilisez uniquement des majuscules, des chiffres, des tirets et #.",
"label": "Suffixe"
},
- "preferred_admin_locale": {
+ "admin_locale": {
"label": "Langue de l'administration",
"placeholder": "Utiliser la langue par défaut"
},
- "preferred_send_consumer_transactional_emails": {
+ "send_consumer_transactional_emails": {
"help": "Si désactivé, aucun e-mail de confirmation de commande, d'expédition ou de remboursement n'est envoyé.",
"label": "Envoyer les e-mails transactionnels aux clients"
},
- "preferred_timezone": {
+ "timezone": {
"label": "Fuseau horaire",
"placeholder": "Sélectionner un fuseau horaire"
},
- "preferred_unit_system": {
+ "unit_system": {
"label": "Système d'unités"
},
- "preferred_weight_unit": {
+ "weight_unit": {
"label": "Unité de poids"
},
"show_products_without_price": {
@@ -2115,14 +2115,14 @@
"digital_asset_authorized_days": {
"label": "Jours de disponibilité"
},
- "preferred_default_package_dimensions": {
+ "default_package_dimensions": {
"height": "Hauteur",
"help": "Le carton habituel d'expédition, utilisé par les transporteurs pour le poids volumétrique — pouces en impérial, centimètres en métrique. Les trois valeurs sont requises.",
"label": "Dimensions de colis par défaut",
"length": "Longueur",
"width": "Largeur"
},
- "preferred_default_package_weight": {
+ "default_package_weight": {
"help": "Poids d'emballage (carton et calage) ajouté au contenu de chaque colis lors du calcul des tarifs de livraison. 0 pour désactiver.",
"label": "Poids de colis par défaut"
},
@@ -2143,22 +2143,22 @@
"help": "Appliquée à votre commission quand ni le taux de commission ni votre fournisseur de taxes n’indique son propre taux. Laissez 0 si votre commission n’est pas taxée.",
"suffix": "%"
},
- "preferred_email_accent_color": {
+ "email_accent_color": {
"label": "Couleur d'accent"
},
- "preferred_email_background_color": {
+ "email_background_color": {
"label": "Couleur de fond"
},
- "preferred_email_card_color": {
+ "email_card_color": {
"label": "Couleur de la carte"
},
- "preferred_email_text_color": {
+ "email_text_color": {
"label": "Couleur du texte"
},
- "preferred_email_heading_color": {
+ "email_heading_color": {
"label": "Couleur des titres"
},
- "preferred_email_font": {
+ "email_font": {
"label": "Police",
"help": "Les applications de messagerie qui ne peuvent pas la charger utilisent une police similaire."
}
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 516d55933c..2dc8d62c57 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -2040,22 +2040,22 @@
"invalid": "Używaj tylko wielkich liter, cyfr, myślników i #.",
"label": "Sufiks"
},
- "preferred_admin_locale": {
+ "admin_locale": {
"label": "Język panelu administracyjnego",
"placeholder": "Użyj języka domyślnego"
},
- "preferred_send_consumer_transactional_emails": {
+ "send_consumer_transactional_emails": {
"help": "Gdy wyłączone, nie są wysyłane żadne wiadomości z potwierdzeniem zamówienia, wysyłki ani zwrotu.",
"label": "Wysyłaj wiadomości transakcyjne do klientów"
},
- "preferred_timezone": {
+ "timezone": {
"label": "Strefa czasowa",
"placeholder": "Wybierz strefę czasową"
},
- "preferred_unit_system": {
+ "unit_system": {
"label": "System jednostek"
},
- "preferred_weight_unit": {
+ "weight_unit": {
"label": "Jednostka wagi"
},
"show_products_without_price": {
@@ -2133,14 +2133,14 @@
"digital_asset_authorized_days": {
"label": "Dostępne dni"
},
- "preferred_default_package_dimensions": {
+ "default_package_dimensions": {
"height": "Wysokość",
"help": "Karton, w którym zwykle wysyłasz, używany przez przewoźników do wyceny wagi wymiarowej — cale dla systemu imperialnego, centymetry dla metrycznego. Działa dopiero po podaniu wszystkich trzech.",
"label": "Domyślne wymiary paczki",
"length": "Długość",
"width": "Szerokość"
},
- "preferred_default_package_weight": {
+ "default_package_weight": {
"help": "Waga opakowania (karton i wypełnienie) dodawana do zawartości każdej paczki przy wyliczaniu stawek dostawy. 0 wyłącza.",
"label": "Domyślna waga paczki"
},
@@ -2161,22 +2161,22 @@
"help": "Naliczany od Twojej prowizji, gdy ani stawka prowizji, ani dostawca podatków nie podaje własnej stawki. Zostaw 0, jeśli Twoja prowizja nie jest opodatkowana.",
"suffix": "%"
},
- "preferred_email_accent_color": {
+ "email_accent_color": {
"label": "Kolor akcentu"
},
- "preferred_email_background_color": {
+ "email_background_color": {
"label": "Kolor tła"
},
- "preferred_email_card_color": {
+ "email_card_color": {
"label": "Kolor karty"
},
- "preferred_email_text_color": {
+ "email_text_color": {
"label": "Kolor tekstu"
},
- "preferred_email_heading_color": {
+ "email_heading_color": {
"label": "Kolor nagłówków"
},
- "preferred_email_font": {
+ "email_font": {
"label": "Czcionka",
"help": "Programy pocztowe, które nie mogą jej wczytać, użyją podobnej czcionki."
}
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index a590cc8d06..0bb87db504 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2017,22 +2017,22 @@
"invalid": "只能使用大写字母、数字、连字符和 #。",
"label": "后缀"
},
- "preferred_admin_locale": {
+ "admin_locale": {
"label": "后台语言",
"placeholder": "使用默认语言"
},
- "preferred_send_consumer_transactional_emails": {
+ "send_consumer_transactional_emails": {
"help": "关闭后,将不会发送订单确认、发货或退款邮件。",
"label": "向客户发送交易类邮件"
},
- "preferred_timezone": {
+ "timezone": {
"label": "时区",
"placeholder": "选择时区"
},
- "preferred_unit_system": {
+ "unit_system": {
"label": "单位制"
},
- "preferred_weight_unit": {
+ "weight_unit": {
"label": "重量单位"
},
"show_products_without_price": {
@@ -2110,14 +2110,14 @@
"digital_asset_authorized_days": {
"label": "可用天数"
},
- "preferred_default_package_dimensions": {
+ "default_package_dimensions": {
"height": "高",
"help": "常用的发货纸箱尺寸,承运商费率提供方据此计算体积重量——英制为英寸,公制为厘米。三项都填写后才生效。",
"label": "默认包裹尺寸",
"length": "长",
"width": "宽"
},
- "preferred_default_package_weight": {
+ "default_package_weight": {
"help": "计算配送费率时加到每个包裹内容上的包装重量(纸箱与填充物)。设为 0 可停用。",
"label": "默认包裹重量"
},
@@ -2138,22 +2138,22 @@
"help": "当佣金费率和税务服务商都未给出税率时,按此税率对佣金计税。若佣金不计税,保持为 0。",
"suffix": "%"
},
- "preferred_email_accent_color": {
+ "email_accent_color": {
"label": "强调色"
},
- "preferred_email_background_color": {
+ "email_background_color": {
"label": "背景色"
},
- "preferred_email_card_color": {
+ "email_card_color": {
"label": "卡片颜色"
},
- "preferred_email_text_color": {
+ "email_text_color": {
"label": "文字颜色"
},
- "preferred_email_heading_color": {
+ "email_heading_color": {
"label": "标题颜色"
},
- "preferred_email_font": {
+ "email_font": {
"label": "字体",
"help": "无法加载该字体的邮件应用会使用相近的字体。"
}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
index 2869bc07ac..d001d06c3d 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
@@ -392,7 +392,7 @@ function CounterRow({
// stays a translation.
const description = t(`admin.pages.home.operations.counters.${counter.key}.description`, {
defaultValue: '',
- count: store?.preferred_low_stock_threshold ?? 0,
+ count: store?.low_stock_threshold ?? 0,
})
const content = (
<>
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/sellers/commission-rates.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/sellers/commission-rates.tsx
index 4f40e2d7a5..3eec370f29 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/sellers/commission-rates.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/sellers/commission-rates.tsx
@@ -805,13 +805,16 @@ function CommissionRuleRow({
onRemove: () => void
}) {
const { t } = useTranslation()
- const schema = ruleType?.preference_schema ?? []
+ const schema = ruleType?.schema
// Catalog-scale references arrive as their own field; everything else names
// records through an id list in preferences. Either way the picker comes
// from the registry, keyed by rule kind.
const picker = ruleType ? commissionRuleSubjectPicker(ruleType.type) : undefined
const associationField = ruleType?.association_fields?.[0]
- const preferenceIdKey = schema.find((preference) => preference.key.endsWith('_ids'))?.key
+ // The id list the schema marks with a record prefix.
+ const preferenceIdKey = Object.entries(schema?.properties ?? {}).find(
+ ([, property]) => property.items?.['x-spree-prefix'],
+ )?.[0]
return (
<div className="flex flex-col gap-2 rounded-md border p-3">
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx
index 2652cab881..65f0a01741 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx
@@ -242,9 +242,9 @@ function EditChannelSheet({
// The rules editor only makes sense under the Rules strategy. Resolve the
// effective strategy live from the (unsaved) select value, falling back to
// the store-level preference for the "inherit" option.
- const strategyOverride = form.watch('preferred_order_routing_strategy')
+ const strategyOverride = form.watch('order_routing_strategy')
const effectiveStrategy =
- strategyOverride || store?.preferred_order_routing_strategy || RULES_ORDER_ROUTING_STRATEGY
+ strategyOverride || store?.order_routing_strategy || RULES_ORDER_ROUTING_STRATEGY
useEffect(() => {
if (channel) {
@@ -253,10 +253,9 @@ function EditChannelSheet({
code: channel.code,
active: channel.active,
default: channel.default,
- preferred_order_routing_strategy: channel.preferred_order_routing_strategy ?? '',
- preferred_storefront_access: channel.preferred_storefront_access ?? '',
- preferred_guest_checkout:
- channel.preferred_guest_checkout == null ? '' : String(channel.preferred_guest_checkout),
+ order_routing_strategy: channel.order_routing_strategy ?? '',
+ storefront_access: channel.storefront_access ?? '',
+ guest_checkout: channel.guest_checkout == null ? '' : String(channel.guest_checkout),
default_catalog_id: channel.default_catalog_id ?? '',
stock_location_ids: channel.stock_location_ids ?? [],
})
@@ -313,10 +312,7 @@ function EditChannelSheet({
)
}
-type ChannelSelectFieldName =
- | 'preferred_order_routing_strategy'
- | 'preferred_storefront_access'
- | 'preferred_guest_checkout'
+type ChannelSelectFieldName = 'order_routing_strategy' | 'storefront_access' | 'guest_checkout'
// One channel-preference <Select> that shares the "inherit from store" blank
// option. Builds its own option list from `values` + the i18n `scope`
@@ -445,21 +441,21 @@ function ChannelFormFields({ form }: { form: UseFormReturn<ChannelFormValues> })
<InheritableSelectField
form={form}
- name="preferred_order_routing_strategy"
+ name="order_routing_strategy"
scope="admin.fields.channel.order_routing_strategy"
values={ORDER_ROUTING_STRATEGY_VALUES}
/>
<InheritableSelectField
form={form}
- name="preferred_storefront_access"
+ name="storefront_access"
scope="admin.fields.channel.storefront_access"
values={STOREFRONT_ACCESS_VALUES}
/>
<InheritableSelectField
form={form}
- name="preferred_guest_checkout"
+ name="guest_checkout"
scope="admin.fields.channel.guest_checkout"
values={GUEST_CHECKOUT_VALUES}
/>
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/index.tsx
index f9b4e83b87..308da3a70d 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/index.tsx
@@ -61,14 +61,13 @@ function storeToFormValues(store: Store): StoreEmailsFormValues {
mail_from_address: store.mail_from_address ?? '',
customer_support_email: store.customer_support_email ?? '',
new_order_notifications_email: store.new_order_notifications_email ?? '',
- preferred_send_consumer_transactional_emails:
- store.preferred_send_consumer_transactional_emails,
- preferred_email_accent_color: store.preferred_email_accent_color ?? '',
- preferred_email_background_color: store.preferred_email_background_color ?? '',
- preferred_email_card_color: store.preferred_email_card_color ?? '',
- preferred_email_text_color: store.preferred_email_text_color ?? '',
- preferred_email_heading_color: store.preferred_email_heading_color ?? '',
- preferred_email_font: store.preferred_email_font ?? 'inter',
+ send_consumer_transactional_emails: store.send_consumer_transactional_emails,
+ email_accent_color: store.email_accent_color ?? '',
+ email_background_color: store.email_background_color ?? '',
+ email_card_color: store.email_card_color ?? '',
+ email_text_color: store.email_text_color ?? '',
+ email_heading_color: store.email_heading_color ?? '',
+ email_font: store.email_font ?? 'inter',
mailer_logo_signed_id: null,
mailer_logo_preview_url: null,
mailer_logo_cleared: false,
@@ -80,14 +79,13 @@ function formValuesToApiParams(values: StoreEmailsFormValues): StoreUpdateParams
mail_from_address: values.mail_from_address,
customer_support_email: values.customer_support_email?.trim() || null,
new_order_notifications_email: values.new_order_notifications_email?.trim() || null,
- preferred_send_consumer_transactional_emails:
- values.preferred_send_consumer_transactional_emails,
- preferred_email_accent_color: values.preferred_email_accent_color || null,
- preferred_email_background_color: values.preferred_email_background_color || null,
- preferred_email_card_color: values.preferred_email_card_color || null,
- preferred_email_text_color: values.preferred_email_text_color || null,
- preferred_email_heading_color: values.preferred_email_heading_color || null,
- preferred_email_font: values.preferred_email_font,
+ send_consumer_transactional_emails: values.send_consumer_transactional_emails,
+ email_accent_color: values.email_accent_color || null,
+ email_background_color: values.email_background_color || null,
+ email_card_color: values.email_card_color || null,
+ email_text_color: values.email_text_color || null,
+ email_heading_color: values.email_heading_color || null,
+ email_font: values.email_font,
}
// Three states for the logo: untouched (omit), uploaded (send signed_id),
// explicitly cleared (send null). Sending an empty value would be ambiguous.
@@ -166,7 +164,7 @@ function EmailSettingsForm({ store }: { store: Store }) {
// Mirror legacy behaviour: when consumer emails are off, hide the address +
// logo cards. Their values stay in form state so toggling back doesn't
// require re-entering anything.
- const sendConsumerEmails = form.watch('preferred_send_consumer_transactional_emails')
+ const sendConsumerEmails = form.watch('send_consumer_transactional_emails')
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
@@ -198,14 +196,14 @@ function EmailSettingsForm({ store }: { store: Store }) {
<div className="flex items-start justify-between gap-4">
<div className="flex flex-col">
<FieldLabel htmlFor="store-send-consumer-emails" className="cursor-pointer">
- {t('admin.fields.store.preferred_send_consumer_transactional_emails.label')}
+ {t('admin.fields.store.send_consumer_transactional_emails.label')}
</FieldLabel>
<FieldDescription>
- {t('admin.fields.store.preferred_send_consumer_transactional_emails.help')}
+ {t('admin.fields.store.send_consumer_transactional_emails.help')}
</FieldDescription>
</div>
<Controller
- name="preferred_send_consumer_transactional_emails"
+ name="send_consumer_transactional_emails"
control={form.control}
render={({ field }) => (
<Switch
@@ -353,7 +351,7 @@ function BrandingCard({ form }: { form: ReturnType<typeof useForm<StoreEmailsFor
<CardContent className="grid gap-6 lg:grid-cols-2">
<FieldGroup>
{EMAIL_BRANDING_COLORS.map((color) => {
- const name = `preferred_email_${color}` as const
+ const name = `email_${color}` as const
return (
<Field key={color}>
<FieldLabel htmlFor={`store-email-${color}`}>
@@ -378,10 +376,10 @@ function BrandingCard({ form }: { form: ReturnType<typeof useForm<StoreEmailsFor
})}
<Field>
<FieldLabel htmlFor="store-email-font">
- {t('admin.fields.store.preferred_email_font.label')}
+ {t('admin.fields.store.email_font.label')}
</FieldLabel>
<Controller
- name="preferred_email_font"
+ name="email_font"
control={form.control}
render={({ field }) => (
<Select
@@ -402,7 +400,7 @@ function BrandingCard({ form }: { form: ReturnType<typeof useForm<StoreEmailsFor
</Select>
)}
/>
- <FieldDescription>{t('admin.fields.store.preferred_email_font.help')}</FieldDescription>
+ <FieldDescription>{t('admin.fields.store.email_font.help')}</FieldDescription>
</Field>
</FieldGroup>
{permissions.can('update', Subject.EmailTemplate) && <BrandingPreview form={form} />}
@@ -417,12 +415,12 @@ function BrandingPreview({ form }: { form: ReturnType<typeof useForm<StoreEmails
const [accent, background, card, text, heading, font] = useWatch({
control: form.control,
name: [
- 'preferred_email_accent_color',
- 'preferred_email_background_color',
- 'preferred_email_card_color',
- 'preferred_email_text_color',
- 'preferred_email_heading_color',
- 'preferred_email_font',
+ 'email_accent_color',
+ 'email_background_color',
+ 'email_card_color',
+ 'email_text_color',
+ 'email_heading_color',
+ 'email_font',
],
})
const branding = useDebouncedValue(
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx
index 2b01006202..2e2595e62d 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx
@@ -101,7 +101,10 @@ function IntegrationsPage() {
// The server already leaves out providers installed on this store, so
// these are only the ones still to set up.
const availablePaymentTypes = useMemo(
- () => (paymentTypesResponse?.data ?? []).filter((type) => type.third_party && !type.superseded),
+ () =>
+ (paymentTypesResponse?.data ?? []).filter(
+ (type) => type.third_party && !type.superseded && !type.installed,
+ ),
[paymentTypesResponse],
)
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx
index bfe9f41039..5da958342d 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/marketplace.tsx
@@ -92,20 +92,20 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
resolver: zodResolver(marketplaceSettingsFormSchema) as any,
defaultValues: {
- preferred_payout_provider: store.preferred_payout_provider ?? '',
- preferred_default_payouts_schedule_interval:
- (store.preferred_default_payouts_schedule_interval as (typeof PAYOUT_SCHEDULE_INTERVALS)[number]) ??
+ payout_provider: store.payout_provider ?? '',
+ default_payouts_schedule_interval:
+ (store.default_payouts_schedule_interval as (typeof PAYOUT_SCHEDULE_INTERVALS)[number]) ??
'monthly',
// `String` only until the regenerated Store type reads these as the decimal strings the API sends.
- preferred_default_minimum_payout_amount: String(
- store.preferred_default_minimum_payout_amount ?? '0',
+ default_minimum_payout_amount: String(
+ store.default_minimum_payout_amount ?? '0',
),
- preferred_auto_approve_sellers: store.preferred_auto_approve_sellers ?? false,
- preferred_auto_approve_seller_products: store.preferred_auto_approve_seller_products ?? false,
- preferred_send_seller_transactional_emails:
- store.preferred_send_seller_transactional_emails ?? true,
+ auto_approve_sellers: store.auto_approve_sellers ?? false,
+ auto_approve_seller_products: store.auto_approve_seller_products ?? false,
+ send_seller_transactional_emails:
+ store.send_seller_transactional_emails ?? true,
commission_tax_rate_percentage:
- fractionToPercent(String(store.preferred_default_commission_tax_rate ?? '')) || '0',
+ fractionToPercent(String(store.default_commission_tax_rate ?? '')) || '0',
},
})
@@ -153,15 +153,15 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {
const onSubmit = async (values: MarketplaceSettingsFormValues) => {
try {
await updateMutation.mutateAsync({
- preferred_payout_provider: values.preferred_payout_provider,
- preferred_default_payouts_schedule_interval:
- values.preferred_default_payouts_schedule_interval,
- preferred_default_minimum_payout_amount: values.preferred_default_minimum_payout_amount,
- preferred_auto_approve_sellers: values.preferred_auto_approve_sellers,
- preferred_auto_approve_seller_products: values.preferred_auto_approve_seller_products,
- preferred_send_seller_transactional_emails:
- values.preferred_send_seller_transactional_emails,
- preferred_default_commission_tax_rate: percentToFraction(
+ payout_provider: values.payout_provider,
+ default_payouts_schedule_interval:
+ values.default_payouts_schedule_interval,
+ default_minimum_payout_amount: values.default_minimum_payout_amount,
+ auto_approve_sellers: values.auto_approve_sellers,
+ auto_approve_seller_products: values.auto_approve_seller_products,
+ send_seller_transactional_emails:
+ values.send_seller_transactional_emails,
+ default_commission_tax_rate: percentToFraction(
values.commission_tax_rate_percentage,
),
})
@@ -179,7 +179,7 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {
// A provider that moves money asks sellers to onboard with it first, which
// is worth saying before the choice rather than after.
const selectedProvider = payoutProviders?.data?.find(
- (provider) => provider.id === form.watch('preferred_payout_provider'),
+ (provider) => provider.id === form.watch('payout_provider'),
)
return (
@@ -216,7 +216,7 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {
<FieldGroup>
<Controller
control={form.control}
- name="preferred_payout_provider"
+ name="payout_provider"
render={({ field }) => (
<Field>
<FieldLabel htmlFor="payout-provider">
@@ -260,14 +260,14 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {
</AlertDescription>
</Alert>
))}
- <FieldError errors={[errors.preferred_payout_provider]} />
+ <FieldError errors={[errors.payout_provider]} />
</Field>
)}
/>
<Controller
control={form.control}
- name="preferred_default_payouts_schedule_interval"
+ name="default_payouts_schedule_interval"
render={({ field }) => (
<Field>
<FieldLabel htmlFor="payout-schedule">
@@ -292,9 +292,7 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {
<FieldDescription>
{t('admin.fields.store.payouts.schedule.help')}
</FieldDescription>
- <FieldError
- errors={[errors.preferred_default_payouts_schedule_interval]}
- />
+ <FieldError errors={[errors.default_payouts_schedule_interval]} />
</Field>
)}
/>
@@ -313,16 +311,14 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {
min={0}
step="any"
inputMode="decimal"
- aria-invalid={
- !!errors.preferred_default_minimum_payout_amount || undefined
- }
- {...form.register('preferred_default_minimum_payout_amount')}
+ aria-invalid={!!errors.default_minimum_payout_amount || undefined}
+ {...form.register('default_minimum_payout_amount')}
/>
</InputGroup>
<FieldDescription>
{t('admin.fields.store.payouts.minimum.help')}
</FieldDescription>
- <FieldError errors={[errors.preferred_default_minimum_payout_amount]} />
+ <FieldError errors={[errors.default_minimum_payout_amount]} />
</Field>
</FieldGroup>
</CardContent>
@@ -341,14 +337,14 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {
id="marketplace-auto-approve-sellers"
label={t('admin.fields.store.auto_approve_sellers.label')}
help={t('admin.fields.store.auto_approve_sellers.help')}
- name="preferred_auto_approve_sellers"
+ name="auto_approve_sellers"
control={form.control}
/>
<SwitchField
id="marketplace-auto-approve-seller-products"
label={t('admin.fields.store.auto_approve_seller_products.label')}
help={t('admin.fields.store.auto_approve_seller_products.help')}
- name="preferred_auto_approve_seller_products"
+ name="auto_approve_seller_products"
control={form.control}
/>
</FieldGroup>
@@ -365,7 +361,7 @@ function MarketplaceSettingsPage({ store }: { store: Store }) {
id="marketplace-send-seller-emails"
label={t('admin.fields.store.send_seller_transactional_emails.label')}
help={t('admin.fields.store.send_seller_transactional_emails.help')}
- name="preferred_send_seller_transactional_emails"
+ name="send_seller_transactional_emails"
control={form.control}
/>
</FieldGroup>
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/seller-requirements.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/seller-requirements.tsx
index 13712fbc5f..b3993a2aae 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/seller-requirements.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/seller-requirements.tsx
@@ -1,4 +1,4 @@
-import type { PreferenceField, SellerRequirement, SellerRequirementType } from '@spree/admin-sdk'
+import type { SellerRequirement, SellerRequirementType } from '@spree/admin-sdk'
import type { ResourceFilterConfig } from '@spree/dashboard-core'
import {
adminClient,
@@ -193,9 +193,7 @@ function CreateRequirementSheet({
function handleTypeChange(value: string) {
setType(value)
const entry = types.find((candidate) => candidate.type === value)
- setPreferences(
- entry ? defaultPreferences(entry.preference_schema as unknown as PreferenceField[]) : {},
- )
+ setPreferences(entry ? defaultPreferences(entry.schema) : {})
}
async function handleSave() {
@@ -527,9 +525,9 @@ function RequirementFields({
/>
</Field>
- {kindEntry.preference_schema.length > 0 && (
+ {Object.keys(kindEntry.schema.properties).length > 0 && (
<PreferencesForm
- schema={kindEntry.preference_schema as unknown as PreferenceField[]}
+ schema={kindEntry.schema}
values={values.preferences}
onChange={onChange.setPreferences}
inlineDatePickers
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
index 1c046a0517..f7ac06caed 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
@@ -101,45 +101,41 @@ const TIMEZONES: string[] = (() => {
function storeToFormValues(store: Store): StoreSettingsFormValues {
return {
name: store.name,
- preferred_admin_locale: store.preferred_admin_locale ?? '',
- preferred_timezone: store.preferred_timezone,
- preferred_unit_system: (store.preferred_unit_system as 'metric' | 'imperial') ?? 'metric',
- preferred_weight_unit: store.preferred_weight_unit,
- preferred_storefront_access:
- (store.preferred_storefront_access as (typeof STOREFRONT_ACCESS_LEVELS)[number]) ?? 'public',
- preferred_guest_checkout: store.preferred_guest_checkout ?? true,
- preferred_always_include_confirm_step: store.preferred_always_include_confirm_step ?? false,
- preferred_company_field_enabled: store.preferred_company_field_enabled ?? false,
- preferred_address_requires_phone: store.preferred_address_requires_phone ?? false,
- preferred_capture_method:
- (store.preferred_capture_method as (typeof CAPTURE_METHODS)[number]) ?? 'checkout',
- preferred_pricing_provider: store.preferred_pricing_provider || INTERNAL_PROVIDER_KEY,
- preferred_inventory_provider: store.preferred_inventory_provider || INTERNAL_PROVIDER_KEY,
- preferred_pricing_provider_failure_policy:
- (store.preferred_pricing_provider_failure_policy as (typeof PROVIDER_FAILURE_POLICIES)[number]) ??
+ admin_locale: store.admin_locale ?? '',
+ timezone: store.timezone,
+ unit_system: (store.unit_system as 'metric' | 'imperial') ?? 'metric',
+ weight_unit: store.weight_unit,
+ storefront_access:
+ (store.storefront_access as (typeof STOREFRONT_ACCESS_LEVELS)[number]) ?? 'public',
+ guest_checkout: store.guest_checkout ?? true,
+ always_include_confirm_step: store.always_include_confirm_step ?? false,
+ company_field_enabled: store.company_field_enabled ?? false,
+ address_requires_phone: store.address_requires_phone ?? false,
+ capture_method: (store.capture_method as (typeof CAPTURE_METHODS)[number]) ?? 'checkout',
+ pricing_provider: store.pricing_provider || INTERNAL_PROVIDER_KEY,
+ inventory_provider: store.inventory_provider || INTERNAL_PROVIDER_KEY,
+ pricing_provider_failure_policy:
+ (store.pricing_provider_failure_policy as (typeof PROVIDER_FAILURE_POLICIES)[number]) ??
'strict',
- preferred_inventory_provider_failure_policy:
- (store.preferred_inventory_provider_failure_policy as (typeof PROVIDER_FAILURE_POLICIES)[number]) ??
+ inventory_provider_failure_policy:
+ (store.inventory_provider_failure_policy as (typeof PROVIDER_FAILURE_POLICIES)[number]) ??
'fallback',
- preferred_tax_using_ship_address: store.preferred_tax_using_ship_address ?? true,
- preferred_track_inventory_levels: store.preferred_track_inventory_levels ?? true,
- preferred_stock_reservations_enabled: store.preferred_stock_reservations_enabled ?? true,
- preferred_low_stock_threshold: store.preferred_low_stock_threshold ?? 5,
- preferred_track_price_history: store.preferred_track_price_history ?? true,
- preferred_show_products_without_price: store.preferred_show_products_without_price ?? false,
- preferred_disable_sku_validation: store.preferred_disable_sku_validation ?? false,
- preferred_document_number_format:
- (store.preferred_document_number_format as (typeof DOCUMENT_NUMBER_FORMATS)[number]) ??
- 'sequential',
- preferred_order_number_prefix: store.preferred_order_number_prefix ?? 'R',
- preferred_order_number_suffix: store.preferred_order_number_suffix ?? '',
- preferred_order_number_sequence_start: Number(
- store.preferred_order_number_sequence_start ?? 1001,
- ),
- preferred_limit_digital_download_count: store.preferred_limit_digital_download_count ?? true,
- preferred_digital_asset_authorized_clicks: store.preferred_digital_asset_authorized_clicks ?? 5,
- preferred_limit_digital_download_days: store.preferred_limit_digital_download_days ?? true,
- preferred_digital_asset_authorized_days: store.preferred_digital_asset_authorized_days ?? 7,
+ tax_using_ship_address: store.tax_using_ship_address ?? true,
+ track_inventory_levels: store.track_inventory_levels ?? true,
+ stock_reservations_enabled: store.stock_reservations_enabled ?? true,
+ low_stock_threshold: store.low_stock_threshold ?? 5,
+ track_price_history: store.track_price_history ?? true,
+ show_products_without_price: store.show_products_without_price ?? false,
+ disable_sku_validation: store.disable_sku_validation ?? false,
+ document_number_format:
+ (store.document_number_format as (typeof DOCUMENT_NUMBER_FORMATS)[number]) ?? 'sequential',
+ order_number_prefix: store.order_number_prefix ?? 'R',
+ order_number_suffix: store.order_number_suffix ?? '',
+ order_number_sequence_start: Number(store.order_number_sequence_start ?? 1001),
+ limit_digital_download_count: store.limit_digital_download_count ?? true,
+ digital_asset_authorized_clicks: store.digital_asset_authorized_clicks ?? 5,
+ limit_digital_download_days: store.limit_digital_download_days ?? true,
+ digital_asset_authorized_days: store.digital_asset_authorized_days ?? 7,
}
}
@@ -196,26 +192,25 @@ function StoreSettingsForm({ store }: { store: Store }) {
const sequenceStarted = store.order_number_sequence_started ?? false
// The failure-policy selects only render for a provider that can fail —
// Spree's own records cannot, so 'internal' has no policy to choose.
- const externalPricingSelected = form.watch('preferred_pricing_provider') !== INTERNAL_PROVIDER_KEY
- const externalInventorySelected =
- form.watch('preferred_inventory_provider') !== INTERNAL_PROVIDER_KEY
+ const externalPricingSelected = form.watch('pricing_provider') !== INTERNAL_PROVIDER_KEY
+ const externalInventorySelected = form.watch('inventory_provider') !== INTERNAL_PROVIDER_KEY
- const numberFormat = form.watch('preferred_document_number_format')
- const numberPrefix = form.watch('preferred_order_number_prefix')
- const numberSuffix = form.watch('preferred_order_number_suffix')
- const numberStart = form.watch('preferred_order_number_sequence_start')
+ const numberFormat = form.watch('document_number_format')
+ const numberPrefix = form.watch('order_number_prefix')
+ const numberSuffix = form.watch('order_number_suffix')
+ const numberStart = form.watch('order_number_sequence_start')
const orderNumberPreview = `${numberPrefix ?? ''}${
numberFormat === 'random' ? '482910375' : (numberStart ?? 1001)
}${numberSuffix ?? ''}`
// When unit_system flips, reset weight_unit to the first valid option for
// that system so the form never holds an inconsistent pair.
- const unitSystem = form.watch('preferred_unit_system')
+ const unitSystem = form.watch('unit_system')
useEffect(() => {
const validUnits = WEIGHT_UNITS[unitSystem] ?? []
- const current = form.getValues('preferred_weight_unit')
+ const current = form.getValues('weight_unit')
if (current && !validUnits.includes(current)) {
- form.setValue('preferred_weight_unit', validUnits[0] ?? '', { shouldDirty: true })
+ form.setValue('weight_unit', validUnits[0] ?? '', { shouldDirty: true })
}
}, [unitSystem, form])
@@ -224,44 +219,43 @@ function StoreSettingsForm({ store }: { store: Store }) {
// store's currently-persisted value, not RHF's `dirtyFields` (which a Base UI
// Select via Controller doesn't reliably populate). Saving unrelated fields
// (name, timezone, units) must not touch the admin's UI language.
- const code = values.preferred_admin_locale
- const localeChanged = (code ?? '') !== (store.preferred_admin_locale ?? '')
+ const code = values.admin_locale
+ const localeChanged = (code ?? '') !== (store.admin_locale ?? '')
// Extension fields come from live form state — the Zod parse behind
// `values` strips keys the first-party schema doesn't know.
const extensionValues = extensionSubmitValues('store', form)
try {
await updateMutation.mutateAsync({
name: values.name,
- preferred_admin_locale: values.preferred_admin_locale || undefined,
- preferred_timezone: values.preferred_timezone,
- preferred_unit_system: values.preferred_unit_system,
- preferred_weight_unit: values.preferred_weight_unit,
- preferred_storefront_access: values.preferred_storefront_access,
- preferred_guest_checkout: values.preferred_guest_checkout,
- preferred_always_include_confirm_step: values.preferred_always_include_confirm_step,
- preferred_company_field_enabled: values.preferred_company_field_enabled,
- preferred_address_requires_phone: values.preferred_address_requires_phone,
- preferred_capture_method: values.preferred_capture_method,
- preferred_pricing_provider: values.preferred_pricing_provider,
- preferred_inventory_provider: values.preferred_inventory_provider,
- preferred_pricing_provider_failure_policy: values.preferred_pricing_provider_failure_policy,
- preferred_inventory_provider_failure_policy:
- values.preferred_inventory_provider_failure_policy,
- preferred_tax_using_ship_address: values.preferred_tax_using_ship_address,
- preferred_track_inventory_levels: values.preferred_track_inventory_levels,
- preferred_stock_reservations_enabled: values.preferred_stock_reservations_enabled,
- preferred_low_stock_threshold: values.preferred_low_stock_threshold,
- preferred_track_price_history: values.preferred_track_price_history,
- preferred_show_products_without_price: values.preferred_show_products_without_price,
- preferred_disable_sku_validation: values.preferred_disable_sku_validation,
- preferred_document_number_format: values.preferred_document_number_format,
- preferred_order_number_prefix: values.preferred_order_number_prefix,
- preferred_order_number_suffix: values.preferred_order_number_suffix,
- preferred_order_number_sequence_start: values.preferred_order_number_sequence_start,
- preferred_limit_digital_download_count: values.preferred_limit_digital_download_count,
- preferred_digital_asset_authorized_clicks: values.preferred_digital_asset_authorized_clicks,
- preferred_limit_digital_download_days: values.preferred_limit_digital_download_days,
- preferred_digital_asset_authorized_days: values.preferred_digital_asset_authorized_days,
+ admin_locale: values.admin_locale || undefined,
+ timezone: values.timezone,
+ unit_system: values.unit_system,
+ weight_unit: values.weight_unit,
+ storefront_access: values.storefront_access,
+ guest_checkout: values.guest_checkout,
+ always_include_confirm_step: values.always_include_confirm_step,
+ company_field_enabled: values.company_field_enabled,
+ address_requires_phone: values.address_requires_phone,
+ capture_method: values.capture_method,
+ pricing_provider: values.pricing_provider,
+ inventory_provider: values.inventory_provider,
+ pricing_provider_failure_policy: values.pricing_provider_failure_policy,
+ inventory_provider_failure_policy: values.inventory_provider_failure_policy,
+ tax_using_ship_address: values.tax_using_ship_address,
+ track_inventory_levels: values.track_inventory_levels,
+ stock_reservations_enabled: values.stock_reservations_enabled,
+ low_stock_threshold: values.low_stock_threshold,
+ track_price_history: values.track_price_history,
+ show_products_without_price: values.show_products_without_price,
+ disable_sku_validation: values.disable_sku_validation,
+ document_number_format: values.document_number_format,
+ order_number_prefix: values.order_number_prefix,
+ order_number_suffix: values.order_number_suffix,
+ order_number_sequence_start: values.order_number_sequence_start,
+ limit_digital_download_count: values.limit_digital_download_count,
+ digital_asset_authorized_clicks: values.digital_asset_authorized_clicks,
+ limit_digital_download_days: values.limit_digital_download_days,
+ digital_asset_authorized_days: values.digital_asset_authorized_days,
...extensionValues,
})
toastManager.add({ type: 'success', title: t('admin.messages.store_settings_updated') })
@@ -368,11 +362,11 @@ function StoreSettingsForm({ store }: { store: Store }) {
// Admin-UI language options come from the dashboard's own shipped locale
// bundles (getAvailableUiLocales) — the SAME canonical source the profile
// picker and top-bar switcher use, so the lists never desync. The leading
- // empty option clears the store-wide override (preferred_admin_locale is
+ // empty option clears the store-wide override (admin_locale is
// nullable → "no override, fall back to the app default").
const adminLocaleOptions = useMemo(
() => [
- { value: '', label: t('admin.fields.store.preferred_admin_locale.placeholder') },
+ { value: '', label: t('admin.fields.store.admin_locale.placeholder') },
...getAvailableUiLocales().map((l) => ({ value: l.code, label: l.name })),
],
[t],
@@ -428,31 +422,31 @@ function StoreSettingsForm({ store }: { store: Store }) {
<FieldGroup>
<SelectField
id="store-admin-locale"
- label={t('admin.fields.store.preferred_admin_locale.label')}
- placeholder={t('admin.fields.store.preferred_admin_locale.placeholder')}
- name="preferred_admin_locale"
+ label={t('admin.fields.store.admin_locale.label')}
+ placeholder={t('admin.fields.store.admin_locale.placeholder')}
+ name="admin_locale"
control={form.control}
options={adminLocaleOptions}
/>
<SelectField
id="store-timezone"
- label={t('admin.fields.store.preferred_timezone.label')}
- placeholder={t('admin.fields.store.preferred_timezone.placeholder')}
- name="preferred_timezone"
+ label={t('admin.fields.store.timezone.label')}
+ placeholder={t('admin.fields.store.timezone.placeholder')}
+ name="timezone"
control={form.control}
options={timezoneOptions}
/>
<SelectField
id="store-unit-system"
- label={t('admin.fields.store.preferred_unit_system.label')}
- name="preferred_unit_system"
+ label={t('admin.fields.store.unit_system.label')}
+ name="unit_system"
control={form.control}
options={unitSystemOptions}
/>
<SelectField
id="store-weight-unit"
- label={t('admin.fields.store.preferred_weight_unit.label')}
- name="preferred_weight_unit"
+ label={t('admin.fields.store.weight_unit.label')}
+ name="weight_unit"
control={form.control}
options={weightOptions}
/>
@@ -469,7 +463,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
<SelectField
id="store-storefront-access"
label={t('admin.fields.store.storefront_access.label')}
- name="preferred_storefront_access"
+ name="storefront_access"
control={form.control}
options={storefrontAccessOptions}
help={t('admin.fields.store.storefront_access.help')}
@@ -485,7 +479,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
</span>
</div>
<Controller
- name="preferred_guest_checkout"
+ name="guest_checkout"
control={form.control}
render={({ field }) => (
<Switch
@@ -501,7 +495,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-always-include-confirm-step"
label={t('admin.fields.store.always_include_confirm_step.label')}
help={t('admin.fields.store.always_include_confirm_step.help')}
- name="preferred_always_include_confirm_step"
+ name="always_include_confirm_step"
control={form.control}
/>
</FieldGroup>
@@ -517,14 +511,14 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-company-field-enabled"
label={t('admin.fields.store.company_field_enabled.label')}
help={t('admin.fields.store.company_field_enabled.help')}
- name="preferred_company_field_enabled"
+ name="company_field_enabled"
control={form.control}
/>
<SwitchField
id="store-address-requires-phone"
label={t('admin.fields.store.address_requires_phone.label')}
help={t('admin.fields.store.address_requires_phone.help')}
- name="preferred_address_requires_phone"
+ name="address_requires_phone"
control={form.control}
/>
</FieldGroup>
@@ -539,7 +533,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
<SelectField
id="store-document-number-format"
label={t('admin.fields.store.document_number_format.label')}
- name="preferred_document_number_format"
+ name="document_number_format"
control={form.control}
options={documentNumberFormatOptions}
help={t('admin.fields.store.document_number_format.help')}
@@ -551,10 +545,10 @@ function StoreSettingsForm({ store }: { store: Store }) {
</FieldLabel>
<Input
id="store-order-number-prefix"
- aria-invalid={!!errors.preferred_order_number_prefix || undefined}
- {...form.register('preferred_order_number_prefix')}
+ aria-invalid={!!errors.order_number_prefix || undefined}
+ {...form.register('order_number_prefix')}
/>
- <FieldError errors={[errors.preferred_order_number_prefix]} />
+ <FieldError errors={[errors.order_number_prefix]} />
</Field>
<Field>
<FieldLabel htmlFor="store-order-number-suffix">
@@ -562,10 +556,10 @@ function StoreSettingsForm({ store }: { store: Store }) {
</FieldLabel>
<Input
id="store-order-number-suffix"
- aria-invalid={!!errors.preferred_order_number_suffix || undefined}
- {...form.register('preferred_order_number_suffix')}
+ aria-invalid={!!errors.order_number_suffix || undefined}
+ {...form.register('order_number_suffix')}
/>
- <FieldError errors={[errors.preferred_order_number_suffix]} />
+ <FieldError errors={[errors.order_number_suffix]} />
</Field>
</div>
{numberFormat === 'sequential' && (
@@ -578,15 +572,15 @@ function StoreSettingsForm({ store }: { store: Store }) {
type="number"
min={1}
disabled={sequenceStarted}
- aria-invalid={!!errors.preferred_order_number_sequence_start || undefined}
- {...form.register('preferred_order_number_sequence_start')}
+ aria-invalid={!!errors.order_number_sequence_start || undefined}
+ {...form.register('order_number_sequence_start')}
/>
<FieldDescription>
{sequenceStarted
? t('admin.fields.store.order_number_sequence_start.locked')
: t('admin.fields.store.order_number_sequence_start.help')}
</FieldDescription>
- <FieldError errors={[errors.preferred_order_number_sequence_start]} />
+ <FieldError errors={[errors.order_number_sequence_start]} />
</Field>
)}
<Field>
@@ -608,7 +602,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
<FieldGroup>
<Controller
control={form.control}
- name="preferred_capture_method"
+ name="capture_method"
render={({ field }) => (
<ChoiceCardPicker
label={t('admin.fields.store.capture_method.label')}
@@ -623,7 +617,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-tax-using-ship-address"
label={t('admin.fields.store.tax_using_ship_address.label')}
help={t('admin.fields.store.tax_using_ship_address.help')}
- name="preferred_tax_using_ship_address"
+ name="tax_using_ship_address"
control={form.control}
/>
</FieldGroup>
@@ -639,14 +633,14 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-track-inventory-levels"
label={t('admin.fields.store.track_inventory_levels.label')}
help={t('admin.fields.store.track_inventory_levels.help')}
- name="preferred_track_inventory_levels"
+ name="track_inventory_levels"
control={form.control}
/>
<SwitchField
id="store-stock-reservations-enabled"
label={t('admin.fields.store.stock_reservations_enabled.label')}
help={t('admin.fields.store.stock_reservations_enabled.help')}
- name="preferred_stock_reservations_enabled"
+ name="stock_reservations_enabled"
control={form.control}
/>
<Field>
@@ -659,8 +653,8 @@ function StoreSettingsForm({ store }: { store: Store }) {
type="number"
min={0}
step={1}
- aria-invalid={!!errors.preferred_low_stock_threshold || undefined}
- {...form.register('preferred_low_stock_threshold')}
+ aria-invalid={!!errors.low_stock_threshold || undefined}
+ {...form.register('low_stock_threshold')}
/>
<InputGroupAddon align="inline-end">
<InputGroupText>
@@ -671,7 +665,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
<FieldDescription>
{t('admin.fields.store.low_stock_threshold.help')}
</FieldDescription>
- <FieldError errors={[errors.preferred_low_stock_threshold]} />
+ <FieldError errors={[errors.low_stock_threshold]} />
</Field>
</FieldGroup>
</CardContent>
@@ -689,7 +683,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-pricing-provider"
label={t('admin.fields.store.data_sources.pricing_provider.label')}
help={t('admin.fields.store.data_sources.pricing_provider.help')}
- name="preferred_pricing_provider"
+ name="pricing_provider"
control={form.control}
options={providerOptions(dataSources?.pricing_providers)}
/>
@@ -701,7 +695,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-pricing-failure-policy"
label={t('admin.fields.store.data_sources.pricing_failure_policy.label')}
help={t('admin.fields.store.data_sources.pricing_failure_policy.help')}
- name="preferred_pricing_provider_failure_policy"
+ name="pricing_provider_failure_policy"
control={form.control}
options={failurePolicyOptions}
/>
@@ -727,7 +721,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-inventory-provider"
label={t('admin.fields.store.data_sources.inventory_provider.label')}
help={t('admin.fields.store.data_sources.inventory_provider.help')}
- name="preferred_inventory_provider"
+ name="inventory_provider"
control={form.control}
options={providerOptions(dataSources?.inventory_providers)}
/>
@@ -736,7 +730,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-inventory-failure-policy"
label={t('admin.fields.store.data_sources.inventory_failure_policy.label')}
help={t('admin.fields.store.data_sources.inventory_failure_policy.help')}
- name="preferred_inventory_provider_failure_policy"
+ name="inventory_provider_failure_policy"
control={form.control}
options={failurePolicyOptions}
/>
@@ -759,21 +753,21 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-show-products-without-price"
label={t('admin.fields.store.show_products_without_price.label')}
help={t('admin.fields.store.show_products_without_price.help')}
- name="preferred_show_products_without_price"
+ name="show_products_without_price"
control={form.control}
/>
<SwitchField
id="store-track-price-history"
label={t('admin.fields.store.track_price_history.label')}
help={t('admin.fields.store.track_price_history.help')}
- name="preferred_track_price_history"
+ name="track_price_history"
control={form.control}
/>
<SwitchField
id="store-disable-sku-validation"
label={t('admin.fields.store.disable_sku_validation.label')}
help={t('admin.fields.store.disable_sku_validation.help')}
- name="preferred_disable_sku_validation"
+ name="disable_sku_validation"
control={form.control}
/>
</FieldGroup>
@@ -802,7 +796,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
</span>
</div>
<Controller
- name="preferred_limit_digital_download_count"
+ name="limit_digital_download_count"
control={form.control}
render={({ field }) => (
<Switch
@@ -814,7 +808,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
/>
</div>
</Field>
- {form.watch('preferred_limit_digital_download_count') && (
+ {form.watch('limit_digital_download_count') && (
<Field>
<FieldLabel htmlFor="store-authorized-clicks">
{t('admin.fields.store.digital_asset_authorized_clicks.label')}
@@ -823,10 +817,10 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-authorized-clicks"
type="number"
min={1}
- {...form.register('preferred_digital_asset_authorized_clicks')}
+ {...form.register('digital_asset_authorized_clicks')}
/>
<FieldError
- errors={[form.formState.errors.preferred_digital_asset_authorized_clicks]}
+ errors={[form.formState.errors.digital_asset_authorized_clicks]}
/>
</Field>
)}
@@ -844,7 +838,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
</span>
</div>
<Controller
- name="preferred_limit_digital_download_days"
+ name="limit_digital_download_days"
control={form.control}
render={({ field }) => (
<Switch
@@ -856,7 +850,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
/>
</div>
</Field>
- {form.watch('preferred_limit_digital_download_days') && (
+ {form.watch('limit_digital_download_days') && (
<Field>
<FieldLabel htmlFor="store-authorized-days">
{t('admin.fields.store.digital_asset_authorized_days.label')}
@@ -865,10 +859,10 @@ function StoreSettingsForm({ store }: { store: Store }) {
id="store-authorized-days"
type="number"
min={1}
- {...form.register('preferred_digital_asset_authorized_days')}
+ {...form.register('digital_asset_authorized_days')}
/>
<FieldError
- errors={[form.formState.errors.preferred_digital_asset_authorized_days]}
+ errors={[form.formState.errors.digital_asset_authorized_days]}
/>
</Field>
)}
diff --git a/packages/dashboard/src/schemas/channel.ts b/packages/dashboard/src/schemas/channel.ts
index 1ccadf308a..cf73f4caa3 100644
--- a/packages/dashboard/src/schemas/channel.ts
+++ b/packages/dashboard/src/schemas/channel.ts
@@ -27,9 +27,9 @@ export const channelFormSchema = z.object({
.optional(),
active: z.boolean(),
default: z.boolean(),
- preferred_order_routing_strategy: z.string(),
- preferred_storefront_access: z.string(),
- preferred_guest_checkout: z.string(),
+ order_routing_strategy: z.string(),
+ storefront_access: z.string(),
+ guest_checkout: z.string(),
// Empty means shoppers outside any assigned catalog see every product
// published on the channel.
default_catalog_id: z.string(),
@@ -45,9 +45,9 @@ export const CHANNEL_DEFAULTS: ChannelFormValues = {
code: '',
active: true,
default: false,
- preferred_order_routing_strategy: '',
- preferred_storefront_access: '',
- preferred_guest_checkout: '',
+ order_routing_strategy: '',
+ storefront_access: '',
+ guest_checkout: '',
default_catalog_id: '',
stock_location_ids: [],
}
@@ -65,11 +65,10 @@ export function channelValuesToParams(
...(v.code ? { code: v.code } : {}),
active: v.active,
default: v.default,
- preferred_order_routing_strategy: v.preferred_order_routing_strategy || null,
- preferred_storefront_access: v.preferred_storefront_access || null,
+ order_routing_strategy: v.order_routing_strategy || null,
+ storefront_access: v.storefront_access || null,
// '' → inherit (null); otherwise an explicit boolean.
- preferred_guest_checkout:
- v.preferred_guest_checkout === '' ? null : v.preferred_guest_checkout === 'true',
+ guest_checkout: v.guest_checkout === '' ? null : v.guest_checkout === 'true',
// '' → no default catalog: shoppers outside any assigned catalog see
// every product published on the channel.
default_catalog_id: v.default_catalog_id || null,
diff --git a/packages/dashboard/src/schemas/commission-rate.test.ts b/packages/dashboard/src/schemas/commission-rate.test.ts
index d0b44ce198..5de07a487f 100644
--- a/packages/dashboard/src/schemas/commission-rate.test.ts
+++ b/packages/dashboard/src/schemas/commission-rate.test.ts
@@ -32,8 +32,7 @@ describe('commissionRateToFormValues', () => {
id: 'comrule_1',
type: 'seller_rule',
commission_rate_id: 'crate_1',
- preferences: { seller_ids: [42] },
- preference_schema: [],
+ preferences: { seller_ids: ['sel_abc'] },
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
product_ids: null,
@@ -44,8 +43,7 @@ describe('commissionRateToFormValues', () => {
id: 'comrule_2',
type: 'category_rule',
commission_rate_id: 'crate_1',
- preferences: { category_ids: [7] },
- preference_schema: [],
+ preferences: { category_ids: ['ctg_xyz'] },
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
product_ids: null,
diff --git a/packages/dashboard/src/schemas/delivery-method.ts b/packages/dashboard/src/schemas/delivery-method.ts
index 09693aaeef..5415714ca3 100644
--- a/packages/dashboard/src/schemas/delivery-method.ts
+++ b/packages/dashboard/src/schemas/delivery-method.ts
@@ -47,8 +47,10 @@ export const deliveryMethodFormSchema = z.object({
estimated_transit_business_days_min: z.string().optional(),
estimated_transit_business_days_max: z.string().optional(),
tax_category_id: z.string().optional(),
- calculator_type: z.string().optional(),
- calculator_preferences: z.record(z.string(), z.unknown()).optional(),
+ calculator: z.object({
+ type: z.string().optional(),
+ preferences: z.record(z.string(), z.unknown()).optional(),
+ }),
// Empty string means no destination restriction — the method serves
// everywhere its profile reaches.
delivery_zone_id: z.string(),
@@ -75,8 +77,7 @@ export const DELIVERY_METHOD_DEFAULTS: DeliveryMethodFormValues = {
estimated_transit_business_days_min: '',
estimated_transit_business_days_max: '',
tax_category_id: '',
- calculator_type: '',
- calculator_preferences: {},
+ calculator: { type: '', preferences: {} },
delivery_zone_id: '',
stock_location_ids: [],
rules: [],
@@ -102,9 +103,17 @@ export function deliveryMethodValuesToParams(values: DeliveryMethodFormValues) {
? Number(values.estimated_transit_business_days_max)
: null,
tax_category_id: values.tax_category_id || null,
- ...(values.calculator_type ? { calculator_type: values.calculator_type } : {}),
- ...(values.calculator_preferences && Object.keys(values.calculator_preferences).length > 0
- ? { calculator_preferences: values.calculator_preferences }
+ ...(values.calculator.type ||
+ (values.calculator.preferences && Object.keys(values.calculator.preferences).length > 0)
+ ? {
+ calculator: {
+ ...(values.calculator.type ? { type: values.calculator.type } : {}),
+ ...(values.calculator.preferences &&
+ Object.keys(values.calculator.preferences).length > 0
+ ? { preferences: values.calculator.preferences }
+ : {}),
+ },
+ }
: {}),
delivery_zone_id: values.delivery_zone_id || null,
stock_location_ids: values.stock_location_ids,
diff --git a/packages/dashboard/src/schemas/marketplace.ts b/packages/dashboard/src/schemas/marketplace.ts
index 063f91a132..b82dee626c 100644
--- a/packages/dashboard/src/schemas/marketplace.ts
+++ b/packages/dashboard/src/schemas/marketplace.ts
@@ -18,13 +18,13 @@ export const PAYOUT_SCHEDULE_INTERVALS = [
export const marketplaceSettingsFormSchema = z.object({
// Blank is the built-in provider: the marketplace keeps the books and
// settles by hand.
- preferred_payout_provider: z.string(),
- preferred_default_payouts_schedule_interval: z.enum(PAYOUT_SCHEDULE_INTERVALS),
+ payout_provider: z.string(),
+ default_payouts_schedule_interval: z.enum(PAYOUT_SCHEDULE_INTERVALS),
// A canonical decimal string from a number input, sent as typed.
- preferred_default_minimum_payout_amount: nonNegativeDecimal,
- preferred_auto_approve_sellers: z.boolean(),
- preferred_auto_approve_seller_products: z.boolean(),
- preferred_send_seller_transactional_emails: z.boolean(),
+ default_minimum_payout_amount: nonNegativeDecimal,
+ auto_approve_sellers: z.boolean(),
+ auto_approve_seller_products: z.boolean(),
+ send_seller_transactional_emails: z.boolean(),
// A percentage, because that is how a merchant states a VAT rate. The
// preference behind it is a fraction bounded at 1, so the field is bounded
// at 100 and converted on the way in and out (see `percentToFraction`).
diff --git a/packages/dashboard/src/schemas/payment-method.test.ts b/packages/dashboard/src/schemas/payment-method.test.ts
index 094bb74c4b..45e595c574 100644
--- a/packages/dashboard/src/schemas/payment-method.test.ts
+++ b/packages/dashboard/src/schemas/payment-method.test.ts
@@ -4,13 +4,21 @@ import { filterPaymentMethodProviderTypes } from './payment-method'
describe('filterPaymentMethodProviderTypes', () => {
it('removes custom payment source from the provider picker list', () => {
const types = [
- { type: 'stripe', label: 'Stripe', preference_schema: [] },
+ {
+ type: 'stripe',
+ label: 'Stripe',
+ schema: { type: 'object' as const, properties: {}, additionalProperties: false as const },
+ },
{
type: 'custom_payment_source_method',
label: 'Custom Payment Source Method',
- preference_schema: [],
+ schema: { type: 'object' as const, properties: {}, additionalProperties: false as const },
+ },
+ {
+ type: 'check',
+ label: 'Check',
+ schema: { type: 'object' as const, properties: {}, additionalProperties: false as const },
},
- { type: 'check', label: 'Check', preference_schema: [] },
]
expect(filterPaymentMethodProviderTypes(types).map((t) => t.type)).toEqual(['stripe', 'check'])
diff --git a/packages/dashboard/src/schemas/price-list.ts b/packages/dashboard/src/schemas/price-list.ts
index 2464d67e25..bec04e1aad 100644
--- a/packages/dashboard/src/schemas/price-list.ts
+++ b/packages/dashboard/src/schemas/price-list.ts
@@ -1,5 +1,5 @@
import type {
- PreferenceField,
+ PreferenceSchema,
PriceListCreateParams,
PriceListUpdateParams,
PriceRule,
@@ -44,11 +44,11 @@ export const MAXIMUM_QUANTITY_TIERS = 10
export type AdjustmentDirection = (typeof ADJUSTMENT_DIRECTIONS)[number]
/**
- * Form-state row for a price rule. Carries `preference_schema` for the
- * editor alongside the payload fields the API consumes (`type`,
- * `preferences`, optional `id`). The rule's name and description are
- * resolved from `type` at render time, so no copy is stored here. Closely
- * mirrors `PromotionRuleFormDraft` so the editor patterns are 1:1.
+ * Form-state row for a price rule: the payload fields the API consumes
+ * (`type`, `preferences`, optional `id`). The rule's name, description and
+ * preference schema are resolved from `type` at render time, so no copy is
+ * stored here. Closely mirrors `PromotionRuleFormDraft` so the editor
+ * patterns are 1:1.
*/
export interface PriceRuleFormDraft {
/** Stable client-side id used as a React key while the row has no server id. */
@@ -57,7 +57,6 @@ export interface PriceRuleFormDraft {
id?: string
/** Wire shorthand — `volume_rule`, `market_rule`, etc. */
type: string
- preference_schema: PreferenceField[]
preferences: Record<string, unknown>
/**
* Display-only embeds the per-rule editors set when the user picks
@@ -94,7 +93,6 @@ const priceRuleDraftSchema: z.ZodType<PriceRuleFormDraft> = z.object({
_localId: z.string(),
id: z.string().optional(),
type: z.string().min(1),
- preference_schema: z.array(z.any()).default([]),
preferences: z.record(z.string(), z.unknown()).default({}),
customers: z.array(z.any()).optional(),
customer_groups: z.array(z.any()).optional(),
@@ -216,7 +214,6 @@ export function ruleDraftFromRule(rule: PriceRule): PriceRuleFormDraft {
_localId: rule.id,
id: rule.id,
type: rule.type,
- preference_schema: rule.preference_schema,
preferences: rule.preferences,
customers: rule.customers ?? undefined,
customer_groups: rule.customer_groups ?? undefined,
@@ -228,13 +225,12 @@ export function ruleDraftFromRule(rule: PriceRule): PriceRuleFormDraft {
/** Materializes a fresh draft from a registry type definition. */
export function ruleDraftFromType(type: {
type: string
- preference_schema: PreferenceField[]
+ schema: PreferenceSchema
}): PriceRuleFormDraft {
return {
_localId: newLocalId(),
type: type.type,
- preference_schema: type.preference_schema,
- preferences: defaultPreferences(type.preference_schema),
+ preferences: defaultPreferences(type.schema),
}
}
diff --git a/packages/dashboard/src/schemas/store-emails.ts b/packages/dashboard/src/schemas/store-emails.ts
index afb9a08dd8..fd14824709 100644
--- a/packages/dashboard/src/schemas/store-emails.ts
+++ b/packages/dashboard/src/schemas/store-emails.ts
@@ -39,13 +39,13 @@ export const storeEmailsFormSchema = z.object({
.email(),
customer_support_email: optionalEmail,
new_order_notifications_email: optionalEmail,
- preferred_send_consumer_transactional_emails: z.boolean(),
- preferred_email_accent_color: optionalColor,
- preferred_email_background_color: optionalColor,
- preferred_email_card_color: optionalColor,
- preferred_email_text_color: optionalColor,
- preferred_email_heading_color: optionalColor,
- preferred_email_font: z.enum(EMAIL_FONTS),
+ send_consumer_transactional_emails: z.boolean(),
+ email_accent_color: optionalColor,
+ email_background_color: optionalColor,
+ email_card_color: optionalColor,
+ email_text_color: optionalColor,
+ email_heading_color: optionalColor,
+ email_font: z.enum(EMAIL_FONTS),
// Active Storage signed_id from a fresh direct upload. Frontend-only state.
mailer_logo_signed_id: z.string().nullable().optional(),
diff --git a/packages/dashboard/src/schemas/store.ts b/packages/dashboard/src/schemas/store.ts
index 972d9d4929..d739c7d543 100644
--- a/packages/dashboard/src/schemas/store.ts
+++ b/packages/dashboard/src/schemas/store.ts
@@ -41,52 +41,52 @@ export const INTERNAL_PROVIDER_KEY = 'internal'
export const storeSettingsFormSchema = z.object({
name: z.string().min(1, { error: requiredMessage('store.name') }),
- preferred_admin_locale: z.string().nullable().optional(),
- preferred_timezone: z.string().min(1, { error: requiredMessage('store.preferred_timezone') }),
- preferred_unit_system: z.enum(['metric', 'imperial']),
- preferred_weight_unit: z.enum(ALL_WEIGHT_UNITS),
- preferred_storefront_access: z.enum(STOREFRONT_ACCESS_LEVELS),
- preferred_guest_checkout: z.boolean(),
- preferred_always_include_confirm_step: z.boolean(),
- preferred_company_field_enabled: z.boolean(),
- preferred_address_requires_phone: z.boolean(),
- preferred_capture_method: z.enum(CAPTURE_METHODS),
- preferred_pricing_provider: z.string(),
- preferred_inventory_provider: z.string(),
- preferred_pricing_provider_failure_policy: z.enum(PROVIDER_FAILURE_POLICIES),
- preferred_inventory_provider_failure_policy: z.enum(PROVIDER_FAILURE_POLICIES),
- preferred_tax_using_ship_address: z.boolean(),
- preferred_track_inventory_levels: z.boolean(),
- preferred_stock_reservations_enabled: z.boolean(),
- preferred_low_stock_threshold: z.coerce
+ admin_locale: z.string().nullable().optional(),
+ timezone: z.string().min(1, { error: requiredMessage('store.timezone') }),
+ unit_system: z.enum(['metric', 'imperial']),
+ weight_unit: z.enum(ALL_WEIGHT_UNITS),
+ storefront_access: z.enum(STOREFRONT_ACCESS_LEVELS),
+ guest_checkout: z.boolean(),
+ always_include_confirm_step: z.boolean(),
+ company_field_enabled: z.boolean(),
+ address_requires_phone: z.boolean(),
+ capture_method: z.enum(CAPTURE_METHODS),
+ pricing_provider: z.string(),
+ inventory_provider: z.string(),
+ pricing_provider_failure_policy: z.enum(PROVIDER_FAILURE_POLICIES),
+ inventory_provider_failure_policy: z.enum(PROVIDER_FAILURE_POLICIES),
+ tax_using_ship_address: z.boolean(),
+ track_inventory_levels: z.boolean(),
+ stock_reservations_enabled: z.boolean(),
+ low_stock_threshold: z.coerce
.number()
.int()
- .min(0, { error: requiredMessage('store.preferred_low_stock_threshold') }),
- preferred_track_price_history: z.boolean(),
- preferred_show_products_without_price: z.boolean(),
- preferred_disable_sku_validation: z.boolean(),
- preferred_document_number_format: z.enum(DOCUMENT_NUMBER_FORMATS),
- preferred_order_number_prefix: z
+ .min(0, { error: requiredMessage('store.low_stock_threshold') }),
+ track_price_history: z.boolean(),
+ show_products_without_price: z.boolean(),
+ disable_sku_validation: z.boolean(),
+ document_number_format: z.enum(DOCUMENT_NUMBER_FORMATS),
+ order_number_prefix: z
.string()
.max(10)
.regex(NUMBER_AFFIX_PATTERN, { error: 'admin.fields.store.order_number_prefix.invalid' }),
- preferred_order_number_suffix: z
+ order_number_suffix: z
.string()
.max(10)
.regex(NUMBER_AFFIX_PATTERN, { error: 'admin.fields.store.order_number_suffix.invalid' }),
- preferred_order_number_sequence_start: z.coerce.number().int().min(1),
+ order_number_sequence_start: z.coerce.number().int().min(1),
// Store-wide download allowances. Individual files can override the numbers;
// switching a limit off here removes it for the whole store.
- preferred_limit_digital_download_count: z.boolean(),
- preferred_digital_asset_authorized_clicks: z.coerce
+ limit_digital_download_count: z.boolean(),
+ digital_asset_authorized_clicks: z.coerce
.number()
.int()
- .min(1, { error: requiredMessage('store.preferred_digital_asset_authorized_clicks') }),
- preferred_limit_digital_download_days: z.boolean(),
- preferred_digital_asset_authorized_days: z.coerce
+ .min(1, { error: requiredMessage('store.digital_asset_authorized_clicks') }),
+ limit_digital_download_days: z.boolean(),
+ digital_asset_authorized_days: z.coerce
.number()
.int()
- .min(1, { error: requiredMessage('store.preferred_digital_asset_authorized_days') }),
+ .min(1, { error: requiredMessage('store.digital_asset_authorized_days') }),
})
export type StoreSettingsFormValues = z.infer<typeof storeSettingsFormSchema>
diff --git a/packages/sdk-core/src/index.ts b/packages/sdk-core/src/index.ts
index c0479cdb66..7d0c5d486f 100644
--- a/packages/sdk-core/src/index.ts
+++ b/packages/sdk-core/src/index.ts
@@ -36,6 +36,8 @@ export type {
LoginCredentials,
PaginatedResponse,
PaginationMeta,
+ PreferencePropertySchema,
+ PreferenceSchema,
ProviderLogin,
ValidationErrorDetail,
} from './types'
diff --git a/packages/sdk-core/src/types.ts b/packages/sdk-core/src/types.ts
index 888d502413..38eff7dfd9 100644
--- a/packages/sdk-core/src/types.ts
+++ b/packages/sdk-core/src/types.ts
@@ -121,3 +121,37 @@ export interface ProviderLogin {
}
export type LoginCredentials = EmailPasswordLogin | ProviderLogin
+
+/**
+ * One setting in a {@link PreferenceSchema}: a JSON Schema (draft 2020-12)
+ * property. `format` names the domain (`money`, `currency`, `iso-country`,
+ * `prefixed-id`, `date`, …); a type that includes `'null'` may be unset.
+ */
+export interface PreferencePropertySchema {
+ type?: string | string[]
+ format?: string
+ pattern?: string
+ enum?: Array<string | number | boolean | null>
+ default?: unknown
+ items?: PreferencePropertySchema
+ properties?: Record<string, PreferencePropertySchema>
+ required?: string[]
+ additionalProperties?: boolean | PreferencePropertySchema
+ propertyNames?: PreferencePropertySchema
+ /** A secret: read back masked (`••••1234`). Sending the mask back keeps it; `null` clears it. */
+ 'x-spree-secret'?: boolean
+ /** The prefix every id in an id list carries (`ch` for `ch_…`). */
+ 'x-spree-prefix'?: string
+ /** A longer text, best edited in a multi-line field. */
+ 'x-spree-widget'?: 'textarea'
+}
+
+/**
+ * The JSON Schema of a type's `preferences`, as every `/…/types` endpoint
+ * returns it. A key it does not list is refused on write.
+ */
+export interface PreferenceSchema {
+ type: 'object'
+ properties: Record<string, PreferencePropertySchema>
+ additionalProperties: false
+}
diff --git a/packages/seller-dashboard/src/hooks/use-store-timezone.ts b/packages/seller-dashboard/src/hooks/use-store-timezone.ts
index be2b2a25e5..d54be2b2b0 100644
--- a/packages/seller-dashboard/src/hooks/use-store-timezone.ts
+++ b/packages/seller-dashboard/src/hooks/use-store-timezone.ts
@@ -22,5 +22,5 @@ export function useStoreTimezone(): string {
enabled: Boolean(sellerId),
})
- return profile?.preferred_timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC'
+ return profile?.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC'
}
diff --git a/packages/seller-dashboard/src/pages/delivery-methods.tsx b/packages/seller-dashboard/src/pages/delivery-methods.tsx
index 5c559025b2..6536154f3b 100644
--- a/packages/seller-dashboard/src/pages/delivery-methods.tsx
+++ b/packages/seller-dashboard/src/pages/delivery-methods.tsx
@@ -37,7 +37,7 @@ import {
useRowClickBridge,
} from '@spree/dashboard-ui'
import { PlusIcon, TrashIcon } from '@spree/dashboard-ui/icons'
-import type { DeliveryMethod, DeliveryPreferenceField } from '@spree/seller-sdk'
+import type { DeliveryMethod, PreferenceSchema } from '@spree/seller-sdk'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useParams } from '@tanstack/react-router'
import { useEffect, useState } from 'react'
@@ -166,8 +166,7 @@ interface DeliveryMethodFormValues {
storefront_visible: boolean
delivery_profile_id: string
delivery_zone_id: string
- calculator_type: string
- calculator_preferences: Record<string, unknown>
+ calculator: { type: string; preferences: Record<string, unknown> }
rules: RuleDraft[]
}
@@ -177,8 +176,7 @@ const DEFAULTS: DeliveryMethodFormValues = {
storefront_visible: true,
delivery_profile_id: '',
delivery_zone_id: '',
- calculator_type: '',
- calculator_preferences: {},
+ calculator: { type: '', preferences: {} },
rules: [],
}
@@ -231,7 +229,7 @@ function DeliveryMethodSheet({
const form = useForm<DeliveryMethodFormValues>({ defaultValues: DEFAULTS })
const profileId = form.watch('delivery_profile_id')
- const calculatorType = form.watch('calculator_type')
+ const calculatorType = form.watch('calculator.type')
const rules = form.watch('rules')
// A zone only means something under its profile, so the picker follows
@@ -252,8 +250,10 @@ function DeliveryMethodSheet({
storefront_visible: method.storefront_visible,
delivery_profile_id: method.delivery_profile_id ?? '',
delivery_zone_id: method.delivery_zone_id ?? '',
- calculator_type: method.calculator_type ?? '',
- calculator_preferences: method.calculator_preferences ?? {},
+ calculator: {
+ type: method.calculator?.type ?? '',
+ preferences: method.calculator?.preferences ?? {},
+ },
rules: (method.rules ?? []).map((rule) => ({
id: rule.id,
type: rule.type,
@@ -274,19 +274,18 @@ function DeliveryMethodSheet({
// the picker blank would show an empty Pricing box while the server
// quietly created the method free.
useEffect(() => {
- if (methodId || form.getValues('calculator_type')) return
+ if (methodId || form.getValues('calculator.type')) return
const flatRate = calculators?.data.find((calculator) => calculator.type === 'flat_rate')
if (!flatRate) return
- form.setValue('calculator_type', flatRate.type)
- form.setValue(
- 'calculator_preferences',
- defaultPreferences(renderableSchema(flatRate.preference_schema)),
- )
+ form.setValue('calculator', {
+ type: flatRate.type,
+ preferences: defaultPreferences(renderableSchema(flatRate.schema)),
+ })
}, [calculators, methodId, form])
const calculatorSchema = renderableSchema(
- calculators?.data.find((calculator) => calculator.type === calculatorType)?.preference_schema,
+ calculators?.data.find((calculator) => calculator.type === calculatorType)?.schema,
)
const save = useMutation({
@@ -297,8 +296,10 @@ function DeliveryMethodSheet({
storefront_visible: values.storefront_visible,
delivery_profile_id: values.delivery_profile_id || undefined,
delivery_zone_id: values.delivery_zone_id || null,
- ...(values.calculator_type ? { calculator_type: values.calculator_type } : {}),
- calculator_preferences: values.calculator_preferences,
+ calculator: {
+ ...(values.calculator.type ? { type: values.calculator.type } : {}),
+ preferences: values.calculator.preferences,
+ },
// The array replaces the whole set: a rule dropped here is deleted,
// which is why every surviving row is re-sent with its id.
rules: values.rules.map((rule) => ({
@@ -329,9 +330,7 @@ function DeliveryMethodSheet({
const { errors } = form.formState
function addRule(type: string) {
- const schema = renderableSchema(
- ruleTypes?.data.find((rule) => rule.type === type)?.preference_schema,
- )
+ const schema = renderableSchema(ruleTypes?.data.find((rule) => rule.type === type)?.schema)
form.setValue('rules', [...rules, { type, preferences: defaultPreferences(schema) }])
}
@@ -482,7 +481,7 @@ function DeliveryMethodSheet({
</FieldLabel>
<Controller
control={form.control}
- name="calculator_type"
+ name="calculator.type"
render={({ field }) => (
<Select
value={field.value}
@@ -490,9 +489,9 @@ function DeliveryMethodSheet({
field.onChange(next)
const schema = renderableSchema(
calculators?.data.find((calculator) => calculator.type === next)
- ?.preference_schema,
+ ?.schema,
)
- form.setValue('calculator_preferences', defaultPreferences(schema))
+ form.setValue('calculator.preferences', defaultPreferences(schema))
}}
>
<SelectTrigger id="delivery-method-calculator">
@@ -521,7 +520,7 @@ function DeliveryMethodSheet({
<Controller
control={form.control}
- name="calculator_preferences"
+ name="calculator.preferences"
render={({ field }) => (
<PreferencesForm
schema={calculatorSchema}
@@ -582,7 +581,7 @@ function DeliveryMethodSheet({
</div>
<PreferencesForm
- schema={renderableSchema(definition?.preference_schema)}
+ schema={renderableSchema(definition?.schema)}
currencyOptions={currencyOptions}
values={rule.preferences}
onChange={(next) =>
@@ -632,16 +631,19 @@ function DeliveryMethodSheet({
}
/**
- * The fields of a preference schema the shared form can render.
+ * The part of a preference schema the shared form can render.
*
- * Drops `hash`-typed preferences — today the flat-rate calculator's
+ * Drops keyed maps — today the flat-rate calculator's
* per-currency `amounts` map, which the operator edits through a dedicated
* multi-currency control and the generic form would show as the hash itself
* in a text box. A seller quotes in the store's currency, so `amount` and
* `currency` are the whole question.
*/
-function renderableSchema(
- schema: DeliveryPreferenceField[] | undefined,
-): DeliveryPreferenceField[] {
- return (schema ?? []).filter((field) => field.type !== 'hash')
+function renderableSchema(schema: PreferenceSchema | undefined): PreferenceSchema | undefined {
+ if (!schema) return undefined
+
+ const properties = Object.entries(schema.properties).filter(
+ ([, property]) => typeof property.additionalProperties !== 'object',
+ )
+ return { ...schema, properties: Object.fromEntries(properties) }
}
diff --git a/packages/seller-sdk/src/index.ts b/packages/seller-sdk/src/index.ts
index 88fc51c5e6..af4e768e2b 100644
--- a/packages/seller-sdk/src/index.ts
+++ b/packages/seller-sdk/src/index.ts
@@ -23,7 +23,6 @@ export type {
DeliveryMethodParams,
DeliveryMethodRuleParams,
DeliveryMethodRuleType,
- DeliveryPreferenceField,
DeliveryZoneListParams,
MeResource,
MeResponse,
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 072982b1f9..e5e0278388 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -1,4 +1,10 @@
-import type { ListParams, PaginatedResponse, RequestFn, RequestOptions } from '@spree/sdk-core'
+import type {
+ ListParams,
+ PaginatedResponse,
+ PreferenceSchema,
+ RequestFn,
+ RequestOptions,
+} from '@spree/sdk-core'
import { transformListParams } from '@spree/sdk-core'
import type {
Account,
@@ -1387,7 +1393,7 @@ export interface ImportCreateParams {
*/
attachment: string
/** CSV column separator. Defaults to a comma on the server. */
- preferred_delimiter?: ',' | ';' | '|' | '\t'
+ delimiter?: ',' | ';' | '|' | '\t'
/**
* Absolute URL of the panel's imports view; the import-done email links back
* to it with `?import=<id>` appended. Honored only when it matches one of
@@ -1435,8 +1441,12 @@ export interface DeliveryMethodParams {
tracking_url?: string | null
estimated_transit_business_days_min?: number | null
estimated_transit_business_days_max?: number | null
- calculator_type?: string
- calculator_preferences?: Record<string, unknown>
+ /**
+ * How the method prices a shipment: the calculator's `type` (see
+ * `deliveryMethods.calculators()`) and its preferences, which must match the
+ * `schema` that list carries.
+ */
+ calculator?: { type?: string; preferences?: Record<string, unknown> }
/** Replaces the whole set; an empty array clears every condition. */
rules?: DeliveryMethodRuleParams[]
}
@@ -1447,22 +1457,12 @@ export interface DeliveryZoneListParams extends ListParams {
[key: string]: unknown
}
-/**
- * One field on a calculator's or rule's configuration form, as the server
- * describes it. The same shape the generated `DeliveryMethodRule` type
- * carries, so a schema from either endpoint renders through one form.
- */
-export interface DeliveryPreferenceField {
- key: string
- type: string
- default: unknown
-}
-
/** One way a delivery method can be priced. */
export interface DeliveryCalculatorType {
type: string
name: string
- preference_schema: DeliveryPreferenceField[]
+ /** JSON Schema of the calculator's `preferences`. */
+ schema: PreferenceSchema
}
/** One condition a seller may put on their own method. */
@@ -1470,7 +1470,8 @@ export interface DeliveryMethodRuleType {
type: string
name: string
description: string
- preference_schema: DeliveryPreferenceField[]
+ /** JSON Schema of the rule's `preferences`. */
+ schema: PreferenceSchema
}
/**
diff --git a/packages/seller-sdk/src/types/generated/DeliveryMethod.ts b/packages/seller-sdk/src/types/generated/DeliveryMethod.ts
index c06f78ac7b..04a5f0c3ef 100644
--- a/packages/seller-sdk/src/types/generated/DeliveryMethod.ts
+++ b/packages/seller-sdk/src/types/generated/DeliveryMethod.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 0cd1fcaf9c4c5a2cb7d6d5a7e643ff68
+// Typelizer digest bfa1ac542621d909937b45d8b40b807b
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {DeliveryMethodRule} from '@/types'
@@ -21,8 +21,7 @@ type DeliveryMethod = {
editable: boolean;
delivery_profile_id: string | null;
delivery_zone_id: string | null;
- calculator_type: string | null;
- calculator_preferences: Record<string, unknown> | null;
+ calculator: { type: string; preferences: Record<string, unknown> } | null;
}
export default DeliveryMethod;
diff --git a/packages/seller-sdk/src/types/generated/DeliveryMethodRule.ts b/packages/seller-sdk/src/types/generated/DeliveryMethodRule.ts
index 83842d0075..41233c84ad 100644
--- a/packages/seller-sdk/src/types/generated/DeliveryMethodRule.ts
+++ b/packages/seller-sdk/src/types/generated/DeliveryMethodRule.ts
@@ -1,4 +1,4 @@
-// Typelizer digest ce017153072038ce18d4cb6ea93b2a8d
+// Typelizer digest 71c665dd6ff9f5ff1f9b2413ca14f275
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -8,7 +8,6 @@ type DeliveryMethodRule = {
/** Rule type. Built-in: item_total_rule, weight_rule, excluded_products_rule, channel_rule, volume_rule, company_rule. Extensions may register more. */
type: string;
preferences: Record<string, unknown>;
- preference_schema: Array<{ key: string; type: string; default: unknown; choices?: string[] }>;
}
export default DeliveryMethodRule;
diff --git a/packages/seller-sdk/src/types/generated/Import.ts b/packages/seller-sdk/src/types/generated/Import.ts
index b2ddddb919..e7286d95d6 100644
--- a/packages/seller-sdk/src/types/generated/Import.ts
+++ b/packages/seller-sdk/src/types/generated/Import.ts
@@ -1,4 +1,4 @@
-// Typelizer digest dd0c73367e634a7e0e8d2bd9a0e27818
+// Typelizer digest b7d441552b5ab7606a9662d18b72e502
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {ImportMapping, ImportStatus} from '@/types'
@@ -18,7 +18,7 @@ type Import = {
owner_id: string | null;
user_id: string | null;
processing_errors: string | null;
- preferred_delimiter: string;
+ delimiter: string;
original_filename: string | null;
original_byte_size: number | null;
original_file_url: string | null;
diff --git a/packages/seller-sdk/src/types/generated/Profile.ts b/packages/seller-sdk/src/types/generated/Profile.ts
index 674d1ebb0e..9a08fd3de8 100644
--- a/packages/seller-sdk/src/types/generated/Profile.ts
+++ b/packages/seller-sdk/src/types/generated/Profile.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 72248d28723538db9f2f68bcf6df620b
+// Typelizer digest 937723e4c17fd5b9e0df90582405860c
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Policy, Address, SellerStatus} from '@/types'
@@ -12,7 +12,7 @@ type Profile = {
logo_url: string | null;
square_logo_url: string | null;
cover_photo_url: string | null;
- preferred_timezone: string | null;
+ timezone: string | null;
status: SellerStatus;
legal_name: string | null;
registration_number: string | null;
diff --git a/packages/seller-sdk/src/types/index.ts b/packages/seller-sdk/src/types/index.ts
index c05a9d44ee..72274fcec8 100644
--- a/packages/seller-sdk/src/types/index.ts
+++ b/packages/seller-sdk/src/types/index.ts
@@ -5,13 +5,16 @@ export type {
ListResponse,
PaginatedResponse,
PaginationMeta,
+ PreferencePropertySchema,
+ PreferenceSchema,
} from '@spree/sdk-core'
-
// Generated from the Seller API's serializers (`Spree::Api::V3::Seller::*`).
// `TeamMember`, `Invitation`, `Profile` and `Address` come from here — the
// serializers are the contract, so hand-writing them again would let the two
// drift apart silently.
export * from './generated'
+// Each configurable family's `preferences`, typed by `type` (generated by `rake typelizer:generate`).
+export type * from './preferences'
import type { default as Account } from './generated/Account'
diff --git a/packages/seller-sdk/src/types/preferences.ts b/packages/seller-sdk/src/types/preferences.ts
new file mode 100644
index 0000000000..8b56a8bd85
--- /dev/null
+++ b/packages/seller-sdk/src/types/preferences.ts
@@ -0,0 +1,128 @@
+// This file is auto-generated from Spree's preference declarations by `rake typelizer:generate`. Do not edit directly.
+import type DeliveryMethodRule from './generated/DeliveryMethodRule'
+
+/** `Resource` with its `preferences` typed by its `type`, one member per entry of `Map`. */
+type Narrowed<Resource, Map> = {
+ [Type in keyof Map]: Omit<Resource, 'type' | 'preferences'> & {
+ type: Type
+ preferences: Map[Type]
+ }
+}[keyof Map]
+
+/** Settings of the `digital_delivery` delivery calculator. */
+export interface DeliveryCalculatorDigitalDeliveryPreferences {
+ amounts: Record<string, string>
+ /** An amount, as an exact decimal string. */
+ amount: string
+ /** Format: `currency`. */
+ currency: string
+}
+
+/** Settings of the `flat_percent_item_total` delivery calculator. */
+export interface DeliveryCalculatorFlatPercentItemTotalPreferences {
+ flat_percent: string
+}
+
+/** Settings of the `flat_rate` delivery calculator. */
+export interface DeliveryCalculatorFlatRatePreferences {
+ amounts: Record<string, string>
+ /** An amount, as an exact decimal string. */
+ amount: string
+ /** Format: `currency`. */
+ currency: string
+}
+
+/** Settings of the `flexi_rate` delivery calculator. */
+export interface DeliveryCalculatorFlexiRatePreferences {
+ /** An amount, as an exact decimal string. */
+ first_item: string
+ /** An amount, as an exact decimal string. */
+ additional_item: string
+ max_items: number
+ /** Format: `currency`. */
+ currency: string
+}
+
+/** Settings of the `per_item` delivery calculator. */
+export interface DeliveryCalculatorPerItemPreferences {
+ amounts: Record<string, string>
+ /** An amount, as an exact decimal string. */
+ amount: string
+ /** Format: `currency`. */
+ currency: string
+}
+
+/** Settings of the `price_sack` delivery calculator. */
+export interface DeliveryCalculatorPriceSackPreferences {
+ /** An amount, as an exact decimal string. */
+ minimal_amount: string
+ /** An amount, as an exact decimal string. */
+ normal_amount: string
+ /** An amount, as an exact decimal string. */
+ discount_amount: string
+ /** Format: `currency`. */
+ currency: string
+}
+
+/**
+ * The settings of each delivery calculator type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface DeliveryCalculatorPreferencesMap {
+ digital_delivery: DeliveryCalculatorDigitalDeliveryPreferences
+ flat_percent_item_total: DeliveryCalculatorFlatPercentItemTotalPreferences
+ flat_rate: DeliveryCalculatorFlatRatePreferences
+ flexi_rate: DeliveryCalculatorFlexiRatePreferences
+ per_item: DeliveryCalculatorPerItemPreferences
+ price_sack: DeliveryCalculatorPriceSackPreferences
+}
+
+/** Settings of the `channel_rule` delivery method rule. */
+export interface DeliveryMethodRuleChannelRulePreferences {
+ /** Prefixed `ch_` ids. */
+ channel_ids: Array<string>
+}
+
+/** Settings of the `company_rule` delivery method rule. */
+export interface DeliveryMethodRuleCompanyRulePreferences {
+ company_orders_only: boolean
+}
+
+/** Settings of the `excluded_products_rule` delivery method rule: none. */
+export type DeliveryMethodRuleExcludedProductsRulePreferences = Record<string, never>
+
+/** Settings of the `item_total_rule` delivery method rule. */
+export interface DeliveryMethodRuleItemTotalRulePreferences {
+ /** An amount, as an exact decimal string. */
+ minimum_amount: string | null
+ /** An amount, as an exact decimal string. */
+ maximum_amount: string | null
+}
+
+/** Settings of the `volume_rule` delivery method rule. */
+export interface DeliveryMethodRuleVolumeRulePreferences {
+ minimum_volume: string | null
+ maximum_volume: string | null
+}
+
+/** Settings of the `weight_rule` delivery method rule. */
+export interface DeliveryMethodRuleWeightRulePreferences {
+ minimum_weight: string | null
+ maximum_weight: string | null
+}
+
+/**
+ * The settings of each delivery method rule type Spree ships, by `type`. An interface,
+ * so an extension types its own by declaration merging.
+ */
+export interface DeliveryMethodRulePreferencesMap {
+ channel_rule: DeliveryMethodRuleChannelRulePreferences
+ company_rule: DeliveryMethodRuleCompanyRulePreferences
+ excluded_products_rule: DeliveryMethodRuleExcludedProductsRulePreferences
+ item_total_rule: DeliveryMethodRuleItemTotalRulePreferences
+ volume_rule: DeliveryMethodRuleVolumeRulePreferences
+ weight_rule: DeliveryMethodRuleWeightRulePreferences
+}
+
+/** A delivery method rule whose `preferences` are typed by its `type`. */
+export type TypedDeliveryMethodRule = Narrowed<DeliveryMethodRule, DeliveryMethodRulePreferencesMap>
diff --git a/packages/seller-sdk/src/zod/generated/DeliveryMethod.ts b/packages/seller-sdk/src/zod/generated/DeliveryMethod.ts
index 56df368e27..c26d0e1c3a 100644
--- a/packages/seller-sdk/src/zod/generated/DeliveryMethod.ts
+++ b/packages/seller-sdk/src/zod/generated/DeliveryMethod.ts
@@ -20,8 +20,7 @@ export const DeliveryMethodSchema = z.object({
editable: z.boolean(),
delivery_profile_id: z.string().nullable(),
delivery_zone_id: z.string().nullable(),
- calculator_type: z.string().nullable(),
- calculator_preferences: z.record(z.string(), z.unknown()).nullable(),
+ calculator: z.object({ type: z.string(), preferences: z.record(z.string(), z.unknown()) }).nullable(),
});
export type DeliveryMethod = z.infer<typeof DeliveryMethodSchema>;
diff --git a/packages/seller-sdk/src/zod/generated/DeliveryMethodRule.ts b/packages/seller-sdk/src/zod/generated/DeliveryMethodRule.ts
index a2ba06c92b..0cf523cc18 100644
--- a/packages/seller-sdk/src/zod/generated/DeliveryMethodRule.ts
+++ b/packages/seller-sdk/src/zod/generated/DeliveryMethodRule.ts
@@ -6,7 +6,6 @@ export const DeliveryMethodRuleSchema = z.object({
active: z.boolean(),
type: z.string(),
preferences: z.record(z.string(), z.unknown()),
- preference_schema: z.array(z.object({ key: z.string(), type: z.string(), default: z.unknown(), choices: z.array(z.string()).optional() })),
});
export type DeliveryMethodRule = z.infer<typeof DeliveryMethodRuleSchema>;
diff --git a/packages/seller-sdk/src/zod/generated/Import.ts b/packages/seller-sdk/src/zod/generated/Import.ts
index 5df025dcf0..041f563ad1 100644
--- a/packages/seller-sdk/src/zod/generated/Import.ts
+++ b/packages/seller-sdk/src/zod/generated/Import.ts
@@ -16,7 +16,7 @@ export const ImportSchema = z.object({
owner_id: z.string().nullable(),
user_id: z.string().nullable(),
processing_errors: z.string().nullable(),
- preferred_delimiter: z.string(),
+ delimiter: z.string(),
original_filename: z.string().nullable(),
original_byte_size: z.number().nullable(),
original_file_url: z.string().nullable(),
diff --git a/packages/seller-sdk/src/zod/generated/Profile.ts b/packages/seller-sdk/src/zod/generated/Profile.ts
index 839aa85fdd..761e4eb076 100644
--- a/packages/seller-sdk/src/zod/generated/Profile.ts
+++ b/packages/seller-sdk/src/zod/generated/Profile.ts
@@ -12,7 +12,7 @@ export const ProfileSchema = z.object({
logo_url: z.string().nullable(),
square_logo_url: z.string().nullable(),
cover_photo_url: z.string().nullable(),
- preferred_timezone: z.string().nullable(),
+ timezone: z.string().nullable(),
status: z.string(),
legal_name: z.string().nullable(),
registration_number: z.string().nullable(),
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb
index 7e51868e27..ea8ddeabf8 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb
@@ -13,11 +13,10 @@ module Spree
#
# The body picks the subclass against the registry (returns 422 with
# the configured error code on miss), strips `type`/`preferences`
- # from the permitted attrs, builds/assigns the rest, and routes
- # preference values through the typed `preferred_<name>=` setters
- # so booleans/decimals/etc. get coerced. Unknown preference keys
- # are silently dropped — the schema endpoint is the source of truth
- # for what's settable.
+ # from the permitted attrs, builds/assigns the rest, and writes the
+ # preferences after checking them against the subclass's schema —
+ # an unknown key or a value of the wrong type is a 422
+ # `invalid_preferences`.
module SubclassedResource
extend ActiveSupport::Concern
@@ -109,25 +108,10 @@ module Spree
)
end
+ # Validated against the subclass's schema before anything is written
+ # (see `Spree::Preferences::Preferable#assign_preferences`).
def apply_preferences(resource, preferences)
- password_keys = resource.password_preference_keys
-
- preferences.each do |key, value|
- pref_name = key.to_sym
- next unless resource.has_preference?(pref_name)
- # Internal preferences are Spree's to write — a secret a
- # provider issued, an id it gave back. They are absent from the
- # schema, so no form offers them; ignoring them here is what
- # stops a client writing one anyway and breaking the signature
- # check that depends on it.
- next if resource.preference_internal(pref_name)
- # Round-trip guard: clients fetching a record see masked
- # `:password` values. Submitting the mask back unchanged
- # must NOT overwrite the real secret with `••••cret`.
- next if password_keys.include?(pref_name) && Spree::Preferences::Masking.masked?(value)
-
- resource.set_preference(pref_name, value)
- end
+ resource.assign_preferences(preferences)
end
# Pulls `preferences` and `calculator` out of the permitted
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/validation_details.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/validation_details.rb
index 28738dc797..af777aa7ef 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/validation_details.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/validation_details.rb
@@ -26,7 +26,7 @@ module Spree
# nil code, which the dashboard reads as "render the message".
details = errors.details[attribute] || []
- result[attribute] = messages.each_with_index.map do |message, index|
+ result[wire_error_attribute(errors, attribute)] = messages.each_with_index.map do |message, index|
detail = details[index] || {}
code = detail[:error].is_a?(Symbol) ? detail[:error] : nil
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
index d956a9b54c..f8a3ba72eb 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
@@ -53,6 +53,7 @@ module Spree
# Validation errors
validation_error: 'validation_error',
+ invalid_preferences: 'invalid_preferences',
parameter_missing: 'parameter_missing',
parameter_invalid: 'parameter_invalid',
@@ -102,6 +103,7 @@ module Spree
rescue_from Spree::Core::GatewayError, with: :handle_gateway_error
rescue_from ActionController::ParameterMissing, with: :handle_parameter_missing
rescue_from ActiveRecord::RecordInvalid, with: :handle_record_invalid
+ rescue_from Spree::Preferences::InvalidPreferences, with: :handle_invalid_preferences
rescue_from ArgumentError, with: :handle_argument_error
rescue_from ActionDispatch::Http::Parameters::ParseError, with: :handle_parse_error
end
@@ -245,6 +247,17 @@ module Spree
render_validation_error(exception.record.errors)
end
+ # Each failing value is keyed by its JSON pointer into the request,
+ # e.g. `/preferences/channel_ids/1`.
+ def handle_invalid_preferences(exception)
+ render_error(
+ code: ERROR_CODES[:invalid_preferences],
+ message: exception.message,
+ status: :unprocessable_content,
+ details: exception.failures.group_by { |failure| failure[:pointer] }.transform_values { |failures| failures.pluck(:message) }
+ )
+ end
+
def handle_argument_error(exception)
Rails.error.report(exception, context: error_context, source: 'spree.api.v3')
render_error(
@@ -269,11 +282,21 @@ module Spree
# Format validation errors for details field
def format_validation_details(errors)
- errors.messages.transform_values do |messages|
- messages.map { |msg| msg }
+ errors.messages.to_h do |attribute, messages|
+ [wire_error_attribute(errors, attribute), messages.map { |msg| msg }]
end
end
+ # A setting the API reads and writes under its plain name reports its
+ # errors under that name too, never the `preferred_` one the model uses.
+ def wire_error_attribute(errors, attribute)
+ name = attribute.to_s.delete_prefix('preferred_')
+ return attribute if name == attribute.to_s
+
+ record_class = errors.objects.first&.base&.class
+ record_class.respond_to?(:exposed_preference?) && record_class.exposed_preference?(name) ? name.to_sym : attribute
+ end
+
# Infer error code from context
def infer_error_code(errors, status)
case status
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb b/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb
index 01e6f86b4a..00f8375e17 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb
@@ -30,6 +30,11 @@ module Spree
def resolve_prefixed_ids(hash)
hash.each_with_object({}.with_indifferent_access) do |(key, value), result|
result[key] = case
+ # Preferences declare which of their values are ids
+ # and decode only those, after checking them against
+ # their schema.
+ when key.to_s == 'preferences'
+ value
when key.to_s.end_with?('_id') && prefixed_id?(value)
decode_prefixed_id(value)
when key.to_s.end_with?('_ids') && value.is_a?(Array)
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 310a4b86f0..aba29705f4 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
@@ -61,8 +61,8 @@ module Spree
end
def permitted_params
- params.permit(*model_additional_permitted_attributes, :name, :code, :active, :default, :preferred_order_routing_strategy,
- :preferred_storefront_access, :preferred_guest_checkout,
+ params.permit(*model_additional_permitted_attributes, :name, :code, :active, :default, :order_routing_strategy,
+ :storefront_access, :guest_checkout,
:default_catalog_id,
stock_location_ids: [])
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/commission_rates_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/commission_rates_controller.rb
index 3eafcae34e..7eec4488e7 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/commission_rates_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/commission_rates_controller.rb
@@ -29,7 +29,7 @@ module Spree
type: klass.api_type,
name: klass.human_name,
description: klass.human_description,
- preference_schema: klass.serialized_preference_schema,
+ schema: klass.preference_json_schema,
# Config a rule takes beyond its preferences — a catalog-scale
# reference list lives in its own table, not the blob, and an
# editor has to know to render a picker for it.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_method_rules_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_method_rules_controller.rb
index 122b123899..238ef60379 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_method_rules_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_method_rules_controller.rb
@@ -15,7 +15,7 @@ module Spree
type: klass.api_type,
name: klass.human_name,
description: klass.human_description,
- preference_schema: klass.serialized_preference_schema,
+ schema: klass.preference_json_schema,
# Association-backed config (e.g. `product_ids`) a rule accepts
# beyond its preferences, so admin UIs can render the right
# editor without hardcoding rule types.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb
index d349530d7d..8edd2bb898 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb
@@ -86,11 +86,7 @@ module Spree
end
def assign_rule_preferences(rule)
- (permitted_params[:preferences] || {}).each do |key, value|
- next unless rule.has_preference?(key)
-
- rule.set_preference(key, value)
- end
+ rule.assign_preferences(permitted_params[:preferences]) if permitted_params[:preferences]
end
# Association-backed rule config (ExcludedProductsRule). Products are
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 b21272ea00..ca9932c352 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
@@ -15,7 +15,7 @@ module Spree
{
type: calculator_class.api_type,
name: calculator_class.description,
- preference_schema: calculator_class.respond_to?(:serialized_preference_schema) ? calculator_class.serialized_preference_schema : []
+ schema: calculator_class.preference_json_schema
}
end
@@ -129,9 +129,9 @@ module Spree
:pickup_point_provider, :rate_provider, :storefront_visible, :tracking_url,
:available_to_sellers,
:estimated_transit_business_days_min, :estimated_transit_business_days_max,
- :tax_category_id, :calculator_type, :markup_flat, :markup_percent,
+ :tax_category_id, :markup_flat, :markup_percent,
:delivery_profile_id, :delivery_origin_group_id, :delivery_zone_id,
- stock_location_ids: [], calculator_preferences: {},
+ stock_location_ids: [], calculator: [:type, { preferences: {} }],
rules: rule_attributes,
services: [:id, :carrier, :service, :label, :markup_flat, :markup_percent, :position]
)
@@ -158,7 +158,7 @@ module Spree
# Resolves prefixed-ID params to records; calculator handled separately.
def assignable_params
- attributes = permitted_params.except(:tax_category_id, :delivery_profile_id, :delivery_origin_group_id, :delivery_zone_id, :stock_location_ids, :calculator_type, :calculator_preferences)
+ attributes = permitted_params.except(:tax_category_id, :delivery_profile_id, :delivery_origin_group_id, :delivery_zone_id, :stock_location_ids, :calculator)
if params.key?(:tax_category_id)
attributes[:tax_category] = params[:tax_category_id].present? ? Spree::TaxCategory.accessible_by(current_ability, :show).find_by_prefix_id!(params[:tax_category_id]) : nil
end
@@ -202,15 +202,15 @@ module Spree
end
def assign_calculator(delivery_method)
- calculator_type = permitted_params[:calculator_type]
- preferences = permitted_params[:calculator_preferences]
+ calculator_type = permitted_params.dig(:calculator, :type)
+ preferences = permitted_params.dig(:calculator, :preferences)
if calculator_type.present? && delivery_method.calculator&.class&.api_type != calculator_type
selected_calculator_class = Spree::DeliveryMethod.calculators.find do |klass|
klass.api_type == calculator_type
end
unless selected_calculator_class
- delivery_method.errors.add(:calculator_type, :invalid)
+ delivery_method.errors.add(:calculator, :invalid)
return
end
@@ -228,11 +228,7 @@ module Spree
delivery_method.ensure_calculator
return if delivery_method.calculator.nil?
- preferences.each do |key, value|
- next unless delivery_method.calculator.has_preference?(key)
-
- delivery_method.calculator.set_preference(key, value)
- end
+ delivery_method.calculator.assign_preferences(preferences)
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 e58c0bf8ea..8c0ca22560 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
@@ -259,7 +259,7 @@ module Spree
end
def permitted_params
- params.permit(*model_additional_permitted_attributes, :type, :attachment, :preferred_delimiter, :results_url, :price_list_id)
+ params.permit(*model_additional_permitted_attributes, :type, :attachment, :delimiter, :results_url, :price_list_id)
end
# A price-list import writes into one list, named by its prefixed id.
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 6441ca51c3..8cc53d8605 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
@@ -11,14 +11,13 @@ module Spree
unknown_type_error: 'unknown_payment_method_type'
# Lists available payment provider subclasses for the create form.
- # Returns: { data: [{ type, label, description, preference_schema }] }.
- # The preference_schema array describes the provider-specific
+ # Returns: { data: [{ type, label, description, schema }] }.
+ # `schema` is the JSON Schema of the provider-specific
# configuration fields, so admin UIs can render a generic
# preferences form without hard-coding per-provider knowledge.
- # Filters out subclasses already installed in the current store —
- # mirrors the legacy admin's "available_payment_methods" helper, so
- # admins don't see (and accidentally double-install) the same
- # provider twice.
+ # Every provider, `installed` when the store already has one: the
+ # 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
@@ -26,11 +25,11 @@ module Spree
installed_shorthands = installed_class_names.filter_map do |name|
name.safe_constantize&.api_type
end
- available = model_class.subclasses_with_preference_schema.reject do |entry|
- installed_shorthands.include?(entry[:type])
+ entries = model_class.subclasses_with_preference_schema.map do |entry|
+ entry.merge(installed: installed_shorthands.include?(entry[:type]))
end
- render json: { data: available }
+ render json: { data: entries }
end
protected
@@ -45,11 +44,11 @@ module Spree
# Explicit allowlist per the v3 convention — flat params. `type` and
# `preferences` are added by `SubclassedResource` on top.
- # Deliberately NOT routed through `normalize_params`: gateway
- # `preferences` are opaque provider values, and prefixed-ID resolution
- # recurses into nested hashes — a Stripe `webhook_endpoint_id` like
- # `we_1MqJ8b...` matches the prefixed-ID shape and would be decoded to
- # an integer. `type` and `preferences` are added by `SubclassedResource`.
+ # Deliberately NOT routed through `normalize_params`: `metadata` holds
+ # opaque merchant values, and prefixed-ID resolution recurses into
+ # nested hashes — a value like `we_1MqJ8b...` matches the prefixed-ID
+ # shape and would be decoded to an integer. `preferences` decode their
+ # own ids from their schema.
def permitted_params
params.permit(
:name, :description, :active, :storefront_visible, :auto_capture, :capture_method, :position,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb
index d0c2c0d97c..000608e570 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb
@@ -28,7 +28,7 @@ module Spree
# GET /api/v3/admin/price_lists/price_rule_types
#
- # Returns `[{ type, label, description, preference_schema }]`
+ # Returns `[{ type, label, description, schema }]`
# for every registered subclass in `Spree.pricing.rules`. The
# SPA uses this to build the "Add rule" picker + render a
# generic preferences form per subclass. Rules themselves are
diff --git a/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb
index ed54f2228b..11b0370136 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb
@@ -38,7 +38,7 @@ module Spree
{
type: calc.api_type,
label: calc.respond_to?(:description) ? calc.description : calc.to_s.demodulize.titleize,
- preference_schema: calc.respond_to?(:serialized_preference_schema) ? calc.serialized_preference_schema : []
+ schema: calc.preference_json_schema
}
end.sort_by { |entry| entry[:label].to_s }
diff --git a/spree/api/app/controllers/spree/api/v3/admin/seller_requirements_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/seller_requirements_controller.rb
index f709caa82f..1d63fe7937 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/seller_requirements_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/seller_requirements_controller.rb
@@ -49,7 +49,7 @@ module Spree
# Config a kind takes beyond its preferences — a reference
# list gets its own picker, not a text box.
association_fields: association_fields_for(klass),
- preference_schema: klass.serialized_preference_schema
+ schema: klass.preference_json_schema
}
end
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 79b84c98b8..a89bdb070f 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
@@ -73,55 +73,51 @@ module Spree
def permitted_params
params.permit(
:name,
- :preferred_admin_locale,
- :preferred_timezone,
- :preferred_weight_unit,
- :preferred_unit_system,
- :preferred_storefront_access,
- :preferred_storefront_url,
- :preferred_guest_checkout,
- :preferred_always_include_confirm_step,
- :preferred_company_field_enabled,
- :preferred_address_requires_company,
- :preferred_address_requires_phone,
- :preferred_capture_method,
- # @deprecated Superseded by preferred_capture_method; the model
- # maps them onto it. Removed in 6.1.
- :preferred_auto_capture,
- :preferred_auto_capture_on_dispatch,
- :preferred_track_inventory_levels,
- :preferred_stock_reservations_enabled,
- :preferred_low_stock_threshold,
- :preferred_tax_using_ship_address,
- :preferred_track_price_history,
- :preferred_show_products_without_price,
- :preferred_disable_sku_validation,
- :preferred_order_routing_strategy,
- :preferred_pricing_provider,
- :preferred_inventory_provider,
- :preferred_pricing_provider_failure_policy,
- :preferred_inventory_provider_failure_policy,
- :preferred_payout_provider,
- :preferred_default_payouts_schedule_interval,
- :preferred_default_minimum_payout_amount,
- :preferred_auto_approve_sellers,
- :preferred_auto_approve_seller_products,
- :preferred_send_seller_transactional_emails,
- :preferred_default_commission_tax_rate,
- :preferred_document_number_format,
- :preferred_order_number_prefix,
- :preferred_order_number_suffix,
- :preferred_order_number_sequence_start,
+ :admin_locale,
+ :timezone,
+ :weight_unit,
+ :unit_system,
+ :storefront_access,
+ :storefront_url,
+ :guest_checkout,
+ :always_include_confirm_step,
+ :company_field_enabled,
+ :address_requires_company,
+ :address_requires_phone,
+ :capture_method,
+ :track_inventory_levels,
+ :stock_reservations_enabled,
+ :low_stock_threshold,
+ :tax_using_ship_address,
+ :track_price_history,
+ :show_products_without_price,
+ :disable_sku_validation,
+ :order_routing_strategy,
+ :pricing_provider,
+ :inventory_provider,
+ :pricing_provider_failure_policy,
+ :inventory_provider_failure_policy,
+ :payout_provider,
+ :default_payouts_schedule_interval,
+ :default_minimum_payout_amount,
+ :auto_approve_sellers,
+ :auto_approve_seller_products,
+ :send_seller_transactional_emails,
+ :default_commission_tax_rate,
+ :document_number_format,
+ :order_number_prefix,
+ :order_number_suffix,
+ :order_number_sequence_start,
:mail_from_address,
:customer_support_email,
:new_order_notifications_email,
- :preferred_send_consumer_transactional_emails,
- :preferred_email_accent_color,
- :preferred_email_background_color,
- :preferred_email_card_color,
- :preferred_email_text_color,
- :preferred_email_heading_color,
- :preferred_email_font,
+ :send_consumer_transactional_emails,
+ :email_accent_color,
+ :email_background_color,
+ :email_card_color,
+ :email_text_color,
+ :email_heading_color,
+ :email_font,
:mailer_logo
)
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/delivery_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/delivery_methods_controller.rb
index 841197e00b..f92cf74641 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
@@ -29,7 +29,7 @@ module Spree
{
type: calculator_class.api_type,
name: calculator_class.description,
- preference_schema: calculator_class.respond_to?(:serialized_preference_schema) ? calculator_class.serialized_preference_schema : []
+ schema: calculator_class.preference_json_schema
}
end
@@ -48,7 +48,7 @@ module Spree
type: klass.api_type,
name: klass.human_name,
description: klass.human_description,
- preference_schema: klass.serialized_preference_schema
+ schema: klass.preference_json_schema
}
end
@@ -125,9 +125,8 @@ module Spree
*model_additional_permitted_attributes,
:name, :admin_name, :code, :storefront_visible, :tracking_url,
:estimated_transit_business_days_min, :estimated_transit_business_days_max,
- :calculator_type,
:delivery_profile_id, :delivery_zone_id,
- calculator_preferences: {},
+ calculator: [:type, { preferences: {} }],
rules: [:id, :type, :active, { preferences: {} }, *subclassed_rule_attributes]
)
end
@@ -175,7 +174,7 @@ module Spree
# resolves its own pickers.
def assignable_params
attributes = permitted_params.except(
- :delivery_profile_id, :delivery_zone_id, :calculator_type, :calculator_preferences, :rules
+ :delivery_profile_id, :delivery_zone_id, :calculator, :rules
)
if params.key?(:delivery_profile_id)
@@ -220,15 +219,15 @@ module Spree
end
def assign_calculator(delivery_method)
- calculator_type = permitted_params[:calculator_type]
- preferences = permitted_params[:calculator_preferences]
+ calculator_type = permitted_params.dig(:calculator, :type)
+ preferences = permitted_params.dig(:calculator, :preferences)
if calculator_type.present? && delivery_method.calculator&.class&.api_type != calculator_type
registered = Spree::DeliveryMethod.calculators.find do |klass|
klass.api_type == calculator_type
end
unless registered
- delivery_method.errors.add(:calculator_type, :invalid)
+ delivery_method.errors.add(:calculator, :invalid)
return
end
@@ -252,11 +251,7 @@ module Spree
delivery_method.ensure_calculator
return if delivery_method.calculator.nil?
- preferences.each do |key, value|
- next unless delivery_method.calculator.has_preference?(key)
-
- delivery_method.calculator.set_preference(key, value)
- end
+ delivery_method.calculator.assign_preferences(preferences)
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 99088d5edc..d363e4f811 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
@@ -248,7 +248,7 @@ module Spree
end
def permitted_params
- params.permit(*model_additional_permitted_attributes, :type, :attachment, :preferred_delimiter, :results_url)
+ params.permit(*model_additional_permitted_attributes, :type, :attachment, :delimiter, :results_url)
end
# The registered Import subclass matching `name`, or nil.
diff --git a/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb
index e461ff7d98..911fb7310f 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb
@@ -4,17 +4,15 @@ module Spree
module Admin
class ChannelSerializer < V3::ChannelSerializer
typelize store_id: :string,
- preferred_order_routing_strategy: [:string, nullable: true, comment: 'Order routing strategy; null inherits the store setting. Built-in: rules. Extensions may register more.'],
- preferred_storefront_access: [:string, nullable: true],
- preferred_guest_checkout: [:boolean, nullable: true],
+ order_routing_strategy: [:string, nullable: true, comment: 'Order routing strategy; null inherits the store setting. Built-in: rules. Extensions may register more.'],
stock_location_ids: [:string, multi: true],
default_catalog_id: [:string, nullable: true]
- attributes :preferred_storefront_access,
- :preferred_guest_checkout,
- created_at: :iso8601, updated_at: :iso8601
+ attributes created_at: :iso8601, updated_at: :iso8601
- api_type_attributes :preferred_order_routing_strategy
+ preference_attributes Spree::Channel, :storefront_access, :guest_checkout
+
+ api_type_attributes :order_routing_strategy
# Fulfillment-origin allowlist; empty means every store location
# serves this channel.
diff --git a/spree/api/app/serializers/spree/api/v3/admin/commission_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/commission_rule_serializer.rb
index f8a58635b3..24ce3a66ce 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/commission_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/commission_rule_serializer.rb
@@ -13,7 +13,6 @@ module Spree
typelize type: [:string, comment: 'Rule type. Built-in: seller_rule, category_rule, product_rule, item_total_rule. Extensions may register more.'],
commission_rate_id: :string,
preferences: 'Record<string, unknown>',
- preference_schema: 'Array<{ key: string; type: string; default: unknown }>',
product_ids: 'Array<string> | null',
seller_ids: 'Array<string> | null',
category_ids: 'Array<string> | null'
@@ -27,7 +26,6 @@ module Spree
prefixed_id_attributes :commission_rate
attribute :preferences, &:serialized_preferences
- attribute :preference_schema, &:serialized_preference_schema
# Reference lists are returned as prefixed IDs to match the rest of
# the API. Product ids are read through a join table; seller and
diff --git a/spree/api/app/serializers/spree/api/v3/admin/delivery_method_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/delivery_method_rule_serializer.rb
index 19ec1aee41..ad9389b558 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/delivery_method_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/delivery_method_rule_serializer.rb
@@ -6,7 +6,6 @@ module Spree
typelize type: [:string, comment: 'Rule type. Built-in: item_total_rule, weight_rule, excluded_products_rule, channel_rule, volume_rule, company_rule. Extensions may register more.'],
active: :boolean,
preferences: 'Record<string, unknown>',
- preference_schema: "Array<{ key: string; type: string; default: unknown; choices?: string[] }>",
product_ids: [:string, multi: true]
attributes :active, created_at: :iso8601, updated_at: :iso8601
@@ -18,7 +17,6 @@ module Spree
end
attribute :preferences, &:serialized_preferences
- attribute :preference_schema, &:serialized_preference_schema
# Association-backed config (ExcludedProductsRule); empty for
# preference-only rules. Same name read and written.
diff --git a/spree/api/app/serializers/spree/api/v3/admin/delivery_method_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/delivery_method_serializer.rb
index 4bded5c45d..4c9fa10722 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/delivery_method_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/delivery_method_serializer.rb
@@ -13,8 +13,7 @@ module Spree
delivery_origin_group_id: [:string, nullable: true],
delivery_zone_id: [:string, nullable: true],
stock_location_ids: [:string, multi: true],
- calculator_type: [:string, nullable: true],
- calculator_preferences: ['Record<string, unknown>', nullable: true],
+ calculator: '{ type: string; preferences: Record<string, unknown> } | null',
markup_flat: [:string, nullable: true],
markup_percent: [:string, nullable: true],
available_to_sellers: :boolean,
@@ -56,12 +55,9 @@ module Spree
api_type_attributes :fulfillment_provider, :pickup_point_provider, :rate_provider
- attribute :calculator_type do |record|
- record.calculator&.class&.api_type
- end
-
- attribute :calculator_preferences do |record|
- record.calculator.respond_to?(:serialized_preferences) ? record.calculator.serialized_preferences : record.calculator&.preferences
+ attribute :calculator do |record|
+ calculator = record.calculator
+ { type: calculator.class.api_type, preferences: calculator.serialized_preferences } if calculator
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/import_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/import_serializer.rb
index fb4a490d8a..88e0ca2bb7 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/import_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/import_serializer.rb
@@ -9,7 +9,7 @@ module Spree
completed_rows_count: :number,
failed_rows_count: :number,
processing_errors: [:string, nullable: true],
- preferred_delimiter: :string,
+ delimiter: :string,
schema_fields: 'Array<{ name: string; label: string; required: boolean }>',
csv_headers: [:string, multi: true],
sample_row: 'Record<string, string | null>',
@@ -18,7 +18,7 @@ module Spree
original_file_url: [:string, nullable: true],
price_list_id: [:string, nullable: true]
- attributes :processing_errors, :preferred_delimiter
+ attributes :processing_errors, :delimiter
# The list a price-list import writes into; nil for every other type.
attribute :price_list_id do |import|
diff --git a/spree/api/app/serializers/spree/api/v3/admin/integration_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/integration_serializer.rb
index 63765a0159..88e7fa6f35 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/integration_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/integration_serializer.rb
@@ -9,8 +9,7 @@ module Spree
name: :string,
group: [:string, nullable: true],
active: :boolean,
- preferences: 'Record<string, unknown>',
- preference_schema: "Array<{ key: string; type: string; default: unknown; choices?: string[] }>"
+ preferences: 'Record<string, unknown>'
attributes :name, :active,
created_at: :iso8601, updated_at: :iso8601
@@ -24,7 +23,6 @@ module Spree
end
attribute :preferences, &:serialized_preferences
- attribute :preference_schema, &:serialized_preference_schema
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/order_routing_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/order_routing_rule_serializer.rb
index 3db676f3c0..4b7d0979cb 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/order_routing_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/order_routing_rule_serializer.rb
@@ -12,8 +12,7 @@ module Spree
channel_id: :string,
position: :number,
active: :boolean,
- preferences: 'Record<string, unknown>',
- preference_schema: "Array<{ key: string; type: string; default: unknown; choices?: string[] }>"
+ preferences: 'Record<string, unknown>'
attributes :position, :active
attributes created_at: :iso8601, updated_at: :iso8601
@@ -25,7 +24,6 @@ module Spree
prefixed_id_attributes :channel
attribute :preferences, &:serialized_preferences
- attribute :preference_schema, &:serialized_preference_schema
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb
index 345f1dea80..262df961b7 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb
@@ -11,7 +11,6 @@ module Spree
position: :number,
metadata: 'Record<string, unknown>',
preferences: 'Record<string, unknown>',
- preference_schema: "Array<{ key: string; type: string; default: unknown; choices?: string[] }>",
logo_url: [:string, nullable: true],
docs_url: [:string, nullable: true],
third_party: :boolean
@@ -24,7 +23,6 @@ module Spree
created_at: :iso8601, updated_at: :iso8601
attribute :preferences, &:serialized_preferences
- attribute :preference_schema, &:serialized_preference_schema
attribute(:logo_url) { |payment_method| payment_method.class.logo_url }
attribute(:docs_url) { |payment_method| payment_method.class.docs_url }
attribute(:third_party) { |payment_method| payment_method.class.third_party? }
diff --git a/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb
index 7086089a76..190f4455ee 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb
@@ -8,8 +8,7 @@ module Spree
class PriceRuleSerializer < V3::BaseSerializer
typelize type: [:string, comment: 'Rule type. Built-in: channel_rule, customer_group_rule, market_rule, user_rule, volume_rule, zone_rule. Extensions may register more.'],
price_list_id: :string,
- preferences: 'Record<string, unknown>',
- preference_schema: 'Array<{ key: string; type: string; default: unknown }>'
+ preferences: 'Record<string, unknown>'
attributes created_at: :iso8601, updated_at: :iso8601
@@ -20,7 +19,6 @@ module Spree
prefixed_id_attributes :price_list
attribute :preferences, &:serialized_preferences
- attribute :preference_schema, &:serialized_preference_schema
# Embeds skip rules that don't carry the association (e.g.
# VolumeRule has no markets/customers — the keys are omitted).
diff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb
index 3495e86341..07f92dc84f 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb
@@ -7,13 +7,13 @@ module Spree
# Serializes Spree::PromotionAction (and its STI subclasses) for the
# admin promotion editor. The shape is intentionally generic so a
# single component can render any subclass — `preferences` is the
- # current value hash, `preference_schema` describes its fields.
+ # current value hash, described by the `schema` its type's entry in
+ # `/promotion_actions/types` carries.
class PromotionActionSerializer < BaseSerializer
typelize type: [:string, comment: 'Action type. Built-in: create_adjustment, create_item_adjustments, create_line_items, free_shipping. Extensions may register more.'],
promotion_id: :string,
preferences: 'Record<string, unknown>',
- preference_schema: "Array<{ key: string; type: string; default: unknown; choices?: string[] }>",
- calculator: "{ type: string; preferences: Record<string, unknown>; preference_schema: Array<{ key: string; type: string; default: unknown }> } | null",
+ calculator: '{ type: string; preferences: Record<string, unknown> } | null',
line_items: 'Array<{ variant_id: string; quantity: number }> | null'
attributes created_at: :iso8601, updated_at: :iso8601
@@ -25,7 +25,6 @@ module Spree
prefixed_id_attributes :promotion
attribute :preferences, &:serialized_preferences
- attribute :preference_schema, &:serialized_preference_schema
# Calculator is exposed as a nested object so the SPA can render
# the calculator picker + its own preference fields. Null for
@@ -38,8 +37,7 @@ module Spree
calc = action.calculator
{
type: calc.class.api_type,
- preferences: calc.serialized_preferences,
- preference_schema: calc.serialized_preference_schema
+ preferences: calc.serialized_preferences
}
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb
index b03392c8ae..855be7d2c9 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb
@@ -11,7 +11,6 @@ module Spree
typelize type: [:string, comment: 'Rule type. Built-in: currency, country, channel, market, item_total, product, customer, customer_group, first_order, customer_logged_in, one_use_per_user, category, option_value. Extensions may register more.'],
promotion_id: :string,
preferences: 'Record<string, unknown>',
- preference_schema: "Array<{ key: string; type: string; default: unknown; choices?: string[] }>",
product_ids: 'Array<string> | null',
category_ids: 'Array<string> | null',
customer_ids: 'Array<string> | null',
@@ -26,7 +25,6 @@ module Spree
prefixed_id_attributes :promotion
attribute :preferences, &:serialized_preferences
- attribute :preference_schema, &:serialized_preference_schema
# Association IDs for rules that wire products/taxons/users through
# join tables. Returned as prefixed IDs to match the rest of the
diff --git a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
index 7096ff7aef..23426dae33 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
@@ -4,7 +4,6 @@ module Spree
module Admin
class StoreSerializer < V3::BaseSerializer
typelize name: :string, url: :string, code: :string, api_url: :string,
- preferred_storefront_url: [:string, nullable: true],
default_currency: :string, default_locale: :string,
default_country_code: [:string, nullable: true],
supported_currencies: [:string, multi: true],
@@ -15,108 +14,41 @@ module Spree
mail_from_address: [:string, nullable: true],
customer_support_email: [:string, nullable: true],
new_order_notifications_email: [:string, nullable: true],
- preferred_send_consumer_transactional_emails: :boolean,
- preferred_email_accent_color: [:string, nullable: true],
- preferred_email_background_color: [:string, nullable: true],
- preferred_email_card_color: [:string, nullable: true],
- preferred_email_text_color: [:string, nullable: true],
- preferred_email_heading_color: [:string, nullable: true],
- preferred_email_font: [:string, nullable: true, enum: Spree::Emails::Branding::FONTS.keys],
- preferred_admin_locale: [:string, nullable: true],
- preferred_timezone: :string,
- preferred_weight_unit: [:string, enum: Spree::Variant::WEIGHT_UNITS],
- preferred_unit_system: :string,
- preferred_storefront_access: :string,
- preferred_guest_checkout: :boolean,
- preferred_always_include_confirm_step: :boolean,
- preferred_company_field_enabled: :boolean,
- preferred_address_requires_company: :boolean,
- preferred_address_requires_phone: :boolean,
- preferred_capture_method: :string,
- preferred_track_inventory_levels: :boolean,
- preferred_stock_reservations_enabled: :boolean,
- preferred_low_stock_threshold: :number,
- preferred_tax_using_ship_address: :boolean,
- preferred_track_price_history: :boolean,
- preferred_show_products_without_price: :boolean,
- preferred_disable_sku_validation: :boolean,
- preferred_order_routing_strategy: [:string, comment: 'Order routing strategy. Built-in: rules. Extensions may register more.'],
- preferred_pricing_provider: :string,
- preferred_inventory_provider: :string,
- preferred_pricing_provider_failure_policy: :string,
- preferred_inventory_provider_failure_policy: :string,
- preferred_payout_provider: [:string, nullable: true, comment: 'Payout provider; null uses the installation default. Built-in: system. Provider gems register more (e.g. stripe).'],
- preferred_default_payouts_schedule_interval: :string,
- preferred_default_minimum_payout_amount: [:string, nullable: true],
- preferred_auto_approve_sellers: :boolean,
- preferred_auto_approve_seller_products: :boolean,
- preferred_send_seller_transactional_emails: :boolean,
- preferred_default_commission_tax_rate: [:string, nullable: true],
- preferred_document_number_format: :string,
- preferred_order_number_prefix: :string,
- preferred_order_number_suffix: :string,
- preferred_order_number_sequence_start: :number,
+ order_routing_strategy: [:string, comment: 'Order routing strategy. Built-in: rules. Extensions may register more.'],
+ payout_provider: [:string, nullable: true, comment: 'Payout provider; null uses the installation default. Built-in: system. Provider gems register more (e.g. stripe).'],
order_number_sequence_started: :boolean,
- preferred_limit_digital_download_count: :boolean,
- preferred_digital_asset_authorized_clicks: :number,
- preferred_limit_digital_download_days: :boolean,
- preferred_digital_asset_authorized_days: :number,
metadata: 'Record<string, unknown>'
attributes :metadata,
:name,
:code,
- :preferred_storefront_url,
:default_currency,
:default_locale,
:default_country_code,
:mail_from_address,
:customer_support_email,
:new_order_notifications_email,
- :preferred_send_consumer_transactional_emails,
- :preferred_email_accent_color,
- :preferred_email_background_color,
- :preferred_email_card_color,
- :preferred_email_text_color,
- :preferred_email_heading_color,
- :preferred_email_font,
- :preferred_admin_locale,
- :preferred_timezone,
- :preferred_weight_unit,
- :preferred_unit_system,
- :preferred_storefront_access,
- :preferred_guest_checkout,
- :preferred_always_include_confirm_step,
- :preferred_company_field_enabled,
- :preferred_address_requires_company,
- :preferred_address_requires_phone,
- :preferred_capture_method,
- :preferred_track_inventory_levels,
- :preferred_stock_reservations_enabled,
- :preferred_low_stock_threshold,
- :preferred_tax_using_ship_address,
- :preferred_track_price_history,
- :preferred_show_products_without_price,
- :preferred_disable_sku_validation,
- :preferred_pricing_provider,
- :preferred_inventory_provider,
- :preferred_pricing_provider_failure_policy,
- :preferred_inventory_provider_failure_policy,
- :preferred_default_payouts_schedule_interval,
- :preferred_auto_approve_sellers,
- :preferred_auto_approve_seller_products,
- :preferred_send_seller_transactional_emails,
- :preferred_document_number_format,
- :preferred_order_number_prefix,
- :preferred_order_number_suffix,
- :preferred_order_number_sequence_start,
- :preferred_limit_digital_download_count,
- :preferred_digital_asset_authorized_clicks,
- :preferred_limit_digital_download_days,
- :preferred_digital_asset_authorized_days,
created_at: :iso8601, updated_at: :iso8601
- api_type_attributes :preferred_order_routing_strategy, :preferred_payout_provider
+ api_type_attributes :order_routing_strategy, :payout_provider
+
+ preference_attributes Spree::Store,
+ :storefront_url, :send_consumer_transactional_emails, :email_accent_color,
+ :email_background_color, :email_card_color, :email_text_color, :email_heading_color,
+ :email_font, :admin_locale, :timezone, :weight_unit, :unit_system, :storefront_access,
+ :guest_checkout, :always_include_confirm_step, :company_field_enabled,
+ :address_requires_company, :address_requires_phone, :capture_method,
+ :track_inventory_levels, :stock_reservations_enabled, :low_stock_threshold,
+ :tax_using_ship_address, :track_price_history, :show_products_without_price,
+ :disable_sku_validation, :pricing_provider, :inventory_provider,
+ :pricing_provider_failure_policy, :inventory_provider_failure_policy,
+ :default_payouts_schedule_interval,
+ :auto_approve_sellers, :auto_approve_seller_products,
+ :send_seller_transactional_emails,
+ :document_number_format, :order_number_prefix, :order_number_suffix,
+ :order_number_sequence_start, :limit_digital_download_count,
+ :digital_asset_authorized_clicks, :limit_digital_download_days,
+ :digital_asset_authorized_days
# Once the counter has issued a number the starting value no longer
# applies, so the settings page can say that instead of accepting a
@@ -125,11 +57,13 @@ module Spree
Spree::NumberSequence.started?(store: store)
end
- attribute :preferred_default_minimum_payout_amount do |store|
+ typelize default_minimum_payout_amount: [:string, nullable: true]
+
+ attribute :default_minimum_payout_amount do |store|
Spree::Money::Rounding.format(store.preferred_default_minimum_payout_amount, store.default_currency, unit_price: true)
end
- rate_attributes :preferred_default_commission_tax_rate
+ rate_attributes :default_commission_tax_rate
attribute :url, &:storefront_url
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 e0142a4b1d..aed3c7af70 100644
--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
@@ -87,6 +87,35 @@ module Spree
end
end
+ # 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.
+ #
+ # preference_attributes Spree::Store, :guest_checkout, :timezone
+ def self.preference_attributes(model, *names)
+ definitions = model.preference_definitions
+ 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.is_a?(BigDecimal) ? value.to_s('F') : value
+ end
+ end
+ end
+
+ TYPELIZER_TYPES = { 'string' => :string, 'integer' => :number, 'number' => :number, 'boolean' => :boolean }.freeze
+ private_constant :TYPELIZER_TYPES
+
+ def self.preference_type_hint(schema)
+ types = Array(schema['type'])
+ hint = TYPELIZER_TYPES.fetch((types - ['null']).first, :unknown)
+ options = {}
+ options[:nullable] = true if types.include?('null')
+ options[:enum] = schema['enum'].compact if schema['enum']
+ options.empty? ? hint : [hint, options]
+ end
+ private_class_method :preference_type_hint
+
# Declares the wire form of an `acted_by` association: the actor's
# prefixed id, the kind of actor it is, and the expansion. Both
# halves read off the columns, so naming an actor costs no query and
diff --git a/spree/api/app/serializers/spree/api/v3/seller/delivery_method_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/delivery_method_rule_serializer.rb
index 4e7cb6a801..5f19fc4d8a 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/delivery_method_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/delivery_method_rule_serializer.rb
@@ -12,8 +12,7 @@ module Spree
class DeliveryMethodRuleSerializer < BaseSerializer
typelize type: [:string, comment: 'Rule type. Built-in: item_total_rule, weight_rule, excluded_products_rule, channel_rule, volume_rule, company_rule. Extensions may register more.'],
active: :boolean,
- preferences: 'Record<string, unknown>',
- preference_schema: "Array<{ key: string; type: string; default: unknown; choices?: string[] }>"
+ preferences: 'Record<string, unknown>'
attributes :active
@@ -24,7 +23,6 @@ module Spree
end
attribute :preferences, &:serialized_preferences
- attribute :preference_schema, &:serialized_preference_schema
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/delivery_method_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/delivery_method_serializer.rb
index 56bf8b3ee1..1a145e190f 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/delivery_method_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/delivery_method_serializer.rb
@@ -22,8 +22,7 @@ module Spree
editable: :boolean,
delivery_profile_id: [:string, nullable: true],
delivery_zone_id: [:string, nullable: true],
- calculator_type: [:string, nullable: true],
- calculator_preferences: ['Record<string, unknown>', nullable: true]
+ calculator: '{ type: string; preferences: Record<string, unknown> } | null'
attributes :admin_name, :storefront_visible, :tracking_url,
created_at: :iso8601, updated_at: :iso8601
@@ -39,12 +38,9 @@ module Spree
prefixed_id_attributes :delivery_profile, :delivery_zone
- attribute :calculator_type do |record|
- record.calculator&.class&.api_type
- end
-
- attribute :calculator_preferences do |record|
- record.calculator.respond_to?(:serialized_preferences) ? record.calculator.serialized_preferences : record.calculator&.preferences
+ attribute :calculator do |record|
+ calculator = record.calculator
+ { type: calculator.class.api_type, preferences: calculator.serialized_preferences } if calculator
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/import_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/import_serializer.rb
index 556da633ac..a829789d63 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/import_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/import_serializer.rb
@@ -15,7 +15,7 @@ module Spree
typelize completed_rows_count: :number,
failed_rows_count: :number,
processing_errors: [:string, nullable: true],
- preferred_delimiter: :string,
+ delimiter: :string,
schema_fields: 'Array<{ name: string; label: string; required: boolean }>',
csv_headers: [:string, multi: true],
sample_row: 'Record<string, string | null>',
@@ -23,7 +23,7 @@ module Spree
original_byte_size: [:number, nullable: true],
original_file_url: [:string, nullable: true]
- attributes :processing_errors, :preferred_delimiter
+ attributes :processing_errors, :delimiter
# The file the seller uploaded. `original_file_url` is this branch's
# own streaming endpoint (JWT-authenticated), not a signed
diff --git a/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb
index 9d36ec6301..51f039413d 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb
@@ -17,9 +17,9 @@ module Spree
products_count: :number,
default_currency: :string,
supported_currencies: [:string, multi: true],
- preferred_timezone: [:string, nullable: true]
+ timezone: [:string, nullable: true]
- attributes :preferred_timezone,
+ attributes :timezone,
:status, :legal_name, :registration_number,
:contact_email, :billing_email,
:tax_remittance, :payouts_schedule_interval,
diff --git a/spree/api/lib/spree/api/openapi/schema_helper.rb b/spree/api/lib/spree/api/openapi/schema_helper.rb
index f1bc1394cd..b029544095 100644
--- a/spree/api/lib/spree/api/openapi/schema_helper.rb
+++ b/spree/api/lib/spree/api/openapi/schema_helper.rb
@@ -1,5 +1,7 @@
# frozen_string_literal: true
+require 'spree/api/preference_families'
+
module Spree
module Api
module OpenAPI
@@ -162,26 +164,31 @@ module Spree
},
required: %w[id name code]
},
- PreferenceField: {
+ PreferenceSchema: {
type: :object,
- description: 'A single configurable preference on a payment method, promotion rule/action, or calculator. The frontend uses `type` + `default` to render a sensible input.',
- properties: {
- key: { type: :string, example: 'amount_min' },
- type: { type: :string, example: 'decimal', description: 'string | text | password | integer | decimal | boolean | array | hash' },
- default: { description: 'Default value (any JSON type), null when there is no default', nullable: true }
- },
- required: %w[key type]
+ description: 'The JSON Schema (draft 2020-12) of a type\'s `preferences`: one property per setting, ' \
+ 'with `format` (`money`, `currency`, `iso-country`, `prefixed-id`, …), `enum`, `default`, ' \
+ '`x-spree-secret` for a secret and `x-spree-prefix` for an id list. Unknown keys are refused.',
+ additionalProperties: true,
+ example: { type: 'object', properties: { amount: { type: 'string', format: 'money', default: '0.0' } }, additionalProperties: false }
},
PromotionActionCalculator: {
type: :object,
description: "The action's nested calculator (when the action carries one — null for actions like `free_shipping`)",
properties: {
type: { type: :string, example: 'flat_rate', description: 'Wire shorthand for the calculator subclass' },
- label: { type: :string, example: 'Flat Rate' },
- preferences: { type: :object, additionalProperties: true },
- preference_schema: { type: :array, items: { '$ref' => '#/components/schemas/PreferenceField' } }
+ preferences: { '$ref' => '#/components/schemas/PromotionCalculatorPreferences' }
},
- required: %w[type label preferences preference_schema]
+ required: %w[type preferences]
+ },
+ DeliveryMethodCalculator: {
+ type: :object,
+ description: 'How the delivery method prices a shipment',
+ properties: {
+ type: { type: :string, example: 'flat_rate', description: 'Wire shorthand for the calculator subclass' },
+ preferences: { '$ref' => '#/components/schemas/DeliveryCalculatorPreferences' }
+ },
+ required: %w[type preferences]
},
PromotionActionLineItem: {
type: :object,
@@ -243,7 +250,7 @@ module Spree
Rails.logger.warn "Failed to load Typelizer admin schemas: #{e.message}"
end
- schemas
+ add_preference_schemas(schemas, Spree::Api::PreferenceFamilies::REGISTRIES.keys)
end
# Get all seller schemas (Typelizer + common).
@@ -280,7 +287,7 @@ module Spree
Rails.logger.warn "Failed to load Typelizer seller schemas: #{e.message}"
end
- schemas
+ add_preference_schemas(schemas, Spree::Api::PreferenceFamilies::SELLER)
end
# Hand-written shapes the seller branch answers with that no serializer
@@ -420,7 +427,6 @@ module Spree
patch_admin_user_schema(schemas)
patch_promotion_rule_schema(schemas)
patch_promotion_action_schema(schemas)
- patch_price_rule_schema(schemas)
patch_import_schema(schemas)
schemas
end
@@ -504,22 +510,12 @@ module Spree
return unless rule
patch_id_arrays(rule, %w[product_ids category_ids customer_ids option_value_ids])
- patch_preference_schema(rule)
- end
-
- def patch_price_rule_schema(schemas)
- rule = schemas['PriceRule'] || schemas[:PriceRule]
- return unless rule
-
- patch_preference_schema(rule)
end
def patch_promotion_action_schema(schemas)
action = schemas['PromotionAction'] || schemas[:PromotionAction]
return unless action
- patch_preference_schema(action)
-
props = action[:properties]
return unless props
@@ -557,17 +553,69 @@ module Spree
end
end
- def patch_preference_schema(schema)
- props = schema[:properties]
- return unless props
+ # One component per subtype Spree ships (`PromotionRuleItemTotalPreferences`)
+ # and one per family (`PromotionRulePreferences`) that the family's
+ # resource points its `preferences` at. A type an extension registers
+ # matches the final plain object; its shape is the `schema` in the
+ # family's `/types` response.
+ #
+ # @param schemas [Hash] components, changed in place
+ # @param families [Array<String>]
+ # @return [Hash] the components
+ def add_preference_schemas(schemas, families)
+ Spree::Api::PreferenceFamilies.schemas(families).each do |family, members|
+ refs = members.to_h do |type, schema|
+ name = Spree::Api::PreferenceFamilies.member_name(family, type)
+ schemas[name] = openapi_schema(schema)
+ [type, "#/components/schemas/#{name}"]
+ end
- key = props.key?('preference_schema') ? 'preference_schema' : :preference_schema
- return unless props[key]
+ schemas["#{family}Preferences"] = {
+ description: "Settings of a #{family.titleize.downcase}, shaped by its `type` (see `x-spree-preferences-by-type`). " \
+ 'A type an extension registers is a plain object, described by the `schema` its `/types` entry carries.',
+ anyOf: refs.values.map { |ref| { '$ref' => ref } } + [{ type: :object, additionalProperties: true }],
+ 'x-spree-preferences-by-type' => refs
+ }
- props[key] = {
- type: :array,
- items: { '$ref' => '#/components/schemas/PreferenceField' }
- }
+ resource = schemas[family] || schemas[family.to_sym]
+ props = resource&.dig(:properties)
+ key = props&.key?('preferences') ? 'preferences' : :preferences
+ props[key] = { '$ref' => "#/components/schemas/#{family}Preferences" } if props&.key?(key)
+ end
+
+ patch_delivery_method_calculator(schemas)
+ schemas
+ end
+
+ # The generated JSON Schema is draft 2020-12; OpenAPI 3.0 spells a
+ # nullable type as `nullable: true` and has no `propertyNames`.
+ def openapi_schema(schema)
+ case schema
+ when Hash
+ converted = schema.each_with_object({}) do |(key, value), result|
+ next if key == 'propertyNames'
+
+ result[key] = %w[enum default required].include?(key) ? value : openapi_schema(value)
+ end
+ if schema['type'].is_a?(Array)
+ converted['type'] = (schema['type'] - ['null']).first
+ converted['nullable'] = true if schema['type'].include?('null')
+ end
+ converted['enum'] = converted['enum'].compact if converted['enum']
+ converted['x-spree-property-names'] = openapi_schema(schema['propertyNames']) if schema['propertyNames']
+ converted
+ when Array then schema.map { |item| openapi_schema(item) }
+ else schema
+ end
+ end
+
+ def patch_delivery_method_calculator(schemas)
+ method = schemas['DeliveryMethod'] || schemas[:DeliveryMethod]
+ props = method&.dig(:properties)
+ return unless props
+
+ key = props.key?('calculator') ? 'calculator' : :calculator
+ props[key] = { allOf: [{ '$ref' => '#/components/schemas/DeliveryMethodCalculator' }], nullable: true } if props[key]
end
# Typelizer cannot represent Array<{...}> inline object types in OpenAPI,
diff --git a/spree/api/lib/spree/api/preference_families.rb b/spree/api/lib/spree/api/preference_families.rb
new file mode 100644
index 0000000000..52cddf1c26
--- /dev/null
+++ b/spree/api/lib/spree/api/preference_families.rb
@@ -0,0 +1,46 @@
+module Spree
+ module Api
+ # The configurable families whose subtypes each declare their own
+ # `preferences`: the subtypes Spree ships, keyed by their wire `type`, with
+ # the JSON Schema of each one's preferences. The OpenAPI components and the
+ # SDK's preference types are both generated from it, so the two cannot
+ # describe different shapes.
+ module PreferenceFamilies
+ # Family name => its registry. The name is the resource the family's
+ # rows are serialized as, or, for calculators, the calculator's role.
+ REGISTRIES = {
+ 'CommissionRule' => -> { Spree.commission_rules },
+ 'DeliveryCalculator' => -> { Spree::DeliveryMethod.calculators },
+ 'DeliveryMethodRule' => -> { Spree.delivery_method_rules },
+ 'Integration' => -> { Spree::Integration.registered_classes },
+ 'OrderRoutingRule' => -> { Spree.order_routing.rules },
+ 'PaymentMethod' => -> { Spree::PaymentMethod.providers },
+ 'PriceRule' => -> { Array(Spree.pricing&.rules) },
+ 'PromotionCalculator' => lambda {
+ Spree.calculators.promotion_actions_create_adjustments + Spree.calculators.promotion_actions_create_item_adjustments
+ },
+ 'PromotionRule' => -> { Spree.promotions.rules },
+ 'SellerRequirement' => -> { Spree.seller_requirements }
+ }.freeze
+
+ # The families a seller reads and writes.
+ SELLER = %w[DeliveryCalculator DeliveryMethodRule].freeze
+
+ # @param names [Array<String>] family names, every family by default
+ # @return [Hash{String => Hash{String => Hash}}] family => { type => JSON Schema of its preferences }
+ def self.schemas(names = REGISTRIES.keys)
+ names.to_h do |name|
+ classes = REGISTRIES.fetch(name).call.map { |entry| entry.is_a?(Class) ? entry : entry.to_s.constantize }
+ [name, classes.uniq.sort_by(&:api_type).to_h { |klass| [klass.api_type, klass.preference_json_schema] }]
+ end
+ end
+
+ # @param family [String] e.g. `PromotionRule`
+ # @param type [String] e.g. `item_total`
+ # @return [String] e.g. `PromotionRuleItemTotalPreferences`
+ def self.member_name(family, type)
+ "#{family}#{type.camelize}Preferences"
+ end
+ end
+ end
+end
diff --git a/spree/api/lib/spree/api/preference_types.rb b/spree/api/lib/spree/api/preference_types.rb
new file mode 100644
index 0000000000..f85acdb646
--- /dev/null
+++ b/spree/api/lib/spree/api/preference_types.rb
@@ -0,0 +1,119 @@
+require 'spree/api/preference_families'
+
+module Spree
+ module Api
+ # Renders each configurable family's preference schemas
+ # ({Spree::Api::PreferenceFamilies}) into the TypeScript types the Admin
+ # and Seller SDKs export: one interface per subtype Spree ships, a map from
+ # `type` to it, and the family's resource with `preferences` typed by its
+ # `type`.
+ #
+ # The map is an interface, so an extension types its own subtypes by
+ # declaration merging. A union with a catch-all member for unknown types
+ # would stop TypeScript from narrowing on `type` at all.
+ #
+ # Run by `rake typelizer:generate`; `preference_types_spec.rb` fails when
+ # the committed files no longer match the declarations.
+ class PreferenceTypes
+ HEADER = "// This file is auto-generated from Spree's preference declarations by `rake typelizer:generate`. Do not edit directly.\n".freeze
+
+ FILES = {
+ 'packages/admin-sdk/src/types/preferences.ts' => PreferenceFamilies::REGISTRIES.keys,
+ 'packages/seller-sdk/src/types/preferences.ts' => PreferenceFamilies::SELLER
+ }.freeze
+
+ # Families serialized as rows of their own; calculators are nested in
+ # their owner and get only the map.
+ RESOURCES = (PreferenceFamilies::REGISTRIES.keys - %w[DeliveryCalculator PromotionCalculator]).freeze
+
+ # @return [Hash{String => String}] file contents keyed by path under the monorepo root
+ def render
+ FILES.transform_values { |families| source(PreferenceFamilies.schemas(families)) }
+ end
+
+ # @param root [Pathname] the monorepo root
+ # @return [void]
+ def write!(root)
+ render.each { |path, content| File.write(root.join(path), content) }
+ end
+
+ private
+
+ NARROWED = <<~TS.freeze
+ /** `Resource` with its `preferences` typed by its `type`, one member per entry of `Map`. */
+ type Narrowed<Resource, Map> = {
+ [Type in keyof Map]: Omit<Resource, 'type' | 'preferences'> & {
+ type: Type
+ preferences: Map[Type]
+ }
+ }[keyof Map]
+ TS
+
+ def source(families)
+ resources = families.keys & RESOURCES
+ imports = resources.map { |family| "import type #{family} from './generated/#{family}'\n" }.join
+ parts = families.flat_map { |family, members| family_parts(family, members, resources.include?(family)) }
+ parts.unshift(NARROWED) if resources.any?
+ parts.unshift(imports) if imports.present?
+
+ HEADER + parts.join("\n")
+ end
+
+ def family_parts(family, members, resource)
+ label = family.titleize.downcase
+ parts = members.map do |type, schema|
+ name = PreferenceFamilies.member_name(family, type)
+ properties = schema['properties']
+ next "/** Settings of the `#{type}` #{label}: none. */\nexport type #{name} = Record<string, never>\n" if properties.empty?
+
+ fields = properties.map { |key, property| "#{field_comment(property)} #{key}: #{ts_type(property)}\n" }.join
+ "/** Settings of the `#{type}` #{label}. */\nexport interface #{name} {\n#{fields}}\n"
+ end
+
+ map = "#{family}PreferencesMap"
+ entries = members.keys.map { |type| " #{type}: #{PreferenceFamilies.member_name(family, type)}\n" }.join
+ ignore = members.empty? ? "// biome-ignore lint/suspicious/noEmptyInterface: extensions add their types by declaration merging\n" : ''
+ parts << "/**\n * The settings of each #{label} type Spree ships, by `type`. An interface,\n" \
+ " * so an extension types its own by declaration merging.\n */\n" \
+ "#{ignore}export interface #{map} {#{"\n#{entries}" if entries.present?}}\n"
+ parts << "/** #{label.match?(/\A[aeiou]/) ? 'An' : 'A'} #{label} whose `preferences` are typed by its `type`. */\nexport type Typed#{family} = Narrowed<#{family}, #{map}>\n" if resource
+ parts
+ end
+
+ def field_comment(property)
+ note = if property['x-spree-secret'] then 'Masked when read (`••••1234`); send it back unchanged to keep it, `null` to clear it.'
+ elsif property.dig('items', 'x-spree-prefix') then "Prefixed `#{property.dig('items', 'x-spree-prefix')}_` ids."
+ elsif property['format'] == 'money' then 'An amount, as an exact decimal string.'
+ elsif property['format'] then "Format: `#{property['format']}`."
+ end
+ note ? " /** #{note} */\n" : ''
+ end
+
+ def ts_type(schema)
+ types = Array(schema['type'])
+ base = base_type(schema, (types - ['null']).first)
+ types.include?('null') ? "#{base} | null" : base
+ end
+
+ def base_type(schema, type)
+ return schema['enum'].compact.map { |value| value.is_a?(String) ? "'#{value}'" : value.to_s }.join(' | ') if schema['enum']
+
+ case type
+ when 'string' then 'string'
+ when 'integer', 'number' then 'number'
+ when 'boolean' then 'boolean'
+ when 'array' then schema['items'] ? "Array<#{ts_type(schema['items'])}>" : 'Array<unknown>'
+ when 'object'
+ if schema['properties']
+ "{ #{schema['properties'].map { |key, property| "#{key}: #{ts_type(property)}" }.join('; ')} }"
+ elsif schema['additionalProperties'].is_a?(Hash)
+ "Record<string, #{ts_type(schema['additionalProperties'])}>"
+ else
+ 'Record<string, unknown>'
+ end
+ else 'unknown'
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/lib/spree/api/typelizer_generation.rb b/spree/api/lib/spree/api/typelizer_generation.rb
index 2252da8bf9..8e855f0368 100644
--- a/spree/api/lib/spree/api/typelizer_generation.rb
+++ b/spree/api/lib/spree/api/typelizer_generation.rb
@@ -29,6 +29,10 @@ module Spree
# The typed webhook events in @spree/sdk, from the event catalog.
require Spree::Api::Engine.root.join('lib/spree/api/webhook_event_types').to_s
Spree::Api::WebhookEventTypes.new.write!(api_root.join('../..'))
+
+ # Each configurable family's preferences, typed by `type`, in the Admin and Seller SDKs.
+ require Spree::Api::Engine.root.join('lib/spree/api/preference_types').to_s
+ Spree::Api::PreferenceTypes.new.write!(api_root.join('../..'))
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb
index acb9a8c3ae..83825d5791 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb
@@ -197,8 +197,8 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller do
it 'persists the storefront gating preferences' do
post :create, params: {
name: 'B2B Portal', code: 'b2b',
- preferred_storefront_access: 'login_required',
- preferred_guest_checkout: false
+ storefront_access: 'login_required',
+ guest_checkout: false
}, as: :json
expect(response).to have_http_status(:created)
@@ -221,14 +221,14 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller do
expect(previous_default.reload.default).to be false
end
- it 'persists preferred_order_routing_strategy' do
+ it 'persists order_routing_strategy' do
patch :update, params: {
id: channel.prefixed_id,
- preferred_order_routing_strategy: 'rules'
+ order_routing_strategy: 'rules'
}, as: :json
expect(response).to have_http_status(:ok)
- expect(json_response['preferred_order_routing_strategy']).to eq('rules')
+ expect(json_response['order_routing_strategy']).to eq('rules')
expect(channel.reload.preferred_order_routing_strategy).to eq('Spree::OrderRouting::Strategy::Rules')
end
@@ -237,7 +237,7 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller do
patch :update, params: {
id: channel.prefixed_id,
- preferred_order_routing_strategy: nil
+ order_routing_strategy: nil
}, as: :json
expect(response).to have_http_status(:ok)
@@ -247,13 +247,13 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller do
it 'persists the storefront gating preferences' do
patch :update, params: {
id: channel.prefixed_id,
- preferred_storefront_access: 'prices_hidden',
- preferred_guest_checkout: false
+ storefront_access: 'prices_hidden',
+ guest_checkout: false
}, as: :json
expect(response).to have_http_status(:ok)
- expect(json_response['preferred_storefront_access']).to eq('prices_hidden')
- expect(json_response['preferred_guest_checkout']).to be(false)
+ expect(json_response['storefront_access']).to eq('prices_hidden')
+ expect(json_response['guest_checkout']).to be(false)
channel.reload
expect(channel.preferred_storefront_access).to eq('prices_hidden')
@@ -265,8 +265,8 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller do
patch :update, params: {
id: channel.prefixed_id,
- preferred_storefront_access: nil,
- preferred_guest_checkout: nil
+ storefront_access: nil,
+ guest_checkout: nil
}, as: :json
expect(response).to have_http_status(:ok)
@@ -281,7 +281,7 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller do
patch :update, params: {
id: channel.prefixed_id,
- preferred_storefront_access: 'members_only'
+ storefront_access: 'members_only'
}, as: :json
expect(response).to have_http_status(:unprocessable_content)
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 ba0a2f4682..6a9f088dae 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
@@ -148,7 +148,9 @@ RSpec.describe Spree::Api::V3::Admin::CommissionRatesController, type: :controll
rules: [{ type: 'seller_rule', preferences: { seller_ids: [foreign_seller.prefixed_id] } }]
}, as: :json
- expect(response).to have_http_status(:not_found)
+ 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(rate.reload.commission_rules.map(&:class)).to eq([Spree::CommissionRules::SellerRule])
end
@@ -167,7 +169,8 @@ RSpec.describe Spree::Api::V3::Admin::CommissionRatesController, type: :controll
rules: [{ type: 'seller_rule', preferences: { seller_ids: ['sel_gone'] } }]
}, as: :json
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('invalid_preferences')
end
it 'still accepts an empty list as clearing the targeting' do
@@ -254,7 +257,7 @@ RSpec.describe Spree::Api::V3::Admin::CommissionRatesController, type: :controll
band = types.find { |row| row['type'] == 'item_total_rule' }
expect(band['name']).to eq('Sale value')
- expect(band['preference_schema'].map { |field| field['key'] }).to include('min_amount', 'max_amount')
+ expect(band['schema']['properties'].keys).to include('min_amount', 'max_amount')
products = types.find { |row| row['type'] == 'product_rule' }
expect(products['association_fields']).to include('product_ids')
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/delivery_method_rules_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/delivery_method_rules_controller_spec.rb
index 00f4c5ad7c..ee7bc66975 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/delivery_method_rules_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_method_rules_controller_spec.rb
@@ -8,14 +8,14 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodRulesController, type: :cont
before { request.headers.merge!(headers) }
describe 'GET #types' do
- it 'lists registered rule kinds with preference schemas' do
+ it 'lists registered rule kinds with their preferences schema' do
get :types, params: {}, as: :json
expect(response).to have_http_status(:ok)
expect(json_response['data'].map { |row| row['type'] }).to contain_exactly('item_total_rule', 'weight_rule', 'excluded_products_rule', 'channel_rule',
'volume_rule', 'company_rule')
item_total = json_response['data'].find { |row| row['type'] == 'item_total_rule' }
- expect(item_total['preference_schema'].map { |field| field['key'] }).to contain_exactly('minimum_amount', 'maximum_amount')
+ expect(item_total['schema']['properties'].keys).to contain_exactly('minimum_amount', 'maximum_amount')
excluded = json_response['data'].find { |row| row['type'] == 'excluded_products_rule' }
expect(excluded['association_fields']).to eq(['product_ids'])
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods/rules_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods/rules_controller_spec.rb
index 7662460507..a077ab8cbb 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods/rules_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods/rules_controller_spec.rb
@@ -12,7 +12,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethods::RulesController, type: :c
describe 'GET #index' do
let!(:rule) do
Spree::DeliveryMethodRules::ItemTotalRule.create!(
- delivery_method: delivery_method, preferences: { minimum_amount: 25 }
+ delivery_method: delivery_method, preferred_minimum_amount: 25
)
end
@@ -23,8 +23,8 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethods::RulesController, type: :c
row = json_response['data'].first
expect(row['type']).to eq('item_total_rule')
expect(row['active']).to be(true)
- expect(row['preferences']['minimum_amount']).to eq('25')
- expect(row['preference_schema'].map { |field| field['key'] }).to contain_exactly('minimum_amount', 'maximum_amount')
+ expect(row['preferences']).to eq('minimum_amount' => '25', 'maximum_amount' => nil)
+ expect(row).not_to have_key('preference_schema')
end
end
@@ -33,7 +33,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethods::RulesController, type: :c
post :create, params: {
delivery_method_id: delivery_method.prefixed_id,
type: 'weight_rule',
- preferences: { maximum_weight: 30 }
+ preferences: { maximum_weight: '30' }
}, as: :json
expect(response).to have_http_status(:created)
@@ -94,7 +94,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethods::RulesController, type: :c
delivery_method_id: delivery_method.prefixed_id,
id: rule.prefixed_id,
active: false,
- preferences: { minimum_amount: 50 }
+ preferences: { minimum_amount: '50' }
}, as: :json
expect(response).to have_http_status(:ok)
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
index 8cc53f32d4..a4ade7e4be 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
@@ -17,7 +17,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
data = json_response['data'].find { |row| row['name'] == 'UPS Ground' }
expect(data).to be_present
expect(data['delivery_profile_id']).to be_present
- expect(data['calculator_type']).to be_present
+ expect(data['calculator']['type']).to be_present
end
end
@@ -29,7 +29,8 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
types = json_response['data'].map { |row| row['type'] }
expect(types).to include('flat_rate')
flat_rate = json_response['data'].find { |row| row['type'] == 'flat_rate' }
- expect(flat_rate['preference_schema']).to be_an(Array)
+ expect(flat_rate['schema']).to include('type' => 'object', 'additionalProperties' => false)
+ expect(flat_rate['schema']['properties']).to include('amount', 'currency', 'amounts')
end
end
@@ -156,14 +157,13 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
post :create, params: {
name: 'Express',
storefront_visible: true,
- calculator_type: 'flat_rate',
- calculator_preferences: { amount: '12.5' },
+ calculator: { type: 'flat_rate', preferences: { amount: '12.5' } },
delivery_zone_id: zone.prefixed_id
}, as: :json
expect(response).to have_http_status(:created)
expect(json_response['name']).to eq('Express')
- expect(json_response['calculator_type']).to eq('flat_rate')
+ expect(json_response['calculator']['type']).to eq('flat_rate')
expect(json_response['delivery_zone_id']).to eq(zone.prefixed_id)
expect(json_response['delivery_profile_id']).to be_present
@@ -177,7 +177,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
it 'keeps the amount when no calculator is named' do
post :create, params: {
name: 'Priced by default',
- calculator_preferences: { amount: '7.25' }
+ calculator: { preferences: { amount: '7.25' } }
}, as: :json
expect(response).to have_http_status(:created)
@@ -190,7 +190,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
post :create, params: {
name: 'Store pickup',
fulfillment_provider: 'pickup',
- calculator_type: 'flat_rate'
+ calculator: { type: 'flat_rate' }
}, as: :json
expect(response).to have_http_status(:created)
@@ -213,7 +213,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
it 'rejects unknown calculator types' do
post :create, params: {
name: 'Sneaky',
- calculator_type: 'Kernel'
+ calculator: { type: 'Kernel' }
}, as: :json
expect(response).to have_http_status(:unprocessable_content)
@@ -227,7 +227,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
patch :update, params: {
id: delivery_method.prefixed_id,
name: 'UPS Ground v2',
- calculator_preferences: { amount: '99' }
+ calculator: { preferences: { amount: '99' } }
}, as: :json
expect(response).to have_http_status(:ok)
@@ -238,12 +238,11 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
it 'stores per-currency amounts' do
patch :update, params: {
id: delivery_method.prefixed_id,
- calculator_type: 'flat_rate',
- calculator_preferences: { amount: '20', currency: 'USD', amounts: { 'EUR' => '15.0' } }
+ calculator: { type: 'flat_rate', preferences: { amount: '20', currency: 'USD', amounts: { 'EUR' => '15.0' } } }
}, as: :json
expect(response).to have_http_status(:ok)
- expect(json_response['calculator_preferences']['amounts']).to eq('EUR' => '15.0')
+ expect(json_response['calculator']['preferences']['amounts']).to eq('EUR' => '15.0')
calculator = delivery_method.reload.calculator
expect(calculator.preferred_amounts).to eq('EUR' => '15.0')
@@ -259,7 +258,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
id: delivery_method.prefixed_id,
name: 'Express',
rules: [
- { type: 'item_total_rule', preferences: { minimum_amount: 25 } },
+ { type: 'item_total_rule', preferences: { minimum_amount: '25' } },
{ type: 'excluded_products_rule', product_ids: [product.prefixed_id] }
]
}, as: :json
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb
index 4d2a61b4b6..f36779c74d 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb
@@ -101,13 +101,13 @@ RSpec.describe Spree::Api::V3::Admin::ImportsController, type: :controller do
post :create,
params: {
type: 'products',
- preferred_delimiter: ';',
+ delimiter: ';',
attachment: csv_signed_id("slug;sku;name;price\nwidget;W-1;Widget;10.00\n")
},
as: :json
expect(response).to have_http_status(:created)
- expect(json_response['preferred_delimiter']).to eq(';')
+ expect(json_response['delimiter']).to eq(';')
expect(json_response['csv_headers']).to eq(%w[slug sku name price])
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/integrations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/integrations_controller_spec.rb
index bc56ab90c8..17207dfa1d 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/integrations_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/integrations_controller_spec.rb
@@ -41,7 +41,7 @@ RSpec.describe Spree::Api::V3::Admin::IntegrationsController, type: :controller
entry = json_response['data'].find { |row| row['type'] == 'carrier' }
expect(entry['name']).to eq('Carrier')
expect(entry['group']).to eq('shipping')
- expect(entry['preference_schema'].map { |f| f['key'] }).to match_array(%w[api_key account_number])
+ expect(entry['schema']['properties'].keys).to match_array(%w[api_key account_number])
end
describe 'gallery metadata' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/order_routing_rules_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/order_routing_rules_controller_spec.rb
index 4d0baa17cd..121d9ef1b2 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/order_routing_rules_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/order_routing_rules_controller_spec.rb
@@ -109,7 +109,7 @@ RSpec.describe Spree::Api::V3::Admin::OrderRoutingRulesController, type: :contro
end
describe 'GET #types' do
- it 'enumerates registered rule kinds with labels and preference schemas' do
+ it 'enumerates registered rule kinds with labels and their preferences schema' do
get :types, as: :json
types = json_response[:data]
@@ -117,7 +117,7 @@ RSpec.describe Spree::Api::V3::Admin::OrderRoutingRulesController, type: :contro
entry = types.find { |t| t[:type] == 'default_location' }
expect(entry[:label]).to eq('Default location')
expect(entry[:description]).to be_present
- expect(entry[:preference_schema]).to eq([])
+ expect(entry[:schema]).to eq('type' => 'object', 'properties' => {}, 'additionalProperties' => false)
end
context 'with a read-only secret API key and no JWT' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb
index 430d2921cb..8624ffb32d 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb
@@ -171,14 +171,13 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
end
# Spree writes these itself — a secret the provider issued, an id it
- # gave back. They are absent from the schema so no form offers them,
- # and ignored here so a client cannot write one anyway and break the
- # signature check that depends on it.
+ # gave back. They are absent from the schema, so a client writing one
+ # is refused and cannot break the signature check that depends on it.
# A gateway of its own, declaring a real internal preference. Stubbing
# `preference_internal` on the shared Bogus class would be read by the
# class-level schema memo as well, caching a schema without its password
# key for every later example in the process.
- it 'ignores a preference the system owns' do
+ it 'refuses a preference the system owns' do
gateway_class = Class.new(Spree::Gateway) do
def self.name = 'InternalPreferenceGateway'
@@ -197,7 +196,8 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
},
as: :json
- expect(response).to have_http_status(:ok)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('invalid_preferences')
expect(gateway.reload.preferred_issued_secret).to eq('whsec_real')
end
@@ -297,25 +297,26 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
expect(types).to include('bogus', 'store_credit', 'custom_payment_source_method')
end
- it 'filters out providers already installed in the current store' do
+ it 'marks providers already installed in the current store, keeping their schema' do
get :types, as: :json
- types = json_response['data'].map { |entry| entry['type'] }
- # The seeded `check_payment_method` is scoped to `store`, so `check`
- # must not be offered again — that's how the admin avoids
- # double-installing a provider.
- expect(types).not_to include('check')
+ # The seeded `check_payment_method` belongs to `store`: the create picker
+ # leaves `check` out, while its edit form still reads its schema here.
+ check = json_response['data'].find { |entry| entry['type'] == 'check' }
+ expect(check).to include('installed' => true, 'schema' => include('type' => 'object'))
+ expect(json_response['data'].find { |entry| entry['type'] == 'bogus' }['installed']).to be(false)
end
# Bogus declares `preference :dummy_secret_key, :password, default: 'SECRETKEY123'`.
# The discovery endpoint must not leak the default — that's a secret
# the gateway author shipped, just like a saved value would be.
- it 'redacts password defaults in each provider\'s preference_schema' do
+ it 'redacts password defaults in each provider\'s schema' do
get :types, as: :json
bogus = json_response['data'].find { |entry| entry['type'] == 'bogus' }
- secret_field = bogus['preference_schema'].find { |f| f['key'] == 'dummy_secret_key' }
- expect(secret_field['default']).to be_nil
+ secret_field = bogus['schema']['properties']['dummy_secret_key']
+ expect(secret_field).to include('x-spree-secret' => true)
+ expect(secret_field).not_to have_key('default')
expect(response.body).not_to include('SECRETKEY123')
end
@@ -358,7 +359,7 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
it 'exposes a unique `type` for every provider' do
get :types, as: :json
- types = json_response['data'].map { |entry| entry['type'] }
+ types = json_response['data'].reject { |entry| entry['installed'] }.map { |entry| entry['type'] }
expect(types).to contain_exactly('stripe', 'adyen')
expect(types).to eq(types.uniq)
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb
index 2d09cd5c3b..7737e87ffa 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb
@@ -283,7 +283,7 @@ RSpec.describe Spree::Api::V3::Admin::PriceListsController, type: :controller do
expect(rule.customer_groups).to contain_exactly(customer_group, other_group)
end
- it 'returns 404 for an unknown customer-group ID' do
+ it 'refuses an unknown customer-group ID' do
post :create,
params: base_params.merge(
rules: [{
@@ -293,7 +293,8 @@ RSpec.describe Spree::Api::V3::Admin::PriceListsController, type: :controller do
),
as: :json
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('invalid_preferences')
end
end
@@ -321,14 +322,15 @@ RSpec.describe Spree::Api::V3::Admin::PriceListsController, type: :controller do
expect(rule.users).to contain_exactly(user, other_user)
end
- it 'returns 404 for an unknown user ID' do
+ it 'refuses an unknown user ID' do
post :create,
params: base_params.merge(
rules: [{ type: 'user_rule', preferences: { user_ids: ['cus_doesnotexist'] } }]
),
as: :json
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('invalid_preferences')
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/seller_requirements_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/seller_requirements_controller_spec.rb
index 8fddade3eb..34a76929e3 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/seller_requirements_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/seller_requirements_controller_spec.rb
@@ -17,7 +17,7 @@ RSpec.describe Spree::Api::V3::Admin::SellerRequirementsController, type: :contr
document = json_response['data'].find { |t| t['type'] == 'document' }
expect(document['accepted_content_types']).to include('application/pdf', 'image/jpeg')
# Nothing to configure — the list is fixed, so it is not a preference.
- expect(document['preference_schema']).to be_empty
+ expect(document['schema']['properties']).to be_empty
end
it 'names the records a kind takes, so the picker is a picker' do
@@ -37,7 +37,7 @@ RSpec.describe Spree::Api::V3::Admin::SellerRequirementsController, type: :contr
accept_terms = types.find { |t| t['type'] == 'accept_terms' }
expect(accept_terms['name']).to eq('Accept terms')
expect(accept_terms['allow_multiple']).to be false
- expect(accept_terms['preference_schema']).to be_an(Array)
+ expect(accept_terms['schema']['properties'].keys).to include('terms_url', 'terms_effective_from')
document = types.find { |t| t['type'] == 'document' }
expect(document['allow_multiple']).to be true
@@ -144,7 +144,7 @@ RSpec.describe Spree::Api::V3::Admin::SellerRequirementsController, type: :contr
let(:requirement) { create(:minimum_products_requirement, store: store) }
it 'changes what the requirement asks for' do
- patch :update, params: { id: requirement.prefixed_id, preferences: { minimum_count: 5 }, format: :json }
+ patch :update, params: { id: requirement.prefixed_id, preferences: { minimum_count: 5 } }, as: :json
expect(response).to have_http_status(:ok)
expect(requirement.reload.preferred_minimum_count).to eq(5)
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 0fa969fa74..bb03807f41 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
@@ -140,7 +140,7 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
'mail_from_address' => store.mail_from_address,
'customer_support_email' => store.customer_support_email,
'new_order_notifications_email' => store.new_order_notifications_email,
- 'preferred_send_consumer_transactional_emails' => store.preferred_send_consumer_transactional_emails
+ 'send_consumer_transactional_emails' => store.preferred_send_consumer_transactional_emails
)
expect(json_response).to have_key('mailer_logo_url')
end
@@ -148,8 +148,8 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
it 'exposes the storefront-access gating defaults' do
subject
expect(json_response).to include(
- 'preferred_storefront_access' => store.preferred_storefront_access,
- 'preferred_guest_checkout' => store.preferred_guest_checkout
+ 'storefront_access' => store.preferred_storefront_access,
+ 'guest_checkout' => store.preferred_guest_checkout
)
end
@@ -188,17 +188,17 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
end
context 'with the low stock threshold' do
- let(:params) { { preferred_low_stock_threshold: 12 } }
+ let(:params) { { low_stock_threshold: 12 } }
it 'saves it and returns it' do
subject
expect(response).to have_http_status(:ok)
- expect(json_response['preferred_low_stock_threshold']).to eq(12)
+ expect(json_response['low_stock_threshold']).to eq(12)
expect(store.reload.preferred_low_stock_threshold).to eq(12)
end
it 'refuses a negative threshold' do
- patch :update, params: { preferred_low_stock_threshold: -1 }, as: :json
+ patch :update, params: { low_stock_threshold: -1 }, as: :json
expect(response).to have_http_status(:unprocessable_content)
end
end
@@ -216,10 +216,10 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
context 'with order-numbering params' do
let(:params) do
{
- preferred_document_number_format: 'random',
- preferred_order_number_prefix: 'INV',
- preferred_order_number_suffix: '-EU',
- preferred_order_number_sequence_start: 5001
+ document_number_format: 'random',
+ order_number_prefix: 'INV',
+ order_number_suffix: '-EU',
+ order_number_sequence_start: 5001
}
end
@@ -235,7 +235,7 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
it 'exposes them in the response' do
subject
- expect(json_response['preferred_order_number_prefix']).to eq('INV')
+ expect(json_response['order_number_prefix']).to eq('INV')
end
it 'reports that numbering has not started yet' do
@@ -248,7 +248,7 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
it 'reports the started flag' do
# Prefix stays editable after numbering starts — only the start locks.
- patch :update, params: { preferred_order_number_prefix: 'INV' }, as: :json
+ patch :update, params: { order_number_prefix: 'INV' }, as: :json
expect(response).to have_http_status(:ok)
expect(json_response['order_number_sequence_started']).to be(true)
end
@@ -256,13 +256,13 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
it 'rejects a changed starting value' do
subject
expect(response).to have_http_status(:unprocessable_content)
- expect(json_response['error']['details']).to have_key('preferred_order_number_sequence_start')
+ expect(json_response['error']['details']).to have_key('order_number_sequence_start')
end
end
end
context 'with an unsupported numbering format' do
- let(:params) { { preferred_document_number_format: 'roman_numerals' } }
+ let(:params) { { document_number_format: 'roman_numerals' } }
it 'returns a validation error' do
subject
@@ -271,7 +271,7 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
end
context 'with a prefix containing unsupported characters' do
- let(:params) { { preferred_order_number_prefix: 'inv/2026' } }
+ let(:params) { { order_number_prefix: 'inv/2026' } }
it 'returns a validation error' do
subject
@@ -285,7 +285,7 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
mail_from_address: '[email protected]',
customer_support_email: '[email protected]',
new_order_notifications_email: '[email protected]',
- preferred_send_consumer_transactional_emails: false
+ send_consumer_transactional_emails: false
}
end
@@ -301,21 +301,21 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
end
context 'with email branding params' do
- let(:params) { { preferred_email_accent_color: '#FF5500', preferred_email_font: 'georgia' } }
+ let(:params) { { email_accent_color: '#FF5500', email_font: 'georgia' } }
it 'saves the colors and font customer emails use' do
subject
expect(response).to have_http_status(:ok)
- expect(json_response).to include('preferred_email_accent_color' => '#FF5500', 'preferred_email_font' => 'georgia')
+ expect(json_response).to include('email_accent_color' => '#FF5500', 'email_font' => 'georgia')
end
context 'with a value that is not a color' do
- let(:params) { { preferred_email_accent_color: 'red' } }
+ let(:params) { { email_accent_color: 'red' } }
it 'refuses it' do
subject
expect(response).to have_http_status(:unprocessable_content)
- expect(json_response['error']['details']).to have_key('preferred_email_accent_color')
+ expect(json_response['error']['details']).to have_key('email_accent_color')
end
end
end
@@ -331,7 +331,7 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
end
context 'with storefront-access gating params' do
- let(:params) { { preferred_storefront_access: 'login_required', preferred_guest_checkout: false } }
+ let(:params) { { storefront_access: 'login_required', guest_checkout: false } }
it 'updates the store-wide gating defaults' do
subject
@@ -343,7 +343,7 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
end
context 'with address params' do
- let(:params) { { preferred_company_field_enabled: true, preferred_address_requires_phone: true } }
+ let(:params) { { company_field_enabled: true, address_requires_phone: true } }
it 'updates the address settings' do
subject
@@ -357,9 +357,9 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
context 'with commerce behavior params' do
let(:params) do
{
- preferred_capture_method: 'on_dispatch',
- preferred_track_inventory_levels: false,
- preferred_show_products_without_price: true
+ capture_method: 'on_dispatch',
+ track_inventory_levels: false,
+ show_products_without_price: true
}
end
@@ -376,10 +376,10 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
context 'with marketplace params' do
let(:params) do
{
- preferred_auto_approve_sellers: true,
- preferred_auto_approve_seller_products: true,
- preferred_send_seller_transactional_emails: false,
- preferred_default_commission_tax_rate: '0.23'
+ auto_approve_sellers: true,
+ auto_approve_seller_products: true,
+ send_seller_transactional_emails: false,
+ default_commission_tax_rate: '0.23'
}
end
@@ -397,7 +397,7 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
# The rate is a fraction, so a percentage typed straight in would bill
# more tax than fee.
context 'with a commission tax rate above 1' do
- let(:params) { { preferred_default_commission_tax_rate: '23' } }
+ let(:params) { { default_commission_tax_rate: '23' } }
it 'returns a validation error' do
subject
@@ -406,20 +406,8 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
end
end
- # Existing API clients keep working for one release; the model maps the
- # old names onto capture_method.
- context 'with the deprecated capture params' do
- let(:params) { { preferred_auto_capture_on_dispatch: true } }
-
- it 'maps them onto the capture method' do
- subject
- expect(response).to have_http_status(:ok)
- expect(store.reload.preferred_capture_method).to eq('on_dispatch')
- end
- end
-
context 'with an invalid storefront_access value' do
- let(:params) { { preferred_storefront_access: 'nonsense' } }
+ let(:params) { { storefront_access: 'nonsense' } }
it 'returns a validation error' do
subject
@@ -512,28 +500,28 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
describe 'PATCH #update' do
it 'saves the chosen providers and policies' do
patch :update, params: {
- preferred_pricing_provider: 'internal',
- preferred_inventory_provider: 'internal',
- preferred_pricing_provider_failure_policy: 'fallback',
- preferred_inventory_provider_failure_policy: 'strict'
+ pricing_provider: 'internal',
+ inventory_provider: 'internal',
+ pricing_provider_failure_policy: 'fallback',
+ inventory_provider_failure_policy: 'strict'
}, as: :json
expect(response).to have_http_status(:ok)
- expect(json_response['preferred_pricing_provider_failure_policy']).to eq('fallback')
+ expect(json_response['pricing_provider_failure_policy']).to eq('fallback')
expect(store.reload.preferred_inventory_provider_failure_policy).to eq('strict')
end
it 'reads and writes the routing strategy and payout provider by their shorthand' do
- patch :update, params: { preferred_order_routing_strategy: 'rules', preferred_payout_provider: 'system' }, as: :json
+ patch :update, params: { order_routing_strategy: 'rules', payout_provider: 'system' }, as: :json
expect(response).to have_http_status(:ok)
- expect(json_response['preferred_order_routing_strategy']).to eq('rules')
- expect(json_response['preferred_payout_provider']).to eq('system')
+ expect(json_response['order_routing_strategy']).to eq('rules')
+ expect(json_response['payout_provider']).to eq('system')
expect(store.reload.preferred_payout_provider).to eq('Spree::PayoutProvider::System')
end
it 'refuses a policy that is neither falling back nor strict' do
- patch :update, params: { preferred_pricing_provider_failure_policy: 'ignore' }, as: :json
+ patch :update, params: { pricing_provider_failure_policy: 'ignore' }, as: :json
expect(response).to have_http_status(:unprocessable_content)
end
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/delivery_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/delivery_methods_controller_spec.rb
index 297170765a..7aa9be8953 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/delivery_methods_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/delivery_methods_controller_spec.rb
@@ -75,8 +75,7 @@ RSpec.describe Spree::Api::V3::Seller::DeliveryMethodsController, type: :control
{
name: 'Next day',
delivery_profile_id: profile.prefixed_id,
- calculator_type: 'flat_rate',
- calculator_preferences: { amount: '9.99', currency: 'USD' }
+ calculator: { type: 'flat_rate', preferences: { amount: '9.99', currency: 'USD' } }
}
end
@@ -111,17 +110,17 @@ RSpec.describe Spree::Api::V3::Seller::DeliveryMethodsController, type: :control
# carrying preferences without naming a calculator used to drop them and
# save a free rate over the amount the seller typed.
it 'keeps the amount when no calculator is named' do
- post :create, params: valid_params.except(:calculator_type), as: :json
+ post :create, params: valid_params.merge(calculator: { preferences: { amount: '9.99', currency: 'USD' } }), as: :json
expect(response).to have_http_status(:created)
expect(Spree::DeliveryMethod.find_by(name: 'Next day').calculator.preferred_amount).to eq(9.99)
end
it 'refuses a calculator this store does not offer' do
- post :create, params: valid_params.merge(calculator_type: 'NoSuchCalculator'), as: :json
+ post :create, params: valid_params.merge(calculator: { type: 'NoSuchCalculator' }), as: :json
expect(response).to have_http_status(:unprocessable_content)
- expect(json_response['error']['details']).to have_key('calculator_type')
+ expect(json_response['error']['details']).to have_key('calculator')
end
it 'refuses to share the seller’s own method with the marketplace' do
@@ -141,7 +140,7 @@ RSpec.describe Spree::Api::V3::Seller::DeliveryMethodsController, type: :control
it 'accepts an eligibility rule the seller may set' do
post :create, params: valid_params.merge(
- rules: [{ type: 'item_total_rule', preferences: { amount_min: '50', currency: 'USD' } }]
+ rules: [{ type: 'item_total_rule', preferences: { minimum_amount: '50' } }]
), as: :json
expect(response).to have_http_status(:created)
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb
index e55b2dbab5..bf6a683599 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb
@@ -29,7 +29,7 @@ RSpec.describe Spree::Api::V3::Seller::ProfileController, type: :controller do
get :show, as: :json
- expect(json_response['preferred_timezone']).to eq('Europe/Warsaw')
+ expect(json_response['timezone']).to eq('Europe/Warsaw')
end
it 'returns the seller their own record' do
diff --git a/spree/api/spec/integration/spree/api/v3/admin/channels_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/channels_spec.rb
index 095a773582..d0b3ab9ba4 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/channels_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/channels_spec.rb
@@ -57,11 +57,11 @@ RSpec.describe 'Admin Channels API', type: :request, swagger_doc: 'api-reference
code: { type: :string, example: 'pos', description: 'Slug — auto-derived from `name` when blank.' },
active: { type: :boolean, default: true },
default: { type: :boolean, default: false },
- preferred_order_routing_strategy: { type: :string, nullable: true,
+ order_routing_strategy: { type: :string, nullable: true,
description: 'Routing strategy shorthand (built-in: `rules`). `null` inherits the store setting.' },
- preferred_storefront_access: { type: :string, nullable: true, enum: %w[public prices_hidden login_required],
+ storefront_access: { type: :string, nullable: true, enum: %w[public prices_hidden login_required],
description: 'Anonymous-visitor access posture. `null` inherits the store setting.' },
- preferred_guest_checkout: { type: :boolean, nullable: true,
+ guest_checkout: { type: :boolean, nullable: true,
description: 'Whether guests can check out without an account. `null` inherits the store setting.' }
}
}
@@ -119,11 +119,11 @@ RSpec.describe 'Admin Channels API', type: :request, swagger_doc: 'api-reference
code: { type: :string },
active: { type: :boolean },
default: { type: :boolean },
- preferred_order_routing_strategy: { type: :string, nullable: true,
+ order_routing_strategy: { type: :string, nullable: true,
description: 'Routing strategy shorthand (built-in: `rules`). `null` inherits the store setting.' },
- preferred_storefront_access: { type: :string, nullable: true, enum: %w[public prices_hidden login_required],
+ storefront_access: { type: :string, nullable: true, enum: %w[public prices_hidden login_required],
description: 'Anonymous-visitor access posture. `null` inherits the store setting.' },
- preferred_guest_checkout: { type: :boolean, nullable: true,
+ guest_checkout: { type: :boolean, nullable: true,
description: 'Whether guests can check out without an account. `null` inherits the store setting.' }
}
}
@@ -132,7 +132,7 @@ RSpec.describe 'Admin Channels API', type: :request, swagger_doc: 'api-reference
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
let(:id) { channel.prefixed_id }
let(:body) do
- { name: 'Wholesale (Updated)', preferred_storefront_access: 'login_required', preferred_guest_checkout: false }
+ { name: 'Wholesale (Updated)', storefront_access: 'login_required', guest_checkout: false }
end
run_test! do |response|
diff --git a/spree/api/spec/integration/spree/api/v3/admin/collections_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/collections_spec.rb
index 4dc93f5024..207fc13275 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/collections_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/collections_spec.rb
@@ -360,7 +360,7 @@ RSpec.describe 'Admin Collections API', type: :request, swagger_doc: 'api-refere
run_test! do |response|
data = JSON.parse(response.body)['data']
expect(data.map { |type| type['type'] }).to contain_exactly('tag', 'sale', 'available_on')
- expect(data.first).to include('label', 'description', 'preference_schema')
+ expect(data.first).to include('label', 'description', 'schema')
end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/commission_rates_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/commission_rates_spec.rb
index 60d5ebaccc..8453192a30 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/commission_rates_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/commission_rates_spec.rb
@@ -145,7 +145,7 @@ RSpec.describe 'Admin Commission Rates API', type: :request, swagger_doc: 'api-r
type: { type: :string, example: 'seller_rule',
description: 'A kind from /commission_rates/rule_types.' },
preferences: { type: :object, example: { seller_ids: ['sel_a1b2c3'] },
- description: "Configuration for the kind, per its preference_schema." },
+ description: "Configuration for the kind, per its type's `schema`." },
product_ids: { type: :array, items: { type: :string },
description: 'For kinds that name products, which are kept outside preferences.' }
}
@@ -209,7 +209,7 @@ RSpec.describe 'Admin Commission Rates API', type: :request, swagger_doc: 'api-r
type: { type: :string, example: 'seller_rule' },
name: { type: :string, example: 'Seller' },
description: { type: :string, nullable: true },
- preference_schema: { type: :array, items: { type: :object } },
+ schema: { type: :object, description: 'JSON Schema of the type\'s `preferences`' },
association_fields: { type: :array, items: { type: :string } }
}
}
diff --git a/spree/api/spec/integration/spree/api/v3/admin/delivery_settings_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/delivery_settings_spec.rb
index f69a1d4d87..c45b0d5865 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/delivery_settings_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/delivery_settings_spec.rb
@@ -56,8 +56,14 @@ RSpec.describe 'Admin Delivery Settings API', type: :request, swagger_doc: 'api-
estimated_transit_business_days_min: { type: :integer, nullable: true },
estimated_transit_business_days_max: { type: :integer, nullable: true },
tax_category_id: { type: :string, nullable: true },
- calculator_type: { type: :string, example: 'flat_rate' },
- calculator_preferences: { type: :object, example: { amount: '12.50' } },
+ calculator: {
+ type: :object,
+ description: 'How the method is priced: a type from `/delivery_methods/calculators` and its preferences, per that type\'s `schema`.',
+ properties: {
+ type: { type: :string, example: 'flat_rate' },
+ preferences: { type: :object, example: { amount: '12.5' } }
+ }
+ },
delivery_zone_id: { type: :string, nullable: true }
},
required: %w[name]
@@ -68,15 +74,14 @@ RSpec.describe 'Admin Delivery Settings API', type: :request, swagger_doc: 'api-
{
name: 'Express',
storefront_visible: true,
- calculator_type: 'flat_rate',
- calculator_preferences: { amount: '12.50' }
+ calculator: { type: 'flat_rate', preferences: { amount: '12.5' } }
}
end
run_test! do |response|
data = JSON.parse(response.body)
expect(data['name']).to eq('Express')
- expect(data['calculator_type']).to eq('flat_rate')
+ expect(data['calculator']['type']).to eq('flat_rate')
end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb
index 72ef40f739..11554d6e7f 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb
@@ -309,7 +309,7 @@ RSpec.describe 'Admin Email Templates API', type: :request, swagger_doc: 'api-re
email_key: { type: :string, example: 'spree.order_mailer.confirm_email', description: 'For the layout or a partial, the email to show it in' },
branding: {
type: :object,
- description: "Unsaved colors and font to preview, named like the store's `preferred_email_*` settings without the prefix",
+ description: "Unsaved colors and font to preview, named like the store's `email_*` settings",
properties: {
accent_color: { type: :string, example: '#FF5500' },
background_color: { type: :string },
diff --git a/spree/api/spec/integration/spree/api/v3/admin/imports_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/imports_spec.rb
index facc5ecff4..9658a5338f 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/imports_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/imports_spec.rb
@@ -85,7 +85,7 @@ RSpec.describe 'Admin Imports API', type: :request, swagger_doc: 'api-reference/
description: 'ActiveStorage signed blob id from POST /api/v3/admin/direct_uploads.',
example: 'eyJfcmFpbHMiOnsiZGF0YSI6MX0=--signed'
},
- preferred_delimiter: {
+ delimiter: {
type: :string,
enum: [',', ';', '|', "\t"],
description: 'CSV column separator. Defaults to a comma.',
diff --git a/spree/api/spec/integration/spree/api/v3/admin/integrations_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/integrations_spec.rb
index 6f5215796f..4f96ddf106 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/integrations_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/integrations_spec.rb
@@ -104,7 +104,7 @@ RSpec.describe 'Admin Integrations API', type: :request, swagger_doc: 'api-refer
run_test! do |response|
data = JSON.parse(response.body)
entry = data['data'].find { |row| row['type'] == 'carrier' }
- expect(entry['preference_schema']).to be_an(Array)
+ expect(entry['schema']).to include('type' => 'object')
end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/order_routing_rules_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/order_routing_rules_spec.rb
index 5f54ba89c6..b69fcaf46d 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/order_routing_rules_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/order_routing_rules_spec.rb
@@ -158,7 +158,7 @@ RSpec.describe 'Admin Order Routing Rules API', type: :request, swagger_doc: 'ap
run_test! do |response|
data = JSON.parse(response.body)['data']
expect(data.map { |t| t['type'] }).to contain_exactly('preferred_location', 'minimize_splits', 'default_location')
- expect(data.first).to include('label', 'description', 'preference_schema')
+ expect(data.first).to include('label', 'description', 'schema')
end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/payment_methods_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/payment_methods_spec.rb
index 35774aa3fb..6521b37f31 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/payment_methods_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/payment_methods_spec.rb
@@ -41,7 +41,7 @@ RSpec.describe 'Admin Payment Methods API', type: :request, swagger_doc: 'api-re
tags 'Payment Methods'
produces 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Returns the registered Spree::PaymentMethod subclasses that can be used to create new payment methods. Useful for populating a "Provider" dropdown in admin UIs.'
+ description 'Returns every registered payment provider with the JSON Schema of its `preferences`. `installed` marks a provider the store already has, which a "Provider" picker leaves out.'
admin_scope :read, :settings
admin_sdk_example 'payment-methods/types'
@@ -53,10 +53,9 @@ RSpec.describe 'Admin Payment Methods API', type: :request, swagger_doc: 'api-re
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
before do
- # Install StoreCredit in the store so we can verify the picker
- # filters out providers that are already configured. (Check is
- # also installed via the let!(:payment_method), but other tests
- # in this file delete it, so it's order-dependent.)
+ # Install StoreCredit in the store so the entry is marked installed.
+ # (Check is also installed via the let!(:payment_method), but other
+ # tests in this file delete it, so it's order-dependent.)
store.payment_methods.create!(type: 'Spree::PaymentMethod::StoreCredit', name: 'Store Credit')
end
@@ -64,10 +63,8 @@ RSpec.describe 'Admin Payment Methods API', type: :request, swagger_doc: 'api-re
data = JSON.parse(response.body)['data']
expect(data).to be_an(Array)
expect(data).to all(include('type', 'label'))
- # StoreCredit was just installed → must be filtered out.
- expect(data.map { |t| t['type'] }).not_to include('store_credit')
- # Bogus is registered but not installed → must show up.
- expect(data.map { |t| t['type'] }).to include('bogus')
+ installed = data.to_h { |entry| [entry['type'], entry['installed']] }
+ expect(installed).to include('store_credit' => true, 'bogus' => false)
end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/promotion_actions_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/promotion_actions_spec.rb
index 60582a41cc..43a84f1736 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/promotion_actions_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/promotion_actions_spec.rb
@@ -34,7 +34,7 @@ RSpec.describe 'Admin Promotion Actions API', type: :request, swagger_doc: 'api-
data = JSON.parse(response.body)['data']
expect(data.size).to eq(1)
expect(data.first['type']).to eq('free_shipping')
- expect(data.first).to have_key('preference_schema')
+ expect(data.first).not_to have_key('preference_schema')
end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb
index 7750f2adb7..122ccef0d1 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb
@@ -395,7 +395,7 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
run_test! do |response|
data = JSON.parse(response.body)['data']
expect(data).to be_an(Array)
- expect(data).to all(include('type', 'label', 'preference_schema'))
+ expect(data).to all(include('type', 'label', 'schema'))
end
end
end
@@ -420,7 +420,7 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
run_test! do |response|
data = JSON.parse(response.body)['data']
expect(data).to be_an(Array)
- expect(data).to all(include('type', 'label', 'preference_schema'))
+ expect(data).to all(include('type', 'label', 'schema'))
end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/seller_requirements_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/seller_requirements_spec.rb
index 73a315583b..e341336a94 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/seller_requirements_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/seller_requirements_spec.rb
@@ -88,7 +88,7 @@ RSpec.describe 'Admin Seller Requirements API', type: :request, swagger_doc: 'ap
active: { type: :boolean, example: true },
position: { type: :integer, example: 1, description: 'Place in the checklist.' },
preferences: { type: :object, example: { accepted_content_types: ['application/pdf'] },
- description: 'Configuration for this kind, per its `preference_schema`.' }
+ description: 'Configuration for this kind, per its type\'s `schema`.' }
}
}
@@ -152,7 +152,7 @@ RSpec.describe 'Admin Seller Requirements API', type: :request, swagger_doc: 'ap
description: 'Whether the operator may add one now. The uniqueness ' \
'rule is the server\'s, so clients filter on this rather ' \
'than deriving it.' },
- preference_schema: { type: :array, items: { type: :object } }
+ schema: { type: :object, description: 'JSON Schema of the type\'s `preferences`' }
}
}
}
diff --git a/spree/api/spec/integration/spree/api/v3/admin/store_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/store_spec.rb
index 75adf99770..3cc1843888 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/store_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/store_spec.rb
@@ -75,10 +75,10 @@ RSpec.describe 'Admin Store API', type: :request, swagger_doc: 'api-reference/ad
type: :object,
properties: {
name: { type: :string, example: 'My Store' },
- preferred_admin_locale: { type: :string, example: 'en' },
- preferred_timezone: { type: :string, example: 'UTC' },
- preferred_weight_unit: { type: :string, example: 'kg' },
- preferred_unit_system: { type: :string, example: 'metric' }
+ admin_locale: { type: :string, example: 'en' },
+ timezone: { type: :string, example: 'UTC' },
+ weight_unit: { type: :string, example: 'kg' },
+ unit_system: { type: :string, example: 'metric' }
}
}
diff --git a/spree/api/spec/integration/spree/api/v3/seller/delivery_methods_spec.rb b/spree/api/spec/integration/spree/api/v3/seller/delivery_methods_spec.rb
index 84c71bd542..2c904eafef 100644
--- a/spree/api/spec/integration/spree/api/v3/seller/delivery_methods_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/seller/delivery_methods_spec.rb
@@ -76,8 +76,14 @@ RSpec.describe 'Seller Delivery Methods API', type: :request, swagger_doc: 'api-
tracking_url: { type: :string, nullable: true },
estimated_transit_business_days_min: { type: :integer, nullable: true },
estimated_transit_business_days_max: { type: :integer, nullable: true },
- calculator_type: { type: :string },
- calculator_preferences: { type: :object },
+calculator: {
+ type: :object,
+ description: 'How the method is priced: a type from `/delivery_methods/calculators` and its preferences, per that type\'s `schema`.',
+ properties: {
+ type: { type: :string, example: 'flat_rate' },
+ preferences: { type: :object, example: { amount: '12.5' } }
+ }
+ },
rules: {
type: :array,
description: 'Conditions on the method, from `/delivery_methods/rule_types`',
@@ -100,8 +106,7 @@ RSpec.describe 'Seller Delivery Methods API', type: :request, swagger_doc: 'api-
{
name: 'Next day',
delivery_profile_id: delivery_profile.prefixed_id,
- calculator_type: 'flat_rate',
- calculator_preferences: { amount: '9.99', currency: 'USD' }
+ calculator: { type: 'flat_rate', preferences: { amount: '9.99', currency: 'USD' } }
}
end
@@ -163,8 +168,14 @@ RSpec.describe 'Seller Delivery Methods API', type: :request, swagger_doc: 'api-
tracking_url: { type: :string, nullable: true },
estimated_transit_business_days_min: { type: :integer, nullable: true },
estimated_transit_business_days_max: { type: :integer, nullable: true },
- calculator_type: { type: :string },
- calculator_preferences: { type: :object },
+calculator: {
+ type: :object,
+ description: 'How the method is priced: a type from `/delivery_methods/calculators` and its preferences, per that type\'s `schema`.',
+ properties: {
+ type: { type: :string, example: 'flat_rate' },
+ preferences: { type: :object, example: { amount: '12.5' } }
+ }
+ },
rules: {
type: :array,
description: 'Replaces the whole set — a rule dropped here is deleted, so re-send surviving rules with their `id`.',
@@ -231,7 +242,7 @@ RSpec.describe 'Seller Delivery Methods API', type: :request, swagger_doc: 'api-
type: { type: :string },
name: { type: :string },
description: { type: :string },
- preference_schema: { type: :array, items: { type: :object } }
+ schema: { type: :object, description: 'JSON Schema of the type\'s `preferences`' }
}
}
}
@@ -264,7 +275,7 @@ RSpec.describe 'Seller Delivery Methods API', type: :request, swagger_doc: 'api-
properties: {
type: { type: :string },
name: { type: :string },
- preference_schema: { type: :array, items: { type: :object } }
+ schema: { type: :object, description: 'JSON Schema of the type\'s `preferences`' }
}
}
}
diff --git a/spree/api/spec/lib/spree/api/preference_conformance_spec.rb b/spree/api/spec/lib/spree/api/preference_conformance_spec.rb
new file mode 100644
index 0000000000..479018a8a6
--- /dev/null
+++ b/spree/api/spec/lib/spree/api/preference_conformance_spec.rb
@@ -0,0 +1,60 @@
+require 'spec_helper'
+require Spree::Api::Engine.root.join('lib/spree/api/preference_families').to_s
+
+# The preferences contract every configurable type keeps, read the way the API
+# reads it (`Masking.serialize`) and written the way the API writes it
+# (`assign_preferences`). A second implementation of the API must pass the
+# same checks.
+RSpec.describe 'Preference contract conformance' do
+ Spree::Api::PreferenceFamilies::REGISTRIES.each do |family, registry|
+ describe family do
+ let(:classes) { registry.call.map { |entry| entry.is_a?(Class) ? entry : entry.to_s.constantize }.uniq }
+
+ it 'publishes a valid schema that a new record of each type satisfies' do
+ classes.each do |klass|
+ schema = klass.preference_json_schema
+ expect(JSONSchemer.valid_schema?(schema)).to be(true), "#{klass.name} has an invalid schema"
+
+ errors = JSONSchemer.schema(schema).validate(Spree::Preferences::Masking.serialize(klass.new)).map { |error| error['error'] }
+ expect(errors).to be_empty, "#{klass.name}: #{errors.join('; ')}"
+ end
+ end
+
+ it 'refuses a key the schema does not list' do
+ classes.each do |klass|
+ expect { klass.new.assign_preferences('not_a_setting' => 'x') }
+ .to raise_error(Spree::Preferences::InvalidPreferences), "#{klass.name} accepted an unknown key"
+ end
+ end
+
+ it 'refuses an id of another model in every id list' do
+ classes.each do |klass|
+ klass.preference_json_schema['properties'].each do |key, property|
+ next unless property.dig('items', 'format') == 'prefixed-id'
+
+ expect { klass.new.assign_preferences(key => ['zz_86Rf07xd4z']) }
+ .to raise_error(Spree::Preferences::InvalidPreferences, %r{/preferences/#{key}/0}), "#{klass.name}##{key} accepted a foreign id"
+ end
+ end
+ end
+
+ it 'keeps a secret sent back masked, and clears it on null' do
+ classes.each do |klass|
+ klass.preference_json_schema['properties'].each do |key, property|
+ next unless property['x-spree-secret']
+
+ record = klass.new
+ record.set_preference(key, 'sk_test_0123456789')
+ masked = Spree::Preferences::Masking.serialize(record)[key]
+
+ record.assign_preferences(key => masked)
+ expect(record.get_preference(key)).to eq('sk_test_0123456789'), "#{klass.name}##{key} overwrote a secret with its mask"
+
+ record.assign_preferences(key => nil)
+ expect(Spree::Preferences::Masking.serialize(record)[key]).to be_nil, "#{klass.name}##{key} kept a secret set to null"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/lib/spree/api/preference_types_spec.rb b/spree/api/spec/lib/spree/api/preference_types_spec.rb
new file mode 100644
index 0000000000..df4e283ec2
--- /dev/null
+++ b/spree/api/spec/lib/spree/api/preference_types_spec.rb
@@ -0,0 +1,32 @@
+require 'spec_helper'
+require Spree::Api::Engine.root.join('lib/spree/api/preference_types').to_s
+
+RSpec.describe Spree::Api::PreferenceTypes do
+ subject(:generator) { described_class.new }
+
+ let(:monorepo_root) { Spree::Api::Engine.root.join('../..') }
+
+ it 'matches the committed SDK files (run `bundle exec rake typelizer:generate` to refresh them)' do
+ generator.render.each do |path, source|
+ expect(monorepo_root.join(path).read).to eq(source), "#{path} is out of date with the preference declarations"
+ end
+ end
+
+ it 'types each subtype of a family and keys the map by its wire type' do
+ source = generator.render.fetch('packages/admin-sdk/src/types/preferences.ts')
+
+ expect(source).to include(
+ "export interface PromotionRuleItemTotalPreferences {\n /** An amount, as an exact decimal string. */\n amount_min: string\n"
+ )
+ expect(source).to include(" item_total: PromotionRuleItemTotalPreferences\n")
+ expect(source).to include(" match_policy: 'any' | 'all' | 'none'\n")
+ expect(source).to include("export type TypedPromotionRule = Narrowed<PromotionRule, PromotionRulePreferencesMap>\n")
+ end
+
+ it 'gives the seller panel only the families a seller writes' do
+ source = generator.render.fetch('packages/seller-sdk/src/types/preferences.ts')
+
+ expect(source).to include('export interface DeliveryMethodRulePreferencesMap')
+ expect(source).not_to include('PromotionRule')
+ end
+end
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/order_routing_rule_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/order_routing_rule_serializer_spec.rb
index f311ed9b68..cb2725c8ee 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/order_routing_rule_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/order_routing_rule_serializer_spec.rb
@@ -20,7 +20,7 @@ RSpec.describe Spree::Api::V3::Admin::OrderRoutingRuleSerializer do
expect(payload).not_to have_key('label')
expect(payload).not_to have_key('description')
expect(payload['preferences']).to eq({})
- expect(payload['preference_schema']).to eq([])
+ expect(payload).not_to have_key('preference_schema')
expect(payload['created_at']).to be_present
expect(payload['updated_at']).to be_present
end
@@ -35,6 +35,7 @@ RSpec.describe Spree::Api::V3::Admin::OrderRoutingRuleSerializer do
stubbed_schema = [{ key: :api_secret, type: :password, default: nil }]
allow(r.class).to receive(:preference_schema).and_return(stubbed_schema)
+ allow(r.class).to receive(:preference_definitions).and_return(r.class.preference_definitions.merge(api_secret: { type: :password }))
end
end
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/payment_method_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/payment_method_serializer_spec.rb
index 75abaea2bb..4d63e9fa0b 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/payment_method_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/payment_method_serializer_spec.rb
@@ -30,24 +30,12 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodSerializer do
end
# Bogus declares `preference :dummy_secret_key, :password, default: 'SECRETKEY123'`.
- # A non-empty default on a password preference is itself a secret —
- # `serialized_preference_schema` must nil it out before it hits the wire.
- it 'redacts password defaults in preference_schema' do
- password_field = payload['preference_schema'].find { |f| f[:key] == :dummy_secret_key }
- expect(password_field).not_to be_nil
- expect(password_field[:default]).to be_nil
+ # A non-empty default on a password preference is itself a secret. Rows
+ # carry no schema at all — it lives on `/payment_methods/types`.
+ it 'carries no preference schema, so no secret default reaches the wire' do
+ expect(payload).not_to have_key('preference_schema')
expect(payload.to_json).not_to include('SECRETKEY123')
end
-
- # `:key_string` is an internal cache used by `Masking.serialize` to
- # avoid `to_s` allocations per request. It must not leak into the
- # wire payload — the documented shape is `{ key, type, default }`.
- it 'does not expose the internal :key_string cache in preference_schema entries' do
- expect(payload['preference_schema']).to all(have_key(:key))
- expect(payload['preference_schema']).to all(have_key(:type))
- expect(payload['preference_schema']).to all(have_key(:default))
- expect(payload['preference_schema']).not_to include(have_key(:key_string))
- end
end
describe 'third_party' do
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb
index 5deab3a19e..74c8a64e20 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/promotion_action_serializer_spec.rb
@@ -22,6 +22,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionActionSerializer do
{ key: :webhook_url, type: :string, default: nil }
]
allow(action.class).to receive(:preference_schema).and_return(stubbed_schema)
+ allow(action.class).to receive(:preference_definitions).and_return(action.class.preference_definitions.merge(api_secret: { type: :password }, webhook_url: { type: :string }))
action
end
@@ -57,6 +58,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionActionSerializer do
{ key: :amount, type: :decimal, default: 0 }
]
allow(action.calculator.class).to receive(:preference_schema).and_return(stubbed_schema)
+ allow(action.calculator.class).to receive(:preference_definitions).and_return(action.calculator.class.preference_definitions.merge(api_secret: { type: :password }))
end
# The `calculator` attribute is a plain Ruby Hash returned from an
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb
index a938904e01..e4d9c4b144 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb
@@ -21,6 +21,7 @@ RSpec.describe Spree::Api::V3::Admin::PromotionRuleSerializer do
{ key: :api_secret, type: :password, default: nil }
]
allow(rule.class).to receive(:preference_schema).and_return(stubbed_schema)
+ allow(rule.class).to receive(:preference_definitions).and_return(rule.class.preference_definitions.merge(api_secret: { type: :password }))
rule
end
diff --git a/spree/core/app/models/concerns/spree/calculated_adjustments.rb b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
index 94e2f3b893..0655c0e8a2 100644
--- a/spree/core/app/models/concerns/spree/calculated_adjustments.rb
+++ b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
@@ -31,10 +31,9 @@ module Spree
self.calculator = klass.new if klass && !calculator.instance_of?(klass)
end
- # API v3 writer for the flat `calculator: { type:, preferences: {} }`
- # payload. Routes preferences through `set_preference` so values are
- # coerced by the typed `preferred_<name>=` setters — direct
- # assignment to the serialized hash would skip coercion.
+ # API v3 writer for the `calculator: { type:, preferences: {} }`
+ # payload. Preferences are checked against the calculator's schema and
+ # written through its typed writers.
def assign_calculator_attributes(attrs)
return if attrs.nil?
@@ -43,11 +42,7 @@ module Spree
return if calculator.nil? || attrs[:preferences].blank?
- attrs[:preferences].to_h.each do |key, value|
- next unless calculator.has_preference?(key.to_sym)
-
- calculator.set_preference(key.to_sym, value)
- end
+ calculator.assign_preferences(attrs[:preferences])
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 a31f5b0881..1555797406 100644
--- a/spree/core/app/models/concerns/spree/preference_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema.rb
@@ -50,29 +50,40 @@ module Spree
# runtime. Each entry also caches `key_string` (frozen) so hot-path
# serializers don't allocate `pref.to_s` per request.
def preference_schema
- @preference_schema ||= compute_preference_schema
+ return @preference_schema if @preference_schema
- # An empty list to callers either way; only the memo tells the two
- # apart, so a schema that could not be computed is retried rather than
- # settled on.
- @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?
+ fields, complete = compute_preference_schema
+ # Settled on only when every default could be read; one computed
+ # before the database was up is retried next time.
+ @preference_schema = fields if complete
+ fields
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.
+ # {#preference_schema}.
#
- # @return [Hash, nil]
+ # @return [Hash]
def preference_json_schema
- @preference_json_schema ||= Spree::PreferenceSchema::JsonSchema.for(self)
+ return @preference_json_schema if @preference_json_schema
+
+ schema = Spree::PreferenceSchema::JsonSchema.for(self)
+ @preference_json_schema = schema if @preference_schema
+ schema
+ end
+
+ # Checks a `preferences` payload against {#preference_json_schema}.
+ #
+ # @param values [Hash{String => Object}]
+ # @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?
+
+ @preference_schemer ||= JSONSchemer.schema(schema)
+ @preference_schemer.validate(values).map do |error|
+ { pointer: error['data_pointer'], message: error['error'] }
+ end
end
# Wire-safe variant of `preference_schema` with `:password`
@@ -114,24 +125,26 @@ module Spree
.freeze
end
+ # @return [Array(Array<Hash>, Boolean)] the fields, and whether their
+ # defaults could all be read
def compute_preference_schema
# Only instantiation is guarded. `new` touches the database to read
# the column list, so it fails whenever the schema is asked for before
- # a connection exists — at boot, or in a rake task on an empty
- # database. Describing the preferences themselves is pure Ruby, so an
- # error there is a real bug: left inside the rescue it would return an
- # empty schema and quietly strip every field from the admin form.
- # Nil rather than an empty list, so `preference_schema`'s `||=` asks
- # again next time. Memoizing the failure would leave a class describing
- # no preferences for the life of the process because it was first asked
- # before the database was up.
+ # a connection exists — at boot, in a rake task on an empty database,
+ # or while generating the SDK types. An uninitialized instance still
+ # describes every preference, since the declarations are pure Ruby;
+ # only a default read from the database is missing, so that result is
+ # not memoized. An error describing the preferences themselves is a
+ # real bug and is left to raise.
+ complete = true
instance = begin
new
rescue StandardError
- return nil
+ complete = false
+ allocate
end
- instance.defined_preferences.filter_map do |pref|
+ fields = instance.defined_preferences.filter_map do |pref|
next if instance.preference_deprecated(pref)
# Written by Spree, not supplied by the operator — a value a
# provider hands back after we register something with it. Offering
@@ -147,6 +160,7 @@ module Spree
choices: instance.preference_choices(pref)
}.compact.freeze
end
+ [fields, complete]
end
# Builds a `parse_on_set:` lambda for `preference :foo_ids, :array`
@@ -202,11 +216,10 @@ module Spree
registered_subclasses.find { |klass| klass.api_type == shorthand.to_s }
end
- # Returns a `[{ type:, label:, description:, preference_schema: }]`
- # array for every concrete subclass in `subclasses`. Sorted by label
- # for stable output. Uses `serialized_preference_schema` so
- # `:password` defaults are redacted — `/types` is an unauthenticated
- # discovery surface and must never leak gateway-shipped defaults.
+ # Returns a `[{ type:, label:, description:, schema: }]` array for every
+ # registered subclass, sorted by label for stable output. `schema` is
+ # the JSON Schema of the subclass's `preferences`, which never carries a
+ # secret's default.
#
# `label` and `description` are a fallback, not the admin UI's copy:
# they resolve in the request's locale, which is the store's rather
@@ -223,7 +236,7 @@ module Spree
# Asking for only one left promotion types with a null description
# and no fallback for a client without its own translation.
description: subclass_description(klass),
- preference_schema: klass.respond_to?(:serialized_preference_schema) ? klass.serialized_preference_schema : []
+ schema: klass.preference_json_schema
}
# Only present when true, so families without the concept keep
# their wire shape byte-identical. Pickers stop offering a
diff --git a/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb b/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb
index 0406756d41..68a0219623 100644
--- a/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema/json_schema.rb
@@ -19,28 +19,34 @@ module Spree
}.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)
+ # @return [Hash] a JSON Schema object (string keys)
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]))] }
+ properties = fields.to_h do |field|
+ [field[:key].to_s, property_schema(definitions.fetch(field[:key]), default: field[:default])]
+ end
{ 'type' => 'object', 'properties' => properties, 'additionalProperties' => false }
end
- def self.property(field, definition)
+ # The schema of one declared preference.
+ #
+ # @param definition [Hash] an entry of `preference_definitions`
+ # @param default [Object] the declared default, already evaluated
+ # @return [Hash]
+ def self.property_schema(definition, default: declared_default(definition))
schema = value_schema(definition)
- choices = field[:choices]
+ choices = definition[:choices]
+ choices = choices.call if choices.respond_to?(:call)
schema['enum'] = choices.map { |choice| choice.is_a?(Symbol) ? choice.to_s : choice } if choices.present?
- default = wire_default(field[:default], definition)
+ default = definition[:dynamic_default] ? nil : wire_default(default, definition)
+ unset_reads_null = default.nil? && !definition[:dynamic_default]
# 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']
+ if (definition[:nullable] || unset_reads_null || definition[:type] == :password) && schema['type']
schema['type'] = [schema['type'], 'null']
schema['enum'] += [nil] if schema['enum']
end
@@ -49,6 +55,14 @@ module Spree
schema
end
+ # A default can be a block that reads the database (the default store's
+ # currency); one that cannot be read here is left out.
+ def self.declared_default(definition)
+ definition[:default].call
+ rescue StandardError
+ nil
+ end
+
def self.value_schema(definition)
case definition[:type]
when :string then string_schema(definition[:format])
@@ -105,7 +119,7 @@ module Spree
default.as_json
end
- private_class_method :property, :value_schema, :item_schema, :string_schema, :wire_default
+ private_class_method :declared_default, :value_schema, :item_schema, :string_schema, :wire_default
end
end
end
diff --git a/spree/core/app/models/concerns/spree/typed_associations.rb b/spree/core/app/models/concerns/spree/typed_associations.rb
index 57febe3769..7544702f94 100644
--- a/spree/core/app/models/concerns/spree/typed_associations.rb
+++ b/spree/core/app/models/concerns/spree/typed_associations.rb
@@ -78,11 +78,7 @@ 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?
- preferences&.each do |key, value|
- next unless record.has_preference?(key.to_sym)
-
- record.set_preference(key.to_sym, value)
- end
+ record.assign_preferences(preferences) if preferences
record.assign_calculator_attributes(calculator) if calculator.present? && record.respond_to?(:assign_calculator_attributes)
# Always save — `record.changed?` doesn't reflect preferences
diff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rb
index 2b2a7033a8..27cf52b72c 100644
--- a/spree/core/app/models/spree/channel.rb
+++ b/spree/core/app/models/spree/channel.rb
@@ -16,6 +16,7 @@ module Spree
# Empty -> falls back to the Store-level preference.
preference :order_routing_strategy, :string, default: nil,
parse_on_set: ->(value) { Spree::ApiTyped.class_name_for(Spree.order_routing.strategies, value) }
+ exposes_preferences :order_routing_strategy
has_many :orders, class_name: 'Spree::Order', inverse_of: :channel, dependent: :nullify
diff --git a/spree/core/app/models/spree/channel/gating.rb b/spree/core/app/models/spree/channel/gating.rb
index 49a526dec6..1d18b26cc0 100644
--- a/spree/core/app/models/spree/channel/gating.rb
+++ b/spree/core/app/models/spree/channel/gating.rb
@@ -19,6 +19,7 @@ module Spree
# false, while an explicit value remains a channel override.
preference :storefront_access, :string, default: nil, nullable: true, choices: STOREFRONT_ACCESS
preference :guest_checkout, :boolean, default: nil, nullable: true
+ exposes_preferences :storefront_access, :guest_checkout
validate :storefront_access_must_be_valid
end
diff --git a/spree/core/app/models/spree/commission_rate.rb b/spree/core/app/models/spree/commission_rate.rb
index 41c99c4d10..e500c1c9aa 100644
--- a/spree/core/app/models/spree/commission_rate.rb
+++ b/spree/core/app/models/spree/commission_rate.rb
@@ -247,7 +247,7 @@ module Spree
# shape a price list's rules use.
#
# Ids inside a rule's preferences are scope-checked against this rate's own
- # store as they are written (see normalize_id_preference), so a rule can
+ # store as they are written (see `of: :id, scope:`), so a rule can
# never be pointed at another marketplace's records.
#
# @param rows [Array<Hash>, nil]
diff --git a/spree/core/app/models/spree/import.rb b/spree/core/app/models/spree/import.rb
index 756d0d80e0..c258a8e254 100644
--- a/spree/core/app/models/spree/import.rb
+++ b/spree/core/app/models/spree/import.rb
@@ -87,6 +87,7 @@ module Spree
# Preferences
#
preference :delimiter, :string, default: ','
+ exposes_preferences :delimiter
# Run the pipeline in-process instead of enqueuing it. For rake tasks, seeds
# and the console, where the caller needs the data to exist when the call
# returns and there may be no worker attached. Never set it from a request:
diff --git a/spree/core/app/models/spree/integration.rb b/spree/core/app/models/spree/integration.rb
index e780a0928b..892da325a4 100644
--- a/spree/core/app/models/spree/integration.rb
+++ b/spree/core/app/models/spree/integration.rb
@@ -98,7 +98,7 @@ module Spree
group: klass.integration_group,
description: klass.human_description,
**klass.provider_listing,
- preference_schema: klass.serialized_preference_schema
+ schema: klass.preference_json_schema
}
end.sort_by { |entry| entry[:name] }
end
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rb
index 74609d8fb7..77985cd834 100644
--- a/spree/core/app/models/spree/seller.rb
+++ b/spree/core/app/models/spree/seller.rb
@@ -340,7 +340,7 @@ module Spree
# A seller keeps no clock of their own: a date means whatever the
# marketplace says it means, so their panel reads timestamps in the
# store's zone rather than in whichever one their browser sits in.
- delegate :preferred_timezone, to: :store, allow_nil: true
+ delegate :preferred_timezone, :timezone, to: :store, allow_nil: true
# Sellers holding an account with one provider, for the reverse lookup a
# provider webhook does — it knows the account, not the seller.
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index d3bbf2878c..0bb8cea2b8 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -169,6 +169,22 @@ module Spree
preference :order_number_suffix, :string, default: ''
preference :order_number_sequence_start, :integer, default: 1001
+ # The settings the API reads and writes under their plain names.
+ exposes_preferences :admin_locale, :timezone, :storefront_url, :weight_unit, :unit_system, :storefront_access, :guest_checkout,
+ :always_include_confirm_step, :company_field_enabled, :address_requires_company,
+ :address_requires_phone, :capture_method, :track_inventory_levels, :stock_reservations_enabled,
+ :low_stock_threshold, :tax_using_ship_address, :track_price_history,
+ :show_products_without_price, :disable_sku_validation, :order_routing_strategy,
+ :pricing_provider, :inventory_provider, :pricing_provider_failure_policy,
+ :inventory_provider_failure_policy, :payout_provider, :default_payouts_schedule_interval,
+ :default_minimum_payout_amount, :auto_approve_sellers, :auto_approve_seller_products,
+ :send_seller_transactional_emails, :default_commission_tax_rate, :document_number_format,
+ :order_number_prefix, :order_number_suffix, :order_number_sequence_start,
+ :limit_digital_download_count, :digital_asset_authorized_clicks,
+ :limit_digital_download_days, :digital_asset_authorized_days,
+ :send_consumer_transactional_emails, :email_accent_color, :email_background_color,
+ :email_card_color, :email_text_color, :email_heading_color, :email_font
+
#
# Associations
#
@@ -529,6 +545,7 @@ module Spree
end
# Returns the storefront origin URL for use in customer-facing emails and links.
+ # Replaces the plain `storefront_url` reader `exposes_preferences` defines.
# Uses the `storefront_url` preference when set, then the oldest non-loopback
# allowed origin (the `http://localhost` origin seeded on install must never
# leak into customer emails), otherwise falls back to formatted_url.
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 585101b9e8..b12297de82 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -650,6 +650,7 @@ require 'spree/core/controller_helpers/store'
require 'spree/core/preferences/runtime_configuration'
require 'spree/core/preferences/masking'
+require 'spree/core/preferences/invalid_preferences'
require 'spree/core/preferences/json_conversion'
require 'spree/core/permission_configuration'
diff --git a/spree/core/lib/spree/core/preferences/invalid_preferences.rb b/spree/core/lib/spree/core/preferences/invalid_preferences.rb
new file mode 100644
index 0000000000..2e55c9a4e2
--- /dev/null
+++ b/spree/core/lib/spree/core/preferences/invalid_preferences.rb
@@ -0,0 +1,17 @@
+module Spree
+ module Preferences
+ # Raised when a `preferences` payload does not match the schema its type
+ # declares. Each failure names the value by a JSON pointer into the
+ # payload, so a client can show it next to the field it belongs to.
+ class InvalidPreferences < StandardError
+ # @return [Array<Hash{Symbol => String}>] `{ pointer:, message: }` per failure
+ 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]}") }
+ super(@failures.map { |failure| "#{failure[:pointer]}: #{failure[:message]}" }.join('; '))
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/preferences/preferable.rb b/spree/core/lib/spree/core/preferences/preferable.rb
index 9865ea7711..d8e2e1060b 100644
--- a/spree/core/lib/spree/core/preferences/preferable.rb
+++ b/spree/core/lib/spree/core/preferences/preferable.rb
@@ -153,6 +153,31 @@ module Spree::Preferences::Preferable
clear_attribute_change(:preferences) if persisted? && !already_changed
end
+ # Writes a `preferences` payload an API client sent. The whole payload is
+ # checked against the type's schema first, so nothing is written when any
+ # value is wrong. Then each value goes through its typed writer. A secret
+ # sent back masked, as it was read, keeps the stored one; `null` clears it.
+ #
+ # @param values [Hash, ActionController::Parameters]
+ # @raise [Spree::Preferences::InvalidPreferences] naming every value that does not match
+ # @return [void]
+ def assign_preferences(values)
+ values = values.respond_to?(:to_unsafe_h) ? values.to_unsafe_h : values.to_h
+ values = values.deep_stringify_keys
+ failures = self.class.preference_failures(values)
+ raise Spree::Preferences::InvalidPreferences, failures if failures.any?
+
+ values.each do |key, value|
+ next if secret_preference?(key) && Spree::Preferences::Masking.masked?(value)
+
+ begin
+ set_preference(key, value)
+ rescue ActiveRecord::RecordNotFound => e
+ raise Spree::Preferences::InvalidPreferences, [{ pointer: "/#{key}", message: e.message }]
+ end
+ end
+ end
+
# Names of the preferences the last save changed, secrets included.
#
# @return [Array<Symbol>]
diff --git a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb b/spree/core/lib/spree/core/preferences/preferable_class_methods.rb
index ea21b4b1ca..136ab5fc80 100644
--- a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb
+++ b/spree/core/lib/spree/core/preferences/preferable_class_methods.rb
@@ -90,10 +90,14 @@ module Spree::Preferences
check_preference_declaration(name, type, options)
default = options[:default]
- default = -> { options[:default] } unless default.is_a?(Proc)
+ dynamic_default = default.is_a?(Proc)
+ default = -> { options[:default] } unless dynamic_default
own_preference_definitions[name] = {
type: type,
default: default,
+ # Computed when read (the default store's currency, say), so it
+ # differs between stores and is not part of the preference's schema.
+ dynamic_default: dynamic_default,
deprecated: options[:deprecated],
# Whether the system writes the value rather than the operator — a
# value a provider hands back, kept out of every admin form.
@@ -146,9 +150,20 @@ module Spree::Preferences
define_method(name) { public_send(:"preferred_#{name}") }
define_method(:"#{name}=") { |value| public_send(:"preferred_#{name}=", value) }
+ own_exposed_preference_names << name
end
end
+ # Whether the preference is read and written under its plain name, so an
+ # error on `preferred_<name>` can be reported as `<name>`.
+ #
+ # @param name [Symbol, String]
+ # @return [Boolean]
+ def exposed_preference?(name)
+ own_exposed_preference_names.include?(name.to_sym) ||
+ (superclass.respond_to?(:exposed_preference?) && superclass.exposed_preference?(name))
+ end
+
private
# A declaration is the preference's contract on the wire. One Spree ships
@@ -184,6 +199,10 @@ module Spree::Preferences
)
end
+ def own_exposed_preference_names
+ @own_exposed_preference_names ||= Set.new
+ end
+
def own_preference_definitions
@own_preference_definitions ||= {}
end
diff --git a/spree/core/spec/models/spree/commission_rate_spec.rb b/spree/core/spec/models/spree/commission_rate_spec.rb
index 891809904a..509325105b 100644
--- a/spree/core/spec/models/spree/commission_rate_spec.rb
+++ b/spree/core/spec/models/spree/commission_rate_spec.rb
@@ -321,7 +321,7 @@ RSpec.describe Spree::CommissionRate, type: :model do
rate = create(:commission_rate, store: store)
create(:commission_seller_rule, commission_rate: rate, sellers: [seller])
- rate.update!(rules: [{ type: 'category_rule', preferences: { category_ids: [category.id] } }])
+ rate.update!(rules: [{ type: 'category_rule', preferences: { category_ids: [category.prefixed_id] } }])
expect(rate.reload.commission_rules.map(&:class)).to eq([Spree::CommissionRules::CategoryRule])
expect(rate.commission_rules.first.preferred_category_ids.map(&:to_s)).to eq([category.id.to_s])
@@ -334,9 +334,9 @@ RSpec.describe Spree::CommissionRate, type: :model do
rate = create(:commission_rate, store: store)
first_seller = create(:seller, store: store)
second_seller = create(:seller, store: store)
- rate.update!(rules: [{ type: 'seller_rule', preferences: { seller_ids: [first_seller.id] } }])
+ rate.update!(rules: [{ type: 'seller_rule', preferences: { seller_ids: [first_seller.prefixed_id] } }])
- rate.update!(rules: [{ type: 'seller_rule', preferences: { seller_ids: [second_seller.id] } }])
+ rate.update!(rules: [{ type: 'seller_rule', preferences: { seller_ids: [second_seller.prefixed_id] } }])
expect(rate.reload.commission_rules.count).to eq(1)
expect(rate.commission_rules.first.preferred_seller_ids.map(&:to_s)).to eq([second_seller.id.to_s])
@@ -359,13 +359,13 @@ RSpec.describe Spree::CommissionRate, type: :model do
foreign_seller = create(:seller, store: create(:store))
expect {
- rate.update!(rules: [{ type: 'seller_rule', preferences: { seller_ids: [foreign_seller.id] } }])
- }.to raise_error(ActiveRecord::RecordNotFound)
+ rate.update!(rules: [{ type: 'seller_rule', preferences: { seller_ids: [foreign_seller.prefixed_id] } }])
+ }.to raise_error(Spree::Preferences::InvalidPreferences, %r{/preferences/seller_ids})
end
it 'builds rules on a rate that does not exist yet' do
rate = create(:commission_rate, store: store,
- rules: [{ type: 'seller_rule', preferences: { seller_ids: [seller.id] } }])
+ rules: [{ type: 'seller_rule', preferences: { seller_ids: [seller.prefixed_id] } }])
expect(rate.reload.commission_rules.map(&:class)).to eq([Spree::CommissionRules::SellerRule])
end
diff --git a/spree/core/spec/models/spree/preferences/preferable_spec.rb b/spree/core/spec/models/spree/preferences/preferable_spec.rb
index 23893f0205..d440630c61 100644
--- a/spree/core/spec/models/spree/preferences/preferable_spec.rb
+++ b/spree/core/spec/models/spree/preferences/preferable_spec.rb
@@ -488,6 +488,34 @@ describe Spree::Preferences::Preferable, type: :model do
expect { preferable_class.preference :unknown_item, :array, of: :thing }.to raise_error(ArgumentError, /Unknown item type/)
end
+ describe '#assign_preferences' do
+ it 'writes a payload that matches the schema' do
+ record.assign_preferences('quantities' => [1, 2], 'channel_ids' => [channel.prefixed_id])
+
+ expect(record.preferred_quantities).to eq([1, 2])
+ expect(record.preferences[:channel_ids]).to eq([channel.id.to_s])
+ end
+
+ it 'refuses the whole payload, naming each failing value, when any value does not match' do
+ expect { record.assign_preferences('flavor' => 'mint', 'quantities' => ['many'], 'colour' => 'red') }.to raise_error(
+ Spree::Preferences::InvalidPreferences
+ ) { |error| expect(error.failures.pluck(:pointer)).to contain_exactly('/preferences/quantities/0', '/preferences/colour') }
+ expect(record.preferred_flavor).to eq('vanilla')
+ end
+
+ it 'refuses an id of another model by its prefix' do
+ expect { record.assign_preferences('channel_ids' => ["mkt_#{Spree::PrefixedId::SQIDS.encode([channel.id])}"]) }
+ .to raise_error(Spree::Preferences::InvalidPreferences, %r{/preferences/channel_ids/0})
+ end
+
+ it 'refuses an id outside the declared scope' do
+ other_channel = create(:channel, store: create(:store))
+
+ expect { record.assign_preferences('channel_ids' => [other_channel.prefixed_id]) }
+ .to raise_error(Spree::Preferences::InvalidPreferences, %r{/preferences/channel_ids})
+ end
+ 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: []