shopify-sdk 1.0.0

A Rust SDK for the Shopify 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
//! Transaction resource implementation.
//!
//! This module provides the Transaction resource, which represents a payment
//! transaction associated with an order in Shopify.
//!
//! # Nested Path Pattern
//!
//! Transactions are always accessed under an order:
//! - List: `/orders/{order_id}/transactions`
//! - Find: `/orders/{order_id}/transactions/{id}`
//! - Create: `/orders/{order_id}/transactions`
//! - Count: `/orders/{order_id}/transactions/count`
//!
//! Use `Transaction::all_with_parent()` to list transactions under a specific order.
//!
//! # Note
//!
//! Transactions cannot be updated or deleted. They represent immutable records
//! of payment events.
//!
//! # Example
//!
//! ```rust,ignore
//! use shopify_sdk::rest::{RestResource, ResourceResponse};
//! use shopify_sdk::rest::resources::v2025_10::{Transaction, TransactionKind, TransactionListParams};
//!
//! // List transactions under a specific order
//! let transactions = Transaction::all_with_parent(&client, "order_id", 450789469, None).await?;
//! for txn in transactions.iter() {
//!     println!("Transaction: {} - {:?}", txn.amount.as_deref().unwrap_or("0"), txn.kind);
//! }
//!
//! // Create a capture transaction
//! let mut transaction = Transaction {
//!     order_id: Some(450789469),
//!     kind: Some(TransactionKind::Capture),
//!     amount: Some("199.99".to_string()),
//!     ..Default::default()
//! };
//! let saved = transaction.save(&client).await?;
//!
//! // Count transactions for an order
//! let count = Transaction::count_with_parent(&client, "order_id", 450789469, None).await?;
//! println!("Total transactions: {}", count);
//! ```

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::clients::RestClient;
use crate::rest::{
    build_path, get_path, ResourceError, ResourceOperation, ResourcePath, RestResource,
};
use crate::HttpMethod;

/// The kind of transaction.
///
/// Represents the type of payment operation performed.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum TransactionKind {
    /// Initial authorization of payment.
    #[default]
    Authorization,
    /// Capture of previously authorized payment.
    Capture,
    /// Combined authorization and capture in one step.
    Sale,
    /// Cancellation of an authorization.
    Void,
    /// Return of funds to customer.
    Refund,
}

/// The status of a transaction.
///
/// Indicates whether the transaction succeeded or failed.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum TransactionStatus {
    /// Transaction is pending completion.
    #[default]
    Pending,
    /// Transaction failed.
    Failure,
    /// Transaction completed successfully.
    Success,
    /// Transaction encountered an error.
    Error,
}

/// Payment details for a transaction.
///
/// Contains information about the payment method used.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct PaymentDetails {
    /// The credit card bin number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_card_bin: Option<String>,

    /// AVS result code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub avs_result_code: Option<String>,

    /// CVV result code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cvv_result_code: Option<String>,

    /// The credit card number (masked).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_card_number: Option<String>,

    /// The credit card company.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_card_company: Option<String>,

    /// The name on the credit card.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_card_name: Option<String>,

    /// The credit card wallet.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_card_wallet: Option<String>,

    /// The credit card expiration month.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_card_expiration_month: Option<i32>,

    /// The credit card expiration year.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_card_expiration_year: Option<i32>,

    /// The buyer action info (complex structure).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buyer_action_info: Option<serde_json::Value>,
}

/// Currency exchange adjustment for multi-currency transactions.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct CurrencyExchangeAdjustment {
    /// The ID of the adjustment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<u64>,

    /// The original amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub original_amount: Option<String>,

    /// The final amount after adjustment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub final_amount: Option<String>,

    /// The currency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,

    /// The adjustment amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adjustment: Option<String>,
}

/// A payment transaction for an order.
///
/// Transactions represent payment events such as authorizations, captures,
/// refunds, and voids. They are nested under orders and cannot be updated
/// or deleted after creation.
///
/// # Nested Resource
///
/// Transactions follow the nested path pattern under orders:
/// - All operations require `order_id` context
/// - Use `all_with_parent()` to list transactions under an order
/// - The `order_id` field is required for creating new transactions
///
/// # Fields
///
/// ## Read-Only Fields
/// - `id` - The unique identifier of the transaction
/// - `created_at` - When the transaction was created
/// - `processed_at` - When the transaction was processed
/// - `admin_graphql_api_id` - The GraphQL API ID
///
/// ## Writable Fields
/// - `order_id` - The ID of the order this transaction belongs to
/// - `kind` - The type of transaction (authorization, capture, sale, void, refund)
/// - `amount` - The transaction amount
/// - `currency` - The currency code
/// - `gateway` - The payment gateway used
/// - `parent_id` - The ID of the parent transaction (for captures/refunds)
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct Transaction {
    /// The unique identifier of the transaction.
    /// Read-only field.
    #[serde(skip_serializing)]
    pub id: Option<u64>,

    /// The ID of the order this transaction belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<u64>,

    /// The kind of transaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<TransactionKind>,

    /// The transaction amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<String>,

    /// The status of the transaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<TransactionStatus>,

    /// The payment gateway used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gateway: Option<String>,

    /// A message describing the transaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,

    /// The error code if the transaction failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,

    /// The authorization code from the payment gateway.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorization: Option<String>,

    /// When the authorization expires.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorization_expires_at: Option<DateTime<Utc>>,

    /// The currency code (e.g., "USD").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,

    /// Whether this is a test transaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test: Option<bool>,

    /// The ID of the parent transaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<u64>,

    /// The ID of the location.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location_id: Option<u64>,

    /// The ID of the device.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_id: Option<u64>,

    /// The ID of the user who processed the transaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_id: Option<u64>,

    /// The source name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_name: Option<String>,

    /// When the transaction was processed.
    /// Read-only field.
    #[serde(skip_serializing)]
    pub processed_at: Option<DateTime<Utc>>,

    /// When the transaction was created.
    /// Read-only field.
    #[serde(skip_serializing)]
    pub created_at: Option<DateTime<Utc>>,

    /// The receipt from the payment gateway.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub receipt: Option<serde_json::Value>,

    /// Payment details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_details: Option<PaymentDetails>,

    /// Currency exchange adjustment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency_exchange_adjustment: Option<CurrencyExchangeAdjustment>,

    /// Total unsettled set (complex structure).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_unsettled_set: Option<serde_json::Value>,

    /// Whether this is a manual payment gateway.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub manual_payment_gateway: Option<bool>,

    /// Amount rounding information.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount_rounding: Option<serde_json::Value>,

    /// Payments refund attributes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payments_refund_attributes: Option<serde_json::Value>,

    /// Extended authorization attributes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extended_authorization_attributes: Option<serde_json::Value>,

    /// The admin GraphQL API ID for this transaction.
    /// Read-only field.
    #[serde(skip_serializing)]
    pub admin_graphql_api_id: Option<String>,
}

impl Transaction {
    /// Counts transactions under a specific order.
    ///
    /// # Arguments
    ///
    /// * `client` - The REST client to use for the request
    /// * `parent_id_name` - The name of the parent ID parameter (should be `order_id`)
    /// * `parent_id` - The order ID
    /// * `params` - Optional parameters for filtering
    ///
    /// # Returns
    ///
    /// The count of matching transactions as a `u64`.
    ///
    /// # Errors
    ///
    /// Returns [`ResourceError::PathResolutionFailed`] if no count path exists.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let count = Transaction::count_with_parent(&client, "order_id", 450789469, None).await?;
    /// println!("Transactions in order: {}", count);
    /// ```
    pub async fn count_with_parent<ParentId: std::fmt::Display + Send>(
        client: &RestClient,
        parent_id_name: &str,
        parent_id: ParentId,
        params: Option<TransactionCountParams>,
    ) -> Result<u64, ResourceError> {
        let mut ids: HashMap<&str, String> = HashMap::new();
        ids.insert(parent_id_name, parent_id.to_string());

        let available_ids: Vec<&str> = ids.keys().copied().collect();
        let path = get_path(Self::PATHS, ResourceOperation::Count, &available_ids).ok_or(
            ResourceError::PathResolutionFailed {
                resource: Self::NAME,
                operation: "count",
            },
        )?;

        let url = build_path(path.template, &ids);

        // Build query params
        let query = params
            .map(|p| {
                let value = serde_json::to_value(&p).map_err(|e| {
                    ResourceError::Http(crate::clients::HttpError::Response(
                        crate::clients::HttpResponseError {
                            code: 400,
                            message: format!("Failed to serialize params: {e}"),
                            error_reference: None,
                        },
                    ))
                })?;

                let mut query = HashMap::new();
                if let serde_json::Value::Object(map) = value {
                    for (key, val) in map {
                        match val {
                            serde_json::Value::String(s) => {
                                query.insert(key, s);
                            }
                            serde_json::Value::Number(n) => {
                                query.insert(key, n.to_string());
                            }
                            serde_json::Value::Bool(b) => {
                                query.insert(key, b.to_string());
                            }
                            _ => {}
                        }
                    }
                }
                Ok::<_, ResourceError>(query)
            })
            .transpose()?
            .filter(|q| !q.is_empty());

        let response = client.get(&url, query).await?;

        if !response.is_ok() {
            return Err(ResourceError::from_http_response(
                response.code,
                &response.body,
                Self::NAME,
                None,
                response.request_id(),
            ));
        }

        // Extract count from response
        let count = response
            .body
            .get("count")
            .and_then(serde_json::Value::as_u64)
            .ok_or_else(|| {
                ResourceError::Http(crate::clients::HttpError::Response(
                    crate::clients::HttpResponseError {
                        code: response.code,
                        message: "Missing 'count' in response".to_string(),
                        error_reference: response.request_id().map(ToString::to_string),
                    },
                ))
            })?;

        Ok(count)
    }
}

