delopay 0.7.0

Official Rust SDK for the DeloPay payments API
Documentation
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! The `operation_limits` resource: per-operation spending caps and the
//! merchant-level enforcement settings.
//!
//! A rule targets the merchant, a role, or one user, and enforcement picks
//! the **most specific** match — user, then role, then merchant — rather than
//! intersecting them. A user rule therefore replaces the merchant default for
//! that user instead of being narrowed by it.
//!
//! Three operations carry rules — `"refund"`, `"settlement_adjustment"` and
//! `"settlement_payout"` — and they do not accept the same dimensions. An
//! adjustment takes amount limits only, and recording a payout takes a
//! per-operation ceiling alone; `require_approval` is refunds-only. The
//! builder refuses the combinations the server refuses, because a rule that
//! saves and renders while nothing enforces it reads as a control that is
//! switched on when it is not.
//!
//! ```no_run
//! # use delopay::{Delopay, UpsertOperationLimitRuleRequest};
//! # async fn run(client: Delopay) -> delopay::Result<()> {
//! let rule = UpsertOperationLimitRuleRequest::for_role("refund", "role_support")
//!     .max_amount_per_operation(50_000) // 500.00 in the rule's currency
//!     .max_count_per_window(10)
//!     .window_hours(24);
//! client.operation_limits().upsert_rule(&rule).await?;
//! # Ok(())
//! # }
//! ```

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;

/// The `operation_limits` resource, obtained via
/// [`crate::Delopay::operation_limits`].
#[derive(Debug, Clone)]
pub struct OperationLimits {
    inner: Arc<Inner>,
}

impl OperationLimits {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// List the merchant's limit rules, optionally for one operation.
    ///
    /// `GET /operation-limits/rules`
    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
    }

    /// Create or replace the limit rule for one target.
    ///
    /// A **full-replace** upsert: a limit you do not set is cleared, not
    /// left alone. Read the rule first if you mean to change one dimension.
    ///
    /// `PUT /operation-limits/rules`
    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
    }

    /// Delete a limit rule.
    ///
    /// `DELETE /operation-limits/rules/{rule_id}`
    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
    }

    /// The merchant-level enforcement settings. An untouched merchant reads
    /// as a rolling window with admins not exempt.
    ///
    /// `GET /operation-limits/settings`
    pub async fn retrieve_settings(&self) -> Result<OperationLimitSettings> {
        self.inner
            .request(
                HttpMethod::Get,
                "/operation-limits/settings",
                None,
                &[],
                None,
            )
            .await
    }

    /// Update the enforcement settings. Only the fields you set change.
    ///
    /// `PUT /operation-limits/settings`
    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
    }
}

/// Body for [`OperationLimits::upsert_rule`] — a full-replace upsert for one
/// target.
///
/// Absent limit fields mean "this rule does not constrain that dimension".
/// A request that sets no limit at all is rejected by the server: delete the
/// rule instead of emptying it.
#[derive(Debug, Clone, Serialize)]
pub struct UpsertOperationLimitRuleRequest {
    /// The operation to constrain, e.g. `"refund"`.
    pub operation: String,
    /// `"merchant"`, `"role"` or `"user"`.
    pub scope: String,
    /// The role or user id. Required for `role`/`user`, absent for
    /// `merchant`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope_id: Option<String>,
    /// Cap on a single operation, minor units of
    /// [`currency`](Self::currency).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_amount_per_operation: Option<i64>,
    /// Cap on the summed amount within the window.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_total_amount_per_window: Option<i64>,
    /// Cap on the number of operations within the window.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_count_per_window: Option<i64>,
    /// How old the underlying payment may be, in days.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_payment_age_days: Option<i64>,
    /// Window length in hours (rolling mode). Server default 24; 1–720.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window_hours: Option<i64>,
    /// Currency of the amount fields. Server default USD.
    ///
    /// Set it whenever you set an amount: the amounts are minor units, and
    /// what a minor unit is depends on this — see [`crate::money`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    /// What an over-limit operation does: `"block"` or `"require_approval"`.
    ///
    /// Server default `"block"`, so a rule written without this keeps
    /// refusing rather than silently becoming approvable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub on_exceeded: Option<String>,
}

impl UpsertOperationLimitRuleRequest {
    /// A rule that applies to everyone at the merchant, unless a role or user
    /// rule is more specific.
    #[must_use]
    pub fn for_merchant(operation: impl Into<String>) -> Self {
        Self::new(operation, "merchant", None)
    }

