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
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
//! The `disputes` resource: view disputes and respond to chargebacks with
//! evidence.

use std::sync::Arc;

use serde::{Deserialize, 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::{Currency, DisputeStage, DisputeStatus};
use crate::core::models::dispute::DisputeResponse;
use crate::core::models::dispute_workspace::{
    DisputeBulkAcceptResponse, DisputeBulkBlockBuyerResponse, DisputeBulkPreviewResponse,
    DisputeRefundAssociationsResponse, DisputeRefundDeclaration, DisputeWorkspaceAggregate,
    DisputeWorkspaceExport, DisputeWorkspaceFilters, DisputeWorkspaceResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

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

    /// List disputes, optionally filtered by status, stage, or date range.
    pub async fn list(&self, params: Option<&DisputeListParams>) -> Result<Vec<DisputeResponse>> {
        let query = params.map(DisputeListParams::to_query).unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/disputes/list", None, &query, None)
            .await
    }

    /// Accept a dispute (concede the chargeback).
    pub async fn accept(&self, dispute_id: &str) -> Result<DisputeResponse> {
        let path = format!("/disputes/accept/{}", encode_segment(dispute_id));
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Submit evidence to challenge a dispute.
    pub async fn submit_evidence(
        &self,
        params: &DisputeEvidenceRequest,
    ) -> Result<DisputeResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/disputes/evidence",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Attach evidence (e.g. uploaded-file references) to a dispute.
    pub async fn attach_evidence(
        &self,
        params: &DisputeEvidenceRequest,
    ) -> Result<DisputeResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Put,
                "/disputes/evidence",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Retrieve previously submitted evidence for a dispute.
    pub async fn retrieve_evidence(&self, dispute_id: &str) -> Result<DisputeEvidenceRequest> {
        let path = format!("/disputes/evidence/{}", encode_segment(dispute_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Delete submitted evidence for a dispute. The body identifies what to
    /// delete, mirroring the submit shape.
    pub async fn delete_evidence(
        &self,
        params: &DisputeEvidenceRequest,
    ) -> Result<DisputeResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Delete,
                "/disputes/evidence",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// List disputes scoped to the profile the API key belongs to.
    pub async fn list_by_profile(
        &self,
        params: Option<&DisputeListParams>,
    ) -> Result<Vec<DisputeResponse>> {
        let query = params.map(DisputeListParams::to_query).unwrap_or_default();
        self.inner
            .request(
                HttpMethod::Get,
                "/disputes/profile/list",
                None,
                &query,
                None,
            )
            .await
    }

    /// Retrieve the filter options available for disputes. 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, "/disputes/filter", None, query, None)
            .await
    }

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

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

    /// Retrieve aggregated dispute 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,
                "/disputes/profile/aggregate",
                None,
                query,
                None,
            )
            .await
    }

    /// Fetch the latest dispute state from the connector (gateway).
    ///
    /// The path parameter is the **connector's** dispute ID on the gateway,
    /// not the Delopay dispute ID.
    pub async fn fetch_from_connector(
        &self,
        connector_dispute_id: &str,
    ) -> Result<DisputeResponse> {
        let path = format!("/disputes/{}/fetch", encode_segment(connector_dispute_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Read native disputes and provider-only cases (PayPal and Whop cases,
    /// subscription disputes) as one list, inside the caller's shop scope and
    /// after the filters. `GET /disputes/workspace`
    pub async fn workspace(
        &self,
        params: Option<&DisputeWorkspaceParams>,
    ) -> Result<DisputeWorkspaceResponse> {
        let query = workspace_query(params);
        self.inner
            .request(HttpMethod::Get, "/disputes/workspace", None, &query, None)
            .await
    }

    /// The filter values present in the same scoped case set; pagination is
    /// ignored. `GET /disputes/workspace/filters`
    pub async fn workspace_filters(
        &self,
        params: Option<&DisputeWorkspaceParams>,
    ) -> Result<DisputeWorkspaceFilters> {
        let query = workspace_query(params);
        self.inner
            .request(
                HttpMethod::Get,
                "/disputes/workspace/filters",
                None,
                &query,
                None,
            )
            .await
    }

    /// Count the filtered case set, including cases whose outcome is unknown;
    /// pagination is ignored. `GET /disputes/workspace/aggregate`
    pub async fn workspace_aggregate(
        &self,
        params: Option<&DisputeWorkspaceParams>,
    ) -> Result<DisputeWorkspaceAggregate> {
        let query = workspace_query(params);
        self.inner
            .request(
                HttpMethod::Get,
                "/disputes/workspace/aggregate",
                None,
                &query,
                None,
            )
            .await
    }

    /// Export the complete filtered case set in one read.
    /// `GET /disputes/workspace/export`
    ///
    /// Over the server's export limit the request is refused with an error,
    /// never answered with a short set. A body whose `data` holds fewer or
    /// more cases than its `total_count` is answered with
    /// [`DelopayError::Decode`] rather than returned.
    pub async fn workspace_export(
        &self,
        params: Option<&DisputeWorkspaceParams>,
    ) -> Result<DisputeWorkspaceExport> {
        let query = workspace_query(params);
        let export: DisputeWorkspaceExport = self
            .inner
            .request(
                HttpMethod::Get,
                "/disputes/workspace/export",
                None,
                &query,
                None,
            )
            .await?;
        let rows = export.data.len();
        if i64::try_from(rows).ok() != Some(export.total_count) {
            return Err(DelopayError::Decode(format!(
                "dispute workspace export is incomplete: {rows} of {} cases arrived",
                export.total_count
            )));
        }
        Ok(export)
    }

    /// [`workspace_export`](Self::workspace_export) laid out as a PDF
    /// document, returned as its bytes. This route offers no CSV.
    pub async fn workspace_export_pdf(
        &self,
        params: Option<&DisputeWorkspaceParams>,
    ) -> Result<Vec<u8>> {
        let query = workspace_query(params);
        self.inner
            .request_bytes(
                HttpMethod::Get,
                "/disputes/workspace/export",
                &query,
                "application/pdf",
            )
            .await
    }

    /// What a bulk action would do to the selected cases, changing nothing:
    /// each case as eligible or skipped with a reason, and what the eligible
    /// ones add up to per currency. At most `max_cases` are read.
    ///
    /// `POST /disputes/workspace/bulk/preview`. Needs a dashboard JWT.
    pub async fn bulk_preview(
        &self,
        params: &DisputeBulkPreviewRequest,
    ) -> Result<DisputeBulkPreviewResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/disputes/workspace/bulk/preview",
                Some(&body),
                None,
            )
            .await
    }

    /// Accept the listed cases at their processors, at most the preview's
    /// `max_run_cases` per call; send a larger set in parts under one
    /// `request_id`. Eligibility is decided again at run time, and every case
    /// gets its own result. An `unknown` result means the processor may have
    /// acted: read the case before acting on it again.
    ///
    /// Not retried after a network error or `5xx`.
    ///
    /// `POST /disputes/workspace/bulk/accept`. Needs a dashboard JWT.
    pub async fn bulk_accept(
        &self,
        params: &DisputeBulkAcceptRequest,
    ) -> Result<DisputeBulkAcceptResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/disputes/workspace/bulk/accept",
                Some(&body),
                None,
            )
            .await
    }

    /// Add the buyer of each listed case's payment to the buyer blocklist: the
    /// payment's email and customer id, and the device ids and IP address of
    /// the browser that paid, when they can be tied to it. Identifiers already
    /// blocked are not added again, and `unattributed` names the kinds that
    /// could not be tied to the buyer.
    ///
    /// `POST /disputes/workspace/bulk/block-buyer`. Needs a dashboard JWT.
    pub async fn bulk_block_buyer(
        &self,
        params: &DisputeBulkBlockBuyerRequest,
    ) -> Result<DisputeBulkBlockBuyerResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/disputes/workspace/bulk/block-buyer",
                Some(&body),
                None,
            )
            .await
    }

    /// Correct the exchange rate of a dispute the processor reported in
    /// another currency, or record its final settled amount. Until it is
    /// settled, the reserved amount is an estimate. Needs a dashboard JWT
    /// with the external-record permission.
    ///
    /// `POST /disputes/{dispute_id}/reconcile`
    pub async fn reconcile(
        &self,
        dispute_id: &str,
        params: &DisputeReconcileRequest,
    ) -> Result<DisputeResponse> {
        let path = format!("/disputes/{}/reconcile", encode_segment(dispute_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
            .await
    }

    /// The refunds declared against a dispute, and the refund references the
    /// provider reported. An empty list means unknown, not "none".
    ///
    /// `GET /disputes/{dispute_id}/refund-associations`
    pub async fn list_refund_associations(
        &self,
        dispute_id: &str,
    ) -> Result<DisputeRefundAssociationsResponse> {
        let path = format!(
            "/disputes/{}/refund-associations",
            encode_segment(dispute_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Declare, or with a `None` amount clear, an allocation of a successful
    /// refund of the disputed payment against the dispute.
    ///
    /// `PUT /disputes/{dispute_id}/refund-associations`
    pub async fn set_refund_association(
        &self,
        dispute_id: &str,
        params: &DisputeRefundAssociationRequest,
    ) -> Result<DisputeRefundDeclaration> {
        params.validate()?;
        let path = format!(
            "/disputes/{}/refund-associations",
            encode_segment(dispute_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Put, &path, Some(&body), None)
            .await
    }
}

/// Filter / pagination parameters for [`Disputes::list`] and
/// [`Disputes::list_by_profile`].
#[derive(Debug, Clone, Default)]
pub struct DisputeListParams {
    /// Maximum number of disputes to return.
    pub limit: Option<i64>,
    /// Number of disputes to skip.
    pub offset: Option<i64>,
    /// Only the dispute with this ID.
    pub dispute_id: Option<String>,
    /// Only disputes raised against this payment.
    pub payment_id: Option<String>,
    /// Only disputes in this shop (business profile).
    pub profile_id: Option<String>,
    /// Only disputes in this status.
    pub dispute_status: Option<DisputeStatus>,
    /// Only disputes at this lifecycle stage.
    pub dispute_stage: Option<DisputeStage>,
    /// Only disputes raised for this reason.
    pub reason: Option<String>,
    /// Only disputes reported by this connector.
    pub connector: Option<String>,
    /// Only the dispute carrying this connector-side dispute id. A literal
    /// value: three characters or more match as a prefix, shorter ones
    /// exactly. Supported across connectors.
    pub connector_dispute_id: Option<String>,
    /// Only disputes in this three-letter ISO 4217 currency.
    pub currency: Option<Currency>,
    /// ISO 8601 creation-time range start (required to time-filter).
    pub start_time: Option<String>,
    /// ISO 8601 creation-time range end; defaults to now.
    pub end_time: Option<String>,
    /// Filter by environment: `true` = test only, `false` = live only, `None`
    /// for all.
    pub test_mode: Option<bool>,
}

impl DisputeListParams {
    pub(crate) fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        if let Some(v) = &self.dispute_id {
            q.push(("dispute_id", v.clone()));
        }
        if let Some(v) = &self.payment_id {
            q.push(("payment_id", v.clone()));
        }
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        if let Some(v) = &self.dispute_status {
            q.push(("dispute_status", v.clone()));
        }
        if let Some(v) = &self.dispute_stage {
            q.push(("dispute_stage", v.clone()));
        }
        if let Some(v) = &self.reason {
            q.push(("reason", v.clone()));
        }
        if let Some(v) = &self.connector {
            q.push(("connector", v.clone()));
        }
        if let Some(v) = &self.connector_dispute_id {
            q.push(("connector_dispute_id", v.clone()));
        }
        if let Some(v) = &self.currency {
            q.push(("currency", v.clone()));
        }
        if let Some(v) = &self.start_time {
            q.push(("start_time", v.clone()));
        }
        if let Some(v) = &self.end_time {
            q.push(("end_time", v.clone()));
        }
        if let Some(v) = self.test_mode {
            q.push(("test_mode", v.to_string()));
        }
        q
    }
}

/// Evidence for challenging a dispute, submitted via
/// [`Disputes::submit_evidence`] / [`Disputes::attach_evidence`] and returned
/// by [`Disputes::retrieve_evidence`].
///
/// Every field is optional; file-shaped fields (`receipt`,
/// `shipping_documentation`, …) carry file IDs from the `files` resource.
/// The dispute being contested is identified by a `dispute_id` key — set it
/// through [`extra`](DisputeEvidenceRequest::extra), matching the wire shape.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DisputeEvidenceRequest {
    /// Concede instead of contesting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancel_dispute: Option<bool>,
    /// Body of an email exchange with the customer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_email_body: Option<String>,
    /// Customer's email address.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_email_address: Option<String>,
    /// Customer's name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_name: Option<String>,
    /// File ID of the customer's signature.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_signature: Option<String>,
    /// Description of the product or service sold.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub product_description: Option<String>,
    /// File ID of the receipt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub receipt: Option<String>,
    /// File ID of the refund policy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refund_policy: Option<String>,
    /// How the refund policy was disclosed to the customer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refund_policy_disclosure: Option<String>,
    /// Why the refund was refused.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refund_refusal_explanation: Option<String>,
    /// Date the service was provided.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service_date: Option<String>,
    /// File ID documenting the service.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service_documentation: Option<String>,
    /// Shipping address used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_address: Option<String>,
    /// Carrier used for shipping.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_carrier: Option<String>,
    /// Date the goods were shipped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_date: Option<String>,
    /// File ID of the shipping documentation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_documentation: Option<String>,
    /// Shipment tracking number.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shipping_tracking_number: Option<String>,
    /// File ID of any uncategorized evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uncategorized_file: Option<String>,
    /// Free-text uncategorized evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uncategorized_text: Option<String>,
    /// Access / activity log evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access_activity_log: Option<String>,
    /// Billing address used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub billing_address: Option<String>,
    /// File ID of the cancellation policy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancellation_policy: Option<String>,
    /// How the cancellation policy was disclosed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancellation_policy_disclosure: Option<String>,
    /// Rebuttal to the cancellation claim.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancellation_rebuttal: Option<String>,
    /// File ID of customer communication.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_communication: Option<String>,
    /// IP address the purchase was made from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_purchase_ip: Option<String>,
    /// File ID documenting the alleged duplicate charge.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duplicate_charge_documentation: Option<String>,
    /// Explanation of why the charge is not a duplicate.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duplicate_charge_explanation: Option<String>,
    /// Payment ID of the alleged duplicate charge.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duplicate_charge_id: Option<String>,
    /// Any additional fields (e.g. `dispute_id`) are merged in verbatim, and
    /// unknown fields returned by `retrieve_evidence` land here.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `DisputeEvidenceRequest`'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 DISPUTE_EVIDENCE_REQUEST_NAMED: &[&str] = &[
    "cancel_dispute",
    "customer_email_body",
    "customer_email_address",
    "customer_name",
    "customer_signature",
    "product_description",
    "receipt",
    "refund_policy",
    "refund_policy_disclosure",
    "refund_refusal_explanation",
    "service_date",
    "service_documentation",
    "shipping_address",
    "shipping_carrier",
    "shipping_date",
    "shipping_documentation",
    "shipping_tracking_number",
    "uncategorized_file",
    "uncategorized_text",
    "access_activity_log",
    "billing_address",
    "cancellation_policy",
    "cancellation_policy_disclosure",
    "cancellation_rebuttal",
    "customer_communication",
    "customer_purchase_ip",
    "duplicate_charge_documentation",
    "duplicate_charge_explanation",
    "duplicate_charge_id",
];

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

/// What the dispute workspace can be sorted by.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DisputeWorkspaceSortBy {
    /// When the case was received.
    ReceivedAt,
    /// The disputed amount.
    Amount,
    /// When the challenge is due.
    RespondBy,
}

impl DisputeWorkspaceSortBy {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ReceivedAt => "received_at",
            Self::Amount => "amount",
            Self::RespondBy => "respond_by",
        }
    }
}

/// Which way a list is sorted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SortDirection {
    /// Oldest, smallest or alphabetically first.
    Ascending,
    /// The default.
    Descending,
}

