delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
//! The user / dashboard-auth models: sessions, tokens, team members, roles and
//! two-factor enrolment.
//!
//! # Secrets
//!
//! Much of this surface *returns* credentials: a sign-in mints a bearer token,
//! TOTP enrolment hands back the shared secret and its `otpauth://`
//! provisioning URI, recovery-code generation returns the codes themselves, and
//! adding a team member can echo a server-generated password once. Every
//! response type below that carries one has a **hand-written `Debug`** that
//! redacts it, so `{:?}` on a response — or on anything containing one — can
//! never spill a credential into a log line. Unit tests at the bottom of this
//! file pin that behaviour for each type, including that an *unset* optional
//! secret still renders as `None`.

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

/// Purpose of a single-purpose JWT, e.g. `"totp"`, `"reset_password"`,
/// `"sso"`, `"verify_email"`. A string rather than an enum so a new purpose
/// minted by the API does not break deserialization.
pub type TokenPurpose = String;

/// A top-level permission group recognized by the Delopay API, e.g.
/// `"Operations"`, `"Connectors"`, `"Users"`. A string so new groups do not
/// break deserialization.
pub type ParentGroup = String;

/// A permission scope: `"Read"` allows viewing, `"Write"` is required for any
/// mutation.
pub type PermissionScope = String;

// =====================================================================
// Sign-in / token responses
// =====================================================================

/// The result of any call that establishes or re-establishes a session:
/// sign-up, sign-in, OIDC sign-in, email verification, merchant / shop
/// switching, invitation acceptance and recovery-code redemption.
///
/// Unmodeled fields are preserved in [`extra`](AuthResponse::extra) so new API
/// fields never break deserialization.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct AuthResponse {
    /// Signed session JWT — send it as `Authorization: Bearer <token>`.
    /// Treat it as a credential: anyone holding it *is* the user.
    pub token: String,

    /// Kind of token issued, when the API says so.
    #[serde(default)]
    pub token_type: Option<String>,
    /// Seconds until the token expires, when the API says so.
    #[serde(default)]
    pub expires: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: `token` is a bearer credential — whoever holds it holds the
// session — so it must never reach a log line through `{:?}`. Pinned by
// `auth_response_debug_redacts_the_token`.
impl std::fmt::Debug for AuthResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthResponse")
            .field("token", &"[redacted]")
            .field("token_type", &self.token_type)
            .field("expires", &self.expires)
            .field("extra", &self.extra)
            .finish()
    }
}

/// A freshly minted single-purpose token, returned by the email-token
/// exchange, the two-factor terminate step and employee impersonation.
///
/// [`token_type`](TokenResponse::token_type) tells the client which step of
/// the flow to run next.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct TokenResponse {
    /// Signed JWT — pass as `Authorization: Bearer <token>` on the next call.
    /// Treat it as a credential.
    pub token: String,
    /// Kind of token — tells the client which step to perform next.
    pub token_type: TokenPurpose,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: `token` authorises the next step of a password-reset,
// invitation or impersonation flow and must never reach a log line through
// `{:?}`. Pinned by `token_response_debug_redacts_the_token`.
impl std::fmt::Debug for TokenResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TokenResponse")
            .field("token", &"[redacted]")
            .field("token_type", &self.token_type)
            .field("extra", &self.extra)
            .finish()
    }
}

// =====================================================================
// The user record
// =====================================================================

/// The authenticated user's own details, as returned by the profile,
/// update and password-change endpoints.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserResponse {
    /// Merchant account the session is currently scoped to.
    pub merchant_id: String,
    /// The user's display name.
    pub name: String,
    /// The user's email address.
    pub email: String,
    /// Role the user holds in the current scope.
    pub role_id: String,
    /// Whether the user has completed TOTP enrolment.
    pub is_two_factor_auth_setup: bool,
    /// Shop (business profile) the session is currently scoped to.
    pub profile_id: String,
    /// Lineage level the session is scoped to, e.g. `"merchant"`.
    pub entity_type: String,
    /// Version of the user record's shape.
    pub version: String,

    /// Days left before email verification becomes mandatory.
    #[serde(default)]
    pub verification_days_left: Option<i64>,
    /// Unused recovery codes remaining.
    #[serde(default)]
    pub recovery_codes_left: Option<i64>,
    /// Dashboard theme selected by the user.
    #[serde(default)]
    pub theme_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Login activity and sessions
// =====================================================================

/// One row from the authenticated user's login history.
///
/// `event_type` enumerates the sign-in attempt outcome (`signin_success`,
/// `signin_failure`, `totp_failure`, …) and `failure_reason` is set on failure
/// rows (`invalid_credentials`, `totp_invalid`, …). Both are strings so older
/// rows stay readable as the enums grow.
///
/// The geo fields are populated by a GeoIP lookup at sign-in time. They stay
/// `None` for private / loopback IPs, when the lookup misses, or when GeoIP is
/// not enabled.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct LoginHistoryEntry {
    /// Unique identifier of this history row.
    pub id: String,
    /// Outcome of the sign-in attempt.
    pub event_type: String,
    /// How the attempt authenticated: `"password"`, `"magic_link"`,
    /// `"sso_oidc"`, `"totp"`, `"recovery_code"`.
    pub auth_method: String,
    /// ISO 8601 timestamp the row was inserted (sign-in attempt time).
    pub created_at: String,

    /// Why the attempt failed, on failure rows.
    #[serde(default)]
    pub failure_reason: Option<String>,
    /// Source IP of the attempt.
    #[serde(default)]
    pub ip_address: Option<String>,
    /// `User-Agent` sent by the client.
    #[serde(default)]
    pub user_agent: Option<String>,
    /// Two-letter country code resolved by GeoIP.
    #[serde(default)]
    pub country_code: Option<String>,
    /// City resolved by GeoIP.
    #[serde(default)]
    pub city: Option<String>,
    /// Latitude resolved by GeoIP.
    #[serde(default)]
    pub latitude: Option<f64>,
    /// Longitude resolved by GeoIP.
    #[serde(default)]
    pub longitude: Option<f64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A page of the authenticated user's login history.
