payrix 0.3.0

Rust client for the Payrix payment processing API
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
//! Expanded entity types with embedded relationships.
//!
//! When using the Payrix API's `expand[]` query parameter, related entities
//! are embedded directly in the response instead of just returning their IDs.
//! These types handle the expanded response format.
//!
//! # Nested Expansions
//!
//! Some expansions can be nested. For example, `token|customer` expands the
//! token AND the customer nested inside the token:
//!
//! ```text
//! expand[token][][customer][]
//! ```
//!
//! Results in:
//! ```json
//! {
//!   "token": {
//!     "id": "t1_tok_xxx",
//!     "customer": {
//!       "id": "t1_cus_xxx",
//!       "first": "John",
//!       ...
//!     }
//!   }
//! }
//! ```
//!
//! # Usage
//!
//! ```rust,ignore
//! // Get a transaction with payment, token, and customer expanded
//! let txn: TransactionExpanded = client
//!     .get_transaction_full(txn_id)
//!     .await?;
//!
//! // Access expanded data
//! if let Some(ref payment) = txn.payment {
//!     println!("Card: {} ending in {}", payment.method, payment.last4);
//! }
//!
//! if let Some(ref token) = txn.token {
//!     if let Some(ref customer) = token.customer {
//!         println!("Customer: {} {}", customer.first, customer.last);
//!     }
//! }
//! ```

use serde::{Deserialize, Serialize};

use super::{
    batch::Platform, bool_from_int_default_false, deserialize_optional_i32, deserialize_string_or_int,
    BatchStatus, ChargebackCycle, ChargebackPaymentMethod, ChargebackStatusValue, Member,
    Payment, PaymentMethod, PayrixId, Plan, PlanSchedule, PlanType, PlanUm, Subscription,
    SubscriptionOrigin, TokenStatus, Transaction, TransactionStatus, TransactionType,
};

// =============================================================================
// TokenExpanded
// =============================================================================

/// A token with expanded relationships.
///
/// Used when expanding `token` with nested expansions like `token|customer`.
/// The `customer` field becomes the full `Customer` object instead of just
/// a `PayrixId`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenExpanded {
    // -------------------------------------------------------------------------
    // Core Identifiers
    // -------------------------------------------------------------------------

    /// The ID of this token.
    pub id: PayrixId,

    /// The date and time this token was created.
    #[serde(default)]
    pub created: Option<String>,

    /// The date and time this token was last modified.
    #[serde(default)]
    pub modified: Option<String>,

    /// The login that created this token.
    #[serde(default)]
    pub creator: Option<PayrixId>,

    /// The login that last modified this token.
    #[serde(default)]
    pub modifier: Option<PayrixId>,

    // -------------------------------------------------------------------------
    // Token Data
    // -------------------------------------------------------------------------

    /// The token string value used for transactions.
    #[serde(default)]
    pub token: Option<String>,

    /// Token status (pending/ready).
    #[serde(default)]
    pub status: Option<TokenStatus>,

    /// Card/account expiration in MMYY format.
    #[serde(default)]
    pub expiration: Option<String>,

    /// Token name.
    #[serde(default)]
    pub name: Option<String>,

    /// Token description.
    #[serde(default)]
    pub description: Option<String>,

    /// Custom data.
    #[serde(default)]
    pub custom: Option<String>,

    /// Whether this token is inactive.
    #[serde(default, with = "bool_from_int_default_false")]
    pub inactive: bool,

    /// Whether this token is frozen.
    #[serde(default, with = "bool_from_int_default_false")]
    pub frozen: bool,

    /// Entry mode.
    #[serde(default)]
    pub entry_mode: Option<i32>,

    /// Origin of the token.
    #[serde(default)]
    pub origin: Option<String>,

    /// Omnitoken value.
    #[serde(default)]
    pub omnitoken: Option<String>,

    /// Auth token customer reference.
    #[serde(default)]
    pub auth_token_customer: Option<String>,

    // -------------------------------------------------------------------------
    // Expanded Relationships
    // -------------------------------------------------------------------------

    /// Expanded payment details.
    ///
    /// Contains card/account information like BIN, last4, routing number.
    /// Only populated when expanding `payment`.
    #[serde(default)]
    pub payment: Option<Payment>,

    /// Expanded customer.
    /// Customer ID.
    ///
    /// Note: The API returns customer as an ID string even when using nested expansion.
    /// Use `client.get_customer_expanded()` to fetch full customer details.
    #[serde(default)]
    pub customer: Option<PayrixId>,
}

impl TokenExpanded {
    /// Returns the payment method if available.
    pub fn payment_method(&self) -> Option<PaymentMethod> {
        self.payment.as_ref().and_then(|p| p.method)
    }

    /// Returns the card display string (e.g., "Visa ending in 1111").
    pub fn card_display(&self) -> Option<String> {
        self.payment.as_ref().map(|p| p.display())
    }

    /// Returns the customer ID if available.
    ///
    /// Note: Customer data is not expanded in token responses.
    /// Use `client.get_customer_expanded()` to fetch full customer details.
    pub fn customer_id(&self) -> Option<&str> {
        self.customer.as_ref().map(|c| c.as_str())
    }
}

// =============================================================================
// TransactionExpanded
// =============================================================================

