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
//! The `paypal_disputes` resource: PayPal seller cases.
//!
//! PayPal raises a seller case for sales this platform never processed —
//! external and subscription sales included — so these cases are read from
//! PayPal rather than from DeloPay's own dispute records, and are kept apart
//! from the [`disputes`](crate::resources::disputes) resource.
//!
//! Every operation honours the caller's connector-account grants: a case on an
//! account the caller was not granted is not listed and cannot be acted on.

use std::sync::Arc;

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

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::paypal_dispute::{
    PaypalDisputeActionRecord, PaypalDisputeActionResponse, PaypalDisputeCase,
    PaypalDisputeDocument, PaypalDisputeImportResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// List seller cases (`GET /disputes/paypal/cases`).
    pub async fn list(
        &self,
        params: Option<&PaypalDisputeListParams>,
    ) -> Result<Vec<PaypalDisputeCase>> {
        let query = params
            .map(PaypalDisputeListParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(
                HttpMethod::Get,
                "/disputes/paypal/cases",
                None,
                &query,
                None,
            )
            .await
    }

    /// Retrieve one seller case (`GET /disputes/paypal/cases/{case_id}`).
    ///
    /// `force_sync` re-reads the case from PayPal before answering. It costs a
    /// call to PayPal, so leave it off for a list row and turn it on when a
    /// decision hangs on the case being current — after acting on it, above all.
    pub async fn retrieve(&self, case_id: &str, force_sync: bool) -> Result<PaypalDisputeCase> {
        let path = format!("/disputes/paypal/cases/{}", encode_segment(case_id));
        let query = [("force_sync", force_sync.to_string())];
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// The stored versions of one case, newest first
    /// (`GET /disputes/paypal/cases/{case_id}/history`).
    ///
    /// Each entry is the case as it stood at one refresh, so a seller can see
    /// what PayPal changed and when.
    pub async fn history(&self, case_id: &str, offset: u64) -> Result<Vec<PaypalDisputeCase>> {
        let path = format!("/disputes/paypal/cases/{}/history", encode_segment(case_id));
        let query = [("offset", offset.to_string())];
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// The actions already taken on one case, newest first
    /// (`GET /disputes/paypal/cases/{case_id}/actions`).
    pub async fn actions(
        &self,
        case_id: &str,
        offset: u64,
    ) -> Result<Vec<PaypalDisputeActionRecord>> {
        let path = format!("/disputes/paypal/cases/{}/actions", encode_segment(case_id));
        let query = [("offset", offset.to_string())];
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Download one document attached to a case
    /// (`POST /disputes/paypal/cases/{case_id}/documents/download`).
    ///
    /// `document_url` comes from the case's own
    /// [`details`](PaypalDisputeCase::details): PayPal's document URLs are
    /// signed and short-lived, and are fetched through this route so the
    /// seller's PayPal credentials never leave the server.
    pub async fn download(
        &self,
        case_id: &str,
        document_url: &str,
    ) -> Result<PaypalDisputeDocument> {
        let path = format!(
            "/disputes/paypal/cases/{}/documents/download",
            encode_segment(case_id)
        );
        let body = to_json_vec(&PaypalDisputeDownloadRequest { document_url })?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Import cases from PayPal for one connector account
    /// (`POST /disputes/paypal/import`).
    ///
    /// One call imports one page. Follow
    /// [`next_page_token`](PaypalDisputeImportResponse::next_page_token) until
    /// it is absent; absent means complete, not "retry the last token".
    pub async fn import(
        &self,
        params: &PaypalDisputeImportRequest,
    ) -> Result<PaypalDisputeImportResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/disputes/paypal/import",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Take a seller action on a case
    /// (`POST /disputes/paypal/cases/{case_id}/actions`).
    ///
    /// The backend checks the account's current PayPal permissions and
    /// deduplicates on [`request_id`](PaypalDisputeActionRequest::request_id),
    /// so re-sending the *same* request id after a lost response is safe and
    /// is the correct retry.
    ///
    /// An **unknown** outcome needs reconciliation — re-read the case with a
    /// forced sync — not a new request id: a second id is a second action, and
    /// on `accept_claim` that means conceding twice.
    pub async fn act(
        &self,
        case_id: &str,
        params: &PaypalDisputeActionRequest,
    ) -> Result<PaypalDisputeActionResponse> {
        let path = format!("/disputes/paypal/cases/{}/actions", encode_segment(case_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }
}

/// Filters for [`PaypalDisputes::list`]. All fields are optional.
#[derive(Debug, Clone, Default)]
pub struct PaypalDisputeListParams {
    /// Only cases on this connector account.
    pub merchant_connector_id: Option<String>,
    /// Only cases mapped to this shop.
    pub profile_id: Option<String>,
    /// Only cases mapped to this project.
    pub project_id: Option<String>,
    /// `true` for sandbox cases, `false` for live.
    pub test_mode: Option<bool>,
    /// Only cases in this PayPal status.
    pub status: Option<String>,
    /// Only cases at this PayPal stage.
    pub stage: Option<String>,
    /// Free-text search across the case's identifiers.
    pub search: Option<String>,
    /// Page size.
    pub limit: Option<i64>,
    /// Rows to skip.
    pub offset: Option<i64>,
}

impl PaypalDisputeListParams {
    /// Empty filters.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = &self.merchant_connector_id {
            q.push(("merchant_connector_id", v.clone()));
        }
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        if let Some(v) = &self.project_id {
            q.push(("project_id", v.clone()));
        }
        if let Some(v) = self.test_mode {
            q.push(("test_mode", v.to_string()));
        }
        if let Some(v) = &self.status {
            q.push(("status", v.clone()));
        }
        if let Some(v) = &self.stage {
            q.push(("stage", v.clone()));
        }
        if let Some(v) = &self.search {
            q.push(("search", v.clone()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// Body of [`PaypalDisputes::import`].
#[derive(Debug, Clone, Serialize)]
pub struct PaypalDisputeImportRequest {
    /// The connector account to import from.
    pub merchant_connector_id: String,
    /// Which credential set to read: `true` for sandbox, `false` for live.
    pub test_mode: bool,
    /// Only cases created at or after this RFC 3339 timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<String>,
    /// The token from the previous page's response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_page_token: Option<String>,
}

impl PaypalDisputeImportRequest {
    /// Import from one connector account's live or sandbox credentials.
    pub fn new(merchant_connector_id: impl Into<String>, test_mode: bool) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            test_mode,
            start_time: None,
            next_page_token: None,
        }
    }

    /// Only import cases created at or after this RFC 3339 timestamp.
    #[must_use]
    pub fn start_time(mut self, start_time: impl Into<String>) -> Self {
        self.start_time = Some(start_time.into());
        self
    }

    /// Continue an import from the previous page's token.
    #[must_use]
    pub fn next_page_token(mut self, token: impl Into<String>) -> Self {
        self.next_page_token = Some(token.into());
        self
    }
}

/// Body of [`PaypalDisputes::act`].
#[derive(Debug, Clone, Serialize)]
pub struct PaypalDisputeActionRequest {
    /// Which action to take. Send one the case actually offers in
    /// [`available_actions`](PaypalDisputeCase::available_actions).
    pub action: String,
    /// The caller's own id for this action. The backend deduplicates on it, so
    /// **reuse it when retrying** a request whose response was lost, and mint a
    /// new one only for a genuinely new action.
    pub request_id: String,
    /// The action's payload, in PayPal's own shape for that action.
    pub data: Value,
    /// Files to attach — evidence, a shipping document.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub documents: Vec<PaypalDisputeDocument>,
}

impl PaypalDisputeActionRequest {
    /// Take `action` under `request_id`, with `data` in PayPal's shape for it.
    pub fn new(action: impl Into<String>, request_id: impl Into<String>, data: Value) -> Self {
        Self {
            action: action.into(),
            request_id: request_id.into(),
            data,
            documents: Vec::new(),
        }
    }

    /// Attach a document to the action.
    #[must_use]
    pub fn document(mut self, document: PaypalDisputeDocument) -> Self {
        self.documents.push(document);
        self
    }

    /// Replace the action's attached documents.
    #[must_use]
    pub fn documents(mut self, documents: Vec<PaypalDisputeDocument>) -> Self {
        self.documents = documents;
        self
    }
}

/// Body of [`PaypalDisputes::download`].
#[derive(Debug, Serialize)]
struct PaypalDisputeDownloadRequest<'a> {
    document_url: &'a str,
}

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

    const CASE_JSON: &str = r#"{
        "case_id": "PP-D-1",
        "connector_dispute_id": "PP-D-1",
        "merchant_connector_id": "mca_1",
        "payment_id": null,
        "amount": "49.99",
        "currency": "USD",
        "status": "WAITING_FOR_SELLER_RESPONSE",
        "available_actions": ["provide_evidence", "accept_claim"],
        "origin": "bank_card_issuer",
        "category": "bank_chargeback"
    }"#;

    /// A case may describe a sale this platform never processed, which is why
    /// `payment_id` is optional, and the money stays a string. Mutation: type
    /// `amount` as `i64` — deserialization fails and the test errors out.
    #[tokio::test]
    async fn retrieve_reads_a_case_with_no_local_payment() {
        let (client, mock) = client_with(vec![Step::ok(CASE_JSON)]);
        let out = client
            .paypal_disputes()
            .retrieve("PP-D-1", true)
            .await
            .unwrap();

        assert_eq!(out.payment_id, None);
        assert_eq!(out.amount.as_deref(), Some("49.99"));
        assert_eq!(out.available_actions.len(), 2);
        assert_eq!(out.origin.as_deref(), Some("bank_card_issuer"));
        assert_eq!(out.category.as_deref(), Some("bank_chargeback"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/paypal/cases/PP-D-1?force_sync=true"
        );
    }

    /// An action is deduplicated on the caller's own request id, so the id
    /// must reach the body verbatim. Mutation: rename the field to
    /// `idempotency_key` — the body assertion fails, and a retry would concede
    /// a case twice.
    #[tokio::test]
    async fn act_posts_the_action_under_its_request_id() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"request_id":"req_1","outcome":"accepted","case":null}"#,
        )]);
        let out = client
            .paypal_disputes()
            .act(
                "PP-D-1",
                &PaypalDisputeActionRequest::new(
                    "accept_claim",
                    "req_1",
                    json!({"note": "out of stock"}),
                ),
            )
            .await
            .unwrap();

        assert_eq!(out.outcome.as_deref(), Some("accepted"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/paypal/cases/PP-D-1/actions"
        );
        assert_eq!(seen[0].body_json()["request_id"], "req_1");
        assert_eq!(seen[0].body_json()["action"], "accept_claim");
        // No documents attached: the key stays off the wire entirely.
        assert!(seen[0].body_json().get("documents").is_none());
    }

    /// The import pages through PayPal on its own token. Mutation: read the
    /// token from `next_offset` — the follow-up assertion fails and an import
    /// would stop after one page.
    #[tokio::test]
    async fn import_follows_the_page_token() {
        let (client, mock) =
            client_with(vec![Step::ok(r#"{"cases":[],"next_page_token":"tok_2"}"#)]);
        let out = client
            .paypal_disputes()
            .import(
                &PaypalDisputeImportRequest::new("mca_1", false).start_time("2026-09-01T00:00:00Z"),
            )
            .await
            .unwrap();

        assert_eq!(out.next_page_token.as_deref(), Some("tok_2"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/disputes/paypal/import");
        assert_eq!(seen[0].body_json()["test_mode"], false);
        assert_eq!(seen[0].body_json()["start_time"], "2026-09-01T00:00:00Z");
    }
}