delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
//! Routing models: routing-configuration records, the routing dictionary,
//! per-profile defaults, connector restrictions and surcharge programs.
//!
//! [`MethodSurcharge`] and [`PerMethodSurchargeItem`] live here rather than in
//! `resources` because they appear on both the request and the response side,
//! and the response side must stay available in the
//! `default-features = false` build.
//!
//! Routing *algorithm* bodies stay raw JSON: they are an adjacently-tagged
//! `{type, data}` union whose `advanced` arm carries a full Euclid program,
//! and the typed builder for that tree is client-gated.

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

/// What a routing algorithm applies to, e.g. `"payment"`, `"payout"`,
/// `"three_ds_authentication"`. Open vocabulary — kept as a string so a new
/// backend value cannot break deserialization.
pub type TransactionType = String;

/// A connector the router may pick.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutableConnectorChoice {
    /// Connector name, e.g. `"stripe"`.
    pub connector: String,
    /// The specific merchant connector account to use, when pinned.
    #[serde(default)]
    pub merchant_connector_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Metadata for one routing configuration, as returned by create, activate,
/// deactivate and the list endpoints. Carries no algorithm body — use the
/// retrieve endpoint for that.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingDictionaryRecord {
    /// Unique routing configuration ID.
    pub id: String,
    /// Shop (business profile) the configuration belongs to.
    pub profile_id: String,
    /// Human-readable name.
    pub name: String,
    /// Algorithm kind, e.g. `"single"`, `"priority"`, `"advanced"`.
    pub kind: String,
    /// Longer description of what the configuration does.
    #[serde(default)]
    pub description: Option<String>,
    /// Creation time, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: Option<i64>,
    /// Last-modified time, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub modified_at: Option<i64>,
    /// Transaction type the configuration applies to, or `None` when it
    /// applies to all of them.
    #[serde(default)]
    pub algorithm_for: Option<TransactionType>,
    /// Decision-engine ID, on backends that mirror configs into it.
    #[serde(default)]
    pub decision_engine_routing_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A full routing configuration, including the algorithm body.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MerchantRoutingAlgorithm {
    /// Unique routing configuration ID.
    pub id: String,
    /// Shop (business profile) the configuration belongs to.
    pub profile_id: String,
    /// Human-readable name.
    pub name: String,
    /// The routing algorithm — an adjacently-tagged `{type, data}` object
    /// (`single`, `priority`, `volume_split`, `advanced`,
    /// `three_ds_decision_rule`). Raw JSON on purpose; see the module docs.
    pub algorithm: Value,

    /// Longer description of what the configuration does.
    #[serde(default)]
    pub description: Option<String>,
    /// Creation time, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub created_at: Option<i64>,
    /// Last-modified time, in milliseconds since the Unix epoch.
    #[serde(default)]
    pub modified_at: Option<i64>,
    /// Transaction type the configuration applies to.
    #[serde(default)]
    pub algorithm_for: Option<TransactionType>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Every routing configuration for a merchant, plus which one is active.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingDictionary {
    /// Merchant account the dictionary belongs to.
    pub merchant_id: String,
    /// The currently active configuration, or `None` when routing falls back
    /// to the default.
    #[serde(default)]
    pub active_id: Option<String>,
    /// The configuration records.
    #[serde(default = "Vec::new")]
    pub records: Vec<RoutingDictionaryRecord>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The active routing configuration wrapped in its `{ "algorithm": … }`
/// envelope, as merchant-account-based backends return it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ActiveRoutingAlgorithm {
    /// The active configuration, or `None` when none is set.
    #[serde(default)]
    pub algorithm: Option<MerchantRoutingAlgorithm>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What the active-routing endpoint returns: either the merchant-account
/// envelope, or a list of profile-based records.
///
/// Untagged: an object decodes as [`Envelope`](Self::Envelope), a JSON array
/// as [`Records`](Self::Records).
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ActiveRoutingConfig {
    /// Merchant-account-based backends: `{ "algorithm": … }`.
    ///
    /// Boxed: the envelope carries a full routing configuration and is an
    /// order of magnitude larger than the other variant.
    Envelope(Box<ActiveRoutingAlgorithm>),
    /// Profile-based backends: an array of configuration records.
    Records(Vec<RoutingDictionaryRecord>),
}

/// Per-profile default fallback routing.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProfileDefaultRoutingConfig {
    /// Shop (business profile) the defaults belong to.
    pub profile_id: String,
    /// Connectors tried, in order, when no algorithm matches.
    #[serde(default = "Vec::new")]
    pub connectors: Vec<RoutableConnectorChoice>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What the default-profile-routing endpoint returns: either a flat connector
/// list (merchant-wide default) or one entry per profile.
///
/// Untagged, and the per-profile arm is tried first because its entries carry
/// a required `profile_id` that a bare connector choice does not. An empty
/// array therefore decodes as an empty
/// [`PerProfile`](Self::PerProfile).
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum DefaultProfileRouting {
    /// One default configuration per shop.
    PerProfile(Vec<ProfileDefaultRoutingConfig>),
    /// A merchant-wide ordered connector list.
    Connectors(Vec<RoutableConnectorChoice>),
}

/// One connector account's lifetime payment cap for a shop.
///
/// The cap is per *account*, not per acquirer: a shop with two Stripe accounts
/// has two of these, and a cap on one is not spent by the other.
///
/// Both counters are read-only. They are serialized on a write because this is
/// one type for both directions, and the server ignores them there.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RoutingConnectorCap {
    /// The connector account the cap applies to.
    pub merchant_connector_id: String,
    /// How many successful payments this account may take for this shop, ever.
    ///
    /// `1` is the acquirer-onboarding case: one live transaction to trigger the
    /// review, after which routing stops selecting it. `0` means never route
    /// here.
    pub limit: i64,
    /// How many successful payments it has taken so far. Read-only.
    ///
    /// `None` means the count could not be read, **not** that nothing has been
    /// taken — a cap that may already have fired is reported as unknown rather
    /// than as untouched. Counts completed payments, not payments in progress.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub used: Option<i64>,
    /// How much of the cap is held by payments still in flight. Read-only.
    ///
    /// Selection stops once `used + reserved` reaches `limit`, so a cap can be
    /// closed to new payments while `used` is still below it — that is a
    /// checkout in progress, and the capacity returns if it never completes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reserved: Option<i64>,
    /// What `limit`, `used` and `reserved` count: `"payments"` (the default
    /// when `None`) or `"amount"`. A shop may list one account twice, once
    /// per unit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    /// How often the counter starts again, in UTC: `"lifetime"` (the default
    /// when `None`), `"daily"`, `"weekly"` or `"monthly"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub window: Option<String>,
    /// The currency of an `"amount"` cap; required exactly then.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    /// The top of a range: each window's limit is drawn from
    /// `limit..=limit_max`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit_max: Option<i64>,
    /// The limit enforced in the window open now. Read-only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_limit: Option<i64>,
    /// Who chose `current_limit` for a range: `"reset"` or `"manual"`.
    /// Read-only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_limit_source: Option<String>,
    /// When `current_limit` was chosen for a range. Read-only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_limit_drawn_at: Option<String>,
    /// Hold this value as the limit for the rest of the window open now; the
    /// next reset draws from the range again. Write-only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub set_current_limit: Option<i64>,
    /// How a ranged limit's value is drawn.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub distribution: Option<ConnectorCapDistribution>,
    /// The range and distribution `current_limit` was drawn from. Read-only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_limit_drawn_from: Option<ConnectorCapDrawnFrom>,
    /// Any additional response fields not modeled above.
    #[serde(flatten, default)]
    pub extra: serde_json::Map<String, Value>,
}

/// How a ranged connector cap's value is drawn, in the cap's own unit.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCapDistribution {
    /// `"uniform"`, `"normal"`, `"triangular"` or `"weighted"`.
    pub kind: String,
    /// `"normal"`: the centre of the curve.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mean: Option<i64>,
    /// `"normal"`: the standard deviation, above 0.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub std_dev: Option<i64>,
    /// `"triangular"`: the most likely value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<i64>,
    /// `"weighted"`: the bands to draw from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bands: Option<Vec<ConnectorCapBand>>,
    /// Any additional fields not modeled above.
    #[serde(flatten, default)]
    pub extra: serde_json::Map<String, Value>,
}

