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.

normalize promotion code before validation

Maksim Shilovf4a064e1565f
diff --git a/core/app/models/spree/promotion.rb b/core/app/models/spree/promotion.rb
index 5f888016ef..ca63197b85 100644
--- a/core/app/models/spree/promotion.rb
+++ b/core/app/models/spree/promotion.rb
@@ -28,6 +28,8 @@ module Spree
before_save :normalize_blank_values
+ before_validation :normalize_code
+
scope :coupons, -> { where.not(code: nil) }
scope :advertised, -> { where(advertise: true) }
scope :applied, lambda {
@@ -227,6 +229,10 @@ module Spree
end
end
+ def normalize_code
+ self.code = code.strip if code.present?
+ end
+
def match_all?
match_policy == 'all'
end
diff --git a/core/spec/models/spree/promotion_spec.rb b/core/spec/models/spree/promotion_spec.rb
index 2a4d987711..ac78948fbd 100644
--- a/core/spec/models/spree/promotion_spec.rb
+++ b/core/spec/models/spree/promotion_spec.rb
@@ -25,6 +25,38 @@ describe Spree::Promotion, type: :model do
expect(@valid_promotion).not_to be_valid
end
+ describe 'code should be unique' do
+ let(:code) { 'code' }
+
+ context 'code is unique' do
+ before do
+ @valid_promotion.code = code
+ end
+
+ it { expect(@valid_promotion).to be_valid }
+ end
+
+ context 'code is not unique' do
+ let!(:promotion_with_code) { Spree::Promotion.create! name: 'test1', code: code }
+
+ context 'code is identical' do
+ before do
+ @valid_promotion.code = code
+ end
+
+ it { expect(@valid_promotion).not_to be_valid }
+ end
+
+ context 'code is identical with whitespace' do
+ before do
+ @valid_promotion.code = code + ' '
+ end
+
+ it { expect(@valid_promotion).not_to be_valid }
+ end
+ end
+ end
+
describe 'expires_at_must_be_later_than_starts_at' do
before do
@valid_promotion.starts_at = Date.today