stateset-embedded 0.7.13

Embeddable commerce library - the SQLite of commerce operations
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
//! Subscription management operations
//!
//! Comprehensive subscription system supporting:
//! - Subscription plans with flexible billing intervals
//! - Customer subscriptions with full lifecycle management
//! - Trial periods and promotional pricing
//! - Pause, resume, skip, and cancel functionality
//! - Billing cycle tracking and payment integration
//!
//! # Example
//!
//! ```rust,ignore
//! use stateset_embedded::{Commerce, CreateSubscriptionPlan, CreateSubscription, BillingInterval};
//! use rust_decimal_macros::dec;
//!
//! let commerce = Commerce::new("./store.db")?;
//!
//! // Create a subscription plan
//! let plan = commerce.subscriptions().create_plan(CreateSubscriptionPlan {
//!     name: "Monthly Coffee Box".into(),
//!     billing_interval: BillingInterval::Monthly,
//!     price: dec!(29.99),
//!     trial_days: Some(14),
//!     ..Default::default()
//! })?;
//!
//! // Activate the plan
//! commerce.subscriptions().activate_plan(plan.id)?;
//!
//! // Subscribe a customer
//! let subscription = commerce.subscriptions().subscribe(CreateSubscription {
//!     customer_id: customer.id,
//!     plan_id: plan.id,
//!     ..Default::default()
//! })?;
//!
//! println!("Subscription #{} created", subscription.subscription_number);
//! # Ok::<(), stateset_embedded::CommerceError>(())
//! ```

use chrono::{DateTime, Utc};
use stateset_core::{
    BillingCycle, BillingCycleFilter, BillingCycleStatus, CancelSubscription, CreateBillingCycle,
    CreateSubscription, CreateSubscriptionPlan, CustomerId, PauseSubscription, Result,
    SkipBillingCycle, Subscription, SubscriptionEvent, SubscriptionFilter, SubscriptionId,
    SubscriptionPlan, SubscriptionPlanFilter, UpdateSubscription, UpdateSubscriptionPlan,
};
use stateset_db::Database;
use stateset_observability::Metrics;
use std::sync::Arc;
use uuid::Uuid;

/// Subscription management interface.
pub struct Subscriptions {
    db: Arc<dyn Database>,
    metrics: Metrics,
}

impl std::fmt::Debug for Subscriptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Subscriptions").finish_non_exhaustive()
    }
}

impl Subscriptions {
    pub(crate) fn new(db: Arc<dyn Database>, metrics: Metrics) -> Self {
        Self { db, metrics }
    }

    // ========================================================================
    // Subscription Plans
    // ========================================================================