///
/// When a Delopay admin is impersonating a merchant the API returns an empty
/// page, so the admin's IP / geo data is not exposed inside the merchant
/// dashboard.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct LoginHistoryResponse {
    /// The rows in this page, newest first.
    pub entries: Vec<LoginHistoryEntry>,
    /// Unpaginated row count, for client-side page-count calculation.
    pub total_count: i64,
    /// Offset this page starts at.
    pub offset: i64,
    /// Maximum rows this page could contain.
    pub limit: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One currently-active dashboard session — a single minted login JWT.
///
/// [`id`](UserSessionEntry::id) is also the JWT's `jti`, and is what you pass
/// to the revoke endpoint.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserSessionEntry {
    /// Session identifier, equal to the JWT's `jti`.
    pub id: String,
    /// Sign-in method that produced the session.
    pub auth_method: String,
    /// ISO 8601 timestamp the session was created (sign-in time).
    pub created_at: String,
    /// ISO 8601 timestamp of the most recent observed API call on this
    /// session.
    pub last_seen_at: String,
    /// ISO 8601 timestamp at which the session JWT expires.
    pub expires_at: String,
    /// `true` for the row matching the JWT that made the listing request —
    /// what lets a dashboard render a "This device" tag.
    pub is_current: bool,

    /// Source IP the session signed in from.
    #[serde(default)]
    pub ip_address: Option<String>,
    /// `User-Agent` the session signed in with.
    #[serde(default)]
    pub user_agent: Option<String>,
    /// Two-letter country code resolved by GeoIP.
    #[serde(default)]
    pub country_code: Option<String>,
    /// City resolved by GeoIP.
    #[serde(default)]
    pub city: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The authenticated user's active sessions.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserSessionListResponse {
    /// One entry per live session.
    pub sessions: Vec<UserSessionEntry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of disconnecting one of the user's sessions.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserSessionRevokeResponse {
    /// Whether the session was revoked.
    pub revoked: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Team members
// =====================================================================

/// The outcome of inviting one team member — one entry per invitee, in the
/// order the invitations were sent.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct InviteUsersResponse {
    /// The invited email address.
    pub email: String,
    /// Whether the invitation email was delivered.
    pub is_email_sent: bool,

    /// Temporary password, present only when the invite email could *not* be
    /// delivered. Shown once — share it with the invitee out of band. They are
    /// forced to change it on first sign-in.
    #[serde(default)]
    pub password: Option<String>,
    /// Why the invitation failed, when it did.
    #[serde(default)]
    pub error: Option<String>,
    /// When the emailed link stops working. Present when the email was sent.
    #[serde(default)]
    pub link_expires_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: `password` is a live credential for the invitee's account and
// must never reach a log line through `{:?}`. The `Option` shape survives
// redaction so callers can still see whether a password was issued. Pinned by
// `invite_users_response_debug_redacts_the_password` and its `None` companion.
impl std::fmt::Debug for InviteUsersResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InviteUsersResponse")
            .field("email", &self.email)
            .field("is_email_sent", &self.is_email_sent)
            .field("password", &self.password.as_ref().map(|_| "[redacted]"))
            .field("error", &self.error)
            .field("link_expires_at", &self.link_expires_at)
            .field("extra", &self.extra)
            .finish()
    }
}

