delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Operation-limit models: per-operation spending caps and the caller's usage
//! against them.
//!
//! 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))
    }
}

/// Why no limit applies to the caller for an operation: `"no_rule"` or
/// `"admin_exempt"`.
pub type OperationLimitUnlimitedReason = String;

/// The caller's own standing against the limit on one operation: the rule
/// that applies to them and how much of its current window they have used.
/// Computed with the same rule selection, window and usage records as
/// enforcement, so the figure shown is the figure that blocks.
///
/// A count or amount field is present only when the rule limits that
/// dimension: `None` means "not limited", never zero.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct OperationLimitUsage {
    /// The operation the usage is for.
    pub operation: LimitedOperation,
    /// Set when no limit applies; `rule` and every usage field are then
    /// `None`.
    #[serde(default)]
    pub unlimited_reason: Option<OperationLimitUnlimitedReason>,
    /// The rule that applies to the caller.
    #[serde(default)]
    pub rule: Option<OperationLimitRule>,
    /// How the window is anchored; present with a window dimension.
    #[serde(default)]
    pub window_mode: Option<OperationLimitWindowMode>,
    /// ISO 8601 start of the current window; present with a window
    /// dimension.
    #[serde(default)]
    pub window_start: Option<String>,
    /// Operations counted in the current window; present with
    /// `max_count_per_window`.
    #[serde(default)]
    pub used_count: Option<i64>,
    /// Operations still allowed in the current window, never below zero.
    #[serde(default)]
    pub remaining_count: Option<i64>,
    /// Amount used in the current window, in minor units of the rule's
    /// currency; present with `max_total_amount_per_window` unless
    /// [`amount_unavailable`](Self::amount_unavailable).
    #[serde(default)]
    pub used_amount: Option<i64>,
    /// Amount still allowed in the current window, never below zero.
    #[serde(default)]
    pub remaining_amount: Option<i64>,
    /// `true` when an operation in the window is in a currency with no usable
    /// exchange rate to the rule's currency. The amount is then unknown, and
    /// enforcement refuses the next operation rather than guess.
    pub amount_unavailable: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl OperationLimitUsage {
    /// [`used_amount`](Self::used_amount) with the rule's currency attached.
    /// `None` without an amount or a rule.
    #[must_use]
    pub fn used(&self) -> Option<Money> {
        let rule = self.rule.as_ref()?;
        self.used_amount
            .map(|amount| Money::new(amount, &rule.currency))
    }

    /// [`remaining_amount`](Self::remaining_amount) with the rule's currency
    /// attached. `None` without an amount or a rule.
    #[must_use]
    pub fn remaining(&self) -> Option<Money> {
        let rule = self.rule.as_ref()?;
        self.remaining_amount
            .map(|amount| Money::new(amount, &rule.currency))
    }
}

#[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);
    }
}