/// A transaction with commonly expanded relationships.
///
/// This type is returned by convenience methods like `get_transaction_full()`
/// that expand payment, token, customer, and other related entities in a
/// single API call.
///
/// # Fields
///
/// The transaction includes all standard transaction fields plus expanded
/// versions of related entities. When a relationship is expanded, you get
/// the full object instead of just an ID.
///
/// # Example
///
/// ```rust,ignore
/// let txn = client.get_transaction_full(txn_id).await?;
///
/// // Transaction data
/// println!("Amount: ${:.2}", txn.total.unwrap_or(0) as f64 / 100.0);
/// println!("Status: {:?}", txn.status);
///
/// // Expanded payment
/// if let Some(ref payment) = txn.payment {
///     println!("Card: {}", payment.display());
/// }
///
/// // Expanded token with nested customer
/// if let Some(ref token) = txn.token {
///     println!("Token: {}", token.token.as_deref().unwrap_or("N/A"));
///     if let Some(ref customer) = token.customer {
///         println!("Customer: {} {}", customer.first, customer.last);
///     }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionExpanded {
    // -------------------------------------------------------------------------
    // Core Identifiers
    // -------------------------------------------------------------------------

    /// The ID of this transaction.
    pub id: PayrixId,

    /// The date and time this transaction was created.
    #[serde(default)]
    pub created: Option<String>,

    /// The date and time this transaction was last modified.
    #[serde(default)]
    pub modified: Option<String>,

    /// The login that created this transaction.
    #[serde(default)]
    pub creator: Option<PayrixId>,

    /// The login that last modified this transaction.
    #[serde(default)]
    pub modifier: Option<PayrixId>,

    // -------------------------------------------------------------------------
    // Transaction Type and Status
    // -------------------------------------------------------------------------

    /// The transaction type (Sale, Auth, Capture, Refund, etc.).
    #[serde(default, rename = "type")]
    pub txn_type: Option<TransactionType>,

    /// The transaction status.
    #[serde(default)]
    pub status: Option<TransactionStatus>,

    /// Transaction origin (ecommerce, terminal, etc.).
    #[serde(default)]
    pub origin: Option<i32>,

    // -------------------------------------------------------------------------
    // Amounts (in cents)
    // -------------------------------------------------------------------------

    /// Total transaction amount in cents.
    #[serde(default)]
    pub total: Option<i64>,

    /// Approved amount in cents.
    #[serde(default)]
    pub approved: Option<i64>,

    /// Original approved amount in cents.
    #[serde(default)]
    pub original_approved: Option<i64>,

    /// Refunded amount in cents.
    #[serde(default)]
    pub refunded: Option<i64>,

    /// Reserved amount in cents.
    #[serde(default)]
    pub reserved: Option<i64>,

    // -------------------------------------------------------------------------
    // Transaction Details
    // -------------------------------------------------------------------------

    /// Authorization code.
    #[serde(default)]
    pub authorization: Option<String>,

    /// Auth code from processor.
    #[serde(default)]
    pub auth_code: Option<String>,

    /// Currency code (e.g., "USD").
    #[serde(default)]
    pub currency: Option<String>,

    /// Transaction descriptor (appears on statements).
    #[serde(default)]
    pub descriptor: Option<String>,

    /// Transaction description.
    #[serde(default)]
    pub description: Option<String>,

    /// Card-on-file type.
    #[serde(default)]
    pub cof_type: Option<String>,

    /// Card expiration in MMYY format.
    #[serde(default)]
    pub expiration: Option<String>,

    /// CVV response code.
    #[serde(default)]
    pub cvv: Option<i32>,

    /// Processing platform.
    #[serde(default)]
    pub platform: Option<String>,

    // -------------------------------------------------------------------------
    // Date Fields (API sometimes returns these as integers in YYYYMMDD format)
    // -------------------------------------------------------------------------

    /// Date/time captured.
    #[serde(default, deserialize_with = "deserialize_string_or_int")]
    pub captured: Option<String>,

    /// Date/time settled.
    #[serde(default, deserialize_with = "deserialize_string_or_int")]
    pub settled: Option<String>,

    /// Date/time returned.
    #[serde(default, deserialize_with = "deserialize_string_or_int")]
    pub returned: Option<String>,

    /// Date funded (integer in YYYYMMDD format).
    #[serde(default, deserialize_with = "deserialize_optional_i32")]
    pub funded: Option<i32>,

    // -------------------------------------------------------------------------
    // Customer Info (from transaction, not expanded customer)
    // -------------------------------------------------------------------------

    /// First name.
    #[serde(default)]
    pub first: Option<String>,

    /// Middle name.
    #[serde(default)]
    pub middle: Option<String>,

    /// Last name.
    #[serde(default)]
    pub last: Option<String>,

    /// Email address.
    #[serde(default)]
    pub email: Option<String>,

    /// Phone number.
    #[serde(default)]
    pub phone: Option<String>,

    // -------------------------------------------------------------------------
    // Address
    // -------------------------------------------------------------------------

    /// Address line 1.
    #[serde(default)]
    pub address1: Option<String>,

    /// Address line 2.
    #[serde(default)]
    pub address2: Option<String>,

    /// City.
    #[serde(default)]
    pub city: Option<String>,

    /// State.
    #[serde(default)]
    pub state: Option<String>,

    /// ZIP/postal code.
    #[serde(default)]
    pub zip: Option<String>,

    /// Country.
    #[serde(default)]
    pub country: Option<String>,

    // -------------------------------------------------------------------------
    // Status Flags
    // -------------------------------------------------------------------------

    /// Whether this transaction is inactive.
    #[serde(default, with = "bool_from_int_default_false")]
    pub inactive: bool,

    /// Whether this transaction is frozen.
    #[serde(default, with = "bool_from_int_default_false")]
    pub frozen: bool,

    /// Whether funding is enabled.
    #[serde(default)]
    pub funding_enabled: Option<i32>,

    // -------------------------------------------------------------------------
    // Relationship IDs (non-expanded)
    // -------------------------------------------------------------------------

    /// Batch ID (not expanded).
    #[serde(default)]
    pub batch: Option<PayrixId>,

    /// Related transaction ID (for refunds, etc.).
    #[serde(default)]
    pub fortxn: Option<PayrixId>,

    /// Source transaction ID (for reauthorizations).
    #[serde(default)]
    pub fromtxn: Option<PayrixId>,

    // -------------------------------------------------------------------------
    // Expanded Relationships
    // -------------------------------------------------------------------------

    /// Expanded payment details.
    ///
    /// Contains card/account information like BIN, last4, routing number.
    #[serde(default)]
    pub payment: Option<Payment>,

    /// Expanded token with optional nested customer.
    ///
    /// When using `token|customer` expansion, the customer is nested here.
    #[serde(default)]
    pub token: Option<TokenExpanded>,

    /// Merchant ID (not expanded - use separate query if full merchant data needed).
    #[serde(default)]
    pub merchant: Option<PayrixId>,

    /// Expanded subscription.
    #[serde(default)]
    pub subscription: Option<Subscription>,
}

