Class: Reji::Subscription

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
InteractsWithPaymentBehavior, Prorates
Defined in:
lib/reji/subscription.rb

Instance Method Summary collapse

Methods included from Prorates

#always_invoice, #no_prorate, #prorate, #prorate_behavior, #set_proration_behavior

Methods included from InteractsWithPaymentBehavior

#allow_payment_failures, #error_if_payment_fails, #payment_behavior, #pending_if_payment_fails

Instance Method Details

#activeObject

Determine if the subscription is active.



78
79
80
81
82
83
84
# File 'lib/reji/subscription.rb', line 78

def active
  (self.ends_at.nil? || self.on_grace_period) &&
  self.stripe_status != 'incomplete' &&
  self.stripe_status != 'incomplete_expired' &&
  self.stripe_status != 'unpaid' &&
  (! Reji.deactivate_past_due || self.stripe_status != 'past_due')
end

#add_plan(plan, quantity = 1, options = {}) ⇒ Object

Add a new Stripe plan to the subscription.



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/reji/subscription.rb', line 273

def add_plan(plan, quantity = 1, options = {})
  self.guard_against_incomplete

  if self.items.any? { |item| item.stripe_plan == plan }
    raise Reji::SubscriptionUpdateFailureError::duplicate_plan(self, plan)
  end

  subscription = self.as_stripe_subscription

  item = subscription.items.create({
    :plan => plan,
    :quantity => quantity,
    :tax_rates => self.get_plan_tax_rates_for_payload(plan),
    :payment_behavior => self.payment_behavior,
    :proration_behavior => self.prorate_behavior,
  }.merge(options))

  self.items.create({
    :stripe_id => item.id,
    :stripe_plan => plan,
    :quantity => quantity
  })

  if self.has_single_plan
    self.update({
      :stripe_plan => nil,
      :quantity => nil,
    })
  end

  self
end

#add_plan_and_invoice(plan, quantity = 1, options = {}) ⇒ Object

Add a new Stripe plan to the subscription, and invoice immediately.



307
308
309
310
311
# File 'lib/reji/subscription.rb', line 307

def add_plan_and_invoice(plan, quantity = 1, options = {})
  self.always_invoice

  self.add_plan(plan, quantity, options)
end

#anchor_billing_cycle_on(date = 'now') ⇒ Object

Change the billing cycle anchor on a plan change.



197
198
199
200
201
# File 'lib/reji/subscription.rb', line 197

def anchor_billing_cycle_on(date = 'now')
  @billing_cycle_anchor = date

  self
end

#as_stripe_subscription(expand = {}) ⇒ Object

Get the subscription as a Stripe subscription object.



512
513
514
515
516
# File 'lib/reji/subscription.rb', line 512

def as_stripe_subscription(expand = {})
  Stripe::Subscription::retrieve(
    {:id => self.stripe_id, :expand => expand}, self.owner.stripe_options
  )
end

#cancelObject

Cancel the subscription at the end of the billing period.



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/reji/subscription.rb', line 338

def cancel
  subscription = self.as_stripe_subscription

  subscription.cancel_at_period_end = true

  subscription = subscription.save

  self.stripe_status = subscription.status

  # If the user was on trial, we will set the grace period to end when the trial
  # would have ended. Otherwise, we'll retrieve the end of the billing period
  # period and make that the end of the grace period for this current user.
  if self.on_trial
    self.ends_at = self.trial_ends_at
  else
    self.ends_at = Time.at(subscription.current_period_end)
  end

  self.save

  self
end

#cancel_nowObject

Cancel the subscription immediately.



362
363
364
365
366
367
368
369
370
# File 'lib/reji/subscription.rb', line 362

def cancel_now
  self.as_stripe_subscription.cancel({
    :prorate => self.prorate_behavior == 'create_prorations',
  })

  self.mark_as_cancelled

  self
end

#cancel_now_and_invoiceObject

Cancel the subscription and invoice immediately.



373
374
375
376
377
378
379
380
381
382
# File 'lib/reji/subscription.rb', line 373

def cancel_now_and_invoice
  self.as_stripe_subscription.cancel({
    :invoice_now => true,
    :prorate => self.prorate_behavior == 'create_prorations',
  })

  self.mark_as_cancelled

  self
end

#cancelledObject

Determine if the subscription is no longer active.



