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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
//! The `refunds` resource.

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::common::{ListResponse, RefundType};
use crate::core::models::refund::RefundResponse;
use crate::core::models::refund_request::{
    BuyerRefundRequest, BuyerRefundRequestList, RefundBulkBlockBuyerResponse,
    RefundBulkBlockPreviewResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
use crate::resources::buyer_blocklist::BuyerBlocklistKind;

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

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

    /// Refund a payment (fully or partially).
    ///
    /// A dashboard-initiated refund is subject to the caller's operation-limit
    /// rule, resolved against the role the request authenticated with. An
    /// over-limit refund fails with `DE_01` when the rule blocks, or with HTTP
    /// 409 `DE_06` when it requires approval — the refund is then parked for a
    /// second person and `error.data` carries `pending_operation_id`,
    /// `expires_at` and the limit it ran into. No refund exists in either case.
    pub async fn create(&self, params: &RefundCreateRequest) -> Result<RefundResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/refunds", Some(&body), &[], None)
            .await
    }

    /// Refund a payment with an `Idempotency-Key` so the call is retry-safe.
    pub async fn create_idempotent(
        &self,
        params: &RefundCreateRequest,
        idempotency_key: &str,
    ) -> Result<RefundResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/refunds",
                Some(&body),
                &[],
                Some(idempotency_key),
            )
            .await
    }

    /// Retrieve a refund by ID.
    pub async fn retrieve(&self, refund_id: &str) -> Result<RefundResponse> {
        let path = format!("/refunds/{}", encode_segment(refund_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a refund's reason or metadata.
    pub async fn update(
        &self,
        refund_id: &str,
        params: &RefundUpdateRequest,
    ) -> Result<RefundResponse> {
        let path = format!("/refunds/{}", encode_segment(refund_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// List refunds. Pass optional filter/pagination params as a JSON object.
    pub async fn list(&self, params: Option<&Value>) -> Result<ListResponse<RefundResponse>> {
        let body = params
            .cloned()
            .unwrap_or_else(|| Value::Object(Default::default()));
        let bytes = to_json_vec(&body)?;
        self.inner
            .request(HttpMethod::Post, "/refunds/list", Some(&bytes), &[], None)
            .await
    }

    /// List refunds scoped to the profile the API key belongs to. Pass
    /// optional filter/pagination params as a JSON object.
    pub async fn list_by_profile(
        &self,
        params: Option<&Value>,
    ) -> Result<ListResponse<RefundResponse>> {
        let body = params
            .cloned()
            .unwrap_or_else(|| Value::Object(Default::default()));
        let bytes = to_json_vec(&body)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/refunds/profile/list",
                Some(&bytes),
                &[],
                None,
            )
            .await
    }

    /// Retrieve the filter options available for refunds. Query keys are open
    /// — pass `&[]` for none; see the API reference.
    pub async fn filters(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(HttpMethod::Get, "/refunds/filter", None, query, None)
            .await
    }

    /// Retrieve aggregated refund statistics. Query keys are open — see the
    /// API reference.
    pub async fn aggregate(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(HttpMethod::Get, "/refunds/aggregate", None, query, None)
            .await
    }

    /// Retrieve aggregated refund statistics, scoped to the profile the API
    /// key belongs to. Query keys are open — see the API reference.
    pub async fn aggregate_by_profile(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(
                HttpMethod::Get,
                "/refunds/profile/aggregate",
                None,
                query,
                None,
            )
            .await
    }

    /// Manually move a refund to a new status. The body shape is open — see
    /// the API reference.
    pub async fn manual_update(&self, refund_id: &str, params: &Value) -> Result<RefundResponse> {
        let path = format!("/refunds/{}/manual-update", encode_segment(refund_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Refund requests buyers raised from the customer portal, newest first.
    /// Limited to the caller's shop when the caller is scoped to one.
    /// `GET /refund-requests`
    pub async fn list_requests(
        &self,
        params: Option<&BuyerRefundRequestListParams>,
    ) -> Result<BuyerRefundRequestList> {
        let query = params
            .map(BuyerRefundRequestListParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/refund-requests", None, &query, None)
            .await
    }

    /// Approve a buyer's refund request with a refund of its payment that has
    /// succeeded, made with [`create`](Self::create) after the buyer asked.
    /// Approving records the decision and moves no money. A refund still
    /// `pending` or in `review` is refused: check it again with
    /// [`retrieve`](Self::retrieve) and approve once it has succeeded, rather
    /// than creating another refund.
    ///
    /// `POST /refund-requests/{id}/approve`
    pub async fn approve_request(
        &self,
        request_id: &str,
        params: &BuyerRefundRequestApprove,
    ) -> Result<BuyerRefundRequest> {
        params.validate()?;
        let path = format!("/refund-requests/{}/approve", encode_segment(request_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
            .await
    }

    /// Decline a buyer's refund request. The buyer sees the reply.
    /// `POST /refund-requests/{id}/decline`
    pub async fn decline_request(
        &self,
        request_id: &str,
        params: &BuyerRefundRequestDecline,
    ) -> Result<BuyerRefundRequest> {
        let path = format!("/refund-requests/{}/decline", encode_segment(request_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
            .await
    }

    /// Every identifier a block of each selected refund's buyer would name,
    /// changing nothing: the payment's email and customer id, and every IP
    /// address and device id seen on its checkout, each with where it was
    /// seen and whether it is already blocked. At most `max_refunds` are read.
    ///
    /// `POST /refunds/bulk/block-buyer/preview`. Needs a dashboard JWT.
    pub async fn bulk_block_preview(
        &self,
        params: &RefundBulkBlockPreviewRequest,
    ) -> Result<RefundBulkBlockPreviewResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/refunds/bulk/block-buyer/preview",
                Some(&body),
                None,
            )
            .await
    }

    /// Add the buyer of each listed refund's payment to the buyer blocklist
    /// with the chosen `kinds`, leaving out the `exclude`d identifiers, at most
    /// the preview's `max_run_refunds` per call. The server reads each payment
    /// again and never blocks a value the request names. Identifiers already
    /// blocked are not added again, and every refund gets its own result.
    ///
    /// `POST /refunds/bulk/block-buyer`. Needs a dashboard JWT.
    pub async fn bulk_block_buyer(
        &self,
        params: &RefundBulkBlockBuyerRequest,
    ) -> Result<RefundBulkBlockBuyerResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/refunds/bulk/block-buyer",
                Some(&body),
                None,
            )
            .await
    }
}

/// Parameters for [`Refunds::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundCreateRequest {
    /// ID of the payment to refund.
    pub payment_id: String,
    /// Provide your own refund ID (acts as an idempotency key server-side).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refund_id: Option<String>,
    /// Amount to refund in minor units. Omit to refund the full amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<i64>,
    /// Reason for the refund (stored for reporting).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Refund processing type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refund_type: Option<RefundType>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// How the refund is credited to the payment's product lines, as
    /// [`Payments::product_lines`](crate::resources::payments::Payments::product_lines)
    /// lists them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_credits: Option<Vec<RefundLineCreditRequest>>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// How much of a refund goes to one product line.
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundLineCreditRequest {
    /// The payment line's ID.
    pub line_id: String,
    /// Units of the line given back. `None` for an amount-only credit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quantity: Option<i32>,
    /// How much of the refund goes to the line, in minor units. Stated,
    /// never derived.
    pub amount: i64,
    /// The part of `amount` that is tax, for a line that carries a tax
    /// amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tax_amount: Option<i64>,
}

impl RefundLineCreditRequest {
    /// Credit `amount` minor units to `line_id`.
    pub fn new(line_id: impl Into<String>, amount: i64) -> Self {
        Self {
            line_id: line_id.into(),
            amount,
            ..Default::default()
        }
    }

    /// Units of the line given back.
    #[must_use]
    pub fn quantity(mut self, quantity: i32) -> Self {
        self.quantity = Some(quantity);
        self
    }

    /// The tax part of the amount.
    #[must_use]
    pub fn tax_amount(mut self, tax_amount: i64) -> Self {
        self.tax_amount = Some(tax_amount);
        self
    }
}

/// Names of `RefundCreateRequest`'s fields, as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const REFUND_CREATE_REQUEST_NAMED: &[&str] = &[
    "payment_id",
    "refund_id",
    "amount",
    "reason",
    "refund_type",
    "metadata",
    "line_credits",
];

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

impl RefundCreateRequest {
    /// A full refund of `payment_id`.
    pub fn new(payment_id: impl Into<String>) -> Self {
        Self {
            payment_id: payment_id.into(),
            ..Default::default()
        }
    }

    /// Refund only `amount` (minor units) instead of the full payment.
    pub fn amount(mut self, amount: i64) -> Self {
        self.amount = Some(amount);
        self
    }

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

    /// Set the refund processing type.
    pub fn refund_type(mut self, refund_type: RefundType) -> Self {
        self.refund_type = Some(refund_type);
        self
    }

    /// Credit the refund to these product lines.
    #[must_use]
    pub fn line_credits(mut self, credits: Vec<RefundLineCreditRequest>) -> Self {
        self.line_credits = Some(credits);
        self
    }
}

/// Parameters for [`Refunds::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundUpdateRequest {
    /// Updated reason.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Updated metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

/// Rejects an `extra` key that collides with one of `named`, so the body
/// never carries a duplicate key.
fn reject_extra_collisions(
    extra: &serde_json::Map<String, Value>,
    named: &[&str],
    type_name: &str,
) -> Result<()> {
    for key in extra.keys() {
        if named.contains(&key.as_str()) {
            return Err(DelopayError::InvalidRequest(format!(
                "`extra` key `{key}` collides with a named field on {type_name}"
            )));
        }
    }
    Ok(())
}

/// A buyer refund request's status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BuyerRefundRequestStatus {
    /// Waiting for the shop.
    Requested,
    /// Approved with a refund.
    Approved,
    /// Declined.
    Declined,
}

impl BuyerRefundRequestStatus {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Requested => "requested",
            Self::Approved => "approved",
            Self::Declined => "declined",
        }
    }
}

/// Filters for [`Refunds::list_requests`].
#[derive(Debug, Clone, Default)]
pub struct BuyerRefundRequestListParams {
    /// Only requests for this payment.
    pub payment_id: Option<String>,
    /// Only requests in this status.
    pub status: Option<BuyerRefundRequestStatus>,
    /// Page size.
    pub limit: Option<u32>,
    /// Requests to skip.
    pub offset: Option<u32>,
}

impl BuyerRefundRequestListParams {
    pub(crate) fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = &self.payment_id {
            q.push(("payment_id", v.clone()));
        }
        if let Some(v) = self.status {
            q.push(("status", v.as_str().to_string()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// Parameters for [`Refunds::approve_request`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerRefundRequestApprove {
    /// A succeeded refund of the request's payment.
    pub refund_id: String,
    /// What to tell the buyer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reply: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl BuyerRefundRequestApprove {
    /// Approve with `refund_id`.
    pub fn new(refund_id: impl Into<String>) -> Self {
        Self {
            refund_id: refund_id.into(),
            ..Default::default()
        }
    }

    /// Set what to tell the buyer.
    #[must_use]
    pub fn reply(mut self, reply: impl Into<String>) -> Self {
        self.reply = Some(reply.into());
        self
    }
}

/// Names of `BuyerRefundRequestApprove`'s fields as they appear on the wire
/// (`extra` excluded).
const BUYER_REFUND_REQUEST_APPROVE_NAMED: &[&str] = &["refund_id", "reply"];

impl ValidateRequest for BuyerRefundRequestApprove {
    fn validate(&self) -> Result<()> {
        reject_extra_collisions(
            &self.extra,
            BUYER_REFUND_REQUEST_APPROVE_NAMED,
            "BuyerRefundRequestApprove",
        )
    }
}

/// Parameters for [`Refunds::decline_request`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerRefundRequestDecline {
    /// What to tell the buyer.
    pub reply: String,
}

impl BuyerRefundRequestDecline {
    /// Decline with `reply`.
    pub fn new(reply: impl Into<String>) -> Self {
        Self {
            reply: reply.into(),
        }
    }
}

/// Parameters for [`Refunds::bulk_block_preview`]. Name the refunds by `ids`
/// or by `filters`, exactly one of the two.
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundBulkBlockPreviewRequest {
    /// Refund ids.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ids: Option<Vec<String>>,
    /// Every refund matching the refund list's filter body, as
    /// [`Refunds::list`] takes it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<Value>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl RefundBulkBlockPreviewRequest {
    /// A preview over the listed refunds.
    pub fn for_ids(ids: Vec<String>) -> Self {
        Self {
            ids: Some(ids),
            ..Default::default()
        }
    }

    /// A preview over every refund matching `filters`.
    pub fn for_filters(filters: Value) -> Self {
        Self {
            filters: Some(filters),
            ..Default::default()
        }
    }
}

/// Names of `RefundBulkBlockPreviewRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const REFUND_BULK_BLOCK_PREVIEW_REQUEST_NAMED: &[&str] = &["ids", "filters"];

impl ValidateRequest for RefundBulkBlockPreviewRequest {
    fn validate(&self) -> Result<()> {
        reject_extra_collisions(
            &self.extra,
            REFUND_BULK_BLOCK_PREVIEW_REQUEST_NAMED,
            "RefundBulkBlockPreviewRequest",
        )
    }
}

/// An identifier a bulk block leaves out.
///
/// The value is personal data: `Debug` prints `<redacted>` in its place.
#[derive(Clone, Serialize)]
pub struct RefundBulkExcludedIdentifier {
    /// The identifier's kind.
    pub kind: BuyerBlocklistKind,
    /// The identifier's value, as the preview showed it.
    pub value: String,
}

impl RefundBulkExcludedIdentifier {
    /// Leave out `value` of `kind`.
    pub fn new(kind: BuyerBlocklistKind, value: impl Into<String>) -> Self {
        Self {
            kind,
            value: value.into(),
        }
    }
}

impl std::fmt::Debug for RefundBulkExcludedIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RefundBulkExcludedIdentifier")
            .field("kind", &self.kind)
            .field("value", &"<redacted>")
            .finish()
    }
}

/// Parameters for [`Refunds::bulk_block_buyer`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundBulkBlockBuyerRequest {
    /// Refund ids, at most the preview's `max_run_refunds`.
    pub ids: Vec<String>,
    /// The identifier kinds to block.
    pub kinds: Vec<BuyerBlocklistKind>,
    /// Identifiers to leave out.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub exclude: Vec<RefundBulkExcludedIdentifier>,
    /// An internal note stored on the entries.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl RefundBulkBlockBuyerRequest {
    /// Block the `kinds` identifiers of the listed refunds' buyers.
    pub fn new(ids: Vec<String>, kinds: Vec<BuyerBlocklistKind>) -> Self {
        Self {
            ids,
            kinds,
            ..Default::default()
        }
    }

    /// Leave out one identifier.
    #[must_use]
    pub fn exclude(mut self, identifier: RefundBulkExcludedIdentifier) -> Self {
        self.exclude.push(identifier);
        self
    }

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

/// Names of `RefundBulkBlockBuyerRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const REFUND_BULK_BLOCK_BUYER_REQUEST_NAMED: &[&str] = &["ids", "kinds", "exclude", "note"];

impl ValidateRequest for RefundBulkBlockBuyerRequest {
    fn validate(&self) -> Result<()> {
        reject_extra_collisions(
            &self.extra,
            REFUND_BULK_BLOCK_BUYER_REQUEST_NAMED,
            "RefundBulkBlockBuyerRequest",
        )
    }
}

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

    /// Every optional field populated so serialization emits the full key set.
    fn full_refund_create_request() -> RefundCreateRequest {
        RefundCreateRequest {
            payment_id: "pay_1".to_string(),
            refund_id: Some("ref_1".to_string()),
            amount: Some(500),
            reason: Some("requested_by_customer".to_string()),
            refund_type: Some(RefundType::Instant),
            metadata: Some(json!({"order_id": "o_1"})),
            line_credits: Some(vec![
                RefundLineCreditRequest::new("pli_1", 500)
                    .quantity(1)
                    .tax_amount(80),
            ]),
            extra: serde_json::Map::new(),
        }
    }

    #[test]
    fn line_credits_serialize_only_the_set_fields() {
        let req = RefundCreateRequest::new("pay_1")
            .amount(500)
            .line_credits(vec![RefundLineCreditRequest::new("pli_1", 500)]);
        let value = serde_json::to_value(req).unwrap();
        assert_eq!(
            value["line_credits"],
            json!([{"line_id": "pli_1", "amount": 500}])
        );
    }

    /// Drift guard: catches a new field added to `RefundCreateRequest`
    /// without a matching update to `REFUND_CREATE_REQUEST_NAMED`.
    #[test]
    fn refund_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_refund_create_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                REFUND_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "REFUND_CREATE_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or RefundCreateRequest's extra-key collision guard \
                 will silently stop covering this field"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_key_colliding_with_named_field() {
        let mut req = RefundCreateRequest::new("pay_1");
        req.extra.insert("amount".to_string(), json!(999));

        let err = req.validate().unwrap_err();
        match err {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("amount")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    use crate::http::mock::{Step, client_with};

    const REFUND_JSON: &str = r#"{
        "refund_id": "ref_1", "payment_id": "pay_1", "amount": 500,
        "currency": "EUR", "status": "succeeded"
    }"#;

    #[tokio::test]
    async fn list_by_profile_posts_to_the_profile_scoped_path() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"size":0,"data":[]}"#),
            Step::ok(r#"{"size":0,"data":[]}"#),
        ]);
        client.refunds().list_by_profile(None).await.unwrap();
        client
            .refunds()
            .list_by_profile(Some(&json!({"limit": 5})))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/refunds/profile/list");
        assert_eq!(
            seen[0].body_json(),
            json!({}),
            "None params must still send an empty JSON object body"
        );
        assert_eq!(seen[1].body_json()["limit"], 5);
    }

    #[tokio::test]
    async fn filters_and_aggregate_endpoints_hit_their_paths_with_queries() {
        let (client, mock) = client_with(vec![Step::ok("{}"), Step::ok("{}"), Step::ok("{}")]);
        client
            .refunds()
            .filters(&[("currency", "EUR".to_string())])
            .await
            .unwrap();
        client
            .refunds()
            .aggregate(&[("start_time", "2024-01-01".to_string())])
            .await
            .unwrap();
        client.refunds().aggregate_by_profile(&[]).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/refunds/filter?currency=EUR")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            (
                "GET",
                "https://api.test/refunds/aggregate?start_time=2024-01-01"
            )
        );
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            ("GET", "https://api.test/refunds/profile/aggregate")
        );
    }

    #[tokio::test]
    async fn manual_update_puts_to_the_encoded_manual_update_path() {
        // The verb is the point: every other refund mutation is a POST.
        let (client, mock) = client_with(vec![Step::ok(REFUND_JSON)]);
        client
            .refunds()
            .manual_update("ref/1", &json!({"status": "succeeded"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/refunds/ref%2F1/manual-update"
        );
        assert_eq!(seen[0].body_json()["status"], "succeeded");
    }

    const REFUND_REQUEST_JSON: &str = r#"{
        "id": "rr_1", "payment_id": "pay_1", "profile_id": "pro_1",
        "customer_id": "cus_1", "purchase_kind": "payment", "reason": "not_received",
        "message": "It never arrived at my flat", "amount": 1500, "currency": "EUR",
        "status": "approved", "refund_id": "ref_1", "approved_amount": 1500,
        "merchant_reply": "Sorry", "decided_by": "user_1", "test_mode": false,
        "created_at": "2026-01-01T00:00:00Z", "decided_at": "2026-01-02T00:00:00Z",
        "rr_surprise": 1
    }"#;

    #[tokio::test]
    async fn list_requests_gets_with_the_filters_and_redacts_the_message() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{REFUND_REQUEST_JSON}],"total_count":1,"limit":10,"offset":0}}"#
        ))]);
        let params = BuyerRefundRequestListParams {
            payment_id: Some("pay_1".to_string()),
            status: Some(BuyerRefundRequestStatus::Requested),
            limit: Some(10),
            offset: Some(0),
        };
        let page = client.refunds().list_requests(Some(&params)).await.unwrap();
        assert_eq!(page.total_count, 1);
        assert_eq!(page.data[0].amount, 1500);
        assert_eq!(page.data[0].extra["rr_surprise"], 1);
        assert!(!format!("{page:?}").contains("never arrived"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/refund-requests?payment_id=pay_1&status=requested&limit=10&offset=0"
        );
    }

    #[tokio::test]
    async fn approve_request_posts_the_refund_to_the_encoded_path() {
        let (client, mock) = client_with(vec![Step::ok(REFUND_REQUEST_JSON)]);
        let out = client
            .refunds()
            .approve_request(
                "rr/1",
                &BuyerRefundRequestApprove::new("ref_1").reply("Refunded"),
            )
            .await
            .unwrap();
        assert_eq!(out.refund_id.as_deref(), Some("ref_1"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/refund-requests/rr%2F1/approve"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"refund_id": "ref_1", "reply": "Refunded"})
        );
    }

    #[tokio::test]
    async fn decline_request_posts_the_reply() {
        let (client, mock) = client_with(vec![Step::ok(REFUND_REQUEST_JSON)]);
        let out = client
            .refunds()
            .decline_request("rr_1", &BuyerRefundRequestDecline::new("Delivered"))
            .await
            .unwrap();
        assert_eq!(out.id, "rr_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/refund-requests/rr_1/decline");
        assert_eq!(seen[0].body_json(), json!({"reply": "Delivered"}));
    }

    #[tokio::test]
    async fn bulk_block_preview_posts_the_filters() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"selected_count":1,"refunds":[{"refund_id":"ref_1","payment_id":"pay_1",
                "profile_id":"pro_1","identifiers":[{"kind":"ip","value":"203.0.113.9",
                "profile_id":"pro_1","source":"paying_browser","already_blocked":false}],
                "omitted_count":0,"error_code":null,"error_message":null}],
                "not_found":["ref_2"],"truncated":false,"max_refunds":500,
                "max_run_refunds":50,"x":1}"#,
        )]);
        let req = RefundBulkBlockPreviewRequest::for_filters(json!({"payment_id": "pay_1"}));
        let out = client.refunds().bulk_block_preview(&req).await.unwrap();
        assert_eq!(out.refunds[0].identifiers[0].source, "paying_browser");
        assert_eq!(out.not_found, ["ref_2"]);
        assert_eq!(out.extra["x"], 1);
        assert!(!format!("{out:?}").contains("203.0.113.9"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/refunds/bulk/block-buyer/preview"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"filters": {"payment_id": "pay_1"}})
        );
    }

    #[tokio::test]
    async fn bulk_block_buyer_posts_kinds_and_exclusions() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"results":[{"refund_id":"ref_1","payment_id":"pay_1","outcome":"blocked",
                "reason":null,"identifiers":[{"kind":"email","value":"b@example.com",
                "state":"added","entry_id":"bbl_1"}],"error_code":null,"error_message":null,"x":1}]}"#,
        )]);
        let req = RefundBulkBlockBuyerRequest::new(
            vec!["ref_1".to_string()],
            vec![BuyerBlocklistKind::Email, BuyerBlocklistKind::Ip],
        )
        .exclude(RefundBulkExcludedIdentifier::new(
            BuyerBlocklistKind::Ip,
            "203.0.113.9",
        ))
        .note("chargeback abuse");
        assert!(!format!("{req:?}").contains("203.0.113.9"));
        let out = client.refunds().bulk_block_buyer(&req).await.unwrap();
        assert_eq!(
            out.results[0].identifiers[0].entry_id.as_deref(),
            Some("bbl_1")
        );
        assert_eq!(out.results[0].extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/refunds/bulk/block-buyer");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "ids": ["ref_1"],
                "kinds": ["email", "ip"],
                "exclude": [{"kind": "ip", "value": "203.0.113.9"}],
                "note": "chargeback abuse"
            })
        );
    }

    #[tokio::test]
    async fn bulk_block_buyer_is_not_retried_on_5xx() {
        let (client, mock) = crate::http::mock::client_with_retries(
            vec![Step::status(500, r#"{"error":{"message":"boom"}}"#)],
            2,
        );
        let req = RefundBulkBlockBuyerRequest::new(
            vec!["ref_1".to_string()],
            vec![BuyerBlocklistKind::Email],
        );
        client.refunds().bulk_block_buyer(&req).await.unwrap_err();
        assert_eq!(mock.call_count(), 1);
    }

    /// Drift guard for `BUYER_REFUND_REQUEST_APPROVE_NAMED`.
    #[test]
    fn buyer_refund_request_approve_named_fields_are_complete() {
        let req = BuyerRefundRequestApprove::new("ref_1").reply("r");
        assert_named_complete(&req, BUYER_REFUND_REQUEST_APPROVE_NAMED);
    }

    /// Drift guard for `REFUND_BULK_BLOCK_PREVIEW_REQUEST_NAMED`.
    #[test]
    fn refund_bulk_block_preview_request_named_fields_are_complete() {
        let mut req = RefundBulkBlockPreviewRequest::for_ids(vec!["ref_1".to_string()]);
        req.filters = Some(json!({}));
        assert_named_complete(&req, REFUND_BULK_BLOCK_PREVIEW_REQUEST_NAMED);
    }

    /// Drift guard for `REFUND_BULK_BLOCK_BUYER_REQUEST_NAMED`.
    #[test]
    fn refund_bulk_block_buyer_request_named_fields_are_complete() {
        let req = RefundBulkBlockBuyerRequest::new(vec![], vec![BuyerBlocklistKind::Email])
            .exclude(RefundBulkExcludedIdentifier::new(
                BuyerBlocklistKind::Email,
                "e",
            ))
            .note("n");
        assert_named_complete(&req, REFUND_BULK_BLOCK_BUYER_REQUEST_NAMED);
    }

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

    fn assert_named_complete<T: Serialize>(req: &T, named: &[&str]) {
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                named.contains(&key.as_str()),
                "NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Every write here ignores the client-wide idempotency key: none sends
    /// it, and none is replayed after a `503`. Switching a call site back to
    /// `request(.., None)` makes it send the key and retry.
    #[tokio::test]
    async fn writes_ignore_the_client_wide_idempotency_key() {
        let steps = (0..4)
            .map(|_| Step::status(503, r#"{"error":{"message":"down"}}"#))
            .collect();
        let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
        let client = client.with_idempotency_key("client-key");
        client
            .refunds()
            .approve_request("rr_1", &BuyerRefundRequestApprove::new("ref_1"))
            .await
            .unwrap_err();
        client
            .refunds()
            .decline_request("rr_1", &BuyerRefundRequestDecline::new("no"))
            .await
            .unwrap_err();
        client
            .refunds()
            .bulk_block_preview(&RefundBulkBlockPreviewRequest::for_ids(vec![
                "ref_1".to_string(),
            ]))
            .await
            .unwrap_err();
        client
            .refunds()
            .bulk_block_buyer(&RefundBulkBlockBuyerRequest::new(
                vec!["ref_1".to_string()],
                vec![BuyerBlocklistKind::Email],
            ))
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 4);
        for seen in mock.seen.lock().unwrap().iter() {
            assert!(
                !seen.had_idempotency_key(),
                "{} sent the client key",
                seen.url
            );
        }
    }
}