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
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
//! The `invoices` resource: the invoices and credit notes a merchant issues
//! to their buyers.
//!
//! Each document is rendered and stored **in the merchant's name**. The
//! seller block comes from the invoice settings (see
//! [`crate::Delopay::invoice_settings`]) and every amount from the source — a
//! paid payment or a paid subscription cycle — so no request here states a
//! seller, an amount or a quantity, except the optional partial amounts of a
//! credit note, which the API caps at what the line has left.
//!
//! A document goes `draft` → `issued` → `voided`. A draft is unnumbered and
//! editable, and deleting it leaves no gap; [`Invoices::finalize`] numbers
//! it, freezes it and stores its PDF. An issued document is corrected with a
//! credit note, or voided if it never reached the buyer.
//!
//! Scope comes from the caller: a shop-scoped key sees only its shop, and a
//! merchant-level one narrows with `profile_id` on the list filters.
//!
//! Refusals arrive as [`DelopayError::Api`]: `IR_16` (400) for a document in
//! the wrong state or a source that may not be invoiced, `IR_06` (422) for a
//! finalise the document cannot pass, and `DE_13` (409) for a second live
//! invoice of one source.

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::invoice::{
    InvoiceEmailDelivery, InvoiceEmailDeliveryList, InvoiceList, InvoiceNoTaxReason,
    InvoiceShareLink, MerchantInvoiceDocument,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Create a draft from a paid payment or subscription cycle, and with
    /// [`finalize`](CreateInvoiceRequest::finalize) issue it in the same
    /// call. `POST /invoices`
    ///
    /// Carries no `Idempotency-Key` of its own, so a network error or a `5xx`
    /// is not retried unless the client was given one with
    /// [`Delopay::with_idempotency_key`](crate::Delopay::with_idempotency_key);
    /// the API deduplicates this route on that header. Use
    /// [`create_idempotent`](Self::create_idempotent) to make one call safe
    /// to retry.
    pub async fn create(&self, params: &CreateInvoiceRequest) -> Result<MerchantInvoiceDocument> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/invoices", Some(&body), &[], None)
            .await
    }

    /// [`create`](Self::create) with an `Idempotency-Key`. `POST /invoices`
    ///
    /// The same key and body return the document the first call created, in
    /// its current state, even after a lost response; a different body under
    /// the same key answers `409`. A retry of a finalising request whose
    /// draft was stored but not finalised finalises that draft.
    pub async fn create_idempotent(
        &self,
        params: &CreateInvoiceRequest,
        idempotency_key: &str,
    ) -> Result<MerchantInvoiceDocument> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/invoices",
                Some(&body),
                &[],
                Some(idempotency_key),
            )
            .await
    }

    /// One page of documents, newest first. List rows carry no `lines`
    /// unless [`include_lines`](InvoiceListParams::include_lines) is set, and
    /// never a `refund` summary. `GET /invoices`
    pub async fn list(&self, params: &InvoiceListParams) -> Result<InvoiceList> {
        self.inner
            .request(
                HttpMethod::Get,
                "/invoices",
                None,
                &params.to_query(true),
                None,
            )
            .await
    }

    /// One page of a payment's invoice and its credit notes, lines included.
    /// `GET /payments/{payment_id}/invoices`
    ///
    /// The page also says whether a merchant of record sold the payment
    /// (`merchant_of_record`, which [`create`](Self::create) then refuses)
    /// and what was refunded (`refunded_amount`, and `refund` on each
    /// invoice).
    pub async fn list_for_payment(
        &self,
        payment_id: &str,
        params: &InvoicePageParams,
    ) -> Result<InvoiceList> {
        let path = format!("/payments/{}/invoices", encode_segment(payment_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &params.to_query(), None)
            .await
    }

    /// The documents with a line of one product; a bundle's components
    /// count, flagged `included`. `GET /products/{product_id}/invoices`
    ///
    /// Takes the list filters, except that the product is the path's:
    /// [`InvoiceListParams::product_id`] is not sent.
    pub async fn list_for_product(
        &self,
        product_id: &str,
        params: &InvoiceListParams,
    ) -> Result<InvoiceList> {
        let path = format!("/products/{}/invoices", encode_segment(product_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &params.to_query(false), None)
            .await
    }

    /// The documents of one period, with the list's filters, as a file.
    /// `GET /invoices/export`
    ///
    /// [`InvoiceExportParams::format`] picks the file: CSV by default, the
    /// rows as JSON, an Excel workbook, or a ZIP of the stored PDF of every
    /// issued or voided document with the CSV beside them (at most 500
    /// documents). Amounts are decimal in each document's currency; drafts
    /// have an empty number. More than 10 000 documents are refused
    /// (`IR_06`): narrow the period.
    ///
    /// Returns the body verbatim.
    pub async fn export(&self, params: &InvoiceExportParams) -> Result<Vec<u8>> {
        self.inner
            .request_bytes(
                HttpMethod::Get,
                "/invoices/export",
                &params.to_query(),
                params.format.accept(),
            )
            .await
    }

    /// One document, lines included. `GET /invoices/{invoice_id}`
    pub async fn retrieve(&self, invoice_id: &str) -> Result<MerchantInvoiceDocument> {
        self.inner
            .request(HttpMethod::Get, &invoice_path(invoice_id), None, &[], None)
            .await
    }

    /// Edit a draft: its words, buyer, dates and tax treatment, never what
    /// was paid. `PATCH /invoices/{invoice_id}`
    ///
    /// Fields you do not set stay as they are; the `clear_*` setters clear a
    /// clearable one. A document that is not a draft is refused
    /// (`not_a_draft`).
    pub async fn update(
        &self,
        invoice_id: &str,
        params: &UpdateInvoiceRequest,
    ) -> Result<MerchantInvoiceDocument> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Patch,
                &invoice_path(invoice_id),
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Delete a draft. `DELETE /invoices/{invoice_id}`
    ///
    /// A draft has no number, so nothing leaves a gap. An issued document is
    /// refused (`not_a_draft`): void or credit it instead.
    pub async fn delete(&self, invoice_id: &str) -> Result<()> {
        // Any success body is accepted: the delete already happened, so a body
        // this SDK does not model must not turn it into an error.
        self.inner
            .request_body_keyed_with_query::<serde::de::IgnoredAny>(
                HttpMethod::Delete,
                &invoice_path(invoice_id),
                None,
                &[],
                None,
            )
            .await
            .map(|_| ())
    }

    /// Issue a draft: allocate its number, freeze it and store its PDF.
    /// `POST /invoices/{invoice_id}/finalize`
    ///
    /// The document is immutable afterwards. One that would be legally
    /// incomplete is refused with `IR_06` and a reason, such as
    /// `seller_tax_id_missing` or `line_tax_unexplained`, that says what to
    /// fix.
    pub async fn finalize(&self, invoice_id: &str) -> Result<MerchantInvoiceDocument> {
        let path = format!("{}/finalize", invoice_path(invoice_id));
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Withdraw an issued document with a reason; its number stays used.
    /// `POST /invoices/{invoice_id}/void`
    ///
    /// For a document that never reached the buyer — one they hold is
    /// corrected with [`create_credit_note`](Self::create_credit_note). An
    /// invoice with live credit notes is refused (`has_credit_notes`).
    pub async fn void(
        &self,
        invoice_id: &str,
        params: &VoidInvoiceRequest,
    ) -> Result<MerchantInvoiceDocument> {
        params.validate()?;
        let path = format!("{}/void", invoice_path(invoice_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Correct an issued invoice with a credit note: all of what it has
    /// left, or the named lines. Returns the **credit note**, not the
    /// invoice. `POST /invoices/{invoice_id}/credit-note`
    pub async fn create_credit_note(
        &self,
        invoice_id: &str,
        params: &CreateCreditNoteRequest,
    ) -> Result<MerchantInvoiceDocument> {
        params.validate()?;
        let path = format!("{}/credit-note", invoice_path(invoice_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// The document as a PDF, returned verbatim.
    /// `GET /invoices/{invoice_id}/pdf`
    ///
    /// An issued document is its stored copy; a draft renders live under a
    /// DRAFT banner, and a voided one under a VOIDED banner.
    pub async fn download_pdf(&self, invoice_id: &str) -> Result<Vec<u8>> {
        let path = format!("{}/pdf", invoice_path(invoice_id));
        self.inner
            .request_bytes(HttpMethod::Get, &path, &[], "application/pdf")
            .await
    }

    /// A public link to an issued document's stored PDF, valid for 7 days.
    /// `POST /invoices/{invoice_id}/share-link`
    ///
    /// **Anyone holding the link can open the document** without logging
    /// in. A document that is not issued is refused (`not_issued`).
    pub async fn create_share_link(&self, invoice_id: &str) -> Result<InvoiceShareLink> {
        let path = format!("{}/share-link", invoice_path(invoice_id));
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Mail an issued invoice to the buyer address it carries, its PDF
    /// attached, in the document's language.
    /// `POST /invoices/{invoice_id}/email`
    ///
    /// Each call is a new message (the next `revision`) and answers with
    /// what became of it: `sent`, or `failed` with `error_code`. Refused
    /// (`IR_16`) with `not_an_invoice` (a credit note), `not_issued`,
    /// `no_buyer_email`, `send_in_progress` and `send_limit_reached` (5 sends
    /// by hand in 24 hours).
    ///
    /// The merchant's daily sending limit is **not** a refusal: the call
    /// answers with the message `failed` and `error_code`
    /// `merchant_limit_reached`. Check `status` on the result, not only that
    /// the call succeeded.
    pub async fn send_email(&self, invoice_id: &str) -> Result<InvoiceEmailDelivery> {
        let path = format!("{}/email", invoice_path(invoice_id));
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Every message about a document to its buyer, automatic and by hand,
    /// newest first, with its delivery status. The recipient is masked.
    /// `GET /invoices/{invoice_id}/emails`
    pub async fn list_emails(&self, invoice_id: &str) -> Result<InvoiceEmailDeliveryList> {
        let path = format!("{}/emails", invoice_path(invoice_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }
}

/// `/invoices/{invoice_id}`, percent-encoded.
fn invoice_path(invoice_id: &str) -> String {
    format!("/invoices/{}", encode_segment(invoice_id))
}

/// Rejects an `extra` key that collides with one of `named`.
fn reject_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(())
}

// ---------------------------------------------------------------------------
// Requests
// ---------------------------------------------------------------------------

/// What a new document is for: **exactly one** of a paid payment of this
/// merchant, or a paid subscription cycle. Both or neither is refused.
#[derive(Debug, Clone, Default, Serialize)]
pub struct InvoiceSourceRef {
    /// A paid payment of this merchant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_id: Option<String>,
    /// A paid subscription cycle: the `id` of one of a subscription's
    /// invoices.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_invoice_id: Option<String>,
}

impl InvoiceSourceRef {
    /// A paid payment.
    pub fn payment(payment_id: impl Into<String>) -> Self {
        Self {
            payment_id: Some(payment_id.into()),
            subscription_invoice_id: None,
        }
    }

    /// A paid subscription cycle.
    pub fn subscription_cycle(subscription_invoice_id: impl Into<String>) -> Self {
        Self {
            payment_id: None,
            subscription_invoice_id: Some(subscription_invoice_id.into()),
        }
    }
}

/// The buyer block of a request. The API refuses the seller-only fields
/// (`phone`, `website`, `registration`, `bank_details`) on a buyer.
///
/// `country` (ISO 3166-1 alpha-2) decides which tax rule applies and can
/// decide the document's language; `region` (ISO 3166-2, such as `US-CA`)
/// must be one of `country`'s.
///
/// `Debug` prints only `country` and `region`: the rest is personal data.
#[derive(Clone, Default, Serialize)]
pub struct InvoiceBuyer {
    /// The buyer's name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The buyer's postal address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<String>,
    /// The buyer's email address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// The buyer's VAT id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vat_id: Option<String>,
    /// The buyer's tax number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tax_id: Option<String>,
    /// ISO 3166-1 alpha-2 country code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    /// ISO 3166-2 subdivision code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
}

impl fmt::Debug for InvoiceBuyer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InvoiceBuyer")
            .field("country", &self.country)
            .field("region", &self.region)
            .field("name", &"<redacted>")
            .field("address", &"<redacted>")
            .field("email", &"<redacted>")
            .field("vat_id", &"<redacted>")
            .field("tax_id", &"<redacted>")
            .finish()
    }
}

impl InvoiceBuyer {
    /// An empty buyer block; set the fields you want printed.
    pub fn new() -> Self {
        Self::default()
    }

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

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

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

    /// Set the buyer's VAT id.
    #[must_use]
    pub fn vat_id(mut self, vat_id: impl Into<String>) -> Self {
        self.vat_id = Some(vat_id.into());
        self
    }

    /// Set the buyer's tax number.
    #[must_use]
    pub fn tax_id(mut self, tax_id: impl Into<String>) -> Self {
        self.tax_id = Some(tax_id.into());
        self
    }

    /// Set the buyer's country (ISO 3166-1 alpha-2).
    #[must_use]
    pub fn country(mut self, country: impl Into<String>) -> Self {
        self.country = Some(country.into());
        self
    }

    /// Set the buyer's region (ISO 3166-2).
    #[must_use]
    pub fn region(mut self, region: impl Into<String>) -> Self {
        self.region = Some(region.into());
        self
    }
}

/// Parameters for [`Invoices::create`]. The lines and every amount come from
/// the source.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateInvoiceRequest {
    /// What the document is for.
    pub source: InvoiceSourceRef,
    /// Finalise the draft in the same call: numbered, frozen and its PDF
    /// stored.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finalize: Option<bool>,
    /// Prefilled from the payment's customer where known; replaces it whole
    /// when sent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buyer: Option<InvoiceBuyer>,
    /// Notes printed on the document.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
    /// `YYYY-MM-DD`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub due_date: 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 CreateInvoiceRequest {
    /// A create request for `source`.
    pub fn new(source: InvoiceSourceRef) -> Self {
        Self {
            source,
            ..Default::default()
        }
    }

    /// Finalise the draft in the same call.
    #[must_use]
    pub fn finalize(mut self, finalize: bool) -> Self {
        self.finalize = Some(finalize);
        self
    }

    /// Set the buyer block.
    #[must_use]
    pub fn buyer(mut self, buyer: InvoiceBuyer) -> Self {
        self.buyer = Some(buyer);
        self
    }

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

    /// Set the due date (`YYYY-MM-DD`).
    #[must_use]
    pub fn due_date(mut self, due_date: impl Into<String>) -> Self {
        self.due_date = Some(due_date.into());
        self
    }
}

/// Names of `CreateInvoiceRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const CREATE_INVOICE_REQUEST_NAMED: &[&str] = &["source", "finalize", "buyer", "notes", "due_date"];

impl ValidateRequest for CreateInvoiceRequest {
    fn validate(&self) -> Result<()> {
        reject_collisions(
            &self.extra,
            CREATE_INVOICE_REQUEST_NAMED,
            "CreateInvoiceRequest",
        )
    }
}

/// A change to one line of a draft. Amounts and quantities are never
/// accepted: they are what was paid.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateInvoiceLine {
    /// The line to change.
    pub id: String,
    /// New description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// `Some(Some(rate))` sets the VAT rate in basis points; `Some(None)`
    /// shows no VAT on the line, which then needs a `tax_exemption_note` or
    /// the document's `no_tax_reason`. The line's gross never changes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tax_rate_bp: Option<Option<i32>>,
    /// `Some(Some(note))` sets why the line shows no VAT or 0 %;
    /// `Some(None)` clears it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tax_exemption_note: Option<Option<String>>,
    /// Drop the line's manual tax and decide it again as a new draft does.
    /// Not together with `tax_rate_bp` or `tax_exemption_note`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reset_to_rule: Option<bool>,
}

impl UpdateInvoiceLine {
    /// A change to line `id`; set what you want changed.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            ..Default::default()
        }
    }

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

    /// Set the VAT rate in basis points (`1900` is 19 %).
    #[must_use]
    pub fn tax_rate_bp(mut self, tax_rate_bp: i32) -> Self {
        self.tax_rate_bp = Some(Some(tax_rate_bp));
        self
    }

    /// Show no VAT on the line (sends `tax_rate_bp: null`).
    #[must_use]
    pub fn no_tax_rate(mut self) -> Self {
        self.tax_rate_bp = Some(None);
        self
    }

    /// Set why the line shows no VAT or 0 %.
    #[must_use]
    pub fn tax_exemption_note(mut self, note: impl Into<String>) -> Self {
        self.tax_exemption_note = Some(Some(note.into()));
        self
    }

    /// Clear the line's exemption note (sends `null`).
    #[must_use]
    pub fn clear_tax_exemption_note(mut self) -> Self {
        self.tax_exemption_note = Some(None);
        self
    }

    /// Decide the line's tax again as a new draft does.
    #[must_use]
    pub fn reset_to_rule(mut self) -> Self {
        self.reset_to_rule = Some(true);
        self
    }
}

/// Parameters for [`Invoices::update`].
///
/// **A field you do not set stays as it is.** A `clear_*` setter sends
/// `null`, which clears that field.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateInvoiceRequest {
    /// Replaces the whole buyer block, `country` and `region` included. When
    /// the country, region, VAT id or tax number changes, every line whose
    /// tax was not set by hand is decided again.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buyer: Option<InvoiceBuyer>,
    /// `YYYY-MM-DD`. Cannot be cleared.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supply_date: Option<String>,
    /// `YYYY-MM-DD`; `Some(None)` clears.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period_start: Option<Option<String>>,
    /// `YYYY-MM-DD`; `Some(None)` clears.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period_end: Option<Option<String>>,
    /// `YYYY-MM-DD`; `Some(None)` clears.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub due_date: Option<Option<String>>,
    /// `Some(None)` clears.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<Option<String>>,
    /// The document-level reason for showing no VAT; `Some(None)` clears.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_tax_reason: Option<Option<InvoiceNoTaxReason>>,
    /// Changes to individual lines.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lines: Option<Vec<UpdateInvoiceLine>>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

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

    /// Replace the buyer block.
    #[must_use]
    pub fn buyer(mut self, buyer: InvoiceBuyer) -> Self {
        self.buyer = Some(buyer);
        self
    }

    /// Set the supply date (`YYYY-MM-DD`).
    #[must_use]
    pub fn supply_date(mut self, supply_date: impl Into<String>) -> Self {
        self.supply_date = Some(supply_date.into());
        self
    }

    /// Set the start of the service period (`YYYY-MM-DD`).
    #[must_use]
    pub fn period_start(mut self, period_start: impl Into<String>) -> Self {
        self.period_start = Some(Some(period_start.into()));
        self
    }

    /// Clear the start of the service period.
    #[must_use]
    pub fn clear_period_start(mut self) -> Self {
        self.period_start = Some(None);
        self
    }

    /// Set the end of the service period (`YYYY-MM-DD`).
    #[must_use]
    pub fn period_end(mut self, period_end: impl Into<String>) -> Self {
        self.period_end = Some(Some(period_end.into()));
        self
    }

    /// Clear the end of the service period.
    #[must_use]
    pub fn clear_period_end(mut self) -> Self {
        self.period_end = Some(None);
        self
    }

    /// Set the due date (`YYYY-MM-DD`).
    #[must_use]
    pub fn due_date(mut self, due_date: impl Into<String>) -> Self {
        self.due_date = Some(Some(due_date.into()));
        self
    }

    /// Clear the due date.
    #[must_use]
    pub fn clear_due_date(mut self) -> Self {
        self.due_date = Some(None);
        self
    }

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

    /// Clear the document's notes.
    #[must_use]
    pub fn clear_notes(mut self) -> Self {
        self.notes = Some(None);
        self
    }

    /// Set the document-level reason for showing no VAT.
    #[must_use]
    pub fn no_tax_reason(mut self, reason: InvoiceNoTaxReason) -> Self {
        self.no_tax_reason = Some(Some(reason));
        self
    }

    /// Clear the document-level reason for showing no VAT.
    #[must_use]
    pub fn clear_no_tax_reason(mut self) -> Self {
        self.no_tax_reason = Some(None);
        self
    }

    /// Change individual lines.
    #[must_use]
    pub fn lines(mut self, lines: Vec<UpdateInvoiceLine>) -> Self {
        self.lines = Some(lines);
        self
    }
}

/// Names of `UpdateInvoiceRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const UPDATE_INVOICE_REQUEST_NAMED: &[&str] = &[
    "buyer",
    "supply_date",
    "period_start",
    "period_end",
    "due_date",
    "notes",
    "no_tax_reason",
    "lines",
];

impl ValidateRequest for UpdateInvoiceRequest {
    fn validate(&self) -> Result<()> {
        reject_collisions(
            &self.extra,
            UPDATE_INVOICE_REQUEST_NAMED,
            "UpdateInvoiceRequest",
        )
    }
}

/// Parameters for [`Invoices::void`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct VoidInvoiceRequest {
    /// Required: it accounts for the number the document used.
    pub reason: String,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl VoidInvoiceRequest {
    /// A void request with the given reason.
    pub fn new(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
            ..Default::default()
        }
    }
}

/// Names of `VoidInvoiceRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const VOID_INVOICE_REQUEST_NAMED: &[&str] = &["reason"];

impl ValidateRequest for VoidInvoiceRequest {
    fn validate(&self) -> Result<()> {
        reject_collisions(
            &self.extra,
            VOID_INVOICE_REQUEST_NAMED,
            "VoidInvoiceRequest",
        )
    }
}

/// One line a credit note credits.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreditNoteLine {
    /// The invoice line to credit.
    pub invoice_line_id: String,
    /// Units to credit; every unit the line has left when unset.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quantity: Option<i64>,
    /// The gross amount to credit, positive, in minor units. Defaults to the
    /// line's remaining gross for `quantity` of its remaining units, and is
    /// never more than the line has left.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<i64>,
}

impl CreditNoteLine {
    /// Credit what invoice line `invoice_line_id` has left.
    pub fn new(invoice_line_id: impl Into<String>) -> Self {
        Self {
            invoice_line_id: invoice_line_id.into(),
            ..Default::default()
        }
    }

    /// Credit this many units.
    #[must_use]
    pub fn quantity(mut self, quantity: i64) -> Self {
        self.quantity = Some(quantity);
        self
    }

    /// Credit this gross amount, in minor units.
    #[must_use]
    pub fn amount(mut self, amount: i64) -> Self {
        self.amount = Some(amount);
        self
    }
}

/// Parameters for [`Invoices::create_credit_note`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateCreditNoteRequest {
    /// Printed on the credit note.
    pub reason: String,
    /// The lines to credit; everything the invoice has left when unset.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lines: Option<Vec<CreditNoteLine>>,
    /// Finalise the credit note in the same call.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finalize: Option<bool>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl CreateCreditNoteRequest {
    /// A credit note for everything the invoice has left, with `reason`.
    pub fn new(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
            ..Default::default()
        }
    }

    /// Credit only these lines.
    #[must_use]
    pub fn lines(mut self, lines: Vec<CreditNoteLine>) -> Self {
        self.lines = Some(lines);
        self
    }

    /// Finalise the credit note in the same call.
    #[must_use]
    pub fn finalize(mut self, finalize: bool) -> Self {
        self.finalize = Some(finalize);
        self
    }
}

