syrup-rail 0.4.0

Validated domain types and lifecycle policy for Syrup Rail billing
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
use std::fmt;

use chrono::{DateTime, Utc};
use thiserror::Error;

use crate::{
    BillingPeriod, BillingScopeId, Entitlement, Money, PaymentAttemptId, PaymentAttemptKind,
    PaymentAttemptStatus, PaymentCardBrand, PlanKey, SubscriberId, string_contains_raw_card_data,
};

/// Exact subscriber and plan identity for a customer-facing billing read.
///
/// Hosts must authenticate and authorize this identity before using it. This
/// query value does not create an authorization boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SubscriptionBillingPortalQuery {
    billing_scope_id: BillingScopeId,
    subscriber_id: SubscriberId,
    plan_key: PlanKey,
}

impl SubscriptionBillingPortalQuery {
    pub const fn new(
        billing_scope_id: BillingScopeId,
        subscriber_id: SubscriberId,
        plan_key: PlanKey,
    ) -> Self {
        Self {
            billing_scope_id,
            subscriber_id,
            plan_key,
        }
    }

    pub const fn billing_scope_id(&self) -> BillingScopeId {
        self.billing_scope_id
    }

    pub const fn subscriber_id(&self) -> SubscriberId {
        self.subscriber_id
    }

    pub const fn plan_key(&self) -> &PlanKey {
        &self.plan_key
    }
}

/// A customer-renderable, masked display of the stored card for a current
/// subscription.
///
/// This intentionally excludes every provider payment-method reference and
/// contains only the card presentation fields needed by an ordinary billing
/// portal. Accessors expose those values deliberately; ordinary formatting
/// remains value-free.
#[derive(Clone, Eq, PartialEq)]
pub struct SubscriptionPaymentMethodDisplay {
    card_brand: Option<PaymentCardBrand>,
    card_last_four: Option<String>,
    card_expiration_month: Option<u8>,
    card_expiration_year: Option<u16>,
}

impl SubscriptionPaymentMethodDisplay {
    /// Constructs a masked display from provider-neutral validated values.
    pub fn new(
        card_brand: Option<PaymentCardBrand>,
        card_last_four: Option<String>,
        card_expiration_month: Option<u8>,
        card_expiration_year: Option<u16>,
    ) -> Result<Self, SubscriptionPaymentMethodDisplayError> {
        if card_brand.is_none()
            && card_last_four.is_none()
            && card_expiration_month.is_none()
            && card_expiration_year.is_none()
        {
            return Err(SubscriptionPaymentMethodDisplayError::Empty);
        }
        if card_last_four.as_deref().is_some_and(|value| {
            value.len() != 4 || !value.bytes().all(|byte| byte.is_ascii_digit())
        }) {
            return Err(SubscriptionPaymentMethodDisplayError::InvalidCardLastFour);
        }
        if card_expiration_month.is_some_and(|value| !(1..=12).contains(&value)) {
            return Err(SubscriptionPaymentMethodDisplayError::InvalidExpirationMonth);
        }
        if card_expiration_year.is_some_and(|value| value < 2000) {
            return Err(SubscriptionPaymentMethodDisplayError::InvalidExpirationYear);
        }
        Ok(Self {
            card_brand,
            card_last_four,
            card_expiration_month,
            card_expiration_year,
        })
    }

