delopay 0.4.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `profile_acquirers` resource: the acquirer identities (BIN, assigned
//! merchant ID, fraud rate) a shop (business profile) presents per card
//! network.

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::profile::ProfileAcquirerResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Create a profile acquirer. `POST /profile-acquirer`
    pub async fn create(
        &self,
        params: &ProfileAcquirerCreateRequest,
    ) -> Result<ProfileAcquirerResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/profile-acquirer",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Update a profile acquirer.
    /// `POST /profile-acquirer/{profile_id}/{profile_acquirer_id}`
    pub async fn update(
        &self,
        profile_id: &str,
        profile_acquirer_id: &str,
        params: &ProfileAcquirerUpdateRequest,
    ) -> Result<ProfileAcquirerResponse> {
        params.validate()?;
        let path = format!(
            "/profile-acquirer/{}/{}",
            encode_segment(profile_id),
            encode_segment(profile_acquirer_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }
}

/// Parameters for [`ProfileAcquirers::create`].
///
/// Every field here is acquirer *identity* data, not a credential, so `Debug`
/// is derived.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProfileAcquirerCreateRequest {
    /// Merchant ID the acquirer assigned to this shop.
    pub acquirer_assigned_merchant_id: String,
    /// Merchant name as registered with the acquirer.
    pub merchant_name: String,
    /// Card network this identity applies to, e.g. `"Visa"`.
    pub network: String,
    /// Acquirer BIN.
    pub acquirer_bin: String,
    /// Acquirer-reported fraud rate.
    pub acquirer_fraud_rate: f64,
    /// Shop (business profile) the identity belongs to.
    pub profile_id: String,
    /// Acquirer ICA, where the network requires one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acquirer_ica: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `ProfileAcquirerCreateRequest`'s fields, as they appear on the
/// wire (`extra` excluded).
const PROFILE_ACQUIRER_CREATE_REQUEST_NAMED: &[&str] = &[
    "acquirer_assigned_merchant_id",
    "merchant_name",
    "network",
    "acquirer_bin",
    "acquirer_fraud_rate",
    "profile_id",
    "acquirer_ica",
];

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

impl ProfileAcquirerCreateRequest {
    /// A request carrying the six fields the API requires.
    pub fn new(
        profile_id: impl Into<String>,
        network: impl Into<String>,
        acquirer_bin: impl Into<String>,
        acquirer_assigned_merchant_id: impl Into<String>,
        merchant_name: impl Into<String>,
        acquirer_fraud_rate: f64,
    ) -> Self {
        Self {
            acquirer_assigned_merchant_id: acquirer_assigned_merchant_id.into(),
            merchant_name: merchant_name.into(),
            network: network.into(),
            acquirer_bin: acquirer_bin.into(),
            acquirer_fraud_rate,
            profile_id: profile_id.into(),
            acquirer_ica: None,
            extra: serde_json::Map::new(),
        }
    }

    /// Set the acquirer ICA.
    #[must_use]
    pub fn acquirer_ica(mut self, ica: impl Into<String>) -> Self {
        self.acquirer_ica = Some(ica.into());
        self
    }
}

/// Parameters for [`ProfileAcquirers::update`]. Every field is optional; only
/// the ones you set are sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProfileAcquirerUpdateRequest {
    /// Merchant ID the acquirer assigned to this shop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acquirer_assigned_merchant_id: Option<String>,
    /// Merchant name as registered with the acquirer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_name: Option<String>,
    /// Card network this identity applies to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network: Option<String>,
    /// Acquirer BIN.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acquirer_bin: Option<String>,
    /// Acquirer ICA.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acquirer_ica: Option<String>,
    /// Acquirer-reported fraud rate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acquirer_fraud_rate: Option<f64>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `ProfileAcquirerUpdateRequest`'s fields, as they appear on the
/// wire (`extra` excluded).
const PROFILE_ACQUIRER_UPDATE_REQUEST_NAMED: &[&str] = &[
    "acquirer_assigned_merchant_id",
    "merchant_name",
    "network",
    "acquirer_bin",
    "acquirer_ica",
    "acquirer_fraud_rate",
];

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

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

    /// Set the acquirer-reported fraud rate.
    #[must_use]
    pub fn acquirer_fraud_rate(mut self, rate: f64) -> Self {
        self.acquirer_fraud_rate = Some(rate);
        self
    }

    /// Set the merchant name registered with the acquirer.
    #[must_use]
    pub fn merchant_name(mut self, name: impl Into<String>) -> Self {
        self.merchant_name = Some(name.into());
        self
    }
}

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

    const ACQUIRER_JSON: &str = r#"{
        "profile_acquirer_id": "pa_1",
        "profile_id": "pro_1",
        "acquirer_assigned_merchant_id": "acq_mid_1",
        "merchant_name": "Acme",
        "network": "Visa",
        "acquirer_bin": "412345",
        "acquirer_fraud_rate": 0.01
    }"#;

    fn full_create_request() -> ProfileAcquirerCreateRequest {
        ProfileAcquirerCreateRequest::new("pro_1", "Visa", "412345", "acq_mid_1", "Acme", 0.01)
            .acquirer_ica("1234")
    }

    fn full_update_request() -> ProfileAcquirerUpdateRequest {
        ProfileAcquirerUpdateRequest {
            acquirer_assigned_merchant_id: Some("acq_mid_1".to_string()),
            merchant_name: Some("Acme".to_string()),
            network: Some("Visa".to_string()),
            acquirer_bin: Some("412345".to_string()),
            acquirer_ica: Some("1234".to_string()),
            acquirer_fraud_rate: Some(0.02),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard for `PROFILE_ACQUIRER_CREATE_REQUEST_NAMED`.
    #[test]
    fn profile_acquirer_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_create_request()).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                PROFILE_ACQUIRER_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "PROFILE_ACQUIRER_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `PROFILE_ACQUIRER_UPDATE_REQUEST_NAMED`.
    #[test]
    fn profile_acquirer_update_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_update_request()).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                PROFILE_ACQUIRER_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "PROFILE_ACQUIRER_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn validate_rejects_colliding_extra_keys() {
        let mut create = full_create_request();
        create.extra.insert("network".to_string(), json!("Amex"));
        match create.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("network")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        let mut update = ProfileAcquirerUpdateRequest::new();
        update.extra.insert("acquirer_bin".to_string(), json!("1"));
        assert!(matches!(
            update.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    #[tokio::test]
    async fn create_posts_the_acquirer_identity() {
        let (client, mock) = client_with(vec![Step::ok(ACQUIRER_JSON)]);
        let created = client
            .profile_acquirers()
            .create(&full_create_request())
            .await
            .unwrap();
        assert_eq!(created.profile_acquirer_id, "pa_1");
        assert_eq!(created.acquirer_fraud_rate, Some(0.01));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/profile-acquirer");
        let body = seen[0].body_json();
        assert_eq!(body["profile_id"], "pro_1");
        assert_eq!(body["acquirer_bin"], "412345");
        assert_eq!(body["acquirer_ica"], "1234");
    }

    #[tokio::test]
    async fn update_posts_to_the_profile_and_acquirer_path() {
        let (client, mock) = client_with(vec![Step::ok(ACQUIRER_JSON)]);
        let req = ProfileAcquirerUpdateRequest::new()
            .acquirer_fraud_rate(0.02)
            .merchant_name("Acme Ltd");
        let updated = client
            .profile_acquirers()
            .update("pro/1", "pa_1", &req)
            .await
            .unwrap();
        assert_eq!(updated.network.as_deref(), Some("Visa"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/profile-acquirer/pro%2F1/pa_1"
        );
        let body = seen[0].body_json();
        assert_eq!(body["merchant_name"], "Acme Ltd");
        assert_eq!(body["acquirer_fraud_rate"], 0.02);
    }
}