/// A role a member holds, as returned when listing the caller's lineage.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MinimalRoleInfo {
    /// Identifier of the role.
    pub role_id: String,
    /// Human-readable role name.
    pub role_name: String,
    /// The level the role sits at: `"tenant"`, `"organization"`,
    /// `"merchant"` or `"profile"`. `None` from an older API.
    #[serde(default)]
    pub entity_type: Option<String>,
    /// The shop this binding is on, for a shop-level binding.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// The project this binding is on, for a project-level binding.
    #[serde(default)]
    pub project_id: Option<String>,
    /// Whether the caller may sign in as this member under this binding.
    #[serde(default)]
    pub can_impersonate: Option<bool>,
    /// When this binding stops granting, in UTC.
    #[serde(default)]
    pub expires_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One member of the caller's lineage.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserInLineage {
    /// Stable identifier of the member. Use it to target them specifically —
    /// for a per-user operation-limit override, or to resolve a user id
    /// stamped on another resource (such as a refund's `initiated_by`) back to
    /// a person.
    pub user_id: String,
    /// The member's email address.
    pub email: String,
    /// Every role the member holds in this lineage.
    pub roles: Vec<MinimalRoleInfo>,
    /// The areas whose level is set for this member apart from their roles.
    /// Empty from an older API.
    #[serde(default)]
    pub permission_overrides: Vec<PermissionOverride>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The outcome of resending an invitation.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ReInviteUserResponse {
    /// When the new link stops working.
    pub link_expires_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// An entity a role is held on: its ID and, where it has one, its name.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoleEntityRef {
    /// The entity's ID.
    pub id: String,
    /// The entity's name. `None` when it has none, or a project no longer
    /// exists.
    #[serde(default)]
    pub name: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One role a team member holds, as listed by `Users::list_user_roles`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct GetUserRoleDetailsResponse {
    /// The role.
    pub role_id: String,
    /// The organization.
    pub org: RoleEntityRef,
    /// The merchant, for a role held at merchant level or below.
    #[serde(default)]
    pub merchant: Option<RoleEntityRef>,
    /// The shop, for a role held on one shop.
    #[serde(default)]
    pub profile: Option<RoleEntityRef>,
    /// The project a project-level role is granted on. The role then applies
    /// to every shop of that project, and `entity_type` is `"profile"`.
    #[serde(default)]
    pub project: Option<RoleEntityRef>,
    /// `"Active"` or `"InvitationSent"`.
    pub status: String,
    /// `"tenant"`, `"organization"`, `"merchant"` or `"profile"`.
    pub entity_type: String,
    /// The role's name.
    pub role_name: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Roles and permissions
// =====================================================================

/// One entry in the caller's permission listing: the role holds the listed
/// [`scopes`](ParentGroupInfo::scopes) over the resources implied by
/// [`name`](ParentGroupInfo::name).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ParentGroupInfo {
    /// The permission group.
    pub name: ParentGroup,
    /// Resources the group covers.
    pub resources: Vec<String>,
    /// Scopes the caller's role holds over them.
    pub scopes: Vec<PermissionScope>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Two-factor authentication
// =====================================================================

/// The TOTP enrolment material: the shared secret and the `otpauth://` URI a
/// dashboard renders as a QR code.
///
/// Both fields are enrolment credentials — anyone who reads either can
/// generate valid codes for the account.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct TotpSecret {
    /// Base32 shared secret to load into an authenticator app.
    pub secret: String,
    /// `otpauth://` provisioning URI — **embeds the secret**, so it is exactly
    /// as sensitive as [`secret`](TotpSecret::secret).
    pub totp_url: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: both the shared secret and the provisioning URI (which embeds
// it) are enrolment credentials and must never reach a log line through
// `{:?}`. Pinned by `totp_secret_debug_redacts_the_secret_and_url`.
impl std::fmt::Debug for TotpSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TotpSecret")
            .field("secret", &"[redacted]")
            .field("totp_url", &"[redacted]")
            .field("extra", &self.extra)
            .finish()
    }
}

/// The result of starting TOTP setup.
///
/// [`secret`](TotpResponse::secret) is `Some` when the user has no TOTP
/// configured yet, and `None` when they are already set up — in which case the
/// caller should prompt for a 6-digit code and verify it instead.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct TotpResponse {
    /// Enrolment material, when the user is not yet enrolled.
    #[serde(default)]
    pub secret: Option<TotpSecret>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: the nested enrolment material is a credential and must never
// reach a log line through `{:?}`. Redacted here as well as on `TotpSecret`
// itself, so neither type can leak on its own. The `Option` shape survives
// redaction so callers can still see whether enrolment is pending. Pinned by
// `totp_response_debug_redacts_the_secret` and its `None` companion.
impl std::fmt::Debug for TotpResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TotpResponse")
            .field("secret", &self.secret.as_ref().map(|_| "[redacted]"))
            .field("extra", &self.extra)
            .finish()
    }
}

/// A freshly generated set of recovery codes. Generating a new set invalidates
/// the previous one.
///
/// The codes are single-use second factors: each one substitutes for a TOTP
/// code. Show them to the user once and never persist them in a log.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct RecoveryCodesResponse {
    /// The codes, in the order the API generated them.
    pub recovery_codes: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: every recovery code is a live second factor and must never
// reach a log line through `{:?}`. The count is kept — it is useful and not
// sensitive. Pinned by `recovery_codes_response_debug_redacts_the_codes`.
impl std::fmt::Debug for RecoveryCodesResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RecoveryCodesResponse")
            .field("recovery_codes", &"[redacted]")
            .field("recovery_codes_len", &self.recovery_codes.len())
            .field("extra", &self.extra)
            .finish()
    }
}

// =====================================================================
// Phone OTP
// =====================================================================

/// The result of sending a one-time code to a phone number.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PhoneOtpResponse {
    /// Human-readable confirmation from the API.
    pub message: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of verifying a one-time code sent to a phone number.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PhoneOtpVerifyResponse {
    /// Whether the code matched.
    pub verified: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Dashboard OAuth sign-in
// =====================================================================

/// The OAuth providers configured for dashboard sign-in, and the ones linked
/// to the current account. Provider names are `"google"`, `"github"` and
/// `"microsoft"`; strings, so a new provider does not break deserialization.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct DashboardOAuthProvidersResponse {
    /// Providers the dashboard may offer for sign-in.
    #[serde(default)]
    pub available: Vec<String>,
    /// Providers linked to the account. A disabled provider stays listed here.
    #[serde(default)]
    pub linked: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Where to send the browser to start an OAuth sign-in or link.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct DashboardOAuthStartResponse {
    /// The provider's authorization URL, carrying the flow's state.
    pub authorization_url: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: the authorization URL carries the flow's state value, which
// binds the provider's answer to this sign-in; it must never reach a log line
// through `{:?}`. Pinned by `oauth_start_response_debug_redacts_the_url`.
impl std::fmt::Debug for DashboardOAuthStartResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DashboardOAuthStartResponse")
            .field("authorization_url", &"[redacted]")
            .field("extra", &self.extra)
            .finish()
    }
}

// =====================================================================
// Preferences and the dashboard tour
// =====================================================================

