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
//! The `processor_imports` resource: import refunds and disputes from the
//! merchant's connected processor accounts, in the background.
//!
//! An import only reads from the processor and records what it already
//! holds: it never answers a dispute, moves money or changes a payment. A
//! record DeloPay already holds is counted as already present. Every method
//! needs a dashboard JWT.
//!
//! The import's progress stream (`GET /refunds-disputes/imports/{id}/stream`,
//! server-sent events) is not wrapped: poll [`ProcessorImports::retrieve`]
//! while the import runs instead.

use std::sync::Arc;

use serde::Serialize;
use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::processor_import::{
    PspImportIssuesResponse, PspImportLatestResponse, PspImportRunResponse,
    PspImportSourcesResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Every connected processor account the caller may see, with what each
    /// can provide in the environment: listed, read payment by payment, or
    /// unavailable with a reason. `GET /refunds-disputes/imports/sources`
    pub async fn sources(&self, test_mode: bool) -> Result<PspImportSourcesResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/refunds-disputes/imports/sources",
                None,
                &[("test_mode", test_mode.to_string())],
                None,
            )
            .await
    }

    /// Start an import. A source a processor cannot provide is stored as
    /// `unavailable` with its reason. Refused while another import of the
    /// merchant runs in the same environment. Not retried after a network
    /// error or `5xx`. `POST /refunds-disputes/imports`
    pub async fn create(&self, params: &PspImportCreateRequest) -> Result<PspImportRunResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/refunds-disputes/imports",
                Some(&body),
                None,
            )
            .await
    }

    /// The newest import in the environment, running or finished.
    /// `GET /refunds-disputes/imports/latest`
    pub async fn latest(&self, test_mode: bool) -> Result<PspImportLatestResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/refunds-disputes/imports/latest",
                None,
                &[("test_mode", test_mode.to_string())],
                None,
            )
            .await
    }

    /// One import. `GET /refunds-disputes/imports/{id}`
    pub async fn retrieve(&self, import_id: &str) -> Result<PspImportRunResponse> {
        self.inner
            .request(HttpMethod::Get, &import_path(import_id), None, &[], None)
            .await
    }

    /// The records an import left out or could not record, each with its
    /// reason. `GET /refunds-disputes/imports/{id}/issues`
    pub async fn issues(
        &self,
        import_id: &str,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<PspImportIssuesResponse> {
        let path = format!("{}/issues", import_path(import_id));
        let mut query = Vec::new();
        if let Some(v) = limit {
            query.push(("limit", v.to_string()));
        }
        if let Some(v) = offset {
            query.push(("offset", v.to_string()));
        }
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Ask a running import to stop. It stops after the page it is reading;
    /// what it recorded stays recorded.
    /// `POST /refunds-disputes/imports/{id}/cancel`
    pub async fn cancel(&self, import_id: &str) -> Result<PspImportRunResponse> {
        let path = format!("{}/cancel", import_path(import_id));
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, None, None)
            .await
    }
}

/// `/refunds-disputes/imports/{id}`, percent-encoded.
fn import_path(import_id: &str) -> String {
    format!("/refunds-disputes/imports/{}", encode_segment(import_id))
}

/// A kind of record an import reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PspImportRecordType {
    /// Refunds.
    Refund,
    /// Disputes.
    Dispute,
}

/// Parameters for [`ProcessorImports::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct PspImportCreateRequest {
    /// Read test records (`true`) or live ones (`false`).
    pub test_mode: bool,
    /// The earliest record to read, RFC 3339. The import reads up to the
    /// moment it starts.
    pub start_time: String,
    /// The record types to read.
    pub record_types: Vec<PspImportRecordType>,
    /// The connector accounts to read; each is read for every record type it
    /// can provide.
    pub merchant_connector_ids: Vec<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl PspImportCreateRequest {
    /// Import `record_types` from `merchant_connector_ids`, from `start_time`
    /// on.
    pub fn new(
        test_mode: bool,
        start_time: impl Into<String>,
        record_types: Vec<PspImportRecordType>,
        merchant_connector_ids: Vec<String>,
    ) -> Self {
        Self {
            test_mode,
            start_time: start_time.into(),
            record_types,
            merchant_connector_ids,
            extra: serde_json::Map::new(),
        }
    }
}

