delopay 0.3.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `blocklist` resource: block card BINs and payment-method fingerprints
//! from transacting.

use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::core::encoding::to_json_vec;
use crate::core::error::Result;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// Add an entry to the blocklist.
    pub async fn add(&self, params: &BlocklistAddRequest) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/blocklist", Some(&body), &[], None)
            .await
    }

    /// Remove an entry from the blocklist.
    ///
    /// This is a `DELETE` that carries a **body**: the entry to remove is
    /// identified by the same `{type, data}` pair used to add it, not by a
    /// path segment.
    pub async fn remove(&self, params: &BlocklistAddRequest) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Delete, "/blocklist", Some(&body), &[], None)
            .await
    }

    /// List blocklist entries, optionally filtered by data kind.
    pub async fn list(&self, params: Option<&BlocklistListParams>) -> Result<Vec<Value>> {
        let query = params
            .map(BlocklistListParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/blocklist", None, &query, None)
            .await
    }

    /// Turn blocklist enforcement on or off for the merchant.
    pub async fn toggle(&self, params: &BlocklistToggleParams) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/blocklist/toggle",
                Some(&body),
                &[],
                None,
            )
            .await
    }
}

/// What a blocklist entry's `data` value is, as sent when adding or removing
/// an entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BlocklistEntryType {
    /// The first six digits of a card number.
    CardBin,
    /// A payment-method fingerprint.
    Fingerprint,
    /// An extended (longer than six digit) card BIN.
    ExtendedCardBin,
}

/// The kind of data a stored blocklist entry holds, used as a list filter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BlocklistDataKind {
    /// Entries keyed by payment-method fingerprint.
    PaymentMethod,
    /// Entries keyed by card BIN.
    CardBin,
    /// Entries keyed by extended card BIN.
    ExtendedCardBin,
}

impl BlocklistDataKind {
    /// The wire value, as it appears in the `data_kind` query parameter.
    pub fn as_str(self) -> &'static str {
        match self {
            BlocklistDataKind::PaymentMethod => "payment_method",
            BlocklistDataKind::CardBin => "card_bin",
            BlocklistDataKind::ExtendedCardBin => "extended_card_bin",
        }
    }
}

/// Parameters for [`Blocklist::add`] and [`Blocklist::remove`].
#[derive(Debug, Clone, Serialize)]
pub struct BlocklistAddRequest {
    /// How to interpret [`data`](Self::data).
    #[serde(rename = "type")]
    pub entry_type: BlocklistEntryType,
    /// The BIN or fingerprint to block.
    pub data: String,
}

impl BlocklistAddRequest {
    /// A request blocking `data`, interpreted per `entry_type`.
    pub fn new(entry_type: BlocklistEntryType, data: impl Into<String>) -> Self {
        Self {
            entry_type,
            data: data.into(),
        }
    }
}

/// Filter / pagination parameters for [`Blocklist::list`].
#[derive(Debug, Clone, Default)]
pub struct BlocklistListParams {
    /// Only entries of this data kind.
    pub data_kind: Option<BlocklistDataKind>,
    /// Maximum number of entries to return.
    pub limit: Option<i64>,
    /// Number of entries to skip.
    pub offset: Option<i64>,
}

impl BlocklistListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.data_kind {
            q.push(("data_kind", v.as_str().to_string()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// Parameters for [`Blocklist::toggle`].
#[derive(Debug, Clone, Serialize)]
pub struct BlocklistToggleParams {
    /// `true` enables blocklist enforcement, `false` disables it.
    pub status: bool,
}

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

    const ENTRY_JSON: &str = r#"{
        "fingerprint_id": "fp_1",
        "data_kind": "card_bin",
        "created_at": "2024-01-01T00:00:00Z"
    }"#;

    #[tokio::test]
    async fn add_posts_the_entry_to_the_blocklist_root() {
        let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON)]);
        client
            .blocklist()
            .add(&BlocklistAddRequest::new(
                BlocklistEntryType::ExtendedCardBin,
                "42424242",
            ))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/blocklist");
        let body = seen[0].body_json();
        assert_eq!(body["type"], "extended_card_bin");
        assert_eq!(body["data"], "42424242");
    }

    #[tokio::test]
    async fn remove_deletes_with_a_body() {
        // The entry to remove is identified by the body, not the path: an
        // impl that dropped the body (or used POST) fails here.
        let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON)]);
        client
            .blocklist()
            .remove(&BlocklistAddRequest::new(
                BlocklistEntryType::Fingerprint,
                "fp_1",
            ))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(seen[0].url, "https://api.test/blocklist");
        let body = seen[0].body_json();
        assert_eq!(body["type"], "fingerprint");
        assert_eq!(body["data"], "fp_1");
    }

    #[tokio::test]
    async fn list_serializes_its_filters_in_order() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        let params = BlocklistListParams {
            data_kind: Some(BlocklistDataKind::PaymentMethod),
            limit: Some(10),
            offset: Some(20),
        };
        client.blocklist().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/blocklist?data_kind=payment_method&limit=10&offset=20"
        );
    }

    #[tokio::test]
    async fn list_without_params_sends_no_query() {
        // Companion to the test above: without it, an impl that always emitted
        // a default `data_kind` would still pass.
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        client.blocklist().list(None).await.unwrap();

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

    #[tokio::test]
    async fn toggle_posts_the_status_flag() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"blocklist_guard_enabled":true}"#)]);
        client
            .blocklist()
            .toggle(&BlocklistToggleParams { status: true })
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/blocklist/toggle");
        assert_eq!(seen[0].body_json()["status"], true);
    }
}