impl TransactionExpanded {
    /// Returns the transaction amount as a decimal (dollars, not cents).
    pub fn amount_dollars(&self) -> f64 {
        self.total.unwrap_or(0) as f64 / 100.0
    }

    /// Returns the approved amount as a decimal (dollars, not cents).
    pub fn approved_dollars(&self) -> f64 {
        self.approved.unwrap_or(0) as f64 / 100.0
    }

    /// Returns the payment display string if payment is expanded.
    pub fn payment_display(&self) -> Option<String> {
        self.payment.as_ref().map(|p| p.display())
    }

    /// Returns the customer name from the transaction's first/last fields.
    ///
    /// Note: Customer object is not expanded in transaction responses.
    pub fn customer_name(&self) -> Option<String> {
        let first = self.first.as_deref().unwrap_or("");
        let last = self.last.as_deref().unwrap_or("");
        let name = format!("{} {}", first, last).trim().to_string();
        if name.is_empty() {
            None
        } else {
            Some(name)
        }
    }

    /// Returns the customer ID from the expanded token.
    ///
    /// Note: Customer data is not expanded. Use `client.get_customer_expanded()`
    /// to fetch full customer details.
    pub fn customer_id(&self) -> Option<&str> {
        self.token.as_ref().and_then(|t| t.customer_id())
    }

    /// Returns true if this transaction was approved.
    pub fn is_approved(&self) -> bool {
        matches!(self.status, Some(TransactionStatus::Captured))
    }
}

// =============================================================================
// CustomerExpanded
// =============================================================================

/// A customer with expanded relationships.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerExpanded {
    // Core fields - flatten the base customer
    /// The ID of this customer.
    pub id: PayrixId,

    /// The date and time this customer was created.
    #[serde(default)]
    pub created: Option<String>,

    /// First name.
    #[serde(default)]
    pub first: Option<String>,

    /// Last name.
    #[serde(default)]
    pub last: Option<String>,

    /// Email address.
    #[serde(default)]
    pub email: Option<String>,

    /// Merchant ID.
    #[serde(default)]
    pub merchant: Option<PayrixId>,

    /// Whether this customer is inactive.
    #[serde(default, with = "bool_from_int_default_false")]
    pub inactive: bool,

    // Expanded relationships

    /// Expanded tokens.
    #[serde(default)]
    pub tokens: Option<Vec<TokenExpanded>>,

    /// Expanded invoices (as JSON for now).
    #[serde(default)]
    pub invoices: Option<Vec<serde_json::Value>>,
}

// =============================================================================
// SubscriptionExpanded
// =============================================================================