impl SortDirection {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ascending => "asc",
            Self::Descending => "desc",
        }
    }
}

/// Filters and pagination for the dispute workspace, its filters, aggregate
/// and export, and the `filters` of a bulk preview.
///
/// The list-valued filters (`connector`, `currency`, `dispute_status`,
/// `dispute_stage`) are sent as one comma-separated value each.
#[derive(Debug, Clone, Default, Serialize)]
pub struct DisputeWorkspaceParams {
    /// Free-text search over the cases.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search: Option<String>,
    /// Only the native dispute with this id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub native_dispute_id: Option<String>,
    /// Only cases of this payment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_id: Option<String>,
    /// Only the subscription dispute with this id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_dispute_id: Option<String>,
    /// Only cases in this shop (business profile).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Only cases in this project.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    /// Only cases of this connector account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_connector_id: Option<String>,
    /// Only cases of these connectors.
    #[serde(skip_serializing_if = "Vec::is_empty", serialize_with = "csv")]
    pub connector: Vec<String>,
    /// Only cases in these currencies.
    #[serde(skip_serializing_if = "Vec::is_empty", serialize_with = "csv")]
    pub currency: Vec<String>,
    /// Only cases in these statuses.
    #[serde(skip_serializing_if = "Vec::is_empty", serialize_with = "csv")]
    pub dispute_status: Vec<String>,
    /// Only cases at these stages.
    #[serde(skip_serializing_if = "Vec::is_empty", serialize_with = "csv")]
    pub dispute_stage: Vec<String>,
    /// Only cases raised for this reason.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// ISO 8601 range start.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<String>,
    /// ISO 8601 range end.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<String>,
    /// `true` for test cases only, `false` for live only, `None` for both.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_mode: Option<bool>,
    /// Page size.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Cases to skip.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
    /// What to sort by.
    #[serde(
        skip_serializing_if = "Option::is_none",
        serialize_with = "sort_by_token"
    )]
    pub sort_by: Option<DisputeWorkspaceSortBy>,
    /// Which way to sort.
    #[serde(
        skip_serializing_if = "Option::is_none",
        serialize_with = "sort_order_token"
    )]
    pub sort_order: Option<SortDirection>,
}