/// Names of `CreateCreditNoteRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const CREATE_CREDIT_NOTE_REQUEST_NAMED: &[&str] = &["reason", "lines", "finalize"];

impl ValidateRequest for CreateCreditNoteRequest {
    fn validate(&self) -> Result<()> {
        reject_collisions(
            &self.extra,
            CREATE_CREDIT_NOTE_REQUEST_NAMED,
            "CreateCreditNoteRequest",
        )
    }
}

// ---------------------------------------------------------------------------
// Query parameters
// ---------------------------------------------------------------------------

/// Filters for [`Invoices::list`] and [`Invoices::list_for_product`]. A
/// shop-scoped caller sees only its own shop; naming another `profile_id` is
/// refused.
#[derive(Debug, Clone, Default)]
pub struct InvoiceListParams {
    /// Narrow to one shop.
    pub profile_id: Option<String>,
    /// `draft`, `issued` or `voided`.
    pub status: Option<String>,
    /// `invoice` or `credit_note`.
    pub kind: Option<String>,
    /// `true` for test documents, `false` for live ones.
    pub test_mode: Option<bool>,
    /// Documents of one payment.
    pub payment_id: Option<String>,
    /// Documents of one subscription.
    pub subscription_id: Option<String>,
    /// Documents of one subscription cycle.
    pub subscription_invoice_id: Option<String>,
    /// Documents with a line of one product. Not sent by
    /// [`Invoices::list_for_product`], whose path names the product.
    pub product_id: Option<String>,
    /// Created at or after (ISO 8601).
    pub from: Option<String>,
    /// Created before (ISO 8601).
    pub to: Option<String>,
    /// A substring of the document number or the buyer's name.
    pub q: Option<String>,
    /// At most 100; 25 when unset.
    pub limit: Option<i64>,
    /// Number of documents to skip.
    pub offset: Option<i64>,
    /// Include every document's `lines`; list rows carry none otherwise.
    pub include_lines: Option<bool>,
}

