Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Enterprise #286

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions app/(team)/team/accept-invite/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { CookieOptions, createServerClient } from "@supabase/ssr";

export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
const token = searchParams.get("token");
const next = searchParams.get("next") ?? "/dashboard";

if (token) {
const cookieStore = cookies();
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
return cookieStore.get(name)?.value;
},
set(name: string, value: string, options: CookieOptions) {
cookieStore.set({ name, value, ...options });
},
remove(name: string, options: CookieOptions) {
cookieStore.delete({ name, ...options });
},
},
},
);

const {
data: { session },
} = await supabase.auth.getSession();

if (!session) {
return NextResponse.redirect(
`${origin}/signin?next=/team/accept-invite?token=${token}`,
);
}

try {
const response = await fetch(
`${process.env.PEARAI_SERVER_URL}/team/accept-invite`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session.access_token}`,
},
body: JSON.stringify({ token }),
},
);

if (!response.ok) {
throw new Error("Failed to accept invitation");
}

return NextResponse.redirect(`${origin}${next}`);
} catch (error) {
return NextResponse.redirect(
`${origin}/team/invite-error?error=accept-failed`,
);
}
}

return NextResponse.redirect(`${origin}/team/invite-error?error=no-token`);
}
4 changes: 2 additions & 2 deletions app/api/create-checkout-session/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ async function createCheckoutSession(request: NextRequest & { user: User }) {
const supabase = createClient();

try {
const { priceId } = await request.json();
const { priceId, teamName } = await request.json();
const {
data: { session },
} = await supabase.auth.getSession();
Expand Down Expand Up @@ -65,7 +65,7 @@ async function createCheckoutSession(request: NextRequest & { user: User }) {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ priceId }),
body: JSON.stringify({ priceId, teamName }),
});

if (!response.ok) {
Expand Down
21 changes: 20 additions & 1 deletion app/api/get-requests-usage/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,37 @@ import { withAuth } from "@/utils/withAuth";
import { createClient } from "@/utils/supabase/server";

const getRequestsUsage = async (request: NextRequest) => {
console.log("Starting getRequestsUsage function");
const supabase = createClient();

try {
console.log("Attempting to get session");
const {
data: { session },
} = await supabase.auth.getSession();

if (!session) {
console.log("No session found");
return NextResponse.json(
{ error: "Failed to get session" },
{ status: 401 },
);
}

console.log("Session found, extracting token and user metadata");
const token = session.access_token;
const res = await fetch(`${process.env.PEARAI_SERVER_URL}/get-usage`, {
// const isTeamOwner = session.user.user_metadata.is_team_owner;
const isTeamOwner = false; // TODO: fix this

let endpoint = `${process.env.PEARAI_SERVER_URL}/user-quota-usage`;
if (isTeamOwner) {
console.log("User is team owner, using team quota endpoint");
endpoint = `${process.env.PEARAI_SERVER_URL}/team-quota-usage`;
}
console.log(`Using endpoint: ${endpoint}`);

console.log("Sending request to server");
const res = await fetch(endpoint, {
method: "GET",
headers: {
"Content-Type": "application/json",
Expand All @@ -27,6 +42,7 @@ const getRequestsUsage = async (request: NextRequest) => {
});

if (!res.ok) {
console.log(`Server responded with status: ${res.status}`);
if (res.status === 401) {
return NextResponse.json(
{ error: "Unauthorized. Please log in again." },
Expand All @@ -39,9 +55,12 @@ const getRequestsUsage = async (request: NextRequest) => {
);
}

console.log("Successfully received data from server");
const data = await res.json();
console.log("Data:", data);
return NextResponse.json(data);
} catch (error) {
console.error("Error in getRequestsUsage:", error);
return NextResponse.json(
{ error: "Error getting requests usage" },
{ status: 500 },
Expand Down
84 changes: 84 additions & 0 deletions app/api/team/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/utils/supabase/server";

export async function POST(request: NextRequest) {
const supabase = createClient();
const {
data: { session },
} = await supabase.auth.getSession();

if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

const { teamId, email, role } = await request.json();

try {
const response = await fetch(
`${process.env.PEARAI_SERVER_URL}/team/invite`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session.access_token}`,
},
body: JSON.stringify({ team_id: teamId, email, role }),
},
);