impl RestResource for Transaction {
    type Id = u64;
    type FindParams = TransactionFindParams;
    type AllParams = TransactionListParams;
    type CountParams = TransactionCountParams;

    const NAME: &'static str = "Transaction";
    const PLURAL: &'static str = "transactions";

    /// Paths for the Transaction resource.
    ///
    /// Transactions are NESTED under orders. All operations require `order_id`.
    /// Note: Transactions cannot be updated or deleted.
    const PATHS: &'static [ResourcePath] = &[
        // All paths require order_id
        ResourcePath::new(
            HttpMethod::Get,
            ResourceOperation::Find,
            &["order_id", "id"],
            "orders/{order_id}/transactions/{id}",
        ),
        ResourcePath::new(
            HttpMethod::Get,
            ResourceOperation::All,
            &["order_id"],
            "orders/{order_id}/transactions",
        ),
        ResourcePath::new(
            HttpMethod::Get,
            ResourceOperation::Count,
            &["order_id"],
            "orders/{order_id}/transactions/count",
        ),
        ResourcePath::new(
            HttpMethod::Post,
            ResourceOperation::Create,
            &["order_id"],
            "orders/{order_id}/transactions",
        ),
        // No Update or Delete paths - transactions are immutable
    ];

    fn get_id(&self) -> Option<Self::Id> {
        self.id
    }
}

/// Parameters for finding a single transaction.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct TransactionFindParams {
    /// Comma-separated list of fields to include in the response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fields: Option<String>,

    /// Whether to return the amount in shop currency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub in_shop_currency: Option<bool>,
}

/// Parameters for listing transactions.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct TransactionListParams {
    /// Maximum number of results to return (default: 50, max: 250).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,

    /// Return transactions after this ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since_id: Option<u64>,

    /// Comma-separated list of fields to include in the response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fields: Option<String>,

    /// Whether to return the amount in shop currency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub in_shop_currency: Option<bool>,
}