impl InvoiceListParams {
    /// No filters.
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Narrow to one status: `draft`, `issued` or `voided`.
    #[must_use]
    pub fn status(mut self, status: impl Into<String>) -> Self {
        self.status = Some(status.into());
        self
    }

    /// Narrow to one kind: `invoice` or `credit_note`.
    #[must_use]
    pub fn kind(mut self, kind: impl Into<String>) -> Self {
        self.kind = Some(kind.into());
        self
    }

    /// Read test (`true`) or live (`false`) documents.
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = Some(test_mode);
        self
    }

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

    /// Narrow to one subscription.
    #[must_use]
    pub fn subscription_id(mut self, subscription_id: impl Into<String>) -> Self {
        self.subscription_id = Some(subscription_id.into());
        self
    }

    /// Narrow to one subscription cycle.
    #[must_use]
    pub fn subscription_invoice_id(mut self, subscription_invoice_id: impl Into<String>) -> Self {
        self.subscription_invoice_id = Some(subscription_invoice_id.into());
        self
    }

    /// Narrow to documents with a line of one product.
    #[must_use]
    pub fn product_id(mut self, product_id: impl Into<String>) -> Self {
        self.product_id = Some(product_id.into());
        self
    }

    /// Created at or after (ISO 8601).
    #[must_use]
    pub fn from(mut self, from: impl Into<String>) -> Self {
        self.from = Some(from.into());
        self
    }

    /// Created before (ISO 8601).
    #[must_use]
    pub fn to(mut self, to: impl Into<String>) -> Self {
        self.to = Some(to.into());
        self
    }

    /// Search the document number and the buyer's name.
    #[must_use]
    pub fn q(mut self, q: impl Into<String>) -> Self {
        self.q = Some(q.into());
        self
    }

    /// Page size, at most 100.
    #[must_use]
    pub fn limit(mut self, limit: i64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Number of documents to skip.
    #[must_use]
    pub fn offset(mut self, offset: i64) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Include every document's lines.
    #[must_use]
    pub fn include_lines(mut self, include_lines: bool) -> Self {
        self.include_lines = Some(include_lines);
        self
    }

    fn to_query(&self, with_product: bool) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        push_filters(
            &mut q,
            &self.profile_id,
            &self.status,
            &self.kind,
            self.test_mode,
            &self.payment_id,
            &self.subscription_id,
            &self.subscription_invoice_id,
        );
        if with_product {
            push_opt(&mut q, "product_id", &self.product_id);
        }
        push_opt(&mut q, "from", &self.from);
        push_opt(&mut q, "to", &self.to);
        push_opt(&mut q, "q", &self.q);
        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.include_lines {
            q.push(("include_lines", v.to_string()));
        }
        q
    }
}

