Skip to content

Instantly share code, notes, and snippets.

@dawidof
Created August 26, 2020 06:55
Show Gist options
  • Save dawidof/32f7ba091bce7cda01323fd1456658f6 to your computer and use it in GitHub Desktop.
Save dawidof/32f7ba091bce7cda01323fd1456658f6 to your computer and use it in GitHub Desktop.
module ChargebeeFetcher
class Subscription
attr_reader :response
delegate :has_card?, to: :customer, allow_nil: true
delegate :card_expired?, :card_will_expire_soon?, to: :card
def initialize(response)
@response = response
end
def self.find_by(**options)
where(options).first
end
def self.where(**options)
conditions = options.each_with_object({}) do |(key, value), memo|
next unless value
internal_condition = value.is_a?(Array) ? :in : :is
value_to_search = value.is_a?(Array) ? value.to_json : value.to_s
memo[key] = { internal_condition => value_to_search }
end
return [] if conditions.empty?
ChargeBee::Subscription.list(conditions).map(&method(:new))
end
def subscription
response.subscription if response
end
def plan_id
subscription.try(:plan_id)
end
def shipping_address
subscription.try(:shipping_address)
end
def id
subscription.try(:id)
end
def active?
%w(active future).include? subscription.status
end
def cancelled?
subscription.status.eql?('cancelled')
end
def skipped?
pluralized_billing_period = subscription.billing_period_unit.pluralize.to_sym
count_current_billing_period_from_now = Time.now.advance(pluralized_billing_period => subscription.billing_period).to_i
return subscription.current_term_end > count_current_billing_period_from_now if subscription.status.eql?('active')
return subscription.start_date > count_current_billing_period_from_now if subscription.status.eql?('future')
false
end
def customer
@customer ||= ChargebeeFetcher::Customer.new(response.customer) if response
end
def billing_address
customer.try(:billing_address)
end
def card
@card ||= ChargebeeFetcher::Card.new(response.card) if response
end
def plan
Spree::Plan.find_by(chargebee_plan_id: plan_id) if plan_id
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment