delopay 0.7.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
//! The `analytics` resource: scoped dashboard drill-downs, cross-index search
//! and the event log feeds. Response shapes are open — see the API reference.

use std::sync::Arc;

use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::analytics::DrillResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// Scoped, drill-level analytics for the authenticated merchant.
    ///
    /// The server ignores `merchant_id` — it always scopes to your merchant,
    /// and to your single shop for profile-scoped users — so pass only
    /// `project_id` / `shop_id` to drill, plus the window and `sections`
    /// fields. Returns one drill level: the scope's daily series and previous
    /// window, processor mix and direct children.
    pub async fn scope(&self, params: Option<&AnalyticsScopeParams>) -> Result<Value> {
        let query = params
            .map(AnalyticsScopeParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/analytics/scope", None, &query, None)
            .await
    }

    /// Device analytics over the canonical client-context observation per
    /// payment: browser and platform families, device classes and models, the
    /// checkout-channel mix and time-to-pay. Scoped and drilled exactly like
    /// [`Self::scope`].
    ///
    /// Gated on the client-context optimisation-use switch. When that is off
    /// the server answers `200` with `enabled: false` and a caveat naming the
    /// switch, rather than an error — so read `enabled` before reading the
    /// figures. `GET /analytics/devices`
    pub async fn devices(&self, params: Option<&ClientAnalyticsParams>) -> Result<Value> {
        let query = params
            .map(ClientAnalyticsParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/analytics/devices", None, &query, None)
            .await
    }

    /// Geo analytics over the canonical client-context observation per
    /// payment: country totals, city bubbles, buyer languages, buyer-local
    /// purchase hours and the IP-versus-billing mismatch share.
    ///
    /// [`ClientAnalyticsParams::mode`] selects the location claim; the two are
    /// never coalesced. Same window, scope and gating contract as
    /// [`Self::devices`]. `GET /analytics/geo`
    pub async fn geo(&self, params: Option<&ClientAnalyticsParams>) -> Result<Value> {
        let query = params
            .map(ClientAnalyticsParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/analytics/geo", None, &query, None)
            .await
    }

    /// The payments behind one clicked element of the payments dashboard.
    ///
    /// Targets combine: a connector *and* an outcome is that connector's
    /// failed payments. Rows and the whole-match summary carry USD figures
    /// converted with the dashboard's own rates, so the drawer agrees with the
    /// chart that was clicked.
    ///
    /// `GET /analytics/scope/transactions`
    pub async fn scope_transactions(&self, params: &ScopeDrillParams) -> Result<DrillResponse> {
        params.validate()?;
        self.inner
            .request(
                HttpMethod::Get,
                "/analytics/scope/transactions",
                None,
                &params.to_query(),
                None,
            )
            .await
    }

    /// The payments behind one clicked geo target: a map country in the active
    /// claim mode, optionally narrowed to an IP-resolved city, or one
    /// buyer-local heatmap cell (paid sessions only).
    ///
    /// Same window, scope, filter and gating contract as [`Self::geo`].
    /// `GET /analytics/geo/transactions`
    pub async fn geo_transactions(&self, params: &GeoDrillParams) -> Result<DrillResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/analytics/geo/transactions",
                None,
                &params.to_query(),
                None,
            )
            .await
    }

    /// The payments behind one clicked device target: a browser family, a
    /// platform family, a device-model label, a device class, a time-to-pay
    /// bar or a checkout channel.
    ///
    /// Same window, scope, filter and gating contract as [`Self::devices`].
    /// `GET /analytics/devices/transactions`
    pub async fn device_transactions(&self, params: &DeviceDrillParams) -> Result<DrillResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/analytics/devices/transactions",
                None,
                &params.to_query(),
                None,
            )
            .await
    }

    /// Subscription analytics over subscriptions and invoices: estimated
    /// recurring volume, the invoice funnel, movement, both processor axes,
    /// plan mix and the breakdown one level below the scope.
    ///
    /// Half of these figures are **stocks** — a snapshot as at the window's
    /// end rather than a sum over it — so the estimated monthly volume and the
    /// active count can match across a 7-day and a 30-day window while billed
    /// volume does not. Day granularity only. `GET /analytics/subscriptions`
    pub async fn subscriptions(
        &self,
        params: Option<&SubscriptionAnalyticsParams>,
    ) -> Result<Value> {
        let query = params
            .map(SubscriptionAnalyticsParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(
                HttpMethod::Get,
                "/analytics/subscriptions",
                None,
                &query,
                None,
            )
            .await
    }

    /// The billing cycles behind one clicked element of the subscription
    /// dashboard.
    ///
    /// A cycle that never reached a payment is listed too — that is what
    /// "still unpaid" means — and carries its invoice id as `payment_id` with
    /// `invoice_id` set to the same value, so a caller can always tell which
    /// of the two they were given.
    ///
    /// `GET /analytics/subscriptions/list`
    pub async fn subscriptions_list(
        &self,
        params: &SubscriptionDrillParams,
    ) -> Result<DrillResponse> {
        params.validate()?;
        self.inner
            .request(
                HttpMethod::Get,
                "/analytics/subscriptions/list",
                None,
                &params.to_query(),
                None,
            )
            .await
    }

    /// Global search across every supported index. The body shape is open —
    /// see [`crate::Search::global`] for the named request form.
    pub async fn search(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/analytics/search",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Domain-specific search, e.g. `"payment_intents"`. The body shape is
    /// open — see the API reference.
    pub async fn search_domain(&self, domain: &str, params: &Value) -> Result<Value> {
        let path = format!("/analytics/search/{}", encode_segment(domain));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Describe the filters and columns a search domain supports.
    pub async fn info(&self, domain: &str) -> Result<Value> {
        let path = format!("/analytics/{}/info", encode_segment(domain));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// API event logs. Query keys are open — pass `&[]` for none.
    pub async fn api_event_logs(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(
                HttpMethod::Get,
                "/analytics/api-event-logs",
                None,
                query,
                None,
            )
            .await
    }

    /// SDK event logs. The body shape is open — see the API reference.
    pub async fn sdk_event_logs(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/analytics/sdk-event-logs",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Connector event logs. Query keys are open — pass `&[]` for none.
    pub async fn connector_event_logs(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(
                HttpMethod::Get,
                "/analytics/connector-event-logs",
                None,
                query,
                None,
            )
            .await
    }

    /// Routing event logs. Query keys are open — pass `&[]` for none.
    pub async fn routing_event_logs(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(
                HttpMethod::Get,
                "/analytics/routing-event-logs",
                None,
                query,
                None,
            )
            .await
    }

    /// Outgoing webhook event logs. Query keys are open — pass `&[]` for none.
    pub async fn outgoing_webhook_event_logs(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(
                HttpMethod::Get,
                "/analytics/outgoing-webhook-event-logs",
                None,
                query,
                None,
            )
            .await
    }
}

/// Window and scope parameters for [`Analytics::scope`].
#[derive(Debug, Clone, Default)]
pub struct AnalyticsScopeParams {
    /// Trailing days for a rolling window ending now. Defaults to 7 server-side,
    /// capped at 90.
    pub days: Option<i64>,
    /// Naive ISO 8601 datetime for the window start (custom range, span ≤ 90 days).
    pub start_date: Option<String>,
    /// Naive ISO 8601 datetime for the inclusive last day. Defaults to now.
    pub end_date: Option<String>,
    /// Scope to a single merchant. Ignored (server-pinned) on this endpoint.
    pub merchant_id: Option<String>,
    /// Scope to one project's shops.
    pub project_id: Option<String>,
    /// Scope to a single shop; wins over [`project_id`](Self::project_id).
    pub shop_id: Option<String>,
    /// Comma-separated selector for which response blocks the server computes:
    /// `series`, `previous`, `connectors`, `children`. Omit for all of them;
    /// unrequested blocks come back as empty arrays.
    pub sections: Option<String>,
    /// Series bucket size, day by default. The limit is a ceiling of 2208
    /// buckets on any grain — hourly over the widest window, 5-minute over a
    /// week — and a request past it is refused, not downgraded. For a sub-day
    /// grain the previous series covers the same span one window (in whole
    /// days) earlier.
    pub granularity: Option<AnalyticsGranularity>,
    /// Filter by test mode: `false` returns only live payments, `true` only
    /// test/sandbox payments. Omit to include both.
    pub test_mode: Option<bool>,
}

impl AnalyticsScopeParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.days {
            q.push(("days", v.to_string()));
        }
        if let Some(v) = &self.start_date {
            q.push(("start_date", v.clone()));
        }
        if let Some(v) = &self.end_date {
            q.push(("end_date", v.clone()));
        }
        if let Some(v) = &self.merchant_id {
            q.push(("merchant_id", v.clone()));
        }
        if let Some(v) = &self.project_id {
            q.push(("project_id", v.clone()));
        }
        if let Some(v) = &self.shop_id {
            q.push(("shop_id", v.clone()));
        }
        if let Some(v) = &self.sections {
            q.push(("sections", v.clone()));
        }
        if let Some(v) = self.granularity {
            q.push(("granularity", v.as_str().to_string()));
        }
        if let Some(v) = self.test_mode {
            q.push(("test_mode", v.to_string()));
        }
        q
    }
}

/// Series bucket size for [`Analytics::scope`].
///
/// The ceiling is on bucket *count* (2208), not on the window: hourly over the
/// widest window and 5-minute over a week both fit, and a request that would
/// exceed it is refused rather than silently downgraded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnalyticsGranularity {
    /// One bucket per UTC day. The default.
    Day,
    /// One bucket per hour.
    Hour,
    /// 30-minute buckets.
    HalfHour,
    /// 15-minute buckets.
    QuarterHour,
    /// 5-minute buckets.
    FiveMinutes,
}

impl AnalyticsGranularity {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Day => "day",
            Self::Hour => "hour",
            Self::HalfHour => "30m",
            Self::QuarterHour => "15m",
            Self::FiveMinutes => "5m",
        }
    }
}

