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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add `coupon_code` attribute to `spree_orders` and finalize rename to match `spree_carts`
Damian Legawieced47d683319a
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex 6ecb37ddca..ae8e459c9c 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -89,6 +89,14 @@ bundle exec rake spree:migrate_taxons_to_categories_and_collectionsTaxons become `Spree::Category` (hierarchy) and automatic taxons become `Spree::Collection` (flat, rule-based). `Spree::Taxon` remains as an alias for one release.+### Backfill order coupon codes++```bash+bundle exec rake spree:backfill_order_coupon_codes+```++`spree_orders` gains a `coupon_code` column (parity with carts). Historical placed orders applied coupons only through the promotion join tables — this fills the column from the attached coupon-code record (or the applied single-code promotion) so admin filtering and the serializer answer consistently for old orders.+### Markets on orders```bash@@ -213,6 +221,8 @@ Every rename keeps the legacy name working for one release with a deprecation wa| `Order#finalize!` | `Spree.order_complete_workflow` || `Order#updater`, `Spree::OrderUpdater`, `Spree::CartUpdater` | `#recalculate_totals!` / `#update_statuses!` || `Order#shipping_discount` | `#fulfillment_discount` |+| `Order#special_instructions` | `#customer_note` (column renamed) |+| `Order#promo_total`, `#item_count`, `#ship_total` | `#discount_total`, `#total_quantity`, `#delivery_total` (columns renamed) || `use_billing` / `clone_billing_address` | `use_shipping` (shipping address is canonical) || `Fulfillment#ship`, `#ship!`, `#shipped?`, `#can_ship?`, `#shipping_method`, `#add_shipping_method` | `#fulfill`, `#fulfill!`, `#fulfilled?`, `#can_fulfill?`, `#delivery_method`, `#add_delivery_method` || `LineItem#target_shipment` | `#target_fulfillment` |diff --git a/docs/plans/5.4-6.0-eu-legal-compliance.md b/docs/plans/5.4-6.0-eu-legal-compliance.mdindex 344995e820..b4bcca67e0 100644--- a/docs/plans/5.4-6.0-eu-legal-compliance.md+++ b/docs/plans/5.4-6.0-eu-legal-compliance.md@@ -308,7 +308,7 @@ module Spreetotal: order.total&.to_s,currency: order.currency,completed_at: order.completed_at&.iso8601,- special_instructions: order.special_instructions,+ customer_note: order.customer_note,billing_address: address_hash(order.bill_address),shipping_address: address_hash(order.ship_address),line_items: order.line_items.map { |li|diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rbindex e444fbea3c..cc4bfca541 100644--- a/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb@@ -224,7 +224,7 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/atype: :object,properties: {email: { type: :string },- special_instructions: { type: :string },+ customer_note: { type: :string },internal_note: { type: :string },channel_id: { type: :string, description: 'Channel ID' },preferred_stock_location_id: {diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rbindex 51f7869226..c984dbc1d9 100644--- a/spree/core/app/models/spree/cart.rb+++ b/spree/core/app/models/spree/cart.rb@@ -56,15 +56,9 @@ module Spreealias_method :user, :customeralias_method :user=, :customer=alias_attribute :user_id, :customer_id- # Normalizes like the legacy Order writer so lookups stay case-insensitive.- def coupon_code=(code)- normalized = begin- code.strip.downcase- rescue StandardError- nil- end- super(normalized)- end+ # Codes are stored stripped + lowercased so lookups stay case-insensitive;+ # normalizes also applies to finder values.+ normalizes :coupon_code, with: ->(code) { code.to_s.strip.downcase.presence }# Pickup location choice is a preference (mirrors the admin-user# preference of the same name), copied to the order column at completion.diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 7a91031793..7db167ab31 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -87,9 +87,20 @@ module Spree# aliases one release.alias_attribute :promo_total, :discount_totalalias display_promo_total display_discount_total- alias_attribute :customer_note, :special_instructionsalias_attribute :item_count, :total_quantity+ # @deprecated The column is +customer_note+ since 6.0; removed in 6.1.+ def special_instructions+ Spree::Deprecation.warn('Spree::Order#special_instructions is deprecated and will be removed in Spree 6.1. Use #customer_note instead.')+ customer_note+ end++ # @deprecated See {#special_instructions}; removed in 6.1.+ def special_instructions=(value)+ Spree::Deprecation.warn('Spree::Order#special_instructions= is deprecated and will be removed in Spree 6.1. Use #customer_note= instead.')+ self.customer_note = value+ end+MONEY_THRESHOLD = 100_000_000MONEY_VALIDATION = {presence: true,@@ -720,14 +731,7 @@ module Spree)end- def coupon_code=(code)- normalized = begin- code.strip.downcase- rescue StandardError- nil- end- super(normalized)- end+ normalizes :coupon_code, with: ->(code) { code.to_s.strip.downcase.presence }def can_add_coupon?Spree::Deprecation.warn('Spree::Order#can_add_coupon? is deprecated and will be removed in Spree 6.1. Use Spree::Promotion.order_activatable? instead.')diff --git a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rbindex c58694a413..2cf4c4cd2c 100644--- a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb+++ b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb@@ -124,7 +124,7 @@ module Spreeformat_date(line_item.order.fulfillments.first&.fulfilled_at),index.zero? ? format_date(order.canceled_at) : nil,index.zero? ? order.canceler&.email : nil,- index.zero? ? order.special_instructions : nil+ index.zero? ? order.customer_note : nil]if index.zero?diff --git a/spree/core/db/migrate/20260729120001_rename_order_totals_to_standard_names.rb b/spree/core/db/migrate/20260729120001_rename_order_totals_to_standard_names.rbindex 88e4e6c9cd..df18087862 100644--- a/spree/core/db/migrate/20260729120001_rename_order_totals_to_standard_names.rb+++ b/spree/core/db/migrate/20260729120001_rename_order_totals_to_standard_names.rb@@ -2,5 +2,6 @@ class RenameOrderTotalsToStandardNames < ActiveRecord::Migration[7.2]def changerename_column :spree_orders, :promo_total, :discount_totalrename_column :spree_orders, :item_count, :total_quantity+ rename_column :spree_orders, :special_instructions, :customer_noteendenddiff --git a/spree/core/lib/tasks/order_coupon_code_backfill.rake b/spree/core/lib/tasks/order_coupon_code_backfill.rakenew file mode 100644index 0000000000..2b9a26c5c2--- /dev/null+++ b/spree/core/lib/tasks/order_coupon_code_backfill.rake@@ -0,0 +1,32 @@+# frozen_string_literal: true++# 5.6 → 6.0: spree_orders gained a coupon_code column (parity with+# spree_carts). Historical placed orders applied coupons through the+# promotion join tables only — backfill the column from those records so+# admin filtering and the serializer answer consistently for old orders.+namespace :spree do+ desc 'Backfill spree_orders.coupon_code from applied promotion/coupon-code records'+ task backfill_order_coupon_codes: :environment do+ batch_size = ENV.fetch('BATCH_SIZE', 500).to_i+ updated = 0++ scope = Spree::Order.unscoped.where(coupon_code: nil).where.not(completed_at: nil)++ scope.in_batches(of: batch_size) do |batch|+ batch.each do |order|+ code = Spree::CouponCode.where(order_id: order.id).order(:id).limit(1).pick(:code) ||+ Spree::Promotion.joins(:order_promotions).+ where(Spree::OrderPromotion.table_name => { order_id: order.id }).+ where.not(code: [nil, '']).order(:id).limit(1).pick(:code)+ next if code.blank?++ order.update_columns(coupon_code: code.downcase)+ updated += 1+ end+ print '.'+ end++ puts+ puts "backfill_order_coupon_codes done. updated: #{updated}"+ end+enddiff --git a/spree/core/spec/lib/tasks/order_coupon_code_backfill_spec.rb b/spree/core/spec/lib/tasks/order_coupon_code_backfill_spec.rbnew file mode 100644index 0000000000..a728d0e078--- /dev/null+++ b/spree/core/spec/lib/tasks/order_coupon_code_backfill_spec.rb@@ -0,0 +1,54 @@+require 'spec_helper'+require 'rake'++describe 'spree:backfill_order_coupon_codes' do+ before(:all) do+ Rake::Task.define_task(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'order_coupon_code_backfill.rake')+ end++ let(:store) { @default_store }++ def run_task+ task = Rake::Task['spree:backfill_order_coupon_codes']+ task.reenable+ old = $stdout.dup+ $stdout.reopen(File::NULL, 'w')+ task.invoke+ ensure+ $stdout.reopen(old)+ end++ let(:order) { create(:completed_order_with_totals, store: store) }++ it 'backfills from an attached coupon code row' do+ promotion = create(:promotion, kind: :coupon_code, store: store)+ create(:coupon_code, promotion: promotion, order: order, code: 'MULTI42', state: 'used')+ order.update_columns(coupon_code: nil)++ run_task++ expect(order.reload.read_attribute(:coupon_code)).to eq('multi42')+ end++ it 'falls back to the applied single-code promotion' do+ promotion = create(:promotion, kind: :coupon_code, code: 'save5', store: store)+ Spree::OrderPromotion.create!(order: order, promotion: promotion)+ order.update_columns(coupon_code: nil)++ run_task++ expect(order.reload.read_attribute(:coupon_code)).to eq('save5')+ end++ it 'leaves orders without promotion records untouched and is idempotent' do+ order.update_columns(coupon_code: nil)++ run_task+ expect(order.reload.read_attribute(:coupon_code)).to be_nil++ order.update_columns(coupon_code: 'existing')+ run_task+ expect(order.reload.read_attribute(:coupon_code)).to eq('existing')+ end+enddiff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rbindex ea97a115e6..ccb942c209 100644--- a/spree/core/spec/models/spree/order_spec.rb+++ b/spree/core/spec/models/spree/order_spec.rb@@ -707,10 +707,10 @@ describe Spree::Order, type: :model doendit 'does not persist other changes to the order' do- order.special_instructions = 'unpersisted change'+ order.customer_note = 'unpersisted change'order.associate_user!(user)order.reload- expect(order.special_instructions).to be_blank+ expect(order.customer_note).to be_blankendit 'does not change any other orders' do