delopay 0.2.1

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
//! The `disputes` resource: view disputes and respond to chargebacks with
//! evidence.

use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::dispute::DisputeResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Retrieve a dispute by ID.
    pub async fn retrieve(&self, dispute_id: &str) -> Result<DisputeResponse> {
        let path = format!("/disputes/{}", encode_segment(dispute_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// List disputes.
    pub async fn list(&self) -> Result<Vec<DisputeResponse>> {
        self.inner
            .request(HttpMethod::Get, "/disputes/list", None, &[], None)
            .await
    }

    /// Accept a dispute (concede the chargeback).
    pub async fn accept(&self, dispute_id: &str) -> Result<DisputeResponse> {
        let path = format!("/disputes/accept/{}", encode_segment(dispute_id));
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Submit evidence to challenge a dispute.
    pub async fn submit_evidence(
        &self,
        params: &DisputeEvidenceRequest,
    ) -> Result<DisputeResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/disputes/evidence",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Attach evidence (e.g. uploaded-file references) to a dispute.
    pub async fn attach_evidence(
        &self,
        params: &DisputeEvidenceRequest,
    ) -> Result<DisputeResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Put,
                "/disputes/evidence",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Retrieve previously submitted evidence for a dispute.
    pub async fn retrieve_evidence(&self, dispute_id: &str) -> Result<DisputeEvidenceRequest> {
        let path = format!("/disputes/evidence/{}", encode_segment(dispute_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Delete submitted evidence for a dispute. The body identifies what to
    /// delete, mirroring the submit shape.
    pub async fn delete_evidence(
        &self,
        params: &DisputeEvidenceRequest,
    ) -> Result<DisputeResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Delete,
                "/disputes/evidence",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Fetch the latest dispute state from the connector (gateway).
    ///
    /// The path parameter is the **connector's** dispute ID on the gateway,
    /// not the Delopay dispute ID.
    pub async fn fetch_from_connector(
        &self,
        connector_dispute_id: &str,
    ) -> Result<DisputeResponse> {
        let path = format!("/disputes/{}/fetch", encode_segment(connector_dispute_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }
}

/// Evidence for challenging a dispute, submitted via
/// [`Disputes::submit_evidence`] / [`Disputes::attach_evidence`] and returned
/// by [`Disputes::retrieve_evidence`].
///
/// Every field is optional; file-shaped fields (`receipt`,
/// `shipping_documentation`, …) carry file IDs from the `files` resource.
/// The dispute being contested is identified by a `dispute_id` key — set it
/// through [`extra`](DisputeEvidenceRequest::extra), matching the wire shape.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DisputeEvidenceRequest {
    /// Concede instead of contesting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancel_dispute: Option<bool>,
    /// Body of an email exchange with the customer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_email_body: Option<String>,
    /// Customer's email address.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_email_address: Option<String>,
    /// Customer's name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_name: Option<String>,
    /// File ID of the customer's signature.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_signature: Option<String>,
    /// Description of the product or service sold.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub product_description: Option<String>,
    /// File ID of the receipt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub receipt: Option<String>,
    /// File ID of the refund policy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refund_policy: Option<String>,
    /// How the refund policy was disclosed to the customer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refund_policy_disclosure: Option<String>,
    /// Why the refund was refused.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refund_refusal_explanation: Option<String>,
    /// Date the service was provided.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service_date: Option<String>,
    /// File ID documenting the service.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service_documentation: Option<String>,
    /// Shipping address used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_address: Option<String>,
    /// Carrier used for shipping.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_carrier: Option<String>,
    /// Date the goods were shipped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_date: Option<String>,
    /// File ID of the shipping documentation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_documentation: Option<String>,
    /// Shipment tracking number.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_tracking_number: Option<String>,
    /// File ID of any uncategorized evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uncategorized_file: Option<String>,
    /// Free-text uncategorized evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uncategorized_text: Option<String>,
    /// Access / activity log evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access_activity_log: Option<String>,
    /// Billing address used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub billing_address: Option<String>,
    /// File ID of the cancellation policy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancellation_policy: Option<String>,
    /// How the cancellation policy was disclosed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancellation_policy_disclosure: Option<String>,
    /// Rebuttal to the cancellation claim.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancellation_rebuttal: Option<String>,
    /// File ID of customer communication.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_communication: Option<String>,
    /// IP address the purchase was made from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_purchase_ip: Option<String>,
    /// File ID documenting the alleged duplicate charge.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duplicate_charge_documentation: Option<String>,
    /// Explanation of why the charge is not a duplicate.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duplicate_charge_explanation: Option<String>,
    /// Payment ID of the alleged duplicate charge.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duplicate_charge_id: Option<String>,
    /// Any additional fields (e.g. `dispute_id`) are merged in verbatim, and
    /// unknown fields returned by `retrieve_evidence` land here.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `DisputeEvidenceRequest`'s fields as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const DISPUTE_EVIDENCE_REQUEST_NAMED: &[&str] = &[
    "cancel_dispute",
    "customer_email_body",
    "customer_email_address",
    "customer_name",
    "customer_signature",
    "product_description",
    "receipt",
    "refund_policy",
    "refund_policy_disclosure",
    "refund_refusal_explanation",
    "service_date",
    "service_documentation",
    "shipping_address",
    "shipping_carrier",
    "shipping_date",
    "shipping_documentation",
    "shipping_tracking_number",
    "uncategorized_file",
    "uncategorized_text",
    "access_activity_log",
    "billing_address",
    "cancellation_policy",
    "cancellation_policy_disclosure",
    "cancellation_rebuttal",
    "customer_communication",
    "customer_purchase_ip",
    "duplicate_charge_documentation",
    "duplicate_charge_explanation",
    "duplicate_charge_id",
];

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

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

    const DISPUTE_JSON: &str = r#"{
        "dispute_id": "dp_1", "payment_id": "pay_1", "attempt_id": "att_1",
        "amount": "500", "currency": "EUR", "dispute_stage": "dispute",
        "dispute_status": "dispute_opened", "connector": "stripe",
        "connector_status": "needs_response", "connector_dispute_id": "du_1",
        "is_already_refunded": false
    }"#;

    /// Every optional field populated so serialization emits the full key set.
    fn full_evidence_request() -> DisputeEvidenceRequest {
        let text = |s: &str| Some(s.to_string());
        DisputeEvidenceRequest {
            cancel_dispute: Some(false),
            customer_email_body: text("body"),
            customer_email_address: text("a@example.com"),
            customer_name: text("Ada"),
            customer_signature: text("file_sig"),
            product_description: text("widget"),
            receipt: text("file_receipt"),
            refund_policy: text("file_policy"),
            refund_policy_disclosure: text("shown at checkout"),
            refund_refusal_explanation: text("outside window"),
            service_date: text("2026-01-01"),
            service_documentation: text("file_service"),
            shipping_address: text("Somestr. 1"),
            shipping_carrier: text("DHL"),
            shipping_date: text("2026-01-02"),
            shipping_documentation: text("file_ship"),
            shipping_tracking_number: text("TRACK1"),
            uncategorized_file: text("file_misc"),
            uncategorized_text: text("misc"),
            access_activity_log: text("log"),
            billing_address: text("Somestr. 1"),
            cancellation_policy: text("file_cancel"),
            cancellation_policy_disclosure: text("shown at checkout"),
            cancellation_rebuttal: text("not cancelled"),
            customer_communication: text("file_comm"),
            customer_purchase_ip: text("203.0.113.7"),
            duplicate_charge_documentation: text("file_dup"),
            duplicate_charge_explanation: text("separate orders"),
            duplicate_charge_id: text("pay_2"),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard for `DISPUTE_EVIDENCE_REQUEST_NAMED`.
    #[test]
    fn evidence_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_evidence_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                DISPUTE_EVIDENCE_REQUEST_NAMED.contains(&key.as_str()),
                "DISPUTE_EVIDENCE_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or the extra-key collision guard silently stops \
                 covering this field"
            );
        }
    }

    #[test]
    fn evidence_validate_rejects_colliding_extra_key() {
        let mut req = DisputeEvidenceRequest::default();
        req.extra.insert("receipt".to_string(), json!("file_x"));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    #[test]
    fn evidence_round_trips_with_dispute_id_in_extra() {
        // `retrieve_evidence` deserializes the same struct that submit
        // serializes; the dispute_id travels in `extra` both ways.
        let mut req = DisputeEvidenceRequest {
            receipt: Some("file_receipt".to_string()),
            ..Default::default()
        };
        req.extra.insert("dispute_id".to_string(), json!("dp_1"));

        let wire = serde_json::to_string(&req).unwrap();
        let back: DisputeEvidenceRequest = serde_json::from_str(&wire).unwrap();
        assert_eq!(back.receipt.as_deref(), Some("file_receipt"));
        assert_eq!(back.extra["dispute_id"], "dp_1");
    }

    #[tokio::test]
    async fn submit_uses_post_and_attach_uses_put_on_the_evidence_path() {
        // The submit/attach pair differ ONLY by verb; a mutation collapsing
        // them to the same method must fail here.
        let (client, mock) = client_with(vec![Step::ok(DISPUTE_JSON), Step::ok(DISPUTE_JSON)]);
        let req = DisputeEvidenceRequest {
            receipt: Some("file_receipt".to_string()),
            ..Default::default()
        };
        client.disputes().submit_evidence(&req).await.unwrap();
        client.disputes().attach_evidence(&req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("POST", "https://api.test/disputes/evidence")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("PUT", "https://api.test/disputes/evidence")
        );
        assert_eq!(seen[1].body_json()["receipt"], "file_receipt");
    }

    #[tokio::test]
    async fn delete_evidence_sends_a_delete_with_a_body() {
        let (client, mock) = client_with(vec![Step::ok(DISPUTE_JSON)]);
        let mut req = DisputeEvidenceRequest::default();
        req.extra.insert("dispute_id".to_string(), json!("dp_1"));
        client.disputes().delete_evidence(&req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(seen[0].url, "https://api.test/disputes/evidence");
        assert_eq!(
            seen[0].body_json()["dispute_id"],
            "dp_1",
            "DELETE must still carry the identifying body"
        );
    }

    #[tokio::test]
    async fn retrieve_evidence_and_connector_fetch_hit_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"receipt":"file_receipt","dispute_id":"dp_1"}"#),
            Step::ok(DISPUTE_JSON),
        ]);
        let evidence = client.disputes().retrieve_evidence("dp_1").await.unwrap();
        assert_eq!(evidence.receipt.as_deref(), Some("file_receipt"));
        client
            .disputes()
            .fetch_from_connector("du_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/disputes/evidence/dp_1")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/disputes/du_1/fetch")
        );
    }
}