impl ConnectorCapDistribution {
    /// A uniform draw over the range.
    #[must_use]
    pub fn uniform() -> Self {
        Self {
            kind: "uniform".to_string(),
            ..Default::default()
        }
    }

    /// A normal draw around `mean`.
    #[must_use]
    pub fn normal(mean: i64, std_dev: i64) -> Self {
        Self {
            kind: "normal".to_string(),
            mean: Some(mean),
            std_dev: Some(std_dev),
            ..Default::default()
        }
    }

    /// A triangular draw peaking at `mode`.
    #[must_use]
    pub fn triangular(mode: i64) -> Self {
        Self {
            kind: "triangular".to_string(),
            mode: Some(mode),
            ..Default::default()
        }
    }

    /// A weighted draw over `bands`.
    #[must_use]
    pub fn weighted(bands: Vec<ConnectorCapBand>) -> Self {
        Self {
            kind: "weighted".to_string(),
            bands: Some(bands),
            ..Default::default()
        }
    }
}

/// One band of a weighted connector cap distribution.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCapBand {
    /// The lowest value in the band, included.
    pub min: i64,
    /// The highest value in the band, included.
    pub max: i64,
    /// How likely the band is relative to the others, 1 to 1,000,000.
    pub weight: i32,
}

impl ConnectorCapBand {
    /// A band from `min` to `max` with `weight`.
    #[must_use]
    pub fn new(min: i64, max: i64, weight: i32) -> Self {
        Self { min, max, weight }
    }
}

/// The range and distribution a cap's current limit was drawn from.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCapDrawnFrom {
    /// The bottom of the range.
    pub limit: i64,
    /// The top of the range.
    pub limit_max: i64,
    /// The distribution of the draw.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub distribution: Option<ConnectorCapDistribution>,
    /// Any additional fields not modeled above.
    #[serde(flatten, default)]
    pub extra: serde_json::Map<String, Value>,
}

/// One connector account's per-payment amount range for a shop.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RoutingConnectorPaymentRange {
    /// The connector account the range applies to.
    pub merchant_connector_id: String,
    /// The currency `min_amount` and `max_amount` are written in.
    pub currency: String,
    /// The smallest amount a payment may have, in minor units, included.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_amount: Option<i64>,
    /// The largest amount a payment may have, in minor units, included.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_amount: Option<i64>,
    /// Any additional fields not modeled above.
    #[serde(flatten, default)]
    pub extra: serde_json::Map<String, Value>,
}

impl RoutingConnectorPaymentRange {
    /// A range for one account, in `currency`; set the bounds you need.
    #[must_use]
    pub fn new(merchant_connector_id: impl Into<String>, currency: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            currency: currency.into(),
            min_amount: None,
            max_amount: None,
            extra: serde_json::Map::new(),
        }
    }
}