99
100
101
# File 'lib/reji/subscription.rb', line 99

def cancelled
  ! self.ends_at.nil?
end

#decrement_quantity(count = 1, plan = nil) ⇒ Object

Decrement the quantity of the subscription.



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/reji/subscription.rb', line 155

def decrement_quantity(count = 1, plan = nil)
  self.guard_against_incomplete

  if plan
    self.find_item_or_fail(plan)
      .set_proration_behavior(self.prorate_behavior)
      .decrement_quantity(count)

    return self
  end

  self.guard_against_multiple_plans

  self.update_quantity([1, self.quantity - count].max, plan)
end

#endedObject

Determine if the subscription has ended and the grace period has expired.



104
105
106
# File 'lib/reji/subscription.rb', line 104

def ended
  !! (self.cancelled && ! self.on_grace_period)
end

#extend_trial(date) ⇒ Object

Extend an existing subscription’s trial period.

Raises:

  • (ArgumentError)


211
212
213
214
215
216
217
218
219
220
221
# File 'lib/reji/subscription.rb', line 211

def extend_trial(date)
  raise ArgumentError.new("Extending a subscription's trial requires a date in the future.") unless date.future?

  subscription = self.as_stripe_subscription
  subscription.trial_end = date.to_i
  subscription.save

  self.update(trial_ends_at: date)

  self
end

#find_item_or_fail(plan) ⇒ Object

Get the subscription item for the given plan.



58
59
60
# File 'lib/reji/subscription.rb', line 58

def find_item_or_fail(plan)
  self.items.where(stripe_plan: plan).first
end

#get_plan_tax_rates_for_payload(plan) ⇒ Object

Get the plan tax rates for the Stripe payload.



472
473
474
475
476
477
478
# File 'lib/reji/subscription.rb', line 472

def get_plan_tax_rates_for_payload(plan)
  tax_rates = self.user.plan_tax_rates

  if tax_rates
    tax_rates.key?(plan) ? tax_rates[plan] : nil
  end
end

#guard_against_incompleteObject

Make sure a subscription is not incomplete when performing changes.



495
496
497
# File 'lib/reji/subscription.rb', line 495

def guard_against_incomplete
  raise Reji::SubscriptionUpdateFailureError.incomplete_subscription(self) if self.incomplete
end

#guard_against_multiple_plansObject

Make sure a plan argument is provided when the subscription is a multi plan subscription.

Raises:

  • (ArgumentError)


500
501
502
# File 'lib/reji/subscription.rb', line 500

def guard_against_multiple_plans
  raise ArgumentError.new('This method requires a plan argument since the subscription has multiple plans.') if self.has_multiple_plans
end

#has_incomplete_paymentObject

Determine if the subscription has an incomplete payment.



481
482
483
# File 'lib/reji/subscription.rb', line 481

def has_incomplete_payment
  self.past_due || self.incomplete
end

#has_multiple_plansObject

Determine if the subscription has multiple plans.



41
42
43
# File 'lib/reji/subscription.rb', line 41

def has_multiple_plans
  self.stripe_plan.nil?
end

#has_plan(plan) ⇒ Object

Determine if the subscription has a specific plan.



51
52
53
54
55
# File 'lib/reji/subscription.rb', line 51

def has_plan(plan)
  return self.items.any? { |item| item.stripe_plan == plan } if self.has_multiple_plans

  self.stripe_plan == plan
end

#has_single_planObject

Determine if the subscription has a single plan.



46
47
48
# File 'lib/reji/subscription.rb', line 46

def has_single_plan
  ! self.has_multiple_plans
end

#incompleteObject

Determine if the subscription is incomplete.



68
69
70
# File 'lib/reji/subscription.rb', line 68

def incomplete
  self.stripe_status == 'incomplete'
end

#increment_and_invoice(count = 1, plan = nil) ⇒ Object

Increment the quantity of the subscription, and invoice immediately.



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/reji/subscription.rb', line 136

def increment_and_invoice(count = 1, plan = nil)
  self.guard_against_incomplete

  self.always_invoice

  if plan
    self.find_item_or_fail(plan)
      .set_proration_behavior(self.prorate_behavior)
      .increment_quantity(count)

    return self
  end

  self.guard_against_multiple_plans

  self.increment_quantity(count, plan)
end

#increment_quantity(count = 1, plan = nil) ⇒ Object

