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.

Admin API - Product catalog

Damian Legawiec66ef50487c87
diff --git a/packages/sdk/src/types/generated/AdminOptionType.ts b/packages/sdk/src/types/generated/AdminOptionType.ts
new file mode 100644
index 0000000000..628c3db647
--- /dev/null
+++ b/packages/sdk/src/types/generated/AdminOptionType.ts
@@ -0,0 +1,15 @@
+// Typelizer digest e080964a17d87cba0fd4d11492b024d3
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {StoreOptionValue} from '@/types'
+
+type AdminOptionType = {
+ id: string;
+ name: string;
+ presentation: string;
+ position: number;
+ filterable: boolean;
+ option_values: Array<StoreOptionValue>;
+}
+
+export default AdminOptionType;
diff --git a/packages/sdk/src/zod/generated/AdminOptionType.ts b/packages/sdk/src/zod/generated/AdminOptionType.ts
new file mode 100644
index 0000000000..b703fdd411
--- /dev/null
+++ b/packages/sdk/src/zod/generated/AdminOptionType.ts
@@ -0,0 +1,14 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+import { StoreOptionValueSchema } from './StoreOptionValue';
+
+export const AdminOptionTypeSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ presentation: z.string(),
+ position: z.number(),
+ filterable: z.boolean(),
+ option_values: z.array(StoreOptionValueSchema),
+});
+
+export type AdminOptionType = z.infer<typeof AdminOptionTypeSchema>;
diff --git a/spree/api/ADMIN_API_PLAN.md b/spree/api/ADMIN_API_PLAN.md
index b5fa4b4ffa..1c70462604 100644
--- a/spree/api/ADMIN_API_PLAN.md
+++ b/spree/api/ADMIN_API_PLAN.md
@@ -190,32 +190,32 @@ Here's the endpoint list we need to implement:
- [ ] `DELETE /api/v3/admin/auth/logout` — Invalidate JWT token
### Products (⭐ high priority)
-- [ ] `GET /api/v3/admin/products` — List products (with Ransack filtering, sorting, pagination)
-- [ ] `GET /api/v3/admin/products/:id` — Show product
-- [ ] `POST /api/v3/admin/products` — Create product (with nested variants, prices, taxon_ids)
-- [ ] `PATCH /api/v3/admin/products/:id` — Update product
-- [ ] `DELETE /api/v3/admin/products/:id` — Soft-delete product
-- [ ] `POST /api/v3/admin/products/:id/clone` — Clone product
+- [x] `GET /api/v3/admin/products` — List products (with Ransack filtering, sorting, pagination)
+- [x] `GET /api/v3/admin/products/:id` — Show product
+- [x] `POST /api/v3/admin/products` — Create product (with nested variants, prices, taxon_ids)
+- [x] `PATCH /api/v3/admin/products/:id` — Update product
+- [x] `DELETE /api/v3/admin/products/:id` — Soft-delete product
+- [x] `POST /api/v3/admin/products/:id/clone` — Clone product
- [ ] `PATCH /api/v3/admin/products/bulk_update` — Bulk update products (status, taxons, tags)
### Variants (nested under Products)
-- [ ] `GET /api/v3/admin/products/:product_id/variants` — List variants
-- [ ] `GET /api/v3/admin/products/:product_id/variants/:id` — Show variant
-- [ ] `POST /api/v3/admin/products/:product_id/variants` — Create variant (with nested prices)
-- [ ] `PATCH /api/v3/admin/products/:product_id/variants/:id` — Update variant
-- [ ] `DELETE /api/v3/admin/products/:product_id/variants/:id` — Soft-delete variant
+- [x] `GET /api/v3/admin/products/:product_id/variants` — List variants
+- [x] `GET /api/v3/admin/products/:product_id/variants/:id` — Show variant
+- [x] `POST /api/v3/admin/products/:product_id/variants` — Create variant (with nested prices)
+- [x] `PATCH /api/v3/admin/products/:product_id/variants/:id` — Update variant
+- [x] `DELETE /api/v3/admin/products/:product_id/variants/:id` — Soft-delete variant
### Prices (nested under Variants)
-- [ ] `GET /api/v3/admin/variants/:variant_id/prices` — List prices for variant
-- [ ] `POST /api/v3/admin/variants/:variant_id/prices` — Create price
-- [ ] `PATCH /api/v3/admin/variants/:variant_id/prices/:id` — Update price
-- [ ] `DELETE /api/v3/admin/variants/:variant_id/prices/:id` — Delete price
+- [x] `GET /api/v3/admin/variants/:variant_id/prices` — List prices for variant
+- [x] `POST /api/v3/admin/variants/:variant_id/prices` — Create price
+- [x] `PATCH /api/v3/admin/variants/:variant_id/prices/:id` — Update price
+- [x] `DELETE /api/v3/admin/variants/:variant_id/prices/:id` — Delete price
### Product Assets (nested under Products)
-- [ ] `GET /api/v3/admin/products/:product_id/assets` — List product assets (filterable by type: image, video, etc.)
-- [ ] `POST /api/v3/admin/products/:product_id/assets` — Create asset. Two modes: (1) file upload via multipart/form-data, (2) URL via `source_url` param (triggers async download). Params: type, alt, position, variant_ids
-- [ ] `PATCH /api/v3/admin/products/:product_id/assets/:id` — Update asset (alt, position, variant assignment)
-- [ ] `DELETE /api/v3/admin/products/:product_id/assets/:id` — Delete asset
+- [x] `GET /api/v3/admin/products/:product_id/assets` — List product assets (filterable by type: image, video, etc.)
+- [x] `POST /api/v3/admin/products/:product_id/assets` — Create asset. Two modes: (1) file upload via multipart/form-data, (2) URL via `source_url` param (triggers async download). Params: type, alt, position, variant_ids
+- [x] `PATCH /api/v3/admin/products/:product_id/assets/:id` — Update asset (alt, position, variant assignment)
+- [x] `DELETE /api/v3/admin/products/:product_id/assets/:id` — Delete asset
### Digital Assets (nested under Products)
- [ ] `GET /api/v3/admin/products/:product_id/digital_assets` — List digital assets
@@ -224,36 +224,36 @@ Here's the endpoint list we need to implement:
- [ ] `DELETE /api/v3/admin/products/:product_id/digital_assets/:id` — Delete digital asset
### Option Types
-- [ ] `GET /api/v3/admin/option_types` — List option types
-- [ ] `GET /api/v3/admin/option_types/:id` — Show option type
-- [ ] `POST /api/v3/admin/option_types` — Create option type
-- [ ] `PATCH /api/v3/admin/option_types/:id` — Update option type
-- [ ] `DELETE /api/v3/admin/option_types/:id` — Delete option type
+- [x] `GET /api/v3/admin/option_types` — List option types
+- [x] `GET /api/v3/admin/option_types/:id` — Show option type
+- [x] `POST /api/v3/admin/option_types` — Create option type
+- [x] `PATCH /api/v3/admin/option_types/:id` — Update option type
+- [x] `DELETE /api/v3/admin/option_types/:id` — Delete option type
### Option Values (nested under Option Types)
-- [ ] `GET /api/v3/admin/option_types/:option_type_id/option_values` — List option values
-- [ ] `POST /api/v3/admin/option_types/:option_type_id/option_values` — Create option value
-- [ ] `PATCH /api/v3/admin/option_types/:option_type_id/option_values/:id` — Update option value
-- [ ] `DELETE /api/v3/admin/option_types/:option_type_id/option_values/:id` — Delete option value
+- [x] `GET /api/v3/admin/option_types/:option_type_id/option_values` — List option values
+- [x] `POST /api/v3/admin/option_types/:option_type_id/option_values` — Create option value
+- [x] `PATCH /api/v3/admin/option_types/:option_type_id/option_values/:id` — Update option value
+- [x] `DELETE /api/v3/admin/option_types/:option_type_id/option_values/:id` — Delete option value
### Taxonomies
-- [ ] `GET /api/v3/admin/taxonomies` — List taxonomies
-- [ ] `GET /api/v3/admin/taxonomies/:id` — Show taxonomy
-- [ ] `POST /api/v3/admin/taxonomies` — Create taxonomy
-- [ ] `PATCH /api/v3/admin/taxonomies/:id` — Update taxonomy
-- [ ] `DELETE /api/v3/admin/taxonomies/:id` — Delete taxonomy
+- [x] `GET /api/v3/admin/taxonomies` — List taxonomies
+- [x] `GET /api/v3/admin/taxonomies/:id` — Show taxonomy
+- [x] `POST /api/v3/admin/taxonomies` — Create taxonomy
+- [x] `PATCH /api/v3/admin/taxonomies/:id` — Update taxonomy
+- [x] `DELETE /api/v3/admin/taxonomies/:id` — Delete taxonomy
### Taxons (nested under Taxonomies)
-- [ ] `GET /api/v3/admin/taxonomies/:taxonomy_id/taxons` — List taxons
-- [ ] `GET /api/v3/admin/taxonomies/:taxonomy_id/taxons/:id` — Show taxon
-- [ ] `POST /api/v3/admin/taxonomies/:taxonomy_id/taxons` — Create taxon
-- [ ] `PATCH /api/v3/admin/taxonomies/:taxonomy_id/taxons/:id` — Update taxon
-- [ ] `DELETE /api/v3/admin/taxonomies/:taxonomy_id/taxons/:id` — Delete taxon
-- [ ] `PATCH /api/v3/admin/taxonomies/:taxonomy_id/taxons/:id/reposition` — Reposition taxon in tree
+- [x] `GET /api/v3/admin/taxonomies/:taxonomy_id/taxons` — List taxons
+- [x] `GET /api/v3/admin/taxonomies/:taxonomy_id/taxons/:id` — Show taxon
+- [x] `POST /api/v3/admin/taxonomies/:taxonomy_id/taxons` — Create taxon
+- [x] `PATCH /api/v3/admin/taxonomies/:taxonomy_id/taxons/:id` — Update taxon
+- [x] `DELETE /api/v3/admin/taxonomies/:taxonomy_id/taxons/:id` — Delete taxon
+- [x] `PATCH /api/v3/admin/taxonomies/:taxonomy_id/taxons/:id/reposition` — Reposition taxon in tree
### Taxons (flat, top-level for convenience)
-- [ ] `GET /api/v3/admin/taxons` — List all taxons across taxonomies
-- [ ] `GET /api/v3/admin/taxons/:id` — Show taxon
+- [x] `GET /api/v3/admin/taxons` — List all taxons across taxonomies
+- [x] `GET /api/v3/admin/taxons/:id` — Show taxon
### Classifications (Product-Taxon assignments, nested under Taxons)
- [ ] `GET /api/v3/admin/taxons/:taxon_id/classifications` — List products in taxon
diff --git a/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb
new file mode 100644
index 0000000000..45488c3118
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb
@@ -0,0 +1,74 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class OptionTypesController < ResourceController
+ # POST /api/v3/admin/option_types
+ def create
+ authorize!(:create, Spree::OptionType)
+
+ result = Spree.option_type_create_service.call(
+ params: option_type_service_params
+ )
+
+ if result.success?
+ @resource = result.value[:option_type]
+ render json: serialize_resource(@resource), status: :created
+ else
+ render_result_error(result)
+ end
+ end
+
+ # PATCH /api/v3/admin/option_types/:id
+ def update
+ result = Spree.option_type_update_service.call(
+ option_type: @resource,
+ params: option_type_service_params
+ )
+
+ if result.success?
+ @resource = result.value[:option_type]
+ render json: serialize_resource(@resource)
+ else
+ render_result_error(result)
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::OptionType
+ end
+
+ def serializer_class
+ Spree.api.admin_option_type_serializer
+ end
+
+ def scope_includes
+ [:option_values]
+ end
+
+ private
+
+ def render_result_error(result)
+ error = result.error
+ errors = error.respond_to?(:value) ? error.value : error
+
+ if errors.is_a?(ActiveModel::Errors)
+ render_validation_error(errors)
+ else
+ render_service_error(error)
+ end
+ end
+
+ def option_type_service_params
+ params.permit(
+ :name, :presentation, :position, :filterable,
+ option_values: [:id, :name, :presentation, :position]
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products/assets_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/assets_controller.rb
new file mode 100644
index 0000000000..a54b847765
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/products/assets_controller.rb
@@ -0,0 +1,61 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Products
+ class AssetsController < ResourceController
+ def create
+ @resource = build_resource
+ authorize_resource!(@resource, :create)
+
+ if @resource.save
+ render json: serialize_resource(@resource), status: :created
+ else
+ render_validation_error(@resource.errors)
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::Asset
+ end
+
+ def serializer_class
+ Spree.api.image_serializer
+ end
+
+ def set_parent
+ @parent = current_store.products.find_by_prefix_id!(params[:product_id])
+ authorize!(:show, @parent)
+ end
+
+ def parent_association
+ :assets
+ end
+
+ def build_resource
+ asset_type = permitted_params[:type] || 'Spree::Image'
+ asset_class = asset_type.safe_constantize
+
+ unless asset_class && asset_class <= Spree::Asset
+ raise ArgumentError, "Invalid asset type: #{asset_type}"
+ end
+
+ # Build through parent association, then set the correct STI type
+ asset = @parent.assets.build(permitted_params.except(:type, :variant_ids))
+ asset.type = asset_class.name
+ asset.viewable = @parent.master if asset.viewable.nil?
+
+ asset
+ end
+
+ def permitted_params
+ params.permit(:alt, :position, :attachment, :type, :viewable_type, :viewable_id, variant_ids: [])
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
new file mode 100644
index 0000000000..a9e1aecfc3
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
@@ -0,0 +1,91 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Products
+ class VariantsController < ResourceController
+ # POST /api/v3/admin/products/:product_id/variants
+ def create
+ authorize!(:create, Spree::Variant)
+
+ result = Spree.variant_create_service.call(
+ product: @parent,
+ params: variant_service_params
+ )
+
+ if result.success?
+ @resource = result.value[:variant]
+ render json: serialize_resource(@resource), status: :created
+ else
+ render_result_error(result)
+ end
+ end
+
+ # PATCH /api/v3/admin/products/:product_id/variants/:id
+ def update
+ result = Spree.variant_update_service.call(
+ variant: @resource,
+ params: variant_service_params
+ )
+
+ if result.success?
+ @resource = result.value[:variant]
+ render json: serialize_resource(@resource)
+ else
+ render_result_error(result)
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::Variant
+ end
+
+ def serializer_class
+ Spree.api.admin_variant_serializer
+ end
+
+ def set_parent
+ @parent = current_store.products.find_by_prefix_id!(params[:product_id])
+ authorize!(:show, @parent)
+ end
+
+ def parent_association
+ :variants_including_master
+ end
+
+ def scope_includes
+ [:prices, stock_items: :stock_location]
+ end
+
+ private
+
+ def render_result_error(result)
+ error = result.error
+ errors = error.respond_to?(:value) ? error.value : error
+
+ if errors.is_a?(ActiveModel::Errors)
+ render_validation_error(errors)
+ else
+ render_service_error(error)
+ end
+ end
+
+ def variant_service_params
+ params.permit(
+ :sku, :barcode, :price, :compare_at_price,
+ :cost_price, :cost_currency,
+ :weight, :height, :width, :depth, :weight_unit, :dimensions_unit,
+ :track_inventory, :tax_category_id,
+ :option_type, :option_value, :total_on_hand, :position,
+ prices: [:amount, :compare_at_amount, :currency],
+ stock_items: [:stock_location_id, :count_on_hand, :backorderable]
+ )
+ end
+ end
+ end
+ end
+ end
+ end
+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
new file mode 100644
index 0000000000..3ada027c1b
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -0,0 +1,152 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class ProductsController < ResourceController
+ # Sort values that require special scopes
+ CUSTOM_SORT_SCOPES = {
+ 'price' => :ascend_by_price,
+ '-price' => :descend_by_price,
+ 'best_selling' => :by_best_selling
+ }.freeze
+
+ # POST /api/v3/admin/products
+ def create
+ authorize!(:create, Spree::Product)
+
+ result = Spree.product_create_service.call(
+ store: current_store,
+ params: product_service_params
+ )
+
+ if result.success?
+ @resource = result.value[:product]
+ render json: serialize_resource(@resource), status: :created
+ else
+ render_result_error(result)
+ end
+ end
+
+ # PATCH /api/v3/admin/products/:id
+ def update
+ result = Spree.product_update_service.call(
+ product: @resource,
+ store: current_store,
+ params: product_service_params
+ )
+
+ if result.success?
+ @resource = result.value[:product]
+ render json: serialize_resource(@resource)
+ else
+ render_result_error(result)
+ end
+ end
+
+ # POST /api/v3/admin/products/:id/clone
+ def clone
+ @resource = find_resource
+ authorize!(:create, @resource)
+
+ result = @resource.duplicate
+ if result.success?
+ render json: serialize_resource(result.value), status: :created
+ else
+ render_service_error(result.error)
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::Product
+ end
+
+ def serializer_class
+ Spree.api.admin_product_serializer
+ end
+
+ def scope_includes
+ [
+ thumbnail: [attachment_attachment: :blob],
+ master: [:prices, stock_items: :stock_location],
+ variants: [:prices, stock_items: :stock_location],
+ variants_including_master: [stock_items: :stock_location]
+ ]
+ end
+
+ def collection_distinct?
+ !custom_sort_requested?
+ end
+
+ def apply_collection_sort(collection)
+ sort_value = sort_param
+ return collection unless sort_value.present?
+
+ scope_method = CUSTOM_SORT_SCOPES[sort_value]
+ return collection unless scope_method
+
+ sorted = collection.reorder(nil)
+ sort_value == 'best_selling' ? sorted.distinct(false).send(scope_method) : sorted.send(scope_method)
+ end
+
+ def ransack_params
+ rp = super
+
+ if sort_param.present? && CUSTOM_SORT_SCOPES.key?(sort_param)
+ rp = rp.is_a?(Hash) ? rp.dup : rp.to_unsafe_h
+ rp.delete('s')
+ end
+
+ rp
+ end
+
+ private
+
+ # Render error from ServiceModule::Result, extracting ActiveModel::Errors
+ # from the ResultError wrapper to get proper validation_error responses.
+ def render_result_error(result)
+ error = result.error
+ errors = error.respond_to?(:value) ? error.value : error
+
+ if errors.is_a?(ActiveModel::Errors)
+ render_validation_error(errors)
+ else
+ render_service_error(error)
+ end
+ end
+
+ def custom_sort_requested?
+ CUSTOM_SORT_SCOPES.key?(sort_param)
+ end
+
+ # Flat JSON params for create/update service.
+ # Accepts the plan's payload format with nested variants array.
+ def product_service_params
+ params.permit(
+ :name, :description, :slug, :status, :price, :sku, :barcode,
+ :available_on, :make_active_at, :discontinue_on,
+ :meta_description, :meta_keywords, :meta_title,
+ :weight, :height, :width, :depth, :weight_unit, :dimensions_unit,
+ :shipping_category_id, :tax_category_id,
+ :cost_currency, :cost_price, :compare_at_price,
+ :track_inventory, :backorderable,
+ tags: [],
+ taxon_ids: [],
+ option_type_ids: [],
+ store_ids: [],
+ variants: [
+ :id, :sku, :barcode, :price, :compare_at_price,
+ :cost_price, :cost_currency,
+ :weight, :height, :width, :depth, :weight_unit, :dimensions_unit,
+ :track_inventory, :tax_category_id,
+ :option_type, :option_value, :total_on_hand, :position,
+ prices: [:amount, :compare_at_amount, :currency]
+ ]
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/taxonomies/taxons_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/taxonomies/taxons_controller.rb
new file mode 100644
index 0000000000..54b3c95827
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/taxonomies/taxons_controller.rb
@@ -0,0 +1,30 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Taxonomies
+ class TaxonsController < ResourceController
+ protected
+
+ def model_class
+ Spree::Taxon
+ end
+
+ def serializer_class
+ Spree.api.admin_taxon_serializer
+ end
+
+ def set_parent
+ @parent = current_store.taxonomies.find_by_prefix_id!(params[:taxonomy_id])
+ authorize!(:show, @parent)
+ end
+
+ def parent_association
+ :taxons
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/taxonomies_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/taxonomies_controller.rb
new file mode 100644
index 0000000000..060a353e33
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/taxonomies_controller.rb
@@ -0,0 +1,19 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class TaxonomiesController < ResourceController
+ protected
+
+ def model_class
+ Spree::Taxonomy
+ end
+
+ def serializer_class
+ Spree.api.admin_taxonomy_serializer
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/taxons_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/taxons_controller.rb
new file mode 100644
index 0000000000..ec39dd0757
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/taxons_controller.rb
@@ -0,0 +1,19 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class TaxonsController < ResourceController
+ protected
+
+ def model_class
+ Spree::Taxon
+ end
+
+ def serializer_class
+ Spree.api.admin_taxon_serializer
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/variants/prices_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/variants/prices_controller.rb
new file mode 100644
index 0000000000..2647f4c52b
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/variants/prices_controller.rb
@@ -0,0 +1,30 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Variants
+ class PricesController < ResourceController
+ protected
+
+ def model_class
+ Spree::Price
+ end
+
+ def serializer_class
+ Spree.api.admin_price_serializer
+ end
+
+ def set_parent
+ @parent = current_store.variants.find_by_prefix_id!(params[:variant_id])
+ authorize!(:show, @parent.product)
+ end
+
+ def parent_association
+ :prices
+ end
+ end
+ end
+ 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 350a94066c..db37878c55 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -80,11 +80,14 @@ module Spree
# Builds a new resource, using parent association when @parent is set
def build_resource
- if @parent.present?
- @parent.send(parent_association).build(permitted_params)
- else
- model_class.new(permitted_params)
- end
+ resource = if @parent.present?
+ @parent.send(parent_association).build(permitted_params)
+ else
+ model_class.new(permitted_params)
+ end
+ resource.store = current_store if resource.respond_to?(:store_id) && resource.store_id.blank?
+ resource.created_by = try_spree_current_user if resource.respond_to?(:created_by_id)
+ resource
end
# Finds a single resource within scope using prefixed ID
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 8dcd57fc25..b8382f2305 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -90,9 +90,31 @@ Spree::Core::Engine.add_routes do
resources :feeds, only: [:show], controller: 'data_feeds', param: :slug
end
- # Webhooks (outside of store namespace — no API key authentication)
- namespace :webhooks do
- post 'payments/:payment_method_id', to: 'payments#create', as: :payment_webhook
+ namespace :admin do
+ # Products
+ resources :products do
+ member do
+ post :clone
+ end
+ resources :variants, controller: 'products/variants'
+ resources :assets, controller: 'products/assets', only: [:index, :create, :update, :destroy]
+ end
+
+ # Variants > Prices
+ resources :variants, only: [] do
+ resources :prices, controller: 'variants/prices', only: [:index, :create, :update, :destroy]
+ end
+
+ # Taxonomies > Taxons
+ resources :taxonomies do
+ resources :taxons, controller: 'taxonomies/taxons'
+ end
+
+ # Taxons (flat, top-level)
+ resources :taxons, only: [:index, :show]
+
+ # Option Types (with nested option_values in payload)
+ resources :option_types
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/option_types_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/option_types_controller_spec.rb
new file mode 100644
index 0000000000..5eef71ed22
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/option_types_controller_spec.rb
@@ -0,0 +1,116 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::OptionTypesController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:option_type) { create(:option_type) }
+ let!(:option_value_1) { create(:option_value, option_type: option_type, position: 1) }
+ let!(:option_value_2) { create(:option_value, option_type: option_type, position: 2) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'returns option types with nested option values' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to be_an(Array)
+
+ ot = json_response['data'].find { |o| o['id'] == option_type.prefixed_id }
+ expect(ot['name']).to eq(option_type.name)
+ expect(ot['option_values']).to be_an(Array)
+ expect(ot['option_values'].length).to eq(2)
+ end
+ end
+
+ describe 'GET #show' do
+ it 'returns the option type with option values' do
+ get :show, params: { id: option_type.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(option_type.prefixed_id)
+ expect(json_response['option_values'].length).to eq(2)
+ end
+ end
+
+ describe 'POST #create' do
+ it 'creates an option type with nested option values' do
+ expect {
+ post :create, params: {
+ name: 'material',
+ presentation: 'Material',
+ option_values: [
+ { name: 'cotton', presentation: 'Cotton', position: 1 },
+ { name: 'silk', presentation: 'Silk', position: 2 }
+ ]
+ }, as: :json
+ }.to change(Spree::OptionType, :count).by(1)
+ .and change(Spree::OptionValue, :count).by(2)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['name']).to eq('material')
+ expect(json_response['option_values'].length).to eq(2)
+ expect(json_response['option_values'].map { |v| v['name'] }).to match_array(%w[cotton silk])
+ end
+
+ it 'creates an option type without option values' do
+ expect {
+ post :create, params: { name: 'size', presentation: 'Size' }, as: :json
+ }.to change(Spree::OptionType, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['name']).to eq('size')
+ end
+
+ context 'with invalid params' do
+ it 'returns validation errors' do
+ post :create, params: { name: '', presentation: '' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('validation_error')
+ end
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'updates option type and syncs option values' do
+ patch :update, params: {
+ id: option_type.prefixed_id,
+ presentation: 'Updated Presentation',
+ option_values: [
+ { id: option_value_1.prefixed_id, name: option_value_1.name, presentation: 'Updated Value 1', position: 1 },
+ { name: 'new-value', presentation: 'New Value', position: 2 }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['presentation']).to eq('Updated Presentation')
+ expect(json_response['option_values'].length).to eq(2)
+
+ # option_value_2 was not in the payload, so it should be deleted
+ expect(Spree::OptionValue.find_by(id: option_value_2.id)).to be_nil
+ end
+
+ it 'updates option type without touching option values' do
+ patch :update, params: {
+ id: option_type.prefixed_id,
+ presentation: 'Just Presentation'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(option_type.reload.option_values.count).to eq(2)
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'deletes the option type' do
+ expect {
+ delete :destroy, params: { id: option_type.prefixed_id }, as: :json
+ }.to change(Spree::OptionType, :count).by(-1)
+
+ expect(response).to have_http_status(:no_content)
+ end
+ end
+end
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
new file mode 100644
index 0000000000..9fbeb07e0c
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
@@ -0,0 +1,176 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::Products::VariantsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:product) { create(:product, stores: [store]) }
+ let!(:variant) { create(:variant, product: product) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'returns variants for the product' do
+ get :index, params: { product_id: product.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to be_an(Array)
+ ids = json_response['data'].map { |v| v['id'] }
+ expect(ids).to include(variant.prefixed_id)
+ end
+
+ context 'with product from another store' do
+ let(:other_store) { create(:store) }
+ let(:other_product) { create(:product, stores: [other_store]) }
+
+ it 'returns 404' do
+ get :index, params: { product_id: other_product.prefixed_id }, as: :json
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+ end
+
+ describe 'GET #show' do
+ it 'returns the variant' do
+ get :show, params: { product_id: product.prefixed_id, id: variant.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(variant.prefixed_id)
+ expect(json_response['sku']).to eq(variant.sku)
+ end
+ end
+
+ describe 'POST #create' do
+ let(:option_type) { create(:option_type) }
+ let(:option_value) { create(:option_value, option_type: option_type) }
+
+ before { product.option_types << option_type }
+
+ it 'creates a variant with option_type and option_value' do
+ expect {
+ post :create, params: {
+ product_id: product.prefixed_id,
+ sku: 'NEW-SKU-001',
+ price: 29.99,
+ option_type: option_type.name,
+ option_value: option_value.name
+ }, as: :json
+ }.to change(product.variants, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['sku']).to eq('NEW-SKU-001')
+ end
+
+ context 'with nested prices and stock_items' do
+ let!(:stock_location_1) { Spree::StockLocation.first || create(:stock_location) }
+ let!(:stock_location_2) { create(:stock_location, name: 'Warehouse 2') }
+
+ it 'creates variant with multi-currency prices and multi-location stock' do
+ expect {
+ post :create, params: {
+ product_id: product.prefixed_id,
+ sku: 'MULTI-001',
+ price: 19.99,
+ option_type: option_type.name,
+ option_value: 'New Value',
+ prices: [
+ { currency: 'USD', amount: 19.99, compare_at_amount: 24.99 },
+ { currency: 'EUR', amount: 17.99 }
+ ],
+ stock_items: [
+ { stock_location_id: stock_location_1.prefixed_id, count_on_hand: 50, backorderable: false },
+ { stock_location_id: stock_location_2.prefixed_id, count_on_hand: 10, backorderable: true }
+ ]
+ }, as: :json
+ }.to change(product.variants, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['sku']).to eq('MULTI-001')
+
+ created_variant = Spree::Variant.find_by(sku: 'MULTI-001')
+ expect(created_variant.prices.find_by(currency: 'USD').amount.to_f).to eq(19.99)
+ expect(created_variant.prices.find_by(currency: 'USD').compare_at_amount.to_f).to eq(24.99)
+ expect(created_variant.prices.find_by(currency: 'EUR').amount.to_f).to eq(17.99)
+
+ si_1 = created_variant.stock_items.find_by(stock_location: stock_location_1)
+ expect(si_1.count_on_hand).to eq(50)
+ expect(si_1.backorderable).to eq(false)
+
+ si_2 = created_variant.stock_items.find_by(stock_location: stock_location_2)
+ expect(si_2.count_on_hand).to eq(10)
+ expect(si_2.backorderable).to eq(true)
+ end
+ end
+
+ context 'with invalid params' do
+ it 'returns validation errors' do
+ post :create, params: {
+ product_id: product.prefixed_id,
+ sku: variant.sku # duplicate SKU
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('validation_error')
+ end
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'updates the variant sku' do
+ patch :update, params: {
+ product_id: product.prefixed_id,
+ id: variant.prefixed_id,
+ sku: 'UPDATED-SKU'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['sku']).to eq('UPDATED-SKU')
+ expect(variant.reload.sku).to eq('UPDATED-SKU')
+ end
+
+ context 'with nested prices' do
+ it 'updates variant prices' do
+ patch :update, params: {
+ product_id: product.prefixed_id,
+ id: variant.prefixed_id,
+ prices: [
+ { currency: 'GBP', amount: 15.99 }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(variant.reload.prices.find_by(currency: 'GBP').amount.to_f).to eq(15.99)
+ end
+ end
+
+ context 'with nested stock_items' do
+ let!(:stock_location) { Spree::StockLocation.first || create(:stock_location) }
+
+ it 'updates stock levels' do
+ patch :update, params: {
+ product_id: product.prefixed_id,
+ id: variant.prefixed_id,
+ stock_items: [
+ { stock_location_id: stock_location.prefixed_id, count_on_hand: 99 }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(variant.reload.stock_items.find_by(stock_location: stock_location).count_on_hand).to eq(99)
+ end
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'soft-deletes the variant' do
+ delete :destroy, params: {
+ product_id: product.prefixed_id,
+ id: variant.prefixed_id
+ }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(variant.reload.deleted_at).not_to be_nil
+ end
+ end
+end
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
new file mode 100644
index 0000000000..c5a1d2013b
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
@@ -0,0 +1,255 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:product) { create(:product, stores: [store]) }
+
+ describe 'GET #index' do
+ subject { get :index, params: {}, as: :json }
+
+ before { request.headers.merge!(headers) }
+
+ it 'returns products list' do
+ subject
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to be_an(Array)
+ expect(json_response['data'].length).to eq(1)
+ expect(json_response['data'].first['id']).to eq(product.prefixed_id)
+ expect(json_response['data'].first['name']).to eq(product.name)
+ end
+
+ it 'includes admin-only fields' do
+ subject
+
+ data = json_response['data'].first
+ expect(data).to have_key('status')
+ end
+
+ it 'returns pagination metadata' do
+ subject
+
+ expect(json_response['meta']).to include('page', 'limit', 'count', 'pages')
+ end
+
+ context 'with ransack filtering' do
+ let!(:other_product) { create(:product, name: 'Unique Widget', stores: [store]) }
+
+ it 'filters by name' do
+ get :index, params: { q: { name_cont: 'Unique' } }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].length).to eq(1)
+ expect(json_response['data'].first['id']).to eq(other_product.prefixed_id)
+ end
+ end
+
+ context 'with sorting' do
+ let!(:second_product) { create(:product, name: 'Alpha Product', stores: [store]) }
+
+ it 'sorts by name ascending' do
+ get :index, params: { sort: 'name' }, as: :json
+
+ names = json_response['data'].map { |p| p['name'] }
+ expect(names).to eq(names.sort)
+ end
+
+ it 'sorts by name descending' do
+ get :index, params: { sort: '-name' }, as: :json
+
+ names = json_response['data'].map { |p| p['name'] }
+ expect(names).to eq(names.sort.reverse)
+ end
+ end
+
+ context 'without authentication' do
+ let(:headers) { {} }
+
+ it 'returns 401 unauthorized' do
+ subject
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+ end
+
+ describe 'GET #show' do
+ subject { get :show, params: { id: product.prefixed_id }, as: :json }
+
+ before { request.headers.merge!(headers) }
+
+ it 'returns the product' do
+ subject
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(product.prefixed_id)
+ expect(json_response['name']).to eq(product.name)
+ expect(json_response['slug']).to eq(product.slug)
+ end
+
+ it 'includes admin-only fields' do
+ subject
+
+ expect(json_response).to have_key('status')
+ end
+
+ context 'with expand' do
+ it 'expands variants' do
+ get :show, params: { id: product.prefixed_id, expand: 'variants' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response).to have_key('variants')
+ end
+ end
+
+ context 'with non-existent product' do
+ it 'returns 404' do
+ get :show, params: { id: 'prod_nonexistent' }, as: :json
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+ end
+
+ describe 'POST #create' do
+ subject { post :create, params: product_params, as: :json }
+
+ before { request.headers.merge!(headers) }
+
+ let(:tax_category) { create(:tax_category) }
+ let(:shipping_category) { create(:shipping_category) }
+ let(:product_params) do
+ {
+ name: 'New Product',
+ price: 19.99,
+ shipping_category_id: shipping_category.id
+ }
+ end
+
+ it 'creates a product' do
+ expect { subject }.to change(Spree::Product, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['name']).to eq('New Product')
+ end
+
+ context 'with nested variants, prices, tags, and taxon_ids' do
+ let(:taxonomy) { create(:taxonomy, store: store) }
+ let(:taxon) { create(:taxon, taxonomy: taxonomy) }
+ let(:product_params) do
+ {
+ name: 'Test product',
+ price: 10.99,
+ shipping_category_id: shipping_category.id,
+ tax_category_id: tax_category.prefixed_id,
+ taxon_ids: [taxon.prefixed_id],
+ tags: ['eco', 'best-seller'],
+ variants: [
+ {
+ option_type: 'size',
+ option_value: 'small',
+ sku: 'TEST-SM',
+ total_on_hand: 10,
+ track_inventory: true,
+ weight: 0.5,
+ prices: [
+ { currency: 'USD', amount: 10.99 },
+ { currency: 'EUR', amount: 9.99 }
+ ]
+ }
+ ]
+ }
+ end
+
+ it 'creates product with all nested data' do
+ expect { subject }.to change(Spree::Product, :count).by(1)
+ .and change(Spree::Variant, :count).by(2) # master + variant
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['name']).to eq('Test product')
+
+ created_product = Spree::Product.find_by(name: 'Test product')
+ expect(created_product.tag_list).to match_array(['eco', 'best-seller'])
+ expect(created_product.taxons).to include(taxon)
+ expect(created_product.tax_category).to eq(tax_category)
+
+ variant = created_product.variants.first
+ expect(variant.sku).to eq('TEST-SM')
+ expect(variant.option_values.first.presentation).to eq('small')
+ expect(variant.prices.count).to be >= 2
+ expect(variant.prices.find_by(currency: 'EUR').amount.to_f).to eq(9.99)
+ end
+ end
+
+ context 'with invalid params' do
+ let(:product_params) { { name: '' } }
+
+ it 'returns validation errors' do
+ subject
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('validation_error')
+ expect(json_response['error']).to have_key('details')
+ end
+ end
+ end
+
+ describe 'PATCH #update' do
+ subject { patch :update, params: { id: product.prefixed_id, name: 'Updated Name' }, as: :json }
+
+ before { request.headers.merge!(headers) }
+
+ it 'updates the product' do
+ subject
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['name']).to eq('Updated Name')
+ expect(product.reload.name).to eq('Updated Name')
+ end
+
+ context 'with tags' do
+ it 'updates product tags' do
+ patch :update, params: { id: product.prefixed_id, tags: ['new-tag', 'sale'] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.tag_list).to match_array(['new-tag', 'sale'])
+ end
+ end
+
+ context 'with invalid params' do
+ it 'returns validation errors' do
+ patch :update, params: { id: product.prefixed_id, name: '' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('validation_error')
+ end
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ subject { delete :destroy, params: { id: product.prefixed_id }, as: :json }
+
+ before { request.headers.merge!(headers) }
+
+ it 'soft-deletes the product' do
+ subject
+
+ expect(response).to have_http_status(:no_content)
+ expect(product.reload.deleted_at).not_to be_nil
+ end
+ end
+
+ describe 'POST #clone' do
+ subject { post :clone, params: { id: product.prefixed_id }, as: :json }
+
+ before { request.headers.merge!(headers) }
+
+ it 'clones the product' do
+ expect { subject }.to change(Spree::Product, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['name']).to include('COPY OF')
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/taxonomies/taxons_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/taxonomies/taxons_controller_spec.rb
new file mode 100644
index 0000000000..43f6b0e731
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/taxonomies/taxons_controller_spec.rb
@@ -0,0 +1,84 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::Taxonomies::TaxonsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:taxonomy) { create(:taxonomy, store: store) }
+ let!(:taxon) { create(:taxon, taxonomy: taxonomy) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'returns taxons for the taxonomy' do
+ get :index, params: { taxonomy_id: taxonomy.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to be_an(Array)
+ ids = json_response['data'].map { |t| t['id'] }
+ expect(ids).to include(taxon.prefixed_id)
+ end
+
+ context 'with taxonomy from another store' do
+ let(:other_taxonomy) { create(:taxonomy, store: create(:store)) }
+
+ it 'returns 404' do
+ get :index, params: { taxonomy_id: other_taxonomy.prefixed_id }, as: :json
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+ end
+
+ describe 'GET #show' do
+ it 'returns the taxon' do
+ get :show, params: { taxonomy_id: taxonomy.prefixed_id, id: taxon.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(taxon.prefixed_id)
+ expect(json_response['name']).to eq(taxon.name)
+ end
+ end
+
+ describe 'POST #create' do
+ it 'creates a taxon under the taxonomy' do
+ expect {
+ post :create, params: {
+ taxonomy_id: taxonomy.prefixed_id,
+ name: 'New Taxon',
+ parent_id: taxonomy.root.id
+ }, as: :json
+ }.to change(taxonomy.taxons, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['name']).to eq('New Taxon')
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'updates the taxon' do
+ patch :update, params: {
+ taxonomy_id: taxonomy.prefixed_id,
+ id: taxon.prefixed_id,
+ name: 'Updated Taxon'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['name']).to eq('Updated Taxon')
+ expect(taxon.reload.name).to eq('Updated Taxon')
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'deletes the taxon' do
+ expect {
+ delete :destroy, params: {
+ taxonomy_id: taxonomy.prefixed_id,
+ id: taxon.prefixed_id
+ }, as: :json
+ }.to change(taxonomy.taxons, :count).by(-1)
+
+ expect(response).to have_http_status(:no_content)
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/taxonomies_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/taxonomies_controller_spec.rb
new file mode 100644
index 0000000000..36721a82ee
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/taxonomies_controller_spec.rb
@@ -0,0 +1,83 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::TaxonomiesController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:taxonomy) { create(:taxonomy, store: store) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'returns taxonomies for the current store' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to be_an(Array)
+ ids = json_response['data'].map { |t| t['id'] }
+ expect(ids).to include(taxonomy.prefixed_id)
+ end
+
+ it 'does not return taxonomies from other stores' do
+ other_taxonomy = create(:taxonomy, store: create(:store))
+
+ get :index, as: :json
+
+ ids = json_response['data'].map { |t| t['id'] }
+ expect(ids).not_to include(other_taxonomy.prefixed_id)
+ end
+ end
+
+ describe 'GET #show' do
+ it 'returns the taxonomy' do
+ get :show, params: { id: taxonomy.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(taxonomy.prefixed_id)
+ expect(json_response['name']).to eq(taxonomy.name)
+ end
+
+ it 'returns 404 for non-existent taxonomy' do
+ get :show, params: { id: 'tax_nonexistent' }, as: :json
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'POST #create' do
+ it 'creates a taxonomy' do
+ post :create, params: { name: 'New Taxonomy' }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['name']).to eq('New Taxonomy')
+ end
+
+ context 'with invalid params' do
+ it 'returns validation errors' do
+ post :create, params: { name: '' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'updates the taxonomy' do
+ patch :update, params: { id: taxonomy.prefixed_id, name: 'Updated Name' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['name']).to eq('Updated Name')
+ expect(taxonomy.reload.name).to eq('Updated Name')
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'deletes the taxonomy' do
+ expect {
+ delete :destroy, params: { id: taxonomy.prefixed_id }, as: :json
+ }.to change(Spree::Taxonomy, :count).by(-1)
+
+ expect(response).to have_http_status(:no_content)
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/taxons_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/taxons_controller_spec.rb
new file mode 100644
index 0000000000..2ae809029a
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/taxons_controller_spec.rb
@@ -0,0 +1,38 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::TaxonsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:taxonomy) { create(:taxonomy, store: store) }
+ let!(:taxon) { create(:taxon, taxonomy: taxonomy) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'returns all taxons' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to be_an(Array)
+ ids = json_response['data'].map { |t| t['id'] }
+ expect(ids).to include(taxon.prefixed_id)
+ end
+ end
+
+ describe 'GET #show' do
+ it 'returns the taxon' do
+ get :show, params: { id: taxon.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(taxon.prefixed_id)
+ expect(json_response['name']).to eq(taxon.name)
+ end
+
+ it 'returns 404 for non-existent taxon' do
+ get :show, params: { id: 'taxon_nonexistent' }, as: :json
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 45d86b1595..fe3d942fd5 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -495,7 +495,11 @@ module Spree
@total_on_hand ||= if any_variants_not_track_inventory?
BigDecimal::INFINITY
else
- stock_items.loaded? ? stock_items.sum(&:count_on_hand) : stock_items.sum(:count_on_hand)
+ if variants_including_master.loaded?
+ variants_including_master.sum(&:total_on_hand)
+ else
+ stock_items.loaded? ? stock_items.sum(&:count_on_hand) : stock_items.sum(:count_on_hand)
+ end
end
end
diff --git a/spree/core/app/services/spree/option_types/create.rb b/spree/core/app/services/spree/option_types/create.rb
new file mode 100644
index 0000000000..3d6f16a283
--- /dev/null
+++ b/spree/core/app/services/spree/option_types/create.rb
@@ -0,0 +1,51 @@
+module Spree
+ module OptionTypes
+ class Create
+ prepend Spree::ServiceModule::Base
+
+ def call(params:)
+ ApplicationRecord.transaction do
+ run :create_option_type
+ run :sync_option_values
+ end
+ end
+
+ private
+
+ def create_option_type(params:)
+ params = params.to_h.with_indifferent_access
+ option_values_params = params.delete(:option_values)
+
+ option_type = Spree::OptionType.new(params)
+
+ if option_type.save
+ success(option_type: option_type, option_values_params: option_values_params)
+ else
+ failure(option_type, option_type.errors)
+ end
+ end
+
+ def sync_option_values(option_type:, option_values_params:)
+ return success(option_type: option_type) if option_values_params.blank?
+
+ now = Time.current
+
+ records = option_values_params.each_with_index.map do |value_data, index|
+ value_data = value_data.to_h.with_indifferent_access
+ {
+ option_type_id: option_type.id,
+ name: value_data[:name],
+ presentation: value_data[:presentation],
+ position: value_data[:position] || (index + 1),
+ created_at: now,
+ updated_at: now
+ }
+ end
+
+ Spree::OptionValue.insert_all!(records)
+
+ success(option_type: option_type.reload)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/option_types/update.rb b/spree/core/app/services/spree/option_types/update.rb
new file mode 100644
index 0000000000..384a560585
--- /dev/null
+++ b/spree/core/app/services/spree/option_types/update.rb
@@ -0,0 +1,61 @@
+module Spree
+ module OptionTypes
+ class Update
+ prepend Spree::ServiceModule::Base
+
+ def call(option_type:, params:)
+ ApplicationRecord.transaction do
+ run :update_option_type
+ run :sync_option_values
+ end
+ end
+
+ private
+
+ def update_option_type(option_type:, params:)
+ params = params.to_h.with_indifferent_access
+ option_values_params = params.delete(:option_values)
+ sync_values = !option_values_params.nil?
+
+ if option_type.update(params)
+ success(option_type: option_type, option_values_params: option_values_params, sync_values: sync_values)
+ else
+ failure(option_type, option_type.errors)
+ end
+ end
+
+ def sync_option_values(option_type:, option_values_params:, sync_values:)
+ return success(option_type: option_type) unless sync_values
+
+ now = Time.current
+ names = []
+
+ records = (option_values_params || []).each_with_index.map do |value_data, index|
+ value_data = value_data.to_h.with_indifferent_access
+ names << value_data[:name]
+ {
+ option_type_id: option_type.id,
+ name: value_data[:name],
+ presentation: value_data[:presentation],
+ position: value_data[:position] || (index + 1),
+ created_at: now,
+ updated_at: now
+ }
+ end
+
+ # Remove option values not in the payload
+ option_type.option_values.where.not(name: names).destroy_all
+
+ if records.any?
+ Spree::OptionValue.upsert_all(
+ records,
+ unique_by: :index_spree_option_values_on_option_type_id_and_name,
+ update_only: [:presentation, :position]
+ )
+ end
+
+ success(option_type: option_type.reload)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/products/create.rb b/spree/core/app/services/spree/products/create.rb
new file mode 100644
index 0000000000..cf9e440c83
--- /dev/null
+++ b/spree/core/app/services/spree/products/create.rb
@@ -0,0 +1,134 @@
+module Spree
+ module Products
+ class Create
+ prepend Spree::ServiceModule::Base
+
+ def call(store:, params:)
+ ApplicationRecord.transaction do
+ run :create_product
+ run :create_variants
+ end
+ end
+
+ private
+
+ def create_product(store:, params:)
+ params = params.to_h.with_indifferent_access
+ variants_params = params.delete(:variants)
+ product_params = resolve_ids(params)
+ product_params[:store_ids] = [store.id] if product_params[:store_ids].blank?
+
+ # Map tags array to tag_list
+ product_params[:tag_list] = product_params.delete(:tags) if product_params.key?(:tags)
+
+ # Extract IDs that after_initialize callbacks may overwrite
+ tax_category_id = product_params.delete(:tax_category_id)
+ shipping_category_id = product_params.delete(:shipping_category_id)
+
+ product = Spree::Product.new(product_params)
+ product.tax_category_id = tax_category_id if tax_category_id.present?
+ product.shipping_category_id = shipping_category_id if shipping_category_id.present?
+
+ if product.save
+ success(product: product, store: store, variants_params: variants_params)
+ else
+ failure(product, product.errors)
+ end
+ end
+
+ def create_variants(product:, store:, variants_params:)
+ return success(product: product) if variants_params.blank?
+
+ variants_params.each do |variant_data|
+ variant_data = variant_data.to_h.with_indifferent_access
+ prices_params = variant_data.delete(:prices)
+ option_type_name = variant_data.delete(:option_type)
+ option_value_name = variant_data.delete(:option_value)
+ total_on_hand = variant_data.delete(:total_on_hand)
+
+ variant = product.variants.build(variant_data)
+
+ # Assign option value if provided
+ if option_type_name.present? && option_value_name.present?
+ option_type = Spree::OptionType.where(name: option_type_name.to_s.parameterize).first_or_create! do |ot|
+ ot.presentation = option_type_name
+ end
+ product.option_types << option_type unless product.option_types.include?(option_type)
+
+ option_value = option_type.option_values.where(name: option_value_name.to_s.parameterize).first_or_create! do |ov|
+ ov.presentation = option_value_name
+ end
+ variant.option_values = [option_value]
+ end
+
+ unless variant.save
+ raise ActiveRecord::Rollback
+ return failure(variant, variant.errors)
+ end
+
+ # Set stock
+ if total_on_hand.present?
+ variant.stock_items.first&.set_count_on_hand(total_on_hand.to_i)
+ end
+
+ # Upsert prices
+ upsert_prices(variant, prices_params) if prices_params.present?
+ end
+
+ success(product: product.reload)
+ end
+
+ def upsert_prices(variant, prices_params)
+ now = Time.current
+ currencies = []
+
+ records = prices_params.map do |price_data|
+ price_data = price_data.to_h.with_indifferent_access
+ currencies << price_data[:currency]
+ {
+ variant_id: variant.id,
+ currency: price_data[:currency],
+ amount: price_data[:amount],
+ compare_at_amount: price_data[:compare_at_amount],
+ created_at: now,
+ updated_at: now
+ }
+ end
+
+ Spree::Price.where(variant_id: variant.id, price_list_id: nil)
+ .where.not(currency: currencies)
+ .update_all(deleted_at: now)
+
+ Spree::Price.upsert_all(
+ records,
+ unique_by: :index_spree_prices_on_variant_id_and_currency,
+ update_only: [:amount, :compare_at_amount]
+ )
+ end
+
+ def resolve_ids(params)
+ params = params.to_h.with_indifferent_access
+
+ if params[:tax_category_id].present?
+ params[:tax_category_id] = resolve_prefix_id(Spree::TaxCategory, params[:tax_category_id])
+ end
+
+ if params[:shipping_category_id].present?
+ params[:shipping_category_id] = resolve_prefix_id(Spree::ShippingCategory, params[:shipping_category_id])
+ end
+
+ if params[:taxon_ids].present?
+ params[:taxon_ids] = params[:taxon_ids].map { |id| resolve_prefix_id(Spree::Taxon, id) }
+ end
+
+ params
+ end
+
+ def resolve_prefix_id(klass, id)
+ return id unless id.is_a?(String) && id.match?(/\A[a-z]+_/)
+
+ klass.find_by_prefix_id!(id).id
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/products/update.rb b/spree/core/app/services/spree/products/update.rb
new file mode 100644
index 0000000000..37121f93e9
--- /dev/null
+++ b/spree/core/app/services/spree/products/update.rb
@@ -0,0 +1,141 @@
+module Spree
+ module Products
+ class Update
+ prepend Spree::ServiceModule::Base
+
+ def call(product:, store:, params:)
+ ApplicationRecord.transaction do
+ run :update_product
+ run :update_variants
+ end
+ end
+
+ private
+
+ def update_product(product:, store:, params:)
+ params = params.to_h.with_indifferent_access
+ variants_params = params.delete(:variants)
+ product_params = resolve_ids(params)
+
+ # Map tags array to tag_list
+ product_params[:tag_list] = product_params.delete(:tags) if product_params.key?(:tags)
+
+ # Preserve taxon associations from other stores
+ if product_params.key?(:taxon_ids)
+ other_store_taxon_ids = product.taxons
+ .joins(:taxonomy)
+ .where.not(spree_taxonomies: { store_id: store.id })
+ .pluck(:id)
+ product_params[:taxon_ids] = (product_params[:taxon_ids] + other_store_taxon_ids).uniq
+ end
+
+ if product.update(product_params)
+ success(product: product, store: store, variants_params: variants_params)
+ else
+ failure(product, product.errors)
+ end
+ end
+
+ def update_variants(product:, store:, variants_params:)
+ return success(product: product) if variants_params.blank?
+
+ variants_params.each do |variant_data|
+ variant_data = variant_data.to_h.with_indifferent_access
+ variant_id = variant_data.delete(:id)
+ prices_params = variant_data.delete(:prices)
+ option_type_name = variant_data.delete(:option_type)
+ option_value_name = variant_data.delete(:option_value)
+ total_on_hand = variant_data.delete(:total_on_hand)
+
+ variant = if variant_id.present?
+ product.variants_including_master.find_by_prefix_id!(variant_id)
+ else
+ product.variants.build
+ end
+
+ # Assign option value if provided
+ if option_type_name.present? && option_value_name.present?
+ option_type = Spree::OptionType.where(name: option_type_name.to_s.parameterize).first_or_create! do |ot|
+ ot.presentation = option_type_name
+ end
+ product.option_types << option_type unless product.option_types.include?(option_type)
+
+ option_value = option_type.option_values.where(name: option_value_name.to_s.parameterize).first_or_create! do |ov|
+ ov.presentation = option_value_name
+ end
+ variant.option_values = [option_value]
+ end
+
+ variant.assign_attributes(variant_data.except(:id))
+
+ unless variant.save
+ raise ActiveRecord::Rollback
+ return failure(variant, variant.errors)
+ end
+
+ # Set stock
+ if total_on_hand.present?
+ variant.stock_items.first&.set_count_on_hand(total_on_hand.to_i)
+ end
+
+ # Upsert prices
+ upsert_prices(variant, prices_params) if prices_params.present?
+ end
+
+ success(product: product.reload)
+ end
+
+ def upsert_prices(variant, prices_params)
+ now = Time.current
+ currencies = []
+
+ records = prices_params.map do |price_data|
+ price_data = price_data.to_h.with_indifferent_access
+ currencies << price_data[:currency]
+ {
+ variant_id: variant.id,
+ currency: price_data[:currency],
+ amount: price_data[:amount],
+ compare_at_amount: price_data[:compare_at_amount],
+ created_at: now,
+ updated_at: now
+ }
+ end
+
+ Spree::Price.where(variant_id: variant.id, price_list_id: nil)
+ .where.not(currency: currencies)
+ .update_all(deleted_at: now)
+
+ Spree::Price.upsert_all(
+ records,
+ unique_by: :index_spree_prices_on_variant_id_and_currency,
+ update_only: [:amount, :compare_at_amount]
+ )
+ end
+
+ def resolve_ids(params)
+ params = params.to_h.with_indifferent_access
+
+ if params[:tax_category_id].present?
+ params[:tax_category_id] = resolve_prefix_id(Spree::TaxCategory, params[:tax_category_id])
+ end
+
+ if params[:shipping_category_id].present?
+ params[:shipping_category_id] = resolve_prefix_id(Spree::ShippingCategory, params[:shipping_category_id])
+ end
+
+ if params[:taxon_ids].present?
+ params[:taxon_ids] = params[:taxon_ids].map { |id| resolve_prefix_id(Spree::Taxon, id) }
+ end
+
+ params
+ end
+
+ def resolve_prefix_id(klass, id)
+ return id unless id.is_a?(String) && id.match?(/\A[a-z]+_/)
+
+ klass.find_by_prefix_id!(id).id
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/variants/create.rb b/spree/core/app/services/spree/variants/create.rb
new file mode 100644
index 0000000000..dc30d3b87f
--- /dev/null
+++ b/spree/core/app/services/spree/variants/create.rb
@@ -0,0 +1,143 @@
+module Spree
+ module Variants
+ class Create
+ prepend Spree::ServiceModule::Base
+
+ def call(product:, params:)
+ ApplicationRecord.transaction do
+ run :create_variant
+ run :sync_prices
+ run :sync_stock_items
+ end
+ end
+
+ private
+
+ def create_variant(product:, params:)
+ params = params.to_h.with_indifferent_access
+ prices_params = params.delete(:prices)
+ stock_items_params = params.delete(:stock_items)
+ option_type_name = params.delete(:option_type)
+ option_value_name = params.delete(:option_value)
+ total_on_hand = params.delete(:total_on_hand)
+
+ resolve_ids!(params)
+
+ variant = product.variants.build(params)
+
+ if option_type_name.present? && option_value_name.present?
+ assign_option_value(product, variant, option_type_name, option_value_name)
+ end
+
+ if variant.save
+ # Simple single-location stock shortcut
+ if total_on_hand.present? && stock_items_params.blank?
+ variant.stock_items.first&.set_count_on_hand(total_on_hand.to_i)
+ end
+
+ success(variant: variant, prices_params: prices_params, stock_items_params: stock_items_params)
+ else
+ failure(variant, variant.errors)
+ end
+ end
+
+ def sync_prices(variant:, prices_params:, stock_items_params:)
+ upsert_prices(variant, prices_params) if prices_params.present?
+ success(variant: variant, stock_items_params: stock_items_params)
+ end
+
+ def sync_stock_items(variant:, stock_items_params:)
+ upsert_stock_items(variant, stock_items_params) if stock_items_params.present?
+ success(variant: variant.reload)
+ end
+
+ def upsert_prices(variant, prices_params)
+ now = Time.current
+ currencies = []
+
+ records = prices_params.map do |price_data|
+ price_data = price_data.to_h.with_indifferent_access
+ currencies << price_data[:currency]
+ {
+ variant_id: variant.id,
+ currency: price_data[:currency],
+ amount: price_data[:amount],
+ compare_at_amount: price_data[:compare_at_amount],
+ created_at: now,
+ updated_at: now
+ }
+ end
+
+ Spree::Price.where(variant_id: variant.id, price_list_id: nil)
+ .where.not(currency: currencies)
+ .update_all(deleted_at: now)
+
+ Spree::Price.upsert_all(
+ records,
+ unique_by: :index_spree_prices_on_variant_id_and_currency,
+ update_only: [:amount, :compare_at_amount]
+ )
+ end
+
+ def upsert_stock_items(variant, stock_items_params)
+ now = Time.current
+ location_ids = []
+
+ records = stock_items_params.map do |stock_data|
+ stock_data = stock_data.to_h.with_indifferent_access
+ stock_location = resolve_stock_location(stock_data[:stock_location_id])
+ location_ids << stock_location.id
+ {
+ variant_id: variant.id,
+ stock_location_id: stock_location.id,
+ count_on_hand: stock_data[:count_on_hand].to_i,
+ backorderable: stock_data[:backorderable] || false,
+ created_at: now,
+ updated_at: now
+ }
+ end
+
+ # Soft-delete stock items for locations not in the payload
+ Spree::StockItem.where(variant_id: variant.id)
+ .where.not(stock_location_id: location_ids)
+ .update_all(deleted_at: now)
+
+ Spree::StockItem.upsert_all(
+ records,
+ unique_by: :index_spree_stock_items_unique_without_deleted_at,
+ update_only: [:count_on_hand, :backorderable]
+ )
+ end
+
+ def assign_option_value(product, variant, option_type_name, option_value_name)
+ option_type = Spree::OptionType.where(name: option_type_name.to_s.parameterize).first_or_create! do |ot|
+ ot.presentation = option_type_name
+ end
+ product.option_types << option_type unless product.option_types.include?(option_type)
+
+ option_value = option_type.option_values.where(name: option_value_name.to_s.parameterize).first_or_create! do |ov|
+ ov.presentation = option_value_name
+ end
+ variant.option_values = [option_value]
+ end
+
+ def resolve_ids!(params)
+ if params[:tax_category_id].present?
+ params[:tax_category_id] = resolve_prefix_id(Spree::TaxCategory, params[:tax_category_id])
+ end
+ end
+
+ def resolve_prefix_id(klass, id)
+ return id unless id.is_a?(String) && id.match?(/\A[a-z]+_/)
+
+ klass.find_by_prefix_id!(id).id
+ end
+
+ def resolve_stock_location(id)
+ return Spree::StockLocation.find(id) unless id.is_a?(String) && id.match?(/\A[a-z]+_/)
+
+ Spree::StockLocation.find_by_prefix_id!(id)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/variants/update.rb b/spree/core/app/services/spree/variants/update.rb
new file mode 100644
index 0000000000..8e3cedef27
--- /dev/null
+++ b/spree/core/app/services/spree/variants/update.rb
@@ -0,0 +1,144 @@
+module Spree
+ module Variants
+ class Update
+ prepend Spree::ServiceModule::Base
+
+ def call(variant:, params:)
+ ApplicationRecord.transaction do
+ run :update_variant
+ run :sync_prices
+ run :sync_stock_items
+ end
+ end
+
+ private
+
+ def update_variant(variant:, params:)
+ params = params.to_h.with_indifferent_access
+ prices_params = params.delete(:prices)
+ stock_items_params = params.delete(:stock_items)
+ option_type_name = params.delete(:option_type)
+ option_value_name = params.delete(:option_value)
+ total_on_hand = params.delete(:total_on_hand)
+
+ resolve_ids!(params)
+
+ if option_type_name.present? && option_value_name.present?
+ assign_option_value(variant.product, variant, option_type_name, option_value_name)
+ end
+
+ variant.assign_attributes(params)
+
+ if variant.save
+ # Simple single-location stock shortcut
+ if total_on_hand.present? && stock_items_params.blank?
+ variant.stock_items.first&.set_count_on_hand(total_on_hand.to_i)
+ end
+
+ success(variant: variant, prices_params: prices_params, stock_items_params: stock_items_params)
+ else
+ failure(variant, variant.errors)
+ end
+ end
+
+ def sync_prices(variant:, prices_params:, stock_items_params:)
+ upsert_prices(variant, prices_params) if prices_params.present?
+ success(variant: variant, stock_items_params: stock_items_params)
+ end
+
+ def sync_stock_items(variant:, stock_items_params:)
+ upsert_stock_items(variant, stock_items_params) if stock_items_params.present?
+ success(variant: variant.reload)
+ end
+
+ def upsert_prices(variant, prices_params)
+ now = Time.current
+ currencies = []
+
+ records = prices_params.map do |price_data|
+ price_data = price_data.to_h.with_indifferent_access
+ currencies << price_data[:currency]
+ {
+ variant_id: variant.id,
+ currency: price_data[:currency],
+ amount: price_data[:amount],
+ compare_at_amount: price_data[:compare_at_amount],
+ created_at: now,
+ updated_at: now
+ }
+ end
+
+ # Soft-delete prices for currencies not in the payload
+ Spree::Price.where(variant_id: variant.id, price_list_id: nil)
+ .where.not(currency: currencies)
+ .update_all(deleted_at: now)
+
+ Spree::Price.upsert_all(
+ records,
+ unique_by: :index_spree_prices_on_variant_id_and_currency,
+ update_only: [:amount, :compare_at_amount]
+ )
+ end
+
+ def upsert_stock_items(variant, stock_items_params)
+ now = Time.current
+ location_ids = []
+
+ records = stock_items_params.map do |stock_data|
+ stock_data = stock_data.to_h.with_indifferent_access
+ stock_location = resolve_stock_location(stock_data[:stock_location_id])
+ location_ids << stock_location.id
+ {
+ variant_id: variant.id,
+ stock_location_id: stock_location.id,
+ count_on_hand: stock_data[:count_on_hand].to_i,
+ backorderable: stock_data[:backorderable] || false,
+ created_at: now,
+ updated_at: now
+ }
+ end
+
+ # Soft-delete stock items for locations not in the payload
+ Spree::StockItem.where(variant_id: variant.id)
+ .where.not(stock_location_id: location_ids)
+ .update_all(deleted_at: now)
+
+ Spree::StockItem.upsert_all(
+ records,
+ unique_by: :index_spree_stock_items_unique_without_deleted_at,
+ update_only: [:count_on_hand, :backorderable]
+ )
+ end
+
+ def assign_option_value(product, variant, option_type_name, option_value_name)
+ option_type = Spree::OptionType.where(name: option_type_name.to_s.parameterize).first_or_create! do |ot|
+ ot.presentation = option_type_name
+ end
+ product.option_types << option_type unless product.option_types.include?(option_type)
+
+ option_value = option_type.option_values.where(name: option_value_name.to_s.parameterize).first_or_create! do |ov|
+ ov.presentation = option_value_name
+ end
+ variant.option_values = [option_value]
+ end
+
+ def resolve_ids!(params)
+ if params[:tax_category_id].present?
+ params[:tax_category_id] = resolve_prefix_id(Spree::TaxCategory, params[:tax_category_id])
+ end
+ end
+
+ def resolve_prefix_id(klass, id)
+ return id unless id.is_a?(String) && id.match?(/\A[a-z]+_/)
+
+ klass.find_by_prefix_id!(id).id
+ end
+
+ def resolve_stock_location(id)
+ return Spree::StockLocation.find(id) unless id.is_a?(String) && id.match?(/\A[a-z]+_/)
+
+ Spree::StockLocation.find_by_prefix_id!(id)
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index c5b52f557b..da148b53fd 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -41,6 +41,18 @@ module Spree
gift_card_remove_service: 'Spree::GiftCards::Remove',
gift_card_redeem_service: 'Spree::GiftCards::Redeem',
+ # products
+ product_create_service: 'Spree::Products::Create',
+ product_update_service: 'Spree::Products::Update',
+
+ # variants
+ variant_create_service: 'Spree::Variants::Create',
+ variant_update_service: 'Spree::Variants::Update',
+
+ # option types
+ option_type_create_service: 'Spree::OptionTypes::Create',
+ option_type_update_service: 'Spree::OptionTypes::Update',
+
# order
order_approve_service: 'Spree::Orders::Approve',
order_cancel_service: 'Spree::Orders::Cancel',
diff --git a/spree/core/spec/services/spree/option_types/create_spec.rb b/spree/core/spec/services/spree/option_types/create_spec.rb
new file mode 100644
index 0000000000..c6b0cba847
--- /dev/null
+++ b/spree/core/spec/services/spree/option_types/create_spec.rb
@@ -0,0 +1,96 @@
+require 'spec_helper'
+
+RSpec.describe Spree::OptionTypes::Create do
+ subject(:result) { described_class.call(params: params) }
+
+ describe 'basic creation' do
+ let(:params) { { name: 'color', presentation: 'Color' } }
+
+ it 'creates an option type' do
+ expect(result).to be_success
+ expect(result.value[:option_type].name).to eq('color')
+ expect(result.value[:option_type].presentation).to eq('Color')
+ end
+ end
+
+ describe 'validation error - missing presentation' do
+ let(:params) { { name: 'bad' } }
+
+ it 'returns failure' do
+ expect(result).not_to be_success
+ end
+ end
+
+ describe 'validation error - blank name and presentation' do
+ let(:params) { { name: '', presentation: '' } }
+
+ it 'returns failure' do
+ expect(result).not_to be_success
+ end
+ end
+
+ describe 'duplicate name' do
+ before { create(:option_type, name: 'size') }
+ let(:params) { { name: 'size', presentation: 'Size' } }
+
+ it 'returns failure' do
+ expect(result).not_to be_success
+ end
+ end
+
+ describe 'with nested option values' do
+ let(:params) do
+ {
+ name: 'material',
+ presentation: 'Material',
+ option_values: [
+ { name: 'cotton', presentation: 'Cotton' },
+ { name: 'silk', presentation: 'Silk' },
+ { name: 'wool', presentation: 'Wool' }
+ ]
+ }
+ end
+
+ it 'creates option values via insert_all' do
+ expect(result).to be_success
+ ot = result.value[:option_type]
+ expect(ot.option_values.count).to eq(3)
+ expect(ot.option_values.pluck(:name)).to match_array(%w[cotton silk wool])
+ end
+
+ it 'assigns positions' do
+ ot = result.value[:option_type]
+ positions = ot.option_values.order(:position).pluck(:position)
+ expect(positions).to eq([1, 2, 3])
+ end
+ end
+
+ describe 'with explicit positions' do
+ let(:params) do
+ {
+ name: 'size',
+ presentation: 'Size',
+ option_values: [
+ { name: 'large', presentation: 'Large', position: 3 },
+ { name: 'small', presentation: 'Small', position: 1 }
+ ]
+ }
+ end
+
+ it 'uses provided positions' do
+ expect(result).to be_success
+ ot = result.value[:option_type]
+ expect(ot.option_values.find_by(name: 'small').position).to eq(1)
+ expect(ot.option_values.find_by(name: 'large').position).to eq(3)
+ end
+ end
+
+ describe 'without option values' do
+ let(:params) { { name: 'weight', presentation: 'Weight' } }
+
+ it 'creates option type with no values' do
+ expect(result).to be_success
+ expect(result.value[:option_type].option_values).to be_empty
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/option_types/update_spec.rb b/spree/core/spec/services/spree/option_types/update_spec.rb
new file mode 100644
index 0000000000..7f04ff3a87
--- /dev/null
+++ b/spree/core/spec/services/spree/option_types/update_spec.rb
@@ -0,0 +1,106 @@
+require 'spec_helper'
+
+RSpec.describe Spree::OptionTypes::Update do
+ subject(:result) { described_class.call(option_type: option_type, params: params) }
+
+ let!(:option_type) { create(:option_type) }
+ let!(:ov1) { create(:option_value, option_type: option_type, name: 'red', presentation: 'Red', position: 1) }
+ let!(:ov2) { create(:option_value, option_type: option_type, name: 'blue', presentation: 'Blue', position: 2) }
+
+ describe 'basic update' do
+ let(:params) { { presentation: 'Updated' } }
+
+ it 'updates option type attributes' do
+ expect(result).to be_success
+ expect(result.value[:option_type].presentation).to eq('Updated')
+ end
+
+ it 'does not touch option values when key is absent' do
+ expect(result).to be_success
+ expect(option_type.option_values.count).to eq(2)
+ end
+ end
+
+ describe 'validation error' do
+ let(:params) { { presentation: '' } }
+
+ it 'returns failure' do
+ expect(result).not_to be_success
+ end
+ end
+
+ describe 'sync option values - update existing, add new, remove missing' do
+ let(:params) do
+ {
+ option_values: [
+ { name: 'red', presentation: 'Bright Red' },
+ { name: 'green', presentation: 'Green' }
+ ]
+ }
+ end
+
+ it 'updates red, creates green, removes blue' do
+ expect(result).to be_success
+ ot = result.value[:option_type]
+
+ expect(ot.option_values.count).to eq(2)
+ expect(ot.option_values.find_by(name: 'red').presentation).to eq('Bright Red')
+ expect(ot.option_values.find_by(name: 'green')).to be_present
+ expect(ot.option_values.find_by(name: 'blue')).to be_nil
+ end
+ end
+
+ describe 'empty option_values array removes all' do
+ let(:params) { { option_values: [] } }
+
+ it 'removes all option values' do
+ expect(result).to be_success
+ expect(option_type.reload.option_values.count).to eq(0)
+ end
+ end
+
+ describe 'option_values key absent does not sync' do
+ let(:params) { { presentation: 'New Pres' } }
+
+ it 'keeps existing option values' do
+ expect(result).to be_success
+ expect(option_type.reload.option_values.count).to eq(2)
+ end
+ end
+
+ describe 'upsert updates position' do
+ let(:params) do
+ {
+ option_values: [
+ { name: 'red', presentation: 'Red', position: 5 },
+ { name: 'blue', presentation: 'Blue', position: 10 }
+ ]
+ }
+ end
+
+ it 'updates positions' do
+ expect(result).to be_success
+ ot = result.value[:option_type]
+ expect(ot.option_values.find_by(name: 'red').position).to eq(5)
+ expect(ot.option_values.find_by(name: 'blue').position).to eq(10)
+ end
+ end
+
+ describe 'duplicate name in same option type' do
+ let(:params) do
+ {
+ option_values: [
+ { name: 'red', presentation: 'Red' },
+ { name: 'red', presentation: 'Also Red' }
+ ]
+ }
+ end
+
+ it 'handles duplicate gracefully via upsert (last wins)' do
+ expect(result).to be_success
+ ot = result.value[:option_type]
+ # upsert_all with duplicate keys: only one record persists
+ expect(ot.option_values.where(name: 'red').count).to eq(1)
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/products/create_spec.rb b/spree/core/spec/services/spree/products/create_spec.rb
new file mode 100644
index 0000000000..c0c1baaf4a
--- /dev/null
+++ b/spree/core/spec/services/spree/products/create_spec.rb
@@ -0,0 +1,161 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Products::Create do
+ subject(:result) { described_class.call(store: store, params: params) }
+
+ let(:store) { @default_store }
+ let(:shipping_category) { create(:shipping_category) }
+
+ describe 'basic product creation' do
+ let(:params) { { name: 'Test Product', price: 19.99, shipping_category_id: shipping_category.id } }
+
+ it 'creates a product' do
+ expect(result).to be_success
+ expect(result.value[:product].name).to eq('Test Product')
+ expect(result.value[:product].stores).to include(store)
+ end
+ end
+
+ describe 'validation errors' do
+ let(:params) { { name: '' } }
+
+ it 'returns failure with errors' do
+ expect(result).not_to be_success
+ expect(result.error).to be_present
+ end
+ end
+
+ describe 'tags mapping' do
+ let(:params) { { name: 'Tagged Product', price: 10, shipping_category_id: shipping_category.id, tags: ['eco', 'sale'] } }
+
+ it 'maps tags to tag_list' do
+ expect(result).to be_success
+ expect(result.value[:product].tag_list).to match_array(['eco', 'sale'])
+ end
+ end
+
+ describe 'prefixed ID resolution' do
+ let(:tax_category) { create(:tax_category) }
+ let(:taxonomy) { create(:taxonomy, store: store) }
+ let(:taxon) { create(:taxon, taxonomy: taxonomy) }
+
+ let(:params) do
+ {
+ name: 'Resolved Product',
+ price: 10,
+ shipping_category_id: shipping_category.prefixed_id,
+ tax_category_id: tax_category.prefixed_id,
+ taxon_ids: [taxon.prefixed_id]
+ }
+ end
+
+ it 'resolves prefixed IDs for associations' do
+ expect(result).to be_success
+ product = result.value[:product]
+ expect(product.shipping_category).to eq(shipping_category)
+ expect(product.tax_category).to eq(tax_category)
+ expect(product.taxons).to include(taxon)
+ end
+ end
+
+ describe 'invalid prefixed ID' do
+ let(:params) { { name: 'Bad ID', price: 10, shipping_category_id: shipping_category.id, tax_category_id: 'tc_nonexistent' } }
+
+ it 'raises RecordNotFound' do
+ expect { result }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+ end
+
+ describe 'nested variants' do
+ let(:params) do
+ {
+ name: 'Product With Variants',
+ price: 10,
+ shipping_category_id: shipping_category.id,
+ variants: [
+ { sku: 'VAR-1', option_type: 'Size', option_value: 'Small', price: 10 },
+ { sku: 'VAR-2', option_type: 'Size', option_value: 'Large', price: 15 }
+ ]
+ }
+ end
+
+ it 'creates variants with option types auto-created' do
+ expect(result).to be_success
+ product = result.value[:product]
+ expect(product.variants.count).to eq(2)
+ expect(product.variants.pluck(:sku)).to match_array(%w[VAR-1 VAR-2])
+ expect(product.option_types.map(&:name)).to include('size')
+ end
+ end
+
+ describe 'variant with prices upserted' do
+ let(:params) do
+ {
+ name: 'Multi-price Product',
+ price: 10,
+ shipping_category_id: shipping_category.id,
+ variants: [
+ {
+ sku: 'MP-1',
+ option_type: 'Color',
+ option_value: 'Red',
+ prices: [
+ { currency: 'USD', amount: 10.99, compare_at_amount: 14.99 },
+ { currency: 'EUR', amount: 9.50 }
+ ]
+ }
+ ]
+ }
+ end
+
+ it 'upserts prices for the variant' do
+ expect(result).to be_success
+ variant = result.value[:product].variants.find_by(sku: 'MP-1')
+ usd = variant.prices.find_by(currency: 'USD')
+ eur = variant.prices.find_by(currency: 'EUR')
+
+ expect(usd.amount.to_f).to eq(10.99)
+ expect(usd.compare_at_amount.to_f).to eq(14.99)
+ expect(eur.amount.to_f).to eq(9.50)
+ end
+ end
+
+ describe 'variant with total_on_hand' do
+ let!(:stock_location) { create(:stock_location, propagate_all_variants: true) }
+
+ let(:params) do
+ {
+ name: 'Stocked Product',
+ price: 10,
+ shipping_category_id: shipping_category.id,
+ variants: [
+ { sku: 'STK-1', option_type: 'Size', option_value: 'M', total_on_hand: 25 }
+ ]
+ }
+ end
+
+ it 'sets stock level' do
+ expect(result).to be_success
+ variant = result.value[:product].variants.find_by(sku: 'STK-1')
+ expect(variant.total_on_hand).to eq(25)
+ end
+ end
+
+ describe 'empty variants array' do
+ let(:params) { { name: 'No Variants', price: 5, shipping_category_id: shipping_category.id, variants: [] } }
+
+ it 'creates product without extra variants' do
+ expect(result).to be_success
+ expect(result.value[:product].variants.count).to eq(0)
+ end
+ end
+
+ describe 'without store_ids assigns current store' do
+ let(:params) { { name: 'Auto Store', price: 5, shipping_category_id: shipping_category.id } }
+
+ it 'assigns the provided store' do
+ expect(result).to be_success
+ expect(result.value[:product].stores).to eq([store])
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/products/update_spec.rb b/spree/core/spec/services/spree/products/update_spec.rb
new file mode 100644
index 0000000000..818cb78072
--- /dev/null
+++ b/spree/core/spec/services/spree/products/update_spec.rb
@@ -0,0 +1,148 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Products::Update do
+ subject(:result) { described_class.call(product: product, store: store, params: params) }
+
+ let(:store) { @default_store }
+ let!(:product) { create(:product, stores: [store]) }
+
+ describe 'basic update' do
+ let(:params) { { name: 'Updated Name' } }
+
+ it 'updates the product' do
+ expect(result).to be_success
+ expect(result.value[:product].name).to eq('Updated Name')
+ end
+ end
+
+ describe 'validation errors' do
+ let(:params) { { name: '' } }
+
+ it 'returns failure' do
+ expect(result).not_to be_success
+ end
+ end
+
+ describe 'tags update' do
+ let(:params) { { tags: ['new-tag'] } }
+
+ it 'updates tag_list' do
+ expect(result).to be_success
+ expect(result.value[:product].tag_list).to eq(['new-tag'])
+ end
+ end
+
+ describe 'clearing tags' do
+ before { product.update!(tag_list: ['old-tag']) }
+ let(:params) { { tags: [] } }
+
+ it 'clears all tags' do
+ expect(result).to be_success
+ expect(result.value[:product].tag_list).to be_empty
+ end
+ end
+
+ describe 'taxon_ids preserves other store taxons' do
+ let(:other_store) { create(:store) }
+ let(:taxonomy_this) { create(:taxonomy, store: store) }
+ let(:taxonomy_other) { create(:taxonomy, store: other_store) }
+ let(:taxon_this) { create(:taxon, taxonomy: taxonomy_this) }
+ let(:taxon_other) { create(:taxon, taxonomy: taxonomy_other) }
+
+ before { product.taxons = [taxon_this, taxon_other] }
+
+ let(:new_taxon) { create(:taxon, taxonomy: taxonomy_this) }
+ let(:params) { { taxon_ids: [new_taxon.id] } }
+
+ it 'keeps taxons from other stores and replaces current store taxons' do
+ expect(result).to be_success
+ expect(result.value[:product].taxons).to include(new_taxon, taxon_other)
+ expect(result.value[:product].taxons).not_to include(taxon_this)
+ end
+ end
+
+ describe 'prefixed ID resolution' do
+ let(:tax_category) { create(:tax_category) }
+ let(:params) { { tax_category_id: tax_category.prefixed_id } }
+
+ it 'resolves prefixed tax_category_id' do
+ expect(result).to be_success
+ expect(result.value[:product].tax_category).to eq(tax_category)
+ end
+ end
+
+ describe 'update existing variant by prefixed ID' do
+ let!(:variant) { create(:variant, product: product) }
+ let(:params) do
+ {
+ variants: [
+ { id: variant.prefixed_id, sku: 'UPDATED-SKU' }
+ ]
+ }
+ end
+
+ it 'updates the variant' do
+ expect(result).to be_success
+ expect(variant.reload.sku).to eq('UPDATED-SKU')
+ end
+ end
+
+ describe 'create new variant via update' do
+ let(:option_type) { create(:option_type) }
+
+ before { product.option_types << option_type }
+
+ let(:params) do
+ {
+ variants: [
+ { sku: 'NEW-VIA-UPDATE', option_type: option_type.name, option_value: 'XL', price: 20 }
+ ]
+ }
+ end
+
+ it 'creates a new variant' do
+ expect { result }.to change { product.variants.count }.by(1)
+ expect(result).to be_success
+ expect(product.variants.find_by(sku: 'NEW-VIA-UPDATE')).to be_present
+ end
+ end
+
+ describe 'variant price upsert on update' do
+ let!(:variant) { create(:variant, product: product) }
+ let(:params) do
+ {
+ variants: [
+ {
+ id: variant.prefixed_id,
+ prices: [
+ { currency: 'GBP', amount: 12.50 }
+ ]
+ }
+ ]
+ }
+ end
+
+ it 'upserts prices and soft-deletes removed currencies' do
+ expect(result).to be_success
+ variant.reload
+ expect(variant.prices.find_by(currency: 'GBP').amount.to_f).to eq(12.50)
+ end
+ end
+
+ describe 'nonexistent variant prefixed ID' do
+ let(:params) { { variants: [{ id: 'variant_nonexistent', sku: 'X' }] } }
+
+ it 'raises RecordNotFound' do
+ expect { result }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+ end
+
+ describe 'no variants key' do
+ let(:params) { { name: 'Just Name' } }
+
+ it 'does not touch variants' do
+ expect(result).to be_success
+ expect(result.value[:product].name).to eq('Just Name')
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/variants/create_spec.rb b/spree/core/spec/services/spree/variants/create_spec.rb
new file mode 100644
index 0000000000..15c0aca006
--- /dev/null
+++ b/spree/core/spec/services/spree/variants/create_spec.rb
@@ -0,0 +1,172 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Variants::Create do
+ subject(:result) { described_class.call(product: product, params: params) }
+
+ let(:store) { @default_store }
+ let!(:product) { create(:product, stores: [store]) }
+ let(:option_type) { create(:option_type) }
+ let(:option_value) { create(:option_value, option_type: option_type) }
+
+ before { product.option_types << option_type }
+
+ describe 'basic variant creation' do
+ let(:params) { { sku: 'NEW-V1', price: 10, option_type: option_type.name, option_value: option_value.name } }
+
+ it 'creates a variant' do
+ expect(result).to be_success
+ expect(result.value[:variant].sku).to eq('NEW-V1')
+ expect(result.value[:variant].product).to eq(product)
+ end
+ end
+
+ describe 'validation error - missing option values' do
+ let(:params) { { sku: 'NO-OPT' } }
+
+ it 'returns failure' do
+ expect(result).not_to be_success
+ end
+ end
+
+ describe 'validation error - duplicate sku' do
+ let!(:existing) { create(:variant, product: product, sku: 'DUPE') }
+ let(:params) { { sku: 'DUPE', option_type: option_type.name, option_value: 'unique-val' } }
+
+ it 'returns failure with sku error' do
+ expect(result).not_to be_success
+ end
+ end
+
+ describe 'with nested prices' do
+ let(:params) do
+ {
+ sku: 'PRICED-V',
+ option_type: option_type.name,
+ option_value: 'priced',
+ price: 10,
+ prices: [
+ { currency: 'USD', amount: 25.00, compare_at_amount: 30.00 },
+ { currency: 'EUR', amount: 22.00 }
+ ]
+ }
+ end
+
+ it 'creates prices via upsert' do
+ expect(result).to be_success
+ variant = result.value[:variant]
+ expect(variant.prices.find_by(currency: 'USD').amount.to_f).to eq(25.00)
+ expect(variant.prices.find_by(currency: 'USD').compare_at_amount.to_f).to eq(30.00)
+ expect(variant.prices.find_by(currency: 'EUR').amount.to_f).to eq(22.00)
+ end
+ end
+
+ describe 'with nested stock_items' do
+ let!(:stock_location_1) { Spree::StockLocation.first || create(:stock_location) }
+ let!(:stock_location_2) { create(:stock_location, name: 'Warehouse 2') }
+
+ let(:params) do
+ {
+ sku: 'STOCKED-V',
+ option_type: option_type.name,
+ option_value: 'stocked',
+ price: 10,
+ stock_items: [
+ { stock_location_id: stock_location_1.prefixed_id, count_on_hand: 50, backorderable: false },
+ { stock_location_id: stock_location_2.prefixed_id, count_on_hand: 10, backorderable: true }
+ ]
+ }
+ end
+
+ it 'sets stock via upsert' do
+ expect(result).to be_success
+ variant = result.value[:variant]
+ si1 = variant.stock_items.find_by(stock_location: stock_location_1)
+ si2 = variant.stock_items.find_by(stock_location: stock_location_2)
+ expect(si1.count_on_hand).to eq(50)
+ expect(si1.backorderable).to eq(false)
+ expect(si2.count_on_hand).to eq(10)
+ expect(si2.backorderable).to eq(true)
+ end
+ end
+
+ describe 'invalid stock_location prefixed ID' do
+ let(:params) do
+ {
+ sku: 'BAD-LOC',
+ option_type: option_type.name,
+ option_value: 'badloc',
+ price: 10,
+ stock_items: [
+ { stock_location_id: 'sloc_nonexistent', count_on_hand: 5 }
+ ]
+ }
+ end
+
+ it 'raises RecordNotFound' do
+ expect { result }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+ end
+
+ describe 'total_on_hand shortcut' do
+ before { Spree::StockLocation.update_all(propagate_all_variants: true) }
+
+ let(:params) { { sku: 'TOH-V', option_type: option_type.name, option_value: 'toh', price: 10, total_on_hand: 42 } }
+
+ it 'sets stock on first stock item' do
+ expect(result).to be_success
+ expect(result.value[:variant].total_on_hand).to eq(42)
+ end
+ end
+
+ describe 'total_on_hand ignored when stock_items present' do
+ let!(:stock_location) { Spree::StockLocation.first || create(:stock_location) }
+
+ let(:params) do
+ {
+ sku: 'BOTH-V',
+ option_type: option_type.name,
+ option_value: 'both',
+ price: 10,
+ total_on_hand: 99,
+ stock_items: [
+ { stock_location_id: stock_location.prefixed_id, count_on_hand: 5 }
+ ]
+ }
+ end
+
+ it 'uses stock_items, not total_on_hand' do
+ expect(result).to be_success
+ variant = result.value[:variant]
+ expect(variant.stock_items.find_by(stock_location: stock_location).count_on_hand).to eq(5)
+ end
+ end
+
+ describe 'option type auto-creation' do
+ let(:params) { { sku: 'AUTO-OPT', price: 10, option_type: 'Material', option_value: 'Cotton' } }
+
+ it 'creates option type and value if they do not exist' do
+ expect(result).to be_success
+ expect(Spree::OptionType.find_by(name: 'material')).to be_present
+ expect(Spree::OptionValue.find_by(name: 'cotton')).to be_present
+ end
+ end
+
+ describe 'prefixed tax_category_id' do
+ let(:tax_category) { create(:tax_category) }
+ let(:params) { { sku: 'TAX-V', option_type: option_type.name, option_value: 'taxed', price: 10, tax_category_id: tax_category.prefixed_id } }
+
+ it 'resolves prefixed ID' do
+ expect(result).to be_success
+ expect(result.value[:variant].read_attribute(:tax_category_id)).to eq(tax_category.id)
+ end
+ end
+
+ describe 'no prices or stock_items' do
+ let(:params) { { sku: 'PLAIN-V', option_type: option_type.name, option_value: 'plain', price: 10 } }
+
+ it 'creates variant without extra prices or stock changes' do
+ expect(result).to be_success
+ expect(result.value[:variant].sku).to eq('PLAIN-V')
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/variants/update_spec.rb b/spree/core/spec/services/spree/variants/update_spec.rb
new file mode 100644
index 0000000000..e8aad30986
--- /dev/null
+++ b/spree/core/spec/services/spree/variants/update_spec.rb
@@ -0,0 +1,141 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Variants::Update do
+ subject(:result) { described_class.call(variant: variant, params: params) }
+
+ let(:store) { @default_store }
+ let!(:product) { create(:product, stores: [store]) }
+ let!(:variant) { create(:variant, product: product) }
+
+ describe 'basic update' do
+ let(:params) { { sku: 'UPDATED-SKU' } }
+
+ it 'updates variant attributes' do
+ expect(result).to be_success
+ expect(result.value[:variant].sku).to eq('UPDATED-SKU')
+ end
+ end
+
+ describe 'validation error' do
+ let!(:other_variant) { create(:variant, product: product, sku: 'TAKEN') }
+ let(:params) { { sku: 'TAKEN' } }
+
+ it 'returns failure for duplicate sku' do
+ expect(result).not_to be_success
+ end
+ end
+
+ describe 'upsert prices' do
+ let(:params) do
+ {
+ prices: [
+ { currency: 'USD', amount: 50.00, compare_at_amount: 60.00 },
+ { currency: 'GBP', amount: 40.00 }
+ ]
+ }
+ end
+
+ it 'creates new prices' do
+ expect(result).to be_success
+ variant.reload
+ expect(variant.prices.find_by(currency: 'USD').amount.to_f).to eq(50.00)
+ expect(variant.prices.find_by(currency: 'GBP').amount.to_f).to eq(40.00)
+ end
+ end
+
+ describe 'upsert prices removes missing currencies' do
+ before do
+ variant.prices.create!(currency: 'EUR', amount: 20)
+ variant.prices.create!(currency: 'GBP', amount: 15)
+ end
+
+ let(:params) do
+ {
+ prices: [
+ { currency: 'EUR', amount: 25.00 }
+ ]
+ }
+ end
+
+ it 'soft-deletes GBP price and updates EUR' do
+ expect(result).to be_success
+ variant.reload
+ expect(variant.prices.find_by(currency: 'EUR').amount.to_f).to eq(25.00)
+ # GBP should be soft-deleted
+ gbp = Spree::Price.with_deleted.find_by(variant_id: variant.id, currency: 'GBP')
+ expect(gbp.deleted_at).to be_present
+ end
+ end
+
+ describe 'upsert stock_items' do
+ let!(:stock_location) { Spree::StockLocation.first || create(:stock_location) }
+
+ let(:params) do
+ {
+ stock_items: [
+ { stock_location_id: stock_location.prefixed_id, count_on_hand: 100, backorderable: true }
+ ]
+ }
+ end
+
+ it 'sets stock levels' do
+ expect(result).to be_success
+ si = variant.reload.stock_items.find_by(stock_location: stock_location)
+ expect(si.count_on_hand).to eq(100)
+ expect(si.backorderable).to eq(true)
+ end
+ end
+
+ describe 'upsert stock_items removes missing locations' do
+ let!(:loc1) { Spree::StockLocation.first || create(:stock_location) }
+ let!(:loc2) { create(:stock_location, name: 'Secondary') }
+
+ before do
+ variant.stock_items.find_or_create_by!(stock_location: loc1).update!(count_on_hand: 10)
+ variant.stock_items.find_or_create_by!(stock_location: loc2).update!(count_on_hand: 20)
+ end
+
+ let(:params) do
+ {
+ stock_items: [
+ { stock_location_id: loc1.prefixed_id, count_on_hand: 50 }
+ ]
+ }
+ end
+
+ it 'soft-deletes stock item for loc2' do
+ expect(result).to be_success
+ variant.reload
+ expect(variant.stock_items.find_by(stock_location: loc1).count_on_hand).to eq(50)
+ deleted_si = Spree::StockItem.with_deleted.find_by(variant_id: variant.id, stock_location_id: loc2.id)
+ expect(deleted_si.deleted_at).to be_present
+ end
+ end
+
+ describe 'option value reassignment' do
+ let(:params) { { option_type: 'Color', option_value: 'Blue' } }
+
+ it 'assigns new option value' do
+ expect(result).to be_success
+ expect(result.value[:variant].option_values.first.presentation).to eq('Blue')
+ end
+ end
+
+ describe 'total_on_hand shortcut' do
+ let(:params) { { total_on_hand: 77 } }
+
+ it 'sets stock on first stock item' do
+ expect(result).to be_success
+ expect(result.value[:variant].total_on_hand).to eq(77)
+ end
+ end
+
+ describe 'no prices or stock params' do
+ let(:params) { { weight: 2.5 } }
+
+ it 'updates only variant attributes' do
+ expect(result).to be_success
+ expect(result.value[:variant].weight.to_f).to eq(2.5)
+ end
+ end
+end