autumn-billing 0.10.0

Subscription billing plugin (Stripe checkout, portal, webhook mirror, dunning) for autumn-web applications
Documentation
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Provider-neutral mirror records.
//!
//! The provider stays the source of truth. These records are the local,
//! read-optimized copy the gate and the routes read.

use std::fmt;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::money::Money;
use crate::plan::PlanId;

/// An opaque identifier issued by the provider (`cus_…`, `sub_…`, `price_…`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProviderId(String);

impl ProviderId {
    /// Build a provider id.
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// The id as a string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ProviderId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<&str> for ProviderId {
    fn from(id: &str) -> Self {
        Self::new(id)
    }
}

impl From<String> for ProviderId {
    fn from(id: String) -> Self {
        Self(id)
    }
}

/// Lifecycle status of a subscription.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SubscriptionStatus {
    /// Created, first payment not complete.
    Incomplete,
    /// First payment window expired.
    IncompleteExpired,
    /// In a trial period.
    Trialing,
    /// Paid and current.
    Active,
    /// Collection paused.
    Paused,
    /// The latest invoice failed; dunning in progress.
    PastDue,
    /// Dunning exhausted; not paid.
    Unpaid,
    /// Ended.
    Canceled,
}

impl SubscriptionStatus {
    /// Stable `snake_case` name (also the stored form).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Incomplete => "incomplete",
            Self::IncompleteExpired => "incomplete_expired",
            Self::Trialing => "trialing",
            Self::Active => "active",
            Self::Paused => "paused",
            Self::PastDue => "past_due",
            Self::Unpaid => "unpaid",
            Self::Canceled => "canceled",
        }
    }

    /// Parse the stored form.
    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "incomplete" => Self::Incomplete,
            "incomplete_expired" => Self::IncompleteExpired,
            "trialing" => Self::Trialing,
            "active" => Self::Active,
            "paused" => Self::Paused,
            "past_due" => Self::PastDue,
            "unpaid" => Self::Unpaid,
            "canceled" => Self::Canceled,
            _ => return None,
        })
    }

    /// Precedence for same-instant events: a higher rank never yields to a
    /// lower one. Terminal states rank highest.
    #[must_use]
    pub const fn rank(self) -> u8 {
        match self {
            Self::Incomplete => 0,
            Self::Paused => 1,
            Self::Trialing => 2,
            Self::Active => 3,
            Self::PastDue => 4,
            Self::Unpaid => 5,
            Self::IncompleteExpired => 6,
            Self::Canceled => 7,
        }
    }

    /// `true` for a subscription the provider still bills (not ended).
    #[must_use]
    pub const fn is_live(self) -> bool {
        matches!(
            self,
            Self::Trialing | Self::Active | Self::PastDue | Self::Paused | Self::Incomplete
        )
    }

    /// `true` for a state that cannot be left by a later event on the same
    /// subscription.
    #[must_use]
    pub const fn is_terminal(self) -> bool {
        matches!(self, Self::Canceled | Self::IncompleteExpired)
    }
}

/// Status of an invoice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum InvoiceStatus {
    /// Not finalized.
    Draft,
    /// Awaiting payment.
    Open,
    /// Paid in full.
    Paid,
    /// Will not be paid.
    Uncollectible,
    /// Voided.
    Void,
}

impl InvoiceStatus {
    /// Stable `snake_case` name (also the stored form).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Draft => "draft",
            Self::Open => "open",
            Self::Paid => "paid",
            Self::Uncollectible => "uncollectible",
            Self::Void => "void",
        }
    }

    /// Parse the stored form.
    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "draft" => Self::Draft,
            "open" => Self::Open,
            "paid" => Self::Paid,
            "uncollectible" => Self::Uncollectible,
            "void" => Self::Void,
            _ => return None,
        })
    }

    /// Precedence for same-instant events.
    #[must_use]
    pub const fn rank(self) -> u8 {
        match self {
            Self::Draft => 0,
            Self::Open => 1,
            Self::Uncollectible => 2,
            Self::Void => 3,
            Self::Paid => 4,
        }
    }
}