/// One of the signed-in user's own preferences. A `None` value means no
/// preference is saved: use your defaults.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserPreferenceResponse {
    /// The preference key.
    pub key: String,
    /// The saved JSON object, or `None` when nothing is saved.
    #[serde(default)]
    pub value: Option<serde_json::Map<String, Value>>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The user's guided dashboard tour in the session's scope.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct DashboardTourResponse {
    /// The scope the progress is kept for.
    pub scope: DashboardTourScope,
    /// Whether to offer the tour now. Never in a read-only session, and never
    /// once the progress's `offer_handled_at` is set.
    pub auto_offer: bool,
    /// Which value decided `auto_offer`: `"member"`, `"merchant"`,
    /// `"platform"` or `"none"`.
    pub offer_source: String,
    /// Whether this merchant offers the tour to new members.
    pub merchant_default: bool,
    /// The saved progress; `None` until the first save in this scope, and in a
    /// read-only session.
    #[serde(default)]
    pub progress: Option<TourProgress>,
    /// What the user may use now, and what they last acknowledged.
    pub access: DashboardTourAccess,
    /// `true` while acting as another user: nothing can be saved.
    pub read_only: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The scope a dashboard tour's progress is kept for, taken from the session.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct DashboardTourScope {
    /// The merchant.
    pub merchant_id: String,
    /// Set only for a user whose role is limited to shops: their progress is
    /// kept per shop.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The user's current access, and the access they last acknowledged.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct DashboardTourAccess {
    /// The user's effective access in this scope.
    #[serde(default)]
    pub current: Vec<TourAccessGroup>,
    /// The access stored at the last acknowledgement; `None` before the first.
    #[serde(default)]
    pub acknowledged: Option<Vec<TourAccessGroup>>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One permission area and the scopes held over it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct TourAccessGroup {
    /// The permission area.
    pub name: ParentGroup,
    /// The scopes held over it.
    #[serde(default)]
    pub scopes: Vec<PermissionScope>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A user's progress through the dashboard tour in one scope.
///
/// Read back from [`DashboardTourResponse::progress`] and sent in a tour
/// update. The API refuses a field it does not know here, so this type has no
/// `extra` map. A step id is 1-64 lower-case letters, digits, dots,
/// underscores or hyphens; each list holds at most 300.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TourProgress {
    /// Stops the user finished. A save adds these to the stored ones; only a
    /// restart replaces them.
    #[serde(default)]
    pub completed: Vec<String>,
    /// Stops the user skipped. A save adds these to the stored ones.
    #[serde(default)]
    pub skipped: Vec<String>,
    /// When the user accepted or dismissed the first-sign-in offer (ISO 8601).
    /// A save replaces it, so send the value read back to keep it.
    #[serde(default)]
    pub offer_handled_at: Option<String>,
    /// The tour in progress. A save replaces it.
    #[serde(default)]
    pub active: Option<TourActive>,
    /// The baseline the user last chose. A save replaces it.
    #[serde(default)]
    pub baseline: Option<TourBaseline>,
}

impl TourProgress {
    /// Empty progress: no stops, no offer handled, no tour running.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the finished stops.
    #[must_use]
    pub fn completed(mut self, completed: Vec<String>) -> Self {
        self.completed = completed;
        self
    }

    /// Set the skipped stops.
    #[must_use]
    pub fn skipped(mut self, skipped: Vec<String>) -> Self {
        self.skipped = skipped;
        self
    }

    /// Set when the first-sign-in offer was handled (ISO 8601).
    #[must_use]
    pub fn offer_handled_at(mut self, offer_handled_at: impl Into<String>) -> Self {
        self.offer_handled_at = Some(offer_handled_at.into());
        self
    }

    /// Set the tour in progress.
    #[must_use]
    pub fn active(mut self, active: TourActive) -> Self {
        self.active = Some(active);
        self
    }

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

/// The dashboard tour in progress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TourActive {
    /// What kind of tour runs.
    pub kind: String,
    /// The stop the user is on, if any.
    #[serde(default)]
    pub step_id: Option<String>,
    /// The baseline the tour runs against, if any.
    #[serde(default)]
    pub baseline: Option<TourBaseline>,
}

impl TourActive {
    /// A running tour of `kind`, at no particular stop.
    pub fn new(kind: impl Into<String>) -> Self {
        Self {
            kind: kind.into(),
            step_id: None,
            baseline: None,
        }
    }

    /// Set the stop the user is on.
    #[must_use]
    pub fn step_id(mut self, step_id: impl Into<String>) -> Self {
        self.step_id = Some(step_id.into());
        self
    }

    /// Set the baseline the tour runs against.
    #[must_use]
    pub fn baseline(mut self, baseline: TourBaseline) -> Self {
        self.baseline = Some(baseline);
        self
    }
}

/// A dashboard-tour baseline.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TourBaseline {
    /// The kind of baseline.
    pub kind: String,
    /// Its value.
    pub value: String,
}

impl TourBaseline {
    /// A baseline of `kind` with `value`.
    pub fn new(kind: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            kind: kind.into(),
            value: value.into(),
        }
    }
}

// =====================================================================
// Role policies and grants
// =====================================================================

/// A role's explicit payment-data policy. Each visibility is `"none"` or
/// `"read"`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RolePaymentVisibilityPolicy {
    /// What the role may read of payment-method data.
    #[serde(default)]
    pub payment_methods: Option<String>,
    /// What the role may read of payment-processor data.
    #[serde(default)]
    pub payment_processors: Option<String>,
    /// Processors the policy singles out.
    #[serde(default)]
    pub processor_exceptions: Vec<ProcessorVisibilityException>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A processor a role's payment-data policy singles out.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProcessorVisibilityException {
    /// The processor, e.g. `"stripe"`.
    pub processor: String,
    /// The access the role has to it.
    pub access: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The connector accounts a role may see.
