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.

Fix: Store API and SDK regressions for 5.6 storefronts (#14889)

Damian Legawiec685bc8766f20
diff --git a/docs/api-reference/store.yaml b/docs/api-reference/store.yaml
index c8e20e931d..b657095a20 100644
--- a/docs/api-reference/store.yaml
+++ b/docs/api-reference/store.yaml
@@ -1125,6 +1125,8 @@ paths:
currency: USD
amount: '19.99'
compare_at_amount:
+ amount_in_cents: 1999
+ compare_at_amount_in_cents:
display_amount: "$19.99"
display_compare_at_amount:
price_list_id:
@@ -1412,6 +1414,8 @@ paths:
currency: USD
amount: '19.99'
compare_at_amount:
+ amount_in_cents: 1999
+ compare_at_amount_in_cents:
display_amount: "$19.99"
display_compare_at_amount:
price_list_id:
@@ -1451,6 +1455,8 @@ paths:
currency: USD
amount: '19.99'
compare_at_amount:
+ amount_in_cents: 1999
+ compare_at_amount_in_cents:
display_amount: "$19.99"
display_compare_at_amount:
price_list_id:
@@ -1570,6 +1576,8 @@ paths:
currency: USD
amount: '19.99'
compare_at_amount:
+ amount_in_cents: 1999
+ compare_at_amount_in_cents:
display_amount: "$19.99"
display_compare_at_amount:
price_list_id:
@@ -1579,6 +1587,7 @@ paths:
id: _AXs1igzRC6
currency: USD
amount: '9.99'
+ amount_in_cents: 999
display_amount: "$9.99"
recorded_at: '2025-12-31T12:00:00Z'
schema:
@@ -2227,7 +2236,7 @@ paths:
message: Shipping address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -2348,7 +2357,7 @@ paths:
message: Shipping address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -2880,7 +2889,7 @@ paths:
message: Email address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -3104,7 +3113,7 @@ paths:
requirements:
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -3663,7 +3672,7 @@ paths:
message: Email address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -3858,7 +3867,7 @@ paths:
message: Email address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -4371,7 +4380,7 @@ paths:
message: Email address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
order_minimum:
order_minimum_shortfall:
@@ -4611,7 +4620,7 @@ paths:
message: Email address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -4803,7 +4812,7 @@ paths:
message: Email address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -5050,7 +5059,7 @@ paths:
message: Email address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -5862,7 +5871,7 @@ paths:
message: Email address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
order_minimum:
order_minimum_shortfall:
@@ -6043,7 +6052,7 @@ paths:
message: Email address is required
- code: delivery_method_required
step: delivery
- field: delivery_method
+ field: shipping_method
message: Select a delivery method for all fulfillments
- code: payment_required
step: payment
@@ -10817,6 +10826,8 @@ paths:
currency: USD
amount: '19.99'
compare_at_amount:
+ amount_in_cents: 1999
+ compare_at_amount_in_cents:
display_amount: "$19.99"
display_compare_at_amount:
price_list_id:
@@ -10901,6 +10912,8 @@ paths:
currency: USD
amount: '19.99'
compare_at_amount:
+ amount_in_cents: 1999
+ compare_at_amount_in_cents:
display_amount: "$19.99"
display_compare_at_amount:
price_list_id:
@@ -20589,6 +20602,10 @@ components:
amount:
type: string
nullable: true
+ amount_in_cents:
+ type: number
+ nullable: true
+ deprecated: true
display_amount:
type: string
description: "`amount` formatted with its currency symbol in the request's
@@ -20600,6 +20617,7 @@ components:
- id
- currency
- amount
+ - amount_in_cents
- display_amount
- recorded_at
x-typelizer: true
@@ -20796,6 +20814,14 @@ components:
compare_at_amount:
type: string
nullable: true
+ amount_in_cents:
+ type: number
+ nullable: true
+ deprecated: true
+ compare_at_amount_in_cents:
+ type: number
+ nullable: true
+ deprecated: true
display_amount:
type: string
nullable: true
@@ -20816,6 +20842,8 @@ components:
- currency
- amount
- compare_at_amount
+ - amount_in_cents
+ - compare_at_amount_in_cents
- display_amount
- display_compare_at_amount
- price_list_id
@@ -23414,6 +23442,10 @@ components:
state_name:
type: string
description: The state name, for countries without predefined states.
+ quick_checkout:
+ type: boolean
+ description: Relaxes validation (name, phone, postal code, street), for
+ express checkouts that share a partial address.
country_iso:
type: string
description: 'Deprecated: Use `country_code`. Removed in 6.1.'
@@ -23466,6 +23498,10 @@ components:
state_name:
type: string
description: The state name, for countries without predefined states.
+ quick_checkout:
+ type: boolean
+ description: Relaxes validation (name, phone, postal code, street), for
+ express checkouts that share a partial address.
country_iso:
type: string
description: 'Deprecated: Use `country_code`. Removed in 6.1.'
@@ -23505,7 +23541,8 @@ components:
type: string
format: decimal
pattern: "^-?\\d+(\\.\\d+)?$"
- description: Defaults to as much as the cart can use.
+ description: Defaults to as much as the cart can use. A JSON number is still
+ read until 6.1, with a deprecation warning.
example: '10.00'
CartAddressParams:
type: object
@@ -23543,6 +23580,10 @@ components:
state_name:
type: string
description: The state name, for countries without predefined states.
+ quick_checkout:
+ type: boolean
+ description: Relaxes validation (name, phone, postal code, street), for
+ express checkouts that share a partial address.
country_iso:
type: string
description: 'Deprecated: Use `country_code`. Removed in 6.1.'
@@ -23551,10 +23592,6 @@ components:
type: string
description: 'Deprecated: Use `state_code`. Removed in 6.1.'
deprecated: true
- quick_checkout:
- type: boolean
- description: Relaxes validation (name, phone, postal code, street), for
- express checkouts that share a partial address.
CompanyAddressCreateParams:
type: object
properties:
diff --git a/docs/developer/core-concepts/pricing.mdx b/docs/developer/core-concepts/pricing.mdx
index d124038784..2c785dd389 100644
--- a/docs/developer/core-concepts/pricing.mdx
+++ b/docs/developer/core-concepts/pricing.mdx
@@ -297,7 +297,6 @@ The response includes a `prior_price` object when expanded:
"price": { "amount": "15.99", "currency": "USD", "display_amount": "$15.99" },
"prior_price": {
"amount": "9.99",
- "amount_in_cents": 999,
"currency": "USD",
"display_amount": "$9.99",
"recorded_at": "2026-03-10T14:30:00Z"
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index 5bd0d484c6..d60482df28 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -316,7 +316,7 @@ Spree::Checkout::Registry.add_requirement(
The requirement appears in the Cart API's `requirements` array (so a storefront rendering the feed generically needs zero changes) *and* blocks completion. `register_step` adds whole steps (spliced into `checkout_steps` at `before:`/`after:` anchors); built-in steps are customized through `Registry.base_steps` — an ordered `{ name => applicability }` hash you can mutate directly (`base_steps.delete('confirm')`).
- **The API `requirements` array now carries a stable `code`** on every entry (`email_required`, `out_of_stock`, `guest_checkout_not_allowed`, ...). Additive change — existing consumers keep working.
-- **The delivery requirement is keyed `delivery_method`, not `shipping_method`.** Its entry is now `{ step: 'delivery', field: 'delivery_method', code: 'delivery_method_required' }`. A storefront that renders the feed generically needs no change; one that keys off the field or code to highlight a specific input must switch both tokens. The `spree.checkout_requirements.shipping_method_required` translation key was renamed to `spree.checkout_requirements.delivery_method_required` — override it under the new key.
+- **The delivery requirement is keyed by its `code`, `delivery_method_required`.** Its entry is `{ step: 'delivery', field: 'shipping_method', code: 'delivery_method_required' }`. The `field` keeps its 5.6 name until 6.1, when it becomes `delivery_method`, so a 5.6 storefront that matches the field keeps working. Match the `code` instead, which does not change. The `spree.checkout_requirements.shipping_method_required` translation key was renamed to `spree.checkout_requirements.delivery_method_required` — override it under the new key.
- **"Logic between steps" has no backend home by design.** Side effects hang off data writes (workflow hooks such as `Carts::Complete`'s `before_finalize` and `Carts::AddItem`'s `after_item_added`) and events (`cart.updated`, `order.placed`) — not step transitions.
## Statuses: derived, then persisted
@@ -915,7 +915,7 @@ Other changes that come with it:
- **The Admin and Seller APIs no longer return `display_*` money fields.** Responses carry the amount (`"29.99"`) with its currency, and the client formats it in the reader's own language. Before 6.0 the server formatted a copy in the request's language, which could disagree with the editable amount beside it. Format with `Intl.NumberFormat` or your platform's equivalent. The Store API and webhook payloads keep their `display_*` money fields until 6.1, marked deprecated in the API reference and the SDK types; format the amount beside each one instead (`total` for `display_total`). Labels such as `display_name` are unchanged.
- **Money preferences have their own type.** Calculator, rule and store preferences holding an amount (`amount`, `first_item`, `minimal_amount`, `amount_min`, `min_amount`, `default_minimum_payout_amount` and the like) are declared `:money` instead of `:decimal`, report `money` in `preference_schema`, and are written with the decimals of the calculator's currency (`"12.50"` rather than `"12.5"`). Declare your own extensions' amounts with `:money` so the dashboard shows their currency. A `:decimal` or `:money` preference now refuses text such as `"1,599.99"` instead of reading it as 1. Money preferences are checked by their type on write: a value that is not a decimal string, or has more decimals than its currency, is refused with `invalid_preferences` and a pointer to the field (`/calculator/preferences/amount`), rather than `invalid_money_format`.
- **Rates are decimal strings, and tax rates are renamed.** Rates and percentages read and write as strings without trailing zeros. A tax rate's `amount` (a fraction) is now `rate`, and `amount_percentage` is `rate_percent`; `Spree::TaxRate#amount_percentage` keeps working with a warning until 6.1.
-- **`amount_in_cents` and `compare_at_amount_in_cents` are removed** from prices and price history. Read `amount`, and each currency's `decimal_places` (new on `GET /api/v3/store/currencies`) if you need minor units.
+- **`amount_in_cents` and `compare_at_amount_in_cents` are deprecated** on Store API prices and price history, and removed in 6.1. They still hold the amount in hundredths, which is wrong for currencies without two decimals. Read `amount`, and each currency's `decimal_places` (new on `GET /api/v3/store/currencies`) if you need minor units. The Admin and Seller APIs no longer return them.
- **Money columns widen to `decimal(19,4)`.** They now hold a Kuwaiti dinar's third decimal, unit prices below a cent (`0.0125`), and very large amounts in currencies like the Vietnamese dong. No stored value changes. Totals, payments and refunds are still rounded to the currency's decimals; only unit prices (`price`, `compare_at_amount`, `cost_price`, `unit_cost`) keep up to four. The migration rewrites each money table while it runs, which locks `spree_orders`, `spree_line_items` and `spree_adjustments` for as long as that takes. If you cannot take that lock, widen those columns online first (add a `decimal(19,4)` shadow column, backfill it in batches, swap it in), and the migration skips any column already at `(19,4)`. Extensions with their own money tables, such as `spree_stripe_payment_intents` from the standalone Stripe gem, should widen theirs the same way.
- **Payment gateways receive the amount with its currency.** `authorize`, `purchase`, `capture` and `credit` are called with a `Spree::Money` (amount and currency) instead of an integer in hundredths, which was wrong for yen and dinar. A gateway opts in with `self.accepts_money_amounts = true` and converts the amount to its provider's unit (Stripe's rules live in `SpreeStripe::Units`). A gateway that has not opted in still receives hundredths, with a deprecation warning, until 6.1. `Spree.payment_capture_workflow.call(amount:)` takes the amount in the currency's own units; an Integer is still read as hundredths, with a warning.
- **Stripe refuses amounts it cannot take.** Stripe charges three-decimal currencies (Bahraini, Jordanian, Kuwaiti and Omani dinar, Tunisian dinar) only in steps of 0.010, and pays out Hungarian forint and New Taiwan dollars only in whole units. `spree_stripe` now raises a gateway error naming the rule, rather than rounding to a sum other than the one the order records.
@@ -995,7 +995,7 @@ Before 6.0 a cart was an incomplete order, so extensions written for 5.x (paymen
| `Order#remove_out_of_stock_items!` | cart-side only (`Spree::Carts::RemoveOutOfStockItems`) |
| `Order#delivery_required?` (Order and Cart) | `#delivery_step_required?` — digital and pickup are deliveries too; this asks whether the customer must choose a delivery option |
| `Order#requires_ship_address?` (Order and Cart) | `#shipping_address_required?` — decided by the selected delivery methods (`DeliveryMethod#requires_address?`); digital, pickup, and pickup-point deliveries need no customer address |
-| `requirements[].field` / `.code` `shipping_method` (Store API) | `delivery_method` / `delivery_method_required` — no bridge; clients keying off the delivery requirement must switch both tokens |
+| `requirements[].field` `shipping_method` (Store API) | `code` `delivery_method_required`; the field becomes `delivery_method` in 6.1 |
| `Cart#number` (Store API field) | `id` — carts have no order-style number; the field mirrors the prefixed ID for one release |
| `order.completed` event | `order.placed` |
| Calling cart services with `order:` kwargs | `cart:` kwargs |
@@ -1101,12 +1101,11 @@ A storefront built on the Store API and `@spree/sdk`, such as the [Spree storefr
| Type error mentions | Cause | Fix |
|---|---|---|
| `CountryCode` or `CurrencyCode` | Country and currency codes are typed | [Country and currency codes](#country-and-currency-codes-are-typed) |
-| `amount_in_cents`, `compare_at_amount_in_cents` | Removed from prices | Read `amount` ([Money](#money)) |
| `string \| null` where a price or amount is read | Money fields are `null` for guests when the store hides prices | [Money can be null](#money-can-be-null) |
| A property that "does not exist" in a `…Params` type | Request types now list exactly what the endpoint accepts | [Request types](#request-types-match-the-api) |
| `ProductSort`, or a filter key | List filters and sort are typed | [List filters and sort](#list-filters-and-sort-are-typed) |
| `number` is not assignable to `string` in a filter or amount | Money is a decimal string everywhere | Send `'20.00'`, not `20` ([Money](#money), [store credit](#store-credit-amounts-are-decimal-strings)) |
-| `name` or `description` "does not exist" on `Discount` | `Discount` now types the discount rows on items and fulfillments. The `discounts` list on carts and orders is unchanged and is typed `AppliedPromotion` | Import `AppliedPromotion` for `cart.discounts` and `order.discounts` |
+| `string` is not assignable to `number` where the price filter's range is read | The price range's `min` and `max` are decimal strings | [The price filter's range is text](#the-price-filters-range-is-text) |
| A property that "does not exist" on `OrderGroup` | Completing a cart, or reading an order by its cart id, can return an order group | [Completing a cart can return an order group](#completing-a-cart-can-return-an-order-group) |
### List filters and sort are typed
@@ -1197,7 +1196,45 @@ Every money field, including `display_*` amounts (a gift card's or store credit'
await client.carts.storeCredits.apply(cartId, '25.00', options) // not 25
```
-The endpoint (`POST /carts/:id/store_credits`) now refuses a JSON number with `422 invalid_money_format`, so a storefront that calls the API without the SDK must send a string too.
+Passing a number still works until 6.1: the SDK marks that form `@deprecated`, and the endpoint (`POST /carts/:id/store_credits`) reads a JSON number through its text and logs a deprecation warning. From 6.1 the endpoint refuses a number with `422 invalid_money_format`, so a storefront that calls the API without the SDK must send a string too.
+
+### The price filter's range is text
+
+The price filter that `products.filters()` returns gives its range as decimal strings, like every other amount: `{ min: '9.99', max: '120.00' }`, where 5.6 sent numbers (`9.99`). `PriceRangeFilter` types them as strings, so a price slider that does arithmetic on `min` and `max`, or passes them to a slider component that expects numbers, now fails to compile (the first 2.0 release candidates still typed them as numbers). Use the SDK's `compareMoney` and `subtractMoney` for exact comparisons, and convert to a number only where the slider component needs one, for display:
+
+```ts
+import type { PriceRangeFilter } from '@spree/sdk'
+
+const range = filters.find((filter): filter is PriceRangeFilter => filter.type === 'price_range')
+const slider = range && { min: Number(range.min), max: Number(range.max) } // display only
+```
+
+Send the chosen bounds back as strings (`price_gte: '20.00'`), not the slider's numbers.
+
+### Status values changed
+
+The statuses of fulfillments and the payment and fulfillment statuses of orders use new values. This is not a type error, because status types accept any string, so search your code for the old values.
+
+**A fulfillment's `status`, and an order's `fulfillment_status`:**
+
+| 5.6 | 6.0 |
+|---|---|
+| `pending`, `ready` | `unfulfilled` |
+| `shipped` | `fulfilled` |
+| `canceled` | `canceled` |
+| (new) | `delivered`, once the customer has the parcel |
+
+An order's `fulfillment_status` also keeps `partial` and `backorder`.
+
+**An order's `payment_status`** is worked out from the payments and refunds on the order, so an old value can become more than one new value:
+
+| 5.6 | 6.0 |
+|---|---|
+| `balance_due` | `none` (nothing paid), `authorized` (authorized, not yet captured) or `partially_paid` |
+| `paid` | `paid`, or `partially_refunded` / `refunded` when the order has refunds |
+| `credit_owed` | `overcharged` |
+| `void` | `voided` |
+| `failed` | `none` |
### Deprecated fields still work until 6.1
@@ -1213,12 +1250,17 @@ These Store API fields keep working in 6.0 and are marked `@deprecated` in the S
| Company address `zipcode`, written | `postal_code` |
| Cart `number` | `id` |
| Market `country_isos` | `country_codes` |
+| Price `amount_in_cents`, `compare_at_amount_in_cents`, and price history `amount_in_cents` | `amount`, `compare_at_amount` ([Money](#money)) |
+| A cart requirement's `field` `shipping_method` | Match its `code`, `delivery_method_required`; the field becomes `delivery_method` |
+| The `Discount` type for `cart.discounts` and `order.discounts` | `AppliedPromotion` |
+| A number passed to `carts.storeCredits.apply()` | A decimal string ([store credit](#store-credit-amounts-are-decimal-strings)) |
### Other Store API changes to check
| Change | What to update | Details |
|---|---|---|
-| Delivery requirement renamed | Match `delivery_method` (field) and `delivery_method_required` (code) instead of `shipping_method` | [Checkout without a state machine](#checkout-without-a-state-machine) |
+| Delivery requirement has a code | Match `delivery_method_required` (code); the `field` keeps `shipping_method` until 6.1 | [Checkout without a state machine](#checkout-without-a-state-machine) |
+| Status values | Map old fulfillment and payment statuses to the new ones | [Status values changed](#status-values-changed) |
| Type values are short names | Compare `payment_source_type` with `credit_card`, and read custom field `field_type` | [Type values are short names](#type-values-are-short-names-not-class-names) |
| Rich text comes in two shapes | Render `description_html` for markup; `description` is plain text | [Rich-text fields](#rich-text-fields-read-as-plain-text-plus-html) |
| Payment source IDs | Stored `source_id` values change prefix from `ps_` to `psrc_` | [Payment source IDs](#payment-source-ids-use-the-psrc_-prefix) |
diff --git a/packages/admin-sdk/CHANGELOG.md b/packages/admin-sdk/CHANGELOG.md
index 357165b2d8..1a78863d74 100644
--- a/packages/admin-sdk/CHANGELOG.md
+++ b/packages/admin-sdk/CHANGELOG.md
@@ -1,5 +1,13 @@
# @spree/admin-sdk
+## 1.0.0-rc.3
+
+### Patch Changes
+
+- Entries of `q` on every list method always stay inside `q`, even one named `page` or `sort`, and nested objects are sent in bracket form.
+
+ `sumMoney`, `subtractMoney`, `multiplyMoney` and `negateMoney` now write every result the same way: with the decimals their inputs carry, and at least the currency's when one is given (`sumMoney(['1.50', '2.50'])` is `"4.00"`, not `"4"`). Nothing is rounded away. `formatMoney` returns an empty string for a currency `Intl` does not know, falls back to the reader's language for a locale it does not know, and no longer shows a minus sign on an amount that rounds to zero.
+
## 1.0.0-rc.2
### Minor Changes
diff --git a/packages/admin-sdk/package.json b/packages/admin-sdk/package.json
index bc52fa8073..3e5372626c 100644
--- a/packages/admin-sdk/package.json
+++ b/packages/admin-sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/admin-sdk",
- "version": "1.0.0-rc.2",
+ "version": "1.0.0-rc.3",
"description": "Official TypeScript SDK for Spree Commerce Admin API",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/packages/admin-sdk/tests/money.test.ts b/packages/admin-sdk/tests/money.test.ts
index c6ed2084a8..0f9935326a 100644
--- a/packages/admin-sdk/tests/money.test.ts
+++ b/packages/admin-sdk/tests/money.test.ts
@@ -9,6 +9,7 @@ import {
isDecimalString,
isZeroMoney,
multiplyMoney,
+ negateMoney,
subtractMoney,
sumMoney,
} from '../src'
@@ -41,6 +42,15 @@ describe('money helpers', () => {
expect(sumMoney([null, '', '19.99'], 'USD')).toBe('19.99')
})
+ it('keeps the decimals its inputs carry', () => {
+ expect(sumMoney(['1.50', '2.50'])).toBe('4.00')
+ expect(subtractMoney('5.00', '1.00')).toBe('4.00')
+ expect(multiplyMoney('0.10', 3)).toBe('0.30')
+ expect(multiplyMoney('19.999', 3, 'USD')).toBe('59.997')
+ expect(multiplyMoney('5', 2, 'USD')).toBe('10.00')
+ expect(negateMoney('0.00')).toBe('0.00')
+ })
+
it('subtracts and multiplies exactly', () => {
expect(subtractMoney('10.00', '10.01', 'USD')).toBe('-0.01')
expect(multiplyMoney('0.0125', 3)).toBe('0.0375')
@@ -78,4 +88,11 @@ describe('money helpers', () => {
expect(formatMoney('99999999999999999.99', 'USD', 'en')).toBe('$99,999,999,999,999,999.99')
expect([formatMoney(null, 'USD'), formatMoney('1,99', 'USD')]).toEqual(['', ''])
})
+
+ it('formats without throwing on an unknown currency or locale', () => {
+ expect(formatMoney('10', '', 'en')).toBe('')
+ expect(formatMoney('10', 'USD', 'en_US')).toBe(formatMoney('10', 'USD'))
+ expect(formatMoney('-0.001', 'USD', 'en')).toBe('$0.00')
+ expect(formatMoney('-0.005', 'USD', 'en')).toBe('-$0.01')
+ })
})
diff --git a/packages/admin-sdk/tsup.config.ts b/packages/admin-sdk/tsup.config.ts
index 27094fc734..bdaaf6c5d1 100644
--- a/packages/admin-sdk/tsup.config.ts
+++ b/packages/admin-sdk/tsup.config.ts
@@ -15,7 +15,7 @@ export default defineConfig({
treeshake: true,
minify: false,
// sdk-core is workspace-private; inline it into the published bundle.
- noExternal: ['@spree/sdk-core'],
+ noExternal: ['@spree/sdk-core', 'spark-md5'],
esbuildOptions(options) {
options.alias = {
'@/types': path.resolve(import.meta.dirname, 'src/types/generated/index.ts'),
diff --git a/packages/dashboard/src/schemas/order.test.ts b/packages/dashboard/src/schemas/order.test.ts
index 303ab0ef49..70c6d3e1db 100644
--- a/packages/dashboard/src/schemas/order.test.ts
+++ b/packages/dashboard/src/schemas/order.test.ts
@@ -201,7 +201,7 @@ describe('projections', () => {
row({ removed: true, price: '99.0', quantity: 1 }),
]
- expect(projectedSubtotal(items)).toBe('200')
+ expect(projectedSubtotal(items)).toBe('200.00')
})
// A partial sum rendered as a total is a wrong number stated confidently.
diff --git a/packages/sdk-core/src/money.ts b/packages/sdk-core/src/money.ts
index 7aa61ae345..aa2bfc2bf0 100644
--- a/packages/sdk-core/src/money.ts
+++ b/packages/sdk-core/src/money.ts
@@ -24,14 +24,18 @@ function rescale(scaled: Scaled, scale: number): bigint {
return scaled.units * 10n ** BigInt(scale - scaled.scale)
}
-function write(units: bigint, scale: number, places = 0): string {
+function write(units: bigint, scale: number): string {
const negative = units < 0n
const digits = (negative ? -units : units).toString().padStart(scale + 1, '0')
- const whole = scale > 0 ? digits.slice(0, -scale) : digits
- let fraction = scale > 0 ? digits.slice(-scale) : ''
- fraction = fraction.replace(/0+$/, '').padEnd(places, '0')
- const text = fraction ? `${whole}.${fraction}` : whole
- return negative && /[1-9]/.test(text) ? `-${text}` : text
+ const text = scale > 0 ? `${digits.slice(0, -scale)}.${digits.slice(-scale)}` : digits
+ return negative ? `-${text}` : text
+}
+
+// Results keep every decimal their inputs carry and, with a currency, at
+// least that currency's decimals, so "1.50" + "2.50" reads "4.00" and nothing
+// is ever rounded away.
+function resultScale(scales: number[], currency?: string): number {
+ return Math.max(0, currency ? decimalPlaces(currency) : 0, ...scales)
}
/**
@@ -63,20 +67,20 @@ export function isZeroMoney(value: string | null | undefined): boolean {
}
/**
- * Adds decimal strings exactly. Blank values count as zero. With a currency,
- * the result is written with that currency's decimals ("10.00").
+ * Adds decimal strings exactly. Blank values count as zero. The result keeps
+ * the most decimals any value has, and at least the currency's when one is
+ * given ("10.00").
*/
export function sumMoney(values: Array<string | null | undefined>, currency?: string): string {
const present = values
.filter((value): value is string => value != null && value !== '')
.map(parse)
- const scale = Math.max(
- 0,
- currency ? decimalPlaces(currency) : 0,
- ...present.map((value) => value.scale),
+ const scale = resultScale(
+ present.map((value) => value.scale),
+ currency,
)
const total = present.reduce((sum, value) => sum + rescale(value, scale), 0n)
- return write(total, scale, currency ? decimalPlaces(currency) : 0)
+ return write(total, scale)
}
/** a minus b, exactly. */
@@ -87,22 +91,28 @@ export function subtractMoney(a: string, b: string, currency?: string): string {
/** The decimal string with its sign flipped. */
export function negateMoney(value: string): string {
const { units, scale } = parse(value)
- return write(-units, scale, scale)
+ return write(-units, scale)
}
-/** A decimal string times a whole quantity, exactly. */
+/**
+ * A decimal string times a whole quantity, exactly. A unit price with four
+ * decimals keeps them ("19.9990" × 3 = "59.9970"); round with the currency
+ * when displaying, through `formatMoney`.
+ */
export function multiplyMoney(value: string, quantity: number, currency?: string): string {
if (!Number.isInteger(quantity)) throw new Error(`Quantity must be a whole number: ${quantity}`)
- const { units, scale } = parse(value)
- return write(units * BigInt(quantity), scale, currency ? decimalPlaces(currency) : scale)
+ const parsed = parse(value)
+ const scale = resultScale([parsed.scale], currency)
+ return write(rescale(parsed, scale) * BigInt(quantity), scale)
}
/**
* Formats a decimal-string amount ("1234.50") in a currency and locale. The
* string goes to `Intl` as it is — `Intl` reads numeric strings exactly — so
* the amount never passes through a JavaScript number. A missing or malformed
- * amount formats as an empty string.
+ * amount, or a currency `Intl` does not know, formats as an empty string; a
+ * locale it does not know falls back to the reader's own.
*
* @example formatMoney(order.total, order.currency, order.locale) // "€129.99"
*/
@@ -117,11 +127,31 @@ export function formatMoney(
// The decimals come from the same ISO 4217 table the API writes amounts
// with, so a dinar shows three and a yen none; a unit price keeps up to four.
const places = decimalPlaces(currency)
- // ES2023's Intl typings accept a numeric string; this package targets ES2022.
- return new Intl.NumberFormat(locale ?? undefined, {
- style: 'currency',
- currency,
- minimumFractionDigits: places,
- maximumFractionDigits: options.unitPrice ? Math.max(places, 4) : places,
- }).format(amount as unknown as number)
+ const maximumPlaces = options.unitPrice ? Math.max(places, 4) : places
+ // An amount that rounds to zero shows no minus sign ("-0.001" is "$0.00").
+ const shown =
+ amount.startsWith('-') && roundsToZero(amount.slice(1), maximumPlaces)
+ ? amount.slice(1)
+ : amount
+ const format = (formatLocale: string | undefined) =>
+ // ES2023's Intl typings accept a numeric string; this package targets ES2022.
+ new Intl.NumberFormat(formatLocale, {
+ style: 'currency',
+ currency,
+ minimumFractionDigits: places,
+ maximumFractionDigits: maximumPlaces,
+ }).format(shown as unknown as number)
+
+ for (const formatLocale of locale ? [locale, undefined] : [undefined]) {
+ try {
+ return format(formatLocale)
+ } catch (error) {
+ if (!(error instanceof RangeError)) throw error
+ }
+ }
+ return ''
+}
+
+function roundsToZero(amount: string, places: number): boolean {
+ return compareMoney(amount, `0.${'0'.repeat(places)}5`) < 0
}
diff --git a/packages/sdk-core/src/params.ts b/packages/sdk-core/src/params.ts
index c42fd2de43..713756143f 100644
--- a/packages/sdk-core/src/params.ts
+++ b/packages/sdk-core/src/params.ts
@@ -10,16 +10,21 @@ type ParamValue = string | number | boolean | (string | number)[] | undefined
*
* - `page`, `limit`, `expand`, `sort` pass through unchanged
* - Keys already in `q[...]` format pass through (backward compat)
- * - The entries of `q` (filters the typed params do not list) are sent like
- * any other filter; a filter given at the top level wins over the same key in `q`
+ * - The entries of `q` (filters the typed params do not list) are always sent
+ * inside `q`, even one named `page` or `sort`; a filter given at the top
+ * level wins over the same key in `q`
+ * - Nested objects are sent in bracket form: `{ g: { a: 1 } }` → `q[g][a]`
* - All other keys are wrapped: `name_cont` → `q[name_cont]`
*/
export function transformListParams(params: object): Record<string, ParamValue> {
const { q, ...rest } = params as { q?: Record<string, unknown> }
- const entries = [...Object.entries(q ?? {}), ...Object.entries(rest)]
const result: Record<string, ParamValue> = {}
- for (const [key, value] of entries) {
+ for (const [key, value] of Object.entries(q ?? {})) {
+ appendFilter(result, key, value)
+ }
+
+ for (const [key, value] of Object.entries(rest)) {
if (value === undefined) continue
if (PASSTHROUGH_KEYS.has(key)) {
@@ -36,14 +41,31 @@ export function transformListParams(params: object): Record<string, ParamValue>
continue
}
- // Array values get [] suffix automatically: `foo: [1,2]` → `q[foo][]`
- if (Array.isArray(value)) {
- const base = key.endsWith('[]') ? key.slice(0, -2) : key
- result[`q[${base}][]`] = value as ParamValue
- } else {
- result[`q[${key}]`] = value as ParamValue
- }
+ appendFilter(result, key, value)
}
return result
}
+
+// Writes `foo: [1, 2]` as `q[foo][]` and `g: { a: 1 }` as `q[g][a]`, the
+// bracket nesting Rails parses back into the `q` hash.
+function appendFilter(
+ result: Record<string, ParamValue>,
+ key: string,
+ value: unknown,
+ prefix = 'q',
+) {
+ if (value === undefined) return
+
+ const name = `${prefix}[${key.endsWith('[]') ? key.slice(0, -2) : key}]`
+
+ if (Array.isArray(value)) {
+ result[`${name}[]`] = value as ParamValue
+ } else if (value !== null && typeof value === 'object') {
+ for (const [nestedKey, nestedValue] of Object.entries(value)) {
+ appendFilter(result, nestedKey, nestedValue, name)
+ }
+ } else {
+ result[name] = value as ParamValue
+ }
+}
diff --git a/packages/sdk-core/src/uploads.ts b/packages/sdk-core/src/uploads.ts
index fd6b44394b..39e8b12aee 100644
--- a/packages/sdk-core/src/uploads.ts
+++ b/packages/sdk-core/src/uploads.ts
@@ -1,5 +1,3 @@
-import SparkMD5 from 'spark-md5'
-
/** What `POST /files` accepts as JSON, for a presigned upload. */
export interface FileUploadCreateParams {
filename: string
@@ -39,6 +37,8 @@ const MD5_CHUNK_SIZE = 2 * 1024 * 1024
/** Base64-encoded MD5 digest of a file, read in chunks so large files stay out of memory. */
export async function computeChecksum(file: Blob): Promise<string> {
+ // Loaded on first upload, so a client that never uploads never ships it.
+ const { default: SparkMD5 } = await import('spark-md5')
const spark = new SparkMD5.ArrayBuffer()
for (let start = 0; start < file.size; start += MD5_CHUNK_SIZE) {
spark.append(await file.slice(start, start + MD5_CHUNK_SIZE).arrayBuffer())
diff --git a/packages/sdk-core/tsup.config.ts b/packages/sdk-core/tsup.config.ts
index b7017bc802..9a9454400c 100644
--- a/packages/sdk-core/tsup.config.ts
+++ b/packages/sdk-core/tsup.config.ts
@@ -11,6 +11,7 @@ export default defineConfig({
clean: true,
treeshake: true,
minify: false,
- // Inlined so the SDKs that bundle sdk-core ship no extra dependency.
- noExternal: ['spark-md5'],
+ // Left to the SDKs that upload, which bundle it themselves; the Store SDK
+ // never uploads and so never ships it.
+ external: ['spark-md5'],
})
diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md
index 04f2d5717c..2dc94f0b40 100644
--- a/packages/sdk/CHANGELOG.md
+++ b/packages/sdk/CHANGELOG.md
@@ -1,5 +1,23 @@
# @spree/sdk
+## 2.0.0-rc.3
+
+### Patch Changes
+
+- Fixed `products.filters()` sending its `q` filters as `[object Object]`, which the API answered with a server error; it now also takes `collection_id`. Entries of `q` on every list method always stay inside `q`, even one named `page` or `sort`, and nested objects are sent in bracket form.
+
+ Store API addresses accept `quick_checkout` everywhere a shopper writes one, in the address book as well as on a cart, so `AddressCreateParams`, `AddressUpdateParams` and the deprecated `AddressParams` carry it again, as `AddressParams` did in rc1.
+
+ The Store SDK no longer bundles the MD5 library used for file uploads, which it never performs.
+
+ `sumMoney`, `subtractMoney`, `multiplyMoney` and `negateMoney` now write every result the same way: with the decimals their inputs carry, and at least the currency's when one is given (`sumMoney(['1.50', '2.50'])` is `"4.00"`, not `"4"`). Nothing is rounded away. `formatMoney` returns an empty string for a currency `Intl` does not know, falls back to the reader's language for a locale it does not know, and no longer shows a minus sign on an amount that rounds to zero.
+
+ Store API prices bring back `amount_in_cents` and `compare_at_amount_in_cents`, and price history brings back `amount_in_cents`, marked `@deprecated` until 6.1 so a 5.6 storefront keeps working. Read `amount` and `compare_at_amount` instead.
+
+ `PriceRangeFilter` types the price filter's `min` and `max` as decimal strings, which is what the API sends; it said numbers. The product filter types (`PriceRangeFilter`, `OptionFilter`, `ProductFiltersResponse` and the rest) are now aliases of the generated ones, so they follow the API.
+
+ Bridges for 5.6 storefronts, each removed in 6.1: `carts.storeCredits.apply()` accepts a number again, marked `@deprecated`, and the API reads it with a deprecation warning; the cart's delivery requirement keeps `field: 'shipping_method'` (match its `code`, `delivery_method_required`); `Discount` is a deprecated alias of `AppliedPromotion`, the type of `cart.discounts` and `order.discounts`.
+
## 2.0.0-rc.2
### Minor Changes
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index 3781a19ff0..074e1e0a0d 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/sdk",
- "version": "2.0.0-rc.2",
+ "version": "2.0.0-rc.3",
"description": "Official TypeScript SDK for Spree Commerce Store API",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index 765a532303..6305ea54a9 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -108,6 +108,24 @@ import type {
WishlistSort,
} from './types/filters.generated'
+// The category and collection go at the top level; only the filters are Ransack params.
+function getFiltersParams(params: ProductFiltersParams = {}) {
+ const { q, ...scope } = params
+ return { ...scope, ...transformListParams({ q }) }
+}
+
+interface ApplyStoreCredit {
+ /**
+ * Apply store credit to the cart
+ * @param cartId - Cart prefixed ID
+ * @param amount - How much to apply, as a decimal string (`'10.00'`). Omit it to apply as much
+ * as the cart can use.
+ */
+ (cartId: string, amount?: string, options?: RequestOptions): Promise<Cart>
+ /** @deprecated Pass the amount as a decimal string (`'25.00'`). A number is refused from 6.1. */
+ (cartId: string, amount: number, options?: RequestOptions): Promise<Cart>
+}
+
export class StoreClient {
/**
* Low-level request function for calling custom API endpoints.
@@ -192,7 +210,7 @@ export class StoreClient {
): Promise<ProductFiltersResponse> =>
this.request<ProductFiltersResponse>('GET', '/products/filters', {
...options,
- params: params as Record<string, string | number | undefined>,
+ params: getFiltersParams(params),
}),
}
@@ -756,17 +774,11 @@ export class StoreClient {
* Store credits
*/
storeCredits: {
- /**
- * Apply store credit to the cart
- * @param cartId - Cart prefixed ID
- * @param amount - How much to apply, as a decimal string (`'10.00'`). Omit it to apply as much
- * as the cart can use.
- */
- apply: (cartId: string, amount?: string, options?: RequestOptions): Promise<Cart> =>
+ apply: ((cartId: string, amount?: string | number, options?: RequestOptions): Promise<Cart> =>
this.request<Cart>('POST', `/carts/${cartId}/store_credits`, {
...options,
- body: amount ? { amount } : undefined,
- }),
+ body: amount != null && amount !== '' ? { amount } : undefined,
+ })) as ApplyStoreCredit,
/**
* Remove store credit from the cart
diff --git a/packages/sdk/src/types/generated/Price.ts b/packages/sdk/src/types/generated/Price.ts
index 2edeab96f2..234f5fb48d 100644
--- a/packages/sdk/src/types/generated/Price.ts
+++ b/packages/sdk/src/types/generated/Price.ts
@@ -1,4 +1,4 @@
-// Typelizer digest d1d8ab56607bdd49dec39815b987d525
+// Typelizer digest e88266bd07c862b5bb9c88bd2d5284a9
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CurrencyCode} from '@/types'
@@ -8,6 +8,10 @@ interface Price {
currency: CurrencyCode | null;
amount: string | null;
compare_at_amount: string | null;
+ /** @deprecated Use `amount`. Removed in 6.1. */
+ amount_in_cents: number | null;
+ /** @deprecated Use `compare_at_amount`. Removed in 6.1. */
+ compare_at_amount_in_cents: number | null;
/** `amount` formatted with its currency symbol in the request's language.
* @deprecated Format `amount` with its currency instead. Removed in 6.1. */
display_amount: string | null;
diff --git a/packages/sdk/src/types/generated/PriceHistory.ts b/packages/sdk/src/types/generated/PriceHistory.ts
index 2d2acc5942..bcbdf00939 100644
--- a/packages/sdk/src/types/generated/PriceHistory.ts
+++ b/packages/sdk/src/types/generated/PriceHistory.ts
@@ -1,4 +1,4 @@
-// Typelizer digest c43732b1c5554a88dff19569bba598dc
+// Typelizer digest 1051b2dd87faa7ce04837223c2abf1c9
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CurrencyCode} from '@/types'
@@ -7,6 +7,8 @@ interface PriceHistory {
id: string;
currency: CurrencyCode;
amount: string | null;
+ /** @deprecated Use `amount`. Removed in 6.1. */
+ amount_in_cents: number | null;
/** `amount` formatted with its currency symbol in the request's language.
* @deprecated Format `amount` with its currency instead. Removed in 6.1. */
display_amount: string;
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index c3e500b49b..06a29b7379 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -9,7 +9,19 @@ import type {
ProductFilters,
ProductSort,
} from './filters.generated'
-import type { Cart as CartType } from './generated'
+import type {
+ AppliedPromotion,
+ Cart as CartType,
+ ProductFilterAvailability,
+ ProductFilterAvailabilityOption,
+ ProductFilterCategory,
+ ProductFilterCategoryOption,
+ ProductFilterOption,
+ ProductFilterOptionValue,
+ ProductFilterPriceRange,
+ ProductFilterSortOption,
+ ProductFilters as ProductFiltersResult,
+} from './generated'
import type { AddressUpdateParams, CompanyAddressUpdateParams, LineItemInputParams } from './params'
export * from './filters.generated'
@@ -38,7 +50,6 @@ export type {
DeliveryRate,
DigitalAsset,
DigitalLink,
- Discount,
Fee,
FreightSummary,
Fulfillment,
@@ -122,8 +133,7 @@ export type CollectionListParams = ListParams<CollectionFilters, CollectionSort>
export type OrderListParams = ListParams<OrderFilters, OrderSort>
-// Line item input for bulk cart/order operations
-/** @deprecated Renamed to `LineItemInputParams`. */
+/** @deprecated Renamed to `LineItemInputParams`. Removed in 6.1. */
export type LineItemInput = LineItemInputParams
/** @deprecated Split by action: `AddressCreateParams` and `AddressUpdateParams`. Removed in 6.1. */
@@ -132,76 +142,26 @@ export type AddressParams = AddressUpdateParams
/** @deprecated Split by action: `CompanyAddressCreateParams` and `CompanyAddressUpdateParams`. Removed in 6.1. */
export type CompanyAddressParams = CompanyAddressUpdateParams
-// Cart operations
-// Payments
-// Payment Sessions
-// Payment Setup Sessions
-// Product Filters types
-export interface FilterOption {
- id: string
- count: number
-}
-
-export interface OptionFilterOption extends FilterOption {
- name: string
- label: string
- position: number
- color_code: string | null
- image_url: string | null
-}
-
-export interface CategoryFilterOption {
- id: string
- name: string
- permalink: string
- count: number
-}
-
-export interface PriceRangeFilter {
- id: 'price'
- type: 'price_range'
- min: number
- max: number
- currency: string
-}
-
-export interface AvailabilityFilter {
- id: 'availability'
- type: 'availability'
- options: FilterOption[]
-}
-
-export interface OptionFilter {
- id: string
- type: 'option'
- name: string
- label: string
- kind: string
- options: OptionFilterOption[]
-}
-
-export interface CategoryFilter {
- id: 'categories'
- type: 'category'
- options: CategoryFilterOption[]
-}
-
+/** @deprecated Renamed to `AppliedPromotion`, the type of `cart.discounts` and `order.discounts`. Removed in 6.1. */
+export type Discount = AppliedPromotion
+
+// Product filters: the names storefronts import, kept as aliases of the generated types
+export type FilterOption = ProductFilterAvailabilityOption
+export type OptionFilterOption = ProductFilterOptionValue
+export type CategoryFilterOption = ProductFilterCategoryOption
+export type PriceRangeFilter = ProductFilterPriceRange
+export type AvailabilityFilter = ProductFilterAvailability
+export type OptionFilter = ProductFilterOption
+export type CategoryFilter = ProductFilterCategory
export type ProductFilter = PriceRangeFilter | AvailabilityFilter | OptionFilter | CategoryFilter
-
-export interface SortOption {
- id: string
-}
-
-export interface ProductFiltersResponse {
- filters: ProductFilter[]
- sort_options: SortOption[]
- default_sort: string
- total_count: number
-}
+export type SortOption = ProductFilterSortOption
+export type ProductFiltersResponse = ProductFiltersResult
export interface ProductFiltersParams {
category_id?: string
- q?: Record<string, unknown>
+ collection_id?: string
+ /** The listing's active filters, so the counts describe the products it shows. */
+ q?: ProductFilters & Record<string, unknown>
}
// The building blocks of the generated filter types, for a declaration file
diff --git a/packages/sdk/src/types/params/AddressCreateParams.ts b/packages/sdk/src/types/params/AddressCreateParams.ts
index 0dcec50672..c46efe538f 100644
--- a/packages/sdk/src/types/params/AddressCreateParams.ts
+++ b/packages/sdk/src/types/params/AddressCreateParams.ts
@@ -17,6 +17,11 @@ export type AddressCreateParams = {
state_code?: string
/** The state name, for countries without predefined states. */
state_name?: string
+ /**
+ * Relaxes validation (name, phone, postal code, street), for express checkouts that share a
+ * partial address.
+ */
+ quick_checkout?: boolean
/** @deprecated Use `country_code`. Removed in 6.1. */
country_iso?: string
/** @deprecated Use `state_code`. Removed in 6.1. */
diff --git a/packages/sdk/src/types/params/AddressUpdateParams.ts b/packages/sdk/src/types/params/AddressUpdateParams.ts
index 2711c926db..628aba0783 100644
--- a/packages/sdk/src/types/params/AddressUpdateParams.ts
+++ b/packages/sdk/src/types/params/AddressUpdateParams.ts
@@ -17,6 +17,11 @@ export type AddressUpdateParams = {
state_code?: string
/** The state name, for countries without predefined states. */
state_name?: string
+ /**
+ * Relaxes validation (name, phone, postal code, street), for express checkouts that share a
+ * partial address.
+ */
+ quick_checkout?: boolean
/** @deprecated Use `country_code`. Removed in 6.1. */
country_iso?: string
/** @deprecated Use `state_code`. Removed in 6.1. */
diff --git a/packages/sdk/src/types/params/ApplyStoreCreditParams.ts b/packages/sdk/src/types/params/ApplyStoreCreditParams.ts
index 201bd8a601..9ecc6d1843 100644
--- a/packages/sdk/src/types/params/ApplyStoreCreditParams.ts
+++ b/packages/sdk/src/types/params/ApplyStoreCreditParams.ts
@@ -1,6 +1,9 @@
// This file is auto-generated from the request schemas in docs/api-reference by `pnpm generate:params`. Do not edit directly.
export type ApplyStoreCreditParams = {
- /** Defaults to as much as the cart can use. */
+ /**
+ * Defaults to as much as the cart can use. A JSON number is still read until 6.1, with a
+ * deprecation warning.
+ */
amount?: string
}
diff --git a/packages/sdk/src/types/params/CartAddressParams.ts b/packages/sdk/src/types/params/CartAddressParams.ts
index 2c07a0d185..d99d222219 100644
--- a/packages/sdk/src/types/params/CartAddressParams.ts
+++ b/packages/sdk/src/types/params/CartAddressParams.ts
@@ -19,13 +19,13 @@ export type CartAddressParams = {
state_code?: string
/** The state name, for countries without predefined states. */
state_name?: string
- /** @deprecated Use `country_code`. Removed in 6.1. */
- country_iso?: string
- /** @deprecated Use `state_code`. Removed in 6.1. */
- state_abbr?: string
/**
* Relaxes validation (name, phone, postal code, street), for express checkouts that share a
* partial address.
*/
quick_checkout?: boolean
+ /** @deprecated Use `country_code`. Removed in 6.1. */
+ country_iso?: string
+ /** @deprecated Use `state_code`. Removed in 6.1. */
+ state_abbr?: string
}
diff --git a/packages/sdk/src/zod/generated/Price.ts b/packages/sdk/src/zod/generated/Price.ts
index 834e31fb10..dcd9b83673 100644
--- a/packages/sdk/src/zod/generated/Price.ts
+++ b/packages/sdk/src/zod/generated/Price.ts
@@ -6,6 +6,8 @@ export const PriceSchema = z.object({
currency: z.string().nullable(),
amount: z.string().nullable(),
compare_at_amount: z.string().nullable(),
+ amount_in_cents: z.number().nullable(),
+ compare_at_amount_in_cents: z.number().nullable(),
display_amount: z.string().nullable(),
display_compare_at_amount: z.string().nullable(),
price_list_id: z.string().nullable(),
diff --git a/packages/sdk/src/zod/generated/PriceHistory.ts b/packages/sdk/src/zod/generated/PriceHistory.ts
index 48f3be55e0..b8f8adcf0d 100644
--- a/packages/sdk/src/zod/generated/PriceHistory.ts
+++ b/packages/sdk/src/zod/generated/PriceHistory.ts
@@ -5,6 +5,7 @@ export const PriceHistorySchema = z.object({
id: z.string(),
currency: z.string(),
amount: z.string().nullable(),
+ amount_in_cents: z.number().nullable(),
display_amount: z.string(),
recorded_at: z.string(),
});
diff --git a/packages/sdk/tests/cart.test.ts b/packages/sdk/tests/cart.test.ts
index 70623d7488..74bfc8fff4 100644
--- a/packages/sdk/tests/cart.test.ts
+++ b/packages/sdk/tests/cart.test.ts
@@ -166,6 +166,11 @@ describe('carts', () => {
expect(result.id).toBe('cart_1')
})
+ it('still accepts a number until 6.1', async () => {
+ const result = await client.carts.storeCredits.apply('cart_1', 25, opts)
+ expect(result.id).toBe('cart_1')
+ })
+
it('removes store credit', async () => {
const result = await client.carts.storeCredits.remove('cart_1', opts)
expect(result.id).toBe('cart_1')
diff --git a/packages/sdk/tests/params.test.ts b/packages/sdk/tests/params.test.ts
index 7ada72eed3..a513e3647c 100644
--- a/packages/sdk/tests/params.test.ts
+++ b/packages/sdk/tests/params.test.ts
@@ -14,6 +14,19 @@ describe('transformListParams', () => {
})
})
+ it('keeps every entry of q inside q, nested objects included', () => {
+ const result = transformListParams({
+ page: 2,
+ q: { page: 3, sort: 'name', g: { '0': { name_cont: 'shirt' } } },
+ })
+ expect(result).toEqual({
+ page: 2,
+ 'q[page]': 3,
+ 'q[sort]': 'name',
+ 'q[g][0][name_cont]': 'shirt',
+ })
+ })
+
it('prefers a typed filter over the same key in q', () => {
const result = transformListParams({ name_cont: 'typed', q: { name_cont: 'raw' } })
expect(result).toEqual({ 'q[name_cont]': 'typed' })
diff --git a/packages/sdk/tests/products.test.ts b/packages/sdk/tests/products.test.ts
index dfc7342e52..d5fe94430a 100644
--- a/packages/sdk/tests/products.test.ts
+++ b/packages/sdk/tests/products.test.ts
@@ -91,5 +91,28 @@ describe('products', () => {
expect(result.default_sort).toBe('default')
expect(result.total_count).toBe(1)
})
+
+ it('sends the category at the top level and the filters inside q', async () => {
+ let capturedUrl = ''
+ const { createClient } = await import('../src')
+ const customClient = createClient({
+ baseUrl: 'https://demo.spreecommerce.org',
+ publishableKey: 'test-key',
+ fetch: async (url, init) => {
+ capturedUrl = decodeURIComponent(url.toString())
+ return globalThis.fetch(url, init)
+ },
+ })
+
+ await customClient.products.filters({
+ category_id: 'ctg_1',
+ q: { price_gte: '10.00', with_option_value_ids: ['optval_1'] },
+ })
+
+ expect(capturedUrl).toContain('category_id=ctg_1')
+ expect(capturedUrl).toContain('q[price_gte]=10.00')
+ expect(capturedUrl).toContain('q[with_option_value_ids][]=optval_1')
+ expect(capturedUrl).not.toContain('[object Object]')
+ })
})
})
diff --git a/packages/seller-dashboard/CHANGELOG.md b/packages/seller-dashboard/CHANGELOG.md
index 6e8392c7dc..e4d23dddb1 100644
--- a/packages/seller-dashboard/CHANGELOG.md
+++ b/packages/seller-dashboard/CHANGELOG.md
@@ -1,5 +1,12 @@
# @spree/seller-dashboard
+## 1.0.0-rc.4
+
+### Patch Changes
+
+- Updated dependencies:
+
## 1.0.0-rc.3
### Minor Changes
diff --git a/packages/seller-dashboard/package.json b/packages/seller-dashboard/package.json
index ecfc3b598e..dcf24eb00a 100644
--- a/packages/seller-dashboard/package.json
+++ b/packages/seller-dashboard/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/seller-dashboard",
- "version": "1.0.0-rc.3",
+ "version": "1.0.0-rc.4",
"license": "MIT",
"type": "module",
"description": "Spree marketplace seller panel — the seller-facing counterpart to the admin dashboard.",
diff --git a/packages/seller-sdk/CHANGELOG.md b/packages/seller-sdk/CHANGELOG.md
index 8b6c8520fd..b53576a4c2 100644
--- a/packages/seller-sdk/CHANGELOG.md
+++ b/packages/seller-sdk/CHANGELOG.md
@@ -1,5 +1,13 @@
# @spree/seller-sdk
+## 1.0.0-rc.3
+
+### Patch Changes
+
+- Entries of `q` on every list method always stay inside `q`, even one named `page` or `sort`, and nested objects are sent in bracket form.
+
+ `sumMoney`, `subtractMoney`, `multiplyMoney` and `negateMoney` now write every result the same way: with the decimals their inputs carry, and at least the currency's when one is given (`sumMoney(['1.50', '2.50'])` is `"4.00"`, not `"4"`). Nothing is rounded away. `formatMoney` returns an empty string for a currency `Intl` does not know, falls back to the reader's language for a locale it does not know, and no longer shows a minus sign on an amount that rounds to zero.
+
## 1.0.0-rc.2
### Minor Changes
diff --git a/packages/seller-sdk/package.json b/packages/seller-sdk/package.json
index 539aed9b8f..5d4478fb94 100644
--- a/packages/seller-sdk/package.json
+++ b/packages/seller-sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/seller-sdk",
- "version": "1.0.0-rc.2",
+ "version": "1.0.0-rc.3",
"description": "TypeScript client for the Spree Seller API — the marketplace seller panel.",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/packages/seller-sdk/tsup.config.ts b/packages/seller-sdk/tsup.config.ts
index 27094fc734..bdaaf6c5d1 100644
--- a/packages/seller-sdk/tsup.config.ts
+++ b/packages/seller-sdk/tsup.config.ts
@@ -15,7 +15,7 @@ export default defineConfig({
treeshake: true,
minify: false,
// sdk-core is workspace-private; inline it into the published bundle.
- noExternal: ['@spree/sdk-core'],
+ noExternal: ['@spree/sdk-core', 'spark-md5'],
esbuildOptions(options) {
options.alias = {
'@/types': path.resolve(import.meta.dirname, 'src/types/generated/index.ts'),
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/store/search_provider_support.rb b/spree/api/app/controllers/concerns/spree/api/v3/store/search_provider_support.rb
index 2a3add7530..06986ec096 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/store/search_provider_support.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/store/search_provider_support.rb
@@ -18,12 +18,11 @@ module Spree
private
def search_query
- params.dig(:q, :search)
+ search_params['search']
end
def search_filters
- q = params[:q]&.to_unsafe_h || params[:q] || {}
- q = q.to_h if q.respond_to?(:to_h) && !q.is_a?(Hash)
+ q = search_params
# Decode Stripe-style prefixed IDs in `*_id_in`/`id_eq`/etc. so
# SPA + storefront filters can pass `prod_…` keys; the search
# provider hands the filter hash straight to Ransack on the
@@ -31,6 +30,12 @@ module Spree
decode_prefixed_id_predicates(q.except('search')).presence
end
+ # A `q` sent as anything but a hash (`q=foo`) filters nothing.
+ def search_params
+ q = params[:q]
+ q.respond_to?(:to_unsafe_h) ? q.to_unsafe_h : {}
+ end
+
def search_provider
@search_provider ||= Spree.search_provider.constantize.new(current_store)
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb
index 1f182a2450..b197588e0c 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb
@@ -9,11 +9,12 @@ module Spree
before_action :require_authentication!
before_action :find_cart!
+ before_action :stringify_numeric_amount, only: :create
request_params 'ApplyStoreCreditParams', action: :create do |body|
body.attribute :amount, :decimal,
example: '10.00',
- description: 'Defaults to as much as the cart can use.'
+ description: 'Defaults to as much as the cart can use. A JSON number is still read until 6.1, with a deprecation warning.'
end
# POST /api/v3/store/carts/:cart_id/store_credits
@@ -46,6 +47,17 @@ module Spree
end
end
end
+
+ private
+
+ # 5.6 storefronts sent a JSON number; read it through its text so no
+ # float reaches the money math.
+ def stringify_numeric_amount
+ return unless params[:amount].is_a?(Numeric)
+
+ Spree::Deprecation.warn('Sending the store credit amount as a JSON number is deprecated and will be refused in Spree 6.1. Send a decimal string such as "25.00".')
+ params[:amount] = params[:amount].to_s
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
index 0abac10b98..d87e70c55a 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
@@ -15,8 +15,6 @@ module Spree
schema.attribute :id, :id,
description: 'An existing address of the customer to use. The other fields are then ignored.'
schema.include_attributes Spree::Api::V3::Store::AddressRequestSchema
- schema.attribute :quick_checkout, :boolean,
- description: 'Relaxes validation (name, phone, postal code, street), for express checkouts that share a partial address.'
end
# Creating and updating a cart accept the same fields.
diff --git a/spree/api/app/request_schemas/spree/api/v3/store/address_request_schema.rb b/spree/api/app/request_schemas/spree/api/v3/store/address_request_schema.rb
index dec77f65f6..a9e19785c4 100644
--- a/spree/api/app/request_schemas/spree/api/v3/store/address_request_schema.rb
+++ b/spree/api/app/request_schemas/spree/api/v3/store/address_request_schema.rb
@@ -20,6 +20,8 @@ module Spree
example: 'NY',
description: 'ISO 3166-2 subdivision code without the country prefix, such as `CA` or `NY`.'
attribute :state_name, :string, description: 'The state name, for countries without predefined states.'
+ attribute :quick_checkout, :boolean,
+ description: 'Relaxes validation (name, phone, postal code, street), for express checkouts that share a partial address.'
attribute :country_iso, :string, deprecated: 'Use `country_code`. Removed in 6.1.'
attribute :state_abbr, :string, deprecated: 'Use `state_code`. Removed in 6.1.'
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/price_history_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/price_history_serializer.rb
index a84769c1c0..d0627e59d6 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/price_history_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/price_history_serializer.rb
@@ -6,6 +6,7 @@ module Spree
module Admin
class PriceHistorySerializer < V3::PriceHistorySerializer
without_formatted_money
+ _attributes.delete(:amount_in_cents)
typelize variant_id: :string,
price_id: :string,
diff --git a/spree/api/app/serializers/spree/api/v3/admin/price_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/price_serializer.rb
index add66cbb4e..4bfbf3953f 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/price_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/price_serializer.rb
@@ -6,6 +6,8 @@ module Spree
# Extends Store Price Serializer with admin-only fields
class PriceSerializer < V3::PriceSerializer
without_formatted_money
+ _attributes.delete(:amount_in_cents)
+ _attributes.delete(:compare_at_amount_in_cents)
typelize variant_id: [:string, nullable: true],
min_quantity: :number,
diff --git a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
index 11176d3a9d..f2c2a16a59 100644
--- a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
@@ -74,7 +74,11 @@ module Spree
# it is dropped rather than redacted for a gated guest: a requirement
# with its numbers stripped tells them nothing they can act on.
attribute :requirements do |order|
- requirements = Spree::Checkout::Requirements.new(order).call
+ # 5.6 storefronts matched the delivery requirement by its field, so
+ # it keeps the old name until 6.1; `code` already carries the new one.
+ requirements = Spree::Checkout::Requirements.new(order).call.map do |requirement|
+ requirement[:field] == 'delivery_method' ? requirement.merge(field: 'shipping_method') : requirement
+ end
next requirements unless params[:hide_prices]
requirements.reject { |requirement| requirement[:code] == 'order_minimum_not_met' }
diff --git a/spree/api/app/serializers/spree/api/v3/price_history_serializer.rb b/spree/api/app/serializers/spree/api/v3/price_history_serializer.rb
index 2271d59959..4f37fa9224 100644
--- a/spree/api/app/serializers/spree/api/v3/price_history_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/price_history_serializer.rb
@@ -6,12 +6,17 @@ module Spree
class PriceHistorySerializer < BaseSerializer
typelize display_amount: display_money_type(:display_amount, nullable: false),
currency: [:string, enum: Spree::Money::Rounding::CURRENCY_CODES, enum_type_name: 'CurrencyCode'],
- recorded_at: :string
+ recorded_at: :string,
+ amount_in_cents: [:number, nullable: true, deprecated: 'Use `amount`. Removed in 6.1.']
attributes :currency
money_attributes :amount, unit_price: true
+ attribute :amount_in_cents do |price_history|
+ price_history.amount_in_cents unless params[:hide_prices]
+ end
+
attributes :display_amount
attribute :recorded_at do |price_history|
diff --git a/spree/api/app/serializers/spree/api/v3/price_serializer.rb b/spree/api/app/serializers/spree/api/v3/price_serializer.rb
index 6b918e9bfa..4f0f777b4d 100644
--- a/spree/api/app/serializers/spree/api/v3/price_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/price_serializer.rb
@@ -8,12 +8,22 @@ module Spree
typelize display_amount: display_money_type(:display_amount),
display_compare_at_amount: display_money_type(:display_compare_at_amount),
currency: [:string, nullable: true, enum: Spree::Money::Rounding::CURRENCY_CODES, enum_type_name: 'CurrencyCode'],
- price_list_id: [:string, nullable: true]
+ price_list_id: [:string, nullable: true],
+ amount_in_cents: [:number, nullable: true, deprecated: 'Use `amount`. Removed in 6.1.'],
+ compare_at_amount_in_cents: [:number, nullable: true, deprecated: 'Use `compare_at_amount`. Removed in 6.1.']
attributes :currency
money_attributes :amount, :compare_at_amount, unit_price: true
+ attribute :amount_in_cents do |price|
+ price.amount_in_cents unless params[:hide_prices]
+ end
+
+ attribute :compare_at_amount_in_cents do |price|
+ price.compare_at_amount_in_cents unless params[:hide_prices]
+ end
+
attribute :display_amount do |price|
price.display_amount&.to_s
end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/price_history_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/price_history_serializer.rb
index c95e14f4e4..7217ebdbcd 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/price_history_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/price_history_serializer.rb
@@ -4,6 +4,7 @@ module Spree
module Seller
class PriceHistorySerializer < V3::PriceHistorySerializer
without_formatted_money(:seller)
+ _attributes.delete(:amount_in_cents)
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/price_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/price_serializer.rb
index f3a776dd21..f5ecba139d 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/price_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/price_serializer.rb
@@ -4,6 +4,8 @@ module Spree
module Seller
class PriceSerializer < V3::PriceSerializer
without_formatted_money(:seller)
+ _attributes.delete(:amount_in_cents)
+ _attributes.delete(:compare_at_amount_in_cents)
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb
index c5fb8e6074..0f89a7cd47 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb
@@ -31,11 +31,14 @@ RSpec.describe Spree::Api::V3::Store::Carts::StoreCreditsController, type: :cont
expect(order.reload.payments.store_credits.sum(:amount)).to eq(BigDecimal('5.05'))
end
- it 'refuses a JSON number: money is a decimal string' do
+ # 5.6 storefronts sent a number; it keeps working until 6.1.
+ it 'still applies a JSON number exactly, with a deprecation warning' do
+ expect(Spree::Deprecation).to receive(:warn).with(/JSON number is deprecated/)
+
post :create, params: { cart_id: order.prefixed_id, amount: 5.05 }, as: :json
- expect(response).to have_http_status(:unprocessable_content)
- expect(json_response['error']['code']).to eq('invalid_money_format')
+ expect(response).to have_http_status(:ok)
+ expect(order.reload.payments.store_credits.sum(:amount)).to eq(BigDecimal('5.05'))
end
it 'refuses a localized amount' do
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
index 05f299b05c..2496b5e961 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
@@ -597,8 +597,9 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
expect(response).to have_http_status(:ok)
expect(json_response['fulfillments']).to be_empty
expect(json_response['warnings'].map { |warning| warning['code'] }).to include('delivery_unavailable')
+ # The field keeps its 5.6 name until 6.1, so 5.6 storefronts still match it.
expect(json_response['requirements']).to include(
- a_hash_including('step' => 'delivery', 'field' => 'delivery_method')
+ a_hash_including('step' => 'delivery', 'field' => 'shipping_method', 'code' => 'delivery_method_required')
)
end
@@ -816,7 +817,7 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
expect(json_response['fulfillments']).to be_empty
expect(json_response['warnings'].map { |warning| warning['code'] }).to include('delivery_unavailable')
expect(json_response['requirements']).to include(
- a_hash_including('step' => 'delivery', 'field' => 'delivery_method')
+ a_hash_including('step' => 'delivery', 'code' => 'delivery_method_required')
)
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/customer/addresses_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/customer/addresses_controller_spec.rb
index 2a49d22a7b..9ce3f84043 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/customer/addresses_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/customer/addresses_controller_spec.rb
@@ -133,6 +133,13 @@ RSpec.describe Spree::Api::V3::Store::Customer::AddressesController, type: :cont
expect(json_response['state_code']).to eq(state.abbr)
end
+ it 'accepts quick_checkout, relaxing the phone requirement' do
+ post :create, params: address_params.except(:phone).merge(quick_checkout: true)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['quick_checkout']).to be(true)
+ end
+
context 'with invalid params' do
it 'returns validation errors for missing first_name' do
post :create, params: address_params.except(:first_name)
diff --git a/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb
index bced5159ec..57a43e6433 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb
@@ -191,6 +191,13 @@ RSpec.describe Spree::Api::V3::Store::Products::FiltersController, type: :contro
expect(json_response['total_count']).to eq(1)
end
+
+ it 'ignores a q that is not a hash' do
+ get :index, params: { q: '[object Object]' }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['total_count']).to eq(3)
+ end
end
context 'without API key' do
diff --git a/spree/api/spec/integration/spree/api/v3/store/products_spec.rb b/spree/api/spec/integration/spree/api/v3/store/products_spec.rb
index be352ce522..abfc2dcf1e 100644
--- a/spree/api/spec/integration/spree/api/v3/store/products_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/products_spec.rb
@@ -181,7 +181,7 @@ RSpec.describe 'Products API', type: :request, swagger_doc: 'api-reference/store
expect(lowest['amount']).to eq('9.99')
expect(lowest['currency']).to eq('USD')
expect(lowest['display_amount']).to be_present
- expect(lowest).not_to have_key('amount_in_cents')
+ expect(lowest['amount_in_cents']).to eq(999)
expect(lowest['recorded_at']).to be_present
end
end
diff --git a/spree/api/spec/serializers/spree/api/v3/money_contract_spec.rb b/spree/api/spec/serializers/spree/api/v3/money_contract_spec.rb
index f05cced8e8..24e5272c42 100644
--- a/spree/api/spec/serializers/spree/api/v3/money_contract_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/money_contract_spec.rb
@@ -10,7 +10,7 @@ RSpec.describe 'API v3 money contract' do
def money_name = /(\A|_)(amount|price|total|cost|fee|payout|discount|tax|revenue|balance|refund|credit|minimum|earned|payable|paid|pending|subtotal)(\z|_)/
def rate_name = /(\A|_)(rate|percent|percentage)\z/
- def not_money = /(\A|_)(id|ids|count|quantity|status|kind|type|code|label|name|at|unit|method|methods|provider|currency)\z|\Adisplay_|\Atotal_(quantity|units|cartons|on_hand)\z|delivery_count/
+ def not_money = /(\A|_)(id|ids|count|quantity|status|kind|type|code|label|name|at|unit|method|methods|provider|currency)\z|\Adisplay_|\Atotal_(quantity|units|cartons|on_hand)\z|delivery_count|_in_cents\z/
def unit_price_keys = %w[price compare_at_amount cost_price unit_cost catalog_price original_price new_variant_price]
# Walks a payload and yields every money- or rate-named scalar with the
diff --git a/spree/api/spec/serializers/spree/api/v3/price_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/price_serializer_spec.rb
index 207f1e130b..fbf2a7ad43 100644
--- a/spree/api/spec/serializers/spree/api/v3/price_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/price_serializer_spec.rb
@@ -19,8 +19,7 @@ RSpec.describe Spree::Api::V3::PriceSerializer do
end
it 'includes nil compare_at fields when not set' do
- expect(subject.values_at('compare_at_amount', 'display_compare_at_amount')).to all(be_nil)
- expect(subject).not_to include('amount_in_cents', 'compare_at_amount_in_cents')
+ expect(subject.values_at('compare_at_amount', 'display_compare_at_amount', 'compare_at_amount_in_cents')).to all(be_nil)
end
it 'includes compare_at fields when set' do
@@ -31,6 +30,17 @@ RSpec.describe Spree::Api::V3::PriceSerializer do
)
end
+ # Deprecated until 6.1, so 5.6 storefronts reading them keep working.
+ it 'still answers to the deprecated amounts in cents' do
+ price.update!(compare_at_amount: 29.99)
+ expect(subject).to include('amount_in_cents' => 1999, 'compare_at_amount_in_cents' => 2999)
+ end
+
+ it 'hides the amounts in cents when prices are hidden' do
+ result = described_class.new(price, params: base_params.merge(hide_prices: true)).to_h
+ expect(result.values_at('amount', 'amount_in_cents', 'compare_at_amount_in_cents')).to all(be_nil)
+ end
+
it 'includes price_list_id when price list is set' do
price_list = create(:price_list, :active, store: store)
price_with_list = create(:price, variant: variant, amount: 14.99, currency: 'USD', price_list: price_list)