delopay 0.4.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `availability_overrides` resource: merchant payment-method
//! availability overrides.
//!
//! Force-show or force-hide a payment method per country or region at global,
//! project, or shop scope, on top of the curated country defaults. Admin
//! (`sk_*`) access required.

use std::sync::Arc;

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

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::common::{PaymentMethod, PaymentMethodType};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// Create an availability override.
    pub async fn create(&self, params: &AvailabilityOverrideCreateRequest) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/availability-overrides",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// List a merchant's availability overrides.
    pub async fn list(&self, merchant_id: &str) -> Result<Vec<Value>> {
        let query = [("merchant_id", merchant_id.to_string())];
        self.inner
            .request(
                HttpMethod::Get,
                "/availability-overrides",
                None,
                &query,
                None,
            )
            .await
    }

    /// Delete an availability override by ID.
    pub async fn delete(&self, id: &str) -> Result<bool> {
        let path = format!("/availability-overrides/{}", encode_segment(id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// Preview the methods a customer in `country` would be shown for a shop —
    /// the connector ceiling narrowed by the smart country defaults and the
    /// merchant overrides, without an active payment.
    pub async fn preview(&self, params: &AvailabilityPreviewParams) -> Result<Value> {
        self.inner
            .request(
                HttpMethod::Get,
                "/availability-overrides/preview",
                None,
                &params.to_query(),
                None,
            )
            .await
    }
}

/// How widely an override applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OverrideScope {
    /// Every project and shop of the merchant.
    Global,
    /// One project (all its shops).
    Project,
    /// One shop (business profile).
    Shop,
}

/// Whether an override force-shows or force-hides the targeted method.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OverrideAction {
    /// Always offer the method, even where the defaults would hide it.
    ForceShow,
    /// Never offer the method, even where the defaults would show it.
    ForceHide,
}

/// Parameters for [`AvailabilityOverrides::create`].
///
/// Exactly one of [`country`](Self::country) / [`region_code`](Self::region_code)
/// must be set; [`scope_id`](Self::scope_id) is required for
/// [`OverrideScope::Project`] and [`OverrideScope::Shop`].
#[derive(Debug, Clone, Serialize)]
pub struct AvailabilityOverrideCreateRequest {
    /// Merchant the override belongs to.
    pub merchant_id: String,
    /// How widely the override applies.
    pub scope: OverrideScope,
    /// Project ID (for `project` scope) or profile ID (for `shop` scope);
    /// omit for `global`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope_id: Option<String>,
    /// Payment method family to target, e.g. `"wallet"`.
    pub payment_method: PaymentMethod,
    /// Omit to target every type of the payment method.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_type: Option<PaymentMethodType>,
    /// Target a single country (ISO 3166-1 alpha-2). Mutually exclusive with
    /// [`region_code`](Self::region_code).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    /// Target a built-in group code (e.g. `"EU"`) or a custom region ID.
    /// Mutually exclusive with [`country`](Self::country).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region_code: Option<String>,
    /// Whether to force-show or force-hide the targeted method.
    pub action: OverrideAction,
}

impl AvailabilityOverrideCreateRequest {
    /// An override of `action` on `payment_method`, at `scope`, for `merchant_id`.
    /// Narrow it with [`scope_id`](Self::scope_id_value),
    /// [`country`](Self::country_code) or [`region_code`](Self::region),
    /// and [`payment_method_type`](Self::payment_method_type_value).
    pub fn new(
        merchant_id: impl Into<String>,
        scope: OverrideScope,
        payment_method: impl Into<PaymentMethod>,
        action: OverrideAction,
    ) -> Self {
        Self {
            merchant_id: merchant_id.into(),
            scope,
            scope_id: None,
            payment_method: payment_method.into(),
            payment_method_type: None,
            country: None,
            region_code: None,
            action,
        }
    }

    /// Set the project or profile ID the scope refers to.
    #[must_use]
    pub fn scope_id_value(mut self, scope_id: impl Into<String>) -> Self {
        self.scope_id = Some(scope_id.into());
        self
    }

