stateset-core 1.22.0

Core domain models and business logic for StateSet iCommerce
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
//! Cart and Checkout domain models
//!
//! Based on the Agentic Commerce Protocol (ACP) checkout system.
//! Supports full checkout flow with items, totals, addresses, and fulfillment.

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use stateset_primitives::{CartId, CurrencyCode, CustomerId, OrderId, PaymentId, ProductId};
use strum::{Display, EnumString};
use uuid::Uuid;

use super::Address;
use super::x402::{X402Asset, X402IntentStatus, X402Network};
use crate::errors::Result;
use crate::validation::{Validate, ValidationBuilder};

/// Cart/Checkout Session aggregate
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cart {
    pub id: CartId,
    pub cart_number: String,
    pub customer_id: Option<CustomerId>,
    pub status: CartStatus,
    pub currency: CurrencyCode,

    // Items
    pub items: Vec<CartItem>,

    // Totals
    pub subtotal: Decimal,
    pub tax_amount: Decimal,
    pub shipping_amount: Decimal,
    pub discount_amount: Decimal,
    pub grand_total: Decimal,

    // Customer info (for guest checkout)
    pub customer_email: Option<String>,
    pub customer_phone: Option<String>,
    pub customer_name: Option<String>,

    // Addresses
    pub shipping_address: Option<CartAddress>,
    pub billing_address: Option<CartAddress>,
    pub billing_same_as_shipping: bool,

    // Fulfillment
    pub fulfillment_type: Option<FulfillmentType>,
    pub shipping_method: Option<String>,
    pub shipping_carrier: Option<String>,
    pub estimated_delivery: Option<DateTime<Utc>>,

    // Payment
    pub payment_method: Option<String>,
    pub payment_token: Option<String>,
    pub payment_status: CartPaymentStatus,

    // Discount/Promo
    pub coupon_code: Option<String>,
    pub discount_description: Option<String>,

    // Order reference (after checkout completes)
    pub order_id: Option<OrderId>,
    pub order_number: Option<String>,

    // Metadata
    pub notes: Option<String>,
    pub metadata: Option<serde_json::Value>,

    // Inventory reservations
    pub inventory_reserved: bool,
    pub reservation_expires_at: Option<DateTime<Utc>>,

    // x402 Payment (for stablecoin checkout)
    pub x402_payment: Option<CartX402Payment>,

    // Timestamps
    pub expires_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// Cart line item
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CartItem {
    pub id: Uuid,
    pub cart_id: CartId,
    pub product_id: Option<ProductId>,
    pub variant_id: Option<Uuid>,
    pub sku: String,
    pub name: String,
    pub description: Option<String>,
    pub image_url: Option<String>,
    pub quantity: i32,
    pub unit_price: Decimal,
    pub original_price: Option<Decimal>,
    pub discount_amount: Decimal,
    pub tax_amount: Decimal,
    pub total: Decimal,
    pub weight: Option<Decimal>,
    pub requires_shipping: bool,
    pub metadata: Option<serde_json::Value>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// Cart address (detailed for checkout)
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CartAddress {
    pub first_name: String,
    pub last_name: String,
    pub company: Option<String>,
    pub line1: String,
    pub line2: Option<String>,
    pub city: String,
    pub state: Option<String>,
    pub postal_code: String,
    pub country: String,
    pub phone: Option<String>,
    pub email: Option<String>,
}

impl From<CartAddress> for Address {
    fn from(addr: CartAddress) -> Self {
        Self {
            line1: addr.line1,
            line2: addr.line2,
            city: addr.city,
            state: addr.state,
            postal_code: addr.postal_code,
            country: addr.country,
        }
    }
}

impl From<Address> for CartAddress {
    fn from(addr: Address) -> Self {
        Self {
            first_name: String::new(),
            last_name: String::new(),
            company: None,
            line1: addr.line1,
            line2: addr.line2,
            city: addr.city,
            state: addr.state,
            postal_code: addr.postal_code,
            country: addr.country,
            phone: None,
            email: None,
        }
    }
}

/// x402 payment configuration for cart checkout
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CartX402Payment {
    /// x402 payment intent ID (if created)
    pub intent_id: Option<Uuid>,
    /// Payer wallet address
    pub payer_address: String,
    /// Target blockchain network
    pub network: X402Network,
    /// Payment asset (stablecoin)
    pub asset: X402Asset,
    /// Current status of the x402 payment
    pub status: X402IntentStatus,
}

/// Input for setting x402 payment on cart
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetCartX402Payment {
    /// Payer wallet address
    pub payer_address: String,
    /// Target blockchain network
    pub network: X402Network,
    /// Payment asset (stablecoin)
    pub asset: X402Asset,
}

/// Result of x402 checkout attempt
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum X402CheckoutResult {
    /// Payment is required - return HTTP 402 with this data
    PaymentRequired(X402PaymentRequiredData),
    /// Intent was created and is awaiting signature
    IntentCreated(X402IntentCreatedData),
    /// Intent is signed and awaiting settlement
    AwaitingSettlement(X402AwaitingSettlementData),
    /// Checkout completed successfully
    Completed(CheckoutResult),
}

/// Data for HTTP 402 Payment Required response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct X402PaymentRequiredData {
    pub cart_id: CartId,
    pub payee_address: String,
    pub amount: u64,
    pub amount_display: String,
    pub asset: X402Asset,
    pub network: X402Network,
    pub chain_id: u64,
    pub valid_seconds: u64,
}

/// Data when intent is created and awaiting signature
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct X402IntentCreatedData {
    pub cart_id: CartId,
    pub intent_id: Uuid,
    pub signing_hash: String,
    pub amount: u64,
    pub amount_display: String,
    pub asset: X402Asset,
    pub network: X402Network,
    pub payee_address: String,
    pub valid_until: u64,
    pub nonce: u64,
}

/// Data when awaiting on-chain settlement
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct X402AwaitingSettlementData {
    pub cart_id: CartId,
    pub intent_id: Uuid,
    pub status: X402IntentStatus,
    pub sequence_number: Option<u64>,
    pub batch_id: Option<Uuid>,
}

/// Cart status enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Display, EnumString)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum CartStatus {
    /// Cart is active and being modified
    Active,
    /// Ready for payment (all required info collected)
    #[strum(serialize = "ready_for_payment", serialize = "readyforpayment")]
    ReadyForPayment,
    /// Payment processing
    #[strum(serialize = "payment_pending", serialize = "paymentpending")]
    PaymentPending,
    /// Checkout completed, order created
    Completed,
    /// Cart abandoned by customer
    Abandoned,
    /// Cart cancelled
    #[strum(serialize = "cancelled", serialize = "canceled")]
    Cancelled,
    /// Cart expired
    Expired,
}

