mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +00:00
feat(billing): defer the cardless trial for invited collaborators
An account that signs up through an invitation works on the inviter's billing, so handing it a trial at signup spent its only trial before it owned anything. The trial is now held back for collaborators and claimed only explicitly: a Start Free Trial button on the new-workspace and billing screens calls the new POST /api/billing/trial endpoint, which grants the once-per-account trial atomically. Nothing starts the clock as a side effect, and pure collaborators no longer see a trial-ending banner about work that is not theirs.
This commit is contained in:
@@ -67,6 +67,7 @@ interface BillingOverview {
|
||||
};
|
||||
workspaceCreation: {
|
||||
canCreateWorkspace: boolean;
|
||||
canStartTrial?: boolean;
|
||||
reason: string | null;
|
||||
ownedWorkspaceCount: number;
|
||||
invitedWorkspaceCount: number;
|
||||
@@ -147,7 +148,7 @@ export default function SettingsPage({ billingOnly = false }: { billingOnly?: bo
|
||||
const [testing, setTesting] = useState<string | null>(null);
|
||||
const [billing, setBilling] = useState<BillingOverview | null>(null);
|
||||
const [billingLoading, setBillingLoading] = useState(true);
|
||||
const [billingAction, setBillingAction] = useState<'checkout' | 'portal' | null>(null);
|
||||
const [billingAction, setBillingAction] = useState<'checkout' | 'portal' | 'trial' | null>(null);
|
||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||
const [storageLoading, setStorageLoading] = useState(true);
|
||||
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
|
||||
@@ -278,6 +279,29 @@ export default function SettingsPage({ billingOnly = false }: { billingOnly?: bo
|
||||
[showMessage]
|
||||
);
|
||||
|
||||
const handleStartTrial = useCallback(async () => {
|
||||
setBillingAction('trial');
|
||||
try {
|
||||
const res = await fetch('/api/billing/trial', { method: 'POST' });
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
showMessage('error', data.error || 'Failed to start your free trial');
|
||||
return;
|
||||
}
|
||||
|
||||
const billingRes = await fetch('/api/billing');
|
||||
if (billingRes.ok) {
|
||||
setBilling((await billingRes.json()).data);
|
||||
}
|
||||
showMessage('success', 'Your free trial has started');
|
||||
} catch {
|
||||
showMessage('error', 'Failed to start your free trial');
|
||||
} finally {
|
||||
setBillingAction(null);
|
||||
}
|
||||
}, [showMessage]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto py-8 px-4 space-y-6">
|
||||
@@ -475,19 +499,34 @@ export default function SettingsPage({ billingOnly = false }: { billingOnly?: bo
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={() => handleBillingRedirect('/api/billing/checkout')}
|
||||
disabled={!billing.checkoutAvailable || billingAction !== null}
|
||||
>
|
||||
{billingAction === 'checkout' ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Redirecting...
|
||||
</>
|
||||
) : (
|
||||
'Upgrade with Stripe'
|
||||
)}
|
||||
</Button>
|
||||
<>
|
||||
{billing.workspaceCreation.canStartTrial ? (
|
||||
<Button onClick={handleStartTrial} disabled={billingAction !== null}>
|
||||
{billingAction === 'trial' ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Starting Trial...
|
||||
</>
|
||||
) : (
|
||||
'Start Free Trial'
|
||||
)}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
variant={billing.workspaceCreation.canStartTrial ? 'outline' : 'default'}
|
||||
onClick={() => handleBillingRedirect('/api/billing/checkout')}
|
||||
disabled={!billing.checkoutAvailable || billingAction !== null}
|
||||
>
|
||||
{billingAction === 'checkout' ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Redirecting...
|
||||
</>
|
||||
) : (
|
||||
'Upgrade with Stripe'
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -15,12 +15,35 @@ export default function NewWorkspacePage({
|
||||
}: {
|
||||
workspaceCreation: {
|
||||
canCreateWorkspace: boolean;
|
||||
canStartTrial?: boolean;
|
||||
reason: string | null;
|
||||
};
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isStartingTrial, setIsStartingTrial] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleStartTrial = async () => {
|
||||
setIsStartingTrial(true);
|
||||
setError('');
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/billing/trial', { method: 'POST' });
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
setError(data.error || 'Failed to start your free trial');
|
||||
return;
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
} catch {
|
||||
setError('Something went wrong. Please try again.');
|
||||
} finally {
|
||||
setIsStartingTrial(false);
|
||||
}
|
||||
};
|
||||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
description: '',
|
||||
@@ -76,7 +99,11 @@ export default function NewWorkspacePage({
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-2xl">
|
||||
{workspaceCreation.canCreateWorkspace ? 'Create New Workspace' : 'Upgrade Required'}
|
||||
{workspaceCreation.canCreateWorkspace
|
||||
? 'Create New Workspace'
|
||||
: workspaceCreation.canStartTrial
|
||||
? 'Start Your Free Trial'
|
||||
: 'Upgrade Required'}
|
||||
</CardTitle>
|
||||
<CardDescription className="text-base">
|
||||
{workspaceCreation.canCreateWorkspace
|
||||
@@ -139,9 +166,27 @@ export default function NewWorkspacePage({
|
||||
You can still create and manage projects inside workspaces where you are already a
|
||||
member.
|
||||
</p>
|
||||
<Button asChild className="w-full">
|
||||
<Link href="/settings">Open Billing Settings</Link>
|
||||
</Button>
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{workspaceCreation.canStartTrial ? (
|
||||
<Button className="w-full" onClick={handleStartTrial} disabled={isStartingTrial}>
|
||||
{isStartingTrial ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Starting Trial...
|
||||
</>
|
||||
) : (
|
||||
'Start Free Trial'
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<Button asChild className="w-full">
|
||||
<Link href="/settings">Open Billing Settings</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
isValidEmailAddress,
|
||||
normalizeEmail,
|
||||
} from '@/lib/email-validation';
|
||||
import { startCardlessTrial } from '@/lib/billing';
|
||||
import { startCardlessTrialOnSignup } from '@/lib/billing';
|
||||
import { recordSignupCompleted } from '@/lib/analytics/signup';
|
||||
import { readRequestVisitor } from '@/lib/analytics/visitor';
|
||||
|
||||
@@ -166,7 +166,7 @@ export async function POST(request: NextRequest) {
|
||||
// just lock the user out of an instance that has billing switched on.
|
||||
if (!emailVerificationRequired) {
|
||||
warnIfTrialsSkipVerification();
|
||||
await startCardlessTrial(user.id);
|
||||
await startCardlessTrialOnSignup(user.id);
|
||||
}
|
||||
|
||||
// Send verification email if SMTP is configured
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse } from '@/lib/api-response';
|
||||
import { startCardlessTrial } from '@/lib/billing';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { isStripeFeatureEnabled } from '@/lib/feature-flags';
|
||||
import { isTrustedSameOriginRequest } from '@/lib/request-origin';
|
||||
import { logError } from '@/lib/logger';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
/**
|
||||
* The explicit claim of a deferred cardless trial.
|
||||
*
|
||||
* An invited collaborator has their trial held back at signup; nothing else in
|
||||
* the product is allowed to start it as a side effect, because the clock spends
|
||||
* the account's only trial. This endpoint is the one place the user says "start
|
||||
* it now", from the workspace-creation and billing screens.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
if (!isTrustedSameOriginRequest(request)) {
|
||||
return apiErrors.forbidden('Invalid request origin');
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
if (!isStripeFeatureEnabled()) {
|
||||
return apiErrors.badRequest('Stripe billing is disabled by this host');
|
||||
}
|
||||
|
||||
const started = await startCardlessTrial(session.user.id);
|
||||
if (!started) {
|
||||
return apiErrors.conflict('Your free trial has already been used');
|
||||
}
|
||||
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { trialEndsAt: true },
|
||||
});
|
||||
|
||||
return successResponse({ trialEndsAt: user?.trialEndsAt ?? null });
|
||||
} catch (error) {
|
||||
logError('billing.trial.start', error);
|
||||
return apiErrors.internalError();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user