    /// Narrow the override to one payment method type.
    #[must_use]
    pub fn payment_method_type_value(
        mut self,
        payment_method_type: impl Into<PaymentMethodType>,
    ) -> Self {
        self.payment_method_type = Some(payment_method_type.into());
        self
    }

    /// Target a single country (ISO 3166-1 alpha-2).
    #[must_use]
    pub fn country_code(mut self, country: impl Into<String>) -> Self {
        self.country = Some(country.into());
        self
    }

    /// Target a region group code or custom region ID.
    #[must_use]
    pub fn region(mut self, region_code: impl Into<String>) -> Self {
        self.region_code = Some(region_code.into());
        self
    }
}

/// Query parameters for [`AvailabilityOverrides::preview`].
#[derive(Debug, Clone, Default)]
pub struct AvailabilityPreviewParams {
    /// Merchant to preview for.
    pub merchant_id: String,
    /// Shop / business profile ID to preview.
    pub profile_id: String,
    /// ISO 3166-1 alpha-2 country to preview for; omit for no country signal.
    pub country: Option<String>,
}

impl AvailabilityPreviewParams {
    /// Preview parameters for `merchant_id` / `profile_id`, with no country
    /// signal.
    pub fn new(merchant_id: impl Into<String>, profile_id: impl Into<String>) -> Self {
        Self {
            merchant_id: merchant_id.into(),
            profile_id: profile_id.into(),
            country: None,
        }
    }

    /// Preview for a specific country.
    #[must_use]
    pub fn country(mut self, country: impl Into<String>) -> Self {
        self.country = Some(country.into());
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = vec![
            ("merchant_id", self.merchant_id.clone()),
            ("profile_id", self.profile_id.clone()),
        ];
        if let Some(v) = &self.country {
            q.push(("country", v.clone()));
        }
        q
    }
}

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

    const OVERRIDE_JSON: &str = r#"{
        "id": "avo_1",
        "merchant_id": "mer_1",
        "scope": "shop",
        "payment_method": "wallet",
        "action": "force_hide"
    }"#;

    #[tokio::test]
    async fn create_posts_the_override() {
        let (client, mock) = client_with(vec![Step::ok(OVERRIDE_JSON)]);
        let req = AvailabilityOverrideCreateRequest::new(
            "mer_1",
            OverrideScope::Shop,
            "wallet",
            OverrideAction::ForceHide,
        )
        .scope_id_value("pro_1")
        .payment_method_type_value("apple_pay")
        .country_code("DE");
        client.availability_overrides().create(&req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/availability-overrides");
        let body = seen[0].body_json();
        assert_eq!(body["scope"], "shop");
        assert_eq!(body["scope_id"], "pro_1");
        assert_eq!(body["payment_method"], "wallet");
        assert_eq!(body["payment_method_type"], "apple_pay");
        assert_eq!(body["country"], "DE");
        assert_eq!(body["action"], "force_hide");
        assert!(
            body.get("region_code").is_none(),
            "an unset region_code must be omitted, not null"
        );
    }

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

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/availability-overrides?merchant_id=mer_1"
        );
    }

    #[tokio::test]
    async fn delete_encodes_the_id_and_returns_the_bare_boolean() {
        let (client, mock) = client_with(vec![Step::ok("true")]);
        let out = client
            .availability_overrides()
            .delete("avo/1")
            .await
            .unwrap();
        assert!(out);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/availability-overrides/avo%2F1"
        );
    }

    #[tokio::test]
    async fn preview_serializes_its_query_in_order() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"payment_methods":[]}"#)]);
        client
            .availability_overrides()
            .preview(&AvailabilityPreviewParams::new("mer_1", "pro_1").country("FR"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/availability-overrides/preview?merchant_id=mer_1&profile_id=pro_1&country=FR"
        );
    }

    #[tokio::test]
    async fn preview_omits_country_when_unset() {
        // Companion to the test above: an impl that always emitted a `country`
        // key (empty or defaulted) would still pass without this.
        let (client, mock) = client_with(vec![Step::ok(r#"{"payment_methods":[]}"#)]);
        client
            .availability_overrides()
            .preview(&AvailabilityPreviewParams::new("mer_1", "pro_1"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/availability-overrides/preview?merchant_id=mer_1&profile_id=pro_1"
        );
    }
}