Skip to content

fix(billing): restore plan after dunning recovery#3627

Merged
PierreBrisorgueil merged 2 commits intomasterfrom
fix/billing-v8-dunning-plan-recovery
May 7, 2026
Merged

fix(billing): restore plan after dunning recovery#3627
PierreBrisorgueil merged 2 commits intomasterfrom
fix/billing-v8-dunning-plan-recovery

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

Summary

V8 audit C1 fix: handleInvoicePaymentSucceeded now re-fetches the live Stripe subscription and restores the correct plan field when clearing pastDueSince after a dunning sweep downgraded the sub to plan=free.

  • Root cause: markUnpaid writes plan='free' status='unpaid' during dunning sweep. When the user later pays the overdue invoice, Stripe fires invoice.payment_succeeded. The handler only wrote { pastDueSince: null, status: 'active' }, relying on customer.subscription.updated to restore the plan — if that event is dead-lettered, the paid customer is permanently stuck on free plan (revenue leak).
  • Fix: re-fetch live Stripe sub via stripe.subscriptions.retrieve(), resolve plan via existing resolvePlan(), add plan to the fields update, call syncOrganizationPlan() after update succeeds.
  • Fallback: Stripe re-fetch failure is non-fatal — logs warn, skips plan restore, pastDueSince: null + status: 'active' update still fires.
  • Guard: added explicit if (!stripe) throw so the fallback warn log emits "Stripe not configured" rather than a cryptic TypeError.

Test plan

  • V8 C1 — dunning recovery: restores plan=pro after unpaid downgrade to free — asserts plan: 'pro', status: 'active', pastDueSince: null + setPlan called on org
  • V8 C1 — Stripe re-fetch failure: falls back gracefully, does not restore plan — asserts no plan field in update, no throw
  • All 28 existing webhook subscription unit tests still pass (842 billing unit tests total)
  • Linter clean (ESLint: No issues found)

…succeeded

V8 audit C1: when markUnpaid downgrades a sub to plan=free and the user later
pays the overdue invoice, re-fetch the live Stripe subscription and write the
correct plan back alongside pastDueSince=null + status=active. Prevents paid
customers being permanently stuck on free plan if customer.subscription.updated
is dead-lettered. Falls back gracefully (warn log, no plan field) on Stripe
re-fetch error.
…t_succeeded

/critical-review medium: add explicit `if (!stripe) throw` so the fallback warn
log is meaningful ("Stripe not configured") rather than a cryptic TypeError.
/critical-review low: update JSDoc @description to document V8 C1 plan-restore
behavior and the non-fatal Stripe re-fetch fallback contract.
Copilot AI review requested due to automatic review settings May 7, 2026 10:09
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 7, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 58 minutes and 10 seconds before requesting another review.

To continue reviewing without waiting, purchase usage credits in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7e3263c3-c2f4-4cd3-965b-1a6f961ae171

📥 Commits

Reviewing files that changed from the base of the PR and between ddb0285 and 1f0250c.

📒 Files selected for processing (2)
  • modules/billing/services/billing.webhook.service.js
  • modules/billing/tests/billing.webhook.subscription.unit.tests.js
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/billing-v8-dunning-plan-recovery

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses a billing revenue-leak edge case where dunning can downgrade a subscription’s persisted plan to 'free', and a later invoice.payment_succeeded webhook would previously clear pastDueSince/activate the sub without restoring the correct paid plan if customer.subscription.updated is dead-lettered.

Changes:

  • Update handleInvoicePaymentSucceeded to re-fetch the live Stripe subscription, resolve the plan, and persist plan alongside clearing pastDueSince / restoring status: 'active'.
  • After a successful DB update, sync the organization plan when a plan was restored.
  • Add/adjust unit tests to cover plan restoration and graceful fallback when Stripe re-fetch fails.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
modules/billing/services/billing.webhook.service.js Restores plan during invoice.payment_succeeded handling via Stripe re-fetch and syncs org plan post-update.
modules/billing/tests/billing.webhook.subscription.unit.tests.js Adds test coverage for dunning recovery plan restoration and Stripe re-fetch failure fallback.

Comment on lines +579 to +580
resolvedPlan = resolvePlan(stripeSub);
fields.plan = resolvedPlan;
Comment on lines +573 to +579
let resolvedPlan = null;
if (isPastDue) {
try {
const stripe = getStripe();
if (!stripe) throw new Error('Stripe not configured');
const stripeSub = await stripe.subscriptions.retrieve(stripeSubscriptionId);
resolvedPlan = resolvePlan(stripeSub);
@codecov
Copy link
Copy Markdown

codecov Bot commented May 7, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.85%. Comparing base (ddb0285) to head (1f0250c).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3627      +/-   ##
==========================================
+ Coverage   88.82%   88.85%   +0.03%     
==========================================
  Files         134      134              
  Lines        4616     4630      +14     
  Branches     1423     1428       +5     
==========================================
+ Hits         4100     4114      +14     
  Misses        403      403              
  Partials      113      113              
Flag Coverage Δ
integration 59.13% <0.00%> (-0.18%) ⬇️
unit 62.95% <100.00%> (+0.11%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update ddb0285...1f0250c. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@PierreBrisorgueil PierreBrisorgueil merged commit cd3cde1 into master May 7, 2026
11 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the fix/billing-v8-dunning-plan-recovery branch May 7, 2026 12:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants