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
//! Analytics and forecasting operations
use rust_decimal::Decimal;
use stateset_core::{
AnalyticsQuery, CustomerMetrics, DemandForecast, FulfillmentMetrics, InventoryHealth,
InventoryMovement, LowStockItem, OrderStatusBreakdown, ProductPerformance, Result,
ReturnMetrics, RevenueByPeriod, RevenueForecast, SalesSummary, TimeGranularity, TopCustomer,
TopProduct,
};
use stateset_db::Database;
use std::sync::Arc;
/// Analytics operations interface.
///
/// Provides sales analytics, inventory forecasting, and business intelligence.
///
/// # Example
///
/// ```rust,no_run
/// use stateset_embedded::{Commerce, AnalyticsQuery, TimePeriod};
///
/// let commerce = Commerce::new("./store.db")?;
///
/// // Get sales summary for last 30 days
/// let summary = commerce.analytics().sales_summary(
/// AnalyticsQuery::new().period(TimePeriod::Last30Days)
/// )?;
/// println!("Revenue: ${}", summary.total_revenue);
///
/// // Get top selling products
/// let top_products = commerce.analytics().top_products(
/// AnalyticsQuery::new().period(TimePeriod::ThisMonth).limit(10)
/// )?;
///
/// // Get demand forecast
/// let forecasts = commerce.analytics().demand_forecast(None, 30)?;
/// # Ok::<(), stateset_embedded::CommerceError>(())
/// ```
pub struct Analytics {
db: Arc<dyn Database>,
}
impl std::fmt::Debug for Analytics {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Analytics").finish_non_exhaustive()
}
}
impl Analytics {
pub(crate) fn new(db: Arc<dyn Database>) -> Self {
Self { db }
}
// ========================================================================
// Sales Analytics
// ========================================================================
/// Get sales summary for a time period.
///
/// Returns total revenue, order count, average order value, and more.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// let summary = commerce.analytics().sales_summary(
/// AnalyticsQuery::new().period(TimePeriod::Last30Days)
/// )?;
/// println!("Revenue: ${}", summary.total_revenue);
/// println!("Orders: {}", summary.order_count);
/// println!("AOV: ${}", summary.average_order_value);
/// # Ok::<(), CommerceError>(())
/// ```
pub fn sales_summary(&self, query: AnalyticsQuery) -> Result<SalesSummary> {
self.db.analytics().get_sales_summary(query)
}
/// Get revenue broken down by time periods.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// let revenue = commerce.analytics().revenue_by_period(
/// AnalyticsQuery::new()
/// .period(TimePeriod::Last30Days)
/// .granularity(TimeGranularity::Day)
/// )?;
/// for day in revenue {
/// println!("{}: ${}", day.period, day.revenue);
/// }
/// # Ok::<(), CommerceError>(())
/// ```
pub fn revenue_by_period(&self, query: AnalyticsQuery) -> Result<Vec<RevenueByPeriod>> {
self.db.analytics().get_revenue_by_period(query)
}
// ========================================================================
// Product Analytics
// ========================================================================
/// Get top selling products.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// let top = commerce.analytics().top_products(
/// AnalyticsQuery::new()
/// .period(TimePeriod::ThisMonth)
/// .limit(10)
/// )?;
/// for product in top {
/// println!("{}: {} units, ${}", product.name, product.units_sold, product.revenue);
/// }
/// # Ok::<(), CommerceError>(())
/// ```
pub fn top_products(&self, query: AnalyticsQuery) -> Result<Vec<TopProduct>> {
self.db.analytics().get_top_products(query)
}
/// Get product performance with period comparison.
pub fn product_performance(&self, query: AnalyticsQuery) -> Result<Vec<ProductPerformance>> {
self.db.analytics().get_product_performance(query)
}
// ========================================================================
// Customer Analytics
// ========================================================================
/// Get customer metrics.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// let metrics = commerce.analytics().customer_metrics(
/// AnalyticsQuery::new().period(TimePeriod::ThisMonth)
/// )?;
/// println!("Total customers: {}", metrics.total_customers);
/// println!("New this month: {}", metrics.new_customers);
/// println!("Avg LTV: ${}", metrics.average_lifetime_value);
/// # Ok::<(), CommerceError>(())
/// ```
pub fn customer_metrics(&self, query: AnalyticsQuery) -> Result<CustomerMetrics> {
self.db.analytics().get_customer_metrics(query)
}
/// Get top customers by spend.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// let top = commerce.analytics().top_customers(
/// AnalyticsQuery::new().period(TimePeriod::AllTime).limit(10)
/// )?;
/// for customer in top {
/// println!("{}: {} orders, ${}", customer.name, customer.order_count, customer.total_spent);
/// }
/// # Ok::<(), CommerceError>(())
/// ```
pub fn top_customers(&self, query: AnalyticsQuery) -> Result<Vec<TopCustomer>> {
self.db.analytics().get_top_customers(query)
}
// ========================================================================
// Inventory Analytics
// ========================================================================
/// Get inventory health summary.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// let health = commerce.analytics().inventory_health()?;
/// println!("Total SKUs: {}", health.total_skus);
/// println!("Low stock: {}", health.low_stock_skus);
/// println!("Out of stock: {}", health.out_of_stock_skus);
/// # Ok::<(), CommerceError>(())
/// ```
pub fn inventory_health(&self) -> Result<InventoryHealth> {
self.db.analytics().get_inventory_health()
}
/// Get low stock items.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # use rust_decimal_macros::dec;
/// # let commerce = Commerce::new(":memory:")?;
/// let low_stock = commerce.analytics().low_stock_items(Some(dec!(20)))?;
/// for item in low_stock {
/// println!("{}: {} available", item.sku, item.available);
/// }
/// # Ok::<(), CommerceError>(())
/// ```
pub fn low_stock_items(&self, threshold: Option<Decimal>) -> Result<Vec<LowStockItem>> {
self.db.analytics().get_low_stock_items(threshold)
}
/// Get inventory movement summary.
pub fn inventory_movement(&self, query: AnalyticsQuery) -> Result<Vec<InventoryMovement>> {
self.db.analytics().get_inventory_movement(query)
}
// ========================================================================
// Order Analytics
// ========================================================================
/// Get order status breakdown.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// let breakdown = commerce.analytics().order_status_breakdown(
/// AnalyticsQuery::new().period(TimePeriod::Last30Days)
/// )?;
/// println!("Pending: {}", breakdown.pending);
/// println!("Shipped: {}", breakdown.shipped);
/// println!("Delivered: {}", breakdown.delivered);
/// # Ok::<(), CommerceError>(())
/// ```
pub fn order_status_breakdown(&self, query: AnalyticsQuery) -> Result<OrderStatusBreakdown> {
self.db.analytics().get_order_status_breakdown(query)
}
/// Get fulfillment metrics.
pub fn fulfillment_metrics(&self, query: AnalyticsQuery) -> Result<FulfillmentMetrics> {
self.db.analytics().get_fulfillment_metrics(query)
}
// ========================================================================
// Return Analytics
// ========================================================================
/// Get return metrics.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// let metrics = commerce.analytics().return_metrics(
/// AnalyticsQuery::new().period(TimePeriod::ThisMonth)
/// )?;
/// println!("Returns: {}", metrics.total_returns);
/// println!("Return rate: {}%", metrics.return_rate_percent);
/// # Ok::<(), CommerceError>(())
/// ```
pub fn return_metrics(&self, query: AnalyticsQuery) -> Result<ReturnMetrics> {
self.db.analytics().get_return_metrics(query)
}
// ========================================================================
// Forecasting
// ========================================================================
/// Get demand forecast for inventory items.
///
/// Predicts future demand based on historical sales data.
///
/// # Arguments
///
/// * `skus` - Optional list of SKUs to forecast. If None, forecasts all items.
/// * `days_ahead` - Number of days to forecast ahead.
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// // Forecast for all items
/// let forecasts = commerce.analytics().demand_forecast(None, 30)?;
/// for f in forecasts {
/// println!("{}: {} units/day, {} days until stockout",
/// f.sku,
/// f.average_daily_demand,
/// f.days_until_stockout.unwrap_or(999)
/// );
/// }
///
/// // Forecast for specific SKUs
/// let forecasts = commerce.analytics().demand_forecast(
/// Some(vec!["SKU-001".to_string(), "SKU-002".to_string()]),
/// 14
/// )?;
/// # Ok::<(), CommerceError>(())
/// ```
pub fn demand_forecast(
&self,
skus: Option<Vec<String>>,
days_ahead: u32,
) -> Result<Vec<DemandForecast>> {
self.db.analytics().get_demand_forecast(skus, days_ahead)
}
/// Get revenue forecast.
///
/// Predicts future revenue based on historical trends.
///
/// # Arguments
///
/// * `periods_ahead` - Number of periods to forecast.
/// * `granularity` - Time granularity (Day, Week, Month).
///
/// # Example
///
/// ```rust,no_run
/// # use stateset_embedded::*;
/// # let commerce = Commerce::new(":memory:")?;
/// let forecasts = commerce.analytics().revenue_forecast(3, TimeGranularity::Month)?;
/// for f in forecasts {
/// println!("{}: ${} (${} - ${})",
/// f.period,
/// f.forecasted_revenue,
/// f.lower_bound,
/// f.upper_bound
/// );
/// }
/// # Ok::<(), CommerceError>(())
/// ```
pub fn revenue_forecast(
&self,
periods_ahead: u32,
granularity: TimeGranularity,
) -> Result<Vec<RevenueForecast>> {
self.db.analytics().get_revenue_forecast(periods_ahead, granularity)
}
}