use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::billing::{
AllocationListResponse, AllocationResponse, AllocationTransferResponse, BillingProfileResponse,
BillingSetupResponse, BlockedAttemptListResponse, LedgerResponse, TopupResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct Billing {
inner: Arc<Inner>,
}
fn billing_path(merchant_id: &str) -> String {
format!("/billing/{}", encode_segment(merchant_id))
}
impl Billing {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub fn allocations(&self) -> BillingAllocations {
BillingAllocations::new(self.inner.clone())
}
pub async fn profile(&self, merchant_id: &str) -> Result<BillingProfileResponse> {
let path = billing_path(merchant_id);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn setup(
&self,
merchant_id: &str,
params: Option<&BillingSetupRequest>,
) -> Result<BillingSetupResponse> {
let body = match params {
Some(p) => {
p.validate()?;
Some(to_json_vec(p)?)
}
None => None,
};
let path = format!("{}/setup", billing_path(merchant_id));
self.inner
.request(HttpMethod::Post, &path, body.as_deref(), &[], None)
.await
}
pub async fn complete_setup(
&self,
merchant_id: &str,
params: &BillingCompleteSetupRequest,
) -> Result<BillingProfileResponse> {
let body = to_json_vec(params)?;
let path = format!("{}/setup/complete", billing_path(merchant_id));
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn topup(&self, merchant_id: &str, params: &TopupRequest) -> Result<TopupResponse> {
let body = to_json_vec(params)?;
let path = format!("{}/topup", billing_path(merchant_id));
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn list_ledger(
&self,
merchant_id: &str,
params: Option<&LedgerListParams>,
) -> Result<LedgerResponse> {
let query = params.map(LedgerListParams::to_query).unwrap_or_default();
let path = format!("{}/ledger", billing_path(merchant_id));
self.inner
.request(HttpMethod::Get, &path, None, &query, None)
.await
}
pub async fn list_blocked_attempts(
&self,
merchant_id: &str,
params: Option<&BlockedAttemptListParams>,
) -> Result<BlockedAttemptListResponse> {
let query = params
.map(BlockedAttemptListParams::to_query)
.unwrap_or_default();
let path = format!("{}/blocked-attempts", billing_path(merchant_id));
self.inner
.request(HttpMethod::Get, &path, None, &query, None)
.await
}
pub async fn update_auto_recharge(
&self,
merchant_id: &str,
params: &AutoRechargeUpdateRequest,
) -> Result<BillingProfileResponse> {
params.validate()?;
let body = to_json_vec(params)?;
let path = format!("{}/auto-recharge", billing_path(merchant_id));
self.inner
.request(HttpMethod::Patch, &path, Some(&body), &[], None)
.await
}
}
#[derive(Debug, Clone)]
pub struct BillingAllocations {
inner: Arc<Inner>,
}
impl BillingAllocations {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn transfer_in(
&self,
merchant_id: &str,
params: &AllocationTransferRequest,
) -> Result<AllocationTransferResponse> {
let body = to_json_vec(params)?;
let path = format!("{}/allocations/transfer-in", billing_path(merchant_id));
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn transfer_out(
&self,
merchant_id: &str,
params: &AllocationTransferRequest,
) -> Result<AllocationTransferResponse> {
let body = to_json_vec(params)?;
let path = format!("{}/allocations/transfer-out", billing_path(merchant_id));
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn list(&self, merchant_id: &str) -> Result<AllocationListResponse> {
let path = format!("{}/allocations", billing_path(merchant_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn retrieve(
&self,
merchant_id: &str,
profile_id: &str,
) -> Result<AllocationResponse> {
let path = format!(
"{}/allocations/{}",
billing_path(merchant_id),
encode_segment(profile_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct BillingSetupRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub balance_currency: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const BILLING_SETUP_REQUEST_NAMED: &[&str] = &["balance_currency"];
impl ValidateRequest for BillingSetupRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if BILLING_SETUP_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on BillingSetupRequest"
)));
}
}
Ok(())
}
}
impl BillingSetupRequest {
pub fn new() -> Self {
Self::default()
}
pub fn balance_currency(mut self, currency: impl Into<String>) -> Self {
self.balance_currency = Some(currency.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct BillingCompleteSetupRequest {
pub setup_intent_id: String,
}
impl BillingCompleteSetupRequest {
pub fn new(setup_intent_id: impl Into<String>) -> Self {
Self {
setup_intent_id: setup_intent_id.into(),
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct TopupRequest {
pub amount: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub idempotency_key: Option<String>,
}
impl TopupRequest {
pub fn new(amount: i64) -> Self {
Self {
amount,
idempotency_key: None,
}
}
pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
self.idempotency_key = Some(key.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct AllocationTransferRequest {
pub profile_id: String,
pub amount: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub idempotency_key: Option<String>,
}
impl AllocationTransferRequest {
pub fn new(profile_id: impl Into<String>, amount: i64) -> Self {
Self {
profile_id: profile_id.into(),
amount,
idempotency_key: None,
}
}
pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
self.idempotency_key = Some(key.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct AutoRechargeUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub threshold_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub recharge_amount: Option<i64>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const AUTO_RECHARGE_UPDATE_REQUEST_NAMED: &[&str] =
&["enabled", "threshold_amount", "recharge_amount"];
impl ValidateRequest for AutoRechargeUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if AUTO_RECHARGE_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on AutoRechargeUpdateRequest"
)));
}
}
Ok(())
}
}
impl AutoRechargeUpdateRequest {
pub fn new() -> Self {
Self::default()
}
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = Some(enabled);
self
}
pub fn amounts(mut self, threshold_amount: i64, recharge_amount: i64) -> Self {
self.threshold_amount = Some(threshold_amount);
self.recharge_amount = Some(recharge_amount);
self
}
}
#[derive(Debug, Clone, Default)]
pub struct LedgerListParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
pub profile_id: Option<String>,
}
impl LedgerListParams {
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.clone()));
}
q
}
}
#[derive(Debug, Clone, Default)]
pub struct BlockedAttemptListParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
pub profile_id: Option<String>,
pub block_reason: Option<String>,
pub created_after: Option<String>,
pub created_before: Option<String>,
}
impl BlockedAttemptListParams {
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.clone()));
}
if let Some(v) = &self.block_reason {
q.push(("block_reason", v.clone()));
}
if let Some(v) = &self.created_after {
q.push(("created_after", v.clone()));
}
if let Some(v) = &self.created_before {
q.push(("created_before", v.clone()));
}
q
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const PROFILE_JSON: &str = r#"{
"id": "bp_1",
"merchant_id": "merch_1",
"has_payment_method": true,
"balance_amount": 1000,
"balance_currency": "USD",
"billing_status": "active",
"auto_recharge": {"enabled": true, "threshold_amount": 1000, "recharge_amount": 20000},
"hard_floor_amount": 0,
"consecutive_recharge_failures": 0,
"is_trusted": false,
"created_at": "2026-01-01T00:00:00Z",
"modified_at": "2026-01-02T00:00:00Z"
}"#;
const SETUP_JSON: &str = r#"{
"billing_profile_id": "bp_1",
"merchant_id": "merch_1",
"stripe_customer_id": "cus_1",
"setup_intent_id": "seti_1",
"setup_intent_client_secret": "seti_1_secret_supersecretvalue",
"billing_status": "setup_incomplete"
}"#;
const TOPUP_JSON: &str =
r#"{"payment_intent_id":"pi_1","status":"succeeded","amount":5000,"currency":"USD"}"#;
const ALLOCATION_JSON: &str = r#"{
"id": "alc_1",
"merchant_id": "merch_1",
"profile_id": "pro_1",
"balance_amount": 250,
"balance_currency": "USD",
"allocation_status": "active"
}"#;
const TRANSFER_JSON: &str = r#"{
"allocation_id": "alc_1",
"profile_id": "pro_1",
"allocation_balance": 250,
"host_balance": 9750,
"ledger_entry_id": "led_1"
}"#;
#[tokio::test]
async fn profile_gets_the_billing_root_and_encodes_the_merchant_id() {
let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON)]);
let profile = client.billing().profile("merch/1").await.unwrap();
assert_eq!(profile.balance_amount, 1000);
assert!(profile.auto_recharge.enabled);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/billing/merch%2F1");
}
#[tokio::test]
async fn setup_posts_params_when_given() {
let (client, mock) = client_with(vec![Step::ok(SETUP_JSON)]);
let params = BillingSetupRequest::new().balance_currency("USD");
let setup = client
.billing()
.setup("merch_1", Some(¶ms))
.await
.unwrap();
assert_eq!(
setup.setup_intent_client_secret,
"seti_1_secret_supersecretvalue"
);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/billing/merch_1/setup");
assert_eq!(seen[0].body_json()["balance_currency"], "USD");
}
#[tokio::test]
async fn setup_sends_no_body_when_params_are_absent() {
let (client, mock) = client_with(vec![Step::ok(SETUP_JSON)]);
client.billing().setup("merch_1", None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert!(seen[0].body.is_none(), "setup(None) must send no body");
}
#[tokio::test]
async fn complete_setup_posts_the_setup_intent_id() {
let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON)]);
client
.billing()
.complete_setup("merch_1", &BillingCompleteSetupRequest::new("seti_1"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/billing/merch_1/setup/complete"
);
assert_eq!(seen[0].body_json()["setup_intent_id"], "seti_1");
}
#[tokio::test]
async fn topup_posts_amount_and_body_level_idempotency_key() {
let (client, mock) = client_with(vec![Step::ok(TOPUP_JSON)]);
let params = TopupRequest::new(5000).idempotency_key("uuid-1");
let topup = client.billing().topup("merch_1", ¶ms).await.unwrap();
assert_eq!(topup.amount, 5000);
assert_eq!(topup.payment_intent_id, "pi_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/billing/merch_1/topup");
let body = seen[0].body_json();
assert_eq!(body["amount"], 5000);
assert_eq!(body["idempotency_key"], "uuid-1");
assert!(!seen[0].had_idempotency_key());
}
#[tokio::test]
async fn topup_omits_the_idempotency_key_when_unset() {
let (client, mock) = client_with(vec![Step::ok(TOPUP_JSON)]);
client
.billing()
.topup("merch_1", &TopupRequest::new(1))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].body_json(), json!({"amount": 1}));
}
#[tokio::test]
async fn list_ledger_serializes_its_filters() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"entries":[{
"id":"led_1","entry_type":"fee","amount":-250,"currency":"USD",
"reference_kind":"payment","reference_id":"pay_1","balance_after":9750
}],"total_count":1}"#,
)]);
let params = LedgerListParams {
limit: Some(25),
offset: Some(50),
profile_id: Some("pro_1".to_string()),
};
let ledger = client
.billing()
.list_ledger("merch_1", Some(¶ms))
.await
.unwrap();
assert_eq!(ledger.total_count, Some(1));
assert_eq!(ledger.entries[0].amount, -250);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/billing/merch_1/ledger?limit=25&offset=50&profile_id=pro_1"
);
}
#[tokio::test]
async fn list_blocked_attempts_serializes_every_filter() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"entries":[{
"id":"blk_1","merchant_id":"merch_1","payment_id":"pay_1",
"block_reason":"billing_suspended"
}]}"#,
)]);
let params = BlockedAttemptListParams {
limit: Some(10),
offset: Some(0),
profile_id: Some("pro_1".to_string()),
block_reason: Some("billing_suspended".to_string()),
created_after: Some("2026-01-01T00:00:00Z".to_string()),
created_before: Some("2026-02-01T00:00:00Z".to_string()),
};
let blocked = client
.billing()
.list_blocked_attempts("merch_1", Some(¶ms))
.await
.unwrap();
assert_eq!(blocked.entries[0].block_reason, "billing_suspended");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/billing/merch_1/blocked-attempts\
?limit=10&offset=0&profile_id=pro_1&block_reason=billing_suspended\
&created_after=2026-01-01T00:00:00Z&created_before=2026-02-01T00:00:00Z"
);
}
#[tokio::test]
async fn list_blocked_attempts_sends_no_query_without_params() {
let (client, mock) = client_with(vec![Step::ok(r#"{"entries":[]}"#)]);
client
.billing()
.list_blocked_attempts("merch_1", None)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/billing/merch_1/blocked-attempts"
);
}
#[tokio::test]
async fn update_auto_recharge_patches_the_auto_recharge_path() {
let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON)]);
let params = AutoRechargeUpdateRequest::new()
.enabled(true)
.amounts(1_000, 20_000);
client
.billing()
.update_auto_recharge("merch_1", ¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PATCH");
assert_eq!(
seen[0].url,
"https://api.test/billing/merch_1/auto-recharge"
);
let body = seen[0].body_json();
assert_eq!(body["enabled"], true);
assert_eq!(body["threshold_amount"], 1_000);
assert_eq!(body["recharge_amount"], 20_000);
}
#[tokio::test]
async fn allocation_transfers_post_to_their_own_paths() {
let (client, mock) = client_with(vec![Step::ok(TRANSFER_JSON), Step::ok(TRANSFER_JSON)]);
let allocations = client.billing().allocations();
let params = AllocationTransferRequest::new("pro_1", 250).idempotency_key("uuid-2");
let moved = allocations.transfer_in("merch_1", ¶ms).await.unwrap();
assert_eq!(moved.allocation_balance, 250);
assert_eq!(moved.host_balance, 9750);
allocations.transfer_out("merch_1", ¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/billing/merch_1/allocations/transfer-in"
);
let body = seen[0].body_json();
assert_eq!(body["profile_id"], "pro_1");
assert_eq!(body["amount"], 250);
assert_eq!(body["idempotency_key"], "uuid-2");
assert_eq!(seen[1].method, "POST");
assert_eq!(
seen[1].url,
"https://api.test/billing/merch_1/allocations/transfer-out"
);
}
#[tokio::test]
async fn allocations_list_and_retrieve_hit_their_paths() {
let (client, mock) = client_with(vec![
Step::ok(&format!(r#"{{"allocations":[{ALLOCATION_JSON}]}}"#)),
Step::ok(ALLOCATION_JSON),
]);
let allocations = client.billing().allocations();
let listed = allocations.list("merch_1").await.unwrap();
assert_eq!(listed.allocations[0].profile_id, "pro_1");
let one = allocations.retrieve("merch_1", "pro/1").await.unwrap();
assert_eq!(one.balance_amount, 250);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/billing/merch_1/allocations");
assert_eq!(seen[1].method, "GET");
assert_eq!(
seen[1].url,
"https://api.test/billing/merch_1/allocations/pro%2F1"
);
}
#[test]
fn billing_setup_request_named_fields_are_complete() {
let req = BillingSetupRequest {
balance_currency: Some("USD".to_string()),
extra: serde_json::Map::new(),
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
BILLING_SETUP_REQUEST_NAMED.contains(&key.as_str()),
"BILLING_SETUP_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn auto_recharge_update_request_named_fields_are_complete() {
let req = AutoRechargeUpdateRequest {
enabled: Some(true),
threshold_amount: Some(1),
recharge_amount: Some(2),
extra: serde_json::Map::new(),
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
AUTO_RECHARGE_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"AUTO_RECHARGE_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn billing_setup_validate_rejects_colliding_extra_key() {
let mut req = BillingSetupRequest::new();
req.extra
.insert("balance_currency".to_string(), json!("EUR"));
assert!(matches!(
req.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
#[test]
fn auto_recharge_validate_rejects_colliding_extra_key() {
let mut req = AutoRechargeUpdateRequest::new();
req.extra.insert("enabled".to_string(), json!(false));
assert!(matches!(
req.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
#[tokio::test]
async fn setup_rejects_a_colliding_extra_key_before_sending() {
let (client, mock) = client_with(vec![Step::ok(SETUP_JSON)]);
let mut params = BillingSetupRequest::new();
params
.extra
.insert("balance_currency".to_string(), json!("EUR"));
let err = client
.billing()
.setup("merch_1", Some(¶ms))
.await
.unwrap_err();
assert!(matches!(err, DelopayError::InvalidRequest(_)));
assert!(
mock.seen.lock().unwrap().is_empty(),
"an invalid request must not reach the transport"
);
}
}