Sha256: b37c9cf08c5b0196bbb6a7eebcd9380e6d676187b106f8285034ad363927d691

Contents?: true

Size: 1.85 KB

Versions: 5

Compression:

Stored size: 1.85 KB

Contents

# == Schema Information
#
# Table name: wbase_subscriptions
#
#  id                :integer          not null, primary key
#  stripe_id         :string           not null
#  plan_id           :integer          not null
#  last_four         :string
#  coupon_id         :integer
#  card_type         :string
#  current_price     :integer
#  user_id           :integer          not null
#  paid_thru         :datetime
#  credit_card_token :string
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#
# Indexes
#
#  index_wbase_subscriptions_on_plan_id  (plan_id)
#  index_wbase_subscriptions_on_user_id  (user_id)
#

module Wbase
  class Subscription < ActiveRecord::Base
    validates :user, :plan, :credit_card_token, presence: true
    belongs_to :plan
    belongs_to :user

    def self.current
      where('paid_thru > ?', 7.days.ago)
    end

    def stripe_customer
      @stripe_customer ||= Stripe::Customer.retrieve(stripe_id)
    end

    def self.monthly_value
      current.where(plan: Plan.monthly).sum(:current_price) +
        current.where(plan: Plan.annual).sum(:current_price).fdiv(12)
    end

    def monthly_value
      if plan.interval.include?("month")
        current_price
      else
        current_price.fdiv(12)
      end
    end

    def update_paid_thru!
      if stripe_customer && stripe_customer.try(:subscriptions).try(:first)
        remote_paid_thru = Time.at(stripe_customer.subscriptions.first.try(:current_period_end))
        if remote_paid_thru > paid_thru
          return self.update(paid_thru: remote_paid_thru)
        end
      end
      false
    end

    def current?
      paid_thru && paid_thru > 7.days.ago
    end

    def trial?
      created_at > 14.days.ago
    end

    def trial_days_left
      return 0 unless trial?
      (conversion_day.to_date - Date.current.to_date).to_i
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
wbase-0.3.20 app/models/wbase/subscription.rb
wbase-0.3.19 app/models/wbase/subscription.rb
wbase-0.3.18 app/models/wbase/subscription.rb
wbase-0.3.17 app/models/wbase/subscription.rb
wbase-0.3.16 app/models/wbase/subscription.rb