delopay 0.4.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
//! Routing models: routing-configuration records, the routing dictionary,
//! per-profile defaults, connector restrictions and surcharge programs.
//!
//! [`MethodSurcharge`] and [`PerMethodSurchargeItem`] live here rather than in
//! `resources` because they appear on both the request and the response side,
//! and the response side must stay available in the
//! `default-features = false` build.
//!
//! Routing *algorithm* bodies stay raw JSON: they are an adjacently-tagged
//! `{type, data}` union whose `advanced` arm carries a full Euclid program,
//! and the typed builder for that tree is client-gated.

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// What a routing algorithm applies to, e.g. `"payment"`, `"payout"`,
/// `"three_ds_authentication"`. Open vocabulary — kept as a string so a new
/// backend value cannot break deserialization.
pub type TransactionType = String;

/// A connector the router may pick.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutableConnectorChoice {
    /// Connector name, e.g. `"stripe"`.
    pub connector: String,
    /// The specific merchant connector account to use, when pinned.
    #[serde(default)]
    pub merchant_connector_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Metadata for one routing configuration, as returned by create, activate,
/// deactivate and the list endpoints. Carries no algorithm body — use the
/// retrieve endpoint for that.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingDictionaryRecord {
    /// Unique routing configuration ID.
    pub id: String,
    /// Shop (business profile) the configuration belongs to.
    pub profile_id: String,
    /// Human-readable name.
    pub name: String,
    /// Algorithm kind, e.g. `"single"`, `"priority"`, `"advanced"`.
    pub kind: String,
    /// Longer description of what the configuration does.
    #[serde(default)]
    pub description: Option<String>,
    /// Creation time, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: Option<i64>,
    /// Last-modified time, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub modified_at: Option<i64>,
    /// Transaction type the configuration applies to, or `None` when it
    /// applies to all of them.
    #[serde(default)]
    pub algorithm_for: Option<TransactionType>,
    /// Decision-engine ID, on backends that mirror configs into it.
    #[serde(default)]
    pub decision_engine_routing_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A full routing configuration, including the algorithm body.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MerchantRoutingAlgorithm {
    /// Unique routing configuration ID.
    pub id: String,
    /// Shop (business profile) the configuration belongs to.
    pub profile_id: String,
    /// Human-readable name.
    pub name: String,
    /// The routing algorithm — an adjacently-tagged `{type, data}` object
    /// (`single`, `priority`, `volume_split`, `advanced`,
    /// `three_ds_decision_rule`). Raw JSON on purpose; see the module docs.
    pub algorithm: Value,

    /// Longer description of what the configuration does.
    #[serde(default)]
    pub description: Option<String>,
    /// Creation time, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: Option<i64>,
    /// Last-modified time, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub modified_at: Option<i64>,
    /// Transaction type the configuration applies to.
    #[serde(default)]
    pub algorithm_for: Option<TransactionType>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Every routing configuration for a merchant, plus which one is active.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingDictionary {
    /// Merchant account the dictionary belongs to.
    pub merchant_id: String,
    /// The currently active configuration, or `None` when routing falls back
    /// to the default.
    #[serde(default)]
    pub active_id: Option<String>,
    /// The configuration records.
    #[serde(default = "Vec::new")]
    pub records: Vec<RoutingDictionaryRecord>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The active routing configuration wrapped in its `{ "algorithm": … }`
/// envelope, as merchant-account-based backends return it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ActiveRoutingAlgorithm {
    /// The active configuration, or `None` when none is set.
    #[serde(default)]
    pub algorithm: Option<MerchantRoutingAlgorithm>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What the active-routing endpoint returns: either the merchant-account
/// envelope, or a list of profile-based records.
///
/// Untagged: an object decodes as [`Envelope`](Self::Envelope), a JSON array
/// as [`Records`](Self::Records).
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ActiveRoutingConfig {
    /// Merchant-account-based backends: `{ "algorithm": … }`.
    ///
    /// Boxed: the envelope carries a full routing configuration and is an
    /// order of magnitude larger than the other variant.
    Envelope(Box<ActiveRoutingAlgorithm>),
    /// Profile-based backends: an array of configuration records.
    Records(Vec<RoutingDictionaryRecord>),
}

/// Per-profile default fallback routing.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProfileDefaultRoutingConfig {
    /// Shop (business profile) the defaults belong to.
    pub profile_id: String,
    /// Connectors tried, in order, when no algorithm matches.
    #[serde(default = "Vec::new")]
    pub connectors: Vec<RoutableConnectorChoice>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What the default-profile-routing endpoint returns: either a flat connector
/// list (merchant-wide default) or one entry per profile.
///
/// Untagged, and the per-profile arm is tried first because its entries carry
/// a required `profile_id` that a bare connector choice does not. An empty
/// array therefore decodes as an empty
/// [`PerProfile`](Self::PerProfile).
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum DefaultProfileRouting {
    /// One default configuration per shop.
    PerProfile(Vec<ProfileDefaultRoutingConfig>),
    /// A merchant-wide ordered connector list.
    Connectors(Vec<RoutableConnectorChoice>),
}

/// Connectors that will not be routed to for a shop — explicit denies plus
/// whitelist-implied exclusions.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProfileDeniedConnectorsResponse {
    /// Connector names not routed for this shop, e.g. `"paypal"`.
    #[serde(default = "Vec::new")]
    pub denied_connectors: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A buyer-facing surcharge added to the checkout amount: either a flat amount
/// in minor currency units, or a percentage of the order amount.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MethodSurcharge {
    /// A flat surcharge, in minor currency units.
    #[serde(rename = "fixed")]
    Fixed {
        /// The surcharge amount, in minor units.
        amount: i64,
    },
    /// A surcharge expressed as a percentage of the order amount.
    #[serde(rename = "rate")]
    Rate {
        /// The surcharge percentage, e.g. `1.0` for 1%.
        percent: f64,
    },
}

/// One per-payment-method surcharge entry, on both the request and the
/// response side of a surcharge program.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PerMethodSurchargeItem {
    /// Payment method family, e.g. `"card"`, `"crypto"`, `"wallet"`.
    pub payment_method: String,
    /// Optional finer scope, e.g. a specific wallet or crypto. Not valid for
    /// cards — use [`card_network`](Self::card_network) instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payment_method_type: Option<String>,
    /// Optional card-network scope (cards only), e.g. `"Visa"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub card_network: Option<String>,
    /// The surcharge to apply.
    pub surcharge: MethodSurcharge,
    /// Optional tax on the surcharge, as a percentage of the surcharge amount.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tax_on_surcharge_percent: Option<f64>,
}