if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || "Failed to send invitation");
}

const data = await response.json();
return NextResponse.json(data);
} catch (error) {
console.error("Error sending invitation:", error);
return NextResponse.json(
{ error: "Failed to send invitation" },
{ status: 500 },
);
}
}

export async function DELETE(request: NextRequest) {
const supabase = createClient();
const {
data: { session },
} = await supabase.auth.getSession();

if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

const { teamId, memberId } = await request.json();

try {
const response = await fetch(
`${process.env.PEARAI_SERVER_URL}/team/member`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session.access_token}`,
},
body: JSON.stringify({ team_id: teamId, member_id: memberId }),
},
);

if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || "Failed to delete member");
}

const data = await response.json();
return NextResponse.json(data);
} catch (error) {
console.error("Error deleting member:", error);
return NextResponse.json(
{ error: "Failed to delete member" },
{ status: 500 },
);
}
}
19 changes: 18 additions & 1 deletion app/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import DashboardPage from "@/components/dashboard";
import { getUserAndSubscription } from "@/lib/data-fetching";
import { getUserAndSubscription, getTeamData } from "@/lib/data-fetching";
import { redirect } from "next/navigation";
import { constructMetadata } from "@/lib/utils";
import { Metadata } from "next/types";
Expand All @@ -22,11 +22,28 @@ export default async function Dashboard() {
return redirect(redirectTo ?? "/signin");
}

let team = null;
let isTeamOwner = false;

if (subscription && subscription.team_id) {
const { team: fetchedTeam, error } = await getTeamData(
subscription.team_id,
);
if (fetchedTeam) {
team = fetchedTeam;
isTeamOwner = team.owner_id === user.id;
} else if (error) {
console.error("Error fetching team data:", error);
}
}

return (
<DashboardPage
subscription={subscription}
openAppQueryParams={openAppQueryParams}
user={user}
team={team}
isTeamOwner={isTeamOwner}
/>
);
}
29 changes: 29 additions & 0 deletions app/dashboard/team/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import EnterpriseDashboard from "@/components/team/enterprise-dashboard";
import { constructMetadata } from "@/lib/utils";
import { Metadata } from "next/types";
import { getUserAndSubscription, getTeamData } from "@/lib/data-fetching";
import { redirect } from "next/navigation";

export const metadata: Metadata = constructMetadata({
title: "Team Dashboard",
description: "Manage your team, members, and roles.",
canonical: "/team/dashboard",
});

export default async function EnterpriseDashboardPage() {
const { user, subscription } = await getUserAndSubscription();

if (!user || !subscription || !subscription.team_id) {
redirect("/dashboard?error=unauthorized");
}

const { team, error } = await getTeamData(subscription.team_id);

if (error || !team) {
redirect("/dashboard?error=team-not-found");
}

return (
<EnterpriseDashboard team={team} user={user} subscription={subscription} />
);
}
45 changes: 45 additions & 0 deletions app/team/new-team/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { createClient } from "@/utils/supabase/server";
import CreateTeamForm from "@/components/team/create-team-form";
import { redirect } from "next/navigation";

export default async function NewTeamPage({
searchParams,
}: {
searchParams: { yearly?: string };
}) {
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();

const initialYearly = searchParams.yearly === "true";

if (!user) {
return <div>Please log in to create a team</div>;
}

const handleSignOut = async () => {
"use server";
const supabase = createClient();
await supabase.auth.signOut();
redirect("/signin");
};

return (
<section
className="relative pt-8 sm:pt-20 md:pt-24 lg:pt-32"
aria-labelledby="create-team-heading"
>
<div className="absolute top-0 z-[-1] mt-[-35px] h-[140px] w-full bg-primary-800/30 blur-3xl"></div>
<div className="mx-auto max-w-7xl px-8 sm:px-6 lg:px-20">
<div className="flex flex-col items-center space-y-6 sm:space-y-8 md:space-y-6 lg:space-y-6">
<CreateTeamForm
user={user}
initialYearly={initialYearly}
handleSignOut={handleSignOut}
/>
</div>
</div>
</section>
);
}
Loading