delopay 0.4.0

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

use std::sync::Arc;

use crate::core::encoding::encode_segment;
use crate::core::error::Result;
use crate::core::models::common::MandateStatus;
use crate::core::models::mandate::MandateResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

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

    /// Revoke a mandate.
    pub async fn revoke(&self, mandate_id: &str) -> Result<MandateResponse> {
        let path = format!("/mandates/revoke/{}", encode_segment(mandate_id));
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// List mandates, optionally filtered by status.
    pub async fn list(&self, params: Option<&MandateListParams>) -> Result<Vec<MandateResponse>> {
        let query = params.map(MandateListParams::to_query).unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/mandates/list", None, &query, None)
            .await
    }
}

/// Filter parameters for [`Mandates::list`].
#[derive(Debug, Clone, Default)]
pub struct MandateListParams {
    /// Only mandates in this status (e.g. `"active"`, `"revoked"`).
    pub mandate_status: Option<MandateStatus>,
}

impl MandateListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = &self.mandate_status {
            q.push(("mandate_status", v.clone()));
        }
        q
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::mock::{Step, client_with};

    #[tokio::test]
    async fn list_serializes_the_status_filter() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        let params = MandateListParams {
            mandate_status: Some("active".to_string()),
        };
        client.mandates().list(Some(&params)).await.unwrap();

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

    #[tokio::test]
    async fn list_without_params_sends_no_query() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        client.mandates().list(None).await.unwrap();

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

    #[tokio::test]
    async fn revoke_posts_to_the_revoke_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"mandate_id":"man/1","status":"revoked"}"#,
        )]);
        client.mandates().revoke("man/1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/mandates/revoke/man%2F1");
    }
}