impl PerMethodSurchargeItem {
    /// An entry surcharging one payment method family.
    pub fn new(payment_method: impl Into<String>, surcharge: MethodSurcharge) -> Self {
        Self {
            payment_method: payment_method.into(),
            payment_method_type: None,
            card_network: None,
            surcharge,
            tax_on_surcharge_percent: None,
        }
    }

    /// Narrow the entry to one payment method sub-type.
    #[must_use]
    pub fn payment_method_type(mut self, payment_method_type: impl Into<String>) -> Self {
        self.payment_method_type = Some(payment_method_type.into());
        self
    }

    /// Narrow the entry to one card network.
    #[must_use]
    pub fn card_network(mut self, card_network: impl Into<String>) -> Self {
        self.card_network = Some(card_network.into());
        self
    }

    /// Tax the surcharge at this percentage of the surcharge amount.
    #[must_use]
    pub fn tax_on_surcharge_percent(mut self, percent: f64) -> Self {
        self.tax_on_surcharge_percent = Some(percent);
        self
    }
}

/// A stored surcharge program: the structured configuration plus its version
/// metadata and any server-side advisories.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SurchargeRuleResponse {
    /// Human-readable program name.
    pub name: String,
    /// Version number of the stored program; bumped on every upsert.
    pub version: i64,

    /// Shop (business profile) the program is scoped to, or `None` when it is
    /// merchant-wide.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Per-method surcharges, evaluated top-to-bottom (first match wins).
    #[serde(default)]
    pub surcharges: Option<Vec<PerMethodSurchargeItem>>,
    /// Applied when no per-method entry matches.
    #[serde(default)]
    pub default_surcharge: Option<MethodSurcharge>,
    /// Whether the checkout shows a surcharge breakup screen.
    #[serde(default)]
    pub show_surcharge_breakup_screen: Option<bool>,
    /// RFC 3339 timestamp the program takes effect from.
    #[serde(default)]
    pub valid_from: Option<String>,
    /// RFC 3339 timestamp the program expires at, or `None` when open-ended.
    #[serde(default)]
    pub valid_until: Option<String>,
    /// Non-blocking advisories about the saved program, e.g. a network-scoped
    /// card surcharge that a connector cannot apply. Empty when there are
    /// none.
    #[serde(default = "Vec::new")]
    pub warnings: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn dictionary_decodes_records_and_a_null_active_id() {
        let dict: RoutingDictionary = serde_json::from_str(
            r#"{
                "merchant_id": "merch_1",
                "active_id": null,
                "records": [{
                    "id": "rou_1",
                    "profile_id": "pro_1",
                    "name": "EU Priority",
                    "kind": "priority",
                    "description": "EU traffic",
                    "created_at": 1767225600000,
                    "modified_at": 1767312000000,
                    "algorithm_for": "payment",
                    "brand_new_field": "keep me"
                }]
            }"#,
        )
        .unwrap();

        assert_eq!(dict.active_id, None);
        let record = &dict.records[0];
        assert_eq!(record.kind, "priority");
        // Milliseconds since epoch: an i32 field would overflow here.
        assert_eq!(record.created_at, Some(1_767_225_600_000));
        assert_eq!(record.algorithm_for.as_deref(), Some("payment"));
        assert_eq!(record.extra["brand_new_field"], "keep me");
    }

    #[test]
    fn merchant_routing_algorithm_keeps_the_algorithm_as_raw_json() {
        let algo: MerchantRoutingAlgorithm = serde_json::from_str(
            r#"{
                "id": "rou_1",
                "profile_id": "pro_1",
                "name": "EU Priority",
                "description": "",
                "algorithm": {"type": "priority", "data": [{"connector": "stripe"}]},
                "created_at": 1767225600000,
                "modified_at": 1767225600000,
                "algorithm_for": "payment"
            }"#,
        )
        .unwrap();

        assert_eq!(algo.algorithm["type"], "priority");
        assert_eq!(algo.algorithm["data"][0]["connector"], "stripe");
    }

    #[test]
    fn active_routing_config_distinguishes_the_envelope_from_a_record_list() {
        let envelope: ActiveRoutingConfig = serde_json::from_str(r#"{"algorithm": null}"#).unwrap();
        match envelope {
            ActiveRoutingConfig::Envelope(e) => assert!(e.algorithm.is_none()),
            other => panic!("expected the envelope arm, got {other:?}"),
        }

        let records: ActiveRoutingConfig = serde_json::from_str(
            r#"[{"id":"rou_1","profile_id":"pro_1","name":"n","kind":"single"}]"#,
        )
        .unwrap();
        match records {
            ActiveRoutingConfig::Records(r) => assert_eq!(r[0].id, "rou_1"),
            other => panic!("expected the records arm, got {other:?}"),
        }
    }

    #[test]
    fn default_profile_routing_prefers_the_per_profile_arm() {
        // The two arms are disjoint on their required fields, so a populated
        // array lands on the right one whatever the declaration order — this
        // half of the test guards the field types, not the ordering.
        let per_profile: DefaultProfileRouting = serde_json::from_str(
            r#"[{"profile_id":"pro_1","connectors":[{"connector":"stripe"}]}]"#,
        )
        .unwrap();
        match per_profile {
            DefaultProfileRouting::PerProfile(p) => {
                assert_eq!(p[0].profile_id, "pro_1");
                assert_eq!(p[0].connectors[0].connector, "stripe");
            }
            other => panic!("expected the per-profile arm, got {other:?}"),
        }

        let connectors: DefaultProfileRouting =
            serde_json::from_str(r#"[{"connector":"stripe","merchant_connector_id":"mca_1"}]"#)
                .unwrap();
        match connectors {
            DefaultProfileRouting::Connectors(c) => {
                assert_eq!(c[0].merchant_connector_id.as_deref(), Some("mca_1"));
            }
            other => panic!("expected the connectors arm, got {other:?}"),
        }

        // An empty array matches *both* arms, so it is decided purely by
        // declaration order: swapping the two variants makes this fail.
        let empty: DefaultProfileRouting = serde_json::from_str("[]").unwrap();
        match empty {
            DefaultProfileRouting::PerProfile(p) => assert!(p.is_empty()),
            other => panic!("an empty array must take the per-profile arm, got {other:?}"),
        }
    }

    #[test]
    fn surcharge_rule_response_round_trips_the_surcharge_union() {
        let rule: SurchargeRuleResponse = serde_json::from_str(
            r#"{
                "name": "EU surcharges",
                "profile_id": null,
                "version": 3,
                "valid_from": "2026-01-01T00:00:00Z",
                "valid_until": null,
                "surcharges": [
                    {"payment_method": "crypto", "surcharge": {"rate": {"percent": 1.0}}},
                    {
                        "payment_method": "card",
                        "card_network": "Visa",
                        "surcharge": {"fixed": {"amount": 35}},
                        "tax_on_surcharge_percent": 20.0
                    }
                ],
                "default_surcharge": {"fixed": {"amount": 10}},
                "warnings": ["card network scoping is ignored on stripe"]
            }"#,
        )
        .unwrap();

        assert_eq!(rule.version, 3);
        assert_eq!(rule.profile_id, None);
        let surcharges = rule.surcharges.expect("surcharges decode");
        assert_eq!(
            surcharges[0].surcharge,
            MethodSurcharge::Rate { percent: 1.0 }
        );
        assert_eq!(
            surcharges[1].surcharge,
            MethodSurcharge::Fixed { amount: 35 }
        );
        assert_eq!(surcharges[1].card_network.as_deref(), Some("Visa"));
        assert_eq!(surcharges[1].tax_on_surcharge_percent, Some(20.0));
        assert_eq!(
            rule.default_surcharge,
            Some(MethodSurcharge::Fixed { amount: 10 })
        );
        assert_eq!(rule.warnings.len(), 1);
    }

    #[test]
    fn surcharge_rule_response_defaults_warnings_to_empty() {
        let rule: SurchargeRuleResponse =
            serde_json::from_str(r#"{"name":"n","version":1}"#).unwrap();
        assert!(rule.warnings.is_empty());
        assert_eq!(rule.surcharges, None);
        assert_eq!(rule.valid_from, None);
    }

    /// The surcharge union must serialize externally-tagged: dropping the
    /// `rename` attributes gives `"Fixed"` / `"Rate"` and fails this.
    #[test]
    fn method_surcharge_serializes_with_lowercase_wire_tags() {
        assert_eq!(
            serde_json::to_value(MethodSurcharge::Fixed { amount: 35 }).unwrap(),
            json!({"fixed": {"amount": 35}})
        );
        assert_eq!(
            serde_json::to_value(MethodSurcharge::Rate { percent: 1.5 }).unwrap(),
            json!({"rate": {"percent": 1.5}})
        );
    }

    #[test]
    fn per_method_item_omits_the_scopes_it_was_not_given() {
        let item = PerMethodSurchargeItem::new("crypto", MethodSurcharge::Rate { percent: 1.0 });
        assert_eq!(
            serde_json::to_value(&item).unwrap(),
            json!({"payment_method": "crypto", "surcharge": {"rate": {"percent": 1.0}}})
        );

        let scoped = PerMethodSurchargeItem::new("card", MethodSurcharge::Fixed { amount: 35 })
            .card_network("Visa")
            .payment_method_type("credit")
            .tax_on_surcharge_percent(20.0);
        let value = serde_json::to_value(&scoped).unwrap();
        assert_eq!(value["card_network"], "Visa");
        assert_eq!(value["payment_method_type"], "credit");
        assert_eq!(value["tax_on_surcharge_percent"], 20.0);
    }

    #[test]
    fn denied_connectors_defaults_to_empty() {
        let denied: ProfileDeniedConnectorsResponse = serde_json::from_str("{}").unwrap();
        assert!(denied.denied_connectors.is_empty());

        let denied: ProfileDeniedConnectorsResponse =
            serde_json::from_str(r#"{"denied_connectors":["paypal"]}"#).unwrap();
        assert_eq!(denied.denied_connectors, vec!["paypal".to_string()]);
    }
}