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, #proration_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
  (ends_at.nil? || on_grace_period) &&
    stripe_status != 'incomplete' &&
    stripe_status != 'incomplete_expired' &&
    stripe_status != 'unpaid' &&
    (!Reji.deactivate_past_due || stripe_status != 'past_due')
end

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

Add a new Stripe plan to the subscription.



269
270
271
272
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
# File 'lib/reji/subscription.rb', line 269

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

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

  subscription = as_stripe_subscription

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

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

  if single_plan?
    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.



303
304
305
306
307
# File 'lib/reji/subscription.rb', line 303

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

  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.



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

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

#cancelObject

Cancel the subscription at the end of the billing period.



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/reji/subscription.rb', line 334

def cancel
  subscription = 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.
  self.ends_at = on_trial ? trial_ends_at : Time.zone.at(subscription.current_period_end)

  save

  self
end

#cancel_nowObject

Cancel the subscription immediately.



354
355
356
357
358
359
360
361
362
# File 'lib/reji/subscription.rb', line 354

def cancel_now
  as_stripe_subscription.cancel({
    prorate: proration_behavior == 'create_prorations',
  })

  mark_as_cancelled

  self
end

#cancel_now_and_invoiceObject

Cancel the subscription and invoice immediately.



365
366
367
368
369
370
371
372
373
374
# File 'lib/reji/subscription.rb', line 365

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

  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
  !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)
  guard_against_incomplete

  if plan
    find_item_or_fail(plan)
      .set_proration_behavior(proration_behavior)
      .decrement_quantity(count)

    return self
  end

  guard_against_multiple_plans

  update_quantity([1, 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
  !!(cancelled && !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, "Extending a subscription's trial requires a date in the future." unless date.future?

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

  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)
  items.where(stripe_plan: plan).first
end

#get_plan_tax_rates_for_payload(plan) ⇒ Object

Get the plan tax rates for the Stripe payload.



458
459
460
461
462
# File 'lib/reji/subscription.rb', line 458

def get_plan_tax_rates_for_payload(plan)
  tax_rates = user.plan_tax_rates

  tax_rates[plan] || nil unless tax_rates.empty?
end

#guard_against_incompleteObject

Make sure a subscription is not incomplete when performing changes.



479
480
481
# File 'lib/reji/subscription.rb', line 479

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

#guard_against_multiple_plansObject

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

Raises:

  • (ArgumentError)


484
485
486
487
488
# File 'lib/reji/subscription.rb', line 484

def guard_against_multiple_plans
  return unless multiple_plans?

  raise ArgumentError, 'This method requires a plan argument since the subscription has multiple plans.'
end

#incompleteObject

Determine if the subscription is incomplete.



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

def incomplete
  stripe_status == 'incomplete'
end

#incomplete_payment?Boolean

Determine if the subscription has an incomplete payment.

Returns:

  • (Boolean)


465
466
467
# File 'lib/reji/subscription.rb', line 465

def incomplete_payment?
  past_due || 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)
  guard_against_incomplete

  always_invoice

  if plan
    find_item_or_fail(plan)
      .set_proration_behavior(proration_behavior)
      .increment_quantity(count)

    return self
  end

  guard_against_multiple_plans

  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)
  guard_against_incomplete

  if plan
    find_item_or_fail(plan)
      .set_proration_behavior(proration_behavior)
      .increment_quantity(count)

    return self
  end

  guard_against_multiple_plans

  update_quantity(quantity + count, plan)
end

#invoice(options = {}) ⇒ Object

Invoice the subscription outside of the regular billing cycle.



413
414
415
416
417
418
419
420
421
422
# File 'lib/reji/subscription.rb', line 413

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

  raise e
end

#latest_invoiceObject

Get the latest invoice for the subscription.



425
426
427
428
429
# File 'lib/reji/subscription.rb', line 425

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

  Invoice.new(user, stripe_subscription.latest_invoice)
end

#latest_paymentObject

Get the latest payment for a Subscription.



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

def latest_payment
  payment_intent = 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.



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

def mark_as_cancelled
  update({
    stripe_status: 'canceled',
    ends_at: Time.current,
  })
end

#multiple_plans?Boolean

Determine if the subscription has multiple plans.

Returns:

  • (Boolean)


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

def multiple_plans?
  stripe_plan.nil?
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
  !!(ends_at && 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
  !!(trial_ends_at && 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
  stripe_status == 'past_due'
end

#pendingObject

Determine if the subscription has pending updates.



408
409
410
# File 'lib/reji/subscription.rb', line 408

def pending
  !as_stripe_subscription.pending_update.nil?
end

#plan?(plan) ⇒ Boolean

Determine if the subscription has a specific plan.

Returns:

  • (Boolean)


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

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

  stripe_plan == plan
end

#recurringObject

Determine if the subscription is recurring and not on trial.



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

def recurring
  !on_trial && !cancelled
end

#remove_plan(plan) ⇒ Object

Remove a Stripe plan from the subscription.



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/reji/subscription.rb', line 310

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

  item = find_item_or_fail(plan)

  item.as_stripe_subscription_item.delete({
    proration_behavior: proration_behavior,
  })

  items.where(stripe_plan: plan).destroy_all

  if items.count < 2
    item = items.first

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

  self
end

#resumeObject

Resume the cancelled subscription.

Raises:

  • (ArgumentError)


385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/reji/subscription.rb', line 385

def resume
  raise ArgumentError, 'Unable to resume subscription that is not within grace period.' unless on_grace_period

  subscription = as_stripe_subscription

  subscription.cancel_at_period_end = false

  subscription.trial_end = on_trial ? Time.zone.at(trial_ends_at).to_i : 'now'

  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.
  update({
    stripe_status: subscription.status,
    ends_at: nil,
  })

  self
end

#single_plan?Boolean

Determine if the subscription has a single plan.

Returns:

  • (Boolean)


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

def single_plan?
  !multiple_plans?
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
# File 'lib/reji/subscription.rb', line 224

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

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

  guard_against_incomplete

  items = merge_items_that_should_be_deleted_during_swap(parse_swap_plans(plans))

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

  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

  Payment.new(stripe_subscription.latest_invoice.payment_intent).validate if incomplete_payment?

  self
end

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

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



262
263
264
265
266
# File 'lib/reji/subscription.rb', line 262

def swap_and_invoice(plans, options = {})
  always_invoice

  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 = as_stripe_subscription

  update({ stripe_status: subscription.status })
end

#sync_tax_percentageObject

Sync the tax percentage of the user to the subscription.



432
433
434
435
436
437
438
# File 'lib/reji/subscription.rb', line 432

def sync_tax_percentage
  subscription = as_stripe_subscription

  subscription.tax_percentage = user.tax_percentage

  subscription.save
end

#sync_tax_ratesObject

Sync the tax rates of the user to the subscription.



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/reji/subscription.rb', line 441

def sync_tax_rates
  subscription = as_stripe_subscription

  subscription.default_tax_rates = user.tax_rates

  subscription.save

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

    stripe_subscription_item.tax_rates = 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)
  guard_against_incomplete

  if plan
    find_item_or_fail(plan)
      .set_proration_behavior(proration_behavior)
      .update_quantity(quantity)

    return self
  end

  guard_against_multiple_plans

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

  update(quantity: quantity)

  self
end

#update_stripe_subscription(options = {}) ⇒ Object

Update the underlying Stripe subscription information for the model.



491
492
493
494
495
# File 'lib/reji/subscription.rb', line 491

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

#userObject

Get the user that owns the subscription.



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

def user
  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
  active || on_trial || on_grace_period
end