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.

Greatly simplify managing Products/Variants with prices and stock in Admin API

Damian Legawiecf2793a936b41
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index ac60d4879d..f4d5f42751 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -144,7 +144,6 @@ export interface MediaUpdateParams {
export interface ProductCreateParams {
name: string;
- price: number;
description?: string;
slug?: string;
status?: 'draft' | 'active' | 'archived';
@@ -168,7 +167,6 @@ export interface ProductCreateParams {
export interface ProductUpdateParams {
name?: string;
- price?: number;
description?: string;
slug?: string;
status?: 'draft' | 'active' | 'archived';
diff --git a/packages/admin-sdk/src/types/generated/Category.ts b/packages/admin-sdk/src/types/generated/Category.ts
index 2745cf1ab5..b36d8960d0 100644
--- a/packages/admin-sdk/src/types/generated/Category.ts
+++ b/packages/admin-sdk/src/types/generated/Category.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 4b7f1380ab5aa7abae6af0861be6a562
+// Typelizer digest a24d2bc437662d7db7897765546e6d92
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CustomField} from '@/types'
@@ -6,7 +6,6 @@ import type {CustomField} from '@/types'
interface Category {
id: string;
name: string;
- pretty_name: string;
permalink: string;
position: number;
depth: number;
@@ -26,6 +25,7 @@ interface Category {
children?: Array<Category>;
ancestors?: Array<Category>;
custom_fields?: Array<CustomField>;
+ pretty_name: string;
lft: number;
rgt: number;
created_at: string;
diff --git a/packages/admin-sdk/src/types/generated/OptionType.ts b/packages/admin-sdk/src/types/generated/OptionType.ts
index e5694629f3..be57c72bc9 100644
--- a/packages/admin-sdk/src/types/generated/OptionType.ts
+++ b/packages/admin-sdk/src/types/generated/OptionType.ts
@@ -1,4 +1,4 @@
-// Typelizer digest b67ef90e0d3df34451e901209ceb5e6e
+// Typelizer digest 48a3b3751e01501ddfb330ed86b365e4
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {OptionValue} from '@/types'
@@ -11,7 +11,7 @@ interface OptionType {
kind: string;
created_at: string;
updated_at: string;
- option_values?: Array<OptionValue>;
+ option_values: Array<OptionValue>;
}
export default OptionType;
diff --git a/packages/admin-sdk/src/types/generated/Order.ts b/packages/admin-sdk/src/types/generated/Order.ts
index bb9ad5b601..07ce167ce8 100644
--- a/packages/admin-sdk/src/types/generated/Order.ts
+++ b/packages/admin-sdk/src/types/generated/Order.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 7ae2eca4c659b4865ab3541c6b91cf9f
+// Typelizer digest d3a5534b8bae8ed6140eeb3e4a855f65
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Discount, LineItem, Fulfillment, Payment, Address, GiftCard, Market, PaymentMethod, Customer, Adjustment, ReturnAuthorization, Reimbursement} from '@/types'
@@ -50,13 +50,13 @@ interface Order {
considered_risky: boolean;
confirmation_delivered: boolean;
store_owner_notification_delivered: boolean;
- internal_note: string | null;
payment_total: string;
display_payment_total: string;
canceled_at: string | null;
approved_at: string | null;
created_at: string;
updated_at: string;
+ internal_note: string | null;
metadata: Record<string, unknown> | null;
approver_id: string | null;
canceler_id: string | null;
diff --git a/packages/admin-sdk/src/types/generated/Price.ts b/packages/admin-sdk/src/types/generated/Price.ts
index 3d0d98f8c6..ebe9c257f4 100644
--- a/packages/admin-sdk/src/types/generated/Price.ts
+++ b/packages/admin-sdk/src/types/generated/Price.ts
@@ -1,6 +1,7 @@
-// Typelizer digest 63bfc856c6af5eeee775270d4ee46c73
+// Typelizer digest afe024e84fb613e6dfd091fc69e09c9e
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {Variant} from '@/types'
interface Price {
id: string;
@@ -15,6 +16,7 @@ interface Price {
variant_id: string | null;
created_at: string;
updated_at: string;
+ variant?: Variant;
}
export default Price;
diff --git a/packages/admin-sdk/src/types/generated/ShippingCategory.ts b/packages/admin-sdk/src/types/generated/ShippingCategory.ts
deleted file mode 100644
index be4551f66e..0000000000
--- a/packages/admin-sdk/src/types/generated/ShippingCategory.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-// Typelizer digest 3f4e629432bf26d461da760bf634fae2
-//
-// DO NOT MODIFY: This file was automatically generated by Typelizer.
-
-interface ShippingCategory {
- id: string;
- name: string;
- created_at: string;
- updated_at: string;
-}
-
-export default ShippingCategory;
diff --git a/packages/admin-sdk/src/types/generated/Store.ts b/packages/admin-sdk/src/types/generated/Store.ts
index a4eb92321c..6c29b6c66d 100644
--- a/packages/admin-sdk/src/types/generated/Store.ts
+++ b/packages/admin-sdk/src/types/generated/Store.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 434248d920da5234a6f1e49b80eaab7a
+// Typelizer digest cd7defafc23e2cb5169a499bc4a3aa6a
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -7,10 +7,6 @@ interface Store {
name: string;
url: string;
code: string;
- default_currency: string;
- default_locale: string;
- supported_currencies: Array<string>;
- supported_locales: Array<string>;
mail_from_address: string;
customer_support_email: string | null;
new_order_notifications_email: string | null;
@@ -23,6 +19,10 @@ interface Store {
default: boolean;
created_at: string;
updated_at: string;
+ default_currency: string;
+ default_locale: string;
+ supported_currencies: Array<string>;
+ supported_locales: Array<string>;
logo_url: string | null;
mailer_logo_url: string | null;
}
diff --git a/packages/admin-sdk/src/types/generated/Variant.ts b/packages/admin-sdk/src/types/generated/Variant.ts
index cac48657a7..79d3525e24 100644
--- a/packages/admin-sdk/src/types/generated/Variant.ts
+++ b/packages/admin-sdk/src/types/generated/Variant.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 1aecfc086e4cce3f916a556c9b27b960
+// Typelizer digest 63a3c10ff6fb4f3bcde508c7ce86f6d4
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Price, PriceHistory, Media, OptionValue, CustomField} from '@/types'
@@ -25,8 +25,6 @@ interface Variant {
option_values: Array<OptionValue>;
custom_fields?: Array<CustomField>;
prior_price?: PriceHistory | null;
- product_name: string;
- display_price: string | null;
position: number;
total_on_hand: number | null;
tax_category_id: string | null;
@@ -35,6 +33,8 @@ interface Variant {
deleted_at: string | null;
created_at: string;
updated_at: string;
+ product_name: string;
+ display_price: string | null;
prices?: Array<Price>;
}
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index 97de9dc2a1..222318a4d5 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 3d6cfbd10466fcce81d2d1aec3b111e7
+// Typelizer digest f06581f4deb5822d41b29acfdb441494
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -32,10 +32,10 @@ export type { default as Product } from './Product'
export type { default as Refund } from './Refund'
export type { default as Reimbursement } from './Reimbursement'
export type { default as ReturnAuthorization } from './ReturnAuthorization'
-export type { default as ShippingCategory } from './ShippingCategory'
export type { default as State } from './State'
export type { default as StockItem } from './StockItem'
export type { default as StockLocation } from './StockLocation'
export type { default as StoreCredit } from './StoreCredit'
+export type { default as Store } from './Store'
export type { default as TaxCategory } from './TaxCategory'
export type { default as Variant } from './Variant'
diff --git a/packages/admin/src/hooks/use-product.ts b/packages/admin/src/hooks/use-product.ts
index 1cd0f4d455..f25096935d 100644
--- a/packages/admin/src/hooks/use-product.ts
+++ b/packages/admin/src/hooks/use-product.ts
@@ -7,7 +7,10 @@ export function useProduct(id: string) {
queryFn: () =>
adminClient.products.get(id, {
expand: [
+ 'default_variant',
+ 'default_variant.prices',
'variants',
+ 'variants.prices',
'images',
'option_types',
'categories',
diff --git a/packages/admin/src/providers/store-provider.tsx b/packages/admin/src/providers/store-provider.tsx
index 22ef957ef7..4fd9e644d9 100644
--- a/packages/admin/src/providers/store-provider.tsx
+++ b/packages/admin/src/providers/store-provider.tsx
@@ -1,4 +1,4 @@
-import { createContext, type ReactNode, useCallback, useContext, useEffect, useState } from 'react'
+import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import type { Store } from '@spree/admin-sdk'
import { adminClient } from '@/client'
@@ -6,6 +6,10 @@ interface StoreContextValue {
store: Store | null
storeId: string
isLoading: boolean
+ currencies: string[]
+ locales: string[]
+ defaultCurrency: string
+ defaultLocale: string
refetch: () => Promise<void>
}
@@ -31,8 +35,13 @@ export function StoreProvider({ storeId, children }: { storeId: string; children
fetchStore()
}, [storeId, fetchStore])
+ const currencies = store?.supported_currencies ?? []
+ const locales = store?.supported_locales ?? []
+ const defaultCurrency = store?.default_currency ?? 'USD'
+ const defaultLocale = store?.default_locale ?? 'en'
+
return (
- <StoreContext.Provider value={{ store, storeId, isLoading, refetch: fetchStore }}>
+ <StoreContext.Provider value={{ store, storeId, isLoading, currencies, locales, defaultCurrency, defaultLocale, refetch: fetchStore }}>
{children}
</StoreContext.Provider>
)
diff --git a/packages/admin/src/routes/_authenticated/$storeId/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/index.tsx
index 424bb259fb..d18fa1aed2 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/index.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/index.tsx
@@ -62,7 +62,7 @@ function DashboardPage() {
staleTime: 5 * 60 * 1000,
})
- if (isLoading || !data) {
+ if (!data) {
return <DashboardSkeleton />
}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
index 6b392ed742..35d73b27bd 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
@@ -6,10 +6,10 @@ type Variant = BaseVariant & {
weight_unit?: string | null
dimensions_unit?: string | null
}
-type Product = Omit<BaseProduct, 'master_variant' | 'variants'> & {
+type Product = Omit<BaseProduct, 'default_variant' | 'variants'> & {
tax_category_id?: string | null
meta_title?: string | null
- master_variant?: Variant
+ default_variant?: Variant
variants?: Variant[]
}
import { zodResolver } from '@hookform/resolvers/zod'
@@ -55,6 +55,7 @@ import {
import { Skeleton } from '@/components/ui/skeleton'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
+import { useStore } from '@/providers/store-provider'
import { useDirectUpload } from '@/hooks/use-direct-upload'
import { useProduct, useUpdateProduct, useDeleteProduct } from '@/hooks/use-product'
import {
@@ -74,8 +75,19 @@ export const Route = createFileRoute('/_authenticated/$storeId/products/$product
// Helpers
// ---------------------------------------------------------------------------
-function productToFormValues(product: Product): ProductFormValues {
- const master = product.master_variant
+function productToFormValues(product: Product, currencies: string[]): ProductFormValues {
+ const master = product.default_variant
+ const basePrices = master?.prices?.filter((p) => !p.price_list_id) ?? []
+
+ // Build prices array for all store currencies, filling in existing values
+ const prices = currencies.map((currency) => {
+ const existing = basePrices.find((p) => p.currency === currency)
+ return {
+ currency,
+ amount: existing?.amount ? Number(existing.amount) : null,
+ compare_at_amount: existing?.compare_at_amount ? Number(existing.compare_at_amount) : null,
+ }
+ })
return {
name: product.name,
@@ -86,10 +98,7 @@ function productToFormValues(product: Product): ProductFormValues {
discontinue_on: product.discontinue_on ?? null,
category_ids: product.categories?.map((t) => t.id) ?? [],
tags: product.tags?.map((t: any) => t.name ?? t) ?? [],
- price: master?.price?.amount ? Number(master.price.amount) : undefined,
- compare_at_price: master?.original_price?.amount
- ? Number(master.original_price.amount)
- : null,
+ prices,
cost_price: product.cost_price ? Number(product.cost_price) : null,
sku: master?.sku ?? '',
barcode: master?.barcode ?? '',
@@ -131,6 +140,7 @@ function ProductForm({ product }: { product: Product }) {
const confirm = useConfirm()
const { productId, storeId } = Route.useParams()
const router = useRouter()
+ const { currencies } = useStore()
const updateProduct = useUpdateProduct()
const deleteProduct = useDeleteProduct()
const hasVariants = (product.variant_count ?? 0) > 0
@@ -138,12 +148,12 @@ function ProductForm({ product }: { product: Product }) {
const form = useForm<ProductFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
resolver: zodResolver(productFormSchema) as any,
- defaultValues: productToFormValues(product),
+ defaultValues: productToFormValues(product, currencies),
})
useEffect(() => {
- form.reset(productToFormValues(product))
- }, [product, form])
+ form.reset(productToFormValues(product, currencies))
+ }, [product, form, currencies])
const onSubmit = async (data: ProductFormValues) => {
try {
@@ -455,51 +465,66 @@ function MediaThumbnail({
// ---------------------------------------------------------------------------
function PricingCard({ form }: FormCardProps) {
+ const prices = form.watch('prices') ?? []
+
return (
<Card>
<CardHeader>
<CardTitle>Pricing</CardTitle>
</CardHeader>
- <CardContent className="flex flex-col gap-4">
- <div className="grid grid-cols-2 gap-4">
- <Field>
- <FieldLabel htmlFor="price">Price</FieldLabel>
- <Input
- id="price"
- type="number"
- step="0.01"
- min="0"
- placeholder="0.00"
- {...form.register('price')}
- />
- </Field>
- <Field>
- <FieldLabel htmlFor="compare_at_price">Compare at price</FieldLabel>
+ <CardContent className="p-0">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b text-left text-muted-foreground">
+ <th className="px-4 py-2 font-medium">Currency</th>
+ <th className="px-4 py-2 font-medium">Amount</th>
+ <th className="px-4 py-2 font-medium">
+ Compare at amount
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {prices.map((_, index) => (
+ <tr key={form.getValues(`prices.${index}.currency`)} className="border-b last:border-0">
+ <td className="px-4 py-2 font-medium">
+ {form.getValues(`prices.${index}.currency`)}
+ </td>
+ <td className="px-4 py-2">
+ <Input
+ type="number"
+ step="0.01"
+ min="0"
+ placeholder="0.00"
+ {...form.register(`prices.${index}.amount`)}
+ />
+ </td>
+ <td className="px-4 py-2">
+ <Input
+ type="number"
+ step="0.01"
+ min="0"
+ placeholder="0.00"
+ {...form.register(`prices.${index}.compare_at_amount`)}
+ />
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ <div className="p-4 border-t">
+ <Field className="max-w-[50%]">
+ <FieldLabel htmlFor="cost_price">Cost price</FieldLabel>
<Input
- id="compare_at_price"
+ id="cost_price"
type="number"
step="0.01"
min="0"
placeholder="0.00"
- {...form.register('compare_at_price')}
+ {...form.register('cost_price')}
/>
- <p className="text-xs text-muted-foreground">
- Original price shown as strikethrough
- </p>
+ <p className="text-xs text-muted-foreground">Not visible to customers</p>
</Field>
</div>
- <Field className="max-w-[50%]">
- <FieldLabel htmlFor="cost_price">Cost price</FieldLabel>
- <Input
- id="cost_price"
- type="number"
- step="0.01"
- min="0"
- placeholder="0.00"
- {...form.register('cost_price')}
- />
- <p className="text-xs text-muted-foreground">Not visible to customers</p>
- </Field>
</CardContent>
</Card>
)
diff --git a/packages/admin/src/schemas/product.ts b/packages/admin/src/schemas/product.ts
index b5af510dcc..3172511e55 100644
--- a/packages/admin/src/schemas/product.ts
+++ b/packages/admin/src/schemas/product.ts
@@ -1,5 +1,11 @@
import { z } from 'zod/v4'
+export const priceSchema = z.object({
+ currency: z.string(),
+ amount: z.coerce.number().nullable().optional(),
+ compare_at_amount: z.coerce.number().nullable().optional(),
+})
+
export const productFormSchema = z.object({
// General
name: z.string().min(1, 'Name is required'),
@@ -16,8 +22,7 @@ export const productFormSchema = z.object({
tags: z.array(z.string()).optional(),
// Pricing (master variant)
- price: z.coerce.number().optional(),
- compare_at_price: z.coerce.number().nullable().optional(),
+ prices: z.array(priceSchema).optional(),
cost_price: z.coerce.number().nullable().optional(),
// Inventory (master variant)
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb b/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb
index e3eae4b8a4..54645ee3a9 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb
@@ -10,20 +10,13 @@ module Spree
# to Rails `_attributes` format (e.g. `taxon_rules_attributes: [...]`) based on
# the model's `accepts_nested_attributes_for` declarations.
#
- # This runs automatically in the ResourceController's `permitted_params` method,
- # eliminating boilerplate ID resolution and nested attribute transformation in
- # individual controllers and services.
+ # Uses `prepend` so it always wraps `permitted_params` regardless of which
+ # controller in the hierarchy defines it — no manual calls needed.
module ParamsNormalizer
extend ActiveSupport::Concern
- protected
-
- # Override permitted_params to apply normalization after permitting
- def permitted_params
- normalize_params(super)
- end
+ private
- # Normalize params: resolve prefixed IDs and convert nested attributes
def normalize_params(permitted)
hash = permitted.to_h.with_indifferent_access
hash = resolve_prefixed_ids(hash)
@@ -31,13 +24,6 @@ module Spree
ActionController::Parameters.new(hash).permit!
end
- private
-
- # Recursively resolve prefixed IDs in params.
- #
- # - Params ending in `_id` with string values matching prefix format → decoded to integer
- # - Params ending in `_ids` with array values → each element decoded
- # - Nested hashes and arrays of hashes are processed recursively
def resolve_prefixed_ids(hash)
hash.each_with_object({}.with_indifferent_access) do |(key, value), result|
result[key] = case
@@ -55,33 +41,36 @@ module Spree
end
end
- # Convert flat nested arrays to Rails _attributes format.
- #
- # Uses the model's `nested_attributes_options` to detect which keys
- # should be renamed. For example, if Spree::Taxon has
- # `accepts_nested_attributes_for :taxon_rules`, then:
- #
- # { taxon_rules: [{type: "...", value: "..."}] }
- #
- # becomes:
- #
- # { taxon_rules_attributes: [{type: "...", value: "..."}] }
- def normalize_nested_attributes(hash)
- return hash unless model_class.respond_to?(:nested_attributes_options)
+ def normalize_nested_attributes(hash, klass = model_class)
+ return hash unless klass.respond_to?(:nested_attributes_options)
- nested_keys = model_class.nested_attributes_options.keys.map(&:to_s)
+ nested_keys = klass.nested_attributes_options.keys.map(&:to_s)
return hash if nested_keys.empty?
hash.each_with_object({}.with_indifferent_access) do |(key, value), result|
key_str = key.to_s
if nested_keys.include?(key_str) && !key_str.end_with?('_attributes')
- result["#{key_str}_attributes"] = value
+ child_class = klass.reflect_on_association(key_str)&.klass
+ result["#{key_str}_attributes"] = normalize_nested_values(value, child_class)
else
result[key] = value
end
end
end
+ def normalize_nested_values(value, child_class)
+ return value unless child_class
+
+ case value
+ when Array
+ value.map { |v| v.is_a?(Hash) ? normalize_nested_attributes(v.with_indifferent_access, child_class) : v }
+ when Hash
+ normalize_nested_attributes(value.with_indifferent_access, child_class)
+ else
+ value
+ end
+ end
+
def prefixed_id?(value)
Spree::PrefixedId.prefixed_id?(value)
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index b0bb0d6024..7c7b55b4b1 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -3,15 +3,6 @@ module Spree
module V3
module Admin
class ProductsController < ResourceController
- # PATCH /api/v3/admin/products/:id
- def update
- if @resource.update(update_params)
- render json: serialize_resource(@resource)
- else
- render_validation_error(@resource.errors)
- end
- end
-
# POST /api/v3/admin/products/:id/clone
def clone
@resource = find_resource
@@ -69,6 +60,7 @@ module Spree
*Spree::PermittedAttributes.product_attributes,
tags: [],
category_ids: [],
+ prices: [:amount, :compare_at_amount, :currency],
variants: [
:id, :sku, :barcode, :price, :compare_at_price,
:cost_price, :cost_currency,
@@ -86,27 +78,6 @@ module Spree
def search_provider
@search_provider ||= Spree::SearchProvider::Database.new(current_store)
end
-
- def update_params
- p = permitted_params.to_h.with_indifferent_access
-
- # Map 6.0 API name (category_ids) to model column (taxon_ids)
- if p.key?(:category_ids)
- p[:taxon_ids] = Array(p.delete(:category_ids)).filter_map do |id|
- id.to_s.include?('_') ? Spree::Taxon.decode_prefixed_id(id) : id
- end
- end
-
- if p.key?(:taxon_ids)
- other_store_taxon_ids = @resource.taxons
- .joins(:taxonomy)
- .where.not(spree_taxonomies: { store_id: current_store.id })
- .pluck(:id)
- p[:taxon_ids] = (Array(p[:taxon_ids]) + other_store_taxon_ids).uniq
- end
-
- p
- end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
index b02e069d9e..b0e26bf894 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -234,7 +234,7 @@ module Spree
#
# Override in subclass for custom parameter handling
def permitted_params
- params.permit(permitted_attributes)
+ normalize_params(params.permit(permitted_attributes))
end
# Returns the permitted attributes list for the model
diff --git a/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
index 266aefbcdb..dae809eaf1 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
@@ -5,12 +5,10 @@ module Spree
# Admin API Category Serializer
# Full category data including admin-only fields
class CategorySerializer < V3::CategorySerializer
- typelize pretty_name: :string, lft: :number, rgt: :number,
- hide_from_nav: :boolean, sort_order: :string, rules_match_policy: :string,
- automatic: :boolean
+ typelize pretty_name: :string, lft: :number, rgt: :number, sort_order: :string
# Admin-only attributes
- attributes :pretty_name, :lft, :rgt, :hide_from_nav, :sort_order, :rules_match_policy, :automatic
+ attributes :pretty_name, :lft, :rgt, created_at: :iso8601, updated_at: :iso8601
# Override inherited associations to use admin serializers
one :parent,
diff --git a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
index 8313308e03..3d4fbc884e 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
@@ -20,7 +20,8 @@ module Spree
attributes :last_ip_address, :considered_risky,
:confirmation_delivered, :store_owner_notification_delivered,
:payment_total, :display_payment_total,
- canceled_at: :iso8601, approved_at: :iso8601
+ canceled_at: :iso8601, approved_at: :iso8601,
+ created_at: :iso8601, updated_at: :iso8601
attribute :internal_note do |order|
order.internal_note&.to_plain_text.presence
diff --git a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
index b09328853e..ffb40f5c13 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
@@ -21,8 +21,6 @@ module Spree
mailer_logo_url: [:string, nullable: true]
attributes :id, :name, :url, :code,
- :default_currency, :default_locale,
- :supported_currencies, :supported_locales,
:mail_from_address, :customer_support_email,
:new_order_notifications_email,
:description, :address, :contact_phone,
@@ -30,6 +28,22 @@ module Spree
:default,
created_at: :iso8601, updated_at: :iso8601
+ attribute :default_currency do |store|
+ store.default_market&.currency
+ end
+
+ attribute :default_locale do |store|
+ store.default_market&.default_locale
+ end
+
+ attribute :supported_currencies do |store|
+ store.supported_currencies_list.map(&:iso_code)
+ end
+
+ attribute :supported_locales do |store|
+ store.supported_locales_list
+ end
+
attribute :logo_url do |store|
store.logo.attached? ? Rails.application.routes.url_helpers.url_for(store.logo) : nil
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/countries_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/countries_controller_spec.rb
index 2016d2582b..aff09aa634 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/countries_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/countries_controller_spec.rb
@@ -21,7 +21,7 @@ RSpec.describe Spree::Api::V3::Admin::CountriesController, type: :controller do
subject
total_countries = Spree::Country.count
expect(json_response['data'].length).to eq(total_countries)
- expect(json_response['meta']['total_count']).to eq(total_countries)
+ expect(json_response['meta']['count']).to eq(total_countries)
end
it 'returns countries ordered by name' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
index 672ad80b0a..d02a006047 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
@@ -70,7 +70,6 @@ RSpec.describe Spree::Api::V3::Admin::Products::VariantsController, type: :contr
post :create, params: {
product_id: product.prefixed_id,
sku: 'MULTI-001',
- price: 19.99,
options: [{ name: option_type.name, value: 'New Value' }],
prices: [
{ currency: 'USD', amount: 19.99, compare_at_amount: 24.99 },
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
index 9c188049aa..752c68d7b7 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
@@ -174,8 +174,6 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
name: 'Premium T-Shirt',
description: 'A premium cotton t-shirt',
status: 'draft',
- price: 29.99,
- compare_at_price: 39.99,
cost_price: 8.50,
sku: 'PREM-TEE',
shipping_category_id: shipping_category.id,
@@ -196,7 +194,6 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
weight_unit: 'kg',
dimensions_unit: 'cm',
track_inventory: true,
- total_on_hand: 50,
prices: [
{ currency: 'USD', amount: 29.99, compare_at_amount: 39.99 },
{ currency: 'EUR', amount: 27.99 },
@@ -208,7 +205,6 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
options: [{ name: 'size', value: 'Medium' }],
weight: 0.22,
track_inventory: true,
- total_on_hand: 100,
prices: [
{ currency: 'USD', amount: 29.99 },
{ currency: 'EUR', amount: 27.99 },
@@ -220,7 +216,6 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
options: [{ name: 'size', value: 'Large' }],
weight: 0.25,
track_inventory: true,
- total_on_hand: 75,
prices: [
{ currency: 'USD', amount: 31.99 },
{ currency: 'EUR', amount: 29.99 },
@@ -243,7 +238,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
expect(created).to be_present
# Product attributes
- expect(created.description.to_plain_text).to include('premium cotton')
+ expect(created.description).to include('premium cotton')
expect(created.status).to eq('draft')
expect(created.slug).to eq('premium-t-shirt')
expect(created.meta_title).to eq('Premium T-Shirt')
@@ -254,8 +249,6 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
# Master variant
master = created.master
expect(master.sku).to eq('PREM-TEE')
- expect(master.price.to_f).to eq(29.99)
- expect(master.compare_at_price.to_f).to eq(39.99)
expect(master.cost_price.to_f).to eq(8.50)
# Variants
@@ -267,7 +260,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
expect(small.width.to_f).to eq(30.0)
expect(small.height.to_f).to eq(40.0)
expect(small.depth.to_f).to eq(2.0)
- expect(small.option_values.first.name).to eq('Small')
+ expect(small.option_values.first.presentation).to eq('Small')
expect(small.option_values.first.option_type.name).to eq('size')
# Multi-currency prices
@@ -279,7 +272,6 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
medium = created.variants.find_by(sku: 'PREM-TEE-M')
expect(medium).to be_present
- expect(medium.total_on_hand).to eq(100)
large = created.variants.find_by(sku: 'PREM-TEE-L')
expect(large).to be_present
@@ -379,7 +371,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
small = updated.variants.find_by(sku: 'UPD-SHIRT-S')
expect(small).to be_present
expect(small.weight.to_f).to eq(0.3)
- expect(small.option_values.first.name).to eq('Small')
+ expect(small.option_values.first.presentation).to eq('Small')
# Multi-currency prices on small variant
expect(small.prices.find_by(currency: 'USD').amount.to_f).to eq(34.99)
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 8da0709665..006df427fa 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -204,6 +204,20 @@ module Spree
self.tag_list = tags
end
+ # Sets prices on the master variant.
+ # Accepts array of { currency:, amount:, compare_at_amount: } hashes.
+ def prices=(prices_params)
+ find_or_build_master.prices = prices_params
+ end
+
+ # Maps 6.0 API name (category_ids) to model column (taxon_ids).
+ # Accepts both prefixed IDs and raw integer IDs.
+ def category_ids=(ids)
+ self.taxon_ids = Array(ids).filter_map do |id|
+ id.to_s.include?('_') ? Spree::Taxon.decode_prefixed_id(id) : id
+ end
+ end
+
# Syncs variants from an array of hashes.
# Creates new variants, updates existing ones (matched by :id), and removes unlisted ones.
# Must be called on a persisted product (use after_save or call explicitly after create).
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index 57050a31b0..8c92fb028b 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -36,7 +36,7 @@ module Spree
with_options inverse_of: :variant do
has_many :inventory_units
has_many :line_items
- has_many :stock_items, dependent: :destroy
+ has_many :stock_items, dependent: :destroy, autosave: true
end
has_many :orders, through: :line_items
@@ -54,7 +54,8 @@ module Spree
has_many :prices,
class_name: 'Spree::Price',
dependent: :destroy,
- inverse_of: :variant
+ inverse_of: :variant,
+ autosave: true
has_many :wished_items, dependent: :destroy
@@ -77,7 +78,6 @@ module Spree
validates :weight_unit, inclusion: { in: WEIGHT_UNITS }, allow_blank: true
after_create :create_stock_items
- after_create :apply_pending_stock_items, if: :pending_stock_items?
after_create :set_master_out_of_stock, unless: :is_master?
after_commit :clear_line_items_cache, on: :update
@@ -459,26 +459,7 @@ module Spree
prices_params.each do |price_data|
price_data = price_data.to_h.with_indifferent_access
currencies_in_payload << price_data[:currency]
-
- if persisted?
- set_price(price_data[:currency], price_data[:amount], price_data[:compare_at_amount])
- else
- # Check default_price first (built via price= setter)
- if default_price && default_price.new_record? && default_price.currency == price_data[:currency]
- default_price.amount = price_data[:amount]
- default_price.compare_at_amount = price_data[:compare_at_amount] if price_data[:compare_at_amount].present?
- else
- # Replace any existing in-memory price for this currency
- existing = prices.detect { |p| p.currency == price_data[:currency] && p.new_record? }
- if existing
- existing.amount = price_data[:amount]
- existing.compare_at_amount = price_data[:compare_at_amount] if price_data[:compare_at_amount].present?
- else
- price = prices.build(currency: price_data[:currency], amount: price_data[:amount])
- price.compare_at_amount = price_data[:compare_at_amount] if price_data[:compare_at_amount].present?
- end
- end
- end
+ set_price(price_data[:currency], price_data[:amount], price_data[:compare_at_amount])
end
# Remove base prices for currencies not in the payload
@@ -493,12 +474,17 @@ module Spree
def stock_items=(stock_items_params)
return super if stock_items_params.blank? || stock_items_params.first.is_a?(Spree::StockItem)
- if new_record?
- @pending_stock_items_params = stock_items_params
- return
+ location_ids_in_payload = []
+
+ stock_items_params.each do |stock_data|
+ stock_data = stock_data.to_h.with_indifferent_access
+ location = Spree::StockLocation.find_by_param(stock_data[:stock_location_id])
+ location_ids_in_payload << location.id
+ set_stock(stock_data[:count_on_hand], stock_data[:backorderable], location)
end
- apply_stock_items(stock_items_params)
+ # Soft-delete stock items for locations not in the payload
+ stock_items.where.not(stock_location_id: location_ids_in_payload).destroy_all if persisted?
end
# Sets the base price (global price, not for a price list) for the given currency.
@@ -528,16 +514,18 @@ module Spree
Spree::Pricing::Resolver.new(context).resolve
end
- # Sets the stock for the variant
+ # Sets the stock for the variant at a given location.
+ # Mirrors set_price: find-or-initialize, set attrs, save only if persisted.
# @param count_on_hand [Integer] the count on hand
# @param backorderable [Boolean] the backorderable flag
- # @param stock_location [Spree::StockLocation] the stock location to set the stock for
+ # @param stock_location [Spree::StockLocation] the stock location (defaults to store default)
# @return [void]
- def set_stock(count_on_hand, backorderable = nil)
- stock_item = stock_items.find_or_initialize_by(stock_location: default_stock_location)
+ def set_stock(count_on_hand, backorderable = nil, stock_location = nil)
+ stock_location ||= default_stock_location
+ stock_item = stock_items.find_or_initialize_by(stock_location: stock_location)
stock_item.count_on_hand = count_on_hand
stock_item.backorderable = backorderable if backorderable.present?
- stock_item.save!
+ stock_item.save! if persisted?
end
def default_stock_location
@@ -665,36 +653,6 @@ module Spree
end
end
- def pending_stock_items?
- @pending_stock_items_params.present?
- end
-
- def apply_pending_stock_items
- return unless @pending_stock_items_params
-
- apply_stock_items(@pending_stock_items_params)
- @pending_stock_items_params = nil
- end
-
- def apply_stock_items(stock_items_params)
- location_ids_in_payload = []
-
- stock_items_params.each do |stock_data|
- stock_data = stock_data.to_h.with_indifferent_access
- location_id = stock_data[:stock_location_id]
- location = if Spree::PrefixedId.prefixed_id?(location_id)
- Spree::StockLocation.find_by_prefix_id!(location_id)
- else
- Spree::StockLocation.find(location_id)
- end
- location_ids_in_payload << location.id
- set_stock(stock_data[:count_on_hand], stock_data[:backorderable], location)
- end
-
- # Soft-delete stock items for locations not in the payload
- stock_items.where.not(stock_location_id: location_ids_in_payload).update_all(deleted_at: Time.current)
- end
-
def ensure_not_in_complete_orders
if orders.complete.any?
errors.add(:base, :cannot_destroy_if_attached_to_line_items)