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.

Extended Price model with `name`, `dicounted?`, `was_discounted?`, `zero?` and `non_zero?` methods

Damian Legawiec7f1c2f221f2f
diff --git a/core/app/models/spree/price.rb b/core/app/models/spree/price.rb
index 1d2dc7dfa4..aea81da737 100644
--- a/core/app/models/spree/price.rb
+++ b/core/app/models/spree/price.rb
@@ -68,6 +68,41 @@ module Spree
Spree::Money.new(compare_at_price_including_vat_for(price_options), currency: currency)
end
+ # returns the name of the price in a format of variant name and currency
+ #
+ # @return [String]
+ def name
+ "#{variant.name} - #{currency.upcase}"
+ end
+
+ # returns true if the price is discounted
+ #
+ # @return [Boolean]
+ def discounted?
+ compare_at_amount.to_i.positive? && compare_at_amount > amount
+ end
+
+ # returns true if the price was discounted
+ #
+ # @return [Boolean]
+ def was_discounted?
+ compare_at_amount_was.to_i.positive? && compare_at_amount_was > amount_was
+ end
+
+ # returns true if the price is zero
+ #
+ # @return [Boolean]
+ def zero?
+ amount.nil? || amount.zero?
+ end
+
+ # returns true if the price is not zero
+ #
+ # @return [Boolean]
+ def non_zero?
+ !zero?
+ end
+
private
def ensure_currency
diff --git a/core/spec/models/spree/price_spec.rb b/core/spec/models/spree/price_spec.rb
index 3aa551f54b..85a79af68f 100644
--- a/core/spec/models/spree/price_spec.rb
+++ b/core/spec/models/spree/price_spec.rb
@@ -217,4 +217,30 @@ describe Spree::Price, type: :model do
subject.display_compare_at_price_including_vat_for(nil)
end
end
+
+ describe '#discounted?' do
+ subject { price.discounted? }
+
+ let(:price) { build(:price, amount: 10, compare_at_amount: compare_at_amount, currency: 'USD') }
+
+ context 'when compare at amount is higher' do
+ let(:compare_at_amount) { 15 }
+ it { is_expected.to be(true) }
+ end
+
+ context 'when compare at amount is lower' do
+ let(:compare_at_amount) { 9 }
+ it { is_expected.to be(false) }
+ end
+
+ context 'when compare at amount is the same' do
+ let(:compare_at_amount) { 10 }
+ it { is_expected.to be(false) }
+ end
+
+ context 'when there is no compare at amount' do
+ let(:compare_at_amount) { nil }
+ it { is_expected.to be(false) }
+ end
+ end
end