-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathbilling_client.rb
More file actions
315 lines (259 loc) · 10.9 KB
/
billing_client.rb
File metadata and controls
315 lines (259 loc) · 10.9 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
module Travis::API::V3
class BillingClient
class ConfigurationError < StandardError; end
ALLOWANCE_TIMEOUT = 1 # second
EXECUTIONS_TIMEOUT = 60 # seconds
def initialize(user_id)
@user_id = user_id
end
def allowance(owner_type, owner_id)
response = connection(timeout: ALLOWANCE_TIMEOUT).get("/usage/#{owner_type.downcase}s/#{owner_id}/allowance")
return BillingClient.default_allowance_response unless response.status == 200
Travis::API::V3::Models::Allowance.new(body(response).fetch('subscription_type', 2), owner_id, body(response))
end
def authorize_build(repo, sender_id, jobs)
response = connection.post("/#{repo.owner.class.name.downcase.pluralize}/#{repo.owner.id}/authorize_build", { repository: { private: repo.private? }, sender_id: sender_id, jobs: jobs })
handle_errors_and_respond(response)
end
def self.default_allowance_response(id = 0)
Travis::API::V3::Models::Allowance.new(1, id, {
"public_repos" => true,
"private_repos" => false,
"concurrency_limit" => 1,
"user_usage" => false,
"pending_user_licenses" => false,
"payment_changes_block_captcha" => false,
"payment_changes_block_credit" => false,
"credit_card_block_duration" => 0,
"captcha_block_duration" => 0
}.freeze)
end
def self.minimal_allowance_response(id = 0)
Travis::API::V3::Models::Allowance.new(2, id, {})
end
def executions(owner_type, owner_id, page, per_page, from, to)
response = connection(timeout: EXECUTIONS_TIMEOUT).get("/usage/#{owner_type.downcase}s/#{owner_id}/executions?page=#{page}&per_page=#{per_page}&from=#{from}&to=#{to}")
executions = body(response).map do |execution_data|
Travis::API::V3::Models::Execution.new(execution_data)
end
executions
end
def calculate_credits(users, executions)
response = connection.post("/usage/credits_calculator", users: users, executions: executions)
body(response).map do |calculator_data|
Travis::API::V3::Models::CreditsResult.new(calculator_data)
end
end
def credits_calculator_default_config
response = connection.get('/usage/credits_calculator/default_config')
Travis::API::V3::Models::CreditsCalculatorConfig.new(body(response))
end
def all
data = body(connection.get('/subscriptions'))
subscriptions = data.fetch('subscriptions').map do |subscription_data|
Travis::API::V3::Models::Subscription.new(subscription_data)
end
permissions = data.fetch('permissions')
Travis::API::V3::Models::SubscriptionsCollection.new(subscriptions, permissions)
end
def all_v2
data = body(connection.get('/v2/subscriptions'))
subscriptions = data.fetch('plans').map do |subscription_data|
Travis::API::V3::Models::V2Subscription.new(subscription_data)
end
permissions = data.fetch('permissions')
Travis::API::V3::Models::SubscriptionsCollection.new(subscriptions, permissions)
end
def get_subscription(id)
response = connection.get("/subscriptions/#{id}")
handle_subscription_response(response)
end
def get_v2_subscription(id)
response = connection.get("/v2/subscriptions/#{id}")
handle_v2_subscription_response(response)
end
def get_invoices_for_subscription(id)
body(connection.get("/subscriptions/#{id}/invoices")).map do |invoice_data|
Travis::API::V3::Models::Invoice.new(invoice_data)
end
end
def trials
body(connection.get('/trials')).map do | trial_data |
Travis::API::V3::Models::Trial.new(trial_data)
end
end
def create_trial(type, id)
response = connection.post("/trials/#{type}/#{id}")
handle_errors_and_respond(response)
end
def update_address(subscription_id, address_data)
response = connection.patch("/subscriptions/#{subscription_id}/address", address_data)
handle_subscription_response(response)
end
def update_v2_address(subscription_id, address_data)
response = connection.patch("/v2/subscriptions/#{subscription_id}/address", address_data)
handle_v2_subscription_response(response)
end
def update_creditcard(subscription_id, creditcard_token)
response = connection.patch("/subscriptions/#{subscription_id}/creditcard", token: creditcard_token)
handle_subscription_response(response)
end
def update_v2_creditcard(subscription_id, creditcard_token, creditcard_fingerprint)
response = connection.patch("/v2/subscriptions/#{subscription_id}/creditcard", token: creditcard_token, fingerprint: creditcard_fingerprint)
handle_v2_subscription_response(response)
end
def update_plan(subscription_id, plan_data)
response = connection.patch("/subscriptions/#{subscription_id}/plan", plan_data)
handle_subscription_response(response)
end
def create_subscription(subscription_data)
response = connection.post('/subscriptions', subscription_data)
handle_subscription_response(response)
end
def create_v2_subscription(subscription_data)
response = connection.post('/v2/subscriptions', subscription_data)
handle_v2_subscription_response(response)
end
def changetofree_v2_subscription(subscription_id, data)
response = connection.patch("/v2/subscriptions/#{subscription_id}/changetofree", data)
handle_v2_subscription_response(response)
end
def update_v2_subscription(subscription_id, plan_data)
response = connection.patch("/v2/subscriptions/#{subscription_id}/plan", plan_data)
handle_v2_subscription_response(response)
end
def purchase_addon(subscription_id, addon_config_id)
response = connection.patch("/v2/subscriptions/#{subscription_id}/addon", { addon: addon_config_id })
handle_v2_subscription_response(response)
end
def v2_subscription_user_usages(subscription_id)
body(connection.get("/v2/subscriptions/#{subscription_id}/user_usage")).map do |usage_data|
Travis::API::V3::Models::V2AddonUsage.new(usage_data)
end
end
def v2_plans_for_organization(organization_id)
body(connection.get("/v2/plans_for/organization/#{organization_id}")).map do |plan_data|
Travis::API::V3::Models::V2PlanConfig.new(plan_data)
end
end
def v2_plans_for_user
body(connection.get('/v2/plans_for/user')).map do |plan_data|
Travis::API::V3::Models::V2PlanConfig.new(plan_data)
end
end
def cancel_subscription(id, reason_data)
response = connection.post("/subscriptions/#{id}/cancel", reason_data)
handle_subscription_response(response)
end
def plans_for_organization(organization_id)
body(connection.get("/plans_for/organization/#{organization_id}")).map do |plan_data|
Travis::API::V3::Models::Plan.new(plan_data)
end
end
def plans_for_user
body(connection.get('/plans_for/user')).map do |plan_data|
Travis::API::V3::Models::Plan.new(plan_data)
end
end
def resubscribe(id)
response = connection.patch("/subscriptions/#{id}/resubscribe")
handle_subscription_response(response)
end
def pay(id)
response = connection.post("/subscriptions/#{id}/pay")
handle_subscription_response(response)
end
def pay_v2(id)
response = connection.post("/v2/subscriptions/#{id}/pay")
handle_v2_subscription_response(response)
end
def get_coupon(code)
response = connection.get("/coupons/#{code}")
handle_coupon_response(response)
end
def update_organization_billing_permission(organization_id, billing_admin_only)
response = connection.patch("/organization/permission_update/#{organization_id}", billing_admin_only)
handle_subscription_response(response)
end
def create_auto_refill(plan_id, is_enabled)
response = connection.post('/auto_refill', {plan: plan_id, enabled: is_enabled})
handle_errors_and_respond(response)
end
def update_auto_refill(addon_id, threshold, amount)
response = connection.patch('/auto_refill', {id: addon_id, threshold: threshold, amount: amount})
handle_errors_and_respond(response)
end
def get_auto_refill(plan_id)
response = connection.get("/auto_refill?plan_id=#{plan_id}")
handle_errors_and_respond(response) { |r| Travis::API::V3::Models::AutoRefill.new(r) }
end
def cancel_v2_subscription(id, reason_data)
response = connection.post("/v2/subscriptions/#{id}/cancel", reason_data)
handle_subscription_response(response)
end
def usage_stats(owners)
data = connection.post("/usage/stats", owners: owners, query: 'paid_plan_count')
data = data&.body
data = data.is_a?(String) && data.length > 0 ? JSON.parse(data) : data
data.fetch('paid_plans').to_i > 0 if data && data['paid_plans']
rescue
false
end
private
def handle_subscription_response(response)
handle_errors_and_respond(response) { |r| Travis::API::V3::Models::Subscription.new(r) }
end
def handle_v2_subscription_response(response)
handle_errors_and_respond(response) { |r| Travis::API::V3::Models::V2Subscription.new(r) }
end
def handle_coupon_response(response)
handle_errors_and_respond(response) { |r| Travis::API::V3::Models::Coupon.new(r) }
end
def handle_errors_and_respond(response)
body = response.body.is_a?(String) && response.body.length > 0 ? JSON.parse(response.body) : response.body
case response.status
when 200, 201
yield(body) if block_given?
when 202
true
when 204
true
when 400
raise Travis::API::V3::ClientError, body['error']
when 403
raise Travis::API::V3::InsufficientAccess, body['rejection_code']
when 404
raise Travis::API::V3::NotFound, body['error']
when 422
raise Travis::API::V3::UnprocessableEntity, body['error']
else
raise Travis::API::V3::ServerError, 'Billing system failed'
end
end
def body(data)
if data&.body.is_a?(String)
data&.body.length > 0 ? JSON.parse(data.body) : {}
else
data&.body
end
end
def connection(timeout: 10)
@connection ||= Faraday.new(url: billing_url, ssl: { ca_path: '/usr/lib/ssl/certs' }) do |conn|
conn.request(:authorization, :basic, '_', billing_auth_key)
conn.headers['X-Travis-User-Id'] = @user_id.to_s
conn.headers['Content-Type'] = 'application/json'
conn.request :json
conn.response :json
conn.options[:open_timeout] = timeout
conn.options[:timeout] = timeout
conn.adapter :net_http
end
end
def billing_url
Travis.config.billing.url || raise(ConfigurationError, 'No billing url configured')
end
def billing_auth_key
Travis.config.billing.auth_key || raise(ConfigurationError, 'No billing auth key configured')
end
end
end