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.

Persist coupon codes on carts and orders

Damian Legawiecd78f5fc8849c
diff --git a/packages/admin-sdk/src/types/generated/Order.ts b/packages/admin-sdk/src/types/generated/Order.ts
index 0484de6eeb..21fedd395c 100644
--- a/packages/admin-sdk/src/types/generated/Order.ts
+++ b/packages/admin-sdk/src/types/generated/Order.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 1366ec45238e85d679d9ea819923b916
+// Typelizer digest 8b878c9b00bbfb1e3cf62a5b088a1418
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {AppliedPromotion, LineItem, Fulfillment, Payment, Address, GiftCard, Market, Channel, StockLocation, PaymentMethod, Customer, ReturnAuthorization, Reimbursement} from '@/types'
@@ -13,6 +13,7 @@ interface Order {
currency: string;
locale: string | null;
total_quantity: number;
+ coupon_code: string | null;
fulfillment_status: string | null;
payment_status: string | null;
completed_at: string | null;
diff --git a/packages/sdk/src/types/generated/Cart.ts b/packages/sdk/src/types/generated/Cart.ts
index 96388f879c..cb64f9dfe5 100644
--- a/packages/sdk/src/types/generated/Cart.ts
+++ b/packages/sdk/src/types/generated/Cart.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 3d56d7fbb58794a17f00610bc537ac71
+// Typelizer digest 33c04dc6c5d4bc56f52a6833f901a5fd
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {AppliedPromotion, LineItem, Fulfillment, Payment, Address, PaymentMethod, GiftCard, Market} from '@/types'
@@ -15,6 +15,7 @@ interface Cart {
locale: string | null;
total_quantity: number;
warnings: Array<{code: string, message: string, line_item_id?: string, variant_id?: string}>;
+ coupon_code: string | null;
item_total: string | null;
display_item_total: string | null;
adjustment_total: string | null;
diff --git a/packages/sdk/src/types/generated/Order.ts b/packages/sdk/src/types/generated/Order.ts
index 362d33d1db..13058ecc15 100644
--- a/packages/sdk/src/types/generated/Order.ts
+++ b/packages/sdk/src/types/generated/Order.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 5e5999265905b5fa1d9bfcdeabad6efd
+// Typelizer digest 077bc4d594f125cf29c01c1083841241
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {AppliedPromotion, LineItem, Fulfillment, Payment, Address, GiftCard, Market} from '@/types'
@@ -13,6 +13,7 @@ interface Order {
currency: string;
locale: string | null;
total_quantity: number;
+ coupon_code: string | null;
fulfillment_status: string | null;
payment_status: string | null;
completed_at: string | null;
diff --git a/packages/sdk/src/zod/generated/Cart.ts b/packages/sdk/src/zod/generated/Cart.ts
index 97a5f57227..747f8802da 100644
--- a/packages/sdk/src/zod/generated/Cart.ts
+++ b/packages/sdk/src/zod/generated/Cart.ts
@@ -21,6 +21,7 @@ export const CartSchema = z.object({
locale: z.string().nullable(),
total_quantity: z.number(),
warnings: z.array(z.any()),
+ coupon_code: z.string().nullable(),
item_total: z.string().nullable(),
display_item_total: z.string().nullable(),
adjustment_total: z.string().nullable(),
diff --git a/packages/sdk/src/zod/generated/Order.ts b/packages/sdk/src/zod/generated/Order.ts
index bf9fe9fc3d..bfb9d44240 100644
--- a/packages/sdk/src/zod/generated/Order.ts
+++ b/packages/sdk/src/zod/generated/Order.ts
@@ -18,6 +18,7 @@ export const OrderSchema = z.object({
currency: z.string(),
locale: z.string().nullable(),
total_quantity: z.number(),
+ coupon_code: z.string().nullable(),
fulfillment_status: z.string().nullable(),
payment_status: z.string().nullable(),
completed_at: z.string().nullable(),
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/discount_codes_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/discount_codes_controller.rb
index cc197040d0..cb240b96d1 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/discount_codes_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/discount_codes_controller.rb
@@ -10,16 +10,22 @@ module Spree
before_action :find_cart!
# POST /api/v3/store/carts/:cart_id/discount_codes
- # Apply a discount code to the cart
+ # Applies a discount code. A real-but-not-yet-eligible code is
+ # accepted and persisted — recalculation activates the discount
+ # the moment the cart qualifies (Shopify-parity). Unknown/expired
+ # codes are rejected and never persisted.
def create
with_order_lock do
@cart.coupon_code = permitted_params[:code]
coupon_handler.apply
- if coupon_handler.successful?
+ if coupon_handler.successful? || pending_eligibility?
+ @cart.save!(validate: false) if @cart.changed?
+ @cart.reload
render_cart(status: :created)
else
+ @cart.update_column(:coupon_code, nil) if @cart.read_attribute(:coupon_code).present?
render_errors(coupon_handler.error)
end
end
@@ -46,6 +52,12 @@ module Spree
@coupon_handler ||= Spree.coupon_handler.new(@cart, enable_gift_cards: false)
end
+ # A real code on a cart that doesn't qualify yet: the code is
+ # kept and recalculation activates it later.
+ def pending_eligibility?
+ coupon_handler.status_code == :coupon_code_not_eligible
+ end
+
def permitted_params
params.permit(:code)
end
diff --git a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
index d907215ece..652cfa0469 100644
--- a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
@@ -7,6 +7,7 @@ module Spree
typelize number: :string, current_step: :string, completed_steps: 'string[]', token: :string, email: [:string, nullable: true],
customer_note: [:string, nullable: true], market_id: [:string, nullable: true], channel_id: [:string, nullable: true],
currency: :string, locale: [:string, nullable: true], total_quantity: :number,
+ coupon_code: [:string, nullable: true],
requirements: 'Array<{step: string, field: string, message: string}>',
item_total: [:string, nullable: true], display_item_total: [:string, nullable: true],
delivery_total: [:string, nullable: true], display_delivery_total: [:string, nullable: true],
@@ -42,7 +43,7 @@ module Spree
end
attributes :number, :token, :email, :customer_note,
- :currency, :locale, :total_quantity, :warnings
+ :currency, :locale, :total_quantity, :warnings, :coupon_code
# Nulled for gated (prices_hidden) guests so the cart can't leak the
# prices that product/variant serializers already withhold.
diff --git a/spree/api/app/serializers/spree/api/v3/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/order_serializer.rb
index b91d13943b..72e5da3183 100644
--- a/spree/api/app/serializers/spree/api/v3/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/order_serializer.rb
@@ -8,6 +8,7 @@ module Spree
customer_note: [:string, nullable: true],
market_id: [:string, nullable: true], channel_id: [:string, nullable: true],
currency: :string, locale: [:string, nullable: true], total_quantity: :number,
+ coupon_code: [:string, nullable: true],
fulfillment_status: [:string, nullable: true], payment_status: [:string, nullable: true],
item_total: [:string, nullable: true], display_item_total: [:string, nullable: true],
delivery_total: [:string, nullable: true], display_delivery_total: [:string, nullable: true],
@@ -34,7 +35,7 @@ module Spree
end
attributes :number, :email, :customer_note,
- :currency, :locale, :total_quantity,
+ :currency, :locale, :total_quantity, :coupon_code,
:fulfillment_status, :payment_status,
completed_at: :iso8601
diff --git a/spree/core/app/models/spree/adjusters/promotion.rb b/spree/core/app/models/spree/adjusters/promotion.rb
index 99f76e1cca..24ab3efb80 100644
--- a/spree/core/app/models/spree/adjusters/promotion.rb
+++ b/spree/core/app/models/spree/adjusters/promotion.rb
@@ -24,6 +24,7 @@ module Spree
apply_line_item_discounts
apply_fulfillment_discounts
apply_order_level_discount
+ sync_coupon_promotion_joins
cleanup_stale_rows
end
@@ -59,11 +60,40 @@ module Spree
def eligible_promotions
@eligible_promotions ||= begin
- promotions = (order.promotions.includes(:promotion_actions).to_a + extra_promotions).uniq(&:id)
+ promotions = (order.promotions.includes(:promotion_actions).to_a + extra_promotions + coupon_promotions).uniq(&:id)
promotions.select { |promotion| promotion.eligible?(order) }
end
end
+ # The owner's PERSISTED coupon code keeps its promotion in candidacy
+ # even before it ever applied — the discount activates on the exact
+ # recalculation where the cart first qualifies, and deactivates the
+ # same way (Shopify-parity for cart-level discount codes). In-memory
+ # assignments deliberately don't participate: unsaved codes belong to
+ # the explicit PromotionHandler::Coupon path.
+ def coupon_promotions
+ return [] unless order.class.respond_to?(:column_names) && order.class.column_names.include?('coupon_code')
+
+ code = order.read_attribute(:coupon_code)
+ return [] if code.blank?
+
+ promotion = order.store.promotions.active.with_coupon_code(code)
+ return [] if promotion.nil? || promotion.usage_limit_exceeded?(order)
+
+ [promotion]
+ end
+
+ # A coupon promotion that produced rows becomes an applied promotion —
+ # the join drives the storefront discounts summary and completion-time
+ # usage accounting.
+ def sync_coupon_promotion_joins
+ coupon_promotions.each do |promotion|
+ next unless order.discounts.where(promotion_id: promotion.id).exists?
+
+ order.order_promotions.find_or_create_by!(promotion: promotion)
+ end
+ end
+
def discount_actions(scope)
eligible_promotions.flat_map(&:promotion_actions).select { |action| action.discount_scope == scope }
end
diff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rb
index 150e6a33bf..67fc8e98c4 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -370,7 +370,7 @@ module Spree
when Spree::LineItem
!promotable.product.promotionable?
when Spree::Order
- (promotable.item_count.positive? || promotable.line_items.any?) &&
+ (promotable.total_quantity.positive? || promotable.line_items.any?) &&
promotable.line_items.joins(:product).where(spree_products: { promotionable: true }).none?
end
end
diff --git a/spree/core/app/models/spree/promotion_handler/coupon.rb b/spree/core/app/models/spree/promotion_handler/coupon.rb
index 989c3f9bb5..6af1e1fb4f 100644
--- a/spree/core/app/models/spree/promotion_handler/coupon.rb
+++ b/spree/core/app/models/spree/promotion_handler/coupon.rb
@@ -12,6 +12,9 @@ module Spree
def apply
if gift_cards_enabled? && load_gift_card_code
+ # The entered code is a gift card, not a coupon — drop the pending
+ # coupon_code assignment so locking flows don't see a dirty record.
+ order.restore_attributes([:coupon_code]) if order.has_attribute?(:coupon_code) && order.will_save_change_to_attribute?(:coupon_code)
if @gift_card.expired?
set_error_code :gift_card_expired
@@ -63,6 +66,7 @@ module Spree
if promotion.present?
# Order promotion has to be destroyed before line item removing
order.promotions.delete(promotion)
+ clear_persisted_coupon_code(coupon_code)
if promotion.multi_codes?
coupon_code = promotion.coupon_codes.find_by(order: order)
@@ -120,6 +124,15 @@ module Spree
private
+ # Carts persist the entered code (adjuster candidacy) — removing the
+ # promotion must clear it or recalculation re-applies immediately.
+ def clear_persisted_coupon_code(code)
+ return unless order.has_attribute?(:coupon_code)
+ return unless order.read_attribute(:coupon_code).to_s.casecmp?(code.to_s.strip)
+
+ order.update_column(:coupon_code, nil)
+ end
+
def remove_promotion_adjustments(promotion)
order.discounts.where(promotion_action_id: promotion.actions.pluck(:id)).destroy_all
end
diff --git a/spree/core/app/services/spree/carts/complete.rb b/spree/core/app/services/spree/carts/complete.rb
index 46a57e2bff..99ff577a52 100644
--- a/spree/core/app/services/spree/carts/complete.rb
+++ b/spree/core/app/services/spree/carts/complete.rb
@@ -110,6 +110,7 @@ module Spree
user: cart.customer,
token: cart.token,
accept_marketing: cart.accept_marketing,
+ coupon_code: cart.read_attribute(:coupon_code),
preferred_stock_location_id: cart.preferred_stock_location_id,
special_instructions: cart.special_instructions,
last_ip_address: cart.last_ip_address,
@@ -126,13 +127,13 @@ module Spree
order.update_columns(
item_total: cart.item_total,
- item_count: cart.item_count,
+ total_quantity: cart.total_quantity,
adjustment_total: cart.adjustment_total,
included_tax_total: cart.included_tax_total,
additional_tax_total: cart.additional_tax_total,
taxable_adjustment_total: cart.taxable_adjustment_total,
non_taxable_adjustment_total: cart.non_taxable_adjustment_total,
- promo_total: cart.promo_total,
+ discount_total: cart.discount_total,
fee_total: cart.fee_total,
delivery_total: cart.delivery_total,
total: cart.total,
diff --git a/spree/core/db/migrate/20260729140001_add_coupon_code_to_spree_orders.rb b/spree/core/db/migrate/20260729140001_add_coupon_code_to_spree_orders.rb
new file mode 100644
index 0000000000..304e61934c
--- /dev/null
+++ b/spree/core/db/migrate/20260729140001_add_coupon_code_to_spree_orders.rb
@@ -0,0 +1,6 @@
+class AddCouponCodeToSpreeOrders < ActiveRecord::Migration[7.2]
+ def change
+ add_column :spree_orders, :coupon_code, :string
+ add_index :spree_orders, :coupon_code
+ end
+end
diff --git a/spree/core/spec/models/spree/adjusters/coupon_code_retry_spec.rb b/spree/core/spec/models/spree/adjusters/coupon_code_retry_spec.rb
new file mode 100644
index 0000000000..516c742c03
--- /dev/null
+++ b/spree/core/spec/models/spree/adjusters/coupon_code_retry_spec.rb
@@ -0,0 +1,50 @@
+require 'spec_helper'
+
+# The persisted cart coupon code keeps its promotion in adjuster candidacy:
+# the discount activates on the recalculation where the cart first qualifies
+# and deactivates the same way (docs/plans review 2026-07-29).
+describe 'coupon code retry on recalculation' do
+ let(:store) { @default_store }
+ let!(:promotion) do
+ create(:promotion_with_item_total_rule, :with_line_item_adjustment,
+ code: 'save5', kind: :coupon_code, store: store,
+ item_total_threshold_amount: 30, adjustment_rate: 5)
+ end
+ let(:cart) { create(:cart_with_line_items, store: store, line_items_price: 10) }
+
+ it 'activates the pending code once the cart qualifies and deactivates below threshold' do
+ cart.update!(coupon_code: 'save5')
+ cart.update_with_updater!
+ expect(cart.reload.discounts.where(promotion_id: promotion.id)).to be_empty
+
+ # Grow the cart past the threshold — recalculation applies the code.
+ create(:line_item, cart: cart, order: nil, price: 25)
+ cart.line_items.reload
+ cart.update_with_updater!
+
+ expect(cart.reload.discounts.where(promotion_id: promotion.id)).to be_present
+ expect(cart.order_promotions.where(promotion_id: promotion.id)).to be_present
+
+ # Shrink below the threshold — rows deactivate, the code stays.
+ cart.line_items.order(:created_at).last.destroy!
+ cart.line_items.reload
+ cart.update_with_updater!
+
+ expect(cart.reload.discounts.where(promotion_id: promotion.id)).to be_empty
+ expect(cart.read_attribute(:coupon_code)).to eq('save5')
+ end
+
+ it 'clears the persisted code when the promotion is removed' do
+ cart.line_items.first.update!(price: 50)
+ cart.update!(coupon_code: 'save5')
+ cart.update_with_updater!
+ expect(cart.reload.discounts.where(promotion_id: promotion.id)).to be_present
+
+ handler = Spree::PromotionHandler::Coupon.new(cart)
+ handler.remove('save5')
+
+ expect(handler.successful?).to be(true)
+ expect(cart.reload.read_attribute(:coupon_code)).to be_nil
+ expect(cart.discounts.where(promotion_id: promotion.id)).to be_empty
+ end
+end
diff --git a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
index 7b150213fa..98145b8ce5 100644
--- a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
@@ -228,7 +228,6 @@ module Spree
let!(:tax_category) { create(:tax_category, name: 'Taxable Foo') }
let!(:rate) { create(:tax_rate, amount: 0.10, tax_category: tax_category, zone: zone) }
- before { allow(order).to receive(:coupon_code).and_return '10off' }
context 'and the product price is less than promo discount' do
let(:product_list) { create_list(:product, 3, tax_category: tax_category, price: 9.0) }
@@ -238,6 +237,7 @@ module Spree
it 'successfully applies the promo' do
# 3 * (9 + 0.9)
expect(order.total).to eq(29.7)
+ order.coupon_code = '10off'
subject.apply
expect(subject.success).to be_present
# 3 * ((9 - [9,10].min) + 0)
@@ -254,6 +254,7 @@ module Spree
it 'successfully applies the promo' do
# 3 * (22 + 2.2)
expect(order.total.to_f).to eq(72.6)
+ order.coupon_code = '10off'
subject.apply
expect(subject.success).to be_present
# 3 * ( (22 - 10) + 1.2)
@@ -267,13 +268,13 @@ module Spree
let(:product_list) { create_list(:product, 3, tax_category: tax_category, price: 10.0) }
before do
- allow(order).to receive(:coupon_code).and_return '20off'
product_list.each { |item| Spree::Carts::AddItem.call(order: order, variant: item.default_variant, quantity: 2) }
end
it 'successfully applies the promo' do
# 3 * ((2 * 10) + 2.0)
expect(order.total.to_f).to eq(66)
+ order.coupon_code = '20off'
subject.apply
expect(subject.success).to be_present
# 0