1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//! 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);
}
}