///
/// Check [`restricted`](Self::restricted) before reading
/// [`connectors`](Self::connectors): `false` means the role holds no grant and
/// sees what its scope already allowed, so an empty list does not mean "sees
/// nothing".
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoleConnectorGrantResponse {
    /// The role.
    pub role_id: String,
    /// Whether the role is limited to the listed connector accounts.
    pub restricted: bool,
    /// The connector accounts the role may see, when restricted.
    #[serde(default)]
    pub connectors: Vec<RoleConnectorGrantEntry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One connector account in a role's grant.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoleConnectorGrantEntry {
    /// The connector account.
    pub merchant_connector_id: String,
    /// Who granted it.
    pub created_by: String,
    /// Why it was granted, when a reason was given.
    #[serde(default)]
    pub reason: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A permission level set for one area: `area` is a permission group such as
/// `"Operations"`, `level` one of `"hidden"`, `"read"`, `"edit"`, `"write"`.
///
/// Returned by the overrides reads and sent in an overrides update. The API
/// refuses a field it does not know here, so this type has no `extra` map.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PermissionOverride {
    /// The permission area.
    pub area: ParentGroup,
    /// The level set for it.
    pub level: String,
}

impl PermissionOverride {
    /// An override setting `area` to `level`.
    pub fn new(area: impl Into<String>, level: impl Into<String>) -> Self {
        Self {
            area: area.into(),
            level: level.into(),
        }
    }
}

// =====================================================================
// Team members
// =====================================================================

/// A team member's scope after a scope change.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ChangeMemberScopeResponse {
    /// The role the member now holds.
    pub role_id: String,
    /// The level the role is defined at: `"merchant"` or `"profile"` (shop).
    pub entity_type: String,
    /// The shops the member holds the role on. Empty for a merchant-level role.
    #[serde(default)]
    pub profile_ids: Vec<String>,
    /// The projects the member holds the role on. Empty for a merchant-level
    /// role.
    #[serde(default)]
    pub project_ids: Vec<String>,
    /// Whether the member's sessions were ended, because the change took a
    /// scope away from them.
    pub sessions_revoked: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A team member's access expiry after an update.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UpdateMemberExpiryResponse {
    /// When the member's access ends, in UTC; `None` when it does not expire.
    #[serde(default)]
    pub expires_at: Option<String>,
    /// How many of the member's roles in the merchant were updated.
    pub roles_updated: u64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One member of the caller's merchant, with the person fields the member
/// list omits.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct TeamMemberDetailsResponse {
    /// The member's user id.
    pub user_id: String,
    /// The member's email address.
    pub email: String,
    /// The member's name.
    pub name: String,
    /// The member's phone number, when one is on file.
    #[serde(default)]
    pub phone_number: Option<String>,
    /// Whether the member verified their email address.
    pub is_verified: bool,
    /// `"Active"` or `"InvitationSent"`.
    pub status: String,
    /// Two-factor state: `"set"`, `"in_progress"` or `"not_set"`.
    pub two_factor: String,
    /// When the account was created (ISO 8601).
    pub created_at: String,
    /// When the member last changed their password (ISO 8601).
    #[serde(default)]
    pub last_password_modified_at: Option<String>,
    /// Every role the member holds in the merchant.
    #[serde(default)]
    pub roles: Vec<MinimalRoleInfo>,
    /// Whether the caller may reset this member's password.
    pub can_reset_password: bool,
    /// Whether the member still has an invitation pending.
    #[serde(default)]
    pub pending_invitation: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A pending member's current invitation link, or why it is not shown.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct InviteLinkResponse {
    /// `"available"` when [`link`](Self::link) is set; otherwise the reason it
    /// is not, e.g. `"expired"` or `"account_in_use"`.
    pub availability: String,
    /// The invitation link. It signs its holder in without a password.
    #[serde(default)]
    pub link: Option<String>,
    /// When the link stops working (ISO 8601).
    #[serde(default)]
    pub expires_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: the link signs its holder in without a password, so it is a
// credential and must never reach a log line through `{:?}`. Pinned by
// `invite_link_response_debug_redacts_the_link`.
impl std::fmt::Debug for InviteLinkResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InviteLinkResponse")
            .field("availability", &self.availability)
            .field("link", &self.link.as_ref().map(|_| "[redacted]"))
            .field("expires_at", &self.expires_at)
            .field("extra", &self.extra)
            .finish()
    }
}

/// A member's supplied contacts and the internal notes kept about them.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct TeamMemberContactProfileResponse {
    /// The tenant.
    pub tenant_id: String,
    /// The merchant.
    pub merchant_id: String,
    /// The member.
    pub user_id: String,
    /// The profile revision. Every write must send the last one read.
    pub revision: String,
    /// The supplied contacts.
    pub contacts: TeamMemberContacts,
    /// The internal notes.
    #[serde(default)]
    pub notes: Vec<TeamMemberNote>,
    /// Whether the caller may write the profile.
    pub can_edit: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A team member's supplied contacts.
///
/// Read back from a contact profile and sent whole in a contacts update; a
/// field left `None` is cleared. The API refuses a field it does not know
/// here, so this type has no `extra` map.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TeamMemberContacts {
    /// Discord name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discord_name: Option<String>,
    /// Discord user id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discord_id: Option<String>,
    /// Telegram username.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub telegram_username: Option<String>,
    /// Contact phone number.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contact_phone: Option<String>,
    /// Further contact channels.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_channels: Vec<TeamMemberContactChannel>,
}

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

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

    /// Set the Discord user id.
    #[must_use]
    pub fn discord_id(mut self, discord_id: impl Into<String>) -> Self {
        self.discord_id = Some(discord_id.into());
        self
    }

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

    /// Set the contact phone number.
    #[must_use]
    pub fn contact_phone(mut self, contact_phone: impl Into<String>) -> Self {
        self.contact_phone = Some(contact_phone.into());
        self
    }

    /// Set the further contact channels.
    #[must_use]
    pub fn extra_channels(mut self, extra_channels: Vec<TeamMemberContactChannel>) -> Self {
        self.extra_channels = extra_channels;
        self
    }
}

/// One further contact channel of a team member.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TeamMemberContactChannel {
    /// The kind of channel.
    pub kind: String,
    /// Its label.
    pub label: String,
    /// The address or handle on it.
    pub value: String,
}

