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
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
//! The `regions` resource: custom named country groups scoped to a shop
//! (business profile), used by the geo-aware payment-method availability
//! overrides.
//!
//! Every endpoint is scoped by `profile_id`, sent as `?profile_id=…`. Admin
//! (`sk_*`) access is required.

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::region::{
    BuiltInRegionGroupResponse, RegionCountriesResponse, RegionResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Create a region. `POST /regions?profile_id=`
    pub async fn create(
        &self,
        profile_id: &str,
        params: &RegionCreateRequest,
    ) -> Result<RegionResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/regions",
                Some(&body),
                &profile_query(profile_id),
                None,
            )
            .await
    }

    /// List all regions for a profile. `GET /regions/list?profile_id=`
    pub async fn list(&self, profile_id: &str) -> Result<Vec<RegionResponse>> {
        self.inner
            .request(
                HttpMethod::Get,
                "/regions/list",
                None,
                &profile_query(profile_id),
                None,
            )
            .await
    }

    /// List the built-in (global) region groups — EU, EEA, SEPA, LATAM, APAC.
    /// `GET /regions/groups`
    pub async fn groups(&self) -> Result<Vec<BuiltInRegionGroupResponse>> {
        self.inner
            .request(HttpMethod::Get, "/regions/groups", None, &[], None)
            .await
    }

    /// Retrieve a region by ID. `GET /regions/{region_id}?profile_id=`
    pub async fn retrieve(&self, region_id: &str, profile_id: &str) -> Result<RegionResponse> {
        let path = region_path(region_id);
        self.inner
            .request(
                HttpMethod::Get,
                &path,
                None,
                &profile_query(profile_id),
                None,
            )
            .await
    }

    /// Update a region. `PUT /regions/{region_id}?profile_id=`
    pub async fn update(
        &self,
        region_id: &str,
        profile_id: &str,
        params: &RegionUpdateRequest,
    ) -> Result<RegionResponse> {
        params.validate()?;
        let path = region_path(region_id);
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Put,
                &path,
                Some(&body),
                &profile_query(profile_id),
                None,
            )
            .await
    }

    /// Delete a region. `DELETE /regions/{region_id}?profile_id=`
    ///
    /// The API answers with a bare boolean.
    pub async fn delete(&self, region_id: &str, profile_id: &str) -> Result<bool> {
        let path = region_path(region_id);
        self.inner
            .request(
                HttpMethod::Delete,
                &path,
                None,
                &profile_query(profile_id),
                None,
            )
            .await
    }

    /// Get the countries that belong to a region.
    /// `GET /regions/{region_id}/countries?profile_id=`
    pub async fn countries(
        &self,
        region_id: &str,
        profile_id: &str,
    ) -> Result<RegionCountriesResponse> {
        let path = format!("{}/countries", region_path(region_id));
        self.inner
            .request(
                HttpMethod::Get,
                &path,
                None,
                &profile_query(profile_id),
                None,
            )
            .await
    }

    /// Replace the full country membership of a region.
    /// `PUT /regions/{region_id}/countries?profile_id=`
    pub async fn set_countries(
        &self,
        region_id: &str,
        profile_id: &str,
        params: &RegionSetCountriesRequest,
    ) -> Result<RegionCountriesResponse> {
        let path = format!("{}/countries", region_path(region_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Put,
                &path,
                Some(&body),
                &profile_query(profile_id),
                None,
            )
            .await
    }
}

/// `/regions/{region_id}`, percent-encoded.
fn region_path(region_id: &str) -> String {
    format!("/regions/{}", encode_segment(region_id))
}

/// The `?profile_id=…` scope every region endpoint but `groups` requires.
fn profile_query(profile_id: &str) -> Vec<(&'static str, String)> {
    vec![("profile_id", profile_id.to_string())]
}

/// Parameters for [`Regions::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RegionCreateRequest {
    /// Display name of the region.
    pub region_name: String,
    /// Short, unique code for the region, e.g. `"NORDICS"`.
    pub region_code: String,
    /// Free-form description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: 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 RegionCreateRequest {
    /// A create request for a region with the given name and code.
    pub fn new(region_name: impl Into<String>, region_code: impl Into<String>) -> Self {
        Self {
            region_name: region_name.into(),
            region_code: region_code.into(),
            ..Default::default()
        }
    }

    /// Set the region's description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// Names of `RegionCreateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const REGION_CREATE_REQUEST_NAMED: &[&str] = &["region_name", "region_code", "description"];

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

/// Parameters for [`Regions::update`]. Only the fields you set are sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct RegionUpdateRequest {
    /// New display name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region_name: Option<String>,
    /// New description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Whether the region is active.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl RegionUpdateRequest {
    /// An empty update; set the fields you want changed.
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Set the region's description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Activate or deactivate the region.
    #[must_use]
    pub fn is_active(mut self, is_active: bool) -> Self {
        self.is_active = Some(is_active);
        self
    }
}

/// Names of `RegionUpdateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const REGION_UPDATE_REQUEST_NAMED: &[&str] = &["region_name", "description", "is_active"];

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

/// Parameters for [`Regions::set_countries`]: the full replacement membership.
#[derive(Debug, Clone, Default, Serialize)]
pub struct RegionSetCountriesRequest {
    /// ISO 3166-1 alpha-2 country codes, e.g. `["SE", "NO", "DK"]`.
    pub countries: Vec<String>,
}