/// Bucket size for the device and geo dashboards, which have no sub-hour view.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClientAnalyticsGranularity {
    /// One bucket per UTC day. The default.
    Day,
    /// One bucket per hour.
    Hour,
}

impl ClientAnalyticsGranularity {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Day => "day",
            Self::Hour => "hour",
        }
    }
}

/// The dashboards' four outcomes; `Open` is processing plus awaiting action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnalyticsOutcome {
    /// Settled.
    Success,
    /// In flight or waiting on the buyer.
    Open,
    /// Terminally failed.
    Failed,
    /// Cancelled or voided.
    Void,
}

impl AnalyticsOutcome {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Success => "success",
            Self::Open => "open",
            Self::Failed => "failed",
            Self::Void => "void",
        }
    }
}

/// Checkout channel, as the device dashboard's channel series names them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnalyticsChannel {
    /// The hosted checkout page.
    Hosted,
    /// The embedded (iframe) checkout.
    Embedded,
    /// A direct API confirm.
    Api,
    /// Raised from the dashboard.
    Dashboard,
    /// A client SDK.
    Sdk,
    /// No channel could be established.
    Unknown,
}

impl AnalyticsChannel {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Hosted => "hosted",
            Self::Embedded => "embedded",
            Self::Api => "api",
            Self::Dashboard => "dashboard",
            Self::Sdk => "sdk",
            Self::Unknown => "unknown",
        }
    }
}

/// A bar of the time-to-pay histogram, in histogram order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimeToPayBucket {
    /// Under 30 seconds.
    UnderThirtySeconds,
    /// 30–60 seconds.
    ThirtyToSixtySeconds,
    /// 1–2 minutes.
    OneToTwoMinutes,
    /// 2–5 minutes.
    TwoToFiveMinutes,
    /// 5–15 minutes.
    FiveToFifteenMinutes,
    /// Over 15 minutes.
    OverFifteenMinutes,
}

impl TimeToPayBucket {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::UnderThirtySeconds => "lt_30s",
            Self::ThirtyToSixtySeconds => "s30_60s",
            Self::OneToTwoMinutes => "m1_2",
            Self::TwoToFiveMinutes => "m2_5",
            Self::FiveToFifteenMinutes => "m5_15",
            Self::OverFifteenMinutes => "gt_15m",
        }
    }
}

/// What a clicked breakdown row is, which is what makes its id resolvable.
///
/// The kind travels with the id on every drill: the server matches nothing
/// rather than everything when it is missing, so an id alone is a silently
/// empty list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DrillChildKind {
    /// A merchant row (cross-merchant scopes only).
    Merchant,
    /// A project row.
    Project,
    /// A shop row.
    Shop,
}

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

/// Sort direction for a drill list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SortDirection {
    /// Oldest, smallest or alphabetically first.
    Ascending,
    /// The default.
    Descending,
}

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

/// A sort key one drill endpoint accepts.
///
/// Implemented by one enum per endpoint rather than by a single shared one:
/// the server answers `400` to a key its endpoint does not take, and typing
/// them apart is what turns that into a compile error.
pub trait DrillSortKey: Copy {
    /// The wire token.
    fn as_str(self) -> &'static str;
}

/// Sort keys of the payments drill.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScopeDrillSortKey {
    /// Observation time — the default, newest first.
    CreatedAt,
    /// The payment's own creation time.
    PaymentCreatedAt,
    /// Amount, in USD.
    Amount,
    /// Raw intent status.
    Status,
    /// Processor of the active attempt.
    Connector,
    /// High-level payment method.
    Method,
}

impl DrillSortKey for ScopeDrillSortKey {
    fn as_str(self) -> &'static str {
        match self {
            Self::CreatedAt => "created_at",
            Self::PaymentCreatedAt => "payment_created_at",
            Self::Amount => "amount",
            Self::Status => "status",
            Self::Connector => "connector",
            Self::Method => "method",
        }
    }
}

/// Sort keys of the geo and device drills: the payments keys plus the time a
/// buyer took to pay.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClientDrillSortKey {
    /// Observation time — the default, newest first.
    CreatedAt,
    /// The payment's own creation time.
    PaymentCreatedAt,
    /// Amount, in USD.
    Amount,
    /// Raw intent status.
    Status,
    /// Processor of the active attempt.
    Connector,
    /// High-level payment method.
    Method,
    /// Seconds from checkout open to success.
    TimeToPay,
}

impl DrillSortKey for ClientDrillSortKey {
    fn as_str(self) -> &'static str {
        match self {
            Self::CreatedAt => "created_at",
            Self::PaymentCreatedAt => "payment_created_at",
            Self::Amount => "amount",
            Self::Status => "status",
            Self::Connector => "connector",
            Self::Method => "method",
            Self::TimeToPay => "time_to_pay",
        }
    }
}

/// Sort keys of the subscription drill. No `method` — a billing cycle has no
/// payment method of its own — and `plan` instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SubscriptionDrillSortKey {
    /// The cycle's time — the default, newest first.
    CreatedAt,
    /// The payment's own creation time.
    PaymentCreatedAt,
    /// Amount, in USD.
    Amount,
    /// Raw invoice status.
    Status,
    /// The charging connector.
    Connector,
    /// The plan the subscription is on.
    Plan,
}

impl DrillSortKey for SubscriptionDrillSortKey {
    fn as_str(self) -> &'static str {
        match self {
            Self::CreatedAt => "created_at",
            Self::PaymentCreatedAt => "payment_created_at",
            Self::Amount => "amount",
            Self::Status => "status",
            Self::Connector => "connector",
            Self::Plan => "plan",
        }
    }
}

/// The drawer's list controls, shared by every drill list.
///
/// Applied server-side over the **whole** match: the list is paged, so a
/// client-side sort or search would only ever cover the loaded page.
#[derive(Debug, Clone)]
pub struct DrillListControls<K: DrillSortKey> {
    /// Free-text search (case-insensitive substring) over the ids a reader has
    /// in front of them: payment id, customer id, description, the
    /// processor's transaction reference and the shop name — invoice and
    /// subscription id on the subscription drill.
    pub q: Option<String>,
    /// Sort key; observation time (newest first) by default.
    pub sort_on: Option<K>,
    /// Sort direction, descending by default.
    pub sort_by: Option<SortDirection>,
    /// Row filter: an outcome token, or one raw intent status — one raw
    /// invoice status on the subscription drill.
    pub status: Option<String>,
    /// Row filter: processor name, `"Direct"` included.
    pub connector: Option<String>,
    /// Row filter: high-level payment method; `"none"` is "no attempt".
    pub method: Option<String>,
    /// Row filter: checkout channel.
    pub channel: Option<AnalyticsChannel>,
    /// Row filter: ISO currency code.
    pub currency: Option<String>,
    /// Page size, default 50, at most 200.
    pub limit: Option<i64>,
    /// Offset into the sorted list. `total` in the response is the full match
    /// count.
    pub offset: Option<i64>,
}

impl<K: DrillSortKey> Default for DrillListControls<K> {
    fn default() -> Self {
        Self {
            q: None,
            sort_on: None,
            sort_by: None,
            status: None,
            connector: None,
            method: None,
            channel: None,
            currency: None,
            limit: None,
            offset: None,
        }
    }
}

impl<K: DrillSortKey> DrillListControls<K> {
    fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
        if let Some(v) = &self.q {
            q.push(("q", v.clone()));
        }
        if let Some(v) = self.sort_on {
            q.push(("sort_on", v.as_str().to_string()));
        }
        if let Some(v) = self.sort_by {
            q.push(("sort_by", v.as_str().to_string()));
        }
        if let Some(v) = &self.status {
            q.push(("status", v.clone()));
        }
        if let Some(v) = &self.connector {
            q.push(("connector", v.clone()));
        }
        if let Some(v) = &self.method {
            q.push(("method", v.clone()));
        }
        if let Some(v) = self.channel {
            q.push(("channel", v.as_str().to_string()));
        }
        if let Some(v) = &self.currency {
            q.push(("currency", 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()));
        }
    }
}

/// The window, scope and active chip filters a drill inherits from the page it
/// was clicked on, so the list reports what the charts counted.
#[derive(Debug, Clone, Default)]
pub struct DrillScope {
    /// Trailing days for a rolling window ending now.
    pub days: Option<i64>,
    /// Naive ISO 8601 datetime for the window start.
    pub start_date: Option<String>,
    /// Naive ISO 8601 datetime for the inclusive last day.
    pub end_date: Option<String>,
    /// Ignored (server-pinned) on the merchant-facing routes.
    pub merchant_id: Option<String>,
    /// Scope to one project's shops.
    pub project_id: Option<String>,
    /// Scope to a single shop; wins over [`project_id`](Self::project_id).
    pub shop_id: Option<String>,
    /// `Some(false)` is live only, `Some(true)` test only. `None` for both.
    pub test_mode: Option<bool>,
    /// Chip filter: one country (ISO alpha-2).
    pub country: Option<String>,
    /// Which country claim [`country`](Self::country) matches: `"ip"`
    /// (default) or `"billing"`.
    pub country_source: Option<String>,
    /// Chip filter: `phone`, `tablet`, `desktop` or `unknown`.
    pub device_class: Option<String>,
}

impl DrillScope {
    fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
        if let Some(v) = self.days {
            q.push(("days", v.to_string()));
        }
        if let Some(v) = &self.start_date {
            q.push(("start_date", v.clone()));
        }
        if let Some(v) = &self.end_date {
            q.push(("end_date", v.clone()));
        }
        if let Some(v) = &self.merchant_id {
            q.push(("merchant_id", v.clone()));
        }
        if let Some(v) = &self.project_id {
            q.push(("project_id", v.clone()));
        }
        if let Some(v) = &self.shop_id {
            q.push(("shop_id", v.clone()));
        }
        if let Some(v) = self.test_mode {
            q.push(("test_mode", v.to_string()));
        }
        if let Some(v) = &self.country {
            q.push(("country", v.clone()));
        }
        if let Some(v) = &self.country_source {
            q.push(("country_source", v.clone()));
        }
        if let Some(v) = &self.device_class {
            q.push(("device_class", v.clone()));
        }
    }
}