impl Default for CartStatus {
    fn default() -> Self {
        Self::Active
    }
}

/// Cart payment status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Display, EnumString)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum CartPaymentStatus {
    /// No payment attempted
    None,
    /// Payment method selected
    #[strum(serialize = "method_selected", serialize = "methodselected")]
    MethodSelected,
    /// Payment authorized but not captured
    Authorized,
    /// Payment captured/completed
    Captured,
    /// Payment failed
    Failed,
    /// Payment refunded
    Refunded,
}

impl Default for CartPaymentStatus {
    fn default() -> Self {
        Self::None
    }
}

/// Fulfillment type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Display, EnumString)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum FulfillmentType {
    /// Ship to address
    Shipping,
    /// Store/local pickup
    #[strum(serialize = "pickup", serialize = "pick_up", serialize = "pick-up")]
    Pickup,
    /// Digital delivery
    Digital,
}

impl Default for FulfillmentType {
    fn default() -> Self {
        Self::Shipping
    }
}

/// Shipping rate/option
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShippingRate {
    pub id: String,
    pub carrier: String,
    pub service: String,
    pub description: Option<String>,
    pub price: Decimal,
    pub currency: CurrencyCode,
    pub estimated_days: Option<i32>,
    pub estimated_delivery: Option<DateTime<Utc>>,
}

