11import { db } from '@sim/db'
22import { subscription , trialCard , userStats } from '@sim/db/schema'
33import { createLogger } from '@sim/logger'
4- import { and , eq , isNotNull , ne , notInArray , or } from 'drizzle-orm'
4+ import { and , asc , eq , isNotNull , notInArray , or } from 'drizzle-orm'
55import type Stripe from 'stripe'
66import { PRO_CREDIT_TIER , PRO_TRIAL_DAYS } from '@/lib/billing/constants'
77import { buildPlanName } from '@/lib/billing/plan-helpers'
@@ -67,10 +67,14 @@ export async function getProTrialCheckoutParams(params: {
6767
6868/**
6969 * Holds each card, and each account, to one Pro trial. Runs when a checkout completes: a trial
70- * whose card already started another trial, whose account already trialed (two checkouts racing),
71- * or whose card cannot be identified ends at once, so Stripe charges the card for the first period
72- * as for any paid checkout. The card's claim is recorded under the subscription it started, so a
73- * redelivered webhook finds its own claim and keeps the trial.
70+ * whose card already started another trial, whose account already has an earlier trial (two
71+ * checkouts racing), or whose card cannot be identified ends at once, so Stripe charges the card
72+ * for the first period as for any paid checkout.
73+ *
74+ * Every trial records a claim on its card, and the first claim wins: a card's winner is whichever
75+ * subscription claimed it, and an account's winner is its earliest claim. The verdict reads only
76+ * the claims, so a redelivered webhook reaches the same verdict, and a check that failed partway
77+ * is safe to run again.
7478 *
7579 * @returns whether the subscription is still in its trial
7680 */
@@ -97,16 +101,49 @@ export async function enforceOneTrialPerCard(
97101 return false
98102}
99103
104+ /**
105+ * Enforces {@link enforceOneTrialPerCard} for a completed checkout, from the webhook path that
106+ * Stripe retries on failure, so a check that failed in the plugin's completion hook still runs.
107+ */
108+ export async function enforceOneTrialPerCardForCheckout (
109+ session : Stripe . Checkout . Session
110+ ) : Promise < void > {
111+ if ( session . mode !== 'subscription' || ! session . subscription || ! session . client_reference_id ) {
112+ return
113+ }
114+ const subscriptionId =
115+ typeof session . subscription === 'string' ? session . subscription : session . subscription . id
116+ const stripeSubscription = await requireStripeClient ( ) . subscriptions . retrieve ( subscriptionId )
117+ await enforceOneTrialPerCard ( stripeSubscription , session . client_reference_id )
118+ }
119+
100120async function findTrialIneligibility (
101121 stripe : Stripe ,
102122 stripeSubscription : Stripe . Subscription ,
103123 userId : string
104- ) : Promise < 'card-unidentified' | 'account-already-trialed' | 'card-already-trialed' | null > {
105- if ( await hasEarlierTrial ( userId , stripeSubscription . id ) ) return 'account-already-trialed'
124+ ) : Promise < 'card-unidentified' | 'card-already-trialed' | 'account-already-trialed' | null > {
106125 const fingerprint = await getCardFingerprint ( stripe , stripeSubscription . default_payment_method )
107126 if ( ! fingerprint ) return 'card-unidentified'
108- if ( ! ( await claimTrialCard ( fingerprint , userId , stripeSubscription . id ) ) ) {
109- return 'card-already-trialed'
127+
128+ await db
129+ . insert ( trialCard )
130+ . values ( { fingerprint, userId, stripeSubscriptionId : stripeSubscription . id } )
131+ . onConflictDoNothing ( { target : trialCard . fingerprint } )
132+ const claims = await db
133+ . select ( {
134+ fingerprint : trialCard . fingerprint ,
135+ userId : trialCard . userId ,
136+ stripeSubscriptionId : trialCard . stripeSubscriptionId ,
137+ } )
138+ . from ( trialCard )
139+ . where ( or ( eq ( trialCard . fingerprint , fingerprint ) , eq ( trialCard . userId , userId ) ) )
140+ . orderBy ( asc ( trialCard . createdAt ) , asc ( trialCard . stripeSubscriptionId ) )
141+
142+ const cardWinner = claims . find ( ( claim ) => claim . fingerprint === fingerprint )
143+ if ( cardWinner ?. stripeSubscriptionId !== stripeSubscription . id ) return 'card-already-trialed'
144+ const accountWinner = claims . find ( ( claim ) => claim . userId === userId )
145+ if ( accountWinner ?. stripeSubscriptionId !== stripeSubscription . id ) {
146+ return 'account-already-trialed'
110147 }
111148 return null
112149}
@@ -122,39 +159,3 @@ async function getCardFingerprint(
122159 : paymentMethod
123160 return resolved . card ?. fingerprint ?? null
124161}
125-
126- async function hasEarlierTrial ( userId : string , stripeSubscriptionId : string ) : Promise < boolean > {
127- const [ earlier ] = await db
128- . select ( { id : subscription . id } )
129- . from ( subscription )
130- . where (
131- and (
132- eq ( subscription . referenceId , userId ) ,
133- isNotNull ( subscription . trialStart ) ,
134- ne ( subscription . stripeSubscriptionId , stripeSubscriptionId )
135- )
136- )
137- . limit ( 1 )
138- return Boolean ( earlier )
139- }
140-
141- /** Claims the card for this trial; true when the claim is this subscription's. */
142- async function claimTrialCard (
143- fingerprint : string ,
144- userId : string ,
145- stripeSubscriptionId : string
146- ) : Promise < boolean > {
147- const [ claimed ] = await db
148- . insert ( trialCard )
149- . values ( { fingerprint, userId, stripeSubscriptionId } )
150- . onConflictDoNothing ( { target : trialCard . fingerprint } )
151- . returning ( { fingerprint : trialCard . fingerprint } )
152- if ( claimed ) return true
153-
154- const [ holder ] = await db
155- . select ( { stripeSubscriptionId : trialCard . stripeSubscriptionId } )
156- . from ( trialCard )
157- . where ( eq ( trialCard . fingerprint , fingerprint ) )
158- . limit ( 1 )
159- return holder ?. stripeSubscriptionId === stripeSubscriptionId
160- }
0 commit comments