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
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! The `fees` resource: merchant-scoped fee schedules and the merchant-owned
//! Euclid fee-rule program.
//!
//! 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.
//!
//! [`Fees::rules`] manages the merchant-owned fee-rule program, which takes
//! precedence over the flat schedules. A program is scoped either to one shop
//! (`profile_id`) or merchant-wide; a shop-scoped program wins for that shop,
//! otherwise the merchant-wide one applies. Programs are open JSON documents —
//! see the API reference for the Euclid program shape.

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::{
    FeeRulePreviewResponse, FeeScheduleResponse, PlatformFeeRuleRecord,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
use crate::resources::fee_program::PlatformFeeProgram;

// `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 }
    }

    /// The merchant-owned Euclid fee-rule program (`/merchant-fees/rules`).
    pub fn rules(&self) -> FeeRules {
        FeeRules::new(self.inner.clone())
    }

    /// 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
    }
}

/// The merchant's Euclid fee-rule programs (merchant-wide or per-shop, one
/// active program per scope), obtained via [`Fees::rules`].
///
/// The SDK injects `fee_owner: "merchant"` into every upserted program; set
/// `profile_id` on the program body to scope it to a shop.
#[derive(Debug, Clone)]
pub struct FeeRules {
    inner: Arc<Inner>,
}

/// The `fee_owner` value this merchant-facing surface pins on every upserted
/// fee-rule program. The platform surface is admin-only and not part of this
/// SDK, so the value is never anything else.
const MERCHANT_FEE_OWNER: &str = "merchant";

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

    /// Create or replace the merchant's fee-rule program (a new active
    /// version; the previous version is deactivated server-side).
    ///
    /// `params` is the program body — `algorithm` plus optional `name`,
    /// `profile_id` shop scope, and `valid_from` / `valid_until` window. It
    /// must be a JSON object; the SDK adds `fee_owner: "merchant"` to it.
    pub async fn upsert(&self, params: &Value, merchant_id: &str) -> Result<PlatformFeeRuleRecord> {
        let body = to_json_vec(&with_merchant_fee_owner(params)?)?;
        let query = [("merchant_id", merchant_id.to_string())];
        self.inner
            .request(
                HttpMethod::Put,
                "/merchant-fees/rules",
                Some(&body),
                &query,
                None,
            )
            .await
    }

    /// Create or replace the merchant's fee-rule program from a typed program
    /// built with [`crate::resources::fee_program::fee_program`].
    ///
    /// A convenience over [`Self::upsert`]: it wraps `program` as `algorithm`
    /// and adds `fee_owner: "merchant"`. Pass `profile_id` to scope the program
    /// to one shop, or `None` for a merchant-wide program. For the remaining
    /// body fields (`name`, `valid_from`, `valid_until`) use [`Self::upsert`].
    pub async fn upsert_program(
        &self,
        program: &PlatformFeeProgram,
        profile_id: Option<&str>,
        merchant_id: &str,
    ) -> Result<PlatformFeeRuleRecord> {
        let mut body = serde_json::Map::new();
        let algorithm =
            serde_json::to_value(program).map_err(|e| DelopayError::Decode(e.to_string()))?;
        body.insert("algorithm".to_string(), algorithm);
        if let Some(id) = profile_id {
            body.insert("profile_id".to_string(), Value::String(id.to_string()));
        }
        self.upsert(&Value::Object(body), merchant_id).await
    }

    /// Retrieve the active fee-rule program for a scope, or `None` when none
    /// is set.
    ///
    /// Pass `None` for `profile_id` to get the merchant-wide program, or a
    /// shop ID to get that shop's program.
    pub async fn retrieve(
        &self,
        merchant_id: &str,
        profile_id: Option<&str>,
    ) -> Result<Option<PlatformFeeRuleRecord>> {
        let query = rules_query(merchant_id, profile_id);
        self.inner
            .request(HttpMethod::Get, "/merchant-fees/rules", None, &query, None)
            .await
    }

    /// Deactivate a fee-rule program, falling back to the flat fee schedules
    /// and volume tier. Idempotent.
    ///
    /// Pass `None` for `profile_id` to target the merchant-wide program, or a
    /// shop ID to delete only that shop's program (other shops' programs are
    /// left intact).
    pub async fn delete(&self, merchant_id: &str, profile_id: Option<&str>) -> Result<()> {
        let query = rules_query(merchant_id, profile_id);
        self.inner
            .request(
                HttpMethod::Delete,
                "/merchant-fees/rules",
                None,
                &query,
                None,
            )
            .await
    }

    /// Dry-run a candidate fee-rule program against a sample transaction.
    /// Returns the matched rule name, whether it fell through, and the
    /// computed fee. Persists nothing.
    ///
    /// `input` is the candidate program plus the sample transaction fields —
    /// see the API reference.
    pub async fn preview(
        &self,
        input: &Value,
        merchant_id: &str,
    ) -> Result<FeeRulePreviewResponse> {
        let body = to_json_vec(input)?;
        let query = [("merchant_id", merchant_id.to_string())];
        self.inner
            .request(
                HttpMethod::Post,
                "/merchant-fees/rules/preview",
                Some(&body),
                &query,
                None,
            )
            .await
    }
}