impl RoutingConnectorCap {
    /// A cap of `limit` successful payments on one connector account.
    #[must_use]
    pub fn new(merchant_connector_id: impl Into<String>, limit: i64) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            limit,
            used: None,
            reserved: None,
            unit: None,
            window: None,
            currency: None,
            limit_max: None,
            current_limit: None,
            current_limit_source: None,
            current_limit_drawn_at: None,
            set_current_limit: None,
            distribution: None,
            current_limit_drawn_from: None,
            extra: serde_json::Map::new(),
        }
    }

    /// A cap on the amount this account may take per `window`, in minor
    /// units of `currency`.
    #[must_use]
    pub fn amount(
        merchant_connector_id: impl Into<String>,
        limit: i64,
        currency: impl Into<String>,
        window: impl Into<String>,
    ) -> Self {
        let mut cap = Self::new(merchant_connector_id, limit);
        cap.unit = Some("amount".to_string());
        cap.currency = Some(currency.into());
        cap.window = Some(window.into());
        cap
    }

    /// Count per `window` (`"daily"`, `"weekly"`, `"monthly"`) rather than
    /// for the account's lifetime.
    #[must_use]
    pub fn window(mut self, window: impl Into<String>) -> Self {
        self.window = Some(window.into());
        self
    }

    /// Draw each window's limit from `limit..=limit_max`.
    #[must_use]
    pub fn limit_max(mut self, limit_max: i64) -> Self {
        self.limit_max = Some(limit_max);
        self
    }

    /// How a ranged limit is drawn.
    #[must_use]
    pub fn distribution(mut self, distribution: ConnectorCapDistribution) -> Self {
        self.distribution = Some(distribution);
        self
    }

    /// Hold this limit for the rest of the window open now.
    #[must_use]
    pub fn set_current_limit(mut self, limit: i64) -> Self {
        self.set_current_limit = Some(limit);
        self
    }

    /// Whether the cap can still take a payment.
    ///
    /// `None` when `used` is absent: the count could not be read, so whether
    /// capacity remains is unknown and must not be guessed at as `true`.
    /// Measured against [`current_limit`](Self::current_limit) when the API
    /// reports one (a ranged limit's draw for the window open now), else
    /// against `limit`.
    #[must_use]
    pub fn has_capacity(&self) -> Option<bool> {
        let used = self.used?;
        let limit = self.current_limit.unwrap_or(self.limit);
        Some(used + self.reserved.unwrap_or(0) < limit)
    }
}

/// A shop's connector caps.
///
/// Whole-set replacement on a write: the list sent becomes the complete set of
/// capped connector accounts, and an empty list clears them all — which is how
/// acquirer onboarding finishes, the new account ceasing to be a special case.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RoutingConnectorCaps {
    /// The shop these caps belong to. Ignored in a request body — the path
    /// names the shop.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Every capped connector account.
    #[serde(default = "Vec::new")]
    pub caps: Vec<RoutingConnectorCap>,
    /// The limits enforced now, scheduled overrides included. Read-only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_caps: Option<Vec<RoutingConnectorCap>>,
    /// Accounts with schedule history. Read-only.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scheduled_account_ids: Vec<String>,
    /// What this router can store, e.g. `"dual_limits"`, `"limit_ranges"` or
    /// `"payment_ranges"`. On reads only: a router that does not list a
    /// feature drops what it would carry without an error.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<String>,
    /// Each account's per-payment amount range. `None` on a write keeps the
    /// stored ranges; a list replaces them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payment_ranges: Option<Vec<RoutingConnectorPaymentRange>>,
    /// Any additional response fields not modeled above.
    #[serde(flatten, default)]
    pub extra: serde_json::Map<String, Value>,
}

impl RoutingConnectorCaps {
    /// The set of caps to send to a shop.
    #[must_use]
    pub fn new(caps: Vec<RoutingConnectorCap>) -> Self {
        Self {
            profile_id: None,
            caps,
            active_caps: None,
            scheduled_account_ids: Vec::new(),
            features: Vec::new(),
            payment_ranges: None,
            extra: serde_json::Map::new(),
        }
    }

    /// Replace the stored per-payment amount ranges with `ranges`.
    #[must_use]
    pub fn payment_ranges(mut self, ranges: Vec<RoutingConnectorPaymentRange>) -> Self {
        self.payment_ranges = Some(ranges);
        self
    }
}

/// One content window in a routing configuration's history.
///
/// A configuration's rule can be edited in place, so "which rule decided this
/// payment" is only answerable because every past version of its content is
/// kept. Each entry is the content the configuration had between `valid_from`
/// and `valid_until`; the live entry carries no `valid_until`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingConfigVersion {
    /// 1-based position in the configuration's timeline, oldest first.
    pub version: i32,
    /// Name the configuration had during this window.
    pub name: String,
    /// Description the configuration had during this window.
    ///
    /// A `String` rather than an `Option`, unlike the two sibling models here:
    /// the backend builds this field with `unwrap_or_default()` on every path,
    /// and the spec marks it required and non-nullable, so a configuration
    /// with no description sends `""` rather than `null` or nothing. Modelling
    /// it as optional would invent a state the contract does not have.
    ///
    /// `serde(default)` covers only the absent case — cheap insurance against
    /// a future spec that stops marking it required, and it degrades one field
    /// to empty instead of failing a whole page of history.
    #[serde(default)]
    pub description: String,
    /// Which routing form this window used.
    pub kind: String,
    /// The rule as it stood during this window. Open shape, as elsewhere in
    /// this module.
    pub algorithm: Value,
    /// When this content took effect, seconds since the epoch.
    pub valid_from: i64,
    /// When this content was replaced, seconds since the epoch — absent while
    /// it is still the live rule.
    #[serde(default)]
    pub valid_until: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl RoutingConfigVersion {
    /// Whether this is the window currently in force.
    #[must_use]
    pub fn is_live(&self) -> bool {
        self.valid_until.is_none()
    }
}