/// The clicked target(s) of a payments drill.
///
/// **At least one**, and they combine — a connector *and* an outcome is "that
/// connector's failed payments" — so unlike the device and subscription drills
/// this is not "exactly one" and is not an enum. What
/// [`Analytics::scope_transactions`] refuses is the shapes the server would answer
/// with a quietly wrong list: no target at all (which would list the whole
/// window, and no click means that), a method type with no method, and a child
/// id with no kind.
#[derive(Debug, Clone, Default)]
pub struct ScopeDrillTargets {
    /// Clicked processor slice (`"Direct"` included).
    pub connector: Option<String>,
    /// Clicked outcome segment of a series bar.
    pub outcome: Option<AnalyticsOutcome>,
    /// Clicked series bucket, in the shape the series draws: `YYYY-MM-DD` for
    /// a day, `YYYY-MM-DDTHH:MM:00Z` for a sub-day bucket. Narrows every other
    /// target to that bucket rather than replacing it.
    pub bucket: Option<String>,
    /// Clicked payment-method slice; `"none"` is the null-method slice.
    pub method: Option<String>,
    /// Narrows [`method`](Self::method) to one method type. Never travels
    /// alone: a type with no method is refused rather than sent.
    pub method_type: Option<String>,
    /// Clicked breakdown row. Travels with
    /// [`child_kind`](Self::child_kind).
    pub child: Option<String>,
    /// What [`child`](Self::child) is.
    pub child_kind: Option<DrillChildKind>,
}

impl ScopeDrillTargets {
    fn is_empty(&self) -> bool {
        self.connector.is_none()
            && self.outcome.is_none()
            && self.bucket.is_none()
            && self.method.is_none()
            && self.child.is_none()
    }

    fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
        if let Some(v) = &self.connector {
            q.push(("target_connector", v.clone()));
        }
        if let Some(v) = self.outcome {
            q.push(("target_outcome", v.as_str().to_string()));
        }
        if let Some(v) = &self.bucket {
            q.push(("target_bucket", v.clone()));
        }
        if let Some(v) = &self.method {
            q.push(("target_method", v.clone()));
        }
        if let Some(v) = &self.method_type {
            q.push(("target_method_type", v.clone()));
        }
        if let Some(v) = &self.child {
            q.push(("target_child", v.clone()));
        }
        if let Some(v) = self.child_kind {
            q.push(("target_child_kind", v.as_str().to_string()));
        }
    }
}

/// The clicked target of a geo drill.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum GeoDrillTarget {
    /// A map country, optionally narrowed to one IP-resolved city.
    Country {
        /// ISO alpha-2, matched against the request's claim mode.
        country: String,
        /// City name, IP claim only.
        city: Option<String>,
    },
    /// One buyer-local heatmap cell: paid sessions only.
    HeatmapCell {
        /// ISO day of week, 1–7 (Monday–Sunday).
        dow: i64,
        /// Buyer-local hour, 0–23.
        hour: i64,
    },
}

impl GeoDrillTarget {
    fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
        match self {
            Self::Country { country, city } => {
                q.push(("target_country", country.clone()));
                if let Some(city) = city {
                    q.push(("target_city", city.clone()));
                }
            }
            Self::HeatmapCell { dow, hour } => {
                q.push(("dow", dow.to_string()));
                q.push(("hour", hour.to_string()));
            }
        }
    }
}

/// The clicked target of a device drill. **Exactly one**, which is why it is
/// an enum.
///
/// The endpoint applies every target it is given as a further `AND`, so two
/// targets are not refused — they answer a narrower question than the click
/// meant and return a shorter list with no indication that they did. A drawer
/// quietly missing rows is worse than an error, so the shape makes the second
/// target unrepresentable.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DeviceDrillTarget {
    /// Clicked browser family (`chrome`, `safari`, …).
    Browser(String),
    /// Clicked platform family (`ios`, `android`, `macos`, …).
    Platform(String),
    /// Clicked device-model label, exactly as the models card lists it.
    Model(String),
    /// Clicked device class (`phone`, `tablet`, `desktop`, `unknown`).
    DeviceClass(String),
    /// Clicked bar of the time-to-pay histogram: paid, timed sessions.
    TimeToPayBucket(TimeToPayBucket),
    /// Clicked checkout channel, optionally one bar of the channel series.
    Channel {
        /// The channel.
        channel: AnalyticsChannel,
        /// One series bucket of it.
        bucket: Option<String>,
    },
}

impl DeviceDrillTarget {
    fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
        match self {
            Self::Browser(v) => q.push(("target_browser", v.clone())),
            Self::Platform(v) => q.push(("target_platform", v.clone())),
            Self::Model(v) => q.push(("target_model", v.clone())),
            Self::DeviceClass(v) => q.push(("target_device_class", v.clone())),
            Self::TimeToPayBucket(v) => q.push(("target_ttp_bucket", v.as_str().to_string())),
            Self::Channel { channel, bucket } => {
                q.push(("target_channel", channel.as_str().to_string()));
                if let Some(bucket) = bucket {
                    q.push(("target_bucket", bucket.clone()));
                }
            }
        }
    }
}

/// Which slice of the invoice funnel was clicked.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SubscriptionInvoiceOutcome {
    /// Paid on the first attempt.
    PaidFirst,
    /// Retried after a failure.
    Retried,
    /// Paid after a retry.
    Recovered,
    /// Never paid.
    Unpaid,
}

impl SubscriptionInvoiceOutcome {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::PaidFirst => "paid_first",
            Self::Retried => "retried",
            Self::Recovered => "recovered",
            Self::Unpaid => "unpaid",
        }
    }
}

/// A component of subscription movement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SubscriptionMovement {
    /// Newly started.
    New,
    /// Grew.
    Expansion,
    /// Shrank.
    Contraction,
    /// Ended.
    Churn,
}

impl SubscriptionMovement {
    /// The wire token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::New => "new",
            Self::Expansion => "expansion",
            Self::Contraction => "contraction",
            Self::Churn => "churn",
        }
    }
}

