Skip to content

Instantly share code, notes, and snippets.

@jzajpt
Created March 25, 2020 14:30
Show Gist options
  • Save jzajpt/b1f8e47ea0e28574c8c5c0859110ead2 to your computer and use it in GitHub Desktop.
Save jzajpt/b1f8e47ea0e28574c8c5c0859110ead2 to your computer and use it in GitHub Desktop.
# == Schema Information
#
# Table name: chargebee_invoices
#
# id :bigint not null, primary key
# client_id :bigint
# created_at :datetime not null
# updated_at :datetime not null
# chargebee_id :string
# chargebee_data :jsonb
# chargebee_subscription_id :string
#
class ChargebeeInvoice < ApplicationRecord
belongs_to :client
belongs_to :chargebee_subscription
before_validation :set_chargebee_subscription_id
after_create :generate_admin_commission
validates :chargebee_id, presence: true, uniqueness: true
def self.unpaid
where('(chargebee_invoices.chargebee_data->>\'amount_due\')::integer > 0')
end
def generate_admin_commission
chargebee_subscription.plan_setup.generate_admin_commission
end
def paid?
amount_due <= 0
end
def reference_number
10400000 + id
end
def credit_repair?
!inquiry_removal?
end
def inquiry_removal?
chargebee_data['line_items'].select do |line_item|
line_item['entity_id'].present? && line_item['entity_id'].include?('inquiry')
end.any?
end
def status_string
if amount_due > 0
"$#{ amount_due } pending"
else
"Paid"
end
end
def amount_due
chargebee_data['amount_due'].to_d / 100
end
def amount_paid
chargebee_data['amount_paid'].to_d / 100
end
def total
chargebee_data['total'].to_d / 100
end
def due_date
timestamp = chargebee_data['due_date'].to_i
return "" if timestamp == 0
DateTime.strptime(chargebee_data['due_date'].to_s, '%s').strftime("%b %-d, %Y")
end
def paid_at
timestamp = chargebee_data['paid_at'].to_i
return "" if timestamp == 0
DateTime.strptime(chargebee_data['paid_at'].to_s, '%s').strftime("%b %-d, %Y")
end
private
def set_chargebee_subscription_id
subscription = ChargebeeSubscription.find_by(chargebee_id: chargebee_data['subscription_id'])
self.chargebee_subscription_id = subscription.id if subscription
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment