@@ -124,13 +124,18 @@ export const upgradeSubscription = async ({
124
124
throw new Error ( 'Subscription not found' ) ;
125
125
}
126
126
127
- const currentPrice = currentSubscription . items . data [ 0 ] ?. price . id ;
127
+ const currentItem = currentSubscription . items . data . find ( ( item ) => item . id === subscriptionItemId ) ;
128
+ if ( ! currentItem ) {
129
+ throw new Error ( 'Subscription item not found' ) ;
130
+ }
131
+
132
+ const currentPrice = currentItem . price . id ;
128
133
if ( currentPrice === priceId ) {
129
134
throw new Error ( 'New price is the same as the current price' ) ;
130
135
}
131
136
132
- const currentPriceAmount = currentSubscription . items . data [ 0 ] ? .price . unit_amount ;
133
- if ( ! currentPriceAmount ) {
137
+ const currentPriceAmount = currentItem . price . unit_amount ;
138
+ if ( currentPriceAmount == null ) {
134
139
throw new Error ( 'Current price amount not found' ) ;
135
140
}
136
141
@@ -145,27 +150,38 @@ export const upgradeSubscription = async ({
145
150
proration_behavior : 'none' ,
146
151
} ) ;
147
152
148
- const newPriceAmount = updatedSubscription . items . data [ 0 ] ?. price . unit_amount ;
149
- if ( ! newPriceAmount ) {
153
+ const newItem =
154
+ updatedSubscription . items . data . find ( ( i ) => i . id === subscriptionItemId )
155
+ ?? updatedSubscription . items . data [ 0 ] ;
156
+ if ( ! newItem ) {
157
+ throw new Error ( 'Subscription item not found on updated subscription' ) ;
158
+ }
159
+ const newPriceAmount = newItem . price ?. unit_amount ;
160
+ if ( newPriceAmount == null ) {
150
161
throw new Error ( 'New price amount not found' ) ;
151
162
}
152
163
153
- const priceDifferenceAmount = newPriceAmount - currentPriceAmount ;
164
+ const quantity = newItem . quantity ?? 1 ;
165
+ const priceDifferenceAmount = ( newPriceAmount - currentPriceAmount ) * quantity ;
154
166
155
167
// Create a one-off invoice item for the price difference if the new price is higher
156
168
if ( priceDifferenceAmount > 0 ) {
157
169
await stripe . invoiceItems . create ( {
158
170
customer : updatedSubscription . customer as string ,
159
171
amount : priceDifferenceAmount ,
160
- currency : updatedSubscription . currency || 'usd' ,
161
- description : 'Price upgrade difference' ,
172
+ description : 'Onlook subscription upgrade' ,
162
173
} ) ;
163
174
164
175
// Create invoice immediately
165
176
const invoice = await stripe . invoices . create ( {
166
177
customer : updatedSubscription . customer as string ,
167
178
auto_advance : true ,
168
179
} ) ;
180
+
181
+ if ( ! invoice . id ) {
182
+ throw new Error ( 'Invoice not created' ) ;
183
+ }
184
+ await stripe . invoices . pay ( invoice . id ) ;
169
185
}
170
186
171
187
return updatedSubscription ;
0 commit comments