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
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
//! Hosted-shop settlement models: monthly statements, the live current-period
//! rollup, per-line detail, fee configuration and backfills.
//!
//! # Two amount families, and they do not mix
//!
//! Statement-level totals are named `*_usd` and are USD minor units — the
//! aggregation normalises every currency into one so a payout is a single
//! figure. Bucket- and line-level amounts are in the **native minor units of
//! that row's `currency`**. Both families are exposed as [`Money`] accessors
//! next to the raw integers, so an amount is never separated from the
//! currency that gives it meaning (see [`crate::money`]).
//!
//! # Redaction is a boundary, not a gap
//!
//! Shop-owner reads come back with the platform fee removed server-side:
//! that figure is DeloPay's cut of the *host's* revenue, and publishing it to
//! a third party hands over the host's margin.
//!
//! The amounts are **zeroed, not omitted** — `platform_fee_amount` and
//! `platform_fee_usd` still arrive, carrying `0`. So a zero is ambiguous by
//! design: a genuinely zero fee and a withheld one look the same, and which
//! it is depends on who asked. `SettlementLine::platform_fee_source` is the
//! one field that is genuinely absent, and it is dropped *together* with the
//! amount it describes — a live source beside a zero would say a fee exists
//! and name what priced it while the zero claims it does not.
//!
//! A single [`SettlementLine`] is the exception: its `platform_fee_amount` is
//! absent or `null` for a viewer who is not the host, and reads as `None`, so
//! there it is not ambiguous.
//!
//! Either way: never reconstruct a withheld figure from the other amounts.
//!
//! # `platform_fee_incomplete` is not `fx_incomplete`
//!
//! `fx_incomplete` means a line was left **out** of the payout figures
//! because its currency had no reporting rate — the totals are wrong until it
//! is fixed. `platform_fee_incomplete` means the informational platform-fee
//! total is a **lower bound** because some line could not be priced. Only the
//! first one is a reason to distrust what a shop owner gets paid.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::core::models::common::ProcessorCostEstimateBasis;
use crate::core::money::Money;

/// Payout progress of a settlement statement.
///
/// Modelled as a string rather than an enum: the backend is free to add a
/// state, and a strict enum would turn that into a decode failure across
/// every statement in a list.
pub type SettlementPayoutStatus = String;

/// Who owns the connector a settlement line ran through: `"host"`, `"shop"`,
/// or `"unknown"` for lines frozen before ownership tracking existed.
pub type ConnectorOwnership = String;

/// One per-connector/currency rollup inside a statement or the current-period
/// view. Amounts are native minor units of [`currency`](Self::currency).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementBucket {
    /// Connector the bucket's payments ran through. `None` groups lines with
    /// no recorded connector.
    #[serde(default)]
    pub connector: Option<String>,
    /// Host-owned or shop-brought connector — see [`ConnectorOwnership`].
    pub ownership: ConnectorOwnership,
    /// ISO 4217 currency of every amount in this bucket.
    pub currency: String,
    /// Gross successfully-captured amount.
    pub gross_amount: i64,
    /// DeloPay's platform fee. Informational for the host, and **zeroed**
    /// server-side on shop-owner reads — the key is still sent, carrying `0`.
    ///
    /// A zero here is therefore ambiguous by design: it is either a genuinely
    /// zero fee or a withheld one, and which it is depends on who asked.
    /// Either way it is a permission boundary rather than a gap, so never
    /// re-derive the figure from the other amounts.
    #[serde(default)]
    pub platform_fee_amount: i64,
    /// `true` when at least one line here is still awaiting its platform-fee
    /// figure, making [`platform_fee_amount`](Self::platform_fee_amount) a
    /// lower bound rather than a total.
    #[serde(default)]
    pub platform_fee_incomplete: bool,
    /// The host's hosting fee — what the shop owner is charged.
    pub merchant_fee_amount: i64,
    /// Refunded amount. Hosting fees are **not** returned on refunds.
    pub refund_amount: i64,
    /// `gross − refunds − hosting fees`.
    pub net_to_shop: i64,
    /// Number of settled attempts in the bucket.
    pub line_count: i64,
    /// Number of refunds in the bucket.
    pub refund_count: i64,
    /// Hosting-fee rate applied, e.g. `"2.9"` percent. `None` when the rate
    /// changed mid-period — the bucket quotes no rate rather than
    /// misattributing one.
    #[serde(default)]
    pub fee_percentage: Option<String>,
    /// Flat component of the hosting fee, minor units of
    /// [`currency`](Self::currency).
    #[serde(default)]
    pub fee_flat_amount: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl SettlementBucket {
    /// [`gross_amount`](Self::gross_amount) with its currency attached.
    #[must_use]
    pub fn gross(&self) -> Money {
        Money::new(self.gross_amount, &self.currency)
    }

    /// [`merchant_fee_amount`](Self::merchant_fee_amount) with its currency.
    #[must_use]
    pub fn merchant_fee(&self) -> Money {
        Money::new(self.merchant_fee_amount, &self.currency)
    }

    /// [`refund_amount`](Self::refund_amount) with its currency.
    #[must_use]
    pub fn refund(&self) -> Money {
        Money::new(self.refund_amount, &self.currency)
    }

    /// [`net_to_shop`](Self::net_to_shop) with its currency.
    #[must_use]
    pub fn net(&self) -> Money {
        Money::new(self.net_to_shop, &self.currency)
    }

    /// [`platform_fee_amount`](Self::platform_fee_amount) with its currency.
    ///
    /// A lower bound when
    /// [`platform_fee_incomplete`](Self::platform_fee_incomplete) is set, and
    /// withheld entirely on shop-owner reads.
    #[must_use]
    pub fn platform_fee(&self) -> Money {
        Money::new(self.platform_fee_amount, &self.currency)
    }
}

/// One generated monthly settlement statement. Every `*_usd` amount is USD
/// minor units.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct FeeStatementSummary {
    /// Statement ID.
    pub id: String,
    /// The host merchant the statement belongs to.
    pub merchant_id: String,
    /// The shop (business profile) the statement is for.
    pub profile_id: String,
    /// ISO 8601 period start (UTC).
    pub period_start: String,
    /// ISO 8601 period end (UTC).
    pub period_end: String,
    /// Whether these are test-mode figures. Test and live never blend.
    pub test_mode: bool,
    /// Gross captured, USD minor units.
    pub gross_usd: i64,
    /// DeloPay's platform fee, USD minor units. **Zeroed** — not omitted —
    /// on shop-owner reads, so a zero is either a genuinely zero fee or a
    /// withheld one. Never re-derive it from the other amounts.
    #[serde(default)]
    pub platform_fee_usd: i64,
    /// The host's hosting fee, USD minor units.
    pub merchant_fee_usd: i64,
    /// Refunded, USD minor units.
    pub refund_usd: i64,
    /// Payments taken back by a **reversal** that produced no refund row, USD
    /// minor units. Already subtracted from the net: do not subtract it again.
    #[serde(default)]
    pub reversal_usd: i64,
    /// Money taken back by settled disputes, USD minor units. Reported apart
    /// from [`refund_usd`](Self::refund_usd) because a dispute is not a refund
    /// and the two are answered for separately.
    #[serde(default)]
    pub dispute_debit_usd: i64,
    /// Money returned by disputes that were won or reversed, USD minor units.
    #[serde(default)]
    pub dispute_recovery_usd: i64,
    /// How many reversals are counted in
    /// [`reversal_usd`](Self::reversal_usd).
    #[serde(default)]
    pub reversal_count: i64,
    /// What the shop owner carried of the rail's own fee, USD minor units,
    /// when the host passes processor costs through.
    #[serde(default)]
    pub processor_cost_passthrough_usd: i64,
    /// `true` when
    /// [`processor_cost_passthrough_usd`](Self::processor_cost_passthrough_usd)
    /// is a **lower bound** — some rail fees were not reported. Never read the
    /// figure as complete while this is set.
    #[serde(default)]
    pub processor_cost_passthrough_incomplete: bool,
    /// `gross − refunds − hosting fees`, USD minor units. The computed
    /// sub-total — see
    /// [`net_after_adjustments_usd`](Self::net_after_adjustments_usd) for
    /// what is actually paid.
    pub net_to_shop_usd: i64,
    /// Settled attempts counted.
    pub line_count: i64,
    /// Refunds counted.
    pub refund_count: i64,
    /// `true` when a line was **excluded** for want of an FX rate: the
    /// figures above are missing money, not merely imprecise.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// `true` when [`platform_fee_usd`](Self::platform_fee_usd) is a lower
    /// bound. Does not affect what the shop owner is paid.
    #[serde(default)]
    pub platform_fee_incomplete: bool,
    /// Whether backfilled lines contributed to these figures.
    #[serde(default)]
    pub includes_backfill: bool,
    /// `"unpaid"`, `"partial"` or `"paid"`. While `unpaid`, re-generating
    /// rewrites the figures; afterwards they are frozen.
    pub payout_status: SettlementPayoutStatus,
    /// Handed over so far, USD minor units.
    #[serde(default)]
    pub paid_amount_usd: i64,
    /// ISO 8601 timestamp of the payout, when recorded.
    #[serde(default)]
    pub paid_at: Option<String>,
    /// Free-form note recorded with the payout.
    #[serde(default)]
    pub payout_note: Option<String>,
    /// ISO 8601 timestamp the statement was generated.
    pub generated_at: String,
    /// Signed sum of the host's manual adjustments, USD minor units.
    /// **Positive means the shop owner owes more** and their payout shrinks.
    #[serde(default)]
    pub adjustments_usd: i64,
    /// `net_to_shop_usd − adjustments_usd` — the payable figure.
    #[serde(default)]
    pub net_after_adjustments_usd: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl FeeStatementSummary {
    /// [`net_after_adjustments_usd`](Self::net_after_adjustments_usd) as
    /// USD [`Money`] — the figure to pay out.
    #[must_use]
    pub fn payable(&self) -> Money {
        Money::new(self.net_after_adjustments_usd, "USD")
    }

    /// [`gross_usd`](Self::gross_usd) as USD [`Money`].
    #[must_use]
    pub fn gross(&self) -> Money {
        Money::new(self.gross_usd, "USD")
    }

    /// [`merchant_fee_usd`](Self::merchant_fee_usd) as USD [`Money`].
    #[must_use]
    pub fn merchant_fee(&self) -> Money {
        Money::new(self.merchant_fee_usd, "USD")
    }
}