/// A mirrored customer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Customer {
    /// Local id (UUID string).
    pub id: String,
    /// Application user id from the session, when linked. Under Autumn's
    /// tenancy feature this is the tenant-scoped identity, not the bare
    /// session id — see [`crate::hooks::BillingHooks::recipient_for`].
    pub user_id: Option<String>,
    /// Provider name (`stripe`).
    pub provider: String,
    /// Provider customer id.
    pub provider_customer_id: ProviderId,
    /// Email known to the provider.
    pub email: Option<String>,
    /// Creation time (app clock).
    pub created_at: DateTime<Utc>,
    /// Last update time (app clock).
    pub updated_at: DateTime<Utc>,
}

impl Customer {
    /// Build a row with no user link and no email. `now` is the app clock.
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        provider: impl Into<String>,
        provider_customer_id: impl Into<ProviderId>,
        now: DateTime<Utc>,
    ) -> Self {
        Self {
            id: id.into(),
            user_id: None,
            provider: provider.into(),
            provider_customer_id: provider_customer_id.into(),
            email: None,
            created_at: now,
            updated_at: now,
        }
    }

    /// Link the application user.
    #[must_use]
    pub fn with_user(mut self, user_id: impl Into<String>) -> Self {
        self.user_id = Some(user_id.into());
        self
    }

    /// Set the email.
    #[must_use]
    pub fn with_email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }
}

/// A mirrored subscription.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Subscription {
    /// Local id (UUID string).
    pub id: String,
    /// Local customer id.
    pub customer_id: String,
    /// Provider subscription id.
    pub provider_subscription_id: ProviderId,
    /// Provider price id of the first item.
    pub provider_price_id: Option<ProviderId>,
    /// Catalog plan resolved from the price id, when known.
    pub plan_id: Option<PlanId>,
    /// Status.
    pub status: SubscriptionStatus,
    /// Seat quantity.
    pub quantity: i64,
    /// End of the current billing period.
    pub current_period_end: Option<DateTime<Utc>>,
    /// Cancels at period end.
    pub cancel_at_period_end: bool,
    /// Provider time of the last event applied.
    pub last_event_at: DateTime<Utc>,
    /// Creation time (app clock).
    pub created_at: DateTime<Utc>,
    /// Last update time (app clock).
    pub updated_at: DateTime<Utc>,
}

impl Subscription {
    /// Build a row with quantity 1, no price, no plan and no period end.
    /// `now` is the app clock.
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        customer_id: impl Into<String>,
        provider_subscription_id: impl Into<ProviderId>,
        status: SubscriptionStatus,
        last_event_at: DateTime<Utc>,
        now: DateTime<Utc>,
    ) -> Self {
        Self {
            id: id.into(),
            customer_id: customer_id.into(),
            provider_subscription_id: provider_subscription_id.into(),
            provider_price_id: None,
            plan_id: None,
            status,
            quantity: 1,
            current_period_end: None,
            cancel_at_period_end: false,
            last_event_at,
            created_at: now,
            updated_at: now,
        }
    }

    /// Set the provider price id.
    #[must_use]
    pub fn with_price(mut self, price_id: impl Into<ProviderId>) -> Self {
        self.provider_price_id = Some(price_id.into());
        self
    }

    /// Set the catalog plan.
    #[must_use]
    pub fn with_plan(mut self, plan_id: impl Into<PlanId>) -> Self {
        self.plan_id = Some(plan_id.into());
        self
    }

    /// Set the seat quantity.
    #[must_use]
    pub const fn with_quantity(mut self, quantity: i64) -> Self {
        self.quantity = quantity;
        self
    }

    /// Set the period end.
    #[must_use]
    pub const fn with_period_end(mut self, end: DateTime<Utc>) -> Self {
        self.current_period_end = Some(end);
        self
    }

    /// Set `cancel_at_period_end`.
    #[must_use]
    pub const fn with_cancel_at_period_end(mut self, cancel: bool) -> Self {
        self.cancel_at_period_end = cancel;
        self
    }
}

/// A mirrored invoice.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Invoice {
    /// Local id (UUID string).
    pub id: String,
    /// Local customer id.
    pub customer_id: String,
    /// Local subscription id, when the invoice belongs to one.
    pub subscription_id: Option<String>,
    /// Provider subscription id. Kept when the subscription is not yet
    /// mirrored, so mirroring it can link this invoice later. Absent in
    /// JSON from older versions.
    #[serde(default)]
    pub provider_subscription_id: Option<ProviderId>,
    /// Provider invoice id.
    pub provider_invoice_id: ProviderId,
    /// Status.
    pub status: InvoiceStatus,
    /// Amount due.
    pub amount_due: Money,
    /// Amount paid.
    pub amount_paid: Money,
    /// Provider payment attempts so far.
    pub attempt_count: i64,
    /// Provider's own next attempt time, when reported.
    pub next_payment_attempt: Option<DateTime<Utc>>,
    /// Provider time of the last event applied.
    pub last_event_at: DateTime<Utc>,
    /// Creation time (app clock).
    pub created_at: DateTime<Utc>,
    /// Last update time (app clock).
    pub updated_at: DateTime<Utc>,
}

