1use serde::de::DeserializeOwned;
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4
5use crate::error::{Error, Result};
6use crate::http::{client, encode, ok};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9#[serde(rename_all = "camelCase")]
10pub struct PaymentMethod {
11 pub brand: String,
12 pub last4: String,
13 pub exp_month: u32,
14 pub exp_year: u32,
15}
16
17#[derive(Debug, Clone, Serialize)]
18#[serde(rename_all = "camelCase")]
19pub struct AutoReload {
20 pub enabled: bool,
21 pub threshold: f64,
22 pub target: f64,
23 pub monthly_cap: f64,
24 pub monthly_spent: f64,
25 pub status: String,
26 pub available: bool,
27}
28
29#[derive(Debug, Clone, Serialize)]
30#[serde(rename_all = "camelCase")]
31pub struct AutoReloadUpdate {
32 pub enabled: bool,
33 pub threshold: f64,
34 pub target: f64,
35 pub monthly_cap: f64,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "lowercase")]
40pub enum TransactionKind {
41 Manual,
42 Automatic,
43 Subscription,
44 Grant,
45}
46
47#[derive(Debug, Clone, Serialize)]
48#[serde(rename_all = "camelCase")]
49pub struct Transaction {
50 pub id: String,
51 pub kind: TransactionKind,
52 pub amount: f64,
53 pub status: String,
54 #[serde(skip_serializing_if = "Option::is_none")]
55 pub failure_message: Option<String>,
56 pub created_at: String,
57 #[serde(skip_serializing_if = "Option::is_none")]
58 pub completed_at: Option<String>,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "lowercase")]
63pub enum Plan {
64 Free,
65 Premium,
66 Enterprise,
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize)]
70#[serde(rename_all = "camelCase")]
71pub struct Subscription {
72 pub plan: Plan,
73 pub status: String,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub period_end: Option<String>,
76 #[serde(default)]
77 pub cancel_at_period_end: bool,
78 #[serde(default)]
80 pub addons: Vec<String>,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase")]
87pub struct Addon {
88 pub id: String,
89 pub name: String,
90 pub price: f64,
91 pub with_premium: f64,
93 pub currency: String,
94 pub interval: String,
95}
96
97#[derive(Debug, Clone, Default)]
100pub struct SubscribeOptions {
101 pub return_url: Option<String>,
102 pub addon: Option<String>,
103}
104
105#[derive(Debug, Clone, Default)]
108pub struct CancelOptions {
109 pub addon: Option<String>,
110}
111
112#[derive(Debug, Clone, Serialize)]
113#[serde(rename_all = "camelCase")]
114pub struct Summary {
115 pub balance: f64,
116 pub currency: String,
117 #[serde(skip_serializing_if = "Option::is_none")]
118 pub payment_method: Option<PaymentMethod>,
119 pub auto_reload: AutoReload,
120 pub subscription: Subscription,
121 pub recent_transactions: Vec<Transaction>,
122}
123
124#[derive(Deserialize)]
125#[serde(rename_all = "camelCase")]
126struct WireSummary {
127 balance_micros: f64,
128 currency: String,
129 #[serde(default)]
130 payment_method: Option<PaymentMethod>,
131 auto_reload: Value,
132 #[serde(default)]
133 subscription: Option<Subscription>,
134 recent_transactions: Vec<Value>,
135}
136
137impl AutoReload {
138 pub fn from_json(json: &Value) -> AutoReload {
139 let number = |key: &str| json[key].as_f64().unwrap_or(0.0);
140 AutoReload {
141 enabled: json["enabled"].as_bool().unwrap_or(false),
142 threshold: number("thresholdMicros") / 1_000_000.0,
143 target: number("targetMicros") / 1_000_000.0,
144 monthly_cap: number("monthlyCapCents") / 100.0,
145 monthly_spent: number("monthlySpentCents") / 100.0,
146 status: json["status"].as_str().unwrap_or_default().to_string(),
147 available: json["available"] == Value::Bool(true),
148 }
149 }
150}
151
152impl Transaction {
153 pub fn from_json(json: &Value) -> Transaction {
154 let text = |key: &str| json[key].as_str().map(str::to_string);
155 Transaction {
156 id: text("id").unwrap_or_default(),
157 kind: serde_json::from_value(json["kind"].clone()).unwrap_or(TransactionKind::Manual),
158 amount: json["amountCents"].as_f64().unwrap_or(0.0) / 100.0,
159 status: text("status").unwrap_or_default(),
160 failure_message: text("failureMessage"),
161 created_at: text("createdAt").unwrap_or_default(),
162 completed_at: text("completedAt"),
163 }
164 }
165}
166
167#[derive(Debug, Clone, Copy)]
170pub struct PageQuery {
171 pub cursor: u32,
172 pub max: u32,
173}
174
175#[derive(Debug, Clone, Deserialize)]
177pub struct RedirectUrl {
178 pub url: String,
179}
180
181#[derive(Debug, Clone, Default)]
184pub struct ReturnOptions {
185 pub return_url: Option<String>,
186}
187
188async fn request<T: DeserializeOwned>(token: &str, request: reqwest::RequestBuilder) -> Result<T> {
189 let response = request
190 .header("Authorization", format!("Token {token}"))
191 .send()
192 .await?;
193 Ok(ok(response).await?.json().await?)
194}
195
196pub async fn get(token: &str) -> Result<Summary> {
197 let value: WireSummary =
198 request(token, client().get(format!("{}/billing", crate::get_url()))).await?;
199 Ok(Summary {
200 balance: value.balance_micros / 1_000_000.0,
201 currency: value.currency,
202 payment_method: value.payment_method,
203 auto_reload: AutoReload::from_json(&value.auto_reload),
204 subscription: value.subscription.unwrap_or(Subscription {
205 plan: Plan::Free,
206 status: "none".to_string(),
207 period_end: None,
208 cancel_at_period_end: false,
209 addons: Vec::new(),
210 }),
211 recent_transactions: value
212 .recent_transactions
213 .iter()
214 .map(Transaction::from_json)
215 .collect(),
216 })
217}
218
219pub async fn checkout(token: &str, amount: f64, options: &ReturnOptions) -> Result<RedirectUrl> {
221 let amount_cents = (amount * 100.0).round();
222 if !amount_cents.is_finite() || amount_cents.abs() > 9_007_199_254_740_991.0 {
223 return Err(Error::Message("Invalid top-up amount.".to_string()));
224 }
225 request(
226 token,
227 client()
228 .post(format!("{}/billing/checkout", crate::get_url()))
229 .json(&json!({ "amountCents": amount_cents as i64, "returnUrl": options.return_url })),
230 )
231 .await
232}
233
234pub async fn setup_payment_method(token: &str, options: &ReturnOptions) -> Result<RedirectUrl> {
235 request(
236 token,
237 client()
238 .post(format!("{}/billing/payment-method/setup", crate::get_url()))
239 .json(&json!({ "returnUrl": options.return_url })),
240 )
241 .await
242}
243
244pub async fn update_auto_reload(token: &str, update: &AutoReloadUpdate) -> Result<AutoReload> {
245 let value: Value = request(
246 token,
247 client()
248 .patch(format!("{}/billing/auto-reload", crate::get_url()))
249 .json(&json!({
250 "enabled": update.enabled,
251 "thresholdCents": (update.threshold * 100.0).round() as i64,
252 "targetCents": (update.target * 100.0).round() as i64,
253 "monthlyCapCents": (update.monthly_cap * 100.0).round() as i64,
254 })),
255 )
256 .await?;
257 Ok(AutoReload::from_json(&value))
258}
259
260pub async fn open_portal(token: &str, options: &ReturnOptions) -> Result<RedirectUrl> {
261 request(
262 token,
263 client()
264 .post(format!(
265 "{}/billing/payment-method/portal",
266 crate::get_url()
267 ))
268 .json(&json!({ "returnUrl": options.return_url })),
269 )
270 .await
271}
272
273pub async fn subscribe(token: &str, options: &SubscribeOptions) -> Result<RedirectUrl> {
278 request(
279 token,
280 client()
281 .post(format!(
282 "{}/billing/subscription/checkout",
283 crate::get_url()
284 ))
285 .json(&json!({ "returnUrl": options.return_url, "addon": options.addon })),
286 )
287 .await
288}
289
290pub async fn cancel_subscription(token: &str, options: &CancelOptions) -> Result<Subscription> {
293 request(
294 token,
295 client()
296 .post(format!("{}/billing/subscription/cancel", crate::get_url()))
297 .json(&json!({ "addon": options.addon })),
298 )
299 .await
300}
301
302pub async fn addons(token: &str) -> Result<Vec<Addon>> {
304 request(
305 token,
306 client().get(format!("{}/billing/addons", crate::get_url())),
307 )
308 .await
309}
310
311pub async fn transactions(token: &str, query: PageQuery) -> Result<Vec<Transaction>> {
312 let rows: Vec<Value> = request(
313 token,
314 client().get(format!(
315 "{}/billing/transactions?cursor={}&max={}",
316 crate::get_url(),
317 query.cursor,
318 query.max
319 )),
320 )
321 .await?;
322 Ok(rows.iter().map(Transaction::from_json).collect())
323}
324
325#[derive(Debug, Clone, Serialize)]
326pub struct UsagePoint {
327 pub day: String,
328 pub service: String,
329 pub base: f64,
330 pub spread: f64,
331}
332
333#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
334#[serde(rename_all = "lowercase")]
335pub enum PrincipalKind {
336 User,
337 Group,
338}
339
340#[derive(Debug, Clone, Serialize)]
341#[serde(rename_all = "camelCase")]
342pub struct Usage {
343 pub principal_kind: PrincipalKind,
344 pub since: String,
345 pub usage: Vec<UsagePoint>,
346}
347
348#[derive(Deserialize)]
349#[serde(rename_all = "camelCase")]
350struct WireUsagePoint {
351 day: String,
352 service: String,
353 base_micros: f64,
354 spread_micros: f64,
355}
356
357#[derive(Deserialize)]
358#[serde(rename_all = "camelCase")]
359struct WireUsage {
360 principal_kind: PrincipalKind,
361 since: String,
362 usage: Vec<WireUsagePoint>,
363}
364
365pub async fn usage(token: &str, group_id: Option<&str>, days: Option<u32>) -> Result<Usage> {
368 let mut query = format!("days={}", days.unwrap_or(30));
369 if let Some(group_id) = group_id {
370 query.push_str(&format!("&groupId={}", encode(group_id)));
371 }
372 let value: WireUsage = request(
373 token,
374 client().get(format!("{}/billing/usage?{query}", crate::get_url())),
375 )
376 .await?;
377 Ok(Usage {
378 principal_kind: value.principal_kind,
379 since: value.since,
380 usage: value
381 .usage
382 .into_iter()
383 .map(|point| UsagePoint {
384 day: point.day,
385 service: point.service,
386 base: point.base_micros / 1_000_000.0,
387 spread: point.spread_micros / 1_000_000.0,
388 })
389 .collect(),
390 })
391}
392
393pub fn format(amount: f64) -> String {
395 let cents = (amount.abs() * 100.0).round() as u64;
396 let dollars = (cents / 100).to_string();
397 let mut grouped = String::new();
398 for (index, digit) in dollars.chars().enumerate() {
399 if index > 0 && (dollars.len() - index).is_multiple_of(3) {
400 grouped.push(',');
401 }
402 grouped.push(digit);
403 }
404 let sign = if amount < 0.0 && cents > 0 { "-" } else { "" };
405 format!("{sign}${grouped}.{:02}", cents % 100)
406}