delopay 0.4.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
//! The `customers` resource.

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::common::ListResponse;
use crate::core::models::customer::CustomerResponse;
use crate::core::models::mandate::MandateResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Create a customer.
    pub async fn create(&self, params: &CustomerCreateRequest) -> Result<CustomerResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/customers", Some(&body), &[], None)
            .await
    }

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

    /// Update a customer.
    pub async fn update(
        &self,
        customer_id: &str,
        params: &CustomerCreateRequest,
    ) -> Result<CustomerResponse> {
        params.validate()?;
        let path = format!("/customers/{}", encode_segment(customer_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a customer.
    pub async fn delete(&self, customer_id: &str) -> Result<CustomerResponse> {
        let path = format!("/customers/{}", encode_segment(customer_id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// List customers, optionally filtered by email, shop (`profile_id`), or
    /// project (`project_id`).
    pub async fn list(&self, params: Option<&CustomerListParams>) -> Result<Vec<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/customers/list", None, &query, None)
            .await
    }

    /// List customers with page and total counts. Same filters as
    /// [`list`](Self::list); the page count arrives in the envelope's `count`
    /// field, preserved in [`crate::ListResponse::extra`].
    pub async fn list_with_count(
        &self,
        params: Option<&CustomerListParams>,
    ) -> Result<ListResponse<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request(
                HttpMethod::Get,
                "/customers/list-with-count",
                None,
                &query,
                None,
            )
            .await
    }

    /// List customers scoped to the shop (business profile) the credential
    /// belongs to. Same filters as [`list`](Self::list); a `profile_id` /
    /// `project_id` outside that scope is rejected by the API.
    pub async fn list_by_profile(
        &self,
        params: Option<&CustomerListParams>,
    ) -> Result<Vec<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request(
                HttpMethod::Get,
                "/customers/profile/list",
                None,
                &query,
                None,
            )
            .await
    }

    /// Profile-scoped variant of [`list_with_count`](Self::list_with_count).
    pub async fn list_by_profile_with_count(
        &self,
        params: Option<&CustomerListParams>,
    ) -> Result<ListResponse<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request(
                HttpMethod::Get,
                "/customers/profile/list-with-count",
                None,
                &query,
                None,
            )
            .await
    }

    /// List the mandates held against a customer.
    pub async fn list_mandates(&self, customer_id: &str) -> Result<Vec<MandateResponse>> {
        let path = format!("/customers/{}/mandates", encode_segment(customer_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }
}

/// Filter / pagination parameters for [`Customers::list`],
/// [`Customers::list_with_count`] and their profile-scoped variants
/// [`Customers::list_by_profile`] and [`Customers::list_by_profile_with_count`].
#[derive(Debug, Clone, Default)]
pub struct CustomerListParams {
    /// Maximum number of customers to return.
    pub limit: Option<i64>,
    /// Number of customers to skip.
    pub offset: Option<i64>,
    /// Only customers with this email.
    pub email: Option<String>,
    /// Only customers who have transacted in this shop (business profile).
    pub profile_id: Option<String>,
    /// Only customers who have transacted in one of these shops. Unions with
    /// [`profile_id`](Self::profile_id) and [`project_id`](Self::project_id) —
    /// a customer matches if they transacted in any of the resolved shops.
    ///
    /// Every id must belong to the calling merchant, otherwise the request is
    /// rejected with `AccessForbidden`.
    pub profile_ids: Vec<String>,
    /// Only customers who have transacted in this project (all its shops).
    pub project_id: Option<String>,
}

impl CustomerListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        if let Some(v) = &self.email {
            q.push(("email", v.clone()));
        }
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        // One comma-separated value, not repeated keys: the customers endpoints
        // cannot parse `?profile_ids=a&profile_ids=b` and fail the whole
        // request rather than ignoring the second id. An empty list means "no
        // shop filter", which is the absent key.
        if !self.profile_ids.is_empty() {
            q.push(("profile_ids", self.profile_ids.join(",")));
        }
        if let Some(v) = &self.project_id {
            q.push(("project_id", v.clone()));
        }
        q
    }

    /// Filter by several shops at once.
    #[must_use]
    pub fn profile_ids<I, S>(mut self, profile_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.profile_ids = profile_ids.into_iter().map(Into::into).collect();
        self
    }
}

/// Parameters for [`Customers::create`] and [`Customers::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CustomerCreateRequest {
    /// Provide your own customer ID (acts as an idempotency key server-side).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    /// Customer's full name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Customer's email address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// Customer's phone number (digits only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone: Option<String>,
    /// Phone country code (e.g. `"+44"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_country_code: Option<String>,
    /// Internal notes about the customer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Default billing/shipping address (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<Value>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `CustomerCreateRequest`'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 CUSTOMER_CREATE_REQUEST_NAMED: &[&str] = &[
    "customer_id",
    "name",
    "email",
    "phone",
    "phone_country_code",
    "description",
    "address",
    "metadata",
];

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

