delopay 0.2.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `customers` resource.

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::common::ListResponse;
use crate::core::models::customer::CustomerResponse;
use crate::core::models::mandate::MandateResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

/// The `customers` resource, obtained via [`crate::Delopay::customers`].
#[derive(Debug, Clone)]
pub struct Customers {
    inner: Arc<Inner>,
}

impl Customers {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Create a customer.
    pub async fn create(&self, params: &CustomerCreateRequest) -> Result<CustomerResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/customers", Some(&body), &[], None)
            .await
    }

    /// Retrieve a customer by ID.
    pub async fn retrieve(&self, customer_id: &str) -> Result<CustomerResponse> {
        let path = format!("/customers/{}", encode_segment(customer_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a customer.
    pub async fn update(
        &self,
        customer_id: &str,
        params: &CustomerCreateRequest,
    ) -> Result<CustomerResponse> {
        params.validate()?;
        let path = format!("/customers/{}", encode_segment(customer_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a customer.
    pub async fn delete(&self, customer_id: &str) -> Result<CustomerResponse> {
        let path = format!("/customers/{}", encode_segment(customer_id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// List customers, optionally filtered by email, shop (`profile_id`), or
    /// project (`project_id`).
    pub async fn list(&self, params: Option<&CustomerListParams>) -> Result<Vec<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/customers/list", None, &query, None)
            .await
    }

    /// List customers with page and total counts. Same filters as
    /// [`list`](Self::list); the page count arrives in the envelope's `count`
    /// field, preserved in [`crate::ListResponse::extra`].
    pub async fn list_with_count(
        &self,
        params: Option<&CustomerListParams>,
    ) -> Result<ListResponse<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request(
                HttpMethod::Get,
                "/customers/list-with-count",
                None,
                &query,
                None,
            )
            .await
    }

    /// List the mandates held against a customer.
    pub async fn list_mandates(&self, customer_id: &str) -> Result<Vec<MandateResponse>> {
        let path = format!("/customers/{}/mandates", encode_segment(customer_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }
}

/// Filter / pagination parameters for [`Customers::list`] and
/// [`Customers::list_with_count`].
#[derive(Debug, Clone, Default)]
pub struct CustomerListParams {
    /// Maximum number of customers to return.
    pub limit: Option<i64>,
    /// Number of customers to skip.
    pub offset: Option<i64>,
    /// Only customers with this email.
    pub email: Option<String>,
    /// Only customers who have transacted in this shop (business profile).
    pub profile_id: Option<String>,
    /// Only customers who have transacted in this project (all its shops).
    pub project_id: Option<String>,
}

impl CustomerListParams {
    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.email {
            q.push(("email", v.clone()));
        }
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        if let Some(v) = &self.project_id {
            q.push(("project_id", v.clone()));
        }
        q
    }
}

/// Parameters for [`Customers::create`] and [`Customers::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CustomerCreateRequest {
    /// Provide your own customer ID (acts as an idempotency key server-side).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    /// Customer's full name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Customer's email address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// Customer's phone number (digits only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone: Option<String>,
    /// Phone country code (e.g. `"+44"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_country_code: Option<String>,
    /// Internal notes about the customer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Default billing/shipping address (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<Value>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `CustomerCreateRequest`'s fields, as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const CUSTOMER_CREATE_REQUEST_NAMED: &[&str] = &[
    "customer_id",
    "name",
    "email",
    "phone",
    "phone_country_code",
    "description",
    "address",
    "metadata",
];

impl ValidateRequest for CustomerCreateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if CUSTOMER_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on CustomerCreateRequest"
                )));
            }
        }
        Ok(())
    }
}

impl CustomerCreateRequest {
    /// An empty request; set the fields you need.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the customer's email.
    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    /// Set the customer's name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the customer's phone (digits) and country code.
    pub fn phone(mut self, phone: impl Into<String>, country_code: impl Into<String>) -> Self {
        self.phone = Some(phone.into());
        self.phone_country_code = Some(country_code.into());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Every optional field populated so serialization emits the full key set.
    fn full_customer_create_request() -> CustomerCreateRequest {
        CustomerCreateRequest {
            customer_id: Some("cus_1".to_string()),
            name: Some("Ada Lovelace".to_string()),
            email: Some("ada@example.com".to_string()),
            phone: Some("5551234".to_string()),
            phone_country_code: Some("+44".to_string()),
            description: Some("VIP customer".to_string()),
            address: Some(json!({"country": "GB"})),
            metadata: Some(json!({"tier": "gold"})),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard: catches a new field added to `CustomerCreateRequest`
    /// without a matching update to `CUSTOMER_CREATE_REQUEST_NAMED`.
    #[test]
    fn customer_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_customer_create_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                CUSTOMER_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "CUSTOMER_CREATE_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or CustomerCreateRequest's extra-key collision guard \
                 will silently stop covering this field"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_key_colliding_with_named_field() {
        let mut req = CustomerCreateRequest::new().email("ada@example.com");
        req.extra.insert("name".to_string(), json!("collide"));

        let err = req.validate().unwrap_err();
        match err {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("name")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    use crate::http::mock::{Step, client_with};

    #[tokio::test]
    async fn list_serializes_shop_filters() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        let params = CustomerListParams {
            limit: Some(10),
            profile_id: Some("pro_1".to_string()),
            ..Default::default()
        };
        client.customers().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/list?limit=10&profile_id=pro_1"
        );
    }

    #[tokio::test]
    async fn list_with_count_hits_its_path_and_keeps_count_in_extra() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"count":1,"total_count":9,"data":[{"customer_id":"cus_1"}]}"#,
        )]);
        let out = client.customers().list_with_count(None).await.unwrap();
        assert_eq!(out.total_count, Some(9));
        assert_eq!(out.extra["count"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/customers/list-with-count");
    }

    #[tokio::test]
    async fn list_mandates_gets_the_customer_mandates_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"[{"mandate_id":"man_1","status":"active"}]"#,
        )]);
        let out = client.customers().list_mandates("cus_1").await.unwrap();
        assert_eq!(out[0].mandate_id, "man_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/customers/cus_1/mandates");
    }
}