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
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! The `processor_costs` resource: a merchant's own processor cost
//! schedules — what the processor the merchant brought itself charges it,
//! per connector and, as narrowly as the rate is written, per shop, payment
//! method, method type, card network or the processor's own method code.
//!
//! A schedule prices the rails that report no fee on the payment itself.
//! What it produces is stamped `estimated` on the settlement line, never
//! `reported`, and the rates that priced it are copied onto the line so the
//! figure survives the schedule being replaced or deleted.
//!
//! A rate is never edited in place: it priced transactions that already
//! happened. [`ProcessorCosts::update`] only closes, deactivates or annotates
//! a schedule; a price change is [`ProcessorCosts::replace`], which closes the
//! old window and opens the successor in one step.
//!
//! 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).

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

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

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

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

    /// Record a processor cost schedule.
    ///
    /// A `shop_id` that is well formed but not a shop of this merchant is
    /// answered `404`, and nothing is recorded.
    ///
    /// `POST /processor-costs?merchant_id=`
    pub async fn create(
        &self,
        merchant_id: &str,
        params: &CreateProcessorCostScheduleRequest,
    ) -> Result<ProcessorCostScheduleResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Post,
                "/processor-costs",
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Record several schedules at once, all or none — copy a price list
    /// across methods or shops.
    ///
    /// 1 to 200 entries. Every entry is validated before anything is stored:
    /// an invalid one is answered `422` naming its index, and nothing is
    /// stored. The answer lists the created schedules in request order.
    ///
    /// `POST /processor-costs/bulk?merchant_id=`
    pub async fn bulk_create(
        &self,
        merchant_id: &str,
        params: &BulkCreateProcessorCostSchedulesRequest,
    ) -> Result<Vec<ProcessorCostScheduleResponse>> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Post,
                "/processor-costs/bulk",
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Close, deactivate or annotate a schedule. The rate is not editable.
    ///
    /// `PUT /processor-costs/{schedule_id}?merchant_id=`
    pub async fn update(
        &self,
        merchant_id: &str,
        schedule_id: &str,
        params: &UpdateProcessorCostScheduleRequest,
    ) -> Result<ProcessorCostScheduleResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Put,
                &schedule_path(schedule_id),
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Close a schedule at `effective_from` and open its successor with the
    /// same scope and the same end, in one step: no transaction is priced by
    /// both rates, and none falls between them. Answers the successor.
    ///
    /// An `effective_from` outside the old schedule's window, an inactive
    /// schedule, or one a concurrent replacement already moved is answered
    /// `400` — retry against the schedule as it now stands.
    ///
    /// The API does not deduplicate this route, so no `Idempotency-Key` is
    /// sent (not even the client-wide default) and a network error or `5xx`
    /// is not replayed: read the schedules back before trying again.
    ///
    /// `POST /processor-costs/{schedule_id}/replace?merchant_id=`
    pub async fn replace(
        &self,
        merchant_id: &str,
        schedule_id: &str,
        params: &ReplaceProcessorCostScheduleRequest,
    ) -> Result<ProcessorCostScheduleResponse> {
        let body = to_json_vec(params)?;
        let path = format!("{}/replace", schedule_path(schedule_id));
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Post,
                &path,
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Delete a schedule. Restates nothing: every figure it derived is
    /// already stamped on the settlement lines it priced.
    ///
    /// `DELETE /processor-costs/{schedule_id}?merchant_id=`
    pub async fn delete(&self, merchant_id: &str, schedule_id: &str) -> Result<()> {
        // The API answers `{"deleted":true,"id":…}`. Any success body is
        // accepted, so the already-applied delete never reports an error.
        self.inner
            .request_body_keyed_with_query::<serde::de::IgnoredAny>(
                HttpMethod::Delete,
                &schedule_path(schedule_id),
                None,
                &merchant_query(merchant_id),
                None,
            )
            .await
            .map(|_| ())
    }
}

/// `/processor-costs/{schedule_id}`, percent-encoded.
fn schedule_path(schedule_id: &str) -> String {
    format!("/processor-costs/{}", encode_segment(schedule_id))
}

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

/// Body of [`ProcessorCosts::create`], and one entry of
/// [`BulkCreateProcessorCostSchedulesRequest`].
///
/// Scope narrows from the connector downwards: with every scope field
/// omitted, the rate covers every shop, method and network of that
/// connector.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateProcessorCostScheduleRequest {
    /// The connector the rate belongs to, e.g. `"stripe"`.
    pub connector: String,
    /// One shop. Omitted, the schedule covers every shop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shop_id: Option<String>,
    /// Payment-method scope, e.g. `"card"`. Omitted, any method.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method: Option<String>,
    /// Card-network scope, e.g. `"Visa"`. Omitted, any network.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_network: Option<String>,
    /// Payment-method-type scope. Omitted, any type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_type: Option<String>,
    /// The processor's own method identifier, for rails where the payment
    /// method type cannot tell two methods apart. Accepted only for
    /// connectors that report one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_method_code: Option<String>,
    /// The processor's own commission, in percent (e.g. `2.9`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percentage: Option<f64>,
    /// The underlying provider's fee the processor passes on, in percent.
    /// Added to `percentage`; the two together may not exceed 100.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider_fee_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; set and different, they are converted at the
    /// daily reference rate.
    #[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). Defaults to now.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effective_from: Option<String>,
    /// When it stops applying (ISO 8601, exclusive). Omitted, open-ended.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effective_to: Option<String>,
    /// Free-text note, e.g. which contract the rate came from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: 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 CreateProcessorCostScheduleRequest {
    /// A schedule for `connector`, unscoped below it.
    pub fn new(connector: impl Into<String>) -> Self {
        Self {
            connector: connector.into(),
            ..Default::default()
        }
    }

    /// Scope the schedule 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
    }

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

    /// Scope the schedule 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
    }

    /// Scope the schedule to one payment method 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
    }

    /// Scope the schedule to one of the processor's own method codes.
    #[must_use]
    pub fn connector_method_code(mut self, connector_method_code: impl Into<String>) -> Self {
        self.connector_method_code = Some(connector_method_code.into());
        self
    }

    /// Set the processor's own commission, in percent.
    #[must_use]
    pub fn percentage(mut self, percentage: f64) -> Self {
        self.percentage = Some(percentage);
        self
    }

    /// Set the underlying provider's fee, in percent.
    #[must_use]
    pub fn provider_fee_percentage(mut self, provider_fee_percentage: f64) -> Self {
        self.provider_fee_percentage = Some(provider_fee_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 a free-text note.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// Names of `CreateProcessorCostScheduleRequest`'s fields as they appear on
/// the wire (`extra` excluded).
const CREATE_PROCESSOR_COST_SCHEDULE_REQUEST_NAMED: &[&str] = &[
    "connector",
    "shop_id",
    "payment_method",
    "card_network",
    "payment_method_type",
    "connector_method_code",
    "percentage",
    "provider_fee_percentage",
    "flat_amount",
    "flat_currency",
    "min_amount",
    "max_amount",
    "effective_from",
    "effective_to",
    "description",
];

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

/// Body of [`ProcessorCosts::bulk_create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct BulkCreateProcessorCostSchedulesRequest {
    /// 1 to 200 schedules.
    pub schedules: Vec<CreateProcessorCostScheduleRequest>,
}

impl BulkCreateProcessorCostSchedulesRequest {
    /// Record `schedules`, all or none.
    pub fn new(schedules: Vec<CreateProcessorCostScheduleRequest>) -> Self {
        Self { schedules }
    }
}

impl ValidateRequest for BulkCreateProcessorCostSchedulesRequest {
    fn validate(&self) -> Result<()> {
        self.schedules
            .iter()
            .try_for_each(CreateProcessorCostScheduleRequest::validate)
    }
}

/// Body of [`ProcessorCosts::update`]. Only the fields you set are sent.
///
/// The rate itself is not editable, and a closed window cannot be reopened.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateProcessorCostScheduleRequest {
    /// 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 schedule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
    /// Replace the free-text note.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl UpdateProcessorCostScheduleRequest {
    /// 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 schedule.
    #[must_use]
    pub fn is_active(mut self, is_active: bool) -> Self {
        self.is_active = Some(is_active);
        self
    }

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

/// Body of [`ProcessorCosts::replace`]: the successor's rate. The scope and
/// the end of the window carry over from the schedule being replaced.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ReplaceProcessorCostScheduleRequest {
    /// The processor's own commission, in percent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percentage: Option<f64>,
    /// The underlying provider's fee, in percent, added to `percentage`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider_fee_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.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flat_currency: Option<String>,
    /// Per-transaction floor.
    #[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 new rate starts and the old one stops (ISO 8601). Defaults to
    /// now. Must fall inside the old schedule's window.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effective_from: Option<String>,
    /// Free-text note for the new rate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl ReplaceProcessorCostScheduleRequest {
    /// An empty rate; set its components.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the processor's own commission, in percent.
    #[must_use]
    pub fn percentage(mut self, percentage: f64) -> Self {
        self.percentage = Some(percentage);
        self
    }

    /// Set the underlying provider's fee, in percent.
    #[must_use]
    pub fn provider_fee_percentage(mut self, provider_fee_percentage: f64) -> Self {
        self.provider_fee_percentage = Some(provider_fee_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 new rate starts (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 a free-text note for the new rate.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

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

    const SCHEDULE_JSON: &str = r#"{
        "id": "pcs_1",
        "merchant_id": "mer_1",
        "shop_id": null,
        "connector": "stripe",
        "payment_method": "card",
        "card_network": "Visa",
        "percentage": 2.9,
        "flat_amount": 30,
        "flat_currency": "USD",
        "effective_from": "2026-01-01T00:00:00Z",
        "is_active": true,
        "surprise_field": 1
    }"#;

    #[tokio::test]
    async fn list_gets_the_merchant_schedules() {
        let (client, mock) = client_with(vec![Step::ok(&format!("[{SCHEDULE_JSON}]"))]);
        let out = client.processor_costs().list("mer_1").await.unwrap();
        assert_eq!(out[0].id, "pcs_1");
        assert_eq!(out[0].percentage, Some(2.9));
        assert!(out[0].shop_id.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/processor-costs?merchant_id=mer_1"
        );
    }

    #[tokio::test]
    async fn create_posts_the_schedule_and_omits_unset_scope() {
        let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
        let params = CreateProcessorCostScheduleRequest::new("stripe")
            .payment_method("card")
            .percentage(2.9)
            .flat_amount(30);
        let out = client
            .processor_costs()
            .create("mer_1", &params)
            .await
            .unwrap();
        assert_eq!(out.connector, "stripe");
        assert_eq!(out.flat_amount, Some(30));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/processor-costs?merchant_id=mer_1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"connector":"stripe","payment_method":"card","percentage":2.9,
                   "flat_amount":30})
        );
    }

    #[tokio::test]
    async fn bulk_create_posts_every_schedule_in_order() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            "[{SCHEDULE_JSON},{SCHEDULE_JSON}]"
        ))]);
        let params = BulkCreateProcessorCostSchedulesRequest::new(vec![
            CreateProcessorCostScheduleRequest::new("stripe").card_network("Visa"),
            CreateProcessorCostScheduleRequest::new("stripe").card_network("Amex"),
        ]);
        let out = client
            .processor_costs()
            .bulk_create("mer_1", &params)
            .await
            .unwrap();
        assert_eq!(out.len(), 2);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/processor-costs/bulk?merchant_id=mer_1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"schedules":[
                {"connector":"stripe","card_network":"Visa"},
                {"connector":"stripe","card_network":"Amex"}]})
        );
    }

    #[tokio::test]
    async fn update_puts_the_encoded_schedule_path() {
        let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
        let params = UpdateProcessorCostScheduleRequest::new()
            .effective_to("2026-06-01T00:00:00Z")
            .is_active(false);
        client
            .processor_costs()
            .update("mer_1", "pcs/1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/processor-costs/pcs%2F1?merchant_id=mer_1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"effective_to":"2026-06-01T00:00:00Z","is_active":false})
        );
    }

    #[tokio::test]
    async fn replace_posts_the_new_rate() {
        let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
        let params = ReplaceProcessorCostScheduleRequest::new()
            .percentage(3.1)
            .effective_from("2026-07-01T00:00:00Z");
        let out = client
            .processor_costs()
            .replace("mer_1", "pcs/1", &params)
            .await
            .unwrap();
        assert_eq!(out.id, "pcs_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/processor-costs/pcs%2F1/replace?merchant_id=mer_1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"percentage":3.1,"effective_from":"2026-07-01T00:00:00Z"})
        );
        assert!(!seen[0].had_idempotency_key());
    }

    /// The API does not deduplicate a replace, so a client-wide key must not
    /// reach it: with one it would be replayed after a `503` into a second
    /// window change. Mutation: call `request(.., None)` again — the header
    /// appears and the request count becomes 2.
    #[tokio::test]
    async fn replace_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(SCHEDULE_JSON),
            ],
            2,
        );
        let params = ReplaceProcessorCostScheduleRequest::new().percentage(3.1);
        assert!(
            client
                .with_idempotency_key("client-key")
                .processor_costs()
                .replace("mer_1", "pcs_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_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(SCHEDULE_JSON),
            ],
            2,
        );
        let params = CreateProcessorCostScheduleRequest::new("stripe");
        assert!(
            client
                .with_idempotency_key("client-key")
                .processor_costs()
                .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 replace_without_a_key_is_not_replayed_on_a_server_error() {
        // The first attempt may already have closed the old window.
        let (client, mock) = client_with_retries(vec![Step::status(500, "{}")], 2);
        let params = ReplaceProcessorCostScheduleRequest::new().percentage(3.1);
        assert!(
            client
                .processor_costs()
                .replace("mer_1", "pcs_1", &params)
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
        assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn delete_deletes_the_encoded_schedule_and_accepts_the_api_body() {
        // The body the API answers with; decoding it as `()` fails.
        let (client, mock) = client_with(vec![Step::ok(r#"{"deleted":true,"id":"pcs/1"}"#)]);
        client
            .processor_costs()
            .delete("mer_1", "pcs/1")
            .await
            .unwrap();

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

    #[tokio::test]
    async fn delete_accepts_an_empty_body() {
        let (client, _mock) = client_with(vec![Step::ok("")]);
        client
            .processor_costs()
            .delete("mer_1", "pcs_1")
            .await
            .unwrap();
    }

    /// Drift guard for `CREATE_PROCESSOR_COST_SCHEDULE_REQUEST_NAMED`.
    #[test]
    fn create_processor_cost_schedule_request_named_fields_are_complete() {
        let req = CreateProcessorCostScheduleRequest::new("stripe")
            .shop_id("pro_1")
            .payment_method("card")
            .card_network("Visa")
            .payment_method_type("credit")
            .connector_method_code("code_1")
            .percentage(2.9)
            .provider_fee_percentage(0.5)
            .flat_amount(30)
            .flat_currency("USD")
            .min_amount(10)
            .max_amount(1000)
            .effective_from("2026-01-01T00:00:00Z")
            .effective_to("2027-01-01T00:00:00Z")
            .description("contract A");
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                CREATE_PROCESSOR_COST_SCHEDULE_REQUEST_NAMED.contains(&key.as_str()),
                "CREATE_PROCESSOR_COST_SCHEDULE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn bulk_validate_rejects_a_colliding_extra_key_in_any_entry() {
        let mut second = CreateProcessorCostScheduleRequest::new("stripe");
        second.extra.insert("connector".to_string(), json!("adyen"));
        let req = BulkCreateProcessorCostSchedulesRequest::new(vec![
            CreateProcessorCostScheduleRequest::new("stripe"),
            second,
        ]);
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("connector")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }
}