|
| 1 | +import { type CommerceMoneyAmount } from './CommercePlan'; |
| 2 | +import { CommerceSubscriptionItem } from './CommerceSubscriptionItem'; |
| 3 | +import type { CommerceSubscriptionJSON } from './JSON'; |
| 4 | + |
| 5 | +/** |
| 6 | + * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. |
| 7 | + * It is advised to pin the SDK version to avoid breaking changes. |
| 8 | + */ |
| 9 | +export class CommerceSubscription { |
| 10 | + constructor( |
| 11 | + /** |
| 12 | + * The unique identifier for the commerce subscription. |
| 13 | + */ |
| 14 | + readonly id: string, |
| 15 | + /** |
| 16 | + * The current status of the subscription. |
| 17 | + */ |
| 18 | + readonly status: CommerceSubscriptionJSON['status'], |
| 19 | + /** |
| 20 | + * The ID of the payer for this subscription. |
| 21 | + */ |
| 22 | + readonly payerId: string, |
| 23 | + /** |
| 24 | + * Unix timestamp (milliseconds) of creation. |
| 25 | + */ |
| 26 | + readonly createdAt: number, |
| 27 | + /** |
| 28 | + * Unix timestamp (milliseconds) of last update. |
| 29 | + */ |
| 30 | + readonly updatedAt: number, |
| 31 | + /** |
| 32 | + * Unix timestamp (milliseconds) when the subscription became active. |
| 33 | + */ |
| 34 | + readonly activeAt: number | null, |
| 35 | + /** |
| 36 | + * Unix timestamp (milliseconds) when the subscription became past due. |
| 37 | + */ |
| 38 | + readonly pastDueAt: number | null, |
| 39 | + /** |
| 40 | + * Array of subscription items in this subscription. |
| 41 | + */ |
| 42 | + readonly subscriptionItems: CommerceSubscriptionItem[], |
| 43 | + /** |
| 44 | + * Information about the next scheduled payment. |
| 45 | + */ |
| 46 | + readonly nextPayment: { date: number; amount: CommerceMoneyAmount } | null, |
| 47 | + /** |
| 48 | + * Whether the payer is eligible for a free trial. |
| 49 | + */ |
| 50 | + readonly eligibleForFreeTrial: boolean, |
| 51 | + ) {} |
| 52 | + |
| 53 | + static fromJSON(data: CommerceSubscriptionJSON): CommerceSubscription { |
| 54 | + const nextPayment = data.next_payment |
| 55 | + ? { |
| 56 | + date: data.next_payment.date, |
| 57 | + amount: { |
| 58 | + amount: data.next_payment.amount.amount, |
| 59 | + amountFormatted: data.next_payment.amount.amount_formatted, |
| 60 | + currency: data.next_payment.amount.currency, |
| 61 | + currencySymbol: data.next_payment.amount.currency_symbol, |
| 62 | + }, |
| 63 | + } |
| 64 | + : null; |
| 65 | + |
| 66 | + return new CommerceSubscription( |
| 67 | + data.id, |
| 68 | + data.status, |
| 69 | + data.payer_id, |
| 70 | + data.created_at, |
| 71 | + data.updated_at, |
| 72 | + data.active_at ?? null, |
| 73 | + data.past_due_at ?? null, |
| 74 | + data.subscription_items.map(item => CommerceSubscriptionItem.fromJSON(item)), |
| 75 | + nextPayment, |
| 76 | + data.eligible_for_free_trial ?? false, |
| 77 | + ); |
| 78 | + } |
| 79 | +} |
0 commit comments