impl TeamMemberContactChannel {
    /// A channel of `kind`, labelled `label`, reached at `value`.
    pub fn new(
        kind: impl Into<String>,
        label: impl Into<String>,
        value: impl Into<String>,
    ) -> Self {
        Self {
            kind: kind.into(),
            label: label.into(),
            value: value.into(),
        }
    }
}

/// One internal note about a team member.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct TeamMemberNote {
    /// The note.
    pub note_id: String,
    /// Its plain text.
    pub body: String,
    /// Who wrote it.
    pub created_by: TeamMemberNoteActor,
    /// Who edited it last.
    pub last_edited_by: TeamMemberNoteActor,
    /// When it was written (ISO 8601).
    pub created_at: String,
    /// When it was edited last (ISO 8601).
    pub last_edited_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The user who wrote or edited a team-member note.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct TeamMemberNoteActor {
    /// Their user id.
    pub user_id: String,
    /// Their name.
    pub name: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A team member's temporary password, returned once by a reset.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ResetTeamMemberPasswordResponse {
    /// The member.
    pub user_id: String,
    /// The temporary password. It is shown only here.
    pub temporary_password: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: `temporary_password` signs the member in, so it must never
// reach a log line through `{:?}`. Pinned by
// `reset_team_member_password_response_debug_redacts_the_password`.
impl std::fmt::Debug for ResetTeamMemberPasswordResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResetTeamMemberPasswordResponse")
            .field("user_id", &self.user_id)
            .field("temporary_password", &"[redacted]")
            .field("extra", &self.extra)
            .finish()
    }
}

/// Which checkout payment methods a member may change in the merchant.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MemberMethodAccessResponse {
    /// The member.
    pub user_id: String,
    /// Whether the member may change every method.
    pub all_methods: bool,
    /// The methods the member may change, when not all.
    #[serde(default)]
    pub methods: Vec<String>,
    /// The revision. An update must send the last one read.
    pub revision: String,
    /// Whether the caller may change it.
    pub can_edit: bool,
    /// Whether the caller may grant every method.
    pub grant_all: bool,
    /// The methods the caller may grant.
    #[serde(default)]
    pub grantable: Vec<String>,
    /// Every method with its label.
    #[serde(default)]
    pub options: Vec<MethodAccessOption>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A checkout payment method and its label.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MethodAccessOption {
    /// The method key.
    pub key: String,
    /// Its label.
    pub label: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A member's permission overrides in the merchant.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MemberPermissionOverridesResponse {
    /// The member.
    pub user_id: String,
    /// The member's level, e.g. `"merchant"` or `"profile"`.
    pub entity_type: String,
    /// The member's roles.
    #[serde(default)]
    pub roles: Vec<MemberPermissionRole>,
    /// Every area that can be overridden at the member's level.
    #[serde(default)]
    pub areas: Vec<MemberPermissionArea>,
    /// The overrides set for the member.
    #[serde(default)]
    pub overrides: Vec<PermissionOverride>,
    /// The revision. An update must send the last one read.
    pub revision: String,
    /// Whether the caller may change them.
    pub can_edit: bool,
    /// Why the caller may not change them, when it may not. Kept as raw JSON:
    /// its shape depends on its `reason`.
    #[serde(default)]
    pub refusal: Option<Value>,
    /// Whether the caller may raise an area above what the member's roles give.
    pub can_raise: bool,
    /// Who changed the overrides last.
    #[serde(default)]
    pub modified_by: Option<String>,
    /// When they were changed last (ISO 8601).
    #[serde(default)]
    pub modified_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A role a member holds, as the permission-overrides read lists it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MemberPermissionRole {
    /// The role.
    pub role_id: String,
    /// Its name.
    pub role_name: String,
    /// The shop it is held on, for a shop-level role.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// The project it is held on, for a project-level role.
    #[serde(default)]
    pub project_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One area of a member's permissions: what their roles give, the level set
/// for them, and what they have. Levels are `"hidden"`, `"read"`, `"edit"` or
/// `"write"`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MemberPermissionArea {
    /// The permission area.
    pub area: ParentGroup,
    /// The levels the area can be set to.
    #[serde(default)]
    pub available_levels: Vec<String>,
    /// What the member's roles give.
    pub role_level: String,
    /// The level set for the member, if any.
    #[serde(default)]
    pub override_level: Option<String>,
    /// What the member has.
    pub effective_level: String,
    /// The highest level the caller may set.
    pub grantable_level: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Team invitation links
// =====================================================================

/// Who may join through a team invitation link: network ranges and a country
/// rule (`"allow"` or `"block"`) over ISO 3166-1 alpha-2 codes.
///
/// Read back from a link and sent in a create or update; an empty list or a
/// `None` rule is not sent. The API refuses a field it does not know here, so
/// this type has no `extra` map.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct InvitationLinkRestrictions {
    /// Network ranges (CIDR) joins may come from. Empty allows any.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ip_ranges: Vec<String>,
    /// Whether [`countries`](Self::countries) are allowed or blocked.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub country_rule: Option<String>,
    /// The countries the rule applies to.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub countries: Vec<String>,
}

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

    /// Set the allowed network ranges.
    #[must_use]
    pub fn ip_ranges(mut self, ip_ranges: Vec<String>) -> Self {
        self.ip_ranges = ip_ranges;
        self
    }

    /// Set the country rule (`"allow"` or `"block"`) and its countries.
    #[must_use]
    pub fn countries(mut self, country_rule: impl Into<String>, countries: Vec<String>) -> Self {
        self.country_rule = Some(country_rule.into());
        self.countries = countries;
        self
    }
}

/// A team invitation link: its policy, usage and status.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvitationLinkResponse {
    /// The link.
    pub id: String,
    /// Its name.
    pub name: String,
    /// What joining grants access to: `"merchant"`, `"shop"` or `"project"`.
    pub target: String,
    /// The shop, for a shop link.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// The project, for a project link.
    #[serde(default)]
    pub project_id: Option<String>,
    /// The target's name.
    #[serde(default)]
    pub target_name: Option<String>,
    /// The role joining grants.
    pub role_id: String,
    /// Its name.
    pub role_name: String,
    /// How many people may join through it.
    pub max_uses: i32,
    /// How many have.
    pub use_count: i32,
    /// How many still may.
    pub remaining: i32,
    /// When the link stops working (ISO 8601).
    pub expires_at: String,
    /// When the access it grants ends (ISO 8601), if it does.
    #[serde(default)]
    pub member_expires_at: Option<String>,
    /// Who may join.
    #[serde(default)]
    pub restrictions: InvitationLinkRestrictions,
    /// `"active"`, `"expired"`, `"revoked"`, `"exhausted"` or
    /// `"needs_reconfirmation"`.
    pub status: String,
    /// Who created it.
    pub created_by: String,
    /// Their name.
    #[serde(default)]
    pub created_by_name: Option<String>,
    /// When it was created (ISO 8601).
    pub created_at: String,
    /// When it was changed last (ISO 8601). Send it as the update's `version`.
    pub modified_at: String,
    /// When it was revoked (ISO 8601).
    #[serde(default)]
    pub revoked_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A newly created team invitation link, with the secret to share.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct CreateInvitationLinkResponse {
    /// The link.
    #[serde(flatten)]
    pub link: InvitationLinkResponse,
    /// The secret to put in the shared link. Returned only here: a lost secret
    /// means a new link.
    pub token: String,
}

// Hand-written: `token` lets anyone join the team, so it must never reach a
// log line through `{:?}`. Pinned by
// `create_invitation_link_response_debug_redacts_the_token`.
impl std::fmt::Debug for CreateInvitationLinkResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CreateInvitationLinkResponse")
            .field("link", &self.link)
            .field("token", &"[redacted]")
            .finish()
    }
}

/// The merchant's team invitation links, newest first.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ListInvitationLinksResponse {
    /// The links.
    #[serde(default)]
    pub links: Vec<InvitationLinkResponse>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a shared team invitation link offers, before joining.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct InvitationLinkPreviewResponse {
    /// The link's status; the other fields are set when it is `"active"`.
    pub status: String,
    /// The merchant.
    #[serde(default)]
    pub merchant_name: Option<String>,
    /// `"merchant"`, `"shop"` or `"project"`.
    #[serde(default)]
    pub target: Option<String>,
    /// The target's name.
    #[serde(default)]
    pub target_name: Option<String>,
    /// The role joining grants.
    #[serde(default)]
    pub role_id: Option<String>,
    /// Its name.
    #[serde(default)]
    pub role_name: Option<String>,
    /// When the link stops working (ISO 8601).
    #[serde(default)]
    pub expires_at: Option<String>,
    /// When the access it grants ends (ISO 8601).
    #[serde(default)]
    pub member_expires_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of joining through a team invitation link.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct JoinInvitationLinkResponse {
    /// `"joined"`, or `"already_member"` when the caller had joined before.
    pub outcome: String,
    /// The organization.
    pub org_id: String,
    /// The merchant.
    pub merchant_id: String,
    /// `"merchant"`, `"shop"` or `"project"`.
    pub target: String,
    /// The shop, for a shop link.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// The project, for a project link.
    #[serde(default)]
    pub project_id: Option<String>,
    /// The target's name.
    #[serde(default)]
    pub target_name: Option<String>,
    /// The role granted.
    pub role_id: String,
    /// Its name.
    pub role_name: String,
    /// When the access ends (ISO 8601), if it does.
    #[serde(default)]
    pub member_expires_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A join during sign-in, with the token for the next sign-in step.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct JoinInvitationLinkPreAuthResponse {
    /// The join.
    #[serde(flatten)]
    pub join: JoinInvitationLinkResponse,
    /// The token for the next sign-in step.
    pub token: String,
    /// Kind of token: which step to run next.
    pub token_type: TokenPurpose,
}

// Hand-written: `token` authorises the next sign-in step and must never reach
// a log line through `{:?}`. Pinned by
// `join_invitation_link_pre_auth_response_debug_redacts_the_token`.
impl std::fmt::Debug for JoinInvitationLinkPreAuthResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JoinInvitationLinkPreAuthResponse")
            .field("join", &self.join)
            .field("token", &"[redacted]")
            .field("token_type", &self.token_type)
            .finish()
    }
}

