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
//! The `external_records` resource: out-of-band transitions, what a payment
//! provider did that DeloPay never observed.
//!
//! A refund issued in the provider's own dashboard, a chargeback settled by
//! phone, a payment the rail holds as paid but never sent a usable
//! notification for. The transition is written through the normal path, an
//! outgoing webhook is raised for the shop, and an audit row records who
//! asserted it and why.
//!
//! Every call needs a dashboard session with the profile external-record
//! write permission; an API key reaches nothing here.

use std::sync::Arc;

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

use crate::core::encoding::to_json_vec;
use crate::core::error::{DelopayError, Result};
use crate::core::models::external_record::{ExternalRecordCapabilities, ExternalRecordResponse};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Record one out-of-band transition. `POST /external-records`
    ///
    /// Which kinds a deployment answers for depends on the payment's
    /// connector: a kind that is not served answers `501`, a statement about
    /// the rail rather than about the request. Read
    /// [`capabilities`](Self::capabilities) first. Not retried after a
    /// network error or `5xx`.
    pub async fn create(&self, params: &ExternalRecordRequest) -> Result<ExternalRecordResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Post, "/external-records", Some(&body), None)
            .await
    }

    /// What this deployment will accept, per kind, for the authenticated
    /// merchant. Every kind is listed, so one that is not served is told
    /// apart from one this SDK does not know: `create.status` says whether it
    /// is a gap (`not_implemented`) or a rule (`not_applicable`).
    /// `GET /external-records/capabilities`
    pub async fn capabilities(&self) -> Result<ExternalRecordCapabilities> {
        self.inner
            .request(
                HttpMethod::Get,
                "/external-records/capabilities",
                None,
                &[],
                None,
            )
            .await
    }
}

/// The kind of object an external record transitions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ExternalRecordResource {
    /// A payment.
    Payment,
    /// A refund.
    Refund,
    /// A dispute.
    Dispute,
    /// A payout.
    Payout,
}

/// The environment of a payment or payout an external record names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ExternalRecordEnvironment {
    /// Live.
    Live,
    /// Sandbox.
    Sandbox,
}

/// Parameters for [`ExternalRecords::create`]: what happened, and why it is
/// being recorded.
///
/// Build it with the constructor for the kind of object: [`payment`],
/// [`refund`], [`new_refund`], [`dispute`] or [`payout`]. `status` takes the
/// kind's own status spelling, as
/// [`capabilities`](ExternalRecords::capabilities) lists it.
///
/// [`payment`]: Self::payment
/// [`refund`]: Self::refund
/// [`new_refund`]: Self::new_refund
/// [`dispute`]: Self::dispute
/// [`payout`]: Self::payout
#[derive(Debug, Clone, Serialize)]
pub struct ExternalRecordRequest {
    /// The kind of object.
    pub resource: ExternalRecordResource,
    /// The payment, for a payment, refund or dispute.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_id: Option<String>,
    /// An existing refund, for a refund.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refund_id: Option<String>,
    /// An existing dispute, for a dispute.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dispute_id: Option<String>,
    /// The payout, for a payout.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payout_id: Option<String>,
    /// The status the provider holds.
    pub status: String,
    /// The environment, for a payment or payout.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<ExternalRecordEnvironment>,
    /// The amount in minor units, for a new refund or a dispute.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<i64>,
    /// Why this is being recorded. Required and non-empty, at most 1024
    /// characters after trimming.
    pub reason: String,
    /// The provider's own identifier for what happened: a dashboard refund
    /// id, a case number, a support ticket.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_reference: Option<String>,
    /// When it happened at the provider, ISO 8601, if known. Never inferred.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub occurred_at: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ExternalRecordRequest {
    fn base(resource: ExternalRecordResource, status: String, reason: String) -> Self {
        Self {
            resource,
            payment_id: None,
            refund_id: None,
            dispute_id: None,
            payout_id: None,
            status,
            environment: None,
            amount: None,
            reason,
            connector_reference: None,
            occurred_at: None,
            extra: serde_json::Map::new(),
        }
    }