/// A subscription with expanded relationships.
///
/// Subscriptions can expand the `plan` relationship to get full plan details
/// in a single API call.
///
/// # Example
///
/// ```rust,ignore
/// let sub = client.get_subscription_expanded(sub_id).await?;
///
/// if let Some(ref plan) = sub.plan {
///     println!("Plan: {} - ${:.2}/month",
///         plan.name.as_deref().unwrap_or("Unknown"),
///         plan.amount.unwrap_or(0) as f64 / 100.0);
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionExpanded {
    // -------------------------------------------------------------------------
    // Core Identifiers
    // -------------------------------------------------------------------------

    /// The ID of this subscription.
    pub id: PayrixId,

    /// The date and time this subscription was created.
    #[serde(default)]
    pub created: Option<String>,

    /// The date and time this subscription was last modified.
    #[serde(default)]
    pub modified: Option<String>,

    /// The login that created this subscription.
    #[serde(default)]
    pub creator: Option<PayrixId>,

    /// The login that last modified this subscription.
    #[serde(default)]
    pub modifier: Option<PayrixId>,

    // -------------------------------------------------------------------------
    // Subscription Data
    // -------------------------------------------------------------------------

    /// Statement entity for billing.
    #[serde(default)]
    pub statement_entity: Option<PayrixId>,

    /// First transaction processed through this subscription.
    #[serde(default)]
    pub first_txn: Option<PayrixId>,

    /// Start date (YYYYMMDD format).
    #[serde(default)]
    pub start: Option<i32>,

    /// End date (YYYYMMDD format).
    #[serde(default)]
    pub finish: Option<i32>,

    /// Tax amount in cents.
    #[serde(default)]
    pub tax: Option<i64>,

    /// Statement descriptor.
    #[serde(default)]
    pub descriptor: Option<String>,

    /// Transaction description.
    #[serde(default)]
    pub txn_description: Option<String>,

    /// Order reference.
    #[serde(default)]
    pub order: Option<String>,

    /// Transaction origin.
    #[serde(default)]
    pub origin: Option<SubscriptionOrigin>,

    /// 3D Secure authentication token.
    #[serde(default)]
    pub authentication: Option<String>,

    /// 3D Secure authentication ID.
    #[serde(default)]
    pub authentication_id: Option<String>,

    /// Current consecutive payment failures.
    #[serde(default)]
    pub failures: Option<i32>,

    /// Maximum allowed consecutive failures.
    #[serde(default)]
    pub max_failures: Option<i32>,

    /// Whether this subscription is inactive.
    #[serde(default, with = "bool_from_int_default_false")]
    pub inactive: bool,

    /// Whether this subscription is frozen.
    #[serde(default, with = "bool_from_int_default_false")]
    pub frozen: bool,

    // -------------------------------------------------------------------------
    // Expanded Relationships
    // -------------------------------------------------------------------------

    /// Expanded plan.
    ///
    /// Contains full plan details including schedule, amount, and billing terms.
    #[serde(default)]
    pub plan: Option<Plan>,
}

impl SubscriptionExpanded {
    /// Returns the plan amount in dollars.
    pub fn plan_amount_dollars(&self) -> Option<f64> {
        self.plan
            .as_ref()
            .and_then(|p| p.amount)
            .map(|a| a as f64 / 100.0)
    }

    /// Returns the plan name if available.
    pub fn plan_name(&self) -> Option<&str> {
        self.plan.as_ref().and_then(|p| p.name.as_deref())
    }
}

// =============================================================================
// PlanExpanded
// =============================================================================

/// A plan with expanded relationships.
///
/// Plans can expand `merchant` and `subscriptions` relationships.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlanExpanded {
    // -------------------------------------------------------------------------
    // Core Identifiers
    // -------------------------------------------------------------------------

    /// The ID of this plan.
    pub id: PayrixId,

    /// The date and time this plan was created.
    #[serde(default)]
    pub created: Option<String>,

    /// The date and time this plan was last modified.
    #[serde(default)]
    pub modified: Option<String>,

    /// The login that created this plan.
    #[serde(default)]
    pub creator: Option<PayrixId>,

    /// The login that last modified this plan.
    #[serde(default)]
    pub modifier: Option<PayrixId>,

    // -------------------------------------------------------------------------
    // Plan Data
    // -------------------------------------------------------------------------

    /// Billing ID.
    #[serde(default)]
    pub billing: Option<PayrixId>,

    /// Plan type (recurring or installment).
    #[serde(default, rename = "type")]
    pub plan_type: Option<PlanType>,

    /// Plan name.
    #[serde(default)]
    pub name: Option<String>,

    /// Plan description.
    #[serde(default)]
    pub description: Option<String>,

    /// Transaction description.
    #[serde(default)]
    pub txn_description: Option<String>,

    /// Order reference.
    #[serde(default)]
    pub order: Option<String>,

    /// Billing schedule (daily, weekly, monthly, annually).
    #[serde(default)]
    pub schedule: Option<PlanSchedule>,

    /// Schedule multiplier.
    #[serde(default)]
    pub schedule_factor: Option<i32>,

    /// Unit of measure (actual cents or percentage).
    #[serde(default)]
    pub um: Option<PlanUm>,

    /// Amount in cents.
    #[serde(default)]
    pub amount: Option<i64>,

    /// Maximum consecutive failures before inactivating.
    #[serde(default)]
    pub max_failures: Option<i32>,

    /// Whether this plan is inactive.
    #[serde(default, with = "bool_from_int_default_false")]
    pub inactive: bool,

    /// Whether this plan is frozen.
    #[serde(default, with = "bool_from_int_default_false")]
    pub frozen: bool,

    // -------------------------------------------------------------------------
    // Expanded Relationships
    // -------------------------------------------------------------------------

    /// Merchant ID (not expanded - use separate query if full merchant data needed).
    #[serde(default)]
    pub merchant: Option<PayrixId>,

    /// Expanded subscriptions.
    #[serde(default)]
    pub subscriptions: Option<Vec<Subscription>>,
}

impl PlanExpanded {
    /// Returns the plan amount in dollars.
    pub fn amount_dollars(&self) -> f64 {
        self.amount.unwrap_or(0) as f64 / 100.0
    }

    /// Returns the number of active subscriptions.
    pub fn subscription_count(&self) -> usize {
        self.subscriptions
            .as_ref()
            .map(|s| s.iter().filter(|sub| !sub.inactive).count())
            .unwrap_or(0)
    }
}

// =============================================================================
// ChargebackExpanded
// =============================================================================

