delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `operation_limits` resource: the caller's own usage against the
//! per-operation spending caps.
//!
//! A rule targets the merchant, a role, or one user, and enforcement picks
//! the **most specific** match — user, then role, then merchant — rather than
//! intersecting them. A user rule therefore replaces the merchant default for
//! that user instead of being narrowed by it.
//!
//! ```no_run
//! # use delopay::Delopay;
//! # async fn run(client: Delopay) -> delopay::Result<()> {
//! let usage = client.operation_limits().retrieve_usage("refund").await?;
//! if let Some(remaining) = usage.remaining() {
//!     println!("{remaining} left in this window");
//! }
//! # Ok(())
//! # }
//! ```

use std::sync::Arc;

use crate::core::error::Result;
use crate::core::models::operation_limit::OperationLimitUsage;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// The caller's own usage against the limit on one operation: the rule
    /// that applies to them, what they have used in the current window and
    /// what remains.
    ///
    /// Refund usage needs merchant-wide refund read and is refused to a role
    /// restricted to some connectors: the totals span every shop and
    /// connector, as the budget does. Settlement usage needs merchant
    /// settlement read.
    ///
    /// `GET /operation-limits/usage?operation=`
    pub async fn retrieve_usage(&self, operation: &str) -> Result<OperationLimitUsage> {
        self.inner
            .request(
                HttpMethod::Get,
                "/operation-limits/usage",
                None,
                &[("operation", operation.to_string())],
                None,
            )
            .await
    }
}

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

    const RULE_JSON: &str = r#"{
        "id": "olr_1",
        "merchant_id": "mer_1",
        "operation": "refund",
        "scope": "role",
        "scope_id": "role_support",
        "max_amount_per_operation": 50000,
        "window_hours": 24,
        "currency": "USD",
        "on_exceeded": "block",
        "created_at": "2026-08-01T00:00:00Z",
        "modified_at": "2026-08-01T00:00:00Z"
    }"#;

    #[tokio::test]
    async fn retrieve_usage_gets_the_usage_path_for_one_operation() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{
                "operation": "refund",
                "rule": {RULE_JSON},
                "window_mode": "rolling",
                "window_start": "2026-08-01T00:00:00Z",
                "used_count": 3,
                "remaining_count": 7,
                "used_amount": 12000,
                "remaining_amount": 38000,
                "amount_unavailable": false,
                "surprise_field": "kept"
            }}"#
        ))]);
        let usage = client
            .operation_limits()
            .retrieve_usage("refund")
            .await
            .unwrap();
        assert_eq!(usage.operation, "refund");
        assert_eq!(usage.rule.as_ref().unwrap().id, "olr_1");
        assert_eq!(usage.used_count, Some(3));
        assert_eq!(usage.remaining_amount, Some(38_000));
        assert!(usage.unlimited_reason.is_none());
        assert!(!usage.amount_unavailable);
        assert_eq!(
            usage.remaining().unwrap().to_major_string().as_deref(),
            Some("380.00")
        );
        assert_eq!(usage.extra["surprise_field"], "kept");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/operation-limits/usage?operation=refund"
        );
    }

    #[tokio::test]
    async fn retrieve_usage_decodes_an_unlimited_caller() {
        let (client, _mock) = client_with(vec![Step::ok(
            r#"{"operation":"settlement_payout","unlimited_reason":"admin_exempt","amount_unavailable":false}"#,
        )]);
        let usage = client
            .operation_limits()
            .retrieve_usage("settlement_payout")
            .await
            .unwrap();
        assert_eq!(usage.unlimited_reason.as_deref(), Some("admin_exempt"));
        assert!(usage.rule.is_none());
        assert!(usage.used_amount.is_none());
        assert!(usage.used().is_none());
    }
}