/// One page of a routing configuration's timeline, oldest first.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingConfigHistoryResponse {
    /// The configuration this history belongs to.
    pub id: String,
    /// Shop the configuration belongs to.
    pub profile_id: String,
    /// One page of content windows, oldest first.
    ///
    /// Paging runs over the whole timeline with the live window as its last
    /// element, so the live window appears on exactly one page. A page past the
    /// end is empty. A configuration never edited has exactly one entry.
    #[serde(default = "Vec::new")]
    pub versions: Vec<RoutingConfigVersion>,
    /// How long the whole timeline is, so a caller can compute the last page
    /// instead of paging until a response comes back empty.
    pub total_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A buyer-facing surcharge added to the checkout amount: either a flat amount
/// in minor currency units, or a percentage of the order amount.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MethodSurcharge {
    /// A flat surcharge, in minor currency units. **Signed**: a negative
    /// amount credits the buyer rather than charging them.
    #[serde(rename = "fixed")]
    Fixed {
        /// The surcharge amount, in minor units. Negative for a discount.
        amount: i64,
    },
    /// A surcharge expressed as a percentage of the order amount. **Signed**:
    /// a negative percentage credits the buyer.
    #[serde(rename = "rate")]
    Rate {
        /// The surcharge percentage, e.g. `1.0` for 1%. Negative for a
        /// discount.
        percent: f64,
    },
}

/// One per-payment-method surcharge entry, on both the request and the
/// response side of a surcharge program.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PerMethodSurchargeItem {
    /// Payment method family, e.g. `"card"`, `"crypto"`, `"wallet"`.
    ///
    /// Optional since a rule may scope on the *provider* instead: a surcharge
    /// tracks what the processor costs the merchant, so "Stripe, any method"
    /// is as expressible as "card, any provider". An entry that names neither
    /// applies to everything the program covers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payment_method: Option<String>,
    /// Optional finer scope, e.g. a specific wallet or crypto. Not valid for
    /// cards — use [`card_network`](Self::card_network) instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payment_method_type: Option<String>,
    /// Optional card-network scope (cards only), e.g. `"Visa"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub card_network: Option<String>,
    /// Optional connector (brand) scope, e.g. `"stripe"` — every account of
    /// that processor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub connector: Option<String>,
    /// Optional connector *account* scope: one stored account of one
    /// processor, narrower than [`connector`](Self::connector).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merchant_connector_id: Option<String>,
    /// Extra conditions on the payment itself. They AND with the entry's
    /// scope and with each other.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub conditions: Vec<SurchargeCondition>,
    /// The surcharge to apply. Signed — see [`MethodSurcharge`].
    pub surcharge: MethodSurcharge,
    /// Optional tax on the surcharge, as a percentage of the surcharge amount.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tax_on_surcharge_percent: Option<f64>,
}

impl PerMethodSurchargeItem {
    /// An entry surcharging one payment method family.
    pub fn new(payment_method: impl Into<String>, surcharge: MethodSurcharge) -> Self {
        Self {
            payment_method: Some(payment_method.into()),
            payment_method_type: None,
            card_network: None,
            connector: None,
            merchant_connector_id: None,
            conditions: Vec::new(),
            surcharge,
            tax_on_surcharge_percent: None,
        }
    }

    /// An entry surcharging every payment made through one connector (brand),
    /// whatever the payment method.
    pub fn for_connector(connector: impl Into<String>, surcharge: MethodSurcharge) -> Self {
        Self {
            payment_method: None,
            payment_method_type: None,
            card_network: None,
            connector: Some(connector.into()),
            merchant_connector_id: None,
            conditions: Vec::new(),
            surcharge,
            tax_on_surcharge_percent: None,
        }
    }

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

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

    /// Add one condition on the payment itself. Conditions AND with the
    /// entry's scope and with each other.
    #[must_use]
    pub fn condition(mut self, condition: SurchargeCondition) -> Self {
        self.conditions.push(condition);
        self
    }

    /// Replace the entry's conditions.
    #[must_use]
    pub fn conditions(mut self, conditions: Vec<SurchargeCondition>) -> Self {
        self.conditions = conditions;
        self
    }

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

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

    /// Tax the surcharge at this percentage of the surcharge amount.
    #[must_use]
    pub fn tax_on_surcharge_percent(mut self, percent: f64) -> Self {
        self.tax_on_surcharge_percent = Some(percent);
        self
    }
}

/// One condition on the payment itself, ANDed with a surcharge entry's scope.
///
/// The same sources and operators the checkout's custom fields already use.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "source", rename_all = "snake_case")]
#[non_exhaustive]
pub enum SurchargeCondition {
    /// Compare one key of the payment's own metadata.
    Metadata {
        /// The metadata key to read.
        key: String,
        /// `"equals"` or `"not_equals"`.
        operator: String,
        /// The value to compare against, as a string.
        value: String,
    },
    /// Compare the payment's currency.
    Currency {
        /// `"equals"`, `"not_equals"`, `"in"` or `"not_in"`. The list forms
        /// take a comma-separated `value`.
        operator: String,
        /// The currency (or comma-separated currencies) to compare against.
        value: String,
    },
    /// Compare the payment's amount, in minor units.
    Amount {
        /// `"equals"`, `"not_equals"`, `"greater_than"`,
        /// `"greater_than_or_equal"`, `"less_than"` or `"less_than_or_equal"`.
        operator: String,
        /// The amount to compare against, in minor units, as a string.
        value: String,
    },
}

