mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +00:00
Follow-up on the same change, from a high-effort code review and security review run over the diff. Access gate: - Scope both period-end guards to the period-end branch of hasBillingAccess instead of the top of the function. A cutoff is only ever cleared by a Stripe sync, so checking it first meant a stale one from a lapsed subscription outranked a freshly started cardless trial: the account burned its once-per-account trial and got nothing. buildBillingAccessWhereInput mirrors the same shape. - Refuse a period end carried by an INCOMPLETE or INCOMPLETE_EXPIRED subscription, the rejection isPaidTier already makes. The cutoff is deliberately left null while a trial is live, so a trial user who abandoned a checkout kept the failed subscription's period once the trial ran out. - Apply the cutoff in isPaidTier too, so it cannot say "paid" for a period where hasBillingAccess says access is over. That split left a locked-out account with no banner explaining it and able to create workspaces it could not then see. Both callers now select the field. Lifecycle: - Cancel through syncStripeCustomerSubscriptions rather than writing the single cancelled subscription, so a customer holding a second live subscription is not locked out of an account they are still being billed for. - Ignore invoice events with no subscription. A one-off invoice against a customer record left by an abandoned checkout was marking the account canceled and booking a churn event for a subscription that never existed. - Fall back to a window measured from now when a subscription behind on payment reports no period start, rather than falling through to "access ended", which locked out the customer that branch exists to keep in. - Let a paused subscription run to its period end; it was being ended at once. - Collapse BLOCKING_STRIPE_STATUSES into LIVE_STRIPE_STATUSES and include incomplete. The two sets were identical, which offered a Cancel button that always returned "No subscription to cancel" and left the Stripe-side checkout guard weaker than the mirror check it backs up. UI and ops: - cancelIsImmediate from the API, so the confirmation says what will actually happen to an incomplete subscription instead of promising the period end. - The access banner reads "ended on" once the date has passed. - The resync script selects the way the write path selects, over the customer's whole set. Filtering to live subscriptions first made the dry run disagree with the real run and skipped canceled and incomplete customers entirely, who are exactly the stale mirrors the script exists for. Three existing tests asserted the behaviour this fixes: that a canceled subscription keeps access to its reported period end, and that the cutoff is ignored while that period runs. Both rest on the premise that a future period end means a paid period, which is what is not true. They now assert the bound, alongside new cases for the retry window, the trial-versus-stale-cutoff ordering, and a never-paid period.
95 lines
4.5 KiB
TypeScript
95 lines
4.5 KiB
TypeScript
import { BillingSubscriptionStatus } from '@prisma/client';
|
|
import { auth } from '@/lib/auth';
|
|
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
|
import { getBillingOverview, getOpenInvoiceForCustomer } from '@/lib/billing';
|
|
import { isStripeFeatureEnabled } from '@/lib/feature-flags';
|
|
import { hasStripeRuntimeConfig, isStripeConfigured } from '@/lib/stripe';
|
|
import { logError } from '@/lib/logger';
|
|
|
|
export async function GET() {
|
|
try {
|
|
const session = await auth();
|
|
if (!session?.user?.id) {
|
|
return apiErrors.unauthorized();
|
|
}
|
|
|
|
const billing = await getBillingOverview(session.user.id);
|
|
const isEnabled = isStripeFeatureEnabled();
|
|
const isConfigured = hasStripeRuntimeConfig();
|
|
|
|
// Only looked up when the account actually owes something, so the common path does not
|
|
// pay for a Stripe round trip.
|
|
const needsPaymentFix =
|
|
billing.subscription.status === BillingSubscriptionStatus.PAST_DUE ||
|
|
billing.subscription.status === BillingSubscriptionStatus.UNPAID;
|
|
const openInvoice =
|
|
isStripeConfigured() && needsPaymentFix && billing.subscription.stripeCustomerId
|
|
? await getOpenInvoiceForCustomer(
|
|
billing.subscription.stripeCustomerId,
|
|
billing.subscription.stripeSubscriptionId
|
|
)
|
|
: null;
|
|
|
|
const response = successResponse({
|
|
isEnabled,
|
|
isConfigured,
|
|
status: !isEnabled ? 'disabled' : isStripeConfigured() ? 'ready' : 'misconfigured',
|
|
checkoutAvailable: isStripeConfigured() && !billing.subscription.hasRecoverableSubscription,
|
|
// A customer id alone is not enough: it is created on the first checkout attempt, so
|
|
// someone who abandoned checkout would be sent to an empty portal.
|
|
portalAvailable:
|
|
isStripeConfigured() &&
|
|
Boolean(billing.subscription.stripeCustomerId) &&
|
|
(billing.subscription.hasRecoverableSubscription ||
|
|
Boolean(billing.subscription.stripeSubscriptionId)),
|
|
// Gated on the status rather than on the mirrored subscription id: the id survives a
|
|
// cancellation until the deletion webhook arrives, and offering Cancel on an already
|
|
// canceled subscription just returns an error.
|
|
cancelAvailable:
|
|
isStripeConfigured() &&
|
|
billing.subscription.hasRecoverableSubscription &&
|
|
!billing.subscription.cancelAt &&
|
|
!billing.subscription.cancelAtPeriodEnd,
|
|
needsPaymentFix,
|
|
// Whether cancelling ends the subscription there and then rather than at the period
|
|
// end, which is what the confirmation copy has to say. Mirrors the branch the cancel
|
|
// route takes: nothing was paid for the open period, so there is nothing to run out.
|
|
cancelIsImmediate:
|
|
needsPaymentFix || billing.subscription.status === BillingSubscriptionStatus.INCOMPLETE,
|
|
openInvoice: openInvoice
|
|
? {
|
|
id: openInvoice.id,
|
|
hostedInvoiceUrl: openInvoice.hostedInvoiceUrl,
|
|
amountDue: openInvoice.amountDue,
|
|
currency: openInvoice.currency,
|
|
attemptCount: openInvoice.attemptCount,
|
|
nextPaymentAttempt: openInvoice.nextPaymentAttempt?.toISOString() ?? null,
|
|
}
|
|
: null,
|
|
subscription: {
|
|
status: billing.subscription.status,
|
|
label: billing.subscription.label,
|
|
hasActiveSubscription: billing.subscription.hasActiveSubscription,
|
|
hasRecoverableSubscription: billing.subscription.hasRecoverableSubscription,
|
|
hasActiveTrial: billing.subscription.hasActiveTrial,
|
|
hasBillingAccess: billing.subscription.hasBillingAccess,
|
|
isPaid: billing.subscription.isPaid,
|
|
priceId: billing.subscription.stripePriceId,
|
|
currentPeriodEnd: billing.subscription.currentPeriodEnd?.toISOString() ?? null,
|
|
cancelAtPeriodEnd: billing.subscription.cancelAtPeriodEnd ?? false,
|
|
cancelAt: billing.subscription.cancelAt?.toISOString() ?? null,
|
|
trialEndsAt: billing.subscription.trialEndsAt?.toISOString() ?? null,
|
|
billingAccessEndedAt: billing.subscription.billingAccessEndedAt?.toISOString() ?? null,
|
|
storageCleanupEligibleAt:
|
|
billing.subscription.storageCleanupEligibleAt?.toISOString() ?? null,
|
|
},
|
|
workspaceCreation: billing.workspaceCreation,
|
|
});
|
|
|
|
return withCacheControl(response, 'private, no-store');
|
|
} catch (error) {
|
|
logError('Error fetching billing overview:', error);
|
|
return apiErrors.internalError('Failed to fetch billing overview');
|
|
}
|
|
}
|