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
//! The `fees` resource: merchant-scoped fee schedules.
//!
//! Each schedule optionally targets a single shop (via `shop_id`). Merchants
//! can CRUD their own fee overrides; platform-wide fee programs are
//! administered by Delopay and are not exposed here.

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

// `FeeType` is a wire value on both the request and the response side, so it
// lives in `core::models::fee` (compiled without the `client` feature) and is
// re-exported here, where callers building a request expect to find it.
pub use crate::core::models::fee::FeeType;

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

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

    /// Create a merchant-scoped fee schedule (optionally per-shop).
    pub async fn create(
        &self,
        params: &FeeScheduleCreateRequest,
        merchant_id: &str,
    ) -> Result<FeeScheduleResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        let query = [("merchant_id", merchant_id.to_string())];
        self.inner
            .request(
                HttpMethod::Post,
                "/merchant-fees",
                Some(&body),
                &query,
                None,
            )
            .await
    }

    /// List the merchant's own fee schedules.
    pub async fn list(&self, merchant_id: &str) -> Result<Vec<FeeScheduleResponse>> {
        let query = [("merchant_id", merchant_id.to_string())];
        self.inner
            .request(HttpMethod::Get, "/merchant-fees/list", None, &query, None)
            .await
    }

    /// Update a merchant-scoped fee schedule.
    pub async fn update(
        &self,
        fee_id: &str,
        params: &FeeScheduleUpdateRequest,
    ) -> Result<FeeScheduleResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        let path = format!("/merchant-fees/{}", encode_segment(fee_id));
        self.inner
            .request(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a merchant-scoped fee schedule. Returns the schedule as it was
    /// just before deletion.
    pub async fn delete(&self, fee_id: &str) -> Result<FeeScheduleResponse> {
        let path = format!("/merchant-fees/{}", encode_segment(fee_id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }
}

/// Parameters for [`Fees::create`].
#[derive(Debug, Clone, Serialize)]
pub struct FeeScheduleCreateRequest {
    /// How the schedule prices a transaction.
    pub fee_type: FeeType,
    /// Restrict the schedule to one shop (business profile).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shop_id: Option<String>,
    /// Percentage fee — `2.5` means 2.5%.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percentage_fee: Option<f64>,
    /// Flat fee in minor units.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flat_fee_amount: Option<i64>,
    /// Currency of [`flat_fee_amount`](Self::flat_fee_amount).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flat_fee_currency: Option<String>,
    /// Floor for the computed fee, in minor units.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_fee_amount: Option<i64>,
    /// Cap for the computed fee, in minor units.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_fee_amount: Option<i64>,
    /// Free-text description of the schedule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// A free allowance in minor units, set together with
    /// `free_allowance_kind`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub free_allowance_amount: Option<i64>,
    /// How the allowance applies: `"exemption_limit"` (no fee up to the
    /// allowance) or `"excess_only"` (the fee applies to the excess only).
    /// Set together with `free_allowance_amount`; there is no default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub free_allowance_kind: Option<String>,
    /// Restrict the schedule to one connector. An empty string means any
    /// connector.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `FeeScheduleCreateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const FEE_SCHEDULE_CREATE_REQUEST_NAMED: &[&str] = &[
    "fee_type",
    "shop_id",
    "percentage_fee",
    "flat_fee_amount",
    "flat_fee_currency",
    "min_fee_amount",
    "max_fee_amount",
    "description",
    "free_allowance_amount",
    "free_allowance_kind",
    "connector",
];

/// A free allowance is an amount and a kind together, or neither.
fn check_free_allowance(amount: Option<i64>, kind: Option<&str>) -> Result<()> {
    if amount.is_some() != kind.is_some() {
        return Err(DelopayError::InvalidRequest(
            "`free_allowance_amount` and `free_allowance_kind` are set together".to_owned(),
        ));
    }
    Ok(())
}

impl ValidateRequest for FeeScheduleCreateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if FEE_SCHEDULE_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on FeeScheduleCreateRequest"
                )));
            }
        }
        check_free_allowance(
            self.free_allowance_amount,
            self.free_allowance_kind.as_deref(),
        )
    }
}

impl FeeScheduleCreateRequest {
    /// A schedule of the given kind; set the amounts you need.
    pub fn new(fee_type: FeeType) -> Self {
        Self {
            fee_type,
            shop_id: None,
            percentage_fee: None,
            flat_fee_amount: None,
            flat_fee_currency: None,
            min_fee_amount: None,
            max_fee_amount: None,
            description: None,
            free_allowance_amount: None,
            free_allowance_kind: None,
            connector: None,
            extra: serde_json::Map::new(),
        }
    }