impl SurchargeCondition {
    /// A condition on one metadata key: `operator` is `"equals"` or
    /// `"not_equals"`.
    pub fn metadata(
        key: impl Into<String>,
        operator: impl Into<String>,
        value: impl Into<String>,
    ) -> Self {
        Self::Metadata {
            key: key.into(),
            operator: operator.into(),
            value: value.into(),
        }
    }

    /// A condition on the payment currency.
    pub fn currency(operator: impl Into<String>, value: impl Into<String>) -> Self {
        Self::Currency {
            operator: operator.into(),
            value: value.into(),
        }
    }

    /// A condition on the payment amount, in minor units.
    pub fn amount(operator: impl Into<String>, value: impl Into<String>) -> Self {
        Self::Amount {
            operator: operator.into(),
            value: value.into(),
        }
    }
}

/// Whether an adjustment adds to or takes off the buyer's total:
/// `"surcharge"` or `"discount"`.
///
/// Carried separately from the magnitude because the router's percentage type
/// is unsigned by construction and persisted. Absent reads as `"surcharge"`.
pub type SurchargeDirection = String;

/// The live `routing_volume` counters behind a shop's active advanced program.
///
/// This answers "what will routing compare against right now", **not** "what
/// did the shop turn over". The counters live in Redis only: a lost Redis
/// restarts a window at zero.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingVolumeCounters {
    /// The shop the counters belong to.
    pub profile_id: String,
    /// The active advanced program that reads them, when there is one.
    #[serde(default)]
    pub routing_algorithm_id: Option<String>,
    /// When the counters were read (RFC 3339).
    #[serde(default)]
    pub read_at: Option<String>,
    /// One entry per distinct budget the program reads.
    #[serde(default = "Vec::new")]
    pub counters: Vec<RoutingVolumeCounter>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One budget a routing program compares against.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingVolumeCounter {
    /// The window this counter covers: `"monthly"`, `"weekly"`, `"daily"`,
    /// `"rolling_7d"` or `"rolling_30d"`.
    ///
    /// `"weekly"` is the ISO week (Monday-based, UTC). The two rolling windows
    /// are the last 7 or 30 UTC days including today, and their history begins
    /// with the backend release that introduced them — so for 30 days after it
    /// a `"rolling_30d"` figure is a lower bound.
    pub window: String,
    /// `"profile"` (one shared counter per shop) or `"payment_method"` (an
    /// independent budget per method).
    pub scope: String,
    /// Under `"payment_method"` scope, the method this counter belongs to.
    /// Only methods that have charged something appear at all; a missing
    /// method is at zero.
    #[serde(default)]
    pub payment_method: Option<String>,
    /// Start of the window (RFC 3339, UTC, half-open with `window_end`).
    #[serde(default)]
    pub window_start: Option<String>,
    /// End of the window (RFC 3339, UTC, exclusive).
    #[serde(default)]
    pub window_end: Option<String>,
    /// The stored figure, in USD.
    #[serde(default)]
    pub amount_usd: Option<f64>,
    /// The currency the program pinned its thresholds to, when it pinned one.
    #[serde(default)]
    pub threshold_currency: Option<String>,
    /// The figure in the pinned threshold currency at the current rate.
    /// **Absent, never zero**, when no currency is pinned or no rate is usable.
    #[serde(default)]
    pub amount_in_threshold_currency: Option<f64>,
    /// The names of the rules that read this counter.
    #[serde(default = "Vec::new")]
    pub rules: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The outcome of soft-deleting a static routing configuration.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingConfigDeleteResponse {
    /// The configuration that was deleted.
    pub id: String,
    /// The shop it belonged to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Whether it is now deleted.
    #[serde(default)]
    pub deleted: Option<bool>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A stored surcharge program: the structured configuration plus its version
/// metadata and any server-side advisories.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SurchargeRuleResponse {
    /// Human-readable program name.
    pub name: String,
    /// Version number of the stored program; bumped on every upsert.
    pub version: i64,

    /// Shop (business profile) the program is scoped to, or `None` when it is
    /// merchant-wide.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Per-method surcharges, evaluated top-to-bottom (first match wins).
    #[serde(default)]
    pub surcharges: Option<Vec<PerMethodSurchargeItem>>,
    /// Applied when no per-method entry matches.
    #[serde(default)]
    pub default_surcharge: Option<MethodSurcharge>,
    /// Whether the checkout shows a surcharge breakup screen.
    #[serde(default)]
    pub show_surcharge_breakup_screen: Option<bool>,
    /// RFC 3339 timestamp the program takes effect from.
    #[serde(default)]
    pub valid_from: Option<String>,
    /// RFC 3339 timestamp the program expires at, or `None` when open-ended.
    #[serde(default)]
    pub valid_until: Option<String>,
    /// Non-blocking advisories about the saved program, e.g. a network-scoped
    /// card surcharge that a connector cannot apply. Empty when there are
    /// none.
    #[serde(default = "Vec::new")]
    pub warnings: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A shop's complete dated limit schedule. Gaps between entries use the
/// ordinary configured caps.
///
/// Used on both sides of the schedule endpoints: read one, change its
/// entries, and send it back. `revision` is always sent — `null` when creating
/// the first schedule — so a write over a newer schedule is refused.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RoutingConnectorCapSchedule {
    /// The last-read revision, for optimistic concurrency; `None` when
    /// creating the first schedule.
    #[serde(default)]
    pub revision: Option<String>,
    /// Every entry. A complete replacement on a write: remove an entry to
    /// cancel it.
    #[serde(default = "Vec::new")]
    pub entries: Vec<RoutingConnectorCapScheduleEntry>,
    /// The schedule's timezone, returned by the server. Ignored on a write.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    /// The server's observation instant, returned on reads.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed_at: Option<String>,
    /// The next activation or expiry instant; `None` when nothing changes
    /// next.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_change_at: Option<String>,
    /// Any additional fields not modeled above.
    #[serde(flatten, default)]
    pub extra: serde_json::Map<String, Value>,
}

impl RoutingConnectorCapSchedule {
    /// A schedule to write over `revision` (`None` for the first one).
    #[must_use]
    pub fn new(revision: Option<String>, entries: Vec<RoutingConnectorCapScheduleEntry>) -> Self {
        Self {
            revision,
            entries,
            timezone: None,
            observed_at: None,
            next_change_at: None,
            extra: serde_json::Map::new(),
        }
    }
}

/// One dated limit for an account and unit, applied without restarting usage.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RoutingConnectorCapScheduleEntry {
    /// Stable UUID; keep it when editing an entry.
    pub id: String,
    /// Inclusive activation instant, RFC 3339 with an explicit UTC offset or
    /// `Z`.
    pub starts_at: String,
    /// Exclusive expiry instant, RFC 3339 with an explicit UTC offset or `Z`.
    pub ends_at: String,
    /// The scheduled limit.
    pub cap: RoutingConnectorCap,
    /// Any additional fields not modeled above.
    #[serde(flatten, default)]
    pub extra: serde_json::Map<String, Value>,
}

