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
//! The `cost_rules` resource: what a merchant's own goods and partners'
//! shares cost it, as a percentage, a flat amount or both, merchant-wide or
//! for one shop, over a validity window.
//!
//! A rule is a record, not an instruction: it writes no billing ledger entry
//! and moves no money. Its rate, category and scope cannot be edited; a price
//! change is a new rule with a new window, so earlier periods keep the rate
//! they were recorded under.
//!
//! Every call takes the merchant account ID, sent as `?merchant_id=…`, and
//! needs a dashboard session for that merchant — authenticate the client
//! with [`Delopay::with_jwt`](crate::Delopay::with_jwt). Listing needs the
//! merchant account read permission, every change the write permission. A
//! shop-scoped session reaches nothing 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::cost_rule::{
    MerchantCostRuleCategory, MerchantCostRuleDeleteResponse, MerchantCostRuleResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Every cost rule of the merchant.
    ///
    /// `GET /cost-rules?merchant_id=`
    pub async fn list(&self, merchant_id: &str) -> Result<Vec<MerchantCostRuleResponse>> {
        self.inner
            .request(
                HttpMethod::Get,
                "/cost-rules",
                None,
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Record a cost rule.
    ///
    /// `POST /cost-rules?merchant_id=`
    pub async fn create(
        &self,
        merchant_id: &str,
        params: &CreateMerchantCostRuleRequest,
    ) -> Result<MerchantCostRuleResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Post,
                "/cost-rules",
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Close, deactivate or rename a cost rule. A closed window cannot be
    /// extended or reopened.
    ///
    /// `PUT /cost-rules/{rule_id}?merchant_id=`
    pub async fn update(
        &self,
        merchant_id: &str,
        rule_id: &str,
        params: &UpdateMerchantCostRuleRequest,
    ) -> Result<MerchantCostRuleResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Put,
                &rule_path(rule_id),
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Delete a cost rule.
    ///
    /// `DELETE /cost-rules/{rule_id}?merchant_id=`
    pub async fn delete(
        &self,
        merchant_id: &str,
        rule_id: &str,
    ) -> Result<MerchantCostRuleDeleteResponse> {
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Delete,
                &rule_path(rule_id),
                None,
                &merchant_query(merchant_id),
                None,
            )
            .await
    }
}

/// `/cost-rules/{rule_id}`, percent-encoded.
fn rule_path(rule_id: &str) -> String {
    format!("/cost-rules/{}", encode_segment(rule_id))
}

/// The `?merchant_id=…` every cost rule call requires.
fn merchant_query(merchant_id: &str) -> Vec<(&'static str, String)> {
    vec![("merchant_id", merchant_id.to_string())]
}

/// Body of [`CostRules::create`].
///
/// A percentage, a flat amount or both, merchant-wide or for one shop, from
/// `effective_from` (default: now) until `effective_to` (exclusive; default:
/// open-ended).
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateMerchantCostRuleRequest {
    /// What the rule records: `"goods"`, `"partner_share"` or `"other"`.
    pub category: MerchantCostRuleCategory,
    /// One shop. Omitted, the rule covers every shop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shop_id: Option<String>,
    /// Percentage of the transaction, e.g. `42.5` for 42.5 %.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percentage: Option<f64>,
    /// Flat component in minor units of `flat_currency`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flat_amount: Option<i64>,
    /// ISO 4217 currency of the fixed components. Omitted, they are stated in
    /// the transaction currency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flat_currency: Option<String>,
    /// Per-transaction floor. Lifts a priced cost; never creates one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_amount: Option<i64>,
    /// Per-transaction ceiling.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_amount: Option<i64>,
    /// When the rate starts applying (ISO 8601).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effective_from: Option<String>,
    /// When it stops applying (ISO 8601, exclusive).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effective_to: Option<String>,
    /// What you call the rule: the supplier, the contract, the product line.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Any additional fields, merged verbatim. The server refuses fields it
    /// does not know.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl CreateMerchantCostRuleRequest {
    /// A merchant-wide rule of `category`, starting now and open-ended.
    pub fn new(category: impl Into<MerchantCostRuleCategory>) -> Self {
        Self {
            category: category.into(),
            ..Default::default()
        }
    }

    /// Scope the rule to one shop.
    #[must_use]
    pub fn shop_id(mut self, shop_id: impl Into<String>) -> Self {
        self.shop_id = Some(shop_id.into());
        self
    }

    /// Set the percentage of the transaction.
    #[must_use]
    pub fn percentage(mut self, percentage: f64) -> Self {
        self.percentage = Some(percentage);
        self
    }

    /// Set a flat component of `flat_amount` minor units.
    #[must_use]
    pub fn flat_amount(mut self, flat_amount: i64) -> Self {
        self.flat_amount = Some(flat_amount);
        self
    }

    /// Set the currency the fixed components are stated in.
    #[must_use]
    pub fn flat_currency(mut self, flat_currency: impl Into<String>) -> Self {
        self.flat_currency = Some(flat_currency.into());
        self
    }

    /// Set a per-transaction floor.
    #[must_use]
    pub fn min_amount(mut self, min_amount: i64) -> Self {
        self.min_amount = Some(min_amount);
        self
    }

    /// Set a per-transaction ceiling.
    #[must_use]
    pub fn max_amount(mut self, max_amount: i64) -> Self {
        self.max_amount = Some(max_amount);
        self
    }

    /// Set when the rate starts applying (ISO 8601).
    #[must_use]
    pub fn effective_from(mut self, effective_from: impl Into<String>) -> Self {
        self.effective_from = Some(effective_from.into());
        self
    }

    /// Set when the rate stops applying (ISO 8601, exclusive).
    #[must_use]
    pub fn effective_to(mut self, effective_to: impl Into<String>) -> Self {
        self.effective_to = Some(effective_to.into());
        self
    }

    /// Set what you call the rule.
    #[must_use]
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }
}

/// Names of `CreateMerchantCostRuleRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const CREATE_MERCHANT_COST_RULE_REQUEST_NAMED: &[&str] = &[
    "category",
    "shop_id",
    "percentage",
    "flat_amount",
    "flat_currency",
    "min_amount",
    "max_amount",
    "effective_from",
    "effective_to",
    "label",
];

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

/// Body of [`CostRules::update`]. Only the fields you set are sent.
///
/// The rate, the category and the scope cannot be edited.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateMerchantCostRuleRequest {
    /// Close the window at this instant (ISO 8601, exclusive).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effective_to: Option<String>,
    /// Activate or deactivate the rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
    /// The label: `None` leaves it alone, `Some(None)` clears it (sent as
    /// `null`), `Some(Some(_))` replaces it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<Option<String>>,
}

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

    /// Close the window at this instant (ISO 8601, exclusive).
    #[must_use]
    pub fn effective_to(mut self, effective_to: impl Into<String>) -> Self {
        self.effective_to = Some(effective_to.into());
        self
    }

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

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

    /// Clear the label: sends `"label": null`.
    #[must_use]
    pub fn clear_label(mut self) -> Self {
        self.label = Some(None);
        self
    }
}

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

    const RULE_JSON: &str = r#"{
        "id": "mcr_1",
        "merchant_id": "mer_1",
        "shop_id": "pro_1",
        "category": "partner_share",
        "percentage": 42.5,
        "effective_from": "2026-01-01T00:00:00Z",
        "is_active": true,
        "label": "Studio A",
        "surprise_field": 1
    }"#;

    #[tokio::test]
    async fn list_gets_the_merchant_rules() {
        let (client, mock) = client_with(vec![Step::ok(&format!("[{RULE_JSON}]"))]);
        let out = client.cost_rules().list("mer_1").await.unwrap();
        assert_eq!(out[0].id, "mcr_1");
        assert_eq!(out[0].category, "partner_share");
        assert_eq!(out[0].percentage, Some(42.5));
        assert!(out[0].effective_to.is_none());
        assert_eq!(out[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/cost-rules?merchant_id=mer_1");
    }

    /// No cost-rule route deduplicates on an `Idempotency-Key`, so a
    /// client-wide key is not sent and a `503` is not replayed into a second
    /// rule. Mutation: call `request(.., None)` again — the header appears
    /// and the request count becomes 2.
    #[tokio::test]
    async fn create_ignores_a_client_wide_key_and_is_not_replayed() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, r#"{"error":{"message":"down"}}"#),
                Step::ok(RULE_JSON),
            ],
            2,
        );
        let params = CreateMerchantCostRuleRequest::new("partner_share").percentage(42.5);
        assert!(
            client
                .with_idempotency_key("client-key")
                .cost_rules()
                .create("mer_1", &params)
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
        assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn create_posts_the_rule_and_omits_unset_fields() {
        let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
        let params = CreateMerchantCostRuleRequest::new("partner_share")
            .shop_id("pro_1")
            .percentage(42.5)
            .label("Studio A");
        let out = client.cost_rules().create("mer_1", &params).await.unwrap();
        assert_eq!(out.shop_id.as_deref(), Some("pro_1"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/cost-rules?merchant_id=mer_1");
        assert_eq!(
            seen[0].body_json(),
            json!({"category":"partner_share","shop_id":"pro_1","percentage":42.5,
                   "label":"Studio A"})
        );
    }

    #[tokio::test]
    async fn update_puts_the_encoded_rule_and_sends_a_null_label_to_clear_it() {
        let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
        let params = UpdateMerchantCostRuleRequest::new()
            .is_active(false)
            .clear_label();
        client
            .cost_rules()
            .update("mer_1", "mcr/1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/cost-rules/mcr%2F1?merchant_id=mer_1"
        );
        // An explicit null clears the label; an absent key leaves it alone.
        assert_eq!(seen[0].body_json(), json!({"is_active":false,"label":null}));
    }

    #[test]
    fn update_without_a_label_leaves_the_key_out() {
        let value =
            serde_json::to_value(UpdateMerchantCostRuleRequest::new().is_active(true)).unwrap();
        assert_eq!(value, json!({"is_active":true}));
        let value = serde_json::to_value(UpdateMerchantCostRuleRequest::new().label("B")).unwrap();
        assert_eq!(value, json!({"label":"B"}));
    }

    #[tokio::test]
    async fn delete_deletes_the_encoded_rule_and_decodes_the_answer() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"deleted":true,"id":"mcr/1","surprise_field":1}"#,
        )]);
        let out = client.cost_rules().delete("mer_1", "mcr/1").await.unwrap();
        assert!(out.deleted);
        assert_eq!(out.id, "mcr/1");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/cost-rules/mcr%2F1?merchant_id=mer_1"
        );
    }

    /// Drift guard for `CREATE_MERCHANT_COST_RULE_REQUEST_NAMED`.
    #[test]
    fn create_merchant_cost_rule_request_named_fields_are_complete() {
        let req = CreateMerchantCostRuleRequest::new("goods")
            .shop_id("pro_1")
            .percentage(10.0)
            .flat_amount(100)
            .flat_currency("EUR")
            .min_amount(1)
            .max_amount(1000)
            .effective_from("2026-01-01T00:00:00Z")
            .effective_to("2027-01-01T00:00:00Z")
            .label("Supplier");
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                CREATE_MERCHANT_COST_RULE_REQUEST_NAMED.contains(&key.as_str()),
                "CREATE_MERCHANT_COST_RULE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

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