/// Serializes a list filter as one comma-separated string, as the workspace
/// takes it.
// `&Vec` rather than `&[String]`: serde hands `serialize_with` a reference to
// the field's own type.
#[allow(clippy::ptr_arg)]
fn csv<S: serde::Serializer>(
    values: &Vec<String>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    serializer.serialize_str(&values.join(","))
}

fn sort_by_token<S: serde::Serializer>(
    value: &Option<DisputeWorkspaceSortBy>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    match value {
        Some(v) => serializer.serialize_str(v.as_str()),
        None => serializer.serialize_none(),
    }
}

fn sort_order_token<S: serde::Serializer>(
    value: &Option<SortDirection>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    match value {
        Some(v) => serializer.serialize_str(v.as_str()),
        None => serializer.serialize_none(),
    }
}

impl DisputeWorkspaceParams {
    /// No filters: the first page of every case the caller sees.
    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        let mut text = |key: &'static str, value: &Option<String>| {
            if let Some(v) = value {
                q.push((key, v.clone()));
            }
        };
        text("search", &self.search);
        text("native_dispute_id", &self.native_dispute_id);
        text("payment_id", &self.payment_id);
        text("subscription_dispute_id", &self.subscription_dispute_id);
        text("profile_id", &self.profile_id);
        text("project_id", &self.project_id);
        text("merchant_connector_id", &self.merchant_connector_id);
        for (key, values) in [
            ("connector", &self.connector),
            ("currency", &self.currency),
            ("dispute_status", &self.dispute_status),
            ("dispute_stage", &self.dispute_stage),
        ] {
            if !values.is_empty() {
                q.push((key, values.join(",")));
            }
        }
        if let Some(v) = &self.reason {
            q.push(("reason", v.clone()));
        }
        if let Some(v) = &self.start_time {
            q.push(("start_time", v.clone()));
        }
        if let Some(v) = &self.end_time {
            q.push(("end_time", v.clone()));
        }
        if let Some(v) = self.test_mode {
            q.push(("test_mode", v.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()));
        }
        if let Some(v) = self.sort_by {
            q.push(("sort_by", v.as_str().to_string()));
        }
        if let Some(v) = self.sort_order {
            q.push(("sort_order", v.as_str().to_string()));
        }
        q
    }
}