    /// Create a new subscription plan.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, CreateSubscriptionPlan, BillingInterval};
    /// use rust_decimal_macros::dec;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// let plan = commerce.subscriptions().create_plan(CreateSubscriptionPlan {
    ///     name: "Weekly Meal Kit".into(),
    ///     billing_interval: BillingInterval::Weekly,
    ///     price: dec!(79.99),
    ///     trial_days: Some(7),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn create_plan(&self, input: CreateSubscriptionPlan) -> Result<SubscriptionPlan> {
        self.db.subscriptions().create_plan(input)
    }

    /// Get a subscription plan by ID.
    pub fn get_plan(&self, id: Uuid) -> Result<Option<SubscriptionPlan>> {
        self.db.subscriptions().get_plan(id)
    }

    /// Get a subscription plan by its code.
    pub fn get_plan_by_code(&self, code: &str) -> Result<Option<SubscriptionPlan>> {
        self.db.subscriptions().get_plan_by_code(code)
    }

    /// List subscription plans with optional filtering.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, SubscriptionPlanFilter, PlanStatus};
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// // List active plans
    /// let plans = commerce.subscriptions().list_plans(SubscriptionPlanFilter {
    ///     status: Some(PlanStatus::Active),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn list_plans(&self, filter: SubscriptionPlanFilter) -> Result<Vec<SubscriptionPlan>> {
        self.db.subscriptions().list_plans(filter)
    }

    /// Update a subscription plan.
    pub fn update_plan(&self, id: Uuid, input: UpdateSubscriptionPlan) -> Result<SubscriptionPlan> {
        self.db.subscriptions().update_plan(id, input)
    }

    /// Activate a subscription plan (make it available for new subscriptions).
    pub fn activate_plan(&self, id: Uuid) -> Result<SubscriptionPlan> {
        self.db.subscriptions().activate_plan(id)
    }

    /// Archive a subscription plan (no new subscriptions, existing ones continue).
    pub fn archive_plan(&self, id: Uuid) -> Result<SubscriptionPlan> {
        self.db.subscriptions().archive_plan(id)
    }

    // ========================================================================
    // Subscriptions
    // ========================================================================

    /// Create a new subscription for a customer.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, CreateSubscription};
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// let subscription = commerce.subscriptions().subscribe(CreateSubscription {
    ///     customer_id: Uuid::new_v4(),
    ///     plan_id: Uuid::new_v4(),
    ///     payment_method_id: Some("pm_1234".into()),
    ///     ..Default::default()
    /// })?;
    ///
    /// println!("Created subscription #{}", subscription.subscription_number);
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn subscribe(&self, input: CreateSubscription) -> Result<Subscription> {
        let subscription = self.db.subscriptions().create_subscription(input)?;
        self.metrics.record_subscription_created(&subscription.id.to_string());
        Ok(subscription)
    }

    /// Get a subscription by ID.
    pub fn get(&self, id: SubscriptionId) -> Result<Option<Subscription>> {
        self.db.subscriptions().get_subscription(id)
    }

    /// Get a subscription by its number (e.g., "SUB-123456").
    pub fn get_by_number(&self, number: &str) -> Result<Option<Subscription>> {
        self.db.subscriptions().get_subscription_by_number(number)
    }

    /// List subscriptions with optional filtering.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, SubscriptionFilter, SubscriptionStatus};
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// // List active subscriptions for a customer
    /// let subs = commerce.subscriptions().list(SubscriptionFilter {
    ///     customer_id: Some(Uuid::new_v4()),
    ///     status: Some(SubscriptionStatus::Active),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn list(&self, filter: SubscriptionFilter) -> Result<Vec<Subscription>> {
        self.db.subscriptions().list_subscriptions(filter)
    }

    /// Update a subscription.
    pub fn update(&self, id: SubscriptionId, input: UpdateSubscription) -> Result<Subscription> {
        self.db.subscriptions().update_subscription(id, input)
    }

    // ========================================================================
    // Subscription Lifecycle
    // ========================================================================

    /// Pause a subscription.
    ///
    /// Pausing stops billing but preserves the subscription. The customer
    /// can resume at any time.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, PauseSubscription};
    /// use uuid::Uuid;
    /// use chrono::{Utc, Duration};
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// // Pause for 30 days
    /// commerce.subscriptions().pause(Uuid::new_v4(), PauseSubscription {
    ///     resume_at: Some(Utc::now() + Duration::days(30)),
    ///     reason: Some("Customer requested vacation hold".into()),
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn pause(&self, id: SubscriptionId, input: PauseSubscription) -> Result<Subscription> {
        self.db.subscriptions().pause_subscription(id, input)
    }

    /// Resume a paused subscription.
    ///
    /// This reactivates billing and creates a new billing period.
    pub fn resume(&self, id: SubscriptionId) -> Result<Subscription> {
        self.db.subscriptions().resume_subscription(id)
    }

    /// Cancel a subscription.
    ///
    /// By default, cancellation takes effect at the end of the current
    /// billing period. Use `immediate: true` to cancel immediately.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, CancelSubscription};
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// // Cancel at end of period
    /// commerce.subscriptions().cancel(Uuid::new_v4(), CancelSubscription {
    ///     reason: Some("Customer found alternative".into()),
    ///     ..Default::default()
    /// })?;
    ///
    /// // Immediate cancellation
    /// commerce.subscriptions().cancel(Uuid::new_v4(), CancelSubscription {
    ///     immediate: Some(true),
    ///     reason: Some("Refund requested".into()),
    ///     ..Default::default()
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn cancel(&self, id: SubscriptionId, input: CancelSubscription) -> Result<Subscription> {
        self.db.subscriptions().cancel_subscription(id, input)
    }

    /// Skip the next billing cycle.
    ///
    /// The subscription remains active, but the next billing date is
    /// pushed forward by one interval.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::{Commerce, SkipBillingCycle};
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// commerce.subscriptions().skip_next_cycle(Uuid::new_v4(), SkipBillingCycle {
    ///     reason: Some("Customer traveling".into()),
    /// })?;
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn skip_next_cycle(
        &self,
        id: SubscriptionId,
        input: SkipBillingCycle,
    ) -> Result<Subscription> {
        self.db.subscriptions().skip_billing_cycle(id, input)
    }

    // ========================================================================
    // Billing Cycles
    // ========================================================================

    /// Create a billing cycle for a subscription.
    ///
    /// This is typically called by the billing system when processing
    /// subscription renewals.
    pub fn create_billing_cycle(
        &self,
        subscription_id: SubscriptionId,
        cycle_number: i32,
        period_start: DateTime<Utc>,
        period_end: DateTime<Utc>,
    ) -> Result<BillingCycle> {
        self.db.subscriptions().create_billing_cycle(CreateBillingCycle {
            subscription_id,
            cycle_number,
            period_start,
            period_end,
        })
    }

    /// Get a billing cycle by ID.
    pub fn get_billing_cycle(&self, id: Uuid) -> Result<Option<BillingCycle>> {
        self.db.subscriptions().get_billing_cycle(id)
    }

    /// List billing cycles with optional filtering.
    pub fn list_billing_cycles(&self, filter: BillingCycleFilter) -> Result<Vec<BillingCycle>> {
        self.db.subscriptions().list_billing_cycles(filter)
    }

    /// Update billing cycle status (mark as paid, failed, etc.).
    pub fn update_billing_cycle_status(
        &self,
        id: Uuid,
        status: BillingCycleStatus,
    ) -> Result<BillingCycle> {
        self.db.subscriptions().update_billing_cycle_status(id, status)
    }

    /// Mark a billing cycle as paid.
    pub fn mark_cycle_paid(&self, id: Uuid) -> Result<BillingCycle> {
        self.db.subscriptions().update_billing_cycle_status(id, BillingCycleStatus::Paid)
    }

    /// Mark a billing cycle as failed.
    pub fn mark_cycle_failed(&self, id: Uuid) -> Result<BillingCycle> {
        self.db.subscriptions().update_billing_cycle_status(id, BillingCycleStatus::Failed)
    }

    // ========================================================================
    // Events
    // ========================================================================

    /// Get subscription events (audit log).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use stateset_embedded::Commerce;
    /// use uuid::Uuid;
    ///
    /// let commerce = Commerce::new(":memory:")?;
    ///
    /// let events = commerce.subscriptions().get_events(Uuid::new_v4())?;
    /// for event in events {
    ///     println!("{}: {}", event.event_type, event.description);
    /// }
    /// # Ok::<(), stateset_embedded::CommerceError>(())
    /// ```
    pub fn get_events(&self, subscription_id: SubscriptionId) -> Result<Vec<SubscriptionEvent>> {
        self.db.subscriptions().get_subscription_events(subscription_id)
    }

    // ========================================================================
    // Convenience Methods
    // ========================================================================

    /// Get all active plans.
    pub fn get_active_plans(&self) -> Result<Vec<SubscriptionPlan>> {
        self.list_plans(SubscriptionPlanFilter {
            status: Some(stateset_core::PlanStatus::Active),
            ..Default::default()
        })
    }

    /// Get all subscriptions for a customer.
    pub fn get_customer_subscriptions(&self, customer_id: CustomerId) -> Result<Vec<Subscription>> {
        self.list(SubscriptionFilter { customer_id: Some(customer_id), ..Default::default() })
    }

    /// Get active subscriptions for a customer.
    pub fn get_active_customer_subscriptions(
        &self,
        customer_id: CustomerId,
    ) -> Result<Vec<Subscription>> {
        self.list(SubscriptionFilter {
            customer_id: Some(customer_id),
            status: Some(stateset_core::SubscriptionStatus::Active),
            ..Default::default()
        })
    }

    /// Check if a subscription is active.
    pub fn is_active(&self, id: SubscriptionId) -> Result<bool> {
        if let Some(sub) = self.get(id)? { Ok(sub.is_active()) } else { Ok(false) }
    }

    /// Check if a subscription is in trial period.
    pub fn is_in_trial(&self, id: SubscriptionId) -> Result<bool> {
        if let Some(sub) = self.get(id)? { Ok(sub.is_in_trial()) } else { Ok(false) }
    }

    /// Get subscriptions due for billing.
    ///
    /// Returns subscriptions where `next_billing_date` is on or before the
    /// specified date.
    pub fn get_due_for_billing(&self, before: DateTime<Utc>) -> Result<Vec<Subscription>> {
        let subs = self.list(SubscriptionFilter {
            status: Some(stateset_core::SubscriptionStatus::Active),
            ..Default::default()
        })?;

        Ok(subs
            .into_iter()
            .filter(|s| {
                if let Some(next_billing) = s.next_billing_date {
                    next_billing <= before
                } else {
                    false
                }
            })
            .collect())
    }

    /// Get subscriptions with trials ending soon.
    ///
    /// Returns subscriptions in trial status where trial ends within the
    /// specified number of days.
    pub fn get_trials_ending(&self, within_days: i64) -> Result<Vec<Subscription>> {
        let cutoff = Utc::now() + chrono::Duration::days(within_days);

        let subs = self.list(SubscriptionFilter {
            status: Some(stateset_core::SubscriptionStatus::Trial),
            ..Default::default()
        })?;

        Ok(subs
            .into_iter()
            .filter(|s| {
                if let Some(trial_ends) = s.trial_ends_at { trial_ends <= cutoff } else { false }
            })
            .collect())
    }
}