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
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
//! The `buyer_blocklist` resource: the buyers a merchant refuses to sell to
//! again, in every shop of the merchant or in one shop.
//!
//! An entry names the buyer by email address, IP address, IP range, customer
//! id, device id, Stripe card fingerprint and card BIN, at most one of each
//! and at least one in total, and blocks a payment when any one of them
//! matches. An entry can instead block a class of network (hosting, VPN or
//! proxy, Tor) on its own. A blocked buyer's hosted checkout and confirms fail
//! with error code `DE_14`. Card fingerprints, emails, IPs and BINs can also be
//! copied to Stripe Radar value lists per Stripe connection; a Radar list
//! blocks only once its rule is added in Stripe (`rule_needed`).
//!
//! Every route needs a dashboard session. Reading needs the `BuyerBlocklist`
//! area at `Read`, adding and removing needs `Write`. A caller scoped to one
//! shop lists, adds and removes that shop's entries only, and never an entry
//! that blocks in every shop.

use std::fmt;
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::buyer_blocklist::{
    BuyerBlocklistCapabilitiesResponse, BuyerBlocklistEntryResponse, BuyerBlocklistEventsResponse,
    BuyerBlocklistFromPaymentPreviewResponse, BuyerBlocklistListResponse,
    PaymentFraudSignalsResponse, RadarSyncSettingsListResponse, RadarSyncSettingsResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// One page of blocked buyers, newest first, filtered by scope, by `kind`
    /// (the entries that include an identifier of that kind) and by a search
    /// over every identifier and the note. Expired entries are not listed.
    /// `GET /buyer-blocklist`
    pub async fn list(
        &self,
        params: Option<&BuyerBlocklistListParams>,
    ) -> Result<BuyerBlocklistListResponse> {
        let query = params
            .map(BuyerBlocklistListParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/buyer-blocklist", None, &query, None)
            .await
    }

    /// Block a buyer in one shop or, without `profile_id`, in every shop of
    /// the merchant. Each identifier is normalised as it is matched; an
    /// identifier another entry already names in that scope is refused. The
    /// change is recorded in the audit log before it is made.
    /// `POST /buyer-blocklist`
    pub async fn create(
        &self,
        params: &BuyerBlocklistEntryCreateRequest,
    ) -> Result<BuyerBlocklistEntryResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Post, "/buyer-blocklist", Some(&body), None)
            .await
    }

    /// Remove an entry, so the buyer can pay again. Payments the entry already
    /// refused keep their status. The removal and the optional reason are
    /// recorded in the audit log. The route requires a body, so `{}` is sent
    /// when no reason is given.
    /// `DELETE /buyer-blocklist/{entry_id}`
    pub async fn delete(
        &self,
        entry_id: &str,
        params: Option<&BuyerBlocklistEntryDeleteRequest>,
    ) -> Result<BuyerBlocklistEntryResponse> {
        let none = BuyerBlocklistEntryDeleteRequest::default();
        let body = to_json_vec(params.unwrap_or(&none))?;
        self.inner
            .request_body_keyed(HttpMethod::Delete, &entry_path(entry_id), Some(&body), None)
            .await
    }

    /// Block the buyer of a payment by the identifiers the payment carries:
    /// its card (the Stripe fingerprint), email, IP, device or customer, in
    /// the payment's shop or in every shop. With `all_ips`, also every address
    /// the buyer was seen paying from, one entry each, grouped under one
    /// `group_id`; the answer then carries `ip_snapshot`.
    /// `POST /buyer-blocklist/from-payment`
    pub async fn create_from_payment(
        &self,
        params: &BuyerBlocklistFromPaymentRequest,
    ) -> Result<BuyerBlocklistEntryResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/buyer-blocklist/from-payment",
                Some(&body),
                None,
            )
            .await
    }

    /// The addresses an "all IPs" block of a payment's buyer would take: the
    /// payment's own, then those its device, email or card were seen at in
    /// the last 90 days, newest first, at most 20. Writes nothing.
    /// `POST /buyer-blocklist/from-payment/preview`
    pub async fn preview_from_payment(
        &self,
        params: &BuyerBlocklistFromPaymentPreviewRequest,
    ) -> Result<BuyerBlocklistFromPaymentPreviewResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/buyer-blocklist/from-payment/preview",
                Some(&body),
                None,
            )
            .await
    }

    /// An entry's recorded refusals, newest first, with where each happened
    /// and which identifier matched.
    /// `GET /buyer-blocklist/{entry_id}/events`
    pub async fn list_events(
        &self,
        entry_id: &str,
        limit: Option<u32>,
    ) -> Result<BuyerBlocklistEventsResponse> {
        let path = format!("{}/events", entry_path(entry_id));
        let query: Vec<(&str, String)> = limit
            .map(|v| vec![("limit", v.to_string())])
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Which classes of network an `ip_class` entry can be judged by on this
    /// deployment now, and by which sources.
    /// `GET /buyer-blocklist/capabilities`
    pub async fn capabilities(&self) -> Result<BuyerBlocklistCapabilitiesResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/buyer-blocklist/capabilities",
                None,
                &[],
                None,
            )
            .await
    }

    /// Retry now every failed or pending Radar sync of an entry.
    /// `POST /buyer-blocklist/{entry_id}/sync/retry`
    pub async fn retry_sync(&self, entry_id: &str) -> Result<BuyerBlocklistEntryResponse> {
        let path = format!("{}/sync/retry", entry_path(entry_id));
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, None, None)
            .await
    }

    /// The Radar sync settings of every Stripe connection the caller sees. A
    /// role that hides processor names is refused (403).
    /// `GET /buyer-blocklist/radar-sync`
    pub async fn list_radar_sync(&self) -> Result<RadarSyncSettingsListResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/buyer-blocklist/radar-sync",
                None,
                &[],
                None,
            )
            .await
    }

    /// The Radar sync settings of one Stripe connection.
    /// `GET /buyer-blocklist/radar-sync/{merchant_connector_id}`
    pub async fn retrieve_radar_sync(
        &self,
        merchant_connector_id: &str,
    ) -> Result<RadarSyncSettingsResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                &radar_path(merchant_connector_id),
                None,
                &[],
                None,
            )
            .await
    }

    /// Turn Radar sync on or off for one Stripe connection and set what an
    /// early fraud warning or a review does.
    /// `PUT /buyer-blocklist/radar-sync/{merchant_connector_id}`
    pub async fn update_radar_sync(
        &self,
        merchant_connector_id: &str,
        params: &RadarSyncSettingsUpdateRequest,
    ) -> Result<RadarSyncSettingsResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Put,
                &radar_path(merchant_connector_id),
                Some(&body),
                None,
            )
            .await
    }

    /// Remove every item synced from this connection's Radar lists. The lists
    /// themselves are kept.
    /// `POST /buyer-blocklist/radar-sync/{merchant_connector_id}/remove-items`
    pub async fn remove_radar_items(
        &self,
        merchant_connector_id: &str,
    ) -> Result<RadarSyncSettingsResponse> {
        let path = format!("{}/remove-items", radar_path(merchant_connector_id));
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, None, None)
            .await
    }

    /// Stripe's fraud signals on a payment (risk, early fraud warnings,
    /// reviews), what of its buyer can be blocked, and the entries that
    /// already match it.
    /// `GET /buyer-blocklist/fraud-signals/{payment_id}`
    pub async fn fraud_signals(&self, payment_id: &str) -> Result<PaymentFraudSignalsResponse> {
        let path = format!(
            "/buyer-blocklist/fraud-signals/{}",
            encode_segment(payment_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }
}

/// `/buyer-blocklist/{entry_id}`, percent-encoded.
fn entry_path(entry_id: &str) -> String {
    format!("/buyer-blocklist/{}", encode_segment(entry_id))
}

/// `/buyer-blocklist/radar-sync/{merchant_connector_id}`, percent-encoded.
fn radar_path(merchant_connector_id: &str) -> String {
    format!(
        "/buyer-blocklist/radar-sync/{}",
        encode_segment(merchant_connector_id)
    )
}

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

/// `Some("<redacted>")` for a present value, so `Debug` still shows which
/// identifiers a request carries.
fn redact<T>(value: &Option<T>) -> Option<&'static str> {
    value.as_ref().map(|_| "<redacted>")
}

/// A kind of buyer identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum BuyerBlocklistKind {
    /// An email address.
    Email,
    /// An IP address.
    Ip,
    /// A customer id.
    CustomerId,
    /// A device id.
    DeviceId,
    /// A Stripe card fingerprint.
    CardFingerprint,
    /// A card BIN.
    CardBin,
    /// An IP range, in CIDR notation.
    IpRange,
    /// A class of network.
    IpClass,
    /// A device's traits.
    DeviceTraits,
}

impl BuyerBlocklistKind {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Email => "email",
            Self::Ip => "ip",
            Self::CustomerId => "customer_id",
            Self::DeviceId => "device_id",
            Self::CardFingerprint => "card_fingerprint",
            Self::CardBin => "card_bin",
            Self::IpRange => "ip_range",
            Self::IpClass => "ip_class",
            Self::DeviceTraits => "device_traits",
        }
    }
}

/// A class of network an `ip_class` entry blocks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum BuyerBlocklistIpClass {
    /// Hosting and data-centre networks.
    Datacenter,
    /// VPNs and proxies.
    ProxyVpn,
    /// Tor exit nodes.
    Tor,
}

/// Which entries a list reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BuyerBlocklistListScope {
    /// Every entry the caller sees.
    All,
    /// Entries that block in every shop.
    Merchant,
    /// Entries that block in one shop.
    Shop,
}

impl BuyerBlocklistListScope {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Merchant => "merchant",
            Self::Shop => "shop",
        }
    }
}

/// Filters for [`BuyerBlocklist::list`].
///
/// The search text may name a buyer: `Debug` prints `<redacted>` in its place.
#[derive(Clone, Default)]
pub struct BuyerBlocklistListParams {
    /// Which entries to read.
    pub scope: Option<BuyerBlocklistListScope>,
    /// Only entries of this shop.
    pub profile_id: Option<String>,
    /// Only entries that include an identifier of this kind.
    pub kind: Option<BuyerBlocklistKind>,
    /// A search over every identifier and the note.
    pub search: Option<String>,
    /// Only the entries one "all IPs" block created.
    pub group_id: Option<String>,
    /// Page size.
    pub limit: Option<u32>,
    /// Entries to skip.
    pub offset: Option<u32>,
}

impl fmt::Debug for BuyerBlocklistListParams {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BuyerBlocklistListParams")
            .field("scope", &self.scope)
            .field("profile_id", &self.profile_id)
            .field("kind", &self.kind)
            .field("search", &redact(&self.search))
            .field("group_id", &self.group_id)
            .field("limit", &self.limit)
            .field("offset", &self.offset)
            .finish()
    }
}

impl BuyerBlocklistListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.scope {
            q.push(("scope", v.as_str().to_string()));
        }
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        if let Some(v) = self.kind {
            q.push(("kind", v.as_str().to_string()));
        }
        if let Some(v) = &self.search {
            q.push(("search", v.clone()));
        }
        if let Some(v) = &self.group_id {
            q.push(("group_id", v.clone()));
        }
        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 [`BuyerBlocklist::create`]: at least one identifier, or an
/// `ip_class` on its own.
///
/// The identifiers are personal data: `Debug` prints `<redacted>` in their
/// place.
#[derive(Clone, Default, Serialize)]
pub struct BuyerBlocklistEntryCreateRequest {
    /// An email address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// An IP address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip: Option<String>,
    /// A customer id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    /// A device id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_id: Option<String>,
    /// A card BIN.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_bin: Option<String>,
    /// An IP range, in CIDR notation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip_range: Option<String>,
    /// A class of network, blocked on its own.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip_class: Option<BuyerBlocklistIpClass>,
    /// One identifier's kind, with `value`, instead of the named fields.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<BuyerBlocklistKind>,
    /// The identifier named by `kind`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
    /// The shop to block in. Omitted, the entry blocks in every shop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// An internal note.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// When the entry expires, ISO 8601.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: 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 fmt::Debug for BuyerBlocklistEntryCreateRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BuyerBlocklistEntryCreateRequest")
            .field("email", &redact(&self.email))
            .field("ip", &redact(&self.ip))
            .field("customer_id", &redact(&self.customer_id))
            .field("device_id", &redact(&self.device_id))
            .field("card_bin", &redact(&self.card_bin))
            .field("ip_range", &redact(&self.ip_range))
            .field("ip_class", &self.ip_class)
            .field("kind", &self.kind)
            .field("value", &redact(&self.value))
            .field("profile_id", &self.profile_id)
            .field("note", &self.note)
            .field("expires_at", &self.expires_at)
            .finish_non_exhaustive()
    }
}

impl BuyerBlocklistEntryCreateRequest {
    /// An empty entry; set at least one identifier.
    pub fn new() -> Self {
        Self::default()
    }

    /// Block an email address.
    #[must_use]
    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    /// Block an IP address.
    #[must_use]
    pub fn ip(mut self, ip: impl Into<String>) -> Self {
        self.ip = Some(ip.into());
        self
    }

    /// Block a customer id.
    #[must_use]
    pub fn customer_id(mut self, customer_id: impl Into<String>) -> Self {
        self.customer_id = Some(customer_id.into());
        self
    }

    /// Block a device id.
    #[must_use]
    pub fn device_id(mut self, device_id: impl Into<String>) -> Self {
        self.device_id = Some(device_id.into());
        self
    }

    /// Block a card BIN.
    #[must_use]
    pub fn card_bin(mut self, card_bin: impl Into<String>) -> Self {
        self.card_bin = Some(card_bin.into());
        self
    }

    /// Block an IP range, in CIDR notation.
    #[must_use]
    pub fn ip_range(mut self, ip_range: impl Into<String>) -> Self {
        self.ip_range = Some(ip_range.into());
        self
    }

    /// Block a class of network.
    #[must_use]
    pub fn ip_class(mut self, ip_class: BuyerBlocklistIpClass) -> Self {
        self.ip_class = Some(ip_class);
        self
    }

    /// Block one identifier named by its kind.
    #[must_use]
    pub fn identifier(mut self, kind: BuyerBlocklistKind, value: impl Into<String>) -> Self {
        self.kind = Some(kind);
        self.value = Some(value.into());
        self
    }

    /// Block in one shop only.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

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

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

/// Names of `BuyerBlocklistEntryCreateRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const BUYER_BLOCKLIST_ENTRY_CREATE_REQUEST_NAMED: &[&str] = &[
    "email",
    "ip",
    "customer_id",
    "device_id",
    "card_bin",
    "ip_range",
    "ip_class",
    "kind",
    "value",
    "profile_id",
    "note",
    "expires_at",
];

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

/// Parameters for [`BuyerBlocklist::delete`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerBlocklistEntryDeleteRequest {
    /// Why the entry is removed, recorded in the audit log.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl BuyerBlocklistEntryDeleteRequest {
    /// Remove the entry for `reason`.
    pub fn new(reason: impl Into<String>) -> Self {
        Self {
            reason: Some(reason.into()),
        }
    }
}

/// An identifier of a payment's buyer to block.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PaymentBlockIdentifier {
    /// The card's Stripe fingerprint.
    Card,
    /// The email address.
    Email,
    /// The IP address.
    Ip,
    /// The device.
    Device,
    /// The customer.
    Customer,
    /// The device's traits.
    DeviceTraits,
}

/// Where a block of a payment's buyer applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PaymentBlockScope {
    /// The payment's shop.
    Shop,
    /// Every shop of the merchant.
    AllShops,
}

/// What a device-traits match does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum BuyerBlocklistTraitAction {
    /// Flag the payment. The default.
    Flag,
    /// Refuse the payment.
    Refuse,
}

/// Parameters for [`BuyerBlocklist::create_from_payment`].
///
/// The listed addresses are personal data: `Debug` prints `<redacted>` in
/// their place.
#[derive(Clone, Serialize)]
pub struct BuyerBlocklistFromPaymentRequest {
    /// The payment whose buyer to block.
    pub payment_id: String,
    /// What of the buyer to block; at least one.
    pub identifiers: Vec<PaymentBlockIdentifier>,
    /// Where the block applies.
    pub scope: PaymentBlockScope,
    /// An internal note, at most 1024 characters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// When the entry expires, ISO 8601.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    /// Also block, one entry each, the addresses the buyer was seen paying
    /// from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub all_ips: Option<bool>,
    /// With `all_ips`: the addresses to block, each one the preview offered.
    /// Omitted, the preselected ones are blocked.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ips: Option<Vec<String>>,
    /// What a device-traits match does.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trait_action: Option<BuyerBlocklistTraitAction>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl fmt::Debug for BuyerBlocklistFromPaymentRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BuyerBlocklistFromPaymentRequest")
            .field("payment_id", &self.payment_id)
            .field("identifiers", &self.identifiers)
            .field("scope", &self.scope)
            .field("note", &self.note)
            .field("expires_at", &self.expires_at)
            .field("all_ips", &self.all_ips)
            .field("ips", &redact(&self.ips))
            .field("trait_action", &self.trait_action)
            .finish_non_exhaustive()
    }
}

impl BuyerBlocklistFromPaymentRequest {
    /// Block `identifiers` of `payment_id`'s buyer within `scope`.
    pub fn new(
        payment_id: impl Into<String>,
        identifiers: Vec<PaymentBlockIdentifier>,
        scope: PaymentBlockScope,
    ) -> Self {
        Self {
            payment_id: payment_id.into(),
            identifiers,
            scope,
            note: None,
            expires_at: None,
            all_ips: None,
            ips: None,
            trait_action: None,
            extra: serde_json::Map::new(),
        }
    }

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

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

    /// Also block every address the buyer was seen paying from.
    #[must_use]
    pub fn all_ips(mut self, all_ips: bool) -> Self {
        self.all_ips = Some(all_ips);
        self
    }

    /// With `all_ips`, block exactly these addresses from the preview.
    #[must_use]
    pub fn ips(mut self, ips: Vec<String>) -> Self {
        self.ips = Some(ips);
        self
    }

    /// Set what a device-traits match does.
    #[must_use]
    pub fn trait_action(mut self, trait_action: BuyerBlocklistTraitAction) -> Self {
        self.trait_action = Some(trait_action);
        self
    }
}

/// Names of `BuyerBlocklistFromPaymentRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const BUYER_BLOCKLIST_FROM_PAYMENT_REQUEST_NAMED: &[&str] = &[
    "payment_id",
    "identifiers",
    "scope",
    "note",
    "expires_at",
    "all_ips",
    "ips",
    "trait_action",
];

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

/// Parameters for [`BuyerBlocklist::preview_from_payment`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerBlocklistFromPaymentPreviewRequest {
    /// The payment whose buyer's addresses to read.
    pub payment_id: String,
}

impl BuyerBlocklistFromPaymentPreviewRequest {
    /// Preview the addresses of `payment_id`'s buyer.
    pub fn new(payment_id: impl Into<String>) -> Self {
        Self {
            payment_id: payment_id.into(),
        }
    }
}

/// What an early fraud warning does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RadarEfwAction {
    /// Notify the merchant.
    Notify,
    /// Notify the merchant and block the buyer.
    NotifyAndBlock,
    /// Nothing.
    None,
}

/// What a Radar review does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RadarReviewAction {
    /// Notify the merchant.
    Notify,
    /// Nothing.
    None,
}

/// Parameters for [`BuyerBlocklist::update_radar_sync`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RadarSyncSettingsUpdateRequest {
    /// Share the blocklist with this connection's Radar lists.
    pub enabled: bool,
    /// What an early fraud warning does.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub efw_action: Option<RadarEfwAction>,
    /// What a Radar review does.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub review_action: Option<RadarReviewAction>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl RadarSyncSettingsUpdateRequest {
    /// Turn Radar sync on (`true`) or off (`false`).
    pub fn new(enabled: bool) -> Self {
        Self {
            enabled,
            ..Default::default()
        }
    }

    /// Set what an early fraud warning does.
    #[must_use]
    pub fn efw_action(mut self, action: RadarEfwAction) -> Self {
        self.efw_action = Some(action);
        self
    }

    /// Set what a Radar review does.
    #[must_use]
    pub fn review_action(mut self, action: RadarReviewAction) -> Self {
        self.review_action = Some(action);
        self
    }
}

/// Names of `RadarSyncSettingsUpdateRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const RADAR_SYNC_SETTINGS_UPDATE_REQUEST_NAMED: &[&str] =
    &["enabled", "efw_action", "review_action"];

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

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

    const ENTRY_JSON: &str = r#"{
        "id": "bbl_1", "email": "fraud@example.com", "ip": "203.0.113.9",
        "customer_id": "cus_1", "device_id": null, "kind": "email",
        "value": "fraud@example.com", "profile_id": "pro_1", "note": "chargebacks",
        "expires_at": null, "block_count": 3, "created_at": "2026-01-01T00:00:00Z",
        "card_fingerprint": "fp_123", "card_display": "visa 4242", "card_bin": "424242",
        "card_source": {"connector": "stripe", "merchant_connector_id": "mca_1"},
        "radar": {
            "processor_names_hidden": false, "status": "pending",
            "connections": [{
                "merchant_connector_id": "mca_1", "connector_label": "main",
                "profile_id": "pro_1", "environment": "live",
                "items": [{"identifier": "email", "status": "pending",
                    "value_list_alias": "delopay_email", "last_error": null,
                    "attempts": 1, "updated_at": "2026-01-01T00:00:00Z"}]
            }],
            "local_only_reason": null
        },
        "entry_surprise": 1
    }"#;

    const RADAR_JSON: &str = r#"{
        "merchant_connector_id": "mca_1", "connector_label": "main", "profile_id": "pro_1",
        "environments": ["live"], "enabled": true, "efw_action": "notify_and_block",
        "review_action": "notify",
        "lists": [{"identifier": "card_fingerprint", "item_type": "card_fingerprint",
            "environment": "live", "value_list_alias": "delopay_cards",
            "value_list_id": "rsl_1", "rule_needed": true,
            "rule_text": "Block if :card_fingerprint: in @delopay_cards"}],
        "counts": {"synced": 4, "pending": 1, "failed": 0, "removing": 0},
        "updated_at": "2026-01-01T00:00:00Z", "radar_surprise": 1
    }"#;

    #[tokio::test]
    async fn list_sends_the_filters_and_redacts_identifiers() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"entries":[{ENTRY_JSON}],"total_count":1,"limit":20,"offset":0}}"#
        ))]);
        let params = BuyerBlocklistListParams {
            scope: Some(BuyerBlocklistListScope::Shop),
            profile_id: Some("pro_1".to_string()),
            kind: Some(BuyerBlocklistKind::CardFingerprint),
            search: Some("fraud@example.com".to_string()),
            limit: Some(20),
            ..Default::default()
        };
        assert!(!format!("{params:?}").contains("fraud@example.com"));
        let page = client.buyer_blocklist().list(Some(&params)).await.unwrap();
        let entry = &page.entries[0];
        assert_eq!(entry.block_count, 3);
        assert_eq!(entry.radar.connections[0].items[0].attempts, 1);
        assert_eq!(entry.extra["entry_surprise"], 1);
        let printed = format!("{page:?}");
        for secret in [
            "fraud@example.com",
            "203.0.113.9",
            "fp_123",
            "424242",
            "cus_1",
        ] {
            assert!(!printed.contains(secret), "Debug leaked {secret}");
        }

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-blocklist?scope=shop&profile_id=pro_1\
             &kind=card_fingerprint&search=fraud@example.com&limit=20"
        );
    }

    #[tokio::test]
    async fn create_posts_the_identifiers() {
        let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON)]);
        let req = BuyerBlocklistEntryCreateRequest::new()
            .email("fraud@example.com")
            .ip_class(BuyerBlocklistIpClass::ProxyVpn)
            .profile_id("pro_1")
            .note("chargebacks");
        assert!(!format!("{req:?}").contains("fraud@example.com"));
        let entry = client.buyer_blocklist().create(&req).await.unwrap();
        assert_eq!(entry.id, "bbl_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/buyer-blocklist");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "email": "fraud@example.com",
                "ip_class": "proxy_vpn",
                "profile_id": "pro_1",
                "note": "chargebacks"
            })
        );
    }

    #[tokio::test]
    async fn delete_sends_an_empty_object_without_a_reason() {
        let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON), Step::ok(ENTRY_JSON)]);
        client
            .buyer_blocklist()
            .delete("bbl/1", None)
            .await
            .unwrap();
        client
            .buyer_blocklist()
            .delete(
                "bbl_1",
                Some(&BuyerBlocklistEntryDeleteRequest::new("resolved")),
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(seen[0].url, "https://api.test/buyer-blocklist/bbl%2F1");
        assert_eq!(seen[0].body_json(), json!({}));
        assert_eq!(seen[1].body_json(), json!({"reason": "resolved"}));
    }

    #[tokio::test]
    async fn create_from_payment_posts_the_payment_block() {
        let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON)]);
        let req = BuyerBlocklistFromPaymentRequest::new(
            "pay_1",
            vec![
                PaymentBlockIdentifier::Card,
                PaymentBlockIdentifier::DeviceTraits,
            ],
            PaymentBlockScope::AllShops,
        )
        .all_ips(true)
        .ips(vec!["198.51.100.7".to_string()])
        .trait_action(BuyerBlocklistTraitAction::Refuse);
        assert!(!format!("{req:?}").contains("198.51.100.7"));
        client
            .buyer_blocklist()
            .create_from_payment(&req)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/buyer-blocklist/from-payment");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "payment_id": "pay_1",
                "identifiers": ["card", "device_traits"],
                "scope": "all_shops",
                "all_ips": true,
                "ips": ["198.51.100.7"],
                "trait_action": "refuse"
            })
        );
    }

    #[tokio::test]
    async fn preview_from_payment_posts_the_payment_id() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"payment_id":"pay_1","ips":[{"ip":"198.51.100.7","sources":["this_payment"],
                "last_seen_at":null,"other_buyers":0,"preselected":true,"x":1}],
                "truncated":false,"total":1}"#,
        )]);
        let out = client
            .buyer_blocklist()
            .preview_from_payment(&BuyerBlocklistFromPaymentPreviewRequest::new("pay_1"))
            .await
            .unwrap();
        assert!(out.ips[0].preselected);
        assert_eq!(out.ips[0].extra["x"], 1);
        assert!(!format!("{out:?}").contains("198.51.100.7"));

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

    #[tokio::test]
    async fn list_events_gets_the_events_with_a_limit() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"entry_id":"bbl_1","block_count":2,"events":[{"stage":"confirm",
                "outcome":"refused","matched_kind":"email","payment_id":"pay_9",
                "created_at":"2026-01-01T00:00:00Z","x":1}]}"#,
        )]);
        let out = client
            .buyer_blocklist()
            .list_events("bbl_1", Some(5))
            .await
            .unwrap();
        assert_eq!(out.events[0].stage, "confirm");
        assert_eq!(out.events[0].extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-blocklist/bbl_1/events?limit=5"
        );
    }

    #[tokio::test]
    async fn capabilities_gets_the_capabilities_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"ip_classes":[{"class":"tor","available":true,"sources":["tor_exit_list"],
                "provider_sources":[],"x":1}]}"#,
        )]);
        let out = client.buyer_blocklist().capabilities().await.unwrap();
        assert_eq!(out.ip_classes[0].class, "tor");
        assert_eq!(out.ip_classes[0].extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/buyer-blocklist/capabilities");
    }

    #[tokio::test]
    async fn retry_sync_posts_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON)]);
        client.buyer_blocklist().retry_sync("bbl/1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-blocklist/bbl%2F1/sync/retry"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn list_radar_sync_gets_every_connection() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"connections":[{RADAR_JSON}]}}"#
        ))]);
        let out = client.buyer_blocklist().list_radar_sync().await.unwrap();
        assert_eq!(out.connections[0].counts.synced, 4);
        assert!(out.connections[0].lists[0].rule_needed);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/buyer-blocklist/radar-sync");
    }

    #[tokio::test]
    async fn retrieve_radar_sync_encodes_the_connector_account() {
        let (client, mock) = client_with(vec![Step::ok(RADAR_JSON)]);
        let out = client
            .buyer_blocklist()
            .retrieve_radar_sync("mca/1")
            .await
            .unwrap();
        assert_eq!(out.efw_action, "notify_and_block");
        assert_eq!(out.extra["radar_surprise"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-blocklist/radar-sync/mca%2F1"
        );
    }

    #[tokio::test]
    async fn update_radar_sync_puts_the_settings() {
        let (client, mock) = client_with(vec![Step::ok(RADAR_JSON)]);
        let req = RadarSyncSettingsUpdateRequest::new(true)
            .efw_action(RadarEfwAction::NotifyAndBlock)
            .review_action(RadarReviewAction::None);
        client
            .buyer_blocklist()
            .update_radar_sync("mca_1", &req)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-blocklist/radar-sync/mca_1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"enabled": true, "efw_action": "notify_and_block", "review_action": "none"})
        );
    }

    #[tokio::test]
    async fn remove_radar_items_posts_to_the_remove_items_path() {
        let (client, mock) = client_with(vec![Step::ok(RADAR_JSON)]);
        client
            .buyer_blocklist()
            .remove_radar_items("mca_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-blocklist/radar-sync/mca_1/remove-items"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn fraud_signals_gets_the_payment_signals() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"payment_id":"pay_1","processor_names_hidden":false,"risk_level":"elevated",
                "risk_score":71,"early_fraud_warnings":[{"id":"issfr_1","fraud_type":"stolen_card",
                "actionable":true,"received_at":"2026-01-01T00:00:00Z"}],"reviews":[],
                "blockable":{"card":true,"email":true,"ip":true,"device":false,"customer":true},
                "blocked_by":["bbl_1"],"ip_classes":[{"class":"datacenter","sources":["asn"]}],
                "device_traits":{"hash":"dt_1","randomized":false,"commonness":3,"history_days":30,
                "summary":{"browser":"Firefox","os":"Linux","screen":null,"time_zone":null,"language":"en"}},
                "x":1}"#,
        )]);
        let out = client
            .buyer_blocklist()
            .fraud_signals("pay/1")
            .await
            .unwrap();
        assert_eq!(out.risk_score, Some(71));
        assert!(out.blockable.card);
        assert_eq!(
            out.early_fraud_warnings[0].fraud_type.as_deref(),
            Some("stolen_card")
        );
        assert_eq!(out.device_traits.unwrap().summary.browser, "Firefox");
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-blocklist/fraud-signals/pay%2F1"
        );
    }

    #[test]
    fn kind_tokens_match_their_serialized_form() {
        // `list` sends `as_str()`, a body sends the serde form: they must agree.
        for kind in [
            BuyerBlocklistKind::Email,
            BuyerBlocklistKind::Ip,
            BuyerBlocklistKind::CustomerId,
            BuyerBlocklistKind::DeviceId,
            BuyerBlocklistKind::CardFingerprint,
            BuyerBlocklistKind::CardBin,
            BuyerBlocklistKind::IpRange,
            BuyerBlocklistKind::IpClass,
            BuyerBlocklistKind::DeviceTraits,
        ] {
            assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
        }
    }

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

    /// Drift guard for `BUYER_BLOCKLIST_ENTRY_CREATE_REQUEST_NAMED`.
    #[test]
    fn buyer_blocklist_entry_create_request_named_fields_are_complete() {
        let req = BuyerBlocklistEntryCreateRequest::new()
            .email("e")
            .ip("i")
            .customer_id("c")
            .device_id("d")
            .card_bin("424242")
            .ip_range("10.0.0.0/8")
            .ip_class(BuyerBlocklistIpClass::Tor)
            .identifier(BuyerBlocklistKind::Email, "e")
            .profile_id("p")
            .note("n")
            .expires_at("2027-01-01T00:00:00Z");
        assert_named_complete(&req, BUYER_BLOCKLIST_ENTRY_CREATE_REQUEST_NAMED);
    }

    /// Drift guard for `BUYER_BLOCKLIST_FROM_PAYMENT_REQUEST_NAMED`.
    #[test]
    fn buyer_blocklist_from_payment_request_named_fields_are_complete() {
        let req = BuyerBlocklistFromPaymentRequest::new(
            "pay_1",
            vec![PaymentBlockIdentifier::Email],
            PaymentBlockScope::Shop,
        )
        .note("n")
        .expires_at("2027-01-01T00:00:00Z")
        .all_ips(true)
        .ips(vec![])
        .trait_action(BuyerBlocklistTraitAction::Flag);
        assert_named_complete(&req, BUYER_BLOCKLIST_FROM_PAYMENT_REQUEST_NAMED);
    }

    /// Drift guard for `RADAR_SYNC_SETTINGS_UPDATE_REQUEST_NAMED`.
    #[test]
    fn radar_sync_settings_update_request_named_fields_are_complete() {
        let req = RadarSyncSettingsUpdateRequest::new(true)
            .efw_action(RadarEfwAction::Notify)
            .review_action(RadarReviewAction::Notify);
        assert_named_complete(&req, RADAR_SYNC_SETTINGS_UPDATE_REQUEST_NAMED);
    }

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

    /// 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..7)
            .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
            .buyer_blocklist()
            .create(&BuyerBlocklistEntryCreateRequest::new().email("e@example.com"))
            .await
            .unwrap_err();
        client
            .buyer_blocklist()
            .delete("bbl_1", None)
            .await
            .unwrap_err();
        client
            .buyer_blocklist()
            .create_from_payment(&BuyerBlocklistFromPaymentRequest::new(
                "pay_1",
                vec![PaymentBlockIdentifier::Email],
                PaymentBlockScope::Shop,
            ))
            .await
            .unwrap_err();
        client
            .buyer_blocklist()
            .preview_from_payment(&BuyerBlocklistFromPaymentPreviewRequest::new("pay_1"))
            .await
            .unwrap_err();
        client
            .buyer_blocklist()
            .retry_sync("bbl_1")
            .await
            .unwrap_err();
        client
            .buyer_blocklist()
            .update_radar_sync("mca_1", &RadarSyncSettingsUpdateRequest::new(true))
            .await
            .unwrap_err();
        client
            .buyer_blocklist()
            .remove_radar_items("mca_1")
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 7);
        for seen in mock.seen.lock().unwrap().iter() {
            assert!(
                !seen.had_idempotency_key(),
                "{} sent the client key",
                seen.url
            );
        }
    }
}