    /// Constructs an optional masked display from untrusted persisted parts.
    ///
    /// Recognized brands are canonicalized, unknown text becomes
    /// [`PaymentCardBrand::Other`], and the original provider text is not
    /// retained. When normalization leaves no renderable field, this returns
    /// `Ok(None)` rather than constructing an empty display.
    pub fn from_provider_parts(
        card_brand: Option<&str>,
        card_last_four: Option<String>,
        card_expiration_month: Option<u8>,
        card_expiration_year: Option<u16>,
    ) -> Result<Option<Self>, SubscriptionPaymentMethodDisplayError> {
        if card_brand.is_some_and(string_contains_raw_card_data) {
            return Err(SubscriptionPaymentMethodDisplayError::CardBrandContainsRawCardData);
        }
        match Self::new(
            card_brand.and_then(PaymentCardBrand::from_provider),
            card_last_four,
            card_expiration_month,
            card_expiration_year,
        ) {
            Ok(display) => Ok(Some(display)),
            Err(SubscriptionPaymentMethodDisplayError::Empty) => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// Returns the provider-neutral card brand.
    pub const fn card_brand(&self) -> Option<PaymentCardBrand> {
        self.card_brand
    }

    /// Returns the deliberately exposed masked last four digits.
    pub fn card_last_four(&self) -> Option<&str> {
        self.card_last_four.as_deref()
    }

    pub const fn card_expiration_month(&self) -> Option<u8> {
        self.card_expiration_month
    }

    pub const fn card_expiration_year(&self) -> Option<u16> {
        self.card_expiration_year
    }
}

impl fmt::Debug for SubscriptionPaymentMethodDisplay {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SubscriptionPaymentMethodDisplay")
            .field("has_card_brand", &self.card_brand.is_some())
            .field("has_card_last_four", &self.card_last_four.is_some())
            .field(
                "has_card_expiration_month",
                &self.card_expiration_month.is_some(),
            )
            .field(
                "has_card_expiration_year",
                &self.card_expiration_year.is_some(),
            )
            .finish()
    }
}

#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum SubscriptionPaymentMethodDisplayError {
    /// No normalized display field was present.
    #[error("subscription payment-method display has no renderable fields")]
    Empty,
    #[error("subscription payment-method card brand cannot contain raw card data")]
    CardBrandContainsRawCardData,
    #[error("subscription payment-method card last four must contain exactly four ASCII digits")]
    InvalidCardLastFour,
    #[error("subscription payment-method expiration month must be between 1 and 12")]
    InvalidExpirationMonth,
    #[error("subscription payment-method expiration year must be at least 2000")]
    InvalidExpirationYear,
}

/// A provider-neutral, customer-facing billing projection for one exact plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SubscriptionBillingPortalSnapshot {
    entitlement: Entitlement,
    payment_method_display: Option<SubscriptionPaymentMethodDisplay>,
}

impl SubscriptionBillingPortalSnapshot {
    pub const fn new(
        entitlement: Entitlement,
        payment_method_display: Option<SubscriptionPaymentMethodDisplay>,
    ) -> Self {
        Self {
            entitlement,
            payment_method_display,
        }
    }

    pub const fn entitlement(&self) -> &Entitlement {
        &self.entitlement
    }

    pub const fn payment_method_display(&self) -> Option<&SubscriptionPaymentMethodDisplay> {
        self.payment_method_display.as_ref()
    }
}

/// Checked number of subscription payment-history entries in one page.
pub const SUBSCRIPTION_PAYMENT_HISTORY_PAGE_LIMIT: i64 = 100;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SubscriptionPaymentHistoryPageLimit(i64);

impl SubscriptionPaymentHistoryPageLimit {
    pub fn new(value: i64) -> Result<Self, SubscriptionPaymentHistoryPageLimitError> {
        if !(1..=SUBSCRIPTION_PAYMENT_HISTORY_PAGE_LIMIT).contains(&value) {
            return Err(SubscriptionPaymentHistoryPageLimitError);
        }
        Ok(Self(value))
    }

    pub const fn get(self) -> i64 {
        self.0
    }
}

#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
#[error("subscription payment-history page limit must be between 1 and 100")]
pub struct SubscriptionPaymentHistoryPageLimitError;

/// Continuation key returned by a prior subscription payment-history page.
///
/// The key is a bound value, never SQL text. The PostgreSQL reader applies it
/// strictly after the preceding row in descending `(created_at, id)` order.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SubscriptionPaymentHistoryCursor {
    created_at: DateTime<Utc>,
    payment_attempt_id: PaymentAttemptId,
}