/// `merchant_id`, plus `profile_id` when a shop scope was given. Omitting the
/// key entirely (rather than sending an empty value) is what selects the
/// merchant-wide program server-side.
fn rules_query(merchant_id: &str, profile_id: Option<&str>) -> Vec<(&'static str, String)> {
    let mut q = vec![("merchant_id", merchant_id.to_string())];
    if let Some(id) = profile_id {
        q.push(("profile_id", id.to_string()));
    }
    q
}

/// The program body with `fee_owner: "merchant"` set. Rejects a non-object
/// body rather than silently sending something the server cannot own.
fn with_merchant_fee_owner(params: &Value) -> Result<Value> {
    let mut obj = match params {
        Value::Object(map) => map.clone(),
        other => {
            return Err(DelopayError::InvalidRequest(format!(
                "fee-rule program body must be a JSON object, got {}",
                json_kind(other)
            )));
        }
    };
    obj.insert(
        "fee_owner".to_string(),
        Value::String(MERCHANT_FEE_OWNER.to_string()),
    );
    Ok(Value::Object(obj))
}

/// A short name for a JSON value's kind, for error messages.
fn json_kind(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "a boolean",
        Value::Number(_) => "a number",
        Value::String(_) => "a string",
        Value::Array(_) => "an array",
        Value::Object(_) => "an object",
    }
}

