Class: Tang::Coupon
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- Tang::Coupon
- Defined in:
- app/models/tang/coupon.rb
Constant Summary collapse
- DURATIONS =
['once', 'repeating', 'forever']
Class Method Summary collapse
Instance Method Summary collapse
- #active_redemptions ⇒ Object
- #coupon_valid? ⇒ Boolean
- #discount(amount) ⇒ Object
- #formatted_duration ⇒ Object
- #repeating? ⇒ Boolean
Class Method Details
.from_stripe(stripe_coupon) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'app/models/tang/coupon.rb', line 71 def self.from_stripe(stripe_coupon) coupon = Coupon.find_or_create_by(stripe_id: stripe_coupon.id) do |c| c.percent_off = stripe_coupon.percent_off c.currency = stripe_coupon.currency c.amount_off = stripe_coupon.amount_off c.duration = stripe_coupon.duration c.duration_in_months = stripe_coupon.duration_in_months c.max_redemptions = stripe_coupon.max_redemptions c.redeem_by = stripe_coupon.redeem_by end return coupon end |
Instance Method Details
#active_redemptions ⇒ Object
48 49 50 51 52 53 54 55 |
# File 'app/models/tang/coupon.rb', line 48 def active_redemptions customer_table = ActiveRecord::Base.connection.quote_table_name(Customer.table_name) Tang.customer_class. joins(:subscriptions). where("#{customer_table}.coupon_id = ? OR tang_subscriptions.coupon_id = ?", self.id, self.id). where.not(tang_subscriptions: { status: :canceled }). uniq end |
#coupon_valid? ⇒ Boolean
27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'app/models/tang/coupon.rb', line 27 def coupon_valid? # check if expired if self.redeem_by.present? return false if Time.now > self.redeem_by end if self.max_redemptions.present? # check if any discounts created end return true end |
#discount(amount) ⇒ Object
61 62 63 64 65 66 67 68 69 |
# File 'app/models/tang/coupon.rb', line 61 def discount(amount) subtotal = amount if self.percent_off.present? subtotal = amount.to_f * (self.percent_off.to_f / 100.0) elsif self.amount_off.present? subtotal = self.amount_off end return -subtotal.to_f end |
#formatted_duration ⇒ Object
40 41 42 43 44 45 46 |
# File 'app/models/tang/coupon.rb', line 40 def formatted_duration if repeating? "for #{duration_in_months} months" else duration end end |
#repeating? ⇒ Boolean
57 58 59 |
# File 'app/models/tang/coupon.rb', line 57 def repeating? duration == "repeating" end |