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.

Added Storefront Variants API endpoint (#12065)

Damian Legawiecf0c9d3a5f0fa
diff --git a/api/app/controllers/spree/api/v2/storefront/variants_controller.rb b/api/app/controllers/spree/api/v2/storefront/variants_controller.rb
new file mode 100644
index 0000000000..d9c9eedb2f
--- /dev/null
+++ b/api/app/controllers/spree/api/v2/storefront/variants_controller.rb
@@ -0,0 +1,41 @@
+module Spree
+ module Api
+ module V2
+ module Storefront
+ class VariantsController < ::Spree::Api::V2::ResourceController
+ private
+
+ def model_class
+ Spree::Variant
+ end
+
+ def scope
+ product_scope = Spree::Product.for_store(current_store)
+ product_scope = product_scope.accessible_by(current_ability, :show)
+ product_scope = product_scope.i18n if model_class.include?(TranslatableResource)
+
+ product = product_scope.friendly.find(params[:id])
+ product.variants_including_master
+ end
+
+ def collection_finder
+ Spree::Api::Dependencies.storefront_variant_finder.constantize
+ end
+
+ def collection_serializer
+ Spree::Api::Dependencies.storefront_variant_serializer.constantize
+ end
+
+ def scope_includes
+ variant_includes = {
+ prices: [],
+ option_values: :option_type,
+ }
+ variant_includes[:images] = [] if params[:include]&.match(/images/)
+ variant_includes
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/api/config/routes.rb b/api/config/routes.rb
index 88641f65e2..c0e57f6384 100644
--- a/api/config/routes.rb
+++ b/api/config/routes.rb
@@ -45,6 +45,7 @@ Spree::Core::Engine.add_routes do
get '/countries/:iso', to: 'countries#show', as: :country
get '/order_status/:number', to: 'order_status#show', as: :order_status
resources :products, only: %i[index show]
+ get '/products/:id/variants', to: 'variants#index', as: :product_variants
resources :taxons, only: %i[index show], id: /.+/
get '/stores/:code', to: 'stores#show', as: :store
get '/store', to: 'stores#current', as: :current_store
diff --git a/api/lib/spree/api/dependencies.rb b/api/lib/spree/api/dependencies.rb
index ca6ab43655..cfb95d983e 100644
--- a/api/lib/spree/api/dependencies.rb
+++ b/api/lib/spree/api/dependencies.rb
@@ -60,6 +60,7 @@ module Spree
storefront_estimated_shipment_serializer: 'Spree::V2::Storefront::EstimatedShippingRateSerializer',
storefront_store_serializer: 'Spree::V2::Storefront::StoreSerializer',
storefront_order_serializer: 'Spree::V2::Storefront::OrderSerializer',
+ storefront_variant_serializer: 'Spree::V2::Storefront::VariantSerializer',
# sorters
storefront_collection_sorter: -> { Spree::Dependencies.collection_sorter },
@@ -81,6 +82,7 @@ module Spree
storefront_find_by_variant_finder: -> { Spree::Dependencies.line_item_by_variant_finder },
storefront_products_finder: -> { Spree::Dependencies.products_finder },
storefront_taxon_finder: -> { Spree::Dependencies.taxon_finder },
+ storefront_variant_finder: -> { Spree::Dependencies.variant_finder },
error_handler: 'Spree::Api::ErrorHandler',
diff --git a/api/spec/requests/spree/api/v2/storefront/variants_spec.rb b/api/spec/requests/spree/api/v2/storefront/variants_spec.rb
new file mode 100644
index 0000000000..6d6cc7e279
--- /dev/null
+++ b/api/spec/requests/spree/api/v2/storefront/variants_spec.rb
@@ -0,0 +1,65 @@
+require 'spec_helper'
+
+RSpec.describe 'API V2 Storefront Variants Spec', type: :request do
+ describe 'GET /api/v2/storefront/products/:id/variants' do
+ let!(:color) { create(:option_type, :color) }
+ let!(:green_color) { create(:option_value, option_type: color, name: 'green', presentation: 'Green') }
+ let!(:white_color) { create(:option_value, option_type: color, name: 'white', presentation: 'White') }
+
+ let!(:size) { create(:option_type, :size) }
+ let!(:s_size) { create(:option_value, option_type: size, name: 's', presentation: 'S') }
+ let!(:m_size) { create(:option_value, option_type: size, name: 'm', presentation: 'M') }
+
+ let!(:product) { create(:product_in_stock, option_types: [color, size]) }
+
+ let!(:variant_1) { create(:variant, product: product, option_values: [green_color, s_size]) }
+ let!(:variant_2) { create(:variant, product: product, option_values: [green_color, m_size]) }
+ let!(:variant_3) { create(:variant, product: product, option_values: [white_color, s_size]) }
+ let!(:variant_4) { create(:variant, product: product, option_values: [white_color, m_size]) }
+
+ let!(:other_product) { create(:product_in_stock, option_types: [color]) }
+
+ let!(:other_variant_1) { create(:variant, product: other_product, option_values: [green_color]) }
+ let!(:other_variant_2) { create(:variant, product: other_product, option_values: [white_color]) }
+
+ context 'with no params' do
+ before { get "/api/v2/storefront/products/#{product.id}/variants" }
+
+ it_behaves_like 'returns 200 HTTP status'
+
+ it 'returns all product variants including master' do
+ expect(json_response['data'].count).to eq(5)
+
+ expect(json_response['data']).to include(have_type('variant').and(have_id(product.master.id.to_s)))
+ expect(json_response['data']).to include(have_type('variant').and(have_id(variant_1.id.to_s)))
+ expect(json_response['data']).to include(have_type('variant').and(have_id(variant_2.id.to_s)))
+ expect(json_response['data']).to include(have_type('variant').and(have_id(variant_3.id.to_s)))
+ expect(json_response['data']).to include(have_type('variant').and(have_id(variant_4.id.to_s)))
+ end
+ end
+
+ context 'with specified option name and value' do
+ before { get "/api/v2/storefront/products/#{product.id}/variants?filter[options][color]=white" }
+
+ it_behaves_like 'returns 200 HTTP status'
+
+ it 'returns product variants with the specified option' do
+ expect(json_response['data'].count).to eq(2)
+
+ expect(json_response['data']).to include(have_type('variant').and(have_id(variant_3.id.to_s)))
+ expect(json_response['data']).to include(have_type('variant').and(have_id(variant_4.id.to_s)))
+ end
+ end
+
+ context 'with multiple options' do
+ before { get "/api/v2/storefront/products/#{product.id}/variants?filter[options][color]=white&filter[options][size]=m" }
+
+ it_behaves_like 'returns 200 HTTP status'
+
+ it 'returns product variants with the specified options' do
+ expect(json_response['data'].count).to eq(1)
+ expect(json_response['data']).to include(have_type('variant').and(have_id(variant_4.id.to_s)))
+ end
+ end
+ end
+end
diff --git a/api/spec/swagger_helper.rb b/api/spec/swagger_helper.rb
index 6c8a10b411..1d525c85b7 100644
--- a/api/spec/swagger_helper.rb
+++ b/api/spec/swagger_helper.rb
@@ -112,7 +112,7 @@ RSpec.configure do |config|
firstname: { type: :string, example: 'John' },
lastname: { type: :string, example: 'Snow' },
label: { type: :string, example: 'My home address' },
- company: { type: :string, example: 'Vendo Cloud Inc' },
+ company: { type: :string, example: 'Vendo Connect Inc' },
user_id: { type: :string },
public_metadata: { type: :object, example: { 'distance_from_nearest_city_in_km' => 10, 'location_type' => 'building' } },
private_metadata: { type: :object, example: { 'close_to_shop' => true } }
@@ -140,7 +140,7 @@ RSpec.configure do |config|
firstname: { type: :string, example: 'John' },
lastname: { type: :string, example: 'Snow' },
label: { type: :string, example: 'My home address' },
- company: { type: :string, example: 'Vendo Cloud Inc' },
+ company: { type: :string, example: 'Vendo Connect Inc' },
user_id: { type: :string },
public_metadata: { type: :object, example: { 'distance_from_city_in_km' => 10, 'location_type' => 'building' } },
private_metadata: { type: :object, example: { 'close_to_shop' => true } }
diff --git a/core/app/finders/spree/variants/find.rb b/core/app/finders/spree/variants/find.rb
new file mode 100644
index 0000000000..834520c25f
--- /dev/null
+++ b/core/app/finders/spree/variants/find.rb
@@ -0,0 +1,30 @@
+module Spree
+ module Variants
+ class Find
+ def initialize(scope:, params:)
+ @scope = scope
+ @options = params.dig(:filter, :options).try(:to_unsafe_hash)
+ end
+
+ def execute
+ variants = by_options(scope)
+ variants.distinct
+ end
+
+ private
+
+ attr_reader :scope, :options
+
+ def options?
+ options.present?
+ end
+
+ def by_options(variants)
+ return variants unless options?
+
+ variants_ids = options.map { |key, value| variants.with_option_value(key, value)&.ids }.compact.uniq
+ variants.where(id: variants_ids.reduce(&:intersection))
+ end
+ end
+ end
+end
diff --git a/core/app/models/spree/variant.rb b/core/app/models/spree/variant.rb
index 5fff956f93..fb6a6ef0bc 100644
--- a/core/app/models/spree/variant.rb
+++ b/core/app/models/spree/variant.rb
@@ -108,6 +108,14 @@ module Spree
not_discontinued.not_deleted.
for_currency_and_available_price_amount(currency)
end
+
+ scope :with_option_value, lambda { |option_name, option_value|
+ option_type_ids = OptionType.where(name: option_name).ids
+ return none if option_type_ids.empty?
+
+ joins(:option_values).where(Spree::OptionValue.table_name => { name: option_value, option_type_id: option_type_ids })
+ }
+
# FIXME: cost price should be represented with DisplayMoney class
LOCALIZED_NUMBERS = %w(cost_price weight depth width height)
diff --git a/core/lib/spree/core/dependencies.rb b/core/lib/spree/core/dependencies.rb
index 5f92821756..605ffcf0d2 100644
--- a/core/lib/spree/core/dependencies.rb
+++ b/core/lib/spree/core/dependencies.rb
@@ -97,7 +97,8 @@ module Spree
credit_card_finder: 'Spree::CreditCards::Find',
products_finder: 'Spree::Products::Find',
taxon_finder: 'Spree::Taxons::Find',
- line_item_by_variant_finder: 'Spree::LineItems::FindByVariant'
+ line_item_by_variant_finder: 'Spree::LineItems::FindByVariant',
+ variant_finder: 'Spree::Variants::Find'
}.freeze
include Spree::DependenciesHelper
diff --git a/docs/api-reference/platform.yaml b/docs/api-reference/platform.yaml
index 200614dd7b..428672f0f0 100644
--- a/docs/api-reference/platform.yaml
+++ b/docs/api-reference/platform.yaml
@@ -18052,7 +18052,7 @@ components:
example: My home address
company:
type: string
- example: Vendo Cloud Inc
+ example: Vendo Connect Inc
user_id:
type: string
public_metadata:
@@ -18110,7 +18110,7 @@ components:
example: My home address
company:
type: string
- example: Vendo Cloud Inc
+ example: Vendo Connect Inc
user_id:
type: string
public_metadata:
diff --git a/docs/api-reference/storefront.yaml b/docs/api-reference/storefront.yaml
index f8378623b6..cb0b59cbd8 100644
--- a/docs/api-reference/storefront.yaml
+++ b/docs/api-reference/storefront.yaml
@@ -1268,6 +1268,41 @@ paths:
'404':
$ref: '#/components/responses/404NotFound'
summary: Retrieve a Product
+ /api/v2/storefront/products/{product_slug}/variants:
+ get:
+ description: |-
+ Returns a list of product variants. You can use product permalink:
+
+ ```
+ GET /api/v2/storefront/products/knitted-high-neck-sweater/variants
+ ```
+
+ Or Product ID:
+
+ ```
+ GET /api/v2/storefront/products/21/variants
+ ```
+
+ **Note** API will attempt a permalink lookup before an ID lookup.
+ tags:
+ - Variants
+ operationId: variants-list
+ parameters:
+ - $ref: '#/components/parameters/ProductSlug'
+ - in: query
+ name: 'filter[options][color]'
+ schema:
+ type: string
+ example: red
+ description: 'Find Variants that have the specified option (eg. color, size) and value (eg. red, XS)'
+ - $ref: '#/components/parameters/PageParam'
+ - $ref: '#/components/parameters/PerPageParam'
+ - $ref: '#/components/parameters/VariantIncludeParam'
+ - $ref: '#/components/parameters/SparseFieldsVariant'
+ responses:
+ '200':
+ $ref: '#/components/responses/VariantList'
+ summary: List all Product Variants
/api/v2/storefront/store:
get:
summary: Return the current Store
@@ -2918,6 +2953,51 @@ components:
- type
- attributes
- relationships
+ OptionValue:
+ title: Option Value
+ type: object
+ x-internal: true
+ properties:
+ id:
+ type: string
+ example: '1'
+ type:
+ type: string
+ default: option_value
+ attributes:
+ type: object
+ properties:
+ name:
+ type: string
+ example: color
+ presentation:
+ type: string
+ example: Color
+ position:
+ type: integer
+ example: 1
+ relationships:
+ type: object
+ properties:
+ option_type:
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ $ref: '#/components/schemas/Relation'
+ filter_value:
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ $ref: '#/components/schemas/Relation'
+ required:
+ - id
+ - type
+ - attributes
+ - relationships
PaymentMethod:
title: Payment Method
description: ''
@@ -3092,6 +3172,13 @@ components:
- $ref: '#/components/schemas/Variant'
- $ref: '#/components/schemas/Image'
- $ref: '#/components/schemas/Taxon'
+ VariantIncludes:
+ x-internal: true
+ title: Product Includes
+ anyOf:
+ - $ref: '#/components/schemas/Product'
+ - $ref: '#/components/schemas/Image'
+ - $ref: '#/components/schemas/OptionValue'
StoreIncludes:
x-internal: false
title: Store Includes
@@ -4084,6 +4171,20 @@ components:
type: string
example: '150'
description: 'Check for the presence of a variant in a wishlist by passing the variant ID, if the variant is present in the wishlist, the `variant_included` attribute will return `true`'
+ VariantIncludeParam:
+ name: include
+ in: query
+ schema:
+ type: string
+ description: |-
+ Specify what related resources (relationships) you would like to receive in the response body. Eg.
+
+ ```
+ product,option_values,images,filter_values
+ ```
+
+ [More information](https://jsonapi.org/format/#fetching-includes)
+ example: 'product,option_values,images,filter_values'
FilterByIds:
in: query
name: 'filter[ids]'
@@ -4168,6 +4269,13 @@ components:
schema:
type: string
example: 'price,description,name'
+ SparseFieldsVariant:
+ name: 'fields[variant]'
+ in: query
+ description: 'Specify the fields you would like returned in the response body. [More information](https://jsonapi.org/format/#fetching-sparse-fieldsets).'
+ schema:
+ type: string
+ example: 'price,currency,options,options_text'
SparseFieldsStore:
name: 'fields[store]'
in: query
@@ -8569,6 +8677,29 @@ components:
prev: 'http://localhost:3000/api/v2/storefront/products?page=1'
last: 'http://localhost:3000/api/v2/storefront/products?page=5'
first: 'http://localhost:3000/api/v2/storefront/products?page=1'
+ VariantList:
+ description: 200 Success - Returns an array of `variant` objects.
+ content:
+ application/vnd.api+json:
+ schema:
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ $ref: '#/components/schemas/Variant'
+ included:
+ type: array
+ items:
+ $ref: '#/components/schemas/VariantIncludes'
+ meta:
+ $ref: '#/components/schemas/ListMeta'
+ links:
+ $ref: '#/components/schemas/ListLinks'
+ required:
+ - data
+ - meta
+ - links
Store:
description: 200 Success - Returns the `store` object.
content:
@@ -16520,6 +16651,7 @@ tags:
- name: Menus
- name: Order Status
- name: Products
+ - name: Variants
- name: Stores
- name: Taxons
- name: Wishlists