impl CustomerCreateRequest {
    /// An empty request; set the fields you need.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the customer's email.
    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    /// Set the customer's name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the customer's phone (digits) and country code.
    pub fn phone(mut self, phone: impl Into<String>, country_code: impl Into<String>) -> Self {
        self.phone = Some(phone.into());
        self.phone_country_code = Some(country_code.into());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Every optional field populated so serialization emits the full key set.
    fn full_customer_create_request() -> CustomerCreateRequest {
        CustomerCreateRequest {
            customer_id: Some("cus_1".to_string()),
            name: Some("Ada Lovelace".to_string()),
            email: Some("ada@example.com".to_string()),
            phone: Some("5551234".to_string()),
            phone_country_code: Some("+44".to_string()),
            description: Some("VIP customer".to_string()),
            address: Some(json!({"country": "GB"})),
            metadata: Some(json!({"tier": "gold"})),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard: catches a new field added to `CustomerCreateRequest`
    /// without a matching update to `CUSTOMER_CREATE_REQUEST_NAMED`.
    #[test]
    fn customer_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_customer_create_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                CUSTOMER_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "CUSTOMER_CREATE_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or CustomerCreateRequest's extra-key collision guard \
                 will silently stop covering this field"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_key_colliding_with_named_field() {
        let mut req = CustomerCreateRequest::new().email("ada@example.com");
        req.extra.insert("name".to_string(), json!("collide"));

        let err = req.validate().unwrap_err();
        match err {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("name")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    use crate::http::mock::{Step, client_with};

    #[tokio::test]
    async fn list_serializes_shop_filters() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        let params = CustomerListParams {
            limit: Some(10),
            profile_id: Some("pro_1".to_string()),
            ..Default::default()
        };
        client.customers().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/list?limit=10&profile_id=pro_1"
        );
    }

    /// `profile_ids` must go out as ONE comma-separated value. Repeated keys
    /// (`?profile_ids=a&profile_ids=b`) fail the whole request server-side
    /// rather than dropping the second id, so a mutation pushing one pair per
    /// id must be caught here.
    #[tokio::test]
    async fn list_sends_profile_ids_as_one_comma_separated_value() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        let params = CustomerListParams::default().profile_ids(["pro_1", "pro_2"]);
        client.customers().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/list?profile_ids=pro_1,pro_2"
        );
    }

    /// An empty list means "no shop filter", which is the absent key — not an
    /// empty `profile_ids=` the server would have to interpret.
    #[tokio::test]
    async fn list_omits_an_empty_profile_ids_filter() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        let params = CustomerListParams::default().profile_ids(Vec::<String>::new());
        client.customers().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/customers/list");
    }

    #[tokio::test]
    async fn list_with_count_hits_its_path_and_keeps_count_in_extra() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"count":1,"total_count":9,"data":[{"customer_id":"cus_1"}]}"#,
        )]);
        let out = client.customers().list_with_count(None).await.unwrap();
        assert_eq!(out.total_count, Some(9));
        assert_eq!(out.extra["count"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/customers/list-with-count");
    }

    #[tokio::test]
    async fn profile_scoped_lists_hit_the_profile_paths() {
        // These differ from `list` / `list_with_count` ONLY by path segment;
        // a mutation dropping `/profile` must fail here.
        let (client, mock) = client_with(vec![
            Step::ok("[]"),
            Step::ok(r#"{"count":1,"total_count":9,"data":[]}"#),
        ]);
        let params = CustomerListParams {
            limit: Some(10),
            email: Some("ada@example.com".to_string()),
            ..Default::default()
        };
        client
            .customers()
            .list_by_profile(Some(&params))
            .await
            .unwrap();
        let out = client
            .customers()
            .list_by_profile_with_count(None)
            .await
            .unwrap();
        assert_eq!(out.total_count, Some(9));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            (
                "GET",
                "https://api.test/customers/profile/list?limit=10&email=ada@example.com"
            )
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/customers/profile/list-with-count")
        );
    }

    #[tokio::test]
    async fn list_mandates_gets_the_customer_mandates_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"[{"mandate_id":"man_1","status":"active"}]"#,
        )]);
        let out = client.customers().list_mandates("cus_1").await.unwrap();
        assert_eq!(out[0].mandate_id, "man_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/customers/cus_1/mandates");
    }
}