    /// A free allowance of `amount` minor units, applied as `kind`
    /// (`"exemption_limit"` or `"excess_only"`).
    pub fn free_allowance(mut self, amount: i64, kind: impl Into<String>) -> Self {
        self.free_allowance_amount = Some(amount);
        self.free_allowance_kind = Some(kind.into());
        self
    }

    /// Restrict the schedule to one connector.
    pub fn connector(mut self, connector: impl Into<String>) -> Self {
        self.connector = Some(connector.into());
        self
    }

    /// Restrict the schedule to one shop (business profile).
    pub fn shop_id(mut self, shop_id: impl Into<String>) -> Self {
        self.shop_id = Some(shop_id.into());
        self
    }

    /// Set the percentage fee — `2.5` means 2.5%.
    pub fn percentage_fee(mut self, percentage_fee: f64) -> Self {
        self.percentage_fee = Some(percentage_fee);
        self
    }

    /// Set the flat fee amount (minor units) and its currency.
    pub fn flat_fee(mut self, amount: i64, currency: impl Into<String>) -> Self {
        self.flat_fee_amount = Some(amount);
        self.flat_fee_currency = Some(currency.into());
        self
    }

    /// Set the free-text description.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// Parameters for [`Fees::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct FeeScheduleUpdateRequest {
    /// How the schedule prices a transaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fee_type: Option<FeeType>,
    /// Percentage fee — `2.5` means 2.5%.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percentage_fee: Option<f64>,
    /// Flat fee in minor units.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flat_fee_amount: Option<i64>,
    /// Currency of [`flat_fee_amount`](Self::flat_fee_amount). `""` clears it
    /// back to the transaction currency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flat_fee_currency: Option<String>,
    /// Floor for the computed fee, in minor units.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_fee_amount: Option<i64>,
    /// Cap for the computed fee, in minor units.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_fee_amount: Option<i64>,
    /// Free-text description of the schedule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Whether the schedule is active.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
    /// A free allowance in minor units, set together with
    /// `free_allowance_kind`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub free_allowance_amount: Option<i64>,
    /// How the allowance applies: `"exemption_limit"` (no fee up to the
    /// allowance) or `"excess_only"` (the fee applies to the excess only).
    /// Set together with `free_allowance_amount`; there is no default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub free_allowance_kind: Option<String>,
    /// Restrict the schedule to one connector. An empty string means any
    /// connector.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `FeeScheduleUpdateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const FEE_SCHEDULE_UPDATE_REQUEST_NAMED: &[&str] = &[
    "fee_type",
    "percentage_fee",
    "flat_fee_amount",
    "flat_fee_currency",
    "min_fee_amount",
    "max_fee_amount",
    "description",
    "is_active",
    "free_allowance_amount",
    "free_allowance_kind",
    "connector",
];

