use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::error::{Error, Result};
use crate::http::{client, encode, ok};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethod {
pub brand: String,
pub last4: String,
pub exp_month: u32,
pub exp_year: u32,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AutoReload {
pub enabled: bool,
pub threshold: f64,
pub target: f64,
pub monthly_cap: f64,
pub monthly_spent: f64,
pub status: String,
pub available: bool,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AutoReloadUpdate {
pub enabled: bool,
pub threshold: f64,
pub target: f64,
pub monthly_cap: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TransactionKind {
Manual,
Automatic,
Subscription,
Grant,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Transaction {
pub id: String,
pub kind: TransactionKind,
pub amount: f64,
pub status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub failure_message: Option<String>,
pub created_at: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub completed_at: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Plan {
Free,
Premium,
Enterprise,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Subscription {
pub plan: Plan,
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub period_end: Option<String>,
#[serde(default)]
pub cancel_at_period_end: bool,
#[serde(default)]
pub addons: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Addon {
pub id: String,
pub name: String,
pub price: f64,
pub with_premium: f64,
pub currency: String,
pub interval: String,
}
#[derive(Debug, Clone, Default)]
pub struct SubscribeOptions {
pub return_url: Option<String>,
pub addon: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct CancelOptions {
pub addon: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Summary {
pub balance: f64,
pub currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method: Option<PaymentMethod>,
pub auto_reload: AutoReload,
pub subscription: Subscription,
pub recent_transactions: Vec<Transaction>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireSummary {
balance_micros: f64,
currency: String,
#[serde(default)]
payment_method: Option<PaymentMethod>,
auto_reload: Value,
#[serde(default)]
subscription: Option<Subscription>,
recent_transactions: Vec<Value>,
}
impl AutoReload {
pub fn from_json(json: &Value) -> AutoReload {
let number = |key: &str| json[key].as_f64().unwrap_or(0.0);
AutoReload {
enabled: json["enabled"].as_bool().unwrap_or(false),
threshold: number("thresholdMicros") / 1_000_000.0,
target: number("targetMicros") / 1_000_000.0,
monthly_cap: number("monthlyCapCents") / 100.0,
monthly_spent: number("monthlySpentCents") / 100.0,
status: json["status"].as_str().unwrap_or_default().to_string(),
available: json["available"] == Value::Bool(true),
}
}
}
impl Transaction {
pub fn from_json(json: &Value) -> Transaction {
let text = |key: &str| json[key].as_str().map(str::to_string);
Transaction {
id: text("id").unwrap_or_default(),
kind: serde_json::from_value(json["kind"].clone()).unwrap_or(TransactionKind::Manual),
amount: json["amountCents"].as_f64().unwrap_or(0.0) / 100.0,
status: text("status").unwrap_or_default(),
failure_message: text("failureMessage"),
created_at: text("createdAt").unwrap_or_default(),
completed_at: text("completedAt"),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct PageQuery {
pub cursor: u32,
pub max: u32,
}
#[derive(Debug, Clone, Deserialize)]
pub struct RedirectUrl {
pub url: String,
}
#[derive(Debug, Clone, Default)]
pub struct ReturnOptions {
pub return_url: Option<String>,
}
async fn request<T: DeserializeOwned>(token: &str, request: reqwest::RequestBuilder) -> Result<T> {
let response = request
.header("Authorization", format!("Token {token}"))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn get(token: &str) -> Result<Summary> {
let value: WireSummary =
request(token, client().get(format!("{}/billing", crate::get_url()))).await?;
Ok(Summary {
balance: value.balance_micros / 1_000_000.0,
currency: value.currency,
payment_method: value.payment_method,
auto_reload: AutoReload::from_json(&value.auto_reload),
subscription: value.subscription.unwrap_or(Subscription {
plan: Plan::Free,
status: "none".to_string(),
period_end: None,
cancel_at_period_end: false,
addons: Vec::new(),
}),
recent_transactions: value
.recent_transactions
.iter()
.map(Transaction::from_json)
.collect(),
})
}
pub async fn checkout(token: &str, amount: f64, options: &ReturnOptions) -> Result<RedirectUrl> {
let amount_cents = (amount * 100.0).round();
if !amount_cents.is_finite() || amount_cents.abs() > 9_007_199_254_740_991.0 {
return Err(Error::Message("Invalid top-up amount.".to_string()));
}
request(
token,
client()
.post(format!("{}/billing/checkout", crate::get_url()))
.json(&json!({ "amountCents": amount_cents as i64, "returnUrl": options.return_url })),
)
.await
}
pub async fn setup_payment_method(token: &str, options: &ReturnOptions) -> Result<RedirectUrl> {
request(
token,
client()
.post(format!("{}/billing/payment-method/setup", crate::get_url()))
.json(&json!({ "returnUrl": options.return_url })),
)
.await
}
pub async fn update_auto_reload(token: &str, update: &AutoReloadUpdate) -> Result<AutoReload> {
let value: Value = request(
token,
client()
.patch(format!("{}/billing/auto-reload", crate::get_url()))
.json(&json!({
"enabled": update.enabled,
"thresholdCents": (update.threshold * 100.0).round() as i64,
"targetCents": (update.target * 100.0).round() as i64,
"monthlyCapCents": (update.monthly_cap * 100.0).round() as i64,
})),
)
.await?;
Ok(AutoReload::from_json(&value))
}
pub async fn open_portal(token: &str, options: &ReturnOptions) -> Result<RedirectUrl> {
request(
token,
client()
.post(format!(
"{}/billing/payment-method/portal",
crate::get_url()
))
.json(&json!({ "returnUrl": options.return_url })),
)
.await
}
pub async fn subscribe(token: &str, options: &SubscribeOptions) -> Result<RedirectUrl> {
request(
token,
client()
.post(format!(
"{}/billing/subscription/checkout",
crate::get_url()
))
.json(&json!({ "returnUrl": options.return_url, "addon": options.addon })),
)
.await
}
pub async fn cancel_subscription(token: &str, options: &CancelOptions) -> Result<Subscription> {
request(
token,
client()
.post(format!("{}/billing/subscription/cancel", crate::get_url()))
.json(&json!({ "addon": options.addon })),
)
.await
}
pub async fn addons(token: &str) -> Result<Vec<Addon>> {
request(
token,
client().get(format!("{}/billing/addons", crate::get_url())),
)
.await
}
pub async fn transactions(token: &str, query: PageQuery) -> Result<Vec<Transaction>> {
let rows: Vec<Value> = request(
token,
client().get(format!(
"{}/billing/transactions?cursor={}&max={}",
crate::get_url(),
query.cursor,
query.max
)),
)
.await?;
Ok(rows.iter().map(Transaction::from_json).collect())
}
#[derive(Debug, Clone, Serialize)]
pub struct UsagePoint {
pub day: String,
pub service: String,
pub base: f64,
pub spread: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PrincipalKind {
User,
Group,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Usage {
pub principal_kind: PrincipalKind,
pub since: String,
pub usage: Vec<UsagePoint>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireUsagePoint {
day: String,
service: String,
base_micros: f64,
spread_micros: f64,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireUsage {
principal_kind: PrincipalKind,
since: String,
usage: Vec<WireUsagePoint>,
}
pub async fn usage(token: &str, group_id: Option<&str>, days: Option<u32>) -> Result<Usage> {
let mut query = format!("days={}", days.unwrap_or(30));
if let Some(group_id) = group_id {
query.push_str(&format!("&groupId={}", encode(group_id)));
}
let value: WireUsage = request(
token,
client().get(format!("{}/billing/usage?{query}", crate::get_url())),
)
.await?;
Ok(Usage {
principal_kind: value.principal_kind,
since: value.since,
usage: value
.usage
.into_iter()
.map(|point| UsagePoint {
day: point.day,
service: point.service,
base: point.base_micros / 1_000_000.0,
spread: point.spread_micros / 1_000_000.0,
})
.collect(),
})
}
pub fn format(amount: f64) -> String {
let cents = (amount.abs() * 100.0).round() as u64;
let dollars = (cents / 100).to_string();
let mut grouped = String::new();
for (index, digit) in dollars.chars().enumerate() {
if index > 0 && (dollars.len() - index).is_multiple_of(3) {
grouped.push(',');
}
grouped.push(digit);
}
let sign = if amount < 0.0 && cents > 0 { "-" } else { "" };
format!("{sign}${grouped}.{:02}", cents % 100)
}