delopay 0.4.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `search` resource: one global, cross-index search. The result groups
//! are an open shape — see the API reference.

use std::sync::Arc;

use serde::Serialize;
use serde_json::Value;

use crate::core::encoding::to_json_vec;
use crate::core::error::{DelopayError, Result};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Search every supported index (payment attempts and intents, refunds,
    /// disputes, payouts, routing rules, webhook events, audit logs,
    /// subscriptions) for the request's query.
    ///
    /// Returns one result group per index, each with its own `count`, `index`,
    /// `hits` and `status`.
    pub async fn global(&self, params: &GlobalSearchRequest) -> Result<Value> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/analytics/search",
                Some(&body),
                &[],
                None,
            )
            .await
    }
}

/// The window a [`GlobalSearchRequest`] is restricted to. Both bounds are
/// ISO 8601 datetimes.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SearchTimeRange {
    /// Inclusive start of the window.
    #[serde(rename = "startTime")]
    pub start_time: String,
    /// Inclusive end of the window.
    #[serde(rename = "endTime")]
    pub end_time: String,
}

/// Parameters for [`Search::global`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct GlobalSearchRequest {
    /// The search term, e.g. a payment ID or an email address.
    pub query: String,
    /// Per-index filters (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<Value>,
    /// Restrict results to this window.
    #[serde(rename = "timeRange", skip_serializing_if = "Option::is_none")]
    pub time_range: Option<SearchTimeRange>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `GlobalSearchRequest`'s fields, as they appear on the wire
/// (`extra` excluded). Note `timeRange` is camelCase on the wire.
const GLOBAL_SEARCH_REQUEST_NAMED: &[&str] = &["query", "filters", "timeRange"];

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

impl GlobalSearchRequest {
    /// A request for `query`, with no filters and no time range.
    pub fn new(query: impl Into<String>) -> Self {
        Self {
            query: query.into(),
            ..Default::default()
        }
    }

    /// Set the per-index filters.
    pub fn filters(mut self, filters: Value) -> Self {
        self.filters = Some(filters);
        self
    }

    /// Restrict results to the window between `start_time` and `end_time`.
    pub fn time_range(
        mut self,
        start_time: impl Into<String>,
        end_time: impl Into<String>,
    ) -> Self {
        self.time_range = Some(SearchTimeRange {
            start_time: start_time.into(),
            end_time: end_time.into(),
        });
        self
    }
}

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

    /// Every optional field populated so serialization emits the full key set.
    fn full_global_search_request() -> GlobalSearchRequest {
        GlobalSearchRequest::new("pay_abc")
            .filters(json!({"currency": "USD"}))
            .time_range("2026-01-01T00:00:00Z", "2026-01-31T00:00:00Z")
    }

    /// Drift guard: catches a new field added to `GlobalSearchRequest` without
    /// a matching update to `GLOBAL_SEARCH_REQUEST_NAMED`.
    #[test]
    fn global_search_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_global_search_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                GLOBAL_SEARCH_REQUEST_NAMED.contains(&key.as_str()),
                "GLOBAL_SEARCH_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or GlobalSearchRequest's extra-key collision guard \
                 will silently stop covering this field"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_key_colliding_with_named_field() {
        let mut req = GlobalSearchRequest::new("pay_abc");
        req.extra.insert("timeRange".to_string(), json!("collide"));

        let err = req.validate().unwrap_err();
        match err {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("timeRange")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn global_posts_the_request_to_analytics_search() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"[{"count":1,"index":"payment_intents","hits":[{"payment_id":"pay_1"}],"status":"Success"}]"#,
        )]);
        let out = client
            .search()
            .global(&full_global_search_request())
            .await
            .unwrap();
        assert_eq!(out[0]["index"], "payment_intents");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/analytics/search");
        let body = seen[0].body_json();
        assert_eq!(body["query"], "pay_abc");
        assert_eq!(body["filters"]["currency"], "USD");
        assert_eq!(body["timeRange"]["startTime"], "2026-01-01T00:00:00Z");
        assert_eq!(body["timeRange"]["endTime"], "2026-01-31T00:00:00Z");
    }

    #[tokio::test]
    async fn global_omits_absent_optional_fields() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        client
            .search()
            .global(&GlobalSearchRequest::new("cus_1"))
            .await
            .unwrap();

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