/// Input for creating a new cart
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CreateCart {
    pub customer_id: Option<CustomerId>,
    pub customer_email: Option<String>,
    pub customer_name: Option<String>,
    pub currency: Option<CurrencyCode>,
    pub items: Option<Vec<AddCartItem>>,
    pub shipping_address: Option<CartAddress>,
    pub billing_address: Option<CartAddress>,
    pub notes: Option<String>,
    pub metadata: Option<serde_json::Value>,
    pub expires_in_minutes: Option<i64>,
}

/// Input for adding an item to cart
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddCartItem {
    pub product_id: Option<ProductId>,
    pub variant_id: Option<Uuid>,
    pub sku: String,
    pub name: String,
    pub description: Option<String>,
    pub image_url: Option<String>,
    pub quantity: i32,
    pub unit_price: Decimal,
    pub original_price: Option<Decimal>,
    pub weight: Option<Decimal>,
    pub requires_shipping: Option<bool>,
    pub metadata: Option<serde_json::Value>,
}

impl Default for AddCartItem {
    fn default() -> Self {
        Self {
            product_id: None,
            variant_id: None,
            sku: String::new(),
            name: String::new(),
            description: None,
            image_url: None,
            quantity: 1,
            unit_price: Decimal::ZERO,
            original_price: None,
            weight: None,
            requires_shipping: Some(true),
            metadata: None,
        }
    }
}

/// Input for updating a cart item
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateCartItem {
    pub quantity: Option<i32>,
    pub unit_price: Option<Decimal>,
    pub discount_amount: Option<Decimal>,
    pub metadata: Option<serde_json::Value>,
}

/// Input for updating a cart
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateCart {
    pub customer_id: Option<CustomerId>,
    pub customer_email: Option<String>,
    pub customer_phone: Option<String>,
    pub customer_name: Option<String>,
    pub shipping_address: Option<CartAddress>,
    pub billing_address: Option<CartAddress>,
    pub billing_same_as_shipping: Option<bool>,
    pub fulfillment_type: Option<FulfillmentType>,
    pub shipping_method: Option<String>,
    pub shipping_carrier: Option<String>,
    pub coupon_code: Option<String>,
    pub discount_amount: Option<Decimal>,
    pub discount_description: Option<String>,
    pub notes: Option<String>,
    pub metadata: Option<serde_json::Value>,
}

/// Input for setting shipping on cart
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetCartShipping {
    pub shipping_address: CartAddress,
    pub shipping_method: Option<String>,
    pub shipping_carrier: Option<String>,
    pub shipping_amount: Option<Decimal>,
}

/// Input for setting payment on cart
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SetCartPayment {
    pub payment_method: String,
    pub payment_token: Option<String>,
    pub billing_address: Option<CartAddress>,
}

/// Input for applying discount/coupon
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApplyCartDiscount {
    pub coupon_code: String,
}

