Skip to content

Commit

Permalink
Add FreeShipping#discount
Browse files Browse the repository at this point in the history
  • Loading branch information
mamhoff committed Mar 18, 2022
1 parent e8d7697 commit 7976ab9
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
13 changes: 13 additions & 0 deletions core/app/models/spree/promotion/actions/free_shipping.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@ module Spree
class Promotion < Spree::Base
module Actions
class FreeShipping < Spree::PromotionAction
def discountable_class
Spree::Shipment
end

def discount(shipment)
discount = shipment.discounts.detect do |discount|
discount.promotion_action == self
end || shipment.discounts.build(promotion_action: self)
discount.label = I18n.t('spree.adjustment_labels.shipment', promotion: Spree::Promotion.model_name.human, promotion_name: promotion.name)
discount.amount = compute_amount(shipment)
discount
end

def perform(payload = {})
order = payload[:order]
promotion_code = payload[:promotion_code]
Expand Down
1 change: 1 addition & 0 deletions core/config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,7 @@ en:
adjustment_labels:
line_item: "%{promotion} (%{promotion_name})"
order: "%{promotion} (%{promotion_name})"
shipment: "%{promotion} (%{promotion_name})"
tax_rates:
sales_tax: "%{name}"
sales_tax_with_rate: "%{name} %{amount}"
Expand Down
26 changes: 26 additions & 0 deletions core/spec/models/spree/promotion/actions/free_shipping_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,32 @@
let(:payload) { { order: order, promotion_code: promotion_code } }
let(:promotion_code) { promotion.codes.first! }

context "#discount" do
subject { action.discount(shipment) }

before do
expect(action).to receive(:compute_amount).and_return(10)
action.promotion = promotion
end

it "builds an unpersisted discount" do
expect(subject).to be_a(Spree::ShipmentDiscount)
expect(subject.amount).to eq(10)
expect(subject.label).to eq("Promotion (Promo)")
end

context "if the shipment already has a discount" do
let!(:existing_shipment_discount) { create(:shipment_discount, shipment: shipment, promotion_action: action) }

it "changes the discounts label and price" do
expect(subject).to be_a(Spree::ShipmentDiscount)
expect(subject.amount).to eq(10)
expect(subject.label).to eq("Promotion (Promo)")
expect(subject).to be_persisted
expect(subject).to be_changed
end
end
end
# From promotion spec:
describe "#perform" do
before do
Expand Down

0 comments on commit 7976ab9

Please sign in to comment.