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
@@ -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>
)}