delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `live` resource: the versions a dashboard editor names in `If-Match`
//! so a save never overwrites a newer change.
//!
//! Needs a dashboard JWT, not an API key. The live change stream
//! (`GET /live/stream`, server-sent events) is not wrapped by this crate.

use std::sync::Arc;

use crate::core::error::{DelopayError, Result};
use crate::core::models::live::LiveVersionsResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// The current version of each kind of record named, in the caller's
    /// merchant and shop.
    ///
    /// Read it before the record, and send the entry's `if_match` in the
    /// `If-Match` header of the save: a save over a newer version is refused
    /// with `IR_16` (400), naming who made the change. At least one entity is
    /// required; an empty list is refused before the request is sent.
    ///
    /// `GET /live/versions`
    pub async fn versions(&self, params: &LiveVersionsParams) -> Result<LiveVersionsResponse> {
        if params.entities.is_empty() {
            return Err(DelopayError::InvalidRequest(
                "live versions need at least one entity".to_string(),
            ));
        }
        let mut query = vec![("entities", params.entities.join(","))];
        if let Some(profile_id) = &params.profile_id {
            query.push(("profile_id", profile_id.clone()));
        }
        if let Some(record_id) = &params.record_id {
            query.push(("record_id", record_id.clone()));
        }
        self.inner
            .request(HttpMethod::Get, "/live/versions", None, &query, None)
            .await
    }
}

/// Which versions [`Live::versions`] reads.
#[derive(Debug, Clone, Default)]
pub struct LiveVersionsParams {
    /// The kinds of record, at least one, e.g. `payment` or
    /// `subscription_settings`. Sent comma-separated.
    pub entities: Vec<String>,
    /// The shop, for a kind kept per shop. A shop-level role always reads its
    /// own.
    pub profile_id: Option<String>,
    /// The one record the editor shows, when it shows one: the id its save
    /// names in the path.
    pub record_id: Option<String>,
}

impl LiveVersionsParams {
    /// Read the versions of these kinds of record.
    pub fn new<I, S>(entities: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            entities: entities.into_iter().map(Into::into).collect(),
            ..Default::default()
        }
    }

    /// Read them for one shop.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Read them for one record.
    #[must_use]
    pub fn record_id(mut self, record_id: impl Into<String>) -> Self {
        self.record_id = Some(record_id.into());
        self
    }
}

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

    #[tokio::test]
    async fn versions_joins_the_entities_and_scopes_the_query() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"versions":[{"entity":"connector","profile_id":"pro_1",
                "record_id":"mca_1","version":3,
                "by":{"kind":"user","user_id":"usr_1","name":"Ada"},
                "if_match":"\"3\"","entry_surprise":1}],"surprise_field":true}"#,
        )]);
        let params = LiveVersionsParams::new(["connector", "routing"])
            .profile_id("pro_1")
            .record_id("mca_1");
        let out = client.live().versions(&params).await.unwrap();
        assert_eq!(out.versions[0].entity, "connector");
        assert_eq!(out.versions[0].version, 3);
        assert_eq!(out.versions[0].if_match, "\"3\"");
        assert_eq!(
            out.versions[0].by.as_ref().map(|b| b.kind.as_str()),
            Some("user")
        );
        assert_eq!(out.versions[0].extra["entry_surprise"], 1);
        assert_eq!(out.extra["surprise_field"], true);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/live/versions?entities=connector,routing\
             &profile_id=pro_1&record_id=mca_1"
        );
    }

    #[tokio::test]
    async fn versions_refuses_an_empty_entity_list_before_sending() {
        let (client, mock) = client_with(vec![]);
        let params = LiveVersionsParams::new(Vec::<String>::new());
        match client.live().versions(&params).await.unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("entity")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
        assert_eq!(mock.call_count(), 0);
    }
}