This repository has been archived by the owner on Jun 8, 2019. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
subscription.rb
100 lines (83 loc) · 2.27 KB
/
subscription.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
require "ashmont/errors"
require "active_support/core_ext"
require "braintree"
module Ashmont
class Subscription
attr_reader :token, :errors
def initialize(token = nil, cached_attributes = {})
@token = token
@cached_attributes = cached_attributes
@errors = {}
end
delegate :transactions, :to => :remote_subscription, :allow_nil => true
def status
@cached_attributes[:status] || remote_status
end
def save(attributes)
attributes_for_merchant = add_merchant_to_attributes(attributes)
if token
update(attributes_for_merchant)
else
create(attributes_for_merchant)
end
end
def retry_charge
transaction = Braintree::Subscription.retry_charge(token).transaction
result = Braintree::Transaction.submit_for_settlement(transaction.id)
reload
if result.success?
true
else
@errors = Ashmont::Errors.new(transaction, result.errors)
false
end
end
def most_recent_transaction
transactions.sort_by(&:created_at).last
end
def next_billing_date
merchant_account_time_zone.parse(remote_subscription.next_billing_date)
end
def reload
@remote_subscription = nil
@cached_attributes = {}
self
end
private
def remote_status
remote_subscription.status if remote_subscription
end
def add_merchant_to_attributes(attributes)
if Ashmont.merchant_account_id
attributes.merge(:merchant_account_id => Ashmont.merchant_account_id)
else
attributes
end
end
def create(attributes)
result = Braintree::Subscription.create(attributes)
if result.success?
@token = result.subscription.id
@remote_subscription = result.subscription
true
else
false
end
end
def update(attributes)
@remote_subscription = nil
Braintree::Subscription.update(token, attributes)
end
def remote_subscription
@remote_subscription ||= find_remote_subscription
end
def find_remote_subscription
if token
Braintree::Subscription.find(token)
end
end
def merchant_account_time_zone
ActiveSupport::TimeZone[Ashmont.merchant_account_time_zone]
end
end
end