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
//! The `shop_labels` resource: the merchant's own tags for grouping shops,
//! for example by industry, brand or region.
//!
//! A shop can carry several labels, and a label is shared by every shop of
//! the merchant. Labels are separate from projects and change nothing about
//! a shop's project, payments or routing.
//!
//! Reading needs the `Account` area at `Read`; every change needs `Write`. A
//! caller limited to one shop may create labels and set its own shop's
//! labels. Labels of one merchant are never visible to another.
//!
//! No write here carries an idempotency key, not even the client-wide one
//! from [`crate::Delopay::with_idempotency_key`]: the API does not
//! deduplicate them, so they are not replayed on a network error or a 5xx.

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::shop_label::{
    ShopLabelDeleteResponse, ShopLabelResponse, ShopLabelsResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Every label of the merchant, ordered by name, each with the IDs of
    /// the shops that carry it. A caller limited to one shop sees every
    /// label but only its own shop in `profile_ids`.
    ///
    /// `GET /account/{merchant_id}/business-profile/labels`
    pub async fn list(&self, merchant_id: &str) -> Result<Vec<ShopLabelResponse>> {
        self.inner
            .request(HttpMethod::Get, &labels_path(merchant_id), None, &[], None)
            .await
    }

    /// Create a label. The name is trimmed and inner whitespace collapsed; a
    /// name that differs from an existing label only in letter case is
    /// refused (`IR_38`). A merchant holds at most 200 labels.
    ///
    /// `POST /account/{merchant_id}/business-profile/labels`
    pub async fn create(
        &self,
        merchant_id: &str,
        params: &ShopLabelCreateRequest,
    ) -> Result<ShopLabelResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                &labels_path(merchant_id),
                Some(&body),
                None,
            )
            .await
    }

    /// Rename a label on every shop that carries it, under the same name
    /// rules as [`create`](Self::create). Renaming changes every shop that
    /// carries the label, so a caller limited to one shop may not do it.
    ///
    /// `PATCH /account/{merchant_id}/business-profile/labels/{label_id}`
    pub async fn update(
        &self,
        merchant_id: &str,
        label_id: &str,
        params: &ShopLabelUpdateRequest,
    ) -> Result<ShopLabelResponse> {
        params.validate()?;
        let path = label_path(merchant_id, label_id);
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Patch, &path, Some(&body), None)
            .await
    }

    /// Delete a label and remove it from every shop. The shops are
    /// unchanged. A caller limited to one shop may not do it.
    ///
    /// `DELETE /account/{merchant_id}/business-profile/labels/{label_id}`
    pub async fn delete(
        &self,
        merchant_id: &str,
        label_id: &str,
    ) -> Result<ShopLabelDeleteResponse> {
        let path = label_path(merchant_id, label_id);
        self.inner
            .request_body_keyed(HttpMethod::Delete, &path, None, None)
            .await
    }

    /// Replace the labels of one shop: `label_ids` is the complete set
    /// afterwards, so a label left out is removed from the shop and an empty
    /// list removes them all. At most 20 per shop.
    ///
    /// `PUT /account/{merchant_id}/business-profile/{profile_id}/labels`
    pub async fn set_for_shop(
        &self,
        merchant_id: &str,
        profile_id: &str,
        params: &ShopLabelsSetRequest,
    ) -> Result<ShopLabelsResponse> {
        params.validate()?;
        let path = format!(
            "/account/{}/business-profile/{}/labels",
            encode_segment(merchant_id),
            encode_segment(profile_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Put, &path, Some(&body), None)
            .await
    }
}

/// `/account/{merchant_id}/business-profile/labels`, percent-encoded.
fn labels_path(merchant_id: &str) -> String {
    format!(
        "/account/{}/business-profile/labels",
        encode_segment(merchant_id)
    )
}

/// `/account/{merchant_id}/business-profile/labels/{label_id}`,
/// percent-encoded.
fn label_path(merchant_id: &str, label_id: &str) -> String {
    format!("{}/{}", labels_path(merchant_id), encode_segment(label_id))
}