impl RegionSetCountriesRequest {
    /// A request replacing the region's membership with `countries`.
    pub fn new(countries: Vec<String>) -> Self {
        Self { countries }
    }
}

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

    const REGION_JSON: &str = r#"{
        "id": "reg_1",
        "profile_id": "pro_1",
        "region_name": "Nordics",
        "region_code": "NORDICS",
        "is_active": true,
        "created_at": "2024-01-01T00:00:00Z",
        "modified_at": "2024-01-02T00:00:00Z",
        "description": "SE/NO/DK",
        "surprise_field": 1
    }"#;
    const COUNTRIES_JSON: &str = r#"{"region_id":"reg_1","countries":["SE","NO"]}"#;

    #[tokio::test]
    async fn create_posts_to_regions_with_the_profile_scope() {
        let (client, mock) = client_with(vec![Step::ok(REGION_JSON)]);
        let params = RegionCreateRequest::new("Nordics", "NORDICS");
        let region = client.regions().create("pro_1", &params).await.unwrap();
        assert_eq!(region.id, "reg_1");
        assert_eq!(region.region_code, "NORDICS");
        assert_eq!(region.description.as_deref(), Some("SE/NO/DK"));
        assert!(region.is_active);
        // Unmodeled fields survive rather than breaking the decode.
        assert_eq!(region.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/regions?profile_id=pro_1");
        let body = seen[0].body_json();
        assert_eq!(body["region_name"], "Nordics");
        assert_eq!(body["region_code"], "NORDICS");
    }

    #[tokio::test]
    async fn list_gets_the_list_path_with_the_profile_scope() {
        let (client, mock) = client_with(vec![Step::ok(&format!("[{REGION_JSON}]"))]);
        let regions = client.regions().list("pro_1").await.unwrap();
        assert_eq!(regions[0].profile_id, "pro_1");

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

    #[tokio::test]
    async fn groups_gets_the_groups_path_unscoped() {
        // The built-in groups are global: a mutation adding a profile_id query
        // here fails.
        let (client, mock) = client_with(vec![Step::ok(
            r#"[{"code":"EU","name":"European Union","countries":["DE","FR"]}]"#,
        )]);
        let groups = client.regions().groups().await.unwrap();
        assert_eq!(groups[0].code, "EU");
        assert_eq!(groups[0].name, "European Union");
        assert_eq!(groups[0].countries, ["DE", "FR"]);

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

    #[tokio::test]
    async fn retrieve_encodes_the_region_id() {
        let (client, mock) = client_with(vec![Step::ok(REGION_JSON)]);
        client.regions().retrieve("reg/1", "pro_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/regions/reg%2F1?profile_id=pro_1"
        );
    }

    #[tokio::test]
    async fn update_puts_the_region_path_with_a_body() {
        let (client, mock) = client_with(vec![Step::ok(REGION_JSON)]);
        let params = RegionUpdateRequest::new()
            .region_name("Nordics EU")
            .is_active(false);
        client
            .regions()
            .update("reg_1", "pro_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/regions/reg_1?profile_id=pro_1"
        );
        let body = seen[0].body_json();
        assert_eq!(body["region_name"], "Nordics EU");
        assert_eq!(body["is_active"], false);
    }

    #[tokio::test]
    async fn delete_deletes_the_region_and_decodes_the_bare_boolean() {
        let (client, mock) = client_with(vec![Step::ok("true")]);
        let out = client.regions().delete("reg_1", "pro_1").await.unwrap();
        assert!(out);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/regions/reg_1?profile_id=pro_1"
        );
    }

    #[tokio::test]
    async fn countries_gets_the_countries_sub_path() {
        let (client, mock) = client_with(vec![Step::ok(COUNTRIES_JSON)]);
        let out = client.regions().countries("reg_1", "pro_1").await.unwrap();
        assert_eq!(out.region_id, "reg_1");
        assert_eq!(out.countries, ["SE", "NO"]);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/regions/reg_1/countries?profile_id=pro_1"
        );
    }

    #[tokio::test]
    async fn set_countries_puts_the_full_membership() {
        let (client, mock) = client_with(vec![Step::ok(COUNTRIES_JSON)]);
        let params = RegionSetCountriesRequest::new(vec!["SE".to_string(), "NO".to_string()]);
        let out = client
            .regions()
            .set_countries("reg_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(out.countries, ["SE", "NO"]);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/regions/reg_1/countries?profile_id=pro_1"
        );
        assert_eq!(seen[0].body_json()["countries"], json!(["SE", "NO"]));
    }

    /// Drift guard for `REGION_CREATE_REQUEST_NAMED`.
    #[test]
    fn region_create_request_named_fields_are_complete() {
        let req = RegionCreateRequest::new("Nordics", "NORDICS").description("SE/NO/DK");
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                REGION_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "REGION_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `REGION_UPDATE_REQUEST_NAMED`.
    #[test]
    fn region_update_request_named_fields_are_complete() {
        let req = RegionUpdateRequest::new()
            .region_name("Nordics")
            .description("SE/NO/DK")
            .is_active(true);
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                REGION_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "REGION_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn create_validate_rejects_colliding_extra_key() {
        let mut req = RegionCreateRequest::new("Nordics", "NORDICS");
        req.extra.insert("region_code".to_string(), json!("OTHER"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("region_code")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    #[test]
    fn update_validate_rejects_colliding_extra_key() {
        let mut req = RegionUpdateRequest::new();
        req.extra.insert("region_name".to_string(), json!("other"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("region_name")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }
}