delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `deployment_branding` resource: the deployment's branding (name,
//! logos, favicon, default checkout colours) as the platform operator saved
//! it. Public: the API needs no credential for it.
//!
//! Not to be confused with a shop's own checkout look, which
//! [`crate::branding`] encodes.

use std::sync::Arc;

use crate::core::encoding::encode_segment;
use crate::core::error::Result;
use crate::core::models::deployment_branding::PublicBranding;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// The saved branding. A `None` field means "keep your own default".
    ///
    /// Branding is cosmetic, so treat any failure as "nothing saved": an API
    /// from before this route answers 404.
    ///
    /// `GET /branding`
    pub async fn retrieve(&self) -> Result<PublicBranding> {
        self.inner
            .request(HttpMethod::Get, "/branding", None, &[], None)
            .await
    }

    /// The address of one branding image or font file on this client's base
    /// URL, for an `<img src>` or a `@font-face` `src`. Makes no request.
    ///
    /// The API serves the file in force from this address: the one the
    /// operator saved, else its own default (only [`BrandingAsset::Logo`] and
    /// [`BrandingAsset::EmailFont`] have one). It answers 404 only when
    /// neither applies, so a `None` field from [`retrieve`](Self::retrieve)
    /// does not mean this address 404s.
    ///
    /// Pass [`PublicBranding::version`] as `version` to bust caches; it is
    /// sent as `?v=`.
    ///
    /// `GET /branding/assets/{asset}`
    pub fn asset_url(&self, asset: BrandingAsset, version: Option<&str>) -> String {
        format!(
            "{}{}",
            self.inner.api_base_url(),
            branding_asset_path(asset, version)
        )
    }
}

/// The path of one branding file relative to the API base URL:
/// `/branding/assets/{asset}`, with `?v={version}` when a non-empty version is
/// given.
pub fn branding_asset_path(asset: BrandingAsset, version: Option<&str>) -> String {
    let path = format!("/branding/assets/{}", asset.as_str());
    match version {
        Some(v) if !v.is_empty() => format!("{path}?v={}", encode_segment(v)),
        _ => path,
    }
}

/// One image or font file of the deployment's branding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BrandingAsset {
    /// The logo.
    Logo,
    /// The logo for dark mode.
    LogoDark,
    /// The square mark, for small spaces.
    Symbol,
    /// The favicon.
    Favicon,
    /// The email font file.
    EmailFont,
}

impl BrandingAsset {
    /// The asset's name on the wire, e.g. `logo_dark`.
    pub fn as_str(self) -> &'static str {
        match self {
            BrandingAsset::Logo => "logo",
            BrandingAsset::LogoDark => "logo_dark",
            BrandingAsset::Symbol => "symbol",
            BrandingAsset::Favicon => "favicon",
            BrandingAsset::EmailFont => "email_font",
        }
    }
}

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

    #[tokio::test]
    async fn retrieve_gets_the_public_branding() {
        let (client, mock) = client_with(vec![Step::ok(
            r##"{"name":"Acme Pay","logo_url":"https://cdn.example/logo.svg",
                "logo_dark_url":null,"symbol_url":null,"favicon_url":null,
                "checkout_theme":"#112233","checkout_background":null,
                "version":"42","surprise_field":1}"##,
        )]);
        let branding = client.deployment_branding().retrieve().await.unwrap();
        assert_eq!(branding.name.as_deref(), Some("Acme Pay"));
        assert_eq!(branding.logo_dark_url, None);
        assert_eq!(branding.checkout_theme.as_deref(), Some("#112233"));
        assert_eq!(branding.version, "42");
        assert_eq!(branding.extra["surprise_field"], 1);

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

    /// Mutations: dropping the `?v=`, sending it for an empty version, or
    /// spelling `logo_dark` as `logodark` — each fails one assertion.
    #[test]
    fn asset_url_names_the_asset_and_the_version() {
        let (client, mock) = client_with(vec![]);
        let branding = client.deployment_branding();
        assert_eq!(
            branding.asset_url(BrandingAsset::LogoDark, Some("4 2")),
            "https://api.test/branding/assets/logo_dark?v=4%202"
        );
        assert_eq!(
            branding.asset_url(BrandingAsset::EmailFont, Some("")),
            "https://api.test/branding/assets/email_font"
        );
        assert_eq!(
            branding_asset_path(BrandingAsset::Favicon, None),
            "/branding/assets/favicon"
        );
        // An address, not a request.
        assert_eq!(mock.call_count(), 0);
    }
}