/// A statement with its per-connector/currency breakdown.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct FeeStatementDetail {
    /// The statement's own figures.
    #[serde(flatten)]
    pub summary: FeeStatementSummary,
    /// Per-connector/currency rollups behind the totals.
    #[serde(default)]
    pub breakdown: Vec<SettlementBucket>,
}

/// A page of generated statements, newest first.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementStatementListResponse {
    /// The statements on this page.
    #[serde(default)]
    pub statements: Vec<FeeStatementSummary>,
    /// Total matching statements, ignoring paging.
    #[serde(default)]
    pub total_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One shop's row in the host merchant's settlement overview.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ShopSettlementOverview {
    /// The shop (business profile).
    pub profile_id: String,
    /// Display name of the shop, when it has one.
    #[serde(default)]
    pub profile_name: Option<String>,
    /// Outstanding across all unpaid statements, USD minor units.
    #[serde(default)]
    pub unpaid_net_usd: i64,
    /// How many statements are still unpaid.
    #[serde(default)]
    pub unpaid_statement_count: i64,
    /// Running net for the current, not-yet-statemented period.
    #[serde(default)]
    pub current_period_net_usd: i64,
    /// Already paid on account of the current period, USD minor units.
    #[serde(default)]
    pub current_period_advances_usd: i64,
    /// What is left of the current period after those advances, USD minor
    /// units.
    #[serde(default)]
    pub current_period_still_accruing_usd: i64,
    /// Running hosting fee for the current period.
    #[serde(default)]
    pub current_period_merchant_fee_usd: i64,
    /// Running gross for the current period.
    #[serde(default)]
    pub current_period_gross_usd: i64,
    /// `true` when a line was excluded for want of an FX rate.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// Whether a hosting-fee schedule is configured for this shop. Without
    /// one, no settlement lines are written at all.
    #[serde(default)]
    pub has_fee_config: bool,
    /// Whether the shop's own owner may open these figures.
    #[serde(default)]
    pub visible_to_shop: bool,
    /// Whether the host passes the rail's own fees through to this shop.
    #[serde(default)]
    pub processor_cost_passthrough: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Per-shop settlement rollup for the host merchant.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementOverviewResponse {
    /// One row per shop.
    #[serde(default)]
    pub shops: Vec<ShopSettlementOverview>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Live rollup of the current (not yet statemented) period.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementCurrentResponse {
    /// ISO 8601 period start (UTC).
    pub period_start: String,
    /// ISO 8601 period end (UTC).
    pub period_end: String,
    /// Whether these are test-mode figures.
    pub test_mode: bool,
    /// Gross captured so far, USD minor units.
    #[serde(default)]
    pub gross_usd: i64,
    /// Platform fee so far, USD minor units. Withheld from shop owners.
    #[serde(default)]
    pub platform_fee_usd: i64,
    /// Hosting fee so far, USD minor units.
    #[serde(default)]
    pub merchant_fee_usd: i64,
    /// Refunded so far, USD minor units.
    #[serde(default)]
    pub refund_usd: i64,
    /// Taken back by reversals that produced no refund row, USD minor units.
    #[serde(default)]
    pub reversal_usd: i64,
    /// Taken back by settled disputes, USD minor units.
    #[serde(default)]
    pub dispute_debit_usd: i64,
    /// Returned by disputes won or reversed, USD minor units.
    #[serde(default)]
    pub dispute_recovery_usd: i64,
    /// How many reversals are counted above.
    #[serde(default)]
    pub reversal_count: i64,
    /// What the shop owner carried of the rail's own fee, USD minor units.
    #[serde(default)]
    pub processor_cost_passthrough_usd: i64,
    /// `true` when the pass-through figure is a lower bound.
    #[serde(default)]
    pub processor_cost_passthrough_incomplete: bool,
    /// Net to the shop so far, USD minor units.
    #[serde(default)]
    pub net_to_shop_usd: i64,
    /// Settled attempts counted so far.
    #[serde(default)]
    pub line_count: i64,
    /// Refunds counted so far.
    #[serde(default)]
    pub refund_count: i64,
    /// `true` when a line was excluded for want of an FX rate.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// `true` when the platform-fee total is a lower bound.
    #[serde(default)]
    pub platform_fee_incomplete: bool,
    /// Already paid on account of the running month, USD minor units — the
    /// advances recorded before a statement exists.
    #[serde(default)]
    pub advances_usd: i64,
    /// What is left of the running month after those advances, USD minor
    /// units.
    #[serde(default)]
    pub still_accruing_usd: i64,
    /// Overpayment: what was advanced beyond what the month has earned, USD
    /// minor units.
    #[serde(default)]
    pub advance_excess_usd: i64,
    /// Per-connector/currency rollups behind the totals.
    #[serde(default)]
    pub breakdown: Vec<SettlementBucket>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One manual position the host added to a statement.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StatementAdjustment {
    /// Adjustment ID.
    pub id: String,
    /// Host-authored label, e.g. `"Setup fee"`.
    pub label: String,
    /// Signed USD minor units. **Positive charges the shop owner** (reducing
    /// their payout); negative credits them.
    pub amount_usd: i64,
    /// ISO 8601 creation timestamp.
    pub created_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl StatementAdjustment {
    /// [`amount_usd`](Self::amount_usd) as USD [`Money`], sign preserved.
    #[must_use]
    pub fn amount(&self) -> Money {
        Money::new(self.amount_usd, "USD")
    }
}

/// The manual adjustments recorded on a statement.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StatementAdjustmentListResponse {
    /// The adjustments, in creation order.
    #[serde(default)]
    pub adjustments: Vec<StatementAdjustment>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One settled payment attempt. Amounts are native minor units of
/// [`currency`](Self::currency).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementLine {
    /// The payment the attempt belongs to.
    pub payment_id: String,
    /// The attempt. Only unique within a merchant.
    pub attempt_id: String,
    /// Connector the attempt ran through.
    #[serde(default)]
    pub connector: Option<String>,
    /// Host-owned or shop-brought connector.
    pub connector_ownership: ConnectorOwnership,
    /// Payment method, as stamped at record time.
    #[serde(default)]
    pub payment_method: Option<String>,
    /// Payment method type, as stamped at record time.
    #[serde(default)]
    pub payment_method_type: Option<String>,
    /// ISO 4217 currency of every amount on this line.
    pub currency: String,
    /// Gross captured.
    pub gross_amount: i64,
    /// What DeloPay charged the host for this attempt. `None` for a viewer
    /// who is not the host: absent or `null`, never zeroed. A line whose fee
    /// could not be priced still carries a figure, and says so through
    /// [`platform_fee_source`](Self::platform_fee_source).
    #[serde(default)]
    pub platform_fee_amount: Option<i64>,
    /// The host's hosting fee.
    pub merchant_fee_amount: i64,
    /// `gross − hosting fee`.
    pub net_to_shop: i64,
    /// How the hosting fee was priced.
    pub merchant_fee_source: String,
    /// How the platform fee was priced — `"unpriceable"` marks a line whose
    /// platform fee could not be computed. Absent on shop-owner reads, which
    /// is redaction rather than a gap.
    #[serde(default)]
    pub platform_fee_source: Option<String>,
    /// What the (untouched) prepaid ledger deduct did for this attempt.
    pub merchant_ledger_outcome: String,
    /// Whether the attempt was in test mode.
    pub test_mode: bool,
    /// Whether the line was written by a backfill rather than at payment time.
    #[serde(default)]
    pub backfilled: bool,
    /// ISO 8601 timestamp of the transaction.
    pub transaction_at: String,
    /// The fee schedule an estimated processor cost was priced from.
    #[serde(default)]
    pub processor_cost_basis: Option<ProcessorCostEstimateBasis>,
    /// The fee schedule the passed-through processor cost was priced from.
    #[serde(default)]
    pub processor_cost_passthrough_basis: Option<ProcessorCostEstimateBasis>,
    /// The processor's own code for the payment method.
    #[serde(default)]
    pub connector_method_code: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl SettlementLine {
    /// [`gross_amount`](Self::gross_amount) with its currency attached.
    #[must_use]
    pub fn gross(&self) -> Money {
        Money::new(self.gross_amount, &self.currency)
    }

    /// [`merchant_fee_amount`](Self::merchant_fee_amount) with its currency.
    #[must_use]
    pub fn merchant_fee(&self) -> Money {
        Money::new(self.merchant_fee_amount, &self.currency)
    }

    /// [`net_to_shop`](Self::net_to_shop) with its currency.
    #[must_use]
    pub fn net(&self) -> Money {
        Money::new(self.net_to_shop, &self.currency)
    }
}

/// A page of settlement lines.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementLineListResponse {
    /// The lines on this page.
    #[serde(default)]
    pub lines: Vec<SettlementLine>,
    /// Total matching lines, ignoring paging.
    #[serde(default)]
    pub total_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One fee schedule that currently applies to a shop.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ShopFeeConfigEntry {
    /// The fee schedule's ID.
    pub schedule_id: String,
    /// Connector the schedule is restricted to, if any.
    #[serde(default)]
    pub connector: Option<String>,
    /// Whether the schedule is scoped to this shop rather than the merchant.
    #[serde(default)]
    pub profile_specific: bool,
    /// Which fee this schedule prices (the hosting fee or the platform fee).
    pub fee_type: String,
    /// Percentage component, e.g. `2.9`.
    #[serde(default)]
    pub percentage_fee: Option<f64>,
    /// Flat component, minor units of
    /// [`flat_fee_currency`](Self::flat_fee_currency).
    #[serde(default)]
    pub flat_fee_amount: Option<i64>,
    /// Currency of the flat and min/max components.
    #[serde(default)]
    pub flat_fee_currency: Option<String>,
    /// Floor, minor units. Lifts a *priced* fee up; never creates one.
    #[serde(default)]
    pub min_fee_amount: Option<i64>,
    /// Ceiling, minor units.
    #[serde(default)]
    pub max_fee_amount: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl ShopFeeConfigEntry {
    /// [`flat_fee_amount`](Self::flat_fee_amount) with its currency attached.
    ///
    /// `None` when either half is missing — a flat fee with no currency is
    /// not an amount, and this deliberately refuses to invent one.
    #[must_use]
    pub fn flat_fee(&self) -> Option<Money> {
        match (self.flat_fee_amount, self.flat_fee_currency.as_deref()) {
            (Some(amount), Some(currency)) => Some(Money::new(amount, currency)),
            _ => None,
        }
    }
}

/// The fee schedules that currently apply to a shop.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ShopFeeConfigResponse {
    /// The shop the schedules apply to.
    pub profile_id: String,
    /// The applicable schedules.
    #[serde(default)]
    pub schedules: Vec<ShopFeeConfigEntry>,
    /// Whether the host passes the rail's own fees through to this shop.
    #[serde(default)]
    pub processor_cost_passthrough: bool,
    /// Whether the shop must consent to the current terms before the figures
    /// are binding.
    #[serde(default)]
    pub consent_required: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Outcome of enqueuing a settlement-line backfill.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementBackfillResponse {
    /// Whether the job was accepted.
    pub enqueued: bool,
    /// The enqueued job's ID.
    pub job_id: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Whether a shop's owner may open their own settlement figures.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ShopVisibilityResponse {
    /// The shop the setting is for.
    pub profile_id: String,
    /// `true` when the shop's owner can see their settlement.
    pub visible_to_shop: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    const BUCKET_JSON: &str = r#"{
        "connector": "stripe",
        "ownership": "host",
        "currency": "JPY",
        "gross_amount": 1999,
        "platform_fee_amount": 20,
        "platform_fee_incomplete": true,
        "merchant_fee_amount": 200,
        "refund_amount": 0,
        "net_to_shop": 1799,
        "line_count": 3,
        "refund_count": 0,
        "fee_percentage": "10",
        "fee_flat_amount": 0,
        "surprise_field": 1
    }"#;

    #[test]
    fn bucket_amounts_carry_their_own_currency() {
        let bucket: SettlementBucket = serde_json::from_str(BUCKET_JSON).unwrap();
        // JPY has no minor unit, so 1999 is ¥1999 — not ¥19.99. A `Money`
        // hard-coded to two digits fails right here.
        assert_eq!(bucket.gross().to_major_string().as_deref(), Some("1999"));
        assert_eq!(bucket.net().to_major_string().as_deref(), Some("1799"));
        assert_eq!(bucket.merchant_fee().amount, 200);
        assert!(bucket.platform_fee_incomplete);
        assert_eq!(bucket.extra["surprise_field"], 1);
    }

    #[test]
    fn statement_detail_flattens_the_summary_beside_the_breakdown() {
        let json = format!(
            r#"{{
                "id": "stmt_1",
                "merchant_id": "mer_1",
                "profile_id": "pro_1",
                "period_start": "2026-07-01T00:00:00Z",
                "period_end": "2026-08-01T00:00:00Z",
                "test_mode": false,
                "gross_usd": 100000,
                "platform_fee_usd": 1000,
                "merchant_fee_usd": 15000,
                "refund_usd": 0,
                "net_to_shop_usd": 85000,
                "line_count": 12,
                "refund_count": 0,
                "payout_status": "unpaid",
                "generated_at": "2026-08-01T00:20:00Z",
                "adjustments_usd": 5000,
                "net_after_adjustments_usd": 80000,
                "breakdown": [{BUCKET_JSON}]
            }}"#
        );
        let detail: FeeStatementDetail = serde_json::from_str(&json).unwrap();
        assert_eq!(detail.summary.id, "stmt_1");
        assert_eq!(detail.breakdown.len(), 1);
        // The payable figure is net *after* the host's positions, not the
        // computed sub-total — swapping the two is the bug this pins.
        assert_eq!(
            detail.summary.payable().to_major_string().as_deref(),
            Some("800.00")
        );
        assert_eq!(detail.summary.net_to_shop_usd, 85000);
        // `breakdown` must not be swallowed into the flattened summary's
        // `extra` — a mutation reordering the two would show up here.
        assert!(!detail.summary.extra.contains_key("breakdown"));
    }

    #[test]
    fn statement_defaults_absent_flags_to_false() {
        let json = r#"{
            "id": "stmt_1",
            "merchant_id": "mer_1",
            "profile_id": "pro_1",
            "period_start": "2026-07-01T00:00:00Z",
            "period_end": "2026-08-01T00:00:00Z",
            "test_mode": true,
            "gross_usd": 0,
            "platform_fee_usd": 0,
            "merchant_fee_usd": 0,
            "refund_usd": 0,
            "net_to_shop_usd": 0,
            "line_count": 0,
            "refund_count": 0,
            "payout_status": "unpaid",
            "generated_at": "2026-08-01T00:20:00Z"
        }"#;
        // Older snapshots carry no `platform_fee_incomplete`; they must
        // parse and read `false` rather than failing the whole list.
        let summary: FeeStatementSummary = serde_json::from_str(json).unwrap();
        assert!(!summary.platform_fee_incomplete);
        assert!(!summary.fx_incomplete);
        assert_eq!(summary.adjustments_usd, 0);
    }

    #[test]
    fn a_redacted_bucket_and_summary_still_decode() {
        // The backend zeroes the platform fee rather than omitting the key,
        // so this is what a shop owner actually receives. `#[serde(default)]`
        // is belt-and-braces: a payload that *did* omit it must not take the
        // whole breakdown — or a whole statement list — down with it.
        let bucket: SettlementBucket = serde_json::from_str(
            r#"{"ownership":"shop","currency":"EUR","gross_amount":1999,
                "merchant_fee_amount":200,"refund_amount":0,"net_to_shop":1799,
                "line_count":1,"refund_count":0}"#,
        )
        .unwrap();
        assert_eq!(bucket.platform_fee_amount, 0);

        let summary: FeeStatementSummary = serde_json::from_str(
            r#"{"id":"stmt_1","merchant_id":"mer_1","profile_id":"pro_1",
                "period_start":"2026-07-01T00:00:00Z","period_end":"2026-08-01T00:00:00Z",
                "test_mode":false,"gross_usd":100000,"merchant_fee_usd":15000,
                "refund_usd":0,"net_to_shop_usd":85000,"line_count":12,"refund_count":0,
                "payout_status":"unpaid","generated_at":"2026-08-01T00:20:00Z"}"#,
        )
        .unwrap();
        assert_eq!(summary.platform_fee_usd, 0);
        // The figures the shop owner is actually paid survive intact.
        assert_eq!(summary.net_to_shop_usd, 85000);
        assert_eq!(summary.merchant_fee_usd, 15000);
    }

    #[test]
    fn adjustment_amount_keeps_its_sign() {
        let json = r#"{
            "id": "adj_1",
            "label": "Goodwill credit",
            "amount_usd": -2500,
            "created_at": "2026-08-02T10:00:00Z"
        }"#;
        let adjustment: StatementAdjustment = serde_json::from_str(json).unwrap();
        // Negative = a credit in the shop owner's favour. Dropping the sign
        // would turn a credit into a charge.
        assert_eq!(
            adjustment.amount().to_major_string().as_deref(),
            Some("-25.00")
        );
    }

    #[test]
    fn line_redaction_is_visible_as_an_absent_source() {
        let json = r#"{
            "payment_id": "pay_1",
            "attempt_id": "pay_1_1",
            "connector_ownership": "shop",
            "currency": "EUR",
            "gross_amount": 1999,
            "merchant_fee_amount": 200,
            "net_to_shop": 1799,
            "merchant_fee_source": "schedule",
            "merchant_ledger_outcome": "deducted",
            "test_mode": false,
            "transaction_at": "2026-07-15T12:00:00Z"
        }"#;
        let line: SettlementLine = serde_json::from_str(json).unwrap();
        assert_eq!(line.platform_fee_source, None);
        assert_eq!(line.platform_fee_amount, None);
        assert_eq!(line.gross().to_major_string().as_deref(), Some("19.99"));
        assert!(line.processor_cost_basis.is_none());
    }

    /// The API sends `null` for a viewer who is not the host. Mutation: type
    /// the field as a plain `i64` again — this decode fails.
    #[test]
    fn line_decodes_a_null_platform_fee() {
        let line: SettlementLine = serde_json::from_str(
            r#"{"payment_id":"pay_1","attempt_id":"pay_1_1","connector_ownership":"shop",
                "currency":"EUR","gross_amount":1999,"platform_fee_amount":null,
                "merchant_fee_amount":200,"net_to_shop":1799,"merchant_fee_source":"schedule",
                "merchant_ledger_outcome":"deducted","test_mode":false,
                "transaction_at":"2026-07-15T12:00:00Z"}"#,
        )
        .unwrap();
        assert_eq!(line.platform_fee_amount, None);
        let host: SettlementLine = serde_json::from_str(
            r#"{"payment_id":"pay_1","attempt_id":"pay_1_1","connector_ownership":"host",
                "currency":"EUR","gross_amount":1999,"platform_fee_amount":40,
                "merchant_fee_amount":200,"net_to_shop":1799,"merchant_fee_source":"schedule",
                "platform_fee_source":"schedule","merchant_ledger_outcome":"deducted",
                "test_mode":false,"transaction_at":"2026-07-15T12:00:00Z"}"#,
        )
        .unwrap();
        assert_eq!(host.platform_fee_amount, Some(40));
    }

    #[test]
    fn line_decodes_the_processor_cost_bases() {
        let line: SettlementLine = serde_json::from_str(
            r#"{"payment_id":"pay_1","attempt_id":"pay_1_1","connector_ownership":"shop",
                "currency":"EUR","gross_amount":1999,"merchant_fee_amount":200,
                "net_to_shop":1799,"merchant_fee_source":"schedule",
                "merchant_ledger_outcome":"deducted","test_mode":false,
                "transaction_at":"2026-07-15T12:00:00Z","connector_method_code":"ideal",
                "processor_cost_basis":{"schedule_id":"pcs_1","merchant_scoped":true,
                    "percentage":0.29,"flat_amount":25,"flat_currency":"EUR",
                    "effective_from":"2026-01-01T00:00:00Z","payment_method_type":"ideal"},
                "processor_cost_passthrough_basis":{"schedule_id":"pcs_2",
                    "merchant_scoped":false,"effective_from":"2026-01-01T00:00:00Z"}}"#,
        )
        .unwrap();
        let basis = line.processor_cost_basis.as_ref().unwrap();
        assert!(basis.merchant_scoped);
        assert_eq!(basis.flat_amount, Some(25));
        assert_eq!(
            line.processor_cost_passthrough_basis
                .as_ref()
                .unwrap()
                .schedule_id,
            "pcs_2"
        );
        assert_eq!(line.connector_method_code.as_deref(), Some("ideal"));
    }

    #[test]
    fn flat_fee_needs_both_halves() {
        let with_currency: ShopFeeConfigEntry = serde_json::from_str(
            r#"{"schedule_id":"fee_1","fee_type":"merchant","flat_fee_amount":30,
                "flat_fee_currency":"USD"}"#,
        )
        .unwrap();
        assert_eq!(
            with_currency
                .flat_fee()
                .unwrap()
                .to_major_string()
                .as_deref(),
            Some("0.30")
        );

        // An amount with no currency is not an amount. Defaulting it to USD
        // is exactly the class of guess this SDK refuses to make.
        let without_currency: ShopFeeConfigEntry = serde_json::from_str(
            r#"{"schedule_id":"fee_1","fee_type":"merchant","flat_fee_amount":30}"#,
        )
        .unwrap();
        assert_eq!(without_currency.flat_fee(), None);
    }
}

