Class: Spree::StripePlan

Inherits:
Base
  • Object
show all
Defined in:
app/models/spree/stripe_plan.rb

Constant Summary collapse

INTERVAL =
{ day: 'Daily', week: 'Weekly', month: 'Monthly', year: 'Annually' }.freeze
CURRENCY =
{ usd: 'USD', gbp: 'GBP', jpy: 'JPY', eur: 'EUR', aud: 'AUD', hkd: 'HKD', sek: 'SEK', nok: 'NOK', dkk: 'DKK', pen: 'PEN',
cad: 'CAD' }.freeze
TAX_BEHAVIOUR_OPTIONS =
{
  'inclusive' => 'inclusive',
  'exclusive' => 'exclusive',
  'unspecified' => 'unspecified'
}.freeze

Instance Method Summary collapse

Instance Method Details

#create_planObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'app/models/spree/stripe_plan.rb', line 53

def create_plan
  plan = Stripe::Plan.create(
    id: stripe_plan_id,
    product: {
      name: name
    },
    currency: currency,
    amount: stripe_amount(amount),
    interval: interval,
    interval_count: interval_count,
    trial_period_days: trial_period_days
  )
  if plan.present?
    update_price_tax_behavior
  end
rescue StandardError
  plan = nil
ensure
  plan
end

#delete_planObject



85
86
87
88
89
90
# File 'app/models/spree/stripe_plan.rb', line 85

def delete_plan
  stripe_plan = find_or_create_stripe_plan
  return unless stripe_plan

  stripe_plan.delete
end

#find_or_create_stripe_planObject



38
39
40
41
42
43
44
45
46
47
# File 'app/models/spree/stripe_plan.rb', line 38

def find_or_create_stripe_plan
  stripe_plan = nil
  return stripe_plan unless active

  stripe_plan = Stripe::Plan.retrieve(stripe_plan_id)
rescue StandardError
  stripe_plan = create_plan
ensure
  stripe_plan
end

#set_api_keyObject



96
97
98
# File 'app/models/spree/stripe_plan.rb', line 96

def set_api_key
  Stripe.api_key = configuration.preferred_secret_key if configuration
end

#set_stripe_plan_idObject



100
101
102
# File 'app/models/spree/stripe_plan.rb', line 100

def set_stripe_plan_id
  self.stripe_plan_id = "VP-Plan-#{Time.current.to_i}"
end

#stripe_amount(amount) ⇒ Object



92
93
94
# File 'app/models/spree/stripe_plan.rb', line 92

def stripe_amount(amount)
  (amount * 100).to_i
end

#update_planObject



74
75
76
77
78
79
80
81
82
83
# File 'app/models/spree/stripe_plan.rb', line 74

def update_plan
  update_price_tax_behavior if tax_behavior_previously_changed?
  return unless name_previously_changed?

  stripe_plan = find_or_create_stripe_plan
  return unless stripe_plan

  stripe_plan.name = name
  stripe_plan.save
end

#update_price_tax_behaviorObject



49
50
51
# File 'app/models/spree/stripe_plan.rb', line 49

def update_price_tax_behavior
  Stripe::Price.update(stripe_plan_id, { tax_behavior: tax_behavior })
end