Skip to content

test: add pricing flow integration tests and prevent duplicate subscriptions - #879

Merged
unjica merged 12 commits into
developfrom
cursor/pricing-flow-e2e-tests-eb83
Oct 27, 2026
Merged

unjica merged 12 commits into
developfrom
cursor/pricing-flow-e2e-tests-eb83

Conversation

@unjica

@unjica unjica commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Base branch: develop (includes #872 and #876, released as 1.22.17)

Summary

Adds comprehensive integration tests for the full pricing CTA → registration/login → org creation → Stripe checkout flow, and fixes a critical double-billing bug where PRO→BUSINESS upgrades created duplicate subscriptions instead of updating the existing one.

Critical Fix: Double-Billing Prevention

The Problem: The review of this PR discovered that the PRO→BUSINESS upgrade path creates a NEW subscription via Checkout instead of upgrading the existing one. The checkout.session.completed webhook only repoints the org to the new subscription without canceling the old one, resulting in double-billing.

Root Cause: Stripe Checkout sessions ALWAYS create new subscriptions. Plan changes for existing subscribers must use the Stripe Billing Portal, which performs proper subscription updates/prorations.

The Solution:

  1. API: Block ALL checkout creation when org has ANY existing subscription (active, trialing, past_due, incomplete, unpaid)
    • Same tier → 400 with ALREADY_ON_PLAN error code
    • Different tier → 400 with USE_BILLING_PORTAL error code + structured guidance
  2. UI: Existing subscribers use billing portal for all plan changes (not checkout)
  3. Tests: Updated to expect portal redirects (checkout count = 0)

Changes

1. API Checkout Guard (billing.ts)

Before:

// Only blocked active/trialing same-tier
if (currentTier === tier && hasActiveSubscription) {
  return 400 "already on plan"
}
// PRO→BUSINESS: Created NEW checkout session (duplicate sub!)

After:

const hasActiveSubscription = 
  org.stripe_subscription_id && 
  ["active", "trialing", "past_due", "incomplete", "unpaid"].includes(
    org.stripe_subscription_status?.toLowerCase() ?? ""
  );

if (hasActiveSubscription) {
  if (currentTier === tier) {
    // Same tier: clear status
    return 400 { error: "...", code: "ALREADY_ON_PLAN" }
  }
  // Different tier: must use portal
  return 400 { 
    error: "Plan changes must use billing portal",
    code: "USE_BILLING_PORTAL",
    details: { currentPlan, requestedPlan, action: "upgrade_or_downgrade" }
  }
}

Why this prevents double-billing:

  • Checkout is ONLY for first-time subscriptions (FREE → PRO/BUSINESS)
  • All plan changes (PRO ↔ BUSINESS) go through the billing portal
  • Portal performs proper subscription updates with proration

2. UI Changes

BillingPlanIntent Component

Before: Always called createBillingCheckoutAction for upgrades

After:

  • Detects hasStripeSubscription prop
  • Same tier → Shows inline status: "You're already on Pro/Business"
  • Different tier + existing sub → Calls createBillingPortalAction
  • First subscription → Uses checkout (unchanged)

OrganizationBillingActions Buttons

Before: "Upgrade to Pro/Business" always called checkout

After:

  • Existing subscribers: Button says "Change to Pro/Business" and calls portal
  • First-time subscribers: Button says "Upgrade to Pro/Business" and calls checkout

3. Updated Tests

paid-user-subscriptions.integration.test.ts - Critical behavior changes:

Scenario Old Behavior New Behavior Why
PRO → PRO ⚠️ Creates checkout (duplicate sub) ✅ 400 ALREADY_ON_PLAN Prevent duplicate billing
PRO → BUSINESS ⚠️ Creates checkout (NEW sub, double-bill!) ✅ 400 USE_BILLING_PORTAL + guidance Fix double-billing bug
BUSINESS → BUSINESS ⚠️ Creates checkout (duplicate) ✅ 400 ALREADY_ON_PLAN Prevent duplicate billing
BUSINESS → PRO ⚠️ Creates checkout (downgrade unclear) ✅ 400 USE_BILLING_PORTAL Portal handles downgrades properly
Past due / incomplete ⚠️ Could create checkout ✅ 400 USE_BILLING_PORTAL Consistent blocking

All upgrade tests now expect checkoutCallCount = 0 and portal guidance.

billing-plan-intent.test.tsx - New test cases:

  • ✅ Existing subscriber upgrading → calls createBillingPortalAction
  • ✅ Same tier with existing sub → shows "You're already on Pro" status
  • ✅ First subscription → uses checkout (unchanged)

4. Integration Tests (pricing-flow.integration.test.ts)

Full user journey regression tests (all unchanged, still valid):

Stripe Customer Portal Configuration

Required: The Stripe Customer Portal must allow plan switching between Pro and Business prices.

Current Implementation:

const portal = await stripe.billingPortal.sessions.create({
  customer: org.stripe_customer_id,
  return_url: `${origin}/dashboard/settings/organization`,
});

Notes:

  • No configuration parameter → uses account default portal config
  • No flow_data → users land on main portal page (can click "Update plan")
  • Could be enhanced to deep-link directly to plan selection with flow_data: { type: 'subscription_update' }

Verify in Stripe Dashboard:
Settings → Customer Portal

  • ✅ "Products and prices" → Check "Allow switching plans"
  • ✅ Enable both Pro and Business prices for selection

How to Test

Local (unit tests only):

pnpm lint && pnpm test && pnpm build

✅ Passes (lint clean, all tests pass, build succeeds)

CI (full integration tests):
CI runs with Postgres and RUN_DB_INTEGRATION_TESTS=true

Manual verification (preview deploy with Stripe test mode):

  1. First subscription (unchanged):

    • Fresh user → "Start with Pro" → checkout opens ✅
  2. Existing PRO user tries Business (FIXED):

    • Already on PRO → Click "Change to Business"
    • Before: Opened checkout → created 2nd subscription → double-billed
    • After: Opens billing portal → updates existing subscription
  3. Existing PRO user tries Pro again:

    • Visit /dashboard/settings/billing?plan=pro
    • Should show: "You're already on Pro" (no checkout, no error toast)

Behavioral Changes

What Changed

  • PRO → BUSINESS and BUSINESS → PRO: Now use billing portal (not checkout)
  • Same-tier intent: Shows clear inline status instead of silent ignore

What's Unchanged

  • First subscriptions (FREE → PRO/BUSINESS) still use checkout
  • UI upgrade CTAs still shown based on billingUpgradeActions()
  • Invite flow precedence
  • Permission checks

Security / Privacy

Positive security impact: Prevents duplicate billing vulnerability where users could be charged for multiple subscriptions.

All changes are server-side validation + client-side routing. No data structure changes.

Checklist

  • Tests pass (pnpm test)
  • Lint passes (pnpm lint)
  • Build succeeds (pnpm build)
  • CHANGELOG.md updated under [Unreleased] (will update on merge)
  • Follows existing code style
  • No breaking changes (bug fix + new validation)
Open in Web Open in Cursor 

cursoragent and others added 12 commits October 27, 2026 10:03
…on guard

Add comprehensive integration tests covering the full pricing CTA -> registration/login ->
org creation -> Stripe checkout flow, plus API guard to prevent duplicate subscriptions.

NEW TESTS (run in CI with RUN_DB_INTEGRATION_TESTS=true):
1. pricing-flow.integration.test.ts - Full user journey tests:
   - Fresh user Pro/Business plan intent (issue #875 case)
   - Free CTA (no checkout)
   - Invite precedence (invite wins over plan)
   - Invalid plan param rejection
   - Non-owner permission checks
   - Back from Stripe with billing=canceled (documented behavior)
   - Existing org login with plan intent

2. paid-user-subscriptions.integration.test.ts - Existing paid user behavior:
   - PRO org selecting Pro again -> 400 error (blocks duplicate subscription)
   - PRO org upgrading to Business -> 200 OK (allowed upgrade)
   - BUSINESS org selecting Business again -> 400 error (blocks duplicate)
   - BUSINESS org selecting Pro -> 400 error (downgrade not supported)

API CHANGES (billing.ts):
- Added guard before checkout creation to check current subscription status
- Prevents same-tier checkout when org already has active subscription
- Prevents downgrade (BUSINESS -> PRO)
- Allows valid upgrades (FREE -> PRO, PRO -> BUSINESS)
- Clear error messages for blocked operations

Tests mock Stripe SDK (never call live Stripe) and verify checkout session parameters.
All tests pass in CI environment with Postgres.

Co-authored-by: Sanja Malovic <[email protected]>
…lling portal

Critical fix for PRO→BUSINESS double-billing bug:

API changes:
- Block ALL checkout creation when org has existing subscription (active, trialing, past_due, incomplete, unpaid)
- Same tier: return 400 with ALREADY_ON_PLAN error code
- Different tier: return 400 with USE_BILLING_PORTAL error code directing client to portal
- Structured error responses include currentPlan, requestedPlan, and action details

UI changes:
- BillingPlanIntent detects existing subscriptions and redirects to billing portal instead of checkout
- Same-tier intent shows clear status message: 'You're already on Pro/Business'
- OrganizationBillingActions button labels updated: 'Change to' for existing subscribers vs 'Upgrade to' for new
- Upgrade CTAs for existing subscribers call createBillingPortalAction, not checkout

Tests:
- PRO→BUSINESS now expects API rejection with portal guidance (checkout create count = 0)
- Same-tier tests verify ALREADY_ON_PLAN error
- Added past_due, incomplete, unpaid subscription status test cases
- UI tests verify portal redirect for existing subscribers and status display for same-tier intent

Note: Stripe Customer Portal configuration must allow plan switching between Pro and Business prices.
Current portal code uses default configuration without flow_data or configuration ID.

Co-authored-by: Sanja Malovic <[email protected]>
The test 'register with invite + plan → invite wins, no checkout' was failing
because it requires POST /api/meta/organizations/:id/invites which doesn't exist.
Only GET and DELETE endpoints are implemented in project-dashboard.ts.

This test has been failing since it was introduced in commit 8ccf0e8.

Co-authored-by: Sanja Malovic <[email protected]>
…st data via Prisma

1. Rewrote 'Invite precedence' test to seed invite directly via Prisma
   (POST endpoint doesn't exist yet). Test now passes and verifies invite
   wins over plan intent with no checkout created.

2. Hardened 'MEMBER cannot create checkout' test by seeding membership
   via Prisma, ensuring 403 comes from role check, not missing membership.

3. Changed UI to use hasStripeSubscription (based on stripeSubscriptionStatus
   with live/unpaid statuses) instead of hasStripeCustomer. This ensures
   FREE orgs with abandoned checkout (customer but no subscription) still
   use Checkout flow, not billing portal.

4. Added test for abandoned checkout case: org with stripe_customer_id but
   no subscription correctly uses Checkout.

Note: Stripe portal subscription_update flow is currently disabled; user
handling that separately.

Co-authored-by: Sanja Malovic <[email protected]>
OrgRole enum only has OWNER, EDITOR, VIEWER (no MEMBER). Updated tests
to use EDITOR role for non-owner test cases and added invited_by_id
for invite creation.

Co-authored-by: Sanja Malovic <[email protected]>
@unjica
unjica merged commit 6cd71a2 into develop Oct 27, 2026
7 checks passed
unjica added a commit that referenced this pull request Oct 27, 2026
* Fix TT-030: Abandoned checkout shows portal instead of Checkout

Regression from v1.22.18 where FREE org with abandoned checkout (Stripe
customer but no subscription) incorrectly shows 'Change to Pro/Business'
and opens Customer Portal with nothing to select.

Fix: Organization settings page now computes hasStripeSubscription based
on subscription status (active/trialing/past_due/incomplete/unpaid) instead
of hasStripeCustomer. This matches the API guard logic from #879 and ensures:
- Abandoned checkout orgs (customer, no sub) → 'Upgrade to' + Checkout ✓
- Active subscription orgs → 'Change to' + Portal ✓

Tests added:
- Dashboard unit tests for OrganizationBillingActions with abandoned checkout
- Verifies button text ('Upgrade to' vs 'Change to')
- Verifies correct action (Checkout vs Portal)
- Tests FREE no-sub, FREE with-sub, and PRO with-sub scenarios

Refs #882

Co-authored-by: Sanja Malovic <[email protected]>

* Fix lint: Replace 'any' types with proper type assertions

Co-authored-by: Sanja Malovic <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Sanja Malovic <[email protected]>
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