fn workspace_query(params: Option<&DisputeWorkspaceParams>) -> Vec<(&'static str, String)> {
    params
        .map(DisputeWorkspaceParams::to_query)
        .unwrap_or_default()
}

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

/// Which bulk action a preview is for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DisputeBulkAction {
    /// Accept the cases at their processors.
    Accept,
    /// Add the cases' buyers to the buyer blocklist.
    BlockBuyer,
}

/// Parameters for [`Disputes::bulk_preview`]. Name the cases by `ids` or by
/// `filters`, exactly one of the two.
#[derive(Debug, Clone, Serialize)]
pub struct DisputeBulkPreviewRequest {
    /// The action to preview.
    pub action: DisputeBulkAction,
    /// Workspace row ids.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ids: Option<Vec<String>>,
    /// Every case matching the workspace's filters; `limit` and `offset` are
    /// ignored.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<DisputeWorkspaceParams>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl DisputeBulkPreviewRequest {
    /// A preview of `action` over the listed workspace rows.
    pub fn for_ids(action: DisputeBulkAction, ids: Vec<String>) -> Self {
        Self {
            action,
            ids: Some(ids),
            filters: None,
            extra: serde_json::Map::new(),
        }
    }

    /// A preview of `action` over every case matching `filters`.
    pub fn for_filters(action: DisputeBulkAction, filters: DisputeWorkspaceParams) -> Self {
        Self {
            action,
            ids: None,
            filters: Some(filters),
            extra: serde_json::Map::new(),
        }
    }
}

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

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

/// Parameters for [`Disputes::bulk_accept`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct DisputeBulkAcceptRequest {
    /// Workspace row ids, at most the preview's `max_run_cases`.
    pub ids: Vec<String>,
    /// Why the cases are accepted.
    pub note: String,
    /// A client-generated id shared by every part of one bulk accept.
    pub request_id: String,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl DisputeBulkAcceptRequest {
    /// Accept the listed cases, with a note, under `request_id`.
    pub fn new(ids: Vec<String>, note: impl Into<String>, request_id: impl Into<String>) -> Self {
        Self {
            ids,
            note: note.into(),
            request_id: request_id.into(),
            extra: serde_json::Map::new(),
        }
    }
}

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

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

/// Parameters for [`Disputes::bulk_block_buyer`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct DisputeBulkBlockBuyerRequest {
    /// Workspace row ids.
    pub ids: Vec<String>,
    /// 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 DisputeBulkBlockBuyerRequest {
    /// Block the buyers of the listed cases.
    pub fn new(ids: Vec<String>) -> Self {
        Self {
            ids,
            ..Default::default()
        }
    }

    /// 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 `DisputeBulkBlockBuyerRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const DISPUTE_BULK_BLOCK_BUYER_REQUEST_NAMED: &[&str] = &["ids", "note"];

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

/// Parameters for [`Disputes::reconcile`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "action", rename_all = "snake_case")]
#[non_exhaustive]
pub enum DisputeReconcileRequest {
    /// Reprice the reservation at the rate the processor applied. The dispute
    /// stays unreconciled.
    CorrectRate {
        /// Payment-currency major units per one major unit of the reported
        /// currency, as a positive decimal string, for example `"0.92010000"`.
        exchange_rate: String,
    },
    /// Record the final amount the processor settled, which replaces the
    /// reservation.
    Settle {
        /// The settled amount, in minor units of the payment currency.
        settled_amount: i64,
        /// Why this amount.
        reason: String,
    },
}

/// Parameters for [`Disputes::set_refund_association`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct DisputeRefundAssociationRequest {
    /// A successful refund of the disputed payment.
    pub refund_id: String,
    /// The amount allocated to the dispute, in minor units. `None` is sent as
    /// `null` and clears the allocation.
    pub allocated_amount: Option<i64>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl DisputeRefundAssociationRequest {
    /// Allocate `allocated_amount` of `refund_id` to the dispute.
    pub fn allocate(refund_id: impl Into<String>, allocated_amount: i64) -> Self {
        Self {
            refund_id: refund_id.into(),
            allocated_amount: Some(allocated_amount),
            extra: serde_json::Map::new(),
        }
    }

    /// Clear the allocation of `refund_id`.
    pub fn clear(refund_id: impl Into<String>) -> Self {
        Self {
            refund_id: refund_id.into(),
            allocated_amount: None,
            extra: serde_json::Map::new(),
        }
    }
}

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

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

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

    const DISPUTE_JSON: &str = r#"{
        "dispute_id": "dp_1", "payment_id": "pay_1", "attempt_id": "att_1",
        "amount": "500", "currency": "EUR", "dispute_stage": "dispute",
        "dispute_status": "dispute_opened", "connector": "stripe",
        "connector_status": "needs_response", "connector_dispute_id": "du_1",
        "is_already_refunded": false
    }"#;

    /// Every optional field populated so serialization emits the full key set.
    fn full_evidence_request() -> DisputeEvidenceRequest {
        let text = |s: &str| Some(s.to_string());
        DisputeEvidenceRequest {
            cancel_dispute: Some(false),
            customer_email_body: text("body"),
            customer_email_address: text("a@example.com"),
            customer_name: text("Ada"),
            customer_signature: text("file_sig"),
            product_description: text("widget"),
            receipt: text("file_receipt"),
            refund_policy: text("file_policy"),
            refund_policy_disclosure: text("shown at checkout"),
            refund_refusal_explanation: text("outside window"),
            service_date: text("2026-01-01"),
            service_documentation: text("file_service"),
            shipping_address: text("Somestr. 1"),
            shipping_carrier: text("DHL"),
            shipping_date: text("2026-01-02"),
            shipping_documentation: text("file_ship"),
            shipping_tracking_number: text("TRACK1"),
            uncategorized_file: text("file_misc"),
            uncategorized_text: text("misc"),
            access_activity_log: text("log"),
            billing_address: text("Somestr. 1"),
            cancellation_policy: text("file_cancel"),
            cancellation_policy_disclosure: text("shown at checkout"),
            cancellation_rebuttal: text("not cancelled"),
            customer_communication: text("file_comm"),
            customer_purchase_ip: text("203.0.113.7"),
            duplicate_charge_documentation: text("file_dup"),
            duplicate_charge_explanation: text("separate orders"),
            duplicate_charge_id: text("pay_2"),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard for `DISPUTE_EVIDENCE_REQUEST_NAMED`.
    #[test]
    fn evidence_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_evidence_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                DISPUTE_EVIDENCE_REQUEST_NAMED.contains(&key.as_str()),
                "DISPUTE_EVIDENCE_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or the extra-key collision guard silently stops \
                 covering this field"
            );
        }
    }

    #[test]
    fn evidence_validate_rejects_colliding_extra_key() {
        let mut req = DisputeEvidenceRequest::default();
        req.extra.insert("receipt".to_string(), json!("file_x"));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    #[test]
    fn evidence_round_trips_with_dispute_id_in_extra() {
        // `retrieve_evidence` deserializes the same struct that submit
        // serializes; the dispute_id travels in `extra` both ways.
        let mut req = DisputeEvidenceRequest {
            receipt: Some("file_receipt".to_string()),
            ..Default::default()
        };
        req.extra.insert("dispute_id".to_string(), json!("dp_1"));

        let wire = serde_json::to_string(&req).unwrap();
        let back: DisputeEvidenceRequest = serde_json::from_str(&wire).unwrap();
        assert_eq!(back.receipt.as_deref(), Some("file_receipt"));
        assert_eq!(back.extra["dispute_id"], "dp_1");
    }

    #[tokio::test]
    async fn submit_uses_post_and_attach_uses_put_on_the_evidence_path() {
        // The submit/attach pair differ ONLY by verb; a mutation collapsing
        // them to the same method must fail here.
        let (client, mock) = client_with(vec![Step::ok(DISPUTE_JSON), Step::ok(DISPUTE_JSON)]);
        let req = DisputeEvidenceRequest {
            receipt: Some("file_receipt".to_string()),
            ..Default::default()
        };
        client.disputes().submit_evidence(&req).await.unwrap();
        client.disputes().attach_evidence(&req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("POST", "https://api.test/disputes/evidence")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("PUT", "https://api.test/disputes/evidence")
        );
        assert_eq!(seen[1].body_json()["receipt"], "file_receipt");
    }

    #[tokio::test]
    async fn delete_evidence_sends_a_delete_with_a_body() {
        let (client, mock) = client_with(vec![Step::ok(DISPUTE_JSON)]);
        let mut req = DisputeEvidenceRequest::default();
        req.extra.insert("dispute_id".to_string(), json!("dp_1"));
        client.disputes().delete_evidence(&req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(seen[0].url, "https://api.test/disputes/evidence");
        assert_eq!(
            seen[0].body_json()["dispute_id"],
            "dp_1",
            "DELETE must still carry the identifying body"
        );
    }

    #[tokio::test]
    async fn list_and_list_by_profile_serialize_the_same_filters() {
        // The two calls differ ONLY by path; a mutation pointing one at the
        // other's URL must fail here.
        let (client, mock) = client_with(vec![Step::ok("[]"), Step::ok("[]")]);
        let params = DisputeListParams {
            limit: Some(10),
            dispute_status: Some("dispute_opened".to_string()),
            test_mode: Some(true),
            ..Default::default()
        };
        client.disputes().list(Some(&params)).await.unwrap();
        client
            .disputes()
            .list_by_profile(Some(&params))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            (
                "GET",
                "https://api.test/disputes/list?limit=10&dispute_status=dispute_opened&test_mode=true"
            )
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            (
                "GET",
                "https://api.test/disputes/profile/list?limit=10&dispute_status=dispute_opened&test_mode=true"
            )
        );
    }

    #[tokio::test]
    async fn list_without_params_sends_no_query() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        client.disputes().list(None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/disputes/list");
    }

    #[tokio::test]
    async fn filter_and_aggregate_paths_are_distinct() {
        let (client, mock) = client_with(vec![
            Step::ok("{}"),
            Step::ok("{}"),
            Step::ok("{}"),
            Step::ok("{}"),
        ]);
        let query = [("start_time", "2026-01-01T00:00:00Z".to_string())];
        client.disputes().filters(&[]).await.unwrap();
        client.disputes().filters_by_profile(&[]).await.unwrap();
        client.disputes().aggregate(&query).await.unwrap();
        client
            .disputes()
            .aggregate_by_profile(&query)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/disputes/filter")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/disputes/profile/filter")
        );
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            (
                "GET",
                "https://api.test/disputes/aggregate?start_time=2026-01-01T00:00:00Z"
            )
        );
        assert_eq!(
            (seen[3].method, seen[3].url.as_str()),
            (
                "GET",
                "https://api.test/disputes/profile/aggregate?start_time=2026-01-01T00:00:00Z"
            )
        );
    }

    #[tokio::test]
    async fn retrieve_evidence_and_connector_fetch_hit_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"receipt":"file_receipt","dispute_id":"dp_1"}"#),
            Step::ok(DISPUTE_JSON),
        ]);
        let evidence = client.disputes().retrieve_evidence("dp_1").await.unwrap();
        assert_eq!(evidence.receipt.as_deref(), Some("file_receipt"));
        client
            .disputes()
            .fetch_from_connector("du_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/disputes/evidence/dp_1")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/disputes/du_1/fetch")
        );
    }

    const WORKSPACE_ROW_JSON: &str = r#"{
        "id": "dp_1", "origin": "bank_card_issuer", "category": "bank_chargeback",
        "native_dispute_id": "dp_1", "payment_id": "pay_1", "connector": "stripe",
        "connector_dispute_id": "du_1", "currency": "EUR", "amount_minor": "500",
        "dispute_status": "dispute_opened", "created_at": "2026-01-01T00:00:00Z",
        "updated_at": "2026-01-02T00:00:00Z", "available_actions": ["accept"],
        "row_surprise": 1
    }"#;

    fn workspace_filters() -> DisputeWorkspaceParams {
        DisputeWorkspaceParams {
            profile_id: Some("pro_1".to_string()),
            connector: vec!["stripe".to_string(), "paypal".to_string()],
            dispute_status: vec!["dispute_opened".to_string()],
            test_mode: Some(false),
            limit: Some(25),
            sort_by: Some(DisputeWorkspaceSortBy::RespondBy),
            sort_order: Some(SortDirection::Ascending),
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn workspace_joins_list_filters_as_csv_in_the_query() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{WORKSPACE_ROW_JSON}],"has_more":true,"page_surprise":2}}"#
        ))]);
        let page = client
            .disputes()
            .workspace(Some(&workspace_filters()))
            .await
            .unwrap();
        assert!(page.has_more);
        assert_eq!(page.data[0].connector_dispute_id, "du_1");
        assert_eq!(page.data[0].available_actions, ["accept"]);
        assert_eq!(page.data[0].extra["row_surprise"], 1);
        assert_eq!(page.extra["page_surprise"], 2);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/workspace?profile_id=pro_1&connector=stripe,paypal\
             &dispute_status=dispute_opened&test_mode=false&limit=25\
             &sort_by=respond_by&sort_order=asc"
        );
    }

    #[tokio::test]
    async fn workspace_filters_gets_the_filters_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"connector":["stripe"],"currency":["EUR"],"dispute_status":[],"dispute_stage":["dispute"],"x":1}"#,
        )]);
        let filters = client.disputes().workspace_filters(None).await.unwrap();
        assert_eq!(filters.connector, ["stripe"]);
        assert_eq!(filters.dispute_stage, ["dispute"]);
        assert_eq!(filters.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/disputes/workspace/filters");
    }

    #[tokio::test]
    async fn workspace_aggregate_gets_the_aggregate_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"total_count":3,"status_with_count":{"dispute_opened":2,"unknown":1},"unknown_count":1,"x":1}"#,
        )]);
        let params = DisputeWorkspaceParams {
            currency: vec!["EUR".to_string(), "USD".to_string()],
            ..Default::default()
        };
        let agg = client
            .disputes()
            .workspace_aggregate(Some(&params))
            .await
            .unwrap();
        assert_eq!(agg.total_count, 3);
        assert_eq!(agg.status_with_count["dispute_opened"], 2);
        assert_eq!(agg.unknown_count, 1);
        assert_eq!(agg.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/workspace/aggregate?currency=EUR,USD"
        );
    }

    #[tokio::test]
    async fn workspace_export_returns_a_complete_set() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{WORKSPACE_ROW_JSON}],"total_count":1,"x":1}}"#
        ))]);
        let export = client.disputes().workspace_export(None).await.unwrap();
        assert_eq!(export.total_count, 1);
        assert_eq!(export.data[0].id, "dp_1");
        assert_eq!(export.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/disputes/workspace/export");
        assert_eq!(seen[0].header("accept"), Some("application/json"));
    }

    #[tokio::test]
    async fn workspace_export_refuses_a_short_set() {
        // Removing the count check makes this decode succeed.
        let (client, _mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{WORKSPACE_ROW_JSON}],"total_count":2}}"#
        ))]);
        match client.disputes().workspace_export(None).await.unwrap_err() {
            DelopayError::Decode(msg) => assert!(msg.contains("1 of 2"), "{msg}"),
            other => panic!("expected Decode, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn workspace_export_pdf_asks_for_a_pdf_and_returns_the_bytes() {
        let (client, mock) = client_with(vec![Step::ok("%PDF-1.7")]);
        let params = DisputeWorkspaceParams {
            search: Some("du_1".to_string()),
            ..Default::default()
        };
        let bytes = client
            .disputes()
            .workspace_export_pdf(Some(&params))
            .await
            .unwrap();
        assert_eq!(bytes, b"%PDF-1.7");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/workspace/export?search=du_1"
        );
        assert_eq!(seen[0].header("accept"), Some("application/pdf"));
    }

    #[tokio::test]
    async fn bulk_preview_sends_filters_with_csv_values() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"action":"accept","selected_count":1,
                "eligible":[{"id":"dp_1","connector":"stripe","connector_dispute_id":"du_1","currency":"EUR","amount_minor":"500"}],
                "ineligible":[{"id":"pp_1","connector":"paypal","reason":"closed"}],
                "totals":[{"currency":"EUR","amount_minor":"500","count":1,"unpriced_count":0}],
                "truncated":false,"max_cases":1000,"max_run_cases":50,"x":1}"#,
        )]);
        let req = DisputeBulkPreviewRequest::for_filters(
            DisputeBulkAction::Accept,
            DisputeWorkspaceParams {
                connector: vec!["stripe".to_string(), "paypal".to_string()],
                test_mode: Some(true),
                ..Default::default()
            },
        );
        let preview = client.disputes().bulk_preview(&req).await.unwrap();
        assert_eq!(preview.eligible[0].connector_dispute_id, "du_1");
        assert_eq!(preview.ineligible[0].reason, "closed");
        assert_eq!(preview.totals[0].count, 1);
        assert_eq!(preview.max_run_cases, 50);
        assert_eq!(preview.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/workspace/bulk/preview"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "action": "accept",
                "filters": {"connector": "stripe,paypal", "test_mode": true}
            })
        );
    }

    #[tokio::test]
    async fn bulk_accept_posts_the_ids_and_is_not_retried_on_5xx() {
        let (client, mock) = crate::http::mock::client_with_retries(
            vec![Step::status(
                503,
                r#"{"error":{"type":"api","message":"down"}}"#,
            )],
            2,
        );
        let req = DisputeBulkAcceptRequest::new(vec!["dp_1".to_string()], "refunded", "req_1");
        client.disputes().bulk_accept(&req).await.unwrap_err();
        assert_eq!(mock.call_count(), 1);
        let seen = mock.seen.lock().unwrap();
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn bulk_accept_decodes_each_result() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"results":[{"id":"dp_1","connector":"stripe","outcome":"unknown","error_code":"CE_00","x":1}]}"#,
        )]);
        let req = DisputeBulkAcceptRequest::new(vec!["dp_1".to_string()], "refunded", "req_1");
        let out = client.disputes().bulk_accept(&req).await.unwrap();
        assert_eq!(out.results[0].outcome, "unknown");
        assert_eq!(out.results[0].error_code.as_deref(), Some("CE_00"));
        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/disputes/workspace/bulk/accept"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"ids": ["dp_1"], "note": "refunded", "request_id": "req_1"})
        );
    }

    #[tokio::test]
    async fn bulk_block_buyer_posts_the_ids_and_redacts_identifier_values() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"results":[{"id":"dp_1","payment_id":"pay_1","outcome":"blocked",
                "identifiers":[{"kind":"email","value":"buyer@example.com","state":"added","entry_id":"bbl_1"}],
                "unattributed":["device_id"],"x":1}]}"#,
        )]);
        let req = DisputeBulkBlockBuyerRequest::new(vec!["dp_1".to_string()]).note("fraud");
        let out = client.disputes().bulk_block_buyer(&req).await.unwrap();
        let result = &out.results[0];
        assert_eq!(result.outcome, "blocked");
        assert_eq!(result.identifiers[0].value, "buyer@example.com");
        assert_eq!(result.unattributed, ["device_id"]);
        assert_eq!(result.extra["x"], 1);
        assert!(!format!("{out:?}").contains("buyer@example.com"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/workspace/bulk/block-buyer"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"ids": ["dp_1"], "note": "fraud"})
        );
    }

    #[tokio::test]
    async fn reconcile_posts_the_tagged_action() {
        let (client, mock) = client_with(vec![Step::ok(DISPUTE_JSON), Step::ok(DISPUTE_JSON)]);
        client
            .disputes()
            .reconcile(
                "dp/1",
                &DisputeReconcileRequest::CorrectRate {
                    exchange_rate: "0.92010000".to_string(),
                },
            )
            .await
            .unwrap();
        client
            .disputes()
            .reconcile(
                "dp_1",
                &DisputeReconcileRequest::Settle {
                    settled_amount: 980,
                    reason: "statement".to_string(),
                },
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/disputes/dp%2F1/reconcile");
        assert_eq!(
            seen[0].body_json(),
            json!({"action": "correct_rate", "exchange_rate": "0.92010000"})
        );
        assert_eq!(
            seen[1].body_json(),
            json!({"action": "settle", "settled_amount": 980, "reason": "statement"})
        );
    }

    const ASSOCIATION_JSON: &str = r#"{
        "merchant_id": "mer_1", "dispute_id": "dp_1", "refund_id": "ref_1",
        "payment_id": "pay_1", "merchant_connector_id": "mca_1", "currency": "EUR",
        "test_mode": false, "allocated_amount": 500, "declared_by": "user_1",
        "provider_reference": null, "created_at": "2026-01-01T00:00:00Z",
        "modified_at": "2026-01-01T00:00:00Z", "x": 1
    }"#;

    #[tokio::test]
    async fn list_refund_associations_gets_the_encoded_path() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"associations":[{ASSOCIATION_JSON}]}}"#
        ))]);
        let out = client
            .disputes()
            .list_refund_associations("dp/1")
            .await
            .unwrap();
        assert_eq!(out.associations[0].allocated_amount, Some(500));
        assert_eq!(out.associations[0].refund_id.as_deref(), Some("ref_1"));
        assert_eq!(out.associations[0].extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/dp%2F1/refund-associations"
        );
    }

    #[tokio::test]
    async fn set_refund_association_puts_and_sends_a_null_to_clear() {
        let (client, mock) = client_with(vec![Step::ok(ASSOCIATION_JSON)]);
        let out = client
            .disputes()
            .set_refund_association("dp_1", &DisputeRefundAssociationRequest::clear("ref_1"))
            .await
            .unwrap();
        assert_eq!(out.refund_id, "ref_1");
        assert_eq!(out.extra["x"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/disputes/dp_1/refund-associations"
        );
        // `allocated_amount` is required on the wire: skipping a `None` fails.
        assert_eq!(
            seen[0].body_json(),
            json!({"refund_id": "ref_1", "allocated_amount": null})
        );
    }

    /// Drift guard for `DISPUTE_BULK_PREVIEW_REQUEST_NAMED`.
    #[test]
    fn dispute_bulk_preview_request_named_fields_are_complete() {
        let mut req = DisputeBulkPreviewRequest::for_ids(
            DisputeBulkAction::BlockBuyer,
            vec!["dp_1".to_string()],
        );
        req.filters = Some(DisputeWorkspaceParams::new());
        assert_named_complete(&req, DISPUTE_BULK_PREVIEW_REQUEST_NAMED);
    }

    /// Drift guard for `DISPUTE_BULK_ACCEPT_REQUEST_NAMED`.
    #[test]
    fn dispute_bulk_accept_request_named_fields_are_complete() {
        let req = DisputeBulkAcceptRequest::new(vec!["dp_1".to_string()], "n", "r");
        assert_named_complete(&req, DISPUTE_BULK_ACCEPT_REQUEST_NAMED);
    }

    /// Drift guard for `DISPUTE_BULK_BLOCK_BUYER_REQUEST_NAMED`.
    #[test]
    fn dispute_bulk_block_buyer_request_named_fields_are_complete() {
        let req = DisputeBulkBlockBuyerRequest::new(vec!["dp_1".to_string()]).note("n");
        assert_named_complete(&req, DISPUTE_BULK_BLOCK_BUYER_REQUEST_NAMED);
    }

    /// Drift guard for `DISPUTE_REFUND_ASSOCIATION_REQUEST_NAMED`.
    #[test]
    fn dispute_refund_association_request_named_fields_are_complete() {
        let req = DisputeRefundAssociationRequest::allocate("ref_1", 500);
        assert_named_complete(&req, DISPUTE_REFUND_ASSOCIATION_REQUEST_NAMED);
    }

    #[test]
    fn bulk_accept_validate_rejects_colliding_extra_key() {
        let mut req = DisputeBulkAcceptRequest::new(vec![], "n", "r");
        req.extra.insert("request_id".to_string(), json!("other"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("request_id")),
            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..5)
            .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
            .disputes()
            .bulk_preview(&DisputeBulkPreviewRequest::for_ids(
                DisputeBulkAction::Accept,
                vec!["dp_1".to_string()],
            ))
            .await
            .unwrap_err();
        client
            .disputes()
            .bulk_accept(&DisputeBulkAcceptRequest::new(
                vec!["dp_1".to_string()],
                "n",
                "req_1",
            ))
            .await
            .unwrap_err();
        client
            .disputes()
            .bulk_block_buyer(&DisputeBulkBlockBuyerRequest::new(vec!["dp_1".to_string()]))
            .await
            .unwrap_err();
        client
            .disputes()
            .reconcile(
                "dp_1",
                &DisputeReconcileRequest::Settle {
                    settled_amount: 1,
                    reason: "r".to_string(),
                },
            )
            .await
            .unwrap_err();
        client
            .disputes()
            .set_refund_association(
                "dp_1",
                &DisputeRefundAssociationRequest::allocate("ref_1", 1),
            )
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 5);
        for seen in mock.seen.lock().unwrap().iter() {
            assert!(
                !seen.had_idempotency_key(),
                "{} sent the client key",
                seen.url
            );
        }
    }
}