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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! The `checkout_templates` resource: a shop's payment methods, behaviour and
//! smart routing, defined once for the merchant and used in many shops.
//!
//! A template is edited where a shop is: its own profile (`template_id`) has a
//! checkout layout, behaviour settings, routing configurations and connector
//! accounts, written with the checkout-methods, checkout-branding, routing and
//! connector calls. Its changes reach the shops on it when
//! [`apply`](CheckoutTemplates::apply) runs. While a shop is on a template,
//! its own payment methods, behaviour and routing cannot be changed; its
//! appearance stays its own.
//!
//! Every method but [`of_shop`](CheckoutTemplates::of_shop) needs a
//! merchant-level role that sees every connector and payment;
//! [`create`](CheckoutTemplates::create), [`assign`](CheckoutTemplates::assign)
//! and [`apply`](CheckoutTemplates::apply) also need routing and connector
//! write.

use std::sync::Arc;

use serde::Serialize;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::checkout_template::{
    CheckoutTemplateApplyResponse, CheckoutTemplateListResponse, CheckoutTemplateOfShopResponse,
    CheckoutTemplateResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// The merchant's templates, each with the shops on it and whether each
    /// runs the template's current settings.
    /// `GET /checkout-templates/{merchant_id}`
    pub async fn list(&self, merchant_id: &str) -> Result<CheckoutTemplateListResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                &merchant_path(merchant_id),
                None,
                &[],
                None,
            )
            .await
    }

    /// Create a template, empty or copied from a shop's current settings. The
    /// shop copied from is not changed.
    /// `POST /checkout-templates/{merchant_id}`
    pub async fn create(
        &self,
        merchant_id: &str,
        params: &CheckoutTemplateCreateRequest,
    ) -> Result<CheckoutTemplateResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Post,
                &merchant_path(merchant_id),
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Retrieve a template. `GET /checkout-templates/{merchant_id}/{template_id}`
    pub async fn retrieve(
        &self,
        merchant_id: &str,
        template_id: &str,
    ) -> Result<CheckoutTemplateResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                &template_path(merchant_id, template_id),
                None,
                &[],
                None,
            )
            .await
    }

    /// Rename a template. A name another template of the merchant holds is
    /// refused.
    /// `POST /checkout-templates/{merchant_id}/{template_id}`
    pub async fn rename(
        &self,
        merchant_id: &str,
        template_id: &str,
        params: &CheckoutTemplateUpdateRequest,
    ) -> Result<CheckoutTemplateResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Post,
                &template_path(merchant_id, template_id),
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Delete a template. Refused while a shop is on it.
    /// `DELETE /checkout-templates/{merchant_id}/{template_id}`
    pub async fn delete(
        &self,
        merchant_id: &str,
        template_id: &str,
    ) -> Result<CheckoutTemplateResponse> {
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Delete,
                &template_path(merchant_id, template_id),
                None,
                &[],
                None,
            )
            .await
    }

    /// Put shops on the template and copy its settings into them; a shop on
    /// another template moves. Each shop is reported on its own: one with
    /// `blockers` is left unchanged. `dry_run` changes nothing and reports
    /// what would change.
    /// `POST /checkout-templates/{merchant_id}/{template_id}/shops`
    pub async fn assign(
        &self,
        merchant_id: &str,
        template_id: &str,
        params: &CheckoutTemplateAssignRequest,
    ) -> Result<CheckoutTemplateApplyResponse> {
        let path = format!("{}/shops", template_path(merchant_id, template_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Take a shop off the template. It keeps every setting it has, as its
    /// own. `reason` is recorded in the audit log.
    /// `DELETE /checkout-templates/{merchant_id}/{template_id}/shops/{profile_id}`
    pub async fn unassign(
        &self,
        merchant_id: &str,
        template_id: &str,
        profile_id: &str,
        reason: Option<&str>,
    ) -> Result<CheckoutTemplateResponse> {
        let path = format!(
            "{}/shops/{}",
            template_path(merchant_id, template_id),
            encode_segment(profile_id)
        );
        let query: Vec<(&str, String)> = reason
            .map(|reason| vec![("reason", reason.to_string())])
            .unwrap_or_default();
        self.inner
            .request_body_keyed_with_query(HttpMethod::Delete, &path, None, &query, None)
            .await
    }

    /// Copy the template's current settings into its shops, all or the ones
    /// named.
    /// `POST /checkout-templates/{merchant_id}/{template_id}/apply`
    pub async fn apply(
        &self,
        merchant_id: &str,
        template_id: &str,
        params: &CheckoutTemplateApplyRequest,
    ) -> Result<CheckoutTemplateApplyResponse> {
        let path = format!("{}/apply", template_path(merchant_id, template_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// The template a shop is on, if any. Readable by the shop's own members.
    /// `GET /checkout-templates/{merchant_id}/shops/{profile_id}`
    pub async fn of_shop(
        &self,
        merchant_id: &str,
        profile_id: &str,
    ) -> Result<CheckoutTemplateOfShopResponse> {
        let path = format!(
            "{}/shops/{}",
            merchant_path(merchant_id),
            encode_segment(profile_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }
}

/// `/checkout-templates/{merchant_id}`, percent-encoded.
fn merchant_path(merchant_id: &str) -> String {
    format!("/checkout-templates/{}", encode_segment(merchant_id))
}

/// `/checkout-templates/{merchant_id}/{template_id}`, percent-encoded.
fn template_path(merchant_id: &str, template_id: &str) -> String {
    format!(
        "{}/{}",
        merchant_path(merchant_id),
        encode_segment(template_id)
    )
}

/// Body of [`CheckoutTemplates::create`].
///
/// The API refuses unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Serialize)]
pub struct CheckoutTemplateCreateRequest {
    /// Shown to the merchant's team only. Unique per merchant, 1 to 64
    /// characters.
    pub name: String,
    /// Start from this shop's current connector accounts, payment methods,
    /// entries, behaviour and active routing, in both environments. The shop
    /// is not changed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub copy_from_profile_id: Option<String>,
}

impl CheckoutTemplateCreateRequest {
    /// An empty template named `name`.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            copy_from_profile_id: None,
        }
    }

    /// Start from this shop's current settings.
    #[must_use]
    pub fn copy_from_profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.copy_from_profile_id = Some(profile_id.into());
        self
    }
}

/// Body of [`CheckoutTemplates::rename`].
///
/// The API refuses unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Serialize)]
pub struct CheckoutTemplateUpdateRequest {
    /// The new name. Unique per merchant, 1 to 64 characters.
    pub name: String,
}

impl CheckoutTemplateUpdateRequest {
    /// Rename the template to `name`.
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }
}

/// Body of [`CheckoutTemplates::assign`].
///
/// The API refuses unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Serialize)]
pub struct CheckoutTemplateAssignRequest {
    /// The shops to put on the template. A shop on another template moves.
    pub profile_ids: Vec<String>,
    /// Only report what would change in each shop.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub dry_run: bool,
    /// Why, for the audit log.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl CheckoutTemplateAssignRequest {
    /// Put `profile_ids` on the template.
    pub fn new(profile_ids: Vec<String>) -> Self {
        Self {
            profile_ids,
            dry_run: false,
            reason: None,
        }
    }

    /// Only report what would change.
    #[must_use]
    pub fn dry_run(mut self, dry_run: bool) -> Self {
        self.dry_run = dry_run;
        self
    }

    /// Record why, for the audit log.
    #[must_use]
    pub fn reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }
}

/// Body of [`CheckoutTemplates::apply`].
///
/// The API refuses unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CheckoutTemplateApplyRequest {
    /// The shops to update; `None` updates every shop on the template.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_ids: Option<Vec<String>>,
    /// Only report what would change in each shop.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub dry_run: bool,
    /// Why, for the audit log.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl CheckoutTemplateApplyRequest {
    /// Update every shop on the template.
    pub fn new() -> Self {
        Self::default()
    }

    /// Update only these shops.
    #[must_use]
    pub fn profile_ids(mut self, profile_ids: Vec<String>) -> Self {
        self.profile_ids = Some(profile_ids);
        self
    }

    /// Only report what would change.
    #[must_use]
    pub fn dry_run(mut self, dry_run: bool) -> Self {
        self.dry_run = dry_run;
        self
    }

    /// Record why, for the audit log.
    #[must_use]
    pub fn reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }
}

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

    const TEMPLATE_JSON: &str = r#"{
        "template_id": "pro_tpl",
        "name": "EU shops",
        "content_version": 7,
        "created_at": "2026-01-01T00:00:00Z",
        "modified_at": "2026-01-02T00:00:00Z",
        "shops": [{"profile_id": "pro_1", "status": "up_to_date", "applied_version": 7}],
        "surprise_field": 1
    }"#;

    const APPLY_JSON: &str = r#"{
        "template_id": "pro_tpl",
        "content_version": 7,
        "dry_run": true,
        "shops": [{
            "profile_id": "pro_1",
            "outcome": "blocked",
            "blockers": [{"reason": "connector_switched_off_in_shop", "connector": "stripe"}],
            "changes": {"connectors_added": ["stripe"], "fallback_order": false}
        }],
        "surprise_field": "a"
    }"#;

    #[tokio::test]
    async fn list_gets_the_merchant_path() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"templates":[{TEMPLATE_JSON}],"surprise_field":0}}"#
        ))]);
        let out = client.checkout_templates().list("mer/1").await.unwrap();
        assert_eq!(out.templates[0].content_version, 7);
        assert_eq!(out.templates[0].shops[0].applied_version, Some(7));
        assert_eq!(out.extra["surprise_field"], 0);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/checkout-templates/mer%2F1");
    }

    #[tokio::test]
    async fn create_posts_the_name_and_source_shop() {
        let (client, mock) = client_with(vec![Step::ok(TEMPLATE_JSON)]);
        let params = CheckoutTemplateCreateRequest::new("EU shops").copy_from_profile_id("pro_1");
        let out = client
            .checkout_templates()
            .create("mer_1", &params)
            .await
            .unwrap();
        assert_eq!(out.template_id, "pro_tpl");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/checkout-templates/mer_1");
        assert_eq!(
            seen[0].body_json(),
            json!({"name": "EU shops", "copy_from_profile_id": "pro_1"})
        );
    }

    #[tokio::test]
    async fn retrieve_gets_the_template_path() {
        let (client, mock) = client_with(vec![Step::ok(TEMPLATE_JSON)]);
        let out = client
            .checkout_templates()
            .retrieve("mer_1", "pro/tpl")
            .await
            .unwrap();
        assert_eq!(out.name, "EU shops");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-templates/mer_1/pro%2Ftpl"
        );
    }

    #[tokio::test]
    async fn rename_posts_the_new_name_to_the_template_path() {
        let (client, mock) = client_with(vec![Step::ok(TEMPLATE_JSON)]);
        client
            .checkout_templates()
            .rename(
                "mer_1",
                "pro_tpl",
                &CheckoutTemplateUpdateRequest::new("EU"),
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-templates/mer_1/pro_tpl"
        );
        assert_eq!(seen[0].body_json(), json!({"name": "EU"}));
    }

    #[tokio::test]
    async fn delete_deletes_the_template_path() {
        let (client, mock) = client_with(vec![Step::ok(TEMPLATE_JSON)]);
        client
            .checkout_templates()
            .delete("mer_1", "pro_tpl")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-templates/mer_1/pro_tpl"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn assign_posts_the_shops_with_dry_run() {
        let (client, mock) = client_with(vec![Step::ok(APPLY_JSON)]);
        let params = CheckoutTemplateAssignRequest::new(vec!["pro_1".to_string()])
            .dry_run(true)
            .reason("rollout");
        let out = client
            .checkout_templates()
            .assign("mer_1", "pro_tpl", &params)
            .await
            .unwrap();
        assert!(out.dry_run);
        assert_eq!(out.shops[0].outcome, "blocked");
        assert_eq!(
            out.shops[0].blockers[0].reason,
            "connector_switched_off_in_shop"
        );
        assert_eq!(out.shops[0].changes["connectors_added"][0], "stripe");
        assert_eq!(out.extra["surprise_field"], "a");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-templates/mer_1/pro_tpl/shops"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"profile_ids": ["pro_1"], "dry_run": true, "reason": "rollout"})
        );
    }

    #[tokio::test]
    async fn unassign_deletes_the_shop_path_with_the_reason() {
        let (client, mock) = client_with(vec![Step::ok(TEMPLATE_JSON)]);
        client
            .checkout_templates()
            .unassign("mer_1", "pro_tpl", "pro/1", Some("moved"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-templates/mer_1/pro_tpl/shops/pro%2F1?reason=moved"
        );
    }

    #[tokio::test]
    async fn apply_with_defaults_posts_an_empty_object() {
        let (client, mock) = client_with(vec![Step::ok(APPLY_JSON)]);
        client
            .checkout_templates()
            .apply("mer_1", "pro_tpl", &CheckoutTemplateApplyRequest::new())
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-templates/mer_1/pro_tpl/apply"
        );
        assert_eq!(seen[0].body_json(), json!({}));
    }

    #[tokio::test]
    async fn of_shop_gets_the_merchant_shop_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"profile_id":"pro_1","template":{"template_id":"pro_tpl","name":"EU shops"},
                "is_template":false,"surprise_field":1}"#,
        )]);
        let out = client
            .checkout_templates()
            .of_shop("mer_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(out.template.as_ref().unwrap().template_id, "pro_tpl");
        assert!(!out.is_template);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-templates/mer_1/shops/pro_1"
        );
    }

    /// A client built with `with_idempotency_key` over a mock that answers
    /// 503 twice, with a retry budget of 2.
    fn keyed_client_over_503s() -> (
        crate::Delopay,
        std::sync::Arc<crate::http::mock::MockTransport>,
    ) {
        let (client, mock) = crate::http::mock::client_with_retries(
            vec![Step::status(503, "{}"), Step::status(503, "{}")],
            2,
        );
        (client.with_idempotency_key("client-wide-key"), mock)
    }

    /// Assert the one request sent carried no `Idempotency-Key` and was not
    /// replayed after its 503.
    fn assert_sent_once_unkeyed(mock: &crate::http::mock::MockTransport) {
        assert_eq!(mock.call_count(), 1, "a 503 was replayed");
        assert!(
            !mock.seen.lock().unwrap()[0].had_idempotency_key(),
            "the client-wide key was inherited"
        );
    }

    /// Mutation: switch the call site back to `request(.., None)` — the
    /// client-wide key is sent and the 503 replayed, so both assertions fail.
    #[tokio::test]
    async fn new_writes_do_not_inherit_the_client_key() {
        let (client, mock) = keyed_client_over_503s();
        let params = CheckoutTemplateCreateRequest::new("Standard");
        assert!(
            client
                .checkout_templates()
                .create("mer_1", &params)
                .await
                .is_err()
        );
        assert_sent_once_unkeyed(&mock);
    }
}