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.

Improve price/original_price handling in Product / Variant Serializer

Damian Legawiec66c6547b9502
diff --git a/CLAUDE.md b/CLAUDE.md
index 9936e275c8..5d89fccf47 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -113,7 +113,7 @@ end
### Serializers
-API v3 uses Alba serializers located in `api/app/serializers/spree/api/v3/`. We have separate serializers for Store and Admin APIs:
+API v3 uses [Alba serializers](https://github.com/okuramasafumi/alba) located in `api/app/serializers/spree/api/v3/`. We have separate serializers for Store and Admin APIs:
- **Store serializers** (`app/serializers/spree/api/v3/`) - Customer-facing, limited data
- **Admin serializers** (`app/serializers/spree/api/v3/admin/`) - Full access, extends store serializers
@@ -158,7 +158,9 @@ We use [typelizer](https://github.com/skryukov/typelizer) to generate TypeScript
### API Authentication
-API uses Publishable and Secret API Keys for authentication. Publishable works for Store API and Secret for Admin API.
+API uses Publishable and Secret API Keys for authentication. Publishable works for Store API and Secret for Admin API, both are passed via headers `x-spree-api-key`.
+
+User authentication uses JWT tokens, passed via headers `Authorization: Bearer <token>`.
## Events System
@@ -170,17 +172,18 @@ order.publish_event('order.completed')
Place subscriber classes in `app/subscribers/spree/` directory:
-```ruby
-# app/subscribers/spree/order_webhook_subscriber.rb
+```ruby app/subscribers/spree/order_completed_subscriber.rb
module Spree
- module OrderWebhookSubscriber
- include Spree::Event::Subscriber
+ class OrderCompletedSubscriber < Spree::Subscriber
+ subscribes_to 'order.complete'
- event_action :order_completed
+ def handle(event)
+ order_id = event.payload['id']
+ order = Spree::Order.find_by(id: order_id)
+ return unless order
- def order_completed(event)
- order = event.payload[:order]
- # Handle the event
+ # Your custom logic here
+ ExternalService.notify_order_placed(order)
end
end
end
@@ -188,7 +191,7 @@ end
For new models that publish events, please add `publishes_lifecycle_events` concern to the model.
-You also need to create an event serializer for the model, see [Events](/docs/developer/core-concepts/events.mdx) for more details.
+You also need to create an event serializer for the model, see [Events](docs/developer/core-concepts/events.mdx) for more details.
## Dependencies System
@@ -207,6 +210,7 @@ When adding new resources to the admin, you need to register tables and navigati
### Admin Tables
+For rendering records lists in Admin always use [Admin Tables](docs/developer/admin/tables.mdx)
Register new tables in `admin/config/initializers/spree_admin_tables.rb`:
```ruby
@@ -316,6 +320,8 @@ Navigation options:
## Testing
+Always run tests before committing changes. Always run tests after making changes.
+
### Test Application
To run tests you need to create test app with `bundle exec rake test_app` in every gem directory (eg. admin, api, core, etc.)
diff --git a/api/app/serializers/spree/api/v3/base_serializer.rb b/api/app/serializers/spree/api/v3/base_serializer.rb
index f3a1b88a76..59f6629be2 100644
--- a/api/app/serializers/spree/api/v3/base_serializer.rb
+++ b/api/app/serializers/spree/api/v3/base_serializer.rb
@@ -55,10 +55,15 @@ module Spree
# Returns price for a variant using full Price List resolution
# This may return a price from a price list if applicable
+ # Memoized per variant to avoid duplicate queries
def price_for(variant, quantity: nil)
return nil unless variant.respond_to?(:price_for)
- variant.price_for(
+ @price_for_cache ||= {}
+ cache_key = [variant.id, quantity]
+ return @price_for_cache[cache_key] if @price_for_cache.key?(cache_key)
+
+ @price_for_cache[cache_key] = variant.price_for(
currency: current_currency,
store: current_store,
user: current_user,
@@ -68,10 +73,14 @@ module Spree
# Returns the base price for a variant without Price List resolution
# This is the "original" price before any price list discounts
+ # Memoized per variant to avoid duplicate queries
def price_in(variant)
return nil unless variant.respond_to?(:price_in)
- variant.price_in(current_currency)
+ @price_in_cache ||= {}
+ return @price_in_cache[variant.id] if @price_in_cache.key?(variant.id)
+
+ @price_in_cache[variant.id] = variant.price_in(current_currency)
end
def image_url_for(image)
diff --git a/api/app/serializers/spree/api/v3/product_serializer.rb b/api/app/serializers/spree/api/v3/product_serializer.rb
index fd7c3d17e0..1c5989ba64 100644
--- a/api/app/serializers/spree/api/v3/product_serializer.rb
+++ b/api/app/serializers/spree/api/v3/product_serializer.rb
@@ -12,7 +12,7 @@ module Spree
available_on: 'string | null',
purchasable: :boolean, in_stock: :boolean, backorderable: :boolean, available: :boolean,
price: 'StorePrice',
- original_price: 'StorePrice',
+ original_price: 'StorePrice | null',
tags: 'string[]'
attributes :name, :description, :slug,
@@ -56,9 +56,15 @@ module Spree
end
# Original price - base price without price list resolution (for showing strikethrough)
+ # Returns null when same as calculated price, only populated when a price list discount is applied
attribute :original_price do |product|
- price = price_in(product.default_variant)
- Spree.api.price_serializer.new(price, params: params).to_h if price.present?
+ variant = product.default_variant
+ calculated = price_for(variant)
+ base = price_in(variant)
+
+ if calculated.present? && base.present? && calculated.id != base.id
+ Spree.api.price_serializer.new(base, params: params).to_h
+ end
end
# Conditional associations
diff --git a/api/app/serializers/spree/api/v3/variant_serializer.rb b/api/app/serializers/spree/api/v3/variant_serializer.rb
index f6f8e9ce59..86feb9143b 100644
--- a/api/app/serializers/spree/api/v3/variant_serializer.rb
+++ b/api/app/serializers/spree/api/v3/variant_serializer.rb
@@ -10,7 +10,7 @@ module Spree
purchasable: :boolean, in_stock: :boolean, backorderable: :boolean,
weight: 'number | null', height: 'number | null', width: 'number | null', depth: 'number | null',
price: 'StorePrice',
- original_price: 'StorePrice'
+ original_price: 'StorePrice | null'
attribute :product_id do |variant|
variant.product&.prefix_id
@@ -59,9 +59,14 @@ module Spree
end
# Original price - base price without price list resolution (for showing strikethrough)
+ # Returns null when same as calculated price, only populated when a price list discount is applied
attribute :original_price do |variant|
- price = price_in(variant)
- Spree.api.price_serializer.new(price, params: params).to_h if price.present?
+ calculated = price_for(variant)
+ base = price_in(variant)
+
+ if calculated.present? && base.present? && calculated.id != base.id
+ Spree.api.price_serializer.new(base, params: params).to_h
+ end
end
# Conditional associations
diff --git a/api/spec/serializers/spree/api/v3/product_serializer_spec.rb b/api/spec/serializers/spree/api/v3/product_serializer_spec.rb
index b2d85ff2be..c9ebe54f93 100644
--- a/api/spec/serializers/spree/api/v3/product_serializer_spec.rb
+++ b/api/spec/serializers/spree/api/v3/product_serializer_spec.rb
@@ -17,13 +17,38 @@ RSpec.describe Spree::Api::V3::ProductSerializer do
)
expect(subject).to have_key('thumbnail_url')
expect(subject).to have_key('price')
- expect(subject).to have_key('original_price')
end
it 'does not include admin-only attributes' do
expect(subject.keys).not_to include('cost_price', 'cost_currency', 'deleted_at', 'sku', 'barcode')
end
+ describe 'original_price' do
+ context 'without price list (base price only)' do
+ it 'returns null when original_price equals calculated price' do
+ expect(subject).to have_key('original_price')
+ expect(subject['original_price']).to be_nil
+ end
+ end
+
+ context 'with price list discount applied' do
+ let(:price_list) { create(:price_list, :active, store: store) }
+ let!(:price_list_price) { create(:price, variant: product.default_variant, currency: 'USD', amount: 50.00, price_list: price_list) }
+
+ before do
+ # Set base price higher than price list price
+ product.default_variant.prices.base_prices.find_by(currency: 'USD').update!(amount: 100.00)
+ end
+
+ it 'includes original_price when different from calculated price' do
+ result = described_class.new(product, params: base_params.merge(price_list: price_list)).to_h
+ expect(result['original_price']).not_to be_nil
+ expect(result['original_price']['amount'].to_f).to eq(100.0)
+ expect(result['price']['amount'].to_f).to eq(50.0)
+ end
+ end
+ end
+
describe 'metafields' do
let(:public_definition) { create(:metafield_definition, resource_type: 'Spree::Product', display_on: 'both') }
let(:private_definition) { create(:metafield_definition, :back_end_only, resource_type: 'Spree::Product') }
diff --git a/api/spec/serializers/spree/api/v3/variant_serializer_spec.rb b/api/spec/serializers/spree/api/v3/variant_serializer_spec.rb
index ea062ac266..e5269a77ba 100644
--- a/api/spec/serializers/spree/api/v3/variant_serializer_spec.rb
+++ b/api/spec/serializers/spree/api/v3/variant_serializer_spec.rb
@@ -16,12 +16,37 @@ RSpec.describe Spree::Api::V3::VariantSerializer do
'product_id' => product.prefix_id
)
expect(subject).to have_key('price')
- expect(subject).to have_key('original_price')
end
it 'does not include admin-only attributes' do
expect(subject.keys).not_to include('cost_price', 'cost_currency', 'total_on_hand', 'deleted_at', 'barcode')
end
+
+ describe 'original_price' do
+ context 'without price list (base price only)' do
+ it 'returns null when original_price equals calculated price' do
+ expect(subject).to have_key('original_price')
+ expect(subject['original_price']).to be_nil
+ end
+ end
+
+ context 'with price list discount applied' do
+ let(:price_list) { create(:price_list, :active, store: store) }
+ let!(:price_list_price) { create(:price, variant: variant, currency: 'USD', amount: 50.00, price_list: price_list) }
+
+ before do
+ # Set base price higher than price list price
+ variant.prices.base_prices.find_by(currency: 'USD').update!(amount: 100.00)
+ end
+
+ it 'includes original_price when different from calculated price' do
+ result = described_class.new(variant, params: base_params.merge(price_list: price_list)).to_h
+ expect(result['original_price']).not_to be_nil
+ expect(result['original_price']['amount'].to_f).to eq(100.0)
+ expect(result['price']['amount'].to_f).to eq(50.0)
+ end
+ end
+ end
end
end
diff --git a/sdk/src/types/generated/AdminProduct.ts b/sdk/src/types/generated/AdminProduct.ts
index 6fc0449bfd..abe5cefaeb 100644
--- a/sdk/src/types/generated/AdminProduct.ts
+++ b/sdk/src/types/generated/AdminProduct.ts
@@ -1,4 +1,4 @@
-// Typelizer digest facd41b13b43734ecb884a0cf6c4df37
+// Typelizer digest 6becabe9d22f6c2ea613e9f755f72652
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {StorePrice, StoreImage, AdminVariant, StoreOptionType, StoreTaxon, AdminMetafield} from '@/types'
@@ -22,7 +22,7 @@ type AdminProduct = {
thumbnail_url: string | null;
tags: Array<string>;
price: StorePrice;
- original_price: StorePrice;
+ original_price: StorePrice | null;
images?: Array<StoreImage>;
variants?: Array<AdminVariant>;
default_variant?: AdminVariant;
diff --git a/sdk/src/types/generated/AdminVariant.ts b/sdk/src/types/generated/AdminVariant.ts
index 3ece6f5c20..961d5c62ec 100644
--- a/sdk/src/types/generated/AdminVariant.ts
+++ b/sdk/src/types/generated/AdminVariant.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 667cc93e3ea9d74a5dce18138c54bad5
+// Typelizer digest 73a4b3ba216f52d55c7f631339a95341
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {StorePrice, StoreImage, StoreOptionValue, AdminMetafield, AdminPrice} from '@/types'
@@ -22,7 +22,7 @@ type AdminVariant = {
width: number | null;
depth: number | null;
price: StorePrice;
- original_price: StorePrice;
+ original_price: StorePrice | null;
images?: Array<StoreImage>;
option_values: Array<StoreOptionValue>;
metafields?: Array<AdminMetafield>;
diff --git a/sdk/src/types/generated/StoreProduct.ts b/sdk/src/types/generated/StoreProduct.ts
index 2cca97758f..e8d042f912 100644
--- a/sdk/src/types/generated/StoreProduct.ts
+++ b/sdk/src/types/generated/StoreProduct.ts
@@ -1,4 +1,4 @@
-// Typelizer digest d5fc34d9f1b52472b66918d452bdf2f9
+// Typelizer digest cd18951bedac9ab02d9d4ab74b50f0ba
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {StorePrice, StoreImage, StoreVariant, StoreOptionType, StoreTaxon, StoreMetafield} from '@/types'
@@ -22,7 +22,7 @@ type StoreProduct = {
thumbnail_url: string | null;
tags: Array<string>;
price: StorePrice;
- original_price: StorePrice;
+ original_price: StorePrice | null;
images?: Array<StoreImage>;
variants?: Array<StoreVariant>;
default_variant?: StoreVariant;
diff --git a/sdk/src/types/generated/StoreVariant.ts b/sdk/src/types/generated/StoreVariant.ts
index 2e6c785393..ccfb9c6925 100644
--- a/sdk/src/types/generated/StoreVariant.ts
+++ b/sdk/src/types/generated/StoreVariant.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 921cbc02d80e22d6911dd7de8397e47e
+// Typelizer digest 517532f364008265ec29f39f67152914
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {StorePrice, StoreImage, StoreOptionValue, StoreMetafield} from '@/types'
@@ -22,7 +22,7 @@ type StoreVariant = {
width: number | null;
depth: number | null;
price: StorePrice;
- original_price: StorePrice;
+ original_price: StorePrice | null;
images?: Array<StoreImage>;
option_values: Array<StoreOptionValue>;
metafields?: Array<StoreMetafield>;