impl RoutingConnectorCapScheduleEntry {
    /// An entry applying `cap` from `starts_at` (inclusive) to `ends_at`
    /// (exclusive).
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        starts_at: impl Into<String>,
        ends_at: impl Into<String>,
        cap: RoutingConnectorCap,
    ) -> Self {
        Self {
            id: id.into(),
            starts_at: starts_at.into(),
            ends_at: ends_at.into(),
            cap,
            extra: serde_json::Map::new(),
        }
    }
}

/// What resetting one limit's usage cleared.
///
/// What settled payments spent stops counting; what payments still in flight
/// hold keeps counting.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingConnectorCapReset {
    /// The connector account.
    pub merchant_connector_id: String,
    /// `"payments"` or `"amount"`.
    pub unit: String,
    /// The limit's window.
    pub window: String,
    /// The budget's currency, for an amount limit.
    #[serde(default)]
    pub currency: Option<String>,
    /// The usage cleared, in `unit`; `None` when it could not be added up.
    #[serde(default)]
    pub cleared: Option<i64>,
    /// Usage held by payments in flight, in `unit`. The reset keeps it.
    #[serde(default)]
    pub reserved: Option<i64>,
    /// ISO 8601 time the reset took effect.
    pub reset_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A connector account's limits overridden for one project or shop.