impl Invoice {
    /// Build a row with no subscription link and no provider attempts.
    /// `now` is the app clock.
    #[must_use]
    #[allow(
        clippy::too_many_arguments,
        reason = "every argument is a required column; the optional ones use `with_*`"
    )]
    pub fn new(
        id: impl Into<String>,
        customer_id: impl Into<String>,
        provider_invoice_id: impl Into<ProviderId>,
        status: InvoiceStatus,
        amount_due: Money,
        amount_paid: Money,
        last_event_at: DateTime<Utc>,
        now: DateTime<Utc>,
    ) -> Self {
        Self {
            id: id.into(),
            customer_id: customer_id.into(),
            subscription_id: None,
            provider_subscription_id: None,
            provider_invoice_id: provider_invoice_id.into(),
            status,
            amount_due,
            amount_paid,
            attempt_count: 0,
            next_payment_attempt: None,
            last_event_at,
            created_at: now,
            updated_at: now,
        }
    }

    /// Link the local subscription.
    #[must_use]
    pub fn with_subscription(mut self, subscription_id: impl Into<String>) -> Self {
        self.subscription_id = Some(subscription_id.into());
        self
    }

    /// Set the provider subscription id.
    #[must_use]
    pub fn with_provider_subscription(mut self, id: impl Into<ProviderId>) -> Self {
        self.provider_subscription_id = Some(id.into());
        self
    }

    /// Set the provider attempt count.
    #[must_use]
    pub const fn with_attempt_count(mut self, count: i64) -> Self {
        self.attempt_count = count;
        self
    }

    /// Set the provider's next attempt time.
    #[must_use]
    pub const fn with_next_payment_attempt(mut self, at: DateTime<Utc>) -> Self {
        self.next_payment_attempt = Some(at);
        self
    }
}

/// State of a dunning schedule row.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DunningState {
    /// A retry is scheduled at `next_attempt_at`.
    Pending,
    /// A retry is in flight.
    Running,
    /// The invoice was paid.
    Recovered,
    /// All retries failed.
    Exhausted,
    /// The subscription ended before recovery.
    Canceled,
}

impl DunningState {
    /// Stable `snake_case` name (also the stored form).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Running => "running",
            Self::Recovered => "recovered",
            Self::Exhausted => "exhausted",
            Self::Canceled => "canceled",
        }
    }

    /// Parse the stored form.
    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "pending" => Self::Pending,
            "running" => Self::Running,
            "recovered" => Self::Recovered,
            "exhausted" => Self::Exhausted,
            "canceled" => Self::Canceled,
            _ => return None,
        })
    }
}

/// The dunning schedule for one invoice. The store row is the truth; the
/// retry job only reads it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DunningAttempt {
    /// Local invoice id (primary key).
    pub invoice_id: String,
    /// Local customer id.
    pub customer_id: String,
    /// Local subscription id.
    pub subscription_id: Option<String>,
    /// Number of the next retry to run (1-based).
    pub attempt: i64,
    /// When the next retry is due.
    pub next_attempt_at: DateTime<Utc>,
    /// State.
    pub state: DunningState,
    /// Last update time (app clock).
    pub updated_at: DateTime<Utc>,
}

impl DunningAttempt {
    /// Build a schedule row with no subscription link.
    #[must_use]
    pub fn new(
        invoice_id: impl Into<String>,
        customer_id: impl Into<String>,
        attempt: i64,
        next_attempt_at: DateTime<Utc>,
        state: DunningState,
        updated_at: DateTime<Utc>,
    ) -> Self {
        Self {
            invoice_id: invoice_id.into(),
            customer_id: customer_id.into(),
            subscription_id: None,
            attempt,
            next_attempt_at,
            state,
            updated_at,
        }
    }

    /// Set the local subscription id.
    #[must_use]
    pub fn with_subscription(mut self, subscription_id: impl Into<String>) -> Self {
        self.subscription_id = Some(subscription_id.into());
        self
    }
}