Method: Pay::PaddleBilling::Subscription.sync

Defined in:
app/models/pay/paddle_billing/subscription.rb

.sync(subscription_id, object: nil, name: Pay.default_product_name, try: 0, retries: 1) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'app/models/pay/paddle_billing/subscription.rb', line 12

def self.sync(subscription_id, object: nil, name: Pay.default_product_name, try: 0, retries: 1)
  # Passthrough is not return from this API, so we can't use that
  object ||= ::Paddle::Subscription.retrieve(id: subscription_id)

  pay_customer = Pay::Customer.find_by(processor: :paddle_billing, processor_id: object.customer_id)
  return unless pay_customer

  attributes = {
    current_period_end: object.current_billing_period&.ends_at,
    current_period_start: object.current_billing_period&.starts_at,
    ends_at: (object.canceled_at ? Time.parse(object.canceled_at) : nil),
    metadata: object.custom_data,
    paddle_cancel_url: object.management_urls&.cancel,
    paddle_update_url: object.management_urls&.update_payment_method,
    pause_starts_at: (object.paused_at ? Time.parse(object.paused_at) : nil),
    status: object.status
  }

  if object.items&.first
    item = object.items.first
    attributes[:processor_plan] = item.price.id
    attributes[:quantity] = item.quantity
  end

  case attributes[:status]
  when "canceled"
    # Remove payment methods since customer cannot be reused after cancelling
    Pay::PaymentMethod.where(customer_id: object.customer_id).destroy_all
  when "trialing"
    attributes[:trial_ends_at] = Time.parse(object.next_billed_at) if object.next_billed_at
  when "paused"
    attributes[:pause_starts_at] = Time.parse(object.paused_at) if object.paused_at
  when "active", "past_due"
    attributes[:trial_ends_at] = nil
    attributes[:pause_starts_at] = nil
    attributes[:ends_at] = nil
  end

  case object.scheduled_change&.action
  when "cancel"
    attributes[:ends_at] = Time.parse(object.scheduled_change.effective_at)
  when "pause"
    attributes[:pause_starts_at] = Time.parse(object.scheduled_change.effective_at)
  when "resume"
    attributes[:pause_resumes_at] = Time.parse(object.scheduled_change.effective_at)
  end

  # Update or create the subscription
  if (pay_subscription = find_by(customer: pay_customer, processor_id: subscription_id))
    pay_subscription.with_lock { pay_subscription.update!(attributes) }
    pay_subscription
  else
    create!(attributes.merge(customer: pay_customer, name: name, processor_id: subscription_id))
  end
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
  try += 1
  if try <= retries
    sleep 0.1
    retry
  else
    raise
  end
end