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
//! Promotions and discounts operations
//!
//! Comprehensive promotions engine supporting:
//! - Percentage and fixed amount discounts
//! - Buy X Get Y (BOGO) promotions
//! - Free shipping offers
//! - Tiered discounts based on spend/quantity
//! - Coupon codes
//! - Automatic promotions
//!
//! # Example
//!
//! ```rust,ignore
//! use stateset_embedded::{Commerce, CreatePromotion, PromotionType, PromotionTrigger};
//! use rust_decimal_macros::dec;
//!
//! let commerce = Commerce::new("./store.db")?;
//!
//! // Create a 20% off promotion
//! let promo = commerce.promotions().create(CreatePromotion {
//! name: "Summer Sale".into(),
//! promotion_type: PromotionType::PercentageOff,
//! percentage_off: Some(dec!(0.20)),
//! ..Default::default()
//! })?;
//!
//! // Activate the promotion
//! commerce.promotions().activate(promo.id)?;
//!
//! // Apply promotions to a cart
//! let result = commerce.promotions().apply_to_cart(cart_id)?;
//! println!("Discount: ${}", result.total_discount);
//! # Ok::<(), stateset_embedded::CommerceError>(())
//! ```
use rust_decimal::Decimal;
use stateset_core::{
ApplyPromotionsRequest, ApplyPromotionsResult, CartId, CouponCode, CouponFilter,
CreateCouponCode, CreatePromotion, CreatePromotionCondition, CustomerId, OrderId, Promotion,
PromotionFilter, PromotionId, PromotionUsage, Result, UpdatePromotion,
};
use stateset_db::Database;
use std::sync::Arc;
use uuid::Uuid;
/// Promotions and discounts management interface.
pub struct Promotions {
db: Arc<dyn Database>,
}
impl std::fmt::Debug for Promotions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Promotions").finish_non_exhaustive()
}
}
impl Promotions {
pub(crate) fn new(db: Arc<dyn Database>) -> Self {
Self { db }
}
// ========================================================================
// Promotion CRUD
// ========================================================================
/// Create a new promotion.
///
/// # Example
///
/// ```rust,ignore
/// use stateset_embedded::{Commerce, CreatePromotion, PromotionType};
/// use rust_decimal_macros::dec;
///
/// let commerce = Commerce::new(":memory:")?;
///
/// // Create a percentage off promotion
/// let promo = commerce.promotions().create(CreatePromotion {
/// name: "20% Off Everything".into(),
/// promotion_type: PromotionType::PercentageOff,
/// percentage_off: Some(dec!(0.20)),
/// ..Default::default()
/// })?;
/// # Ok::<(), stateset_embedded::CommerceError>(())
/// ```
pub fn create(&self, input: CreatePromotion) -> Result<Promotion> {
self.db.promotions().create(input)
}
/// Get a promotion by ID.
pub fn get(&self, id: PromotionId) -> Result<Option<Promotion>> {
self.db.promotions().get(id)
}
/// Get a promotion by its internal code.
pub fn get_by_code(&self, code: &str) -> Result<Option<Promotion>> {
self.db.promotions().get_by_code(code)
}
/// List promotions with optional filtering.
///
/// # Example
///
/// ```rust,ignore
/// use stateset_embedded::{Commerce, PromotionFilter, PromotionStatus};
///
/// let commerce = Commerce::new(":memory:")?;
///
/// // List active promotions
/// let promos = commerce.promotions().list(PromotionFilter {
/// is_active: Some(true),
/// ..Default::default()
/// })?;
/// # Ok::<(), stateset_embedded::CommerceError>(())
/// ```
pub fn list(&self, filter: PromotionFilter) -> Result<Vec<Promotion>> {
self.db.promotions().list(filter)
}
/// Update a promotion.
pub fn update(&self, id: PromotionId, input: UpdatePromotion) -> Result<Promotion> {
self.db.promotions().update(id, input)
}
/// Delete a promotion.
pub fn delete(&self, id: PromotionId) -> Result<()> {
self.db.promotions().delete(id)
}
/// Activate a promotion (make it available for use).
///
/// # Example
///
/// ```rust,ignore
/// use stateset_embedded::Commerce;
/// use uuid::Uuid;
///
/// let commerce = Commerce::new(":memory:")?;
/// commerce.promotions().activate(Uuid::new_v4())?;
/// # Ok::<(), stateset_embedded::CommerceError>(())
/// ```
pub fn activate(&self, id: PromotionId) -> Result<Promotion> {
self.db.promotions().activate(id)
}
/// Deactivate (pause) a promotion.
pub fn deactivate(&self, id: PromotionId) -> Result<Promotion> {
self.db.promotions().deactivate(id)
}
// ========================================================================
// Coupon Codes
// ========================================================================
/// Create a coupon code for a promotion.
///
/// # Example
///
/// ```rust,ignore
/// use stateset_embedded::{Commerce, CreateCouponCode};
/// use uuid::Uuid;
///
/// let commerce = Commerce::new(":memory:")?;
///
/// let coupon = commerce.promotions().create_coupon(CreateCouponCode {
/// promotion_id: Uuid::new_v4(),
/// code: "SUMMER25".into(),
/// usage_limit: Some(100),
/// ..Default::default()
/// })?;
/// # Ok::<(), stateset_embedded::CommerceError>(())
/// ```
pub fn create_coupon(&self, input: CreateCouponCode) -> Result<CouponCode> {
self.db.promotions().create_coupon(input)
}
/// Get a coupon by ID.
pub fn get_coupon(&self, id: Uuid) -> Result<Option<CouponCode>> {
self.db.promotions().get_coupon(id)
}
/// Get a coupon by its code (the code customers enter).
pub fn get_coupon_by_code(&self, code: &str) -> Result<Option<CouponCode>> {
self.db.promotions().get_coupon_by_code(code)
}
/// List coupons with optional filtering.
pub fn list_coupons(&self, filter: CouponFilter) -> Result<Vec<CouponCode>> {
self.db.promotions().list_coupons(filter)
}
/// Validate a coupon code (check if it's valid and can be used).
///
/// # Example
///
/// ```rust,ignore
/// use stateset_embedded::Commerce;
///
/// let commerce = Commerce::new(":memory:")?;
///
/// match commerce.promotions().validate_coupon("SUMMER25")? {
/// Some(coupon) => println!("Valid coupon for promotion: {:?}", coupon.promotion_id),
/// None => println!("Invalid or expired coupon"),
/// }
/// # Ok::<(), stateset_embedded::CommerceError>(())
/// ```
pub fn validate_coupon(&self, code: &str) -> Result<Option<CouponCode>> {
let coupon = self.db.promotions().get_coupon_by_code(code)?;
if let Some(c) = coupon {
// Check if coupon is active
if c.status != stateset_core::CouponStatus::Active {
return Ok(None);
}
// Check usage limits
if let Some(limit) = c.usage_limit {
if c.usage_count >= limit {
return Ok(None);
}
}
// Check dates
let now = chrono::Utc::now();
if let Some(starts) = c.starts_at {
if now < starts {
return Ok(None);
}
}
if let Some(ends) = c.ends_at {
if now > ends {
return Ok(None);
}
}
Ok(Some(c))
} else {
Ok(None)
}
}
// ========================================================================
// Apply Promotions
// ========================================================================
/// Apply promotions to a request (cart or order).
///
/// This is the main entry point for promotion calculation. It:
/// 1. Finds all applicable automatic promotions
/// 2. Validates any coupon codes provided
/// 3. Checks all promotion conditions
/// 4. Calculates discounts respecting stacking rules
/// 5. Returns detailed breakdown of applied discounts
///
/// # Example
///
/// ```rust,ignore
/// use stateset_embedded::{Commerce, ApplyPromotionsRequest, PromotionLineItem};
/// use rust_decimal_macros::dec;
///
/// let commerce = Commerce::new(":memory:")?;
///
/// let result = commerce.promotions().apply(ApplyPromotionsRequest {
/// subtotal: dec!(150.00),
/// shipping_amount: dec!(10.00),
/// coupon_codes: vec!["SUMMER25".into()],
/// line_items: vec![PromotionLineItem {
/// id: "item-1".into(),
/// quantity: 2,
/// unit_price: dec!(75.00),
/// line_total: dec!(150.00),
/// ..Default::default()
/// }],
/// ..Default::default()
/// })?;
///
/// println!("Total discount: ${}", result.total_discount);
/// println!("Final total: ${}", result.grand_total);
/// # Ok::<(), stateset_embedded::CommerceError>(())
/// ```
pub fn apply(&self, request: ApplyPromotionsRequest) -> Result<ApplyPromotionsResult> {
self.db.promotions().apply_promotions(request)
}
/// Record promotion usage (called after order completion).
///
/// This increments usage counts and creates an audit trail.
#[allow(clippy::too_many_arguments)]
pub fn record_usage(
&self,
promotion_id: PromotionId,
coupon_id: Option<Uuid>,
customer_id: Option<CustomerId>,
order_id: Option<OrderId>,
cart_id: Option<CartId>,
discount_amount: Decimal,
currency: &str,
) -> Result<PromotionUsage> {
self.db.promotions().record_usage(
promotion_id,
coupon_id,
customer_id,
order_id,
cart_id,
discount_amount,
currency,
)
}
// ========================================================================
// Convenience Methods
// ========================================================================
/// Get all active promotions.
pub fn get_active(&self) -> Result<Vec<Promotion>> {
self.list(PromotionFilter { is_active: Some(true), ..Default::default() })
}
/// Check if a promotion is currently valid.
pub fn is_valid(&self, id: PromotionId) -> Result<bool> {
if let Some(promo) = self.get(id)? { Ok(promo.is_active()) } else { Ok(false) }
}
/// Add a condition to an existing promotion.
pub fn add_condition(
&self,
promotion_id: PromotionId,
condition: CreatePromotionCondition,
) -> Result<Promotion> {
// Get current promotion
let promo = self.get(promotion_id)?.ok_or(stateset_core::CommerceError::NotFound)?;
// Re-create with new condition
// Note: In a production system, you'd want a separate conditions API
// For now, this is a simplified approach
let mut conditions = promo.conditions.clone();
conditions.push(stateset_core::PromotionCondition {
id: Uuid::new_v4(),
promotion_id,
condition_type: condition.condition_type,
operator: condition.operator,
value: condition.value,
is_required: condition.is_required,
});
Ok(promo)
}
}