/// The clicked target of a subscription drill. **Exactly one**, on the same
/// rule as [`DeviceDrillTarget`].
///
/// A clicked day with no further target is not a variant here: it is
/// [`SubscriptionDrillParams::bucket`], which also narrows any of these.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SubscriptionDrillTarget {
    /// Clicked slice of the invoice funnel.
    Outcome(SubscriptionInvoiceOutcome),
    /// Clicked slice of the "bills it" ring.
    BillingProcessor(String),
    /// Clicked slice of the "charges the card" ring.
    ChargingConnector(String),
    /// Clicked plan row.
    Plan(String),
    /// Clicked subscription status.
    Status(String),
    /// Clicked movement component.
    Movement(SubscriptionMovement),
    /// Clicked breakdown row, with the kind that makes it resolvable.
    Child {
        /// The row's id.
        id: String,
        /// What the id is.
        kind: DrillChildKind,
    },
}

impl SubscriptionDrillTarget {
    fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
        match self {
            Self::Outcome(v) => q.push(("target_outcome", v.as_str().to_string())),
            Self::BillingProcessor(v) => q.push(("target_billing_processor", v.clone())),
            Self::ChargingConnector(v) => q.push(("target_charging_connector", v.clone())),
            Self::Plan(v) => q.push(("target_plan", v.clone())),
            Self::Status(v) => q.push(("target_status", v.clone())),
            Self::Movement(v) => q.push(("target_movement", v.as_str().to_string())),
            Self::Child { id, kind } => {
                q.push(("target_child", id.clone()));
                q.push(("target_child_kind", kind.as_str().to_string()));
            }
        }
    }
}

/// Query for [`Analytics::scope_transactions`].
#[derive(Debug, Clone, Default)]
pub struct ScopeDrillParams {
    /// Window, scope and chip filters from the page that was clicked.
    pub scope: DrillScope,
    /// Sorting, searching, row filters and paging.
    pub controls: DrillListControls<ScopeDrillSortKey>,
    /// The bucket size the series was drawn in, so a sub-day
    /// [`ScopeDrillTargets::bucket`] spans the right interval. Defaults
    /// server-side to hour for a timestamp bucket and day for a date.
    pub granularity: Option<AnalyticsGranularity>,
    /// What was clicked.
    pub targets: ScopeDrillTargets,
}

impl ScopeDrillParams {
    fn validate(&self) -> Result<()> {
        if self.targets.is_empty() {
            return Err(DelopayError::InvalidRequest(
                "a payments drill needs at least one target: an untargeted request lists the \
                 whole window, which no click means"
                    .to_string(),
            ));
        }
        if self.targets.method_type.is_some() && self.targets.method.is_none() {
            return Err(DelopayError::InvalidRequest(
                "`method_type` qualifies `method`: sent alone it narrows nothing and the list \
                 silently answers a different question"
                    .to_string(),
            ));
        }
        if self.targets.child.is_some() != self.targets.child_kind.is_some() {
            return Err(DelopayError::InvalidRequest(
                "`child` and `child_kind` travel together: the server resolves a child id only \
                 with its kind, and matches nothing without it"
                    .to_string(),
            ));
        }
        Ok(())
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        self.scope.push_query(&mut q);
        if let Some(v) = self.granularity {
            q.push(("granularity", v.as_str().to_string()));
        }
        self.targets.push_query(&mut q);
        self.controls.push_query(&mut q);
        q
    }
}

/// Query for [`Analytics::geo_transactions`].
#[derive(Debug, Clone)]
pub struct GeoDrillParams {
    /// Window, scope and chip filters from the page that was clicked.
    pub scope: DrillScope,
    /// Sorting, searching, row filters and paging.
    pub controls: DrillListControls<ClientDrillSortKey>,
    /// Which claim the clicked country is matched against: `"ip"` (default) or
    /// `"billing"`. The two are never coalesced.
    pub mode: Option<String>,
    /// What was clicked.
    pub target: GeoDrillTarget,
}

impl GeoDrillParams {
    /// A drill on one country, with everything else left at its default.
    pub fn country(country: impl Into<String>) -> Self {
        Self::new(GeoDrillTarget::Country {
            country: country.into(),
            city: None,
        })
    }

    /// A drill on one target, with everything else left at its default.
    pub fn new(target: GeoDrillTarget) -> Self {
        Self {
            scope: DrillScope::default(),
            controls: DrillListControls::default(),
            mode: None,
            target,
        }
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        self.scope.push_query(&mut q);
        if let Some(v) = &self.mode {
            q.push(("mode", v.clone()));
        }
        self.target.push_query(&mut q);
        self.controls.push_query(&mut q);
        q
    }
}

/// Query for [`Analytics::device_transactions`].
#[derive(Debug, Clone)]
pub struct DeviceDrillParams {
    /// Window, scope and chip filters from the page that was clicked.
    pub scope: DrillScope,
    /// Sorting, searching, row filters and paging.
    pub controls: DrillListControls<ClientDrillSortKey>,
    /// What was clicked.
    pub target: DeviceDrillTarget,
}

impl DeviceDrillParams {
    /// A drill on one target, with everything else left at its default.
    pub fn new(target: DeviceDrillTarget) -> Self {
        Self {
            scope: DrillScope::default(),
            controls: DrillListControls::default(),
            target,
        }
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        self.scope.push_query(&mut q);
        self.target.push_query(&mut q);
        self.controls.push_query(&mut q);
        q
    }
}

/// Query for [`Analytics::subscriptions_list`].
///
/// Either [`target`](Self::target) or [`bucket`](Self::bucket) must be set:
/// a request with neither lists every cycle in the window, which no click
/// means.
#[derive(Debug, Clone, Default)]
pub struct SubscriptionDrillParams {
    /// Window, scope and chip filters from the page that was clicked.
    pub scope: DrillScope,
    /// Sorting, searching, row filters and paging. `status` here is one raw
    /// invoice status, and `connector` the charging connector.
    pub controls: DrillListControls<SubscriptionDrillSortKey>,
    /// What was clicked, when it was not just a day.
    pub target: Option<SubscriptionDrillTarget>,
    /// Clicked series bucket (`YYYY-MM-DD`). Narrows
    /// [`target`](Self::target) to that one day, or stands alone as "every
    /// cycle raised that day".
    pub bucket: Option<String>,
}

impl SubscriptionDrillParams {
    /// A drill on one target, with everything else left at its default.
    pub fn new(target: SubscriptionDrillTarget) -> Self {
        Self {
            scope: DrillScope::default(),
            controls: DrillListControls::default(),
            target: Some(target),
            bucket: None,
        }
    }

    /// A drill on one day of the series, with no further target.
    pub fn bucket(bucket: impl Into<String>) -> Self {
        Self {
            scope: DrillScope::default(),
            controls: DrillListControls::default(),
            target: None,
            bucket: Some(bucket.into()),
        }
    }

