Skip to content

Commit

Permalink
Add missing association between promo codes and order promotions
Browse files Browse the repository at this point in the history
This fixes the foreign key constraint error when deleting a promotion
code that has been applied to an order.

This will, of course, change the applicability of the promotion in
question for that particular order. If the order is shipped, no worries
though: The adjustments will stay as our service object will not try to
recalculate. If the order is not shipped, the promotion will stop being
applied. However, if you as a user deleted the promotion or the
promotion code, that's probably what you want.

Fixes #94
  • Loading branch information
mamhoff committed Jan 24, 2024
1 parent 85c1d62 commit 774fa9c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ module SolidusFriendlyPromotions
class PromotionCode < Spree::Base
belongs_to :promotion, inverse_of: :codes
belongs_to :promotion_code_batch, inverse_of: :promotion_codes, optional: true

has_many :order_promotions, class_name: "SolidusFriendlyPromotions::OrderPromotion", dependent: :destroy
has_many :adjustments, class_name: "Spree::Adjustment"

before_validation :normalize_code
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
require "spec_helper"

RSpec.describe SolidusFriendlyPromotions::PromotionCode do
let(:promotion) { create(:friendly_promotion) }
subject { create(:friendly_promotion_code, promotion: promotion) }

it { is_expected.to belong_to(:promotion) }
it { is_expected.to have_many(:order_promotions).class_name("SolidusFriendlyPromotions::OrderPromotion").dependent(:destroy) }

context "callbacks" do
subject { promotion_code.save }

Expand Down Expand Up @@ -287,4 +293,19 @@
}.to raise_error ActiveRecord::RecordInvalid,
"Validation failed: Could not create promotion code on promotion that apply automatically"
end

describe "#destroy" do
subject { promotion_code.destroy }

let(:promotion_code) { create(:friendly_promotion_code) }
let(:order) { create(:order_with_line_items) }

before do
order.friendly_order_promotions.create(promotion: promotion_code.promotion, promotion_code: promotion_code)
end

it "destroys the order_promotion" do
expect { subject }.to change { SolidusFriendlyPromotions::OrderPromotion.count }.by(-1)
end
end
end

0 comments on commit 774fa9c

Please sign in to comment.