///
/// The most specific one applies: the shop's own, else the nearest project's
/// above the shop, else the account's limits.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCapOverride {
    /// The connector account.
    pub merchant_connector_id: String,
    /// `"project"` or `"shop"`.
    pub level: String,
    /// The project id, or the shop's profile id.
    pub scope_id: String,
    /// The project's or shop's name, when it still exists.
    #[serde(default)]
    pub scope_name: Option<String>,
    /// `"unlimited"` or `"own"`.
    pub mode: String,
    /// The `own` limits; empty for `unlimited`.
    #[serde(default = "Vec::new")]
    pub caps: Vec<RoutingConnectorCap>,
    /// ISO 8601 time of the last change.
    pub modified_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Every connector cap override of the merchant.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCapOverrideList {
    /// The overrides.
    #[serde(default = "Vec::new")]
    pub overrides: Vec<ConnectorCapOverride>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One connector account's overrides, and the limits each shop it serves
/// applies.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCapOverrides {
    /// The connector account.
    pub merchant_connector_id: String,
    /// The scope the account's own limits are kept under.
    pub account_scope: String,
    /// The account's overrides.
    #[serde(default = "Vec::new")]
    pub overrides: Vec<ConnectorCapOverride>,
    /// Every shop the account takes payments in, with the limits it applies.
    #[serde(default = "Vec::new")]
    pub shops: Vec<ConnectorCapShopLimit>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The limits one shop applies to a connector account, and where they come
/// from.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCapShopLimit {
    /// The shop (business profile).
    pub profile_id: String,
    /// The shop's name.
    #[serde(default)]
    pub profile_name: Option<String>,
    /// `"account"`, `"project"` or `"shop"`.
    pub source: String,
    /// The project or shop whose override applies; absent for `account`.
    #[serde(default)]
    pub source_id: Option<String>,
    /// The override's mode; absent when the account's limits apply.
    #[serde(default)]
    pub mode: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A stored checkout theme program: which of a shop's appearance variants a
/// buyer is shown.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct CheckoutThemeProgramResponse {
    /// The program's id.
    pub id: String,
    /// The program's name.
    pub name: String,
    /// The scope the program is stored against, resolved. Absent is not the
    /// same as merchant-wide: the field is optional on the wire.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// The program as stored: rules run top-down, first match wins, with a
    /// default selection as the fallback.
    #[serde(default)]
    pub algorithm: Value,
    /// The stored revision.
    pub version: i32,
    /// Whether this revision is the live one.
    pub is_active: bool,
    /// RFC 3339 start of validity.
    pub valid_from: String,
    /// RFC 3339 end of validity; `None` when open-ended.
    #[serde(default)]
    pub valid_until: Option<String>,
    /// Non-blocking advisories, recomputed on every read — e.g. a rule naming
    /// a variant the shop has not defined. Empty when none.
    #[serde(default = "Vec::new")]
    pub warnings: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Rendered-to-paid checkout conversion, per appearance variant and segment.
///
/// Rates, intervals, verdicts and the variant-vs-default test are computed
/// server-side: render them, do not recompute them.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct CheckoutThemeConversionResponse {
    /// The dimension the cells are grouped by: `"none"`, `"device"`,
    /// `"country"` or `"hour"`.
    pub segment: String,
    /// The filters applied.
    pub filters: CheckoutThemeConversionFilters,
    /// One cell per variant and segment.
    #[serde(default = "Vec::new")]
    pub cells: Vec<CheckoutThemeConversionCell>,
    /// Every named variant measured against the shop default in its own
    /// bucket.
    #[serde(default = "Vec::new")]
    pub comparisons: Vec<CheckoutThemeConversionComparison>,
    /// What the denominator counts, e.g. `"deduplicated_checkout_opens"`.
    pub denominator: String,
    /// Codes for the known ways this result is not the whole truth. Render
    /// nothing for a code you do not know.
    #[serde(default = "Vec::new")]
    pub caveats: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The filters a conversion report applied.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct CheckoutThemeConversionFilters {
    /// Device class filter.
    #[serde(default)]
    pub device_class: Option<String>,
    /// Country filter, ISO 3166-1 alpha-2.
    #[serde(default)]
    pub country: Option<String>,
    /// How the look was chosen.
    #[serde(default)]
    pub selection: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One cell of a conversion report.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct CheckoutThemeConversionCell {
    /// The variant; `None` for the shop default.
    #[serde(default)]
    pub variant: Option<String>,
    /// The appearance shown.
    #[serde(default)]
    pub appearance: Option<String>,
    /// The segment value.
    #[serde(default)]
    pub segment: Option<String>,
    /// Whether the payments were in test mode; `None` when undeclared.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// Checkout opens counted.
    pub rendered: i64,
    /// Paid checkouts counted.
    pub paid: i64,
    /// Conversion rate; `None` when nothing was rendered.
    #[serde(default)]
    pub rate: Option<f64>,
    /// Lower bound of the interval.
    #[serde(default)]
    pub interval_low: Option<f64>,
    /// Upper bound of the interval.
    #[serde(default)]
    pub interval_high: Option<f64>,
    /// Whether the sample supports a conclusion.
    pub verdict: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A named variant measured against the shop default.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct CheckoutThemeConversionComparison {
    /// The variant.
    pub variant: String,
    /// The segment value.
    #[serde(default)]
    pub segment: Option<String>,
    /// Whether the payments were in test mode; `None` when undeclared.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// The variant's rate.
    #[serde(default)]
    pub variant_rate: Option<f64>,
    /// The default's rate.
    #[serde(default)]
    pub baseline_rate: Option<f64>,
    /// Whether the two are shown to differ. When `false`, say nothing.
    pub separates: bool,
    /// Which side converts better, when they separate.
    #[serde(default)]
    pub higher: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    #[test]
    fn dictionary_decodes_records_and_a_null_active_id() {
        let dict: RoutingDictionary = serde_json::from_str(
            r#"{
                "merchant_id": "merch_1",
                "active_id": null,
                "records": [{
                    "id": "rou_1",
                    "profile_id": "pro_1",
                    "name": "EU Priority",
                    "kind": "priority",
                    "description": "EU traffic",
                    "created_at": 1767225600000,
                    "modified_at": 1767312000000,
                    "algorithm_for": "payment",
                    "brand_new_field": "keep me"
                }]
            }"#,
        )
        .unwrap();

        assert_eq!(dict.active_id, None);
        let record = &dict.records[0];
        assert_eq!(record.kind, "priority");
        // Milliseconds since epoch: an i32 field would overflow here.
        assert_eq!(record.created_at, Some(1_767_225_600_000));
        assert_eq!(record.algorithm_for.as_deref(), Some("payment"));
        assert_eq!(record.extra["brand_new_field"], "keep me");
    }

    #[test]
    fn merchant_routing_algorithm_keeps_the_algorithm_as_raw_json() {
        let algo: MerchantRoutingAlgorithm = serde_json::from_str(
            r#"{
                "id": "rou_1",
                "profile_id": "pro_1",
                "name": "EU Priority",
                "description": "",
                "algorithm": {"type": "priority", "data": [{"connector": "stripe"}]},
                "created_at": 1767225600000,
                "modified_at": 1767225600000,
                "algorithm_for": "payment"
            }"#,
        )
        .unwrap();

        assert_eq!(algo.algorithm["type"], "priority");
        assert_eq!(algo.algorithm["data"][0]["connector"], "stripe");
    }

    #[test]
    fn active_routing_config_distinguishes_the_envelope_from_a_record_list() {
        let envelope: ActiveRoutingConfig = serde_json::from_str(r#"{"algorithm": null}"#).unwrap();
        match envelope {
            ActiveRoutingConfig::Envelope(e) => assert!(e.algorithm.is_none()),
            other => panic!("expected the envelope arm, got {other:?}"),
        }

        let records: ActiveRoutingConfig = serde_json::from_str(
            r#"[{"id":"rou_1","profile_id":"pro_1","name":"n","kind":"single"}]"#,
        )
        .unwrap();
        match records {
            ActiveRoutingConfig::Records(r) => assert_eq!(r[0].id, "rou_1"),
            other => panic!("expected the records arm, got {other:?}"),
        }
    }

    #[test]
    fn default_profile_routing_prefers_the_per_profile_arm() {
        // The two arms are disjoint on their required fields, so a populated
        // array lands on the right one whatever the declaration order — this
        // half of the test guards the field types, not the ordering.
        let per_profile: DefaultProfileRouting = serde_json::from_str(
            r#"[{"profile_id":"pro_1","connectors":[{"connector":"stripe"}]}]"#,
        )
        .unwrap();
        match per_profile {
            DefaultProfileRouting::PerProfile(p) => {
                assert_eq!(p[0].profile_id, "pro_1");
                assert_eq!(p[0].connectors[0].connector, "stripe");
            }
            other => panic!("expected the per-profile arm, got {other:?}"),
        }

        let connectors: DefaultProfileRouting =
            serde_json::from_str(r#"[{"connector":"stripe","merchant_connector_id":"mca_1"}]"#)
                .unwrap();
        match connectors {
            DefaultProfileRouting::Connectors(c) => {
                assert_eq!(c[0].merchant_connector_id.as_deref(), Some("mca_1"));
            }
            other => panic!("expected the connectors arm, got {other:?}"),
        }

        // An empty array matches *both* arms, so it is decided purely by
        // declaration order: swapping the two variants makes this fail.
        let empty: DefaultProfileRouting = serde_json::from_str("[]").unwrap();
        match empty {
            DefaultProfileRouting::PerProfile(p) => assert!(p.is_empty()),
            other => panic!("an empty array must take the per-profile arm, got {other:?}"),
        }
    }

    #[test]
    fn surcharge_rule_response_round_trips_the_surcharge_union() {
        let rule: SurchargeRuleResponse = serde_json::from_str(
            r#"{
                "name": "EU surcharges",
                "profile_id": null,
                "version": 3,
                "valid_from": "2026-01-01T00:00:00Z",
                "valid_until": null,
                "surcharges": [
                    {"payment_method": "crypto", "surcharge": {"rate": {"percent": 1.0}}},
                    {
                        "payment_method": "card",
                        "card_network": "Visa",
                        "surcharge": {"fixed": {"amount": 35}},
                        "tax_on_surcharge_percent": 20.0
                    }
                ],
                "default_surcharge": {"fixed": {"amount": 10}},
                "warnings": ["card network scoping is ignored on stripe"]
            }"#,
        )
        .unwrap();

        assert_eq!(rule.version, 3);
        assert_eq!(rule.profile_id, None);
        let surcharges = rule.surcharges.expect("surcharges decode");
        assert_eq!(
            surcharges[0].surcharge,
            MethodSurcharge::Rate { percent: 1.0 }
        );
        assert_eq!(
            surcharges[1].surcharge,
            MethodSurcharge::Fixed { amount: 35 }
        );
        assert_eq!(surcharges[1].card_network.as_deref(), Some("Visa"));
        assert_eq!(surcharges[1].tax_on_surcharge_percent, Some(20.0));
        assert_eq!(
            rule.default_surcharge,
            Some(MethodSurcharge::Fixed { amount: 10 })
        );
        assert_eq!(rule.warnings.len(), 1);
    }

    #[test]
    fn surcharge_rule_response_defaults_warnings_to_empty() {
        let rule: SurchargeRuleResponse =
            serde_json::from_str(r#"{"name":"n","version":1}"#).unwrap();
        assert!(rule.warnings.is_empty());
        assert_eq!(rule.surcharges, None);
        assert_eq!(rule.valid_from, None);
    }

    /// The surcharge union must serialize externally-tagged: dropping the
    /// `rename` attributes gives `"Fixed"` / `"Rate"` and fails this.
    #[test]
    fn method_surcharge_serializes_with_lowercase_wire_tags() {
        assert_eq!(
            serde_json::to_value(MethodSurcharge::Fixed { amount: 35 }).unwrap(),
            json!({"fixed": {"amount": 35}})
        );
        assert_eq!(
            serde_json::to_value(MethodSurcharge::Rate { percent: 1.5 }).unwrap(),
            json!({"rate": {"percent": 1.5}})
        );
    }

    #[test]
    fn per_method_item_omits_the_scopes_it_was_not_given() {
        let item = PerMethodSurchargeItem::new("crypto", MethodSurcharge::Rate { percent: 1.0 });
        assert_eq!(
            serde_json::to_value(&item).unwrap(),
            json!({"payment_method": "crypto", "surcharge": {"rate": {"percent": 1.0}}})
        );

        let scoped = PerMethodSurchargeItem::new("card", MethodSurcharge::Fixed { amount: 35 })
            .card_network("Visa")
            .payment_method_type("credit")
            .tax_on_surcharge_percent(20.0);
        let value = serde_json::to_value(&scoped).unwrap();
        assert_eq!(value["card_network"], "Visa");
        assert_eq!(value["payment_method_type"], "credit");
        assert_eq!(value["tax_on_surcharge_percent"], 20.0);
    }
}