Skip to content

Commit a372f5d

Browse files
committed
fix(billing): trial reminder quotes the discounted charge and retries a failed send, eligibility-accurate trial copy
1 parent e512ddd commit a372f5d

6 files changed

Lines changed: 72 additions & 20 deletions

File tree

‎apps/sim/app/workspace/[workspaceId]/settings/components/billing/billing.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -654,7 +654,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
654654
</div>
655655
)}
656656

657-
{isTrialing && canManageBilling && !isCancelledAtPeriodEnd && (
657+
{isTrialing && !isOrganizationScope && canManageBilling && !isCancelledAtPeriodEnd && (
658658
<div className='flex items-center justify-between'>
659659
<span className='text-[var(--text-body)] text-small'>
660660
End the trial and start paying today

‎apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,14 @@ export function Upgrade({ workspaceId }: UpgradeProps) {
6767
...upgradeUrlKeys,
6868
})
6969
const [showAllFeatures, setShowAllFeatures] = useState(false)
70-
const { data: viewerBilling } = useSubscriptionData()
71-
const proTrialEligible = viewerBilling?.data?.proTrialEligible === true
72-
7370
const header = reason ? UPGRADE_REASON_COPY[reason].header : DEFAULT_UPGRADE_HEADER
7471
const canManageBilling = canManageWorkspaceBilling(hostContext, session?.user?.id)
72+
// The trial is a personal checkout, so only a payer viewing their own workspace can start one.
73+
const isPersonalWorkspace = !hostContext.hostOrganizationId
74+
const { data: viewerBilling } = useSubscriptionData({
75+
enabled: canManageBilling && isPersonalWorkspace,
76+
})
77+
const proTrialEligible = isPersonalWorkspace && viewerBilling?.data?.proTrialEligible === true
7578

7679
const handleBack = useCallback(() => {
7780
router.replace(origin ?? `/workspace/${workspaceId}`)

‎apps/sim/components/emails/billing/credits-exhausted-email.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export function CreditsExhaustedEmail({
3131
<ProFeaturesBox />
3232

3333
<Text style={baseStyles.paragraph}>
34-
New Pro subscribers start with a {PRO_TRIAL_DAYS}-day free trial.
34+
If you haven't had a Sim trial, Pro starts with a {PRO_TRIAL_DAYS}-day free trial.
3535
</Text>
3636

3737
<EmailButton href={upgradeLink}>Upgrade to Pro</EmailButton>

‎apps/sim/components/emails/billing/free-tier-upgrade-email.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export function FreeTierUpgradeEmail({
3535
<ProFeaturesBox />
3636

3737
<Text style={baseStyles.paragraph}>
38-
New Pro subscribers start with a {PRO_TRIAL_DAYS}-day free trial.
38+
If you haven't had a Sim trial, Pro starts with a {PRO_TRIAL_DAYS}-day free trial.
3939
</Text>
4040

4141
<EmailButton href={upgradeLink}>Upgrade to Pro</EmailButton>

‎apps/sim/lib/billing/free-plan.integration.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { executeSearchTool } from '@/lib/internal/search/execute-tool'
2020
import { applyScheduleRunFailureUpdate } from '@/background/schedule-execution'
2121

2222
const { stripeStub, mockSendEmail, mockNotifyScheduleAutoDisabled } = vi.hoisted(() => ({
23-
stripeStub: { subscriptions: { update: vi.fn() } },
23+
stripeStub: { subscriptions: { update: vi.fn() }, invoices: { createPreview: vi.fn() } },
2424
mockSendEmail: vi.fn(),
2525
mockNotifyScheduleAutoDisabled: vi.fn(),
2626
}))
@@ -144,6 +144,8 @@ beforeEach(() => {
144144
stripeStub.subscriptions.update.mockResolvedValue({})
145145
mockSendEmail.mockReset()
146146
mockSendEmail.mockResolvedValue({ success: true })
147+
stripeStub.invoices.createPreview.mockReset()
148+
stripeStub.invoices.createPreview.mockResolvedValue({ amount_due: 2500 })
147149
mockNotifyScheduleAutoDisabled.mockReset()
148150
})
149151

@@ -239,6 +241,28 @@ describe('handleTrialWillEnd', () => {
239241
)
240242
})
241243

244+
it('quotes the discounted charge from the invoice preview', async () => {
245+
const userId = await createUser()
246+
const stripeSubscriptionId = await addSubscription(userId, 'trialing')
247+
stripeStub.invoices.createPreview.mockResolvedValue({ amount_due: 1250 })
248+
249+
await handleTrialWillEnd(trialWillEnd(stripeSubscriptionId))
250+
251+
expect(mockSendEmail.mock.calls[0]?.[0].html).toContain('$12.50/month')
252+
})
253+
254+
it('retries a reminder whose email failed to send', async () => {
255+
const userId = await createUser()
256+
const stripeSubscriptionId = await addSubscription(userId, 'trialing')
257+
const event = trialWillEnd(stripeSubscriptionId)
258+
mockSendEmail.mockResolvedValueOnce({ success: false, message: 'Failed to send email' })
259+
260+
await expect(handleTrialWillEnd(event)).rejects.toThrow()
261+
await handleTrialWillEnd(event)
262+
263+
expect(mockSendEmail).toHaveBeenCalledTimes(2)
264+
})
265+
242266
it('sends nothing for a subscription that is no longer trialing', async () => {
243267
const userId = await createUser()
244268
const stripeSubscriptionId = await addSubscription(userId, 'active')

‎apps/sim/lib/billing/webhooks/plan-notices.ts‎

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { db } from '@sim/db'
22
import { member, subscription, user } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
4+
import { getErrorMessage } from '@sim/utils/errors'
45
import { and, eq } from 'drizzle-orm'
56
import { getHighestPrioritySubscription } from '@/lib/billing/core/plan'
67
import { getDisplayPlanName, isPaid } from '@/lib/billing/plan-helpers'
8+
import { requireStripeClient } from '@/lib/billing/stripe-client'
79
import { formatTrialEndDate, hasPaidSubscriptionStatus } from '@/lib/billing/subscriptions/utils'
810
import { stripeWebhookIdempotency } from '@/lib/billing/webhooks/idempotency'
911
import { 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
5072
export 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

Comments
 (0)