@@ -15,12 +15,10 @@ import { getGlobalQueue } from '../../../config/global-queues'
1515import assert from 'node:assert'
1616import { publicRoute } from '../../../lib/routing/router'
1717
18- const stripe = initStripe ( )
19-
2018async function getOrganisationPricingPlan (
2119 ctx : PublicRouteContext ,
2220 stripeCustomerId : string
23- ) : Promise < OrganisationPricingPlan > {
21+ ) {
2422 const em = ctx . em
2523
2624 const orgPlan = await em . repo ( OrganisationPricingPlan ) . findOneOrFail ( {
@@ -46,7 +44,8 @@ async function handleSubscriptionDeleted(
4644
4745async function handleSubscriptionUpdated (
4846 ctx : PublicRouteContext ,
49- subscription : Stripe . Subscription
47+ subscription : Stripe . Subscription ,
48+ stripe : Stripe
5049) {
5150 const em = ctx . em
5251
@@ -69,7 +68,7 @@ async function handleSubscriptionUpdated(
6968
7069 if ( prevStripePriceId !== orgPlan . stripePriceId ) {
7170 const price = subscription . items . data [ 0 ] . price
72- const product = await stripe ! . products . retrieve ( price . product as string )
71+ const product = await stripe . products . retrieve ( price . product as string )
7372 await queueEmail ( getGlobalQueue ( 'email' ) , new PlanUpgraded ( orgPlan . organisation , price , product ) )
7473 }
7574
@@ -83,15 +82,15 @@ async function handleSubscriptionUpdated(
8382async function handleNewInvoice (
8483 ctx : PublicRouteContext ,
8584 invoice : Stripe . Invoice
86- ) : Promise < void > {
85+ ) {
8786 const orgPlan = await getOrganisationPricingPlan ( ctx , invoice . customer as string )
8887 await queueEmail ( getGlobalQueue ( 'email' ) , new PlanInvoice ( orgPlan . organisation , invoice ) )
8988}
9089
9190async function handlePaymentFailed (
9291 ctx : PublicRouteContext ,
9392 invoice : Stripe . Invoice
94- ) : Promise < void > {
93+ ) {
9594 const orgPlan = await getOrganisationPricingPlan ( ctx , invoice . customer as string )
9695 await queueEmail ( getGlobalQueue ( 'email' ) , new PlanPaymentFailed ( orgPlan . organisation , invoice ) )
9796}
@@ -100,6 +99,7 @@ export const subscriptionsRoute = publicRoute({
10099 method : 'post' ,
101100 path : '/subscriptions' ,
102101 handler : async ( ctx ) => {
102+ const stripe = initStripe ( )
103103 assert ( stripe )
104104
105105 let event : Stripe . Event
@@ -122,7 +122,7 @@ export const subscriptionsRoute = publicRoute({
122122 break
123123 case 'customer.subscription.created' :
124124 case 'customer.subscription.updated' :
125- await handleSubscriptionUpdated ( ctx , event . data . object as Stripe . Subscription )
125+ await handleSubscriptionUpdated ( ctx , event . data . object as Stripe . Subscription , stripe )
126126 break
127127 case 'invoice.finalized' :
128128 await handleNewInvoice ( ctx , event . data . object as Stripe . Invoice )
0 commit comments