impl SubscriptionPaymentHistoryCursor {
    pub const fn new(created_at: DateTime<Utc>, payment_attempt_id: PaymentAttemptId) -> Self {
        Self {
            created_at,
            payment_attempt_id,
        }
    }

    pub const fn created_at(self) -> DateTime<Utc> {
        self.created_at
    }

    pub const fn payment_attempt_id(self) -> PaymentAttemptId {
        self.payment_attempt_id
    }
}

/// One safe, provider-neutral subscription payment attempt for a billing portal.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SubscriptionPaymentHistoryItem {
    payment_attempt_id: PaymentAttemptId,
    kind: PaymentAttemptKind,
    status: PaymentAttemptStatus,
    amount: Money,
    billing_period: Option<BillingPeriod>,
    submitted_at: Option<DateTime<Utc>>,
    resolved_at: Option<DateTime<Utc>>,
    created_at: DateTime<Utc>,
}

impl SubscriptionPaymentHistoryItem {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        payment_attempt_id: PaymentAttemptId,
        kind: PaymentAttemptKind,
        status: PaymentAttemptStatus,
        amount: Money,
        billing_period: Option<BillingPeriod>,
        submitted_at: Option<DateTime<Utc>>,
        resolved_at: Option<DateTime<Utc>>,
        created_at: DateTime<Utc>,
    ) -> Result<Self, SubscriptionPaymentHistoryItemError> {
        if kind == PaymentAttemptKind::HostCharge {
            return Err(SubscriptionPaymentHistoryItemError);
        }
        Ok(Self {
            payment_attempt_id,
            kind,
            status,
            amount,
            billing_period,
            submitted_at,
            resolved_at,
            created_at,
        })
    }

    pub const fn payment_attempt_id(&self) -> PaymentAttemptId {
        self.payment_attempt_id
    }

    pub const fn kind(&self) -> PaymentAttemptKind {
        self.kind
    }

    pub const fn status(&self) -> PaymentAttemptStatus {
        self.status
    }

    pub const fn amount(&self) -> Money {
        self.amount
    }

    pub const fn billing_period(&self) -> Option<&BillingPeriod> {
        self.billing_period.as_ref()
    }

    pub const fn submitted_at(&self) -> Option<DateTime<Utc>> {
        self.submitted_at
    }

    pub const fn resolved_at(&self) -> Option<DateTime<Utc>> {
        self.resolved_at
    }

    pub const fn created_at(&self) -> DateTime<Utc> {
        self.created_at
    }
}

#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
#[error("subscription payment history cannot contain a host charge")]
pub struct SubscriptionPaymentHistoryItemError;

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SubscriptionPaymentHistoryPage {
    items: Vec<SubscriptionPaymentHistoryItem>,
    next_cursor: Option<SubscriptionPaymentHistoryCursor>,
}

impl SubscriptionPaymentHistoryPage {
    pub fn new(
        items: Vec<SubscriptionPaymentHistoryItem>,
        next_cursor: Option<SubscriptionPaymentHistoryCursor>,
    ) -> Self {
        Self { items, next_cursor }
    }

    pub fn items(&self) -> &[SubscriptionPaymentHistoryItem] {
        &self.items
    }

    pub fn into_items(self) -> Vec<SubscriptionPaymentHistoryItem> {
        self.items
    }

    pub const fn next_cursor(&self) -> Option<SubscriptionPaymentHistoryCursor> {
        self.next_cursor
    }
}

#[cfg(test)]
mod tests {
    use chrono::{TimeZone, Utc};

    use super::*;
    use crate::{CurrencyCode, PaymentAttemptId};
    use uuid::Uuid;