/// A chargeback with expanded relationships.
///
/// Chargebacks can expand `txn` (transaction) and `merchant` relationships
/// to get full details in a single API call.
///
/// # Example
///
/// ```rust,ignore
/// let cb = client.get_chargeback_expanded(chargeback_id).await?;
///
/// if let Some(ref txn) = cb.txn {
///     println!("Original transaction: {} for ${:.2}",
///         txn.id.as_str(),
///         txn.total.unwrap_or(0) as f64 / 100.0);
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChargebackExpanded {
    // -------------------------------------------------------------------------
    // Core Identifiers
    // -------------------------------------------------------------------------

    /// The ID of this chargeback.
    pub id: PayrixId,

    /// The date and time this chargeback was created.
    #[serde(default)]
    pub created: Option<String>,

    /// The date and time this chargeback was last modified.
    #[serde(default)]
    pub modified: Option<String>,

    /// The login that created this chargeback.
    #[serde(default)]
    pub creator: Option<PayrixId>,

    /// The login that last modified this chargeback.
    #[serde(default)]
    pub modifier: Option<PayrixId>,

    // -------------------------------------------------------------------------
    // Chargeback Data
    // -------------------------------------------------------------------------

    /// Merchant's processing MID.
    #[serde(default)]
    pub mid: Option<String>,

    /// Chargeback description.
    #[serde(default)]
    pub description: Option<String>,

    /// Total amount in cents.
    #[serde(default)]
    pub total: Option<i64>,

    /// Represented total in cents.
    #[serde(default)]
    pub represented_total: Option<i64>,

    /// Current cycle/stage.
    #[serde(default)]
    pub cycle: Option<ChargebackCycle>,

    /// Currency code.
    #[serde(default)]
    pub currency: Option<String>,

    /// Processing platform.
    #[serde(default)]
    pub platform: Option<String>,

    /// Payment method.
    #[serde(default)]
    pub payment_method: Option<ChargebackPaymentMethod>,

    /// Processing reference number.
    #[serde(default, rename = "ref")]
    pub reference: Option<String>,

    /// Reason description.
    #[serde(default)]
    pub reason: Option<String>,

    /// Reason code.
    #[serde(default)]
    pub reason_code: Option<String>,

    /// Date issued (YYYYMMDD).
    #[serde(default)]
    pub issued: Option<i32>,

    /// Date received (YYYYMMDD).
    #[serde(default)]
    pub received: Option<i32>,

    /// Reply deadline (YYYYMMDD).
    #[serde(default)]
    pub reply: Option<i32>,

    /// Bank reference number.
    #[serde(default)]
    pub bank_ref: Option<String>,

    /// Chargeback reference number.
    #[serde(default)]
    pub chargeback_ref: Option<String>,

    /// Current status.
    #[serde(default)]
    pub status: Option<ChargebackStatusValue>,

    /// Last status change ID.
    #[serde(default)]
    pub last_status_change: Option<PayrixId>,

    /// Whether actionable.
    #[serde(default, with = "bool_from_int_default_false")]
    pub actionable: bool,

    /// Whether shadowed.
    #[serde(default, with = "bool_from_int_default_false")]
    pub shadow: bool,

    /// Whether inactive.
    #[serde(default, with = "bool_from_int_default_false")]
    pub inactive: bool,

    /// Whether frozen.
    #[serde(default, with = "bool_from_int_default_false")]
    pub frozen: bool,

    // -------------------------------------------------------------------------
    // Expanded Relationships
    // -------------------------------------------------------------------------

    /// Expanded transaction.
    ///
    /// The original transaction that was disputed.
    #[serde(default)]
    pub txn: Option<Transaction>,

    /// Merchant ID (not expanded - use separate query if full merchant data needed).
    #[serde(default)]
    pub merchant: Option<PayrixId>,
}

impl ChargebackExpanded {
    /// Returns the chargeback amount in dollars.
    pub fn amount_dollars(&self) -> f64 {
        self.total.unwrap_or(0) as f64 / 100.0
    }

    /// Returns the original transaction amount in dollars.
    pub fn original_transaction_amount(&self) -> Option<f64> {
        self.txn.as_ref().and_then(|t| t.total).map(|a| a as f64 / 100.0)
    }

    /// Returns true if this chargeback can still be responded to.
    pub fn is_actionable(&self) -> bool {
        self.actionable && matches!(self.status, Some(ChargebackStatusValue::Open))
    }

    /// Returns the merchant ID if available.
    ///
    /// Note: Merchant data is not expanded in chargeback responses.
    /// Use `client.get_merchant_expanded()` to fetch full merchant details.
    pub fn merchant_id(&self) -> Option<&str> {
        self.merchant.as_ref().map(|m| m.as_str())
    }
}

// =============================================================================
// BatchExpanded
// =============================================================================

