From 73d45abf73fdd3c0ca7142646e7f517806ea12bc Mon Sep 17 00:00:00 2001 From: Huang Xin Date: Mon, 30 Nov 2026 01:29:17 +0800 Subject: [PATCH] fix(payment): keep the plan while a plan switch's bank debit is processing (#8121) Switching plans in the Stripe billing portal bills the prorated difference at once. Paid by US bank debit (ACH), that payment stays `processing` for days, and Stripe marks the subscription `past_due` until it clears. getHighestActivePlan counted only `active` and `trialing`, so the customer.subscription.updated webhook wrote `plan: free` the moment the subscriber switched: no paid features, and cloud sync blocked once their library was over the free quota. A new subscription paid the same way is `active` from the start, so only the switch hit this. A `past_due` subscription now counts while its latest invoice's PaymentIntent is `processing`. When the debit settles, invoice.paid or invoice.payment_failed (both on the live endpoint) re-resolves the plan, so a failed debit still drops it as before. Failed card payments are unchanged. Reported by a subscriber by email. Verified: - stripe-server.test.ts: the two new processing tests fail on main with `expected 'free' to be 'plus'` and pass with the fix. - stripe-server.live.test.ts, read-only against the reporter's live subscription (past_due, ACH payment processing): main resolves `free`, this branch resolves `plus`. - pnpm test: 1452 files passed, 0 failed. pnpm lint: clean apart from one warning and one info that main has too. pnpm format:check: clean. - Not run: an end-to-end ACH plan switch with webhook delivery in Stripe test mode. Co-authored-by: Claude Code (Claude Opus 5.5) --- .../libs/payment/stripe-server.test.ts | 58 +++++++++++++++++++ .../src/libs/payment/stripe/server.ts | 32 +++++++++- 2 files changed, 87 insertions(+), 3 deletions(-) diff --git a/apps/readest-app/src/__tests__/libs/payment/stripe-server.test.ts b/apps/readest-app/src/__tests__/libs/payment/stripe-server.test.ts index 2f0ea6d3e..697027e5c 100644 --- a/apps/readest-app/src/__tests__/libs/payment/stripe-server.test.ts +++ b/apps/readest-app/src/__tests__/libs/payment/stripe-server.test.ts @@ -13,6 +13,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; const stripeMocks = vi.hoisted(() => ({ subscriptionsRetrieve: vi.fn(), subscriptionsList: vi.fn(), + paymentIntentsRetrieve: vi.fn(), })); const db = vi.hoisted(() => ({ @@ -27,6 +28,7 @@ vi.mock('stripe', () => { retrieve: stripeMocks.subscriptionsRetrieve, list: stripeMocks.subscriptionsList, }, + paymentIntents: { retrieve: stripeMocks.paymentIntentsRetrieve }, }; } MockStripe.createFetchHttpClient = () => ({}); @@ -106,9 +108,26 @@ const makeSub = (id: string, plan: string, status = 'active') => ({ }, }); +// A subscription as `subscriptions.list` returns it with +// `data.latest_invoice.payments` expanded: the latest invoice is paid by one +// PaymentIntent. +const listedSub = (id: string, status: string, paymentIntent: string) => ({ + id, + status, + latest_invoice: { + id: `in_${id}`, + payments: { + data: [ + { status: 'open', payment: { type: 'payment_intent', payment_intent: paymentIntent } }, + ], + }, + }, +}); + beforeEach(() => { stripeMocks.subscriptionsRetrieve.mockReset(); stripeMocks.subscriptionsList.mockReset(); + stripeMocks.paymentIntentsRetrieve.mockReset(); db.existingSubscription = null; db.planUpdates = []; process.env['STRIPE_SECRET_KEY_DEV'] = 'sk_test_dummy'; @@ -155,6 +174,32 @@ describe('getHighestActivePlan', () => { expect(await getHighestActivePlan(getStripe(), 'cus_1')).toBe('pro'); }); + // Switching plans bills the difference at once. Paid by bank debit (ACH), + // that payment stays `processing` for days, and Stripe marks the + // subscription `past_due` until it clears. + it('keeps the plan of a past_due subscription whose latest payment is still processing', async () => { + stripeMocks.subscriptionsList.mockResolvedValue({ + data: [listedSub('sub_plus', 'past_due', 'pi_ach')], + }); + stripeMocks.paymentIntentsRetrieve.mockResolvedValue({ id: 'pi_ach', status: 'processing' }); + stripeMocks.subscriptionsRetrieve.mockResolvedValue(makeSub('sub_plus', 'plus', 'past_due')); + + expect(await getHighestActivePlan(getStripe(), 'cus_1')).toBe('plus'); + }); + + it('drops a past_due subscription once its latest payment has failed', async () => { + stripeMocks.subscriptionsList.mockResolvedValue({ + data: [listedSub('sub_plus', 'past_due', 'pi_ach')], + }); + stripeMocks.paymentIntentsRetrieve.mockResolvedValue({ + id: 'pi_ach', + status: 'requires_payment_method', + }); + stripeMocks.subscriptionsRetrieve.mockResolvedValue(makeSub('sub_plus', 'plus', 'past_due')); + + expect(await getHighestActivePlan(getStripe(), 'cus_1')).toBe('free'); + }); + it('returns "free" when no subscription is active', async () => { stripeMocks.subscriptionsList.mockResolvedValue({ data: [{ id: 'sub_plus', status: 'canceled' }], @@ -203,6 +248,19 @@ describe('createOrUpdateSubscription', () => { expect(db.planUpdates.at(-1)?.['plan']).toBe('pro'); }); + it('keeps the new plan while the bank debit for a plan switch is processing', async () => { + db.existingSubscription = { id: 1 }; + stripeMocks.subscriptionsRetrieve.mockResolvedValue(makeSub('sub_1', 'plus', 'past_due')); + stripeMocks.subscriptionsList.mockResolvedValue({ + data: [listedSub('sub_1', 'past_due', 'pi_ach')], + }); + stripeMocks.paymentIntentsRetrieve.mockResolvedValue({ id: 'pi_ach', status: 'processing' }); + + await createOrUpdateSubscription('user-1', 'cus_1', 'sub_1'); + + expect(db.planUpdates.at(-1)?.['plan']).toBe('plus'); + }); + it('downgrades to "free" when the only subscription becomes inactive', async () => { db.existingSubscription = { id: 1 }; stripeMocks.subscriptionsRetrieve.mockResolvedValue(makeSub('sub_plus', 'plus', 'canceled')); diff --git a/apps/readest-app/src/libs/payment/stripe/server.ts b/apps/readest-app/src/libs/payment/stripe/server.ts index 6e3b19eb7..77f9d1bf2 100644 --- a/apps/readest-app/src/libs/payment/stripe/server.ts +++ b/apps/readest-app/src/libs/payment/stripe/server.ts @@ -39,9 +39,33 @@ const getSubscriptionPlan = (subscription: Stripe.Subscription): UserPlan => { return product?.metadata?.plan || 'free'; }; +// Switching plans bills the difference at once. Paid by bank debit (ACH), that +// payment stays `processing` for days and Stripe marks the subscription +// `past_due` until it clears, while a new subscription paid the same way is +// `active` from the start. Keep the plan while the payment is in flight; +// `invoice.paid` or `invoice.payment_failed` resolves it again once it settles. +const isLatestPaymentProcessing = async (stripe: Stripe, sub: Stripe.Subscription) => { + const invoice = sub.latest_invoice; + if (!invoice || typeof invoice === 'string') return false; + const intents = (invoice.payments?.data ?? []) + .filter((p) => p.status === 'open') + .flatMap((p) => p.payment.payment_intent ?? []); + const statuses = await Promise.all( + intents.map(async (pi) => + typeof pi === 'string' ? (await stripe.paymentIntents.retrieve(pi)).status : pi.status, + ), + ); + return statuses.includes('processing'); +}; + +const isEntitledSubscription = async (stripe: Stripe, sub: Stripe.Subscription) => + ['active', 'trialing'].includes(sub.status) || + (sub.status === 'past_due' && (await isLatestPaymentProcessing(stripe, sub))); + /** * Resolve the highest plan among a customer's currently active (or trialing) - * Stripe subscriptions. Returns `'free'` when none are active. This keeps the + * Stripe subscriptions, counting a past_due one whose payment is still + * processing. Returns `'free'` when none are entitled. This keeps the * `plans` table correct regardless of the order in which subscription webhooks * arrive when multiple subscriptions overlap. */ @@ -53,10 +77,12 @@ export const getHighestActivePlan = async ( customer: customerId, status: 'all', limit: 100, + expand: ['data.latest_invoice.payments'], }); - const activeSubscriptions = subscriptions.filter((sub) => - ['active', 'trialing'].includes(sub.status), + const entitled = await Promise.all( + subscriptions.map((sub) => isEntitledSubscription(stripe, sub)), ); + const activeSubscriptions = subscriptions.filter((_, i) => entitled[i]); const plans = await Promise.all( activeSubscriptions.map(async (sub) => { const detailed = await stripe.subscriptions.retrieve(sub.id, {