fix(payment): keep the plan while a plan switch's bank debit is processing (#8121)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / build_web_app (push) Blocked by required conditions
PR checks / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run

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) <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-30 01:29:17 +08:00 • committed by GitHub
parent 18824247b9
commit 73d45abf73
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 87 additions and 3 deletions

View file

@ -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'));

View file

@ -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, {