/// Parameters for [`ShopLabels::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ShopLabelUpdateRequest {
    /// The new name, under the same rules as on create.
    pub name: String,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ShopLabelUpdateRequest {
    /// A rename to `name`.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ..Default::default()
        }
    }
}

/// Names of `ShopLabelUpdateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const SHOP_LABEL_UPDATE_REQUEST_NAMED: &[&str] = &["name"];

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

/// Parameters for [`ShopLabels::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ShopLabelCreateRequest {
    /// The label's name, 1 to 64 characters.
    pub name: String,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ShopLabelCreateRequest {
    /// A create request for a label with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ..Default::default()
        }
    }
}

/// Names of `ShopLabelCreateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const SHOP_LABEL_CREATE_REQUEST_NAMED: &[&str] = &["name"];

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

/// Parameters for [`ShopLabels::set_for_shop`]: the shop's complete set of
/// labels afterwards.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ShopLabelsSetRequest {
    /// Labels of this merchant, at most 20. Always sent, so an empty list
    /// removes every label from the shop.
    pub label_ids: Vec<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ShopLabelsSetRequest {
    /// A request leaving the shop with exactly `label_ids`.
    pub fn new(label_ids: Vec<String>) -> Self {
        Self {
            label_ids,
            ..Default::default()
        }
    }
}