/// 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>,
    /// 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",
];

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"
                )));
            }
        }
        Ok(())
    }
}

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,
            extra: serde_json::Map::new(),
        }
    }

    /// 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).
    #[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>,
    /// 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",
];

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"
                )));
            }
        }
        Ok(())
    }
}

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

    /// 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
    }"#;

    const PROGRAM_JSON: &str = r#"{
        "name": "standard",
        "fee_owner": "merchant",
        "algorithm": {"defaultSelection": {}, "rules": [], "metadata": {}},
        "created_at": 1767225600,
        "modified_at": 1767225600
    }"#;

    fn sample_program() -> Value {
        json!({
            "algorithm": {
                "defaultSelection": {},
                "rules": [],
                "metadata": {}
            },
            "name": "standard",
            "profile_id": "pro_1"
        })
    }

    #[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);

        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");
    }

    #[tokio::test]
    async fn rules_upsert_injects_the_merchant_fee_owner() {
        // The server needs `fee_owner` to decide which fee book the program
        // lands in; dropping the injection makes this assertion fail.
        let (client, mock) = client_with(vec![Step::ok(PROGRAM_JSON)]);
        let record = client
            .fees()
            .rules()
            .upsert(&sample_program(), "merch_1")
            .await
            .unwrap();
        assert_eq!(record.name, "standard");
        assert_eq!(record.created_at, Some(1_767_225_600));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/merchant-fees/rules?merchant_id=merch_1"
        );
        let body = seen[0].body_json();
        assert_eq!(body["fee_owner"], "merchant");
        // The caller's own fields survive the injection.
        assert_eq!(body["name"], "standard");
        assert_eq!(body["profile_id"], "pro_1");
        assert_eq!(body["algorithm"]["rules"], json!([]));
    }

    #[tokio::test]
    async fn rules_upsert_program_wraps_the_typed_program_as_algorithm() {
        use crate::resources::fee_program::{FeeRuleConditions, FeeRuleInput, FeeSpecInput};

        let (client, mock) = client_with(vec![Step::ok(PROGRAM_JSON)]);
        let program = crate::resources::fee_program::fee_program()
            .rule(
                FeeRuleInput::new("crypto", FeeSpecInput::new().percentage(1.0))
                    .when(FeeRuleConditions::new().payment_method("crypto")),
            )
            .otherwise(FeeSpecInput::new().percentage(3.0))
            .build()
            .unwrap();
        client
            .fees()
            .rules()
            .upsert_program(&program, Some("pro_1"), "merch_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/merchant-fees/rules?merchant_id=merch_1"
        );
        let body = seen[0].body_json();
        assert_eq!(body["fee_owner"], "merchant");
        assert_eq!(body["profile_id"], "pro_1");
        assert_eq!(body["algorithm"]["rules"][0]["name"], "crypto");
        assert_eq!(
            body["algorithm"]["rules"][0]["statements"][0]["condition"][0]["lhs"],
            "payment_method"
        );
        assert_eq!(
            body["algorithm"]["defaultSelection"]["fee"]["percentage_fee"],
            3.0
        );
    }

    #[tokio::test]
    async fn rules_upsert_program_omits_profile_id_when_merchant_wide() {
        let (client, mock) = client_with(vec![Step::ok(PROGRAM_JSON)]);
        let program = crate::resources::fee_program::PlatformFeeProgram::default();
        client
            .fees()
            .rules()
            .upsert_program(&program, None, "merch_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].body_json().get("profile_id"), None);
    }

    #[tokio::test]
    async fn rules_upsert_overrides_a_caller_supplied_fee_owner() {
        // A merchant must not be able to write a platform-owned program by
        // putting `fee_owner` in the body themselves.
        let (client, mock) = client_with(vec![Step::ok(PROGRAM_JSON)]);
        let program = json!({"algorithm": {}, "fee_owner": "platform"});
        client
            .fees()
            .rules()
            .upsert(&program, "merch_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].body_json()["fee_owner"], "merchant");
    }

    #[tokio::test]
    async fn rules_upsert_rejects_a_non_object_program() {
        let (client, mock) = client_with(vec![Step::ok("{}")]);
        let err = client
            .fees()
            .rules()
            .upsert(&json!([1, 2, 3]), "merch_1")
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::InvalidRequest(_)));
        assert!(
            mock.seen.lock().unwrap().is_empty(),
            "a non-object program must not reach the transport"
        );
    }

    #[tokio::test]
    async fn rules_retrieve_and_delete_scope_by_profile_when_given() {
        let (client, mock) = client_with(vec![
            Step::ok(PROGRAM_JSON),
            Step::ok("null"),
            Step::ok("null"),
        ]);
        let rules = client.fees().rules();
        rules.retrieve("merch_1", Some("pro_1")).await.unwrap();
        rules.retrieve("merch_1", None).await.unwrap();
        rules.delete("merch_1", Some("pro_1")).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/merchant-fees/rules?merchant_id=merch_1&profile_id=pro_1"
        );
        // Merchant-wide: `profile_id` must be absent, not empty.
        assert_eq!(
            seen[1].url,
            "https://api.test/merchant-fees/rules?merchant_id=merch_1"
        );
        assert_eq!(seen[2].method, "DELETE");
        assert_eq!(
            seen[2].url,
            "https://api.test/merchant-fees/rules?merchant_id=merch_1&profile_id=pro_1"
        );
    }

    #[tokio::test]
    async fn rules_retrieve_decodes_a_null_program_as_none() {
        let (client, _mock) = client_with(vec![Step::ok("null"), Step::ok(PROGRAM_JSON)]);
        let rules = client.fees().rules();
        assert!(
            rules.retrieve("merch_1", None).await.unwrap().is_none(),
            "a null body means no program is set for the scope"
        );
        let record = rules
            .retrieve("merch_1", Some("pro_1"))
            .await
            .unwrap()
            .expect("a program body decodes to Some");
        assert_eq!(record.name, "standard");
    }

    #[tokio::test]
    async fn rules_preview_posts_the_candidate_program_verbatim() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"matched_rule":"crypto","fell_through":false,"fee_amount":125,"fee_currency":"USD"}"#,
        )]);
        let input = json!({
            "algorithm": {"defaultSelection": {}, "rules": [], "metadata": {}},
            "amount": 1000,
            "currency": "USD"
        });
        let preview = client
            .fees()
            .rules()
            .preview(&input, "merch_1")
            .await
            .unwrap();
        assert_eq!(preview.matched_rule.as_deref(), Some("crypto"));
        assert_eq!(preview.fee_amount, Some(125));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/merchant-fees/rules/preview?merchant_id=merch_1"
        );
        let body = seen[0].body_json();
        assert_eq!(body["amount"], 1000);
        assert_eq!(body["currency"], "USD");
        // Preview is a dry run against a candidate program: unlike `upsert`,
        // nothing is injected into the body.
        assert_eq!(body.get("fee_owner"), None);
    }

    /// 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()),
            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),
            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(_)
        ));
    }
}