Increment the quantity of the subscription.



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/reji/subscription.rb', line 119

def increment_quantity(count = 1, plan = nil)
  self.guard_against_incomplete

  if plan
    self.find_item_or_fail(plan)
      .set_proration_behavior(self.prorate_behavior)
      .increment_quantity(count)

    return self
  end

  self.guard_against_multiple_plans

  self.update_quantity(self.quantity + count, plan)
end

#invoice(options = {}) ⇒ Object

Invoice the subscription outside of the regular billing cycle.



425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/reji/subscription.rb', line 425

def invoice(options = {})
  begin
    self.user.invoice(options.merge({
      :subscription => self.stripe_id
    }))
  rescue IncompletePaymentError => e
    # Set the new Stripe subscription status immediately when payment fails...
    self.update(stripe_status: e.payment.invoice.subscription.status)

    raise e
  end
end

#latest_invoiceObject

Get the latest invoice for the subscription.



439
440
441
442
443
# File 'lib/reji/subscription.rb', line 439

def latest_invoice
  stripe_subscription = self.as_stripe_subscription(['latest_invoice'])

  Invoice.new(self.user, stripe_subscription.latest_invoice)
end

#latest_paymentObject

Get the latest payment for a Subscription.



486
487
488
489
490
491
492
# File 'lib/reji/subscription.rb', line 486

def latest_payment
  payment_intent = self.as_stripe_subscription(['latest_invoice.payment_intent'])
    .latest_invoice
    .payment_intent

  payment_intent ? Payment.new(payment_intent) : nil
end

#mark_as_cancelledObject

Mark the subscription as cancelled.



385
386
387
388
389
390
# File 'lib/reji/subscription.rb', line 385

def mark_as_cancelled
  self.update({
    :stripe_status => 'canceled',
    :ends_at => Time.now,
  })
end

#on_grace_periodObject

Determine if the subscription is within its grace period after cancellation.



114
115
116
# File 'lib/reji/subscription.rb', line 114

def on_grace_period
  !! (self.ends_at && self.ends_at.future?)
end

#on_trialObject

Determine if the subscription is within its trial period.



109
110
111
# File 'lib/reji/subscription.rb', line 109

def on_trial
  !! (self.trial_ends_at && self.trial_ends_at.future?)
end

#past_dueObject

Determine if the subscription is past due.



73
74
75
# File 'lib/reji/subscription.rb', line 73

def past_due
  self.stripe_status == 'past_due'
end

#pendingObject

Determine if the subscription has pending updates.



420
421
422
# File 'lib/reji/subscription.rb', line 420

def pending
  ! self.as_stripe_subscription.pending_update.nil?
end

#recurringObject

Determine if the subscription is recurring and not on trial.



94
95
96
# File 'lib/reji/subscription.rb', line 94

def recurring
  ! self.on_trial && ! self.cancelled
end

#remove_plan(plan) ⇒ Object

Remove a Stripe plan from the subscription.



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/reji/subscription.rb', line 314

def remove_plan(plan)
  raise Reji::SubscriptionUpdateFailureError::cannot_delete_last_plan(self) if self.has_single_plan

  item = self.find_item_or_fail(plan)

  item.as_stripe_subscription_item.delete({
    :proration_behavior => self.prorate_behavior
  })

  self.items.where(stripe_plan: plan).destroy_all

  if self.items.count < 2
    item = self.items.first

    self.update({
      :stripe_plan => item.stripe_plan,
      :quantity => quantity,
    })
  end

  self
end

#resumeObject

Resume the cancelled subscription.

Raises:

  • (ArgumentError)


393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/reji/subscription.rb', line 393

def resume
  raise ArgumentError.new('Unable to resume subscription that is not within grace period.') unless self.on_grace_period

  subscription = self.as_stripe_subscription

  subscription.cancel_at_period_end = false

  if self.on_trial
    subscription.trial_end = Time.at(self.trial_ends_at).to_i
  else
    subscription.trial_end = 'now'
  end

  subscription = subscription.save

  # Finally, we will remove the ending timestamp from the user's record in the
  # local database to indicate that the subscription is active again and is
  # no longer "cancelled". Then we will save this record in the database.
  self.update({
    :stripe_status => subscription.status,
    :ends_at => nil,
  })

  self
end

#skip_trialObject

Force the trial to end immediately.



