use serde::Deserialize;
use serde_json::Value;
use crate::core::money::Money;
pub type LimitedOperation = String;
pub type OperationLimitScope = String;
pub type OperationLimitOnExceeded = String;
pub type OperationLimitWindowMode = String;
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct OperationLimitRule {
pub id: String,
pub merchant_id: String,
pub operation: LimitedOperation,
pub scope: OperationLimitScope,
#[serde(default)]
pub scope_id: Option<String>,
#[serde(default)]
pub max_amount_per_operation: Option<i64>,
#[serde(default)]
pub max_total_amount_per_window: Option<i64>,
#[serde(default)]
pub max_count_per_window: Option<i64>,
#[serde(default)]
pub max_payment_age_days: Option<i64>,
pub window_hours: i64,
pub currency: String,
pub on_exceeded: OperationLimitOnExceeded,
pub created_at: String,
pub modified_at: String,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
impl OperationLimitRule {
#[must_use]
pub fn max_per_operation(&self) -> Option<Money> {
self.max_amount_per_operation
.map(|amount| Money::new(amount, &self.currency))
}
#[must_use]
pub fn max_total_per_window(&self) -> Option<Money> {
self.max_total_amount_per_window
.map(|amount| Money::new(amount, &self.currency))
}
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct OperationLimitRuleDeleteResponse {
pub id: String,
pub deleted: bool,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct OperationLimitSettings {
pub window_mode: OperationLimitWindowMode,
pub admins_exempt: bool,
#[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();
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();
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);
}
}