delopay 0.20.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
//! The `chargeback_prevention` resource: alerts from a chargeback prevention
//! provider account the merchant connected in the dashboard.
//!
//! Read only. Connecting an account, replacing its key, setting its shops and
//! turning on its refund rule happen in the dashboard; nothing here answers an
//! alert, refunds or opens a dispute.

use std::sync::Arc;

use serde::Serialize;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::chargeback_prevention::{
    PreventionCaseDetail, PreventionCaseList, PreventionConnectionList, PreventionRefundActionList,
    PreventionRefundLimit, PreventionRefundPreview, PreventionRefundRuleList,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// The merchant's connections, with their business accounts and how
    /// current their cases are. No key is returned. Needs a merchant-wide API
    /// key: a connection serves every shop, so a shop's key is refused.
    /// `GET /chargeback-prevention/connections`
    pub async fn list_connections(&self) -> Result<PreventionConnectionList> {
        self.inner
            .request(
                HttpMethod::Get,
                "/chargeback-prevention/connections",
                None,
                &[],
                None,
            )
            .await
    }

    /// Cases with what DeloPay's records say happened to each payment.
    /// `GET /chargeback-prevention/cases`
    pub async fn list_cases(
        &self,
        params: &PreventionCaseListParams,
    ) -> Result<PreventionCaseList> {
        self.inner
            .request(
                HttpMethod::Get,
                "/chargeback-prevention/cases",
                None,
                &params.query(),
                None,
            )
            .await
    }

    /// One case with its references and observed history.
    /// `GET /chargeback-prevention/cases/{case_id}`
    pub async fn retrieve_case(&self, case_id: &str) -> Result<PreventionCaseDetail> {
        let path = format!("/chargeback-prevention/cases/{}", encode_segment(case_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// The refund rule of every connected account and environment; version
    /// `0` and off for one never saved. A rule is turned on in the dashboard.
    /// Needs a merchant-wide API key.
    /// `GET /chargeback-prevention/refund-rules`
    pub async fn list_refund_rules(&self) -> Result<PreventionRefundRuleList> {
        self.inner
            .request(
                HttpMethod::Get,
                "/chargeback-prevention/refund-rules",
                None,
                &[],
                None,
            )
            .await
    }

    /// What the stored rule, or unsaved settings, would do with each open
    /// alert of the account now. Nothing is refunded.
    /// `POST /chargeback-prevention/refund-rules/preview`
    pub async fn preview_refund_rule(
        &self,
        params: &PreventionRefundPreviewRequest,
    ) -> Result<PreventionRefundPreview> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/chargeback-prevention/refund-rules/preview",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// What the merchant's refund rules did, newest first: refunds made and
    /// payments found already refunded.
    /// `GET /chargeback-prevention/refund-actions`
    pub async fn list_refund_actions(
        &self,
        params: &PreventionRefundActionListParams,
    ) -> Result<PreventionRefundActionList> {
        self.inner
            .request(
                HttpMethod::Get,
                "/chargeback-prevention/refund-actions",
                None,
                &params.query(),
                None,
            )
            .await
    }
}

/// A refund rule's settings, for [`ChargebackPrevention::preview_refund_rule`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct PreventionRefundRuleSettings {
    /// Whether the rule acts.
    pub enabled: bool,
    /// `cdrn`, `ethoca` or `paypal`; `rdr` is refused.
    pub alert_sources: Vec<String>,
    /// At most 20 currencies.
    pub amount_limits: Vec<PreventionRefundLimit>,
    /// Between 1 and 500.
    pub daily_limit: i32,
    /// Between 1 and 720.
    pub max_alert_age_hours: i32,
}

/// Parameters for [`ChargebackPrevention::preview_refund_rule`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct PreventionRefundPreviewRequest {
    /// The prevention connector account.
    pub merchant_connector_id: String,
    /// Its test or live slot.
    pub test_mode: bool,
    /// Unsaved settings to preview instead of the stored rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub settings: Option<PreventionRefundRuleSettings>,
}

/// Filters for [`ChargebackPrevention::list_refund_actions`].
#[derive(Debug, Clone, Default)]
pub struct PreventionRefundActionListParams {
    /// A prevention connector account.
    pub merchant_connector_id: Option<String>,
    /// Test or live actions; both when unset.
    pub test_mode: Option<bool>,
    /// `refunding`, `pending`, `succeeded`, `failed` or `reconciled`.
    pub state: Option<String>,
    /// A payment.
    pub payment_id: Option<String>,
    /// At most 100. Default 25.
    pub limit: Option<i64>,
    /// Actions to skip.
    pub offset: Option<i64>,
}

impl PreventionRefundActionListParams {
    fn query(&self) -> Vec<(&'static str, String)> {
        let mut query = Vec::new();
        if let Some(value) = &self.merchant_connector_id {
            query.push(("merchant_connector_id", value.clone()));
        }
        if let Some(test_mode) = self.test_mode {
            query.push(("test_mode", test_mode.to_string()));
        }
        if let Some(value) = &self.state {
            query.push(("state", value.clone()));
        }
        if let Some(value) = &self.payment_id {
            query.push(("payment_id", value.clone()));
        }
        if let Some(limit) = self.limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(offset) = self.offset {
            query.push(("offset", offset.to_string()));
        }
        query
    }
}

/// Filters for [`ChargebackPrevention::list_cases`]. Times are RFC 3339.
#[derive(Debug, Clone, Default)]
pub struct PreventionCaseListParams {
    /// A shop.
    pub profile_id: Option<String>,
    /// A connection.
    pub connection_id: Option<String>,
    /// A payment.
    pub payment_id: Option<String>,
    /// Test or live cases; both when unset.
    pub test_mode: Option<bool>,
    /// Providers, e.g. `chargebackio`, `chargebackhit`.
    pub provider: Vec<String>,
    /// Networks or programs, e.g. `ethoca`, `cdrn`, `rdr`.
    pub source: Vec<String>,
    /// DeloPay's readings of the provider's status.
    pub status: Vec<String>,
    /// Outcomes.
    pub outcome: Vec<String>,
    /// Match statuses.
    pub match_status: Vec<String>,
    /// Deadline at or after.
    pub respond_by_from: Option<String>,
    /// Deadline before.
    pub respond_by_to: Option<String>,
    /// Alert raised at or after.
    pub alerted_from: Option<String>,
    /// Alert raised before.
    pub alerted_to: Option<String>,
    /// `respond_by` (soonest deadline first) or `alerted_at` (newest first).
    pub sort: Option<String>,
    /// At most 100. Default 25.
    pub limit: Option<i64>,
    /// Cases to skip.
    pub offset: Option<i64>,
}

impl PreventionCaseListParams {
    fn query(&self) -> Vec<(&'static str, String)> {
        let mut query = Vec::new();
        let single = [
            ("profile_id", &self.profile_id),
            ("connection_id", &self.connection_id),
            ("payment_id", &self.payment_id),
            ("respond_by_from", &self.respond_by_from),
            ("respond_by_to", &self.respond_by_to),
            ("alerted_from", &self.alerted_from),
            ("alerted_to", &self.alerted_to),
            ("sort", &self.sort),
        ];
        for (name, value) in single {
            if let Some(value) = value {
                query.push((name, value.clone()));
            }
        }
        if let Some(test_mode) = self.test_mode {
            query.push(("test_mode", test_mode.to_string()));
        }
        let lists = [
            ("provider", &self.provider),
            ("source", &self.source),
            ("status", &self.status),
            ("outcome", &self.outcome),
            ("match_status", &self.match_status),
        ];
        for (name, values) in lists {
            if !values.is_empty() {
                query.push((name, values.join(",")));
            }
        }
        if let Some(limit) = self.limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(offset) = self.offset {
            query.push(("offset", offset.to_string()));
        }
        query
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::mock::{Step, client_with};

    const CASE_JSON: &str = r#"{
        "id": "cbpa_1", "merchant_id": "mer_1", "connection_id": "cbpc_1",
        "provider": "chargebackio", "test_mode": true, "provider_account_id": "ba_1",
        "provider_case_id": "a390ba0c", "source": "ethoca", "provider_status": "Attention",
        "status": "attention", "outcome": "open", "amount": "61.00", "currency": "EUR",
        "processors": ["stripe"], "match_status": "matched", "payment_id": "pay_1",
        "refund_confirmed": false, "created_at": "2026-11-04T12:00:00",
        "modified_at": "2026-11-04T12:00:00", "case_surprise": 1
    }"#;

    #[tokio::test]
    async fn list_cases_sends_lists_as_comma_separated_values() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{CASE_JSON}],"total":1,"connections":[]}}"#
        ))]);
        let params = PreventionCaseListParams {
            outcome: vec!["open".to_string(), "refund_confirmed".to_string()],
            sort: Some("respond_by".to_string()),
            limit: Some(50),
            ..Default::default()
        };
        let out = client
            .chargeback_prevention()
            .list_cases(&params)
            .await
            .unwrap();
        assert_eq!(out.total, 1);
        assert_eq!(out.data[0].outcome, "open");
        assert_eq!(out.data[0].extra["case_surprise"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/chargeback-prevention/cases?sort=respond_by&outcome=open,refund_confirmed&limit=50"
        );
    }

    #[tokio::test]
    async fn retrieve_case_reads_the_detail_and_its_history() {
        let detail = CASE_JSON.trim_end().trim_end_matches('}').to_string()
            + r#", "arn": "123", "transaction_ids": ["pi_1"], "events": [{
                "provider_status": "Attention", "status": "attention",
                "provider_updated_at": "2026-11-04T12:00:00", "observed_at": "2026-11-04T12:01:00"
            }]}"#;
        let (client, mock) = client_with(vec![Step::ok(&detail)]);
        let out = client
            .chargeback_prevention()
            .retrieve_case("cbpa/1")
            .await
            .unwrap();
        assert_eq!(out.case.id, "cbpa_1");
        assert_eq!(out.arn.as_deref(), Some("123"));
        assert_eq!(out.events.len(), 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/chargeback-prevention/cases/cbpa%2F1"
        );
    }

    #[tokio::test]
    async fn an_answered_case_carries_its_answer_and_withdrawal() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[{
                "id": "cbpa_2", "merchant_id": "mer_1", "connection_id": "cbpc_2",
                "provider": "chargebackhit", "test_mode": true, "provider_account_id": "pk_1",
                "provider_case_id": "alert_1", "source": "ethoca", "alert_type": "inquiry",
                "provider_status": "withdrawn", "status": "answered", "outcome": "withdrawn",
                "processors": [], "match_status": "matched", "refund_confirmed": false,
                "answer": {"outcome": "acknowledged", "reason": "matched", "elapsed_ms": 840,
                    "answered_at": "2026-11-05T09:00:00", "answer_surprise": true},
                "withdrawn_at": "2026-11-05T10:00:00",
                "created_at": "2026-11-05T09:00:00", "modified_at": "2026-11-05T10:00:00"
            }, {
                "id": "cbpa_3", "merchant_id": "mer_1", "connection_id": "cbpc_1",
                "provider": "chargebackio", "test_mode": true, "provider_account_id": "ba_1",
                "provider_case_id": "a390ba0d", "provider_status": "Attention",
                "status": "attention", "outcome": "open", "processors": [],
                "match_status": "unmatched", "refund_confirmed": false, "answer": null,
                "created_at": "2026-11-05T09:00:00", "modified_at": "2026-11-05T09:00:00"
            }],"total":2,"connections":[]}"#,
        )]);
        let params = PreventionCaseListParams {
            provider: vec!["chargebackhit".to_string()],
            status: vec!["answered".to_string(), "issuer_report".to_string()],
            outcome: vec!["withdrawn".to_string(), "informational".to_string()],
            ..Default::default()
        };
        let out = client
            .chargeback_prevention()
            .list_cases(&params)
            .await
            .unwrap();
        let answered = &out.data[0];
        let answer = answered.answer.as_ref().unwrap();
        assert_eq!(answer.outcome.as_deref(), Some("acknowledged"));
        assert_eq!(answer.reason.as_deref(), Some("matched"));
        assert_eq!(answer.elapsed_ms, Some(840));
        assert_eq!(answer.answered_at.as_deref(), Some("2026-11-05T09:00:00"));
        assert_eq!(answer.extra["answer_surprise"], true);
        assert_eq!(
            answered.withdrawn_at.as_deref(),
            Some("2026-11-05T10:00:00")
        );
        assert!(!answered.extra.contains_key("answer"));
        assert!(!answered.extra.contains_key("withdrawn_at"));
        assert!(out.data[1].answer.is_none());
        assert!(out.data[1].withdrawn_at.is_none());

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/chargeback-prevention/cases?provider=chargebackhit&status=answered,issuer_report&outcome=withdrawn,informational"
        );
    }

    const RULE_JSON: &str = r#"{
        "merchant_id": "mer_1", "merchant_connector_id": "mca_1", "connection_id": "cbpc_1",
        "provider": "chargebackio", "test_mode": true, "enabled": true,
        "alert_sources": ["cdrn", "ethoca"],
        "amount_limits": [{"currency": "USD", "max_amount": 5000}],
        "daily_limit": 5, "max_alert_age_hours": 48, "version": 1,
        "updated_by": "usr_1", "updated_at": "2026-11-07T08:00:00", "rule_surprise": 1
    }"#;

    #[tokio::test]
    async fn list_refund_rules_reads_every_accounts_rule() {
        let (client, mock) = client_with(vec![Step::ok(&format!(r#"{{"rules":[{RULE_JSON}]}}"#))]);
        let out = client
            .chargeback_prevention()
            .list_refund_rules()
            .await
            .unwrap();
        let rule = &out.rules[0];
        assert!(rule.enabled);
        assert_eq!(rule.version, 1);
        assert_eq!(
            rule.amount_limits,
            vec![PreventionRefundLimit {
                currency: "USD".to_string(),
                max_amount: 5000
            }]
        );
        assert_eq!(rule.extra["rule_surprise"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/chargeback-prevention/refund-rules"
        );
    }

    #[tokio::test]
    async fn preview_refund_rule_posts_the_proposed_settings() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"rule":{RULE_JSON},"items":[{{"case_id":"cbpa_1","payment_id":"pay_1",
                "amount":"49.99","currency":"USD","decision":"skip","reason":"over_limit"}}]}}"#
        ))]);
        let params = PreventionRefundPreviewRequest {
            merchant_connector_id: "mca_1".to_string(),
            test_mode: true,
            settings: Some(PreventionRefundRuleSettings {
                enabled: true,
                alert_sources: vec!["ethoca".to_string()],
                amount_limits: vec![PreventionRefundLimit {
                    currency: "USD".to_string(),
                    max_amount: 1000,
                }],
                daily_limit: 5,
                max_alert_age_hours: 48,
            }),
        };
        let out = client
            .chargeback_prevention()
            .preview_refund_rule(&params)
            .await
            .unwrap();
        assert_eq!(out.items[0].decision, "skip");
        assert_eq!(out.items[0].reason.as_deref(), Some("over_limit"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/chargeback-prevention/refund-rules/preview"
        );
        let body: serde_json::Value =
            serde_json::from_slice(seen[0].body.as_ref().unwrap()).unwrap();
        assert_eq!(body["merchant_connector_id"], "mca_1");
        assert_eq!(body["settings"]["amount_limits"][0]["max_amount"], 1000);
    }

    #[tokio::test]
    async fn a_preview_of_the_stored_rule_sends_no_settings() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"rule":{RULE_JSON},"items":[]}}"#
        ))]);
        let params = PreventionRefundPreviewRequest {
            merchant_connector_id: "mca_1".to_string(),
            test_mode: false,
            settings: None,
        };
        client
            .chargeback_prevention()
            .preview_refund_rule(&params)
            .await
            .unwrap();
        let seen = mock.seen.lock().unwrap();
        let body: serde_json::Value =
            serde_json::from_slice(seen[0].body.as_ref().unwrap()).unwrap();
        assert!(body.get("settings").is_none());
    }

    #[tokio::test]
    async fn list_refund_actions_sends_its_filters_and_a_case_shows_its_action() {
        let (client, mock) = client_with(vec![
            Step::ok(
                r#"{"data":[{"id":"cbpr_1","merchant_id":"mer_1","case_id":"cbpa_1",
                    "merchant_connector_id":"mca_1","test_mode":true,"payment_id":"pay_1",
                    "refund_id":"cbpr_1","amount":4999,"currency":"USD","state":"succeeded",
                    "rule_version":1,"rule":{"version":1},"report_status":"Manually refunded",
                    "report_state":"reported","created_at":"2026-11-07T08:00:00",
                    "modified_at":"2026-11-07T08:05:00"}],"total":1}"#,
            ),
            Step::ok(&format!(
                r#"{{"data":[{}],"total":1,"connections":[]}}"#,
                CASE_JSON.trim_end().trim_end_matches('}').to_string()
                    + r#", "refund_action": {"id":"cbpr_1","case_id":"cbpa_1","refund_id":"cbpr_1",
                        "amount":4999,"currency":"USD","state":"succeeded","report_state":"reported"}}"#
            )),
        ]);
        let params = PreventionRefundActionListParams {
            state: Some("succeeded".to_string()),
            limit: Some(10),
            ..Default::default()
        };
        let actions = client
            .chargeback_prevention()
            .list_refund_actions(&params)
            .await
            .unwrap();
        assert_eq!(actions.data[0].state, "succeeded");
        assert_eq!(actions.data[0].refund_id, actions.data[0].id);

        let cases = client
            .chargeback_prevention()
            .list_cases(&PreventionCaseListParams::default())
            .await
            .unwrap();
        let action = cases.data[0].refund_action.as_ref().unwrap();
        assert_eq!(action.state, "succeeded");
        assert!(!cases.data[0].extra.contains_key("refund_action"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/chargeback-prevention/refund-actions?state=succeeded&limit=10"
        );
    }

    #[tokio::test]
    async fn list_connections_reads_sync_health() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"connections":[{"id":"cbpc_1","merchant_id":"mer_1","provider":"chargebackio",
                "test_mode":true,"status":"active","sync":{"status":"rate_limited",
                "retry_at":"2026-11-04T13:00:00","stale":false},"accounts":[],
                "created_at":"2026-11-04T12:00:00"}]}"#,
        )]);
        let out = client
            .chargeback_prevention()
            .list_connections()
            .await
            .unwrap();
        assert_eq!(
            out.connections[0].sync.status.as_deref(),
            Some("rate_limited")
        );

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/chargeback-prevention/connections"
        );
    }
}