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.

Rebuilt the Admin Promotions API and UI to allow full promotion (with rules/actions) edit in place

Damian Legawiecba9768b6bc04
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index b29755f884..e74aa45f20 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -82,11 +82,11 @@ paths:
example:
data:
- id: admin_UkLWZg9DAJ
- first_name: Vernell
- last_name: Cruickshank
- created_at: '2026-05-10T19:04:53.278Z'
- updated_at: '2026-05-10T19:04:53.278Z'
+ first_name: Lulu
+ last_name: Barrows
+ created_at: '2026-05-12T13:52:20.745Z'
+ updated_at: '2026-05-12T13:52:20.745Z'
roles:
- id: role_UkLWZg9DAJ
name: admin
@@ -144,11 +144,11 @@ paths:
application/json:
example:
id: admin_UkLWZg9DAJ
- first_name: Leslie
- last_name: Douglas
- created_at: '2026-05-10T19:04:53.643Z'
- updated_at: '2026-05-10T19:04:53.643Z'
+ first_name: Gwen
+ last_name: Cronin
+ created_at: '2026-05-12T13:52:21.120Z'
+ updated_at: '2026-05-12T13:52:21.120Z'
roles:
- id: role_UkLWZg9DAJ
name: admin
@@ -201,11 +201,11 @@ paths:
application/json:
example:
id: admin_UkLWZg9DAJ
first_name: Renamed
- last_name: Jerde
- created_at: '2026-05-10T19:04:53.929Z'
- updated_at: '2026-05-10T19:04:53.945Z'
+ last_name: Hettinger
+ created_at: '2026-05-12T13:52:21.405Z'
+ updated_at: '2026-05-12T13:52:21.421Z'
roles:
- id: role_UkLWZg9DAJ
name: admin
@@ -314,32 +314,32 @@ paths:
key_type: publishable
token_prefix:
scopes: []
- created_at: '2026-05-10T19:04:54.240Z'
- updated_at: '2026-05-10T19:04:54.240Z'
+ created_at: '2026-05-12T13:52:21.721Z'
+ updated_at: '2026-05-12T13:52:21.721Z'
revoked_at:
last_used_at:
- plaintext_token: pk_mLseFubocKpVYZtxYz3vrwxD
+ plaintext_token: pk_MsEw4niGffKQWWXZqMwhs5WE
created_by_email:
- id: key_gbHJdmfrXB
name: Backend integration
key_type: secret
- token_prefix: sk_2S3f7xs7c
+ token_prefix: sk_qw4d7jxhy
scopes:
- write_all
- created_at: '2026-05-10T19:04:54.241Z'
- updated_at: '2026-05-10T19:04:54.241Z'
+ created_at: '2026-05-12T13:52:21.724Z'
+ updated_at: '2026-05-12T13:52:21.724Z'
revoked_at:
last_used_at:
plaintext_token:
created_by_email:
- id: key_EfhxLZ9ck8
- name: placeat
+ name: nihil
key_type: secret
- token_prefix: sk_LYBqPXtK2
+ token_prefix: sk_5onu8GphS
scopes:
- write_all
- created_at: '2026-05-10T19:04:54.241Z'
- updated_at: '2026-05-10T19:04:54.241Z'
+ created_at: '2026-05-12T13:52:21.725Z'
+ updated_at: '2026-05-12T13:52:21.725Z'
revoked_at:
last_used_at:
plaintext_token:
@@ -402,15 +402,15 @@ paths:
id: key_VqXmZF31wY
name: CI key
key_type: secret
- token_prefix: sk_W1fgVVQ8c
+ token_prefix: sk_pbB3mHVDa
scopes:
- read_orders
- created_at: '2026-05-10T19:04:54.824Z'
- updated_at: '2026-05-10T19:04:54.824Z'
+ created_at: '2026-05-12T13:52:22.318Z'
+ updated_at: '2026-05-12T13:52:22.318Z'
revoked_at:
last_used_at:
- plaintext_token: sk_W1fgVVQ8cNCx5tiQ6Kyuf1Ft
- created_by_email: [email protected]
+ plaintext_token: sk_pbB3mHVDaFZHB1yThP7eCsbF
+ created_by_email: [email protected]
'422':
description: validation error
content:
@@ -496,11 +496,11 @@ paths:
key_type: publishable
token_prefix:
scopes: []
- created_at: '2026-05-10T19:04:55.133Z'
- updated_at: '2026-05-10T19:04:55.133Z'
+ created_at: '2026-05-12T13:52:22.629Z'
+ updated_at: '2026-05-12T13:52:22.629Z'
revoked_at:
last_used_at:
- plaintext_token: pk_6WiiXiiCrWS9VJXDJ4Xz93QN
+ plaintext_token: pk_oVSDZkT6qSMJ6DpPzrdnbbNs
created_by_email:
delete:
summary: Delete an API key
@@ -590,15 +590,87 @@ paths:
id: key_gbHJdmfrXB
name: Backend integration
key_type: secret
- token_prefix: sk_cGvGbCCnD
+ token_prefix: sk_7SKcTvp8w
scopes:
- write_all
- created_at: '2026-05-10T19:04:55.775Z'
- updated_at: '2026-05-10T19:04:56.059Z'
- revoked_at: '2026-05-10T19:04:56.058Z'
+ created_at: '2026-05-12T13:52:23.206Z'
+ updated_at: '2026-05-12T13:52:23.487Z'
+ revoked_at: '2026-05-12T13:52:23.486Z'
last_used_at:
plaintext_token:
created_by_email:
+ "/api/v3/admin/promotions/{promotion_id}/coupon_codes":
+ parameters:
+ - name: promotion_id
+ in: path
+ required: true
+ schema:
+ type: string
+ get:
+ summary: List coupon codes for a promotion
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Returns the auto-generated coupon codes for a multi-code promotion. Single-code promotions store the code on the promotion itself; this endpoint returns an empty list for them.
+
+ **Required scope:** `read_promotions` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const { data: coupons } = await client.promotions.couponCodes.list('promo_UkLWZg9DAJ')
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: coupon codes found
+ content:
+ application/json:
+ example:
+ data:
+ - id: coupon_UkLWZg9DAJ
+ code: AAA111
+ state: unused
+ created_at: '2026-05-12T13:52:23.503Z'
+ updated_at: '2026-05-12T13:52:23.503Z'
+ promotion_id: promo_UkLWZg9DAJ
+ order_id:
+ - id: coupon_gbHJdmfrXB
+ code: BBB222
+ state: unused
+ created_at: '2026-05-12T13:52:23.504Z'
+ updated_at: '2026-05-12T13:52:23.504Z'
+ promotion_id: promo_UkLWZg9DAJ
+ order_id:
+ meta:
+ page: 1
+ limit: 25
+ count: 2
+ pages: 1
+ from: 1
+ to: 2
+ in: 2
+ previous:
+ next:
"/api/v3/admin/custom_field_definitions":
get:
summary: List custom field definitions
@@ -664,8 +736,8 @@ paths:
field_type: short_text
resource_type: Spree::Product
storefront_visible: true
- created_at: '2026-05-10T19:04:56.069Z'
- updated_at: '2026-05-10T19:04:56.069Z'
+ created_at: '2026-05-12T13:52:23.795Z'
+ updated_at: '2026-05-12T13:52:23.795Z'
- id: cfdef_gbHJdmfrXB
namespace: custom
key: order_notes
@@ -673,8 +745,8 @@ paths:
field_type: short_text
resource_type: Spree::Order
storefront_visible: true
- created_at: '2026-05-10T19:04:56.070Z'
- updated_at: '2026-05-10T19:04:56.070Z'
+ created_at: '2026-05-12T13:52:23.796Z'
+ updated_at: '2026-05-12T13:52:23.796Z'
meta:
page: 1
limit: 25
@@ -737,8 +809,8 @@ paths:
field_type: short_text
resource_type: Spree::Product
storefront_visible: true
- created_at: '2026-05-10T19:04:56.674Z'
- updated_at: '2026-05-10T19:04:56.674Z'
+ created_at: '2026-05-12T13:52:24.351Z'
+ updated_at: '2026-05-12T13:52:24.351Z'
requestBody:
content:
application/json:
@@ -821,8 +893,8 @@ paths:
field_type: short_text
resource_type: Spree::Product
storefront_visible: true
- created_at: '2026-05-10T19:04:56.678Z'
- updated_at: '2026-05-10T19:04:56.678Z'
+ created_at: '2026-05-12T13:52:24.354Z'
+ updated_at: '2026-05-12T13:52:24.354Z'
patch:
summary: Update a custom field definition
tags:
@@ -861,8 +933,8 @@ paths:
field_type: short_text
resource_type: Spree::Product
storefront_visible: false
- created_at: '2026-05-10T19:04:56.961Z'
- updated_at: '2026-05-10T19:04:57.238Z'
+ created_at: '2026-05-12T13:52:24.630Z'
+ updated_at: '2026-05-12T13:52:24.908Z'
requestBody:
content:
application/json:
@@ -984,8 +1056,8 @@ paths:
state_name: New York
label:
metadata: {}
- created_at: '2026-05-10T19:04:57.867Z'
- updated_at: '2026-05-10T19:04:57.867Z'
+ created_at: '2026-05-12T13:52:25.472Z'
+ updated_at: '2026-05-12T13:52:25.472Z'
customer_id: cus_UkLWZg9DAJ
meta:
page: 1
@@ -1073,8 +1145,8 @@ paths:
state_name: New York
label: Office
metadata: {}
- created_at: '2026-05-10T19:04:59.419Z'
- updated_at: '2026-05-10T19:04:59.419Z'
+ created_at: '2026-05-12T13:52:26.816Z'
+ updated_at: '2026-05-12T13:52:26.816Z'
customer_id: cus_UkLWZg9DAJ
requestBody:
content:
@@ -1185,8 +1257,8 @@ paths:
state_name: New York
label:
metadata: {}
- created_at: '2026-05-10T19:04:59.702Z'
- updated_at: '2026-05-10T19:05:00.258Z'
+ created_at: '2026-05-12T13:52:27.086Z'
+ updated_at: '2026-05-12T13:52:27.631Z'
customer_id: cus_UkLWZg9DAJ
requestBody:
content:
@@ -1319,8 +1391,8 @@ paths:
customer_id: cus_UkLWZg9DAJ
payment_method_id: pm_UkLWZg9DAJ
metadata: {}
- created_at: '2026-05-10T19:05:01.504Z'
- updated_at: '2026-05-10T19:05:01.504Z'
+ created_at: '2026-05-12T13:52:28.723Z'
+ updated_at: '2026-05-12T13:52:28.723Z'
meta:
page: 1
limit: 25
@@ -1407,8 +1479,8 @@ paths:
customer_id: cus_UkLWZg9DAJ
payment_method_id: pm_UkLWZg9DAJ
metadata: {}
- created_at: '2026-05-10T19:05:02.190Z'
- updated_at: '2026-05-10T19:05:02.190Z'
+ created_at: '2026-05-12T13:52:29.271Z'
+ updated_at: '2026-05-12T13:52:29.271Z'
delete:
summary: Delete a customer credit card
tags:
@@ -1527,8 +1599,8 @@ paths:
currency: USD
memo:
metadata: {}
- created_at: '2026-05-10T19:05:03.599Z'
- updated_at: '2026-05-10T19:05:03.599Z'
+ created_at: '2026-05-12T13:52:30.629Z'
+ updated_at: '2026-05-12T13:52:30.629Z'
customer_id: cus_UkLWZg9DAJ
created_by_id: admin_UkLWZg9DAJ
category_id: sccat_UkLWZg9DAJ
@@ -1568,7 +1640,7 @@ paths:
const credit = await client.customers.storeCredits.create('cus_UkLWZg9DAJ', {
amount: 25.00,
currency: 'USD',
- category_id: 1,
+ category_id: 'cat_UkLWZg9DAJ',
memo: 'Goodwill credit',
})
parameters:
@@ -1603,8 +1675,8 @@ paths:
currency: USD
memo: Goodwill
metadata: {}
- created_at: '2026-05-10T19:05:04.772Z'
- updated_at: '2026-05-10T19:05:04.772Z'
+ created_at: '2026-05-12T13:52:31.749Z'
+ updated_at: '2026-05-12T13:52:31.749Z'
customer_id: cus_UkLWZg9DAJ
created_by_id: admin_gbHJdmfrXB
category_id: sccat_UkLWZg9DAJ
@@ -1695,8 +1767,8 @@ paths:
currency: USD
memo: Updated
metadata: {}
- created_at: '2026-05-10T19:05:05.319Z'
- updated_at: '2026-05-10T19:05:05.602Z'
+ created_at: '2026-05-12T13:52:32.281Z'
+ updated_at: '2026-05-12T13:52:32.557Z'
customer_id: cus_UkLWZg9DAJ
created_by_id: admin_UkLWZg9DAJ
category_id: sccat_UkLWZg9DAJ
@@ -1850,8 +1922,8 @@ paths:
metadata: {}
last_sign_in_at:
current_sign_in_at:
- created_at: '2026-05-10T19:05:06.688Z'
- updated_at: '2026-05-10T19:05:06.688Z'
+ created_at: '2026-05-12T13:52:33.836Z'
+ updated_at: '2026-05-12T13:52:33.836Z'
sign_in_count: 0
failed_attempts: 0
last_sign_in_ip:
@@ -1934,8 +2006,8 @@ paths:
metadata: {}
last_sign_in_at:
current_sign_in_at:
- created_at: '2026-05-10T19:05:07.528Z'
- updated_at: '2026-05-10T19:05:07.528Z'
+ created_at: '2026-05-12T13:52:34.706Z'
+ updated_at: '2026-05-12T13:52:34.706Z'
sign_in_count: 0
failed_attempts: 0
last_sign_in_ip:
@@ -2051,8 +2123,8 @@ paths:
metadata: {}
last_sign_in_at:
current_sign_in_at:
- created_at: '2026-05-10T19:05:07.797Z'
- updated_at: '2026-05-10T19:05:07.797Z'
+ created_at: '2026-05-12T13:52:34.985Z'
+ updated_at: '2026-05-12T13:52:34.985Z'
sign_in_count: 0
failed_attempts: 0
last_sign_in_ip:
@@ -2126,8 +2198,8 @@ paths:
metadata: {}
last_sign_in_at:
current_sign_in_at:
- created_at: '2026-05-10T19:05:08.341Z'
- updated_at: '2026-05-10T19:05:08.623Z'
+ created_at: '2026-05-12T13:52:35.524Z'
+ updated_at: '2026-05-12T13:52:35.811Z'
sign_in_count: 0
failed_attempts: 0
last_sign_in_ip:
@@ -2249,11 +2321,11 @@ paths:
example:
data:
- id: exp_UkLWZg9DAJ
- number: EF619903416
+ number: EF490857990
type: Spree::Exports::Products
format: csv
- created_at: '2026-05-10T19:05:09.462Z'
- updated_at: '2026-05-10T19:05:09.462Z'
+ created_at: '2026-05-12T13:52:36.786Z'
+ updated_at: '2026-05-12T13:52:36.786Z'
user_id: admin_UkLWZg9DAJ
done: false
filename:
@@ -2320,11 +2392,11 @@ paths:
application/json:
example:
id: exp_gbHJdmfrXB
- number: EF495925650
+ number: EF670540679
type: Spree::Exports::Products
format: csv
- created_at: '2026-05-10T19:05:09.767Z'
- updated_at: '2026-05-10T19:05:09.767Z'
+ created_at: '2026-05-12T13:52:37.137Z'
+ updated_at: '2026-05-12T13:52:37.137Z'
user_id: admin_UkLWZg9DAJ
done: false
filename:
@@ -2411,11 +2483,11 @@ paths:
application/json:
example:
id: exp_UkLWZg9DAJ
- number: EF997071626
+ number: EF081938224
type: Spree::Exports::Products
format: csv
- created_at: '2026-05-10T19:05:10.038Z'
- updated_at: '2026-05-10T19:05:10.038Z'
+ created_at: '2026-05-12T13:52:37.456Z'
+ updated_at: '2026-05-12T13:52:37.456Z'
user_id: admin_UkLWZg9DAJ
done: false
filename:
@@ -2566,15 +2638,15 @@ paths:
example:
data:
- id: inv_UkLWZg9DAJ
status: pending
- created_at: '2026-05-10T19:05:10.925Z'
- updated_at: '2026-05-10T19:05:10.925Z'
- expires_at: '2026-05-24T19:05:10.922Z'
+ created_at: '2026-05-12T13:52:38.323Z'
+ updated_at: '2026-05-12T13:52:38.323Z'
+ expires_at: '2026-05-26T13:52:38.320Z'
role_id: role_UkLWZg9DAJ
role_name: admin
- inviter_email: [email protected]
- acceptance_url: "/accept-invitation/inv_UkLWZg9DAJ?token=Frj9tTVi2QrAJFXDoFotMsdN"
+ inviter_email: [email protected]
+ acceptance_url: "/accept-invitation/inv_UkLWZg9DAJ?token=BEKdzA4XX8ArfFNpekJPb93e"
meta:
page: 1
limit: 25
@@ -2631,13 +2703,13 @@ paths:
id: inv_gbHJdmfrXB
status: pending
- created_at: '2026-05-10T19:05:11.233Z'
- updated_at: '2026-05-10T19:05:11.233Z'
- expires_at: '2026-05-24T19:05:11.231Z'
+ created_at: '2026-05-12T13:52:38.644Z'
+ updated_at: '2026-05-12T13:52:38.644Z'
+ expires_at: '2026-05-26T13:52:38.641Z'
role_id: role_UkLWZg9DAJ
role_name: admin
- inviter_email: [email protected]
- acceptance_url: "/accept-invitation/inv_gbHJdmfrXB?token=5Cksd1c5WHKFZTcWyppmbXkf"
+ inviter_email: [email protected]
+ acceptance_url: "/accept-invitation/inv_gbHJdmfrXB?token=4Sc9HqfZgPB9npnRtjzVBUKB"
requestBody:
content:
application/json:
@@ -2740,15 +2812,15 @@ paths:
application/json:
example:
id: inv_UkLWZg9DAJ
status: pending
- created_at: '2026-05-10T19:05:11.787Z'
- updated_at: '2026-05-10T19:05:11.787Z'
- expires_at: '2026-05-24T19:05:11.785Z'
+ created_at: '2026-05-12T13:52:39.200Z'
+ updated_at: '2026-05-12T13:52:39.200Z'
+ expires_at: '2026-05-26T13:52:39.198Z'
role_id: role_UkLWZg9DAJ
role_name: admin
- inviter_email: [email protected]
- acceptance_url: "/accept-invitation/inv_UkLWZg9DAJ?token=BptfnByw5gUEbkxc9dYwidY6"
+ inviter_email: [email protected]
+ acceptance_url: "/accept-invitation/inv_UkLWZg9DAJ?token=Xo4eyJtBEXxZLodS9RjcgEMC"
"/api/v3/admin/me":
get:
summary: Get current admin user and permissions
@@ -2794,11 +2866,11 @@ paths:
example:
user:
id: admin_UkLWZg9DAJ
- first_name: Irwin
- last_name: Gulgowski
- created_at: '2026-05-10T19:05:12.062Z'
- updated_at: '2026-05-10T19:05:12.062Z'
+ first_name: Albertha
+ last_name: Legros
+ created_at: '2026-05-12T13:52:39.480Z'
+ updated_at: '2026-05-12T13:52:39.480Z'
roles:
- id: role_UkLWZg9DAJ
name: admin
@@ -2947,8 +3019,8 @@ paths:
position: 1
kind: dropdown
metadata: {}
- created_at: '2026-05-10T19:05:12.127Z'
- updated_at: '2026-05-10T19:05:12.127Z'
+ created_at: '2026-05-12T13:52:39.522Z'
+ updated_at: '2026-05-12T13:52:39.522Z'
option_values: []
meta:
page: 1
@@ -3039,8 +3111,8 @@ paths:
position: 2
kind: dropdown
metadata: {}
- created_at: '2026-05-10T19:05:12.721Z'
- updated_at: '2026-05-10T19:05:12.721Z'
+ created_at: '2026-05-12T13:52:40.097Z'
+ updated_at: '2026-05-12T13:52:40.097Z'
option_values: []
schema:
"$ref": "#/components/schemas/OptionType"
@@ -3161,8 +3233,8 @@ paths:
position: 1
kind: dropdown
metadata: {}
- created_at: '2026-05-10T19:05:13.011Z'
- updated_at: '2026-05-10T19:05:13.011Z'
+ created_at: '2026-05-12T13:52:40.384Z'
+ updated_at: '2026-05-12T13:52:40.384Z'
option_values: []
schema:
"$ref": "#/components/schemas/OptionType"
@@ -3234,8 +3306,8 @@ paths:
position: 1
kind: dropdown
metadata: {}
- created_at: '2026-05-10T19:05:13.579Z'
- updated_at: '2026-05-10T19:05:13.860Z'
+ created_at: '2026-05-12T13:52:40.943Z'
+ updated_at: '2026-05-12T13:52:41.222Z'
option_values: []
schema:
"$ref": "#/components/schemas/OptionType"
@@ -3395,7 +3467,7 @@ paths:
example:
data:
- id: ful_UkLWZg9DAJ
- number: H18678087621
+ number: H09289059947
tracking: U10000
tracking_url:
cost: '10.0'
@@ -3420,8 +3492,8 @@ paths:
metadata: {}
adjustment_total: '0.0'
pre_tax_amount: '0.0'
- created_at: '2026-05-10T19:05:14.879Z'
- updated_at: '2026-05-10T19:05:14.971Z'
+ created_at: '2026-05-12T13:52:42.185Z'
+ updated_at: '2026-05-12T13:52:42.284Z'
order_id: or_UkLWZg9DAJ
stock_location_id: sloc_UkLWZg9DAJ
meta:
@@ -3504,7 +3576,7 @@ paths:
application/json:
example:
id: ful_UkLWZg9DAJ
- number: H08398775347
+ number: H83635081160
tracking: U10000
tracking_url:
cost: '10.0'
@@ -3529,8 +3601,8 @@ paths:
metadata: {}
adjustment_total: '0.0'
pre_tax_amount: '0.0'
- created_at: '2026-05-10T19:05:15.585Z'
- updated_at: '2026-05-10T19:05:15.642Z'
+ created_at: '2026-05-12T13:52:42.905Z'
+ updated_at: '2026-05-12T13:52:42.964Z'
order_id: or_UkLWZg9DAJ
stock_location_id: sloc_UkLWZg9DAJ
patch:
@@ -3589,7 +3661,7 @@ paths:
application/json:
example:
id: ful_UkLWZg9DAJ
- number: H39719785623
+ number: H88161575537
tracking: 1Z999AA10123456784
tracking_url: https://wwwapps.ups.com/WebTracking/track?track=yes&trackNums=1Z999AA10123456784
cost: '10.0'
@@ -3614,8 +3686,8 @@ paths:
metadata: {}
adjustment_total: '0.0'
pre_tax_amount: '0.0'
- created_at: '2026-05-10T19:05:16.235Z'
- updated_at: '2026-05-10T19:05:16.599Z'
+ created_at: '2026-05-12T13:52:43.682Z'
+ updated_at: '2026-05-12T13:52:44.248Z'
order_id: or_UkLWZg9DAJ
stock_location_id: sloc_UkLWZg9DAJ
requestBody:
@@ -3684,7 +3756,7 @@ paths:
application/json:
example:
id: ful_UkLWZg9DAJ
- number: H08362693432
+ number: H77493159128
tracking: U10000
tracking_url:
cost: '10.0'
@@ -3701,7 +3773,7 @@ paths:
display_tax_total: "$0.00"
status: shipped
fulfillment_type: shipping
- fulfilled_at: '2026-05-10T19:05:17Z'
+ fulfilled_at: '2026-05-12T13:52:45Z'
items:
- item_id: li_UkLWZg9DAJ
variant_id: variant_UkLWZg9DAJ
@@ -3709,8 +3781,8 @@ paths:
metadata: {}
adjustment_total: '0.0'
pre_tax_amount: '0.0'
- created_at: '2026-05-10T19:05:16.930Z'
- updated_at: '2026-05-10T19:05:17.287Z'
+ created_at: '2026-05-12T13:52:44.612Z'
+ updated_at: '2026-05-12T13:52:45.169Z'
order_id: or_UkLWZg9DAJ
stock_location_id: sloc_UkLWZg9DAJ
"/api/v3/admin/orders/{order_id}/fulfillments/{id}/cancel":
@@ -3768,7 +3840,7 @@ paths:
application/json:
example:
id: ful_UkLWZg9DAJ
- number: H51615127829
+ number: H50748707414
tracking: U10000
tracking_url:
cost: '10.0'
@@ -3793,8 +3865,8 @@ paths:
metadata: {}
adjustment_total: '0.0'
pre_tax_amount: '0.0'
- created_at: '2026-05-10T19:05:17.611Z'
- updated_at: '2026-05-10T19:05:17.993Z'
+ created_at: '2026-05-12T13:52:45.587Z'
+ updated_at: '2026-05-12T13:52:46.030Z'
order_id: or_UkLWZg9DAJ
stock_location_id: sloc_UkLWZg9DAJ
"/api/v3/admin/orders/{order_id}/fulfillments/{id}/resume":
@@ -3852,7 +3924,7 @@ paths:
application/json:
example:
id: ful_UkLWZg9DAJ
- number: H08000233726
+ number: H95632621030
tracking: U10000
tracking_url:
cost: '10.0'
@@ -3877,8 +3949,8 @@ paths:
metadata: {}
adjustment_total: '0.0'
pre_tax_amount: '0.0'
- created_at: '2026-05-10T19:05:18.339Z'
- updated_at: '2026-05-10T19:05:18.701Z'
+ created_at: '2026-05-12T13:52:46.355Z'
+ updated_at: '2026-05-12T13:52:46.710Z'
order_id: or_UkLWZg9DAJ
stock_location_id: sloc_UkLWZg9DAJ
"/api/v3/admin/orders/{order_id}/fulfillments/{id}/split":
@@ -3939,7 +4011,7 @@ paths:
example:
data:
- id: ful_gbHJdmfrXB
- number: H65292498931
+ number: H46349262750
tracking:
tracking_url:
cost: '10.0'
@@ -3964,8 +4036,8 @@ paths:
metadata: {}
adjustment_total: '0.0'
pre_tax_amount: '0.0'
- created_at: '2026-05-10T19:05:19.379Z'
- updated_at: '2026-05-10T19:05:19.422Z'
+ created_at: '2026-05-12T13:52:47.409Z'
+ updated_at: '2026-05-12T13:52:47.463Z'
order_id: or_UkLWZg9DAJ
stock_location_id: sloc_gbHJdmfrXB
requestBody:
@@ -4037,7 +4109,7 @@ paths:
application/json:
example:
id: gc_UkLWZg9DAJ
- code: 29EDB3F4CEC224D3
+ code: B55F3FDE33B25D26
status: active
currency: USD
amount: '10.0'
@@ -4051,8 +4123,8 @@ paths:
redeemed_at:
expired: false
active: true
- created_at: '2026-05-10T19:05:19.786Z'
- updated_at: '2026-05-10T19:05:20.088Z'
+ created_at: '2026-05-12T13:52:47.836Z'
+ updated_at: '2026-05-12T13:52:48.148Z'
requestBody:
content:
application/json:
@@ -4183,8 +4255,8 @@ paths:
variant_id: variant_gbHJdmfrXB
quantity: 2
currency: USD
- name: Product 108314
- slug: product-108314
+ name: Product 102850
+ slug: product-102850
options_text: 'Size: S'
price: '10.0'
display_price: "$10.00"
@@ -4216,12 +4288,12 @@ paths:
option_type_label: Size
image_url:
metadata: {}
- created_at: '2026-05-10T19:05:20.776Z'
- updated_at: '2026-05-10T19:05:20.776Z'
+ created_at: '2026-05-12T13:52:48.863Z'
+ updated_at: '2026-05-12T13:52:48.863Z'
digital_links: []
metadata: {}
- created_at: '2026-05-10T19:05:21.065Z'
- updated_at: '2026-05-10T19:05:21.065Z'
+ created_at: '2026-05-12T13:52:49.187Z'
+ updated_at: '2026-05-12T13:52:49.187Z'
cost_price: '17.0'
tax_category_id: taxcat_UkLWZg9DAJ
meta:
@@ -4288,8 +4360,8 @@ paths:
variant_id: variant_VqXmZF31wY
quantity: 3
currency: USD
- name: Product 124883
- slug: product-124883
+ name: Product 126661
+ slug: product-126661
options_text: 'Size: S'
price: '19.99'
display_price: "$19.99"
@@ -4321,12 +4393,12 @@ paths:
option_type_label: Size
image_url:
metadata: {}
- created_at: '2026-05-10T19:05:22.076Z'
- updated_at: '2026-05-10T19:05:22.076Z'
+ created_at: '2026-05-12T13:52:50.283Z'
+ updated_at: '2026-05-12T13:52:50.283Z'
digital_links: []
metadata: {}
- created_at: '2026-05-10T19:05:22.113Z'
- updated_at: '2026-05-10T19:05:22.113Z'
+ created_at: '2026-05-12T13:52:50.551Z'
+ updated_at: '2026-05-12T13:52:50.551Z'
cost_price: '17.0'
tax_category_id: taxcat_UkLWZg9DAJ
requestBody:
@@ -4415,8 +4487,8 @@ paths:
variant_id: variant_gbHJdmfrXB
quantity: 2
currency: USD
- name: Product 137551
- slug: product-137551
+ name: Product 138760
+ slug: product-138760
options_text: 'Size: S'
price: '10.0'
display_price: "$10.00"
@@ -4448,12 +4520,12 @@ paths:
option_type_label: Size
image_url:
metadata: {}
- created_at: '2026-05-10T19:05:22.188Z'
- updated_at: '2026-05-10T19:05:22.188Z'
+ created_at: '2026-05-12T13:52:50.629Z'
+ updated_at: '2026-05-12T13:52:50.629Z'
digital_links: []
metadata: {}
- created_at: '2026-05-10T19:05:22.476Z'
- updated_at: '2026-05-10T19:05:22.476Z'
+ created_at: '2026-05-12T13:52:50.920Z'
+ updated_at: '2026-05-12T13:52:50.920Z'
cost_price: '17.0'
tax_category_id: taxcat_UkLWZg9DAJ
patch:
@@ -4515,8 +4587,8 @@ paths:
variant_id: variant_gbHJdmfrXB
quantity: 5
currency: USD
- name: Product 148612
- slug: product-148612
+ name: Product 148537
+ slug: product-148537
options_text: 'Size: S'
price: '19.99'
display_price: "$19.99"
@@ -4548,12 +4620,12 @@ paths:
option_type_label: Size
image_url:
metadata: {}
- created_at: '2026-05-10T19:05:22.804Z'
- updated_at: '2026-05-10T19:05:22.804Z'
+ created_at: '2026-05-12T13:52:51.242Z'
+ updated_at: '2026-05-12T13:52:51.242Z'
digital_links: []
metadata: {}
- created_at: '2026-05-10T19:05:23.091Z'
- updated_at: '2026-05-10T19:05:23.388Z'
+ created_at: '2026-05-12T13:52:51.531Z'
+ updated_at: '2026-05-12T13:52:51.951Z'
cost_price: '17.0'
tax_category_id: taxcat_UkLWZg9DAJ
requestBody:
@@ -4679,8 +4751,8 @@ paths:
data:
- id: py_UkLWZg9DAJ
payment_method_id: pm_UkLWZg9DAJ
- response_code: BGS-bbf309e2f363
- number: POJB0JYY
+ response_code: BGS-def187403c5d
+ number: P33KWFRB
amount: '110.0'
display_amount: "$110.00"
status: completed
@@ -4698,14 +4770,14 @@ paths:
customer_id:
payment_method_id: pm_gbHJdmfrXB
metadata: {}
- created_at: '2026-05-10T19:05:24.400Z'
- updated_at: '2026-05-10T19:05:24.404Z'
+ created_at: '2026-05-12T13:52:53.007Z'
+ updated_at: '2026-05-12T13:52:53.012Z'
metadata: {}
avs_response:
cvv_response_code:
cvv_response_message:
- created_at: '2026-05-10T19:05:24.402Z'
- updated_at: '2026-05-10T19:05:24.402Z'
+ created_at: '2026-05-12T13:52:53.010Z'
+ updated_at: '2026-05-12T13:52:53.010Z'
captured_amount: '0.0'
order_id: or_UkLWZg9DAJ
meta:
@@ -4772,7 +4844,7 @@ paths:
id: py_gbHJdmfrXB
payment_method_id: pm_EfhxLZ9ck8
response_code:
- number: PAR7TWVK
+ number: PCM1VIMO
amount: '110.0'
display_amount: "$110.00"
status: checkout
@@ -4783,8 +4855,8 @@ paths:
avs_response:
cvv_response_code:
cvv_response_message:
- created_at: '2026-05-10T19:05:25.702Z'
- updated_at: '2026-05-10T19:05:25.702Z'
+ created_at: '2026-05-12T13:52:54.512Z'
+ updated_at: '2026-05-12T13:52:54.512Z'
captured_amount: '0.0'
order_id: or_gbHJdmfrXB
requestBody:
@@ -4874,8 +4946,8 @@ paths:
example:
id: py_UkLWZg9DAJ
payment_method_id: pm_UkLWZg9DAJ
- response_code: BGS-386ab0a10734
- number: PFTJT6UH
+ response_code: BGS-0e1ae0134be4
+ number: PQBU2BJL
amount: '110.0'
display_amount: "$110.00"
status: completed
@@ -4893,14 +4965,14 @@ paths:
customer_id:
payment_method_id: pm_gbHJdmfrXB
metadata: {}
- created_at: '2026-05-10T19:05:26.087Z'
- updated_at: '2026-05-10T19:05:26.090Z'
+ created_at: '2026-05-12T13:52:54.910Z'
+ updated_at: '2026-05-12T13:52:54.913Z'
metadata: {}
avs_response:
cvv_response_code:
cvv_response_message:
- created_at: '2026-05-10T19:05:26.089Z'
- updated_at: '2026-05-10T19:05:26.089Z'
+ created_at: '2026-05-12T13:52:54.912Z'
+ updated_at: '2026-05-12T13:52:54.912Z'
captured_amount: '0.0'
order_id: or_UkLWZg9DAJ
"/api/v3/admin/orders/{order_id}/payments/{id}/capture":
@@ -4959,8 +5031,8 @@ paths:
example:
id: py_UkLWZg9DAJ
payment_method_id: pm_UkLWZg9DAJ
- response_code: BGS-ce84a3f7ed9f
- number: P5MER82K
+ response_code: BGS-1761630c1fa3
+ number: P9JGM2QJ
amount: '110.0'
display_amount: "$110.00"
status: completed
@@ -4978,14 +5050,14 @@ paths:
customer_id:
payment_method_id: pm_gbHJdmfrXB
metadata: {}
- created_at: '2026-05-10T19:05:26.742Z'
- updated_at: '2026-05-10T19:05:26.745Z'
+ created_at: '2026-05-12T13:52:55.693Z'
+ updated_at: '2026-05-12T13:52:55.701Z'
metadata: {}
avs_response:
cvv_response_code:
cvv_response_message:
- created_at: '2026-05-10T19:05:26.744Z'
- updated_at: '2026-05-10T19:05:27.079Z'
+ created_at: '2026-05-12T13:52:55.699Z'
+ updated_at: '2026-05-12T13:52:56.070Z'
captured_amount: '110.0'
order_id: or_UkLWZg9DAJ
'422':
@@ -5054,8 +5126,8 @@ paths:
example:
id: py_UkLWZg9DAJ
payment_method_id: pm_UkLWZg9DAJ
- response_code: void-BGS-d840cf659b24
- number: PPQZJCO8
+ response_code: void-BGS-819e3f798e82
+ number: PR43WTXS
amount: '110.0'
display_amount: "$110.00"
status: void
@@ -5073,14 +5145,14 @@ paths:
customer_id:
payment_method_id: pm_gbHJdmfrXB
metadata: {}
- created_at: '2026-05-10T19:05:28.173Z'
- updated_at: '2026-05-10T19:05:28.175Z'
+ created_at: '2026-05-12T13:52:57.393Z'
+ updated_at: '2026-05-12T13:52:57.396Z'
metadata: {}
avs_response:
cvv_response_code:
cvv_response_message:
- created_at: '2026-05-10T19:05:28.174Z'
- updated_at: '2026-05-10T19:05:28.474Z'
+ created_at: '2026-05-12T13:52:57.395Z'
+ updated_at: '2026-05-12T13:52:57.738Z'
captured_amount: '0.0'
order_id: or_UkLWZg9DAJ
"/api/v3/admin/orders/{order_id}/refunds":
@@ -5208,14 +5280,14 @@ paths:
application/json:
example:
id: re_UkLWZg9DAJ
- transaction_id: BGS-ddcac879d3ca
+ transaction_id: BGS-951b7f624e1d
amount: '5.0'
payment_id: py_UkLWZg9DAJ
refund_reason_id: rr_UkLWZg9DAJ
reimbursement_id:
metadata: {}
- created_at: '2026-05-10T19:05:29.827Z'
- updated_at: '2026-05-10T19:05:29.827Z'
+ created_at: '2026-05-12T13:52:59.158Z'
+ updated_at: '2026-05-12T13:52:59.158Z'
requestBody:
content:
application/json:
@@ -5287,8 +5359,8 @@ paths:
id: or_UkLWZg9DAJ
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R426893365
+ number: R980291368
customer_note:
currency: USD
locale: en
@@ -5331,8 +5403,8 @@ paths:
metadata: {}
canceled_at:
approved_at:
- created_at: '2026-05-10T19:05:30.126Z'
- updated_at: '2026-05-10T19:05:30.174Z'
+ created_at: '2026-05-12T13:52:59.462Z'
+ updated_at: '2026-05-12T13:52:59.520Z'
preferred_stock_location_id:
tags: []
internal_note:
@@ -5503,8 +5575,8 @@ paths:
- id: or_UkLWZg9DAJ
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R469979825
+ number: R433237846
customer_note:
currency: USD
locale: en
@@ -5547,8 +5619,8 @@ paths:
metadata: {}
canceled_at:
approved_at:
- created_at: '2026-05-10T19:05:31.913Z'
- updated_at: '2026-05-10T19:05:31.913Z'
+ created_at: '2026-05-12T13:53:01.302Z'
+ updated_at: '2026-05-12T13:53:01.302Z'
preferred_stock_location_id:
tags: []
internal_note:
@@ -5691,7 +5763,7 @@ paths:
id: or_gbHJdmfrXB
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R468200665
+ number: R331514986
customer_note:
currency: USD
@@ -5735,8 +5807,8 @@ paths:
metadata: {}
canceled_at:
approved_at:
- created_at: '2026-05-10T19:05:33.658Z'
- updated_at: '2026-05-10T19:05:33.661Z'
+ created_at: '2026-05-12T13:53:03.002Z'
+ updated_at: '2026-05-12T13:53:03.005Z'
preferred_stock_location_id: sloc_UkLWZg9DAJ
tags: []
internal_note:
@@ -5920,8 +5992,8 @@ paths:
id: or_UkLWZg9DAJ
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R806837587
+ number: R055386525
customer_note:
currency: USD
locale: en
@@ -5964,8 +6036,8 @@ paths:
metadata: {}
canceled_at:
approved_at:
- created_at: '2026-05-10T19:05:33.943Z'
- updated_at: '2026-05-10T19:05:33.943Z'
+ created_at: '2026-05-12T13:53:03.283Z'
+ updated_at: '2026-05-12T13:53:03.283Z'
preferred_stock_location_id:
tags: []
internal_note:
@@ -6036,7 +6108,7 @@ paths:
id: or_UkLWZg9DAJ
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R338377254
+ number: R715802260
customer_note:
currency: USD
@@ -6080,8 +6152,8 @@ paths:
metadata: {}
canceled_at:
approved_at:
- created_at: '2026-05-10T19:05:35.056Z'
- updated_at: '2026-05-10T19:05:35.343Z'
+ created_at: '2026-05-12T13:53:04.378Z'
+ updated_at: '2026-05-12T13:53:04.673Z'
preferred_stock_location_id:
tags: []
internal_note:
@@ -6262,8 +6334,8 @@ paths:
id: or_UkLWZg9DAJ
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R303184460
+ number: R870176568
customer_note:
currency: USD
locale: en
@@ -6290,7 +6362,7 @@ paths:
display_delivery_total: "$100.00"
fulfillment_status: ready
payment_status: paid
- completed_at: '2026-05-10T19:05:36.294Z'
+ completed_at: '2026-05-12T13:53:05.593Z'
store_credit_total: '0.0'
display_store_credit_total: "$0.00"
covered_by_store_credit: false
@@ -6306,8 +6378,8 @@ paths:
metadata: {}
canceled_at:
approved_at:
- created_at: '2026-05-10T19:05:36.196Z'
- updated_at: '2026-05-10T19:05:36.353Z'
+ created_at: '2026-05-12T13:53:05.519Z'
+ updated_at: '2026-05-12T13:53:05.619Z'
preferred_stock_location_id:
tags: []
internal_note:
@@ -6388,8 +6460,8 @@ paths:
id: or_UkLWZg9DAJ
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R392180445
+ number: R758905493
customer_note:
currency: USD
locale: en
@@ -6416,7 +6488,7 @@ paths:
display_delivery_total: "$10.00"
fulfillment_status: canceled
payment_status: void
- completed_at: '2026-05-10T19:05:37.619Z'
+ completed_at: '2026-05-12T13:53:06.868Z'
store_credit_total: '0.0'
display_store_credit_total: "$0.00"
covered_by_store_credit: false
@@ -6430,10 +6502,10 @@ paths:
payment_total: '0.0'
display_payment_total: "$0.00"
metadata: {}
- canceled_at: '2026-05-10T19:05:37.910Z'
+ canceled_at: '2026-05-12T13:53:07.162Z'
approved_at:
- created_at: '2026-05-10T19:05:37.563Z'
- updated_at: '2026-05-10T19:05:37.949Z'
+ created_at: '2026-05-12T13:53:06.812Z'
+ updated_at: '2026-05-12T13:53:07.215Z'
preferred_stock_location_id:
tags: []
internal_note:
@@ -6492,8 +6564,8 @@ paths:
id: or_UkLWZg9DAJ
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R704788094
+ number: R066309680
customer_note:
currency: USD
locale: en
@@ -6520,7 +6592,7 @@ paths:
display_delivery_total: "$100.00"
fulfillment_status:
payment_status:
- completed_at: '2026-05-10T19:05:38.297Z'
+ completed_at: '2026-05-12T13:53:07.579Z'
store_credit_total: '0.0'
display_store_credit_total: "$0.00"
covered_by_store_credit: false
@@ -6535,9 +6607,9 @@ paths:
display_payment_total: "$0.00"
metadata: {}
canceled_at:
- approved_at: '2026-05-10T19:05:38.594Z'
- created_at: '2026-05-10T19:05:38.244Z'
- updated_at: '2026-05-10T19:05:38.297Z'
+ approved_at: '2026-05-12T13:53:07.875Z'
+ created_at: '2026-05-12T13:53:07.521Z'
+ updated_at: '2026-05-12T13:53:07.579Z'
preferred_stock_location_id:
tags: []
internal_note:
@@ -6596,8 +6668,8 @@ paths:
id: or_UkLWZg9DAJ
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R573392501
+ number: R076714967
customer_note:
currency: USD
locale: en
@@ -6624,7 +6696,7 @@ paths:
display_delivery_total: "$10.00"
fulfillment_status: canceled
payment_status: void
- completed_at: '2026-05-10T19:05:38.939Z'
+ completed_at: '2026-05-12T13:53:08.214Z'
store_credit_total: '0.0'
display_store_credit_total: "$0.00"
covered_by_store_credit: false
@@ -6638,10 +6710,10 @@ paths:
payment_total: '0.0'
display_payment_total: "$0.00"
metadata: {}
- canceled_at: '2026-05-10T19:05:39.216Z'
+ canceled_at: '2026-05-12T13:53:08.496Z'
approved_at:
- created_at: '2026-05-10T19:05:38.880Z'
- updated_at: '2026-05-10T19:05:39.297Z'
+ created_at: '2026-05-12T13:53:08.157Z'
+ updated_at: '2026-05-12T13:53:08.587Z'
preferred_stock_location_id:
tags: []
internal_note:
@@ -6700,8 +6772,8 @@ paths:
id: or_UkLWZg9DAJ
market_id:
channel_id: ch_UkLWZg9DAJ
- number: R853852389
+ number: R141869974
customer_note:
currency: USD
locale: en
@@ -6728,7 +6800,7 @@ paths:
display_delivery_total: "$100.00"
fulfillment_status:
payment_status:
- completed_at: '2026-05-10T19:05:39.640Z'
+ completed_at: '2026-05-12T13:53:08.937Z'
store_credit_total: '0.0'
display_store_credit_total: "$0.00"
covered_by_store_credit: false
@@ -6744,8 +6816,8 @@ paths:
metadata: {}
canceled_at:
approved_at:
- created_at: '2026-05-10T19:05:39.584Z'
- updated_at: '2026-05-10T19:05:39.640Z'
+ created_at: '2026-05-12T13:53:08.868Z'
+ updated_at: '2026-05-12T13:53:08.937Z'
preferred_stock_location_id:
tags: []
internal_note:
@@ -6812,14 +6884,18 @@ paths:
- id: pm_UkLWZg9DAJ
name: Check
description:
- type: Spree::PaymentMethod::Check
+ type: check
session_required: false
source_required: false
metadata: {}
active: true
auto_capture:
- created_at: '2026-05-10T19:05:39.941Z'
- updated_at: '2026-05-10T19:05:39.942Z'
+ display_on: both
+ position: 1
+ created_at: '2026-05-12T13:53:09.238Z'
+ updated_at: '2026-05-12T13:53:09.239Z'
+ preferences: {}
+ preference_schema: []
meta:
page: 1
limit: 25
@@ -6830,6 +6906,62 @@ paths:
in: 1
previous:
next:
+ "/api/v3/admin/payment_methods/types":
+ get:
+ summary: List available payment provider types
+ tags:
+ - Configuration
+ 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.
+
+ **Required scope:** `read_settings` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const { data: types } = await client.paymentMethods.types()
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: provider types found
+ content:
+ application/json:
+ example:
+ data:
+ - type: bogus
+ label: Bogus
+ description:
+ preference_schema:
+ - key: dummy_key
+ type: string
+ default: PUBLICKEY123
+ - key: dummy_secret_key
+ type: password
+ default: SECRETKEY123
+ - type: custom_payment_source_method
+ label: Custom Payment Source Method
+ description:
+ preference_schema: []
"/api/v3/admin/payment_methods/{id}":
get:
summary: Show a payment method
@@ -6893,14 +7025,18 @@ paths:
id: pm_UkLWZg9DAJ
name: Check
description:
- type: Spree::PaymentMethod::Check
+ type: check
session_required: false
source_required: false
metadata: {}
active: true
auto_capture:
- created_at: '2026-05-10T19:05:40.228Z'
- updated_at: '2026-05-10T19:05:40.229Z'
+ display_on: both
+ position: 1
+ created_at: '2026-05-12T13:53:09.813Z'
+ updated_at: '2026-05-12T13:53:09.814Z'
+ preferences: {}
+ preference_schema: []
"/api/v3/admin/products/{product_id}/custom_fields":
get:
summary: List product custom fields
@@ -6968,8 +7104,8 @@ paths:
field_type: short_text
key: custom.title
value: wool
- created_at: '2026-05-10T19:05:40.540Z'
- updated_at: '2026-05-10T19:05:40.540Z'
+ created_at: '2026-05-12T13:53:10.133Z'
+ updated_at: '2026-05-12T13:53:10.133Z'
storefront_visible: true
custom_field_definition_id: cfdef_UkLWZg9DAJ
meta:
@@ -7036,8 +7172,8 @@ paths:
field_type: long_text
key: custom.description
value: A longer description
- created_at: '2026-05-10T19:05:41.164Z'
- updated_at: '2026-05-10T19:05:41.164Z'
+ created_at: '2026-05-12T13:53:10.741Z'
+ updated_at: '2026-05-12T13:53:10.741Z'
storefront_visible: true
custom_field_definition_id: cfdef_gbHJdmfrXB
'422':
@@ -7121,8 +7257,8 @@ paths:
field_type: short_text
key: custom.title
value: wool
- created_at: '2026-05-10T19:05:41.520Z'
- updated_at: '2026-05-10T19:05:41.520Z'
+ created_at: '2026-05-12T13:53:11.118Z'
+ updated_at: '2026-05-12T13:53:11.118Z'
storefront_visible: true
custom_field_definition_id: cfdef_UkLWZg9DAJ
patch:
@@ -7169,8 +7305,8 @@ paths:
field_type: short_text
key: custom.title
value: cotton
- created_at: '2026-05-10T19:05:41.838Z'
- updated_at: '2026-05-10T19:05:42.118Z'
+ created_at: '2026-05-12T13:53:11.441Z'
+ updated_at: '2026-05-12T13:53:11.718Z'
storefront_visible: true
custom_field_definition_id: cfdef_UkLWZg9DAJ
requestBody:
@@ -7308,30 +7444,24 @@ paths:
example:
data:
- id: prod_UkLWZg9DAJ
- name: Product 392413
- slug: product-392413
+ name: Product 393215
+ slug: product-393215
meta_description:
meta_keywords:
variant_count: 0
- available_on: '2025-05-10T19:05:42.440Z'
+ available_on: '2025-05-12T13:53:12.038Z'
purchasable: true
in_stock: false
backorderable: true
available: true
- description: Sed sit corrupti animi quasi ipsum quo. Sapiente nihil
- consequatur voluptate qui quibusdam. Vel laboriosam nihil sint
- nulla. Optio voluptate dolores veritatis incidunt. Enim magni
- unde iusto quidem id. Quaerat iste reiciendis dolores voluptatum
- similique provident. Aspernatur pariatur perspiciatis asperiores
- sit veniam. Aspernatur fugit eligendi iste doloremque blanditiis
- iusto sunt. Expedita similique totam incidunt tempore eum itaque
- quod. Reiciendis quasi ex tempora dolor quis repudiandae. Dolore
- minima fugiat laudantium repellendus assumenda magnam similique
- consequuntur.
- description_html: |-
- Sed sit corrupti animi quasi ipsum quo. Sapiente nihil consequatur voluptate qui quibusdam. Vel laboriosam nihil sint nulla.
- Optio voluptate dolores veritatis incidunt. Enim magni unde iusto quidem id. Quaerat iste reiciendis dolores voluptatum similique provident. Aspernatur pariatur perspiciatis asperiores sit veniam.
- Aspernatur fugit eligendi iste doloremque blanditiis iusto sunt. Expedita similique totam incidunt tempore eum itaque quod. Reiciendis quasi ex tempora dolor quis repudiandae. Dolore minima fugiat laudantium repellendus assumenda magnam similique consequuntur.
+ description: Voluptatum placeat enim saepe provident. Provident
+ illo reprehenderit ut illum rem voluptas nemo. Quia voluptas consequatur
+ rerum quam repellendus quis a eveniet. Magnam dicta ea dolorum
+ fuga voluptatem et beatae ab.
+ description_html: Voluptatum placeat enim saepe provident. Provident
+ illo reprehenderit ut illum rem voluptas nemo. Quia voluptas consequatur
+ rerum quam repellendus quis a eveniet. Magnam dicta ea dolorum
+ fuga voluptatem et beatae ab.
default_variant_id: variant_UkLWZg9DAJ
thumbnail_url:
tags: []
@@ -7346,16 +7476,16 @@ paths:
display_compare_at_amount:
price_list_id:
variant_id: variant_UkLWZg9DAJ
- created_at: '2026-05-10T19:05:42.463Z'
- updated_at: '2026-05-10T19:05:42.463Z'
+ created_at: '2026-05-12T13:53:12.063Z'
+ updated_at: '2026-05-12T13:53:12.063Z'
original_price:
status: active
- make_active_at: '2025-05-10T19:05:42.440Z'
+ make_active_at: '2025-05-12T13:53:12.038Z'
discontinue_on:
metadata: {}
deleted_at:
- created_at: '2026-05-10T19:05:42.451Z'
- updated_at: '2026-05-10T19:05:42.464Z'
+ created_at: '2026-05-12T13:53:12.051Z'
+ updated_at: '2026-05-12T13:53:12.064Z'
cost_price: '17.0'
cost_currency: USD
meta:
@@ -7494,16 +7624,16 @@ paths:
display_compare_at_amount:
price_list_id:
variant_id: variant_gbHJdmfrXB
- created_at: '2026-05-10T19:05:43.151Z'
- updated_at: '2026-05-10T19:05:43.151Z'
+ created_at: '2026-05-12T13:53:12.739Z'
+ updated_at: '2026-05-12T13:53:12.739Z'
original_price:
status: draft
make_active_at:
discontinue_on:
metadata: {}
deleted_at:
- created_at: '2026-05-10T19:05:43.149Z'
- updated_at: '2026-05-10T19:05:43.155Z'
+ created_at: '2026-05-12T13:53:12.737Z'
+ updated_at: '2026-05-12T13:53:12.744Z'
cost_price:
cost_currency: USD
schema:
@@ -7690,42 +7820,24 @@ paths:
application/json:
example:
id: prod_UkLWZg9DAJ
- name: Product 431433
- slug: product-431433
+ name: Product 432135
+ slug: product-432135
meta_description:
meta_keywords:
variant_count: 0
- available_on: '2025-05-10T19:05:43.495Z'
+ available_on: '2025-05-12T13:53:13.100Z'
purchasable: true
in_stock: false
backorderable: true
available: true
- description: Quas eos vitae odio atque perferendis iste vel dicta.
- Officia amet quod ipsam quibusdam quidem consequuntur nostrum. Esse
- quis assumenda nesciunt maxime recusandae quod illo. Corrupti error
- vitae nostrum eaque quas veniam. Labore cupiditate hic praesentium
- dignissimos deleniti nemo incidunt. Vitae et sapiente autem natus.
- Laudantium aperiam fuga deleniti consequatur. Repellat unde natus
- praesentium doloremque dicta similique aut possimus. Tempore facilis
- molestias adipisci soluta quo. Ex adipisci delectus sequi alias.
- Odit corrupti velit amet id officiis ducimus laboriosam autem. Eos
- vero ex voluptate harum sequi quisquam nemo odio. Vel architecto
- doloribus animi ea fuga esse. Voluptatem provident atque dolore
- beatae minus ea debitis id. Expedita architecto provident dolorem
- non reprehenderit maiores sint in. In sint maiores aliquam commodi
- delectus iusto. Mollitia possimus quod cumque blanditiis sit. Nobis
- qui dolorum fugit incidunt assumenda iusto dolor. Ab asperiores
- praesentium illo quos eaque maxime fugit voluptatum. Reiciendis
- praesentium tempore cupiditate illum iusto ullam assumenda labore.
- Soluta rerum repellendus cupiditate nam placeat asperiores ullam.
- Atque possimus porro animi quia quidem aut. Fugiat velit maiores
- aliquam earum.
- description_html: |-
- Quas eos vitae odio atque perferendis iste vel dicta. Officia amet quod ipsam quibusdam quidem consequuntur nostrum. Esse quis assumenda nesciunt maxime recusandae quod illo. Corrupti error vitae nostrum eaque quas veniam. Labore cupiditate hic praesentium dignissimos deleniti nemo incidunt.
- Vitae et sapiente autem natus. Laudantium aperiam fuga deleniti consequatur. Repellat unde natus praesentium doloremque dicta similique aut possimus. Tempore facilis molestias adipisci soluta quo.
- Ex adipisci delectus sequi alias. Odit corrupti velit amet id officiis ducimus laboriosam autem. Eos vero ex voluptate harum sequi quisquam nemo odio. Vel architecto doloribus animi ea fuga esse. Voluptatem provident atque dolore beatae minus ea debitis id.
- Expedita architecto provident dolorem non reprehenderit maiores sint in. In sint maiores aliquam commodi delectus iusto. Mollitia possimus quod cumque blanditiis sit. Nobis qui dolorum fugit incidunt assumenda iusto dolor.
- Ab asperiores praesentium illo quos eaque maxime fugit voluptatum. Reiciendis praesentium tempore cupiditate illum iusto ullam assumenda labore. Soluta rerum repellendus cupiditate nam placeat asperiores ullam. Atque possimus porro animi quia quidem aut. Fugiat velit maiores aliquam earum.
+ description: Dolorum animi deleniti soluta nostrum. Iusto excepturi
+ eos pariatur veniam eligendi sapiente numquam. Impedit expedita
+ eveniet animi voluptatibus perspiciatis distinctio fugiat. Praesentium
+ corporis laboriosam unde harum eaque pariatur.
+ description_html: Dolorum animi deleniti soluta nostrum. Iusto excepturi
+ eos pariatur veniam eligendi sapiente numquam. Impedit expedita
+ eveniet animi voluptatibus perspiciatis distinctio fugiat. Praesentium
+ corporis laboriosam unde harum eaque pariatur.
default_variant_id: variant_UkLWZg9DAJ
thumbnail_url:
tags: []
@@ -7740,16 +7852,16 @@ paths:
display_compare_at_amount:
price_list_id:
variant_id: variant_UkLWZg9DAJ
- created_at: '2026-05-10T19:05:43.536Z'
- updated_at: '2026-05-10T19:05:43.536Z'
+ created_at: '2026-05-12T13:53:13.129Z'
+ updated_at: '2026-05-12T13:53:13.129Z'
original_price:
status: active
- make_active_at: '2025-05-10T19:05:43.495Z'
+ make_active_at: '2025-05-12T13:53:13.100Z'
discontinue_on:
metadata: {}
deleted_at:
- created_at: '2026-05-10T19:05:43.511Z'
- updated_at: '2026-05-10T19:05:43.538Z'
+ created_at: '2026-05-12T13:53:13.115Z'
+ updated_at: '2026-05-12T13:53:13.131Z'
cost_price: '17.0'
cost_currency: USD
schema:
@@ -7817,39 +7929,23 @@ paths:
example:
id: prod_UkLWZg9DAJ
name: Updated Name
- slug: product-45349
+ slug: product-457382
meta_description:
meta_keywords:
variant_count: 0
- available_on: '2025-05-10T19:05:44.221Z'
+ available_on: '2025-05-12T13:53:13.752Z'
purchasable: true
in_stock: false
backorderable: true
available: true
- description: Quis aperiam tempora molestias architecto minima debitis
- expedita. Laboriosam nam aspernatur repudiandae modi reiciendis
- iure neque. Reprehenderit amet explicabo cumque voluptatem asperiores
- nisi dolore dignissimos. Esse a nostrum tempore at laudantium exercitationem
- reiciendis. Voluptate libero corrupti odio aut quae saepe mollitia.
- Porro recusandae ratione consequatur non explicabo. Ea assumenda
- vel consequuntur adipisci repudiandae odit. A magnam saepe temporibus
- voluptates. Cumque minus rerum culpa cum non. Aliquid nesciunt dolorum
- necessitatibus officia repudiandae quisquam. Nostrum iure facere
- at id. Ab temporibus explicabo dolorum unde facilis. Velit rerum
- provident aperiam nostrum fugit. Perferendis magni voluptate consectetur
- asperiores esse aliquid eligendi. Ipsum repellat voluptatem fuga
- illum corporis consectetur saepe iusto. Porro vel quod libero culpa
- facilis possimus aperiam suscipit. Quidem totam magnam perferendis
- ab dicta. Laudantium nesciunt beatae quis libero saepe deleniti
- suscipit asperiores. Exercitationem tenetur consectetur perspiciatis
- veritatis. Cumque nemo doloremque odit nostrum voluptatem qui a
- incidunt. Quos cumque adipisci velit ullam dolore dicta exercitationem.
- description_html: |-
- Quis aperiam tempora molestias architecto minima debitis expedita. Laboriosam nam aspernatur repudiandae modi reiciendis iure neque. Reprehenderit amet explicabo cumque voluptatem asperiores nisi dolore dignissimos. Esse a nostrum tempore at laudantium exercitationem reiciendis. Voluptate libero corrupti odio aut quae saepe mollitia.
- Porro recusandae ratione consequatur non explicabo. Ea assumenda vel consequuntur adipisci repudiandae odit. A magnam saepe temporibus voluptates. Cumque minus rerum culpa cum non. Aliquid nesciunt dolorum necessitatibus officia repudiandae quisquam.
- Nostrum iure facere at id. Ab temporibus explicabo dolorum unde facilis. Velit rerum provident aperiam nostrum fugit.
- Perferendis magni voluptate consectetur asperiores esse aliquid eligendi. Ipsum repellat voluptatem fuga illum corporis consectetur saepe iusto. Porro vel quod libero culpa facilis possimus aperiam suscipit.
- Quidem totam magnam perferendis ab dicta. Laudantium nesciunt beatae quis libero saepe deleniti suscipit asperiores. Exercitationem tenetur consectetur perspiciatis veritatis. Cumque nemo doloremque odit nostrum voluptatem qui a incidunt. Quos cumque adipisci velit ullam dolore dicta exercitationem.
+ description: Esse a explicabo quibusdam qui. Facilis dolorum totam
+ porro odio amet aspernatur consequuntur. Architecto provident itaque
+ quis voluptatem quisquam tempore quae. Ipsum et voluptate a consequatur
+ voluptas consequuntur ex pariatur.
+ description_html: Esse a explicabo quibusdam qui. Facilis dolorum
+ totam porro odio amet aspernatur consequuntur. Architecto provident
+ itaque quis voluptatem quisquam tempore quae. Ipsum et voluptate
+ a consequatur voluptas consequuntur ex pariatur.
default_variant_id: variant_UkLWZg9DAJ
thumbnail_url:
tags: []
@@ -7864,16 +7960,16 @@ paths:
display_compare_at_amount:
price_list_id:
variant_id: variant_UkLWZg9DAJ
- created_at: '2026-05-10T19:05:44.249Z'
- updated_at: '2026-05-10T19:05:44.249Z'
+ created_at: '2026-05-12T13:53:13.783Z'
+ updated_at: '2026-05-12T13:53:13.783Z'
original_price:
status: active
- make_active_at: '2025-05-10T19:05:44.222Z'
+ make_active_at: '2025-05-12T13:53:13.752Z'
discontinue_on:
metadata: {}
deleted_at:
- created_at: '2026-05-10T19:05:44.236Z'
- updated_at: '2026-05-10T19:05:44.537Z'
+ created_at: '2026-05-12T13:53:13.768Z'
+ updated_at: '2026-05-12T13:53:14.073Z'
cost_price: '17.0'
cost_currency: USD
schema:
@@ -8036,18 +8132,21 @@ paths:
responses:
'204':
description: product deleted
- "/api/v3/admin/roles":
+ "/api/v3/admin/promotions/{promotion_id}/promotion_actions":
+ parameters:
+ - name: promotion_id
+ in: path
+ required: true
+ schema:
+ type: string
get:
- summary: List roles
+ summary: List actions for a promotion
tags:
- - Configuration
+ - Promotions
security:
- api_key: []
bearer_auth: []
- description: |-
- Returns the roles available for staff role pickers. Roles are global, not per-store.
-
- **Required scope:** `read_settings` (for API-key authentication).
+ description: "**Required scope:** `read_promotions` (for API-key authentication)."
x-codeSamples:
- lang: javascript
label: Spree Admin SDK
@@ -8059,7 +8158,7 @@ paths:
secretKey: 'sk_xxx',
})
- const { data: roles } = await client.roles.list()
+ const { data: actions } = await client.promotions.actions.list('promo_UkLWZg9DAJ')
parameters:
- name: x-spree-api-key
in: header
@@ -8073,15 +8172,21 @@ paths:
type: string
responses:
'200':
- description: roles found
+ description: actions found
content:
application/json:
example:
data:
- - id: role_UkLWZg9DAJ
- name: admin
- created_at: '2026-05-10T19:05:45.220Z'
- updated_at: '2026-05-10T19:05:45.220Z'
+ - id: pact_UkLWZg9DAJ
+ created_at: '2026-05-12T13:53:14.779Z'
+ updated_at: '2026-05-12T13:53:14.779Z'
+ type: free_shipping
+ promotion_id: promo_UkLWZg9DAJ
+ preferences: {}
+ preference_schema: []
+ label: Free shipping
+ calculator:
+ line_items:
meta:
page: 1
limit: 25
@@ -8092,28 +8197,17 @@ paths:
in: 1
previous:
next:
- "/api/v3/admin/stock_locations":
- get:
- summary: List stock locations
+ post:
+ summary: Create an action on a promotion
tags:
- - Configuration
+ - Promotions
security:
- api_key: []
bearer_auth: []
description: |-
- Returns the configured stock locations. Stock locations are global
- (shared across stores). Filter with Ransack predicates such as
- `q[active_eq]`, `q[kind_eq]`, `q[pickup_enabled_eq]`, or
- `q[name_cont]`.
-
- Pickup-related attributes (`kind`, `pickup_enabled`,
- `pickup_stock_policy`, `pickup_ready_in_minutes`,
- `pickup_instructions`) drive merchant pickup support at checkout —
- customers can collect orders from any active location with
- `pickup_enabled: true`.
-
+ Adds a new action to a promotion. The `type` is the wire shorthand from `GET /promotion_actions/types` (e.g. `free_shipping`, `create_item_adjustments`). Fully-qualified Ruby class names are also accepted for backward compatibility.
- **Required scope:** `read_settings` (for API-key authentication).
+ **Required scope:** `write_promotions` (for API-key authentication).
x-codeSamples:
- lang: javascript
label: Spree Admin SDK
@@ -8125,7 +8219,9 @@ paths:
secretKey: 'sk_xxx',
})
- const { data: stockLocations } = await client.stockLocations.list()
+ const action = await client.promotions.actions.create('promo_UkLWZg9DAJ', {
+ type: 'free_shipping',
+ })
parameters:
- name: x-spree-api-key
in: header
@@ -8135,79 +8231,1242 @@ paths:
- name: Authorization
in: header
required: true
- description: Bearer token for admin authentication
schema:
type: string
- - name: page
- in: query
- required: false
- description: Page number
- schema:
- type: integer
- - name: limit
- in: query
- required: false
- description: Number of records per page
- schema:
- type: integer
- - name: q[name_cont]
- in: query
- required: false
- description: Filter by name (contains)
+ responses:
+ '201':
+ description: action created
+ content:
+ application/json:
+ example:
+ id: pact_UkLWZg9DAJ
+ created_at: '2026-05-12T13:53:15.357Z'
+ updated_at: '2026-05-12T13:53:15.357Z'
+ type: free_shipping
+ promotion_id: promo_UkLWZg9DAJ
+ preferences: {}
+ preference_schema: []
+ label: Free shipping
+ calculator:
+ line_items:
+ '422':
+ description: unknown action type
+ content:
+ application/json:
+ example:
+ error:
+ code: unknown_promotion_action_type
+ message: Unknown type
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ type:
+ type: string
+ example: free_shipping
+ preferences:
+ type: object
+ additionalProperties: true
+ required:
+ - type
+ "/api/v3/admin/promotions/{promotion_id}/promotion_actions/{id}":
+ parameters:
+ - name: promotion_id
+ in: path
+ required: true
+ schema:
+ type: string
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ delete:
+ summary: Delete an action from a promotion
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: "**Required scope:** `write_promotions` (for API-key authentication)."
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
schema:
type: string
- - name: q[active_eq]
- in: query
- required: false
- description: Filter by active status
- schema:
- type: boolean
- - name: q[kind_eq]
- in: query
- required: false
- description: 'Filter by kind (built-in: ''warehouse'', ''store'', ''fulfillment_center'')'
+ - name: Authorization
+ in: header
+ required: true
schema:
type: string
- - name: q[pickup_enabled_eq]
- in: query
- required: false
- description: Filter by pickup-enabled flag
- schema:
- type: boolean
- - name: sort
- in: query
- required: false
- description: Sort by field. Prefix with `-` for descending (e.g., `-created_at`).
+ responses:
+ '204':
+ description: action deleted
+ "/api/v3/admin/promotions/{promotion_id}/promotion_rules":
+ parameters:
+ - name: promotion_id
+ in: path
+ required: true
+ schema:
+ type: string
+ get:
+ summary: List rules for a promotion
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: "**Required scope:** `read_promotions` (for API-key authentication)."
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const { data: rules } = await client.promotions.rules.list('promo_UkLWZg9DAJ')
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
schema:
type: string
- - name: fields
- in: query
- required: false
- description: Comma-separated list of fields to include. id is always included.
+ - name: Authorization
+ in: header
+ required: true
schema:
type: string
responses:
'200':
- description: stock locations found
+ description: rules found
content:
application/json:
example:
data:
- - id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_21
- name: Brooklyn warehouse
- address1: 1600 Pennsylvania Ave NW
- city: Washington
- zipcode: '20500'
- country_iso: US
- country_name: United States of America
- state_text: STATE_ABBR_21
- admin_name:
- address2:
- state_name:
- phone: "(202) 456-1111"
- company:
- active: true
+ - id: prorule_UkLWZg9DAJ
+ created_at: '2026-05-12T13:53:15.957Z'
+ updated_at: '2026-05-12T13:53:15.957Z'
+ type: currency
+ promotion_id: promo_UkLWZg9DAJ
+ preferences:
+ currency: USD
+ preference_schema:
+ - key: currency
+ type: string
+ default:
+ label: Currency
+ product_ids:
+ category_ids:
+ customer_ids:
+ meta:
+ page: 1
+ limit: 25
+ count: 1
+ pages: 1
+ from: 1
+ to: 1
+ in: 1
+ previous:
+ next:
+ post:
+ summary: Create a rule on a promotion
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Adds a new rule to a promotion. The `type` is the wire shorthand from `GET /promotion_rules/types` (e.g. `currency`, `item_total`, `product`). Fully-qualified Ruby class names are also accepted for backward compatibility.
+
+ **Required scope:** `write_promotions` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const rule = await client.promotions.rules.create('promo_UkLWZg9DAJ', {
+ type: 'currency',
+ preferences: { currency: 'EUR' },
+ })
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '201':
+ description: rule created with preferences
+ content:
+ application/json:
+ example:
+ id: prorule_UkLWZg9DAJ
+ created_at: '2026-05-12T13:53:16.539Z'
+ updated_at: '2026-05-12T13:53:16.539Z'
+ type: currency
+ promotion_id: promo_UkLWZg9DAJ
+ preferences:
+ currency: EUR
+ preference_schema:
+ - key: currency
+ type: string
+ default:
+ label: Currency
+ product_ids:
+ category_ids:
+ customer_ids:
+ '422':
+ description: unknown rule type
+ content:
+ application/json:
+ example:
+ error:
+ code: unknown_promotion_rule_type
+ message: Unknown type
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ type:
+ type: string
+ example: currency
+ preferences:
+ type: object
+ additionalProperties: true
+ required:
+ - type
+ "/api/v3/admin/promotions/{promotion_id}/promotion_rules/{id}":
+ parameters:
+ - name: promotion_id
+ in: path
+ required: true
+ schema:
+ type: string
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ patch:
+ summary: Update a rule's preferences
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: "**Required scope:** `write_promotions` (for API-key authentication)."
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: rule updated
+ content:
+ application/json:
+ example:
+ id: prorule_UkLWZg9DAJ
+ created_at: '2026-05-12T13:53:16.832Z'
+ updated_at: '2026-05-12T13:53:17.109Z'
+ type: currency
+ promotion_id: promo_UkLWZg9DAJ
+ preferences:
+ currency: GBP
+ preference_schema:
+ - key: currency
+ type: string
+ default:
+ label: Currency
+ product_ids:
+ category_ids:
+ customer_ids:
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ preferences:
+ type: object
+ additionalProperties: true
+ delete:
+ summary: Delete a rule from a promotion
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: "**Required scope:** `write_promotions` (for API-key authentication)."
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '204':
+ description: rule deleted
+ "/api/v3/admin/promotions":
+ get:
+ summary: List promotions
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Returns the store's promotions, including manual coupon and automatic promotions.
+
+ **Required scope:** `read_promotions` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const { data: promotions } = await client.promotions.list()
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: promotions found
+ content:
+ application/json:
+ example:
+ data:
+ - id: promo_UkLWZg9DAJ
+ name: Summer Sale
+ description:
+ code: summer
+ starts_at: '2026-05-12T13:53:17.399Z'
+ expires_at:
+ usage_limit:
+ match_policy: all
+ path:
+ kind: coupon_code
+ multi_codes: false
+ number_of_codes:
+ code_prefix:
+ promotion_category_id:
+ metadata: {}
+ created_at: '2026-05-12T13:53:17.400Z'
+ updated_at: '2026-05-12T13:53:17.401Z'
+ store_ids:
+ - store_UkLWZg9DAJ
+ action_ids: []
+ rule_ids: []
+ meta:
+ page: 1
+ limit: 25
+ count: 1
+ pages: 1
+ from: 1
+ to: 1
+ in: 1
+ previous:
+ next:
+ post:
+ summary: Create a promotion
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Creates a new promotion. `code` is required for single-code coupon promotions;
+ pass `multi_codes: true` with `number_of_codes` to auto-generate a batch.
+
+ Rules and actions can be created in the same request by passing arrays of
+ `{ type, preferences, ... }` rows. The server reconciles to the desired set:
+ new rows are built, existing rows (by `id`) are updated, omitted rows are removed.
+
+
+ **Required scope:** `write_promotions` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ // Single coupon code, no rules/actions
+ const promotion = await client.promotions.create({
+ name: 'Black Friday',
+ code: 'BLACKFRIDAY',
+ starts_at: '2026-11-29T00:00:00Z',
+ expires_at: '2026-12-01T00:00:00Z',
+ })
+
+ // One-shot: promotion + rules + actions in a single request
+ const blackFriday = await client.promotions.create({
+ name: 'Black Friday',
+ code: 'BLACKFRIDAY',
+ kind: 'coupon_code',
+ starts_at: '2026-11-29T00:00:00Z',
+ expires_at: '2026-12-01T00:00:00Z',
+ match_policy: 'all',
+ rules: [
+ {
+ type: 'currency',
+ preferences: { currency: 'USD' },
+ },
+ {
+ type: 'item_total',
+ preferences: { amount_min: 100, operator_min: 'gte' },
+ },
+ {
+ type: 'product',
+ preferences: { match_policy: 'any' },
+ product_ids: ['prod_abc123', 'prod_def456'],
+ },
+ ],
+ actions: [
+ {
+ type: 'create_item_adjustments',
+ calculator: {
+ type: 'percent_on_line_item',
+ preferences: { percent: 25 },
+ },
+ },
+ { type: 'free_shipping' },
+ ],
+ })
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '201':
+ description: promotion created with rules and actions
+ content:
+ application/json:
+ example:
+ id: promo_gbHJdmfrXB
+ name: Black Friday
+ description:
+ code: blackfriday-os
+ starts_at: '2026-05-12T13:53:18.339Z'
+ expires_at:
+ usage_limit:
+ match_policy: all
+ path:
+ kind: coupon_code
+ multi_codes: false
+ number_of_codes:
+ code_prefix:
+ promotion_category_id:
+ metadata: {}
+ created_at: '2026-05-12T13:53:18.340Z'
+ updated_at: '2026-05-12T13:53:18.365Z'
+ store_ids:
+ - store_UkLWZg9DAJ
+ action_ids:
+ - pact_UkLWZg9DAJ
+ - pact_gbHJdmfrXB
+ rule_ids:
+ - prorule_UkLWZg9DAJ
+ - prorule_gbHJdmfrXB
+ - prorule_EfhxLZ9ck8
+ '422':
+ description: invalid params
+ content:
+ application/json:
+ example:
+ error:
+ code: validation_error
+ message: Name can't be blank and Code can't be blank
+ details:
+ name:
+ - can't be blank
+ code:
+ - can't be blank
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ name:
+ type: string
+ code:
+ type: string
+ nullable: true
+ description:
+ type: string
+ nullable: true
+ starts_at:
+ type: string
+ format: date-time
+ nullable: true
+ expires_at:
+ type: string
+ format: date-time
+ nullable: true
+ usage_limit:
+ type: integer
+ nullable: true
+ match_policy:
+ type: string
+ enum:
+ - all
+ - any
+ kind:
+ type: string
+ enum:
+ - coupon_code
+ - automatic
+ multi_codes:
+ type: boolean
+ number_of_codes:
+ type: integer
+ nullable: true
+ code_prefix:
+ type: string
+ nullable: true
+ promotion_category_id:
+ type: string
+ nullable: true
+ rules:
+ type: array
+ items:
+ type: object
+ properties:
+ type:
+ type: string
+ example: currency
+ preferences:
+ type: object
+ additionalProperties: true
+ product_ids:
+ type: array
+ items:
+ type: string
+ category_ids:
+ type: array
+ items:
+ type: string
+ customer_ids:
+ type: array
+ items:
+ type: string
+ required:
+ - type
+ actions:
+ type: array
+ items:
+ type: object
+ properties:
+ type:
+ type: string
+ example: free_shipping
+ preferences:
+ type: object
+ additionalProperties: true
+ calculator:
+ type: object
+ properties:
+ type:
+ type: string
+ example: flat_percent_item_total
+ preferences:
+ type: object
+ additionalProperties: true
+ required:
+ - type
+ required:
+ - name
+ "/api/v3/admin/promotions/{id}":
+ get:
+ summary: Show a promotion
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: "**Required scope:** `read_promotions` (for API-key authentication)."
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: promotion found
+ content:
+ application/json:
+ example:
+ id: promo_UkLWZg9DAJ
+ name: Summer Sale
+ description:
+ code: summer
+ starts_at: '2026-05-12T13:53:18.668Z'
+ expires_at:
+ usage_limit:
+ match_policy: all
+ path:
+ kind: coupon_code
+ multi_codes: false
+ number_of_codes:
+ code_prefix:
+ promotion_category_id:
+ metadata: {}
+ created_at: '2026-05-12T13:53:18.669Z'
+ updated_at: '2026-05-12T13:53:18.670Z'
+ store_ids:
+ - store_UkLWZg9DAJ
+ action_ids: []
+ rule_ids: []
+ patch:
+ summary: Update a promotion
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Updates a promotion. The `rules` and `actions` arrays are treated as
+ a *desired set* — rows with `id` update in place, rows without `id` are
+ built fresh, and any existing row not present in the array is destroyed.
+ Pass `rules: []` or `actions: []` to clear them.
+
+
+ **Required scope:** `write_promotions` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ // Basic field update
+ await client.promotions.update(promotionId, {
+ description: 'Updated description',
+ })
+
+ // One-shot: rewrite rules + actions in a single request
+ await client.promotions.update(promotionId, {
+ name: 'Holiday Sale',
+ rules: [
+ // Update an existing rule by id — `preferences` overwrite the prior set
+ {
+ id: 'prorule_existing',
+ type: 'currency',
+ preferences: { currency: 'EUR' },
+ },
+ // Add a new rule
+ {
+ type: 'item_total',
+ preferences: { amount_min: 50, operator_min: 'gte' },
+ },
+ ],
+ actions: [
+ // Swap calculator type on an existing action
+ {
+ id: 'proaction_existing',
+ type: 'create_item_adjustments',
+ calculator: {
+ type: 'percent_on_line_item',
+ preferences: { percent: 15 },
+ },
+ },
+ ],
+ })
+
+ // Remove all rules/actions
+ await client.promotions.update(promotionId, {
+ rules: [],
+ actions: [],
+ })
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: rules and actions cleared with empty arrays
+ content:
+ application/json:
+ example:
+ id: promo_UkLWZg9DAJ
+ name: Summer Sale
+ description:
+ code: summer
+ starts_at: '2026-05-12T13:53:19.541Z'
+ expires_at:
+ usage_limit:
+ match_policy: all
+ path:
+ kind: coupon_code
+ multi_codes: false
+ number_of_codes:
+ code_prefix:
+ promotion_category_id:
+ metadata: {}
+ created_at: '2026-05-12T13:53:19.541Z'
+ updated_at: '2026-05-12T13:53:19.821Z'
+ store_ids:
+ - store_UkLWZg9DAJ
+ action_ids: []
+ rule_ids: []
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ name:
+ type: string
+ description:
+ type: string
+ nullable: true
+ code:
+ type: string
+ nullable: true
+ starts_at:
+ type: string
+ format: date-time
+ nullable: true
+ expires_at:
+ type: string
+ format: date-time
+ nullable: true
+ usage_limit:
+ type: integer
+ nullable: true
+ match_policy:
+ type: string
+ enum:
+ - all
+ - any
+ kind:
+ type: string
+ enum:
+ - coupon_code
+ - automatic
+ promotion_category_id:
+ type: string
+ nullable: true
+ rules:
+ type: array
+ items:
+ type: object
+ properties:
+ id:
+ type: string
+ nullable: true
+ description: Pass to update an existing rule; omit to build
+ a new one
+ type:
+ type: string
+ example: currency
+ preferences:
+ type: object
+ additionalProperties: true
+ product_ids:
+ type: array
+ items:
+ type: string
+ category_ids:
+ type: array
+ items:
+ type: string
+ customer_ids:
+ type: array
+ items:
+ type: string
+ required:
+ - type
+ actions:
+ type: array
+ items:
+ type: object
+ properties:
+ id:
+ type: string
+ nullable: true
+ type:
+ type: string
+ example: free_shipping
+ preferences:
+ type: object
+ additionalProperties: true
+ calculator:
+ type: object
+ properties:
+ type:
+ type: string
+ example: flat_percent_item_total
+ preferences:
+ type: object
+ additionalProperties: true
+ required:
+ - type
+ delete:
+ summary: Delete a promotion
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: "**Required scope:** `write_promotions` (for API-key authentication)."
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '204':
+ description: promotion deleted
+ "/api/v3/admin/promotion_actions/types":
+ get:
+ summary: List available promotion action types
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Returns the registered Spree::PromotionAction subclasses with their preference schemas. Used by admin UIs to populate the "Add action" picker and render generic preference forms.
+
+ **Required scope:** `read_promotions` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const { data: actionTypes } = await client.promotionActions.types()
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: action types found
+ content:
+ application/json:
+ example:
+ data:
+ - type: create_adjustment
+ label: Create Adjustment
+ description:
+ preference_schema: []
+ - type: create_item_adjustments
+ label: Create Item Adjustments
+ description:
+ preference_schema: []
+ - type: create_line_items
+ label: Create Line Items
+ description:
+ preference_schema: []
+ - type: free_shipping
+ label: Free Shipping
+ description:
+ preference_schema: []
+ "/api/v3/admin/promotion_rules/types":
+ get:
+ summary: List available promotion rule types
+ tags:
+ - Promotions
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Returns the registered Spree::PromotionRule subclasses with their preference schemas.
+
+ **Required scope:** `read_promotions` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const { data: ruleTypes } = await client.promotionRules.types()
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: rule types found
+ content:
+ application/json:
+ example:
+ data:
+ - type: country
+ label: Country
+ description:
+ preference_schema:
+ - key: country_isos
+ type: array
+ default: []
+ - key: country_id
+ type: integer
+ default:
+ - key: country_iso
+ type: string
+ default:
+ - type: currency
+ label: Currency
+ description:
+ preference_schema:
+ - key: currency
+ type: string
+ default:
+ - type: customer_group
+ label: Customer Group
+ description:
+ preference_schema:
+ - key: customer_group_ids
+ type: array
+ default: []
+ - type: first_order
+ label: First Order
+ description:
+ preference_schema: []
+ - type: item_total
+ label: Item Total
+ description:
+ preference_schema:
+ - key: operator_min
+ type: string
+ default: ">"
+ - key: amount_max
+ type: decimal
+ default:
+ - key: operator_max
+ type: string
+ default: "<"
+ - key: amount_min
+ type: decimal
+ default: 100.0
+ - type: one_use_per_user
+ label: One Use Per User
+ description:
+ preference_schema: []
+ - type: option_value
+ label: Option Value
+ description:
+ preference_schema:
+ - key: eligible_values
+ type: array
+ default: []
+ - key: match_policy
+ type: string
+ default: any
+ - type: product
+ label: Product
+ description:
+ preference_schema:
+ - key: match_policy
+ type: string
+ default: any
+ - type: category
+ label: Taxon
+ description:
+ preference_schema:
+ - key: match_policy
+ type: string
+ default: any
+ - type: user
+ label: User
+ description:
+ preference_schema: []
+ - type: user_logged_in
+ label: User Logged In
+ description:
+ preference_schema: []
+ "/api/v3/admin/roles":
+ get:
+ summary: List roles
+ tags:
+ - Configuration
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Returns the roles available for staff role pickers. Roles are global, not per-store.
+
+ **Required scope:** `read_settings` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const { data: roles } = await client.roles.list()
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: roles found
+ content:
+ application/json:
+ example:
+ data:
+ - id: role_UkLWZg9DAJ
+ name: admin
+ created_at: '2026-05-12T13:53:20.690Z'
+ updated_at: '2026-05-12T13:53:20.690Z'
+ meta:
+ page: 1
+ limit: 25
+ count: 1
+ pages: 1
+ from: 1
+ to: 1
+ in: 1
+ previous:
+ next:
+ "/api/v3/admin/stock_locations":
+ get:
+ summary: List stock locations
+ tags:
+ - Configuration
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Returns the configured stock locations. Stock locations are global
+ (shared across stores). Filter with Ransack predicates such as
+ `q[active_eq]`, `q[kind_eq]`, `q[pickup_enabled_eq]`, or
+ `q[name_cont]`.
+
+ Pickup-related attributes (`kind`, `pickup_enabled`,
+ `pickup_stock_policy`, `pickup_ready_in_minutes`,
+ `pickup_instructions`) drive merchant pickup support at checkout —
+ customers can collect orders from any active location with
+ `pickup_enabled: true`.
+
+
+ **Required scope:** `read_settings` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const { data: stockLocations } = await client.stockLocations.list()
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ - name: page
+ in: query
+ required: false
+ description: Page number
+ schema:
+ type: integer
+ - name: limit
+ in: query
+ required: false
+ description: Number of records per page
+ schema:
+ type: integer
+ - name: q[name_cont]
+ in: query
+ required: false
+ description: Filter by name (contains)
+ schema:
+ type: string
+ - name: q[active_eq]
+ in: query
+ required: false
+ description: Filter by active status
+ schema:
+ type: boolean
+ - name: q[kind_eq]
+ in: query
+ required: false
+ description: 'Filter by kind (built-in: ''warehouse'', ''store'', ''fulfillment_center'')'
+ schema:
+ type: string
+ - name: q[pickup_enabled_eq]
+ in: query
+ required: false
+ description: Filter by pickup-enabled flag
+ schema:
+ type: boolean
+ - name: sort
+ in: query
+ required: false
+ description: Sort by field. Prefix with `-` for descending (e.g., `-created_at`).
+ schema:
+ type: string
+ - name: fields
+ in: query
+ required: false
+ description: Comma-separated list of fields to include. id is always included.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: stock locations found
+ content:
+ application/json:
+ example:
+ data:
+ - id: sloc_UkLWZg9DAJ
+ state_abbr: STATE_ABBR_22
+ name: Brooklyn warehouse
+ address1: 1600 Pennsylvania Ave NW
+ city: Washington
+ zipcode: '20500'
+ country_iso: US
+ country_name: United States of America
+ state_text: STATE_ABBR_22
+ admin_name:
+ address2:
+ state_name:
+ phone: "(202) 456-1111"
+ company:
+ active: true
default: false
backorderable_default: true
propagate_all_variants: false
@@ -8216,8 +9475,8 @@ paths:
pickup_stock_policy: local
pickup_ready_in_minutes:
pickup_instructions:
- created_at: '2026-05-10T19:05:45.508Z'
- updated_at: '2026-05-10T19:05:45.508Z'
+ created_at: '2026-05-12T13:53:20.970Z'
+ updated_at: '2026-05-12T13:53:20.970Z'
meta:
page: 1
limit: 25
@@ -8328,8 +9587,8 @@ paths:
pickup_stock_policy: local
pickup_ready_in_minutes: 30
pickup_instructions:
- created_at: '2026-05-10T19:05:46.083Z'
- updated_at: '2026-05-10T19:05:46.083Z'
+ created_at: '2026-05-12T13:53:21.554Z'
+ updated_at: '2026-05-12T13:53:21.554Z'
schema:
"$ref": "#/components/schemas/StockLocation"
'422':
@@ -8481,14 +9740,14 @@ paths:
application/json:
example:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_25
+ state_abbr: STATE_ABBR_26
name: Brooklyn warehouse
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_25
+ state_text: STATE_ABBR_26
admin_name:
address2:
state_name:
@@ -8503,8 +9762,8 @@ paths:
pickup_stock_policy: local
pickup_ready_in_minutes:
pickup_instructions:
- created_at: '2026-05-10T19:05:46.385Z'
- updated_at: '2026-05-10T19:05:46.385Z'
+ created_at: '2026-05-12T13:53:21.845Z'
+ updated_at: '2026-05-12T13:53:21.845Z'
schema:
"$ref": "#/components/schemas/StockLocation"
'404':
@@ -8567,14 +9826,14 @@ paths:
application/json:
example:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_27
+ state_abbr: STATE_ABBR_28
name: Renamed warehouse
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_27
+ state_text: STATE_ABBR_28
admin_name:
address2:
state_name:
@@ -8589,8 +9848,8 @@ paths:
pickup_stock_policy: local
pickup_ready_in_minutes: 45
pickup_instructions:
- created_at: '2026-05-10T19:05:46.950Z'
- updated_at: '2026-05-10T19:05:47.228Z'
+ created_at: '2026-05-12T13:53:22.405Z'
+ updated_at: '2026-05-12T13:53:22.681Z'
schema:
"$ref": "#/components/schemas/StockLocation"
'422':
@@ -8793,8 +10052,8 @@ paths:
data:
- id: sccat_UkLWZg9DAJ
name: Goodwill
- created_at: '2026-05-10T19:05:47.797Z'
- updated_at: '2026-05-10T19:05:47.797Z'
+ created_at: '2026-05-12T13:53:23.259Z'
+ updated_at: '2026-05-12T13:53:23.259Z'
non_expiring: false
meta:
page: 1
@@ -8885,8 +10144,8 @@ paths:
example:
id: sccat_UkLWZg9DAJ
name: Goodwill
- created_at: '2026-05-10T19:05:48.092Z'
- updated_at: '2026-05-10T19:05:48.092Z'
+ created_at: '2026-05-12T13:53:23.572Z'
+ updated_at: '2026-05-12T13:53:23.572Z'
non_expiring: false
schema:
"$ref": "#/components/schemas/StoreCreditCategory"
@@ -8951,8 +10210,8 @@ paths:
preferred_timezone: UTC
preferred_weight_unit: lb
preferred_unit_system: imperial
- created_at: '2026-05-10T19:04:52.954Z'
- updated_at: '2026-05-10T19:05:48.671Z'
+ created_at: '2026-05-12T13:52:20.414Z'
+ updated_at: '2026-05-12T13:53:24.223Z'
url: http://www.example.com:3000
supported_currencies:
- USD
@@ -9023,8 +10282,8 @@ paths:
preferred_timezone: UTC
preferred_weight_unit: lb
preferred_unit_system: imperial
- created_at: '2026-05-10T19:04:52.954Z'
- updated_at: '2026-05-10T19:05:49.290Z'
+ created_at: '2026-05-12T13:52:20.414Z'
+ updated_at: '2026-05-12T13:53:24.935Z'
url: http://www.example.com:3000
supported_currencies:
- USD
@@ -9212,7 +10471,7 @@ paths:
data:
- id: variant_UkLWZg9DAJ
product_id: prod_UkLWZg9DAJ
- sku: SKU-54
+ sku: SKU-56
options_text: ''
track_inventory: true
media_count: 0
@@ -9242,16 +10501,16 @@ paths:
cost_price: '17.0'
cost_currency: USD
deleted_at:
- created_at: '2026-05-10T19:05:50.703Z'
- updated_at: '2026-05-10T19:05:50.716Z'
+ created_at: '2026-05-12T13:53:26.396Z'
+ updated_at: '2026-05-12T13:53:26.411Z'
available_stock: 0
reserved_quantity: 0
total_on_hand: 0
- product_name: Product 487262
+ product_name: Product 506322
display_price: "$0.00"
- id: variant_gbHJdmfrXB
product_id: prod_UkLWZg9DAJ
- sku: SKU-55
+ sku: SKU-57
options_text: 'Size: S'
track_inventory: true
media_count: 0
@@ -9259,10 +10518,10 @@ paths:
purchasable: true
in_stock: false
backorderable: true
- weight: 126.76
- height: 172.58
- width: 177.1
- depth: 38.9
+ weight: 137.36
+ height: 56.41
+ width: 110.33
+ depth: 98.46
price:
id: price_gbHJdmfrXB
amount: '19.99'
@@ -9285,20 +10544,20 @@ paths:
option_type_label: Size
image_url:
metadata: {}
- created_at: '2026-05-10T19:05:50.724Z'
- updated_at: '2026-05-10T19:05:50.724Z'
+ created_at: '2026-05-12T13:53:26.424Z'
+ updated_at: '2026-05-12T13:53:26.424Z'
metadata: {}
position: 2
tax_category_id: 1
cost_price: '17.0'
cost_currency: USD
deleted_at:
- created_at: '2026-05-10T19:05:50.722Z'
- updated_at: '2026-05-10T19:05:50.734Z'
+ created_at: '2026-05-12T13:53:26.421Z'
+ updated_at: '2026-05-12T13:53:26.436Z'
available_stock: 0
reserved_quantity: 0
total_on_hand: 0
- product_name: Product 487262
+ product_name: Product 506322
display_price: "$19.99"
meta:
page: 1
@@ -9410,20 +10669,20 @@ paths:
option_type_label: Size
image_url:
metadata: {}
- created_at: '2026-05-10T19:05:51.376Z'
- updated_at: '2026-05-10T19:05:51.376Z'
+ created_at: '2026-05-12T13:53:27.099Z'
+ updated_at: '2026-05-12T13:53:27.099Z'
metadata: {}
position: 3
tax_category_id: 1
cost_price:
cost_currency: USD
deleted_at:
- created_at: '2026-05-10T19:05:51.380Z'
- updated_at: '2026-05-10T19:05:51.382Z'
+ created_at: '2026-05-12T13:53:27.103Z'
+ updated_at: '2026-05-12T13:53:27.104Z'
available_stock: 0
reserved_quantity: 0
total_on_hand: 0
- product_name: Product 493275
+ product_name: Product 515143
display_price: "$24.99"
'422':
description: validation error
@@ -9603,7 +10862,7 @@ paths:
example:
id: variant_gbHJdmfrXB
product_id: prod_UkLWZg9DAJ
- sku: SKU-61
+ sku: SKU-63
options_text: 'Size: S'
track_inventory: true
media_count: 0
@@ -9611,10 +10870,10 @@ paths:
purchasable: true
in_stock: false
backorderable: true
- weight: 172.76
- height: 191.52
- width: 124.34
- depth: 142.7
+ weight: 82.29
+ height: 43.48
+ width: 55.32
+ depth: 41.2
price:
id: price_gbHJdmfrXB
amount: '19.99'
@@ -9637,20 +10896,20 @@ paths:
option_type_label: Size
image_url:
metadata: {}
- created_at: '2026-05-10T19:05:51.805Z'
- updated_at: '2026-05-10T19:05:51.805Z'
+ created_at: '2026-05-12T13:53:27.536Z'
+ updated_at: '2026-05-12T13:53:27.536Z'
metadata: {}
position: 2
tax_category_id: 1
cost_price: '17.0'
cost_currency: USD
deleted_at:
- created_at: '2026-05-10T19:05:51.803Z'
- updated_at: '2026-05-10T19:05:51.815Z'
+ created_at: '2026-05-12T13:53:27.533Z'
+ updated_at: '2026-05-12T13:53:27.549Z'
available_stock: 0
reserved_quantity: 0
total_on_hand: 0
- product_name: Product 517669
+ product_name: Product 532781
display_price: "$19.99"
'404':
description: variant not found
@@ -9730,10 +10989,10 @@ paths:
purchasable: true
in_stock: false
backorderable: true
- weight: 24.66
- height: 126.93
- width: 95.25
- depth: 183.29
+ weight: 118.18
+ height: 48.83
+ width: 38.67
+ depth: 171.32
price:
id: price_gbHJdmfrXB
amount: '19.99'
@@ -9756,20 +11015,20 @@ paths:
option_type_label: Size
image_url:
metadata: {}
- created_at: '2026-05-10T19:05:52.482Z'
- updated_at: '2026-05-10T19:05:52.482Z'
+ created_at: '2026-05-12T13:53:28.228Z'
+ updated_at: '2026-05-12T13:53:28.228Z'
metadata: {}
position: 2
tax_category_id: 1
cost_price: '17.0'
cost_currency: USD
deleted_at:
- created_at: '2026-05-10T19:05:52.480Z'
- updated_at: '2026-05-10T19:05:52.775Z'
+ created_at: '2026-05-12T13:53:28.225Z'
+ updated_at: '2026-05-12T13:53:28.540Z'
available_stock: 0
reserved_quantity: 0
total_on_hand: 0
- product_name: Product 534057
+ product_name: Product 554685
display_price: "$19.99"
requestBody:
content:
@@ -10130,44 +11389,102 @@ components:
description: Prefixed variant ID (when applicable)
example: variant_abc123
required:
- - code
- - message
- FulfillmentManifestItem:
+ - code
+ - message
+ FulfillmentManifestItem:
+ type: object
+ description: An item within a fulfillment — which line item and how many units
+ are in this fulfillment
+ properties:
+ item_id:
+ type: string
+ description: Line item ID
+ example: li_abc123
+ variant_id:
+ type: string
+ description: Variant ID
+ example: variant_abc123
+ quantity:
+ type: integer
+ description: Quantity in this fulfillment
+ example: 2
+ required:
+ - item_id
+ - variant_id
+ - quantity
+ AdminUserRoleAssignment:
+ type: object
+ description: A role assignment for the current store on a staff member
+ properties:
+ id:
+ type: string
+ description: Prefixed role ID
+ example: role_abc123
+ name:
+ type: string
+ description: Role name
+ example: admin
+ required:
+ - id
+ - name
+ PreferenceField:
+ 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:
+ - key
+ - type
+ 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"
+ required:
+ - type
+ - label
+ - preferences
+ - preference_schema
+ PromotionActionLineItem:
type: object
- description: An item within a fulfillment — which line item and how many units
- are in this fulfillment
+ description: One row in a `create_line_items` action — the variant added to
+ the order and how many
properties:
- item_id:
- type: string
- description: Line item ID
- example: li_abc123
variant_id:
type: string
- description: Variant ID
example: variant_abc123
quantity:
type: integer
- description: Quantity in this fulfillment
- example: 2
+ example: 1
required:
- - item_id
- variant_id
- quantity
- AdminUserRoleAssignment:
- type: object
- description: A role assignment for the current store on a staff member
- properties:
- id:
- type: string
- description: Prefixed role ID
- example: role_abc123
- name:
- type: string
- description: Role name
- example: admin
- required:
- - id
- - name
Address:
type: object
properties:
@@ -10538,6 +11855,34 @@ components:
- created_at
- updated_at
x-typelizer: true
+ CouponCode:
+ type: object
+ properties:
+ id:
+ type: string
+ code:
+ type: string
+ state:
+ type: string
+ nullable: true
+ created_at:
+ type: string
+ updated_at:
+ type: string
+ promotion_id:
+ type: string
+ order_id:
+ type: string
+ nullable: true
+ required:
+ - id
+ - code
+ - state
+ - created_at
+ - updated_at
+ - promotion_id
+ - order_id
+ x-typelizer: true
CreditCard:
type: object
properties:
@@ -10668,6 +12013,26 @@ components:
- storefront_visible
- custom_field_definition_id
x-typelizer: true
+ CustomerGroup:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ users_count:
+ type: number
+ created_at:
+ type: string
+ updated_at:
+ type: string
+ required:
+ - id
+ - name
+ - users_count
+ - created_at
+ - updated_at
+ x-typelizer: true
Customer:
type: object
properties:
@@ -11395,6 +12760,9 @@ components:
type: string
viewable_id:
type: string
+ download_url:
+ type: string
+ nullable: true
metadata:
type: object
viewable_type:
@@ -11419,6 +12787,7 @@ components:
- created_at
- updated_at
- viewable_id
+ - download_url
- metadata
- viewable_type
x-typelizer: true
@@ -11771,10 +13140,18 @@ components:
auto_capture:
type: boolean
nullable: true
+ display_on:
+ type: string
+ position:
+ type: number
created_at:
type: string
updated_at:
type: string
+ preferences:
+ type: object
+ preference_schema:
+ type: object
required:
- id
- name
@@ -11785,8 +13162,12 @@ components:
- metadata
- active
- auto_capture
+ - display_on
+ - position
- created_at
- updated_at
+ - preferences
+ - preference_schema
x-typelizer: true
Payment:
type: object
@@ -12108,6 +13489,203 @@ components:
- cost_price
- cost_currency
x-typelizer: true
+ PromotionAction:
+ type: object
+ properties:
+ id:
+ type: string
+ created_at:
+ type: string
+ updated_at:
+ type: string
+ type:
+ type: string
+ promotion_id:
+ type: string
+ preferences:
+ type: object
+ preference_schema:
+ type: array
+ items:
+ "$ref": "#/components/schemas/PreferenceField"
+ label:
+ type: string
+ calculator:
+ allOf:
+ - "$ref": "#/components/schemas/PromotionActionCalculator"
+ nullable: true
+ line_items:
+ type: array
+ items:
+ "$ref": "#/components/schemas/PromotionActionLineItem"
+ nullable: true
+ required:
+ - id
+ - created_at
+ - updated_at
+ - type
+ - promotion_id
+ - preferences
+ - preference_schema
+ - label
+ - calculator
+ - line_items
+ x-typelizer: true
+ PromotionRule:
+ type: object
+ properties:
+ id:
+ type: string
+ created_at:
+ type: string
+ updated_at:
+ type: string
+ type:
+ type: string
+ promotion_id:
+ type: string
+ preferences:
+ type: object
+ preference_schema:
+ type: array
+ items:
+ "$ref": "#/components/schemas/PreferenceField"
+ label:
+ type: string
+ product_ids:
+ type: array
+ items:
+ type: string
+ nullable: true
+ category_ids:
+ type: array
+ items:
+ type: string
+ nullable: true
+ customer_ids:
+ type: array
+ items:
+ type: string
+ nullable: true
+ products:
+ type: array
+ items:
+ "$ref": "#/components/schemas/Product"
+ categories:
+ type: array
+ items:
+ "$ref": "#/components/schemas/Category"
+ customers:
+ type: array
+ items:
+ "$ref": "#/components/schemas/Customer"
+ customer_groups:
+ type: array
+ items:
+ "$ref": "#/components/schemas/CustomerGroup"
+ countries:
+ type: array
+ items:
+ "$ref": "#/components/schemas/Country"
+ required:
+ - id
+ - created_at
+ - updated_at
+ - type
+ - promotion_id
+ - preferences
+ - preference_schema
+ - label
+ - product_ids
+ - category_ids
+ - customer_ids
+ x-typelizer: true
+ Promotion:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ description:
+ type: string
+ nullable: true
+ code:
+ type: string
+ nullable: true
+ starts_at:
+ type: string
+ nullable: true
+ expires_at:
+ type: string
+ nullable: true
+ usage_limit:
+ type: number
+ nullable: true
+ match_policy:
+ type: string
+ enum:
+ - all
+ - any
+ path:
+ type: string
+ nullable: true
+ kind:
+ type: string
+ enum:
+ - coupon_code
+ - automatic
+ multi_codes:
+ type: boolean
+ number_of_codes:
+ type: number
+ nullable: true
+ code_prefix:
+ type: string
+ nullable: true
+ promotion_category_id:
+ type: string
+ nullable: true
+ metadata:
+ type: object
+ created_at:
+ type: string
+ updated_at:
+ type: string
+ store_ids:
+ type: array
+ items:
+ type: string
+ action_ids:
+ type: array
+ items:
+ type: string
+ rule_ids:
+ type: array
+ items:
+ type: string
+ required:
+ - id
+ - name
+ - description
+ - code
+ - starts_at
+ - expires_at
+ - usage_limit
+ - match_policy
+ - path
+ - kind
+ - multi_codes
+ - number_of_codes
+ - code_prefix
+ - promotion_category_id
+ - metadata
+ - created_at
+ - updated_at
+ - store_ids
+ - action_ids
+ - rule_ids
+ x-typelizer: true
Refund:
type: object
properties:
@@ -12429,6 +14007,42 @@ components:
- created_at
- updated_at
x-typelizer: true
+ StockTransfer:
+ type: object
+ properties:
+ id:
+ type: string
+ number:
+ type: string
+ reference:
+ type: string
+ nullable: true
+ metadata:
+ type: object
+ created_at:
+ type: string
+ updated_at:
+ type: string
+ source_location_id:
+ type: string
+ nullable: true
+ destination_location_id:
+ type: string
+ nullable: true
+ source_location:
+ "$ref": "#/components/schemas/StockLocation"
+ destination_location:
+ "$ref": "#/components/schemas/StockLocation"
+ required:
+ - id
+ - number
+ - reference
+ - metadata
+ - created_at
+ - updated_at
+ - source_location_id
+ - destination_location_id
+ x-typelizer: true
StoreCreditCategory:
type: object
properties:
@@ -12573,6 +14187,9 @@ components:
tax_code:
type: string
nullable: true
+ description:
+ type: string
+ nullable: true
is_default:
type: boolean
created_at:
@@ -12583,6 +14200,7 @@ components:
- id
- name
- tax_code
+ - description
- is_default
- created_at
- updated_at
diff --git a/packages/admin-sdk/examples/admin-users/delete.ts b/packages/admin-sdk/examples/admin-users/delete.ts
new file mode 100644
index 0000000000..c1d18bf685
--- /dev/null
+++ b/packages/admin-sdk/examples/admin-users/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.adminUsers.delete('admin_xxx')
+// endregion:example
diff --git a/packages/admin-sdk/examples/admin-users/get.ts b/packages/admin-sdk/examples/admin-users/get.ts
new file mode 100644
index 0000000000..c7247eca2c
--- /dev/null
+++ b/packages/admin-sdk/examples/admin-users/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const staff = await client.adminUsers.get('admin_xxx')
+// endregion:example
+
+export { staff }
diff --git a/packages/admin-sdk/examples/admin-users/list.ts b/packages/admin-sdk/examples/admin-users/list.ts
new file mode 100644
index 0000000000..856522f50c
--- /dev/null
+++ b/packages/admin-sdk/examples/admin-users/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: staff } = await client.adminUsers.list()
+// endregion:example
+
+export { staff }
diff --git a/packages/admin-sdk/examples/admin-users/update.ts b/packages/admin-sdk/examples/admin-users/update.ts
new file mode 100644
index 0000000000..d8f4e24810
--- /dev/null
+++ b/packages/admin-sdk/examples/admin-users/update.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const staff = await client.adminUsers.update('admin_xxx', {
+ first_name: 'Ada',
+ role_ids: ['role_xxx']
+})
+// endregion:example
+
+export { staff }
diff --git a/packages/admin-sdk/examples/api-keys/create.ts b/packages/admin-sdk/examples/api-keys/create.ts
new file mode 100644
index 0000000000..46797c6802
--- /dev/null
+++ b/packages/admin-sdk/examples/api-keys/create.ts
@@ -0,0 +1,17 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const key = await client.apiKeys.create({
+ name: 'Backend integration',
+ key_type: 'secret',
+ scopes: ['read_orders', 'write_orders']
+})
+// `key.plaintext_token` is available only on this response.
+// endregion:example
+
+export { key }
diff --git a/packages/admin-sdk/examples/api-keys/delete.ts b/packages/admin-sdk/examples/api-keys/delete.ts
new file mode 100644
index 0000000000..d6515f2bce
--- /dev/null
+++ b/packages/admin-sdk/examples/api-keys/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.apiKeys.delete('key_xxx')
+// endregion:example
diff --git a/packages/admin-sdk/examples/api-keys/get.ts b/packages/admin-sdk/examples/api-keys/get.ts
new file mode 100644
index 0000000000..98127f406b
--- /dev/null
+++ b/packages/admin-sdk/examples/api-keys/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const key = await client.apiKeys.get('key_xxx')
+// endregion:example
+
+export { key }
diff --git a/packages/admin-sdk/examples/api-keys/list.ts b/packages/admin-sdk/examples/api-keys/list.ts
new file mode 100644
index 0000000000..fc85508230
--- /dev/null
+++ b/packages/admin-sdk/examples/api-keys/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: keys } = await client.apiKeys.list()
+// endregion:example
+
+export { keys }
diff --git a/packages/admin-sdk/examples/api-keys/revoke.ts b/packages/admin-sdk/examples/api-keys/revoke.ts
new file mode 100644
index 0000000000..d48d9d66d9
--- /dev/null
+++ b/packages/admin-sdk/examples/api-keys/revoke.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const key = await client.apiKeys.revoke('key_xxx')
+// endregion:example
+
+export { key }
diff --git a/packages/admin-sdk/examples/coupon-codes/list.ts b/packages/admin-sdk/examples/coupon-codes/list.ts
new file mode 100644
index 0000000000..f157f171df
--- /dev/null
+++ b/packages/admin-sdk/examples/coupon-codes/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: coupons } = await client.promotions.couponCodes.list('promo_UkLWZg9DAJ')
+// endregion:example
+
+export { coupons }
diff --git a/packages/admin-sdk/examples/custom-field-definitions/create.ts b/packages/admin-sdk/examples/custom-field-definitions/create.ts
new file mode 100644
index 0000000000..6338391de8
--- /dev/null
+++ b/packages/admin-sdk/examples/custom-field-definitions/create.ts
@@ -0,0 +1,19 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const definition = await client.customFieldDefinitions.create({
+ namespace: 'specs',
+ key: 'origin',
+ label: 'Country of Origin',
+ field_type: 'short_text',
+ resource_type: 'Spree::Product',
+ storefront_visible: true,
+})
+// endregion:example
+
+export { definition }
diff --git a/packages/admin-sdk/examples/custom-field-definitions/list.ts b/packages/admin-sdk/examples/custom-field-definitions/list.ts
new file mode 100644
index 0000000000..d991fc9e18
--- /dev/null
+++ b/packages/admin-sdk/examples/custom-field-definitions/list.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: definitions } = await client.customFieldDefinitions.list({
+ q: { resource_type_eq: 'Spree::Product' },
+})
+// endregion:example
+
+export { definitions }
diff --git a/packages/admin-sdk/examples/customer-addresses/create.ts b/packages/admin-sdk/examples/customer-addresses/create.ts
new file mode 100644
index 0000000000..b73eef14f5
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-addresses/create.ts
@@ -0,0 +1,23 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const address = await client.customers.addresses.create('cus_UkLWZg9DAJ', {
+ first_name: 'Jane',
+ last_name: 'Doe',
+ address1: '350 Fifth Avenue',
+ city: 'New York',
+ postal_code: '10118',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ phone: '+1 212 555 1234',
+ label: 'Office',
+ is_default_shipping: true,
+})
+// endregion:example
+
+export { address }
diff --git a/packages/admin-sdk/examples/customer-addresses/delete.ts b/packages/admin-sdk/examples/customer-addresses/delete.ts
new file mode 100644
index 0000000000..8765eea1a0
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-addresses/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.customers.addresses.delete('cus_UkLWZg9DAJ', 'addr_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/customer-addresses/list.ts b/packages/admin-sdk/examples/customer-addresses/list.ts
new file mode 100644
index 0000000000..fe084cf19a
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-addresses/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: addresses } = await client.customers.addresses.list('cus_UkLWZg9DAJ')
+// endregion:example
+
+export { addresses }
diff --git a/packages/admin-sdk/examples/customer-addresses/update.ts b/packages/admin-sdk/examples/customer-addresses/update.ts
new file mode 100644
index 0000000000..4a8c451a0a
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-addresses/update.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const address = await client.customers.addresses.update(
+ 'cus_UkLWZg9DAJ',
+ 'addr_UkLWZg9DAJ',
+ { city: 'Manhattan' },
+)
+// endregion:example
+
+export { address }
diff --git a/packages/admin-sdk/examples/customer-credit-cards/delete.ts b/packages/admin-sdk/examples/customer-credit-cards/delete.ts
new file mode 100644
index 0000000000..4459483d19
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-credit-cards/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.customers.creditCards.delete('cus_UkLWZg9DAJ', 'cc_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/customer-credit-cards/get.ts b/packages/admin-sdk/examples/customer-credit-cards/get.ts
new file mode 100644
index 0000000000..405def0ddf
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-credit-cards/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const card = await client.customers.creditCards.get('cus_UkLWZg9DAJ', 'cc_UkLWZg9DAJ')
+// endregion:example
+
+export { card }
diff --git a/packages/admin-sdk/examples/customer-credit-cards/list.ts b/packages/admin-sdk/examples/customer-credit-cards/list.ts
new file mode 100644
index 0000000000..d9ee9f46a8
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-credit-cards/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: cards } = await client.customers.creditCards.list('cus_UkLWZg9DAJ')
+// endregion:example
+
+export { cards }
diff --git a/packages/admin-sdk/examples/customer-store-credits/create.ts b/packages/admin-sdk/examples/customer-store-credits/create.ts
new file mode 100644
index 0000000000..8eb7be805c
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-store-credits/create.ts
@@ -0,0 +1,17 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const credit = await client.customers.storeCredits.create('cus_UkLWZg9DAJ', {
+ amount: 25.00,
+ currency: 'USD',
+ category_id: 'cat_UkLWZg9DAJ',
+ memo: 'Goodwill credit',
+})
+// endregion:example
+
+export { credit }
diff --git a/packages/admin-sdk/examples/customer-store-credits/delete.ts b/packages/admin-sdk/examples/customer-store-credits/delete.ts
new file mode 100644
index 0000000000..ac28a5933d
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-store-credits/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.customers.storeCredits.delete('cus_UkLWZg9DAJ', 'sc_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/customer-store-credits/list.ts b/packages/admin-sdk/examples/customer-store-credits/list.ts
new file mode 100644
index 0000000000..4ab104cddb
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-store-credits/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: storeCredits } = await client.customers.storeCredits.list('cus_UkLWZg9DAJ')
+// endregion:example
+
+export { storeCredits }
diff --git a/packages/admin-sdk/examples/customer-store-credits/update.ts b/packages/admin-sdk/examples/customer-store-credits/update.ts
new file mode 100644
index 0000000000..4324f89a6c
--- /dev/null
+++ b/packages/admin-sdk/examples/customer-store-credits/update.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const credit = await client.customers.storeCredits.update(
+ 'cus_UkLWZg9DAJ',
+ 'sc_UkLWZg9DAJ',
+ { memo: 'Reissued for damaged shipment' },
+)
+// endregion:example
+
+export { credit }
diff --git a/packages/admin-sdk/examples/customers/create.ts b/packages/admin-sdk/examples/customers/create.ts
new file mode 100644
index 0000000000..ac48d0083c
--- /dev/null
+++ b/packages/admin-sdk/examples/customers/create.ts
@@ -0,0 +1,19 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const customer = await client.customers.create({
+ email: '[email protected]',
+ first_name: 'Jane',
+ last_name: 'Doe',
+ phone: '+1 212 555 1234',
+ tags: ['wholesale'],
+ accepts_email_marketing: true,
+})
+// endregion:example
+
+export { customer }
diff --git a/packages/admin-sdk/examples/customers/delete.ts b/packages/admin-sdk/examples/customers/delete.ts
new file mode 100644
index 0000000000..7e31c18196
--- /dev/null
+++ b/packages/admin-sdk/examples/customers/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.customers.delete('cus_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/customers/get.ts b/packages/admin-sdk/examples/customers/get.ts
new file mode 100644
index 0000000000..53b2a836e3
--- /dev/null
+++ b/packages/admin-sdk/examples/customers/get.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const customer = await client.customers.get('cus_UkLWZg9DAJ', {
+ expand: ['addresses', 'store_credits'],
+})
+// endregion:example
+
+export { customer }
diff --git a/packages/admin-sdk/examples/customers/list.ts b/packages/admin-sdk/examples/customers/list.ts
new file mode 100644
index 0000000000..c08bb51aee
--- /dev/null
+++ b/packages/admin-sdk/examples/customers/list.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: customers } = await client.customers.list({
+ search: 'jane',
+ sort: '-created_at',
+ limit: 25,
+})
+// endregion:example
+
+export { customers }
diff --git a/packages/admin-sdk/examples/customers/update.ts b/packages/admin-sdk/examples/customers/update.ts
new file mode 100644
index 0000000000..8db6a9d54b
--- /dev/null
+++ b/packages/admin-sdk/examples/customers/update.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const customer = await client.customers.update('cus_UkLWZg9DAJ', {
+ first_name: 'Updated',
+ tags: ['wholesale', 'vip'],
+})
+// endregion:example
+
+export { customer }
diff --git a/packages/admin-sdk/examples/exports/create.ts b/packages/admin-sdk/examples/exports/create.ts
new file mode 100644
index 0000000000..5e49a55dc9
--- /dev/null
+++ b/packages/admin-sdk/examples/exports/create.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const exp = await client.exports.create({
+ type: 'Spree::Exports::Products',
+ search_params: { name_cont: 'shirt' }
+})
+// endregion:example
+
+export { exp }
diff --git a/packages/admin-sdk/examples/exports/delete.ts b/packages/admin-sdk/examples/exports/delete.ts
new file mode 100644
index 0000000000..e2d0181e2b
--- /dev/null
+++ b/packages/admin-sdk/examples/exports/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.exports.delete('exp_xxx')
+// endregion:example
diff --git a/packages/admin-sdk/examples/exports/download.ts b/packages/admin-sdk/examples/exports/download.ts
new file mode 100644
index 0000000000..f578e37a61
--- /dev/null
+++ b/packages/admin-sdk/examples/exports/download.ts
@@ -0,0 +1,27 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+declare const token: string
+const _exp = await client.exports.get('exp_xxx')
+// The download endpoint only returns a URL once the export is `done`; narrow
+// the type for the example so callers don't have to handle the null branch.
+const exp = _exp as { download_url: string; filename: string }
+
+// region:example
+// Fetch with the Bearer token, then drive the browser download:
+const res = await fetch(exp.download_url, {
+ headers: { Authorization: `Bearer ${token}` }
+})
+const blob = await res.blob()
+const url = URL.createObjectURL(blob)
+const a = Object.assign(document.createElement('a'), {
+ href: url,
+ download: exp.filename
+})
+a.click()
+URL.revokeObjectURL(url)
+// endregion:example
diff --git a/packages/admin-sdk/examples/exports/get.ts b/packages/admin-sdk/examples/exports/get.ts
new file mode 100644
index 0000000000..f1839633a9
--- /dev/null
+++ b/packages/admin-sdk/examples/exports/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const exp = await client.exports.get('exp_xxx')
+// endregion:example
+
+export { exp }
diff --git a/packages/admin-sdk/examples/exports/list.ts b/packages/admin-sdk/examples/exports/list.ts
new file mode 100644
index 0000000000..102bd14c5e
--- /dev/null
+++ b/packages/admin-sdk/examples/exports/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: exports } = await client.exports.list()
+// endregion:example
+
+export { exports }
diff --git a/packages/admin-sdk/examples/invitations/create.ts b/packages/admin-sdk/examples/invitations/create.ts
new file mode 100644
index 0000000000..d5955226ed
--- /dev/null
+++ b/packages/admin-sdk/examples/invitations/create.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const invitation = await client.invitations.create({
+ email: '[email protected]',
+ role_id: 'role_xxx'
+})
+// endregion:example
+
+export { invitation }
diff --git a/packages/admin-sdk/examples/invitations/delete.ts b/packages/admin-sdk/examples/invitations/delete.ts
new file mode 100644
index 0000000000..89d3cbf69f
--- /dev/null
+++ b/packages/admin-sdk/examples/invitations/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.invitations.delete('inv_xxx')
+// endregion:example
diff --git a/packages/admin-sdk/examples/invitations/list.ts b/packages/admin-sdk/examples/invitations/list.ts
new file mode 100644
index 0000000000..6041e86208
--- /dev/null
+++ b/packages/admin-sdk/examples/invitations/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: invitations } = await client.invitations.list()
+// endregion:example
+
+export { invitations }
diff --git a/packages/admin-sdk/examples/invitations/resend.ts b/packages/admin-sdk/examples/invitations/resend.ts
new file mode 100644
index 0000000000..cff0fa5c60
--- /dev/null
+++ b/packages/admin-sdk/examples/invitations/resend.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const invitation = await client.invitations.resend('inv_xxx')
+// endregion:example
+
+export { invitation }
diff --git a/packages/admin-sdk/examples/me/get.ts b/packages/admin-sdk/examples/me/get.ts
new file mode 100644
index 0000000000..d65fc5b5bf
--- /dev/null
+++ b/packages/admin-sdk/examples/me/get.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const me = await client.me.get()
+if (me.permissions.some((r) => r.allow && r.actions.includes('manage') && r.subjects.includes('Spree::Product'))) {
+ // show "Create product" button
+}
+// endregion:example
+
+export { me }
diff --git a/packages/admin-sdk/examples/option-types/create.ts b/packages/admin-sdk/examples/option-types/create.ts
new file mode 100644
index 0000000000..28e263edeb
--- /dev/null
+++ b/packages/admin-sdk/examples/option-types/create.ts
@@ -0,0 +1,19 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const optionType = await client.optionTypes.create({
+ name: 'color',
+ presentation: 'Color',
+ option_values: [
+ { name: 'red', presentation: 'Red' },
+ { name: 'navy', presentation: 'Navy' },
+ ],
+})
+// endregion:example
+
+export { optionType }
diff --git a/packages/admin-sdk/examples/option-types/delete.ts b/packages/admin-sdk/examples/option-types/delete.ts
new file mode 100644
index 0000000000..a4fdab30a2
--- /dev/null
+++ b/packages/admin-sdk/examples/option-types/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.optionTypes.delete('ot_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/option-types/get.ts b/packages/admin-sdk/examples/option-types/get.ts
new file mode 100644
index 0000000000..15dc43c160
--- /dev/null
+++ b/packages/admin-sdk/examples/option-types/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const optionType = await client.optionTypes.get('ot_UkLWZg9DAJ')
+// endregion:example
+
+export { optionType }
diff --git a/packages/admin-sdk/examples/option-types/list.ts b/packages/admin-sdk/examples/option-types/list.ts
new file mode 100644
index 0000000000..b39597ec34
--- /dev/null
+++ b/packages/admin-sdk/examples/option-types/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: optionTypes } = await client.optionTypes.list()
+// endregion:example
+
+export { optionTypes }
diff --git a/packages/admin-sdk/examples/option-types/update.ts b/packages/admin-sdk/examples/option-types/update.ts
new file mode 100644
index 0000000000..6c2b67c8c1
--- /dev/null
+++ b/packages/admin-sdk/examples/option-types/update.ts
@@ -0,0 +1,17 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const optionType = await client.optionTypes.update('ot_UkLWZg9DAJ', {
+ presentation: 'Updated Presentation',
+ option_values: [
+ { name: 'red', presentation: 'Crimson' },
+ ],
+})
+// endregion:example
+
+export { optionType }
diff --git a/packages/admin-sdk/examples/order-fulfillments/cancel.ts b/packages/admin-sdk/examples/order-fulfillments/cancel.ts
new file mode 100644
index 0000000000..86a6d78d8c
--- /dev/null
+++ b/packages/admin-sdk/examples/order-fulfillments/cancel.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const fulfillment = await client.orders.fulfillments.cancel('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ')
+// endregion:example
+
+export { fulfillment }
diff --git a/packages/admin-sdk/examples/order-fulfillments/fulfill.ts b/packages/admin-sdk/examples/order-fulfillments/fulfill.ts
new file mode 100644
index 0000000000..9c8d8266be
--- /dev/null
+++ b/packages/admin-sdk/examples/order-fulfillments/fulfill.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const fulfillment = await client.orders.fulfillments.fulfill('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ')
+// endregion:example
+
+export { fulfillment }
diff --git a/packages/admin-sdk/examples/order-fulfillments/get.ts b/packages/admin-sdk/examples/order-fulfillments/get.ts
new file mode 100644
index 0000000000..bb872d9a4b
--- /dev/null
+++ b/packages/admin-sdk/examples/order-fulfillments/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const fulfillment = await client.orders.fulfillments.get('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ')
+// endregion:example
+
+export { fulfillment }
diff --git a/packages/admin-sdk/examples/order-fulfillments/list.ts b/packages/admin-sdk/examples/order-fulfillments/list.ts
new file mode 100644
index 0000000000..85a94608ab
--- /dev/null
+++ b/packages/admin-sdk/examples/order-fulfillments/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: fulfillments } = await client.orders.fulfillments.list('or_UkLWZg9DAJ')
+// endregion:example
+
+export { fulfillments }
diff --git a/packages/admin-sdk/examples/order-fulfillments/resume.ts b/packages/admin-sdk/examples/order-fulfillments/resume.ts
new file mode 100644
index 0000000000..721e1c3af4
--- /dev/null
+++ b/packages/admin-sdk/examples/order-fulfillments/resume.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const fulfillment = await client.orders.fulfillments.resume('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ')
+// endregion:example
+
+export { fulfillment }
diff --git a/packages/admin-sdk/examples/order-fulfillments/split.ts b/packages/admin-sdk/examples/order-fulfillments/split.ts
new file mode 100644
index 0000000000..70f435145c
--- /dev/null
+++ b/packages/admin-sdk/examples/order-fulfillments/split.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const fulfillment = await client.orders.fulfillments.split('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ', {
+ quantity: 1,
+})
+// endregion:example
+
+export { fulfillment }
diff --git a/packages/admin-sdk/examples/order-fulfillments/update.ts b/packages/admin-sdk/examples/order-fulfillments/update.ts
new file mode 100644
index 0000000000..bf6122489a
--- /dev/null
+++ b/packages/admin-sdk/examples/order-fulfillments/update.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const fulfillment = await client.orders.fulfillments.update('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ', {
+ tracking: '1Z999AA10123456784',
+})
+// endregion:example
+
+export { fulfillment }
diff --git a/packages/admin-sdk/examples/order-gift-cards/apply.ts b/packages/admin-sdk/examples/order-gift-cards/apply.ts
new file mode 100644
index 0000000000..a14576156b
--- /dev/null
+++ b/packages/admin-sdk/examples/order-gift-cards/apply.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.orders.giftCards.apply('or_UkLWZg9DAJ', {
+ code: 'GIFT-XXXX-YYYY',
+})
+// endregion:example
diff --git a/packages/admin-sdk/examples/order-gift-cards/remove.ts b/packages/admin-sdk/examples/order-gift-cards/remove.ts
new file mode 100644
index 0000000000..c7f3389c61
--- /dev/null
+++ b/packages/admin-sdk/examples/order-gift-cards/remove.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.orders.giftCards.remove('or_UkLWZg9DAJ', 'gc_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/order-items/create.ts b/packages/admin-sdk/examples/order-items/create.ts
new file mode 100644
index 0000000000..ffc5920a68
--- /dev/null
+++ b/packages/admin-sdk/examples/order-items/create.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const item = await client.orders.items.create('or_UkLWZg9DAJ', {
+ variant_id: 'variant_k5nR8xLq',
+ quantity: 2,
+})
+// endregion:example
+
+export { item }
diff --git a/packages/admin-sdk/examples/order-items/delete.ts b/packages/admin-sdk/examples/order-items/delete.ts
new file mode 100644
index 0000000000..7760107e29
--- /dev/null
+++ b/packages/admin-sdk/examples/order-items/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.orders.items.delete('or_UkLWZg9DAJ', 'li_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/order-items/get.ts b/packages/admin-sdk/examples/order-items/get.ts
new file mode 100644
index 0000000000..2cd6ed14d1
--- /dev/null
+++ b/packages/admin-sdk/examples/order-items/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const item = await client.orders.items.get('or_UkLWZg9DAJ', 'li_UkLWZg9DAJ')
+// endregion:example
+
+export { item }
diff --git a/packages/admin-sdk/examples/order-items/list.ts b/packages/admin-sdk/examples/order-items/list.ts
new file mode 100644
index 0000000000..282a26371a
--- /dev/null
+++ b/packages/admin-sdk/examples/order-items/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: items } = await client.orders.items.list('or_UkLWZg9DAJ')
+// endregion:example
+
+export { items }
diff --git a/packages/admin-sdk/examples/order-items/update.ts b/packages/admin-sdk/examples/order-items/update.ts
new file mode 100644
index 0000000000..c2faec5e03
--- /dev/null
+++ b/packages/admin-sdk/examples/order-items/update.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const item = await client.orders.items.update('or_UkLWZg9DAJ', 'li_UkLWZg9DAJ', {
+ quantity: 5,
+})
+// endregion:example
+
+export { item }
diff --git a/packages/admin-sdk/examples/order-payments/capture.ts b/packages/admin-sdk/examples/order-payments/capture.ts
new file mode 100644
index 0000000000..0e629cd7c6
--- /dev/null
+++ b/packages/admin-sdk/examples/order-payments/capture.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const payment = await client.orders.payments.capture('or_UkLWZg9DAJ', 'pay_UkLWZg9DAJ')
+// endregion:example
+
+export { payment }
diff --git a/packages/admin-sdk/examples/order-payments/create.ts b/packages/admin-sdk/examples/order-payments/create.ts
new file mode 100644
index 0000000000..9ae9011735
--- /dev/null
+++ b/packages/admin-sdk/examples/order-payments/create.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const payment = await client.orders.payments.create('or_UkLWZg9DAJ', {
+ payment_method_id: 'pm_UkLWZg9DAJ',
+ amount: 99.99,
+ source_id: 'cc_UkLWZg9DAJ',
+})
+// endregion:example
+
+export { payment }
diff --git a/packages/admin-sdk/examples/order-payments/get.ts b/packages/admin-sdk/examples/order-payments/get.ts
new file mode 100644
index 0000000000..e8fac7221d
--- /dev/null
+++ b/packages/admin-sdk/examples/order-payments/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const payment = await client.orders.payments.get('or_UkLWZg9DAJ', 'pay_UkLWZg9DAJ')
+// endregion:example
+
+export { payment }
diff --git a/packages/admin-sdk/examples/order-payments/list.ts b/packages/admin-sdk/examples/order-payments/list.ts
new file mode 100644
index 0000000000..e37760d6f4
--- /dev/null
+++ b/packages/admin-sdk/examples/order-payments/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: payments } = await client.orders.payments.list('or_UkLWZg9DAJ')
+// endregion:example
+
+export { payments }
diff --git a/packages/admin-sdk/examples/order-payments/void.ts b/packages/admin-sdk/examples/order-payments/void.ts
new file mode 100644
index 0000000000..b1841de917
--- /dev/null
+++ b/packages/admin-sdk/examples/order-payments/void.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const payment = await client.orders.payments.void('or_UkLWZg9DAJ', 'pay_UkLWZg9DAJ')
+// endregion:example
+
+export { payment }
diff --git a/packages/admin-sdk/examples/order-refunds/create.ts b/packages/admin-sdk/examples/order-refunds/create.ts
new file mode 100644
index 0000000000..c3304b5db5
--- /dev/null
+++ b/packages/admin-sdk/examples/order-refunds/create.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const refund = await client.orders.refunds.create('or_UkLWZg9DAJ', {
+ payment_id: 'pay_UkLWZg9DAJ',
+ amount: 5.00,
+ refund_reason_id: 'refrsn_UkLWZg9DAJ',
+})
+// endregion:example
+
+export { refund }
diff --git a/packages/admin-sdk/examples/order-refunds/list.ts b/packages/admin-sdk/examples/order-refunds/list.ts
new file mode 100644
index 0000000000..753aa421da
--- /dev/null
+++ b/packages/admin-sdk/examples/order-refunds/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: refunds } = await client.orders.refunds.list('or_UkLWZg9DAJ')
+// endregion:example
+
+export { refunds }
diff --git a/packages/admin-sdk/examples/order-store-credits/apply.ts b/packages/admin-sdk/examples/order-store-credits/apply.ts
new file mode 100644
index 0000000000..c8f2f7eba3
--- /dev/null
+++ b/packages/admin-sdk/examples/order-store-credits/apply.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const order = await client.orders.storeCredits.apply('or_UkLWZg9DAJ', {
+ amount: 25.00,
+})
+// endregion:example
+
+export { order }
diff --git a/packages/admin-sdk/examples/order-store-credits/remove.ts b/packages/admin-sdk/examples/order-store-credits/remove.ts
new file mode 100644
index 0000000000..3d26012fc1
--- /dev/null
+++ b/packages/admin-sdk/examples/order-store-credits/remove.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.orders.storeCredits.remove('or_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/orders/approve.ts b/packages/admin-sdk/examples/orders/approve.ts
new file mode 100644
index 0000000000..6a2c2d5c6b
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/approve.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const order = await client.orders.approve('or_UkLWZg9DAJ')
+// endregion:example
+
+export { order }
diff --git a/packages/admin-sdk/examples/orders/cancel.ts b/packages/admin-sdk/examples/orders/cancel.ts
new file mode 100644
index 0000000000..e52a60ca0d
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/cancel.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const order = await client.orders.cancel('or_UkLWZg9DAJ')
+// endregion:example
+
+export { order }
diff --git a/packages/admin-sdk/examples/orders/complete.ts b/packages/admin-sdk/examples/orders/complete.ts
new file mode 100644
index 0000000000..4f95ee2a71
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/complete.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const order = await client.orders.complete('or_UkLWZg9DAJ', {
+ notify_customer: true,
+})
+// endregion:example
+
+export { order }
diff --git a/packages/admin-sdk/examples/orders/create.ts b/packages/admin-sdk/examples/orders/create.ts
new file mode 100644
index 0000000000..b730a0cfe5
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/create.ts
@@ -0,0 +1,73 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+// One-shot order create: customer, items, addresses, market, channel,
+// notes, metadata, and a coupon code in a single call. Everything
+// except `email` is optional.
+const order = await client.orders.create({
+ email: '[email protected]',
+ customer_id: 'cus_UkLWZg9DAJ', // Existing customer; omit for guest orders
+ use_customer_default_address: false, // true to copy the customer's saved addresses
+
+ currency: 'USD',
+ market_id: 'mkt_UkLWZg9DAJ',
+ channel_id: 'ch_UkLWZg9DAJ', // Optional — defaults to the store's primary channel
+ locale: 'en-US',
+
+ // Pin the order's preferred fulfillment location. Order Routing's
+ // built-in PreferredLocation rule ranks this location first when
+ // it stocks the cart's items; if it doesn't, routing falls back
+ // to the next rule (Minimize Splits → Default Location).
+ preferred_stock_location_id: 'sloc_UkLWZg9DAJ',
+
+ customer_note: 'Please leave at the front desk.',
+ internal_note: 'VIP customer — handle with care.',
+ metadata: {
+ external_reference: 'subscription_invoice_2026_04',
+ source: 'recurring-engine',
+ },
+
+ // Items: each variant_id + quantity. Optional metadata per line.
+ items: [
+ { variant_id: 'variant_k5nR8xLq', quantity: 2 },
+ { variant_id: 'variant_QXyZ12abCD', quantity: 1, metadata: { gift: true } },
+ ],
+
+ // Provide addresses inline OR by ID (existing customer addresses).
+ shipping_address: {
+ first_name: 'Jane',
+ last_name: 'Doe',
+ address1: '350 Fifth Avenue',
+ address2: 'Floor 42',
+ city: 'New York',
+ postal_code: '10118',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ phone: '+1 212 555 1234',
+ company: 'Acme Inc.',
+ },
+ // shipping_address_id: 'addr_UkLWZg9DAJ', // alternative to inline
+
+ billing_address: {
+ first_name: 'Jane',
+ last_name: 'Doe',
+ address1: '350 Fifth Avenue',
+ city: 'New York',
+ postal_code: '10118',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ phone: '+1 212 555 1234',
+ },
+ // billing_address_id: 'addr_UkLWZg9DAJ',
+
+ // Optional. Invalid codes are non-fatal — the order is created either way.
+ coupon_code: 'WELCOME10',
+})
+// endregion:example
+
+export { order }
diff --git a/packages/admin-sdk/examples/orders/delete.ts b/packages/admin-sdk/examples/orders/delete.ts
new file mode 100644
index 0000000000..a96d84b49a
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.orders.delete('or_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/orders/get.ts b/packages/admin-sdk/examples/orders/get.ts
new file mode 100644
index 0000000000..693508c0eb
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/get.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const order = await client.orders.get('or_UkLWZg9DAJ', {
+ expand: ['items', 'fulfillments', 'payments', 'customer'],
+})
+// endregion:example
+
+export { order }
diff --git a/packages/admin-sdk/examples/orders/list.ts b/packages/admin-sdk/examples/orders/list.ts
new file mode 100644
index 0000000000..97b9a41944
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/list.ts
@@ -0,0 +1,17 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: orders, meta } = await client.orders.list({
+ status_eq: 'complete',
+ completed_at_gt: '2026-01-01',
+ sort: '-completed_at',
+ limit: 25,
+})
+// endregion:example
+
+export { orders, meta }
diff --git a/packages/admin-sdk/examples/orders/resend-confirmation.ts b/packages/admin-sdk/examples/orders/resend-confirmation.ts
new file mode 100644
index 0000000000..a5590e840e
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/resend-confirmation.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.orders.resendConfirmation('or_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/orders/resume.ts b/packages/admin-sdk/examples/orders/resume.ts
new file mode 100644
index 0000000000..05ff74e5bf
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/resume.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const order = await client.orders.resume('or_UkLWZg9DAJ')
+// endregion:example
+
+export { order }
diff --git a/packages/admin-sdk/examples/orders/update.ts b/packages/admin-sdk/examples/orders/update.ts
new file mode 100644
index 0000000000..e40c9a7c62
--- /dev/null
+++ b/packages/admin-sdk/examples/orders/update.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const order = await client.orders.update('or_UkLWZg9DAJ', {
+ email: '[email protected]',
+ internal_note: 'VIP — gift wrap on next order',
+})
+// endregion:example
+
+export { order }
diff --git a/packages/admin-sdk/examples/payment-methods/get.ts b/packages/admin-sdk/examples/payment-methods/get.ts
new file mode 100644
index 0000000000..160996fc69
--- /dev/null
+++ b/packages/admin-sdk/examples/payment-methods/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const paymentMethod = await client.paymentMethods.get('pm_UkLWZg9DAJ')
+// endregion:example
+
+export { paymentMethod }
diff --git a/packages/admin-sdk/examples/payment-methods/list.ts b/packages/admin-sdk/examples/payment-methods/list.ts
new file mode 100644
index 0000000000..e143d50a0b
--- /dev/null
+++ b/packages/admin-sdk/examples/payment-methods/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: paymentMethods } = await client.paymentMethods.list()
+// endregion:example
+
+export { paymentMethods }
diff --git a/packages/admin-sdk/examples/payment-methods/types.ts b/packages/admin-sdk/examples/payment-methods/types.ts
new file mode 100644
index 0000000000..c4b35ce71b
--- /dev/null
+++ b/packages/admin-sdk/examples/payment-methods/types.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: types } = await client.paymentMethods.types()
+// endregion:example
+
+export { types }
diff --git a/packages/admin-sdk/examples/product-custom-fields/create.ts b/packages/admin-sdk/examples/product-custom-fields/create.ts
new file mode 100644
index 0000000000..2d054dcc16
--- /dev/null
+++ b/packages/admin-sdk/examples/product-custom-fields/create.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const customField = await client.products.customFields.create('prod_UkLWZg9DAJ', {
+ custom_field_definition_id: 'cfdef_AbC123XyZ',
+ value: 'wool',
+})
+// endregion:example
+
+export { customField }
diff --git a/packages/admin-sdk/examples/product-custom-fields/list.ts b/packages/admin-sdk/examples/product-custom-fields/list.ts
new file mode 100644
index 0000000000..681eaf8c9e
--- /dev/null
+++ b/packages/admin-sdk/examples/product-custom-fields/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: customFields } = await client.products.customFields.list('prod_UkLWZg9DAJ')
+// endregion:example
+
+export { customFields }
diff --git a/packages/admin-sdk/examples/products/create.ts b/packages/admin-sdk/examples/products/create.ts
new file mode 100644
index 0000000000..4d0b33d278
--- /dev/null
+++ b/packages/admin-sdk/examples/products/create.ts
@@ -0,0 +1,44 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const product = await client.products.create({
+ name: 'Premium T-Shirt',
+ price: 29.99,
+ description: 'Soft, organic cotton.',
+ status: 'active',
+ variants: [
+ {
+ sku: 'TSHIRT-S-NAVY',
+ options: [
+ { name: 'size', value: 'Small' },
+ { name: 'color', value: 'navy' },
+ ],
+ prices: [
+ { currency: 'USD', amount: 29.99 },
+ { currency: 'EUR', amount: 27.99 },
+ ],
+ stock_items: [
+ { stock_location_id: 'sloc_UkLWZg9DAJ', count_on_hand: 50 },
+ ],
+ },
+ {
+ sku: 'TSHIRT-M-NAVY',
+ options: [
+ { name: 'size', value: 'Medium' },
+ { name: 'color', value: 'navy' },
+ ],
+ prices: [{ currency: 'USD', amount: 29.99 }],
+ stock_items: [
+ { stock_location_id: 'sloc_UkLWZg9DAJ', count_on_hand: 30 },
+ ],
+ },
+ ],
+})
+// endregion:example
+
+export { product }
diff --git a/packages/admin-sdk/examples/products/delete.ts b/packages/admin-sdk/examples/products/delete.ts
new file mode 100644
index 0000000000..4e6f104494
--- /dev/null
+++ b/packages/admin-sdk/examples/products/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.products.delete('prod_86Rf07xd4z')
+// endregion:example
diff --git a/packages/admin-sdk/examples/products/get.ts b/packages/admin-sdk/examples/products/get.ts
new file mode 100644
index 0000000000..6ed0487a19
--- /dev/null
+++ b/packages/admin-sdk/examples/products/get.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const product = await client.products.get('prod_86Rf07xd4z', {
+ expand: ['variants', 'option_types'],
+})
+// endregion:example
+
+export { product }
diff --git a/packages/admin-sdk/examples/products/list.ts b/packages/admin-sdk/examples/products/list.ts
new file mode 100644
index 0000000000..c2835890c6
--- /dev/null
+++ b/packages/admin-sdk/examples/products/list.ts
@@ -0,0 +1,17 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: products } = await client.products.list({
+ name_cont: 'shirt',
+ status_eq: 'active',
+ sort: '-created_at',
+ limit: 25,
+})
+// endregion:example
+
+export { products }
diff --git a/packages/admin-sdk/examples/products/update.ts b/packages/admin-sdk/examples/products/update.ts
new file mode 100644
index 0000000000..31360a2301
--- /dev/null
+++ b/packages/admin-sdk/examples/products/update.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const product = await client.products.update('prod_86Rf07xd4z', {
+ name: 'Updated Name',
+ status: 'active',
+ tags: ['eco', 'sale'],
+})
+// endregion:example
+
+export { product }
diff --git a/packages/admin-sdk/examples/promotion-actions/create.ts b/packages/admin-sdk/examples/promotion-actions/create.ts
new file mode 100644
index 0000000000..5782b1d37a
--- /dev/null
+++ b/packages/admin-sdk/examples/promotion-actions/create.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const action = await client.promotions.actions.create('promo_UkLWZg9DAJ', {
+ type: 'free_shipping',
+})
+// endregion:example
+
+export { action }
diff --git a/packages/admin-sdk/examples/promotion-actions/list.ts b/packages/admin-sdk/examples/promotion-actions/list.ts
new file mode 100644
index 0000000000..b982c860a3
--- /dev/null
+++ b/packages/admin-sdk/examples/promotion-actions/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: actions } = await client.promotions.actions.list('promo_UkLWZg9DAJ')
+// endregion:example
+
+export { actions }
diff --git a/packages/admin-sdk/examples/promotion-rules/create.ts b/packages/admin-sdk/examples/promotion-rules/create.ts
new file mode 100644
index 0000000000..8bdfbb018c
--- /dev/null
+++ b/packages/admin-sdk/examples/promotion-rules/create.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const rule = await client.promotions.rules.create('promo_UkLWZg9DAJ', {
+ type: 'currency',
+ preferences: { currency: 'EUR' },
+})
+// endregion:example
+
+export { rule }
diff --git a/packages/admin-sdk/examples/promotion-rules/list.ts b/packages/admin-sdk/examples/promotion-rules/list.ts
new file mode 100644
index 0000000000..3e18b8bc34
--- /dev/null
+++ b/packages/admin-sdk/examples/promotion-rules/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: rules } = await client.promotions.rules.list('promo_UkLWZg9DAJ')
+// endregion:example
+
+export { rules }
diff --git a/packages/admin-sdk/examples/promotions/action-types.ts b/packages/admin-sdk/examples/promotions/action-types.ts
new file mode 100644
index 0000000000..1ce8980f3b
--- /dev/null
+++ b/packages/admin-sdk/examples/promotions/action-types.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: actionTypes } = await client.promotionActions.types()
+// endregion:example
+
+export { actionTypes }
diff --git a/packages/admin-sdk/examples/promotions/create.ts b/packages/admin-sdk/examples/promotions/create.ts
new file mode 100644
index 0000000000..dc97260394
--- /dev/null
+++ b/packages/admin-sdk/examples/promotions/create.ts
@@ -0,0 +1,54 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+// Single coupon code, no rules/actions
+const promotion = await client.promotions.create({
+ name: 'Black Friday',
+ code: 'BLACKFRIDAY',
+ starts_at: '2026-11-29T00:00:00Z',
+ expires_at: '2026-12-01T00:00:00Z',
+})
+
+// One-shot: promotion + rules + actions in a single request
+const blackFriday = await client.promotions.create({
+ name: 'Black Friday',
+ code: 'BLACKFRIDAY',
+ kind: 'coupon_code',
+ starts_at: '2026-11-29T00:00:00Z',
+ expires_at: '2026-12-01T00:00:00Z',
+ match_policy: 'all',
+ rules: [
+ {
+ type: 'currency',
+ preferences: { currency: 'USD' },
+ },
+ {
+ type: 'item_total',
+ preferences: { amount_min: 100, operator_min: 'gte' },
+ },
+ {
+ type: 'product',
+ preferences: { match_policy: 'any' },
+ product_ids: ['prod_abc123', 'prod_def456'],
+ },
+ ],
+ actions: [
+ {
+ type: 'create_item_adjustments',
+ calculator: {
+ type: 'percent_on_line_item',
+ preferences: { percent: 25 },
+ },
+ },
+ { type: 'free_shipping' },
+ ],
+})
+// endregion:example
+
+// Suppress unused-binding warnings — these are display-only example values.
+export { promotion, blackFriday }
diff --git a/packages/admin-sdk/examples/promotions/list.ts b/packages/admin-sdk/examples/promotions/list.ts
new file mode 100644
index 0000000000..337773d938
--- /dev/null
+++ b/packages/admin-sdk/examples/promotions/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: promotions } = await client.promotions.list()
+// endregion:example
+
+export { promotions }
diff --git a/packages/admin-sdk/examples/promotions/rule-types.ts b/packages/admin-sdk/examples/promotions/rule-types.ts
new file mode 100644
index 0000000000..2bb13544dd
--- /dev/null
+++ b/packages/admin-sdk/examples/promotions/rule-types.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: ruleTypes } = await client.promotionRules.types()
+// endregion:example
+
+export { ruleTypes }
diff --git a/packages/admin-sdk/examples/promotions/update.ts b/packages/admin-sdk/examples/promotions/update.ts
new file mode 100644
index 0000000000..8307995d05
--- /dev/null
+++ b/packages/admin-sdk/examples/promotions/update.ts
@@ -0,0 +1,50 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+const promotionId = 'promo_UkLWZg9DAJ'
+
+// region:example
+// Basic field update
+await client.promotions.update(promotionId, {
+ description: 'Updated description',
+})
+
+// One-shot: rewrite rules + actions in a single request
+await client.promotions.update(promotionId, {
+ name: 'Holiday Sale',
+ rules: [
+ // Update an existing rule by id — `preferences` overwrite the prior set
+ {
+ id: 'prorule_existing',
+ type: 'currency',
+ preferences: { currency: 'EUR' },
+ },
+ // Add a new rule
+ {
+ type: 'item_total',
+ preferences: { amount_min: 50, operator_min: 'gte' },
+ },
+ ],
+ actions: [
+ // Swap calculator type on an existing action
+ {
+ id: 'proaction_existing',
+ type: 'create_item_adjustments',
+ calculator: {
+ type: 'percent_on_line_item',
+ preferences: { percent: 15 },
+ },
+ },
+ ],
+})
+
+// Remove all rules/actions
+await client.promotions.update(promotionId, {
+ rules: [],
+ actions: [],
+})
+// endregion:example
diff --git a/packages/admin-sdk/examples/roles/list.ts b/packages/admin-sdk/examples/roles/list.ts
new file mode 100644
index 0000000000..6b5715ecd4
--- /dev/null
+++ b/packages/admin-sdk/examples/roles/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: roles } = await client.roles.list()
+// endregion:example
+
+export { roles }
diff --git a/packages/admin-sdk/examples/stock-locations/create.ts b/packages/admin-sdk/examples/stock-locations/create.ts
new file mode 100644
index 0000000000..6ff1d43661
--- /dev/null
+++ b/packages/admin-sdk/examples/stock-locations/create.ts
@@ -0,0 +1,22 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const stockLocation = await client.stockLocations.create({
+ name: 'Brooklyn warehouse',
+ kind: 'warehouse',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ city: 'Brooklyn',
+ zipcode: '11201',
+ pickup_enabled: true,
+ pickup_stock_policy: 'local',
+ pickup_ready_in_minutes: 60,
+})
+// endregion:example
+
+export { stockLocation }
diff --git a/packages/admin-sdk/examples/stock-locations/delete.ts b/packages/admin-sdk/examples/stock-locations/delete.ts
new file mode 100644
index 0000000000..4417043a8e
--- /dev/null
+++ b/packages/admin-sdk/examples/stock-locations/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.stockLocations.delete('sloc_UkLWZg9DAJ')
+// endregion:example
diff --git a/packages/admin-sdk/examples/stock-locations/get.ts b/packages/admin-sdk/examples/stock-locations/get.ts
new file mode 100644
index 0000000000..d38524c059
--- /dev/null
+++ b/packages/admin-sdk/examples/stock-locations/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const stockLocation = await client.stockLocations.get('sloc_UkLWZg9DAJ')
+// endregion:example
+
+export { stockLocation }
diff --git a/packages/admin-sdk/examples/stock-locations/list.ts b/packages/admin-sdk/examples/stock-locations/list.ts
new file mode 100644
index 0000000000..ae16429900
--- /dev/null
+++ b/packages/admin-sdk/examples/stock-locations/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: stockLocations } = await client.stockLocations.list()
+// endregion:example
+
+export { stockLocations }
diff --git a/packages/admin-sdk/examples/stock-locations/update.ts b/packages/admin-sdk/examples/stock-locations/update.ts
new file mode 100644
index 0000000000..a1f33113d2
--- /dev/null
+++ b/packages/admin-sdk/examples/stock-locations/update.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const stockLocation = await client.stockLocations.update('sloc_UkLWZg9DAJ', {
+ pickup_enabled: true,
+ pickup_ready_in_minutes: 45,
+ pickup_instructions: 'Enter through the back door, ring the bell.',
+})
+// endregion:example
+
+export { stockLocation }
diff --git a/packages/admin-sdk/examples/store-credit-categories/get.ts b/packages/admin-sdk/examples/store-credit-categories/get.ts
new file mode 100644
index 0000000000..fd1fedc482
--- /dev/null
+++ b/packages/admin-sdk/examples/store-credit-categories/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const category = await client.storeCreditCategories.get('sccat_UkLWZg9DAJ')
+// endregion:example
+
+export { category }
diff --git a/packages/admin-sdk/examples/store-credit-categories/list.ts b/packages/admin-sdk/examples/store-credit-categories/list.ts
new file mode 100644
index 0000000000..d4ac5a8ca9
--- /dev/null
+++ b/packages/admin-sdk/examples/store-credit-categories/list.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: categories } = await client.storeCreditCategories.list()
+// endregion:example
+
+export { categories }
diff --git a/packages/admin-sdk/examples/store/get.ts b/packages/admin-sdk/examples/store/get.ts
new file mode 100644
index 0000000000..0333b9e404
--- /dev/null
+++ b/packages/admin-sdk/examples/store/get.ts
@@ -0,0 +1,12 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const store = await client.store.get()
+// endregion:example
+
+export { store }
diff --git a/packages/admin-sdk/examples/store/update.ts b/packages/admin-sdk/examples/store/update.ts
new file mode 100644
index 0000000000..bdc644a9c0
--- /dev/null
+++ b/packages/admin-sdk/examples/store/update.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const store = await client.store.update({
+ name: 'My Store'
+})
+// endregion:example
+
+export { store }
diff --git a/packages/admin-sdk/examples/tags/list.ts b/packages/admin-sdk/examples/tags/list.ts
new file mode 100644
index 0000000000..29da535843
--- /dev/null
+++ b/packages/admin-sdk/examples/tags/list.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: tags } = await client.tags.list({
+ taggable_type: 'Spree::User',
+ q: 'vip',
+})
+// endregion:example
+
+export { tags }
diff --git a/packages/admin-sdk/examples/variants/create.ts b/packages/admin-sdk/examples/variants/create.ts
new file mode 100644
index 0000000000..98233e526a
--- /dev/null
+++ b/packages/admin-sdk/examples/variants/create.ts
@@ -0,0 +1,25 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const variant = await client.products.variants.create('prod_86Rf07xd4z', {
+ sku: 'TSHIRT-L-NAVY',
+ options: [
+ { name: 'size', value: 'Large' },
+ { name: 'color', value: 'navy' },
+ ],
+ prices: [
+ { currency: 'USD', amount: 29.99, compare_at_amount: 34.99 },
+ { currency: 'EUR', amount: 27.99 },
+ ],
+ stock_items: [
+ { stock_location_id: 'sloc_UkLWZg9DAJ', count_on_hand: 25 },
+ ],
+})
+// endregion:example
+
+export { variant }
diff --git a/packages/admin-sdk/examples/variants/delete.ts b/packages/admin-sdk/examples/variants/delete.ts
new file mode 100644
index 0000000000..e6a3a6b0b9
--- /dev/null
+++ b/packages/admin-sdk/examples/variants/delete.ts
@@ -0,0 +1,10 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+await client.products.variants.delete('prod_86Rf07xd4z', 'variant_k5nR8xLq')
+// endregion:example
diff --git a/packages/admin-sdk/examples/variants/get.ts b/packages/admin-sdk/examples/variants/get.ts
new file mode 100644
index 0000000000..26afbc91f4
--- /dev/null
+++ b/packages/admin-sdk/examples/variants/get.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const variant = await client.products.variants.get('prod_86Rf07xd4z', 'variant_k5nR8xLq', {
+ expand: ['prices', 'stock_items'],
+})
+// endregion:example
+
+export { variant }
diff --git a/packages/admin-sdk/examples/variants/list.ts b/packages/admin-sdk/examples/variants/list.ts
new file mode 100644
index 0000000000..e0bf4a9de0
--- /dev/null
+++ b/packages/admin-sdk/examples/variants/list.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { data: variants } = await client.products.variants.list('prod_86Rf07xd4z', {
+ expand: ['prices', 'stock_items'],
+})
+// endregion:example
+
+export { variants }
diff --git a/packages/admin-sdk/examples/variants/update.ts b/packages/admin-sdk/examples/variants/update.ts
new file mode 100644
index 0000000000..b4f4e81280
--- /dev/null
+++ b/packages/admin-sdk/examples/variants/update.ts
@@ -0,0 +1,17 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const variant = await client.products.variants.update('prod_86Rf07xd4z', 'variant_k5nR8xLq', {
+ sku: 'UPDATED-SKU',
+ stock_items: [
+ { stock_location_id: 'sloc_UkLWZg9DAJ', count_on_hand: 75 },
+ ],
+})
+// endregion:example
+
+export { variant }
diff --git a/packages/admin-sdk/package.json b/packages/admin-sdk/package.json
index 098dc51761..9d87e4eacd 100644
--- a/packages/admin-sdk/package.json
+++ b/packages/admin-sdk/package.json
@@ -38,6 +38,7 @@
"build": "tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
+ "examples:typecheck": "tsc --noEmit -p tsconfig.examples.json",
"test": "vitest run --passWithNoTests",
"test:watch": "vitest",
"lint": "biome check src tests",
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index f53d67fc12..beabc6a0bb 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -122,6 +122,7 @@ import type {
PaymentMethodCreateParams,
PaymentMethodType,
PaymentMethodUpdateParams,
+ ProductCreateParams,
ProductUpdateParams,
PromotionActionCalculator,
PromotionActionCreateParams,
@@ -445,6 +446,9 @@ export class AdminClient {
params: getParams(params),
}),
+ create: (params: ProductCreateParams, options?: RequestOptions): Promise<Product> =>
+ this.request<Product>('POST', '/products', { ...options, body: params }),
+
update: (id: string, params: ProductUpdateParams, options?: RequestOptions): Promise<Product> =>
this.request<Product>('PATCH', `/products/${id}`, { ...options, body: params }),
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 58515312c2..8ebac039fd 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -70,6 +70,7 @@ export interface AddressInputParams {
country_iso?: string
state_abbr?: string
phone?: string
+ company?: string
}
export interface OrderCreateParams {
@@ -79,6 +80,15 @@ export interface OrderCreateParams {
use_customer_default_address?: boolean
currency?: string
market_id?: string
+ /** Channel ID. Defaults to the store primary channel when omitted. */
+ channel_id?: string
+ /**
+ * Stock Location ID to prefer for fulfillment. Order Routing's built-in
+ * `PreferredLocation` rule reads this and ranks the location first;
+ * routing falls back to the next rule when the preferred location can't
+ * cover the cart.
+ */
+ preferred_stock_location_id?: string
locale?: string
customer_note?: string
internal_note?: string
@@ -92,6 +102,7 @@ export interface OrderCreateParams {
quantity: number
metadata?: Record<string, unknown>
}>
+ /** Optional. Applied non-fatally; invalid codes do not block creation. */
coupon_code?: string
}
@@ -221,6 +232,8 @@ export interface MediaUpdateParams {
export interface ProductCreateParams {
name: string
+ /** Default price in the store's primary currency. */
+ price?: number
description?: string
slug?: string
status?: 'draft' | 'active' | 'archived'
@@ -604,7 +617,6 @@ export interface PromotionCreateParams {
multi_codes?: boolean
number_of_codes?: number | null
code_prefix?: string | null
- store_ids?: string[]
metadata?: Record<string, unknown>
/** Optional rules to create alongside the promotion. Sent as a desired-set on update. */
rules?: PromotionRuleDraft[]
@@ -626,7 +638,6 @@ export interface PromotionUpdateParams {
multi_codes?: boolean
number_of_codes?: number | null
code_prefix?: string | null
- store_ids?: string[]
metadata?: Record<string, unknown>
/** Replaces the rule set: rows with `id` update, rows without build, missing rows are removed. */
rules?: PromotionRuleDraft[]
@@ -642,35 +653,42 @@ export interface PromotionUpdateParams {
*/
export interface PromotionRuleDraft {
id?: string
- /** Fully-qualified STI subclass (`'Spree::Promotion::Rules::Currency'`). */
+ /**
+ * Wire shorthand for the rule subclass (e.g. `'currency'`, `'item_total'`,
+ * `'product'`, `'category'`). Returned by `GET /promotion_rules/types`.
+ */
type: string
preferences?: Record<string, unknown>
- /** For `Rules::Product`. */
+ /** For the `product` rule. */
product_ids?: string[]
- /** For `Rules::Taxon` (renamed Category in 6.0). */
+ /** For the `category` rule. */
category_ids?: string[]
- /** For `Rules::User`. */
- user_ids?: string[]
+ /** For the `user` rule — customers who qualify for the promotion. */
+ customer_ids?: string[]
}
export interface PromotionActionDraft {
id?: string
- /** Fully-qualified STI subclass (`'Spree::Promotion::Actions::FreeShipping'`). */
+ /**
+ * Wire shorthand for the action subclass (e.g. `'free_shipping'`,
+ * `'create_item_adjustments'`, `'create_adjustment'`). Returned by
+ * `GET /promotion_actions/types`.
+ */
type: string
preferences?: Record<string, unknown>
/** For adjustment actions. */
calculator?: PromotionActionCalculatorParams
- /** For `CreateLineItems`. */
+ /** For `create_line_items`. */
line_items?: PromotionActionLineItemParams[]
}
/**
* Nested calculator payload for adjustment actions. Sent on
- * `Spree::Promotion::Actions::CreateAdjustment` and `CreateItemAdjustments`.
+ * `create_adjustment` and `create_item_adjustments`.
*
- * - `type` — fully-qualified calculator STI subclass (e.g.
- * `'Spree::Calculator::FlatRate'`); changing the type swaps the
- * underlying calculator record.
+ * - `type` — wire shorthand for the calculator subclass (e.g. `'flat_rate'`,
+ * `'flat_percent_item_total'`, `'percent_on_line_item'`); changing the
+ * type swaps the underlying calculator record.
* - `preferences` — per-calculator preference values (`amount`,
* `flat_percent`, `currency`, …). Keys are coerced via the typed
* setters server-side.
@@ -703,7 +721,7 @@ export interface PromotionActionCalculator {
}
export interface PromotionActionCreateParams {
- /** Fully-qualified STI subclass (`'Spree::Promotion::Actions::FreeShipping'`). */
+ /** Wire shorthand for the action subclass (e.g. `'free_shipping'`). */
type: string
preferences?: Record<string, unknown>
/** For adjustment actions — calculator subclass + its preference values. */
@@ -719,20 +737,20 @@ export interface PromotionActionUpdateParams {
}
export interface PromotionRuleCreateParams {
- /** Fully-qualified STI subclass (`'Spree::Promotion::Rules::Currency'`). */
+ /** Wire shorthand for the rule subclass (e.g. `'currency'`, `'item_total'`). */
type: string
preferences?: Record<string, unknown>
- /** For `Rules::Product` — prefixed product IDs to associate with this rule. */
+ /** For the `product` rule — prefixed product IDs to associate with this rule. */
product_ids?: string[]
- /** For `Rules::Taxon` — prefixed category IDs (Taxon is renamed to Category in 6.0). */
+ /** For the `category` rule — prefixed category IDs. */
category_ids?: string[]
- /** For `Rules::User` — prefixed user IDs. */
- user_ids?: string[]
+ /** For the `user` rule — prefixed customer IDs. */
+ customer_ids?: string[]
}
export interface PromotionRuleUpdateParams {
preferences?: Record<string, unknown>
product_ids?: string[]
category_ids?: string[]
- user_ids?: string[]
+ customer_ids?: string[]
}
diff --git a/packages/admin-sdk/src/types/generated/PromotionAction.ts b/packages/admin-sdk/src/types/generated/PromotionAction.ts
index 86c69ab8c3..108f845b6a 100644
--- a/packages/admin-sdk/src/types/generated/PromotionAction.ts
+++ b/packages/admin-sdk/src/types/generated/PromotionAction.ts
@@ -1,13 +1,12 @@
-// Typelizer digest 7afe7b75ef6cc7880ba53b93194e1f1e
+// Typelizer digest d8d786c45e83537b5ab1d43b6b24d771
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
interface PromotionAction {
id: string;
- type: string;
created_at: string;
updated_at: string;
- key: string;
+ type: string;
promotion_id: string;
preferences: Record<string, unknown>;
preference_schema: Array<{ key: string; type: string; default: unknown }>;
diff --git a/packages/admin-sdk/src/types/generated/PromotionRule.ts b/packages/admin-sdk/src/types/generated/PromotionRule.ts
index 5fa1824bd7..16a708cb96 100644
--- a/packages/admin-sdk/src/types/generated/PromotionRule.ts
+++ b/packages/admin-sdk/src/types/generated/PromotionRule.ts
@@ -1,21 +1,20 @@
-// Typelizer digest b00d15e0fe6e07d81e070bfa94cc8933
+// Typelizer digest 216b085a4b19c589b137ef282f9f50aa
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Product, Category, Customer, CustomerGroup, Country} from '@/types'
interface PromotionRule {
id: string;
- type: string;
created_at: string;
updated_at: string;
- key: string;
+ type: string;
promotion_id: string;
preferences: Record<string, unknown>;
preference_schema: Array<{ key: string; type: string; default: unknown }>;
label: string;
product_ids: Array<string> | null;
category_ids: Array<string> | null;
- user_ids: Array<string> | null;
+ customer_ids: Array<string> | null;
products?: Array<Product>;
categories?: Array<Category>;
customers?: Array<Customer>;
diff --git a/packages/admin-sdk/tsconfig.examples.json b/packages/admin-sdk/tsconfig.examples.json
new file mode 100644
index 0000000000..7f90cc4ee0
--- /dev/null
+++ b/packages/admin-sdk/tsconfig.examples.json
@@ -0,0 +1,16 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": true,
+ "rootDir": "./",
+ "noUnusedLocals": false,
+ "noUnusedParameters": false,
+ "paths": {
+ "@/types": ["./src/types/generated/index.ts"],
+ "@spree/admin-sdk": ["./src/index.ts"],
+ "@spree/admin-sdk/types": ["./src/types/generated/index.ts"]
+ }
+ },
+ "include": ["examples/**/*.ts", "src/**/*.ts"],
+ "exclude": ["node_modules", "dist", "tests"]
+}
diff --git a/packages/admin/src/components/spree/preferences-form.tsx b/packages/admin/src/components/spree/preferences-form.tsx
index b5e2d590fe..2accbd8b8e 100644
--- a/packages/admin/src/components/spree/preferences-form.tsx
+++ b/packages/admin/src/components/spree/preferences-form.tsx
@@ -1,5 +1,8 @@
import type { PreferenceField as PreferenceFieldDef } from '@spree/admin-sdk'
+import { PlusIcon, TrashIcon } from 'lucide-react'
+import { useId, useMemo, useState } from 'react'
import { CurrencySelect } from '@/components/spree/currency-select'
+import { Button } from '@/components/ui/button'
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
@@ -87,6 +90,14 @@ export function PreferenceField({
)
}
+ // `tiers` preference (Spree::Calculator::TieredPercent /
+ // TieredFlatRate) — a Hash<threshold, value> that the default
+ // hash-as-text input would render as `[object Object]`. Render a row
+ // editor so the merchant can add tier breakpoints directly.
+ if (field.key === 'tiers') {
+ return <TiersEditor value={value} onChange={onChange} />
+ }
+
switch (field.type) {
case 'boolean':
return (
@@ -211,3 +222,153 @@ function humanizeKey(key: string): string {
function isCurrencyKey(key: string): boolean {
return key === 'currency' || key.endsWith('_currency')
}
+
+interface TierRowState {
+ /** Stable across edits — used for React keys so input focus survives reorder. */
+ uid: string
+ threshold: string
+ value: string
+}
+
+/**
+ * Editor for `Spree::Calculator::TieredPercent` / `TieredFlatRate`
+ * preferences. The underlying shape is `Hash<threshold, value>` — orders
+ * at or above `threshold` get `value` (% or $ depending on the
+ * calculator).
+ *
+ * Owns its row list locally so the user can add an empty row and fill
+ * it in afterwards — projecting to the hash on every change would drop
+ * empty-threshold rows the moment they're added. Empty rows are
+ * filtered when projecting to the parent's hash value.
+ */
+function TiersEditor({
+ value,
+ onChange,
+}: {
+ value: unknown
+ onChange: (next: Record<string, number>) => void
+}) {
+ const idPrefix = useId()
+ // Seed once from the initial value. Subsequent rerenders driven by
+ // parent state (e.g. another preference field changes) keep our row
+ // list intact so the user doesn't lose their in-progress empty rows.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: intentional one-time seed
+ const initialRows = useMemo(() => parseTiers(value, idPrefix), [])
+ const [rows, setRows] = useState<TierRowState[]>(initialRows)
+
+ function commit(next: TierRowState[]) {
+ setRows(next)
+ const out: Record<string, number> = {}
+ for (const row of next) {
+ const t = row.threshold.trim()
+ if (!t) continue
+ const parsed = Number(row.value)
+ out[t] = Number.isFinite(parsed) ? parsed : 0
+ }
+ onChange(out)
+ }
+
+ function updateRow(uid: string, patch: Partial<Pick<TierRowState, 'threshold' | 'value'>>) {
+ commit(rows.map((row) => (row.uid === uid ? { ...row, ...patch } : row)))
+ }
+
+ function addRow() {
+ commit([
+ ...rows,
+ { uid: `${idPrefix}-${rows.length + 1}-${Date.now()}`, threshold: '', value: '' },
+ ])
+ }
+
+ function removeRow(uid: string) {
+ commit(rows.filter((row) => row.uid !== uid))
+ }
+
+ return (
+ <Field>
+ <FieldLabel>Tiers</FieldLabel>
+ <div className="space-y-2">
+ {rows.length === 0 ? (
+ <p className="text-xs text-muted-foreground">
+ No tiers yet. The base rate applies until you add a tier.
+ </p>
+ ) : (
+ <div className="grid grid-cols-[1fr_1fr_auto] gap-2">
+ <span className="text-xs font-medium text-muted-foreground">Order total ≥</span>
+ <span className="text-xs font-medium text-muted-foreground">Discount</span>
+ <span />
+ {rows.map((row) => (
+ <TierRow
+ key={row.uid}
+ row={row}
+ onChange={(patch) => updateRow(row.uid, patch)}
+ onRemove={() => removeRow(row.uid)}
+ />
+ ))}
+ </div>
+ )}
+ <Button type="button" variant="outline" size="sm" onClick={addRow}>
+ <PlusIcon className="size-4" />
+ Add tier
+ </Button>
+ </div>
+ </Field>
+ )
+}
+
+function TierRow({
+ row,
+ onChange,
+ onRemove,
+}: {
+ row: TierRowState
+ onChange: (patch: Partial<Pick<TierRowState, 'threshold' | 'value'>>) => void
+ onRemove: () => void
+}) {
+ return (
+ <>
+ <Input
+ type="number"
+ step="any"
+ min={0}
+ value={row.threshold}
+ placeholder="100"
+ onChange={(e) => onChange({ threshold: e.target.value })}
+ />
+ <Input
+ type="number"
+ step="any"
+ min={0}
+ value={row.value}
+ placeholder="10"
+ onChange={(e) => onChange({ value: e.target.value })}
+ />
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ onClick={onRemove}
+ aria-label="Remove tier"
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ <TrashIcon className="size-4" />
+ </Button>
+ </>
+ )
+}
+
+/**
+ * Normalize whatever shape the server sent — typically `Hash<number,
+ * number>` but JSON serialization stringifies the keys, so we may
+ * receive `{ "100": 10 }` or `{ 100: 10 }`. Either form converts to
+ * `TierRowState[]` for editor state.
+ */
+function parseTiers(value: unknown, idPrefix: string): TierRowState[] {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return []
+ return Object.entries(value as Record<string, unknown>)
+ .map(([threshold, v], i) => ({
+ uid: `${idPrefix}-seed-${i}`,
+ threshold: String(threshold),
+ value: v === null || v === undefined ? '' : String(v),
+ }))
+ .sort((a, b) => Number(a.threshold) - Number(b.threshold))
+}
diff --git a/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx b/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx
new file mode 100644
index 0000000000..0a5551af05
--- /dev/null
+++ b/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx
@@ -0,0 +1,1322 @@
+import type {
+ Promotion,
+ PromotionAction,
+ PromotionActionDraft,
+ PromotionRule,
+ PromotionRuleDraft,
+ ResourceTypeDefinition,
+} from '@spree/admin-sdk'
+import { DownloadIcon, PlusIcon, TrashIcon } from 'lucide-react'
+import { useEffect, useState } from 'react'
+import { Controller, useFieldArray, useForm } from 'react-hook-form'
+import { formatCalculatorSummary } from '@/components/spree/calculator-summary'
+import { Can } from '@/components/spree/can'
+import { useConfirm } from '@/components/spree/confirm-dialog'
+import { PageHeader } from '@/components/spree/page-header'
+import { PreferencesForm } from '@/components/spree/preferences-form'
+import { EditorShell } from '@/components/spree/promotion-editors/editor-shell'
+import '@/components/spree/promotion-editors/register'
+import {
+ actionDraftFromAction,
+ actionDraftFromType,
+ actionDraftToPayload,
+ actionFormSlot,
+ type PromotionActionEditorContext,
+ type PromotionActionFormDraft,
+ type PromotionRuleEditorContext,
+ type PromotionRuleFormDraft,
+ ruleDraftFromRule,
+ ruleDraftFromType,
+ ruleDraftToPayload,
+ ruleFormSlot,
+} from '@/components/spree/promotion-editors/types'
+import { ResourceLayout } from '@/components/spree/resource-layout'
+import { Slot } from '@/components/spree/slot'
+import { ActiveBadge, Badge } from '@/components/ui/badge'
+import { Button } from '@/components/ui/button'
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/data-table'
+import { DatePicker } from '@/components/ui/date-picker'
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Input } from '@/components/ui/input'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet'
+import { Switch } from '@/components/ui/switch'
+import { Textarea } from '@/components/ui/textarea'
+import { useExport } from '@/hooks/use-export'
+import {
+ usePromotionActionTypes,
+ usePromotionCouponCodes,
+ usePromotionRuleTypes,
+} from '@/hooks/use-promotions'
+import { Subject } from '@/lib/permissions'
+
+// =============================================================================
+// Types
+// =============================================================================
+
+type PromotionKind = 'coupon_code' | 'automatic'
+type MatchPolicy = 'all' | 'any'
+
+/**
+ * Form values for the unified promotion form. Both create and edit use the
+ * same shape; the create page sends the full set on POST, the edit page
+ * sends the full set on PATCH.
+ *
+ * Trigger fields (kind/code/multi_codes/number_of_codes/code_prefix) are
+ * editable in create mode and locked in edit mode (the server doesn't
+ * accept changes to them after creation — see `permitted_params` in
+ * Spree::Api::V3::Admin::PromotionsController).
+ */
+export interface PromotionFormValues {
+ name: string
+ description: string
+ kind: PromotionKind
+ code: string
+ multi_codes: boolean
+ number_of_codes: number | undefined
+ code_prefix: string
+ starts_at: string
+ expires_at: string
+ usage_limit: number | undefined
+ match_policy: MatchPolicy
+ rules: PromotionRuleFormDraft[]
+ actions: PromotionActionFormDraft[]
+}
+
+export interface PromotionFormPayload {
+ name: string
+ description: string | null
+ starts_at: string | null
+ expires_at: string | null
+ usage_limit: number | null
+ match_policy: MatchPolicy
+ rules: PromotionRuleDraft[]
+ actions: PromotionActionDraft[]
+ /** Only sent in create mode — server rejects these on update. */
+ kind?: PromotionKind
+ code?: string | null
+ multi_codes?: boolean
+ number_of_codes?: number | null
+ code_prefix?: string | null
+}
+
+interface PromotionFormProps {
+ mode: 'create' | 'edit'
+ /** Existing promotion (edit mode only) — drives the trigger summary card. */
+ promotion?: Promotion
+ /** Existing rules (edit mode only). */
+ initialRules?: PromotionRule[]
+ /** Existing actions (edit mode only). */
+ initialActions?: PromotionAction[]
+ /** Called when the user clicks Save / Create. */
+ onSubmit: (payload: PromotionFormPayload) => Promise<void>
+ /** Optional — when provided in edit mode, shows a Delete button in the header. */
+ onDelete?: () => void
+ /** True while the delete mutation is in-flight (for button disabled state). */
+ deletePending?: boolean
+}
+
+const KIND_OPTIONS = [
+ { value: 'coupon_code', label: 'Coupon code' },
+ { value: 'automatic', label: 'Automatic (no code)' },
+] as const
+
+const MATCH_POLICY_OPTIONS = [
+ { value: 'all', label: 'All rules must match' },
+ { value: 'any', label: 'Any rule may match' },
+] as const
+
+const CREATE_DEFAULTS: PromotionFormValues = {
+ name: '',
+ description: '',
+ kind: 'coupon_code',
+ code: '',
+ multi_codes: false,
+ number_of_codes: undefined,
+ code_prefix: '',
+ starts_at: '',
+ expires_at: '',
+ usage_limit: undefined,
+ match_policy: 'all',
+ rules: [],
+ actions: [],
+}
+
+// =============================================================================
+// Root component
+// =============================================================================
+
+export function PromotionForm({
+ mode,
+ promotion,
+ initialRules,
+ initialActions,
+ onSubmit,
+ onDelete,
+ deletePending = false,
+}: PromotionFormProps) {
+ const form = useForm<PromotionFormValues>({ defaultValues: CREATE_DEFAULTS })
+
+ const rulesArray = useFieldArray({ control: form.control, name: 'rules', keyName: '_key' })
+ const actionsArray = useFieldArray({ control: form.control, name: 'actions', keyName: '_key' })
+
+ // Hydrate edit mode once all three queries have settled. Re-runs after
+ // a successful submit because the queries are invalidated.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: form is stable
+ useEffect(() => {
+ if (mode !== 'edit') return
+ if (!promotion || !initialRules || !initialActions) return
+ form.reset({
+ name: promotion.name,
+ description: promotion.description ?? '',
+ kind: promotion.kind as PromotionKind,
+ code: promotion.code ?? '',
+ multi_codes: promotion.multi_codes,
+ number_of_codes: promotion.number_of_codes ?? undefined,
+ code_prefix: promotion.code_prefix ?? '',
+ starts_at: promotion.starts_at ?? '',
+ expires_at: promotion.expires_at ?? '',
+ usage_limit: promotion.usage_limit ?? undefined,
+ match_policy: promotion.match_policy,
+ rules: initialRules.map(ruleDraftFromRule),
+ actions: initialActions.map(actionDraftFromAction),
+ })
+ }, [mode, promotion, initialRules, initialActions])
+
+ async function handleSubmit(values: PromotionFormValues) {
+ const payload: PromotionFormPayload = {
+ name: values.name,
+ description: values.description?.length ? values.description : null,
+ starts_at: values.starts_at || null,
+ expires_at: values.expires_at || null,
+ usage_limit: values.usage_limit ?? null,
+ match_policy: values.match_policy,
+ rules: values.rules.map(ruleDraftToPayload),
+ actions: values.actions.map(actionDraftToPayload),
+ }
+ if (mode === 'create') {
+ Object.assign(payload, couponFieldsForKind(values))
+ }
+ await onSubmit(payload)
+ }
+
+ const isLoading = mode === 'edit' && (!promotion || !initialRules || !initialActions)
+ if (isLoading) {
+ return (
+ <ResourceLayout
+ header={<PageHeader title="Loading…" backTo="promotions" />}
+ main={<div className="text-sm text-muted-foreground">Loading promotion…</div>}
+ />
+ )
+ }
+
+ return (
+ <form onSubmit={form.handleSubmit(handleSubmit)}>
+ <ResourceLayout
+ header={
+ <PageHeader
+ title={mode === 'create' ? 'New promotion' : (promotion?.name ?? '')}
+ backTo="promotions"
+ actions={
+ <div className="flex gap-2">
+ {mode === 'edit' && onDelete && (
+ <Can I="destroy" a={Subject.Promotion}>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ onClick={onDelete}
+ disabled={deletePending}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ Delete
+ </Button>
+ </Can>
+ )}
+ <Button
+ type="submit"
+ size="sm"
+ disabled={
+ form.formState.isSubmitting || (mode === 'edit' && !form.formState.isDirty)
+ }
+ >
+ {form.formState.isSubmitting
+ ? mode === 'create'
+ ? 'Creating…'
+ : 'Saving…'
+ : mode === 'create'
+ ? 'Create promotion'
+ : 'Save'}
+ </Button>
+ </div>
+ }
+ />
+ }
+ main={
+ <>
+ <RulesCard
+ form={form}
+ rulesArray={rulesArray}
+ matchPolicy={form.watch('match_policy')}
+ />
+ <ActionsCard form={form} actionsArray={actionsArray} />
+ </>
+ }
+ sidebar={
+ <>
+ <BasicsCard form={form} />
+ <TriggerCard mode={mode} form={form} promotion={promotion} />
+ <ScheduleCard form={form} />
+ </>
+ }
+ />
+ </form>
+ )
+}
+
+// =============================================================================
+// Sidebar cards
+// =============================================================================
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function BasicsCard({ form }: { form: any }) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Basics</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="name">Name</FieldLabel>
+ <Input
+ id="name"
+ placeholder="Summer Sale"
+ {...form.register('name', { required: true })}
+ aria-invalid={!!form.formState.errors.name}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="description">Description</FieldLabel>
+ <Textarea
+ id="description"
+ rows={3}
+ placeholder="Internal description (optional)"
+ {...form.register('description')}
+ />
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+ )
+}
+
+function TriggerCard({
+ mode,
+ form,
+ promotion,
+}: {
+ mode: 'create' | 'edit'
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ form: any
+ promotion?: Promotion
+}) {
+ const kind = form.watch('kind')
+ const multiCodes = form.watch('multi_codes')
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Trigger</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {mode === 'edit' && promotion ? (
+ <ReadOnlyTriggerSummary promotion={promotion} />
+ ) : (
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="kind">How is this promotion applied?</FieldLabel>
+ <Controller
+ name="kind"
+ control={form.control}
+ render={({ field }) => (
+ <Select items={KIND_OPTIONS} value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger id="kind">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {KIND_OPTIONS.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </Field>
+
+ {kind === 'coupon_code' && (
+ <>
+ <Field>
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col">
+ <FieldLabel htmlFor="multi_codes" className="cursor-pointer">
+ Generate a batch of unique codes
+ </FieldLabel>
+ <span className="text-xs text-muted-foreground">
+ Useful for one-time-use codes — each customer redeems a different code.
+ </span>
+ </div>
+ <Controller
+ name="multi_codes"
+ control={form.control}
+ render={({ field }) => (
+ <Switch
+ id="multi_codes"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
+ />
+ </div>
+ </Field>
+
+ {!multiCodes ? (
+ <Field>
+ <FieldLabel htmlFor="code">Code</FieldLabel>
+ <Input id="code" placeholder="SUMMER2026" {...form.register('code')} />
+ </Field>
+ ) : (
+ <>
+ <Field>
+ <FieldLabel htmlFor="number_of_codes">Number of codes</FieldLabel>
+ <Input
+ id="number_of_codes"
+ type="number"
+ min={1}
+ placeholder="100"
+ {...form.register('number_of_codes')}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="code_prefix">Code prefix (optional)</FieldLabel>
+ <Input id="code_prefix" placeholder="VIP" {...form.register('code_prefix')} />
+ <span className="text-xs text-muted-foreground">
+ Each generated code will start with this prefix.
+ </span>
+ </Field>
+ </>
+ )}
+ </>
+ )}
+ </FieldGroup>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function ReadOnlyTriggerSummary({ promotion }: { promotion: Promotion }) {
+ const [codesOpen, setCodesOpen] = useState(false)
+
+ return (
+ <div className="space-y-2 text-sm">
+ {promotion.kind === 'automatic' ? (
+ <Badge variant="outline">Automatic</Badge>
+ ) : promotion.multi_codes ? (
+ <div className="space-y-2">
+ <div>
+ Multi-code coupon ({promotion.number_of_codes ?? 0} codes
+ {promotion.code_prefix ? ` with prefix "${promotion.code_prefix}"` : ''})
+ </div>
+ <Button type="button" variant="outline" size="sm" onClick={() => setCodesOpen(true)}>
+ Show codes
+ </Button>
+ {codesOpen && (
+ <CouponCodesSheet
+ promotionId={promotion.id}
+ open
+ onOpenChange={(o) => !o && setCodesOpen(false)}
+ />
+ )}
+ </div>
+ ) : (
+ <div>
+ Single coupon code:{' '}
+ <code className="rounded bg-muted px-1 py-0.5 text-xs">{promotion.code ?? '—'}</code>
+ </div>
+ )}
+ <p className="text-xs text-muted-foreground">
+ Trigger settings can't be changed after creation. Make a new promotion to change them.
+ </p>
+ </div>
+ )
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function ScheduleCard({ form }: { form: any }) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Schedule & limits</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <Field>
+ <FieldLabel>Starts</FieldLabel>
+ <Controller
+ name="starts_at"
+ control={form.control}
+ render={({ field }) => (
+ <DatePicker
+ value={field.value || null}
+ onChange={(v) => field.onChange(v ?? '')}
+ placeholder="No start date"
+ includeTime
+ />
+ )}
+ />
+ </Field>
+ <Field>
+ <FieldLabel>Expires</FieldLabel>
+ <Controller
+ name="expires_at"
+ control={form.control}
+ render={({ field }) => (
+ <DatePicker
+ value={field.value || null}
+ onChange={(v) => field.onChange(v ?? '')}
+ placeholder="No expiry"
+ includeTime
+ />
+ )}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="usage_limit">Usage limit</FieldLabel>
+ <Input
+ id="usage_limit"
+ type="number"
+ min={1}
+ placeholder="Unlimited"
+ {...form.register('usage_limit')}
+ />
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+ )
+}
+
+// =============================================================================
+// Main column — Rules
+// =============================================================================
+
+type RulesArray = ReturnType<typeof useFieldArray<PromotionFormValues, 'rules', '_key'>>
+type ActionsArray = ReturnType<typeof useFieldArray<PromotionFormValues, 'actions', '_key'>>
+
+function RulesCard({
+ form,
+ rulesArray,
+ matchPolicy,
+}: {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ form: any
+ rulesArray: RulesArray
+ matchPolicy: MatchPolicy
+}) {
+ const { data: typesData } = usePromotionRuleTypes()
+ const [pickerOpen, setPickerOpen] = useState(false)
+ const [editingIndex, setEditingIndex] = useState<number | null>(null)
+
+ const types = typesData?.data ?? []
+ // Use `watch` for the row drafts — `rulesArray.fields` is RHF's
+ // snapshot that only updates for registered inputs. Our drafts carry
+ // unregistered nested data (preferences, embedded records, schema),
+ // so reading from fields alone leaves the row summary stale after
+ // editor saves. `watch('rules')` subscribes to the whole list.
+ const watchedRules = (form.watch('rules') ?? []) as PromotionRuleFormDraft[]
+ // Multi-rule logic is only meaningful when there are 2+ rules. For 0 or 1
+ // rules, hide the picker — the description still hints at the policy so
+ // the merchant knows it will matter once they add a second rule.
+ const showMatchPolicy = rulesArray.fields.length >= 2
+
+ return (
+ <Card>
+ <CardHeader>
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <CardTitle>Rules</CardTitle>
+ <p className="text-sm text-muted-foreground">
+ Conditions that decide whether the promotion applies.{' '}
+ {matchPolicy === 'all' ? 'All rules must match.' : 'Any rule may match.'}
+ </p>
+ </div>
+ {showMatchPolicy && (
+ <Controller
+ name="match_policy"
+ control={form.control}
+ render={({ field }) => (
+ <Select
+ items={MATCH_POLICY_OPTIONS}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger id="match_policy" data-size="sm" className="w-auto">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {MATCH_POLICY_OPTIONS.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ )}
+ </div>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-2">
+ {rulesArray.fields.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ No rules. Without rules, the promotion always qualifies (subject to schedule and usage
+ limit).
+ </p>
+ ) : (
+ rulesArray.fields.map((field, index) => (
+ <RuleRow
+ key={field._key}
+ draft={(watchedRules[index] ?? field) as unknown as PromotionRuleFormDraft}
+ onEdit={() => setEditingIndex(index)}
+ onRemove={() => rulesArray.remove(index)}
+ />
+ ))
+ )}
+ <Can I="create" a={Subject.PromotionRule}>
+ <Button type="button" variant="outline" size="sm" onClick={() => setPickerOpen(true)}>
+ <PlusIcon className="size-4" />
+ Add rule
+ </Button>
+ </Can>
+ </div>
+
+ {pickerOpen && (
+ <RulePickerSheet
+ types={types}
+ open
+ onOpenChange={(o) => !o && setPickerOpen(false)}
+ onPicked={(type) => {
+ const draft = ruleDraftFromType(type)
+ rulesArray.append(draft)
+ setPickerOpen(false)
+ setEditingIndex(rulesArray.fields.length)
+ }}
+ />
+ )}
+
+ {editingIndex !== null && rulesArray.fields[editingIndex] && (
+ <RuleEditSheet
+ draft={
+ (watchedRules[editingIndex] ??
+ rulesArray.fields[editingIndex]) as unknown as PromotionRuleFormDraft
+ }
+ open
+ onOpenChange={(o) => !o && setEditingIndex(null)}
+ onSave={(next) => rulesArray.update(editingIndex, next)}
+ />
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function RuleRow({
+ draft,
+ onEdit,
+ onRemove,
+}: {
+ draft: PromotionRuleFormDraft
+ onEdit: () => void
+ onRemove: () => void
+}) {
+ const confirm = useConfirm()
+
+ async function handleRemove(e: React.MouseEvent) {
+ e.stopPropagation()
+ const ok = await confirm({
+ title: 'Remove rule?',
+ message: 'Removed when you save the promotion.',
+ variant: 'destructive',
+ confirmLabel: 'Remove',
+ })
+ if (!ok) return
+ onRemove()
+ }
+
+ // The row is a div, not a button, so the trash <Button> below can be a
+ // valid sibling. The "edit" area is its own <button> spanning the
+ // label/summary slot; trash is the second column.
+ return (
+ <div className="flex w-full items-stretch rounded-md border bg-card hover:bg-muted/50">
+ <button
+ type="button"
+ onClick={onEdit}
+ className="min-w-0 flex-1 px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-l-md"
+ >
+ <div className="text-sm font-medium">{draft.label}</div>
+ <RuleSummary draft={draft} />
+ </button>
+ <Can I="destroy" a={Subject.PromotionRule}>
+ <div className="flex items-center pr-1.5">
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ onClick={handleRemove}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ <TrashIcon className="size-4" />
+ </Button>
+ </div>
+ </Can>
+ </div>
+ )
+}
+
+function RuleSummary({ draft }: { draft: PromotionRuleFormDraft }) {
+ const parts: string[] = []
+ const products = nameList(draft.products)
+ const categories = nameList(draft.categories)
+ const customers = nameList(draft.customers, customerLabel)
+ const groups = nameList(draft.customer_groups)
+ const countries = nameList(draft.countries)
+
+ if (products) parts.push(products)
+ else if (draft.product_ids?.length) parts.push(`${draft.product_ids.length} products`)
+
+ if (categories) parts.push(categories)
+ else if (draft.category_ids?.length) parts.push(`${draft.category_ids.length} categories`)
+
+ if (customers) parts.push(customers)
+ else if (draft.customer_ids?.length) parts.push(`${draft.customer_ids.length} customers`)
+
+ if (groups) parts.push(groups)
+ if (countries) parts.push(countries)
+
+ // 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.
+ const prefSummary = formatPreferencesSummary(draft)
+ if (prefSummary) parts.push(prefSummary)
+
+ if (parts.length === 0) return null
+ return <div className="truncate text-xs text-muted-foreground">{parts.join(' · ')}</div>
+}
+
+const RULE_PREFS_SHOWN_ELSEWHERE = new Set([
+ 'match_policy', // shown in the rules card header
+ 'customer_group_ids', // surfaced via `customer_groups` records
+ 'country_isos', // surfaced via `countries` records
+ 'country_id',
+ 'country_iso',
+])
+
+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]
+ if (value === null || value === undefined || value === '') continue
+ if (Array.isArray(value) && value.length === 0) continue
+ pairs.push(`${humanize(field.key)}: ${formatPreferenceValue(value)}`)
+ }
+ return pairs.length > 0 ? pairs.join(', ') : null
+}
+
+function formatPreferenceValue(value: unknown): string {
+ if (Array.isArray(value)) return value.join(', ')
+ if (typeof value === 'boolean') return value ? 'yes' : 'no'
+ return String(value)
+}
+
+function humanize(key: string): string {
+ const spaced = key.replace(/_/g, ' ').trim()
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
+}
+
+/**
+ * Joins up to 3 names; collapses the tail into "+N more". Returns null
+ * when the list is missing or empty so the caller can fall back to a
+ * count-based summary built from `*_ids`.
+ */
+function nameList<T>(
+ items: T[] | undefined,
+ getLabel: (item: T) => string = defaultLabel,
+): string | null {
+ if (!items?.length) return null
+ const labels = items.map(getLabel).filter(Boolean)
+ if (labels.length === 0) return null
+ if (labels.length <= 3) return labels.join(', ')
+ return `${labels.slice(0, 3).join(', ')} +${labels.length - 3} more`
+}
+
+function defaultLabel(o: unknown): string {
+ if (
+ o &&
+ typeof o === 'object' &&
+ 'name' in o &&
+ typeof (o as { name: unknown }).name === 'string'
+ ) {
+ return (o as { name: string }).name
+ }
+ return ''
+}
+
+function customerLabel(c: unknown): string {
+ if (!c || typeof c !== 'object') return ''
+ const o = c as { first_name?: string; last_name?: string; email?: string }
+ const full = [o.first_name, o.last_name].filter(Boolean).join(' ').trim()
+ return full || o.email || ''
+}
+
+function RulePickerSheet({
+ types,
+ open,
+ onOpenChange,
+ onPicked,
+}: {
+ types: ResourceTypeDefinition[]
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onPicked: (type: ResourceTypeDefinition) => void
+}) {
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>Add rule</SheetTitle>
+ <SheetDescription>Pick a rule type to configure.</SheetDescription>
+ </SheetHeader>
+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4">
+ {types.map((t) => (
+ <button
+ key={t.type}
+ type="button"
+ onClick={() => onPicked(t)}
+ className="flex flex-col items-start rounded-md border p-3 text-left transition-colors hover:bg-muted/50"
+ >
+ <span className="text-sm font-medium">{t.label}</span>
+ {t.description && (
+ <span className="text-xs text-muted-foreground">{t.description}</span>
+ )}
+ </button>
+ ))}
+ </div>
+ <SheetFooter>
+ <Button type="button" variant="outline" size="sm" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function RuleEditSheet({
+ draft,
+ open,
+ onOpenChange,
+ onSave,
+}: {
+ draft: PromotionRuleFormDraft
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onSave: (next: PromotionRuleFormDraft) => void
+}) {
+ const onClose = () => onOpenChange(false)
+ const ctx: PromotionRuleEditorContext = { draft, onSave, onClose }
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{draft.label}</SheetTitle>
+ <SheetDescription>Tune the rule's parameters.</SheetDescription>
+ </SheetHeader>
+ <Slot
+ name={ruleFormSlot(draft.type)}
+ context={ctx}
+ fallback={<DefaultRuleEditor {...ctx} />}
+ />
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function DefaultRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
+ const [values, setValues] = useState<Record<string, unknown>>(draft.preferences ?? {})
+ const hasPreferences = !!draft.preference_schema?.length
+
+ function handleSave() {
+ onSave({ ...draft, preferences: values })
+ onClose()
+ }
+
+ return (
+ <EditorShell
+ onSave={handleSave}
+ onCancel={onClose}
+ pending={false}
+ saveDisabled={!hasPreferences}
+ >
+ {hasPreferences ? (
+ <PreferencesForm schema={draft.preference_schema} values={values} onChange={setValues} />
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ This rule has no configurable options — its presence alone applies the constraint.
+ </p>
+ )}
+ </EditorShell>
+ )
+}
+
+// =============================================================================
+// Main column — Actions
+// =============================================================================
+
+function ActionsCard({
+ form,
+ actionsArray,
+}: {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ form: any
+ actionsArray: ActionsArray
+}) {
+ const { data: typesData } = usePromotionActionTypes()
+ const [pickerOpen, setPickerOpen] = useState(false)
+ const [editingIndex, setEditingIndex] = useState<number | null>(null)
+
+ const types = typesData?.data ?? []
+ // See `RulesCard` — read row drafts from `watch` so unregistered
+ // nested fields (preferences, calculator, line_items) stay fresh
+ // after editor saves.
+ const watchedActions = (form.watch('actions') ?? []) as PromotionActionFormDraft[]
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Actions</CardTitle>
+ <p className="text-sm text-muted-foreground">What happens when the promotion qualifies.</p>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-2">
+ {actionsArray.fields.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ No actions yet. A promotion without actions doesn't do anything when applied.
+ </p>
+ ) : (
+ actionsArray.fields.map((field, index) => (
+ <ActionRow
+ key={field._key}
+ draft={(watchedActions[index] ?? field) as unknown as PromotionActionFormDraft}
+ onEdit={() => setEditingIndex(index)}
+ onRemove={() => actionsArray.remove(index)}
+ />
+ ))
+ )}
+ <Can I="create" a={Subject.PromotionAction}>
+ <Button type="button" variant="outline" size="sm" onClick={() => setPickerOpen(true)}>
+ <PlusIcon className="size-4" />
+ Add action
+ </Button>
+ </Can>
+ </div>
+
+ {pickerOpen && (
+ <ActionPickerSheet
+ types={types}
+ open
+ onOpenChange={(o) => !o && setPickerOpen(false)}
+ onPicked={(type) => {
+ const draft = actionDraftFromType(type)
+ actionsArray.append(draft)
+ setPickerOpen(false)
+ setEditingIndex(actionsArray.fields.length)
+ }}
+ />
+ )}
+
+ {editingIndex !== null && actionsArray.fields[editingIndex] && (
+ <ActionEditSheet
+ draft={
+ (watchedActions[editingIndex] ??
+ actionsArray.fields[editingIndex]) as unknown as PromotionActionFormDraft
+ }
+ open
+ onOpenChange={(o) => !o && setEditingIndex(null)}
+ onSave={(next) => actionsArray.update(editingIndex, next)}
+ />
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function ActionRow({
+ draft,
+ onEdit,
+ onRemove,
+}: {
+ draft: PromotionActionFormDraft
+ onEdit: () => void
+ onRemove: () => void
+}) {
+ const confirm = useConfirm()
+
+ async function handleRemove(e: React.MouseEvent) {
+ e.stopPropagation()
+ const ok = await confirm({
+ title: 'Remove action?',
+ message: 'Removed when you save the promotion.',
+ variant: 'destructive',
+ confirmLabel: 'Remove',
+ })
+ if (!ok) return
+ onRemove()
+ }
+
+ return (
+ <div className="flex w-full items-stretch rounded-md border bg-card hover:bg-muted/50">
+ <button
+ type="button"
+ onClick={onEdit}
+ className="min-w-0 flex-1 px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-l-md"
+ >
+ <div className="text-sm font-medium">{draft.label}</div>
+ <ActionSummary draft={draft} />
+ </button>
+ <Can I="destroy" a={Subject.PromotionAction}>
+ <div className="flex items-center pr-1.5">
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ onClick={handleRemove}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ <TrashIcon className="size-4" />
+ </Button>
+ </div>
+ </Can>
+ </div>
+ )
+}
+
+function ActionSummary({ draft }: { draft: PromotionActionFormDraft }) {
+ const parts: string[] = []
+ const calc = formatCalculatorSummary(draft.calculator)
+ if (calc) parts.push(calc)
+ if (draft.line_items?.length) parts.push(`${draft.line_items.length} variants`)
+ if (parts.length === 0) return null
+ return <div className="truncate text-xs text-muted-foreground">{parts.join(' · ')}</div>
+}
+
+function ActionPickerSheet({
+ types,
+ open,
+ onOpenChange,
+ onPicked,
+}: {
+ types: ResourceTypeDefinition[]
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onPicked: (type: ResourceTypeDefinition) => void
+}) {
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>Add action</SheetTitle>
+ <SheetDescription>Pick what should happen when the promotion qualifies.</SheetDescription>
+ </SheetHeader>
+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4">
+ {types.map((t) => (
+ <button
+ key={t.type}
+ type="button"
+ onClick={() => onPicked(t)}
+ className="flex flex-col items-start rounded-md border p-3 text-left transition-colors hover:bg-muted/50"
+ >
+ <span className="text-sm font-medium">{t.label}</span>
+ {t.description && (
+ <span className="text-xs text-muted-foreground">{t.description}</span>
+ )}
+ </button>
+ ))}
+ </div>
+ <SheetFooter>
+ <Button type="button" variant="outline" size="sm" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function ActionEditSheet({
+ draft,
+ open,
+ onOpenChange,
+ onSave,
+}: {
+ draft: PromotionActionFormDraft
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onSave: (next: PromotionActionFormDraft) => void
+}) {
+ const onClose = () => onOpenChange(false)
+ const ctx: PromotionActionEditorContext = { draft, onSave, onClose }
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{draft.label}</SheetTitle>
+ <SheetDescription>Configure the action's parameters.</SheetDescription>
+ </SheetHeader>
+ <Slot
+ name={actionFormSlot(draft.type)}
+ context={ctx}
+ fallback={<DefaultActionEditor {...ctx} />}
+ />
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function DefaultActionEditor({ draft, onSave, onClose }: PromotionActionEditorContext) {
+ const [values, setValues] = useState<Record<string, unknown>>(draft.preferences ?? {})
+ const hasPreferences = !!draft.preference_schema?.length
+
+ function handleSave() {
+ onSave({ ...draft, preferences: values })
+ onClose()
+ }
+
+ return (
+ <EditorShell
+ onSave={handleSave}
+ onCancel={onClose}
+ pending={false}
+ saveDisabled={!hasPreferences}
+ >
+ {hasPreferences ? (
+ <PreferencesForm schema={draft.preference_schema} values={values} onChange={setValues} />
+ ) : (
+ <p className="text-sm text-muted-foreground">This action has no configurable options.</p>
+ )}
+ </EditorShell>
+ )
+}
+
+// =============================================================================
+// Coupon codes (multi-code promotions only) — opened from the Trigger card
+// =============================================================================
+
+function CouponCodesSheet({
+ promotionId,
+ open,
+ onOpenChange,
+}: {
+ promotionId: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const [page, setPage] = useState(1)
+ const { data: codesData, isFetching } = usePromotionCouponCodes(promotionId, {
+ limit: 50,
+ page,
+ })
+ const codes = codesData?.data ?? []
+ const totalCount = codesData?.meta?.count ?? codes.length
+ const totalPages = codesData?.meta?.pages ?? 1
+
+ const exportMutation = useExport()
+ function handleExport() {
+ exportMutation.mutate({
+ type: 'Spree::Exports::CouponCodes',
+ record_selection: 'filtered',
+ search_params: { promotion_id_eq: promotionId },
+ })
+ }
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent className="sm:max-w-xl">
+ <SheetHeader>
+ <SheetTitle>Coupon codes</SheetTitle>
+ <SheetDescription>
+ {totalCount > 0
+ ? `${totalCount} auto-generated codes. Read-only — regenerate by changing the promotion's number-of-codes setting.`
+ : "Auto-generated codes for this promotion. Read-only — regenerate by changing the promotion's number-of-codes setting."}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
+ {codes.length === 0 ? (
+ <p className="px-4 py-6 text-sm text-muted-foreground">No codes generated yet.</p>
+ ) : (
+ <div className="flex-1 overflow-y-auto">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Code</TableHead>
+ <TableHead className="w-32">Status</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {codes.map((c) => {
+ const used = c.state && c.state !== 'unused'
+ return (
+ <TableRow key={c.id}>
+ <TableCell>
+ <code
+ className={`font-mono text-xs ${used ? 'text-muted-foreground line-through' : ''}`}
+ >
+ {c.code}
+ </code>
+ </TableCell>
+ <TableCell>
+ <ActiveBadge
+ active={!used}
+ activeLabel="Unused"
+ inactiveLabel={c.state ?? 'Used'}
+ />
+ </TableCell>
+ </TableRow>
+ )
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+
+ {totalPages > 1 && (
+ <div className="flex items-center justify-between border-t px-4 py-2">
+ <span className="text-xs text-muted-foreground">
+ Page {page} of {totalPages}
+ </span>
+ <div className="flex gap-1">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
+ disabled={page === 1 || isFetching}
+ >
+ Prev
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
+ disabled={page === totalPages || isFetching}
+ >
+ Next
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <SheetFooter>
+ {totalCount > 0 && (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={handleExport}
+ disabled={exportMutation.isPending}
+ >
+ <DownloadIcon className="size-4" />
+ {exportMutation.isPending ? 'Exporting…' : 'Export CSV'}
+ </Button>
+ )}
+ <Button type="button" size="sm" variant="outline" onClick={() => onOpenChange(false)}>
+ Close
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+/**
+ * Server expects a coherent trigger set: automatic clears all coupon
+ * fields, single-code sets `code`, multi-code sets `number_of_codes` +
+ * optional prefix. Only sent on create — these fields are locked on edit.
+ */
+function couponFieldsForKind(values: PromotionFormValues) {
+ if (values.kind !== 'coupon_code') {
+ return {
+ kind: 'automatic' as const,
+ code: null,
+ multi_codes: false,
+ number_of_codes: null,
+ code_prefix: null,
+ }
+ }
+ if (values.multi_codes) {
+ return {
+ kind: 'coupon_code' as const,
+ code: null,
+ multi_codes: true,
+ number_of_codes: values.number_of_codes ?? null,
+ code_prefix: values.code_prefix || null,
+ }
+ }
+ return {
+ kind: 'coupon_code' as const,
+ code: values.code || null,
+ multi_codes: false,
+ number_of_codes: null,
+ code_prefix: null,
+ }
+}
diff --git a/packages/admin/src/components/spree/promotion-editors/register.ts b/packages/admin/src/components/spree/promotion-editors/register.ts
index 2d57d07b5a..2bac7c00fd 100644
--- a/packages/admin/src/components/spree/promotion-editors/register.ts
+++ b/packages/admin/src/components/spree/promotion-editors/register.ts
@@ -13,8 +13,8 @@ import { actionFormSlot, ruleFormSlot } from './types'
* side effects from the promotion detail route — extensions can call
* `removeSlot(name, 'builtin')` to replace any of these with their own.
*
- * Slot keys follow `promotion.rule_form.<rule.key>` and
- * `promotion.action_form.<action.key>`. Rules/actions whose key isn't
+ * Slot keys follow `promotion.rule_form.<rule.type>` and
+ * `promotion.action_form.<action.type>`. Rules/actions whose type isn't
* registered fall through to the generic `<DefaultRuleEditor>` /
* `<DefaultActionEditor>` (preferences-only) in the parent route.
*/
diff --git a/packages/admin/src/components/spree/promotion-editors/rule-user.tsx b/packages/admin/src/components/spree/promotion-editors/rule-user.tsx
index 3a7438f79c..6bd753f768 100644
--- a/packages/admin/src/components/spree/promotion-editors/rule-user.tsx
+++ b/packages/admin/src/components/spree/promotion-editors/rule-user.tsx
@@ -7,11 +7,11 @@ import { EditorShell } from './editor-shell'
import type { PromotionRuleEditorContext } from './types'
export function UserRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
- const [userIds, setUserIds] = useState<string[]>(draft.user_ids ?? [])
+ const [customerIds, setCustomerIds] = useState<string[]>(draft.customer_ids ?? [])
const [customers, setCustomers] = useState<Customer[]>(draft.customers ?? [])
function handleSave() {
- onSave({ ...draft, user_ids: userIds, customers })
+ onSave({ ...draft, customer_ids: customerIds, customers })
onClose()
}
@@ -21,9 +21,9 @@ export function UserRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorCo
<Field>
<FieldLabel>Customers</FieldLabel>
<ResourceMultiAutocomplete
- queryKey="promotion-rule-users"
- value={userIds}
- onChange={setUserIds}
+ queryKey="promotion-rule-customers"
+ value={customerIds}
+ onChange={setCustomerIds}
onResolvedOptionsChange={setCustomers}
search={(q) => adminClient.customers.list({ search: q, limit: 10 })}
hydrate={(ids) => adminClient.customers.list({ id_in: ids, limit: ids.length })}
diff --git a/packages/admin/src/components/spree/promotion-editors/types.ts b/packages/admin/src/components/spree/promotion-editors/types.ts
index 6e9385daa2..58638417b8 100644
--- a/packages/admin/src/components/spree/promotion-editors/types.ts
+++ b/packages/admin/src/components/spree/promotion-editors/types.ts
@@ -22,8 +22,6 @@ import type {
* created via the picker have no id until the parent form saves.
*/
export interface PromotionRuleFormDraft extends PromotionRuleDraft {
- /** Stable key for slot dispatch + React list keys (`product`, `category`, …). */
- key: string
/** Human-readable header rendered by the edit sheet. */
label: string
preference_schema: PreferenceField[]
@@ -45,7 +43,6 @@ export interface PromotionRuleFormDraft extends PromotionRuleDraft {
/** Mirrors `PromotionRuleFormDraft` for actions. */
export interface PromotionActionFormDraft extends Omit<PromotionActionDraft, 'calculator'> {
- key: string
label: string
preference_schema: PreferenceField[]
_localId: string
@@ -69,7 +66,7 @@ export interface PromotionActionCalculatorFormDraft extends PromotionActionCalcu
* the parent persists everything via a single `PATCH /promotions`
* when the user hits Save on the page header.
*
- * Slot key: `promotion.rule_form.<draft.key>`
+ * Slot key: `promotion.rule_form.<draft.type>`
*/
export interface PromotionRuleEditorContext {
draft: PromotionRuleFormDraft
@@ -89,7 +86,7 @@ export interface PromotionActionEditorContext {
* "United States, Canada" for Country, "3 products · any" for Product.
* Falls back to a generic preferences dump when no slot is registered.
*
- * Slot key: `promotion.rule_summary.<draft.key>`
+ * Slot key: `promotion.rule_summary.<draft.type>`
*/
export interface PromotionRuleSummaryContext {
draft: PromotionRuleFormDraft
@@ -141,12 +138,6 @@ export function ruleDraftFromType(type: {
return {
_localId: newLocalId(),
type: type.type,
- key:
- type.type
- .split('::')
- .pop()
- ?.replace(/([a-z])([A-Z])/g, '$1_$2')
- .toLowerCase() ?? type.type,
label: type.label,
preference_schema: type.preference_schema,
preferences: defaultPreferences(type.preference_schema),
@@ -161,12 +152,6 @@ export function actionDraftFromType(type: {
return {
_localId: newLocalId(),
type: type.type,
- key:
- type.type
- .split('::')
- .pop()
- ?.replace(/([a-z])([A-Z])/g, '$1_$2')
- .toLowerCase() ?? type.type,
label: type.label,
preference_schema: type.preference_schema,
preferences: defaultPreferences(type.preference_schema),
@@ -179,13 +164,12 @@ export function ruleDraftFromRule(rule: PromotionRule): PromotionRuleFormDraft {
_localId: rule.id,
id: rule.id,
type: rule.type,
- key: rule.key,
label: rule.label,
preference_schema: rule.preference_schema,
preferences: rule.preferences,
product_ids: rule.product_ids ?? undefined,
category_ids: rule.category_ids ?? undefined,
- user_ids: rule.user_ids ?? undefined,
+ customer_ids: rule.customer_ids ?? undefined,
products: rule.products,
categories: rule.categories,
customers: rule.customers,
@@ -199,7 +183,6 @@ export function actionDraftFromAction(action: PromotionAction): PromotionActionF
_localId: action.id,
id: action.id,
type: action.type,
- key: action.key,
label: action.label,
preference_schema: action.preference_schema,
preferences: action.preferences,
@@ -232,21 +215,20 @@ function defaultPreferences(schema: PreferenceField[]): Record<string, unknown>
export function ruleDraftToPayload(draft: PromotionRuleFormDraft): PromotionRuleDraft {
const {
_localId: _,
- key: __,
- label: ___,
- preference_schema: ____,
- products: _____,
- categories: ______,
- customers: _______,
- customer_groups: ________,
- countries: _________,
+ label: __,
+ preference_schema: ___,
+ products: ____,
+ categories: _____,
+ customers: ______,
+ customer_groups: _______,
+ countries: ________,
...rest
} = draft
return rest
}
export function actionDraftToPayload(draft: PromotionActionFormDraft): PromotionActionDraft {
- const { _localId: _, key: __, label: ___, preference_schema: ____, calculator, ...rest } = draft
+ const { _localId: _, label: __, preference_schema: ___, calculator, ...rest } = draft
return {
...rest,
calculator: calculator
diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx
index 1d739ce4d1..a4324ee251 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx
@@ -1,144 +1,30 @@
-import type { ResourceTypeDefinition } from '@spree/admin-sdk'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import { DownloadIcon, PlusIcon, TrashIcon } from 'lucide-react'
-import { useEffect, useState } from 'react'
-import { Controller, useFieldArray, useForm } from 'react-hook-form'
-import { formatCalculatorSummary } from '@/components/spree/calculator-summary'
-import { Can } from '@/components/spree/can'
import { useConfirm } from '@/components/spree/confirm-dialog'
-import { PageHeader } from '@/components/spree/page-header'
-import { PreferencesForm } from '@/components/spree/preferences-form'
-import { EditorShell } from '@/components/spree/promotion-editors/editor-shell'
-import '@/components/spree/promotion-editors/register'
-import {
- actionDraftFromAction,
- actionDraftFromType,
- actionDraftToPayload,
- actionFormSlot,
- type PromotionActionEditorContext,
- type PromotionActionFormDraft,
- type PromotionRuleEditorContext,
- type PromotionRuleFormDraft,
- ruleDraftFromRule,
- ruleDraftFromType,
- ruleDraftToPayload,
- ruleFormSlot,
-} from '@/components/spree/promotion-editors/types'
-import { ResourceLayout } from '@/components/spree/resource-layout'
-import { Slot } from '@/components/spree/slot'
-import { Badge } from '@/components/ui/badge'
-import { Button } from '@/components/ui/button'
-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
-import { DatePicker } from '@/components/ui/date-picker'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
-import { Input } from '@/components/ui/input'
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@/components/ui/select'
-import {
- Sheet,
- SheetContent,
- SheetDescription,
- SheetFooter,
- SheetHeader,
- SheetTitle,
-} from '@/components/ui/sheet'
-import { Textarea } from '@/components/ui/textarea'
-import { useExport } from '@/hooks/use-export'
+import { PromotionForm } from '@/components/spree/promotion-editors/promotion-form'
import {
useDeletePromotion,
usePromotion,
usePromotionActions,
- usePromotionActionTypes,
- usePromotionCouponCodes,
usePromotionRules,
- usePromotionRuleTypes,
useUpdatePromotion,
} from '@/hooks/use-promotions'
-import { Subject } from '@/lib/permissions'
export const Route = createFileRoute('/_authenticated/$storeId/promotions/$promotionId')({
component: EditPromotionPage,
})
-interface PromotionFormValues {
- name: string
- description: string
- starts_at: string
- expires_at: string
- usage_limit: number | undefined
- match_policy: 'all' | 'any'
- rules: PromotionRuleFormDraft[]
- actions: PromotionActionFormDraft[]
-}
-
-const MATCH_POLICY_OPTIONS = [
- { value: 'all', label: 'All rules must match' },
- { value: 'any', label: 'Any rule may match' },
-] as const
-
-const DEFAULT_VALUES: PromotionFormValues = {
- name: '',
- description: '',
- starts_at: '',
- expires_at: '',
- usage_limit: undefined,
- match_policy: 'all',
- rules: [],
- actions: [],
-}
-
function EditPromotionPage() {
const { storeId, promotionId } = Route.useParams()
const navigate = useNavigate()
- const { data: promotion, isLoading } = usePromotion(promotionId)
+ const { data: promotion } = usePromotion(promotionId)
// Rules and actions are listed separately because the promotion serializer
- // doesn't embed them; we re-hydrate the form once both lists arrive.
+ // doesn't embed them; the shared form re-hydrates once all three arrive.
const { data: rulesData } = usePromotionRules(promotionId)
const { data: actionsData } = usePromotionActions(promotionId)
const updateMutation = useUpdatePromotion(promotionId)
const deleteMutation = useDeletePromotion()
const confirm = useConfirm()
- const form = useForm<PromotionFormValues>({ defaultValues: DEFAULT_VALUES })
-
- const rulesArray = useFieldArray({ control: form.control, name: 'rules', keyName: '_key' })
- const actionsArray = useFieldArray({ control: form.control, name: 'actions', keyName: '_key' })
-
- // Seed the form once the promotion + its child collections all arrive.
- // Re-runs after a successful submit because the queries are invalidated.
- // biome-ignore lint/correctness/useExhaustiveDependencies: form is stable
- useEffect(() => {
- if (!promotion || !rulesData || !actionsData) return
- form.reset({
- name: promotion.name,
- description: promotion.description ?? '',
- starts_at: promotion.starts_at ?? '',
- expires_at: promotion.expires_at ?? '',
- usage_limit: promotion.usage_limit ?? undefined,
- match_policy: promotion.match_policy,
- rules: rulesData.data.map(ruleDraftFromRule),
- actions: actionsData.data.map(actionDraftFromAction),
- })
- }, [promotion, rulesData, actionsData])
-
- async function onSubmit(values: PromotionFormValues) {
- await updateMutation.mutateAsync({
- name: values.name,
- description: values.description?.length ? values.description : null,
- starts_at: values.starts_at || null,
- expires_at: values.expires_at || null,
- usage_limit: values.usage_limit ?? null,
- match_policy: values.match_policy,
- rules: values.rules.map(ruleDraftToPayload),
- actions: values.actions.map(actionDraftToPayload),
- })
- }
-
async function onDelete() {
const ok = await confirm({
title: 'Delete promotion?',
@@ -151,804 +37,17 @@ function EditPromotionPage() {
navigate({ to: '/$storeId/promotions', params: { storeId } })
}
- if (isLoading || !promotion) {
- return (
- <ResourceLayout
- header={<PageHeader title="Loading…" backTo="promotions" />}
- main={<div className="text-sm text-muted-foreground">Loading promotion…</div>}
- />
- )
- }
-
return (
- <ResourceLayout
- header={
- <PageHeader
- title={promotion.name}
- backTo="promotions"
- actions={
- <div className="flex gap-2">
- <Can I="destroy" a={Subject.Promotion}>
- <Button
- type="button"
- size="sm"
- variant="ghost"
- onClick={onDelete}
- disabled={deleteMutation.isPending}
- className="text-destructive hover:bg-destructive/10 hover:text-destructive"
- >
- Delete
- </Button>
- </Can>
- <Button
- type="button"
- size="sm"
- onClick={form.handleSubmit(onSubmit)}
- disabled={!form.formState.isDirty || form.formState.isSubmitting}
- >
- {form.formState.isSubmitting ? 'Saving…' : 'Save'}
- </Button>
- </div>
- }
- />
- }
- main={
- <>
- <PromotionBasicsCard form={form} promotion={promotion} />
- <PromotionRulesCard rulesArray={rulesArray} matchPolicy={form.watch('match_policy')} />
- <PromotionActionsCard actionsArray={actionsArray} />
- {promotion.multi_codes && <PromotionCouponCodesCard promotionId={promotionId} />}
- </>
- }
+ <PromotionForm
+ mode="edit"
+ promotion={promotion}
+ initialRules={rulesData?.data}
+ initialActions={actionsData?.data}
+ onSubmit={async (payload) => {
+ await updateMutation.mutateAsync(payload)
+ }}
+ onDelete={onDelete}
+ deletePending={deleteMutation.isPending}
/>
)
}
-
-// ============================================================================
-// Basics
-// ============================================================================
-
-interface PromotionBasicsCardProps {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- form: any
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- promotion: any
-}
-
-function PromotionBasicsCard({ form, promotion }: PromotionBasicsCardProps) {
- return (
- <Card>
- <CardHeader>
- <CardTitle>Basics</CardTitle>
- </CardHeader>
- <CardContent>
- <FieldGroup>
- <Field>
- <FieldLabel htmlFor="name">Name</FieldLabel>
- <Input id="name" {...form.register('name')} />
- </Field>
- <Field>
- <FieldLabel htmlFor="description">Description</FieldLabel>
- <Textarea id="description" rows={2} {...form.register('description')} />
- </Field>
-
- <div className="rounded-md border bg-muted/30 px-3 py-2 text-sm">
- <span className="font-medium">Trigger: </span>
- {promotion.kind === 'automatic' ? (
- <Badge variant="outline">Automatic</Badge>
- ) : promotion.multi_codes ? (
- <span>
- Multi-code coupon ({promotion.number_of_codes ?? 0} codes
- {promotion.code_prefix ? ` with prefix "${promotion.code_prefix}"` : ''})
- </span>
- ) : (
- <span>
- Single coupon code:{' '}
- <code className="rounded bg-muted px-1 py-0.5 text-xs">
- {promotion.code ?? '—'}
- </code>
- </span>
- )}
- <p className="mt-1 text-xs text-muted-foreground">
- Trigger settings can't be changed after creation. Make a new promotion to change them.
- </p>
- </div>
-
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
- <Field>
- <FieldLabel>Starts</FieldLabel>
- <Controller
- name="starts_at"
- control={form.control}
- render={({ field }) => (
- <DatePicker
- value={field.value || null}
- onChange={(v) => field.onChange(v ?? '')}
- placeholder="No start date"
- includeTime
- />
- )}
- />
- </Field>
- <Field>
- <FieldLabel>Expires</FieldLabel>
- <Controller
- name="expires_at"
- control={form.control}
- render={({ field }) => (
- <DatePicker
- value={field.value || null}
- onChange={(v) => field.onChange(v ?? '')}
- placeholder="No expiry"
- includeTime
- />
- )}
- />
- </Field>
- </div>
-
- <Field>
- <FieldLabel htmlFor="usage_limit">Usage limit</FieldLabel>
- <Input
- id="usage_limit"
- type="number"
- min={1}
- placeholder="Unlimited"
- {...form.register('usage_limit')}
- />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="match_policy">When promotion has multiple rules</FieldLabel>
- <Controller
- name="match_policy"
- control={form.control}
- render={({ field }) => (
- <Select
- items={MATCH_POLICY_OPTIONS}
- value={field.value}
- onValueChange={field.onChange}
- >
- <SelectTrigger id="match_policy">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {MATCH_POLICY_OPTIONS.map((o) => (
- <SelectItem key={o.value} value={o.value}>
- {o.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- </Field>
- </FieldGroup>
- </CardContent>
- </Card>
- )
-}
-
-// ============================================================================
-// Rules
-// ============================================================================
-
-type RulesArray = ReturnType<typeof useFieldArray<PromotionFormValues, 'rules', '_key'>>
-type ActionsArray = ReturnType<typeof useFieldArray<PromotionFormValues, 'actions', '_key'>>
-
-function PromotionRulesCard({
- rulesArray,
- matchPolicy,
-}: {
- rulesArray: RulesArray
- matchPolicy: 'all' | 'any'
-}) {
- const { data: typesData } = usePromotionRuleTypes()
- const [pickerOpen, setPickerOpen] = useState(false)
- const [editingIndex, setEditingIndex] = useState<number | null>(null)
-
- const types = typesData?.data ?? []
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>Rules</CardTitle>
- <p className="text-sm text-muted-foreground">
- Conditions that decide whether the promotion applies.{' '}
- {matchPolicy === 'all' ? 'All rules must match.' : 'Any rule may match.'}
- </p>
- </CardHeader>
- <CardContent>
- <div className="space-y-2">
- {rulesArray.fields.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- No rules. Without rules, the promotion always qualifies (subject to schedule and usage
- limit).
- </p>
- ) : (
- rulesArray.fields.map((field, index) => (
- <RuleRow
- key={field._key}
- draft={field as unknown as PromotionRuleFormDraft}
- onEdit={() => setEditingIndex(index)}
- onRemove={() => rulesArray.remove(index)}
- />
- ))
- )}
- <Can I="create" a={Subject.PromotionRule}>
- <Button type="button" variant="outline" size="sm" onClick={() => setPickerOpen(true)}>
- <PlusIcon className="size-4" />
- Add rule
- </Button>
- </Can>
- </div>
-
- {pickerOpen && (
- <RulePickerSheet
- types={types}
- open
- onOpenChange={(o) => !o && setPickerOpen(false)}
- onPicked={(type) => {
- const draft = ruleDraftFromType(type)
- rulesArray.append(draft)
- setPickerOpen(false)
- setEditingIndex(rulesArray.fields.length) // newly-appended row index
- }}
- />
- )}
-
- {editingIndex !== null && rulesArray.fields[editingIndex] && (
- <RuleEditSheet
- draft={rulesArray.fields[editingIndex] as unknown as PromotionRuleFormDraft}
- open
- onOpenChange={(o) => !o && setEditingIndex(null)}
- onSave={(next) => rulesArray.update(editingIndex, next)}
- />
- )}
- </CardContent>
- </Card>
- )
-}
-
-function RuleRow({
- draft,
- onEdit,
- onRemove,
-}: {
- draft: PromotionRuleFormDraft
- onEdit: () => void
- onRemove: () => void
-}) {
- const confirm = useConfirm()
-
- async function handleRemove(e: React.MouseEvent) {
- e.stopPropagation()
- const ok = await confirm({
- title: 'Remove rule?',
- message: 'Removed when you save the promotion.',
- variant: 'destructive',
- confirmLabel: 'Remove',
- })
- if (!ok) return
- onRemove()
- }
-
- return (
- <button
- type="button"
- onClick={onEdit}
- className="flex w-full items-center justify-between rounded-md border bg-card px-3 py-2 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- <div className="min-w-0">
- <div className="text-sm font-medium">{draft.label}</div>
- <RuleSummary draft={draft} />
- </div>
- <Can I="destroy" a={Subject.PromotionRule}>
- <Button
- type="button"
- size="icon-xs"
- variant="ghost"
- onClick={handleRemove}
- className="text-destructive hover:bg-destructive/10 hover:text-destructive"
- >
- <TrashIcon className="size-4" />
- </Button>
- </Can>
- </button>
- )
-}
-
-function RuleSummary({ draft }: { draft: PromotionRuleFormDraft }) {
- const parts: string[] = []
- const products = nameList(draft.products)
- const categories = nameList(draft.categories)
- const customers = nameList(draft.customers, customerLabel)
- const groups = nameList(draft.customer_groups)
- const countries = nameList(draft.countries)
-
- if (products) parts.push(products)
- else if (draft.product_ids?.length) parts.push(`${draft.product_ids.length} products`)
-
- if (categories) parts.push(categories)
- else if (draft.category_ids?.length) parts.push(`${draft.category_ids.length} categories`)
-
- if (customers) parts.push(customers)
- else if (draft.user_ids?.length) parts.push(`${draft.user_ids.length} customers`)
-
- if (groups) parts.push(groups)
- if (countries) parts.push(countries)
-
- const policy = draft.preferences?.match_policy
- if (policy) parts.push(String(policy))
-
- if (parts.length === 0) return null
- return <div className="truncate text-xs text-muted-foreground">{parts.join(' · ')}</div>
-}
-
-/**
- * Joins up to 3 names; collapses the tail into "+N more". Returns null
- * when the list is missing or empty so the caller can fall back to a
- * count-based summary built from `*_ids`.
- */
-function nameList<T>(
- items: T[] | undefined,
- getLabel: (item: T) => string = defaultLabel,
-): string | null {
- if (!items?.length) return null
- const labels = items.map(getLabel).filter(Boolean)
- if (labels.length === 0) return null
- if (labels.length <= 3) return labels.join(', ')
- return `${labels.slice(0, 3).join(', ')} +${labels.length - 3} more`
-}
-
-function defaultLabel(o: unknown): string {
- if (
- o &&
- typeof o === 'object' &&
- 'name' in o &&
- typeof (o as { name: unknown }).name === 'string'
- ) {
- return (o as { name: string }).name
- }
- return ''
-}
-
-function customerLabel(c: unknown): string {
- if (!c || typeof c !== 'object') return ''
- const o = c as { first_name?: string; last_name?: string; email?: string }
- const full = [o.first_name, o.last_name].filter(Boolean).join(' ').trim()
- return full || o.email || ''
-}
-
-function RulePickerSheet({
- types,
- open,
- onOpenChange,
- onPicked,
-}: {
- types: ResourceTypeDefinition[]
- open: boolean
- onOpenChange: (open: boolean) => void
- onPicked: (type: ResourceTypeDefinition) => void
-}) {
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>Add rule</SheetTitle>
- <SheetDescription>Pick a rule type to configure.</SheetDescription>
- </SheetHeader>
- <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4">
- {types.map((t) => (
- <button
- key={t.type}
- type="button"
- onClick={() => onPicked(t)}
- className="flex flex-col items-start rounded-md border p-3 text-left transition-colors hover:bg-muted/50"
- >
- <span className="text-sm font-medium">{t.label}</span>
- {t.description && (
- <span className="text-xs text-muted-foreground">{t.description}</span>
- )}
- </button>
- ))}
- </div>
- <SheetFooter>
- <Button type="button" variant="outline" size="sm" onClick={() => onOpenChange(false)}>
- Cancel
- </Button>
- </SheetFooter>
- </SheetContent>
- </Sheet>
- )
-}
-
-function RuleEditSheet({
- draft,
- open,
- onOpenChange,
- onSave,
-}: {
- draft: PromotionRuleFormDraft
- open: boolean
- onOpenChange: (open: boolean) => void
- onSave: (next: PromotionRuleFormDraft) => void
-}) {
- const onClose = () => onOpenChange(false)
- const ctx: PromotionRuleEditorContext = { draft, onSave, onClose }
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{draft.label}</SheetTitle>
- <SheetDescription>Tune the rule's parameters.</SheetDescription>
- </SheetHeader>
- <Slot
- name={ruleFormSlot(draft.key)}
- context={ctx}
- fallback={<DefaultRuleEditor {...ctx} />}
- />
- </SheetContent>
- </Sheet>
- )
-}
-
-/**
- * Default rule editor — renders a generic PreferencesForm for rules
- * whose configuration is exhausted by their preference schema
- * (Currency, FirstOrder, ItemTotal, etc.).
- */
-function DefaultRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
- const [values, setValues] = useState<Record<string, unknown>>(draft.preferences ?? {})
-
- const hasPreferences = !!draft.preference_schema?.length
-
- function handleSave() {
- onSave({ ...draft, preferences: values })
- onClose()
- }
-
- return (
- <EditorShell
- onSave={handleSave}
- onCancel={onClose}
- pending={false}
- saveDisabled={!hasPreferences}
- >
- {hasPreferences ? (
- <PreferencesForm schema={draft.preference_schema} values={values} onChange={setValues} />
- ) : (
- <p className="text-sm text-muted-foreground">
- This rule has no configurable options — its presence alone applies the constraint.
- </p>
- )}
- </EditorShell>
- )
-}
-
-// ============================================================================
-// Actions
-// ============================================================================
-
-function PromotionActionsCard({ actionsArray }: { actionsArray: ActionsArray }) {
- const { data: typesData } = usePromotionActionTypes()
- const [pickerOpen, setPickerOpen] = useState(false)
- const [editingIndex, setEditingIndex] = useState<number | null>(null)
-
- const types = typesData?.data ?? []
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>Actions</CardTitle>
- <p className="text-sm text-muted-foreground">What happens when the promotion qualifies.</p>
- </CardHeader>
- <CardContent>
- <div className="space-y-2">
- {actionsArray.fields.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- No actions yet. A promotion without actions doesn't do anything when applied.
- </p>
- ) : (
- actionsArray.fields.map((field, index) => (
- <ActionRow
- key={field._key}
- draft={field as unknown as PromotionActionFormDraft}
- onEdit={() => setEditingIndex(index)}
- onRemove={() => actionsArray.remove(index)}
- />
- ))
- )}
- <Can I="create" a={Subject.PromotionAction}>
- <Button type="button" variant="outline" size="sm" onClick={() => setPickerOpen(true)}>
- <PlusIcon className="size-4" />
- Add action
- </Button>
- </Can>
- </div>
-
- {pickerOpen && (
- <ActionPickerSheet
- types={types}
- open
- onOpenChange={(o) => !o && setPickerOpen(false)}
- onPicked={(type) => {
- const draft = actionDraftFromType(type)
- actionsArray.append(draft)
- setPickerOpen(false)
- setEditingIndex(actionsArray.fields.length)
- }}
- />
- )}
-
- {editingIndex !== null && actionsArray.fields[editingIndex] && (
- <ActionEditSheet
- draft={actionsArray.fields[editingIndex] as unknown as PromotionActionFormDraft}
- open
- onOpenChange={(o) => !o && setEditingIndex(null)}
- onSave={(next) => actionsArray.update(editingIndex, next)}
- />
- )}
- </CardContent>
- </Card>
- )
-}
-
-function ActionRow({
- draft,
- onEdit,
- onRemove,
-}: {
- draft: PromotionActionFormDraft
- onEdit: () => void
- onRemove: () => void
-}) {
- const confirm = useConfirm()
-
- async function handleRemove(e: React.MouseEvent) {
- e.stopPropagation()
- const ok = await confirm({
- title: 'Remove action?',
- message: 'Removed when you save the promotion.',
- variant: 'destructive',
- confirmLabel: 'Remove',
- })
- if (!ok) return
- onRemove()
- }
-
- return (
- <button
- type="button"
- onClick={onEdit}
- className="flex w-full items-center justify-between rounded-md border bg-card px-3 py-2 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- <div className="min-w-0">
- <div className="text-sm font-medium">{draft.label}</div>
- <ActionSummary draft={draft} />
- </div>
- <Can I="destroy" a={Subject.PromotionAction}>
- <Button
- type="button"
- size="icon-xs"
- variant="ghost"
- onClick={handleRemove}
- className="text-destructive hover:bg-destructive/10 hover:text-destructive"
- >
- <TrashIcon className="size-4" />
- </Button>
- </Can>
- </button>
- )
-}
-
-function ActionSummary({ draft }: { draft: PromotionActionFormDraft }) {
- const parts: string[] = []
- const calc = formatCalculatorSummary(draft.calculator)
- if (calc) parts.push(calc)
- if (draft.line_items?.length) parts.push(`${draft.line_items.length} variants`)
- if (parts.length === 0) return null
- return <div className="truncate text-xs text-muted-foreground">{parts.join(' · ')}</div>
-}
-
-function ActionPickerSheet({
- types,
- open,
- onOpenChange,
- onPicked,
-}: {
- types: ResourceTypeDefinition[]
- open: boolean
- onOpenChange: (open: boolean) => void
- onPicked: (type: ResourceTypeDefinition) => void
-}) {
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>Add action</SheetTitle>
- <SheetDescription>Pick what should happen when the promotion qualifies.</SheetDescription>
- </SheetHeader>
- <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4">
- {types.map((t) => (
- <button
- key={t.type}
- type="button"
- onClick={() => onPicked(t)}
- className="flex flex-col items-start rounded-md border p-3 text-left transition-colors hover:bg-muted/50"
- >
- <span className="text-sm font-medium">{t.label}</span>
- {t.description && (
- <span className="text-xs text-muted-foreground">{t.description}</span>
- )}
- </button>
- ))}
- </div>
- <SheetFooter>
- <Button type="button" variant="outline" size="sm" onClick={() => onOpenChange(false)}>
- Cancel
- </Button>
- </SheetFooter>
- </SheetContent>
- </Sheet>
- )
-}
-
-function ActionEditSheet({
- draft,
- open,
- onOpenChange,
- onSave,
-}: {
- draft: PromotionActionFormDraft
- open: boolean
- onOpenChange: (open: boolean) => void
- onSave: (next: PromotionActionFormDraft) => void
-}) {
- const onClose = () => onOpenChange(false)
- const ctx: PromotionActionEditorContext = { draft, onSave, onClose }
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{draft.label}</SheetTitle>
- <SheetDescription>Configure the action's parameters.</SheetDescription>
- </SheetHeader>
- <Slot
- name={actionFormSlot(draft.key)}
- context={ctx}
- fallback={<DefaultActionEditor {...ctx} />}
- />
- </SheetContent>
- </Sheet>
- )
-}
-
-function DefaultActionEditor({ draft, onSave, onClose }: PromotionActionEditorContext) {
- const [values, setValues] = useState<Record<string, unknown>>(draft.preferences ?? {})
-
- const hasPreferences = !!draft.preference_schema?.length
-
- function handleSave() {
- onSave({ ...draft, preferences: values })
- onClose()
- }
-
- return (
- <EditorShell
- onSave={handleSave}
- onCancel={onClose}
- pending={false}
- saveDisabled={!hasPreferences}
- >
- {hasPreferences ? (
- <PreferencesForm schema={draft.preference_schema} values={values} onChange={setValues} />
- ) : (
- <p className="text-sm text-muted-foreground">This action has no configurable options.</p>
- )}
- </EditorShell>
- )
-}
-
-// ============================================================================
-// Coupon codes (multi-codes only)
-// ============================================================================
-
-function PromotionCouponCodesCard({ promotionId }: { promotionId: string }) {
- const [page, setPage] = useState(1)
- const { data: codesData, isFetching } = usePromotionCouponCodes(promotionId, {
- limit: 50,
- page,
- })
- const codes = codesData?.data ?? []
- const totalCount = codesData?.meta?.count ?? codes.length
- const totalPages = codesData?.meta?.pages ?? 1
-
- const exportMutation = useExport()
- function handleExport() {
- exportMutation.mutate({
- type: 'Spree::Exports::CouponCodes',
- record_selection: 'filtered',
- search_params: { promotion_id_eq: promotionId },
- })
- }
-
- return (
- <Card>
- <CardHeader>
- <div className="flex items-start justify-between gap-3">
- <div>
- <CardTitle>Coupon codes</CardTitle>
- <p className="text-sm text-muted-foreground">
- {totalCount > 0
- ? `${totalCount} auto-generated codes. Read-only; regenerate by changing the promotion's number-of-codes setting.`
- : "Auto-generated codes for this promotion. Codes are read-only; regenerate by changing the promotion's number-of-codes setting."}
- </p>
- </div>
- {totalCount > 0 && (
- <Button
- type="button"
- size="sm"
- variant="outline"
- onClick={handleExport}
- disabled={exportMutation.isPending}
- >
- <DownloadIcon className="size-4" />
- {exportMutation.isPending ? 'Exporting…' : 'Export CSV'}
- </Button>
- )}
- </div>
- </CardHeader>
- <CardContent>
- {codes.length === 0 ? (
- <p className="text-sm text-muted-foreground">No codes generated yet.</p>
- ) : (
- <>
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
- {codes.map((c) => (
- <code
- key={c.id}
- className={`rounded border px-2 py-1 font-mono text-xs ${
- c.state && c.state !== 'unused' ? 'text-muted-foreground line-through' : ''
- }`}
- title={c.state ?? undefined}
- >
- {c.code}
- </code>
- ))}
- </div>
- {totalPages > 1 && (
- <div className="mt-3 flex items-center justify-between">
- <span className="text-xs text-muted-foreground">
- Page {page} of {totalPages}
- </span>
- <div className="flex gap-1">
- <Button
- type="button"
- size="sm"
- variant="outline"
- onClick={() => setPage((p) => Math.max(1, p - 1))}
- disabled={page === 1 || isFetching}
- >
- Prev
- </Button>
- <Button
- type="button"
- size="sm"
- variant="outline"
- onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
- disabled={page === totalPages || isFetching}
- >
- Next
- </Button>
- </div>
- </div>
- )}
- </>
- )}
- </CardContent>
- </Card>
- )
-}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx
index 5d9daae392..6074ad85bd 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx
@@ -1,396 +1,26 @@
-import { zodResolver } from '@hookform/resolvers/zod'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import { Controller, useForm } from 'react-hook-form'
-import { z } from 'zod/v4'
-import { PageHeader } from '@/components/spree/page-header'
-import { ResourceLayout } from '@/components/spree/resource-layout'
-import { Button } from '@/components/ui/button'
-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
-import { DatePicker } from '@/components/ui/date-picker'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
-import { Input } from '@/components/ui/input'
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@/components/ui/select'
-import { Switch } from '@/components/ui/switch'
-import { Textarea } from '@/components/ui/textarea'
+import { PromotionForm } from '@/components/spree/promotion-editors/promotion-form'
import { useCreatePromotion } from '@/hooks/use-promotions'
export const Route = createFileRoute('/_authenticated/$storeId/promotions/new')({
component: NewPromotionPage,
})
-const formSchema = z
- .object({
- name: z.string().min(1, 'Name is required'),
- description: z.string().optional(),
- kind: z.enum(['coupon_code', 'automatic']),
- code: z.string().optional(),
- multi_codes: z.boolean(),
- number_of_codes: z.coerce.number().int().positive().optional(),
- code_prefix: z.string().optional(),
- starts_at: z.string().optional(),
- expires_at: z.string().optional(),
- usage_limit: z.coerce.number().int().positive().optional(),
- match_policy: z.enum(['all', 'any']),
- })
- .superRefine((v, ctx) => {
- if (v.kind === 'coupon_code' && !v.multi_codes && !v.code?.trim()) {
- ctx.addIssue({
- code: 'custom',
- path: ['code'],
- message: 'Coupon promotions need a code (or enable multi-codes).',
- })
- }
- if (v.kind === 'coupon_code' && v.multi_codes && !v.number_of_codes) {
- ctx.addIssue({
- code: 'custom',
- path: ['number_of_codes'],
- message: 'How many codes should be generated?',
- })
- }
- })
-
-type FormValues = z.infer<typeof formSchema>
-
-const KIND_OPTIONS = [
- { value: 'coupon_code', label: 'Coupon code' },
- { value: 'automatic', label: 'Automatic (no code)' },
-] as const
-
-const MATCH_POLICY_OPTIONS = [
- { value: 'all', label: 'All rules must match' },
- { value: 'any', label: 'Any rule may match' },
-] as const
-
-// Server expects a coherent set: automatic clears all coupon fields,
-// single-code sets `code`, multi-code sets `number_of_codes` + optional
-// prefix. Centralized so the create body stays flat.
-function couponFieldsForKind(values: FormValues) {
- if (values.kind !== 'coupon_code') {
- return {
- kind: 'automatic' as const,
- code: null,
- multi_codes: false,
- number_of_codes: null,
- code_prefix: null,
- }
- }
- if (values.multi_codes) {
- return {
- kind: 'coupon_code' as const,
- code: null,
- multi_codes: true,
- number_of_codes: values.number_of_codes ?? null,
- code_prefix: values.code_prefix || null,
- }
- }
- return {
- kind: 'coupon_code' as const,
- code: values.code || null,
- multi_codes: false,
- number_of_codes: null,
- code_prefix: null,
- }
-}
-
-const DEFAULTS: FormValues = {
- name: '',
- description: '',
- kind: 'coupon_code',
- code: '',
- multi_codes: false,
- number_of_codes: undefined,
- code_prefix: '',
- starts_at: '',
- expires_at: '',
- usage_limit: undefined,
- match_policy: 'all',
-}
-
function NewPromotionPage() {
const navigate = useNavigate()
const { storeId } = Route.useParams()
const createMutation = useCreatePromotion()
- const form = useForm<FormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(formSchema) as any,
- defaultValues: DEFAULTS,
- })
-
- const kind = form.watch('kind')
- const multiCodes = form.watch('multi_codes')
-
- async function onSubmit(values: FormValues) {
- const promotion = await createMutation.mutateAsync({
- name: values.name,
- description: values.description?.length ? values.description : null,
- starts_at: values.starts_at || null,
- expires_at: values.expires_at || null,
- usage_limit: values.usage_limit ?? null,
- match_policy: values.match_policy,
- ...couponFieldsForKind(values),
- })
- navigate({
- to: '/$storeId/promotions/$promotionId',
- params: { storeId, promotionId: promotion.id },
- })
- }
-
return (
- <form onSubmit={form.handleSubmit(onSubmit)}>
- <ResourceLayout
- header={
- <PageHeader
- title="New promotion"
- backTo="promotions"
- actions={
- <Button type="submit" size="sm" disabled={form.formState.isSubmitting}>
- {form.formState.isSubmitting ? 'Creating…' : 'Create promotion'}
- </Button>
- }
- />
- }
- main={
- <>
- <Card>
- <CardHeader>
- <CardTitle>Basics</CardTitle>
- </CardHeader>
- <CardContent>
- <FieldGroup>
- <Field>
- <FieldLabel htmlFor="name">Name</FieldLabel>
- <Input
- id="name"
- placeholder="Summer Sale"
- {...form.register('name')}
- aria-invalid={!!form.formState.errors.name}
- />
- {form.formState.errors.name && (
- <p className="text-sm text-destructive">
- {form.formState.errors.name.message}
- </p>
- )}
- </Field>
-
- <Field>
- <FieldLabel htmlFor="description">Description</FieldLabel>
- <Textarea
- id="description"
- rows={2}
- placeholder="Internal description (optional)"
- {...form.register('description')}
- />
- </Field>
- </FieldGroup>
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader>
- <CardTitle>Trigger</CardTitle>
- </CardHeader>
- <CardContent>
- <FieldGroup>
- <Field>
- <FieldLabel htmlFor="kind">How is this promotion applied?</FieldLabel>
- <Controller
- name="kind"
- control={form.control}
- render={({ field }) => (
- <Select
- items={KIND_OPTIONS}
- value={field.value}
- onValueChange={field.onChange}
- >
- <SelectTrigger id="kind">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {KIND_OPTIONS.map((o) => (
- <SelectItem key={o.value} value={o.value}>
- {o.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- </Field>
-
- {kind === 'coupon_code' && (
- <>
- <Field>
- <div className="flex items-start justify-between gap-4">
- <div className="flex flex-col">
- <FieldLabel htmlFor="multi_codes" className="cursor-pointer">
- Generate a batch of unique codes
- </FieldLabel>
- <span className="text-xs text-muted-foreground">
- Useful for one-time-use codes — each customer redeems a different
- code.
- </span>
- </div>
- <Controller
- name="multi_codes"
- control={form.control}
- render={({ field }) => (
- <Switch
- id="multi_codes"
- checked={!!field.value}
- onCheckedChange={field.onChange}
- />
- )}
- />
- </div>
- </Field>
-
- {!multiCodes ? (
- <Field>
- <FieldLabel htmlFor="code">Code</FieldLabel>
- <Input
- id="code"
- placeholder="SUMMER2026"
- {...form.register('code')}
- aria-invalid={!!form.formState.errors.code}
- />
- {form.formState.errors.code && (
- <p className="text-sm text-destructive">
- {form.formState.errors.code.message}
- </p>
- )}
- </Field>
- ) : (
- <>
- <Field>
- <FieldLabel htmlFor="number_of_codes">Number of codes</FieldLabel>
- <Input
- id="number_of_codes"
- type="number"
- min={1}
- placeholder="100"
- {...form.register('number_of_codes')}
- aria-invalid={!!form.formState.errors.number_of_codes}
- />
- {form.formState.errors.number_of_codes && (
- <p className="text-sm text-destructive">
- {form.formState.errors.number_of_codes.message}
- </p>
- )}
- </Field>
-
- <Field>
- <FieldLabel htmlFor="code_prefix">Code prefix (optional)</FieldLabel>
- <Input
- id="code_prefix"
- placeholder="VIP"
- {...form.register('code_prefix')}
- />
- <span className="text-xs text-muted-foreground">
- Each generated code will start with this prefix.
- </span>
- </Field>
- </>
- )}
- </>
- )}
- </FieldGroup>
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader>
- <CardTitle>Schedule & limits</CardTitle>
- </CardHeader>
- <CardContent>
- <FieldGroup>
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
- <Field>
- <FieldLabel>Starts</FieldLabel>
- <Controller
- name="starts_at"
- control={form.control}
- render={({ field }) => (
- <DatePicker
- value={field.value || null}
- onChange={(v) => field.onChange(v ?? '')}
- placeholder="No start date"
- includeTime
- />
- )}
- />
- </Field>
- <Field>
- <FieldLabel>Expires</FieldLabel>
- <Controller
- name="expires_at"
- control={form.control}
- render={({ field }) => (
- <DatePicker
- value={field.value || null}
- onChange={(v) => field.onChange(v ?? '')}
- placeholder="No expiry"
- includeTime
- />
- )}
- />
- </Field>
- </div>
-
- <Field>
- <FieldLabel htmlFor="usage_limit">Usage limit</FieldLabel>
- <Input
- id="usage_limit"
- type="number"
- min={1}
- placeholder="Unlimited"
- {...form.register('usage_limit')}
- />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="match_policy">
- When promotion has multiple rules
- </FieldLabel>
- <Controller
- name="match_policy"
- control={form.control}
- render={({ field }) => (
- <Select
- items={MATCH_POLICY_OPTIONS}
- value={field.value}
- onValueChange={field.onChange}
- >
- <SelectTrigger id="match_policy">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {MATCH_POLICY_OPTIONS.map((o) => (
- <SelectItem key={o.value} value={o.value}>
- {o.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- </Field>
- </FieldGroup>
- </CardContent>
- </Card>
-
- <p className="text-sm text-muted-foreground">
- Configure rules and actions after the promotion is created.
- </p>
- </>
- }
- />
- </form>
+ <PromotionForm
+ mode="create"
+ onSubmit={async (payload) => {
+ const promotion = await createMutation.mutateAsync(payload)
+ navigate({
+ to: '/$storeId/promotions/$promotionId',
+ params: { storeId, promotionId: promotion.id },
+ })
+ }}
+ />
)
}
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 6c7efd84b7..f73a288ee3 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
@@ -97,7 +97,7 @@ module Spree
def resolve_subclass(type_name)
return nil if type_name.blank?
- self.class.subclass_registry.call.find { |klass| klass.to_s == type_name }
+ self.class.subclass_registry.call.find { |klass| klass.api_type == type_name.to_s }
end
def render_unknown_type
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 bc587a1bc2..ae97c499b8 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
@@ -26,12 +26,15 @@ module Spree
# — the has_many-through association can cache stale results when
# `current_store` was loaded earlier in the request (e.g. by the
# auth layer).
- installed_types = Spree::PaymentMethod
- .joins(:store_payment_methods)
- .where(spree_payment_methods_stores: { store_id: current_store.id })
- .pluck(:type)
+ installed_class_names = Spree::PaymentMethod
+ .joins(:store_payment_methods)
+ .where(spree_payment_methods_stores: { store_id: current_store.id })
+ .pluck(:type)
+ 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_types.include?(entry[:type])
+ installed_shorthands.include?(entry[:type])
end
render json: { data: available }
diff --git a/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb
index 566700902c..f5402e4ee6 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb
@@ -15,9 +15,6 @@ module Spree
Spree.api.admin_promotion_serializer
end
- # Used by index. Show/update/create paths read these too — the
- # serializer flattens stores/actions/rules into id arrays — so
- # also expose via scope_includes for find_resource.
def collection_includes
promotion_includes
end
@@ -26,47 +23,53 @@ module Spree
promotion_includes
end
- # Extends the base permit list with `rules` and `actions` arrays
- # so a single `POST` / `PATCH /promotions[/:id]` can ship the
- # full graph (basics + rules + actions). Each entry is a flat
- # hash whose `type` selects the STI subclass; per-subclass
- # extras come from `additional_permitted_attributes`. The
- # `Promotion#rules=`/`actions=` setters reconcile to the
- # desired set on save.
+ # A single POST/PATCH /promotions can ship rules and actions
+ # alongside the basics; `Promotion#rules=` / `actions=` reconcile
+ # to the desired set. The nested allowlist below is the union of
+ # every built-in rule/action's expected keys. Plugin-defined
+ # subclasses can add to it — see `additional_permitted_attributes`
+ # below.
def permitted_params
- base = params.permit(*permitted_attributes).to_h
- rules = permit_subclassed_collection(:rules, Spree.promotions.rules)
- actions = permit_subclassed_collection(:actions, Spree.promotions.actions)
-
- base[:rules] = rules if params.key?(:rules)
- base[:actions] = actions if params.key?(:actions)
-
- normalize_params(ActionController::Parameters.new(base).permit!)
+ normalize_params(params.permit(*permitted_attributes))
end
- private
+ def permitted_attributes
+ [
+ :name, :description, :code, :path,
+ :starts_at, :expires_at, :usage_limit, :match_policy,
+ :kind, :multi_codes, :number_of_codes, :code_prefix,
+ :promotion_category_id,
+ rules: rule_attributes,
+ actions: action_attributes
+ ]
+ end
- def promotion_includes
- [:stores, :promotion_actions, :promotion_rules]
+ def rule_attributes
+ [:id, :type, { preferences: {} }, *subclassed_collection_attributes(Spree.promotions.rules)]
end
- # Permits an array of subclass payloads (`rules` / `actions`).
- # Each entry is permitted with the union of every registered
- # subclass's `additional_permitted_attributes`, plus `id`,
- # `type`, and `preferences`. Returns the array of plain
- # hashes ready to hand to `Promotion#rules=`/`actions=`.
- def permit_subclassed_collection(key, registry)
- entries = params[key]
- return [] unless entries.is_a?(Array) || entries.respond_to?(:to_a)
+ def action_attributes
+ [
+ :id, :type,
+ { preferences: {} },
+ { calculator: [:type, { preferences: {} }] },
+ *subclassed_collection_attributes(Spree.promotions.actions)
+ ]
+ end
- extras = registry.flat_map do |klass|
+ # Pulls in plugin-defined permitted attributes from every
+ # registered rule/action subclass. Subclasses declare these via
+ # `additional_permitted_attributes` (e.g. `[product_ids: []]`).
+ def subclassed_collection_attributes(registry)
+ registry.flat_map do |klass|
klass.respond_to?(:additional_permitted_attributes) ? klass.additional_permitted_attributes : []
end.uniq
+ end
+
+ private
- Array(entries).map do |entry|
- entry = entry.respond_to?(:to_unsafe_h) ? ActionController::Parameters.new(entry.to_unsafe_h) : ActionController::Parameters.new(entry.to_h)
- entry.permit(:id, :type, { preferences: {} }, *extras).to_h
- end
+ def promotion_includes
+ [:stores, :promotion_actions, :promotion_rules]
end
end
end
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 7f04d27e74..775230dab9 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
@@ -10,7 +10,6 @@ module Spree
# current value hash, `preference_schema` describes its fields.
class PromotionActionSerializer < BaseSerializer
typelize type: :string,
- key: :string,
promotion_id: :string,
preferences: 'Record<string, unknown>',
preference_schema: "Array<{ key: string; type: string; default: unknown }>",
@@ -18,11 +17,10 @@ module Spree
calculator: "{ type: string; label: string; preferences: Record<string, unknown>; preference_schema: Array<{ key: string; type: string; default: unknown }> } | null",
line_items: 'Array<{ variant_id: string; quantity: number }> | null'
- attributes :type,
- created_at: :iso8601, updated_at: :iso8601
+ attributes created_at: :iso8601, updated_at: :iso8601
- attribute :key do |action|
- action.key
+ attribute :type do |action|
+ action.class.api_type
end
attribute :promotion_id do |action|
@@ -51,7 +49,7 @@ module Spree
calc = action.calculator
{
- type: calc.class.to_s,
+ type: calc.class.api_type,
label: calc.class.respond_to?(:description) ? calc.class.description : calc.class.to_s.demodulize.titleize,
preferences: calc.preferences.to_h,
preference_schema: calc.class.preference_schema
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 406e7cbf6a..8b1c42033f 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
@@ -9,20 +9,18 @@ module Spree
# frontend renders both with the same generic component.
class PromotionRuleSerializer < BaseSerializer
typelize type: :string,
- key: :string,
promotion_id: :string,
preferences: 'Record<string, unknown>',
preference_schema: "Array<{ key: string; type: string; default: unknown }>",
label: :string,
product_ids: 'Array<string> | null',
category_ids: 'Array<string> | null',
- user_ids: 'Array<string> | null'
+ customer_ids: 'Array<string> | null'
- attributes :type,
- created_at: :iso8601, updated_at: :iso8601
+ attributes created_at: :iso8601, updated_at: :iso8601
- attribute :key do |rule|
- rule.key
+ attribute :type do |rule|
+ rule.class.api_type
end
attribute :promotion_id do |rule|
@@ -38,7 +36,7 @@ module Spree
end
attribute :label do |rule|
- rule.respond_to?(:human_name) ? rule.human_name : rule.type.to_s.demodulize
+ rule.respond_to?(:human_name) ? rule.human_name : rule.class.to_s.demodulize
end
# Association IDs for rules that wire products/taxons/users through
@@ -55,7 +53,7 @@ module Spree
rule.taxons.map(&:prefixed_id) if rule.respond_to?(:taxons)
end
- attribute :user_ids do |rule|
+ attribute :customer_ids do |rule|
rule.users.map(&:prefixed_id) if rule.respond_to?(:users)
end
diff --git a/spree/api/app/serializers/spree/api/v3/payment_method_serializer.rb b/spree/api/app/serializers/spree/api/v3/payment_method_serializer.rb
index 137646a005..4465245cae 100644
--- a/spree/api/app/serializers/spree/api/v3/payment_method_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/payment_method_serializer.rb
@@ -5,7 +5,11 @@ module Spree
typelize name: :string, description: [:string, nullable: true], type: :string,
session_required: :boolean, source_required: :boolean
- attributes :name, :description, :type
+ attributes :name, :description
+
+ attribute :type do |payment_method|
+ payment_method.class.api_type
+ end
attribute :session_required do |payment_method|
payment_method.session_required?
diff --git a/spree/api/lib/spree/api/openapi/schema_helper.rb b/spree/api/lib/spree/api/openapi/schema_helper.rb
index f4e7b39bbd..ecccf8fa12 100644
--- a/spree/api/lib/spree/api/openapi/schema_helper.rb
+++ b/spree/api/lib/spree/api/openapi/schema_helper.rb
@@ -144,6 +144,36 @@ module Spree
name: { type: :string, description: 'Role name', example: 'admin' }
},
required: %w[id name]
+ },
+ PreferenceField: {
+ 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]
+ },
+ 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' } }
+ },
+ required: %w[type label preferences preference_schema]
+ },
+ PromotionActionLineItem: {
+ type: :object,
+ description: 'One row in a `create_line_items` action — the variant added to the order and how many',
+ properties: {
+ variant_id: { type: :string, example: 'variant_abc123' },
+ quantity: { type: :integer, example: 1 }
+ },
+ required: %w[variant_id quantity]
}
}
end
@@ -189,6 +219,8 @@ module Spree
patch_cart_schema(schemas)
patch_fulfillment_schema(schemas)
patch_admin_user_schema(schemas)
+ patch_promotion_rule_schema(schemas)
+ patch_promotion_action_schema(schemas)
schemas
end
end
@@ -237,6 +269,73 @@ module Spree
end
end
+ # Same Array<{...}> + Array<string> typelize hints that Typelizer
+ # collapses to `object` in OpenAPI. Patch the affected properties to
+ # their correct array shapes.
+ def patch_promotion_rule_schema(schemas)
+ rule = schemas['PromotionRule'] || schemas[:PromotionRule]
+ return unless rule
+
+ patch_id_arrays(rule, %w[product_ids category_ids customer_ids])
+ 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
+
+ calc_key = props.key?('calculator') ? 'calculator' : :calculator
+ if props[calc_key]
+ props[calc_key] = {
+ allOf: [{ '$ref' => '#/components/schemas/PromotionActionCalculator' }],
+ nullable: true
+ }
+ end
+
+ items_key = props.key?('line_items') ? 'line_items' : :line_items
+ if props[items_key]
+ props[items_key] = {
+ type: :array,
+ items: { '$ref' => '#/components/schemas/PromotionActionLineItem' },
+ nullable: true
+ }
+ end
+ end
+
+ def patch_id_arrays(schema, keys)
+ props = schema[:properties]
+ return unless props
+
+ keys.each do |key|
+ actual = props.key?(key) ? key : key.to_sym
+ next unless props[actual]
+
+ props[actual] = {
+ type: :array,
+ items: { type: :string },
+ nullable: true
+ }
+ end
+ end
+
+ def patch_preference_schema(schema)
+ props = schema[:properties]
+ return unless props
+
+ key = props.key?('preference_schema') ? 'preference_schema' : :preference_schema
+ return unless props[key]
+
+ props[key] = {
+ type: :array,
+ items: { '$ref' => '#/components/schemas/PreferenceField' }
+ }
+ end
+
# Typelizer cannot represent Array<{...}> inline object types in OpenAPI,
# so we patch Fulfillment#items to reference the FulfillmentManifestItem component schema.
def patch_fulfillment_schema(schemas)
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 98574fd9ef..e1e8386681 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
@@ -42,7 +42,7 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
describe 'POST #create' do
let(:create_params) do
{
- type: 'Spree::PaymentMethod::Check',
+ type: 'check',
name: 'Check on delivery',
description: 'Pay by physical check',
active: true,
@@ -55,7 +55,7 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
to change(Spree::PaymentMethod, :count).by(1)
expect(response).to have_http_status(:created)
- expect(json_response['type']).to eq('Spree::PaymentMethod::Check')
+ expect(json_response['type']).to eq('check')
expect(json_response['name']).to eq('Check on delivery')
created = Spree::PaymentMethod.find_by_prefix_id(json_response['id'])
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
new file mode 100644
index 0000000000..ebb67686c9
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
@@ -0,0 +1,474 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ let!(:promotion) { create(:promotion, stores: [store]) }
+
+ it 'returns promotions list' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to be_an(Array)
+ expect(json_response['data'].map { |p| p['id'] }).to include(promotion.prefixed_id)
+ end
+ end
+
+ describe 'GET #show' do
+ let!(:promotion) { create(:promotion_with_item_adjustment, stores: [store]) }
+
+ it 'returns the promotion' do
+ get :show, params: { id: promotion.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(promotion.prefixed_id)
+ expect(json_response['name']).to eq(promotion.name)
+ end
+ end
+
+ describe 'POST #create' do
+ let(:base_params) { { name: 'Spring Sale', kind: 'automatic' } }
+
+ context 'with basic attributes only' do
+ it 'creates a promotion' do
+ expect { post :create, params: base_params, as: :json }.to change(Spree::Promotion, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['name']).to eq('Spring Sale')
+ expect(json_response['kind']).to eq('automatic')
+ end
+
+ it 'returns 422 without a name' do
+ post :create, params: { kind: 'automatic' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+
+ context 'with rules' do
+ it 'creates a Currency rule with preferences' do
+ post :create,
+ params: base_params.merge(
+ rules: [{ type: 'currency', preferences: { currency: 'EUR' } }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
+ expect(promotion.rules.size).to eq(1)
+ rule = promotion.rules.first
+ expect(rule).to be_a(Spree::Promotion::Rules::Currency)
+ expect(rule.preferred_currency).to eq('EUR')
+ end
+
+ it 'creates an ItemTotal rule with multiple preferences' do
+ post :create,
+ params: base_params.merge(
+ rules: [{
+ type: 'item_total',
+ preferences: { amount_min: '50.0', operator_min: 'gte', amount_max: '500.0', operator_max: 'lt' }
+ }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ rule = Spree::Promotion.find_by_prefix_id(json_response['id']).rules.first
+ expect(rule).to be_a(Spree::Promotion::Rules::ItemTotal)
+ expect(rule.preferred_amount_min).to eq(50.0)
+ expect(rule.preferred_operator_min).to eq('gte')
+ expect(rule.preferred_amount_max).to eq(500.0)
+ expect(rule.preferred_operator_max).to eq('lt')
+ end
+
+ it 'creates a Product rule with prefixed product_ids on a new promotion' do
+ product_a = create(:product, stores: [store])
+ product_b = create(:product, stores: [store])
+
+ post :create,
+ params: base_params.merge(
+ rules: [{
+ type: 'product',
+ preferences: { match_policy: 'any' },
+ product_ids: [product_a.prefixed_id, product_b.prefixed_id]
+ }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
+ rule = promotion.rules.first
+ expect(rule).to be_a(Spree::Promotion::Rules::Product)
+ expect(rule.product_ids).to contain_exactly(product_a.id, product_b.id)
+ expect(rule.preferred_match_policy).to eq('any')
+ end
+
+ it 'creates a Taxon rule with prefixed category_ids' do
+ taxonomy = create(:taxonomy, store: store)
+ taxon = create(:taxon, taxonomy: taxonomy)
+
+ post :create,
+ params: base_params.merge(
+ rules: [{
+ type: 'category',
+ category_ids: [taxon.prefixed_id]
+ }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ rule = Spree::Promotion.find_by_prefix_id(json_response['id']).rules.first
+ expect(rule).to be_a(Spree::Promotion::Rules::Taxon)
+ expect(rule.taxon_ids).to eq([taxon.id])
+ end
+
+ it 'creates multiple rules of different types in one request' do
+ post :create,
+ params: base_params.merge(
+ rules: [
+ { type: 'currency', preferences: { currency: 'USD' } },
+ { type: 'first_order' }
+ ]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
+ types = promotion.rules.map(&:class)
+ expect(types).to contain_exactly(Spree::Promotion::Rules::Currency, Spree::Promotion::Rules::FirstOrder)
+ end
+
+ it 'silently ignores rules with an unknown type' do
+ post :create,
+ params: base_params.merge(
+ rules: [
+ { type: 'currency', preferences: { currency: 'USD' } },
+ { type: 'NotARealRule' }
+ ]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
+ expect(promotion.rules.size).to eq(1)
+ expect(promotion.rules.first).to be_a(Spree::Promotion::Rules::Currency)
+ end
+ end
+
+ context 'with actions' do
+ it 'creates a CreateItemAdjustments action with a FlatRate calculator' do
+ post :create,
+ params: base_params.merge(
+ actions: [{
+ type: 'create_item_adjustments',
+ calculator: {
+ type: 'flat_rate',
+ preferences: { amount: '25.0', currency: 'USD' }
+ }
+ }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ action = Spree::Promotion.find_by_prefix_id(json_response['id']).actions.first
+ expect(action).to be_a(Spree::Promotion::Actions::CreateItemAdjustments)
+ expect(action.calculator).to be_a(Spree::Calculator::FlatRate)
+ expect(action.calculator.preferred_amount).to eq(25.0)
+ expect(action.calculator.preferred_currency).to eq('USD')
+ end
+
+ it 'creates a FreeShipping action without a calculator' do
+ post :create,
+ params: base_params.merge(
+ actions: [{ type: 'free_shipping' }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ action = Spree::Promotion.find_by_prefix_id(json_response['id']).actions.first
+ expect(action).to be_a(Spree::Promotion::Actions::FreeShipping)
+ end
+
+ it 'creates a CreateAdjustment action with FlatPercentItemTotal calculator' do
+ post :create,
+ params: base_params.merge(
+ actions: [{
+ type: 'create_adjustment',
+ calculator: {
+ type: 'flat_percent_item_total',
+ preferences: { flat_percent: '10.5' }
+ }
+ }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ action = Spree::Promotion.find_by_prefix_id(json_response['id']).actions.first
+ expect(action.calculator).to be_a(Spree::Calculator::FlatPercentItemTotal)
+ expect(action.calculator.preferred_flat_percent).to eq(10.5)
+ end
+ end
+
+ context 'with rules and actions in the same request' do
+ it 'persists both atomically' do
+ post :create,
+ params: base_params.merge(
+ rules: [{ type: 'currency', preferences: { currency: 'USD' } }],
+ actions: [{
+ type: 'create_item_adjustments',
+ calculator: { type: 'flat_rate', preferences: { amount: '5.0' } }
+ }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
+ expect(promotion.rules.size).to eq(1)
+ expect(promotion.actions.size).to eq(1)
+ end
+ end
+
+ context 'with shorthand type strings' do
+ it 'resolves shorthand to the correct rule subclass' do
+ post :create,
+ params: base_params.merge(
+ rules: [{ type: 'currency', preferences: { currency: 'EUR' } }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
+ expect(promotion.rules.first).to be_a(Spree::Promotion::Rules::Currency)
+ expect(promotion.rules.first.preferred_currency).to eq('EUR')
+ end
+
+ it 'resolves shorthand for rules with overridden api_type' do
+ taxonomy = create(:taxonomy, store: store)
+ taxon = create(:taxon, taxonomy: taxonomy)
+
+ post :create,
+ params: base_params.merge(
+ rules: [{ type: 'category', category_ids: [taxon.prefixed_id] }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ rule = Spree::Promotion.find_by_prefix_id(json_response['id']).rules.first
+ expect(rule).to be_a(Spree::Promotion::Rules::Taxon)
+ expect(rule.taxon_ids).to eq([taxon.id])
+ end
+
+ it 'resolves shorthand for actions and calculators' do
+ post :create,
+ params: base_params.merge(
+ actions: [{
+ type: 'create_item_adjustments',
+ calculator: { type: 'flat_rate', preferences: { amount: '12.5' } }
+ }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ action = Spree::Promotion.find_by_prefix_id(json_response['id']).actions.first
+ expect(action).to be_a(Spree::Promotion::Actions::CreateItemAdjustments)
+ expect(action.calculator).to be_a(Spree::Calculator::FlatRate)
+ expect(action.calculator.preferred_amount).to eq(12.5)
+ end
+
+ it 'exposes shorthand via the rule/action `type` attribute' do
+ post :create,
+ params: base_params.merge(
+ rules: [{ type: 'currency', preferences: { currency: 'USD' } }],
+ actions: [{ type: 'free_shipping' }]
+ ),
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
+ expect(promotion.rules.first.class.api_type).to eq('currency')
+ expect(promotion.actions.first.class.api_type).to eq('free_shipping')
+ end
+
+ it 'rejects unknown shorthand' do
+ post :create,
+ params: base_params.merge(
+ rules: [{ type: 'not_a_real_rule' }]
+ ),
+ as: :json
+
+ # Unknown shorthand → rule silently dropped (same behavior as unknown class name).
+ expect(response).to have_http_status(:created)
+ expect(Spree::Promotion.find_by_prefix_id(json_response['id']).rules).to be_empty
+ end
+ end
+ end
+
+ describe 'PATCH #update' do
+ let!(:promotion) { create(:promotion_with_item_adjustment, stores: [store]) }
+
+ it 'updates basic attributes' do
+ patch :update, params: { id: promotion.prefixed_id, name: 'Renamed' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(promotion.reload.name).to eq('Renamed')
+ end
+
+ context 'with rules' do
+ it 'adds a new rule to an existing promotion' do
+ patch :update,
+ params: {
+ id: promotion.prefixed_id,
+ rules: [{ type: 'currency', preferences: { currency: 'GBP' } }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ promotion.reload
+ expect(promotion.rules.size).to eq(1)
+ expect(promotion.rules.first.preferred_currency).to eq('GBP')
+ end
+
+ it 'updates an existing rule by prefixed id' do
+ rule = create(:promotion_rule, promotion: promotion, type: 'Spree::Promotion::Rules::Currency')
+ rule.becomes(Spree::Promotion::Rules::Currency).update!(preferred_currency: 'USD')
+
+ patch :update,
+ params: {
+ id: promotion.prefixed_id,
+ rules: [{
+ id: rule.prefixed_id,
+ type: 'currency',
+ preferences: { currency: 'CAD' }
+ }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(rule.becomes(Spree::Promotion::Rules::Currency).reload.preferred_currency).to eq('CAD')
+ expect(promotion.reload.rules.size).to eq(1)
+ end
+
+ it 'replaces product_ids on an existing Product rule' do
+ rule = Spree::Promotion::Rules::Product.create!(promotion: promotion)
+ product_a = create(:product, stores: [store])
+ product_b = create(:product, stores: [store])
+ rule.products = [product_a]
+ rule.save!
+
+ patch :update,
+ params: {
+ id: promotion.prefixed_id,
+ rules: [{
+ id: rule.prefixed_id,
+ type: 'product',
+ product_ids: [product_b.prefixed_id]
+ }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(rule.reload.product_ids).to eq([product_b.id])
+ end
+
+ it 'destroys rules omitted from the payload' do
+ rule = Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+
+ patch :update, params: { id: promotion.prefixed_id, rules: [] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(Spree::PromotionRule.where(id: rule.id)).to be_empty
+ expect(promotion.reload.rules).to be_empty
+ end
+
+ it 'destroys removed rules while keeping the ones explicitly passed' do
+ keep = Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+ drop = Spree::Promotion::Rules::FirstOrder.create!(promotion: promotion)
+
+ patch :update,
+ params: {
+ id: promotion.prefixed_id,
+ rules: [{ id: keep.prefixed_id, type: 'currency', preferences: { currency: 'USD' } }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(promotion.reload.rules.map(&:id)).to eq([keep.id])
+ expect(Spree::PromotionRule.where(id: drop.id)).to be_empty
+ end
+ end
+
+ context 'with actions' do
+ it 'swaps the calculator type and persists new preferences' do
+ action = promotion.actions.first
+
+ patch :update,
+ params: {
+ id: promotion.prefixed_id,
+ actions: [{
+ id: action.prefixed_id,
+ type: action.class.api_type,
+ calculator: {
+ type: 'percent_on_line_item',
+ preferences: { percent: '7.5' }
+ }
+ }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ action.reload
+ expect(action.calculator).to be_a(Spree::Calculator::PercentOnLineItem)
+ expect(action.calculator.preferred_percent).to eq(7.5)
+ end
+
+ it 'destroys actions omitted from the payload' do
+ existing = promotion.actions.first
+
+ patch :update, params: { id: promotion.prefixed_id, actions: [] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(Spree::PromotionAction.where(id: existing.id)).to be_empty
+ end
+
+ it 'adds a FreeShipping action alongside an existing one' do
+ existing = promotion.actions.first
+
+ patch :update,
+ params: {
+ id: promotion.prefixed_id,
+ actions: [
+ {
+ id: existing.prefixed_id,
+ type: existing.class.api_type,
+ calculator: {
+ type: existing.calculator.class.api_type,
+ preferences: { amount: existing.calculator.preferred_amount.to_s }
+ }
+ },
+ { type: 'free_shipping' }
+ ]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ types = promotion.reload.actions.map(&:class)
+ expect(types).to include(Spree::Promotion::Actions::FreeShipping)
+ end
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ let!(:promotion) { create(:promotion, stores: [store]) }
+
+ it 'destroys the promotion' do
+ expect { delete :destroy, params: { id: promotion.prefixed_id }, as: :json }.
+ to change(Spree::Promotion, :count).by(-1)
+
+ expect(response).to have_http_status(:no_content)
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/admin_users_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/admin_users_spec.rb
index e9d355d9b1..c0f987a724 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/admin_users_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/admin_users_spec.rb
@@ -26,9 +26,7 @@ RSpec.describe 'Admin Staff API', type: :request, swagger_doc: 'api-reference/ad
description 'Returns admin users with at least one role assignment on the current store.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const { data: staff } = await client.adminUsers.list()
- JS
+ admin_sdk_example 'admin-users/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -54,9 +52,7 @@ RSpec.describe 'Admin Staff API', type: :request, swagger_doc: 'api-reference/ad
security [api_key: [], bearer_auth: []]
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const staff = await client.adminUsers.get('admin_xxx')
- JS
+ admin_sdk_example 'admin-users/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -83,12 +79,7 @@ RSpec.describe 'Admin Staff API', type: :request, swagger_doc: 'api-reference/ad
'`role_ids` is a complete replacement — roles not in the array are removed for this store.'
admin_scope :write, :settings
- admin_sdk_example <<~JS
- const staff = await client.adminUsers.update('admin_xxx', {
- first_name: 'Ada',
- role_ids: ['role_xxx']
- })
- JS
+ admin_sdk_example 'admin-users/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -120,9 +111,7 @@ RSpec.describe 'Admin Staff API', type: :request, swagger_doc: 'api-reference/ad
description "Removes the user's role assignments on the current store. The account is preserved — the user keeps access to any other stores."
admin_scope :write, :settings
- admin_sdk_example <<~JS
- await client.adminUsers.delete('admin_xxx')
- JS
+ admin_sdk_example 'admin-users/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/api_keys_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/api_keys_spec.rb
index 5510fa8c6a..33d259b57e 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/api_keys_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/api_keys_spec.rb
@@ -20,9 +20,7 @@ RSpec.describe 'Admin API Keys API', type: :request, swagger_doc: 'api-reference
'Secret keys are listed by `token_prefix` only — the plaintext token is delivered exactly once on create.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const { data: keys } = await client.apiKeys.list()
- JS
+ admin_sdk_example 'api-keys/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -53,14 +51,7 @@ RSpec.describe 'Admin API Keys API', type: :request, swagger_doc: 'api-reference
'publishable keys expose their token on every read since they are intended for client-side use.'
admin_scope :write, :settings
- admin_sdk_example <<~JS
- const key = await client.apiKeys.create({
- name: 'Backend integration',
- key_type: 'secret',
- scopes: ['read_orders', 'write_orders']
- })
- // `key.plaintext_token` is available only on this response.
- JS
+ admin_sdk_example 'api-keys/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -106,9 +97,7 @@ RSpec.describe 'Admin API Keys API', type: :request, swagger_doc: 'api-reference
security [api_key: [], bearer_auth: []]
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const key = await client.apiKeys.get('key_xxx')
- JS
+ admin_sdk_example 'api-keys/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -129,9 +118,7 @@ RSpec.describe 'Admin API Keys API', type: :request, swagger_doc: 'api-reference
security [api_key: [], bearer_auth: []]
admin_scope :write, :settings
- admin_sdk_example <<~JS
- await client.apiKeys.delete('key_xxx')
- JS
+ admin_sdk_example 'api-keys/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -155,9 +142,7 @@ RSpec.describe 'Admin API Keys API', type: :request, swagger_doc: 'api-reference
description 'Marks the key revoked. Future requests using its token will fail; the row is preserved for audit.'
admin_scope :write, :settings
- admin_sdk_example <<~JS
- const key = await client.apiKeys.revoke('key_xxx')
- JS
+ admin_sdk_example 'api-keys/revoke'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/coupon_codes_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/coupon_codes_spec.rb
index cb504a27eb..c392000316 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/coupon_codes_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/coupon_codes_spec.rb
@@ -21,9 +21,7 @@ RSpec.describe 'Admin Coupon Codes API', type: :request, swagger_doc: 'api-refer
description 'Returns the auto-generated coupon codes for a multi-code promotion. Single-code promotions store the code on the promotion itself; this endpoint returns an empty list for them.'
admin_scope :read, :promotions
- admin_sdk_example <<~JS
- const { data: coupons } = await client.promotions.couponCodes.list('promo_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'coupon-codes/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb
index abde670631..c0b0cc75ae 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb
@@ -21,11 +21,7 @@ RSpec.describe 'Admin Custom Field Definitions API', type: :request, swagger_doc
description 'Returns all defined custom fields. Filter by `?q[resource_type_eq]=Spree::Product` to narrow to one parent type.'
admin_scope :read, :custom_field_definitions
- admin_sdk_example <<~JS
- const { data: definitions } = await client.customFieldDefinitions.list({
- q: { resource_type_eq: 'Spree::Product' },
- })
- JS
+ admin_sdk_example 'custom-field-definitions/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -57,16 +53,7 @@ RSpec.describe 'Admin Custom Field Definitions API', type: :request, swagger_doc
security [api_key: [], bearer_auth: []]
admin_scope :write, :custom_field_definitions
- admin_sdk_example <<~JS
- const definition = await client.customFieldDefinitions.create({
- namespace: 'specs',
- key: 'origin',
- label: 'Country of Origin',
- field_type: 'short_text',
- resource_type: 'Spree::Product',
- storefront_visible: true,
- })
- JS
+ admin_sdk_example 'custom-field-definitions/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/customers/addresses_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/customers/addresses_spec.rb
index 55d23c8b9f..a2c74e922b 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/customers/addresses_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/customers/addresses_spec.rb
@@ -21,9 +21,7 @@ RSpec.describe 'Admin Customer Addresses API', type: :request, swagger_doc: 'api
description 'Returns the customer\'s saved addresses.'
admin_scope :read, :customers
- admin_sdk_example <<~JS
- const { data: addresses } = await client.customers.addresses.list('cus_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'customer-addresses/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -51,20 +49,7 @@ RSpec.describe 'Admin Customer Addresses API', type: :request, swagger_doc: 'api
description 'Adds a new address to the customer\'s address book. Pass `is_default_billing: true` or `is_default_shipping: true` to set as the default — the previous default loses its flag in the same transaction.'
admin_scope :write, :customers
- admin_sdk_example <<~JS
- const address = await client.customers.addresses.create('cus_UkLWZg9DAJ', {
- first_name: 'Jane',
- last_name: 'Doe',
- address1: '350 Fifth Avenue',
- city: 'New York',
- postal_code: '10118',
- country_iso: 'US',
- state_abbr: 'NY',
- phone: '+1 212 555 1234',
- label: 'Office',
- is_default_shipping: true,
- })
- JS
+ admin_sdk_example 'customer-addresses/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -119,13 +104,7 @@ RSpec.describe 'Admin Customer Addresses API', type: :request, swagger_doc: 'api
description 'Updates a customer address.'
admin_scope :write, :customers
- admin_sdk_example <<~JS
- const address = await client.customers.addresses.update(
- 'cus_UkLWZg9DAJ',
- 'addr_UkLWZg9DAJ',
- { city: 'Manhattan' },
- )
- JS
+ admin_sdk_example 'customer-addresses/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -157,9 +136,7 @@ RSpec.describe 'Admin Customer Addresses API', type: :request, swagger_doc: 'api
description 'Deletes the address. If it was a default, the customer loses that default (no auto-promotion).'
admin_scope :write, :customers
- admin_sdk_example <<~JS
- await client.customers.addresses.delete('cus_UkLWZg9DAJ', 'addr_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'customer-addresses/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/customers/credit_cards_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/customers/credit_cards_spec.rb
index 1f80218875..ae4e71dcea 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/customers/credit_cards_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/customers/credit_cards_spec.rb
@@ -20,9 +20,7 @@ RSpec.describe 'Admin Customer Credit Cards API', type: :request, swagger_doc: '
description 'Returns the customer\'s saved credit cards. Useful for off-session admin charges via `POST /admin/orders/:id/payments { source_id }`.'
admin_scope :read, :customers
- admin_sdk_example <<~JS
- const { data: cards } = await client.customers.creditCards.list('cus_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'customer-credit-cards/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -54,9 +52,7 @@ RSpec.describe 'Admin Customer Credit Cards API', type: :request, swagger_doc: '
description 'Returns a saved credit card by ID.'
admin_scope :read, :customers
- admin_sdk_example <<~JS
- const card = await client.customers.creditCards.get('cus_UkLWZg9DAJ', 'cc_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'customer-credit-cards/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -83,9 +79,7 @@ RSpec.describe 'Admin Customer Credit Cards API', type: :request, swagger_doc: '
description 'Deletes a saved credit card.'
admin_scope :write, :customers
- admin_sdk_example <<~JS
- await client.customers.creditCards.delete('cus_UkLWZg9DAJ', 'cc_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'customer-credit-cards/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/customers/store_credits_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/customers/store_credits_spec.rb
index 2411289fb8..d3910452f9 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/customers/store_credits_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/customers/store_credits_spec.rb
@@ -20,9 +20,7 @@ RSpec.describe 'Admin Customer Store Credits API', type: :request, swagger_doc:
description 'Returns store credits issued to the customer.'
admin_scope :read, :store_credits
- admin_sdk_example <<~JS
- const { data: storeCredits } = await client.customers.storeCredits.list('cus_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'customer-store-credits/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -50,14 +48,7 @@ RSpec.describe 'Admin Customer Store Credits API', type: :request, swagger_doc:
description '`created_by` is set automatically from the authenticated admin.'
admin_scope :write, :store_credits
- admin_sdk_example <<~JS
- const credit = await client.customers.storeCredits.create('cus_UkLWZg9DAJ', {
- amount: 25.00,
- currency: 'USD',
- category_id: 1,
- memo: 'Goodwill credit',
- })
- JS
+ admin_sdk_example 'customer-store-credits/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -98,13 +89,7 @@ RSpec.describe 'Admin Customer Store Credits API', type: :request, swagger_doc:
description 'Update memo / category / amount. The amount can only be changed if `amount_used == 0`.'
admin_scope :write, :store_credits
- admin_sdk_example <<~JS
- const credit = await client.customers.storeCredits.update(
- 'cus_UkLWZg9DAJ',
- 'sc_UkLWZg9DAJ',
- { memo: 'Reissued for damaged shipment' },
- )
- JS
+ admin_sdk_example 'customer-store-credits/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -135,9 +120,7 @@ RSpec.describe 'Admin Customer Store Credits API', type: :request, swagger_doc:
description 'Deletes an unused store credit (amount_used == 0). Returns 422 otherwise.'
admin_scope :write, :store_credits
- admin_sdk_example <<~JS
- await client.customers.storeCredits.delete('cus_UkLWZg9DAJ', 'sc_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'customer-store-credits/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/customers_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/customers_spec.rb
index 51dbf73e5c..3c3257c049 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/customers_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/customers_spec.rb
@@ -16,13 +16,7 @@ RSpec.describe 'Admin Customers API', type: :request, swagger_doc: 'api-referenc
description 'Returns a paginated list of customers. Supports Ransack search/filters.'
admin_scope :read, :customers
- admin_sdk_example <<~JS
- const { data: customers } = await client.customers.list({
- search: 'jane',
- sort: '-created_at',
- limit: 25,
- })
- JS
+ admin_sdk_example 'customers/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -54,16 +48,7 @@ RSpec.describe 'Admin Customers API', type: :request, swagger_doc: 'api-referenc
description 'Creates a customer. No welcome email is sent automatically.'
admin_scope :write, :customers
- admin_sdk_example <<~JS
- const customer = await client.customers.create({
- email: '[email protected]',
- first_name: 'Jane',
- last_name: 'Doe',
- phone: '+1 212 555 1234',
- tags: ['wholesale'],
- accepts_email_marketing: true,
- })
- JS
+ admin_sdk_example 'customers/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -104,11 +89,7 @@ RSpec.describe 'Admin Customers API', type: :request, swagger_doc: 'api-referenc
description 'Returns full customer details including computed order stats (orders_count, total_spent, last_order_completed_at).'
admin_scope :read, :customers
- admin_sdk_example <<~JS
- const customer = await client.customers.get('cus_UkLWZg9DAJ', {
- expand: ['addresses', 'store_credits'],
- })
- JS
+ admin_sdk_example 'customers/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -138,12 +119,7 @@ RSpec.describe 'Admin Customers API', type: :request, swagger_doc: 'api-referenc
description 'Updates customer attributes. `tags` replaces the full set.'
admin_scope :write, :customers
- admin_sdk_example <<~JS
- const customer = await client.customers.update('cus_UkLWZg9DAJ', {
- first_name: 'Updated',
- tags: ['wholesale', 'vip'],
- })
- JS
+ admin_sdk_example 'customers/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -179,9 +155,7 @@ RSpec.describe 'Admin Customers API', type: :request, swagger_doc: 'api-referenc
description 'Deletes a customer. Returns 422 if the customer has any orders.'
admin_scope :write, :customers
- admin_sdk_example <<~JS
- await client.customers.delete('cus_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'customers/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/exports_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/exports_spec.rb
index f3a301d506..345bb110a1 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/exports_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/exports_spec.rb
@@ -19,9 +19,7 @@ RSpec.describe 'Admin Exports API', type: :request, swagger_doc: 'api-reference/
'Polled by the admin SPA to detect when an export finishes (`done: true`).'
admin_scope :read, :exports
- admin_sdk_example <<~JS
- const { data: exports } = await client.exports.list()
- JS
+ admin_sdk_example 'exports/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -53,12 +51,7 @@ RSpec.describe 'Admin Exports API', type: :request, swagger_doc: 'api-reference/
MD
admin_scope :write, :exports
- admin_sdk_example <<~JS
- const exp = await client.exports.create({
- type: 'Spree::Exports::Products',
- search_params: { name_cont: 'shirt' }
- })
- JS
+ admin_sdk_example 'exports/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -117,9 +110,7 @@ RSpec.describe 'Admin Exports API', type: :request, swagger_doc: 'api-reference/
description 'Returns export status. While `done` is `false`, the SPA continues polling.'
admin_scope :read, :exports
- admin_sdk_example <<~JS
- const exp = await client.exports.get('exp_xxx')
- JS
+ admin_sdk_example 'exports/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -141,9 +132,7 @@ RSpec.describe 'Admin Exports API', type: :request, swagger_doc: 'api-reference/
description 'Removes the export and purges its attachment.'
admin_scope :write, :exports
- admin_sdk_example <<~JS
- await client.exports.delete('exp_xxx')
- JS
+ admin_sdk_example 'exports/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -180,20 +169,7 @@ RSpec.describe 'Admin Exports API', type: :request, swagger_doc: 'api-reference/
'carry the JWT.'
admin_scope :read, :exports
- admin_sdk_example <<~JS
- // Fetch with the Bearer token, then drive the browser download:
- const res = await fetch(exp.download_url, {
- headers: { Authorization: `Bearer ${token}` }
- })
- const blob = await res.blob()
- const url = URL.createObjectURL(blob)
- const a = Object.assign(document.createElement('a'), {
- href: url,
- download: exp.filename
- })
- a.click()
- URL.revokeObjectURL(url)
- JS
+ admin_sdk_example 'exports/download'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb
index b7e33815e6..394b02d45f 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb
@@ -19,9 +19,7 @@ RSpec.describe 'Admin Invitations API', type: :request, swagger_doc: 'api-refere
description 'Returns invitations for the current store, including pending and accepted.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const { data: invitations } = await client.invitations.list()
- JS
+ admin_sdk_example 'invitations/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -46,12 +44,7 @@ RSpec.describe 'Admin Invitations API', type: :request, swagger_doc: 'api-refere
'on accept, a `RoleUser` is created via the invitation\'s `after_accept` callback.'
admin_scope :write, :settings
- admin_sdk_example <<~JS
- const invitation = await client.invitations.create({
- email: '[email protected]',
- role_id: 'role_xxx'
- })
- JS
+ admin_sdk_example 'invitations/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -86,9 +79,7 @@ RSpec.describe 'Admin Invitations API', type: :request, swagger_doc: 'api-refere
security [api_key: [], bearer_auth: []]
admin_scope :write, :settings
- admin_sdk_example <<~JS
- await client.invitations.delete('inv_xxx')
- JS
+ admin_sdk_example 'invitations/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -112,9 +103,7 @@ RSpec.describe 'Admin Invitations API', type: :request, swagger_doc: 'api-refere
description 'Issues a fresh token and dispatches the invitation email again.'
admin_scope :write, :settings
- admin_sdk_example <<~JS
- const invitation = await client.invitations.resend('inv_xxx')
- JS
+ admin_sdk_example 'invitations/resend'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/me_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/me_spec.rb
index 069352f78c..36d4420f91 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/me_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/me_spec.rb
@@ -12,12 +12,7 @@ RSpec.describe 'Admin Me API', type: :request, swagger_doc: 'api-reference/admin
security [api_key: [], bearer_auth: []]
description 'Returns the current admin user profile and a serialized list of permissions (CanCanCan rules). The SPA uses these to drive UI permission checks.'
- admin_sdk_example <<~JS
- const me = await client.me.get()
- if (me.permissions.some((r) => r.allow && r.actions.includes('manage') && r.subjects.includes('Spree::Product'))) {
- // show "Create product" button
- }
- JS
+ admin_sdk_example 'me/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/option_types_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/option_types_spec.rb
index c0d826b203..259ad15f6c 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/option_types_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/option_types_spec.rb
@@ -16,9 +16,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-refer
description 'Returns a paginated list of option types.'
admin_scope :read, :products
- admin_sdk_example <<~JS
- const { data: optionTypes } = await client.optionTypes.list()
- JS
+ admin_sdk_example 'option-types/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -66,16 +64,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-refer
DESC
admin_scope :write, :products
- admin_sdk_example <<~JS
- const optionType = await client.optionTypes.create({
- name: 'color',
- presentation: 'Color',
- option_values: [
- { name: 'red', presentation: 'Red' },
- { name: 'navy', presentation: 'Navy' },
- ],
- })
- JS
+ admin_sdk_example 'option-types/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -134,9 +123,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-refer
description 'Returns a single option type by ID, including its option values.'
admin_scope :read, :products
- admin_sdk_example <<~JS
- const optionType = await client.optionTypes.get('ot_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'option-types/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -177,14 +164,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-refer
description 'Updates an option type. Supports updating nested option values.'
admin_scope :write, :products
- admin_sdk_example <<~JS
- const optionType = await client.optionTypes.update('ot_UkLWZg9DAJ', {
- presentation: 'Updated Presentation',
- option_values: [
- { name: 'red', presentation: 'Crimson' },
- ],
- })
- JS
+ admin_sdk_example 'option-types/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -242,9 +222,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-refer
description 'Deletes an option type.'
admin_scope :write, :products
- admin_sdk_example <<~JS
- await client.optionTypes.delete('ot_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'option-types/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/fulfillments_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/fulfillments_spec.rb
index 2e5160e0e5..959fd87820 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/orders/fulfillments_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/fulfillments_spec.rb
@@ -19,9 +19,7 @@ RSpec.describe 'Admin Order Fulfillments API', type: :request, swagger_doc: 'api
description 'Returns all shipments for an order.'
admin_scope :read, :fulfillments
- admin_sdk_example <<~JS
- const { data: fulfillments } = await client.orders.fulfillments.list('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-fulfillments/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -56,9 +54,7 @@ RSpec.describe 'Admin Order Fulfillments API', type: :request, swagger_doc: 'api
description 'Returns details of a specific shipment.'
admin_scope :read, :fulfillments
- admin_sdk_example <<~JS
- const fulfillment = await client.orders.fulfillments.get('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-fulfillments/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -91,11 +87,7 @@ RSpec.describe 'Admin Order Fulfillments API', type: :request, swagger_doc: 'api
description 'Updates a shipment (tracking, shipping rate).'
admin_scope :write, :fulfillments
- admin_sdk_example <<~JS
- const fulfillment = await client.orders.fulfillments.update('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ', {
- tracking: '1Z999AA10123456784',
- })
- JS
+ admin_sdk_example 'order-fulfillments/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -132,9 +124,7 @@ RSpec.describe 'Admin Order Fulfillments API', type: :request, swagger_doc: 'api
description 'Marks a fulfillment as fulfilled.'
admin_scope :write, :fulfillments
- admin_sdk_example <<~JS
- const fulfillment = await client.orders.fulfillments.fulfill('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-fulfillments/fulfill'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -169,9 +159,7 @@ RSpec.describe 'Admin Order Fulfillments API', type: :request, swagger_doc: 'api
description 'Cancels a fulfillment.'
admin_scope :write, :fulfillments
- admin_sdk_example <<~JS
- const fulfillment = await client.orders.fulfillments.cancel('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-fulfillments/cancel'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -202,9 +190,7 @@ RSpec.describe 'Admin Order Fulfillments API', type: :request, swagger_doc: 'api
description 'Resumes a canceled fulfillment.'
admin_scope :write, :fulfillments
- admin_sdk_example <<~JS
- const fulfillment = await client.orders.fulfillments.resume('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-fulfillments/resume'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -240,11 +226,7 @@ RSpec.describe 'Admin Order Fulfillments API', type: :request, swagger_doc: 'api
description 'Transfers items from this shipment to a new shipment at a different stock location.'
admin_scope :write, :fulfillments
- admin_sdk_example <<~JS
- const fulfillment = await client.orders.fulfillments.split('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ', {
- quantity: 1,
- })
- JS
+ admin_sdk_example 'order-fulfillments/split'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/gift_cards_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/gift_cards_spec.rb
index 54ab9e2118..d884e020e0 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/orders/gift_cards_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/gift_cards_spec.rb
@@ -21,11 +21,7 @@ RSpec.describe 'Admin Order Gift Cards API', type: :request, swagger_doc: 'api-r
description 'Applies a gift card by code to the order. Returns the gift card.'
admin_scope :write, :gift_cards
- admin_sdk_example <<~JS
- await client.orders.giftCards.apply('or_UkLWZg9DAJ', {
- code: 'GIFT-XXXX-YYYY',
- })
- JS
+ admin_sdk_example 'order-gift-cards/apply'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -62,9 +58,7 @@ RSpec.describe 'Admin Order Gift Cards API', type: :request, swagger_doc: 'api-r
description 'Removes the gift card from the order.'
admin_scope :write, :gift_cards
- admin_sdk_example <<~JS
- await client.orders.giftCards.remove('or_UkLWZg9DAJ', 'gc_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-gift-cards/remove'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/items_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/items_spec.rb
index 2739fd9311..f2f18683ca 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/orders/items_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/items_spec.rb
@@ -21,9 +21,7 @@ RSpec.describe 'Admin Order Line Items API', type: :request, swagger_doc: 'api-r
description 'Returns all line items for an order.'
admin_scope :read, :orders
- admin_sdk_example <<~JS
- const { data: items } = await client.orders.items.list('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-items/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -54,12 +52,7 @@ RSpec.describe 'Admin Order Line Items API', type: :request, swagger_doc: 'api-r
description 'Adds a new line item to the order.'
admin_scope :write, :orders
- admin_sdk_example <<~JS
- const item = await client.orders.items.create('or_UkLWZg9DAJ', {
- variant_id: 'variant_k5nR8xLq',
- quantity: 2,
- })
- JS
+ admin_sdk_example 'order-items/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -99,9 +92,7 @@ RSpec.describe 'Admin Order Line Items API', type: :request, swagger_doc: 'api-r
description 'Returns details of a specific line item.'
admin_scope :read, :orders
- admin_sdk_example <<~JS
- const item = await client.orders.items.get('or_UkLWZg9DAJ', 'li_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-items/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -133,11 +124,7 @@ RSpec.describe 'Admin Order Line Items API', type: :request, swagger_doc: 'api-r
description 'Updates an order item quantity or metadata.'
admin_scope :write, :orders
- admin_sdk_example <<~JS
- const item = await client.orders.items.update('or_UkLWZg9DAJ', 'li_UkLWZg9DAJ', {
- quantity: 5,
- })
- JS
+ admin_sdk_example 'order-items/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -170,9 +157,7 @@ RSpec.describe 'Admin Order Line Items API', type: :request, swagger_doc: 'api-r
description 'Removes an item from the order.'
admin_scope :write, :orders
- admin_sdk_example <<~JS
- await client.orders.items.delete('or_UkLWZg9DAJ', 'li_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-items/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/payments_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/payments_spec.rb
index 293d34b4cc..8c3d38e59b 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/orders/payments_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/payments_spec.rb
@@ -19,9 +19,7 @@ RSpec.describe 'Admin Order Payments API', type: :request, swagger_doc: 'api-ref
description 'Returns all payments for an order.'
admin_scope :read, :payments
- admin_sdk_example <<~JS
- const { data: payments } = await client.orders.payments.list('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-payments/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -52,13 +50,7 @@ RSpec.describe 'Admin Order Payments API', type: :request, swagger_doc: 'api-ref
description 'Creates a new payment for the order.'
admin_scope :write, :payments
- admin_sdk_example <<~JS
- const payment = await client.orders.payments.create('or_UkLWZg9DAJ', {
- payment_method_id: 'pm_UkLWZg9DAJ',
- amount: 99.99,
- source_id: 'cc_UkLWZg9DAJ',
- })
- JS
+ admin_sdk_example 'order-payments/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -101,9 +93,7 @@ RSpec.describe 'Admin Order Payments API', type: :request, swagger_doc: 'api-ref
description 'Returns details of a specific payment.'
admin_scope :read, :payments
- admin_sdk_example <<~JS
- const payment = await client.orders.payments.get('or_UkLWZg9DAJ', 'pay_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-payments/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -136,9 +126,7 @@ RSpec.describe 'Admin Order Payments API', type: :request, swagger_doc: 'api-ref
description 'Captures a pending payment.'
admin_scope :write, :payments
- admin_sdk_example <<~JS
- const payment = await client.orders.payments.capture('or_UkLWZg9DAJ', 'pay_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-payments/capture'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -194,9 +182,7 @@ RSpec.describe 'Admin Order Payments API', type: :request, swagger_doc: 'api-ref
description 'Voids a payment.'
admin_scope :write, :payments
- admin_sdk_example <<~JS
- const payment = await client.orders.payments.void('or_UkLWZg9DAJ', 'pay_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-payments/void'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/refunds_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/refunds_spec.rb
index feebfca98d..4115f6a321 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/orders/refunds_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/refunds_spec.rb
@@ -20,9 +20,7 @@ RSpec.describe 'Admin Order Refunds API', type: :request, swagger_doc: 'api-refe
description 'Returns all refunds for an order.'
admin_scope :read, :refunds
- admin_sdk_example <<~JS
- const { data: refunds } = await client.orders.refunds.list('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-refunds/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -52,13 +50,7 @@ RSpec.describe 'Admin Order Refunds API', type: :request, swagger_doc: 'api-refe
description 'Creates a refund for a payment on the order. The refund is automatically processed via the payment gateway.'
admin_scope :write, :refunds
- admin_sdk_example <<~JS
- const refund = await client.orders.refunds.create('or_UkLWZg9DAJ', {
- payment_id: 'pay_UkLWZg9DAJ',
- amount: 5.00,
- refund_reason_id: 'refrsn_UkLWZg9DAJ',
- })
- JS
+ admin_sdk_example 'order-refunds/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/store_credits_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/store_credits_spec.rb
index 047b4a3461..0828152116 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/orders/store_credits_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/store_credits_spec.rb
@@ -23,11 +23,7 @@ RSpec.describe 'Admin Order Store Credits API', type: :request, swagger_doc: 'ap
'When `amount` is omitted, applies up to the order outstanding balance.'
admin_scope :write, :store_credits
- admin_sdk_example <<~JS
- const order = await client.orders.storeCredits.apply('or_UkLWZg9DAJ', {
- amount: 25.00,
- })
- JS
+ admin_sdk_example 'order-store-credits/apply'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -58,9 +54,7 @@ RSpec.describe 'Admin Order Store Credits API', type: :request, swagger_doc: 'ap
description "Removes any applied store credit from the order."
admin_scope :write, :store_credits
- admin_sdk_example <<~JS
- await client.orders.storeCredits.remove('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'order-store-credits/remove'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb
index b28a48426d..e444fbea3c 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb
@@ -16,14 +16,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
description 'Returns a paginated list of orders for the current store.'
admin_scope :read, :orders
- admin_sdk_example <<~JS
- const { data: orders, meta } = await client.orders.list({
- status_eq: 'complete',
- completed_at_gt: '2026-01-01',
- sort: '-completed_at',
- limit: 25,
- })
- JS
+ admin_sdk_example 'orders/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -71,70 +64,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
produces 'application/json'
security [api_key: [], bearer_auth: []]
- admin_sdk_example <<~JS
- // One-shot order create: customer, items, addresses, market, channel,
- // notes, metadata, and a coupon code in a single call. Everything
- // except `email` is optional.
- const order = await client.orders.create({
- email: '[email protected]',
- customer_id: 'cus_UkLWZg9DAJ', // Existing customer; omit for guest orders
- use_customer_default_address: false, // true to copy the customer's saved addresses
-
- currency: 'USD',
- market_id: 'mkt_UkLWZg9DAJ',
- channel_id: 'ch_UkLWZg9DAJ', // Optional — defaults to the store's primary channel
- locale: 'en-US',
-
- // Pin the order's preferred fulfillment location. Order Routing's
- // built-in PreferredLocation rule ranks this location first when
- // it stocks the cart's items; if it doesn't, routing falls back
- // to the next rule (Minimize Splits → Default Location).
- preferred_stock_location_id: 'sloc_UkLWZg9DAJ',
-
- customer_note: 'Please leave at the front desk.',
- internal_note: 'VIP customer — handle with care.',
- metadata: {
- external_reference: 'subscription_invoice_2026_04',
- source: 'recurring-engine',
- },
-
- // Items: each variant_id + quantity. Optional metadata per line.
- items: [
- { variant_id: 'variant_k5nR8xLq', quantity: 2 },
- { variant_id: 'variant_QXyZ12abCD', quantity: 1, metadata: { gift: true } },
- ],
-
- // Provide addresses inline OR by ID (existing customer addresses).
- shipping_address: {
- first_name: 'Jane',
- last_name: 'Doe',
- address1: '350 Fifth Avenue',
- address2: 'Floor 42',
- city: 'New York',
- postal_code: '10118',
- country_iso: 'US',
- state_abbr: 'NY',
- phone: '+1 212 555 1234',
- company: 'Acme Inc.',
- },
- // shipping_address_id: 'addr_UkLWZg9DAJ', // alternative to inline
-
- billing_address: {
- first_name: 'Jane',
- last_name: 'Doe',
- address1: '350 Fifth Avenue',
- city: 'New York',
- postal_code: '10118',
- country_iso: 'US',
- state_abbr: 'NY',
- phone: '+1 212 555 1234',
- },
- // billing_address_id: 'addr_UkLWZg9DAJ',
-
- // Optional. Invalid codes are non-fatal — the order is created either way.
- coupon_code: 'WELCOME10',
- })
- JS
+ admin_sdk_example 'orders/create'
description <<~DESC
Creates a new draft order in one shot. Customer, items, addresses, currency,
@@ -244,11 +174,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
description 'Returns full order details including admin-only fields.'
admin_scope :read, :orders
- admin_sdk_example <<~JS
- const order = await client.orders.get('or_UkLWZg9DAJ', {
- expand: ['items', 'fulfillments', 'payments', 'customer'],
- })
- JS
+ admin_sdk_example 'orders/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -287,12 +213,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
description 'Updates an order. Supports updating email, addresses, special instructions, and line items.'
admin_scope :write, :orders
- admin_sdk_example <<~JS
- const order = await client.orders.update('or_UkLWZg9DAJ', {
- email: '[email protected]',
- internal_note: 'VIP — gift wrap on next order',
- })
- JS
+ admin_sdk_example 'orders/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -368,9 +289,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
description 'Deletes a draft order. Completed orders cannot be deleted.'
admin_scope :write, :orders
- admin_sdk_example <<~JS
- await client.orders.delete('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'orders/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -399,11 +318,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
DESC
admin_scope :write, :orders
- admin_sdk_example <<~JS
- const order = await client.orders.complete('or_UkLWZg9DAJ', {
- notify_customer: true,
- })
- JS
+ admin_sdk_example 'orders/complete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -447,9 +362,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
description 'Cancels a completed order.'
admin_scope :write, :orders
- admin_sdk_example <<~JS
- const order = await client.orders.cancel('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'orders/cancel'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -475,9 +388,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
description 'Approves an order (e.g., for fraud review).'
admin_scope :write, :orders
- admin_sdk_example <<~JS
- const order = await client.orders.approve('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'orders/approve'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -506,9 +417,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
description 'Resumes a previously canceled order.'
admin_scope :write, :orders
- admin_sdk_example <<~JS
- const order = await client.orders.resume('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'orders/resume'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -538,9 +447,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/a
description 'Publishes the order.completed event to trigger confirmation email delivery.'
admin_scope :write, :orders
- admin_sdk_example <<~JS
- await client.orders.resendConfirmation('or_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'orders/resend-confirmation'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
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 926ede119c..2adafee262 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
@@ -16,9 +16,7 @@ RSpec.describe 'Admin Payment Methods API', type: :request, swagger_doc: 'api-re
description 'Returns the store\'s configured payment methods. Use `source_required: true` to know which methods need a saved source.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const { data: paymentMethods } = await client.paymentMethods.list()
- JS
+ admin_sdk_example 'payment-methods/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -46,9 +44,7 @@ RSpec.describe 'Admin Payment Methods API', type: :request, swagger_doc: 'api-re
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.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const { data: types } = await client.paymentMethods.types()
- JS
+ admin_sdk_example 'payment-methods/types'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -69,9 +65,9 @@ RSpec.describe 'Admin Payment Methods API', type: :request, swagger_doc: 'api-re
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('Spree::PaymentMethod::StoreCredit')
+ 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('Spree::Gateway::Bogus')
+ expect(data.map { |t| t['type'] }).to include('bogus')
end
end
end
@@ -87,9 +83,7 @@ RSpec.describe 'Admin Payment Methods API', type: :request, swagger_doc: 'api-re
description 'Returns a payment method by ID.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const paymentMethod = await client.paymentMethods.get('pm_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'payment-methods/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/products/custom_fields_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/products/custom_fields_spec.rb
index af63fb50fa..67521a2da8 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/products/custom_fields_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/products/custom_fields_spec.rb
@@ -22,9 +22,7 @@ RSpec.describe 'Admin Product Custom Fields API', type: :request, swagger_doc: '
description "Returns the product's custom field values."
admin_scope :read, :products
- admin_sdk_example <<~JS
- const { data: customFields } = await client.products.customFields.list('prod_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'product-custom-fields/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -55,12 +53,7 @@ RSpec.describe 'Admin Product Custom Fields API', type: :request, swagger_doc: '
description "Sets a custom field value on the product. Requires an existing CustomFieldDefinition; pass its prefixed `cfdef_…` id."
admin_scope :write, :products
- admin_sdk_example <<~JS
- const customField = await client.products.customFields.create('prod_UkLWZg9DAJ', {
- custom_field_definition_id: 'cfdef_AbC123XyZ',
- value: 'wool',
- })
- JS
+ admin_sdk_example 'product-custom-fields/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
index c4e3b0b25f..ed71c5e5f6 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
@@ -16,14 +16,7 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-reference
description 'Returns a paginated list of products for the current store.'
admin_scope :read, :products
- admin_sdk_example <<~JS
- const { data: products } = await client.products.list({
- name_cont: 'shirt',
- status_eq: 'active',
- sort: '-created_at',
- limit: 25,
- })
- JS
+ admin_sdk_example 'products/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -76,41 +69,7 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-reference
DESC
admin_scope :write, :products
- admin_sdk_example <<~JS
- const product = await client.products.create({
- name: 'Premium T-Shirt',
- price: 29.99,
- description: 'Soft, organic cotton.',
- status: 'active',
- variants: [
- {
- sku: 'TSHIRT-S-NAVY',
- options: [
- { name: 'size', value: 'Small' },
- { name: 'color', value: 'navy' },
- ],
- prices: [
- { currency: 'USD', amount: 29.99 },
- { currency: 'EUR', amount: 27.99 },
- ],
- stock_items: [
- { stock_location_id: 'sloc_UkLWZg9DAJ', count_on_hand: 50 },
- ],
- },
- {
- sku: 'TSHIRT-M-NAVY',
- options: [
- { name: 'size', value: 'Medium' },
- { name: 'color', value: 'navy' },
- ],
- prices: [{ currency: 'USD', amount: 29.99 }],
- stock_items: [
- { stock_location_id: 'sloc_UkLWZg9DAJ', count_on_hand: 30 },
- ],
- },
- ],
- })
- JS
+ admin_sdk_example 'products/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -210,11 +169,7 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-reference
description 'Returns a single product by ID.'
admin_scope :read, :products
- admin_sdk_example <<~JS
- const product = await client.products.get('prod_86Rf07xd4z', {
- expand: ['variants', 'option_types'],
- })
- JS
+ admin_sdk_example 'products/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -255,13 +210,7 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-reference
description 'Updates a product. Only provided fields are updated.'
admin_scope :write, :products
- admin_sdk_example <<~JS
- const product = await client.products.update('prod_86Rf07xd4z', {
- name: 'Updated Name',
- status: 'active',
- tags: ['eco', 'sale'],
- })
- JS
+ admin_sdk_example 'products/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -360,9 +309,7 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-reference
description 'Soft-deletes a product.'
admin_scope :write, :products
- admin_sdk_example <<~JS
- await client.products.delete('prod_86Rf07xd4z')
- JS
+ admin_sdk_example 'products/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
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 6c5616a3ec..16ec163af3 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
@@ -18,9 +18,7 @@ RSpec.describe 'Admin Promotion Actions API', type: :request, swagger_doc: 'api-
security [api_key: [], bearer_auth: []]
admin_scope :read, :promotions
- admin_sdk_example <<~JS
- const { data: actions } = await client.promotions.actions.list('promo_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'promotion-actions/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -35,7 +33,7 @@ RSpec.describe 'Admin Promotion Actions API', type: :request, swagger_doc: 'api-
run_test! do |response|
data = JSON.parse(response.body)['data']
expect(data.size).to eq(1)
- expect(data.first['type']).to eq('Spree::Promotion::Actions::FreeShipping')
+ expect(data.first['type']).to eq('free_shipping')
expect(data.first).to have_key('preference_schema')
end
end
@@ -46,21 +44,17 @@ RSpec.describe 'Admin Promotion Actions API', type: :request, swagger_doc: 'api-
produces 'application/json'
consumes 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Adds a new action to a promotion. The `type` is the fully-qualified subclass; pick from `GET /promotion_actions/types`.'
+ description 'Adds a new action to a promotion. The `type` is the wire shorthand from `GET /promotion_actions/types` (e.g. `free_shipping`, `create_item_adjustments`). Fully-qualified Ruby class names are also accepted for backward compatibility.'
admin_scope :write, :promotions
- admin_sdk_example <<~JS
- const action = await client.promotions.actions.create('promo_UkLWZg9DAJ', {
- type: 'Spree::Promotion::Actions::FreeShipping'
- })
- JS
+ admin_sdk_example 'promotion-actions/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
parameter name: :body, in: :body, schema: {
type: :object,
properties: {
- type: { type: :string },
+ type: { type: :string, example: 'free_shipping' },
preferences: { type: :object, additionalProperties: true }
},
required: ['type']
@@ -68,18 +62,18 @@ RSpec.describe 'Admin Promotion Actions API', type: :request, swagger_doc: 'api-
response '201', 'action created' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
- let(:body) { { type: 'Spree::Promotion::Actions::FreeShipping' } }
+ let(:body) { { type: 'free_shipping' } }
run_test! do |response|
data = JSON.parse(response.body)
- expect(data['type']).to eq('Spree::Promotion::Actions::FreeShipping')
+ expect(data['type']).to eq('free_shipping')
expect(data['promotion_id']).to eq(promotion.prefixed_id)
end
end
response '422', 'unknown action type' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
- let(:body) { { type: 'Bogus::Action' } }
+ let(:body) { { type: 'bogus_action' } }
run_test! do |response|
expect(JSON.parse(response.body)['error']['code']).to eq('unknown_promotion_action_type')
diff --git a/spree/api/spec/integration/spree/api/v3/admin/promotion_rules_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/promotion_rules_spec.rb
index 230241377e..b2911112ce 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/promotion_rules_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/promotion_rules_spec.rb
@@ -18,9 +18,7 @@ RSpec.describe 'Admin Promotion Rules API', type: :request, swagger_doc: 'api-re
security [api_key: [], bearer_auth: []]
admin_scope :read, :promotions
- admin_sdk_example <<~JS
- const { data: rules } = await client.promotions.rules.list('promo_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'promotion-rules/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -35,7 +33,7 @@ RSpec.describe 'Admin Promotion Rules API', type: :request, swagger_doc: 'api-re
run_test! do |response|
data = JSON.parse(response.body)['data']
expect(data.size).to eq(1)
- expect(data.first['type']).to eq('Spree::Promotion::Rules::Currency')
+ expect(data.first['type']).to eq('currency')
expect(data.first['preferences']).to include('currency' => 'USD')
end
end
@@ -46,22 +44,17 @@ RSpec.describe 'Admin Promotion Rules API', type: :request, swagger_doc: 'api-re
produces 'application/json'
consumes 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Adds a new rule to a promotion. The `type` is the fully-qualified subclass; pick from `GET /promotion_rules/types`. `preferences` round-trips through the typed setters declared on the subclass.'
+ description 'Adds a new rule to a promotion. The `type` is the wire shorthand from `GET /promotion_rules/types` (e.g. `currency`, `item_total`, `product`). Fully-qualified Ruby class names are also accepted for backward compatibility.'
admin_scope :write, :promotions
- admin_sdk_example <<~JS
- const rule = await client.promotions.rules.create('promo_UkLWZg9DAJ', {
- type: 'Spree::Promotion::Rules::Currency',
- preferences: { currency: 'EUR' }
- })
- JS
+ admin_sdk_example 'promotion-rules/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
parameter name: :body, in: :body, schema: {
type: :object,
properties: {
- type: { type: :string },
+ type: { type: :string, example: 'currency' },
preferences: { type: :object, additionalProperties: true }
},
required: ['type']
@@ -69,18 +62,18 @@ RSpec.describe 'Admin Promotion Rules API', type: :request, swagger_doc: 'api-re
response '201', 'rule created with preferences' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
- let(:body) { { type: 'Spree::Promotion::Rules::Currency', preferences: { currency: 'EUR' } } }
+ let(:body) { { type: 'currency', preferences: { currency: 'EUR' } } }
run_test! do |response|
data = JSON.parse(response.body)
- expect(data['type']).to eq('Spree::Promotion::Rules::Currency')
+ expect(data['type']).to eq('currency')
expect(data['preferences']).to include('currency' => 'EUR')
end
end
response '422', 'unknown rule type' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
- let(:body) { { type: 'Bogus::Rule' } }
+ let(:body) { { type: 'bogus_rule' } }
run_test! do |response|
expect(JSON.parse(response.body)['error']['code']).to eq('unknown_promotion_rule_type')
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 1a0a80b0ed..278f7255e1 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
@@ -16,9 +16,7 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
description 'Returns the store\'s promotions, including manual coupon and automatic promotions.'
admin_scope :read, :promotions
- admin_sdk_example <<~JS
- const { data: promotions } = await client.promotions.list()
- JS
+ admin_sdk_example 'promotions/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -39,17 +37,17 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
produces 'application/json'
consumes 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Creates a new promotion. `code` is required for single-code coupon promotions; pass `multi_codes: true` with `number_of_codes` to auto-generate a batch.'
+ description <<~DESC
+ Creates a new promotion. `code` is required for single-code coupon promotions;
+ pass `multi_codes: true` with `number_of_codes` to auto-generate a batch.
+
+ Rules and actions can be created in the same request by passing arrays of
+ `{ type, preferences, ... }` rows. The server reconciles to the desired set:
+ new rows are built, existing rows (by `id`) are updated, omitted rows are removed.
+ DESC
admin_scope :write, :promotions
- admin_sdk_example <<~JS
- const promotion = await client.promotions.create({
- name: 'Black Friday',
- code: 'BLACKFRIDAY',
- starts_at: '2026-11-29T00:00:00Z',
- expires_at: '2026-12-01T00:00:00Z'
- })
- JS
+ admin_sdk_example 'promotions/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -63,7 +61,43 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
expires_at: { type: :string, format: 'date-time', nullable: true },
usage_limit: { type: :integer, nullable: true },
match_policy: { type: :string, enum: %w[all any] },
- advertise: { type: :boolean }
+ kind: { type: :string, enum: %w[coupon_code automatic] },
+ multi_codes: { type: :boolean },
+ number_of_codes: { type: :integer, nullable: true },
+ code_prefix: { type: :string, nullable: true },
+ promotion_category_id: { type: :string, nullable: true },
+ rules: {
+ type: :array,
+ items: {
+ type: :object,
+ properties: {
+ type: { type: :string, example: 'currency' },
+ preferences: { type: :object, additionalProperties: true },
+ product_ids: { type: :array, items: { type: :string } },
+ category_ids: { type: :array, items: { type: :string } },
+ customer_ids: { type: :array, items: { type: :string } }
+ },
+ required: ['type']
+ }
+ },
+ actions: {
+ type: :array,
+ items: {
+ type: :object,
+ properties: {
+ type: { type: :string, example: 'free_shipping' },
+ preferences: { type: :object, additionalProperties: true },
+ calculator: {
+ type: :object,
+ properties: {
+ type: { type: :string, example: 'flat_percent_item_total' },
+ preferences: { type: :object, additionalProperties: true }
+ }
+ }
+ },
+ required: ['type']
+ }
+ }
},
required: ['name']
}
@@ -79,6 +113,64 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
end
end
+ response '201', 'promotion created with rules and actions' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:product_a) { create(:product, stores: [store]) }
+ let(:product_b) { create(:product, stores: [store]) }
+ let(:body) do
+ {
+ name: 'Black Friday',
+ code: 'BLACKFRIDAY-OS',
+ kind: 'coupon_code',
+ match_policy: 'all',
+ rules: [
+ { type: 'currency', preferences: { currency: 'USD' } },
+ {
+ type: 'item_total',
+ preferences: { amount_min: 100, operator_min: 'gte' }
+ },
+ {
+ type: 'product',
+ preferences: { match_policy: 'any' },
+ product_ids: [product_a.prefixed_id, product_b.prefixed_id]
+ }
+ ],
+ actions: [
+ {
+ type: 'create_item_adjustments',
+ calculator: {
+ type: 'percent_on_line_item',
+ preferences: { percent: 25 }
+ }
+ },
+ { type: 'free_shipping' }
+ ]
+ }
+ end
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ promotion = Spree::Promotion.find_by_prefix_id(data['id'])
+
+ expect(promotion.rules.map(&:class)).to contain_exactly(
+ Spree::Promotion::Rules::Currency,
+ Spree::Promotion::Rules::ItemTotal,
+ Spree::Promotion::Rules::Product
+ )
+ expect(promotion.actions.map(&:class)).to contain_exactly(
+ Spree::Promotion::Actions::CreateItemAdjustments,
+ Spree::Promotion::Actions::FreeShipping
+ )
+
+ product_rule = promotion.rules.find { |r| r.is_a?(Spree::Promotion::Rules::Product) }
+ expect(product_rule.product_ids).to contain_exactly(product_a.id, product_b.id)
+
+ adjustment_action = promotion.actions.find { |a| a.is_a?(Spree::Promotion::Actions::CreateItemAdjustments) }
+ expect(adjustment_action.calculator).to be_a(Spree::Calculator::PercentOnLineItem)
+ expect(adjustment_action.calculator.preferred_percent).to eq(25)
+ end
+ end
+
response '422', 'invalid params' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
let(:body) { { name: '' } }
@@ -116,14 +208,66 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
produces 'application/json'
consumes 'application/json'
security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Updates a promotion. The `rules` and `actions` arrays are treated as
+ a *desired set* — rows with `id` update in place, rows without `id` are
+ built fresh, and any existing row not present in the array is destroyed.
+ Pass `rules: []` or `actions: []` to clear them.
+ DESC
admin_scope :write, :promotions
+ admin_sdk_example 'promotions/update'
+
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
parameter name: :id, in: :path, type: :string, required: true
parameter name: :body, in: :body, schema: {
type: :object,
- properties: { name: { type: :string }, description: { type: :string, nullable: true } }
+ properties: {
+ name: { type: :string },
+ description: { type: :string, nullable: true },
+ code: { type: :string, nullable: true },
+ starts_at: { type: :string, format: 'date-time', nullable: true },
+ expires_at: { type: :string, format: 'date-time', nullable: true },
+ usage_limit: { type: :integer, nullable: true },
+ match_policy: { type: :string, enum: %w[all any] },
+ kind: { type: :string, enum: %w[coupon_code automatic] },
+ promotion_category_id: { type: :string, nullable: true },
+ rules: {
+ type: :array,
+ items: {
+ type: :object,
+ properties: {
+ id: { type: :string, nullable: true, description: 'Pass to update an existing rule; omit to build a new one' },
+ type: { type: :string, example: 'currency' },
+ preferences: { type: :object, additionalProperties: true },
+ product_ids: { type: :array, items: { type: :string } },
+ category_ids: { type: :array, items: { type: :string } },
+ customer_ids: { type: :array, items: { type: :string } }
+ },
+ required: ['type']
+ }
+ },
+ actions: {
+ type: :array,
+ items: {
+ type: :object,
+ properties: {
+ id: { type: :string, nullable: true },
+ type: { type: :string, example: 'free_shipping' },
+ preferences: { type: :object, additionalProperties: true },
+ calculator: {
+ type: :object,
+ properties: {
+ type: { type: :string, example: 'flat_percent_item_total' },
+ preferences: { type: :object, additionalProperties: true }
+ }
+ }
+ },
+ required: ['type']
+ }
+ }
+ }
}
response '200', 'promotion updated' do
@@ -134,6 +278,81 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
expect(JSON.parse(response.body)['description']).to eq('Updated description')
end
end
+
+ response '200', 'rules and actions reconciled to desired set' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let!(:existing_rule) do
+ Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+ end
+ let!(:existing_action) do
+ calc = Spree::Calculator::FlatRate.new(preferred_amount: 10)
+ Spree::Promotion::Actions::CreateItemAdjustments.create!(promotion: promotion, calculator: calc)
+ end
+ let!(:dropped_rule) { Spree::Promotion::Rules::FirstOrder.create!(promotion: promotion) }
+
+ let(:body) do
+ {
+ name: 'Holiday Sale',
+ rules: [
+ # Update existing currency rule
+ {
+ id: existing_rule.prefixed_id,
+ type: 'currency',
+ preferences: { currency: 'EUR' }
+ },
+ # Add a new rule
+ {
+ type: 'item_total',
+ preferences: { amount_min: 50, operator_min: 'gte' }
+ }
+ # `dropped_rule` (FirstOrder) omitted — should be destroyed
+ ],
+ actions: [
+ # Swap calculator type on existing action
+ {
+ id: existing_action.prefixed_id,
+ type: 'create_item_adjustments',
+ calculator: {
+ type: 'percent_on_line_item',
+ preferences: { percent: 15 }
+ }
+ }
+ ]
+ }
+ end
+
+ run_test! do |_response|
+ promotion.reload
+ expect(promotion.name).to eq('Holiday Sale')
+
+ # Existing currency rule was updated, FirstOrder dropped, ItemTotal added
+ expect(promotion.rules.map(&:class)).to contain_exactly(
+ Spree::Promotion::Rules::Currency,
+ Spree::Promotion::Rules::ItemTotal
+ )
+ expect(existing_rule.reload.preferred_currency).to eq('EUR')
+ expect(Spree::PromotionRule.where(id: dropped_rule.id)).to be_empty
+
+ # Action calculator was swapped in place
+ existing_action.reload
+ expect(existing_action.calculator).to be_a(Spree::Calculator::PercentOnLineItem)
+ expect(existing_action.calculator.preferred_percent).to eq(15)
+ end
+ end
+
+ response '200', 'rules and actions cleared with empty arrays' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let!(:rule_to_drop) do
+ Spree::Promotion::Rules::Currency.create!(promotion: promotion, preferred_currency: 'USD')
+ end
+ let(:body) { { rules: [], actions: [] } }
+
+ run_test! do |_response|
+ promotion.reload
+ expect(promotion.rules).to be_empty
+ expect(Spree::PromotionRule.where(id: rule_to_drop.id)).to be_empty
+ end
+ end
end
delete 'Delete a promotion' do
@@ -161,9 +380,7 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
description 'Returns the registered Spree::PromotionAction subclasses with their preference schemas. Used by admin UIs to populate the "Add action" picker and render generic preference forms.'
admin_scope :read, :promotions
- admin_sdk_example <<~JS
- const { data: actionTypes } = await client.promotionActions.types()
- JS
+ admin_sdk_example 'promotions/action-types'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
@@ -188,9 +405,7 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
description 'Returns the registered Spree::PromotionRule subclasses with their preference schemas.'
admin_scope :read, :promotions
- admin_sdk_example <<~JS
- const { data: ruleTypes } = await client.promotionRules.types()
- JS
+ admin_sdk_example 'promotions/rule-types'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/roles_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/roles_spec.rb
index 7e97ec1e9d..43e6489623 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/roles_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/roles_spec.rb
@@ -16,9 +16,7 @@ RSpec.describe 'Admin Roles API', type: :request, swagger_doc: 'api-reference/ad
description 'Returns the roles available for staff role pickers. Roles are global, not per-store.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const { data: roles } = await client.roles.list()
- JS
+ admin_sdk_example 'roles/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/stock_locations_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/stock_locations_spec.rb
index c9f168570c..0cfd05b0da 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/stock_locations_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/stock_locations_spec.rb
@@ -27,9 +27,7 @@ RSpec.describe 'Admin Stock Locations API', type: :request, swagger_doc: 'api-re
DESC
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const { data: stockLocations } = await client.stockLocations.list()
- JS
+ admin_sdk_example 'stock-locations/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -84,19 +82,7 @@ RSpec.describe 'Admin Stock Locations API', type: :request, swagger_doc: 'api-re
DESC
admin_scope :write, :settings
- admin_sdk_example <<~JS
- const stockLocation = await client.stockLocations.create({
- name: 'Brooklyn warehouse',
- kind: 'warehouse',
- country_iso: 'US',
- state_abbr: 'NY',
- city: 'Brooklyn',
- zipcode: '11201',
- pickup_enabled: true,
- pickup_stock_policy: 'local',
- pickup_ready_in_minutes: 60,
- })
- JS
+ admin_sdk_example 'stock-locations/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -180,9 +166,7 @@ RSpec.describe 'Admin Stock Locations API', type: :request, swagger_doc: 'api-re
description 'Returns a single stock location by prefixed ID.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const stockLocation = await client.stockLocations.get('sloc_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'stock-locations/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -225,13 +209,7 @@ RSpec.describe 'Admin Stock Locations API', type: :request, swagger_doc: 'api-re
DESC
admin_scope :write, :settings
- admin_sdk_example <<~JS
- const stockLocation = await client.stockLocations.update('sloc_UkLWZg9DAJ', {
- pickup_enabled: true,
- pickup_ready_in_minutes: 45,
- pickup_instructions: 'Enter through the back door, ring the bell.',
- })
- JS
+ admin_sdk_example 'stock-locations/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -298,9 +276,7 @@ RSpec.describe 'Admin Stock Locations API', type: :request, swagger_doc: 'api-re
DESC
admin_scope :write, :settings
- admin_sdk_example <<~JS
- await client.stockLocations.delete('sloc_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'stock-locations/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/store_credit_categories_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/store_credit_categories_spec.rb
index b2abd72007..b6a999011d 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/store_credit_categories_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/store_credit_categories_spec.rb
@@ -22,9 +22,7 @@ RSpec.describe 'Admin Store Credit Categories API', type: :request, swagger_doc:
DESC
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const { data: categories } = await client.storeCreditCategories.list()
- JS
+ admin_sdk_example 'store-credit-categories/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -71,9 +69,7 @@ RSpec.describe 'Admin Store Credit Categories API', type: :request, swagger_doc:
description 'Returns a single store credit category by prefixed ID.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const category = await client.storeCreditCategories.get('sccat_UkLWZg9DAJ')
- JS
+ admin_sdk_example 'store-credit-categories/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
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 86ffbc7642..c1ef9e3a0e 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
@@ -22,9 +22,7 @@ RSpec.describe 'Admin Store API', type: :request, swagger_doc: 'api-reference/ad
description 'Returns the current store configuration. The store is resolved from the request context (host or admin selection); there is no `id` parameter.'
admin_scope :read, :settings
- admin_sdk_example <<~JS
- const store = await client.store.get()
- JS
+ admin_sdk_example 'store/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -62,11 +60,7 @@ RSpec.describe 'Admin Store API', type: :request, swagger_doc: 'api-reference/ad
description 'Updates the current store configuration.'
admin_scope :write, :settings
- admin_sdk_example <<~JS
- const store = await client.store.update({
- name: 'My Store'
- })
- JS
+ admin_sdk_example 'store/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/tags_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/tags_spec.rb
index 05116d8677..b72b096087 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/tags_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/tags_spec.rb
@@ -14,12 +14,7 @@ RSpec.describe 'Admin Tags API', type: :request, swagger_doc: 'api-reference/adm
security [api_key: [], bearer_auth: []]
description 'Returns tag names for a given taggable type. Used for autocomplete in tag inputs on products, orders, and customers.'
- admin_sdk_example <<~JS
- const { data: tags } = await client.tags.list({
- taggable_type: 'Spree::User',
- q: 'vip',
- })
- JS
+ admin_sdk_example 'tags/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
diff --git a/spree/api/spec/integration/spree/api/v3/admin/variants_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/variants_spec.rb
index 694a7f2533..f69d8d0455 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/variants_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/variants_spec.rb
@@ -17,11 +17,7 @@ RSpec.describe 'Admin Variants API', type: :request, swagger_doc: 'api-reference
description 'Returns a paginated list of variants for a product, including the master variant.'
admin_scope :read, :products
- admin_sdk_example <<~JS
- const { data: variants } = await client.products.variants.list('prod_86Rf07xd4z', {
- expand: ['prices', 'stock_items'],
- })
- JS
+ admin_sdk_example 'variants/list'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -58,22 +54,7 @@ RSpec.describe 'Admin Variants API', type: :request, swagger_doc: 'api-reference
DESC
admin_scope :write, :products
- admin_sdk_example <<~JS
- const variant = await client.products.variants.create('prod_86Rf07xd4z', {
- sku: 'TSHIRT-L-NAVY',
- options: [
- { name: 'size', value: 'Large' },
- { name: 'color', value: 'navy' },
- ],
- prices: [
- { currency: 'USD', amount: 29.99, compare_at_amount: 34.99 },
- { currency: 'EUR', amount: 27.99 },
- ],
- stock_items: [
- { stock_location_id: 'sloc_UkLWZg9DAJ', count_on_hand: 25 },
- ],
- })
- JS
+ admin_sdk_example 'variants/create'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -169,11 +150,7 @@ RSpec.describe 'Admin Variants API', type: :request, swagger_doc: 'api-reference
description 'Returns a single variant by ID.'
admin_scope :read, :products
- admin_sdk_example <<~JS
- const variant = await client.products.variants.get('prod_86Rf07xd4z', 'variant_k5nR8xLq', {
- expand: ['prices', 'stock_items'],
- })
- JS
+ admin_sdk_example 'variants/get'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -215,14 +192,7 @@ RSpec.describe 'Admin Variants API', type: :request, swagger_doc: 'api-reference
description 'Updates a variant. Only provided fields are updated.'
admin_scope :write, :products
- admin_sdk_example <<~JS
- const variant = await client.products.variants.update('prod_86Rf07xd4z', 'variant_k5nR8xLq', {
- sku: 'UPDATED-SKU',
- stock_items: [
- { stock_location_id: 'sloc_UkLWZg9DAJ', count_on_hand: 75 },
- ],
- })
- JS
+ admin_sdk_example 'variants/update'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
@@ -303,9 +273,7 @@ RSpec.describe 'Admin Variants API', type: :request, swagger_doc: 'api-reference
description 'Soft-deletes a variant.'
admin_scope :write, :products
- admin_sdk_example <<~JS
- await client.products.variants.delete('prod_86Rf07xd4z', 'variant_k5nR8xLq')
- JS
+ admin_sdk_example 'variants/delete'
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true,
diff --git a/spree/api/spec/support/code_samples_helper.rb b/spree/api/spec/support/code_samples_helper.rb
index e883f75230..d9cc8310da 100644
--- a/spree/api/spec/support/code_samples_helper.rb
+++ b/spree/api/spec/support/code_samples_helper.rb
@@ -19,6 +19,12 @@ module CodeSamplesHelper
})
JS
+ ADMIN_SDK_EXAMPLES_ROOT = File.expand_path('../../../../packages/admin-sdk/examples', __dir__)
+
+ # Match `// region:example` / `// endregion:example` markers and extract
+ # the body between them. The markers can have arbitrary indentation.
+ ADMIN_SDK_EXAMPLE_REGION = /^[ \t]*\/\/\s*region:example\s*\n(.*?)^[ \t]*\/\/\s*endregion:example/m
+
def code_samples(*samples)
metadata[:operation][:'x-codeSamples'] = samples.map do |sample|
{ lang: sample[:lang], label: sample[:label], source: sample[:source].strip }
@@ -35,16 +41,39 @@ module CodeSamplesHelper
)
end
- def admin_sdk_example(source)
+ ADMIN_SDK_EXAMPLE_CACHE = {}
+
+ # Renders an admin SDK code sample from a typechecked example file under
+ # `packages/admin-sdk/examples/`. The file must be a complete `.ts`
+ # module (imports + `createAdminClient` initializer) so `tsc` can verify
+ # it against the live SDK types; the helper extracts only the body
+ # between `// region:example` / `// endregion:example` markers and
+ # re-prepends the canonical client init block so rendered docs stay
+ # consistent across endpoints.
+ #
+ # admin_sdk_example 'promotions/create'
+ # → packages/admin-sdk/examples/promotions/create.ts
+ def admin_sdk_example(name)
+ source = ADMIN_SDK_EXAMPLE_CACHE[name] ||= load_admin_sdk_example(name)
code_samples(
{
lang: 'javascript',
label: 'Spree Admin SDK',
- source: "#{ADMIN_SDK_CLIENT_INIT}\n\n#{source.strip}\n"
+ source: "#{ADMIN_SDK_CLIENT_INIT}\n\n#{source}\n"
}
)
end
+ def load_admin_sdk_example(name)
+ path = File.join(ADMIN_SDK_EXAMPLES_ROOT, "#{name}.ts")
+ raise "Admin SDK example not found: #{path}" unless File.exist?(path)
+
+ body = File.read(path).match(ADMIN_SDK_EXAMPLE_REGION)&.captures&.first
+ raise "Admin SDK example #{name.inspect} has no `// region:example` marker" if body.nil?
+
+ body.rstrip.strip_heredoc.strip
+ end
+
# Appends a `**Required scope:**` line to the operation description.
# Use in admin integration specs to surface scope requirements in the
# rendered Mintlify docs without inventing a custom OpenAPI extension.
diff --git a/spree/core/app/models/concerns/spree/calculated_adjustments.rb b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
index 776213a081..bfde8972cb 100644
--- a/spree/core/app/models/concerns/spree/calculated_adjustments.rb
+++ b/spree/core/app/models/concerns/spree/calculated_adjustments.rb
@@ -18,14 +18,21 @@ module Spree
calculator.class.to_s if calculator
end
+ # Look up a calculator by its wire shorthand (`'flat_rate'`) against
+ # the calculators registered for this parent. Scoping to the
+ # registered set ensures a `CreateAdjustment` action can't be
+ # assigned a shipping-only calculator just by knowing its shorthand.
def calculator_type=(calculator_type)
- klass = calculator_type.constantize if calculator_type
+ return if calculator_type.blank?
+
+ registry = self.class.respond_to?(:calculators) ? self.class.calculators : []
+ klass = registry.find { |k| k.api_type == calculator_type.to_s }
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
+ # 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.
def assign_calculator_attributes(attrs)
return if attrs.nil?
diff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rb
index 32b2f62e49..a224f38246 100644
--- a/spree/core/app/models/concerns/spree/preference_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema.rb
@@ -39,13 +39,22 @@ module Spree
[]
end
+ # Resolve a wire-format shorthand back to its registered subclass.
+ # Returns nil for unknown shorthands. Lookup is registry-driven so
+ # removed/foreign subclasses can't be smuggled in.
+ def find_by_api_type(shorthand)
+ return nil if shorthand.blank?
+
+ 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.
def subclasses_with_preference_schema
registered_subclasses.map do |klass|
{
- type: klass.to_s,
+ type: klass.api_type,
label: subclass_label(klass),
description: klass.respond_to?(:description) ? klass.description : nil,
preference_schema: klass.respond_to?(:preference_schema) ? klass.preference_schema : []
@@ -69,6 +78,7 @@ module Spree
# module, with a leading `Spree` namespace stripped.
def subclass_label(klass)
return klass.display_name if klass.respond_to?(:display_name) && klass.display_name.present?
+ return klass.human_name if klass.respond_to?(:human_name) && klass.human_name.present?
leaf = klass.to_s.demodulize
return leaf.titleize unless leaf == 'Gateway'
diff --git a/spree/core/app/models/spree/base.rb b/spree/core/app/models/spree/base.rb
index f729badec7..0c087319d1 100644
--- a/spree/core/app/models/spree/base.rb
+++ b/spree/core/app/models/spree/base.rb
@@ -71,7 +71,12 @@ class Spree::Base < ApplicationRecord
column_names.reject { |c| skipped_attributes.include?(c.to_s) }
end
- def self.json_api_type
+ # Public-API shorthand for this class, used as the `type` value on the
+ # wire (e.g. `"currency"` for `Spree::Promotion::Rules::Currency`,
+ # `"flat_rate"` for `Spree::Calculator::FlatRate`). Defaults to the
+ # demodulized + underscored leaf; override on a subclass when the wire
+ # format should stay stable across class renames.
+ def self.api_type
to_s.demodulize.underscore
end
diff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rb
index c60b84194e..5cbde115a1 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -120,15 +120,15 @@ module Spree
# `[{ type:, preferences:, product_ids:, ... }]` and reconciles to
# the desired set: existing rows update by `id`, new rows build,
# missing rows destroy. Falls through to AR's standard writer
- # when assigned a real array of `Spree::PromotionRule` instances
- # (Rails internals do this on association swap).
- def rules=(rules_params)
- assign_subclassed_collection(:promotion_rules, rules_params, registry: Spree.promotions.rules)
+ # when assigned `Spree::PromotionRule` instances (Rails internals
+ # do this on association swap).
+ def rules=(rows)
+ assign_subclassed(:promotion_rules, rows)
end
- # Same shape as `rules=` for promotion actions.
- def actions=(actions_params)
- assign_subclassed_collection(:promotion_actions, actions_params, registry: Spree.promotions.actions)
+ # Mirrors `rules=` for promotion actions.
+ def actions=(rows)
+ assign_subclassed(:promotion_actions, rows)
end
def pending_rules_or_actions?
@@ -303,80 +303,86 @@ module Spree
private
- def assign_subclassed_collection(association, params, registry:)
- first = Array(params).first
- return public_send(:"#{association}=", params) if first.nil? || first.is_a?(Spree.base_class)
+ # Reconciles `association` (`:promotion_rules` or `:promotion_actions`)
+ # to the desired set of `rows`. Each row is a `{type, id, preferences,
+ # calculator, <assoc>_ids}` hash. New rows are built, existing rows
+ # (matched by `id`) updated, anything missing destroyed.
+ #
+ # When the promotion is a new record the work is deferred until
+ # `after_save` so child rows can FK to a persisted parent.
+ def assign_subclassed(association, rows)
+ first = Array(rows).first
+ return public_send(:"#{association}=", rows) if first.nil? || first.is_a?(Spree.base_class)
- pending = Array(params).map { |entry| entry.respond_to?(:to_h) ? entry.to_h.with_indifferent_access : entry.with_indifferent_access }
+ pending = Array(rows).map { |entry| entry.respond_to?(:to_h) ? entry.to_h.with_indifferent_access : entry.with_indifferent_access }
if new_record?
- instance_variable_set(:"@pending_#{association}", { params: pending, registry: registry })
+ instance_variable_set(:"@pending_#{association}", pending)
return
end
- apply_subclassed_collection(association, pending, registry: registry)
+ reconcile_subclassed(association, pending)
end
def apply_pending_rules_and_actions
if (pending = @pending_promotion_rules)
- apply_subclassed_collection(:promotion_rules, pending[:params], registry: pending[:registry])
+ reconcile_subclassed(:promotion_rules, pending)
@pending_promotion_rules = nil
end
if (pending = @pending_promotion_actions)
- apply_subclassed_collection(:promotion_actions, pending[:params], registry: pending[:registry])
+ reconcile_subclassed(:promotion_actions, pending)
@pending_promotion_actions = nil
end
end
- # Applied to a persisted promotion. Reconciles `association` to the
- # supplied desired-set: rows with `id:` update, rows without build,
- # rows missing from the payload are destroyed.
- def apply_subclassed_collection(association, rows, registry:)
+ def reconcile_subclassed(association, rows)
collection = public_send(association)
- kept_ids = []
-
- rows.each do |row|
- klass = registry.find { |k| k.to_s == row[:type] } if row[:type]
- klass ||= collection.find_by(id: decode_id(row[:id]))&.class
+ kept_ids = rows.filter_map { |row| save_subclassed_row(collection, row) }
+ collection.where.not(id: kept_ids).destroy_all if kept_ids.any? || rows.empty?
+ end
- next unless klass
+ def save_subclassed_row(collection, row)
+ record = find_or_build_subclassed(collection, row)
+ return nil unless record
- record = if row[:id].present?
- collection.find { |r| r.id == decode_id(row[:id]) } || collection.find_by(id: decode_id(row[:id]))
- else
- collection.build(type: klass.to_s)
- end
+ preferences = row[:preferences]
+ calculator = row[:calculator]
+ attrs = row.except(:id, :type, :preferences, :calculator)
- next unless record
+ # Any `*_ids` mass-assignment on a new record builds join rows with
+ # a nil FK to the parent — they fail `presence: true` on autosave.
+ # Defer those assignments until after the rule itself is persisted.
+ 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?
- # Promote to the right STI subclass when building new (collection.build
- # uses the declared class_name, which is the parent).
- record = record.becomes(klass) if record.class != klass
- assign_subclass_attributes(record, row)
- record.save! if record.changed? || record.new_record?
- kept_ids << record.id
+ preferences&.each do |key, value|
+ record.set_preference(key.to_sym, value) if record.has_preference?(key.to_sym)
end
+ record.assign_calculator_attributes(calculator) if calculator.present? && record.respond_to?(:assign_calculator_attributes)
- collection.where.not(id: kept_ids).destroy_all if kept_ids.any? || rows.empty?
- end
-
- def assign_subclass_attributes(record, row)
- preferences = row.delete(:preferences)
- calculator = row.delete(:calculator)
- row.delete(:type)
- row.delete(:id)
+ # Always save — `record.changed?` doesn't reflect changes to
+ # preferences (stored in a serialized hash) or to the calculator
+ # association, and we may have built a new record above.
+ record.save!
- record.assign_attributes(row) if row.any?
+ deferred_ids.each { |key, value| record.public_send("#{key}=", value) }
+ record.save! if record.changed?
- if preferences.present?
- preferences.to_h.each do |key, value|
- next unless record.has_preference?(key.to_sym)
+ record.id
+ end
- record.set_preference(key.to_sym, value)
- end
+ def find_or_build_subclassed(collection, row)
+ if row[:id].present?
+ id = decode_id(row[:id])
+ existing = collection.find { |r| r.id == id } || collection.find_by(id: id)
+ return existing if existing
end
- record.assign_calculator_attributes(calculator) if calculator.present? && record.respond_to?(:assign_calculator_attributes)
+ klass = collection.proxy_association.klass.find_by_api_type(row[:type])
+ return nil unless klass
+
+ record = collection.build(type: klass.to_s)
+ record.class == klass ? record : record.becomes(klass)
end
def decode_id(value)
diff --git a/spree/core/app/models/spree/promotion/rules/taxon.rb b/spree/core/app/models/spree/promotion/rules/taxon.rb
index f3922e3df5..87e4d5ee01 100644
--- a/spree/core/app/models/spree/promotion/rules/taxon.rb
+++ b/spree/core/app/models/spree/promotion/rules/taxon.rb
@@ -14,8 +14,9 @@ module Spree
[category_ids: []]
end
- # API key is `category` (model is still `Taxon` pre-table-rename).
- def key
+ # Wire-format shorthand is `category` (the model is still `Taxon`
+ # pre-6.0 rename). `key` (instance) cascades through `api_type`.
+ def self.api_type
'category'
end
@@ -36,7 +37,7 @@ module Spree
# Preferences
#
MATCH_POLICIES = %w(any all)
- preference :match_policy, default: MATCH_POLICIES.first
+ preference :match_policy, :string, default: MATCH_POLICIES.first
#
# Attributes
diff --git a/spree/core/app/models/spree/promotion/rules/user.rb b/spree/core/app/models/spree/promotion/rules/user.rb
index 70f7070427..e87213a419 100644
--- a/spree/core/app/models/spree/promotion/rules/user.rb
+++ b/spree/core/app/models/spree/promotion/rules/user.rb
@@ -10,8 +10,19 @@ module Spree
dependent: :destroy
has_many :users, through: :promotion_rule_users, class_name: "::#{Spree.user_class}"
+ # Customers, not admin users — the rule keys off `Spree::Order#user_id`.
+ # The data layer keeps the `users` association (legacy column name);
+ # the API exposes the same set as `customer_ids`.
def self.additional_permitted_attributes
- [user_ids: []]
+ [customer_ids: []]
+ end
+
+ def customer_ids
+ user_ids
+ end
+
+ def customer_ids=(ids)
+ self.user_ids = ids
end
#
diff --git a/spree/core/app/models/spree/promotion_action.rb b/spree/core/app/models/spree/promotion_action.rb
index afb7cc55cb..5b7a05461e 100644
--- a/spree/core/app/models/spree/promotion_action.rb
+++ b/spree/core/app/models/spree/promotion_action.rb
@@ -38,25 +38,22 @@ module Spree
type == 'Spree::Promotion::Actions::FreeShipping'
end
- # Returns the human name of the promotion action
- #
- # @return [String] eg. Free Shipping
- def human_name
- Spree.t("promotion_action_types.#{key}.name")
+ def self.human_name
+ Spree.t("promotion_action_types.#{api_type}.name", default: api_type.titleize)
end
- # Returns the human description of the promotion action
- #
- # @return [String]
- def human_description
- Spree.t("promotion_action_types.#{key}.description")
+ def self.human_description
+ Spree.t("promotion_action_types.#{api_type}.description", default: '')
end
+ def human_name = self.class.human_name
+ def human_description = self.class.human_description
+
# Returns the key of the promotion action
#
# @return [String] eg. free_shipping
def key
- type.demodulize.underscore
+ self.class.api_type
end
protected
diff --git a/spree/core/app/models/spree/promotion_rule.rb b/spree/core/app/models/spree/promotion_rule.rb
index 1ae84d2164..af7e50aa65 100644
--- a/spree/core/app/models/spree/promotion_rule.rb
+++ b/spree/core/app/models/spree/promotion_rule.rb
@@ -65,25 +65,22 @@ module Spree
@eligibility_errors ||= ActiveModel::Errors.new(self)
end
- # Returns the human name of the promotion rule
- #
- # @return [String] eg. Currency
- def human_name
- Spree.t("promotion_rule_types.#{key}.name")
+ def self.human_name
+ Spree.t("promotion_rule_types.#{api_type}.name", default: api_type.titleize)
end
- # Returns the human description of the promotion rule
- #
- # @return [String]
- def human_description
- Spree.t("promotion_rule_types.#{key}.description")
+ def self.human_description
+ Spree.t("promotion_rule_types.#{api_type}.description", default: '')
end
+ def human_name = self.class.human_name
+ def human_description = self.class.human_description
+
# Returns the key of the promotion rule
#
# @return [String] eg. currency
def key
- type.demodulize.underscore
+ self.class.api_type
end
private
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index be34299547..daad79a049 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1890,8 +1890,8 @@ en:
promotion_rule: Promotion Rule
promotion_rule_types:
category:
- description: Order includes products in specified category(ies)
- name: Category(ies)
+ description: Order includes products in specified categories
+ name: Categories
country:
description: Limit to orders with shipping address in a specific country
name: Country
@@ -1918,10 +1918,10 @@ en:
name: Product(s)
user:
description: Available only to the specified customers
- name: User
+ name: Customers
user_logged_in:
- description: Available only to logged in users
- name: User Logged In
+ description: Available only to logged in customers
+ name: Only logged in customers
promotion_uses: Promotion uses
promotionable: Promotable
promotions: Promotions
diff --git a/spree/core/spec/models/spree/base_spec.rb b/spree/core/spec/models/spree/base_spec.rb
index 3e17b73191..fb57b98018 100644
--- a/spree/core/spec/models/spree/base_spec.rb
+++ b/spree/core/spec/models/spree/base_spec.rb
@@ -46,9 +46,9 @@ describe Spree::Base do
end
end
- describe '.json_api_type' do
- it { expect(Spree::InventoryUnit.json_api_type).to eq('inventory_unit') }
- it { expect(Spree::Address.json_api_type).to eq('address') }
+ describe '.api_type' do
+ it { expect(Spree::InventoryUnit.api_type).to eq('inventory_unit') }
+ it { expect(Spree::Address.api_type).to eq('address') }
end
describe '.json_api_columns' do
diff --git a/spree/core/spec/models/spree/promotion_spec.rb b/spree/core/spec/models/spree/promotion_spec.rb
index 36d0c53a5e..4b526707ac 100644
--- a/spree/core/spec/models/spree/promotion_spec.rb
+++ b/spree/core/spec/models/spree/promotion_spec.rb
@@ -906,4 +906,200 @@ describe Spree::Promotion, type: :model do
end
end
end
+
+ describe '#rules=' do
+ let(:promotion) { create(:promotion) }
+ let(:product) { create(:product) }
+ let(:other_product) { create(:product) }
+ let(:taxon) { create(:taxon) }
+
+ it 'builds a rule from a {type, preferences} hash' do
+ promotion.rules = [{ type: 'item_total', preferences: { amount_min: 50 } }]
+ promotion.reload
+
+ expect(promotion.rules.size).to eq(1)
+ expect(promotion.rules.first).to be_a(Spree::Promotion::Rules::ItemTotal)
+ expect(promotion.rules.first.preferred_amount_min).to eq(50)
+ end
+
+ it 'updates an existing rule when matched by id' do
+ existing = promotion.rules.create!(type: 'Spree::Promotion::Rules::ItemTotal', preferences: { amount_min: 10 })
+
+ promotion.rules = [{ id: existing.id, type: 'item_total', preferences: { amount_min: 99 } }]
+ promotion.reload
+
+ expect(promotion.rules.size).to eq(1)
+ expect(promotion.rules.first.id).to eq(existing.id)
+ expect(promotion.rules.first.preferred_amount_min).to eq(99)
+ end
+
+ it 'destroys rules omitted from the payload' do
+ kept = promotion.rules.create!(type: 'Spree::Promotion::Rules::ItemTotal', preferences: { amount_min: 10 })
+ removed = promotion.rules.create!(type: 'Spree::Promotion::Rules::FirstOrder')
+
+ promotion.rules = [{ id: kept.id, type: 'item_total' }]
+ promotion.reload
+
+ expect(promotion.rules.pluck(:id)).to eq([kept.id])
+ expect(Spree::PromotionRule.find_by(id: removed.id)).to be_nil
+ end
+
+ it 'destroys all rules when given an empty array' do
+ promotion.rules.create!(type: 'Spree::Promotion::Rules::ItemTotal')
+
+ promotion.rules = []
+ promotion.reload
+
+ expect(promotion.rules).to be_empty
+ end
+
+ # Regression: assigning `product_ids` on a brand-new rule used to fail
+ # because Rails autosaved the through-join rows before the parent
+ # rule had an id, tripping `presence: true` on the join model.
+ it 'builds a Product rule with product_ids in a single assignment' do
+ promotion.rules = [{
+ type: 'product',
+ preferences: { match_policy: 'any' },
+ product_ids: [product.id, other_product.id]
+ }]
+ promotion.reload
+
+ rule = promotion.rules.first
+ expect(rule).to be_a(Spree::Promotion::Rules::Product)
+ expect(rule.products).to contain_exactly(product, other_product)
+ expect(rule.preferred_match_policy).to eq('any')
+ end
+
+ it 'replaces product_ids on an existing Product rule' do
+ rule = promotion.rules.create!(type: 'Spree::Promotion::Rules::Product')
+ rule.products = [product]
+
+ promotion.rules = [{ id: rule.id, type: 'product', product_ids: [other_product.id] }]
+ promotion.reload
+
+ expect(promotion.rules.first.products).to contain_exactly(other_product)
+ end
+
+ it 'builds a Taxon rule with taxon_ids' do
+ promotion.rules = [{ type: 'category', taxon_ids: [taxon.id] }]
+ promotion.reload
+
+ rule = promotion.rules.first
+ expect(rule).to be_a(Spree::Promotion::Rules::Taxon)
+ expect(rule.taxons).to contain_exactly(taxon)
+ end
+
+ # Regression: `category_ids=` on Rules::Taxon is a custom setter (not a
+ # bare through-association writer), so `*_ids` deferral has to handle
+ # any key ending in `_ids` on a new record — not just keys that match
+ # an association name.
+ it 'builds a Taxon rule on a new promotion using category_ids (custom setter)' do
+ fresh = build(:promotion)
+ fresh.rules = [{ type: 'category', category_ids: [taxon.id] }]
+ fresh.save!
+
+ rule = fresh.reload.rules.first
+ expect(rule).to be_a(Spree::Promotion::Rules::Taxon)
+ expect(rule.taxons).to contain_exactly(taxon)
+ end
+
+ it 'defers application until after_save on a new promotion record' do
+ promotion = build(:promotion)
+ promotion.rules = [{ type: 'item_total', preferences: { amount_min: 25 } }]
+
+ expect(promotion).to be_pending_rules_or_actions
+ expect(promotion.rules).to be_empty
+
+ promotion.save!
+ promotion.reload
+
+ expect(promotion.rules.size).to eq(1)
+ expect(promotion.rules.first.preferred_amount_min).to eq(25)
+ end
+
+ it 'ignores rows with an unknown type' do
+ promotion.rules = [{ type: 'NotARealRule' }]
+ promotion.reload
+
+ expect(promotion.rules).to be_empty
+ end
+
+ it 'falls through to AR when assigned PromotionRule instances' do
+ rule = Spree::Promotion::Rules::FirstOrder.new
+ promotion.rules = [rule]
+
+ expect(promotion.rules).to include(rule)
+ end
+ end
+
+ describe '#actions=' do
+ let(:promotion) { create(:promotion) }
+
+ it 'builds a CreateAdjustment action with a calculator hash' do
+ promotion.actions = [{
+ type: 'create_adjustment',
+ calculator: {
+ type: 'flat_rate',
+ preferences: { amount: 7.5, currency: 'USD' }
+ }
+ }]
+ promotion.reload
+
+ action = promotion.actions.first
+ expect(action).to be_a(Spree::Promotion::Actions::CreateAdjustment)
+ expect(action.calculator).to be_a(Spree::Calculator::FlatRate)
+ expect(action.calculator.preferred_amount).to eq(7.5)
+ expect(action.calculator.preferred_currency).to eq('USD')
+ end
+
+ it 'updates the calculator type on an existing action' do
+ action = promotion.actions.create!(
+ type: 'Spree::Promotion::Actions::CreateAdjustment',
+ calculator: Spree::Calculator::FlatRate.new(preferred_amount: 5)
+ )
+
+ promotion.actions = [{
+ id: action.id,
+ type: 'create_adjustment',
+ calculator: { type: 'flat_percent_item_total', preferences: { flat_percent: 15 } }
+ }]
+ promotion.reload
+
+ reloaded = promotion.actions.first
+ expect(reloaded.id).to eq(action.id)
+ expect(reloaded.calculator).to be_a(Spree::Calculator::FlatPercentItemTotal)
+ expect(reloaded.calculator.preferred_flat_percent).to eq(15)
+ end
+
+ it 'builds a FreeShipping action without a calculator' do
+ promotion.actions = [{ type: 'free_shipping' }]
+ promotion.reload
+
+ expect(promotion.actions.first).to be_a(Spree::Promotion::Actions::FreeShipping)
+ end
+
+ it 'destroys actions omitted from the payload' do
+ kept = promotion.actions.create!(type: 'Spree::Promotion::Actions::FreeShipping')
+ removed = promotion.actions.create!(type: 'Spree::Promotion::Actions::CreateAdjustment')
+
+ promotion.actions = [{ id: kept.id, type: 'free_shipping' }]
+ promotion.reload
+
+ expect(promotion.actions.pluck(:id)).to eq([kept.id])
+ expect(Spree::PromotionAction.find_by(id: removed.id)).to be_nil
+ end
+
+ it 'defers application until after_save on a new promotion record' do
+ promotion = build(:promotion)
+ promotion.actions = [{ type: 'free_shipping' }]
+
+ expect(promotion).to be_pending_rules_or_actions
+ expect(promotion.actions).to be_empty
+
+ promotion.save!
+ promotion.reload
+
+ expect(promotion.actions.size).to eq(1)
+ end
+ end
end