    /// A payment's status at the provider, for example `succeeded`.
    pub fn payment(
        payment_id: impl Into<String>,
        status: impl Into<String>,
        environment: ExternalRecordEnvironment,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            payment_id: Some(payment_id.into()),
            environment: Some(environment),
            ..Self::base(
                ExternalRecordResource::Payment,
                status.into(),
                reason.into(),
            )
        }
    }

    /// An existing refund's status at the provider, for example `success`.
    pub fn refund(
        payment_id: impl Into<String>,
        refund_id: impl Into<String>,
        status: impl Into<String>,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            payment_id: Some(payment_id.into()),
            refund_id: Some(refund_id.into()),
            ..Self::base(ExternalRecordResource::Refund, status.into(), reason.into())
        }
    }

    /// A refund DeloPay does not hold yet, of `amount` minor units.
    pub fn new_refund(
        payment_id: impl Into<String>,
        amount: i64,
        status: impl Into<String>,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            payment_id: Some(payment_id.into()),
            amount: Some(amount),
            ..Self::base(ExternalRecordResource::Refund, status.into(), reason.into())
        }
    }

    /// A dispute's status at the provider, for example `dispute_lost`. Name
    /// an existing dispute with [`dispute_id`](Self::dispute_id).
    pub fn dispute(
        payment_id: impl Into<String>,
        status: impl Into<String>,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            payment_id: Some(payment_id.into()),
            ..Self::base(
                ExternalRecordResource::Dispute,
                status.into(),
                reason.into(),
            )
        }
    }

    /// A payout's status at the provider, for example `success`.
    pub fn payout(
        payout_id: impl Into<String>,
        status: impl Into<String>,
        environment: ExternalRecordEnvironment,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            payout_id: Some(payout_id.into()),
            environment: Some(environment),
            ..Self::base(ExternalRecordResource::Payout, status.into(), reason.into())
        }
    }

    /// Name the existing dispute.
    #[must_use]
    pub fn dispute_id(mut self, dispute_id: impl Into<String>) -> Self {
        self.dispute_id = Some(dispute_id.into());
        self
    }

    /// Set the disputed amount, in minor units.
    #[must_use]
    pub fn amount(mut self, amount: i64) -> Self {
        self.amount = Some(amount);
        self
    }

    /// Set the provider's own identifier for what happened.
    #[must_use]
    pub fn connector_reference(mut self, reference: impl Into<String>) -> Self {
        self.connector_reference = Some(reference.into());
        self
    }

    /// Set when it happened at the provider, ISO 8601.
    #[must_use]
    pub fn occurred_at(mut self, occurred_at: impl Into<String>) -> Self {
        self.occurred_at = Some(occurred_at.into());
        self
    }
}