/// Parameters for counting transactions.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct TransactionCountParams {
    // No specific count params for transactions
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rest::{get_path, ResourceOperation};

    #[test]
    fn test_transaction_kind_enum_serialization() {
        // Test serialization to snake_case
        assert_eq!(
            serde_json::to_string(&TransactionKind::Authorization).unwrap(),
            "\"authorization\""
        );
        assert_eq!(
            serde_json::to_string(&TransactionKind::Capture).unwrap(),
            "\"capture\""
        );
        assert_eq!(
            serde_json::to_string(&TransactionKind::Sale).unwrap(),
            "\"sale\""
        );
        assert_eq!(
            serde_json::to_string(&TransactionKind::Void).unwrap(),
            "\"void\""
        );
        assert_eq!(
            serde_json::to_string(&TransactionKind::Refund).unwrap(),
            "\"refund\""
        );

        // Test deserialization from snake_case
        let auth: TransactionKind = serde_json::from_str("\"authorization\"").unwrap();
        let capture: TransactionKind = serde_json::from_str("\"capture\"").unwrap();
        let sale: TransactionKind = serde_json::from_str("\"sale\"").unwrap();
        let void_txn: TransactionKind = serde_json::from_str("\"void\"").unwrap();
        let refund: TransactionKind = serde_json::from_str("\"refund\"").unwrap();

        assert_eq!(auth, TransactionKind::Authorization);
        assert_eq!(capture, TransactionKind::Capture);
        assert_eq!(sale, TransactionKind::Sale);
        assert_eq!(void_txn, TransactionKind::Void);
        assert_eq!(refund, TransactionKind::Refund);

        // Test default
        assert_eq!(TransactionKind::default(), TransactionKind::Authorization);
    }

    #[test]
    fn test_transaction_status_enum_serialization() {
        // Test serialization
        assert_eq!(
            serde_json::to_string(&TransactionStatus::Pending).unwrap(),
            "\"pending\""
        );
        assert_eq!(
            serde_json::to_string(&TransactionStatus::Failure).unwrap(),
            "\"failure\""
        );
        assert_eq!(
            serde_json::to_string(&TransactionStatus::Success).unwrap(),
            "\"success\""
        );
        assert_eq!(
            serde_json::to_string(&TransactionStatus::Error).unwrap(),
            "\"error\""
        );

        // Test deserialization
        let success: TransactionStatus = serde_json::from_str("\"success\"").unwrap();
        let failure: TransactionStatus = serde_json::from_str("\"failure\"").unwrap();

        assert_eq!(success, TransactionStatus::Success);
        assert_eq!(failure, TransactionStatus::Failure);

        // Test default
        assert_eq!(TransactionStatus::default(), TransactionStatus::Pending);
    }

    #[test]
    fn test_transaction_nested_paths_require_order_id() {
        // All paths should require order_id (nested under orders)

        // Find requires both order_id and id
        let find_path = get_path(Transaction::PATHS, ResourceOperation::Find, &["order_id", "id"]);
        assert!(find_path.is_some());
        assert_eq!(
            find_path.unwrap().template,
            "orders/{order_id}/transactions/{id}"
        );

        // Find with only id should fail (no standalone path)
        let find_without_order = get_path(Transaction::PATHS, ResourceOperation::Find, &["id"]);
        assert!(find_without_order.is_none());

        // All requires order_id
        let all_path = get_path(Transaction::PATHS, ResourceOperation::All, &["order_id"]);
        assert!(all_path.is_some());
        assert_eq!(
            all_path.unwrap().template,
            "orders/{order_id}/transactions"
        );

        // All without order_id should fail
        let all_without_order = get_path(Transaction::PATHS, ResourceOperation::All, &[]);
        assert!(all_without_order.is_none());

        // Count requires order_id
        let count_path = get_path(Transaction::PATHS, ResourceOperation::Count, &["order_id"]);
        assert!(count_path.is_some());
        assert_eq!(
            count_path.unwrap().template,
            "orders/{order_id}/transactions/count"
        );

        // Create requires order_id
        let create_path = get_path(Transaction::PATHS, ResourceOperation::Create, &["order_id"]);
        assert!(create_path.is_some());
        assert_eq!(
            create_path.unwrap().template,
            "orders/{order_id}/transactions"
        );

        // No Update path
        let update_path = get_path(
            Transaction::PATHS,
            ResourceOperation::Update,
            &["order_id", "id"],
        );
        assert!(update_path.is_none());

        // No Delete path
        let delete_path = get_path(
            Transaction::PATHS,
            ResourceOperation::Delete,
            &["order_id", "id"],
        );
        assert!(delete_path.is_none());
    }

    #[test]
    fn test_transaction_struct_serialization() {
        let transaction = Transaction {
            id: Some(389404469),
            order_id: Some(450789469),
            kind: Some(TransactionKind::Capture),
            amount: Some("199.99".to_string()),
            status: Some(TransactionStatus::Success),
            gateway: Some("bogus".to_string()),
            message: Some("Transaction successful".to_string()),
            currency: Some("USD".to_string()),
            test: Some(true),
            parent_id: Some(389404468),
            created_at: Some(
                DateTime::parse_from_rfc3339("2024-01-15T10:30:00Z")
                    .unwrap()
                    .with_timezone(&Utc),
            ),
            admin_graphql_api_id: Some("gid://shopify/OrderTransaction/389404469".to_string()),
            ..Default::default()
        };

        let json = serde_json::to_string(&transaction).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        // Writable fields should be present
        assert_eq!(parsed["order_id"], 450789469);
        assert_eq!(parsed["kind"], "capture");
        assert_eq!(parsed["amount"], "199.99");
        assert_eq!(parsed["status"], "success");
        assert_eq!(parsed["gateway"], "bogus");
        assert_eq!(parsed["message"], "Transaction successful");
        assert_eq!(parsed["currency"], "USD");
        assert_eq!(parsed["test"], true);
        assert_eq!(parsed["parent_id"], 389404468);

        // Read-only fields should be omitted
        assert!(parsed.get("id").is_none());
        assert!(parsed.get("created_at").is_none());
        assert!(parsed.get("processed_at").is_none());
        assert!(parsed.get("admin_graphql_api_id").is_none());
    }

    #[test]
    fn test_transaction_deserialization_from_api_response() {
        let json = r#"{
            "id": 389404469,
            "order_id": 450789469,
            "kind": "capture",
            "amount": "199.99",
            "status": "success",
            "gateway": "bogus",
            "message": "Bogus Gateway: Forced success",
            "error_code": null,
            "authorization": "ch_1234567890",
            "authorization_expires_at": "2024-01-22T10:30:00Z",
            "currency": "USD",
            "test": true,
            "parent_id": 389404468,
            "location_id": 655441491,
            "user_id": 799407056,
            "source_name": "web",
            "processed_at": "2024-01-15T10:30:00Z",
            "created_at": "2024-01-15T10:30:00Z",
            "payment_details": {
                "credit_card_bin": "424242",
                "credit_card_number": "xxxx xxxx xxxx 4242",
                "credit_card_company": "Visa",
                "credit_card_name": "John Doe"
            },
            "receipt": {
                "testcase": true,
                "authorization": "ch_1234567890"
            },
            "admin_graphql_api_id": "gid://shopify/OrderTransaction/389404469"
        }"#;

        let transaction: Transaction = serde_json::from_str(json).unwrap();

        assert_eq!(transaction.id, Some(389404469));
        assert_eq!(transaction.order_id, Some(450789469));
        assert_eq!(transaction.kind, Some(TransactionKind::Capture));
        assert_eq!(transaction.amount, Some("199.99".to_string()));
        assert_eq!(transaction.status, Some(TransactionStatus::Success));
        assert_eq!(transaction.gateway, Some("bogus".to_string()));
        assert_eq!(
            transaction.authorization,
            Some("ch_1234567890".to_string())
        );
        assert!(transaction.authorization_expires_at.is_some());
        assert_eq!(transaction.currency, Some("USD".to_string()));
        assert_eq!(transaction.test, Some(true));
        assert_eq!(transaction.parent_id, Some(389404468));
        assert_eq!(transaction.location_id, Some(655441491));
        assert_eq!(transaction.user_id, Some(799407056));
        assert!(transaction.processed_at.is_some());
        assert!(transaction.created_at.is_some());
        assert!(transaction.payment_details.is_some());
        assert!(transaction.receipt.is_some());

        let payment_details = transaction.payment_details.unwrap();
        assert_eq!(payment_details.credit_card_bin, Some("424242".to_string()));
        assert_eq!(payment_details.credit_card_company, Some("Visa".to_string()));
    }

    #[test]
    fn test_transaction_list_params_serialization() {
        let params = TransactionListParams {
            limit: Some(50),
            since_id: Some(100),
            fields: Some("id,kind,amount".to_string()),
            in_shop_currency: Some(true),
        };

        let json = serde_json::to_value(&params).unwrap();

        assert_eq!(json["limit"], 50);
        assert_eq!(json["since_id"], 100);
        assert_eq!(json["fields"], "id,kind,amount");
        assert_eq!(json["in_shop_currency"], true);

        // Test empty params
        let empty_params = TransactionListParams::default();
        let empty_json = serde_json::to_value(&empty_params).unwrap();
        assert_eq!(empty_json, serde_json::json!({}));
    }

    #[test]
    fn test_transaction_find_params_serialization() {
        let params = TransactionFindParams {
            fields: Some("id,kind,amount".to_string()),
            in_shop_currency: Some(true),
        };

        let json = serde_json::to_value(&params).unwrap();

        assert_eq!(json["fields"], "id,kind,amount");
        assert_eq!(json["in_shop_currency"], true);
    }

    #[test]
    fn test_transaction_get_id_returns_correct_value() {
        // Transaction with ID
        let txn_with_id = Transaction {
            id: Some(389404469),
            order_id: Some(450789469),
            kind: Some(TransactionKind::Capture),
            ..Default::default()
        };
        assert_eq!(txn_with_id.get_id(), Some(389404469));

        // Transaction without ID (new transaction)
        let txn_without_id = Transaction {
            id: None,
            order_id: Some(450789469),
            kind: Some(TransactionKind::Capture),
            ..Default::default()
        };
        assert_eq!(txn_without_id.get_id(), None);
    }

    #[test]
    fn test_transaction_constants() {
        assert_eq!(Transaction::NAME, "Transaction");
        assert_eq!(Transaction::PLURAL, "transactions");
    }
}