mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
feat(billing): integrate Stripe for subscription management and billing access
- Added billing-related fields to the User model in the database. - Implemented functions for managing billing access, including trial periods and subscription statuses. - Created new billing utility functions for Stripe integration. - Updated onboarding page to include billing overview and workspace creation eligibility. - Enhanced route access checks to require billing access for certain actions. - Implemented cleanup scripts for expired billing workspaces and associated media. - Updated header component to conditionally show app navigation based on billing access. - Added new migrations for billing-related database changes.
This commit is contained in:
@@ -2,7 +2,9 @@ import { auth } from '@/lib/auth';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { db } from '@/lib/db';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { hasCollaboratorBillingBackedAccess, requireBillingAccessOrRedirect } from '@/lib/route-access';
|
||||
import { DashboardClient } from './dashboard-client';
|
||||
import { buildBillingAccessWhereInput } from '@/lib/billing';
|
||||
|
||||
export default async function DashboardPage({
|
||||
searchParams,
|
||||
@@ -14,6 +16,11 @@ export default async function DashboardPage({
|
||||
redirect('/login');
|
||||
}
|
||||
|
||||
const hasCollaboratorAccess = await hasCollaboratorBillingBackedAccess(session.user.id);
|
||||
if (!hasCollaboratorAccess) {
|
||||
await requireBillingAccessOrRedirect({ userId: session.user.id });
|
||||
}
|
||||
|
||||
const userOnboarding = await db.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { onboardingCompletedAt: true },
|
||||
@@ -37,6 +44,7 @@ export default async function DashboardPage({
|
||||
{ members: { some: { userId: session.user.id } } },
|
||||
{
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
OR: [
|
||||
{ ownerId: session.user.id },
|
||||
{ members: { some: { userId: session.user.id } } },
|
||||
@@ -44,6 +52,9 @@ export default async function DashboardPage({
|
||||
},
|
||||
},
|
||||
],
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
},
|
||||
};
|
||||
|
||||
// Build unique workspace list for filter (Needs an unbounded list of accessible workspaces)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Header } from '@/components/layout';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { hasAppNavigationAccess } from '@/lib/route-access';
|
||||
|
||||
export default async function DashboardLayout({
|
||||
children,
|
||||
@@ -7,10 +8,13 @@ export default async function DashboardLayout({
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const session = await auth();
|
||||
const showAppNavigation = session?.user?.id
|
||||
? await hasAppNavigationAccess(session.user.id)
|
||||
: false;
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen flex-col">
|
||||
<Header user={session?.user ?? null} />
|
||||
<Header user={session?.user ?? null} showAppNavigation={showAppNavigation} />
|
||||
<main className="flex-1">{children}</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
ArrowLeft,
|
||||
} from 'lucide-react';
|
||||
import { GuestGate } from '@/components/guest-gate';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkProjectAccess } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { ProjectContentClient } from './project-content-client';
|
||||
|
||||
@@ -65,6 +65,8 @@ export default async function ProjectPage({ params, searchParams }: ProjectPageP
|
||||
notFound();
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session?.user?.id);
|
||||
|
||||
// Check access
|
||||
const isOwner = session?.user?.id === project.ownerId;
|
||||
const isMember = project.members.length > 0;
|
||||
@@ -92,7 +94,7 @@ export default async function ProjectPage({ params, searchParams }: ProjectPageP
|
||||
}
|
||||
}
|
||||
|
||||
if (!isOwner && !isMember && !isPublic && !isWorkspaceMember) {
|
||||
if (!access.hasAccess || (!isOwner && !isMember && !isPublic && !isWorkspaceMember)) {
|
||||
if (!session?.user?.id) {
|
||||
redirect('/login');
|
||||
}
|
||||
@@ -139,7 +141,7 @@ export default async function ProjectPage({ params, searchParams }: ProjectPageP
|
||||
};
|
||||
});
|
||||
|
||||
const canEdit = isOwner || project.members[0]?.role === 'ADMIN' || workspaceRole === 'OWNER' || workspaceRole === 'ADMIN';
|
||||
const canEdit = access.canEdit && (isOwner || project.members[0]?.role === 'ADMIN' || workspaceRole === 'OWNER' || workspaceRole === 'ADMIN');
|
||||
const isAuthenticated = !!session?.user?.id;
|
||||
|
||||
const projectData = {
|
||||
|
||||
@@ -1,7 +1,21 @@
|
||||
import { requireAuthOrRedirect } from '@/lib/route-access';
|
||||
import { hasCollaboratorBillingBackedAccess, requireAuthOrRedirect } from '@/lib/route-access';
|
||||
import { getBillingOverview } from '@/lib/billing';
|
||||
import SettingsPageClient from './settings-page-client';
|
||||
|
||||
export default async function SettingsPage() {
|
||||
await requireAuthOrRedirect();
|
||||
return <SettingsPageClient />;
|
||||
const session = await requireAuthOrRedirect();
|
||||
if (!session?.user?.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [billing, hasCollaboratorAccess] = await Promise.all([
|
||||
getBillingOverview(session.user.id),
|
||||
hasCollaboratorBillingBackedAccess(session.user.id),
|
||||
]);
|
||||
|
||||
return (
|
||||
<SettingsPageClient
|
||||
billingOnly={!billing.subscription.hasBillingAccess && !hasCollaboratorAccess}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Bell, Send, Mail, CheckCircle2, AlertCircle, Loader2, Globe } from 'lucide-react';
|
||||
import { Bell, Send, Mail, CheckCircle2, AlertCircle, Loader2, Globe, CreditCard } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -32,6 +32,32 @@ interface NotificationSettings {
|
||||
timezone: string;
|
||||
}
|
||||
|
||||
interface BillingOverview {
|
||||
isConfigured: boolean;
|
||||
checkoutAvailable: boolean;
|
||||
portalAvailable: boolean;
|
||||
subscription: {
|
||||
status: string;
|
||||
label: string;
|
||||
hasActiveSubscription: boolean;
|
||||
hasActiveTrial: boolean;
|
||||
hasBillingAccess: boolean;
|
||||
priceId: string | null;
|
||||
currentPeriodEnd: string | null;
|
||||
cancelAtPeriodEnd: boolean;
|
||||
cancelAt: string | null;
|
||||
trialEndsAt: string | null;
|
||||
billingAccessEndedAt: string | null;
|
||||
storageCleanupEligibleAt: string | null;
|
||||
};
|
||||
workspaceCreation: {
|
||||
canCreateWorkspace: boolean;
|
||||
reason: string | null;
|
||||
ownedWorkspaceCount: number;
|
||||
invitedWorkspaceCount: number;
|
||||
};
|
||||
}
|
||||
|
||||
function ToggleButton({
|
||||
enabled,
|
||||
onToggle,
|
||||
@@ -77,7 +103,7 @@ function ToggleButton({
|
||||
);
|
||||
}
|
||||
|
||||
export default function SettingsPage() {
|
||||
export default function SettingsPage({ billingOnly = false }: { billingOnly?: boolean }) {
|
||||
const [settings, setSettings] = useState<NotificationSettings>({
|
||||
telegramChatId: null,
|
||||
telegramEnabled: false,
|
||||
@@ -92,24 +118,41 @@ export default function SettingsPage() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
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 [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
|
||||
|
||||
// Form state for Telegram chat ID (separate from saved settings for editing)
|
||||
const [telegramChatId, setTelegramChatId] = useState('');
|
||||
|
||||
const hasScheduledCancellation = Boolean(
|
||||
billing?.subscription.cancelAtPeriodEnd || billing?.subscription.cancelAt
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchSettings() {
|
||||
try {
|
||||
const res = await fetch('/api/settings/notifications');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const [settingsRes, billingRes] = await Promise.all([
|
||||
fetch('/api/settings/notifications'),
|
||||
fetch('/api/billing'),
|
||||
]);
|
||||
|
||||
if (settingsRes.ok) {
|
||||
const data = await settingsRes.json();
|
||||
setSettings(data.data);
|
||||
setTelegramChatId(data.data.telegramChatId || '');
|
||||
}
|
||||
|
||||
if (billingRes.ok) {
|
||||
const data = await billingRes.json();
|
||||
setBilling(data.data);
|
||||
}
|
||||
} catch {
|
||||
console.error('Failed to fetch notification settings');
|
||||
console.error('Failed to fetch settings');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setBillingLoading(false);
|
||||
}
|
||||
}
|
||||
fetchSettings();
|
||||
@@ -174,6 +217,31 @@ export default function SettingsPage() {
|
||||
[telegramChatId, showMessage]
|
||||
);
|
||||
|
||||
const handleBillingRedirect = useCallback(
|
||||
async (endpoint: '/api/billing/checkout' | '/api/billing/portal') => {
|
||||
setBillingAction(endpoint.endsWith('checkout') ? 'checkout' : 'portal');
|
||||
try {
|
||||
const res = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
showMessage('error', data.error || 'Failed to open billing flow');
|
||||
return;
|
||||
}
|
||||
|
||||
window.location.href = data.data.url;
|
||||
} catch {
|
||||
showMessage('error', 'Failed to open billing flow');
|
||||
} finally {
|
||||
setBillingAction(null);
|
||||
}
|
||||
},
|
||||
[showMessage]
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto py-8 px-4 space-y-6">
|
||||
@@ -212,7 +280,7 @@ export default function SettingsPage() {
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Settings</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Manage your notification preferences
|
||||
{billingOnly ? 'Manage your billing access' : 'Manage your notification preferences'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -235,6 +303,130 @@ export default function SettingsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card className="mb-6">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<CreditCard className="h-5 w-5" />
|
||||
Billing
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Manage your paid plan and workspace creation access
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{billingLoading || !billing ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-4 w-40" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-10 w-44 rounded-md" />
|
||||
</div>
|
||||
) : !billing.isConfigured ? (
|
||||
<div className="rounded-md border border-amber-500/30 bg-amber-500/10 p-4 text-sm text-amber-700 dark:text-amber-400">
|
||||
Stripe is not configured yet. Add your Stripe environment variables before using billing.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium">Current plan</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{billing.subscription.hasActiveSubscription
|
||||
? hasScheduledCancellation
|
||||
? billing.subscription.hasActiveTrial
|
||||
? 'Trial canceled. Access remains active until the trial ends.'
|
||||
: 'Subscription canceled. Access remains active until the end of the current billing period.'
|
||||
: 'Paid account with workspace creation unlocked.'
|
||||
: billing.subscription.hasActiveTrial
|
||||
? 'Trial access is active.'
|
||||
: 'Billing access has ended.'}
|
||||
</p>
|
||||
</div>
|
||||
<Badge
|
||||
variant={billing.subscription.hasActiveSubscription ? 'default' : 'secondary'}
|
||||
>
|
||||
{billing.subscription.label}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{billing.subscription.hasActiveTrial
|
||||
&& billing.subscription.trialEndsAt
|
||||
&& hasScheduledCancellation ? (
|
||||
<p
|
||||
className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm font-medium text-destructive"
|
||||
>
|
||||
Access ends on {' '}
|
||||
{new Date(billing.subscription.trialEndsAt).toLocaleDateString()}.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{billing.subscription.currentPeriodEnd ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{hasScheduledCancellation ? 'Your subscription ends on ' : 'Current billing period ends on '}
|
||||
{new Date(billing.subscription.currentPeriodEnd).toLocaleDateString()}.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{hasScheduledCancellation && billing.subscription.cancelAt ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Cancellation was scheduled on {new Date(billing.subscription.cancelAt).toLocaleDateString()}.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!billing.subscription.hasBillingAccess
|
||||
&& billing.subscription.billingAccessEndedAt
|
||||
&& billing.subscription.storageCleanupEligibleAt ? (
|
||||
<p className="text-sm text-amber-700 dark:text-amber-400">
|
||||
Stored media cleanup is scheduled after {new Date(billing.subscription.storageCleanupEligibleAt).toLocaleDateString()} unless billing is restored first.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="rounded-lg border bg-muted/30 p-4 space-y-2">
|
||||
<p className="text-sm font-medium">Workspace creation</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{billing.workspaceCreation.canCreateWorkspace
|
||||
? 'This account can create workspaces.'
|
||||
: billing.workspaceCreation.reason || 'Upgrade to create another workspace.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
{billing.subscription.hasActiveSubscription && billing.portalAvailable ? (
|
||||
<Button
|
||||
onClick={() => handleBillingRedirect('/api/billing/portal')}
|
||||
disabled={billingAction !== null}
|
||||
>
|
||||
{billingAction === 'portal' ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Opening Portal...
|
||||
</>
|
||||
) : (
|
||||
'Manage Subscription'
|
||||
)}
|
||||
</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>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{!billingOnly && (
|
||||
<>
|
||||
{/* Event Subscriptions */}
|
||||
<Card className="mb-6">
|
||||
<CardHeader>
|
||||
@@ -246,7 +438,7 @@ export default function SettingsPage() {
|
||||
Choose which events trigger notifications
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<CardContent className="space-y-4">
|
||||
<ToggleButton
|
||||
enabled={settings.onNewVideo}
|
||||
onToggle={() =>
|
||||
@@ -518,6 +710,8 @@ export default function SettingsPage() {
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { VideoDragDropUploader } from '@/components/video-drag-drop-uploader';
|
||||
|
||||
@@ -94,8 +94,9 @@ export default async function WorkspacePage({ params, searchParams }: WorkspaceP
|
||||
const membership = workspace.members[0];
|
||||
const isMember = !!membership;
|
||||
const isAdmin = isOwner || membership?.role === 'ADMIN';
|
||||
const access = await checkWorkspaceAccess({ id: workspace.id, ownerId: workspace.ownerId }, session.user.id);
|
||||
|
||||
if (!isOwner && !isMember) {
|
||||
if (!access.hasAccess || (!isOwner && !isMember)) {
|
||||
redirect('/dashboard');
|
||||
}
|
||||
|
||||
|
||||
@@ -8,10 +8,10 @@ interface WorkspaceSettingsPageProps {
|
||||
export default async function WorkspaceSettingsPage({ params }: WorkspaceSettingsPageProps) {
|
||||
const { workspaceId } = await params;
|
||||
|
||||
await requireWorkspaceAccessOrRedirect({
|
||||
const { access } = await requireWorkspaceAccessOrRedirect({
|
||||
workspaceId,
|
||||
intent: 'manage',
|
||||
});
|
||||
|
||||
return <WorkspaceSettingsPageClient workspaceId={workspaceId} />;
|
||||
return <WorkspaceSettingsPageClient workspaceId={workspaceId} canDelete={access.canDelete} />;
|
||||
}
|
||||
|
||||
+68
-59
@@ -30,7 +30,13 @@ interface WorkspaceData {
|
||||
ownerId: string;
|
||||
}
|
||||
|
||||
export default function WorkspaceSettingsPageClient({ workspaceId }: { workspaceId: string }) {
|
||||
export default function WorkspaceSettingsPageClient({
|
||||
workspaceId,
|
||||
canDelete,
|
||||
}: {
|
||||
workspaceId: string;
|
||||
canDelete: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
|
||||
const [workspace, setWorkspace] = useState<WorkspaceData | null>(null);
|
||||
@@ -202,65 +208,68 @@ export default function WorkspaceSettingsPageClient({ workspaceId }: { workspace
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Separator className="my-8" />
|
||||
{canDelete ? (
|
||||
<>
|
||||
<Separator className="my-8" />
|
||||
|
||||
{/* Danger Zone */}
|
||||
<Card className="border-destructive/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-destructive">Danger Zone</CardTitle>
|
||||
<CardDescription>
|
||||
Irreversible actions. Proceed with caution.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="destructive">
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete Workspace
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete "{workspace.name}"?</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-4">
|
||||
<p>
|
||||
This will permanently delete this workspace and everything inside it
|
||||
(projects, videos, comments, images, and voice notes). This action cannot be undone.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="delete-workspace-confirm">
|
||||
Type <strong className="text-foreground">{workspace.name}</strong> to confirm
|
||||
</Label>
|
||||
<Input
|
||||
id="delete-workspace-confirm"
|
||||
value={deleteConfirmation}
|
||||
onChange={(e) => setDeleteConfirmation(e.target.value)}
|
||||
placeholder="Workspace name"
|
||||
className="h-11"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={() => setDeleteConfirmation('')}>
|
||||
Cancel
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
disabled={deleteConfirmation !== workspace.name || isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Delete Workspace
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="border-destructive/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-destructive">Danger Zone</CardTitle>
|
||||
<CardDescription>
|
||||
Irreversible actions. Proceed with caution.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="destructive">
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete Workspace
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete "{workspace.name}"?</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-4">
|
||||
<p>
|
||||
This will permanently delete this workspace and everything inside it
|
||||
(projects, videos, comments, images, and voice notes). This action cannot be undone.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="delete-workspace-confirm">
|
||||
Type <strong className="text-foreground">{workspace.name}</strong> to confirm
|
||||
</Label>
|
||||
<Input
|
||||
id="delete-workspace-confirm"
|
||||
value={deleteConfirmation}
|
||||
onChange={(e) => setDeleteConfirmation(e.target.value)}
|
||||
placeholder="Workspace name"
|
||||
className="h-11"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={() => setDeleteConfirmation('')}>
|
||||
Cancel
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
disabled={deleteConfirmation !== workspace.name || isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Delete Workspace
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,14 +3,21 @@
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { ArrowLeft, Loader2, Building2 } from 'lucide-react';
|
||||
import { ArrowLeft, Loader2, Building2, Lock } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
|
||||
export default function NewWorkspacePage() {
|
||||
export default function NewWorkspacePage({
|
||||
workspaceCreation,
|
||||
}: {
|
||||
workspaceCreation: {
|
||||
canCreateWorkspace: boolean;
|
||||
reason: string | null;
|
||||
};
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
@@ -62,65 +69,84 @@ export default function NewWorkspacePage() {
|
||||
<Card className="border-border/50 shadow-lg">
|
||||
<CardHeader className="text-center pb-2">
|
||||
<div className="mx-auto w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center mb-4">
|
||||
<Building2 className="h-7 w-7 text-primary" />
|
||||
{workspaceCreation.canCreateWorkspace ? (
|
||||
<Building2 className="h-7 w-7 text-primary" />
|
||||
) : (
|
||||
<Lock className="h-7 w-7 text-primary" />
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Create New Workspace</CardTitle>
|
||||
<CardTitle className="text-2xl">
|
||||
{workspaceCreation.canCreateWorkspace ? 'Create New Workspace' : 'Upgrade Required'}
|
||||
</CardTitle>
|
||||
<CardDescription className="text-base">
|
||||
Set up a workspace to organize projects and invite your team
|
||||
{workspaceCreation.canCreateWorkspace
|
||||
? 'Set up a workspace to organize projects and invite your team'
|
||||
: workspaceCreation.reason || 'Upgrade your account to create another workspace.'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-6">
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name" className="text-sm font-medium">
|
||||
Workspace Name
|
||||
</Label>
|
||||
<Input
|
||||
id="name"
|
||||
placeholder="e.g., My Studio"
|
||||
value={formData.name}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, name: e.target.value })
|
||||
}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description" className="text-sm font-medium">
|
||||
Description{' '}
|
||||
<span className="text-muted-foreground font-normal">(optional)</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
placeholder="What is this workspace for?"
|
||||
value={formData.description}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, description: e.target.value })
|
||||
}
|
||||
rows={3}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
{workspaceCreation.canCreateWorkspace ? (
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name" className="text-sm font-medium">
|
||||
Workspace Name
|
||||
</Label>
|
||||
<Input
|
||||
id="name"
|
||||
placeholder="e.g., My Studio"
|
||||
value={formData.name}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, name: e.target.value })
|
||||
}
|
||||
required
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
'Create Workspace'
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description" className="text-sm font-medium">
|
||||
Description{' '}
|
||||
<span className="text-muted-foreground font-normal">(optional)</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
placeholder="What is this workspace for?"
|
||||
value={formData.description}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, description: e.target.value })
|
||||
}
|
||||
rows={3}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
'Create Workspace'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
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>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { requireAuthOrRedirect } from '@/lib/route-access';
|
||||
import { getBillingOverview } from '@/lib/billing';
|
||||
import NewWorkspacePageClient from './new-workspace-page-client';
|
||||
|
||||
export default async function NewWorkspacePage() {
|
||||
await requireAuthOrRedirect();
|
||||
return <NewWorkspacePageClient />;
|
||||
const session = await requireAuthOrRedirect();
|
||||
if (!session?.user?.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const billing = await getBillingOverview(session.user.id);
|
||||
|
||||
return <NewWorkspacePageClient workspaceCreation={billing.workspaceCreation} />;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { auth } from '@/lib/auth';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { db } from '@/lib/db';
|
||||
import { buildBillingAccessWhereInput, getBillingOverview } from '@/lib/billing';
|
||||
import { hasCollaboratorBillingBackedAccess, requireBillingAccessOrRedirect } from '@/lib/route-access';
|
||||
import { WorkspacesClient } from './workspaces-client';
|
||||
|
||||
export default async function WorkspacesPage({
|
||||
@@ -13,19 +15,24 @@ export default async function WorkspacesPage({
|
||||
redirect('/login');
|
||||
}
|
||||
|
||||
const hasCollaboratorAccess = await hasCollaboratorBillingBackedAccess(session.user.id);
|
||||
if (!hasCollaboratorAccess) {
|
||||
await requireBillingAccessOrRedirect({ userId: session.user.id });
|
||||
}
|
||||
|
||||
const resolvedSearchParams = await searchParams;
|
||||
const page = Number(resolvedSearchParams?.page) || 1;
|
||||
const pageSize = 20;
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const [workspaces, totalWorkspaces] = await Promise.all([
|
||||
const [workspaces, totalWorkspaces, billing] = await Promise.all([
|
||||
db.workspace.findMany({
|
||||
skip,
|
||||
take: pageSize,
|
||||
where: {
|
||||
OR: [
|
||||
{ ownerId: session.user.id },
|
||||
{ members: { some: { userId: session.user.id } } },
|
||||
{ ownerId: session.user.id, owner: buildBillingAccessWhereInput() },
|
||||
{ members: { some: { userId: session.user.id } }, owner: buildBillingAccessWhereInput() },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
@@ -42,11 +49,12 @@ export default async function WorkspacesPage({
|
||||
db.workspace.count({
|
||||
where: {
|
||||
OR: [
|
||||
{ ownerId: session.user.id },
|
||||
{ members: { some: { userId: session.user.id } } },
|
||||
{ ownerId: session.user.id, owner: buildBillingAccessWhereInput() },
|
||||
{ members: { some: { userId: session.user.id } }, owner: buildBillingAccessWhereInput() },
|
||||
],
|
||||
}
|
||||
})
|
||||
}),
|
||||
getBillingOverview(session.user.id),
|
||||
]);
|
||||
|
||||
const totalPages = Math.ceil(totalWorkspaces / pageSize);
|
||||
@@ -60,6 +68,11 @@ export default async function WorkspacesPage({
|
||||
}));
|
||||
|
||||
return (
|
||||
<WorkspacesClient workspaces={serializedWorkspaces} totalPages={totalPages} currentPage={page} />
|
||||
<WorkspacesClient
|
||||
workspaces={serializedWorkspaces}
|
||||
totalPages={totalPages}
|
||||
currentPage={page}
|
||||
workspaceCreation={billing.workspaceCreation}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,9 +35,18 @@ interface WorkspacesClientProps {
|
||||
workspaces: SerializedWorkspace[];
|
||||
totalPages: number;
|
||||
currentPage: number;
|
||||
workspaceCreation: {
|
||||
canCreateWorkspace: boolean;
|
||||
reason: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export function WorkspacesClient({ workspaces, totalPages, currentPage }: WorkspacesClientProps) {
|
||||
export function WorkspacesClient({
|
||||
workspaces,
|
||||
totalPages,
|
||||
currentPage,
|
||||
workspaceCreation,
|
||||
}: WorkspacesClientProps) {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
@@ -49,13 +58,26 @@ export function WorkspacesClient({ workspaces, totalPages, currentPage }: Worksp
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Manage your workspaces and their projects
|
||||
</p>
|
||||
{!workspaceCreation.canCreateWorkspace && workspaceCreation.reason ? (
|
||||
<p className="text-sm text-amber-700 dark:text-amber-400 mt-2">
|
||||
{workspaceCreation.reason}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Button asChild className="w-full sm:w-auto">
|
||||
<Link href="/workspaces/new">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Workspace
|
||||
</Link>
|
||||
</Button>
|
||||
{workspaceCreation.canCreateWorkspace ? (
|
||||
<Button asChild className="w-full sm:w-auto">
|
||||
<Link href="/workspaces/new">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Workspace
|
||||
</Link>
|
||||
</Button>
|
||||
) : (
|
||||
<Button asChild className="w-full sm:w-auto">
|
||||
<Link href="/settings">
|
||||
Upgrade to Create Workspace
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Workspaces Grid */}
|
||||
@@ -101,12 +123,18 @@ export function WorkspacesClient({ workspaces, totalPages, currentPage }: Worksp
|
||||
<p className="text-muted-foreground text-center mb-4">
|
||||
Create a workspace to organize your projects and invite team members
|
||||
</p>
|
||||
<Button asChild>
|
||||
<Link href="/workspaces/new">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Create Workspace
|
||||
</Link>
|
||||
</Button>
|
||||
{workspaceCreation.canCreateWorkspace ? (
|
||||
<Button asChild>
|
||||
<Link href="/workspaces/new">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Create Workspace
|
||||
</Link>
|
||||
</Button>
|
||||
) : (
|
||||
<Button asChild>
|
||||
<Link href="/settings">Upgrade to Create Workspace</Link>
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
@@ -17,7 +17,7 @@ export default async function AdminLayout({
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen flex-col">
|
||||
<Header user={session.user} />
|
||||
<Header user={session.user} showAppNavigation />
|
||||
<div className="w-full px-4 md:px-8 flex-1 items-start md:grid md:grid-cols-[220px_minmax(0,1fr)] md:gap-6 lg:grid-cols-[240px_minmax(0,1fr)] lg:gap-10">
|
||||
{/* Mobile Nav */}
|
||||
<div className="md:hidden py-4 border-b mb-4">
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import {
|
||||
DEFAULT_TRIAL_PERIOD_DAYS,
|
||||
getOrCreateStripeCustomerId,
|
||||
getStripeCheckoutState,
|
||||
} from '@/lib/billing';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { getStripe, getStripePriceId, isStripeConfigured } from '@/lib/stripe';
|
||||
import { isTrustedSameOriginRequest } from '@/lib/request-origin';
|
||||
|
||||
function getAppOrigin(request: NextRequest) {
|
||||
if (isTrustedSameOriginRequest(request)) {
|
||||
const origin = request.headers.get('origin');
|
||||
if (origin) {
|
||||
return new URL(origin).origin;
|
||||
}
|
||||
}
|
||||
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
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 (!isStripeConfigured()) {
|
||||
return apiErrors.internalError('Stripe billing is not configured');
|
||||
}
|
||||
|
||||
const checkoutState = await getStripeCheckoutState(session.user.id);
|
||||
if (checkoutState.hasActiveSubscription) {
|
||||
return apiErrors.badRequest('An active subscription already exists for this account');
|
||||
}
|
||||
|
||||
const stripe = getStripe();
|
||||
const priceId = getStripePriceId();
|
||||
const customerId = await getOrCreateStripeCustomerId(session.user.id);
|
||||
const appOrigin = getAppOrigin(request);
|
||||
|
||||
const checkoutSession = await stripe.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
customer: customerId,
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
allow_promotion_codes: true,
|
||||
success_url: `${appOrigin}/settings?billing=success`,
|
||||
cancel_url: `${appOrigin}/settings?billing=canceled`,
|
||||
metadata: {
|
||||
userId: session.user.id,
|
||||
},
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
userId: session.user.id,
|
||||
},
|
||||
...(checkoutState.isTrialEligible ? { trial_period_days: DEFAULT_TRIAL_PERIOD_DAYS } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (!checkoutSession.url) {
|
||||
throw new Error('Stripe did not return a checkout URL');
|
||||
}
|
||||
|
||||
const response = successResponse({ url: checkoutSession.url });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error creating Stripe checkout session:', error);
|
||||
return apiErrors.internalError('Failed to start checkout');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { getBillingOverview } from '@/lib/billing';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { getStripe, isStripeConfigured } from '@/lib/stripe';
|
||||
import { isTrustedSameOriginRequest } from '@/lib/request-origin';
|
||||
|
||||
function getAppOrigin(request: NextRequest) {
|
||||
if (isTrustedSameOriginRequest(request)) {
|
||||
const origin = request.headers.get('origin');
|
||||
if (origin) {
|
||||
return new URL(origin).origin;
|
||||
}
|
||||
}
|
||||
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
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 (!isStripeConfigured()) {
|
||||
return apiErrors.internalError('Stripe billing is not configured');
|
||||
}
|
||||
|
||||
const billing = await getBillingOverview(session.user.id);
|
||||
if (!billing.subscription.stripeCustomerId) {
|
||||
return apiErrors.badRequest('No Stripe customer exists for this account');
|
||||
}
|
||||
|
||||
const stripe = getStripe();
|
||||
const portalSession = await stripe.billingPortal.sessions.create({
|
||||
customer: billing.subscription.stripeCustomerId,
|
||||
return_url: `${getAppOrigin(request)}/settings`,
|
||||
});
|
||||
|
||||
const response = successResponse({ url: portalSession.url });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error creating Stripe portal session:', error);
|
||||
return apiErrors.internalError('Failed to open billing portal');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { getBillingOverview } from '@/lib/billing';
|
||||
import { isStripeConfigured } from '@/lib/stripe';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const billing = await getBillingOverview(session.user.id);
|
||||
const response = successResponse({
|
||||
isConfigured: isStripeConfigured(),
|
||||
checkoutAvailable: isStripeConfigured() && !billing.subscription.hasActiveSubscription,
|
||||
portalAvailable: isStripeConfigured() && Boolean(billing.subscription.stripeCustomerId),
|
||||
subscription: {
|
||||
status: billing.subscription.status,
|
||||
label: billing.subscription.label,
|
||||
hasActiveSubscription: billing.subscription.hasActiveSubscription,
|
||||
hasActiveTrial: billing.subscription.hasActiveTrial,
|
||||
hasBillingAccess: billing.subscription.hasBillingAccess,
|
||||
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) {
|
||||
console.error('Error fetching billing overview:', error);
|
||||
return apiErrors.internalError('Failed to fetch billing overview');
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkProjectAccess } from '@/lib/auth';
|
||||
import { ProjectMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
@@ -29,10 +29,11 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
@@ -44,15 +45,24 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
|
||||
}
|
||||
|
||||
const member = await db.projectMember.update({
|
||||
where: { id: memberId },
|
||||
const member = await db.projectMember.findFirst({
|
||||
where: { id: memberId, projectId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const updatedMember = await db.projectMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: role as ProjectMemberRole },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(member);
|
||||
const response = successResponse(updatedMember);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error updating member role:', error);
|
||||
@@ -82,11 +92,13 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
const memberToRemove = await db.projectMember.findUnique({
|
||||
where: { id: memberId },
|
||||
const memberToRemove = await db.projectMember.findFirst({
|
||||
where: { id: memberId, projectId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
|
||||
if (!memberToRemove) {
|
||||
@@ -95,11 +107,11 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
const isSelf = memberToRemove.userId === session.user.id;
|
||||
|
||||
if (!isOwner && !isAdmin && !isSelf) {
|
||||
if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
await db.projectMember.delete({ where: { id: memberId } });
|
||||
await db.projectMember.delete({ where: { id: memberToRemove.id } });
|
||||
|
||||
const response = successResponse({ message: 'Member removed' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { InvitationStatus, ProjectMemberRole } from '@prisma/client';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkProjectAccess } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
@@ -29,10 +29,11 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only project owners and admins can cancel invitations');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkProjectAccess } from '@/lib/auth';
|
||||
import { InvitationRole, ProjectMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
|
||||
@@ -29,11 +29,12 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id);
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isMember = project.members.length > 0;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isMember) {
|
||||
if (!access.hasAccess || (!isOwner && !isMember)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
@@ -105,10 +106,11 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only project owners and admins can invite members');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { ProjectVisibility } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildBillingAccessWhereInput } from '@/lib/billing';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { DEFAULT_COMMENT_TAGS } from '@/lib/comment-tags';
|
||||
|
||||
@@ -48,10 +49,14 @@ export async function GET(request: NextRequest) {
|
||||
// Also include projects in workspaces where the user is a workspace member
|
||||
...(workspaceId ? [] : [{
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
members: { some: { userId: session.user.id } },
|
||||
},
|
||||
}]),
|
||||
],
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
},
|
||||
};
|
||||
|
||||
// Filter by workspace if provided
|
||||
@@ -150,10 +155,12 @@ export async function POST(request: NextRequest) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const isWsOwner = workspace.ownerId === session.user.id;
|
||||
const isWsAdmin = workspace.members[0]?.role === 'ADMIN';
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (!isWsOwner && !isWsAdmin) {
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can create projects');
|
||||
}
|
||||
|
||||
@@ -164,7 +171,7 @@ export async function POST(request: NextRequest) {
|
||||
description: description?.trim() || null,
|
||||
slug,
|
||||
visibility: visibility || ProjectVisibility.PRIVATE,
|
||||
ownerId: session.user.id,
|
||||
ownerId: workspace.ownerId,
|
||||
workspaceId,
|
||||
},
|
||||
include: {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import type Stripe from 'stripe';
|
||||
import {
|
||||
markSubscriptionCanceledByCustomerId,
|
||||
syncStripeSubscriptionToUser,
|
||||
} from '@/lib/billing';
|
||||
import { getStripe, getStripeWebhookSecret } from '@/lib/stripe';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
async function handleSubscriptionDeleted(subscription: Stripe.Subscription) {
|
||||
const customerId =
|
||||
typeof subscription.customer === 'string'
|
||||
? subscription.customer
|
||||
: subscription.customer.id;
|
||||
|
||||
const currentPeriodEnd =
|
||||
'current_period_end' in subscription && typeof subscription.current_period_end === 'number'
|
||||
? new Date(subscription.current_period_end * 1000)
|
||||
: null;
|
||||
const endedAt =
|
||||
'ended_at' in subscription && typeof subscription.ended_at === 'number'
|
||||
? new Date(subscription.ended_at * 1000)
|
||||
: currentPeriodEnd;
|
||||
|
||||
await markSubscriptionCanceledByCustomerId(customerId, {
|
||||
currentPeriodEnd,
|
||||
endedAt,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const signature = request.headers.get('stripe-signature');
|
||||
if (!signature) {
|
||||
return new Response('Missing Stripe signature', { status: 400 });
|
||||
}
|
||||
|
||||
let event: Stripe.Event;
|
||||
|
||||
try {
|
||||
const stripe = getStripe();
|
||||
const body = await request.text();
|
||||
event = stripe.webhooks.constructEvent(body, signature, getStripeWebhookSecret());
|
||||
} catch (error) {
|
||||
console.error('Failed to verify Stripe webhook:', error);
|
||||
return new Response('Invalid webhook signature', { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const stripe = getStripe();
|
||||
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed': {
|
||||
const session = event.data.object as Stripe.Checkout.Session;
|
||||
if (session.mode === 'subscription' && session.subscription) {
|
||||
const subscriptionId =
|
||||
typeof session.subscription === 'string'
|
||||
? session.subscription
|
||||
: session.subscription.id;
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
||||
await syncStripeSubscriptionToUser(subscription);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'customer.subscription.created':
|
||||
case 'customer.subscription.updated': {
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
await syncStripeSubscriptionToUser(subscription);
|
||||
break;
|
||||
}
|
||||
case 'customer.subscription.deleted': {
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
await handleSubscriptionDeleted(subscription);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ received: true }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to process Stripe webhook:', error);
|
||||
return new Response('Webhook processing failed', { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { WorkspaceMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
@@ -30,10 +30,14 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
@@ -45,15 +49,24 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
|
||||
}
|
||||
|
||||
const member = await db.workspaceMember.update({
|
||||
where: { id: memberId },
|
||||
const member = await db.workspaceMember.findFirst({
|
||||
where: { id: memberId, workspaceId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const updatedMember = await db.workspaceMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: role as WorkspaceMemberRole },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(member);
|
||||
const response = successResponse(updatedMember);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error updating member role:', error);
|
||||
@@ -83,12 +96,17 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
// Users can remove themselves, admins/owners can remove anyone
|
||||
const memberToRemove = await db.workspaceMember.findUnique({
|
||||
where: { id: memberId },
|
||||
const memberToRemove = await db.workspaceMember.findFirst({
|
||||
where: { id: memberId, workspaceId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
|
||||
if (!memberToRemove) {
|
||||
@@ -97,11 +115,32 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
const isSelf = memberToRemove.userId === session.user.id;
|
||||
|
||||
if (!isOwner && !isAdmin && !isSelf) {
|
||||
if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
await db.workspaceMember.delete({ where: { id: memberId } });
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.projectMember.deleteMany({
|
||||
where: {
|
||||
userId: memberToRemove.userId,
|
||||
project: {
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.project.updateMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
ownerId: memberToRemove.userId,
|
||||
},
|
||||
data: {
|
||||
ownerId: workspace.ownerId,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workspaceMember.delete({ where: { id: memberToRemove.id } });
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Member removed' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { InvitationStatus, WorkspaceMemberRole } from '@prisma/client';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
@@ -29,10 +29,14 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can cancel invitations');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { InvitationRole, WorkspaceMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
|
||||
@@ -53,11 +53,15 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isMember = workspace.members.length > 0;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isMember) {
|
||||
if (!access.hasAccess || (!isOwner && !isMember)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
@@ -145,10 +149,14 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can invite members');
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildBillingAccessWhereInput, getWorkspaceCreationEligibility } from '@/lib/billing';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
|
||||
// GET /api/workspaces - List all workspaces for the authenticated user
|
||||
@@ -39,8 +40,8 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const where = {
|
||||
OR: [
|
||||
{ ownerId: session.user.id },
|
||||
{ members: { some: { userId: session.user.id } } },
|
||||
{ ownerId: session.user.id, owner: buildBillingAccessWhereInput() },
|
||||
{ members: { some: { userId: session.user.id } }, owner: buildBillingAccessWhereInput() },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -88,6 +89,13 @@ export async function POST(request: NextRequest) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const billing = await getWorkspaceCreationEligibility(session.user.id);
|
||||
if (!billing.canCreateWorkspace) {
|
||||
return apiErrors.forbidden(
|
||||
billing.reason || 'Upgrade your account to create another workspace'
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description } = body;
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { acceptInvitationTokenForUser } from '@/lib/invitations';
|
||||
|
||||
interface InvitationAcceptPageProps {
|
||||
@@ -23,6 +24,26 @@ export default async function InvitationAcceptPage({ searchParams }: InvitationA
|
||||
redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`);
|
||||
}
|
||||
|
||||
const invitation = await db.invitation.findUnique({
|
||||
where: { token },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
scope: true,
|
||||
workspaceId: true,
|
||||
projectId: true,
|
||||
},
|
||||
});
|
||||
|
||||
function redirectToInvitationTarget(inviteStatus: string) {
|
||||
if (invitation?.scope === 'WORKSPACE' && invitation.workspaceId) {
|
||||
redirect(`/workspaces/${invitation.workspaceId}?invite=${inviteStatus}`);
|
||||
}
|
||||
if (invitation?.scope === 'PROJECT' && invitation.projectId) {
|
||||
redirect(`/projects/${invitation.projectId}?invite=${inviteStatus}`);
|
||||
}
|
||||
}
|
||||
|
||||
const userEmail = session.user.email?.toLowerCase().trim();
|
||||
if (!userEmail) {
|
||||
redirect('/dashboard?invite=invalid_email');
|
||||
@@ -35,13 +56,20 @@ export default async function InvitationAcceptPage({ searchParams }: InvitationA
|
||||
});
|
||||
|
||||
if (result === 'accepted') {
|
||||
redirectToInvitationTarget('accepted');
|
||||
redirect('/dashboard?invite=accepted');
|
||||
}
|
||||
if (result === 'expired') {
|
||||
redirectToInvitationTarget('expired');
|
||||
redirect('/dashboard?invite=expired');
|
||||
}
|
||||
if (result === 'forbidden') {
|
||||
redirect('/dashboard?invite=wrong_account');
|
||||
}
|
||||
|
||||
if (result === 'not_found' && invitation?.status === 'ACCEPTED') {
|
||||
redirectToInvitationTarget('already_accepted');
|
||||
}
|
||||
|
||||
redirect('/dashboard?invite=not_found');
|
||||
}
|
||||
|
||||
@@ -25,6 +25,13 @@ import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type Visibility = 'PRIVATE' | 'INVITE' | 'PUBLIC';
|
||||
@@ -110,9 +117,17 @@ function StepWelcome({ userName, onNext }: { userName: string; onNext: () => voi
|
||||
// ─── Step 2: Create Workspace ──────────────────────────────────────────────────
|
||||
|
||||
function StepWorkspace({
|
||||
canCreateWorkspace,
|
||||
availableWorkspaces,
|
||||
selectedWorkspaceId,
|
||||
onWorkspaceSelected,
|
||||
onNext,
|
||||
onWorkspaceCreated,
|
||||
}: {
|
||||
canCreateWorkspace: boolean;
|
||||
availableWorkspaces: Array<{ id: string; name: string; isOwner: boolean }>;
|
||||
selectedWorkspaceId: string | null;
|
||||
onWorkspaceSelected: (workspaceId: string) => void;
|
||||
onNext: () => void;
|
||||
onWorkspaceCreated: (id: string) => void;
|
||||
}) {
|
||||
@@ -144,6 +159,70 @@ function StepWorkspace({
|
||||
}
|
||||
};
|
||||
|
||||
if (!canCreateWorkspace) {
|
||||
return (
|
||||
<div className="space-y-7">
|
||||
<div className="text-center space-y-3">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-3">
|
||||
<Building2 className="h-8 w-8 text-primary" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">Workspace access</h2>
|
||||
<p className="text-base text-muted-foreground">
|
||||
Your account can't create a new workspace right now.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{availableWorkspaces.length > 0 ? (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-start gap-3 rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
|
||||
<Info className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>
|
||||
You can still create projects inside workspaces where you already have admin access.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="onboarding-workspace">Choose a workspace</Label>
|
||||
<Select
|
||||
value={selectedWorkspaceId ?? undefined}
|
||||
onValueChange={onWorkspaceSelected}
|
||||
>
|
||||
<SelectTrigger id="onboarding-workspace" className="w-full">
|
||||
<SelectValue placeholder="Select a workspace" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableWorkspaces.map((workspace) => (
|
||||
<SelectItem key={workspace.id} value={workspace.id}>
|
||||
{workspace.name}{workspace.isOwner ? ' (Owner)' : ' (Admin)'}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Button onClick={onNext} className="w-full h-11" disabled={!selectedWorkspaceId}>
|
||||
Continue
|
||||
<ChevronRight className="h-4 w-4 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start gap-3 rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
|
||||
<Info className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>
|
||||
You don't currently have a workspace where you can create projects. Ask a workspace owner to invite you as an admin, or upgrade later to create your own workspace.
|
||||
</span>
|
||||
</div>
|
||||
<Button onClick={onNext} className="w-full h-11">
|
||||
Continue
|
||||
<ChevronRight className="h-4 w-4 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-7">
|
||||
<div className="text-center space-y-3">
|
||||
@@ -217,10 +296,14 @@ function StepWorkspace({
|
||||
|
||||
function StepProject({
|
||||
workspaceId,
|
||||
availableWorkspaces,
|
||||
canCreateWorkspace,
|
||||
onNext,
|
||||
onProjectCreated,
|
||||
}: {
|
||||
workspaceId: string | null;
|
||||
availableWorkspaces: Array<{ id: string; name: string; isOwner: boolean }>;
|
||||
canCreateWorkspace: boolean;
|
||||
onNext: () => void;
|
||||
onProjectCreated: (id: string) => void;
|
||||
}) {
|
||||
@@ -273,7 +356,13 @@ function StepProject({
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start gap-3 rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
|
||||
<Info className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>You skipped workspace creation. Projects require a workspace — you can create both from the dashboard later.</span>
|
||||
<span>
|
||||
{canCreateWorkspace
|
||||
? 'You skipped workspace creation. Projects require a workspace — you can create both from the dashboard later.'
|
||||
: availableWorkspaces.length === 0
|
||||
? 'You do not currently have permission to create projects in any workspace.'
|
||||
: 'Pick a workspace in the previous step to create a project here.'}
|
||||
</span>
|
||||
</div>
|
||||
<Button onClick={onNext} className="w-full h-11">
|
||||
Continue
|
||||
@@ -547,10 +636,18 @@ function StepNotifications({ onFinish }: { onFinish: () => Promise<void> }) {
|
||||
|
||||
// ─── Wizard Shell ──────────────────────────────────────────────────────────────
|
||||
|
||||
export function OnboardingWizard({ userName }: { userName: string }) {
|
||||
export function OnboardingWizard({
|
||||
userName,
|
||||
canCreateWorkspace,
|
||||
availableWorkspaces,
|
||||
}: {
|
||||
userName: string;
|
||||
canCreateWorkspace: boolean;
|
||||
availableWorkspaces: Array<{ id: string; name: string; isOwner: boolean }>;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [currentStep, setCurrentStep] = useState(1);
|
||||
const [createdWorkspaceId, setCreatedWorkspaceId] = useState<string | null>(null);
|
||||
const [createdWorkspaceId, setCreatedWorkspaceId] = useState<string | null>(availableWorkspaces[0]?.id ?? null);
|
||||
const [isCompleting, setIsCompleting] = useState(false);
|
||||
|
||||
const goNext = () => setCurrentStep((s) => Math.min(s + 1, TOTAL_STEPS));
|
||||
@@ -615,10 +712,23 @@ export function OnboardingWizard({ userName }: { userName: string }) {
|
||||
<StepWelcome userName={userName} onNext={goNext} />
|
||||
)}
|
||||
{currentStep === 2 && (
|
||||
<StepWorkspace onNext={goNext} onWorkspaceCreated={setCreatedWorkspaceId} />
|
||||
<StepWorkspace
|
||||
canCreateWorkspace={canCreateWorkspace}
|
||||
availableWorkspaces={availableWorkspaces}
|
||||
selectedWorkspaceId={createdWorkspaceId}
|
||||
onWorkspaceSelected={setCreatedWorkspaceId}
|
||||
onNext={goNext}
|
||||
onWorkspaceCreated={setCreatedWorkspaceId}
|
||||
/>
|
||||
)}
|
||||
{currentStep === 3 && (
|
||||
<StepProject workspaceId={createdWorkspaceId} onNext={goNext} onProjectCreated={() => {}} />
|
||||
<StepProject
|
||||
workspaceId={createdWorkspaceId}
|
||||
availableWorkspaces={availableWorkspaces}
|
||||
canCreateWorkspace={canCreateWorkspace}
|
||||
onNext={goNext}
|
||||
onProjectCreated={() => {}}
|
||||
/>
|
||||
)}
|
||||
{currentStep === 4 && (
|
||||
<StepVideo onNext={goNext} />
|
||||
|
||||
+34
-5
@@ -1,4 +1,5 @@
|
||||
import { auth } from '@/lib/auth';
|
||||
import { buildBillingAccessWhereInput, getBillingOverview } from '@/lib/billing';
|
||||
import { db } from '@/lib/db';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { OnboardingWizard } from './onboarding-wizard';
|
||||
@@ -9,10 +10,28 @@ export default async function OnboardingPage() {
|
||||
redirect('/login');
|
||||
}
|
||||
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { onboardingCompletedAt: true, name: true, email: true },
|
||||
});
|
||||
const [user, billing, creatableWorkspaces] = await Promise.all([
|
||||
db.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { onboardingCompletedAt: true, name: true, email: true },
|
||||
}),
|
||||
getBillingOverview(session.user.id),
|
||||
db.workspace.findMany({
|
||||
where: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
OR: [
|
||||
{ ownerId: session.user.id },
|
||||
{ members: { some: { userId: session.user.id, role: 'ADMIN' } } },
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
ownerId: true,
|
||||
},
|
||||
orderBy: { name: 'asc' },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (user?.onboardingCompletedAt) {
|
||||
redirect('/dashboard');
|
||||
@@ -20,5 +39,15 @@ export default async function OnboardingPage() {
|
||||
|
||||
const userName = user?.name || user?.email?.split('@')[0] || 'there';
|
||||
|
||||
return <OnboardingWizard userName={userName} />;
|
||||
return (
|
||||
<OnboardingWizard
|
||||
userName={userName}
|
||||
canCreateWorkspace={billing.workspaceCreation.canCreateWorkspace}
|
||||
availableWorkspaces={creatableWorkspaces.map((workspace) => ({
|
||||
id: workspace.id,
|
||||
name: workspace.name,
|
||||
isOwner: workspace.ownerId === session.user.id,
|
||||
}))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user