/// Names of `ShopLabelsSetRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const SHOP_LABELS_SET_REQUEST_NAMED: &[&str] = &["label_ids"];

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

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

    const LABEL_JSON: &str = r#"{
        "label_id": "lbl_1",
        "name": "Gaming",
        "profile_ids": ["pro_1", "pro_2"],
        "surprise_field": 1
    }"#;

    #[tokio::test]
    async fn list_gets_the_labels_path() {
        let (client, mock) = client_with(vec![Step::ok(&format!("[{LABEL_JSON}]"))]);
        let labels = client.shop_labels().list("mer/1").await.unwrap();
        assert_eq!(labels[0].label_id, "lbl_1");
        assert_eq!(labels[0].profile_ids, ["pro_1", "pro_2"]);
        assert_eq!(labels[0].extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer%2F1/business-profile/labels"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn create_posts_the_name_to_the_labels_path() {
        let (client, mock) = client_with(vec![Step::ok(LABEL_JSON)]);
        let label = client
            .shop_labels()
            .create("mer_1", &ShopLabelCreateRequest::new("Gaming"))
            .await
            .unwrap();
        assert_eq!(label.name, "Gaming");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/business-profile/labels"
        );
        assert_eq!(seen[0].body_json(), json!({"name": "Gaming"}));
    }

    #[tokio::test]
    async fn set_for_shop_puts_the_complete_set_even_when_empty() {
        let (client, mock) = client_with(vec![
            Step::ok(
                r#"{"profile_id":"pro_1","labels":[{"label_id":"lbl_1","name":"Gaming"}],"surprise_field":1}"#,
            ),
            Step::ok(r#"{"profile_id":"pro_1","labels":[]}"#),
        ]);
        let labels = client.shop_labels();
        let out = labels
            .set_for_shop(
                "mer_1",
                "pro/1",
                &ShopLabelsSetRequest::new(vec!["lbl_1".to_string()]),
            )
            .await
            .unwrap();
        assert_eq!(out.profile_id, "pro_1");
        assert_eq!(out.labels[0].name, "Gaming");
        assert_eq!(out.extra["surprise_field"], 1);
        let cleared = labels
            .set_for_shop("mer_1", "pro/1", &ShopLabelsSetRequest::new(Vec::new()))
            .await
            .unwrap();
        assert!(cleared.labels.is_empty());

        let seen = mock.seen.lock().unwrap();
        for step in seen.iter() {
            assert_eq!(step.method, "PUT");
            assert_eq!(
                step.url,
                "https://api.test/account/mer_1/business-profile/pro%2F1/labels"
            );
        }
        assert_eq!(seen[0].body_json(), json!({"label_ids": ["lbl_1"]}));
        // An empty set is the request that removes every label: it must be
        // sent, not skipped.
        assert_eq!(seen[1].body_json(), json!({"label_ids": []}));
    }

    #[tokio::test]
    async fn update_patches_and_delete_deletes_the_label_path() {
        let (client, mock) = client_with(vec![
            Step::ok(LABEL_JSON),
            Step::ok(r#"{"label_id":"lbl_1","deleted":true,"surprise_field":1}"#),
        ]);
        let labels = client.shop_labels();
        let renamed = labels
            .update("mer_1", "lbl/1", &ShopLabelUpdateRequest::new("Games"))
            .await
            .unwrap();
        assert_eq!(renamed.label_id, "lbl_1");
        let deleted = labels.delete("mer_1", "lbl/1").await.unwrap();
        assert!(deleted.deleted);
        assert_eq!(deleted.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        for step in seen.iter() {
            assert_eq!(
                step.url,
                "https://api.test/account/mer_1/business-profile/labels/lbl%2F1"
            );
        }
        assert_eq!(seen[0].method, "PATCH");
        assert_eq!(seen[0].body_json(), json!({"name": "Games"}));
        assert_eq!(seen[1].method, "DELETE");
        assert!(seen[1].body.is_none());
    }

    /// Drift guard for `SHOP_LABEL_UPDATE_REQUEST_NAMED`.
    #[test]
    fn shop_label_update_request_named_fields_are_complete() {
        let value = serde_json::to_value(ShopLabelUpdateRequest::new("Games")).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                SHOP_LABEL_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "SHOP_LABEL_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
        let mut colliding = ShopLabelUpdateRequest::new("Games");
        colliding.extra.insert("name".to_string(), json!("x"));
        assert!(colliding.validate().is_err());
    }

    /// Drift guard for `SHOP_LABEL_CREATE_REQUEST_NAMED`.
    #[test]
    fn shop_label_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(ShopLabelCreateRequest::new("Gaming")).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                SHOP_LABEL_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "SHOP_LABEL_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `SHOP_LABELS_SET_REQUEST_NAMED`.
    #[test]
    fn shop_labels_set_request_named_fields_are_complete() {
        let value =
            serde_json::to_value(ShopLabelsSetRequest::new(vec!["lbl_1".to_string()])).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                SHOP_LABELS_SET_REQUEST_NAMED.contains(&key.as_str()),
                "SHOP_LABELS_SET_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_keys_colliding_with_named_fields() {
        let mut create = ShopLabelCreateRequest::new("Gaming");
        create.extra.insert("name".to_string(), json!("Other"));
        match create.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("name")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        let mut set = ShopLabelsSetRequest::new(Vec::new());
        set.extra.insert("label_ids".to_string(), json!([]));
        match set.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("label_ids")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    /// A label write never carries an idempotency key, not even the
    /// client-wide one, so a 5xx is not replayed. Mutation: switch a call
    /// site back to `request(.., None)` — the header appears and the call
    /// count grows.
    #[tokio::test]
    async fn label_writes_ignore_the_client_wide_idempotency_key() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, "{}"),
                Step::status(503, "{}"),
                Step::status(503, "{}"),
                Step::status(503, "{}"),
                Step::ok("{}"),
            ],
            2,
        );
        let labels = client.with_idempotency_key("client-key").shop_labels();
        assert!(
            labels
                .create("mer_1", &ShopLabelCreateRequest::new("Gaming"))
                .await
                .is_err()
        );
        assert!(
            labels
                .update("mer_1", "lbl_1", &ShopLabelUpdateRequest::new("Games"))
                .await
                .is_err()
        );
        assert!(labels.delete("mer_1", "lbl_1").await.is_err());
        assert!(
            labels
                .set_for_shop("mer_1", "pro_1", &ShopLabelsSetRequest::new(Vec::new()))
                .await
                .is_err()
        );
        let seen = mock.seen.lock().unwrap();
        // One attempt per write: none was replayed.
        assert_eq!(seen.len(), 4);
        assert!(seen.iter().all(|step| !step.had_idempotency_key()));
    }
}