/// A batch with expanded relationships.
///
/// Batches can expand `merchant` and `txns` (transactions) relationships.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchExpanded {
    // -------------------------------------------------------------------------
    // Core Identifiers
    // -------------------------------------------------------------------------

    /// The ID of this batch.
    pub id: PayrixId,

    /// The date and time this batch was created.
    #[serde(default)]
    pub created: Option<String>,

    /// The date and time this batch was last modified.
    #[serde(default)]
    pub modified: Option<String>,

    /// The login that created this batch.
    #[serde(default)]
    pub creator: Option<PayrixId>,

    /// The login that last modified this batch.
    #[serde(default)]
    pub modifier: Option<PayrixId>,

    // -------------------------------------------------------------------------
    // Batch Data
    // -------------------------------------------------------------------------

    /// Batch date.
    #[serde(default)]
    pub date: Option<String>,

    /// Processing date.
    #[serde(default)]
    pub processing_date: Option<String>,

    /// Processing ID.
    #[serde(default)]
    pub processing_id: Option<String>,

    /// Processing platform.
    #[serde(default)]
    pub platform: Option<Platform>,

    /// Batch status (open/closed).
    #[serde(default)]
    pub status: Option<BatchStatus>,

    /// Reference code.
    #[serde(default, rename = "ref")]
    pub reference: Option<String>,

    /// Client reference code.
    #[serde(default)]
    pub client_ref: Option<String>,

    /// Close time.
    #[serde(default)]
    pub close_time: Option<String>,

    /// Whether inactive.
    #[serde(default, with = "bool_from_int_default_false")]
    pub inactive: bool,

    /// Whether frozen.
    #[serde(default, with = "bool_from_int_default_false")]
    pub frozen: bool,

    // -------------------------------------------------------------------------
    // Expanded Relationships
    // -------------------------------------------------------------------------

    /// Merchant ID (not expanded - use separate query if full merchant data needed).
    #[serde(default)]
    pub merchant: Option<PayrixId>,

    /// Expanded transactions in this batch.
    #[serde(default)]
    pub txns: Option<Vec<Transaction>>,
}

impl BatchExpanded {
    /// Returns the number of transactions in this batch.
    pub fn transaction_count(&self) -> usize {
        self.txns.as_ref().map(|t| t.len()).unwrap_or(0)
    }

    /// Returns the total amount of all transactions in dollars.
    pub fn total_amount_dollars(&self) -> f64 {
        self.txns
            .as_ref()
            .map(|txns| txns.iter().filter_map(|t| t.total).sum::<i64>())
            .unwrap_or(0) as f64
            / 100.0
    }

    /// Returns true if this batch is still open for transactions.
    pub fn is_open(&self) -> bool {
        matches!(self.status, Some(BatchStatus::Open))
    }

    /// Returns the merchant ID if available.
    ///
    /// Note: Merchant data is not expanded in batch responses.
    /// Use `client.get_merchant_expanded()` to fetch full merchant details.
    pub fn merchant_id(&self) -> Option<&str> {
        self.merchant.as_ref().map(|m| m.as_str())
    }
}

// =============================================================================
// MerchantExpanded
// =============================================================================

/// A merchant with expanded relationships.
///
/// Merchants can expand the `members` relationship to get beneficial owners
/// and control persons in a single API call.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantExpanded {
    // -------------------------------------------------------------------------
    // Core Identifiers
    // -------------------------------------------------------------------------

    /// The ID of this merchant.
    pub id: PayrixId,

    /// The date and time this merchant was created.
    #[serde(default)]
    pub created: Option<String>,

    /// The date and time this merchant was last modified.
    #[serde(default)]
    pub modified: Option<String>,

    /// The login that created this merchant.
    #[serde(default)]
    pub creator: Option<PayrixId>,

    /// The login that last modified this merchant.
    #[serde(default)]
    pub modifier: Option<PayrixId>,

    // -------------------------------------------------------------------------
    // Merchant Data
    // -------------------------------------------------------------------------

    /// DBA (Doing Business As) name.
    #[serde(default)]
    pub dba: Option<String>,

    /// Legal business name.
    #[serde(default)]
    pub name: Option<String>,

    /// Entity ID.
    #[serde(default)]
    pub entity: Option<PayrixId>,

    /// Merchant email.
    #[serde(default)]
    pub email: Option<String>,

    /// Merchant phone.
    #[serde(default)]
    pub phone: Option<String>,

    /// Website URL.
    #[serde(default)]
    pub website: Option<String>,

    /// Address line 1.
    #[serde(default)]
    pub address1: Option<String>,

    /// Address line 2.
    #[serde(default)]
    pub address2: Option<String>,

    /// City.
    #[serde(default)]
    pub city: Option<String>,

    /// State.
    #[serde(default)]
    pub state: Option<String>,

    /// ZIP/postal code.
    #[serde(default)]
    pub zip: Option<String>,

    /// Country.
    #[serde(default)]
    pub country: Option<String>,

    /// Timezone.
    #[serde(default)]
    pub timezone: Option<String>,

    /// MCC (Merchant Category Code).
    #[serde(default)]
    pub mcc: Option<String>,

    /// Merchant status.
    #[serde(default)]
    pub status: Option<i32>,

    /// Whether inactive.
    #[serde(default, with = "bool_from_int_default_false")]
    pub inactive: bool,

    /// Whether frozen.
    #[serde(default, with = "bool_from_int_default_false")]
    pub frozen: bool,

    // -------------------------------------------------------------------------
    // Expanded Relationships
    // -------------------------------------------------------------------------

    /// Expanded members (beneficial owners, control persons).
    #[serde(default)]
    pub members: Option<Vec<Member>>,
}

impl MerchantExpanded {
    /// Returns the number of members.
    pub fn member_count(&self) -> usize {
        self.members.as_ref().map(|m| m.len()).unwrap_or(0)
    }

    /// Returns the primary member if one exists.
    pub fn primary_member(&self) -> Option<&Member> {
        self.members
            .as_ref()
            .and_then(|members| members.iter().find(|m| m.primary))
    }

