delopay 0.7.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Operation-limit models: per-operation spending caps and the merchant-level
//! enforcement settings.
//!
//! Enforcement resolves the **most specific** rule and stops there: a user
//! rule beats a role rule, which beats the merchant default. Rules do not add
//! up, so a permissive user rule is not narrowed by a strict merchant one.

use serde::Deserialize;
use serde_json::Value;

use crate::core::money::Money;

/// Which operation a rule constrains. Only `"refund"` today.
pub type LimitedOperation = String;

/// Rule target: `"merchant"`, `"role"` or `"user"`.
pub type OperationLimitScope = String;

/// What happens on exceeding a limit. `"block"` today; `require_approval`
/// (four-eyes) arrives with the backend's phase 2.
pub type OperationLimitOnExceeded = String;

/// How the usage window is anchored: `"rolling"` (default) or `"calendar"`.
pub type OperationLimitWindowMode = String;

/// One persisted operation-limit rule. Amounts are minor units of
/// [`currency`](Self::currency).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct OperationLimitRule {
    /// Rule ID.
    pub id: String,
    /// The merchant the rule belongs to.
    pub merchant_id: String,
    /// The constrained operation.
    pub operation: LimitedOperation,
    /// Whether the rule targets the merchant, a role or a user.
    pub scope: OperationLimitScope,
    /// The role or user the rule targets. `None` for the merchant default.
    #[serde(default)]
    pub scope_id: Option<String>,
    /// Cap on a single operation.
    #[serde(default)]
    pub max_amount_per_operation: Option<i64>,
    /// Cap on the summed amount within the window.
    #[serde(default)]
    pub max_total_amount_per_window: Option<i64>,
    /// Cap on the number of operations within the window.
    #[serde(default)]
    pub max_count_per_window: Option<i64>,
    /// How old the underlying payment may be, in days.
    #[serde(default)]
    pub max_payment_age_days: Option<i64>,
    /// Window length in hours.
    pub window_hours: i64,
    /// ISO 4217 currency of every amount field above.
    pub currency: String,
    /// What happens when a limit is exceeded.
    pub on_exceeded: OperationLimitOnExceeded,
    /// ISO 8601 creation timestamp.
    pub created_at: String,
    /// ISO 8601 last-modification timestamp.
    pub modified_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl OperationLimitRule {
    /// [`max_amount_per_operation`](Self::max_amount_per_operation) with its
    /// currency attached. `None` means the rule does not cap single
    /// operations — not that the cap is zero.
    #[must_use]
    pub fn max_per_operation(&self) -> Option<Money> {
        self.max_amount_per_operation
            .map(|amount| Money::new(amount, &self.currency))
    }

    /// [`max_total_amount_per_window`](Self::max_total_amount_per_window)
    /// with its currency attached.
    #[must_use]
    pub fn max_total_per_window(&self) -> Option<Money> {
        self.max_total_amount_per_window
            .map(|amount| Money::new(amount, &self.currency))
    }
}

/// Outcome of deleting a limit rule.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct OperationLimitRuleDeleteResponse {
    /// The rule that was deleted.
    pub id: String,
    /// Always `true` on success — the endpoint errors otherwise.
    pub deleted: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Merchant-level enforcement settings. An untouched merchant reads as a
/// rolling window with admins not exempt.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct OperationLimitSettings {
    /// How the usage window is anchored.
    pub window_mode: OperationLimitWindowMode,
    /// Whether merchant/organization admins bypass limit rules.
    pub admins_exempt: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

#[cfg(test)]
mod tests {
    use super::*;

    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,
        "max_count_per_window": 10,
        "window_hours": 24,
        "currency": "KWD",
        "on_exceeded": "block",
        "created_at": "2026-08-01T00:00:00Z",
        "modified_at": "2026-08-01T00:00:00Z",
        "surprise_field": true
    }"#;

    #[test]
    fn rule_amounts_carry_the_rule_currency() {
        let rule: OperationLimitRule = serde_json::from_str(RULE_JSON).unwrap();
        // KWD has three minor digits: 50000 is 50.000, not 500.00.
        assert_eq!(
            rule.max_per_operation()
                .unwrap()
                .to_major_string()
                .as_deref(),
            Some("50.000")
        );
        assert_eq!(rule.extra["surprise_field"], true);
    }

    #[test]
    fn an_absent_cap_is_none_not_zero() {
        let rule: OperationLimitRule = serde_json::from_str(RULE_JSON).unwrap();
        // "no window cap" and "a window cap of zero" are opposite rules.
        assert_eq!(rule.max_total_per_window(), None);
        assert_eq!(rule.max_payment_age_days, None);
    }

    #[test]
    fn settings_decode_both_flags() {
        let settings: OperationLimitSettings =
            serde_json::from_str(r#"{"window_mode":"calendar","admins_exempt":true}"#).unwrap();
        assert_eq!(settings.window_mode, "calendar");
        assert!(settings.admins_exempt);
    }
}