diff --git a/app/models/spree/credit_card_decorator.rb b/app/models/spree/credit_card_decorator.rb index 630e0fab4f..d6c8904846 100644 --- a/app/models/spree/credit_card_decorator.rb +++ b/app/models/spree/credit_card_decorator.rb @@ -15,7 +15,7 @@ Spree::CreditCard.class_eval do belongs_to :user after_create :ensure_single_default_card - after_save :ensure_single_default_card, if: :is_default_changed? + after_save :ensure_single_default_card, if: :default_card_needs_updating? # Allows us to use a gateway_payment_profile_id to store Stripe Tokens # Should be able to remove once we reach Spree v2.2.0 @@ -39,6 +39,10 @@ Spree::CreditCard.class_eval do !user.credit_cards.exists?(is_default: true) end + def default_card_needs_updating? + is_default_changed? || gateway_customer_profile_id_changed? + end + def ensure_single_default_card return unless user return unless is_default? || (reusable? && default_missing?) diff --git a/spec/models/spree/credit_card_spec.rb b/spec/models/spree/credit_card_spec.rb index 48522ffa28..99f04e1362 100644 --- a/spec/models/spree/credit_card_spec.rb +++ b/spec/models/spree/credit_card_spec.rb @@ -83,12 +83,27 @@ module Spree end end - context "and the checkout creates a one-time-use card" do + context "and the checkout creates a card" do let!(:card1) { create(:credit_card, onetime_card_attrs) } + let(:store_card_profile_attrs) { + { + cc_type: "visa", + gateway_customer_profile_id: "cus_FH9HflKAJw6Kxy", + gateway_payment_profile_id: "card_1EmayNBZvgSKc1B2wctIzzoh" + } + } - it "sets it as the default anyway" do + it "doesn't set a one-time card as the default" do expect(card1.reload.is_default).to be false end + + it "sets a re-usable card as the default" do + # The checkout first creates a one-time card and then converts it + # to a re-usable card. + # This imitates Stripe::ProfileStorer. + card1.update_attributes!(store_card_profile_attrs) + expect(card1.reload.is_default).to be true + end end end end