/// Names of `PspImportCreateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const PSP_IMPORT_CREATE_REQUEST_NAMED: &[&str] = &[
    "test_mode",
    "start_time",
    "record_types",
    "merchant_connector_ids",
];

impl ValidateRequest for PspImportCreateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if PSP_IMPORT_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on PspImportCreateRequest"
                )));
            }
        }
        Ok(())
    }
}

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

    const RUN_JSON: &str = r#"{
        "id": "imp_1", "test_mode": true, "start_time": "2026-01-01T00:00:00Z",
        "end_time": "2026-02-01T00:00:00Z", "record_types": ["refund", "dispute"],
        "status": "running", "cancel_requested": false,
        "created_at": "2026-02-01T00:00:00Z",
        "totals": {"fetched": 10, "imported": 7, "already_present": 2, "skipped": 1, "failed": 0},
        "sources": [{
            "merchant_connector_id": "mca_1", "connector": "stripe", "record_type": "refund",
            "status": "running",
            "counts": {"fetched": 10, "imported": 7, "already_present": 2, "skipped": 1, "failed": 0},
            "progress_done": 10, "progress_total": 40, "updated_at": "2026-02-01T00:01:00Z"
        }],
        "run_surprise": 1
    }"#;

    #[tokio::test]
    async fn sources_sends_the_environment() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"accounts":[{"merchant_connector_id":"mca_1","connector":"stripe",
                "profile_id":"pro_1","records":[{"record_type":"dispute",
                "availability":"per_payment","reason":null}],"x":1}]}"#,
        )]);
        let out = client.processor_imports().sources(true).await.unwrap();
        assert_eq!(out.accounts[0].records[0].availability, "per_payment");
        assert_eq!(out.accounts[0].extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/refunds-disputes/imports/sources?test_mode=true"
        );
    }

    #[tokio::test]
    async fn create_posts_the_import() {
        let (client, mock) = client_with(vec![Step::ok(RUN_JSON)]);
        let req = PspImportCreateRequest::new(
            true,
            "2026-01-01T00:00:00Z",
            vec![PspImportRecordType::Refund, PspImportRecordType::Dispute],
            vec!["mca_1".to_string()],
        );
        let run = client.processor_imports().create(&req).await.unwrap();
        assert_eq!(run.totals.imported, 7);
        assert_eq!(run.sources[0].progress_total, Some(40));
        assert_eq!(run.extra["run_surprise"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/refunds-disputes/imports");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "test_mode": true,
                "start_time": "2026-01-01T00:00:00Z",
                "record_types": ["refund", "dispute"],
                "merchant_connector_ids": ["mca_1"]
            })
        );
    }

    #[tokio::test]
    async fn create_is_not_retried_on_5xx() {
        let (client, mock) = client_with_retries(
            vec![Step::status(500, r#"{"error":{"message":"boom"}}"#)],
            2,
        );
        let req = PspImportCreateRequest::new(true, "2026-01-01T00:00:00Z", vec![], vec![]);
        client.processor_imports().create(&req).await.unwrap_err();
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn latest_sends_the_environment_and_decodes_no_run() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"run":null,"x":1}"#)]);
        let out = client.processor_imports().latest(false).await.unwrap();
        assert!(out.run.is_none());
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/refunds-disputes/imports/latest?test_mode=false"
        );
    }

    #[tokio::test]
    async fn retrieve_encodes_the_import_id() {
        let (client, mock) = client_with(vec![Step::ok(RUN_JSON)]);
        let run = client.processor_imports().retrieve("imp/1").await.unwrap();
        assert_eq!(run.status, "running");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/refunds-disputes/imports/imp%2F1"
        );
    }

    #[tokio::test]
    async fn issues_sends_the_page() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"issues":[{"merchant_connector_id":"mca_1","record_type":"dispute",
                "connector_record_id":"du_1","outcome":"skipped","reason":"payment_not_found",
                "created_at":"2026-02-01T00:00:00Z","x":1}],"has_more":true}"#,
        )]);
        let out = client
            .processor_imports()
            .issues("imp_1", Some(50), Some(100))
            .await
            .unwrap();
        assert!(out.has_more);
        assert_eq!(out.issues[0].reason, "payment_not_found");
        assert_eq!(out.issues[0].extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/refunds-disputes/imports/imp_1/issues?limit=50&offset=100"
        );
    }

    #[tokio::test]
    async fn cancel_posts_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(RUN_JSON)]);
        client.processor_imports().cancel("imp_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/refunds-disputes/imports/imp_1/cancel"
        );
        assert!(seen[0].body.is_none());
    }

    /// Drift guard for `PSP_IMPORT_CREATE_REQUEST_NAMED`.
    #[test]
    fn psp_import_create_request_named_fields_are_complete() {
        let req = PspImportCreateRequest::new(
            false,
            "2026-01-01T00:00:00Z",
            vec![PspImportRecordType::Refund],
            vec!["mca_1".to_string()],
        );
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                PSP_IMPORT_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "PSP_IMPORT_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn create_validate_rejects_colliding_extra_key() {
        let mut req = PspImportCreateRequest::new(false, "t", vec![], vec![]);
        req.extra.insert("test_mode".to_string(), json!(true));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("test_mode")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    /// Every write here ignores the client-wide idempotency key: none sends
    /// it, and none is replayed after a `503`. Switching a call site back to
    /// `request(.., None)` makes it send the key and retry.
    #[tokio::test]
    async fn writes_ignore_the_client_wide_idempotency_key() {
        let steps = (0..2)
            .map(|_| Step::status(503, r#"{"error":{"message":"down"}}"#))
            .collect();
        let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
        let client = client.with_idempotency_key("client-key");
        client
            .processor_imports()
            .create(&PspImportCreateRequest::new(
                true,
                "2026-01-01T00:00:00Z",
                vec![PspImportRecordType::Refund],
                vec!["mca_1".to_string()],
            ))
            .await
            .unwrap_err();
        client
            .processor_imports()
            .cancel("imp_1")
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 2);
        for seen in mock.seen.lock().unwrap().iter() {
            assert!(
                !seen.had_idempotency_key(),
                "{} sent the client key",
                seen.url
            );
        }
    }

    /// A keyed client does not replay these writes after a network error
    /// either: a connect failure is retriable for a keyed call, so a call site
    /// that fell back to the client-wide key would send it and try again.
    #[tokio::test]
    async fn writes_are_not_retried_after_a_network_error_with_a_client_key() {
        let steps = (0..2)
            .map(|_| Step::Fail(crate::http::transport::TransportErrorKind::Connect))
            .collect();
        let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
        let client = client.with_idempotency_key("client-key");
        client
            .processor_imports()
            .create(&PspImportCreateRequest::new(
                true,
                "2026-01-01T00:00:00Z",
                vec![PspImportRecordType::Dispute],
                vec!["mca_1".to_string()],
            ))
            .await
            .unwrap_err();
        client
            .processor_imports()
            .cancel("imp_1")
            .await
            .unwrap_err();

        assert_eq!(mock.call_count(), 2);
        let seen = mock.seen.lock().unwrap();
        for request in seen.iter() {
            assert!(
                !request.had_idempotency_key(),
                "{} sent the client key",
                request.url
            );
        }
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("POST", "https://api.test/refunds-disputes/imports")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            (
                "POST",
                "https://api.test/refunds-disputes/imports/imp_1/cancel"
            )
        );
    }
}