    /// Returns total ownership percentage of all members.
    pub fn total_ownership_percent(&self) -> f64 {
        self.members
            .as_ref()
            .map(|members| members.iter().filter_map(|m| m.ownership).sum::<i32>())
            .unwrap_or(0) as f64
            / 100.0
    }

    /// Returns a display name for the merchant (DBA or name or "Unknown").
    pub fn display_name(&self) -> String {
        self.dba
            .as_ref()
            .or(self.name.as_ref())
            .cloned()
            .unwrap_or_else(|| "Unknown".to_string())
    }
}

// =============================================================================
// Tests
// =============================================================================

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

    // =========================================================================
    // TokenExpanded Tests
    // =========================================================================

    #[test]
    fn test_token_expanded_with_minimal_fields() {
        // Test that TokenExpanded works with only required fields
        let json = json!({
            "id": "t1_tok_test123456789012345678"
        });

        let token: TokenExpanded = serde_json::from_value(json).unwrap();

        assert!(token.id.as_str().starts_with("t1_tok_"));
        assert!(token.payment.is_none());
        assert!(token.customer.is_none());
        assert!(!token.inactive);
        assert!(!token.frozen);
    }

    #[test]
    fn test_token_expanded_with_expansions() {
        let json = json!({
            "id": "t1_tok_694380e35c8eca506eb3856",
            "token": "36720364621c45c3227c95022e527839",
            "status": "ready",
            "expiration": "1229",
            "inactive": 1,
            "frozen": 0,
            "payment": {
                "bin": "411111",
                "method": 2,
                "number": "1111"
            },
            "customer": "t1_cus_694380e3086a60cfae6d1eb"
        });

        let token: TokenExpanded = serde_json::from_value(json).unwrap();

        // Core fields
        assert!(token.id.as_str().starts_with("t1_tok_"));
        assert!(token.token.is_some());
        assert_eq!(token.status, Some(TokenStatus::Ready));
        assert!(token.inactive);

        // Payment expansion should be present
        assert!(token.payment.is_some());
        let payment = token.payment.as_ref().unwrap();
        assert_eq!(payment.method, Some(PaymentMethod::Visa));
        assert_eq!(payment.bin.as_deref(), Some("411111"));

        // Customer should be an ID (not expanded by API)
        assert!(token.customer.is_some());
        assert!(token.customer_id().unwrap().starts_with("t1_cus_"));

        // Convenience methods
        assert_eq!(token.payment_method(), Some(PaymentMethod::Visa));
        assert!(token.customer_id().is_some());
    }

    #[test]
    fn test_token_expanded_handles_unknown_fields() {
        // API may return fields not in our schema - should not fail
        let json = json!({
            "id": "t1_tok_test123456789012345678",
            "status": "ready",
            "future_field": "should be ignored",
            "another_unknown": 12345
        });

        let result: Result<TokenExpanded, _> = serde_json::from_value(json);
        assert!(result.is_ok(), "Should handle unknown fields gracefully");

        let token = result.unwrap();
        assert_eq!(token.status, Some(TokenStatus::Ready));
    }

    // =========================================================================
    // TransactionExpanded Tests
    // =========================================================================

    #[test]
    fn test_transaction_expanded_with_minimal_fields() {
        let json = json!({
            "id": "t1_txn_test123456789012345678"
        });

        let txn: TransactionExpanded = serde_json::from_value(json).unwrap();

        assert!(txn.id.as_str().starts_with("t1_txn_"));
        assert!(txn.payment.is_none());
        assert!(txn.token.is_none());
        assert!(txn.merchant.is_none());
        assert_eq!(txn.amount_dollars(), 0.0);
    }

    #[test]
    fn test_transaction_expanded_with_all_expansions() {
        let json = json!({
            "id": "t1_txn_694380e3e1bd4ad74cdf956",
            "type": 1,
            "status": 3,
            "total": 1000,
            "approved": 1000,
            "currency": "USD",
            "first": "John",
            "last": "Doe",
            "payment": {
                "bin": "411111",
                "method": 2,
                "number": "1111"
            },
            "token": {
                "id": "t1_tok_694380e35c8eca506eb3856",
                "token": "abc123",
                "customer": "t1_cus_694380e3086a60cfae6d1eb"
            },
            "merchant": "t1_mer_test123456789012345678"
        });

        let txn: TransactionExpanded = serde_json::from_value(json).unwrap();

        // Core fields
        assert!(txn.id.as_str().starts_with("t1_txn_"));
        assert_eq!(txn.total, Some(1000));
        assert_eq!(txn.amount_dollars(), 10.0);

        // Payment expansion (payment IS expanded as an object)
        assert!(txn.payment.is_some());
        assert_eq!(txn.payment.as_ref().unwrap().method, Some(PaymentMethod::Visa));

        // Token expansion with nested customer ID
        assert!(txn.token.is_some());
        let token = txn.token.as_ref().unwrap();
        assert!(token.customer.is_some());
        assert!(token.customer_id().unwrap().starts_with("t1_cus_"));

        // Merchant is an ID (not expanded by API)
        assert!(txn.merchant.is_some());
        assert!(txn.merchant.as_ref().unwrap().as_str().starts_with("t1_mer_"));

        // Convenience methods (customer_name from first/last fields)
        assert_eq!(txn.customer_name(), Some("John Doe".to_string()));
        assert!(txn.payment_display().is_some());
    }

    #[test]
    fn test_transaction_expanded_amount_calculation() {
        let json = json!({
            "id": "t1_txn_test123456789012345678",
            "total": 12345
        });

        let txn: TransactionExpanded = serde_json::from_value(json).unwrap();
        assert_eq!(txn.amount_dollars(), 123.45);
    }

    // =========================================================================
    // CustomerExpanded Tests
    // =========================================================================

    #[test]
    fn test_customer_expanded_with_tokens_array() {
        let json = json!({
            "id": "t1_cus_test123456789012345678",
            "first": "Jane",
            "last": "Smith",
            "tokens": [
                {"id": "t1_tok_111111111111111111111", "status": "ready"},
                {"id": "t1_tok_222222222222222222222", "status": "pending"}
            ]
        });

        let customer: CustomerExpanded = serde_json::from_value(json).unwrap();

        assert!(customer.id.as_str().starts_with("t1_cus_"));
        assert_eq!(customer.first.as_deref(), Some("Jane"));

        // Tokens expansion
        assert!(customer.tokens.is_some());
        let tokens = customer.tokens.as_ref().unwrap();
        assert_eq!(tokens.len(), 2);

        // Each token should have an ID
        for token in tokens {
            assert!(token.id.as_str().starts_with("t1_tok_"));
        }
    }

    // =========================================================================
    // Subscription & Plan Expanded Tests
    // =========================================================================

    #[test]
    fn test_subscription_expanded_with_plan() {
        let json = json!({
            "id": "t1_sbn_test123456789012345678",
            "start": 20250101,
            "plan": {
                "id": "t1_pln_test123456789012345678",
                "name": "Monthly Plan",
                "amount": 1999
            }
        });

        let sub: SubscriptionExpanded = serde_json::from_value(json).unwrap();

        assert!(sub.id.as_str().starts_with("t1_sbn_"));
        assert!(sub.plan.is_some());

        let plan = sub.plan.as_ref().unwrap();
        assert_eq!(plan.name.as_deref(), Some("Monthly Plan"));
        assert_eq!(plan.amount, Some(1999));

        // Convenience methods
        assert_eq!(sub.plan_amount_dollars(), Some(19.99));
        assert_eq!(sub.plan_name(), Some("Monthly Plan"));
    }

    #[test]
    fn test_plan_expanded_with_subscriptions() {
        let json = json!({
            "id": "t1_pln_test123456789012345678",
            "name": "Premium Plan",
            "amount": 4999,
            "subscriptions": [
                {"id": "t1_sbn_111111111111111111111", "inactive": 0},
                {"id": "t1_sbn_222222222222222222222", "inactive": 1}
            ]
        });

        let plan: PlanExpanded = serde_json::from_value(json).unwrap();

        assert!(plan.id.as_str().starts_with("t1_pln_"));
        assert_eq!(plan.amount_dollars(), 49.99);
        assert_eq!(plan.subscription_count(), 1); // Only active subscriptions
    }

    // =========================================================================
    // Chargeback & Batch Expanded Tests
    // =========================================================================

    #[test]
    fn test_chargeback_expanded_with_transaction() {
        let json = json!({
            "id": "t1_chb_test123456789012345678",
            "status": "open",
            "total": 5000,
            "cycle": "first",
            "actionable": 1,
            "txn": {
                "id": "t1_txn_test123456789012345678",
                "type": 1,
                "total": 5000
            }
        });

        let cb: ChargebackExpanded = serde_json::from_value(json).unwrap();

        assert!(cb.id.as_str().starts_with("t1_chb_"));
        assert_eq!(cb.amount_dollars(), 50.0);
        assert!(cb.is_actionable());
        assert!(cb.txn.is_some());

        // Convenience method
        assert_eq!(cb.original_transaction_amount(), Some(50.0));
    }

    #[test]
    fn test_batch_expanded_with_transactions() {
        let json = json!({
            "id": "t1_bat_test123456789012345678",
            "status": "open",
            "txns": [
                {"id": "t1_txn_111111111111111111111", "type": 1, "total": 1000},
                {"id": "t1_txn_222222222222222222222", "type": 1, "total": 2000}
            ]
        });

        let batch: BatchExpanded = serde_json::from_value(json).unwrap();

        assert!(batch.id.as_str().starts_with("t1_bat_"));
        assert!(batch.is_open());
        assert_eq!(batch.transaction_count(), 2);
        assert_eq!(batch.total_amount_dollars(), 30.0);
    }

    // =========================================================================
    // Merchant Expanded Tests
    // =========================================================================

    #[test]
    fn test_merchant_expanded_with_members() {
        let json = json!({
            "id": "t1_mer_test123456789012345678",
            "dba": "Test Business",
            "name": "Test Business Inc",
            "members": [
                {"id": "t1_mem_111111111111111111111", "first": "John", "ownership": 6000},
                {"id": "t1_mem_222222222222222222222", "first": "Jane", "ownership": 4000}
            ]
        });

        let merchant: MerchantExpanded = serde_json::from_value(json).unwrap();

        assert!(merchant.id.as_str().starts_with("t1_mer_"));
        assert_eq!(merchant.display_name(), "Test Business");
        assert_eq!(merchant.member_count(), 2);
        assert_eq!(merchant.total_ownership_percent(), 100.0);
    }
}