Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Workspace billing
Richie McIlroy81282d2d840b
diff --git a/apps/web/app/api/invite/accept/route.ts b/apps/web/app/api/invite/accept/route.tsnew file mode 100644index 000000000..584817775--- /dev/null+++ b/apps/web/app/api/invite/accept/route.ts@@ -0,0 +1,48 @@+import { NextRequest, NextResponse } from "next/server";+import { db } from "@cap/database";+import { getCurrentUser } from "@cap/database/auth/session";+import { spaceInvites, spaceMembers } from "@cap/database/schema";+import { eq } from "drizzle-orm";+import { nanoId } from "@cap/database/helpers"++export async function POST(request: NextRequest) {+ const user = await getCurrentUser();+ if (!user) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { inviteId } = await request.json();++ try {+ // Find the invite+ const [invite] = await db+ .select()+ .from(spaceInvites)+ .where(eq(spaceInvites.id, inviteId));++ if (!invite) {+ return NextResponse.json({ error: "Invite not found" }, { status: 404 });+ }++ // Check if the user's email matches the invited email+ if (user.email !== invite.invitedEmail) {+ return NextResponse.json({ error: "Email mismatch" }, { status: 403 });+ }++ // Create a new space member+ await db.insert(spaceMembers).values({+ id: nanoId(),+ spaceId: invite.spaceId,+ userId: user.id,+ role: invite.role,+ });++ // Delete the invite+ await db.delete(spaceInvites).where(eq(spaceInvites.id, inviteId));++ return NextResponse.json({ success: true });+ } catch (error) {+ console.error("Error accepting invite:", error);+ return NextResponse.json({ error: "Internal server error" }, { status: 500 });+ }+}\ No newline at end of filediff --git a/apps/web/app/api/invite/decline/route.ts b/apps/web/app/api/invite/decline/route.tsnew file mode 100644index 000000000..b4a392479--- /dev/null+++ b/apps/web/app/api/invite/decline/route.ts@@ -0,0 +1,18 @@+import { NextRequest, NextResponse } from "next/server";+import { db } from "@cap/database";+import { spaceInvites } from "@cap/database/schema";+import { eq } from "drizzle-orm";++export async function POST(request: NextRequest) {+ const { inviteId } = await request.json();++ try {+ // Delete the invite+ await db.delete(spaceInvites).where(eq(spaceInvites.id, inviteId));++ return NextResponse.json({ success: true });+ } catch (error) {+ console.error("Error declining invite:", error);+ return NextResponse.json({ error: "Internal server error" }, { status: 500 });+ }+}\ No newline at end of filediff --git a/apps/web/app/api/settings/billing/manage/route.ts b/apps/web/app/api/settings/billing/manage/route.tsindex 19b0cb459..2cf06fc16 100644--- a/apps/web/app/api/settings/billing/manage/route.ts+++ b/apps/web/app/api/settings/billing/manage/route.ts@@ -40,7 +40,7 @@ export async function POST(request: NextRequest) {const { url } = await stripe.billingPortal.sessions.create({customer: customerId as string,- return_url: `${process.env.NEXT_PUBLIC_URL}/dashboard/settings/billing`,+ return_url: `${process.env.NEXT_PUBLIC_URL}/dashboard/settings/workspace`,});return NextResponse.json(url);}diff --git a/apps/web/app/api/settings/billing/quota/route.ts b/apps/web/app/api/settings/billing/quota/route.tsnew file mode 100644index 000000000..e69de29bbdiff --git a/apps/web/app/api/settings/onboarding/route.ts b/apps/web/app/api/settings/onboarding/route.tsindex f88ef43f4..e3b3ab7cd 100644--- a/apps/web/app/api/settings/onboarding/route.ts+++ b/apps/web/app/api/settings/onboarding/route.ts@@ -63,12 +63,17 @@ export async function POST(request: NextRequest) {.where(eq(users.id, user.id));}+ // After updating user and creating spacereturn new Response(JSON.stringify({+ success: true,+ message: "Onboarding completed successfully",+ }),+ {status: 200,headers: {"Content-Type": "application/json",},- })+ });}diff --git a/apps/web/app/api/settings/workspace/details/route.ts b/apps/web/app/api/settings/workspace/details/route.tsnew file mode 100644index 000000000..e75b288a8--- /dev/null+++ b/apps/web/app/api/settings/workspace/details/route.ts@@ -0,0 +1,66 @@+import { type NextRequest } from "next/server";+import { getCurrentUser } from "@cap/database/auth/session";+import { spaces } from "@cap/database/schema";+import { db } from "@cap/database";+import { eq } from "drizzle-orm";++export async function POST(request: NextRequest) {+ console.log("POST request received for workspace details update");+ const user = await getCurrentUser();+ const { workspaceName, spaceId } = await request.json();+ console.log(`Received workspaceName: ${workspaceName}, spaceId: ${spaceId}`);++ if (!user) {+ console.error("User not found");++ return new Response(JSON.stringify({ error: true }), {+ status: 401,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ console.log(`User found: ${user.id}`);++ const space = await db.select().from(spaces).where(eq(spaces.id, spaceId));+ console.log(`Space query result:`, space);++ if (!space) {+ console.error(`Space not found for spaceId: ${spaceId}`);+ return new Response(JSON.stringify({ error: true }), {+ status: 404,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ if (space.length > 0 && space[0]?.ownerId !== user.id) {+ console.error(`User ${user.id} is not the owner of space ${spaceId}`);+ return new Response(JSON.stringify({ error: true }), {+ status: 403,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ console.log(`Updating space name to: ${workspaceName}`);+ await db+ .update(spaces)+ .set({+ name: workspaceName,+ })+ .where(eq(spaces.id, spaceId));++ console.log("Workspace details updated successfully");+ return new Response(+ JSON.stringify({+ status: 200,+ headers: {+ "Content-Type": "application/json",+ },+ })+ );+}diff --git a/apps/web/app/api/settings/workspace/invite/remove/route.ts b/apps/web/app/api/settings/workspace/invite/remove/route.tsnew file mode 100644index 000000000..9dd2ff79f--- /dev/null+++ b/apps/web/app/api/settings/workspace/invite/remove/route.ts@@ -0,0 +1,76 @@+import { type NextRequest } from "next/server";+import { getCurrentUser } from "@cap/database/auth/session";+import { spaces, spaceInvites } from "@cap/database/schema";+import { db } from "@cap/database";+import { eq, and } from "drizzle-orm";++export async function POST(request: NextRequest) {+ console.log("POST request received for removing workspace invite");+ const user = await getCurrentUser();+ const { inviteId, spaceId } = await request.json();+ console.log(`Received inviteId: ${inviteId}, spaceId: ${spaceId}`);++ if (!user) {+ console.error("User not found");+ return new Response(JSON.stringify({ error: true }), {+ status: 401,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ console.log(`User found: ${user.id}`);++ const space = await db.select().from(spaces).where(eq(spaces.id, spaceId)).limit(1);+ console.log(`Space query result:`, space);++ if (!space || space.length === 0) {+ console.error(`Space not found for spaceId: ${spaceId}`);+ return new Response(JSON.stringify({ error: true }), {+ status: 404,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ if (space[0]?.ownerId !== user.id) {+ console.error(`User ${user.id} is not the owner of space ${spaceId}`);+ return new Response(JSON.stringify({ error: true }), {+ status: 403,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ const result = await db.delete(spaceInvites)+ .where(+ and(+ eq(spaceInvites.id, inviteId),+ eq(spaceInvites.spaceId, spaceId)+ )+ );++ if (result.rowsAffected === 0) {+ console.error(`No invite found with id ${inviteId} for space ${spaceId}`);+ return new Response(JSON.stringify({ error: true }), {+ status: 404,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ console.log("Workspace invite removed successfully");+ return new Response(+ JSON.stringify({ success: true }),+ {+ status: 200,+ headers: {+ "Content-Type": "application/json",+ },+ }+ );+}diff --git a/apps/web/app/api/settings/workspace/invite/send/route.ts b/apps/web/app/api/settings/workspace/invite/send/route.tsnew file mode 100644index 000000000..4131bd4c4--- /dev/null+++ b/apps/web/app/api/settings/workspace/invite/send/route.ts@@ -0,0 +1,86 @@+import { type NextRequest } from "next/server";+import { getCurrentUser } from "@cap/database/auth/session";+import { spaces, spaceInvites } from "@cap/database/schema";+import { db } from "@cap/database";+import { eq } from "drizzle-orm";+import { nanoId } from "@cap/database/helpers";+import { sendEmail } from "@cap/database/emails/config";+import { WorkspaceInvite } from "@cap/database/emails/workspace-invite";++export async function POST(request: NextRequest) {+ console.log("POST request received for workspace invite");+ const user = await getCurrentUser();+ const { invitedEmails, spaceId } = await request.json();+ console.log(`Received invitedEmails: ${invitedEmails}, spaceId: ${spaceId}`);++ if (!user) {+ console.error("User not found");+ return new Response(JSON.stringify({ error: true }), {+ status: 401,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ console.log(`User found: ${user.id}`);++ const space = await db.select().from(spaces).where(eq(spaces.id, spaceId));+ console.log(`Space query result:`, space);++ if (!space || space.length === 0) {+ console.error(`Space not found for spaceId: ${spaceId}`);+ return new Response(JSON.stringify({ error: true }), {+ status: 404,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ if (space[0]?.ownerId !== user.id) {+ console.error(`User ${user.id} is not the owner of space ${spaceId}`);+ return new Response(JSON.stringify({ error: true }), {+ status: 403,+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;+ const validEmails = invitedEmails.filter((email: string) => emailRegex.test(email.trim()));++ for (const email of validEmails) {+ const inviteId = nanoId();+ await db.insert(spaceInvites).values({+ id: inviteId,+ spaceId: spaceId,+ invitedEmail: email.trim(),+ invitedByUserId: user.id,+ role: "member",+ });++ // Send invitation email+ const inviteUrl = `${process.env.NEXT_PUBLIC_URL}/invite/${inviteId}`;+ await sendEmail({+ email: email.trim(),+ subject: `Invitation to join ${space[0].name} on Cap`,+ react: WorkspaceInvite({+ email: email.trim(),+ url: inviteUrl,+ workspaceName: space[0].name,+ }),+ });+ }++ console.log("Workspace invites created and emails sent successfully");+ return new Response(+ JSON.stringify({+ status: 200,+ headers: {+ "Content-Type": "application/json",+ },+ })+ );+}diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.tsindex 52b1de594..12f372781 100644--- a/apps/web/app/api/webhooks/stripe/route.ts+++ b/apps/web/app/api/webhooks/stripe/route.ts@@ -38,10 +38,33 @@ export const POST = async (req: Request) => {foundUserId = customer.metadata.userId;}if (!foundUserId) {- console.log("No user found in checkout.session.completed event");- return new Response("No user found", {- status: 400,- });+ console.log("No user found in metadata, checking customer email");+ if ("email" in customer && customer.email) {+ const userByEmail = await db+ .select()+ .from(users)+ .where(eq(users.email, customer.email))+ .limit(1);++ if (userByEmail && userByEmail.length > 0 && userByEmail[0]) {+ foundUserId = userByEmail[0].id;+ console.log(`User found by email: ${foundUserId}`);+ // Update customer metadata with userId+ await stripe.customers.update(customer.id, {+ metadata: { userId: foundUserId },+ });+ } else {+ console.log("No user found by email");+ return new Response("No user found", {+ status: 400,+ });+ }+ } else {+ console.log("No email found for customer");+ return new Response("No user found", {+ status: 400,+ });+ }}const user = await db@@ -56,11 +79,15 @@ export const POST = async (req: Request) => {});}+ const subscription = await stripe.subscriptions.retrieve(event.data.object.subscription as string);+ const inviteQuota = subscription.items.data.reduce((total, item) => total + (item.quantity || 1), 0);+await db.update(users).set({stripeSubscriptionId: event.data.object.subscription as string,stripeSubscriptionStatus: event.data.object.status,+ inviteQuota: inviteQuota,}).where(eq(users.id, foundUserId));console.log("User updated successfully for checkout.session.completed event");@@ -76,10 +103,33 @@ export const POST = async (req: Request) => {foundUserId = customer.metadata.userId;}if (!foundUserId) {- console.log("No user found in customer.subscription.updated event");- return new Response("No user found", {- status: 400,- });+ console.log("No user found in metadata, checking customer email");+ if ("email" in customer && customer.email) {+ const userByEmail = await db+ .select()+ .from(users)+ .where(eq(users.email, customer.email))+ .limit(1);++ if (userByEmail && userByEmail.length > 0 && userByEmail[0]) {+ foundUserId = userByEmail[0].id;+ console.log(`User found by email: ${foundUserId}`);+ // Update customer metadata with userId+ await stripe.customers.update(customer.id, {+ metadata: { userId: foundUserId },+ });+ } else {+ console.log("No user found by email");+ return new Response("No user found", {+ status: 400,+ });+ }+ } else {+ console.log("No email found for customer");+ return new Response("No user found", {+ status: 400,+ });+ }}const user = await db@@ -94,11 +144,15 @@ export const POST = async (req: Request) => {});}+ const subscription = event.data.object as Stripe.Subscription;+ const inviteQuota = subscription.items.data.reduce((total, item) => total + (item.quantity || 1), 0);+await db.update(users).set({stripeSubscriptionId: event.data.object.id,stripeSubscriptionStatus: event.data.object.status,+ inviteQuota: inviteQuota,}).where(eq(users.id, foundUserId));console.log("User updated successfully for customer.subscription.updated event");@@ -114,10 +168,33 @@ export const POST = async (req: Request) => {foundUserId = customer.metadata.userId;}if (!foundUserId) {- console.log("No user found in customer.subscription.deleted event");- return new Response("No user found", {- status: 400,- });+ console.log("No user found in metadata, checking customer email");+ if ("email" in customer && customer.email) {+ const userByEmail = await db+ .select()+ .from(users)+ .where(eq(users.email, customer.email))+ .limit(1);++ if (userByEmail && userByEmail.length > 0 && userByEmail[0]) {+ foundUserId = userByEmail[0].id;+ console.log(`User found by email: ${foundUserId}`);+ // Update customer metadata with userId+ await stripe.customers.update(customer.id, {+ metadata: { userId: foundUserId },+ });+ } else {+ console.log("No user found by email");+ return new Response("No user found", {+ status: 400,+ });+ }+ } else {+ console.log("No email found for customer");+ return new Response("No user found", {+ status: 400,+ });+ }}const user = await db@@ -137,6 +214,7 @@ export const POST = async (req: Request) => {.set({stripeSubscriptionId: event.data.object.id,stripeSubscriptionStatus: event.data.object.status,+ inviteQuota: 1, // Reset to default quota when subscription is deleted}).where(eq(users.id, foundUserId));console.log("User updated successfully for customer.subscription.deleted event");diff --git a/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx b/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsxindex 65b0bc60a..f42606cde 100644--- a/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx+++ b/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx@@ -2,12 +2,12 @@import { usePathname, useRouter } from "next/navigation";import {Plus,- Settings,LogOut,ChevronDown,- Clapperboard,- Video,- Download,+ User,+ MoreVertical,+ Settings,+ MessageSquare,} from "lucide-react";import Link from "next/link";import { classNames } from "@cap/utils";@@ -33,10 +33,60 @@ import { signOut } from "next-auth/react";import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";import { UsageButton } from "@/components/UsageButton";+const Avatar = ({+ children,+ className,+}: {+ children: React.ReactNode;+ className?: string;+}) => (+ <div+ className={`flex items-center justify-center rounded-lg bg-gray-200 ${className}`}+ >+ {children}+ </div>+);++const Clapperboard = ({ className }: { className: string }) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ fill="none"+ viewBox="0 0 18 15"+ className={className}+ >+ <path+ stroke="#8991A3"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.667"+ d="M1.5 5.833h15m-15 0v5a2.5 2.5 0 002.5 2.5h10a2.5 2.5 0 002.5-2.5v-5m-15 0V4.167a2.5 2.5 0 012.5-2.5h10a2.5 2.5 0 012.5 2.5v1.666M5.583 2.083l-.666 3.334m4.416-3.334l-.666 3.334m4.416-3.334l-.666 3.334"+ ></path>+ </svg>+);++const Download = ({ className }: { className: string }) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ fill="none"+ viewBox="0 0 16 15"+ className={className}+ >+ <path+ stroke="#8991A3"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.667"+ d="M14.667 10v1.667a2.5 2.5 0 01-2.5 2.5H3.833a2.5 2.5 0 01-2.5-2.5V10M8 9.583V.833m0 8.75L5.083 6.667M8 9.583l2.917-2.916"+ ></path>+ </svg>+);+export const AdminNavItems = () => {const pathname = usePathname();const [open, setOpen] = useState(false);- const { spaceData, activeSpace } = useSharedContext();+ const { spaceData, activeSpace, user } = useSharedContext();+ const [menuOpen, setMenuOpen] = useState(false);+ const router = useRouter();const manageNavigation = [{@@ -51,15 +101,6 @@ export const AdminNavItems = () => {icon: Download,subNav: [],},- {- name: "Settings",- href: `/dashboard/settings`,- icon: Settings,- subNav: [- { name: "My account", href: `/dashboard/settings` },- { name: "Billing", href: `/dashboard/settings/billing` },- ],- },];const navItemClass =@@ -78,7 +119,7 @@ export const AdminNavItems = () => {<div className="flex items-center w-full text-left"><div><p className="text-[0.875rem]">- {activeSpace?.name ?? "No space found"}+ {activeSpace?.space.name ?? "No space found"}</p></div></div>@@ -95,14 +136,14 @@ export const AdminNavItems = () => {{spaceData !== null &&spaceData?.map((space) => (<CommandItem- key={space.name + "-space"}+ key={space.space.name + "-space"}// onSelect={async () => {// await handleActiveSpace(space.id);// router.refresh();// setOpen(false);// }}>- {space.name}+ {space.space.name}</CommandItem>))}<DialogTrigger className="w-full">@@ -136,7 +177,7 @@ export const AdminNavItems = () => {><item.iconclassName={classNames(- "flex-shrink-0 w-6 h-6 stroke-[1.8px]",+ "flex-shrink-0 w-5 h-5 stroke-[1.5px]",pathname.includes(item.href) ? "text-black" : "")}aria-hidden="true"@@ -169,15 +210,64 @@ export const AdminNavItems = () => {</div><div className="mt-auto"><div className="w-full mb-3 pb-5 border-b-2 border-gray-200 border-dotted">- <UsageButton />+ <UsageButton+ subscribed={+ user.stripeSubscriptionStatus !== null &&+ user.stripeSubscriptionStatus !== "canceled"+ }+ /></div>- <button- onClick={() => signOut()}- className={classNames("opacity-75 hover:opacity-100", navItemClass)}- >- <LogOut className="flex-shrink-0 w-6 h-6" aria-hidden="true" />- <span className="text-base ml-2.5">Sign out</span>- </button>+ <Popover open={menuOpen} onOpenChange={setMenuOpen}>+ <PopoverTrigger asChild>+ <div className="flex items-center justify-between cursor-pointer hover:bg-gray-100 p-2 rounded-lg transition-colors">+ <div className="flex items-center">+ <Avatar className="h-8 w-8">+ <User className="h-4 w-4 text-gray-400" />+ </Avatar>+ <span className="ml-2 text-sm">{user.name}</span>+ </div>+ <MoreVertical className="h-5 w-5 text-gray-500 group-hover:text-gray-500" />+ </div>+ </PopoverTrigger>+ <PopoverContent className="bg-gray-100 w-48 p-1">+ <Command>+ <CommandGroup>+ <CommandItem+ className="py-2 px-2 rounded-lg hover:bg-gray-200 cursor-pointer group"+ onSelect={() => {+ router.push("/dashboard/settings");+ setMenuOpen(false);+ }}+ >+ <Settings className="mr-2 h-4 w-4 text-gray-400 group-hover:text-gray-500" />+ <span className="text-gray-400 group-hover:text-gray-500 text-sm">+ Settings+ </span>+ </CommandItem>+ <CommandItem+ className="py-2 px-2 rounded-lg hover:bg-gray-200 cursor-pointer group"+ onSelect={() =>+ window.open("https://cap.link/discord", "_blank")+ }+ >+ <MessageSquare className="mr-2 h-4 w-4 text-gray-400 group-hover:text-gray-500" />+ <span className="text-gray-400 group-hover:text-gray-500 text-sm">+ Chat Support+ </span>+ </CommandItem>+ <CommandItem+ className="py-2 px-2 rounded-lg hover:bg-gray-200 cursor-pointer group"+ onSelect={() => signOut()}+ >+ <LogOut className="mr-2 h-4 w-4 text-gray-400 group-hover:text-gray-500" />+ <span className="text-gray-400 group-hover:text-gray-500 text-sm">+ Sign Out+ </span>+ </CommandItem>+ </CommandGroup>+ </Command>+ </PopoverContent>+ </Popover></div></nav><DialogContent>diff --git a/apps/web/app/dashboard/_components/DynamicSharedLayout.tsx b/apps/web/app/dashboard/_components/DynamicSharedLayout.tsxindex 7f42eab3b..019b38592 100644--- a/apps/web/app/dashboard/_components/DynamicSharedLayout.tsx+++ b/apps/web/app/dashboard/_components/DynamicSharedLayout.tsx@@ -1,23 +1,13 @@"use client";-import { createContext, useContext, useState } from "react";+import { createContext, useContext } from "react";import AdminDesktopNav from "@/app/dashboard/_components/AdminNavbar/AdminDesktopNav";import AdminMobileNav from "@/app/dashboard/_components/AdminNavbar/AdminMobileNav";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@cap/ui";-import { UsageButton } from "@/components/UsageButton";import { users, spaces } from "@cap/database/schema";-import Link from "next/link";-import { isUserOnProPlan } from "@cap/utils";-import { signOut } from "next-auth/react";+import { Space } from "@/app/dashboard/layout";type SharedContext = {- spaceData: (typeof spaces.$inferSelect)[] | null;- activeSpace: typeof spaces.$inferSelect | null;+ spaceData: Space[] | null;+ activeSpace: Space | null;user: typeof users.$inferSelect;};@@ -40,95 +30,6 @@ export default function DynamicSharedLayout({<AdminDesktopNav /><div className="flex-1 overflow-auto focus:outline-none"><AdminMobileNav />- {/* <div className="py-3 -mb-3 flex items-center justify-end wrapper space-x-3">- <div>- <UsageButton />- </div>- <DropdownMenu>- <DropdownMenuTrigger- asChild- className="flex items-center justify-center cursor-pointer w-9 h-9 bg-white hover:bg-gray-100 rounded-xl"- >- <button>- <svg- xmlns="http://www.w3.org/2000/svg"- width="24"- height="24"- fill="none"- stroke="currentColor"- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth="2"- className="w-7 h-7"- viewBox="0 0 24 24"- >- <circle cx="12" cy="12" r="1"></circle>- <circle cx="19" cy="12" r="1"></circle>- <circle cx="5" cy="12" r="1"></circle>- </svg>- </button>- </DropdownMenuTrigger>- <DropdownMenuContent className="w-56">- <DropdownMenuItem>- <div>- {isUserOnProPlan({- subscriptionStatus:- user?.stripeSubscriptionStatus as string,- }) ? (- <Link- className="w-full text-blue-500 font-medium text-base"- href="/dashboard/settings/billing"- >- Cap Pro- </Link>- ) : (- <Link- className="w-full text-blue-500 font-medium text-base"- href="/pricing"- >- Upgrade to Cap Pro- </Link>- )}- </div>- </DropdownMenuItem>- <DropdownMenuItem>- <Link className="w-full text-base" href="/dashboard/settings">- Settings- </Link>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem>- <Link- className="w-full text-base"- href="https://discord.gg/y8gdQ3WRN3"- target="_blank"- >- Chat support- </Link>- </DropdownMenuItem>- <DropdownMenuItem>- <Link className="w-full text-base" href="/download">- Download Mac App- </Link>- </DropdownMenuItem>- <DropdownMenuItem>- <Link className="w-full text-base" href="/record">- Record a Video- </Link>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem>- <button- className="w-full text-base hover:text-black"- onClick={() => signOut()}- >- Sign out- </button>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div> */}-<main className="min-h-screen w-full">{children}</main></div></div>diff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsxindex 4ad141c36..d66161ac2 100644--- a/apps/web/app/dashboard/caps/Caps.tsx+++ b/apps/web/app/dashboard/caps/Caps.tsx@@ -2,7 +2,7 @@import { Button } from "@cap/ui";import moment from "moment";import { VideoThumbnail } from "@/components/VideoThumbnail";-import { useRouter, useSearchParams } from "next/navigation";+import { redirect, useRouter, useSearchParams } from "next/navigation";import toast, { Toaster } from "react-hot-toast";import {EyeIcon,@@ -38,17 +38,21 @@ type videoData = {}[];export const Caps = ({ data, count }: { data: videoData; count: number }) => {- const { refresh } = useRouter();+ const { refresh, replace } = useRouter();const params = useSearchParams();const page = Number(params.get("page")) || 1;const [analytics, setAnalytics] = useState<Record<string, number>>({});- const { user } = useSharedContext();+ const { user, activeSpace } = useSharedContext();const limit = 15;const totalPages = Math.ceil(count / limit);const [isEditing, setIsEditing] = useState<null | string>(null);const [isDownloading, setIsDownloading] = useState<null | string>(null);const [titles, setTitles] = useState<Record<string, string>>({});+ if (!activeSpace && (user?.name === undefined || user?.name === "")) {+ replace("/onboarding");+ }+const handleTitleBlur = async ({ id }: { id: string }) => {setIsEditing(id);diff --git a/apps/web/app/dashboard/caps/page.tsx b/apps/web/app/dashboard/caps/page.tsxindex 93b130bee..a7eb11a5b 100644--- a/apps/web/app/dashboard/caps/page.tsx+++ b/apps/web/app/dashboard/caps/page.tsx@@ -3,7 +3,6 @@ import { db } from "@cap/database";import { comments, videos } from "@cap/database/schema";import { desc, eq, sql, count } from "drizzle-orm";import { getCurrentUser } from "@cap/database/auth/session";-import { redirect } from "next/navigation";import { Metadata } from "next";export const metadata: Metadata = {@@ -21,17 +20,6 @@ export default async function CapsPage({const limit = Number(searchParams.limit) || 15;const user = await getCurrentUser();const userId = user?.id as string;-- if (- user !== null &&- (user.name === null ||- user.name.length === 0 ||- user.activeSpaceId === null ||- user.activeSpaceId.length === 0)- ) {- return redirect("/onboarding");- }-const offset = (page - 1) * limit;const totalCountResult = await dbdiff --git a/apps/web/app/dashboard/layout.tsx b/apps/web/app/dashboard/layout.tsxindex 859e28fdd..97a533831 100644--- a/apps/web/app/dashboard/layout.tsx+++ b/apps/web/app/dashboard/layout.tsx@@ -1,11 +1,25 @@-"use server";import DynamicSharedLayout from "@/app/dashboard/_components/DynamicSharedLayout";import { getCurrentUser } from "@cap/database/auth/session";import { redirect } from "next/navigation";import { DashboardTemplate } from "@/components/templates/DashboardTemplate";import { db } from "@cap/database";-import { spaceMembers, spaces } from "@cap/database/schema";-import { eq, or } from "drizzle-orm";+import {+ spaceMembers,+ spaces,+ spaceInvites,+ users,+} from "@cap/database/schema";+import { eq, inArray, or, and, count, sql } from "drizzle-orm";++export type Space = {+ space: typeof spaces.$inferSelect;+ members: (typeof spaceMembers.$inferSelect & {+ user: Pick<typeof users.$inferSelect, "id" | "name" | "email" | "lastName">;+ })[];+ invites: (typeof spaceInvites.$inferSelect)[];+ inviteQuota: number;+ totalInvites: number;+};export default async function DashboardLayout({children,@@ -18,27 +32,105 @@ export default async function DashboardLayout({redirect("/login");}- const spaceSelect = await db+ const spacesWithMembers = await db.select({- id: spaces.id,- name: spaces.name,- ownerId: spaces.ownerId,- metadata: spaces.metadata,- createdAt: spaces.createdAt,- updatedAt: spaces.updatedAt,+ space: spaces,+ member: spaceMembers,+ user: {+ id: users.id,+ name: users.name,+ lastName: users.lastName,+ email: users.email,+ inviteQuota: users.inviteQuota,+ },}).from(spaces)- .where(or(eq(spaces.ownerId, user.id), eq(spaceMembers.userId, user.id)))- .leftJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId));+ .leftJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId))+ .leftJoin(users, eq(spaceMembers.userId, users.id))+ .where(or(eq(spaces.ownerId, user.id), eq(spaceMembers.userId, user.id)));++ const spaceIds = spacesWithMembers.map((row) => row.space.id);++ let spaceInvitesData: (typeof spaceInvites.$inferSelect)[] = [];+ if (spaceIds.length > 0) {+ spaceInvitesData = await db+ .select()+ .from(spaceInvites)+ .where(inArray(spaceInvites.spaceId, spaceIds));+ }++ const spaceSelect: Space[] = await Promise.all(+ spacesWithMembers+ .reduce((acc: (typeof spaces.$inferSelect)[], row) => {+ const existingSpace = acc.find((s) => s.id === row.space.id);+ if (!existingSpace) {+ acc.push(row.space);+ }+ return acc;+ }, [])+ .map(async (space) => {+ const allMembers = await db+ .select({+ member: spaceMembers,+ user: {+ id: users.id,+ name: users.name,+ lastName: users.lastName,+ email: users.email,+ },+ })+ .from(spaceMembers)+ .leftJoin(users, eq(spaceMembers.userId, users.id))+ .where(eq(spaceMembers.spaceId, space.id));++ const owner = await db+ .select({+ inviteQuota: users.inviteQuota,+ })+ .from(users)+ .where(eq(users.id, space.ownerId))+ .then((result) => result[0]);++ const totalInvitesResult = await db+ .select({+ value: sql<number>`+ ${count(spaceMembers.id)} + ${count(spaceInvites.id)}+ `,+ })+ .from(spaces)+ .leftJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId))+ .leftJoin(spaceInvites, eq(spaces.id, spaceInvites.spaceId))+ .where(eq(spaces.ownerId, space.ownerId));- const activeSpace = spaceSelect.find(- (space) => space.id === user.activeSpaceId+ const totalInvites = totalInvitesResult[0]?.value || 0;++ return {+ space,+ members: allMembers.map((m) => ({ ...m.member, user: m.user! })),+ invites: spaceInvitesData.filter(+ (invite) => invite.spaceId === space.id+ ),+ inviteQuota: owner?.inviteQuota || 1,+ totalInvites,+ };+ })+ );++ let findActiveSpace = spaceSelect.find(+ (space) => space.space.id === user.activeSpaceId);+ if (!findActiveSpace && spaceSelect.length > 0) {+ findActiveSpace = spaceSelect[0];+ }++ console.log("spaceSelect", spaceSelect);+ console.log("findActiveSpace", findActiveSpace);+return (<DynamicSharedLayoutspaceData={spaceSelect}- activeSpace={activeSpace || null}+ activeSpace={findActiveSpace || null}user={user}><div className="full-layout">diff --git a/apps/web/app/dashboard/settings/Settings.tsx b/apps/web/app/dashboard/settings/Settings.tsxindex 318f68132..c2dcf3e14 100644--- a/apps/web/app/dashboard/settings/Settings.tsx+++ b/apps/web/app/dashboard/settings/Settings.tsx@@ -13,6 +13,7 @@ import {Label,} from "@cap/ui";import { useRouter } from "next/navigation";+import { useState } from "react";import toast from "react-hot-toast";export const Settings = ({@@ -55,59 +56,57 @@ export const Settings = ({return (<form onSubmit={handleSubmit}>- <Card>- <CardHeader>- <CardTitle>Your name</CardTitle>- <CardDescription>- Changing your name below will update how your name appears when- sharing a Cap, and in your profile.- </CardDescription>- </CardHeader>- <CardContent>- <div className="space-y-3">- <div className="flex flex-col items-center">- <Label htmlFor="firstName">First name</Label>- <Input- type="text"- defaultValue={firstName as string}- id="firstName"- name="firstName"- />- </div>- <div className="flex flex-col items-center">- <Label htmlFor="lastName">Last name</Label>- <Input- type="text"- defaultValue={lastName as string}- id="lastName"- name="lastName"- />- </div>+ <CardContent>+ <CardTitle>Your name</CardTitle>+ <CardDescription>+ Changing your name below will update how your name appears when+ sharing a Cap, and in your profile.+ </CardDescription>+ </CardContent>+ <CardContent>+ <div className="space-y-3">+ <div>+ <Label htmlFor="firstName">First name</Label>+ <Input+ type="text"+ defaultValue={firstName as string}+ id="firstName"+ name="firstName"+ /></div>- </CardContent>- <CardHeader>- <CardTitle>Contact email address</CardTitle>- <CardDescription>- This is the email address you used to sign up to Cap with.- </CardDescription>- </CardHeader>- <CardContent><div>+ <Label htmlFor="lastName">Last name</Label><Input- type="email"- value={email as string}- id="contactEmail"- name="contactEmail"- disabled+ type="text"+ defaultValue={lastName as string}+ id="lastName"+ name="lastName"/></div>- </CardContent>- <CardFooter className="border-t px-6 py-4">- <Button type="submit" size="md" variant="gray">- Save- </Button>- </CardFooter>- </Card>+ </div>+ </CardContent>+ <CardContent>+ <CardTitle>Contact email address</CardTitle>+ <CardDescription>+ This is the email address you used to sign up to Cap with.+ </CardDescription>+ </CardContent>+ <CardContent>+ <div>+ <Input+ type="email"+ value={email as string}+ id="contactEmail"+ name="contactEmail"+ disabled+ />+ </div>+ </CardContent>+ <CardFooter className="border-t px-6 py-4">+ <Button type="submit" size="sm" variant="gray">+ Save+ </Button>+ </CardFooter></form>);};diff --git a/apps/web/app/dashboard/settings/billing/Billing.tsx b/apps/web/app/dashboard/settings/billing/Billing.tsxdeleted file mode 100644index 3ab52f883..000000000--- a/apps/web/app/dashboard/settings/billing/Billing.tsx+++ /dev/null@@ -1,65 +0,0 @@-"use client";--import {- Card,- CardContent,- CardDescription,- CardFooter,- CardHeader,- CardTitle,- Button,- Input,- Label,-} from "@cap/ui";-import { users } from "@cap/database/schema";-import { useRouter } from "next/navigation";-import { useState } from "react";--export const Billing = ({- user,-}: {- user: typeof users.$inferSelect | null;-}) => {- const router = useRouter();- const [loading, setLoading] = useState(false);-- return (- <Card>- <CardHeader>- <CardTitle>Billing</CardTitle>- <CardDescription>Manage all things billing.</CardDescription>- </CardHeader>- <CardContent>- <CardTitle>View and manage your billing details</CardTitle>- <CardDescription>- View and edit your billing details, as well as manage your- subscription.- </CardDescription>- <CardDescription className="mt-3">- <Button- type="button"- size="sm"- variant="default"- onClick={() => {- setLoading(true);- fetch(`/api/settings/billing/manage`, {- method: "POST",- })- .then(async (res) => {- const url = await res.json();- router.push(url);- })- .catch((err) => {- alert(err);- setLoading(false);- });- }}- spinner={loading}- >- Manage Billing- </Button>- </CardDescription>- </CardContent>- </Card>- );-};diff --git a/apps/web/app/dashboard/settings/billing/page.tsx b/apps/web/app/dashboard/settings/billing/page.tsxdeleted file mode 100644index b6268d9f0..000000000--- a/apps/web/app/dashboard/settings/billing/page.tsx+++ /dev/null@@ -1,15 +0,0 @@-import { Billing } from "./Billing";-import { getCurrentUser } from "@cap/database/auth/session";-import { Metadata } from "next";--export const metadata: Metadata = {- title: "Billing Settings — Cap",-};--export const revalidate = 0;--export default async function BillingPage() {- const user = await getCurrentUser();-- return <Billing user={user} />;-}diff --git a/apps/web/app/dashboard/settings/layout.tsx b/apps/web/app/dashboard/settings/layout.tsxindex 318dfd8f8..5c0dc3183 100644--- a/apps/web/app/dashboard/settings/layout.tsx+++ b/apps/web/app/dashboard/settings/layout.tsx@@ -1,9 +1,10 @@"use client";+import { Card, CardHeader } from "@cap/ui";import Link from "next/link";import { usePathname } from "next/navigation";-export default async function DashboardLayout({+export default function DashboardLayout({children,}: {children: React.ReactNode;@@ -11,41 +12,35 @@ export default async function DashboardLayout({const pathname = usePathname();const secondaryNavigation = [- { name: "My account", title: "Settings", href: "/dashboard/settings" },- { name: "Billing", title: "Billing", href: "/dashboard/settings/billing" },+ { name: "Account", href: "/dashboard/settings" },+ { name: "Workspace", href: "/dashboard/settings/workspace" },];- const currentPage = secondaryNavigation.find(- (item) => item.href === pathname- );-return (<div>- <header className="border-b border-white/5">- <h1 className="text-3xl">{currentPage?.title ?? "Settings"}</h1>- <nav className="mb-4 flex overflow-x-auto py-4">- <ul- role="list"- className="flex min-w-full flex-none gap-x-6 text-sm leading-6 text-gray-400 p-0"- >- {secondaryNavigation.map((item, index) => (- <li key={index}>- <Link- href={item.href}- className={`${- item.href === pathname- ? "text-black border-black primary font-medium"- : "text-gray-900 opacity-50 hover:opacity-100 border-transparent"- } pb-2 border-b-2`}- >- {item.name}- </Link>- </li>- ))}- </ul>- </nav>- </header>- {children}+ <Card>+ <CardHeader>+ <nav>+ <ul className="inline-flex rounded-lg bg-gray-50 p-1 border-[1px] border-gray-200">+ {secondaryNavigation.map((item) => (+ <li key={item.name}>+ <Link+ href={item.href}+ className={`block rounded-md px-3 py-2 text-xs ${+ item.href === pathname+ ? "bg-gray-200 text-gray-900"+ : "text-gray-500 hover:bg-gray-100 hover:text-gray-900"+ }`}+ >+ {item.name}+ </Link>+ </li>+ ))}+ </ul>+ </nav>+ </CardHeader>+ {children}+ </Card></div>);}diff --git a/apps/web/app/dashboard/settings/workspace/Workspace.tsx b/apps/web/app/dashboard/settings/workspace/Workspace.tsxnew file mode 100644index 000000000..58c291974--- /dev/null+++ b/apps/web/app/dashboard/settings/workspace/Workspace.tsx@@ -0,0 +1,442 @@+"use client";++import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ Button,+ Input,+ Label,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "@cap/ui";+import { useRouter } from "next/navigation";+import { useState, useRef } from "react";+import toast from "react-hot-toast";+import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";+import { format } from "date-fns";+import { Tooltip } from "react-tooltip";++export const Workspace = () => {+ const { spaceData, activeSpace, user } = useSharedContext();+ const workspaceName = activeSpace?.space.name;+ const router = useRouter();+ const [loading, setLoading] = useState(false);+ const isOwner = user?.id === activeSpace?.space.ownerId;+ const [isInviteDialogOpen, setIsInviteDialogOpen] = useState(false);+ const [inviteEmails, setInviteEmails] = useState<string[]>([]);+ const [emailInput, setEmailInput] = useState("");+ const ownerToastShown = useRef(false);++ const showOwnerToast = () => {+ if (!ownerToastShown.current) {+ toast.error("Only the owner can make changes");+ ownerToastShown.current = true;+ setTimeout(() => {+ ownerToastShown.current = false;+ }, 3000);+ }+ };++ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {+ e.preventDefault();++ if (!isOwner) {+ showOwnerToast();+ return;+ }++ const formData = new FormData(e.currentTarget);+ const workspaceName = formData.get("workspaceName") as string;++ try {+ const response = await fetch("/api/settings/workspace/details", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ workspaceName, spaceId: activeSpace?.space.id }),+ });++ if (response.ok) {+ toast.success("Name updated successfully");+ router.refresh();+ } else {+ toast.error("Failed to update name");+ }+ } catch (error) {+ console.error("Error updating name:", error);+ toast.error("An error occurred while updating name");+ }+ };++ const handleAddEmails = () => {+ const newEmails = emailInput+ .split(",")+ .map((email) => email.trim())+ .filter((email) => email !== "");+ setInviteEmails([...new Set([...inviteEmails, ...newEmails])]);+ setEmailInput("");+ };++ const handleRemoveEmail = (email: string) => {+ setInviteEmails(inviteEmails.filter((e) => e !== email));+ };++ const handleSendInvites = async () => {+ if (!isOwner) {+ showOwnerToast();+ return;+ }++ try {+ const response = await fetch("/api/settings/workspace/invite/send", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ invitedEmails: inviteEmails,+ spaceId: activeSpace?.space.id,+ }),+ });++ if (response.ok) {+ toast.success("Invites sent successfully");+ setInviteEmails([]);+ setIsInviteDialogOpen(false);+ router.refresh();+ } else {+ toast.error("Failed to send invites");+ }+ } catch (error) {+ console.error("Error sending invites:", error);+ toast.error("An error occurred while sending invites");+ }+ };++ const handleDeleteInvite = async (inviteId: string) => {+ if (!isOwner) {+ showOwnerToast();+ return;+ }++ try {+ const response = await fetch("/api/settings/workspace/invite/remove", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ inviteId,+ spaceId: activeSpace?.space.id,+ }),+ });++ if (response.ok) {+ toast.success("Invite deleted successfully");+ router.refresh();+ } else {+ toast.error("Failed to delete invite");+ }+ } catch (error) {+ console.error("Error deleting invite:", error);+ toast.error("An error occurred while deleting invite");+ }+ };++ return (+ <form onSubmit={handleSubmit}>+ {isOwner === false && (+ <CardContent>+ <CardTitle>*Only the owner can make changes</CardTitle>+ <CardDescription>+ Only the owner can make changes to this workspace.+ </CardDescription>+ </CardContent>+ )}+ <CardContent>+ <CardTitle>Workspace Details</CardTitle>+ <CardDescription>+ Changing the name and image will update how your workspace appears to+ others members.+ </CardDescription>+ </CardContent>+ <CardContent>+ <div className="space-y-3">+ <div>+ <Label htmlFor="workspaceName">Workspace name</Label>+ <Input+ type="text"+ defaultValue={workspaceName as string}+ id="workspaceName"+ name="workspaceName"+ disabled={!isOwner}+ onChange={() => {+ if (!isOwner) showOwnerToast();+ }}+ />+ </div>+ </div>+ </CardContent>+ <CardFooter className="border-b px-6 pt-0 pb-6">+ <Button+ type="submit"+ size="sm"+ variant="gray"+ disabled={!isOwner}+ onClick={() => {+ if (!isOwner) showOwnerToast();+ }}+ >+ Save+ </Button>+ </CardFooter>+ <CardHeader>+ <div className="flex items-center justify-between">+ <div>+ <CardTitle>Workspace Members</CardTitle>+ <CardDescription>Manage your workspace members.</CardDescription>+ <CardDescription>+ Current seats capacity:{" "}+ {`${activeSpace?.inviteQuota} paid ${+ activeSpace && activeSpace?.inviteQuota > 1+ ? "subscriptions"+ : "subscription"+ } across all of your workspaces`}+ </CardDescription>+ </div>+ </div>+ </CardHeader>+ <CardContent>+ <div className="flex items-center space-x-2">+ <Button+ type="button"+ size="sm"+ variant="primary"+ disabled={!isOwner || loading}+ onClick={() => {+ if (!isOwner) {+ showOwnerToast();+ return;+ }+ setLoading(true);+ fetch(`/api/settings/billing/manage`, {+ method: "POST",+ })+ .then(async (res) => {+ const url = await res.json();+ router.push(url);+ })+ .catch((err) => {+ alert(err);+ setLoading(false);+ });+ }}+ data-tooltip-id="purchase-seats-tooltip"+ data-tooltip-content='Once inside the Stripe dashboard, click "Manage Plan", then increase quantity of subscriptions to purchase more seats.'+ >+ {loading ? "Loading..." : "Purchase more seats"}+ </Button>+ <Tooltip id="purchase-seats-tooltip" place="top" />+ <Button+ type="button"+ size="sm"+ variant="gray"+ onClick={() => {+ if (!isOwner) {+ showOwnerToast();+ } else if (+ activeSpace &&+ activeSpace.inviteQuota <= activeSpace.totalInvites+ ) {+ toast.error("Invite limit reached, please purchase more seats");+ } else {+ setIsInviteDialogOpen(true);+ }+ }}+ disabled={!isOwner}+ >+ Invite users+ </Button>+ </div>+ </CardContent>+ <CardContent>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{"Member"}</TableHead>+ <TableHead>{"Email"}</TableHead>+ <TableHead>{"Role"}</TableHead>+ <TableHead>{"Joined"}</TableHead>+ <TableHead>{"Status"}</TableHead>+ <TableHead>{"Actions"}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {activeSpace?.members &&+ activeSpace.members.map((member) => (+ <TableRow key={member.id}>+ <TableCell>{member.user.name}</TableCell>+ <TableCell>{member.user.email}</TableCell>+ <TableCell>+ {member.user.id === activeSpace?.space.ownerId+ ? "Owner"+ : "Member"}+ </TableCell>+ <TableCell>+ {format(member.createdAt, "MMM d, yyyy")}+ </TableCell>+ <TableCell>Active</TableCell>+ <TableCell>-</TableCell>+ </TableRow>+ ))}+ {activeSpace?.invites &&+ activeSpace.invites.map((invite) => (+ <TableRow key={invite.id}>+ <TableCell>{invite.id}</TableCell>+ <TableCell>{invite.invitedEmail}</TableCell>+ <TableCell>Member</TableCell>+ <TableCell>-</TableCell>+ <TableCell>Invited</TableCell>+ <TableCell>+ <Button+ type="button"+ size="sm"+ variant="destructive"+ onClick={() => {+ if (isOwner) {+ handleDeleteInvite(invite.id);+ } else {+ showOwnerToast();+ }+ }}+ disabled={!isOwner}+ >+ Delete Invite+ </Button>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </CardContent>+ <CardHeader>+ <CardTitle>View and manage your billing details</CardTitle>+ <CardDescription>+ View and edit your billing details, as well as manage your+ subscription.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <CardDescription className="mt-1">+ <Button+ type="button"+ size="sm"+ variant="gray"+ onClick={() => {+ if (!isOwner) {+ showOwnerToast();+ return;+ }+ setLoading(true);+ fetch(`/api/settings/billing/manage`, {+ method: "POST",+ })+ .then(async (res) => {+ const url = await res.json();+ router.push(url);+ })+ .catch((err) => {+ alert(err);+ setLoading(false);+ });+ }}+ disabled={!isOwner}+ >+ {loading ? "Loading..." : "Manage Billing"}+ </Button>+ </CardDescription>+ </CardContent>++ <Dialog open={isInviteDialogOpen} onOpenChange={setIsInviteDialogOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Invite Teammates</DialogTitle>+ <DialogDescription>+ Invite your teammates to join {activeSpace?.space.name} workspace.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div>+ <Label htmlFor="emails">Email</Label>+ <Input+ id="emails"+ value={emailInput}+ onChange={(e) => setEmailInput(e.target.value)}+ placeholder="[email protected]"+ onBlur={handleAddEmails}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === ",") {+ e.preventDefault();+ handleAddEmails();+ }+ }}+ />+ </div>+ <div className="space-y-2">+ {inviteEmails.map((email) => (+ <div+ key={email}+ className="flex items-center justify-between bg-gray-100 p-2 rounded"+ >+ <span>{email}</span>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ onClick={() => handleRemoveEmail(email)}+ disabled={!isOwner}+ >+ Remove+ </Button>+ </div>+ ))}+ </div>+ </div>+ <DialogFooter className="flex justify-between items-center">+ <Button+ type="button"+ variant="white"+ onClick={() => setIsInviteDialogOpen(false)}+ >+ Cancel+ </Button>+ <div className="flex space-x-2">+ <Button+ type="button"+ onClick={handleSendInvites}+ disabled={inviteEmails.length === 0}+ >+ Send Invites+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </form>+ );+};diff --git a/apps/web/app/dashboard/settings/workspace/page.tsx b/apps/web/app/dashboard/settings/workspace/page.tsxnew file mode 100644index 000000000..bd8635cd0--- /dev/null+++ b/apps/web/app/dashboard/settings/workspace/page.tsx@@ -0,0 +1,13 @@+import { Workspace } from "./Workspace";+import { Metadata } from "next";+import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";++export const metadata: Metadata = {+ title: "Workspace Settings — Cap",+};++export const revalidate = 0;++export default async function BillingPage() {+ return <Workspace />;+}diff --git a/apps/web/app/invite/[inviteId]/InviteAccept.tsx b/apps/web/app/invite/[inviteId]/InviteAccept.tsxnew file mode 100644index 000000000..5185c3fa8--- /dev/null+++ b/apps/web/app/invite/[inviteId]/InviteAccept.tsx@@ -0,0 +1,117 @@+"use client";++import { Button, Logo } from "@cap/ui";+import { userSelectProps } from "@cap/database/auth/session";+import { useRouter } from "next/navigation";+import { useState } from "react";+import toast from "react-hot-toast";+import { signOut } from "next-auth/react";+import { LogOut } from "lucide-react";++type InviteAcceptProps = {+ inviteId: string;+ teamName: string;+ inviterName: string;+ user: typeof userSelectProps | null;+};++export function InviteAccept({+ inviteId,+ teamName,+ inviterName,+ user,+}: InviteAcceptProps) {+ const router = useRouter();+ const [isLoading, setIsLoading] = useState(false);++ const handleAccept = async () => {+ setIsLoading(true);+ try {+ if (!user) {+ // Redirect to sign in page with a return URL+ router.push(`/login?next=/invite/${inviteId}`);+ return;+ }++ const response = await fetch("/api/invite/accept", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ inviteId }),+ });++ if (response.ok) {+ toast.success("Invite accepted successfully");+ router.push("/dashboard"); // Redirect to dashboard or appropriate page+ } else {+ const error = await response.text();+ toast.error(`Failed to accept invite: ${error}`);+ }+ } catch (error) {+ console.error("Error accepting invite:", error);+ toast.error("An error occurred while accepting the invite");+ } finally {+ setIsLoading(false);+ }+ };++ const handleDecline = async () => {+ setIsLoading(true);+ try {+ const response = await fetch("/api/invite/decline", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ inviteId }),+ });++ if (response.ok) {+ toast.success("Invite declined");+ router.push("/"); // Redirect to homepage+ } else {+ const error = await response.text();+ toast.error(`Failed to decline invite: ${error}`);+ }+ } catch (error) {+ console.error("Error declining invite:", error);+ toast.error("An error occurred while declining the invite");+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 relative">+ <div className="bg-gray-50 p-4 rounded-[20px] border-[1px] border-gray-200 shadow-[0px 8px 16px rgba(18, 22, 31, 0.04)]">+ <Logo className="w-20 h-auto mb-4" />+ <h1 className="text-xl mb-4">+ You're invited to join <strong>{teamName}</strong> on Cap+ </h1>+ <p className="text-gray-600 text-sm mb-6">+ {inviterName} invited you to join their team on Cap.+ </p>+ <div className="flex space-x-2">+ <Button onClick={handleAccept} variant="primary" disabled={isLoading}>+ {isLoading ? "Processing..." : "Accept"}+ </Button>+ <Button onClick={handleDecline} variant="gray" disabled={isLoading}>+ {isLoading ? "Processing..." : "Decline"}+ </Button>+ </div>+ </div>+ {!user && (+ <Button+ onClick={() => signOut({ callbackUrl: "/login" })}+ size="sm"+ variant="white"+ className="absolute bottom-4 left-4 text-gray-500 hover:text-gray-700"+ >+ <LogOut className="w-4 h-4 mr-2" />+ Sign Out+ </Button>+ )}+ </div>+ );+}diff --git a/apps/web/app/invite/[inviteId]/page.tsx b/apps/web/app/invite/[inviteId]/page.tsxnew file mode 100644index 000000000..728991b5e--- /dev/null+++ b/apps/web/app/invite/[inviteId]/page.tsx@@ -0,0 +1,64 @@+"use server";+import { db } from "@cap/database";+import { eq } from "drizzle-orm";+import { spaceInvites, spaces, users } from "@cap/database/schema";+import { getCurrentUser, userSelectProps } from "@cap/database/auth/session";+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { InviteAccept } from ".//InviteAccept";++type Props = {+ params: { inviteId: string };+};++export async function generateMetadata({ params }: Props): Promise<Metadata> {+ const inviteId = params.inviteId;+ const invite = await getInviteDetails(inviteId);++ if (!invite) {+ return notFound();+ }++ return {+ title: `Join ${invite.spaceName} on Cap`,+ description: `You've been invited to join ${invite.spaceName} on Cap.`,+ };+}++async function getInviteDetails(inviteId: string) {+ const query = await db+ .select({+ invite: spaceInvites,+ spaceName: spaces.name,+ inviterName: users.name,+ })+ .from(spaceInvites)+ .leftJoin(spaces, eq(spaceInvites.spaceId, spaces.id))+ .leftJoin(users, eq(spaceInvites.invitedByUserId, users.id))+ .where(eq(spaceInvites.id, inviteId));++ return query[0];+}++export default async function InvitePage({ params }: Props) {+ const inviteId = params.inviteId;+ const user = await getCurrentUser();+ const inviteDetails = await getInviteDetails(inviteId);++ if (!inviteDetails) {+ return notFound();+ }++ if (!inviteDetails.spaceName || !inviteDetails.inviterName) {+ return notFound();+ }++ return (+ <InviteAccept+ inviteId={inviteId}+ teamName={inviteDetails.spaceName}+ inviterName={inviteDetails.inviterName}+ user={user as typeof userSelectProps | null}+ />+ );+}diff --git a/apps/web/app/onboarding/Onboarding.tsx b/apps/web/app/onboarding/Onboarding.tsxindex 9a68a8361..b8f5df99b 100644--- a/apps/web/app/onboarding/Onboarding.tsx+++ b/apps/web/app/onboarding/Onboarding.tsx@@ -45,15 +45,15 @@ export const Onboarding = ({if (response.ok) {toast.success("Name updated successfully");- router.refresh();+ // Redirect to dashboard after successful onboarding+ router.push("/dashboard");} else {toast.error("Failed to update name");}-- setLoading(false);} catch (error) {console.error("Error updating name:", error);toast.error("An error occurred while updating name");+ } finally {setLoading(false);}};diff --git a/apps/web/app/onboarding/page.tsx b/apps/web/app/onboarding/page.tsxindex c615172a2..e9a06a34b 100644--- a/apps/web/app/onboarding/page.tsx+++ b/apps/web/app/onboarding/page.tsx@@ -8,10 +8,10 @@ export default async function OnboardingPage() {const user = await getCurrentUser();if (- user !== null &&- user.name !== null &&+ user &&+ user.name &&user.name.length > 1 &&- user.activeSpaceId !== null &&+ user.activeSpaceId &&user.activeSpaceId.length > 1) {redirect("/dashboard");@@ -32,7 +32,7 @@ export default async function OnboardingPage() {</p></div><div className="fade-in-down animate-delay-2 flex flex-col space-y-3">- <Onboarding user={user} />+ <Onboarding user={user ?? null} /></div></div></div>diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsxindex 93e5a48ce..2af4faa9d 100644--- a/apps/web/components/Footer.tsx+++ b/apps/web/components/Footer.tsx@@ -9,6 +9,7 @@ export const Footer = () => {if (pathname === "/login" ||pathname.includes("/dashboard") ||+ pathname.includes("/invite") ||pathname.includes("/s/") ||pathname.includes("/onboarding") ||pathname.includes("/record") ||diff --git a/apps/web/components/Navbar.tsx b/apps/web/components/Navbar.tsxindex 362b0f104..a9b054f6c 100644--- a/apps/web/components/Navbar.tsx+++ b/apps/web/components/Navbar.tsx@@ -25,6 +25,7 @@ export const Navbar = ({ auth }: { auth: boolean }) => {if (pathname === "/login" ||pathname.includes("/dashboard") ||+ pathname.includes("/invite") ||pathname.includes("/s/") ||pathname.includes("/onboarding") ||pathname.includes("/record") ||diff --git a/apps/web/components/UsageButton.tsx b/apps/web/components/UsageButton.tsxindex 0cc0e9684..b625e1c62 100644--- a/apps/web/components/UsageButton.tsx+++ b/apps/web/components/UsageButton.tsx@@ -1,29 +1,10 @@-import { useEffect, useState } from "react";import Link from "next/link";-export const UsageButton = () => {- const [isSubscribed, setIsSubscribed] = useState(false);- const [isLoading, setIsLoading] = useState(true);-- useEffect(() => {- fetch("/api/settings/billing/subscription")- .then((response) => response.json())- .then((data) => {- setIsSubscribed(data.subscription);- setIsLoading(false);- });- }, []);-- if (isLoading) {- return (- <div className="w-full h-12 bg-gray-200 rounded-xl py-2 px-4 animate-pulse"></div>- );- }-+export const UsageButton = ({ subscribed }: { subscribed: boolean }) => {return (- <Link href={isSubscribed ? "/dashboard/settings/billing" : "/pricing"}>+ <Link href={subscribed ? "/dashboard/settings/workspace" : "/pricing"}><div className="w-full flex items-center justify-center bg-white border border-gray-200 rounded-xl py-2 px-4 hover:border-blue-500 transition-all">- {isSubscribed ? (+ {subscribed ? (<div className="text-primary font-medium tracking-tighter">Cap Pro</div>diff --git a/apps/web/public/upgrade-demo.gif b/apps/web/public/upgrade-demo.gifnew file mode 100644index 000000000..8b7a8e654Binary files /dev/null and b/apps/web/public/upgrade-demo.gif differdiff --git a/packages/database/emails/workspace-invite.tsx b/packages/database/emails/workspace-invite.tsxnew file mode 100644index 000000000..3fe010db5--- /dev/null+++ b/packages/database/emails/workspace-invite.tsx@@ -0,0 +1,70 @@+import { CAP_LOGO_URL } from "@cap/utils";+import {+ Body,+ Container,+ Head,+ Heading,+ Html,+ Img,+ Link,+ Preview,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";+import Footer from "./components/Footer";++export function WorkspaceInvite({+ email = "",+ url = "",+ workspaceName = "",+}: {+ email: string;+ url: string;+ workspaceName: string;+}) {+ return (+ <Html>+ <Head />+ <Preview>Invitation to join {workspaceName} on Cap</Preview>+ <Tailwind>+ <Body className="mx-auto my-auto bg-white font-sans">+ <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5">+ <Section className="mt-8">+ <Img+ src={CAP_LOGO_URL}+ width="40"+ height="40"+ alt="Cap"+ className="mx-auto my-0"+ />+ </Section>+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">+ You're invited to join {workspaceName}+ </Heading>+ <Text className="text-sm leading-6 text-black">Hello,</Text>+ <Text className="text-sm leading-6 text-black">+ You've been invited to join the {workspaceName} workspace on Cap.+ Click the button below to accept the invitation and join the team.+ </Text>+ <Section className="my-8 text-center">+ <Link+ className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"+ href={url}+ >+ Join Workspace+ </Link>+ </Section>+ <Text className="text-sm leading-6 text-black">+ or copy and paste this URL into your browser:+ </Text>+ <Text className="max-w-sm flex-wrap break-words font-medium text-purple-600 no-underline">+ {url.replace(/^https?:\/\//, "")}+ </Text>+ <Footer email={email} />+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+}diff --git a/packages/database/schema.ts b/packages/database/schema.tsindex 41ae6311c..2d466965c 100644--- a/packages/database/schema.ts+++ b/packages/database/schema.ts@@ -51,6 +51,7 @@ export const users = mysqlTable(updated_at: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),onboarding_completed_at: timestamp("onboarding_completed_at"),customBucket: nanoId("customBucket"),+ inviteQuota: int("inviteQuota").notNull().default(1),},(table) => ({emailIndex: uniqueIndex("email_idx").on(table.email),@@ -143,6 +144,27 @@ export const spaceMembers = mysqlTable(}));+export const spaceInvites = mysqlTable(+ "space_invites",+ {+ id: nanoId("id").notNull().primaryKey().unique(),+ spaceId: nanoId("spaceId").notNull(),+ invitedEmail: varchar("invitedEmail", { length: 255 }).notNull(),+ invitedByUserId: nanoId("invitedByUserId").notNull(),+ role: varchar("role", { length: 255 }).notNull(),+ status: varchar("status", { length: 255 }).notNull().default("pending"),+ createdAt: timestamp("createdAt").notNull().defaultNow(),+ updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),+ expiresAt: timestamp("expiresAt"),+ },+ (table) => ({+ spaceIdIndex: index("space_id_idx").on(table.spaceId),+ invitedEmailIndex: index("invited_email_idx").on(table.invitedEmail),+ invitedByUserIdIndex: index("invited_by_user_id_idx").on(table.invitedByUserId),+ statusIndex: index("status_idx").on(table.status),+ })+);+export const videos = mysqlTable("videos",{@@ -271,6 +293,7 @@ export const spacesRelations = relations(spaces, ({ one, many }) => ({}),spaceMembers: many(spaceMembers),sharedVideos: many(sharedVideos),+ spaceInvites: many(spaceInvites),}));export const sessionsRelations = relations(sessions, ({ one }) => ({@@ -298,6 +321,17 @@ export const spaceMembersRelations = relations(spaceMembers, ({ one }) => ({}),}));+export const spaceInvitesRelations = relations(spaceInvites, ({ one }) => ({+ space: one(spaces, {+ fields: [spaceInvites.spaceId],+ references: [spaces.id],+ }),+ invitedByUser: one(users, {+ fields: [spaceInvites.invitedByUserId],+ references: [users.id],+ }),+}));+export const videosRelations = relations(videos, ({ one, many }) => ({owner: one(users, {fields: [videos.ownerId],diff --git a/packages/ui/src/components/Table.tsx b/packages/ui/src/components/Table.tsxnew file mode 100644index 000000000..158a39f76--- /dev/null+++ b/packages/ui/src/components/Table.tsx@@ -0,0 +1,125 @@+"use client";++import * as React from "react";+import { classNames } from "@cap/utils";++const Table = React.forwardRef<+ HTMLTableElement,+ React.HTMLAttributes<HTMLTableElement>+>(({ className, ...props }, ref) => (+ <div className="relative w-full overflow-auto">+ <table+ ref={ref}+ className={classNames("w-full caption-bottom text-sm", className)}+ {...props}+ />+ </div>+));+Table.displayName = "Table";++const TableHeader = React.forwardRef<+ HTMLTableSectionElement,+ React.HTMLAttributes<HTMLTableSectionElement>+>(({ className, ...props }, ref) => (+ <thead+ ref={ref}+ className={classNames("[&_tr]:border-b", className)}+ {...props}+ />+));+TableHeader.displayName = "TableHeader";++const TableBody = React.forwardRef<+ HTMLTableSectionElement,+ React.HTMLAttributes<HTMLTableSectionElement>+>(({ className, ...props }, ref) => (+ <tbody+ ref={ref}+ className={classNames("[&_tr:last-child]:border-0", className)}+ {...props}+ />+));+TableBody.displayName = "TableBody";++const TableFooter = React.forwardRef<+ HTMLTableSectionElement,+ React.HTMLAttributes<HTMLTableSectionElement>+>(({ className, ...props }, ref) => (+ <tfoot+ ref={ref}+ className={classNames(+ "border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",+ className+ )}+ {...props}+ />+));+TableFooter.displayName = "TableFooter";++const TableRow = React.forwardRef<+ HTMLTableRowElement,+ React.HTMLAttributes<HTMLTableRowElement>+>(({ className, ...props }, ref) => (+ <tr+ ref={ref}+ className={classNames(+ "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",+ className+ )}+ {...props}+ />+));+TableRow.displayName = "TableRow";++const TableHead = React.forwardRef<+ HTMLTableCellElement,+ React.ThHTMLAttributes<HTMLTableCellElement>+>(({ className, ...props }, ref) => (+ <th+ ref={ref}+ className={classNames(+ "h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",+ className+ )}+ {...props}+ />+));+TableHead.displayName = "TableHead";++const TableCell = React.forwardRef<+ HTMLTableCellElement,+ React.TdHTMLAttributes<HTMLTableCellElement>+>(({ className, ...props }, ref) => (+ <td+ ref={ref}+ className={classNames(+ "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",+ className+ )}+ {...props}+ />+));+TableCell.displayName = "TableCell";++const TableCaption = React.forwardRef<+ HTMLTableCaptionElement,+ React.HTMLAttributes<HTMLTableCaptionElement>+>(({ className, ...props }, ref) => (+ <caption+ ref={ref}+ className={classNames("mt-4 text-sm text-muted-foreground", className)}+ {...props}+ />+));+TableCaption.displayName = "TableCaption";++export {+ Table,+ TableHeader,+ TableBody,+ TableFooter,+ TableHead,+ TableRow,+ TableCell,+ TableCaption,+};diff --git a/packages/ui/src/components/input/Input.tsx b/packages/ui/src/components/input/Input.tsxindex ccdf57dc9..1da1489e0 100644--- a/packages/ui/src/components/input/Input.tsx+++ b/packages/ui/src/components/input/Input.tsx@@ -11,7 +11,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(<inputtype={type}className={classNames(- "flex h-11 w-full max-w-[250px] rounded-[8px] border border-gray-200 focus:border-black px-3 h-10 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",+ "flex h-[32px] w-full max-w-[250px] bg-gray-50 rounded-[8px] border-[1px] border-gray-300 focus:border-black px-3 h-10 text-gray-500 ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",className)}ref={ref}diff --git a/packages/ui/src/components/input/Label.tsx b/packages/ui/src/components/input/Label.tsxindex cc6e26f1f..8a0f56d59 100644--- a/packages/ui/src/components/input/Label.tsx+++ b/packages/ui/src/components/input/Label.tsx@@ -7,7 +7,7 @@ import { cva, type VariantProps } from "class-variance-authority";import { classNames } from "@cap/utils";const labelVariants = cva(- "text-sm font-normal text-gray-500 leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 mb-1.5"+ "text-[14px] font-normal text-gray-400 leading-[20px] peer-disabled:cursor-not-allowed peer-disabled:opacity-70 mb-1.5");const Label = React.forwardRef<diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsxindex 2d9f80d69..847f635f5 100644--- a/packages/ui/src/index.tsx+++ b/packages/ui/src/index.tsx@@ -21,6 +21,7 @@ export * from "./components/NavigationMenu";export * from "./components/Dropdown";export * from "./components/Pagination";export * from "./components/Switch";+export * from "./components/Table";// Forms & Inputsexport * from "./components/input/Form";