Sha256: 2adb440fedd2e5fbe2ef5c5b40f43a536560075e52881f480d740378e2848167

Contents?: true

Size: 1.84 KB

Versions: 1

Compression:

Stored size: 1.84 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.subscriptions.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

1 entries across 1 versions & 1 rubygems

Version Path
wbase-0.3.15 app/models/wbase/subscription.rb