impl ValidateRequest for FeeScheduleUpdateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if FEE_SCHEDULE_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on FeeScheduleUpdateRequest"
                )));
            }
        }
        check_free_allowance(
            self.free_allowance_amount,
            self.free_allowance_kind.as_deref(),
        )
    }
}

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

    /// Set the free allowance. It cannot be removed, only set to `0`.
    pub fn free_allowance(mut self, amount: i64, kind: impl Into<String>) -> Self {
        self.free_allowance_amount = Some(amount);
        self.free_allowance_kind = Some(kind.into());
        self
    }

    /// Restrict the schedule to one connector; `""` means any connector.
    pub fn connector(mut self, connector: impl Into<String>) -> Self {
        self.connector = Some(connector.into());
        self
    }

    /// Change how the schedule prices a transaction.
    pub fn fee_type(mut self, fee_type: FeeType) -> Self {
        self.fee_type = Some(fee_type);
        self
    }

    /// Set the percentage fee — `2.5` means 2.5%.
    pub fn percentage_fee(mut self, percentage_fee: f64) -> Self {
        self.percentage_fee = Some(percentage_fee);
        self
    }

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

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

    const SCHEDULE_JSON: &str = r#"{
        "id": "fee_1",
        "merchant_id": "merch_1",
        "fee_type": "percentage",
        "is_active": true,
        "fee_owner": "merchant",
        "shop_id": "pro_1",
        "percentage_fee": 2.5,
        "free_allowance_amount": 10000,
        "free_allowance_kind": "excess_only",
        "connector": "stripe"
    }"#;

    #[tokio::test]
    async fn create_posts_with_the_merchant_id_query() {
        let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
        let params = FeeScheduleCreateRequest::new(FeeType::Combined)
            .shop_id("pro_1")
            .percentage_fee(2.5)
            .flat_fee(30, "USD");
        let created = client.fees().create(&params, "merch_1").await.unwrap();
        assert_eq!(created.id, "fee_1");
        assert_eq!(created.fee_type, FeeType::Percentage);
        assert_eq!(created.free_allowance_amount, Some(10_000));
        assert_eq!(created.free_allowance_kind.as_deref(), Some("excess_only"));
        assert_eq!(created.connector.as_deref(), Some("stripe"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/merchant-fees?merchant_id=merch_1"
        );
        let body = seen[0].body_json();
        assert_eq!(body["fee_type"], "combined");
        assert_eq!(body["shop_id"], "pro_1");
        assert_eq!(body["percentage_fee"], 2.5);
        assert_eq!(body["flat_fee_amount"], 30);
        assert_eq!(body["flat_fee_currency"], "USD");
    }

    #[tokio::test]
    async fn list_gets_the_list_path_with_the_merchant_id_query() {
        let (client, mock) = client_with(vec![Step::ok(&format!("[{SCHEDULE_JSON}]"))]);
        let schedules = client.fees().list("merch_1").await.unwrap();
        assert_eq!(schedules.len(), 1);
        assert_eq!(schedules[0].shop_id.as_deref(), Some("pro_1"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/merchant-fees/list?merchant_id=merch_1"
        );
    }

    #[tokio::test]
    async fn update_puts_to_the_encoded_fee_path() {
        let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
        let params = FeeScheduleUpdateRequest::new()
            .fee_type(FeeType::Flat)
            .is_active(false);
        client.fees().update("fee/1", &params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/merchant-fees/fee%2F1");
        let body = seen[0].body_json();
        assert_eq!(body["fee_type"], "flat");
        assert_eq!(body["is_active"], false);
    }

    #[tokio::test]
    async fn delete_removes_the_schedule_by_id() {
        let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
        let deleted = client.fees().delete("fee_1").await.unwrap();
        assert_eq!(deleted.id, "fee_1");

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

    /// An allowance needs its amount and its kind. Mutation: return `Ok` from
    /// `check_free_allowance` — the first assertion fails.
    #[test]
    fn a_half_set_free_allowance_is_refused() {
        let mut half = FeeScheduleCreateRequest::new(FeeType::Percentage);
        half.free_allowance_amount = Some(100);
        assert!(half.validate().is_err());
        let mut kind_only = FeeScheduleUpdateRequest::new();
        kind_only.free_allowance_kind = Some("excess_only".to_string());
        assert!(kind_only.validate().is_err());
        let whole = FeeScheduleCreateRequest::new(FeeType::Percentage)
            .free_allowance(100, "exemption_limit")
            .connector("stripe");
        assert!(whole.validate().is_ok());
        let value = serde_json::to_value(whole).unwrap();
        assert_eq!(value["free_allowance_amount"], 100);
        assert_eq!(value["free_allowance_kind"], "exemption_limit");
        assert_eq!(value["connector"], "stripe");
    }

    /// Drift guard for `FEE_SCHEDULE_CREATE_REQUEST_NAMED`.
    #[test]
    fn fee_schedule_create_request_named_fields_are_complete() {
        let req = FeeScheduleCreateRequest {
            fee_type: FeeType::Combined,
            shop_id: Some("pro_1".to_string()),
            percentage_fee: Some(2.5),
            flat_fee_amount: Some(30),
            flat_fee_currency: Some("USD".to_string()),
            min_fee_amount: Some(1),
            max_fee_amount: Some(1000),
            description: Some("standard".to_string()),
            free_allowance_amount: Some(10_000),
            free_allowance_kind: Some("excess_only".to_string()),
            connector: Some("stripe".to_string()),
            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!(
                FEE_SCHEDULE_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "FEE_SCHEDULE_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `FEE_SCHEDULE_UPDATE_REQUEST_NAMED`.
    #[test]
    fn fee_schedule_update_request_named_fields_are_complete() {
        let req = FeeScheduleUpdateRequest {
            fee_type: Some(FeeType::Flat),
            percentage_fee: Some(2.5),
            flat_fee_amount: Some(30),
            flat_fee_currency: Some("USD".to_string()),
            min_fee_amount: Some(1),
            max_fee_amount: Some(1000),
            description: Some("standard".to_string()),
            is_active: Some(true),
            free_allowance_amount: Some(0),
            free_allowance_kind: Some("exemption_limit".to_string()),
            connector: Some(String::new()),
            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!(
                FEE_SCHEDULE_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "FEE_SCHEDULE_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn fee_schedule_create_validate_rejects_colliding_extra_key() {
        let mut req = FeeScheduleCreateRequest::new(FeeType::Flat);
        req.extra.insert("shop_id".to_string(), json!("pro_2"));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    #[test]
    fn fee_schedule_update_validate_rejects_colliding_extra_key() {
        let mut req = FeeScheduleUpdateRequest::new();
        req.extra.insert("is_active".to_string(), json!(false));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }
}