    fn validate(&self) -> Result<()> {
        if self.target.is_none() && self.bucket.is_none() {
            return Err(DelopayError::InvalidRequest(
                "a subscription drill needs a target or a bucket: an untargeted request lists \
                 every cycle in the window, which no click means"
                    .to_string(),
            ));
        }
        Ok(())
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        self.scope.push_query(&mut q);
        if let Some(target) = &self.target {
            target.push_query(&mut q);
        }
        if let Some(v) = &self.bucket {
            q.push(("target_bucket", v.clone()));
        }
        self.controls.push_query(&mut q);
        q
    }
}

/// Window and scope parameters for [`Analytics::devices`] and
/// [`Analytics::geo`].
#[derive(Debug, Clone, Default)]
pub struct ClientAnalyticsParams {
    /// Trailing days for a rolling window ending now. Defaults to 7
    /// server-side, capped at 92.
    pub days: Option<i64>,
    /// Naive ISO 8601 datetime for the window start (span ≤ 92 days).
    pub start_date: Option<String>,
    /// Naive ISO 8601 datetime for the inclusive last day. Defaults to now.
    pub end_date: Option<String>,
    /// Ignored (server-pinned) on these routes.
    pub merchant_id: Option<String>,
    /// Scope to one project's shops.
    pub project_id: Option<String>,
    /// Scope to a single shop; wins over [`project_id`](Self::project_id).
    pub shop_id: Option<String>,
    /// `Some(false)` is live only, `Some(true)` test only. `None` for both.
    pub test_mode: Option<bool>,
    /// Series bucket size. These pages have no sub-hour view.
    pub granularity: Option<ClientAnalyticsGranularity>,
    /// Comma-separated response blocks to compute; omit for all. Devices:
    /// `totals`, `browsers`, `platforms`, `classes`, `models`, `channels`,
    /// `timing`, `children`. Geo: `totals`, `countries`, `cities`, `heatmap`,
    /// `languages`, `children`.
    pub sections: Option<String>,
    /// Geo only: which location claim to aggregate — `"ip"` (default;
    /// IP-derived country and city coordinates) or `"billing"` (the plaintext
    /// billing address, no coordinates). Never coalesced.
    pub mode: Option<String>,
    /// Restrict to sessions from one country (ISO alpha-2).
    pub country: Option<String>,
    /// Which country claim [`country`](Self::country) filters on: `"ip"`
    /// (default) or `"billing"`.
    pub country_source: Option<String>,
    /// Restrict to one device class: `phone`, `tablet`, `desktop`, `unknown`.
    pub device_class: Option<String>,
}

impl ClientAnalyticsParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.days {
            q.push(("days", v.to_string()));
        }
        if let Some(v) = &self.start_date {
            q.push(("start_date", v.clone()));
        }
        if let Some(v) = &self.end_date {
            q.push(("end_date", v.clone()));
        }
        if let Some(v) = &self.merchant_id {
            q.push(("merchant_id", v.clone()));
        }
        if let Some(v) = &self.project_id {
            q.push(("project_id", v.clone()));
        }
        if let Some(v) = &self.shop_id {
            q.push(("shop_id", v.clone()));
        }
        if let Some(v) = self.test_mode {
            q.push(("test_mode", v.to_string()));
        }
        if let Some(v) = self.granularity {
            q.push(("granularity", v.as_str().to_string()));
        }
        if let Some(v) = &self.sections {
            q.push(("sections", v.clone()));
        }
        if let Some(v) = &self.mode {
            q.push(("mode", v.clone()));
        }
        if let Some(v) = &self.country {
            q.push(("country", v.clone()));
        }
        if let Some(v) = &self.country_source {
            q.push(("country_source", v.clone()));
        }
        if let Some(v) = &self.device_class {
            q.push(("device_class", v.clone()));
        }
        q
    }
}

/// Window and scope parameters for [`Analytics::subscriptions`].
///
/// No granularity: a billing cycle carries day resolution at best, so the
/// endpoint takes day only and rejects anything else rather than downgrading
/// it.
#[derive(Debug, Clone, Default)]
pub struct SubscriptionAnalyticsParams {
    /// Trailing days for a rolling window ending now. Defaults to 7
    /// server-side, capped at 92.
    pub days: Option<i64>,
    /// Naive ISO 8601 datetime for the window start (span ≤ 92 days).
    pub start_date: Option<String>,
    /// Naive ISO 8601 datetime for the inclusive last day. Defaults to now.
    pub end_date: Option<String>,
    /// Ignored (server-pinned) on this route.
    pub merchant_id: Option<String>,
    /// Scope to one project's shops.
    pub project_id: Option<String>,
    /// Scope to a single shop; wins over [`project_id`](Self::project_id).
    pub shop_id: Option<String>,
    /// `Some(false)` is live only, `Some(true)` test only. `None` for both.
    pub test_mode: Option<bool>,
    /// Comma-separated blocks to compute; omit for all. Tokens: `totals`,
    /// `series`, `movement`, `processors`, `plans`, `outcomes`, `children`,
    /// `previous`. A block you did not ask for comes back empty, zeroed or
    /// null — never stale.
    pub sections: Option<String>,
    /// Restrict to subscriptions charged from one country (ISO alpha-2). This
    /// narrows the population to subscriptions with at least one matching
    /// invoice in the window, so it is not a display filter.
    pub country: Option<String>,
    /// Which country claim the filter matches: `"ip"` (default) or
    /// `"billing"`.
    pub country_source: Option<String>,
    /// `phone`, `tablet`, `desktop` or `unknown`.
    pub device_class: Option<String>,
}

impl SubscriptionAnalyticsParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.days {
            q.push(("days", v.to_string()));
        }
        if let Some(v) = &self.start_date {
            q.push(("start_date", v.clone()));
        }
        if let Some(v) = &self.end_date {
            q.push(("end_date", v.clone()));
        }
        if let Some(v) = &self.merchant_id {
            q.push(("merchant_id", v.clone()));
        }
        if let Some(v) = &self.project_id {
            q.push(("project_id", v.clone()));
        }
        if let Some(v) = &self.shop_id {
            q.push(("shop_id", v.clone()));
        }
        if let Some(v) = self.test_mode {
            q.push(("test_mode", v.to_string()));
        }
        if let Some(v) = &self.sections {
            q.push(("sections", v.clone()));
        }
        if let Some(v) = &self.country {
            q.push(("country", v.clone()));
        }
        if let Some(v) = &self.country_source {
            q.push(("country_source", v.clone()));
        }
        if let Some(v) = &self.device_class {
            q.push(("device_class", v.clone()));
        }
        q
    }
}

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

    #[tokio::test]
    async fn scope_serializes_every_named_param_in_order() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"series":[]}"#)]);
        let params = AnalyticsScopeParams {
            days: Some(30),
            start_date: Some("2026-01-01T00:00:00".to_string()),
            end_date: Some("2026-01-31T00:00:00".to_string()),
            merchant_id: Some("mer_1".to_string()),
            project_id: Some("pro_1".to_string()),
            shop_id: Some("shop_1".to_string()),
            sections: Some("series,previous".to_string()),
            granularity: Some(AnalyticsGranularity::Hour),
            test_mode: Some(false),
        };
        client.analytics().scope(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/scope?days=30&start_date=2026-01-01T00:00:00\
             &end_date=2026-01-31T00:00:00&merchant_id=mer_1&project_id=pro_1\
             &shop_id=shop_1&sections=series,previous&granularity=hour&test_mode=false"
        );
    }

    #[tokio::test]
    async fn scope_without_params_sends_no_query() {
        let (client, mock) = client_with(vec![Step::ok("{}")]);
        client.analytics().scope(None).await.unwrap();

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

    #[tokio::test]
    async fn search_posts_the_body_to_analytics_search() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        client
            .analytics()
            .search(&json!({"query": "pay_abc"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/analytics/search");
        assert_eq!(seen[0].body_json()["query"], "pay_abc");
    }

    #[tokio::test]
    async fn search_domain_encodes_the_domain_segment() {
        let (client, mock) = client_with(vec![Step::ok("{}")]);
        client
            .analytics()
            .search_domain("payment intents/v2", &json!({"query": "x"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/search/payment%20intents%2Fv2"
        );
        assert_eq!(seen[0].body_json()["query"], "x");
    }

    #[tokio::test]
    async fn info_encodes_the_domain_segment() {
        let (client, mock) = client_with(vec![Step::ok("{}")]);
        client.analytics().info("payment intents").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/payment%20intents/info"
        );
    }

    #[tokio::test]
    async fn event_log_feeds_hit_their_own_paths() {
        let (client, mock) = client_with(vec![
            Step::ok("{}"),
            Step::ok("{}"),
            Step::ok("{}"),
            Step::ok("{}"),
            Step::ok("{}"),
        ]);
        client
            .analytics()
            .api_event_logs(&[("limit", "5".to_string())])
            .await
            .unwrap();
        client
            .analytics()
            .sdk_event_logs(&json!({"payment_id": "pay_1"}))
            .await
            .unwrap();
        client
            .analytics()
            .connector_event_logs(&[("payment_id", "pay_1".to_string())])
            .await
            .unwrap();
        client.analytics().routing_event_logs(&[]).await.unwrap();
        client
            .analytics()
            .outgoing_webhook_event_logs(&[])
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/analytics/api-event-logs?limit=5")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("POST", "https://api.test/analytics/sdk-event-logs")
        );
        assert_eq!(seen[1].body_json()["payment_id"], "pay_1");
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            (
                "GET",
                "https://api.test/analytics/connector-event-logs?payment_id=pay_1"
            )
        );
        assert_eq!(
            (seen[3].method, seen[3].url.as_str()),
            ("GET", "https://api.test/analytics/routing-event-logs")
        );
        assert_eq!(
            (seen[4].method, seen[4].url.as_str()),
            (
                "GET",
                "https://api.test/analytics/outgoing-webhook-event-logs"
            )
        );
    }

    /// The drill list decodes, and the two timestamps stay apart.
    ///
    /// Mutation: alias `payment_created_at` onto `created_at` (or drop it) and
    /// this fails — which is the shape that makes a drill list look like it is
    /// ignoring its own window, because the observation time is what the
    /// window filters on.
    #[tokio::test]
    async fn a_drill_row_keeps_the_observation_time_and_the_payment_age_apart() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{
                "enabled": true,
                "caveats": [],
                "total": 2,
                "payments": [{
                    "payment_id": "pay_1",
                    "merchant_id": "mer_1",
                    "status": "succeeded",
                    "created_at": "2026-03-12T09:00:00Z",
                    "payment_created_at": "2026-02-01T08:00:00Z",
                    "connector": "stripe",
                    "payment_method": "card",
                    "payment_method_type": "credit",
                    "channel": "hosted",
                    "device_class": "phone",
                    "browser_family": "safari",
                    "platform_family": "ios",
                    "time_to_pay_s": 41.5,
                    "amount_usd": 12.5,
                    "refunded_minor": 0,
                    "customer_id": "cus_1",
                    "brand_new_field": 1
                }],
                "summary": {
                    "count": 2,
                    "successful_count": 1,
                    "successful_volume_usd": 12.5,
                    "refund_volume_usd": 0.0,
                    "success_rate": 0.5,
                    "median_amount_usd": 12.5,
                    "median_time_to_pay_s": 41.5,
                    "subscriptions": null,
                    "unconverted_count": 1
                }
            }"#,
        )]);
        let params = ScopeDrillParams {
            targets: ScopeDrillTargets {
                connector: Some("stripe".to_string()),
                outcome: Some(AnalyticsOutcome::Failed),
                ..ScopeDrillTargets::default()
            },
            ..ScopeDrillParams::default()
        };
        let drill = client
            .analytics()
            .scope_transactions(&params)
            .await
            .unwrap();

        let row = &drill.payments[0];
        assert_eq!(row.created_at, "2026-03-12T09:00:00Z");
        assert_eq!(row.payment_created_at, "2026-02-01T08:00:00Z");
        assert_eq!(row.connector.as_deref(), Some("stripe"));
        assert!(row.extra.contains_key("brand_new_field"));
        assert_eq!(drill.total, 2);

        // A row whose currency had no rate is counted but not summed, so the
        // USD figures are a lower bound. Reading them as totals is the thing
        // `usd_is_complete` exists to stop.
        let summary = drill.summary.as_ref().unwrap();
        assert_eq!(summary.unconverted_count, 1);
        assert!(!summary.usd_is_complete());

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/scope/transactions\
             ?target_connector=stripe&target_outcome=failed"
        );
    }

    /// An older backend sends no summary block. That is "no summary", not
    /// zeros — a drawer header must be able to tell the two apart.
    ///
    /// Mutation: type `summary` as `DrillSummary` with a `Default` and this
    /// stops compiling; give it `#[serde(default)]` on a non-`Option` and a
    /// missing block silently reads as a zero match.
    #[tokio::test]
    async fn a_missing_summary_is_absent_rather_than_zero() {
        let (client, _mock) = client_with(vec![Step::ok(
            r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
        )]);
        let drill = client
            .analytics()
            .device_transactions(&DeviceDrillParams::new(DeviceDrillTarget::Browser(
                "chrome".to_string(),
            )))
            .await
            .unwrap();
        assert!(drill.summary.is_none());
    }

    /// The three shapes a payments drill refuses before spending a request.
    ///
    /// Each is a request the server would answer, with a list that quietly
    /// means something other than the click: no target lists the whole window,
    /// a method type alone narrows nothing, and a child id with no kind
    /// matches nothing.
    #[tokio::test]
    async fn a_payments_drill_refuses_the_targets_that_answer_a_different_question() {
        let (client, mock) = client_with(vec![]);

        let untargeted = ScopeDrillParams::default();
        assert!(matches!(
            client.analytics().scope_transactions(&untargeted).await,
            Err(DelopayError::InvalidRequest(_))
        ));

        let orphan_type = ScopeDrillParams {
            targets: ScopeDrillTargets {
                connector: Some("stripe".to_string()),
                method_type: Some("credit".to_string()),
                ..ScopeDrillTargets::default()
            },
            ..ScopeDrillParams::default()
        };
        assert!(matches!(
            client.analytics().scope_transactions(&orphan_type).await,
            Err(DelopayError::InvalidRequest(_))
        ));

        let child_without_kind = ScopeDrillParams {
            targets: ScopeDrillTargets {
                child: Some("pro_1".to_string()),
                ..ScopeDrillTargets::default()
            },
            ..ScopeDrillParams::default()
        };
        assert!(matches!(
            client
                .analytics()
                .scope_transactions(&child_without_kind)
                .await,
            Err(DelopayError::InvalidRequest(_))
        ));

        // Refused before the wire, not after: none of the three cost a request.
        assert!(mock.seen.lock().unwrap().is_empty());
    }

    /// A subscription drill with neither target nor bucket is the same
    /// mistake, and is refused on the same terms.
    #[tokio::test]
    async fn a_subscription_drill_needs_a_target_or_a_bucket() {
        let (client, mock) = client_with(vec![]);
        assert!(matches!(
            client
                .analytics()
                .subscriptions_list(&SubscriptionDrillParams::default())
                .await,
            Err(DelopayError::InvalidRequest(_))
        ));
        assert!(mock.seen.lock().unwrap().is_empty());
    }

    /// The clicked day stands alone, and the controls ride along with it.
    #[tokio::test]
    async fn a_subscription_bucket_drill_sends_the_bucket_and_its_controls() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
        )]);
        let mut params = SubscriptionDrillParams::bucket("2026-03-12");
        params.scope.days = Some(30);
        params.controls.sort_on = Some(SubscriptionDrillSortKey::Plan);
        params.controls.sort_by = Some(SortDirection::Ascending);
        params.controls.limit = Some(200);
        client
            .analytics()
            .subscriptions_list(&params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/subscriptions/list\
             ?days=30&target_bucket=2026-03-12&sort_on=plan&sort_by=asc&limit=200"
        );
    }

    /// A geo country drill carries the claim mode with it: the two claims are
    /// never coalesced server-side, so a country matched under the wrong one
    /// lists different payments.
    #[tokio::test]
    async fn a_geo_drill_sends_its_claim_mode_and_city() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
        )]);
        let mut params = GeoDrillParams::new(GeoDrillTarget::Country {
            country: "DE".to_string(),
            city: Some("Berlin".to_string()),
        });
        params.mode = Some("billing".to_string());
        client.analytics().geo_transactions(&params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/geo/transactions\
             ?mode=billing&target_country=DE&target_city=Berlin"
        );
    }

    /// The channel target is the one device target that takes a bucket, and
    /// the bucket has to reach the wire under its own key.
    #[tokio::test]
    async fn a_device_channel_drill_sends_the_channel_and_its_bucket() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
        )]);
        let params = DeviceDrillParams::new(DeviceDrillTarget::Channel {
            channel: AnalyticsChannel::Embedded,
            bucket: Some("2026-03-12".to_string()),
        });
        client
            .analytics()
            .device_transactions(&params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/devices/transactions\
             ?target_channel=embedded&target_bucket=2026-03-12"
        );
    }

    /// The time-to-pay bar keeps its wire token: the labels are a fixed
    /// vocabulary the histogram is drawn from, not free text.
    #[tokio::test]
    async fn a_time_to_pay_drill_sends_the_bar_token() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
        )]);
        let params = DeviceDrillParams::new(DeviceDrillTarget::TimeToPayBucket(
            TimeToPayBucket::FiveToFifteenMinutes,
        ));
        client
            .analytics()
            .device_transactions(&params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/devices/transactions?target_ttp_bucket=m5_15"
        );
    }

    /// Sub-hour buckets reach the wire as the series' own tokens.
    #[tokio::test]
    async fn the_scope_series_takes_a_sub_hour_grain() {
        let (client, mock) = client_with(vec![Step::ok("{}")]);
        let params = AnalyticsScopeParams {
            days: Some(7),
            granularity: Some(AnalyticsGranularity::FiveMinutes),
            ..AnalyticsScopeParams::default()
        };
        client.analytics().scope(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/scope?days=7&granularity=5m"
        );
    }

    /// The two client dashboards send the same window and are told apart only
    /// by their path and, on geo, the claim mode.
    #[tokio::test]
    async fn devices_and_geo_share_a_window_shape() {
        let (client, mock) = client_with(vec![Step::ok("{}"), Step::ok("{}")]);
        let params = ClientAnalyticsParams {
            days: Some(30),
            granularity: Some(ClientAnalyticsGranularity::Hour),
            sections: Some("totals,children".to_string()),
            device_class: Some("phone".to_string()),
            ..ClientAnalyticsParams::default()
        };
        client.analytics().devices(Some(&params)).await.unwrap();
        client.analytics().geo(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/devices\
             ?days=30&granularity=hour&sections=totals,children&device_class=phone"
        );
        assert!(
            seen[1]
                .url
                .starts_with("https://api.test/analytics/geo?days=30")
        );
    }

    /// The subscription dashboard sends no granularity at all — the endpoint
    /// rejects anything but day, so offering the field would only let a caller
    /// build a request the server refuses.
    #[tokio::test]
    async fn subscription_analytics_sends_its_window_without_a_grain() {
        let (client, mock) = client_with(vec![Step::ok("{}")]);
        let params = SubscriptionAnalyticsParams {
            days: Some(92),
            sections: Some("totals,movement".to_string()),
            country: Some("DE".to_string()),
            ..SubscriptionAnalyticsParams::default()
        };
        client
            .analytics()
            .subscriptions(Some(&params))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/analytics/subscriptions\
             ?days=92&sections=totals,movement&country=DE"
        );
    }
}