    /// A rule for one role.
    #[must_use]
    pub fn for_role(operation: impl Into<String>, role_id: impl Into<String>) -> Self {
        Self::new(operation, "role", Some(role_id.into()))
    }

    /// A rule for one user.
    #[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,
        }
    }

    /// Cap a single operation, minor units of the rule's currency.
    #[must_use]
    pub fn max_amount_per_operation(mut self, amount: i64) -> Self {
        self.max_amount_per_operation = Some(amount);
        self
    }

    /// Cap the summed amount within the window.
    #[must_use]
    pub fn max_total_amount_per_window(mut self, amount: i64) -> Self {
        self.max_total_amount_per_window = Some(amount);
        self
    }

    /// Cap the number of operations within the window.
    #[must_use]
    pub fn max_count_per_window(mut self, count: i64) -> Self {
        self.max_count_per_window = Some(count);
        self
    }

    /// Cap how old the underlying payment may be, in days.
    #[must_use]
    pub fn max_payment_age_days(mut self, days: i64) -> Self {
        self.max_payment_age_days = Some(days);
        self
    }

    /// Set the window length in hours.
    #[must_use]
    pub fn window_hours(mut self, hours: i64) -> Self {
        self.window_hours = Some(hours);
        self
    }

    /// Set the currency the amount fields are denominated in.
    #[must_use]
    pub fn currency(mut self, currency: impl Into<String>) -> Self {
        self.currency = Some(currency.into());
        self
    }

    /// What an over-limit operation does: `"block"` (the server default) or
    /// `"require_approval"`.
    ///
    /// `"require_approval"` parks the operation as a request a second person
    /// decides on instead of refusing it. It is accepted for refunds only —
    /// approval needs an executor that can run the operation once somebody
    /// says yes, and no settlement one exists.
    #[must_use]
    pub fn on_exceeded(mut self, on_exceeded: impl Into<String>) -> Self {
        self.on_exceeded = Some(on_exceeded.into());
        self
    }

    /// Reject a scope/`scope_id` pairing the server would reject anyway.
    ///
    /// Caught here because the failure is silent in the wrong direction: a
    /// `role` rule sent without its role id is not "a rule for every role",
    /// and a `merchant` rule carrying a stray id is not the merchant default.
    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(()),
        }
    }

    /// Reject a rule the server would reject for naming something its
    /// operation cannot honour.
    ///
    /// Caught here for the same reason the server refuses it rather than
    /// storing it: a rule that saves, lists and renders while no hook can read
    /// it reads as configured control that does not exist.
    ///
    /// Only the operations known to refuse something are checked. `operation`
    /// is an open vocabulary, so one this SDK has never heard of passes
    /// through to the server rather than being blocked by a stale client.
    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(())
    }
}

/// Body for [`OperationLimits::update_settings`]. Only the fields you set
/// change.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateOperationLimitSettingsRequest {
    /// `"rolling"` or `"calendar"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window_mode: Option<String>,
    /// Whether merchant/organization admins bypass limit rules.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub admins_exempt: Option<bool>,
}

impl UpdateOperationLimitSettingsRequest {
    /// An empty update; set the fields you want changed.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Anchor the usage window.
    #[must_use]
    pub fn window_mode(mut self, window_mode: impl Into<String>) -> Self {
        self.window_mode = Some(window_mode.into());
        self
    }

    /// Exempt (or stop exempting) admins.
    #[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(&params)
            .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);
        // An unset dimension is absent, not null: this is a full-replace
        // upsert, and `null` vs absent is the server's business either way —
        // but sending it would claim we meant to clear something.
        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");
        // `admins_exempt` was not set, so it must not be sent — sending
        // `false` would turn a one-field update into a two-field one.
        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(&params)
            .await
            .unwrap_err()
        {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("scope_id"), "{msg}"),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
        // Rejected before the wire, so the mock's empty script is never hit.
        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(&params)
            .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(&params).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();
        // Absent, not `"block"`: the server default is what decides, and
        // sending a value would overwrite a rule that had been made approvable.
        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"));
        // Refused before the wire, not after a round trip.
        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)]);
        // An open vocabulary: a stale client must not block an operation the
        // backend has since learned to enforce.
        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);
    }
}