delopay 0.3.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `events` resource — webhook delivery events and their retry history.

use std::sync::Arc;

use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::common::ListResponse;
use crate::core::models::event::{EventDeliveryAttemptResponse, EventResponse};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// List events for a merchant. Pass optional filter/pagination params as a
    /// JSON object.
    pub async fn list(
        &self,
        merchant_id: &str,
        params: Option<&Value>,
    ) -> Result<ListResponse<EventResponse>> {
        let path = format!("/events/{}", encode_segment(merchant_id));
        let body = params
            .cloned()
            .unwrap_or_else(|| Value::Object(Default::default()));
        let bytes = to_json_vec(&body)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&bytes), &[], None)
            .await
    }

    /// List the delivery attempts made for a webhook event, newest first.
    pub async fn list_delivery_attempts(
        &self,
        merchant_id: &str,
        event_id: &str,
    ) -> Result<Vec<EventDeliveryAttemptResponse>> {
        let path = format!(
            "/events/{}/{}/attempts",
            encode_segment(merchant_id),
            encode_segment(event_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// List events scoped to the shop (business profile) the credential
    /// belongs to. Pass optional filter/pagination params as a JSON object.
    pub async fn list_by_profile(
        &self,
        params: Option<&Value>,
    ) -> Result<ListResponse<EventResponse>> {
        let body = params
            .cloned()
            .unwrap_or_else(|| Value::Object(Default::default()));
        let bytes = to_json_vec(&body)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/events/profile/list",
                Some(&bytes),
                &[],
                None,
            )
            .await
    }

    /// Retry delivery of a webhook event.
    pub async fn retry_delivery(&self, merchant_id: &str, event_id: &str) -> Result<Value> {
        let path = format!(
            "/events/{}/{}/retry",
            encode_segment(merchant_id),
            encode_segment(event_id)
        );
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }
}

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

    #[tokio::test]
    async fn list_by_profile_posts_the_filter_body_to_the_profile_path() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"data":[]}"#)]);
        let params = json!({"limit": 10, "event_class": "payments"});
        client
            .events()
            .list_by_profile(Some(&params))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/events/profile/list");
        assert_eq!(seen[0].body_json()["event_class"], "payments");
    }

    #[tokio::test]
    async fn list_by_profile_sends_an_empty_object_when_given_no_params() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"data":[]}"#)]);
        client.events().list_by_profile(None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].body_json(), json!({}));
    }

    #[tokio::test]
    async fn list_delivery_attempts_gets_the_attempts_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"[{"attempt_id":"eda_1","status":"failed","response_status_code":500}]"#,
        )]);
        let out = client
            .events()
            .list_delivery_attempts("mer_1", "evt_1")
            .await
            .unwrap();
        assert_eq!(out[0].attempt_id.as_deref(), Some("eda_1"));
        assert_eq!(out[0].response_status_code, Some(500));

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