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
//! The `settlement` resource: hosted-shop settlement — monthly statements,
//! the live current-period rollup, per-line detail, fee configuration,
//! backfills, and the host's manual positions.
//!
//! This is the "who is owed what" layer for a merchant that hosts shops on
//! behalf of third-party owners. It is deliberately independent of the
//! prepaid platform-fee ledger: a settlement figure is what the *host* owes a
//! *shop owner*, not what DeloPay charged the host.
//!
//! # `test_mode` is in every read signature, not a default
//!
//! Test and live figures must never blend, so the environment is an argument
//! the caller has to answer rather than something with a convenient default.
//! `false` is transmitted, not dropped.
//!
//! ```no_run
//! # use delopay::Delopay;
//! # async fn run(client: Delopay) -> delopay::Result<()> {
//! let overview = client.settlement().overview(false).await?;
//! for shop in &overview.shops {
//! println!("{}: {} unpaid", shop.profile_id, shop.unpaid_net_usd);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Who can call what
//!
//! Reads need `ProfileSettlementRead`; shop-owner callers are pinned to their
//! own shop server-side, and a host can hide a shop's settlement from its
//! owner entirely. The host actions — [`generate_statement`], [`backfill`],
//! [`update_statement_payout`], [`set_shop_visibility`] and the adjustment
//! calls — need `MerchantSettlementWrite`.
//!
//! [`generate_statement`]: Settlement::generate_statement
//! [`backfill`]: Settlement::backfill
//! [`update_statement_payout`]: Settlement::update_statement_payout
//! [`set_shop_visibility`]: Settlement::set_shop_visibility
use std::sync::Arc;
use serde::Serialize;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::settlement::{
FeeStatementDetail, NativeSettlementFeeRefreshResponse, NativeSettlementPayout,
NativeSettlementPayoutListResponse, NativeSettlementPreview, NativeSettlementReport,
NativeSettlementReportListResponse, NativeSettlementTerms, ProcessorCostEventsResponse,
ProcessorCostPeriodResponse, SettlementAdvanceListResponse, SettlementBackfillResponse,
SettlementCostResponse, SettlementCurrentResponse, SettlementLineListResponse,
SettlementOverviewResponse, SettlementStatementListResponse, ShopFeeConfigResponse,
ShopVisibilityResponse, StatementAdjustment, StatementAdjustmentListResponse, StatementAdvance,
StatementPayoutListResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
/// The `settlement` resource, obtained via [`crate::Delopay::settlement`].
///
/// See the [module docs](self) for the `test_mode` rule and the permission
/// split between reads and host actions.
#[derive(Debug, Clone)]
pub struct Settlement {
inner: Arc<Inner>,
}
impl Settlement {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
/// Per-shop settlement rollup for the host merchant: unpaid totals and
/// the running current period, one row per shop.
///
/// `GET /settlement/overview`
pub async fn overview(&self, test_mode: bool) -> Result<SettlementOverviewResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/overview",
None,
&[("test_mode", test_mode.to_string())],
None,
)
.await
}
/// Live rollup of the current (not yet statemented) period.
///
/// `profile_id` narrows to one shop; shop-owner callers are pinned to
/// their own regardless.
///
/// `GET /settlement/current`
pub async fn current(
&self,
test_mode: bool,
profile_id: Option<&str>,
) -> Result<SettlementCurrentResponse> {
let mut query = vec![("test_mode", test_mode.to_string())];
if let Some(profile_id) = profile_id {
query.push(("profile_id", profile_id.to_string()));
}
self.inner
.request(HttpMethod::Get, "/settlement/current", None, &query, None)
.await
}
/// List generated settlement statements, newest first.
///
/// `GET /settlement/statements`
pub async fn list_statements(
&self,
params: &StatementListParams,
) -> Result<SettlementStatementListResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/statements",
None,
¶ms.to_query(),
None,
)
.await
}
/// One statement with its per-connector/currency breakdown.
///
/// `GET /settlement/statements/{statement_id}`
pub async fn retrieve_statement(&self, statement_id: &str) -> Result<FeeStatementDetail> {
let path = statement_path(statement_id);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
/// Generate — or regenerate — the statement for one shop and calendar
/// month.
///
/// Regeneration only rewrites the figures while the statement is
/// `unpaid`; once it is `partial` or `paid` the money has moved and the
/// numbers are frozen.
///
/// `POST /settlement/statements/generate`
pub async fn generate_statement(
&self,
params: &StatementGenerateRequest,
) -> Result<FeeStatementDetail> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/settlement/statements/generate",
Some(&body),
&[],
None,
)
.await
}
/// Record payout progress on a statement.
///
/// `POST /settlement/statements/{statement_id}/payout`
pub async fn update_statement_payout(
&self,
statement_id: &str,
params: &StatementPayoutUpdateRequest,
) -> Result<FeeStatementDetail> {
let path = format!("{}/payout", statement_path(statement_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
/// Export a statement as a PDF, returned as raw bytes.
///
/// Same auth, retries and error handling as every JSON call — write the
/// bytes to a file or hand them to whatever serves them.
///
/// The document deliberately carries **no platform fee for any viewer**:
/// a host forwards this to a shop owner as their invoice, and a figure
/// that is only safe for one of them cannot live on a page that gets
/// forwarded.
///
/// `GET /settlement/statements/{statement_id}/pdf`
///
/// ```no_run
/// # use delopay::{Delopay, StatementPdfParams};
/// # async fn run(client: Delopay) -> delopay::Result<()> {
/// let pdf = client
/// .settlement()
/// .download_statement_pdf("stmt_1", &StatementPdfParams::new().currency("EUR"))
/// .await?;
/// std::fs::write("statement.pdf", pdf).unwrap();
/// # Ok(())
/// # }
/// ```
pub async fn download_statement_pdf(
&self,
statement_id: &str,
params: &StatementPdfParams,
) -> Result<Vec<u8>> {
let path = format!("{}/pdf", statement_path(statement_id));
self.inner
.request_bytes(
HttpMethod::Get,
&path,
¶ms.to_query(),
"application/pdf",
)
.await
}
/// Record a transfer already made against a statement.
///
/// `POST /settlement/statements/{statement_id}/payout`
///
/// **This records a transfer; it never sends money.** Each call is its own
/// attributed, server-timestamped entry, and those entries are what a
/// payout limit's windows count.
///
/// Carry an
/// [`idempotency_key`](StatementPayoutRecordRequest::idempotency_key): the
/// key makes the write safe to retry, and the SDK retries a keyed write on
/// a network error or a `5xx`. Without one, neither is retried — a lost
/// response leaves the caller to check
/// [`list_statement_payouts`](Self::list_statement_payouts) before sending
/// again.
///
/// A `429` is the one exception, and it holds with or without a key: a
/// rate-limited request never reached the handler, so replaying it cannot
/// record a second transfer.
pub async fn record_statement_payout(
&self,
statement_id: &str,
params: &StatementPayoutRecordRequest,
) -> Result<FeeStatementDetail> {
let key = validated_body_key(params.idempotency_key.as_deref())?;
let path = format!("{}/payout", statement_path(statement_id));
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Post, &path, Some(&body), key)
.await
}
/// Every transfer recorded against one statement, with what they add up to
/// and any overpayment.
///
/// `GET /settlement/statements/{statement_id}/payouts`
pub async fn list_statement_payouts(
&self,
statement_id: &str,
) -> Result<StatementPayoutListResponse> {
let path = format!("{}/payouts", statement_path(statement_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
/// Record a transfer against a shop's month **before** that month's
/// statement exists.
///
/// `POST /settlement/advances`
///
/// Records a transfer; it never sends money. The advance attaches to the
/// statement once it is generated. A keyed write is retried on a network
/// error or a `5xx`; an unkeyed one is not — except on a `429`, which never
/// reached the handler and so cannot have recorded anything.
pub async fn record_advance(
&self,
params: &StatementAdvanceRecordRequest,
) -> Result<StatementAdvance> {
let key = validated_body_key(params.idempotency_key.as_deref())?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Post, "/settlement/advances", Some(&body), key)
.await
}
/// The advances recorded against one shop-month.
///
/// `GET /settlement/advances`
pub async fn list_advances(
&self,
profile_id: Option<&str>,
year: i32,
month: u32,
test_mode: bool,
) -> Result<SettlementAdvanceListResponse> {
let mut query = vec![
("year", year.to_string()),
("month", month.to_string()),
("test_mode", test_mode.to_string()),
];
if let Some(profile_id) = profile_id {
query.push(("profile_id", profile_id.to_string()));
}
self.inner
.request(HttpMethod::Get, "/settlement/advances", None, &query, None)
.await
}
/// Refund and dispute cost evidence: what the rail charged, and where the
/// figure came from.
///
/// `GET /settlement/processor-cost-events`
///
/// A source whose `cost_source` is `"unavailable"` or `"unrecorded"` is an
/// absence, not a zero fee. `force_sync` re-asks the provider for one
/// payment's evidence and is only accepted together with a `payment_id`.
pub async fn list_processor_cost_events(
&self,
params: &ProcessorCostEventsParams,
) -> Result<ProcessorCostEventsResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/processor-cost-events",
None,
¶ms.to_query(),
None,
)
.await
}
/// What a period's payments cost, and what was left over: gross, the
/// platform fee, hosting fees, what the rails took, the merchant's own
/// costs, and the margin, with per-connector and per-method breakdowns.
///
/// `GET /settlement/cost`
///
/// For the merchant account holder only: a shop-scoped caller is refused
/// with `403` rather than given a redacted answer, so gate the surface on
/// the caller's scope. [`margin_usd`](SettlementCostResponse::margin_usd)
/// is absent, not zero, whenever
/// [`margin_quality`](SettlementCostResponse::margin_quality) is
/// `"unknown"`.
pub async fn cost(&self, params: &SettlementCostParams) -> Result<SettlementCostResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/cost",
None,
¶ms.to_query(),
None,
)
.await
}
/// What a period's payments cost at the rails, grouped by shop,
/// connector and payment method. Answers for every merchant, including
/// one that hosts nobody.
///
/// `GET /settlement/processor-cost`
///
/// The answer carries no period total, and none should be computed from
/// it: each bucket keeps the unit its rail reported in. A shop-scoped
/// token, a role narrowed to selected connector accounts, or a role
/// without settlement read is refused with `403`.
pub async fn processor_cost(
&self,
params: &SettlementCostParams,
) -> Result<ProcessorCostPeriodResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/processor-cost",
None,
¶ms.to_query(),
None,
)
.await
}
/// Calculate a period in its **transaction currency**, without saving
/// anything.
///
/// `POST /settlement/native/preview`
///
/// Rates apply once to the period total, not per transaction. Unknown or
/// estimated fees keep every dependent amount provisional — read
/// [`quality`](NativeSettlementPreview::quality) before treating a figure
/// as payable. Native amounts stay integer strings so large values keep
/// every digit.
///
/// Needs a host-level dashboard JWT with settlement read — authenticate the
/// client with [`Delopay::with_jwt`](crate::Delopay::with_jwt). A
/// shop-scoped user, or a role restricted to selected connector accounts,
/// cannot read this aggregate at all.
pub async fn preview_native(
&self,
terms: &NativeSettlementTerms,
) -> Result<NativeSettlementPreview> {
let body = to_json_vec(terms)?;
self.inner
.request(
HttpMethod::Post,
"/settlement/native/preview",
Some(&body),
&[],
None,
)
.await
}
/// Recalculate the period and **freeze** it as an immutable report
/// version.
///
/// `POST /settlement/native/reports`
///
/// A report records a calculation and sends no money. Pass
/// `allow_provisional` to save a figure whose source fees are incomplete —
/// deliberately explicit, so a provisional report is never frozen by
/// accident. Re-send the **same** idempotency key when retrying the same
/// request; the SDK retries a keyed write on a transient failure.
pub async fn create_native_report(
&self,
params: &NativeSettlementReportCreateRequest,
) -> Result<NativeSettlementReport> {
let key = require_body_key(¶ms.idempotency_key)?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(
HttpMethod::Post,
"/settlement/native/reports",
Some(&body),
Some(key),
)
.await
}
/// One frozen report, with the rows and calculation it saved.
///
/// `GET /settlement/native/reports/{report_id}`
pub async fn retrieve_native_report(&self, report_id: &str) -> Result<NativeSettlementReport> {
let path = format!("/settlement/native/reports/{}", encode_segment(report_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
/// Report summaries for one shop and currency, without the per-transaction
/// rows each snapshot holds.
///
/// `GET /settlement/native/reports`
pub async fn list_native_reports(
&self,
params: &NativeSettlementListParams,
) -> Result<NativeSettlementReportListResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/native/reports",
None,
¶ms.to_query(),
None,
)
.await
}
/// Record a native-currency transfer already made.
///
/// `POST /settlement/native/payouts`
///
/// **This never sends money**: it records a transfer someone else made,
/// under settlement write permission and the caller's payout limits. Minor
/// units stay strings, and a negative record must name the same-scope entry
/// it reverses. These records belong to the native ledger, which is
/// separate from monthly USD statement payouts and advances.
pub async fn record_native_payout(
&self,
params: &NativeSettlementPayoutCreateRequest,
) -> Result<NativeSettlementPayout> {
let key = require_body_key(¶ms.idempotency_key)?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(
HttpMethod::Post,
"/settlement/native/payouts",
Some(&body),
Some(key),
)
.await
}
/// The native ledger's transfers for one shop and currency.
///
/// `GET /settlement/native/payouts`
pub async fn list_native_payouts(
&self,
params: &NativeSettlementListParams,
) -> Result<NativeSettlementPayoutListResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/native/payouts",
None,
¶ms.to_query(),
None,
)
.await
}
/// Refresh one bounded page of provider fee evidence for a calculation.
///
/// `POST /settlement/native/fees/refresh`
///
/// Follow [`next_offset`](NativeSettlementFeeRefreshResponse::next_offset)
/// while [`has_more`](NativeSettlementFeeRefreshResponse::has_more) is set:
/// one call refreshes a page, not the whole period.
pub async fn refresh_native_fees(
&self,
params: &NativeSettlementFeeRefreshRequest,
) -> Result<NativeSettlementFeeRefreshResponse> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/settlement/native/fees/refresh",
Some(&body),
&[],
None,
)
.await
}
/// One frozen report as a PDF.
///
/// `GET /settlement/native/reports/{report_id}/pdf`
pub async fn download_native_report_pdf(
&self,
report_id: &str,
include_transactions: Option<bool>,
) -> Result<Vec<u8>> {
let path = format!(
"/settlement/native/reports/{}/pdf",
encode_segment(report_id)
);
let query = match include_transactions {
Some(v) => vec![("include_transactions", v.to_string())],
None => Vec::new(),
};
self.inner
.request_bytes(HttpMethod::Get, &path, &query, "application/pdf")
.await
}
/// One frozen report's source rows and calculation as CSV.
///
/// `GET /settlement/native/reports/{report_id}/export`
pub async fn download_native_report_csv(&self, report_id: &str) -> Result<Vec<u8>> {
let path = format!(
"/settlement/native/reports/{}/export",
encode_segment(report_id)
);
self.inner
.request_bytes(HttpMethod::Get, &path, &[], "text/csv")
.await
}
/// One frozen report as shareable JSON.
///
/// `GET /settlement/native/reports/{report_id}/export`
///
/// The shareable form **omits host account-level costs**: the snapshot it
/// carries has no `account_fees`, because those are the host's own costs
/// and not the shop owner's business.
pub async fn export_native_report_json(
&self,
report_id: &str,
) -> Result<NativeSettlementReport> {
let path = format!(
"/settlement/native/reports/{}/export",
encode_segment(report_id)
);
self.inner
.request_with_headers(
HttpMethod::Get,
&path,
None,
&[],
None,
&[("accept", "application/json")],
)
.await
}
/// The individual settled attempts of one shop's calendar month.
///
/// `GET /settlement/lines`
pub async fn list_lines(
&self,
params: &SettlementLineListParams,
) -> Result<SettlementLineListResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/lines",
None,
¶ms.to_query(),
None,
)
.await
}
/// The fee schedules that currently apply to a shop.
///
/// These are today's schedules, not the ones a past statement was priced
/// with — statements keep their own pricing.
///
/// `GET /settlement/fee-config`
pub async fn fee_config(&self, profile_id: &str) -> Result<ShopFeeConfigResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/fee-config",
None,
&[("profile_id", profile_id.to_string())],
None,
)
.await
}
/// Enqueue a settlement-line backfill over historical attempts.
///
/// Attempts already covered by a line are skipped, so this is safe to run
/// again. Historical attempts are priced with the **currently
/// configured** schedules — the one place settlement prices the past with
/// today's rates — and attempts with no applicable schedule are skipped
/// rather than written at zero, so they stay re-priceable.
///
/// `POST /settlement/backfill`
pub async fn backfill(
&self,
params: &SettlementBackfillRequest,
) -> Result<SettlementBackfillResponse> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/settlement/backfill",
Some(&body),
&[],
None,
)
.await
}
/// Toggle whether a shop's owner can open their own settlement figures.
///
/// Read-side only: lines and statements keep accruing while a shop is
/// hidden, so re-enabling reveals the full history rather than a gap.
///
/// `POST /settlement/shops/visibility`
pub async fn set_shop_visibility(
&self,
profile_id: &str,
visible_to_shop: bool,
) -> Result<ShopVisibilityResponse> {
let body = to_json_vec(&ShopVisibilityUpdateRequest {
profile_id: profile_id.to_string(),
visible_to_shop,
})?;
self.inner
.request(
HttpMethod::Post,
"/settlement/shops/visibility",
Some(&body),
&[],
None,
)
.await
}
/// The manual positions the host recorded on a statement.
///
/// `GET /settlement/statements/{statement_id}/adjustments`
pub async fn list_statement_adjustments(
&self,
statement_id: &str,
) -> Result<StatementAdjustmentListResponse> {
let path = format!("{}/adjustments", statement_path(statement_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
/// Add a manual position to a statement.
///
/// **Positive `amount_usd` charges the shop owner** (their payout
/// shrinks); negative credits them. Only editable while the statement is
/// `unpaid`.
///
/// `POST /settlement/statements/{statement_id}/adjustments`
pub async fn create_statement_adjustment(
&self,
statement_id: &str,
params: &StatementAdjustmentCreateRequest,
) -> Result<StatementAdjustment> {
let path = format!("{}/adjustments", statement_path(statement_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
/// Remove a manual position from a statement.
///
/// `DELETE /settlement/statements/{statement_id}/adjustments/{adjustment_id}`
pub async fn delete_statement_adjustment(
&self,
statement_id: &str,
adjustment_id: &str,
) -> Result<()> {
let path = format!(
"{}/adjustments/{}",
statement_path(statement_id),
encode_segment(adjustment_id)
);
// Any success body, empty or JSON, is accepted and dropped.
self.inner
.request::<serde::de::IgnoredAny>(HttpMethod::Delete, &path, None, &[], None)
.await
.map(|_| ())
}
}
/// `/settlement/statements/{statement_id}`, percent-encoded.
fn statement_path(statement_id: &str) -> String {
format!("/settlement/statements/{}", encode_segment(statement_id))
}
/// Parameters for [`Settlement::list_statements`].
#[derive(Debug, Clone)]
pub struct StatementListParams {
/// Statement environment. Required, and transmitted even when `false`.
pub test_mode: bool,
/// Restrict to one shop. Enforced from the token for shop-owner callers.
pub profile_id: Option<String>,
/// Maximum statements to return.
pub limit: Option<i64>,
/// Statements to skip.
pub offset: Option<i64>,
}
impl StatementListParams {
/// List statements for one environment.
#[must_use]
pub fn new(test_mode: bool) -> Self {
Self {
test_mode,
profile_id: None,
limit: None,
offset: None,
}
}
/// Restrict to one shop.
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
/// Page size.
#[must_use]
pub fn limit(mut self, limit: i64) -> Self {
self.limit = Some(limit);
self
}
/// Page offset.
#[must_use]
pub fn offset(mut self, offset: i64) -> Self {
self.offset = Some(offset);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = vec![("test_mode", self.test_mode.to_string())];
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.clone()));
}
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
/// Parameters for [`Settlement::list_lines`].
#[derive(Debug, Clone)]
pub struct SettlementLineListParams {
/// The shop whose lines to list.
pub profile_id: String,
/// Calendar year (UTC).
pub year: i32,
/// Calendar month, 1–12 (UTC).
pub month: u32,
/// Line environment. Required, and transmitted even when `false`.
pub test_mode: bool,
/// Maximum lines to return.
pub limit: Option<i64>,
/// Lines to skip.
pub offset: Option<i64>,
}
impl SettlementLineListParams {
/// List one shop's lines for one calendar month and environment.
#[must_use]
pub fn new(profile_id: impl Into<String>, year: i32, month: u32, test_mode: bool) -> Self {
Self {
profile_id: profile_id.into(),
year,
month,
test_mode,
limit: None,
offset: None,
}
}
/// Page size.
#[must_use]
pub fn limit(mut self, limit: i64) -> Self {
self.limit = Some(limit);
self
}
/// Page offset.
#[must_use]
pub fn offset(mut self, offset: i64) -> Self {
self.offset = Some(offset);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = vec![
("profile_id", self.profile_id.clone()),
("year", self.year.to_string()),
("month", self.month.to_string()),
("test_mode", self.test_mode.to_string()),
];
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
/// Query parameters for [`Settlement::download_statement_pdf`].
#[derive(Debug, Clone, Default)]
pub struct StatementPdfParams {
/// ISO currency the PDF totals are converted to. Defaults to USD.
pub currency: Option<String>,
/// Append a per-transaction table. Off by default.
pub include_transactions: Option<bool>,
}
impl StatementPdfParams {
/// The default PDF: USD totals, no transaction appendix.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Convert the totals to this currency.
#[must_use]
pub fn currency(mut self, currency: impl Into<String>) -> Self {
self.currency = Some(currency.into());
self
}
/// Append the per-transaction table.
#[must_use]
pub fn include_transactions(mut self, include_transactions: bool) -> Self {
self.include_transactions = Some(include_transactions);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = &self.currency {
q.push(("currency", v.clone()));
}
if let Some(v) = self.include_transactions {
q.push(("include_transactions", v.to_string()));
}
q
}
}
/// Body for [`Settlement::generate_statement`].
#[derive(Debug, Clone, Serialize)]
pub struct StatementGenerateRequest {
/// The shop to generate for.
pub profile_id: String,
/// Calendar year (UTC).
pub year: i32,
/// Calendar month, 1–12 (UTC).
pub month: u32,
/// Statement environment. Always sent.
pub test_mode: bool,
}
impl StatementGenerateRequest {
/// Generate one shop's statement for one calendar month and environment.
#[must_use]
pub fn new(profile_id: impl Into<String>, year: i32, month: u32, test_mode: bool) -> Self {
Self {
profile_id: profile_id.into(),
year,
month,
test_mode,
}
}
}
/// Body for [`Settlement::update_statement_payout`].
#[derive(Debug, Clone, Serialize)]
pub struct StatementPayoutUpdateRequest {
/// `"unpaid"`, `"partial"` or `"paid"`.
pub payout_status: String,
/// Handed over so far, USD minor units — what makes `partial` a real
/// figure. Omitted, it defaults to the full net for `paid` and zero for
/// `unpaid`.
#[serde(skip_serializing_if = "Option::is_none")]
pub paid_amount_usd: Option<i64>,
/// ISO 8601 payout timestamp. Defaults to now (UTC) when marking `paid`.
#[serde(skip_serializing_if = "Option::is_none")]
pub paid_at: Option<String>,
/// Free-form note recorded with the payout.
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
impl StatementPayoutUpdateRequest {
/// Set the payout status, leaving the amount to the server default.
#[must_use]
pub fn new(payout_status: impl Into<String>) -> Self {
Self {
payout_status: payout_status.into(),
paid_amount_usd: None,
paid_at: None,
note: None,
}
}
/// Record how much has actually been handed over, USD minor units.
#[must_use]
pub fn paid_amount_usd(mut self, paid_amount_usd: i64) -> Self {
self.paid_amount_usd = Some(paid_amount_usd);
self
}
/// Record when the payout happened (ISO 8601).
#[must_use]
pub fn paid_at(mut self, paid_at: impl Into<String>) -> Self {
self.paid_at = Some(paid_at.into());
self
}
/// Attach a note.
#[must_use]
pub fn note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
}
/// Body for [`Settlement::backfill`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct SettlementBackfillRequest {
/// Restrict to one shop. Omitted, every shop of the merchant is covered.
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
/// ISO 8601 inclusive start (UTC). Omitted, from the beginning.
#[serde(skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
/// ISO 8601 exclusive end (UTC). Omitted, up to now.
#[serde(skip_serializing_if = "Option::is_none")]
pub to: Option<String>,
}
impl SettlementBackfillRequest {
/// Backfill every shop, over all time.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Restrict to one shop.
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
/// Inclusive start of the range (ISO 8601, UTC).
#[must_use]
pub fn from(mut self, from: impl Into<String>) -> Self {
self.from = Some(from.into());
self
}
/// Exclusive end of the range (ISO 8601, UTC).
#[must_use]
pub fn to(mut self, to: impl Into<String>) -> Self {
self.to = Some(to.into());
self
}
}
/// Body of [`Settlement::set_shop_visibility`].
#[derive(Debug, Clone, Serialize)]
struct ShopVisibilityUpdateRequest {
profile_id: String,
visible_to_shop: bool,
}
/// Body for [`Settlement::create_statement_adjustment`].
#[derive(Debug, Clone, Serialize)]
pub struct StatementAdjustmentCreateRequest {
/// Host-authored label, e.g. `"Setup fee"`.
pub label: String,
/// Signed USD minor units. **Positive charges the shop owner**; negative
/// credits them.
pub amount_usd: i64,
}
impl StatementAdjustmentCreateRequest {
/// A position that **charges** the shop owner `amount_usd` USD minor
/// units, reducing their payout.
///
/// The magnitude is taken, so the sign of the argument cannot flip the
/// direction of the money. `saturating_abs` rather than `abs` because
/// `i64::MIN.abs()` overflows — the same reason [`crate::Money`] reaches
/// for `unsigned_abs`.
#[must_use]
pub fn charge(label: impl Into<String>, amount_usd: i64) -> Self {
Self {
label: label.into(),
amount_usd: amount_usd.saturating_abs(),
}
}
/// A position that **credits** the shop owner `amount_usd` USD minor
/// units, increasing their payout.
///
/// Takes the magnitude and negates it, so a caller cannot accidentally
/// bill someone by passing a positive number to the credit constructor.
#[must_use]
pub fn credit(label: impl Into<String>, amount_usd: i64) -> Self {
Self {
label: label.into(),
amount_usd: -amount_usd.saturating_abs(),
}
}
}
/// The body key to send as the header too, or `None` when the body carries
/// none.
///
/// A blank key is rejected rather than sent: an empty `Idempotency-Key` header
/// deduplicates nothing and would still mark the write replayable.
fn validated_body_key(key: Option<&str>) -> Result<Option<&str>> {
match key {
Some(key) if key.trim().is_empty() => Err(DelopayError::InvalidRequest(
"`idempotency_key` must not be blank; omit it instead".to_string(),
)),
other => Ok(other),
}
}
/// The same check where the API requires a key.
fn require_body_key(key: &str) -> Result<&str> {
if key.trim().is_empty() {
return Err(DelopayError::InvalidRequest(
"`idempotency_key` is required and must not be blank".to_string(),
));
}
Ok(key)
}
/// Body of [`Settlement::record_statement_payout`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct StatementPayoutRecordRequest {
/// What was transferred, USD minor units.
#[serde(skip_serializing_if = "Option::is_none")]
pub amount_usd: Option<i64>,
/// The amount as it left the bank, in its own currency, when that was not
/// USD.
#[serde(skip_serializing_if = "Option::is_none")]
pub original_amount: Option<i64>,
/// The currency of [`original_amount`](Self::original_amount).
#[serde(skip_serializing_if = "Option::is_none")]
pub original_currency: Option<String>,
/// The value date the transfer carries. A backdated entry keeps its own
/// date; the window a limit counts it in is the server's own timestamp.
#[serde(skip_serializing_if = "Option::is_none")]
pub value_date: Option<String>,
/// How it was sent.
#[serde(skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
/// The bank's or operator's own reference.
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
/// A free-form note to record with it.
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
/// The caller's own key for this write. It travels in the body **and** as
/// the `Idempotency-Key` header, so the two cannot disagree, and it is what
/// makes the write safe to retry.
#[serde(skip_serializing_if = "Option::is_none")]
pub idempotency_key: Option<String>,
}
impl StatementPayoutRecordRequest {
/// Record `amount_usd` (USD minor units) against the statement.
pub fn new(amount_usd: i64) -> Self {
Self {
amount_usd: Some(amount_usd),
..Self::default()
}
}
/// The amount and currency as it actually left the bank.
#[must_use]
pub fn original(mut self, amount: i64, currency: impl Into<String>) -> Self {
self.original_amount = Some(amount);
self.original_currency = Some(currency.into());
self
}
/// The value date the transfer carries.
#[must_use]
pub fn value_date(mut self, value_date: impl Into<String>) -> Self {
self.value_date = Some(value_date.into());
self
}
/// How it was sent.
#[must_use]
pub fn method(mut self, method: impl Into<String>) -> Self {
self.method = Some(method.into());
self
}
/// The bank's or operator's own reference.
#[must_use]
pub fn reference(mut self, reference: impl Into<String>) -> Self {
self.reference = Some(reference.into());
self
}
/// A free-form note.
#[must_use]
pub fn note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
/// The key that makes this write retriable and deduplicated.
#[must_use]
pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
self.idempotency_key = Some(key.into());
self
}
}
/// Body of [`Settlement::record_advance`].
#[derive(Debug, Clone, Serialize)]
pub struct StatementAdvanceRecordRequest {
/// The shop the transfer was made to.
pub profile_id: String,
/// Calendar year of the month it is against.
pub year: i32,
/// Calendar month, 1-12.
pub month: u32,
/// What was transferred, USD minor units.
pub amount_usd: i64,
/// Which environment it belongs to.
#[serde(skip_serializing_if = "Option::is_none")]
pub test_mode: Option<bool>,
/// The amount as it left the bank, in its own currency.
#[serde(skip_serializing_if = "Option::is_none")]
pub original_amount: Option<i64>,
/// The currency of [`original_amount`](Self::original_amount).
#[serde(skip_serializing_if = "Option::is_none")]
pub original_currency: Option<String>,
/// The value date the transfer carries.
#[serde(skip_serializing_if = "Option::is_none")]
pub value_date: Option<String>,
/// How it was sent.
#[serde(skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
/// The bank's or operator's own reference.
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
/// A free-form note to record with it.
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
/// The caller's own key for this write — see
/// [`StatementPayoutRecordRequest::idempotency_key`].
#[serde(skip_serializing_if = "Option::is_none")]
pub idempotency_key: Option<String>,
}
impl StatementAdvanceRecordRequest {
/// Record `amount_usd` (USD minor units) against one shop-month.
pub fn new(profile_id: impl Into<String>, year: i32, month: u32, amount_usd: i64) -> Self {
Self {
profile_id: profile_id.into(),
year,
month,
amount_usd,
test_mode: None,
original_amount: None,
original_currency: None,
value_date: None,
method: None,
reference: None,
note: None,
idempotency_key: None,
}
}
/// Which environment the advance belongs to.
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
/// The amount and currency as it actually left the bank.
#[must_use]
pub fn original(mut self, amount: i64, currency: impl Into<String>) -> Self {
self.original_amount = Some(amount);
self.original_currency = Some(currency.into());
self
}
/// The value date the transfer carries.
#[must_use]
pub fn value_date(mut self, value_date: impl Into<String>) -> Self {
self.value_date = Some(value_date.into());
self
}
/// How it was sent.
#[must_use]
pub fn method(mut self, method: impl Into<String>) -> Self {
self.method = Some(method.into());
self
}
/// The bank's or operator's own reference.
#[must_use]
pub fn reference(mut self, reference: impl Into<String>) -> Self {
self.reference = Some(reference.into());
self
}
/// A free-form note.
#[must_use]
pub fn note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
/// The key that makes this write retriable and deduplicated.
#[must_use]
pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
self.idempotency_key = Some(key.into());
self
}
}
/// Query parameters for [`Settlement::list_processor_cost_events`].
#[derive(Debug, Clone, Default)]
pub struct ProcessorCostEventsParams {
/// Narrow to one shop.
pub profile_id: Option<String>,
/// Narrow to one payment. Required before
/// [`force_sync`](Self::force_sync) is accepted.
pub payment_id: Option<String>,
/// Re-ask the provider for that payment's evidence. Only valid with a
/// `payment_id`.
pub force_sync: Option<bool>,
/// Calendar year of the period.
pub year: Option<i32>,
/// Calendar month of the period, 1-12.
pub month: Option<u32>,
/// Which environment to read.
pub test_mode: Option<bool>,
/// Page size.
pub limit: Option<i64>,
/// Rows to skip.
pub offset: Option<i64>,
}
impl ProcessorCostEventsParams {
/// Empty parameters.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Read one calendar month.
#[must_use]
pub fn period(mut self, year: i32, month: u32) -> Self {
self.year = Some(year);
self.month = Some(month);
self
}
/// Narrow to one shop.
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
/// Narrow to one payment, and optionally re-ask the provider for its
/// evidence.
#[must_use]
pub fn payment(mut self, payment_id: impl Into<String>, force_sync: bool) -> Self {
self.payment_id = Some(payment_id.into());
self.force_sync = Some(force_sync);
self
}
/// Which environment to read.
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
/// Page the results.
#[must_use]
pub fn page(mut self, limit: i64, offset: i64) -> Self {
self.limit = Some(limit);
self.offset = Some(offset);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.clone()));
}
if let Some(v) = &self.payment_id {
q.push(("payment_id", v.clone()));
}
if let Some(v) = self.force_sync {
q.push(("force_sync", v.to_string()));
}
if let Some(v) = self.year {
q.push(("year", v.to_string()));
}
if let Some(v) = self.month {
q.push(("month", v.to_string()));
}
if let Some(v) = self.test_mode {
q.push(("test_mode", v.to_string()));
}
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
/// Query parameters for [`Settlement::cost`] and
/// [`Settlement::processor_cost`].
///
/// The period is one UTC calendar month set with [`period`](Self::period),
/// or the running month when it is not set. `year` and `month` go together:
/// half a period is refused by the server, so the builder sets both at once.
#[derive(Debug, Clone, Default)]
pub struct SettlementCostParams {
/// Which environment to read. Always sent, `false` included.
pub test_mode: bool,
/// Narrow to one shop. Omitted spans every shop of the merchant.
pub profile_id: Option<String>,
/// UTC calendar year of the period.
pub year: Option<i32>,
/// UTC calendar month of the period, 1-12.
pub month: Option<u32>,
}
impl SettlementCostParams {
/// The running month so far, in one environment, across every shop.
pub fn new(test_mode: bool) -> Self {
Self {
test_mode,
..Default::default()
}
}
/// Read one UTC calendar month instead of the running one.
#[must_use]
pub fn period(mut self, year: i32, month: u32) -> Self {
self.year = Some(year);
self.month = Some(month);
self
}
/// Narrow to one shop.
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.clone()));
}
q.push(("test_mode", self.test_mode.to_string()));
if let Some(v) = self.year {
q.push(("year", v.to_string()));
}
if let Some(v) = self.month {
q.push(("month", v.to_string()));
}
q
}
}
/// Body of [`Settlement::create_native_report`].
#[derive(Debug, Clone, Serialize)]
pub struct NativeSettlementReportCreateRequest {
/// The terms to recalculate and freeze.
pub calculation: NativeSettlementTerms,
/// The caller's own key for this write. Re-send the same one when retrying
/// the same request.
pub idempotency_key: String,
/// Allow freezing a report whose source fees are incomplete. Explicit on
/// purpose: a provisional report must be asked for, never arrived at.
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_provisional: Option<bool>,
}
impl NativeSettlementReportCreateRequest {
/// Freeze `calculation` under `idempotency_key`.
pub fn new(calculation: NativeSettlementTerms, idempotency_key: impl Into<String>) -> Self {
Self {
calculation,
idempotency_key: idempotency_key.into(),
allow_provisional: None,
}
}
/// Allow the report to be frozen while source fees are incomplete.
#[must_use]
pub fn allow_provisional(mut self, allow: bool) -> Self {
self.allow_provisional = Some(allow);
self
}
}
/// Body of [`Settlement::record_native_payout`].
#[derive(Debug, Clone, Serialize)]
pub struct NativeSettlementPayoutCreateRequest {
/// The shop the transfer was made to.
pub profile_id: String,
/// The currency it was made in.
pub currency: String,
/// Which environment it belongs to.
pub test_mode: bool,
/// The amount, minor units as a decimal string. Negative for a reversal,
/// which must also name [`reversal_of`](Self::reversal_of).
pub amount_minor: String,
/// The value date the transfer carries.
pub value_date: String,
/// How it was sent.
#[serde(skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
/// The bank's or operator's own reference.
#[serde(skip_serializing_if = "Option::is_none")]
pub reference: Option<String>,
/// A free-form note to record with it.
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
/// The entry this one reverses. Required for a negative amount, and it
/// must be in the same shop, currency and environment.
#[serde(skip_serializing_if = "Option::is_none")]
pub reversal_of: Option<String>,
/// The caller's own key for this write.
pub idempotency_key: String,
}
impl NativeSettlementPayoutCreateRequest {
/// Record a transfer of `amount_minor` (minor units, as a string) in
/// `currency`, valued on `value_date`.
pub fn new(
profile_id: impl Into<String>,
currency: impl Into<String>,
test_mode: bool,
amount_minor: impl Into<String>,
value_date: impl Into<String>,
idempotency_key: impl Into<String>,
) -> Self {
Self {
profile_id: profile_id.into(),
currency: currency.into(),
test_mode,
amount_minor: amount_minor.into(),
value_date: value_date.into(),
method: None,
reference: None,
note: None,
reversal_of: None,
idempotency_key: idempotency_key.into(),
}
}
/// How it was sent.
#[must_use]
pub fn method(mut self, method: impl Into<String>) -> Self {
self.method = Some(method.into());
self
}
/// The bank's or operator's own reference.
#[must_use]
pub fn reference(mut self, reference: impl Into<String>) -> Self {
self.reference = Some(reference.into());
self
}
/// A free-form note.
#[must_use]
pub fn note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
/// The entry this one reverses.
#[must_use]
pub fn reversal_of(mut self, payout_id: impl Into<String>) -> Self {
self.reversal_of = Some(payout_id.into());
self
}
}
/// Body of [`Settlement::refresh_native_fees`].
#[derive(Debug, Clone, Serialize)]
pub struct NativeSettlementFeeRefreshRequest {
/// The calculation whose evidence to refresh.
pub calculation: NativeSettlementTerms,
/// How many sources to refresh in this call.
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<i64>,
/// Where to resume — the previous response's `next_offset`.
#[serde(skip_serializing_if = "Option::is_none")]
pub offset: Option<i64>,
}
impl NativeSettlementFeeRefreshRequest {
/// Refresh evidence for `calculation`, from the start.
pub fn new(calculation: NativeSettlementTerms) -> Self {
Self {
calculation,
limit: None,
offset: None,
}
}
/// Bound the page and resume from an offset.
#[must_use]
pub fn page(mut self, limit: i64, offset: i64) -> Self {
self.limit = Some(limit);
self.offset = Some(offset);
self
}
}
/// Query parameters for the native report and payout listings.
#[derive(Debug, Clone)]
pub struct NativeSettlementListParams {
/// The shop to list for.
pub profile_id: String,
/// The currency to list for.
pub currency: String,
/// Which environment to list.
pub test_mode: bool,
/// Page size.
pub limit: Option<i64>,
/// Rows to skip.
pub offset: Option<i64>,
}
impl NativeSettlementListParams {
/// List one shop's entries in one currency and environment.
pub fn new(
profile_id: impl Into<String>,
currency: impl Into<String>,
test_mode: bool,
) -> Self {
Self {
profile_id: profile_id.into(),
currency: currency.into(),
test_mode,
limit: None,
offset: None,
}
}
/// Page the results.
#[must_use]
pub fn page(mut self, limit: i64, offset: i64) -> Self {
self.limit = Some(limit);
self.offset = Some(offset);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = vec![
("profile_id", self.profile_id.clone()),
("currency", self.currency.clone()),
("test_mode", self.test_mode.to_string()),
];
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
const STATEMENT_JSON: &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,
"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",
"paid_amount_usd": 0,
"generated_at": "2026-08-01T00:20:00Z",
"adjustments_usd": 0,
"net_after_adjustments_usd": 85000,
"breakdown": []
}"#;
#[tokio::test]
async fn overview_transmits_a_false_test_mode() {
let (client, mock) = client_with(vec![Step::ok(r#"{"shops":[]}"#)]);
client.settlement().overview(false).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
// Dropping `test_mode=false` as "falsy" would silently return the
// wrong environment's money. Pin the literal.
assert_eq!(
seen[0].url,
"https://api.test/settlement/overview?test_mode=false"
);
}
#[tokio::test]
async fn current_omits_an_absent_profile_but_keeps_test_mode() {
let (client, mock) = client_with(vec![
Step::ok(
r#"{"period_start":"2026-08-01T00:00:00Z","period_end":"2026-09-01T00:00:00Z",
"test_mode":true,"breakdown":[]}"#,
),
Step::ok(
r#"{"period_start":"2026-08-01T00:00:00Z","period_end":"2026-09-01T00:00:00Z",
"test_mode":true,"breakdown":[]}"#,
),
]);
client.settlement().current(true, None).await.unwrap();
client
.settlement()
.current(true, Some("pro/1"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/current?test_mode=true"
);
assert_eq!(
seen[1].url,
"https://api.test/settlement/current?test_mode=true&profile_id=pro/1"
);
}
#[tokio::test]
async fn list_statements_sends_every_set_filter() {
let (client, mock) = client_with(vec![Step::ok(r#"{"statements":[],"total_count":0}"#)]);
let params = StatementListParams::new(false)
.profile_id("pro_1")
.limit(20)
.offset(40);
client.settlement().list_statements(¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements?test_mode=false&profile_id=pro_1&limit=20&offset=40"
);
}
#[tokio::test]
async fn retrieve_statement_encodes_the_id_and_decodes_the_breakdown() {
let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
let detail = client
.settlement()
.retrieve_statement("stmt/1")
.await
.unwrap();
assert_eq!(detail.summary.id, "stmt_1");
assert_eq!(detail.summary.net_after_adjustments_usd, 85000);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/stmt%2F1"
);
}
#[tokio::test]
async fn generate_statement_posts_the_period() {
let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
let params = StatementGenerateRequest::new("pro_1", 2026, 7, false);
client
.settlement()
.generate_statement(¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/generate"
);
let body = seen[0].body_json();
assert_eq!(body["profile_id"], "pro_1");
assert_eq!(body["year"], 2026);
assert_eq!(body["month"], 7);
// `test_mode` is not optional in the body either.
assert_eq!(body["test_mode"], false);
}
#[tokio::test]
async fn update_statement_payout_posts_only_the_set_fields() {
let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
let params = StatementPayoutUpdateRequest::new("partial").paid_amount_usd(40000);
client
.settlement()
.update_statement_payout("stmt_1", ¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/stmt_1/payout"
);
let body = seen[0].body_json();
assert_eq!(body["payout_status"], "partial");
assert_eq!(body["paid_amount_usd"], 40000);
// An unset note must not be sent as `null` — the server reads that as
// "clear the note".
assert!(body.get("note").is_none());
assert!(body.get("paid_at").is_none());
}
#[tokio::test]
async fn download_statement_pdf_returns_bytes_and_asks_for_pdf() {
let (client, mock) = client_with(vec![Step::ok("%PDF-1.4\nnot json at all")]);
let params = StatementPdfParams::new()
.currency("EUR")
.include_transactions(true);
let bytes = client
.settlement()
.download_statement_pdf("stmt_1", ¶ms)
.await
.unwrap();
// The body is returned verbatim: a JSON decode step would fail here.
assert!(bytes.starts_with(b"%PDF-1.4"));
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/stmt_1/pdf?currency=EUR&include_transactions=true"
);
assert_eq!(seen[0].header("accept"), Some("application/pdf"));
// Exactly one `accept`: the JSON default must have been replaced, not
// joined.
assert_eq!(
seen[0]
.headers
.iter()
.filter(|(name, _)| name.eq_ignore_ascii_case("accept"))
.count(),
1
);
}
#[tokio::test]
async fn list_lines_sends_the_full_period_key() {
let (client, mock) = client_with(vec![Step::ok(r#"{"lines":[],"total_count":0}"#)]);
let params = SettlementLineListParams::new("pro_1", 2026, 7, true).limit(50);
client.settlement().list_lines(¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/lines?profile_id=pro_1&year=2026&month=7&test_mode=true&limit=50"
);
}
#[tokio::test]
async fn fee_config_scopes_by_profile() {
let (client, mock) =
client_with(vec![Step::ok(r#"{"profile_id":"pro_1","schedules":[]}"#)]);
let out = client.settlement().fee_config("pro_1").await.unwrap();
assert_eq!(out.profile_id, "pro_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/fee-config?profile_id=pro_1"
);
}
#[tokio::test]
async fn backfill_posts_an_empty_body_when_unrestricted() {
let (client, mock) = client_with(vec![Step::ok(r#"{"enqueued":true,"job_id":"job_1"}"#)]);
let out = client
.settlement()
.backfill(&SettlementBackfillRequest::new())
.await
.unwrap();
assert!(out.enqueued);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/settlement/backfill");
// An unrestricted backfill sends `{}`, not `{"profile_id":null}` —
// a null there is a different request.
assert_eq!(seen[0].body_json(), serde_json::json!({}));
}
#[tokio::test]
async fn set_shop_visibility_posts_both_fields() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"profile_id":"pro_1","visible_to_shop":false}"#,
)]);
let out = client
.settlement()
.set_shop_visibility("pro_1", false)
.await
.unwrap();
assert!(!out.visible_to_shop);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/settlement/shops/visibility");
let body = seen[0].body_json();
assert_eq!(body["profile_id"], "pro_1");
assert_eq!(body["visible_to_shop"], false);
}
#[tokio::test]
async fn adjustments_round_trip_on_the_statement_sub_path() {
let (client, mock) = client_with(vec![
Step::ok(r#"{"adjustments":[]}"#),
Step::ok(
r#"{"id":"adj_1","label":"Setup fee","amount_usd":5000,
"created_at":"2026-08-02T00:00:00Z"}"#,
),
Step::ok(r#"{"id":"adj_1","deleted":true}"#),
]);
let settlement = client.settlement();
settlement
.list_statement_adjustments("stmt_1")
.await
.unwrap();
settlement
.create_statement_adjustment(
"stmt_1",
&StatementAdjustmentCreateRequest::charge("Setup fee", 5000),
)
.await
.unwrap();
settlement
.delete_statement_adjustment("stmt_1", "adj/1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/stmt_1/adjustments"
);
assert_eq!(seen[1].method, "POST");
assert_eq!(seen[2].method, "DELETE");
assert_eq!(
seen[2].url,
"https://api.test/settlement/statements/stmt_1/adjustments/adj%2F1"
);
}
#[test]
fn credit_is_negative_and_charge_is_positive_whatever_the_caller_passes() {
// The sign is the whole meaning of the field: a credit constructed
// with a positive magnitude must still bill nobody.
assert_eq!(
StatementAdjustmentCreateRequest::credit("Goodwill", 2500).amount_usd,
-2500
);
assert_eq!(
StatementAdjustmentCreateRequest::credit("Goodwill", -2500).amount_usd,
-2500
);
assert_eq!(
StatementAdjustmentCreateRequest::charge("Setup", 2500).amount_usd,
2500
);
assert_eq!(
StatementAdjustmentCreateRequest::charge("Setup", -2500).amount_usd,
2500
);
}
#[test]
fn the_adjustment_constructors_survive_i64_min() {
// `abs()` overflows here; `saturating_abs()` does not. Pathological
// input, but a panic in a money constructor is not a failure mode
// worth having.
assert_eq!(
StatementAdjustmentCreateRequest::charge("Setup", i64::MIN).amount_usd,
i64::MAX
);
assert_eq!(
StatementAdjustmentCreateRequest::credit("Goodwill", i64::MIN).amount_usd,
-i64::MAX
);
}
/// A delete answered with an empty body is as done as one answered with
/// JSON. Mutation: decode the body as `()` again — the JSON-body test
/// above fails with `Decode`.
#[tokio::test]
async fn delete_statement_adjustment_accepts_an_empty_body() {
let (client, mock) = client_with(vec![Step::ok("")]);
client
.settlement()
.delete_statement_adjustment("stmt_1", "adj_1")
.await
.unwrap();
assert_eq!(mock.seen.lock().unwrap()[0].method, "DELETE");
}
/// A body-keyed settlement write travels with the key in the body **and**
/// as the header that makes it retriable, and the two are the same value.
/// Mutation: pass `None` as the idempotency key — the header assertion
/// fails, and with it the write's retry eligibility.
#[tokio::test]
async fn a_keyed_native_payout_carries_its_key_in_both_places() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"id":"npo_1","profile_id":"pro_1","currency":"EUR","test_mode":false,"amount_minor":"125000","value_date":"2026-09-10"}"#,
)]);
let out = client
.settlement()
.record_native_payout(
&NativeSettlementPayoutCreateRequest::new(
"pro_1",
"EUR",
false,
"125000",
"2026-09-10",
"idem_1",
)
.reference("SEPA-99"),
)
.await
.unwrap();
// Minor units stay strings: a large native figure must keep every digit.
assert_eq!(out.amount_minor.as_deref(), Some("125000"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/settlement/native/payouts");
assert_eq!(seen[0].body_json()["idempotency_key"], "idem_1");
assert_eq!(seen[0].body_json()["reference"], "SEPA-99");
assert_eq!(seen[0].header("idempotency-key"), Some("idem_1"));
}
/// An omitted body key must suppress the client-wide default too: these
/// routes deduplicate on the key **in the body**, so a header key the body
/// does not carry would dedupe nothing while making the write replayable.
/// Mutation: route the write back through `Inner::request` — the header
/// assertion fails, because the client default is substituted.
#[tokio::test]
async fn an_unkeyed_statement_payout_sends_no_key_even_under_a_client_default() {
let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
client
.with_idempotency_key("client-wide-key")
.settlement()
.record_statement_payout("stmt_1", &StatementPayoutRecordRequest::new(25_000))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].header("idempotency-key"), None);
assert!(seen[0].body_json().get("idempotency_key").is_none());
}
/// A keyed write still carries the client default's place: the body key
/// wins and travels in both. Mutation: pass the client default through on
/// the keyed path — the header stops matching the body.
#[tokio::test]
async fn a_keyed_statement_payout_sends_its_own_key_in_both_places() {
let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
client
.with_idempotency_key("client-wide-key")
.settlement()
.record_statement_payout(
"stmt_1",
&StatementPayoutRecordRequest::new(25_000).idempotency_key("payout-7"),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].header("idempotency-key"), Some("payout-7"));
assert_eq!(seen[0].body_json()["idempotency_key"], "payout-7");
}
/// A blank key deduplicates nothing and would still mark the write
/// replayable, so it is refused before the request is built. Mutation: drop
/// the `validated_body_key` call — the write goes out and `is_err` fails.
#[tokio::test]
async fn a_blank_body_key_is_refused_before_sending() {
let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
let out = client
.settlement()
.record_statement_payout(
"stmt_1",
&StatementPayoutRecordRequest::new(25_000).idempotency_key(" "),
)
.await;
assert!(out.is_err());
assert!(mock.seen.lock().unwrap().is_empty(), "nothing was sent");
}
/// Retry eligibility follows the body key, not the client default. An
/// unkeyed write meeting a `5xx` is sent **once** and the error reaches the
/// caller; re-sending it is the caller's decision, because the server has
/// no key to deduplicate a second copy on. Mutation: let the client default
/// through — the request count becomes 2.
#[tokio::test]
async fn an_unkeyed_settlement_write_is_not_replayed_after_a_5xx() {
let (client, mock) = client_with_retries(
vec![
Step::status(500, r#"{"error":{"message":"boom"}}"#),
Step::ok(STATEMENT_JSON),
],
2,
);
let out = client
.with_idempotency_key("client-wide-key")
.settlement()
.record_statement_payout("stmt_1", &StatementPayoutRecordRequest::new(25_000))
.await;
assert!(out.is_err());
assert_eq!(mock.seen.lock().unwrap().len(), 1);
}
/// The `429` exception, preserved deliberately and stated here so the
/// no-replay guarantee above is not read wider than it is: a rate-limited
/// request never reached the handler, so replaying it cannot record a
/// second transfer — and the replay still carries no key, because the body
/// carries none. Mutation: gate the `429` retry on `is_idempotent` in
/// `send_raw_keyed` — the request count drops to 1.
#[tokio::test]
async fn an_unkeyed_settlement_write_is_still_replayed_after_a_429() {
let (client, mock) =
client_with_retries(vec![Step::status(429, ""), Step::ok(STATEMENT_JSON)], 2);
client
.with_idempotency_key("client-wide-key")
.settlement()
.record_statement_payout("stmt_1", &StatementPayoutRecordRequest::new(25_000))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 2);
assert_eq!(seen[1].header("idempotency-key"), None);
}
/// A keyed write is replayed, because the server deduplicates the second
/// copy on the key the body carries. Mutation: stop passing the body key
/// into the request — only one attempt is made and the call fails.
#[tokio::test]
async fn a_keyed_settlement_write_is_replayed_under_its_own_key() {
let (client, mock) = client_with_retries(
vec![
Step::status(500, r#"{"error":{"message":"boom"}}"#),
Step::ok(STATEMENT_JSON),
],
2,
);
client
.settlement()
.record_statement_payout(
"stmt_1",
&StatementPayoutRecordRequest::new(25_000).idempotency_key("payout-7"),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 2);
assert_eq!(seen[1].header("idempotency-key"), Some("payout-7"));
}
/// The native listings are scoped by shop, currency and environment, all
/// three on the query. Mutation: drop `test_mode` from `to_query` — test
/// and live figures would blend, and the URL assertion fails.
#[tokio::test]
async fn native_report_listing_scopes_by_shop_currency_and_environment() {
let (client, mock) = client_with(vec![Step::ok(r#"{"data":[],"has_more":false}"#)]);
client
.settlement()
.list_native_reports(
&NativeSettlementListParams::new("pro_1", "EUR", true).page(25, 50),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/native/reports?profile_id=pro_1¤cy=EUR&test_mode=true&limit=25&offset=50"
);
}
/// An advance is recorded against a shop-month before its statement
/// exists. Mutation: send `year`/`month` as query parameters instead of in
/// the body — the body assertions fail.
#[tokio::test]
async fn record_advance_posts_the_shop_month_in_the_body() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"id":"adv_1","profile_id":"pro_1","amount_usd":50000,"statement_id":null}"#,
)]);
let out = client
.settlement()
.record_advance(
&StatementAdvanceRecordRequest::new("pro_1", 2026, 9, 50_000)
.test_mode(false)
.idempotency_key("idem_2"),
)
.await
.unwrap();
// Not yet attached to a statement, which is the whole point of an advance.
assert_eq!(out.statement_id, None);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/settlement/advances");
assert_eq!(seen[0].body_json()["year"], 2026);
assert_eq!(seen[0].body_json()["month"], 9);
assert_eq!(seen[0].header("idempotency-key"), Some("idem_2"));
}
const SETTLEMENT_COST_TERM_JSON: &str = r#"{"bearer":"merchant","amount_usd":0,
"row_count":0,"unavailable_count":0,"excluded_count":0,"unclassified_count":0,
"incomplete":false,"fx_incomplete":false,"uncovered_captured_attempt_count":0,
"uncovered_unresolved_attempt_count":0}"#;
#[tokio::test]
async fn cost_gets_the_period_with_test_mode_always_sent() {
let body = format!(
r#"{{"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,"processor_cost_usd":2900,
"host_processor_cost_usd":2900,"passed_through_cost_usd":0,
"revenue_usd":15000,"revenue_basis":"hosting_fee","payment_cost_usd":3900,
"hosting_fee":{{"bearer":"merchant","amount_usd":15000,"line_count":12,
"fx_incomplete":false,"uncovered_captured_attempt_count":0,
"uncovered_unresolved_attempt_count":0}},
"cost_of_goods":{SETTLEMENT_COST_TERM_JSON},
"partner_shares":{SETTLEMENT_COST_TERM_JSON},
"period_expenses":{{"bearer":"merchant","amount_usd":0,"row_count":0,
"excluded_count":0,"incomplete":false,"fx_incomplete":false,
"allocation":"pro_rata_days"}},
"operating_cost_usd":0,"total_cost_usd":3900,"margin_quality":"unknown",
"unlined_captured_attempt_count":3,"unlined_unresolved_attempt_count":1,
"coverage_complete":false,"cost_basis":"mixed","line_count":12,
"priced_line_count":10,"reported_line_count":8,"estimated_line_count":2,
"unavailable_line_count":1,"unrecorded_line_count":1,
"processor_cost_incomplete":true,"processor_cost_fx_incomplete":false,
"fx_incomplete":false,"platform_fee_incomplete":false,
"breakdown":[{{"connector":"stripe","ownership":"host","cost_currency":"USD",
"cost_exponent":2,"cost_amount":2900,"cost_usd":2900,"line_count":12,
"reported_count":8,"estimated_count":2,"unavailable_count":1,
"unrecorded_count":1}}],
"method_breakdown":[],
"refund_processor_cost":{{"source_count":0,"reported_count":0,
"unavailable_count":0,"unrecorded_count":0,"incomplete":false,
"fx_incomplete":false,"host_incomplete":false,"host_fx_incomplete":false,
"breakdown":[]}},
"dispute_processor_cost":{{"amount_usd":-1500,"host_amount_usd":-1500,
"source_count":1,"reported_count":1,"unavailable_count":0,
"unrecorded_count":0,"incomplete":false,"fx_incomplete":false,
"host_incomplete":false,"host_fx_incomplete":false,"breakdown":[]}},
"surprise_field":1}}"#
);
let (client, mock) = client_with(vec![Step::ok(&body)]);
let params = SettlementCostParams::new(false)
.profile_id("pro_1")
.period(2026, 7);
let out = client.settlement().cost(¶ms).await.unwrap();
assert_eq!(out.margin_quality, "unknown");
// Absent, not zero: an unknown margin must not read as break-even.
assert!(out.margin_usd.is_none());
assert_eq!(out.hosting_fee.amount_usd, 15000);
assert_eq!(out.breakdown[0].cost_usd, Some(2900));
assert_eq!(out.period_expenses.allocation, "pro_rata_days");
assert!(out.refund_processor_cost.is_some());
// Signed: a dispute fee credit arrives negative, not clamped to zero.
let dispute = out.dispute_processor_cost.as_ref().unwrap();
assert_eq!(dispute.amount_usd, Some(-1500));
assert_eq!(dispute.source_count, 1);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/settlement/cost?profile_id=pro_1&test_mode=false&year=2026&month=7"
);
}
#[tokio::test]
async fn processor_cost_gets_the_running_month_without_a_period() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"period_start":"2026-07-01T00:00:00Z","period_end":"2026-08-01T00:00:00Z",
"test_mode":true,"profile_id":null,"generated_at":"2026-07-15T00:00:00Z",
"attempt_count":4,"reported_count":2,"estimated_count":1,
"unavailable_count":0,"unwritten_count":1,"unreadable_count":0,
"buckets":[{"profile_id":"pro_1","connector":"stripe","cost_currency":"USD",
"cost_exponent":2,"cost_amount":120,"gross_currency":"EUR",
"gross_exponent":2,"gross_amount":4000,"attempt_count":4,
"reported_count":2,"estimated_count":1,"unavailable_count":0,
"unwritten_count":1,"unreadable_count":0,"surprise_bucket":true}],
"surprise_field":1}"#,
)]);
let out = client
.settlement()
.processor_cost(&SettlementCostParams::new(true))
.await
.unwrap();
assert!(out.test_mode);
assert!(out.profile_id.is_none());
assert_eq!(out.unwritten_count, 1);
assert_eq!(out.buckets[0].cost_amount, Some(120));
// Different currencies on cost and gross: no rate is published.
assert!(out.buckets[0].effective_rate_pct.is_none());
assert_eq!(out.buckets[0].extra["surprise_bucket"], true);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/settlement/processor-cost?test_mode=true"
);
}
}