/// Cart filter for querying
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CartFilter {
    pub customer_id: Option<CustomerId>,
    pub customer_email: Option<String>,
    pub status: Option<CartStatus>,
    pub has_items: Option<bool>,
    pub is_abandoned: Option<bool>,
    pub created_after: Option<DateTime<Utc>>,
    pub created_before: Option<DateTime<Utc>>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// Checkout result after completing a cart
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckoutResult {
    pub cart_id: CartId,
    pub order_id: OrderId,
    pub order_number: String,
    pub payment_id: Option<PaymentId>,
    pub total_charged: Decimal,
    pub currency: CurrencyCode,
}

impl Cart {
    /// Check if cart has items
    #[must_use]
    pub fn has_items(&self) -> bool {
        !self.items.is_empty()
    }

    /// Get total item count
    #[must_use]
    pub fn item_count(&self) -> i32 {
        self.items.iter().map(|i| i.quantity).sum()
    }

    /// Check if cart requires shipping
    #[must_use]
    pub fn requires_shipping(&self) -> bool {
        self.items.iter().any(|i| i.requires_shipping)
    }

    /// Check if the cart's lifecycle status permits it to be checked out into
    /// an order.
    ///
    /// A cart in a terminal/non-checkoutable state ([`CartStatus::Cancelled`],
    /// [`CartStatus::Abandoned`], or [`CartStatus::Expired`]) can never be
    /// completed into a real order. [`CartStatus::Completed`] is excluded here
    /// too — completion of an already-completed cart is handled separately as an
    /// idempotent short-circuit, not via this readiness check.
    #[must_use]
    pub const fn is_checkoutable_status(&self) -> bool {
        matches!(
            self.status,
            CartStatus::Active | CartStatus::ReadyForPayment | CartStatus::PaymentPending
        )
    }

    /// Check if cart is ready for checkout
    #[must_use]
    pub fn is_ready_for_checkout(&self) -> bool {
        // A cancelled/abandoned/expired (or already-completed) cart must never be
        // minted into a new order, regardless of whether its items/customer/address
        // fields happen to be populated.
        if !self.is_checkoutable_status() {
            return false;
        }

        if self.items.is_empty() {
            return false;
        }

        // Must have customer info (either customer_id or email)
        if self.customer_id.is_none() && self.customer_email.is_none() {
            return false;
        }

        // Must have shipping address if requires shipping
        if self.requires_shipping() && self.shipping_address.is_none() {
            return false;
        }

        true
    }

    /// Check if cart can be modified
    #[must_use]
    pub const fn can_modify(&self) -> bool {
        matches!(self.status, CartStatus::Active)
    }

    /// Check if cart can be completed
    #[must_use]
    pub const fn can_complete(&self) -> bool {
        matches!(self.status, CartStatus::ReadyForPayment | CartStatus::PaymentPending)
    }

    /// Check if cart can be cancelled
    #[must_use]
    pub const fn can_cancel(&self) -> bool {
        matches!(
            self.status,
            CartStatus::Active | CartStatus::ReadyForPayment | CartStatus::PaymentPending
        )
    }

    /// Check if cart is abandoned
    #[must_use]
    pub fn is_abandoned(&self) -> bool {
        self.status == CartStatus::Abandoned
    }

    /// Check if cart is expired
    #[must_use]
    pub fn is_expired(&self) -> bool {
        if let Some(expires_at) = self.expires_at { Utc::now() > expires_at } else { false }
    }

    /// Recalculate totals from items
    pub fn recalculate_totals(&mut self) {
        self.subtotal = self
            .items
            .iter()
            .map(|i| (i.unit_price * Decimal::from(i.quantity)) - i.discount_amount)
            .sum();
        self.grand_total =
            self.subtotal + self.tax_amount + self.shipping_amount - self.discount_amount;
    }
}

impl CartItem {
    /// Calculate a line item's money total, rounded to the currency minor unit
    /// (2 dp) so the stored/returned line total is a real money amount rather
    /// than a sub-cent value like `9.999`. This matches the Postgres
    /// `cart_items.total DECIMAL(12,2)` column (which coerces to 2 dp) and the
    /// order pipeline's `OrderItem::calculate_total`.
    #[must_use]
    pub fn calculate_total(
        quantity: i32,
        unit_price: Decimal,
        discount: Decimal,
        tax: Decimal,
    ) -> Decimal {
        let subtotal = unit_price * Decimal::from(quantity);
        (subtotal - discount + tax).round_dp(2)
    }

    /// Recalculate this item's total
    pub fn recalculate(&mut self) {
        self.total = Self::calculate_total(
            self.quantity,
            self.unit_price,
            self.discount_amount,
            self.tax_amount,
        );
    }
}

impl Validate for AddCartItem {
    /// Validate an item being added to a cart.
    ///
    /// Rejects empty SKU/name, a non-positive quantity, and a negative unit
    /// or original price. A zero unit price is allowed (e.g. a free/gift item),
    /// but a negative price never is.
    fn validate(&self) -> Result<()> {
        ValidationBuilder::new()
            .required("sku", &self.sku)
            .required("name", &self.name)
            .positive_i32("quantity", self.quantity)
            .non_negative("unit_price", self.unit_price)
            .non_negative("original_price", self.original_price.unwrap_or(Decimal::ZERO))
            .build()
    }
}

impl Validate for CreateCart {
    /// Validate a cart create request.
    ///
    /// Validates each provided line item; an empty/no-items cart is allowed at
    /// create time since items are commonly added afterward.
    fn validate(&self) -> Result<()> {
        if let Some(items) = &self.items {
            for item in items {
                item.validate()?;
            }
        }
        Ok(())
    }
}

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

    #[test]
    fn test_cart_item_total_calculation() {
        let total = CartItem::calculate_total(2, dec!(10.00), dec!(0), dec!(1.60));
        assert_eq!(total, dec!(21.60));
    }

    #[test]
    fn test_cart_is_ready_for_checkout() {
        let mut cart = Cart {
            id: CartId::new(),
            cart_number: "CART-001".to_string(),
            customer_id: Some(CustomerId::new()),
            status: CartStatus::Active,
            currency: CurrencyCode::USD,
            items: vec![CartItem {
                id: Uuid::new_v4(),
                cart_id: CartId::new(),
                product_id: None,
                variant_id: None,
                sku: "SKU-001".to_string(),
                name: "Test Item".to_string(),
                description: None,
                image_url: None,
                quantity: 1,
                unit_price: dec!(10.00),
                original_price: None,
                discount_amount: dec!(0),
                tax_amount: dec!(0.80),
                total: dec!(10.80),
                weight: None,
                requires_shipping: true,
                metadata: None,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
            subtotal: dec!(10.00),
            tax_amount: dec!(0.80),
            shipping_amount: dec!(5.00),
            discount_amount: dec!(0),
            grand_total: dec!(15.80),
            customer_email: None,
            customer_phone: None,
            customer_name: None,
            shipping_address: None,
            billing_address: None,
            billing_same_as_shipping: true,
            fulfillment_type: Some(FulfillmentType::Shipping),
            shipping_method: None,
            shipping_carrier: None,
            estimated_delivery: None,
            payment_method: None,
            payment_token: None,
            payment_status: CartPaymentStatus::None,
            coupon_code: None,
            discount_description: None,
            order_id: None,
            order_number: None,
            notes: None,
            metadata: None,
            inventory_reserved: false,
            reservation_expires_at: None,
            x402_payment: None,
            expires_at: None,
            completed_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        // Not ready - no shipping address
        assert!(!cart.is_ready_for_checkout());

        // Add shipping address
        cart.shipping_address = Some(CartAddress {
            first_name: "John".to_string(),
            last_name: "Doe".to_string(),
            company: None,
            line1: "123 Main St".to_string(),
            line2: None,
            city: "Anytown".to_string(),
            state: Some("CA".to_string()),
            postal_code: "12345".to_string(),
            country: "US".to_string(),
            phone: None,
            email: None,
        });

        // Now ready
        assert!(cart.is_ready_for_checkout());
    }

    /// Build a fully-populated cart that satisfies the item/customer/address
    /// requirements of [`Cart::is_ready_for_checkout`], with the given status.
    fn ready_cart_with_status(status: CartStatus) -> Cart {
        Cart {
            id: CartId::new(),
            cart_number: "CART-READY".to_string(),
            customer_id: Some(CustomerId::new()),
            status,
            currency: CurrencyCode::USD,
            items: vec![CartItem {
                id: Uuid::new_v4(),
                cart_id: CartId::new(),
                product_id: None,
                variant_id: None,
                sku: "SKU-001".to_string(),
                name: "Test Item".to_string(),
                description: None,
                image_url: None,
                quantity: 1,
                unit_price: dec!(10.00),
                original_price: None,
                discount_amount: dec!(0),
                tax_amount: dec!(0.80),
                total: dec!(10.80),
                weight: None,
                requires_shipping: true,
                metadata: None,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
            subtotal: dec!(10.00),
            tax_amount: dec!(0.80),
            shipping_amount: dec!(5.00),
            discount_amount: dec!(0),
            grand_total: dec!(15.80),
            customer_email: None,
            customer_phone: None,
            customer_name: None,
            shipping_address: Some(CartAddress {
                first_name: "John".to_string(),
                last_name: "Doe".to_string(),
                company: None,
                line1: "123 Main St".to_string(),
                line2: None,
                city: "Anytown".to_string(),
                state: Some("CA".to_string()),
                postal_code: "12345".to_string(),
                country: "US".to_string(),
                phone: None,
                email: None,
            }),
            billing_address: None,
            billing_same_as_shipping: true,
            fulfillment_type: Some(FulfillmentType::Shipping),
            shipping_method: None,
            shipping_carrier: None,
            estimated_delivery: None,
            payment_method: None,
            payment_token: None,
            payment_status: CartPaymentStatus::None,
            coupon_code: None,
            discount_description: None,
            order_id: None,
            order_number: None,
            notes: None,
            metadata: None,
            inventory_reserved: false,
            reservation_expires_at: None,
            x402_payment: None,
            expires_at: None,
            completed_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }

    #[test]
    fn test_is_checkoutable_status() {
        // Active/in-flight statuses are checkoutable.
        assert!(ready_cart_with_status(CartStatus::Active).is_checkoutable_status());
        assert!(ready_cart_with_status(CartStatus::ReadyForPayment).is_checkoutable_status());
        assert!(ready_cart_with_status(CartStatus::PaymentPending).is_checkoutable_status());

        // Terminal/non-checkoutable statuses are not.
        assert!(!ready_cart_with_status(CartStatus::Completed).is_checkoutable_status());
        assert!(!ready_cart_with_status(CartStatus::Cancelled).is_checkoutable_status());
        assert!(!ready_cart_with_status(CartStatus::Abandoned).is_checkoutable_status());
        assert!(!ready_cart_with_status(CartStatus::Expired).is_checkoutable_status());
    }

    #[test]
    fn test_ready_for_checkout_rejects_terminal_status() {
        // A fully-populated Active cart is ready for checkout.
        assert!(ready_cart_with_status(CartStatus::Active).is_ready_for_checkout());

        // The same cart is NOT ready once it is cancelled/abandoned/expired,
        // even though its items/customer/address are all still populated.
        for status in [CartStatus::Cancelled, CartStatus::Abandoned, CartStatus::Expired] {
            let cart = ready_cart_with_status(status);
            assert!(
                !cart.is_ready_for_checkout(),
                "cart in status {status:?} must not be ready for checkout"
            );
        }
    }

    #[test]
    fn test_add_cart_item_validate_rejects_negative_and_zero_quantity() {
        // Negative unit price is rejected.
        let mut item = AddCartItem { sku: "SKU".into(), name: "Item".into(), ..Default::default() };
        item.unit_price = dec!(-1.00);
        assert!(item.validate().is_err());

        // Zero quantity is rejected (quantity must be positive).
        let mut item = AddCartItem { sku: "SKU".into(), name: "Item".into(), ..Default::default() };
        item.quantity = 0;
        assert!(item.validate().is_err());

        // Negative quantity is rejected.
        let mut item = AddCartItem { sku: "SKU".into(), name: "Item".into(), ..Default::default() };
        item.quantity = -3;
        assert!(item.validate().is_err());

        // A free item ($0 unit price) with positive quantity is valid.
        let item = AddCartItem {
            sku: "FREE".into(),
            name: "Free Gift".into(),
            quantity: 1,
            unit_price: dec!(0),
            ..Default::default()
        };
        assert!(item.validate().is_ok());
    }

    #[test]
    fn test_create_cart_validate() {
        // No-items cart is allowed at create time.
        assert!(CreateCart::default().validate().is_ok());

        // A cart carrying an invalid item is rejected.
        let bad = CreateCart {
            items: Some(vec![AddCartItem {
                sku: "SKU".into(),
                name: "Item".into(),
                quantity: -1,
                unit_price: dec!(5.00),
                ..Default::default()
            }]),
            ..Default::default()
        };
        assert!(bad.validate().is_err());

        // A cart carrying a valid item is accepted.
        let good = CreateCart {
            items: Some(vec![AddCartItem {
                sku: "SKU".into(),
                name: "Item".into(),
                quantity: 2,
                unit_price: dec!(5.00),
                ..Default::default()
            }]),
            ..Default::default()
        };
        assert!(good.validate().is_ok());
    }

    #[test]
    fn test_cart_status_from_str() {
        use std::str::FromStr;

        assert_eq!(CartStatus::from_str("active").unwrap(), CartStatus::Active);
        assert_eq!(CartStatus::from_str("ready_for_payment").unwrap(), CartStatus::ReadyForPayment);
        assert_eq!(CartStatus::from_str("paymentpending").unwrap(), CartStatus::PaymentPending);
        assert_eq!(CartStatus::from_str("canceled").unwrap(), CartStatus::Cancelled);
    }

    #[test]
    fn test_cart_payment_status_from_str() {
        use std::str::FromStr;

        assert_eq!(
            CartPaymentStatus::from_str("method_selected").unwrap(),
            CartPaymentStatus::MethodSelected
        );
        assert_eq!(
            CartPaymentStatus::from_str("methodselected").unwrap(),
            CartPaymentStatus::MethodSelected
        );
        assert_eq!(
            CartPaymentStatus::from_str("authorized").unwrap(),
            CartPaymentStatus::Authorized
        );
        assert_eq!(CartPaymentStatus::from_str("captured").unwrap(), CartPaymentStatus::Captured);
    }

    #[test]
    fn test_fulfillment_type_from_str() {
        use std::str::FromStr;

        assert_eq!(FulfillmentType::from_str("shipping").unwrap(), FulfillmentType::Shipping);
        assert_eq!(FulfillmentType::from_str("pick_up").unwrap(), FulfillmentType::Pickup);
        assert_eq!(FulfillmentType::from_str("digital").unwrap(), FulfillmentType::Digital);
    }

    #[test]
    fn test_recalculate_totals_does_not_double_count_tax() {
        let mut cart = Cart {
            id: CartId::new(),
            cart_number: "CART-002".to_string(),
            customer_id: None,
            status: CartStatus::Active,
            currency: CurrencyCode::USD,
            items: vec![CartItem {
                id: Uuid::new_v4(),
                cart_id: CartId::new(),
                product_id: None,
                variant_id: None,
                sku: "SKU-TAX".to_string(),
                name: "Taxed Item".to_string(),
                description: None,
                image_url: None,
                quantity: 1,
                unit_price: dec!(10.00),
                original_price: None,
                discount_amount: Decimal::ZERO,
                tax_amount: dec!(0.80),
                total: dec!(10.80),
                weight: None,
                requires_shipping: false,
                metadata: None,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            }],
            subtotal: Decimal::ZERO,
            tax_amount: dec!(0.80),
            shipping_amount: Decimal::ZERO,
            discount_amount: Decimal::ZERO,
            grand_total: Decimal::ZERO,
            customer_email: None,
            customer_phone: None,
            customer_name: None,
            shipping_address: None,
            billing_address: None,
            billing_same_as_shipping: true,
            fulfillment_type: None,
            shipping_method: None,
            shipping_carrier: None,
            estimated_delivery: None,
            payment_method: None,
            payment_token: None,
            payment_status: CartPaymentStatus::None,
            coupon_code: None,
            discount_description: None,
            order_id: None,
            order_number: None,
            notes: None,
            metadata: None,
            inventory_reserved: false,
            reservation_expires_at: None,
            x402_payment: None,
            expires_at: None,
            completed_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        cart.recalculate_totals();

        assert_eq!(cart.subtotal, dec!(10.00));
        assert_eq!(cart.grand_total, dec!(10.80));
    }
}