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:
Yusuf İpek
2026-04-08 17:50:40 +03:00
parent 8db7a031e6
commit 6f22b0bf8b
45 changed files with 1859 additions and 218 deletions
+11
View File
@@ -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)
+5 -1
View File
@@ -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 = {
+17 -3
View File
@@ -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} />;
}
@@ -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 &quot;{workspace.name}&quot;?</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 &quot;{workspace.name}&quot;?</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>
+9 -2
View File
@@ -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} />;
}
+20 -7
View File
@@ -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>
)}