bachs-sdk 0.1.0

Unofficial Rust SDK for the Bachs API — payments and billing for internet businesses.
Documentation
use crate::client::{Bachs, RequestOptions};
use crate::common::{Address, ListParams, ListResponse, Metadata, Timestamp};
use crate::error::BachsResult;
use reqwest::Method;
use serde::{Deserialize, Serialize};

/// A customer's billing address. Treated as one atomic value: on update, a
/// supplied object replaces every component rather than merging with what's
/// stored.
pub type CustomerBillingAddress = Address;

#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateCustomerRequest {
    /// The customer's email address. Used to identify the customer and send receipts.
    pub email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// E.164 format, e.g. `+2348012345678`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_number: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing_address: Option<CustomerBillingAddress>,
}

impl CreateCustomerRequest {
    pub fn new(email: impl Into<String>) -> Self {
        Self {
            email: email.into(),
            ..Default::default()
        }
    }

    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    pub fn phone_number(mut self, phone: impl Into<String>) -> Self {
        self.phone_number = Some(phone.into());
        self
    }

    pub fn metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = Some(metadata);
        self
    }

    pub fn billing_address(mut self, address: CustomerBillingAddress) -> Self {
        self.billing_address = Some(address);
        self
    }
}

/// Fields you can change on an existing customer. Any field left `None`
/// (the default) is left untouched by the API — except `billing_address`,
/// which replaces the whole address atomically when supplied.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateCustomerRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_number: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing_address: Option<CustomerBillingAddress>,
}

impl UpdateCustomerRequest {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    pub fn phone_number(mut self, phone: impl Into<String>) -> Self {
        self.phone_number = Some(phone.into());
        self
    }

    pub fn metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = Some(metadata);
        self
    }

    pub fn billing_address(mut self, address: CustomerBillingAddress) -> Self {
        self.billing_address = Some(address);
        self
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Customer {
    /// Unique identifier for the customer, prefixed with `cust_`.
    pub customer_id: String,
    pub email: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub phone_number: Option<String>,
    #[serde(default)]
    pub metadata: Metadata,
    #[serde(default)]
    pub billing_address: Option<CustomerBillingAddress>,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

/// Query parameters for listing customers.
#[derive(Debug, Clone, Default)]
pub struct ListCustomersParams {
    pub base: ListParams,
    pub email: Option<String>,
}

impl ListCustomersParams {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn limit(mut self, limit: u32) -> Self {
        self.base = self.base.limit(limit);
        self
    }

    pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
        self.base = self.base.cursor(cursor);
        self
    }

    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    fn to_query(&self) -> Vec<(&str, String)> {
        let mut q = self.base.to_query();
        if let Some(email) = &self.email {
            q.push(("email", email.clone()));
        }
        q
    }
}

/// Client for the `/v1/customers` resource. Requires the `customers:write`
/// scope for mutating calls.
pub struct Customers<'a> {
    pub(crate) client: &'a Bachs,
}

impl<'a> Customers<'a> {
    /// Create a customer. Only `email` is required.
    pub async fn create(&self, req: &CreateCustomerRequest) -> BachsResult<Customer> {
        self.create_with_options(req, None).await
    }

    pub async fn create_with_options(
        &self,
        req: &CreateCustomerRequest,
        options: Option<&RequestOptions>,
    ) -> BachsResult<Customer> {
        self.client
            .send(Method::POST, "/v1/customers", Some(req), None, options)
            .await
    }

    /// Retrieve a customer by ID.
    pub async fn get(&self, customer_id: &str) -> BachsResult<Customer> {
        self.client
            .send::<(), _>(
                Method::GET,
                &format!("/v1/customers/{customer_id}"),
                None,
                None,
                None,
            )
            .await
    }

    /// Update a customer. Only the fields you set are changed.
    pub async fn update(
        &self,
        customer_id: &str,
        req: &UpdateCustomerRequest,
    ) -> BachsResult<Customer> {
        self.client
            .send(
                Method::PATCH,
                &format!("/v1/customers/{customer_id}"),
                Some(req),
                None,
                None,
            )
            .await
    }

    /// Delete a customer.
    pub async fn delete(&self, customer_id: &str) -> BachsResult<()> {
        self.client
            .send::<(), serde_json::Value>(
                Method::DELETE,
                &format!("/v1/customers/{customer_id}"),
                None,
                None,
                None,
            )
            .await
            .map(|_| ())
    }

    /// List customers, optionally filtered by email.
    pub async fn list(&self, params: &ListCustomersParams) -> BachsResult<ListResponse<Customer>> {
        let query = params.to_query();
        self.client
            .send::<(), _>(Method::GET, "/v1/customers", None, Some(&query), None)
            .await
    }
}