Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions apps/sim/lib/billing/free-plan.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ import { executeSearchTool } from '@/lib/internal/search/execute-tool'
import { applyScheduleRunFailureUpdate } from '@/background/schedule-execution'

const { stripeStub, mockSendEmail, mockNotifyScheduleAutoDisabled } = vi.hoisted(() => ({
stripeStub: { subscriptions: { update: vi.fn() }, invoices: { createPreview: vi.fn() } },
stripeStub: {
subscriptions: { update: vi.fn(), retrieve: vi.fn() },
invoices: { createPreview: vi.fn() },
},
mockSendEmail: vi.fn(),
mockNotifyScheduleAutoDisabled: vi.fn(),
}))
Expand Down Expand Up @@ -110,15 +113,21 @@ function search(userId: string, workspaceId: string) {
})
}

/** The subscriptions as Stripe holds them now, which the reminder reads back. */
const liveSubscriptions = new Map<string, TrialEndingSubscription>()

/** A `trial_will_end` payload, which Stripe also holds as the live subscription. */
function trialWillEnd(stripeSubscriptionId: string, status = 'trialing'): TrialEndingSubscription {
return {
const subscription = {
id: stripeSubscriptionId,
status,
trial_end: Math.floor((Date.now() + 3 * DAY_MS) / 1000),
items: {
data: [{ quantity: 1, price: { unit_amount: 2500, recurring: { interval: 'month' } } }],
},
}
liveSubscriptions.set(stripeSubscriptionId, subscription)
return subscription
}

async function addClaimedSchedule() {
Expand Down Expand Up @@ -152,6 +161,10 @@ beforeEach(() => {
mockSendEmail.mockResolvedValue({ success: true })
stripeStub.invoices.createPreview.mockReset()
stripeStub.invoices.createPreview.mockResolvedValue({ amount_due: 2500 })
stripeStub.subscriptions.retrieve.mockReset()
stripeStub.subscriptions.retrieve.mockImplementation(async (id: string) =>
liveSubscriptions.get(id)
)
mockNotifyScheduleAutoDisabled.mockReset()
})

Expand Down Expand Up @@ -280,6 +293,32 @@ describe('handleTrialWillEnd', () => {

expect(mockSendEmail).not.toHaveBeenCalled()
})

it('sends nothing when the trial ended before the reminder arrived', async () => {
const userId = await createUser()
const stripeSubscriptionId = await addSubscription(userId, 'trialing')
const event = trialWillEnd(stripeSubscriptionId)
// A card that already had a trial ends the new one at once; the event still says trialing.
liveSubscriptions.set(stripeSubscriptionId, { ...event, status: 'past_due', trial_end: null })
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved

await handleTrialWillEnd(event)

expect(mockSendEmail).not.toHaveBeenCalled()
})
it('sends nothing for a reminder about an end date the trial no longer has', async () => {
const userId = await createUser()
const stripeSubscriptionId = await addSubscription(userId, 'trialing')
const event = trialWillEnd(stripeSubscriptionId)
// Still trialing, but its end moved after this event was sent.
liveSubscriptions.set(stripeSubscriptionId, {
...event,
trial_end: (event.trial_end ?? 0) + 7 * 86_400,
})

await handleTrialWillEnd(event)

expect(mockSendEmail).not.toHaveBeenCalled()
})
})

describe('endProTrial', () => {
Expand Down
11 changes: 7 additions & 4 deletions apps/sim/lib/billing/webhooks/plan-notices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,15 @@ async function readRenewalCharge(
* Handles Stripe's `customer.subscription.trial_will_end`, which arrives three days before a trial
* converts: emails the trialing account the date, the charge, and how to cancel. Sent once per
* subscription and trial end, however often Stripe redelivers the event.
*
* Reads the subscription as Stripe holds it now: the event's copy can predate a trial ended early
* (a card that already had a trial is charged at once), and Stripe does not order its webhooks.
*/
export async function handleTrialWillEnd(
stripeSubscription: TrialEndingSubscription
): Promise<void> {
export async function handleTrialWillEnd(event: TrialEndingSubscription): Promise<void> {
const stripeSubscription: TrialEndingSubscription =
await requireStripeClient().subscriptions.retrieve(event.id)
const trialEnd = stripeSubscription.trial_end
if (stripeSubscription.status !== 'trialing' || !trialEnd) return
if (stripeSubscription.status !== 'trialing' || !trialEnd || trialEnd !== event.trial_end) return

const [recorded] = await db
.select({ plan: subscription.plan, referenceId: subscription.referenceId })
Expand Down
Loading