11import { db } from '@sim/db'
22import { member , subscription , user } from '@sim/db/schema'
33import { createLogger } from '@sim/logger'
4+ import { getErrorMessage } from '@sim/utils/errors'
45import { and , eq } from 'drizzle-orm'
56import { getHighestPrioritySubscription } from '@/lib/billing/core/plan'
67import { getDisplayPlanName , isPaid } from '@/lib/billing/plan-helpers'
8+ import { requireStripeClient } from '@/lib/billing/stripe-client'
79import { formatTrialEndDate , hasPaidSubscriptionStatus } from '@/lib/billing/subscriptions/utils'
810import { stripeWebhookIdempotency } from '@/lib/billing/webhooks/idempotency'
911import { getBaseUrl } from '@/lib/core/utils/urls'
@@ -32,14 +34,34 @@ export interface TrialEndingSubscription {
3234 }
3335}
3436
35- /** What the card is charged when a trial converts, from the subscription's own Stripe price. */
36- function formatRenewalPrice ( stripeSubscription : TrialEndingSubscription ) : string | null {
37- const price = stripeSubscription . items ?. data ?. [ 0 ] ?. price
38- if ( ! price ?. unit_amount || ! price . recurring ) return null
39- const quantity = stripeSubscription . items . data [ 0 ] ?. quantity ?? 1
40- const dollars = ( price . unit_amount * quantity ) / 100
41- const amount = Number . isInteger ( dollars ) ? `$${ dollars } ` : `$${ dollars . toFixed ( 2 ) } `
42- return `${ amount } /${ price . recurring . interval } `
37+ function formatDollars ( cents : number ) : string {
38+ const dollars = cents / 100
39+ return Number . isInteger ( dollars ) ? `$${ dollars } ` : `$${ dollars . toFixed ( 2 ) } `
40+ }
41+
42+ /**
43+ * What the card is charged when a trial converts. Stripe's invoice preview includes any discount a
44+ * promotion code applied; the subscription's list price is the fallback if the preview fails.
45+ */
46+ async function readRenewalCharge (
47+ stripeSubscription : TrialEndingSubscription
48+ ) : Promise < string | null > {
49+ const item = stripeSubscription . items ?. data ?. [ 0 ]
50+ const interval = item ?. price . recurring ?. interval
51+ if ( ! interval ) return null
52+ try {
53+ const preview = await requireStripeClient ( ) . invoices . createPreview ( {
54+ subscription : stripeSubscription . id ,
55+ } )
56+ return `${ formatDollars ( preview . amount_due ) } /${ interval } `
57+ } catch ( error ) {
58+ logger . warn ( 'Invoice preview failed for the trial reminder; quoting the list price' , {
59+ stripeSubscriptionId : stripeSubscription . id ,
60+ error : getErrorMessage ( error ) ,
61+ } )
62+ }
63+ if ( ! item ?. price . unit_amount ) return null
64+ return `${ formatDollars ( item . price . unit_amount * ( item . quantity ?? 1 ) ) } /${ interval } `
4365}
4466
4567/**
@@ -50,7 +72,8 @@ function formatRenewalPrice(stripeSubscription: TrialEndingSubscription): string
5072export async function handleTrialWillEnd (
5173 stripeSubscription : TrialEndingSubscription
5274) : Promise < void > {
53- if ( stripeSubscription . status !== 'trialing' || ! stripeSubscription . trial_end ) return
75+ const trialEnd = stripeSubscription . trial_end
76+ if ( stripeSubscription . status !== 'trialing' || ! trialEnd ) return
5477
5578 const [ recorded ] = await db
5679 . select ( { plan : subscription . plan , referenceId : subscription . referenceId } )
@@ -66,29 +89,31 @@ export async function handleTrialWillEnd(
6689
6790 await stripeWebhookIdempotency . executeWithIdempotency (
6891 'trial-ending-reminder' ,
69- `${ stripeSubscription . id } :${ stripeSubscription . trial_end } ` ,
92+ `${ stripeSubscription . id } :${ trialEnd } ` ,
7093 async ( ) => {
7194 const recipient = await readRecipient ( recorded . referenceId )
72- const price = formatRenewalPrice ( stripeSubscription )
95+ const price = await readRenewalCharge ( stripeSubscription )
7396 if ( ! recipient || ! price ) return { sent : false }
7497
7598 const { getTrialEndingSubject, renderTrialEndingEmail } = await import ( '@/components/emails' )
7699 const { sendEmail } = await import ( '@/lib/messaging/email/mailer' )
77100 const planName = getDisplayPlanName ( recorded . plan )
78- const endsOn = formatTrialEndDate ( new Date ( stripeSubscription . trial_end * 1000 ) )
101+ const endsOn = formatTrialEndDate ( new Date ( trialEnd * 1000 ) )
79102 const html = await renderTrialEndingEmail ( {
80103 planName,
81104 userName : recipient . name || undefined ,
82105 endsOn,
83106 price,
84107 billingLink : `${ getBaseUrl ( ) } /account/settings/billing` ,
85108 } )
86- await sendEmail ( {
109+ const result = await sendEmail ( {
87110 to : recipient . email ,
88111 subject : getTrialEndingSubject ( planName , endsOn ) ,
89112 html,
90113 emailType : 'transactional' ,
91114 } )
115+ // Throwing leaves the reminder unrecorded, so Stripe's redelivery retries it.
116+ if ( ! result . success ) throw new Error ( 'Trial reminder email failed to send' )
92117 return { sent : true }
93118 }
94119 )
0 commit comments