    #[test]
    fn payment_method_display_exposes_values_only_through_accessors_and_redacts_debug() {
        let display = SubscriptionPaymentMethodDisplay::new(
            Some(PaymentCardBrand::Visa),
            Some("4242".to_owned()),
            Some(12),
            Some(2031),
        )
        .expect("valid masked card display");

        assert_eq!(display.card_brand(), Some(PaymentCardBrand::Visa));
        assert_eq!(display.card_last_four(), Some("4242"));
        assert_eq!(display.card_expiration_month(), Some(12));
        assert_eq!(display.card_expiration_year(), Some(2031));

        let debug = format!("{display:?}");
        for value in ["Visa", "4242", "12", "2031"] {
            assert!(
                !debug.contains(value),
                "masked payment-method value appeared in Debug: {debug}"
            );
        }
        assert!(debug.contains("has_card_brand: true"));
        assert!(debug.contains("has_card_last_four: true"));
    }

    #[test]
    fn payment_method_display_rejects_raw_or_invalid_card_presentation() {
        assert_eq!(
            SubscriptionPaymentMethodDisplay::from_provider_parts(
                Some("4111111111111111"),
                Some("4242".to_owned()),
                None,
                None,
            ),
            Err(SubscriptionPaymentMethodDisplayError::CardBrandContainsRawCardData)
        );
        let unknown = SubscriptionPaymentMethodDisplay::from_provider_parts(
            Some("private-provider-sentinel"),
            Some("4242".to_owned()),
            None,
            None,
        )
        .unwrap()
        .unwrap();
        assert_eq!(unknown.card_brand(), Some(PaymentCardBrand::Other));
        assert!(!format!("{unknown:?}").contains("private-provider-sentinel"));
        assert_eq!(
            SubscriptionPaymentMethodDisplay::new(None, None, None, None),
            Err(SubscriptionPaymentMethodDisplayError::Empty)
        );
        assert_eq!(
            SubscriptionPaymentMethodDisplay::from_provider_parts(Some(" \t "), None, None, None,),
            Ok(None)
        );
        assert_eq!(
            SubscriptionPaymentMethodDisplay::new(None, Some("42".to_owned()), None, None),
            Err(SubscriptionPaymentMethodDisplayError::InvalidCardLastFour)
        );
        assert_eq!(
            SubscriptionPaymentMethodDisplay::new(None, None, Some(13), None),
            Err(SubscriptionPaymentMethodDisplayError::InvalidExpirationMonth)
        );
        assert_eq!(
            SubscriptionPaymentMethodDisplay::new(None, None, None, Some(1999)),
            Err(SubscriptionPaymentMethodDisplayError::InvalidExpirationYear)
        );
    }

    #[test]
    fn payment_history_limit_and_host_charge_boundary_are_checked() {
        assert_eq!(
            SubscriptionPaymentHistoryPageLimit::new(0),
            Err(SubscriptionPaymentHistoryPageLimitError)
        );
        assert_eq!(
            SubscriptionPaymentHistoryPageLimit::new(1)
                .expect("lower boundary")
                .get(),
            1
        );
        assert_eq!(
            SubscriptionPaymentHistoryPageLimit::new(SUBSCRIPTION_PAYMENT_HISTORY_PAGE_LIMIT)
                .expect("upper boundary")
                .get(),
            SUBSCRIPTION_PAYMENT_HISTORY_PAGE_LIMIT
        );
        assert_eq!(
            SubscriptionPaymentHistoryPageLimit::new(SUBSCRIPTION_PAYMENT_HISTORY_PAGE_LIMIT + 1),
            Err(SubscriptionPaymentHistoryPageLimitError)
        );

        let at = Utc.with_ymd_and_hms(2026, 8, 11, 12, 0, 0).unwrap();
        let amount = Money::new(500, CurrencyCode::new("USD").unwrap()).unwrap();
        assert_eq!(
            SubscriptionPaymentHistoryItem::new(
                PaymentAttemptId::new(Uuid::now_v7()),
                PaymentAttemptKind::HostCharge,
                PaymentAttemptStatus::Approved,
                amount,
                None,
                Some(at),
                Some(at),
                at,
            ),
            Err(SubscriptionPaymentHistoryItemError)
        );
    }
}