// --- Statement payouts and advances -------------------------------------

/// One recorded transfer against a monthly statement.
///
/// Each payment is its own attributed, server-timestamped entry, which is what
/// a payout limit's windows count.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StatementPayout {
    /// The entry.
    pub id: String,
    /// What was transferred, USD minor units.
    #[serde(default)]
    pub amount_usd: i64,
    /// The amount as it left the bank, in its own currency, when that was not
    /// USD.
    #[serde(default)]
    pub original_amount: Option<i64>,
    /// The currency of [`original_amount`](Self::original_amount).
    #[serde(default)]
    pub original_currency: Option<String>,
    /// The value date the transfer carries (RFC 3339 or a plain date).
    #[serde(default)]
    pub value_date: Option<String>,
    /// How it was sent.
    #[serde(default)]
    pub method: Option<String>,
    /// The bank's or operator's own reference.
    #[serde(default)]
    pub reference: Option<String>,
    /// A free-form note recorded with it.
    #[serde(default)]
    pub note: Option<String>,
    /// Where the entry came from.
    #[serde(default)]
    pub source: Option<String>,
    /// When it was recorded, server-side (RFC 3339).
    #[serde(default)]
    pub created_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Every transfer recorded against one statement.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StatementPayoutListResponse {
    /// The entries, newest first.
    #[serde(default = "Vec::new")]
    pub payouts: Vec<StatementPayout>,
    /// What they add up to, USD minor units.
    #[serde(default)]
    pub total_usd: i64,
    /// What was paid beyond the statement's payable figure, USD minor units.
    /// A non-zero value is an overpayment to carry, not an error to hide.
    #[serde(default)]
    pub overpaid_usd: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A transfer recorded against a shop's month **before** that month's
/// statement exists.
///
/// An advance attaches to the statement once it is generated —
/// [`statement_id`](Self::statement_id) and
/// [`attached_at`](Self::attached_at) say whether that has happened.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StatementAdvance {
    /// The advance.
    pub id: String,
    /// The shop it was paid to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Start of the month it is against (RFC 3339).
    #[serde(default)]
    pub period_start: Option<String>,
    /// End of that month (RFC 3339).
    #[serde(default)]
    pub period_end: Option<String>,
    /// Which environment it belongs to. Test and live never blend.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// What was transferred, USD minor units.
    #[serde(default)]
    pub amount_usd: i64,
    /// The amount as it left the bank, in its own currency.
    #[serde(default)]
    pub original_amount: Option<i64>,
    /// The currency of [`original_amount`](Self::original_amount).
    #[serde(default)]
    pub original_currency: Option<String>,
    /// The value date the transfer carries.
    #[serde(default)]
    pub value_date: Option<String>,
    /// How it was sent.
    #[serde(default)]
    pub method: Option<String>,
    /// The bank's or operator's own reference.
    #[serde(default)]
    pub reference: Option<String>,
    /// A free-form note recorded with it.
    #[serde(default)]
    pub note: Option<String>,
    /// Where the entry came from.
    #[serde(default)]
    pub source: Option<String>,
    /// The statement it was attached to, once one exists.
    #[serde(default)]
    pub statement_id: Option<String>,
    /// When it was attached (RFC 3339).
    #[serde(default)]
    pub attached_at: Option<String>,
    /// When it was recorded (RFC 3339).
    #[serde(default)]
    pub created_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The advances recorded against one shop-month.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementAdvanceListResponse {
    /// The shop.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Start of the month (RFC 3339).
    #[serde(default)]
    pub period_start: Option<String>,
    /// End of the month (RFC 3339).
    #[serde(default)]
    pub period_end: Option<String>,
    /// Which environment the figures are for.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// The advances themselves.
    #[serde(default = "Vec::new")]
    pub advances: Vec<StatementAdvance>,
    /// What they add up to, USD minor units.
    #[serde(default)]
    pub total_usd: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// --- Processor cost events ----------------------------------------------

/// One refund or dispute, with the rail's own fee movements for it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorCostEventSource {
    /// `"refund"` or `"dispute"`.
    #[serde(default)]
    pub source_kind: Option<String>,
    /// The refund or dispute id.
    #[serde(default)]
    pub source_id: Option<String>,
    /// The payment behind it.
    #[serde(default)]
    pub payment_id: Option<String>,
    /// The attempt behind it.
    #[serde(default)]
    pub attempt_id: Option<String>,
    /// The connector that reported it.
    #[serde(default)]
    pub connector: Option<String>,
    /// The connector account it ran on.
    #[serde(default)]
    pub merchant_connector_id: Option<String>,
    /// Payment method family.
    #[serde(default)]
    pub payment_method: Option<String>,
    /// Payment method sub-type.
    #[serde(default)]
    pub payment_method_type: Option<String>,
    /// The refund's or dispute's own status.
    #[serde(default)]
    pub source_status: Option<String>,
    /// When it was created (RFC 3339).
    #[serde(default)]
    pub source_created_at: Option<String>,
    /// Which environment it belongs to.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// `"reported"`, `"unavailable"` or `"unrecorded"` — where the cost figure
    /// comes from. Only `"reported"` is a figure the rail stated; the other two
    /// are absences, and must never be rendered as a zero fee.
    #[serde(default)]
    pub cost_source: Option<String>,
    /// Why nothing could be established, when the source is `"unavailable"`.
    #[serde(default)]
    pub unavailable_reason: Option<String>,
    /// Whether every movement for this source has been collected.
    #[serde(default)]
    pub complete: Option<bool>,
    /// Whether asking the rail again could complete it.
    #[serde(default)]
    pub refreshable: Option<bool>,
    /// When the rail was last asked (RFC 3339).
    #[serde(default)]
    pub checked_at: Option<String>,
    /// The fee movements the rail reported.
    #[serde(default = "Vec::new")]
    pub events: Vec<ProcessorFeeMovement>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One fee movement the rail reported.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorFeeMovement {
    /// The provider's own event id.
    #[serde(default)]
    pub provider_event_id: Option<String>,
    /// The amount, in minor units of [`currency`](Self::currency), signed:
    /// a charge and a fee credit move opposite ways.
    #[serde(default)]
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    #[serde(default)]
    pub currency: Option<String>,
    /// Minor-unit exponent of that currency.
    #[serde(default)]
    pub exponent: Option<i64>,
    /// When the movement happened (RFC 3339).
    #[serde(default)]
    pub event_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A page of refund and dispute cost evidence.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorCostEventsResponse {
    /// The sources on this page.
    #[serde(default = "Vec::new")]
    pub data: Vec<ProcessorCostEventSource>,
    /// How many sources match in total.
    #[serde(default)]
    pub total_count: i64,
    /// Whether another page exists.
    #[serde(default)]
    pub has_more: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// --- Native-currency settlement -----------------------------------------

/// Native settlement money: **minor units as a decimal string**.
///
/// A string, not a number, because these figures are in the transaction's own
/// currency and can be large enough that a JSON number would lose digits on the
/// way through a client that parses numbers as doubles. Parse it yourself,
/// against [`NativeSettlementPreview::currency_exponent`], when you need
/// arithmetic.
pub type NativeMinor = String;

/// Whether a native settlement calculation is final or still provisional:
/// `"complete"` or `"provisional"`.
///
/// `"provisional"` means at least one source fee is unknown or estimated, so
/// every figure that depends on it is a working figure — never a number to pay
/// against.
pub type NativeSettlementQuality = String;

/// The terms a native settlement calculation ran under. Sent to preview a
/// period, and echoed back on every report so a saved figure carries the
/// question it answered.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NativeSettlementTerms {
    /// The shop being settled.
    pub profile_id: String,
    /// The transaction currency the period is calculated in.
    pub currency: String,
    /// Start of the window, UTC (RFC 3339).
    pub from: String,
    /// End of the window, UTC (RFC 3339).
    pub to: String,
    /// Which environment to calculate. Test and live never blend.
    pub test_mode: bool,
    /// The hosting rate applied to the period total, as a decimal string
    /// percentage. Applied **once to the period total**, not per transaction.
    pub hosting_rate_pct: String,
    /// The reserve rate withheld, as a decimal string percentage.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reserve_rate_pct: Option<String>,
    /// Whether disputes still open are included in the calculation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include_open_disputes: Option<bool>,
    /// Which fees may be used: `"reported_only"` takes only what the rail
    /// stated; `"reported_or_contract"` falls back to the contracted rate where
    /// nothing was reported, which is what makes a figure estimated rather than
    /// unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fee_basis: Option<String>,
}

impl NativeSettlementTerms {
    /// The terms for one shop, currency and UTC window.
    pub fn new(
        profile_id: impl Into<String>,
        currency: impl Into<String>,
        from: impl Into<String>,
        to: impl Into<String>,
        test_mode: bool,
        hosting_rate_pct: impl Into<String>,
    ) -> Self {
        Self {
            profile_id: profile_id.into(),
            currency: currency.into(),
            from: from.into(),
            to: to.into(),
            test_mode,
            hosting_rate_pct: hosting_rate_pct.into(),
            reserve_rate_pct: None,
            include_open_disputes: None,
            fee_basis: None,
        }
    }

    /// Withhold a reserve, as a decimal string percentage.
    #[must_use]
    pub fn reserve_rate_pct(mut self, reserve_rate_pct: impl Into<String>) -> Self {
        self.reserve_rate_pct = Some(reserve_rate_pct.into());
        self
    }

    /// Include disputes that are still open.
    #[must_use]
    pub fn include_open_disputes(mut self, include: bool) -> Self {
        self.include_open_disputes = Some(include);
        self
    }

    /// `"reported_only"` or `"reported_or_contract"`.
    #[must_use]
    pub fn fee_basis(mut self, fee_basis: impl Into<String>) -> Self {
        self.fee_basis = Some(fee_basis.into());
        self
    }
}

/// One fee term of a native calculation, with how far it can be trusted.
///
/// A term whose [`incomplete_source_count`](Self::incomplete_source_count) is
/// non-zero is a **lower bound**, never a total.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementFeeTerm {
    /// What the rail actually reported, minor units.
    #[serde(default)]
    pub known_amount_minor: Option<NativeMinor>,
    /// What was estimated from contract rates, minor units.
    #[serde(default)]
    pub estimated_amount_minor: Option<NativeMinor>,
    /// What the calculation applied, minor units.
    #[serde(default)]
    pub applied_amount_minor: Option<NativeMinor>,
    /// How many sources reported a fee.
    #[serde(default)]
    pub observed_source_count: i64,
    /// How many had one estimated.
    #[serde(default)]
    pub estimated_source_count: i64,
    /// How many have neither — the reason a term is a lower bound.
    #[serde(default)]
    pub incomplete_source_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The totals of a native settlement calculation, all in minor units of the
/// calculation's own currency.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementTotals {
    /// Gross captured.
    #[serde(default)]
    pub gross_minor: Option<NativeMinor>,
    /// The hosting fee, applied once to the period total.
    #[serde(default)]
    pub hosting_fee_minor: Option<NativeMinor>,
    /// The rail's fees on payments.
    #[serde(default)]
    pub payment_fees: Option<NativeSettlementFeeTerm>,
    /// Refunded.
    #[serde(default)]
    pub refund_minor: Option<NativeMinor>,
    /// The rail's fees on refunds.
    #[serde(default)]
    pub refund_fees: Option<NativeSettlementFeeTerm>,
    /// Taken back by reversals.
    #[serde(default)]
    pub reversal_minor: Option<NativeMinor>,
    /// Taken back by disputes that have settled.
    #[serde(default)]
    pub settled_dispute_minor: Option<NativeMinor>,
    /// At stake in disputes still open.
    #[serde(default)]
    pub open_dispute_minor: Option<NativeMinor>,
    /// What the calculation actually deducted for disputes — which is the open
    /// figure only when the terms said to include them.
    #[serde(default)]
    pub applied_dispute_minor: Option<NativeMinor>,
    /// The rail's fees on disputes.
    #[serde(default)]
    pub dispute_fees: Option<NativeSettlementFeeTerm>,
    /// What the shop is owed before the reserve.
    #[serde(default)]
    pub owed_minor: Option<NativeMinor>,
    /// What is withheld as reserve.
    #[serde(default)]
    pub reserve_minor: Option<NativeMinor>,
    /// What is payable after the reserve.
    #[serde(default)]
    pub payable_minor: Option<NativeMinor>,
    /// What has already been transferred against this period.
    #[serde(default)]
    pub paid_minor: Option<NativeMinor>,
    /// What is still outstanding.
    #[serde(default)]
    pub outstanding_minor: Option<NativeMinor>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One component of a provider fee, as the provider itemised it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementFeeComponent {
    /// What kind of component it is.
    #[serde(default)]
    pub kind: Option<String>,
    /// The provider's own description.
    #[serde(default)]
    pub description: Option<String>,
    /// The amount, minor units.
    #[serde(default)]
    pub amount_minor: Option<NativeMinor>,
    /// Three-letter ISO 4217 currency code.
    #[serde(default)]
    pub currency: Option<String>,
    /// Minor-unit exponent of that currency.
    #[serde(default)]
    pub exponent: Option<i64>,
    /// Whether it is already counted in the parent total, rather than being
    /// itemised beside it.
    #[serde(default)]
    pub included_in_total: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One piece of provider fee evidence behind a native calculation.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementFeeEvidence {
    /// The provider's own event id.
    #[serde(default)]
    pub provider_event_id: Option<String>,
    /// What the figure rests on.
    #[serde(default)]
    pub basis: Option<String>,
    /// The amount, minor units of [`currency`](Self::currency).
    #[serde(default)]
    pub amount_minor: Option<NativeMinor>,
    /// The currency the provider reported in — not necessarily the
    /// calculation's own.
    #[serde(default)]
    pub currency: Option<String>,
    /// Minor-unit exponent of that currency.
    #[serde(default)]
    pub exponent: Option<i64>,
    /// Which fee category it falls in.
    #[serde(default)]
    pub category: Option<String>,
    /// The amount converted into the calculation's currency, when a rate was
    /// usable.
    #[serde(default)]
    pub native_amount_minor: Option<NativeMinor>,
    /// The provider's own FX rate for that conversion.
    #[serde(default)]
    pub provider_fx_rate: Option<String>,
    /// Where that rate came from. Kept because a converted fee is only as good
    /// as the rate behind it.
    #[serde(default)]
    pub fx_provenance: Option<String>,
    /// The processor's share of the amount.
    #[serde(default)]
    pub processor_amount_minor: Option<NativeMinor>,
    /// The application's share of the amount.
    #[serde(default)]
    pub application_amount_minor: Option<NativeMinor>,
    /// Whether every component of this fee was classified.
    #[serde(default)]
    pub classification_complete: bool,
    /// Whether this evidence may overlap another piece — if set, do not add
    /// them together.
    #[serde(default)]
    pub overlap_uncertain: bool,
    /// The fee's components, as the provider itemised them.
    #[serde(default = "Vec::new")]
    pub components: Vec<NativeSettlementFeeComponent>,
    /// When the provider recorded it (RFC 3339).
    #[serde(default)]
    pub event_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One transaction behind a native settlement calculation.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementSource {
    /// What kind of row this is — a capture, a refund, a dispute.
    #[serde(default)]
    pub source_kind: Option<String>,
    /// The row's own id.
    #[serde(default)]
    pub source_id: Option<String>,
    /// The payment behind it.
    #[serde(default)]
    pub payment_id: Option<String>,
    /// The attempt behind it.
    #[serde(default)]
    pub attempt_id: Option<String>,
    /// The connector that processed it.
    #[serde(default)]
    pub connector: Option<String>,
    /// The connector account's label **as it stood when the report was
    /// frozen**, beside the stable id below: a label renamed afterwards must
    /// not silently rewrite a saved report.
    #[serde(default)]
    pub connector_label: Option<String>,
    /// The connector account it ran on.
    #[serde(default)]
    pub merchant_connector_id: Option<String>,
    /// The provider's own id for the row.
    #[serde(default)]
    pub provider_source_id: Option<String>,
    /// Payment method family.
    #[serde(default)]
    pub payment_method: Option<String>,
    /// The row's status.
    #[serde(default)]
    pub status: Option<String>,
    /// Whether the capture behind it is final.
    #[serde(default)]
    pub capture_final: bool,
    /// The row's own amount, minor units.
    #[serde(default)]
    pub amount_minor: Option<NativeMinor>,
    /// How much of that amount the calculation applied.
    #[serde(default)]
    pub applied_principal_minor: Option<NativeMinor>,
    /// The fee the rail reported for it.
    #[serde(default)]
    pub known_fee_minor: Option<NativeMinor>,
    /// The fee estimated for it from contract rates.
    #[serde(default)]
    pub estimated_fee_minor: Option<NativeMinor>,
    /// The fee the calculation applied.
    #[serde(default)]
    pub applied_fee_minor: Option<NativeMinor>,
    /// Where the applied fee came from.
    #[serde(default)]
    pub cost_source: Option<String>,
    /// Whether the fee evidence for this row is complete.
    #[serde(default)]
    pub fee_complete: bool,
    /// Why no fee could be established, when none could.
    #[serde(default)]
    pub unavailable_reason: Option<String>,
    /// When the row was created (RFC 3339).
    #[serde(default)]
    pub created_at: Option<String>,
    /// When it was last modified (RFC 3339).
    #[serde(default)]
    pub modified_at: Option<String>,
    /// When its fee was last checked with the provider (RFC 3339).
    #[serde(default)]
    pub fee_checked_at: Option<String>,
    /// The provider evidence behind its fee.
    #[serde(default = "Vec::new")]
    pub fee_evidence: Vec<NativeSettlementFeeEvidence>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Account-level fees a provider charges beside the per-transaction ones.
///
/// Host account costs: present on a report read, and **omitted from a shareable
/// export**.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementAccountFees {
    /// Which account namespace the fees belong to.
    #[serde(default)]
    pub account_namespace: Option<String>,
    /// The account's own reference.
    #[serde(default)]
    pub account_reference: Option<String>,
    /// The connector.
    #[serde(default)]
    pub connector: Option<String>,
    /// The connector account.
    #[serde(default)]
    pub merchant_connector_id: Option<String>,
    /// Whether every account fee was collected.
    #[serde(default)]
    pub complete: bool,
    /// Whether the provider explicitly reported **zero** — which is a figure,
    /// unlike an absence.
    #[serde(default)]
    pub reported_zero: bool,
    /// Why nothing could be established, when nothing could.
    #[serde(default)]
    pub unavailable_reason: Option<String>,
    /// When the provider was last asked (RFC 3339).
    #[serde(default)]
    pub checked_at: Option<String>,
    /// The evidence collected.
    #[serde(default = "Vec::new")]
    pub evidence: Vec<NativeSettlementFeeEvidence>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A native settlement calculation: a period worked out in its transaction
/// currency, with everything it rests on.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementPreview {
    /// Which calculation the figures were produced by.
    #[serde(default)]
    pub calculation_version: Option<i64>,
    /// Which rendering the figures were shaped for.
    #[serde(default)]
    pub render_version: Option<i64>,
    /// When it was calculated (RFC 3339).
    #[serde(default)]
    pub calculated_at: Option<String>,
    /// The terms it ran under.
    #[serde(default)]
    pub terms: Option<NativeSettlementTerms>,
    /// The shop's name at the time.
    #[serde(default)]
    pub profile_name: Option<String>,
    /// Minor-unit exponent of the calculation's currency — what the `*_minor`
    /// strings are scaled by.
    #[serde(default)]
    pub currency_exponent: Option<i64>,
    /// Whether the calculation is `"complete"` or `"provisional"`.
    #[serde(default)]
    pub quality: Option<NativeSettlementQuality>,
    /// The totals.
    #[serde(default)]
    pub totals: Option<NativeSettlementTotals>,
    /// The transactions behind them.
    #[serde(default = "Vec::new")]
    pub sources: Vec<NativeSettlementSource>,
    /// Transfers already recorded inside the window.
    #[serde(default = "Vec::new")]
    pub payouts_in_window: Vec<NativeSettlementPayout>,
    /// Transfers recorded outside it that still bear on the shop's balance.
    #[serde(default = "Vec::new")]
    pub payouts_outside_window: Vec<NativeSettlementPayout>,
    /// Account-level provider fees. Absent from a shareable export.
    #[serde(default = "Vec::new")]
    pub account_fees: Vec<NativeSettlementAccountFees>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A frozen, immutable version of a native settlement calculation.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementReport {
    /// The report.
    pub id: String,
    /// When it was frozen (RFC 3339).
    #[serde(default)]
    pub created_at: Option<String>,
    /// The calculation as it stood then. It does not change afterwards, even
    /// when the underlying rows do.
    #[serde(default)]
    pub snapshot: Option<NativeSettlementPreview>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One report, without its per-transaction rows.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementReportSummary {
    /// The report.
    pub id: String,
    /// When it was frozen (RFC 3339).
    #[serde(default)]
    pub created_at: Option<String>,
    /// The terms it ran under.
    #[serde(default)]
    pub terms: Option<NativeSettlementTerms>,
    /// The shop's name at the time.
    #[serde(default)]
    pub profile_name: Option<String>,
    /// Minor-unit exponent of its currency.
    #[serde(default)]
    pub currency_exponent: Option<i64>,
    /// Which calculation produced it.
    #[serde(default)]
    pub calculation_version: Option<i64>,
    /// Which rendering it was shaped for.
    #[serde(default)]
    pub render_version: Option<i64>,
    /// `"complete"` or `"provisional"`.
    #[serde(default)]
    pub quality: Option<NativeSettlementQuality>,
    /// Its totals.
    #[serde(default)]
    pub totals: Option<NativeSettlementTotals>,
    /// How many transactions it covers.
    #[serde(default)]
    pub source_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A page of report summaries.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementReportListResponse {
    /// The summaries.
    #[serde(default = "Vec::new")]
    pub data: Vec<NativeSettlementReportSummary>,
    /// Whether another page exists.
    #[serde(default)]
    pub has_more: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One transfer recorded in the native-currency ledger.
///
/// This ledger is **separate** from monthly USD statement payouts and advances:
/// the same money is never in both.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementPayout {
    /// The entry.
    pub id: String,
    /// The shop it was paid to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// The currency it was paid in.
    #[serde(default)]
    pub currency: Option<String>,
    /// Which environment it belongs to.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// The amount, minor units as a string. Negative for a reversal.
    #[serde(default)]
    pub amount_minor: Option<NativeMinor>,
    /// The value date the transfer carries.
    #[serde(default)]
    pub value_date: Option<String>,
    /// How it was sent.
    #[serde(default)]
    pub method: Option<String>,
    /// The bank's or operator's own reference.
    #[serde(default)]
    pub reference: Option<String>,
    /// A free-form note recorded with it.
    #[serde(default)]
    pub note: Option<String>,
    /// The entry this one reverses, when it is a reversal.
    #[serde(default)]
    pub reversal_of: Option<String>,
    /// When it was recorded (RFC 3339).
    #[serde(default)]
    pub created_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A page of native-ledger transfers.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementPayoutListResponse {
    /// The transfers.
    #[serde(default = "Vec::new")]
    pub data: Vec<NativeSettlementPayout>,
    /// Whether another page exists.
    #[serde(default)]
    pub has_more: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// How far a bounded fee refresh got.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NativeSettlementFeeRefreshResponse {
    /// How many sources the calculation covers.
    #[serde(default)]
    pub source_count: i64,
    /// How many now have complete fee evidence.
    #[serde(default)]
    pub complete_count: i64,
    /// Whether more sources remain.
    #[serde(default)]
    pub has_more: bool,
    /// The offset to send next. Follow it while
    /// [`has_more`](Self::has_more) is set.
    #[serde(default)]
    pub next_offset: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// --- Period cost and margin ----------------------------------------------

/// How much weight [`SettlementCostResponse::margin_usd`] carries:
/// `"exact"`, `"upper_bound"` (the real figure is this or lower) or
/// `"unknown"` (no figure is published).
pub type MarginQuality = String;

/// What the figures of a cost rollup rest on: `"reported"` (observations from
/// the rails), `"estimated"` (configured rates), `"mixed"` or `"none"`.
pub type ProcessorCostBasis = String;

/// Which revenue a margin is a margin on: `"hosting_fee"` (what a host
/// charged its shops) or `"merchant_sales"` (a merchant's own captured
/// sales). The two are never added.
pub type RevenueBasis = String;

/// Whose money a term of the cost model comes out of: `"merchant"` or
/// `"shop_owner"`.
pub type TermBearer = String;

/// How a period expense that only partly overlaps the report window is
/// counted: `"pro_rata_days"` or `"not_applied"`.
pub type ExpenseAllocation = String;

/// One bucket of processor cost in the rail's own currency, keyed by
/// connector, ownership, cost currency and cost exponent together.
///
/// Never sum [`cost_amount`](Self::cost_amount) across buckets with a
/// different currency or exponent.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorCostNativeBucket {
    /// Whether the original payment's processor cost was passed to the shop.
    /// `None` is unreported, not a statement that the host kept the cost.
    #[serde(default)]
    pub passed_through: Option<bool>,
    /// The connector.
    #[serde(default)]
    pub connector: Option<String>,
    /// Host-owned or shop-brought connector — see [`ConnectorOwnership`].
    pub ownership: ConnectorOwnership,
    /// Currency the rail reported its cut in. `None` on the bucket holding
    /// the lines that carry no figure.
    #[serde(default)]
    pub cost_currency: Option<String>,
    /// Decimal places [`cost_amount`](Self::cost_amount) is expressed in.
    #[serde(default)]
    pub cost_exponent: Option<i32>,
    /// Summed cost in `cost_currency` at `cost_exponent`. `None`, never zero,
    /// when no line in the bucket carries a figure.
    #[serde(default)]
    pub cost_amount: Option<i64>,
    /// Settlement lines in the bucket.
    #[serde(default)]
    pub line_count: i64,
    /// Lines whose cost the rail reported.
    #[serde(default)]
    pub reported_count: i64,
    /// Lines whose cost came from a configured rate.
    #[serde(default)]
    pub estimated_count: i64,
    /// Lines where the rail was asked and reports no cost: an answer, not a
    /// zero.
    #[serde(default)]
    pub unavailable_count: i64,
    /// Lines that predate cost recording, so nothing was ever asked.
    #[serde(default)]
    pub unrecorded_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A per-connector processor cost bucket, with a USD conversion.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorCostBucket {
    /// Whether the original payment's processor cost was passed to the shop.
    /// `None` is unreported.
    #[serde(default)]
    pub passed_through: Option<bool>,
    /// The connector.
    #[serde(default)]
    pub connector: Option<String>,
    /// Host-owned or shop-brought connector — see [`ConnectorOwnership`].
    pub ownership: ConnectorOwnership,
    /// Currency the rail reported its cut in.
    #[serde(default)]
    pub cost_currency: Option<String>,
    /// Decimal places [`cost_amount`](Self::cost_amount) is expressed in.
    #[serde(default)]
    pub cost_exponent: Option<i32>,
    /// Summed cost in `cost_currency` at `cost_exponent`. `None`, never zero,
    /// when no line carries a figure.
    #[serde(default)]
    pub cost_amount: Option<i64>,
    /// The same cost in USD minor units. `None` when no reporting rate covers
    /// the currency: unconverted is not free.
    #[serde(default)]
    pub cost_usd: Option<i64>,
    /// Settlement lines in the bucket.
    #[serde(default)]
    pub line_count: i64,
    /// Lines whose cost the rail reported.
    #[serde(default)]
    pub reported_count: i64,
    /// Lines whose cost came from a configured rate.
    #[serde(default)]
    pub estimated_count: i64,
    /// Lines where the rail was asked and reports no cost.
    #[serde(default)]
    pub unavailable_count: i64,
    /// Lines that predate cost recording.
    #[serde(default)]
    pub unrecorded_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Payment fees grouped by the method recorded when each payment settled.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorCostMethodBucket {
    /// The connector.
    #[serde(default)]
    pub connector: Option<String>,
    /// Host-owned or shop-brought connector — see [`ConnectorOwnership`].
    pub ownership: ConnectorOwnership,
    /// Payment method family.
    #[serde(default)]
    pub payment_method: Option<String>,
    /// Payment method sub-type.
    #[serde(default)]
    pub payment_method_type: Option<String>,
    /// The processor's own method identifier, where it reports one.
    #[serde(default)]
    pub connector_method_code: Option<String>,
    /// Transaction currency; [`gross_amount`](Self::gross_amount) is in its
    /// minor units.
    pub currency: String,
    /// Gross captured amount.
    #[serde(default)]
    pub gross_amount: i64,
    /// The cost, per rail currency.
    #[serde(default)]
    pub cost_buckets: Vec<ProcessorCostNativeBucket>,
    /// Settlement lines in the bucket.
    #[serde(default)]
    pub line_count: i64,
    /// Lines whose cost the rail reported.
    #[serde(default)]
    pub reported_count: i64,
    /// Lines whose cost came from a configured rate.
    #[serde(default)]
    pub estimated_count: i64,
    /// Lines where the rail was asked and reports no cost.
    #[serde(default)]
    pub unavailable_count: i64,
    /// Lines that predate cost recording.
    #[serde(default)]
    pub unrecorded_count: i64,
    /// Lines whose cost source this release cannot place.
    #[serde(default)]
    pub unclassified_count: i64,
    /// The fee as a percentage of gross. `None` unless coverage is complete,
    /// the currencies match and gross is positive.
    #[serde(default)]
    pub effective_rate_pct: Option<f64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Signed refund or dispute fees of one connector and currency.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorCostEventBucket {
    /// The connector.
    pub connector: String,
    /// Host-owned or shop-brought connector — see [`ConnectorOwnership`].
    pub ownership: ConnectorOwnership,
    /// Payment method family.
    #[serde(default)]
    pub payment_method: Option<String>,
    /// Payment method sub-type.
    #[serde(default)]
    pub payment_method_type: Option<String>,
    /// Currency of [`amount`](Self::amount).
    pub currency: String,
    /// Decimal places [`amount`](Self::amount) is expressed in.
    #[serde(default)]
    pub exponent: i32,
    /// Signed native minor units: positive expense, negative fee credit.
    #[serde(default)]
    pub amount: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Refund or dispute processor fees in one reporting period.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorCostEventTerm {
    /// USD minor units. `None` when no usable USD amount is known; a partial
    /// amount carries the gap flags below.
    #[serde(default)]
    pub amount_usd: Option<i64>,
    /// The host-borne part, USD minor units.
    #[serde(default)]
    pub host_amount_usd: Option<i64>,
    /// Refunds or disputes in the period.
    #[serde(default)]
    pub source_count: i64,
    /// Sources whose fees the rail reported.
    #[serde(default)]
    pub reported_count: i64,
    /// Sources where the rail reports no figure.
    #[serde(default)]
    pub unavailable_count: i64,
    /// Sources nothing was ever recorded for.
    #[serde(default)]
    pub unrecorded_count: i64,
    /// Some fee report is missing, stale or partial.
    #[serde(default)]
    pub incomplete: bool,
    /// Some fee could not be converted to USD.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// A host-borne fee is missing: the host's margin is then unknown, not an
    /// upper bound.
    #[serde(default)]
    pub host_incomplete: bool,
    /// A host-borne fee could not be converted to USD.
    #[serde(default)]
    pub host_fx_incomplete: bool,
    /// The fees, per connector and currency.
    #[serde(default)]
    pub breakdown: Vec<ProcessorCostEventBucket>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a host charged the shops it runs, with the evidence behind the
/// figure.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct HostingFeeTerm {
    /// Whose money it is — see [`TermBearer`].
    pub bearer: TermBearer,
    /// USD minor units. Identical to
    /// [`SettlementCostResponse::merchant_fee_usd`].
    #[serde(default)]
    pub amount_usd: i64,
    /// Settlement lines in the period.
    #[serde(default)]
    pub line_count: i64,
    /// A bucket with a non-zero hosting fee had no USD reporting rate, so
    /// `amount_usd` understates.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// Attempts where the rail took money and no settlement line exists.
    #[serde(default)]
    pub uncovered_captured_attempt_count: i64,
    /// Unlined attempts whose outcome never resolved. Informational.
    #[serde(default)]
    pub uncovered_unresolved_attempt_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One merchant-side cost term (cost of goods, partner shares).
/// [`amount_usd`](Self::amount_usd) is a lower bound whenever
/// [`incomplete`](Self::incomplete) or [`fx_incomplete`](Self::fx_incomplete)
/// is set; a gap is never a zero.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProfitCostTerm {
    /// Whose money it is — see [`TermBearer`].
    pub bearer: TermBearer,
    /// USD minor units.
    #[serde(default)]
    pub amount_usd: i64,
    /// Rows in the period, priced or not.
    #[serde(default)]
    pub row_count: i64,
    /// Rows carrying no figure at all.
    #[serde(default)]
    pub unavailable_count: i64,
    /// Rows carrying a figure this term deliberately does not sum.
    #[serde(default)]
    pub excluded_count: i64,
    /// Rows whose stored source this release cannot place.
    #[serde(default)]
    pub unclassified_count: i64,
    /// Any count above is non-zero: the total is a floor.
    #[serde(default)]
    pub incomplete: bool,
    /// A figure is in a currency no USD reporting rate covered.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// Attempts where the rail took money and no row of this kind exists.
    #[serde(default)]
    pub uncovered_captured_attempt_count: i64,
    /// The same for attempts whose outcome never resolved. Informational.
    #[serde(default)]
    pub uncovered_unresolved_attempt_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What the period cost the merchant outside the payment rails.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PeriodExpenseTerm {
    /// Whose money it is — see [`TermBearer`].
    pub bearer: TermBearer,
    /// USD minor units, after allocation. A lower bound whenever
    /// `incomplete` or `fx_incomplete` is set.
    #[serde(default)]
    pub amount_usd: i64,
    /// Rows that contributed a figure.
    #[serde(default)]
    pub row_count: i64,
    /// Rows in the window that contributed nothing, for a reason other than
    /// costing nothing.
    #[serde(default)]
    pub excluded_count: i64,
    /// `excluded_count > 0`: `amount_usd` is a floor.
    #[serde(default)]
    pub incomplete: bool,
    /// A row's currency had no USD reporting rate.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// How partly overlapping expenses were counted — see
    /// [`ExpenseAllocation`].
    pub allocation: ExpenseAllocation,
    /// Exclusive end of the sub-window expenses were allocated to (ISO date).
    /// `None` when nothing was allocated.
    #[serde(default)]
    pub allocated_through: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a merchant that hosts nobody sold in the period.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SalesRevenueTerm {
    /// `captured_usd - refunded_usd`, USD minor units. Negative in a period
    /// that refunded more than it sold.
    #[serde(default)]
    pub amount_usd: i64,
    /// What the rails captured in the period, USD minor units.
    #[serde(default)]
    pub captured_usd: i64,
    /// Successful refunds created in the period, USD minor units.
    #[serde(default)]
    pub refunded_usd: i64,
    /// Attempts contributing to `captured_usd`.
    #[serde(default)]
    pub attempt_count: i64,
    /// Refunds contributing to `refunded_usd`.
    #[serde(default)]
    pub refund_count: i64,
    /// Captures whose money went back to the buyer outside the refund flow.
    #[serde(default)]
    pub reversed_attempt_count: i64,
    /// Captures with no usable figure for how much.
    #[serde(default)]
    pub unpriced_captured_attempt_count: i64,
    /// Attempts establishing neither a capture nor its absence.
    #[serde(default)]
    pub unresolved_attempt_count: i64,
    /// Refunds left out because their attempt's gross was never counted.
    #[serde(default)]
    pub excluded_refund_count: i64,
    /// A count above is non-zero: no margin is published.
    #[serde(default)]
    pub incomplete: bool,
    /// A currency had no USD reporting rate.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a period's payments cost, and what was left over. All `*_usd`
/// figures are USD minor units.
///
/// For the merchant account holder only: a shop-scoped caller is refused.
/// The processor cost is margin reporting laid over settlement; it never
/// moves what a shop is paid.
///
/// [`margin_usd`](Self::margin_usd) is `None`, not zero, whenever
/// [`margin_quality`](Self::margin_quality) is `"unknown"`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SettlementCostResponse {
    /// Inclusive start of the period (ISO 8601, UTC).
    pub period_start: String,
    /// Exclusive end of the period (ISO 8601, UTC).
    pub period_end: String,
    /// Which environment the figures are for.
    pub test_mode: bool,
    /// Succeeded volume in the period.
    #[serde(default)]
    pub gross_usd: i64,
    /// What DeloPay charged the merchant for these attempts.
    #[serde(default)]
    pub platform_fee_usd: i64,
    /// What the merchant charged its shop owners (hosting fees). Zero for a
    /// merchant that hosts nobody.
    #[serde(default)]
    pub merchant_fee_usd: i64,
    /// Payment fees plus the known refund and dispute fees, across every
    /// ownership.
    #[serde(default)]
    pub processor_cost_usd: i64,
    /// The host-borne part of the processor cost.
    #[serde(default)]
    pub host_processor_cost_usd: i64,
    /// The part of `processor_cost_usd` shop owners carried through
    /// pass-through.
    #[serde(default)]
    pub passed_through_cost_usd: i64,
    /// The revenue every cost is subtracted from — see
    /// [`revenue_basis`](Self::revenue_basis).
    #[serde(default)]
    pub revenue_usd: i64,
    /// Which revenue `revenue_usd` is.
    pub revenue_basis: RevenueBasis,
    /// The merchant's own sales. Present only when `revenue_basis` is
    /// `"merchant_sales"`.
    #[serde(default)]
    pub sales_revenue: Option<SalesRevenueTerm>,
    /// `platform_fee_usd + host_processor_cost_usd`.
    #[serde(default)]
    pub payment_cost_usd: i64,
    /// What the host charged its shops, with the evidence behind it.
    pub hosting_fee: HostingFeeTerm,
    /// The merchant's cost of goods.
    pub cost_of_goods: ProfitCostTerm,
    /// Partners' shares of the revenue.
    pub partner_shares: ProfitCostTerm,
    /// Costs booked to the period rather than to a payment.
    pub period_expenses: PeriodExpenseTerm,
    /// `cost_of_goods + partner_shares + period_expenses`.
    #[serde(default)]
    pub operating_cost_usd: i64,
    /// Total cost in the period.
    #[serde(default)]
    pub total_cost_usd: i64,
    /// What was left over. `None` when it cannot be established; never
    /// render that as zero.
    #[serde(default)]
    pub margin_usd: Option<i64>,
    /// How much weight `margin_usd` carries.
    pub margin_quality: MarginQuality,
    /// Attempts the rail charged for that carry no settlement line: cost that
    /// is definitely missing.
    #[serde(default)]
    pub unlined_captured_attempt_count: i64,
    /// Attempts whose outcome never resolved, mostly ordinary abandonment.
    /// Not to be added to `unlined_captured_attempt_count`.
    #[serde(default)]
    pub unlined_unresolved_attempt_count: i64,
    /// `true` exactly when both unlined counts are zero.
    #[serde(default)]
    pub coverage_complete: bool,
    /// What the totals rest on — see [`ProcessorCostBasis`].
    pub cost_basis: ProcessorCostBasis,
    /// Settlement lines in the period.
    #[serde(default)]
    pub line_count: i64,
    /// Lines carrying a cost figure of any kind.
    #[serde(default)]
    pub priced_line_count: i64,
    /// Lines whose cost the rail reported.
    #[serde(default)]
    pub reported_line_count: i64,
    /// Lines whose cost came from a configured rate.
    #[serde(default)]
    pub estimated_line_count: i64,
    /// Lines where the rail was asked and reports nothing.
    #[serde(default)]
    pub unavailable_line_count: i64,
    /// Lines that predate cost recording.
    #[serde(default)]
    pub unrecorded_line_count: i64,
    /// Some payment cost or refund or dispute fee report is missing, stale or
    /// partial.
    #[serde(default)]
    pub processor_cost_incomplete: bool,
    /// Some processor fee cannot be converted to USD.
    #[serde(default)]
    pub processor_cost_fx_incomplete: bool,
    /// Some revenue currency had no USD rate, so its bucket is not in gross.
    #[serde(default)]
    pub fx_incomplete: bool,
    /// Some platform-fee figure could not be resolved.
    #[serde(default)]
    pub platform_fee_incomplete: bool,
    /// Per-connector cost breakdown.
    #[serde(default)]
    pub breakdown: Vec<ProcessorCostBucket>,
    /// Payment fees per method. `None` on a server that predates it; that is
    /// not an empty period.
    #[serde(default)]
    pub method_breakdown: Option<Vec<ProcessorCostMethodBucket>>,
    /// Refund fees. `None` on a server that predates fee events; that does
    /// not mean no fees.
    #[serde(default)]
    pub refund_processor_cost: Option<ProcessorCostEventTerm>,
    /// Dispute fees, under the same rule as
    /// [`refund_processor_cost`](Self::refund_processor_cost).
    #[serde(default)]
    pub dispute_processor_cost: Option<ProcessorCostEventTerm>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One `(shop, connector, account, method, unit)` bucket of a period's rail
/// costs. The unit is part of the key, so nothing here adds figures in
/// different currencies.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorCostPeriodBucket {
    /// The shop these payments ran under.
    pub profile_id: String,
    /// The connector.
    #[serde(default)]
    pub connector: Option<String>,
    /// The connector account.
    #[serde(default)]
    pub merchant_connector_id: Option<String>,
    /// Payment method family.
    #[serde(default)]
    pub payment_method: Option<String>,
    /// Payment method sub-type.
    #[serde(default)]
    pub payment_method_type: Option<String>,
    /// The processor's own method identifier, where the method type cannot
    /// tell two vendors apart.
    #[serde(default)]
    pub connector_method_code: Option<String>,
    /// The unit the rail reported its fee in.
    #[serde(default)]
    pub cost_currency: Option<String>,
    /// Decimal places [`cost_amount`](Self::cost_amount) is expressed in.
    #[serde(default)]
    pub cost_exponent: Option<i32>,
    /// The rail's fee over the attempts that carried one. `None` means no
    /// attempt carried a figure, not zero. Never a period total: it covers
    /// `reported_count + estimated_count` of `attempt_count` attempts.
    #[serde(default)]
    pub cost_amount: Option<i64>,
    /// The transaction currency of [`gross_amount`](Self::gross_amount).
    #[serde(default)]
    pub gross_currency: Option<String>,
    /// Decimal places `gross_amount` is expressed in.
    #[serde(default)]
    pub gross_exponent: Option<i32>,
    /// What these attempts took from buyers.
    #[serde(default)]
    pub gross_amount: Option<i64>,
    /// Established captures in the bucket.
    #[serde(default)]
    pub attempt_count: i64,
    /// The rail said what it took.
    #[serde(default)]
    pub reported_count: i64,
    /// A configured cost schedule derived the figure: an estimate.
    #[serde(default)]
    pub estimated_count: i64,
    /// The rail has no answer.
    #[serde(default)]
    pub unavailable_count: i64,
    /// Nothing was ever written for the attempt: a gap in the recording, not
    /// the rail's answer.
    #[serde(default)]
    pub unwritten_count: i64,
    /// The stored source is a value this release cannot name.
    #[serde(default)]
    pub unreadable_count: i64,
    /// The fee as a percentage of the gross it was taken from. `None` unless
    /// every attempt is priced, gross is positive and the cost is in the same
    /// currency as the gross.
    #[serde(default)]
    pub effective_rate_pct: Option<f64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a period's payments cost at the rails, per shop, connector and
/// method.
///
/// There is no period total, and none may be derived: the buckets keep the
/// unit each rail reported in. The counts are totalled because a count has
/// no unit.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorCostPeriodResponse {
    /// Start of the period (ISO 8601, UTC).
    pub period_start: String,
    /// End of the period (ISO 8601, UTC).
    pub period_end: String,
    /// Which environment the figures are for.
    pub test_mode: bool,
    /// The shop the read was narrowed to. `None` spans every shop.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// When this was computed (ISO 8601). A rail reporting late changes a
    /// past period's figures.
    pub generated_at: String,
    /// Established captures in the period, across every bucket.
    #[serde(default)]
    pub attempt_count: i64,
    /// Attempts whose fee the rail reported.
    #[serde(default)]
    pub reported_count: i64,
    /// Attempts priced by a configured schedule.
    #[serde(default)]
    pub estimated_count: i64,
    /// Attempts the rail has no figure for.
    #[serde(default)]
    pub unavailable_count: i64,
    /// Attempts nothing was ever recorded for.
    #[serde(default)]
    pub unwritten_count: i64,
    /// Attempts whose stored source this release cannot name.
    #[serde(default)]
    pub unreadable_count: i64,
    /// The buckets, in a stable order.
    #[serde(default)]
    pub buckets: Vec<ProcessorCostPeriodBucket>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}