use std::sync::Arc;
use serde::Serialize;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::operation_limit::{
OperationLimitRule, OperationLimitRuleDeleteResponse, OperationLimitSettings,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
#[derive(Debug, Clone)]
pub struct OperationLimits {
inner: Arc<Inner>,
}
impl OperationLimits {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn list_rules(&self, operation: Option<&str>) -> Result<Vec<OperationLimitRule>> {
let query = match operation {
Some(operation) => vec![("operation", operation.to_string())],
None => Vec::new(),
};
self.inner
.request(
HttpMethod::Get,
"/operation-limits/rules",
None,
&query,
None,
)
.await
}
pub async fn upsert_rule(
&self,
params: &UpsertOperationLimitRuleRequest,
) -> Result<OperationLimitRule> {
params.validate_scope()?;
params.validate_dimensions()?;
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Put,
"/operation-limits/rules",
Some(&body),
&[],
None,
)
.await
}
pub async fn delete_rule(&self, rule_id: &str) -> Result<OperationLimitRuleDeleteResponse> {
let path = format!("/operation-limits/rules/{}", encode_segment(rule_id));
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn retrieve_settings(&self) -> Result<OperationLimitSettings> {
self.inner
.request(
HttpMethod::Get,
"/operation-limits/settings",
None,
&[],
None,
)
.await
}
pub async fn update_settings(
&self,
params: &UpdateOperationLimitSettingsRequest,
) -> Result<OperationLimitSettings> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Put,
"/operation-limits/settings",
Some(&body),
&[],
None,
)
.await
}
}
#[derive(Debug, Clone, Serialize)]
pub struct UpsertOperationLimitRuleRequest {
pub operation: String,
pub scope: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub scope_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_amount_per_operation: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_total_amount_per_window: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_count_per_window: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_payment_age_days: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub window_hours: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub currency: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub on_exceeded: Option<String>,
}
impl UpsertOperationLimitRuleRequest {
#[must_use]
pub fn for_merchant(operation: impl Into<String>) -> Self {
Self::new(operation, "merchant", None)
}
#[must_use]
pub fn for_role(operation: impl Into<String>, role_id: impl Into<String>) -> Self {
Self::new(operation, "role", Some(role_id.into()))
}
#[must_use]
pub fn for_user(operation: impl Into<String>, user_id: impl Into<String>) -> Self {
Self::new(operation, "user", Some(user_id.into()))
}
fn new(operation: impl Into<String>, scope: &str, scope_id: Option<String>) -> Self {
Self {
operation: operation.into(),
scope: scope.to_string(),
scope_id,
max_amount_per_operation: None,
max_total_amount_per_window: None,
max_count_per_window: None,
max_payment_age_days: None,
window_hours: None,
currency: None,
on_exceeded: None,
}
}
#[must_use]
pub fn max_amount_per_operation(mut self, amount: i64) -> Self {
self.max_amount_per_operation = Some(amount);
self
}
#[must_use]
pub fn max_total_amount_per_window(mut self, amount: i64) -> Self {
self.max_total_amount_per_window = Some(amount);
self
}
#[must_use]
pub fn max_count_per_window(mut self, count: i64) -> Self {
self.max_count_per_window = Some(count);
self
}
#[must_use]
pub fn max_payment_age_days(mut self, days: i64) -> Self {
self.max_payment_age_days = Some(days);
self
}
#[must_use]
pub fn window_hours(mut self, hours: i64) -> Self {
self.window_hours = Some(hours);
self
}
#[must_use]
pub fn currency(mut self, currency: impl Into<String>) -> Self {
self.currency = Some(currency.into());
self
}
#[must_use]
pub fn on_exceeded(mut self, on_exceeded: impl Into<String>) -> Self {
self.on_exceeded = Some(on_exceeded.into());
self
}
fn validate_scope(&self) -> Result<()> {
match (self.scope.as_str(), self.scope_id.as_deref()) {
("merchant", Some(_)) => Err(DelopayError::InvalidRequest(
"a `merchant`-scoped operation limit must not carry a `scope_id`".to_string(),
)),
("role" | "user", None) => Err(DelopayError::InvalidRequest(format!(
"a `{}`-scoped operation limit needs a `scope_id`",
self.scope
))),
_ => Ok(()),
}
}
fn validate_dimensions(&self) -> Result<()> {
let refuse = |field: &str, why: &str| {
Err(DelopayError::InvalidRequest(format!(
"{field} cannot be enforced for the {} operation: {why}",
self.operation
)))
};
match self.operation.as_str() {
"settlement_adjustment" | "settlement_payout" => {
if self.max_payment_age_days.is_some() {
return refuse(
"max_payment_age_days",
"it constrains the age of the payment being refunded, and there is no payment behind this operation",
);
}
if self.max_count_per_window.is_some() {
return refuse(
"max_count_per_window",
"counting actions needs an immutable per-action record, and this operation's rows are deleted or overwritten",
);
}
if self.on_exceeded.as_deref() == Some("require_approval") {
return Err(DelopayError::InvalidRequest(format!(
"approval is not available for the {} operation; only refunds can be sent for review",
self.operation
)));
}
}
_ => {}
}
if self.operation == "settlement_payout" && self.max_total_amount_per_window.is_some() {
return refuse(
"max_total_amount_per_window",
"its window would rest on a caller-supplied date and on a row that later writes overwrite",
);
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateOperationLimitSettingsRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub window_mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub admins_exempt: Option<bool>,
}
impl UpdateOperationLimitSettingsRequest {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn window_mode(mut self, window_mode: impl Into<String>) -> Self {
self.window_mode = Some(window_mode.into());
self
}
#[must_use]
pub fn admins_exempt(mut self, admins_exempt: bool) -> Self {
self.admins_exempt = Some(admins_exempt);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
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 list_rules_omits_the_operation_filter_when_absent() {
let (client, mock) = client_with(vec![
Step::ok(&format!("[{RULE_JSON}]")),
Step::ok(&format!("[{RULE_JSON}]")),
]);
client.operation_limits().list_rules(None).await.unwrap();
client
.operation_limits()
.list_rules(Some("refund"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/operation-limits/rules");
assert_eq!(
seen[1].url,
"https://api.test/operation-limits/rules?operation=refund"
);
}
#[tokio::test]
async fn upsert_rule_puts_only_the_set_limits() {
let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
let params = UpsertOperationLimitRuleRequest::for_role("refund", "role_support")
.max_amount_per_operation(50_000)
.window_hours(24)
.currency("USD");
let rule = client
.operation_limits()
.upsert_rule(¶ms)
.await
.unwrap();
assert_eq!(rule.scope_id.as_deref(), Some("role_support"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/operation-limits/rules");
let body = seen[0].body_json();
assert_eq!(body["scope"], "role");
assert_eq!(body["scope_id"], "role_support");
assert_eq!(body["max_amount_per_operation"], 50000);
assert!(body.get("max_count_per_window").is_none());
}
#[tokio::test]
async fn delete_rule_encodes_the_id() {
let (client, mock) = client_with(vec![Step::ok(r#"{"id":"olr_1","deleted":true}"#)]);
let out = client
.operation_limits()
.delete_rule("olr/1")
.await
.unwrap();
assert!(out.deleted);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/operation-limits/rules/olr%2F1"
);
}
#[tokio::test]
async fn settings_round_trip() {
let (client, mock) = client_with(vec![
Step::ok(r#"{"window_mode":"rolling","admins_exempt":false}"#),
Step::ok(r#"{"window_mode":"calendar","admins_exempt":false}"#),
]);
client.operation_limits().retrieve_settings().await.unwrap();
let updated = client
.operation_limits()
.update_settings(&UpdateOperationLimitSettingsRequest::new().window_mode("calendar"))
.await
.unwrap();
assert_eq!(updated.window_mode, "calendar");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/operation-limits/settings");
assert_eq!(seen[1].method, "PUT");
let body = seen[1].body_json();
assert_eq!(body["window_mode"], "calendar");
assert!(body.get("admins_exempt").is_none());
}
#[tokio::test]
async fn upsert_rejects_a_role_rule_with_no_target() {
let (client, mock) = client_with(vec![]);
let mut params = UpsertOperationLimitRuleRequest::for_role("refund", "role_support");
params.scope_id = None;
match client
.operation_limits()
.upsert_rule(¶ms)
.await
.unwrap_err()
{
DelopayError::InvalidRequest(msg) => assert!(msg.contains("scope_id"), "{msg}"),
other => panic!("expected InvalidRequest, got {other:?}"),
}
assert_eq!(mock.call_count(), 0);
}
#[tokio::test]
async fn upsert_rejects_a_merchant_rule_with_a_stray_target() {
let (client, mock) = client_with(vec![]);
let mut params = UpsertOperationLimitRuleRequest::for_merchant("refund");
params.scope_id = Some("role_support".to_string());
match client
.operation_limits()
.upsert_rule(¶ms)
.await
.unwrap_err()
{
DelopayError::InvalidRequest(msg) => assert!(msg.contains("scope_id"), "{msg}"),
other => panic!("expected InvalidRequest, got {other:?}"),
}
assert_eq!(mock.call_count(), 0);
}
#[test]
fn a_merchant_rule_sends_no_scope_id() {
let params = UpsertOperationLimitRuleRequest::for_merchant("refund");
let value = serde_json::to_value(¶ms).unwrap();
assert_eq!(value["scope"], "merchant");
assert!(value.get("scope_id").is_none());
}
#[tokio::test]
async fn upsert_sends_on_exceeded_for_a_refund_rule() {
let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
let req = UpsertOperationLimitRuleRequest::for_role("refund", "role_1")
.max_amount_per_operation(50_000)
.on_exceeded("require_approval");
client.operation_limits().upsert_rule(&req).await.unwrap();
let seen = mock.seen.lock().unwrap();
let body = seen[0].body_json();
assert_eq!(body["on_exceeded"], "require_approval");
}
#[tokio::test]
async fn upsert_omits_on_exceeded_when_unset() {
let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
let req = UpsertOperationLimitRuleRequest::for_merchant("refund").max_count_per_window(3);
client.operation_limits().upsert_rule(&req).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert!(seen[0].body_json().get("on_exceeded").is_none());
}
#[tokio::test]
async fn upsert_refuses_approval_on_a_settlement_rule() {
let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
let req = UpsertOperationLimitRuleRequest::for_user("settlement_adjustment", "user_1")
.max_amount_per_operation(10_000)
.on_exceeded("require_approval");
let err = client
.operation_limits()
.upsert_rule(&req)
.await
.unwrap_err();
assert!(matches!(err, DelopayError::InvalidRequest(_)));
assert!(err.to_string().contains("only refunds"));
assert!(mock.seen.lock().unwrap().is_empty());
}
#[tokio::test]
async fn upsert_refuses_a_dimension_the_operation_cannot_enforce() {
for (operation, rule) in [
(
"settlement_adjustment",
UpsertOperationLimitRuleRequest::for_merchant("settlement_adjustment")
.max_count_per_window(5),
),
(
"settlement_payout",
UpsertOperationLimitRuleRequest::for_merchant("settlement_payout")
.max_total_amount_per_window(5_000),
),
(
"settlement_payout",
UpsertOperationLimitRuleRequest::for_merchant("settlement_payout")
.max_payment_age_days(30),
),
] {
let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
let err = client
.operation_limits()
.upsert_rule(&rule)
.await
.unwrap_err();
assert!(err.to_string().contains(operation), "{operation}: {err}");
assert!(mock.seen.lock().unwrap().is_empty(), "{operation}");
}
}
#[tokio::test]
async fn upsert_lets_an_operation_this_sdk_does_not_know_through() {
let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
let req = UpsertOperationLimitRuleRequest::for_merchant("payout")
.max_count_per_window(2)
.on_exceeded("require_approval");
client.operation_limits().upsert_rule(&req).await.unwrap();
assert_eq!(mock.seen.lock().unwrap().len(), 1);
}
}