Skip to main content

stateset_core/
events.rs

1//! Domain events for commerce operations.
2//!
3//! Events are emitted when significant state changes occur in the commerce
4//! system. They follow an append-only event-sourcing pattern and can be used
5//! for:
6//!
7//! - **Audit logging** — immutable record of all state transitions
8//! - **Sync with remote services** — replicate changes to external systems
9//! - **Triggering side effects** — email, webhooks, analytics, etc.
10//!
11//! All events are serializable via [`serde`] using tagged JSON (`"type": "snake_case"`)
12//! for easy consumption by downstream event processors.
13//!
14//! # Example
15//!
16//! ```rust
17//! use stateset_core::events::CommerceEvent;
18//! use stateset_core::{OrderId, CustomerId};
19//!
20//! let event = CommerceEvent::OrderCreated {
21//!     order_id: OrderId::new(),
22//!     customer_id: CustomerId::new(),
23//!     total_amount: rust_decimal::Decimal::new(9999, 2),
24//!     item_count: 3,
25//!     timestamp: chrono::Utc::now(),
26//! };
27//!
28//! let json = serde_json::to_string(&event).unwrap();
29//! assert!(json.contains("\"type\":\"order_created\""));
30//! ```
31
32use chrono::{DateTime, NaiveDate, Utc};
33use rust_decimal::Decimal;
34use serde::{Deserialize, Serialize};
35use stateset_primitives::{
36    CartId, CurrencyCode, CustomerId, GiftCardId, InvoiceId, LoyaltyProgramId, OrderId,
37    OrderItemId, PaymentId, ProductId, ReturnId, ShipmentId, StoreCreditId, SubscriptionId,
38};
39use uuid::Uuid;
40
41use crate::models::{
42    CartStatus, CustomerStatus, FulfillmentStatus, InvoiceStatus, OrderStatus, PaymentStatus,
43    ReturnReason, ReturnStatus, SubscriptionStatus, TrustLevel, X402Asset, X402Network,
44};
45
46/// Commerce domain event
47#[derive(Debug, Clone, Serialize, Deserialize)]
48#[serde(tag = "type", rename_all = "snake_case")]
49pub enum CommerceEvent {
50    // Order events
51    OrderCreated {
52        order_id: OrderId,
53        customer_id: CustomerId,
54        total_amount: Decimal,
55        item_count: usize,
56        timestamp: DateTime<Utc>,
57    },
58    OrderStatusChanged {
59        order_id: OrderId,
60        from_status: OrderStatus,
61        to_status: OrderStatus,
62        timestamp: DateTime<Utc>,
63    },
64    OrderPaymentStatusChanged {
65        order_id: OrderId,
66        from_status: PaymentStatus,
67        to_status: PaymentStatus,
68        timestamp: DateTime<Utc>,
69    },
70    OrderFulfillmentStatusChanged {
71        order_id: OrderId,
72        from_status: FulfillmentStatus,
73        to_status: FulfillmentStatus,
74        timestamp: DateTime<Utc>,
75    },
76    OrderCancelled {
77        order_id: OrderId,
78        reason: Option<String>,
79        timestamp: DateTime<Utc>,
80    },
81    OrderItemAdded {
82        order_id: OrderId,
83        item_id: OrderItemId,
84        sku: String,
85        quantity: i32,
86        timestamp: DateTime<Utc>,
87    },
88    OrderItemRemoved {
89        order_id: OrderId,
90        item_id: OrderItemId,
91        timestamp: DateTime<Utc>,
92    },
93
94    // Inventory events
95    InventoryItemCreated {
96        item_id: i64,
97        sku: String,
98        name: String,
99        timestamp: DateTime<Utc>,
100    },
101    InventoryAdjusted {
102        item_id: i64,
103        sku: String,
104        location_id: i32,
105        quantity_change: Decimal,
106        new_quantity: Decimal,
107        reason: String,
108        timestamp: DateTime<Utc>,
109    },
110    InventoryReserved {
111        reservation_id: Uuid,
112        sku: String,
113        quantity: Decimal,
114        reference_type: String,
115        reference_id: String,
116        timestamp: DateTime<Utc>,
117    },
118    InventoryReservationReleased {
119        reservation_id: Uuid,
120        sku: String,
121        quantity: Decimal,
122        timestamp: DateTime<Utc>,
123    },
124    InventoryReservationConfirmed {
125        reservation_id: Uuid,
126        sku: String,
127        quantity: Decimal,
128        timestamp: DateTime<Utc>,
129    },
130    LowStockAlert {
131        sku: String,
132        location_id: i32,
133        current_quantity: Decimal,
134        reorder_point: Decimal,
135        timestamp: DateTime<Utc>,
136    },
137
138    // Customer events
139    CustomerCreated {
140        customer_id: CustomerId,
141        email: String,
142        timestamp: DateTime<Utc>,
143    },
144    CustomerUpdated {
145        customer_id: CustomerId,
146        fields_changed: Vec<String>,
147        timestamp: DateTime<Utc>,
148    },
149    CustomerStatusChanged {
150        customer_id: CustomerId,
151        from_status: CustomerStatus,
152        to_status: CustomerStatus,
153        timestamp: DateTime<Utc>,
154    },
155    CustomerAddressAdded {
156        customer_id: CustomerId,
157        address_id: Uuid,
158        timestamp: DateTime<Utc>,
159    },
160
161    // Product events
162    ProductCreated {
163        product_id: ProductId,
164        name: String,
165        slug: String,
166        timestamp: DateTime<Utc>,
167    },
168    ProductUpdated {
169        product_id: ProductId,
170        fields_changed: Vec<String>,
171        timestamp: DateTime<Utc>,
172    },
173    ProductStatusChanged {
174        product_id: ProductId,
175        from_status: String,
176        to_status: String,
177        timestamp: DateTime<Utc>,
178    },
179    ProductVariantAdded {
180        product_id: ProductId,
181        variant_id: Uuid,
182        sku: String,
183        timestamp: DateTime<Utc>,
184    },
185    ProductVariantUpdated {
186        variant_id: Uuid,
187        sku: String,
188        timestamp: DateTime<Utc>,
189    },
190
191    // Custom Objects (custom states / metaobjects)
192    CustomObjectTypeCreated {
193        type_id: Uuid,
194        handle: String,
195        timestamp: DateTime<Utc>,
196    },
197    CustomObjectTypeUpdated {
198        type_id: Uuid,
199        handle: String,
200        fields_changed: Vec<String>,
201        timestamp: DateTime<Utc>,
202    },
203    CustomObjectTypeDeleted {
204        type_id: Uuid,
205        handle: String,
206        timestamp: DateTime<Utc>,
207    },
208    CustomObjectCreated {
209        object_id: Uuid,
210        type_handle: String,
211        owner_type: Option<String>,
212        owner_id: Option<String>,
213        timestamp: DateTime<Utc>,
214    },
215    CustomObjectUpdated {
216        object_id: Uuid,
217        type_handle: String,
218        fields_changed: Vec<String>,
219        timestamp: DateTime<Utc>,
220    },
221    CustomObjectDeleted {
222        object_id: Uuid,
223        type_handle: String,
224        timestamp: DateTime<Utc>,
225    },
226
227    // Return events
228    ReturnRequested {
229        return_id: ReturnId,
230        order_id: OrderId,
231        customer_id: CustomerId,
232        reason: ReturnReason,
233        item_count: usize,
234        timestamp: DateTime<Utc>,
235    },
236    ReturnStatusChanged {
237        return_id: ReturnId,
238        from_status: ReturnStatus,
239        to_status: ReturnStatus,
240        timestamp: DateTime<Utc>,
241    },
242    ReturnApproved {
243        return_id: ReturnId,
244        order_id: OrderId,
245        timestamp: DateTime<Utc>,
246    },
247    ReturnRejected {
248        return_id: ReturnId,
249        order_id: OrderId,
250        reason: String,
251        timestamp: DateTime<Utc>,
252    },
253    ReturnCompleted {
254        return_id: ReturnId,
255        order_id: OrderId,
256        refund_amount: Decimal,
257        timestamp: DateTime<Utc>,
258    },
259    RefundIssued {
260        return_id: ReturnId,
261        order_id: OrderId,
262        amount: Decimal,
263        method: String,
264        timestamp: DateTime<Utc>,
265    },
266
267    // Cart events
268    CartCreated {
269        cart_id: CartId,
270        customer_id: Option<CustomerId>,
271        timestamp: DateTime<Utc>,
272    },
273    CartItemAdded {
274        cart_id: CartId,
275        product_id: ProductId,
276        sku: String,
277        quantity: i32,
278        timestamp: DateTime<Utc>,
279    },
280    CartStatusChanged {
281        cart_id: CartId,
282        from_status: CartStatus,
283        to_status: CartStatus,
284        timestamp: DateTime<Utc>,
285    },
286    CartCheckoutCompleted {
287        cart_id: CartId,
288        order_id: OrderId,
289        total_amount: Decimal,
290        timestamp: DateTime<Utc>,
291    },
292    // Payment events
293    PaymentCreated {
294        payment_id: PaymentId,
295        order_id: OrderId,
296        amount: Decimal,
297        currency: CurrencyCode,
298        timestamp: DateTime<Utc>,
299    },
300    PaymentStatusChanged {
301        payment_id: PaymentId,
302        from_status: PaymentStatus,
303        to_status: PaymentStatus,
304        timestamp: DateTime<Utc>,
305    },
306    PaymentCompleted {
307        payment_id: PaymentId,
308        order_id: OrderId,
309        amount: Decimal,
310        timestamp: DateTime<Utc>,
311    },
312    // Shipment events
313    ShipmentCreated {
314        shipment_id: ShipmentId,
315        order_id: OrderId,
316        carrier: String,
317        tracking_number: Option<String>,
318        timestamp: DateTime<Utc>,
319    },
320    ShipmentDelivered {
321        shipment_id: ShipmentId,
322        order_id: OrderId,
323        timestamp: DateTime<Utc>,
324    },
325    // Invoice events
326    InvoiceCreated {
327        invoice_id: InvoiceId,
328        customer_id: CustomerId,
329        total_amount: Decimal,
330        currency: CurrencyCode,
331        timestamp: DateTime<Utc>,
332    },
333    InvoiceStatusChanged {
334        invoice_id: InvoiceId,
335        from_status: InvoiceStatus,
336        to_status: InvoiceStatus,
337        timestamp: DateTime<Utc>,
338    },
339    // Subscription events
340    SubscriptionCreated {
341        subscription_id: SubscriptionId,
342        customer_id: CustomerId,
343        plan_name: String,
344        price: Decimal,
345        timestamp: DateTime<Utc>,
346    },
347    SubscriptionStatusChanged {
348        subscription_id: SubscriptionId,
349        from_status: SubscriptionStatus,
350        to_status: SubscriptionStatus,
351        timestamp: DateTime<Utc>,
352    },
353    SubscriptionRenewed {
354        subscription_id: SubscriptionId,
355        billing_amount: Decimal,
356        timestamp: DateTime<Utc>,
357    },
358    SubscriptionCancelled {
359        subscription_id: SubscriptionId,
360        reason: Option<String>,
361        timestamp: DateTime<Utc>,
362    },
363    // Gift card events
364    GiftCardCreated {
365        gift_card_id: GiftCardId,
366        initial_balance: Decimal,
367        currency: CurrencyCode,
368        timestamp: DateTime<Utc>,
369    },
370    GiftCardRedeemed {
371        gift_card_id: GiftCardId,
372        amount: Decimal,
373        order_id: Option<OrderId>,
374        timestamp: DateTime<Utc>,
375    },
376    // Store credit events
377    StoreCreditIssued {
378        store_credit_id: StoreCreditId,
379        customer_id: CustomerId,
380        amount: Decimal,
381        reason: String,
382        timestamp: DateTime<Utc>,
383    },
384    StoreCreditApplied {
385        store_credit_id: StoreCreditId,
386        order_id: OrderId,
387        amount: Decimal,
388        timestamp: DateTime<Utc>,
389    },
390    // Loyalty events
391    LoyaltyPointsEarned {
392        program_id: LoyaltyProgramId,
393        customer_id: CustomerId,
394        points: i64,
395        source: String,
396        timestamp: DateTime<Utc>,
397    },
398    LoyaltyPointsRedeemed {
399        program_id: LoyaltyProgramId,
400        customer_id: CustomerId,
401        points: i64,
402        timestamp: DateTime<Utc>,
403    },
404
405    // x402 Payment Intent events
406    X402IntentCreated {
407        intent_id: Uuid,
408        cart_id: Option<CartId>,
409        payer_address: String,
410        payee_address: String,
411        amount: u64,
412        asset: X402Asset,
413        network: X402Network,
414        timestamp: DateTime<Utc>,
415    },
416    X402IntentSigned {
417        intent_id: Uuid,
418        signing_hash: String,
419        payer_public_key: String,
420        timestamp: DateTime<Utc>,
421    },
422    X402IntentSequenced {
423        intent_id: Uuid,
424        sequence_number: u64,
425        batch_id: Uuid,
426        timestamp: DateTime<Utc>,
427    },
428    X402IntentSettled {
429        intent_id: Uuid,
430        tx_hash: String,
431        block_number: u64,
432        timestamp: DateTime<Utc>,
433    },
434    X402IntentFailed {
435        intent_id: Uuid,
436        reason: String,
437        timestamp: DateTime<Utc>,
438    },
439    X402IntentExpired {
440        intent_id: Uuid,
441        timestamp: DateTime<Utc>,
442    },
443
444    // Agent Card events
445    AgentCardCreated {
446        agent_id: Uuid,
447        name: String,
448        wallet_address: String,
449        trust_level: TrustLevel,
450        timestamp: DateTime<Utc>,
451    },
452    AgentCardVerified {
453        agent_id: Uuid,
454        trust_level: TrustLevel,
455        verification_method: String,
456        timestamp: DateTime<Utc>,
457    },
458    AgentCardSuspended {
459        agent_id: Uuid,
460        reason: String,
461        timestamp: DateTime<Utc>,
462    },
463    AgentCardReactivated {
464        agent_id: Uuid,
465        timestamp: DateTime<Utc>,
466    },
467
468    // A2A Commerce events
469    A2AQuoteRequested {
470        quote_id: Uuid,
471        buyer_agent_id: Uuid,
472        seller_agent_id: Uuid,
473        total: Decimal,
474        item_count: usize,
475        timestamp: DateTime<Utc>,
476    },
477    A2AQuoteAccepted {
478        quote_id: Uuid,
479        buyer_agent_id: Uuid,
480        seller_agent_id: Uuid,
481        timestamp: DateTime<Utc>,
482    },
483    A2AQuoteRejected {
484        quote_id: Uuid,
485        buyer_agent_id: Uuid,
486        reason: Option<String>,
487        timestamp: DateTime<Utc>,
488    },
489    A2APurchaseInitiated {
490        purchase_id: Uuid,
491        quote_id: Option<Uuid>,
492        buyer_agent_id: Uuid,
493        seller_agent_id: Uuid,
494        payment_intent_id: Uuid,
495        total: Decimal,
496        timestamp: DateTime<Utc>,
497    },
498    A2APurchasePaid {
499        purchase_id: Uuid,
500        payment_intent_id: Uuid,
501        tx_hash: String,
502        timestamp: DateTime<Utc>,
503    },
504    A2ADeliveryConfirmed {
505        purchase_id: Uuid,
506        order_id: Option<OrderId>,
507        buyer_agent_id: Uuid,
508        seller_agent_id: Uuid,
509        rating: Option<u8>,
510        timestamp: DateTime<Utc>,
511    },
512
513    // Fixed asset events
514    FixedAssetPlacedInService {
515        asset_id: Uuid,
516        asset_number: String,
517        in_service_date: NaiveDate,
518        acquisition_cost: Decimal,
519        timestamp: DateTime<Utc>,
520    },
521    FixedAssetDisposed {
522        asset_id: Uuid,
523        asset_number: String,
524        disposal_date: NaiveDate,
525        proceeds: Decimal,
526        gain_loss: Decimal,
527        timestamp: DateTime<Utc>,
528    },
529    FixedAssetWrittenOff {
530        asset_id: Uuid,
531        asset_number: String,
532        write_off_date: NaiveDate,
533        loss: Decimal,
534        timestamp: DateTime<Utc>,
535    },
536    DepreciationPosted {
537        asset_id: Uuid,
538        asset_number: String,
539        periods: u32,
540        amount: Decimal,
541        accumulated_depreciation: Decimal,
542        timestamp: DateTime<Utc>,
543    },
544
545    // Revenue recognition events
546    RevenueRecognized {
547        obligation_id: Uuid,
548        amount: Decimal,
549        total_recognized: Decimal,
550        timestamp: DateTime<Utc>,
551    },
552    RevenueContractCompleted {
553        contract_id: Uuid,
554        contract_number: String,
555        transaction_price: Decimal,
556        currency: CurrencyCode,
557        timestamp: DateTime<Utc>,
558    },
559
560    // Warehouse events
561    CycleCountCompleted {
562        cycle_count_id: Uuid,
563        warehouse_id: i32,
564        line_count: usize,
565        variance_line_count: usize,
566        total_variance: Decimal,
567        timestamp: DateTime<Utc>,
568    },
569
570    // Accounts payable events
571    ThreeWayMatchVarianceDetected {
572        bill_id: Uuid,
573        purchase_order_id: Uuid,
574        variance_line_count: usize,
575        tolerance_percent: Decimal,
576        timestamp: DateTime<Utc>,
577    },
578
579    // General ledger events
580    FxRevaluationPosted {
581        as_of_date: NaiveDate,
582        base_currency: CurrencyCode,
583        total_unrealized_gain_loss: Decimal,
584        journal_entry_id: Option<Uuid>,
585        timestamp: DateTime<Utc>,
586    },
587    MonthEndCloseCompleted {
588        period_id: Uuid,
589        period_name: String,
590        depreciation_total: Decimal,
591        revenue_recognized_total: Decimal,
592        fx_unrealized_gain_loss: Decimal,
593        closing_entry_id: Option<Uuid>,
594        timestamp: DateTime<Utc>,
595    },
596}
597
598impl CommerceEvent {
599    /// Get event type as string
600    #[must_use]
601    pub const fn event_type(&self) -> &'static str {
602        match self {
603            Self::OrderCreated { .. } => "order_created",
604            Self::OrderStatusChanged { .. } => "order_status_changed",
605            Self::OrderPaymentStatusChanged { .. } => "order_payment_status_changed",
606            Self::OrderFulfillmentStatusChanged { .. } => "order_fulfillment_status_changed",
607            Self::OrderCancelled { .. } => "order_cancelled",
608            Self::OrderItemAdded { .. } => "order_item_added",
609            Self::OrderItemRemoved { .. } => "order_item_removed",
610            Self::InventoryItemCreated { .. } => "inventory_item_created",
611            Self::InventoryAdjusted { .. } => "inventory_adjusted",
612            Self::InventoryReserved { .. } => "inventory_reserved",
613            Self::InventoryReservationReleased { .. } => "inventory_reservation_released",
614            Self::InventoryReservationConfirmed { .. } => "inventory_reservation_confirmed",
615            Self::LowStockAlert { .. } => "low_stock_alert",
616            Self::CustomerCreated { .. } => "customer_created",
617            Self::CustomerUpdated { .. } => "customer_updated",
618            Self::CustomerStatusChanged { .. } => "customer_status_changed",
619            Self::CustomerAddressAdded { .. } => "customer_address_added",
620            Self::ProductCreated { .. } => "product_created",
621            Self::ProductUpdated { .. } => "product_updated",
622            Self::ProductStatusChanged { .. } => "product_status_changed",
623            Self::ProductVariantAdded { .. } => "product_variant_added",
624            Self::ProductVariantUpdated { .. } => "product_variant_updated",
625            Self::CustomObjectTypeCreated { .. } => "custom_object_type_created",
626            Self::CustomObjectTypeUpdated { .. } => "custom_object_type_updated",
627            Self::CustomObjectTypeDeleted { .. } => "custom_object_type_deleted",
628            Self::CustomObjectCreated { .. } => "custom_object_created",
629            Self::CustomObjectUpdated { .. } => "custom_object_updated",
630            Self::CustomObjectDeleted { .. } => "custom_object_deleted",
631            Self::ReturnRequested { .. } => "return_requested",
632            Self::ReturnStatusChanged { .. } => "return_status_changed",
633            Self::ReturnApproved { .. } => "return_approved",
634            Self::ReturnRejected { .. } => "return_rejected",
635            Self::ReturnCompleted { .. } => "return_completed",
636            Self::RefundIssued { .. } => "refund_issued",
637            // Cart events
638            Self::CartCreated { .. } => "cart_created",
639            Self::CartItemAdded { .. } => "cart_item_added",
640            Self::CartStatusChanged { .. } => "cart_status_changed",
641            Self::CartCheckoutCompleted { .. } => "cart_checkout_completed",
642            Self::PaymentCreated { .. } => "payment_created",
643            Self::PaymentStatusChanged { .. } => "payment_status_changed",
644            Self::PaymentCompleted { .. } => "payment_completed",
645            Self::ShipmentCreated { .. } => "shipment_created",
646            Self::ShipmentDelivered { .. } => "shipment_delivered",
647            Self::InvoiceCreated { .. } => "invoice_created",
648            Self::InvoiceStatusChanged { .. } => "invoice_status_changed",
649            Self::SubscriptionCreated { .. } => "subscription_created",
650            Self::SubscriptionStatusChanged { .. } => "subscription_status_changed",
651            Self::SubscriptionRenewed { .. } => "subscription_renewed",
652            Self::SubscriptionCancelled { .. } => "subscription_cancelled",
653            Self::GiftCardCreated { .. } => "gift_card_created",
654            Self::GiftCardRedeemed { .. } => "gift_card_redeemed",
655            Self::StoreCreditIssued { .. } => "store_credit_issued",
656            Self::StoreCreditApplied { .. } => "store_credit_applied",
657            Self::LoyaltyPointsEarned { .. } => "loyalty_points_earned",
658            Self::LoyaltyPointsRedeemed { .. } => "loyalty_points_redeemed",
659            // x402 events
660            Self::X402IntentCreated { .. } => "x402_intent_created",
661            Self::X402IntentSigned { .. } => "x402_intent_signed",
662            Self::X402IntentSequenced { .. } => "x402_intent_sequenced",
663            Self::X402IntentSettled { .. } => "x402_intent_settled",
664            Self::X402IntentFailed { .. } => "x402_intent_failed",
665            Self::X402IntentExpired { .. } => "x402_intent_expired",
666            // Agent card events
667            Self::AgentCardCreated { .. } => "agent_card_created",
668            Self::AgentCardVerified { .. } => "agent_card_verified",
669            Self::AgentCardSuspended { .. } => "agent_card_suspended",
670            Self::AgentCardReactivated { .. } => "agent_card_reactivated",
671            // A2A commerce events
672            Self::A2AQuoteRequested { .. } => "a2a_quote_requested",
673            Self::A2AQuoteAccepted { .. } => "a2a_quote_accepted",
674            Self::A2AQuoteRejected { .. } => "a2a_quote_rejected",
675            Self::A2APurchaseInitiated { .. } => "a2a_purchase_initiated",
676            Self::A2APurchasePaid { .. } => "a2a_purchase_paid",
677            Self::A2ADeliveryConfirmed { .. } => "a2a_delivery_confirmed",
678            // Fixed asset events
679            Self::FixedAssetPlacedInService { .. } => "fixed_asset_placed_in_service",
680            Self::FixedAssetDisposed { .. } => "fixed_asset_disposed",
681            Self::FixedAssetWrittenOff { .. } => "fixed_asset_written_off",
682            Self::DepreciationPosted { .. } => "depreciation_posted",
683            // Revenue recognition events
684            Self::RevenueRecognized { .. } => "revenue_recognized",
685            Self::RevenueContractCompleted { .. } => "revenue_contract_completed",
686            // Warehouse events
687            Self::CycleCountCompleted { .. } => "cycle_count_completed",
688            // Accounts payable events
689            Self::ThreeWayMatchVarianceDetected { .. } => "three_way_match_variance_detected",
690            // General ledger events
691            Self::FxRevaluationPosted { .. } => "fx_revaluation_posted",
692            Self::MonthEndCloseCompleted { .. } => "month_end_close_completed",
693        }
694    }
695
696    /// Get timestamp from event
697    #[must_use]
698    pub const fn timestamp(&self) -> DateTime<Utc> {
699        match self {
700            Self::OrderCreated { timestamp, .. }
701            | Self::OrderStatusChanged { timestamp, .. }
702            | Self::OrderPaymentStatusChanged { timestamp, .. }
703            | Self::OrderFulfillmentStatusChanged { timestamp, .. }
704            | Self::OrderCancelled { timestamp, .. }
705            | Self::OrderItemAdded { timestamp, .. }
706            | Self::OrderItemRemoved { timestamp, .. }
707            | Self::InventoryItemCreated { timestamp, .. }
708            | Self::InventoryAdjusted { timestamp, .. }
709            | Self::InventoryReserved { timestamp, .. }
710            | Self::InventoryReservationReleased { timestamp, .. }
711            | Self::InventoryReservationConfirmed { timestamp, .. }
712            | Self::LowStockAlert { timestamp, .. }
713            | Self::CustomerCreated { timestamp, .. }
714            | Self::CustomerUpdated { timestamp, .. }
715            | Self::CustomerStatusChanged { timestamp, .. }
716            | Self::CustomerAddressAdded { timestamp, .. }
717            | Self::ProductCreated { timestamp, .. }
718            | Self::ProductUpdated { timestamp, .. }
719            | Self::ProductStatusChanged { timestamp, .. }
720            | Self::ProductVariantAdded { timestamp, .. }
721            | Self::ProductVariantUpdated { timestamp, .. }
722            | Self::CustomObjectTypeCreated { timestamp, .. }
723            | Self::CustomObjectTypeUpdated { timestamp, .. }
724            | Self::CustomObjectTypeDeleted { timestamp, .. }
725            | Self::CustomObjectCreated { timestamp, .. }
726            | Self::CustomObjectUpdated { timestamp, .. }
727            | Self::CustomObjectDeleted { timestamp, .. }
728            | Self::ReturnRequested { timestamp, .. }
729            | Self::ReturnStatusChanged { timestamp, .. }
730            | Self::ReturnApproved { timestamp, .. }
731            | Self::ReturnRejected { timestamp, .. }
732            | Self::ReturnCompleted { timestamp, .. }
733            | Self::RefundIssued { timestamp, .. }
734            // New domain events
735            | Self::CartCreated { timestamp, .. }
736            | Self::CartItemAdded { timestamp, .. }
737            | Self::CartStatusChanged { timestamp, .. }
738            | Self::CartCheckoutCompleted { timestamp, .. }
739            | Self::PaymentCreated { timestamp, .. }
740            | Self::PaymentStatusChanged { timestamp, .. }
741            | Self::PaymentCompleted { timestamp, .. }
742            | Self::ShipmentCreated { timestamp, .. }
743            | Self::ShipmentDelivered { timestamp, .. }
744            | Self::InvoiceCreated { timestamp, .. }
745            | Self::InvoiceStatusChanged { timestamp, .. }
746            | Self::SubscriptionCreated { timestamp, .. }
747            | Self::SubscriptionStatusChanged { timestamp, .. }
748            | Self::SubscriptionRenewed { timestamp, .. }
749            | Self::SubscriptionCancelled { timestamp, .. }
750            | Self::GiftCardCreated { timestamp, .. }
751            | Self::GiftCardRedeemed { timestamp, .. }
752            | Self::StoreCreditIssued { timestamp, .. }
753            | Self::StoreCreditApplied { timestamp, .. }
754            | Self::LoyaltyPointsEarned { timestamp, .. }
755            | Self::LoyaltyPointsRedeemed { timestamp, .. }
756            // x402 events
757            | Self::X402IntentCreated { timestamp, .. }
758            | Self::X402IntentSigned { timestamp, .. }
759            | Self::X402IntentSequenced { timestamp, .. }
760            | Self::X402IntentSettled { timestamp, .. }
761            | Self::X402IntentFailed { timestamp, .. }
762            | Self::X402IntentExpired { timestamp, .. }
763            // Agent card events
764            | Self::AgentCardCreated { timestamp, .. }
765            | Self::AgentCardVerified { timestamp, .. }
766            | Self::AgentCardSuspended { timestamp, .. }
767            | Self::AgentCardReactivated { timestamp, .. }
768            // A2A commerce events
769            | Self::A2AQuoteRequested { timestamp, .. }
770            | Self::A2AQuoteAccepted { timestamp, .. }
771            | Self::A2AQuoteRejected { timestamp, .. }
772            | Self::A2APurchaseInitiated { timestamp, .. }
773            | Self::A2APurchasePaid { timestamp, .. }
774            | Self::A2ADeliveryConfirmed { timestamp, .. }
775            // Fixed asset events
776            | Self::FixedAssetPlacedInService { timestamp, .. }
777            | Self::FixedAssetDisposed { timestamp, .. }
778            | Self::FixedAssetWrittenOff { timestamp, .. }
779            | Self::DepreciationPosted { timestamp, .. }
780            // Revenue recognition events
781            | Self::RevenueRecognized { timestamp, .. }
782            | Self::RevenueContractCompleted { timestamp, .. }
783            // Warehouse events
784            | Self::CycleCountCompleted { timestamp, .. }
785            // Accounts payable events
786            | Self::ThreeWayMatchVarianceDetected { timestamp, .. }
787            // General ledger events
788            | Self::FxRevaluationPosted { timestamp, .. }
789            | Self::MonthEndCloseCompleted { timestamp, .. } => *timestamp,
790        }
791    }
792
793    /// Serialize event to JSON
794    #[must_use = "serialization result should not be discarded"]
795    pub fn to_json(&self) -> serde_json::Result<String> {
796        serde_json::to_string(self)
797    }
798
799    /// Deserialize event from JSON
800    pub fn from_json(json: &str) -> serde_json::Result<Self> {
801        serde_json::from_str(json)
802    }
803}
804
805/// Event store for persisting and replaying events
806pub trait EventStore {
807    /// Append event to store
808    fn append(&self, event: &CommerceEvent) -> crate::errors::Result<u64>;
809
810    /// Get events since sequence number
811    fn get_events_since(
812        &self,
813        sequence: u64,
814        limit: u32,
815    ) -> crate::errors::Result<Vec<(u64, CommerceEvent)>>;
816
817    /// Get events for aggregate
818    fn get_events_for_aggregate(
819        &self,
820        aggregate_type: &str,
821        aggregate_id: &str,
822    ) -> crate::errors::Result<Vec<CommerceEvent>>;
823
824    /// Get latest sequence number
825    fn latest_sequence(&self) -> crate::errors::Result<u64>;
826}