204
205
206
207
208
# File 'lib/reji/subscription.rb', line 204

def skip_trial
  self.trial_ends_at = nil

  self
end

#swap(plans, options = {}) ⇒ Object

Swap the subscription to new Stripe plans.

Raises:

  • (ArgumentError)


224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/reji/subscription.rb', line 224

def swap(plans, options = {})
  plans = [plans] unless plans.instance_of? Array

  raise ArgumentError.new('Please provide at least one plan when swapping.') if plans.empty?

  self.guard_against_incomplete

  items = self.merge_items_that_should_be_deleted_during_swap(
    self.parse_swap_plans(plans)
  )

  stripe_subscription = Stripe::Subscription::update(
    self.stripe_id,
    self.get_swap_options(items, options),
    self.owner.stripe_options
  )

  self.update({
    :stripe_status => stripe_subscription.status,
    :stripe_plan => stripe_subscription.plan ? stripe_subscription.plan.id : nil,
    :quantity => stripe_subscription.quantity,
    :ends_at => nil,
  })

  stripe_subscription.items.each do |item|
    self.items.find_or_create_by(stripe_id: item.id) do |subscription_item|
      subscription_item.stripe_plan = item.plan.id
      subscription_item.quantity = item.quantity
    end
  end

  # Delete items that aren't attached to the subscription anymore...
  self.items.where('stripe_plan NOT IN (?)', items.values.pluck(:plan).compact).destroy_all

  if self.has_incomplete_payment
    Payment.new(stripe_subscription.latest_invoice.payment_intent).validate
  end

  self
end

#swap_and_invoice(plans, options = {}) ⇒ Object

Swap the subscription to new Stripe plans, and invoice immediately.



266
267
268
269
270
# File 'lib/reji/subscription.rb', line 266

def swap_and_invoice(plans, options = {})
  self.always_invoice

  self.swap(plans, options)
end

#sync_stripe_statusObject

Sync the Stripe status of the subscription.



87
88
89
90
91
# File 'lib/reji/subscription.rb', line 87

def sync_stripe_status
  subscription = self.as_stripe_subscription

  self.update({stripe_status: subscription.status})
end

#sync_tax_percentageObject

Sync the tax percentage of the user to the subscription.



446
447
448
449
450
451
452
# File 'lib/reji/subscription.rb', line 446

def sync_tax_percentage
  subscription = self.as_stripe_subscription

  subscription.tax_percentage = self.user.tax_percentage

  subscription.save
end

#sync_tax_ratesObject

Sync the tax rates of the user to the subscription.



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/reji/subscription.rb', line 455

def sync_tax_rates
  subscription = self.as_stripe_subscription

  subscription.default_tax_rates = self.user.tax_rates

  subscription.save

  self.items.each do |item|
    stripe_subscription_item = item.as_stripe_subscription_item

    stripe_subscription_item.tax_rates = self.get_plan_tax_rates_for_payload(item.stripe_plan)

    stripe_subscription_item.save
  end
end

#update_quantity(quantity, plan = nil) ⇒ Object

Update the quantity of the subscription.



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/reji/subscription.rb', line 172

def update_quantity(quantity, plan = nil)
  self.guard_against_incomplete

  if plan
    self.find_item_or_fail(plan)
      .set_proration_behavior(self.prorate_behavior)
      .update_quantity(quantity)

    return self
  end

  self.guard_against_multiple_plans

  stripe_subscription = self.as_stripe_subscription
  stripe_subscription.quantity = quantity
  stripe_subscription.payment_behavior = self.payment_behavior
  stripe_subscription.proration_behavior = self.prorate_behavior
  stripe_subscription.save

  self.update(quantity: quantity)

  self
end

#update_stripe_subscription(options = {}) ⇒ Object

Update the underlying Stripe subscription information for the model.



505
506
507
508
509
# File 'lib/reji/subscription.rb', line 505

def update_stripe_subscription(options = {})
  Stripe::Subscription.update(
    self.stripe_id, options, self.owner.stripe_options
  )
end

#userObject

Get the user that owns the subscription.



36
37
38
# File 'lib/reji/subscription.rb', line 36

def user
  self.owner
end

#validObject

Determine if the subscription is active, on trial, or within its grace period.



63
64
65
# File 'lib/reji/subscription.rb', line 63

def valid
  self.active || self.on_trial || self.on_grace_period
end