| 368 | } |
| 369 | |
| 370 | public async updateAdditionalSeats(subscriptionId: string, quantity: number, prorationDate: number) { |
| 371 | if (!this.stripe) { |
| 372 | throw new Error('Stripe is not initialized') |
| 373 | } |
| 374 | |
| 375 | try { |
| 376 | const subscription = await this.stripe.subscriptions.retrieve(subscriptionId) |
| 377 | const additionalSeatsItem = subscription.items.data.find( |
| 378 | (item) => (item.price.product as string) === process.env.ADDITIONAL_SEAT_ID |
| 379 | ) |
| 380 | |
| 381 | // Get the price ID for additional seats if needed |
| 382 | const prices = await this.stripe.prices.list({ |
| 383 | product: process.env.ADDITIONAL_SEAT_ID, |
| 384 | active: true, |
| 385 | limit: 1 |
| 386 | }) |
| 387 | |
| 388 | if (prices.data.length === 0) { |
| 389 | throw new Error('No active price found for additional seats') |
| 390 | } |
| 391 | |
| 392 | // Create an invoice immediately for the proration |
| 393 | const updatedSubscription = await this.stripe.subscriptions.update(subscriptionId, { |
| 394 | items: [ |
| 395 | additionalSeatsItem |
| 396 | ? { |
| 397 | id: additionalSeatsItem.id, |
| 398 | quantity: quantity |
| 399 | } |
| 400 | : { |
| 401 | price: prices.data[0].id, |
| 402 | quantity: quantity |
| 403 | } |
| 404 | ], |
| 405 | proration_behavior: 'always_invoice', |
| 406 | proration_date: prorationDate |
| 407 | }) |
| 408 | |
| 409 | // Get the latest invoice for this subscription |
| 410 | const invoice = await this.stripe.invoices.list({ |
| 411 | subscription: subscriptionId, |
| 412 | limit: 1 |
| 413 | }) |
| 414 | |
| 415 | if (invoice.data.length > 0) { |
| 416 | const latestInvoice = invoice.data[0] |
| 417 | // Only try to pay if the invoice is not already paid |
| 418 | if (latestInvoice.status !== 'paid') { |
| 419 | await this.stripe.invoices.pay(latestInvoice.id) |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | return { |
| 424 | success: true, |
| 425 | subscription: updatedSubscription, |
| 426 | invoice: invoice.data[0] |
| 427 | } |