/// The result of making an account through a team invitation link.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RegisterThroughInvitationLinkResponse {
    /// Whether the verification email was sent.
    pub is_email_sent: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    // Each redaction test below fails if the hand-written `Debug` is deleted
    // (the derive would print the secret) or if the field is rendered with
    // `&self.x` instead of `&"[redacted]"`. The `None` companions fail if an
    // impl hard-codes `Some("[redacted]")` instead of mapping the `Option`.

    fn de<T: serde::de::DeserializeOwned>(json: &str) -> T {
        serde_json::from_str(json).expect("fixture deserializes")
    }

    #[test]
    fn auth_response_debug_redacts_the_token() {
        let res: AuthResponse =
            de(r#"{"token":"jwt-super-secret","token_type":"bearer","expires":3600}"#);
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("jwt-super-secret"), "{rendered}");
        assert!(rendered.contains("bearer"), "{rendered}");
        assert!(rendered.contains("3600"), "{rendered}");
    }

    #[test]
    fn auth_response_keeps_unknown_fields_in_extra() {
        let res: AuthResponse = de(r#"{"token":"t","brand_new_field":"kept"}"#);
        assert_eq!(res.extra["brand_new_field"], "kept");
        assert_eq!(res.token_type, None);
    }

    #[test]
    fn token_response_debug_redacts_the_token() {
        let res: TokenResponse = de(r#"{"token":"spt-super-secret","token_type":"totp"}"#);
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("spt-super-secret"), "{rendered}");
        assert!(rendered.contains("totp"), "{rendered}");
    }

    #[test]
    fn invite_users_response_debug_redacts_the_password() {
        let res: InviteUsersResponse = de(
            r#"{"email":"bob@example.com","is_email_sent":false,"password":"temp-pw-1234","error":"smtp down"}"#,
        );
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("temp-pw-1234"), "{rendered}");
        assert!(rendered.contains("bob@example.com"), "{rendered}");
        assert!(rendered.contains("smtp down"), "{rendered}");
        assert!(rendered.contains("Some("), "{rendered}");
    }

    #[test]
    fn invite_users_response_debug_shows_none_when_no_password() {
        let res: InviteUsersResponse = de(r#"{"email":"bob@example.com","is_email_sent":true}"#);
        assert!(format!("{res:?}").contains("password: None"));
    }

    #[test]
    fn totp_secret_debug_redacts_the_secret_and_url() {
        let res: TotpSecret = de(
            r#"{"secret":"JBSWY3DPEHPK3PXP","totp_url":"otpauth://totp/x?secret=JBSWY3DPEHPK3PXP"}"#,
        );
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("JBSWY3DPEHPK3PXP"), "{rendered}");
        assert!(!rendered.contains("otpauth"), "{rendered}");
    }

    #[test]
    fn totp_response_debug_redacts_the_secret() {
        let res: TotpResponse = de(
            r#"{"secret":{"secret":"JBSWY3DPEHPK3PXP","totp_url":"otpauth://totp/x?secret=JBSWY3DPEHPK3PXP"}}"#,
        );
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("JBSWY3DPEHPK3PXP"), "{rendered}");
        assert!(!rendered.contains("otpauth"), "{rendered}");
        assert!(rendered.contains("Some("), "{rendered}");
    }

    #[test]
    fn totp_response_debug_shows_none_when_already_enrolled() {
        let res: TotpResponse = de(r#"{"secret":null}"#);
        assert!(format!("{res:?}").contains("secret: None"));
    }

    #[test]
    fn recovery_codes_response_debug_redacts_the_codes() {
        let res: RecoveryCodesResponse =
            de(r#"{"recovery_codes":["aaaa-bbbb","cccc-dddd","eeee-ffff"]}"#);
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("aaaa-bbbb"), "{rendered}");
        assert!(!rendered.contains("eeee-ffff"), "{rendered}");
        // The count is not sensitive and is kept, so an impl that dropped the
        // field entirely is distinguishable from one that redacts it.
        assert!(rendered.contains("recovery_codes_len: 3"), "{rendered}");
    }

    #[test]
    fn user_response_parses_optional_fields_and_keeps_extras() {
        let res: UserResponse = de(
            r#"{"merchant_id":"mer_1","name":"Ada","email":"ada@example.com","role_id":"role_1",
                "is_two_factor_auth_setup":true,"profile_id":"pro_1","entity_type":"merchant",
                "version":"v2","theme_id":"dark","new_api_field":7}"#,
        );
        assert_eq!(res.theme_id.as_deref(), Some("dark"));
        assert_eq!(res.verification_days_left, None);
        assert_eq!(res.extra["new_api_field"], 7);
    }

    #[test]
    fn login_history_parses_null_geo_fields() {
        let res: LoginHistoryResponse = de(
            r#"{"entries":[{"id":"lh_1","event_type":"signin_failure","failure_reason":"totp_invalid",
                "auth_method":"totp","ip_address":"127.0.0.1","user_agent":null,"country_code":null,
                "city":null,"latitude":null,"longitude":null,"created_at":"2026-01-01T00:00:00Z"}],
                "total_count":1,"offset":0,"limit":25}"#,
        );
        assert_eq!(res.total_count, 1);
        assert_eq!(
            res.entries[0].failure_reason.as_deref(),
            Some("totp_invalid")
        );
        assert_eq!(res.entries[0].latitude, None);
        assert_eq!(res.entries[0].ip_address.as_deref(), Some("127.0.0.1"));
    }

    #[test]
    fn session_list_parses_the_current_flag() {
        let res: UserSessionListResponse = de(
            r#"{"sessions":[{"id":"ses_1","auth_method":"password","ip_address":null,
                "user_agent":null,"country_code":null,"city":null,
                "created_at":"2026-01-01T00:00:00Z","last_seen_at":"2026-01-02T00:00:00Z",
                "expires_at":"2026-01-08T00:00:00Z","is_current":true}]}"#,
        );
        assert_eq!(res.sessions.len(), 1);
        assert!(res.sessions[0].is_current);
        assert_eq!(res.sessions[0].last_seen_at, "2026-01-02T00:00:00Z");
    }

    #[test]
    fn user_in_lineage_parses_nested_roles() {
        let res: UserInLineage = de(r#"{"user_id":"usr_1","email":"bob@example.com",
                "roles":[{"role_id":"role_1","role_name":"Admin"}]}"#);
        assert_eq!(res.roles[0].role_name, "Admin");
    }

    #[test]
    fn parent_group_info_parses_scopes() {
        let res: ParentGroupInfo = de(
            r#"{"name":"Operations","resources":["payment","refund"],"scopes":["Read","Write"]}"#,
        );
        assert_eq!(res.name, "Operations");
        assert_eq!(res.resources, vec!["payment", "refund"]);
        assert_eq!(res.scopes, vec!["Read", "Write"]);
    }
}