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