Skip to main content

stateset_embedded/commerce/
events.rs

1use super::Commerce;
2
3#[cfg(feature = "events")]
4use crate::events::{
5    EventSubscription, EventSystem, Webhook, WebhookDelivery, WebhookRegistrationError,
6};
7
8impl Commerce {
9    /// Access the event system for pub/sub and webhook management.
10    ///
11    /// # Example
12    ///
13    /// ```rust,ignore
14    /// use stateset_embedded::Commerce;
15    /// use futures::StreamExt;
16    ///
17    /// #[tokio::main]
18    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
19    ///     let commerce = Commerce::new("./store.db")?;
20    ///
21    ///     // Subscribe to all events
22    ///     let mut subscription = commerce.events().subscribe();
23    ///
24    ///     // Process events in background
25    ///     tokio::spawn(async move {
26    ///         while let Some(event) = subscription.next().await {
27    ///             println!("Event: {:?}", event);
28    ///         }
29    ///     });
30    ///
31    ///     Ok(())
32    /// }
33    /// ```
34    #[cfg(feature = "events")]
35    #[must_use]
36    pub fn events(&self) -> &EventSystem {
37        &self.event_system
38    }
39
40    /// Subscribe to commerce events.
41    ///
42    /// This is a convenience method that returns an event subscription
43    /// for receiving real-time commerce events.
44    ///
45    /// # Example
46    ///
47    /// ```rust,ignore
48    /// use stateset_embedded::Commerce;
49    /// use futures::StreamExt;
50    ///
51    /// #[tokio::main]
52    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
53    ///     let commerce = Commerce::new("./store.db")?;
54    ///
55    ///     let mut subscription = commerce.subscribe_events();
56    ///
57    ///     while let Some(event) = subscription.next().await {
58    ///         match event {
59    ///             stateset_core::CommerceEvent::OrderCreated { order_id, .. } => {
60    ///                 println!("New order: {}", order_id);
61    ///             }
62    ///             _ => {}
63    ///         }
64    ///     }
65    ///
66    ///     Ok(())
67    /// }
68    /// ```
69    #[cfg(feature = "events")]
70    #[must_use]
71    pub fn subscribe_events(&self) -> EventSubscription {
72        self.event_system.subscribe()
73    }
74
75    /// Register a webhook endpoint for event delivery.
76    ///
77    /// # Example
78    ///
79    /// ```rust,ignore
80    /// use stateset_embedded::{Commerce, Webhook};
81    ///
82    /// let commerce = Commerce::new("./store.db")?;
83    ///
84    /// let webhook = Webhook::new(
85    ///     "My Webhook",
86    ///     "https://my-app.com/webhooks/stateset",
87    /// ).with_secret("my-webhook-secret");
88    ///
89    /// if let Some(id) = commerce.try_register_webhook(webhook) {
90    ///     println!("Webhook registered: {}", id);
91    /// } else {
92    ///     println!("Webhook registration failed");
93    /// }
94    /// # Ok::<(), stateset_embedded::CommerceError>(())
95    /// ```
96    #[cfg(feature = "events")]
97    #[must_use]
98    pub fn register_webhook(&self, webhook: Webhook) -> uuid::Uuid {
99        self.event_system.register_webhook(webhook)
100    }
101
102    /// Register a webhook endpoint with explicit failure semantics.
103    #[cfg(feature = "events")]
104    pub fn register_webhook_strict(
105        &self,
106        webhook: Webhook,
107    ) -> Result<uuid::Uuid, WebhookRegistrationError> {
108        self.event_system.register_webhook_strict(webhook)
109    }
110
111    /// Register a webhook endpoint, returning `None` when registration fails validation.
112    ///
113    /// This is the safer API when you need to distinguish between a successful
114    /// registration ID and a blocked/invalid webhook definition.
115    #[cfg(feature = "events")]
116    #[must_use]
117    pub fn try_register_webhook(&self, webhook: Webhook) -> Option<uuid::Uuid> {
118        self.event_system.try_register_webhook(webhook)
119    }
120
121    /// Unregister a webhook endpoint.
122    #[cfg(feature = "events")]
123    #[must_use]
124    pub fn unregister_webhook(&self, id: uuid::Uuid) -> bool {
125        self.event_system.unregister_webhook(id)
126    }
127
128    /// List all registered webhooks.
129    #[cfg(feature = "events")]
130    #[must_use]
131    pub fn list_webhooks(&self) -> Vec<Webhook> {
132        self.event_system.list_webhooks()
133    }
134
135    /// Get delivery history for a webhook (newest-first).
136    #[cfg(feature = "events")]
137    #[must_use]
138    pub fn webhook_deliveries(&self, id: uuid::Uuid) -> Vec<WebhookDelivery> {
139        self.event_system.webhook_deliveries(id)
140    }
141
142    /// Emit a commerce event manually.
143    ///
144    /// Events are typically emitted automatically by commerce operations,
145    /// but you can also emit custom events using this method.
146    #[cfg(feature = "events")]
147    pub fn emit_event(&self, event: stateset_core::CommerceEvent) {
148        self.event_system.emit(event);
149    }
150}