fn push_opt(q: &mut Vec<(&'static str, String)>, key: &'static str, value: &Option<String>) {
    if let Some(v) = value {
        q.push((key, v.clone()));
    }
}

/// The filters shared by the list and the export, in wire order.
#[allow(clippy::too_many_arguments)]
fn push_filters(
    q: &mut Vec<(&'static str, String)>,
    profile_id: &Option<String>,
    status: &Option<String>,
    kind: &Option<String>,
    test_mode: Option<bool>,
    payment_id: &Option<String>,
    subscription_id: &Option<String>,
    subscription_invoice_id: &Option<String>,
) {
    push_opt(q, "profile_id", profile_id);
    push_opt(q, "status", status);
    push_opt(q, "kind", kind);
    if let Some(v) = test_mode {
        q.push(("test_mode", v.to_string()));
    }
    push_opt(q, "payment_id", payment_id);
    push_opt(q, "subscription_id", subscription_id);
    push_opt(q, "subscription_invoice_id", subscription_invoice_id);
}

/// Paging for [`Invoices::list_for_payment`].
#[derive(Debug, Clone, Default)]
pub struct InvoicePageParams {
    /// At most 100; 100 when unset.
    pub limit: Option<i64>,
    /// Number of documents to skip.
    pub offset: Option<i64>,
}

impl InvoicePageParams {
    /// The first page at the default size.
    pub fn new() -> Self {
        Self::default()
    }

    /// Page size, at most 100.
    #[must_use]
    pub fn limit(mut self, limit: i64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Number of documents to skip.
    #[must_use]
    pub fn offset(mut self, offset: i64) -> Self {
        self.offset = Some(offset);
        self
    }

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

/// The file [`Invoices::export`] asks for, sent as `Accept`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvoiceExportFormat {
    /// `text/csv`, the default.
    #[default]
    Csv,
    /// `application/json`: the rows as `records`, with `record_count` and the
    /// filters applied.
    Json,
    /// An Excel workbook.
    Xlsx,
    /// `application/zip`: the stored PDF of every issued or voided document,
    /// with the CSV as `invoices.csv`. At most 500 documents.
    Zip,
}

impl InvoiceExportFormat {
    /// The `Accept` value for this format.
    pub fn accept(self) -> &'static str {
        match self {
            Self::Csv => "text/csv",
            Self::Json => "application/json",
            Self::Xlsx => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            Self::Zip => "application/zip",
        }
    }
}

/// Query for [`Invoices::export`]: the list filters over one period. `from`
/// and `to` are required.
#[derive(Debug, Clone, Default)]
pub struct InvoiceExportParams {
    /// Created at or after (ISO 8601).
    pub from: String,
    /// Created before (ISO 8601).
    pub to: String,
    /// Narrow to one shop.
    pub profile_id: Option<String>,
    /// `draft`, `issued` or `voided`.
    pub status: Option<String>,
    /// `invoice` or `credit_note`.
    pub kind: Option<String>,
    /// `true` for test documents, `false` for live ones.
    pub test_mode: Option<bool>,
    /// Documents of one payment.
    pub payment_id: Option<String>,
    /// Documents of one subscription.
    pub subscription_id: Option<String>,
    /// Documents of one subscription cycle.
    pub subscription_invoice_id: Option<String>,
    /// Documents with a line of one product.
    pub product_id: Option<String>,
    /// A substring of the document number or the buyer's name.
    pub q: Option<String>,
    /// The file to ask for. Not a query parameter: it is sent as `Accept`.
    pub format: InvoiceExportFormat,
}

impl InvoiceExportParams {
    /// An export of the documents created in `[from, to)` (ISO 8601), as CSV.
    pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
        Self {
            from: from.into(),
            to: to.into(),
            ..Default::default()
        }
    }

    /// Ask for another file.
    #[must_use]
    pub fn format(mut self, format: InvoiceExportFormat) -> Self {
        self.format = format;
        self
    }

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

    /// Narrow to one status.
    #[must_use]
    pub fn status(mut self, status: impl Into<String>) -> Self {
        self.status = Some(status.into());
        self
    }

    /// Narrow to one kind.
    #[must_use]
    pub fn kind(mut self, kind: impl Into<String>) -> Self {
        self.kind = Some(kind.into());
        self
    }

    /// Export test (`true`) or live (`false`) documents.
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = Some(test_mode);
        self
    }

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

    /// Narrow to one subscription.
    #[must_use]
    pub fn subscription_id(mut self, subscription_id: impl Into<String>) -> Self {
        self.subscription_id = Some(subscription_id.into());
        self
    }

    /// Narrow to one subscription cycle.
    #[must_use]
    pub fn subscription_invoice_id(mut self, subscription_invoice_id: impl Into<String>) -> Self {
        self.subscription_invoice_id = Some(subscription_invoice_id.into());
        self
    }

    /// Narrow to documents with a line of one product.
    #[must_use]
    pub fn product_id(mut self, product_id: impl Into<String>) -> Self {
        self.product_id = Some(product_id.into());
        self
    }

    /// Search the document number and the buyer's name.
    #[must_use]
    pub fn q(mut self, q: impl Into<String>) -> Self {
        self.q = Some(q.into());
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        push_filters(
            &mut q,
            &self.profile_id,
            &self.status,
            &self.kind,
            self.test_mode,
            &self.payment_id,
            &self.subscription_id,
            &self.subscription_invoice_id,
        );
        push_opt(&mut q, "product_id", &self.product_id);
        q.push(("from", self.from.clone()));
        q.push(("to", self.to.clone()));
        push_opt(&mut q, "q", &self.q);
        q
    }
}

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

    const DOCUMENT_JSON: &str = r#"{
        "id": "inv_1",
        "merchant_id": "mer_1",
        "profile_id": "pro_1",
        "kind": "invoice",
        "status": "draft",
        "source": "payment",
        "payment_id": "pay_1",
        "test_mode": true,
        "supply_date": "2026-01-02",
        "seller": {"name": "Shop GmbH", "address": "Berlin", "country": "DE"},
        "buyer": {"name": "Erika", "address": "Hamburg", "country": "DE"},
        "currency": "EUR",
        "net_amount": 1000,
        "tax_amount": 190,
        "gross_amount": 1190,
        "locale": "de",
        "tax_warnings": [],
        "lines": [{
            "id": "line_1", "position": 1, "description": "Mug", "quantity": 2,
            "unit_net_amount": 500, "line_net_amount": 1000, "tax_rate_bp": 1900,
            "tax_amount": 190, "gross_amount": 1190, "included": false,
            "tax_source": "rule"
        }],
        "credit_notes": [],
        "created_at": "2026-01-02T10:00:00Z",
        "modified_at": "2026-01-02T10:00:00Z",
        "surprise_field": 1
    }"#;

    fn list_json() -> String {
        format!(
            r#"{{"data":[{DOCUMENT_JSON}],"total_count":1,"limit":25,"offset":0,"surprise_field":2}}"#
        )
    }

    const DELIVERY_JSON: &str = r#"{
        "id": "ied_1", "invoice_id": "inv_1", "template_id": "invoice_issued",
        "revision": 2, "origin": "manual", "status": "failed",
        "recipient": "e***@example.com", "test_mode": false, "attempts": 1,
        "error_code": "merchant_limit_reached",
        "created_at": "2026-01-02T10:00:00Z", "modified_at": "2026-01-02T10:00:01Z",
        "surprise_field": 3
    }"#;

    #[tokio::test]
    async fn create_posts_the_source_and_decodes_the_document() {
        let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
        let params = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"))
            .finalize(true)
            .buyer(InvoiceBuyer::new().name("Erika").country("DE"))
            .due_date("2026-02-01");
        let doc = client.invoices().create(&params).await.unwrap();
        assert_eq!(doc.id, "inv_1");
        assert_eq!(doc.gross_amount, 1190);
        assert_eq!(doc.lines[0].tax_rate_bp, Some(1900));
        assert_eq!(doc.buyer.country.as_deref(), Some("DE"));
        assert_eq!(doc.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/invoices");
        assert!(!seen[0].had_idempotency_key());
        assert_eq!(
            seen[0].body_json(),
            json!({
                "source": {"payment_id": "pay_1"},
                "finalize": true,
                "buyer": {"name": "Erika", "country": "DE"},
                "due_date": "2026-02-01"
            })
        );
    }

    /// An unkeyed create meeting a `5xx` is sent once: the server has no key
    /// to deduplicate a second draft on. Mutation: pass a key in `create` —
    /// the request count becomes 2.
    #[tokio::test]
    async fn an_unkeyed_create_is_not_replayed_after_a_5xx() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(500, r#"{"error":{"message":"boom"}}"#),
                Step::ok(DOCUMENT_JSON),
            ],
            2,
        );
        let params = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"));
        assert!(client.invoices().create(&params).await.is_err());
        assert_eq!(mock.seen.lock().unwrap().len(), 1);
    }

    /// Finalising is not deduplicated by the API, so a client-wide key is
    /// not sent and a `503` is not replayed into a second issue. Mutation:
    /// call `request(.., None)` again — the header appears and the request
    /// count becomes 2.
    #[tokio::test]
    async fn finalize_ignores_a_client_wide_key_and_is_not_replayed() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, r#"{"error":{"message":"down"}}"#),
                Step::ok(DOCUMENT_JSON),
            ],
            2,
        );
        assert!(
            client
                .with_idempotency_key("client-key")
                .invoices()
                .finalize("inv_1")
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
        assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
    }

    /// `POST /invoices` deduplicates on the `Idempotency-Key` header, so a
    /// client-wide key is sent and a `503` is replayed under it.
    #[tokio::test]
    async fn create_sends_a_client_wide_key_and_is_replayed_after_a_5xx() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, r#"{"error":{"message":"down"}}"#),
                Step::ok(DOCUMENT_JSON),
            ],
            2,
        );
        let params = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"));
        client
            .with_idempotency_key("client-key")
            .invoices()
            .create(&params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 2);
        assert_eq!(seen[0].header("idempotency-key"), Some("client-key"));
        assert_eq!(seen[1].header("idempotency-key"), Some("client-key"));
    }

    #[tokio::test]
    async fn create_idempotent_sends_the_key_and_is_replayed_after_a_5xx() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(500, r#"{"error":{"message":"boom"}}"#),
                Step::ok(DOCUMENT_JSON),
            ],
            2,
        );
        let params = CreateInvoiceRequest::new(InvoiceSourceRef::subscription_cycle("sub_inv_1"));
        client
            .invoices()
            .create_idempotent(&params, "inv-key-1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 2);
        assert_eq!(seen[1].header("idempotency-key"), Some("inv-key-1"));
        assert_eq!(
            seen[1].body_json(),
            json!({"source": {"subscription_invoice_id": "sub_inv_1"}})
        );
    }

    #[tokio::test]
    async fn list_sends_every_filter() {
        let (client, mock) = client_with(vec![Step::ok(&list_json())]);
        let params = InvoiceListParams::new()
            .profile_id("pro_1")
            .status("issued")
            .kind("invoice")
            .test_mode(false)
            .payment_id("pay_1")
            .subscription_id("sub_1")
            .subscription_invoice_id("si_1")
            .product_id("prod_1")
            .from("2026-01-01T00:00:00Z")
            .to("2026-02-01T00:00:00Z")
            .q("INV-")
            .limit(10)
            .offset(20)
            .include_lines(true);
        let page = client.invoices().list(&params).await.unwrap();
        assert_eq!(page.total_count, 1);
        assert_eq!(page.data[0].id, "inv_1");
        assert_eq!(page.extra["surprise_field"], 2);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/invoices?profile_id=pro_1&status=issued&kind=invoice\
             &test_mode=false&payment_id=pay_1&subscription_id=sub_1\
             &subscription_invoice_id=si_1&product_id=prod_1\
             &from=2026-01-01T00:00:00Z&to=2026-02-01T00:00:00Z&q=INV-\
             &limit=10&offset=20&include_lines=true"
        );
    }

    #[tokio::test]
    async fn list_for_payment_encodes_the_payment_and_pages() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[],"total_count":0,"limit":5,"offset":0,
                "merchant_of_record":"creem","refunded_amount":300,"surprise_field":4}"#,
        )]);
        let page = client
            .invoices()
            .list_for_payment("pay/1", &InvoicePageParams::new().limit(5).offset(0))
            .await
            .unwrap();
        assert_eq!(page.merchant_of_record.as_deref(), Some("creem"));
        assert_eq!(page.refunded_amount, Some(300));
        assert_eq!(page.extra["surprise_field"], 4);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/payments/pay%2F1/invoices?limit=5&offset=0"
        );
    }

    /// The product is the path's: a `product_id` filter set on the params is
    /// not sent. Mutation: pass `true` to `to_query` here — the URL gains
    /// `product_id=other`.
    #[tokio::test]
    async fn list_for_product_takes_the_product_from_the_path() {
        let (client, mock) = client_with(vec![Step::ok(&list_json())]);
        let params = InvoiceListParams::new()
            .product_id("other")
            .status("issued");
        let page = client
            .invoices()
            .list_for_product("prod/1", &params)
            .await
            .unwrap();
        assert_eq!(page.data[0].extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/products/prod%2F1/invoices?status=issued"
        );
    }

    #[tokio::test]
    async fn export_returns_bytes_and_asks_for_the_chosen_format() {
        let (client, mock) = client_with(vec![Step::ok("PK\u{3}\u{4}not json")]);
        let params = InvoiceExportParams::new("2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z")
            .format(InvoiceExportFormat::Zip)
            .status("issued");
        let bytes = client.invoices().export(&params).await.unwrap();
        assert!(bytes.starts_with(b"PK"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/invoices/export?status=issued\
             &from=2026-01-01T00:00:00Z&to=2026-02-01T00:00:00Z"
        );
        assert_eq!(seen[0].header("accept"), Some("application/zip"));
    }

    #[tokio::test]
    async fn export_defaults_to_csv() {
        let (client, mock) = client_with(vec![Step::ok("number,buyer\n")]);
        let params = InvoiceExportParams::new("a", "b");
        client.invoices().export(&params).await.unwrap();
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("accept"), Some("text/csv"));
    }

    #[tokio::test]
    async fn retrieve_encodes_the_invoice_id() {
        let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
        let doc = client.invoices().retrieve("inv/1").await.unwrap();
        assert_eq!(doc.extra["surprise_field"], 1);

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

    /// Absent leaves a field, `null` clears it: the body must carry the
    /// cleared keys as `null` and leave the untouched ones out. Mutation:
    /// drop the inner `Option` on `due_date` — the `null` disappears.
    #[tokio::test]
    async fn update_patches_with_set_and_cleared_fields() {
        let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
        let params = UpdateInvoiceRequest::new()
            .supply_date("2026-01-03")
            .clear_due_date()
            .notes("Thanks")
            .no_tax_reason(InvoiceNoTaxReason::reverse_charge())
            .lines(vec![
                UpdateInvoiceLine::new("line_1")
                    .no_tax_rate()
                    .tax_exemption_note("Art. 196"),
                UpdateInvoiceLine::new("line_2").reset_to_rule(),
            ]);
        let doc = client.invoices().update("inv_1", &params).await.unwrap();
        assert_eq!(doc.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PATCH");
        assert_eq!(seen[0].url, "https://api.test/invoices/inv_1");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "supply_date": "2026-01-03",
                "due_date": null,
                "notes": "Thanks",
                "no_tax_reason": {"kind": "reverse_charge"},
                "lines": [
                    {"id": "line_1", "tax_rate_bp": null, "tax_exemption_note": "Art. 196"},
                    {"id": "line_2", "reset_to_rule": true}
                ]
            })
        );
    }

    #[tokio::test]
    async fn delete_deletes_the_draft() {
        // Decoding the body as `()` fails here: the API answers with an object.
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"deleted":true,"id":"inv_1","surprise_field":1}"#,
        )]);
        client.invoices().delete("inv_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(seen[0].url, "https://api.test/invoices/inv_1");
        assert!(seen[0].body.is_none());
    }

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

    #[tokio::test]
    async fn finalize_posts_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
        let doc = client.invoices().finalize("inv/1").await.unwrap();
        assert_eq!(doc.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/invoices/inv%2F1/finalize");
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn void_posts_the_reason() {
        let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
        let doc = client
            .invoices()
            .void("inv_1", &VoidInvoiceRequest::new("Sent to the wrong buyer"))
            .await
            .unwrap();
        assert_eq!(doc.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/invoices/inv_1/void");
        assert_eq!(
            seen[0].body_json(),
            json!({"reason": "Sent to the wrong buyer"})
        );
    }

    #[tokio::test]
    async fn create_credit_note_posts_the_lines() {
        let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
        let params = CreateCreditNoteRequest::new("Returned one mug")
            .lines(vec![CreditNoteLine::new("line_1").quantity(1).amount(595)])
            .finalize(true);
        let doc = client
            .invoices()
            .create_credit_note("inv_1", &params)
            .await
            .unwrap();
        assert_eq!(doc.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/invoices/inv_1/credit-note");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "reason": "Returned one mug",
                "lines": [{"invoice_line_id": "line_1", "quantity": 1, "amount": 595}],
                "finalize": true
            })
        );
    }

    #[tokio::test]
    async fn download_pdf_returns_bytes_and_asks_for_pdf() {
        let (client, mock) = client_with(vec![Step::ok("%PDF-1.7\nnot json")]);
        let bytes = client.invoices().download_pdf("inv/1").await.unwrap();
        assert!(bytes.starts_with(b"%PDF-1.7"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/invoices/inv%2F1/pdf");
        assert_eq!(seen[0].header("accept"), Some("application/pdf"));
    }

    #[tokio::test]
    async fn create_share_link_posts_and_decodes_the_link() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"url":"https://api.test/x?token=t","expires_at":"2026-01-09T00:00:00Z","surprise_field":5}"#,
        )]);
        let link = client.invoices().create_share_link("inv_1").await.unwrap();
        assert_eq!(link.url, "https://api.test/x?token=t");
        assert_eq!(link.extra["surprise_field"], 5);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/invoices/inv_1/share-link");
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn send_email_posts_and_decodes_a_failed_delivery() {
        let (client, mock) = client_with(vec![Step::ok(DELIVERY_JSON)]);
        let out = client.invoices().send_email("inv_1").await.unwrap();
        // A sending limit is a successful call whose message failed.
        assert_eq!(out.status, "failed");
        assert_eq!(out.error_code.as_deref(), Some("merchant_limit_reached"));
        assert_eq!(out.revision, 2);
        assert_eq!(out.extra["surprise_field"], 3);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/invoices/inv_1/email");
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn list_emails_gets_the_emails_path() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{DELIVERY_JSON}],"surprise_field":6}}"#
        ))]);
        let out = client.invoices().list_emails("inv/1").await.unwrap();
        assert_eq!(out.data[0].id, "ied_1");
        assert_eq!(out.extra["surprise_field"], 6);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/invoices/inv%2F1/emails");
    }

    #[test]
    fn buyer_debug_prints_no_personal_data() {
        let buyer = InvoiceBuyer::new()
            .name("Erika Muster")
            .email("erika@example.com")
            .vat_id("DE123456789")
            .country("DE");
        let out = format!("{buyer:?}");
        assert!(out.contains("DE"));
        for secret in ["Erika", "erika@example.com", "DE123456789"] {
            assert!(!out.contains(secret), "Debug leaked `{secret}`: {out}");
        }
    }

    fn assert_named_complete(value: Value, named: &[&str], name: &str) {
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                named.contains(&key.as_str()),
                "{name} is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `CREATE_INVOICE_REQUEST_NAMED`.
    #[test]
    fn create_invoice_request_named_fields_are_complete() {
        let req = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"))
            .finalize(true)
            .buyer(InvoiceBuyer::new().name("x"))
            .notes("n")
            .due_date("2026-01-01");
        assert_named_complete(
            serde_json::to_value(req).unwrap(),
            CREATE_INVOICE_REQUEST_NAMED,
            "CREATE_INVOICE_REQUEST_NAMED",
        );
    }

    /// Drift guard for `UPDATE_INVOICE_REQUEST_NAMED`.
    #[test]
    fn update_invoice_request_named_fields_are_complete() {
        let req = UpdateInvoiceRequest::new()
            .buyer(InvoiceBuyer::new().name("x"))
            .supply_date("2026-01-01")
            .period_start("2026-01-01")
            .period_end("2026-01-31")
            .due_date("2026-02-01")
            .notes("n")
            .no_tax_reason(InvoiceNoTaxReason::small_business())
            .lines(vec![UpdateInvoiceLine::new("l")]);
        assert_named_complete(
            serde_json::to_value(req).unwrap(),
            UPDATE_INVOICE_REQUEST_NAMED,
            "UPDATE_INVOICE_REQUEST_NAMED",
        );
    }

    /// Drift guard for `VOID_INVOICE_REQUEST_NAMED`.
    #[test]
    fn void_invoice_request_named_fields_are_complete() {
        assert_named_complete(
            serde_json::to_value(VoidInvoiceRequest::new("r")).unwrap(),
            VOID_INVOICE_REQUEST_NAMED,
            "VOID_INVOICE_REQUEST_NAMED",
        );
    }

    /// Drift guard for `CREATE_CREDIT_NOTE_REQUEST_NAMED`.
    #[test]
    fn create_credit_note_request_named_fields_are_complete() {
        let req = CreateCreditNoteRequest::new("r")
            .lines(vec![CreditNoteLine::new("l")])
            .finalize(false);
        assert_named_complete(
            serde_json::to_value(req).unwrap(),
            CREATE_CREDIT_NOTE_REQUEST_NAMED,
            "CREATE_CREDIT_NOTE_REQUEST_NAMED",
        );
    }

    #[test]
    fn validate_rejects_colliding_extra_keys() {
        let mut create = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"));
        create.extra.insert("source".to_string(), json!({}));
        let mut update = UpdateInvoiceRequest::new();
        update.extra.insert("notes".to_string(), json!("x"));
        let mut void = VoidInvoiceRequest::new("r");
        void.extra.insert("reason".to_string(), json!("x"));
        let mut credit = CreateCreditNoteRequest::new("r");
        credit.extra.insert("lines".to_string(), json!([]));
        for (err, key) in [
            (create.validate().unwrap_err(), "source"),
            (update.validate().unwrap_err(), "notes"),
            (void.validate().unwrap_err(), "reason"),
            (credit.validate().unwrap_err(), "lines"),
        ] {
            match err {
                DelopayError::InvalidRequest(msg) => assert!(msg.contains(key), "{msg}"),
                other => panic!("expected InvalidRequest, got {other:?}"),
            }
        }
    }
}