/// Names of `ExternalRecordRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const EXTERNAL_RECORD_REQUEST_NAMED: &[&str] = &[
    "resource",
    "payment_id",
    "refund_id",
    "dispute_id",
    "payout_id",
    "status",
    "environment",
    "amount",
    "reason",
    "connector_reference",
    "occurred_at",
];

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

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

    const RECORD_JSON: &str = r#"{
        "record_id": "xr_1", "resource_kind": "refund", "resource_id": "ref_1",
        "payment_id": "pay_1", "created_resource": true, "previous_status": null,
        "recorded_status": "success", "webhook_outcome": "persisted",
        "recorded_by": "user_1", "recorded_at": "2026-01-01T00:00:00Z",
        "record_surprise": 1
    }"#;

    #[tokio::test]
    async fn create_posts_the_flat_target_and_reason() {
        let (client, mock) = client_with(vec![Step::ok(RECORD_JSON)]);
        let req = ExternalRecordRequest::new_refund("pay_1", 500, "success", "refunded by phone")
            .connector_reference("re_123")
            .occurred_at("2026-01-01T00:00:00Z");
        let out = client.external_records().create(&req).await.unwrap();
        assert!(out.created_resource);
        assert_eq!(out.recorded_status, "success");
        assert_eq!(out.extra["record_surprise"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/external-records");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "resource": "refund",
                "payment_id": "pay_1",
                "status": "success",
                "amount": 500,
                "reason": "refunded by phone",
                "connector_reference": "re_123",
                "occurred_at": "2026-01-01T00:00:00Z"
            })
        );
    }

    #[test]
    fn each_constructor_sends_its_kinds_fields() {
        let body = |req: ExternalRecordRequest| serde_json::to_value(req).unwrap();
        assert_eq!(
            body(ExternalRecordRequest::payment(
                "pay_1",
                "succeeded",
                ExternalRecordEnvironment::Sandbox,
                "r"
            )),
            json!({"resource": "payment", "payment_id": "pay_1", "status": "succeeded",
                   "environment": "sandbox", "reason": "r"})
        );
        assert_eq!(
            body(ExternalRecordRequest::refund(
                "pay_1", "ref_1", "failure", "r"
            )),
            json!({"resource": "refund", "payment_id": "pay_1", "refund_id": "ref_1",
                   "status": "failure", "reason": "r"})
        );
        assert_eq!(
            body(ExternalRecordRequest::dispute("pay_1", "dispute_lost", "r").dispute_id("dp_1")),
            json!({"resource": "dispute", "payment_id": "pay_1", "dispute_id": "dp_1",
                   "status": "dispute_lost", "reason": "r"})
        );
        assert_eq!(
            body(ExternalRecordRequest::payout(
                "po_1",
                "success",
                ExternalRecordEnvironment::Live,
                "r"
            )),
            json!({"resource": "payout", "payout_id": "po_1", "status": "success",
                   "environment": "live", "reason": "r"})
        );
    }

    #[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 = ExternalRecordRequest::dispute("pay_1", "dispute_won", "r");
        client.external_records().create(&req).await.unwrap_err();
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn capabilities_gets_every_kind() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"kinds":[{"resource":"payout","transition":true,
                "create":{"status":"not_implemented","reason":"payout creation is not built"},
                "statuses":["success","failed"],"x":1}]}"#,
        )]);
        let out = client.external_records().capabilities().await.unwrap();
        let kind = &out.kinds[0];
        assert_eq!(kind.create.status, "not_implemented");
        assert_eq!(
            kind.create.reason.as_deref(),
            Some("payout creation is not built")
        );
        assert_eq!(kind.statuses, ["success", "failed"]);
        assert_eq!(kind.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/external-records/capabilities"
        );
    }

    /// Drift guard for `EXTERNAL_RECORD_REQUEST_NAMED`.
    #[test]
    fn external_record_request_named_fields_are_complete() {
        let mut req = ExternalRecordRequest::payment(
            "pay_1",
            "succeeded",
            ExternalRecordEnvironment::Live,
            "r",
        )
        .dispute_id("dp_1")
        .amount(1)
        .connector_reference("c")
        .occurred_at("2026-01-01T00:00:00Z");
        req.refund_id = Some("ref_1".to_string());
        req.payout_id = Some("po_1".to_string());
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                EXTERNAL_RECORD_REQUEST_NAMED.contains(&key.as_str()),
                "EXTERNAL_RECORD_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn create_validate_rejects_colliding_extra_key() {
        let mut req = ExternalRecordRequest::dispute("pay_1", "dispute_won", "r");
        req.extra.insert("reason".to_string(), json!("other"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("reason")),
            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..1)
            .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
            .external_records()
            .create(&ExternalRecordRequest::dispute("pay_1", "dispute_won", "r"))
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 1);
        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..1)
            .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
            .external_records()
            .create(&ExternalRecordRequest::dispute("pay_1", "dispute_won", "r"))
            .await
            .unwrap_err();

        assert_eq!(mock.call_count(), 1);
        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/external-records")
        );
    }
}