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
//! The `settings` resource: the settings of the caller's merchant, its
//! projects and its shops.
//!
//! One resource for every setting: each is a key with a JSON value, listed
//! with its default, whether a value is stored, its revision and who changed
//! it last. A merchant changes only its own values; values the platform
//! operator sets at the same scope are listed beside them
//! (`authority: "operator"`) and are read-only here.
//!
//! Every change is recorded in the audit log with the previous and the new
//! value (`entity_type: "setting"`).
//!
//! Dashboard (JWT) routes. Reading the merchant's settings needs
//! `MerchantAccountRead`, a shop's `ProfileAccountRead`; each change needs the
//! permission its setting names.

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::settings::SettingsResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// The merchant's settings, or one project's when `project_id` is given.
    ///
    /// `GET /settings/merchant`
    pub async fn retrieve_merchant(&self, project_id: Option<&str>) -> Result<SettingsResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/settings/merchant",
                None,
                &project_query(project_id),
                None,
            )
            .await
    }

    /// Change the merchant's own settings, or one project's when
    /// `project_id` is given. All changes are applied or none is.
    ///
    /// `PATCH /settings/merchant`
    pub async fn update_merchant(
        &self,
        params: &UpdateSettingsRequest,
        project_id: Option<&str>,
    ) -> Result<SettingsResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Patch,
                "/settings/merchant",
                Some(&body),
                &project_query(project_id),
                None,
            )
            .await
    }

    /// One shop's settings.
    ///
    /// `GET /settings/shops/{profile_id}`
    pub async fn retrieve_shop(&self, profile_id: &str) -> Result<SettingsResponse> {
        self.inner
            .request(HttpMethod::Get, &shop_path(profile_id), None, &[], None)
            .await
    }

    /// Change one shop's own settings. All changes are applied or none is.
    ///
    /// `PATCH /settings/shops/{profile_id}`
    pub async fn update_shop(
        &self,
        profile_id: &str,
        params: &UpdateSettingsRequest,
    ) -> Result<SettingsResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Patch,
                &shop_path(profile_id),
                Some(&body),
                &[],
                None,
            )
            .await
    }
}

/// `/settings/shops/{profile_id}`, percent-encoded.
fn shop_path(profile_id: &str) -> String {
    format!("/settings/shops/{}", encode_segment(profile_id))
}

/// `?project_id=…` when a project is named; nothing otherwise.
fn project_query(project_id: Option<&str>) -> Vec<(&'static str, String)> {
    match project_id {
        Some(id) if !id.is_empty() => vec![("project_id", id.to_string())],
        _ => Vec::new(),
    }
}

/// Body of [`Settings::update_merchant`] and [`Settings::update_shop`]:
/// several changes at one scope, applied together or not at all.
///
/// A setting kept outside the settings store (`risk_settings`,
/// `dashboard_oauth.provider`, `dashboard_oauth.urls`) must be the only change
/// in its request; a request mixing it with others is refused with 422.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateSettingsRequest {
    /// The changes.
    pub changes: Vec<SettingChangeRequest>,
}

impl UpdateSettingsRequest {
    /// A request applying `changes`.
    pub fn new(changes: Vec<SettingChangeRequest>) -> Self {
        Self { changes }
    }
}

impl ValidateRequest for UpdateSettingsRequest {
    fn validate(&self) -> Result<()> {
        self.changes.iter().try_for_each(|change| change.validate())
    }
}

/// One change in an [`UpdateSettingsRequest`].
///
/// `Debug` shows neither the value nor the values in `extra`: a change may
/// write a secret.
#[derive(Clone, Default, Serialize)]
pub struct SettingChangeRequest {
    /// The setting's key, e.g. `replay_retention`.
    pub key: String,
    /// Required for settings kept per connector or per provider at the
    /// platform scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qualifier: Option<String>,
    /// The new value. `Some(Value::Null)` sends JSON `null`, which is a value
    /// for settings that give it one; `None` sends no value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<Value>,
    /// Remove the stored value so the default, or the next scope out,
    /// applies.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub clear: Option<bool>,
    /// The revision last read. The whole request is refused when any value
    /// moved since, with 400 and code `IR_16`; omit it to write
    /// unconditionally. Required for `risk_settings`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expected_revision: Option<i64>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for SettingChangeRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SettingChangeRequest")
            .field("key", &self.key)
            .field("qualifier", &self.qualifier)
            .field("value", &self.value.as_ref().map(|_| "[redacted]"))
            .field("clear", &self.clear)
            .field("expected_revision", &self.expected_revision)
            .field("extra_keys", &self.extra.keys().collect::<Vec<_>>())
            .finish()
    }
}

impl SettingChangeRequest {
    /// Store `value` under `key`.
    pub fn set_value(key: impl Into<String>, value: Value) -> Self {
        Self {
            key: key.into(),
            value: Some(value),
            ..Default::default()
        }
    }

    /// Remove the value stored under `key`.
    pub fn clear_value(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            clear: Some(true),
            ..Default::default()
        }
    }

    /// Name the connector or provider the setting is kept for.
    #[must_use]
    pub fn qualifier(mut self, qualifier: impl Into<String>) -> Self {
        self.qualifier = Some(qualifier.into());
        self
    }

    /// Refuse the whole request when this setting moved since `revision`.
    #[must_use]
    pub fn expected_revision(mut self, revision: i64) -> Self {
        self.expected_revision = Some(revision);
        self
    }
}

/// Names of `SettingChangeRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const SETTING_CHANGE_REQUEST_NAMED: &[&str] =
    &["key", "qualifier", "value", "clear", "expected_revision"];

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

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

    const SETTINGS_JSON: &str = r#"{
        "scope": "merchant",
        "scope_id": "mer_1",
        "settings": [{
            "key": "replay_retention", "qualifier": null, "authority": "merchant",
            "value": 30, "default_value": 7, "is_set": true, "revision": 4,
            "updated_at": "2026-11-01T00:00:00Z",
            "updated_by": {"id": "usr_1", "name": "ada@example.com"},
            "secret": false, "effective_value": 30,
            "effective_source": {"scope": "merchant", "scope_id": "mer_1",
                                 "authority": "merchant"},
            "detail": null, "entry_surprise": 1
        }],
        "surprise_field": "x"
    }"#;

    #[tokio::test]
    async fn retrieve_merchant_gets_the_merchant_scope_without_a_project() {
        let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
        let out = client.settings().retrieve_merchant(None).await.unwrap();
        assert_eq!(out.scope, "merchant");
        assert_eq!(out.settings[0].key, "replay_retention");
        assert_eq!(out.settings[0].value, json!(30));
        assert_eq!(out.settings[0].revision, 4);
        assert_eq!(
            out.settings[0].updated_by.as_ref().map(|a| a.id.as_str()),
            Some("usr_1")
        );
        assert_eq!(out.settings[0].extra["entry_surprise"], 1);
        assert_eq!(out.extra["surprise_field"], "x");

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

    #[tokio::test]
    async fn update_merchant_patches_a_project_with_the_changes() {
        let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
        let params = UpdateSettingsRequest::new(vec![
            SettingChangeRequest::set_value("replay_retention", json!(30)).expected_revision(3),
            SettingChangeRequest::clear_value("iframe_origin_rules"),
            SettingChangeRequest::set_value("nullable_setting", Value::Null),
        ]);
        client
            .settings()
            .update_merchant(&params, Some("prj_1"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PATCH");
        assert_eq!(
            seen[0].url,
            "https://api.test/settings/merchant?project_id=prj_1"
        );
        // An explicit JSON null is a value and must reach the wire; a mutation
        // dropping `Some(Null)` with the `None`s fails the third entry.
        assert_eq!(
            seen[0].body_json(),
            json!({"changes": [
                {"key": "replay_retention", "value": 30, "expected_revision": 3},
                {"key": "iframe_origin_rules", "clear": true},
                {"key": "nullable_setting", "value": null}
            ]})
        );
        // A PATCH with no idempotency key: the shared policy never replays it.
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn retrieve_shop_encodes_the_profile_id() {
        let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
        client.settings().retrieve_shop("pro/1").await.unwrap();

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

    #[tokio::test]
    async fn update_shop_patches_the_shop_path() {
        let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
        let params = UpdateSettingsRequest::new(vec![
            SettingChangeRequest::set_value("payment_amount_limits", json!({"limits": []}))
                .qualifier("stripe"),
        ]);
        client
            .settings()
            .update_shop("pro_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PATCH");
        assert_eq!(seen[0].url, "https://api.test/settings/shops/pro_1");
        assert_eq!(
            seen[0].body_json()["changes"][0],
            json!({"key": "payment_amount_limits", "qualifier": "stripe",
                   "value": {"limits": []}})
        );
    }

    #[tokio::test]
    async fn update_rejects_a_colliding_extra_key_before_sending() {
        let (client, mock) = client_with(vec![]);
        let mut change = SettingChangeRequest::set_value("k", json!(1));
        change.extra.insert("value".to_string(), json!(2));
        let params = UpdateSettingsRequest::new(vec![change]);
        match client
            .settings()
            .update_shop("pro_1", &params)
            .await
            .unwrap_err()
        {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("value")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
        assert_eq!(mock.call_count(), 0);
    }

    #[test]
    fn a_change_debug_hides_the_value() {
        let change = SettingChangeRequest::set_value("api_secret", json!("s3cr3t"));
        assert!(!format!("{change:?}").contains("s3cr3t"));
    }

    /// Drift guard for `SETTING_CHANGE_REQUEST_NAMED`.
    #[test]
    fn setting_change_request_named_fields_are_complete() {
        let req = SettingChangeRequest {
            key: "k".to_string(),
            qualifier: Some("q".to_string()),
            value: Some(json!(1)),
            clear: Some(false),
            expected_revision: Some(1),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                SETTING_CHANGE_REQUEST_NAMED.contains(&key.as_str()),
                "SETTING_CHANGE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// 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 = UpdateSettingsRequest::new(vec![SettingChangeRequest::set_value(
            "replay_retention",
            json!(30),
        )]);
        assert!(
            client
                .settings()
                .update_shop("pro_1", &params)
                .await
                .is_err()
        );
        assert_sent_once_unkeyed(&mock);
    }
}