Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Replace workspace API routes with server actions
Richie McIlroy5ae04e0c9595
diff --git a/apps/web/actions/workspace/check-domain.ts b/apps/web/actions/workspace/check-domain.tsnew file mode 100644index 000000000..8fdb64b13--- /dev/null+++ b/apps/web/actions/workspace/check-domain.ts@@ -0,0 +1,52 @@+'use server';++import { getCurrentUser } from "@cap/database/auth/session";+import { spaces } from "@cap/database/schema";+import { db } from "@cap/database";+import { eq } from "drizzle-orm";+import { checkDomainStatus } from "./domain-utils";++export async function checkWorkspaceDomain(spaceId: string) {+ const user = await getCurrentUser();++ if (!user || !spaceId) {+ throw new Error("Unauthorized");+ }++ const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));++ if (!space || space.ownerId !== user.id) {+ throw new Error("Only the owner can check domain status");+ }++ if (!space.customDomain) {+ throw new Error("No custom domain set");+ }++ try {+ const status = await checkDomainStatus(space.customDomain);++ if (status.verified && !space.domainVerified) {+ await db+ .update(spaces)+ .set({+ domainVerified: new Date(),+ })+ .where(eq(spaces.id, spaceId));+ } else if (!status.verified && space.domainVerified) {+ await db+ .update(spaces)+ .set({+ domainVerified: null,+ })+ .where(eq(spaces.id, spaceId));+ }++ return status;+ } catch (error) {+ if (error instanceof Error) {+ throw new Error(error.message);+ }+ throw new Error("Failed to check domain status");+ }+}\ No newline at end of filediff --git a/apps/web/actions/workspace/domain-utils.ts b/apps/web/actions/workspace/domain-utils.tsnew file mode 100644index 000000000..263b04f0b--- /dev/null+++ b/apps/web/actions/workspace/domain-utils.ts@@ -0,0 +1,185 @@+export const getConfigResponse = async (domain: string) => {+ const response = await fetch(+ `https://api.vercel.com/v6/domains/${domain.toLowerCase()}/config?teamId=${+ process.env.VERCEL_TEAM_ID+ }&strict=true`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,+ "Content-Type": "application/json",+ },+ cache: "no-store",+ }+ ).then((res) => res.json());+ return response;+};++export const getDomainResponse = async (domain: string) => {+ const response = await fetch(+ `https://api.vercel.com/v9/projects/${+ process.env.VERCEL_PROJECT_ID+ }/domains/${domain.toLowerCase()}?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,+ "Content-Type": "application/json",+ },+ cache: "no-store",+ }+ ).then((res) => res.json());+ return response;+};++export const verifyDomain = async (domain: string) => {+ const response = await fetch(+ `https://api.vercel.com/v9/projects/${+ process.env.VERCEL_PROJECT_ID+ }/domains/${domain.toLowerCase()}/verify?teamId=${+ process.env.VERCEL_TEAM_ID+ }&strict=true`,+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,+ "Content-Type": "application/json",+ },+ }+ ).then((res) => res.json());+ return response;+};++export const addDomain = async (domain: string) => {+ const response = await fetch(+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ name: domain }),+ cache: "no-store",+ }+ ).then((res) => res.json());++ return response;+};++export const getRequiredConfig = async (domain: string) => {+ // First try to get the records directly+ try {+ const recordsResponse = await fetch(+ `https://api.vercel.com/v4/domains/${domain.toLowerCase()}/records?limit=10&teamId=${+ process.env.VERCEL_TEAM_ID+ }`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,+ "Content-Type": "application/json",+ },+ cache: "no-store",+ }+ ).then((res) => res.json());++ if (recordsResponse.records) {+ const aRecord = recordsResponse.records.find(+ (record: any) => record.type === "A" && record.name === ""+ );++ if (aRecord) {+ return {+ configuredBy: "vercel",+ aValues: [aRecord.value],+ serviceType: "vercel",+ };+ }+ }+ } catch (error) {+ // Continue to fallback+ }++ // Fallback to the old config endpoint+ const response = await fetch(+ `https://api.vercel.com/v6/domains/${domain.toLowerCase()}/config?teamId=${+ process.env.VERCEL_TEAM_ID+ }`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,+ "Content-Type": "application/json",+ },+ cache: "no-store",+ }+ ).then((res) => res.json());++ // If we still don't have the A record, try the project domains endpoint+ if (!response.aValues || response.aValues.length === 0) {+ const projectResponse = await fetch(+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,+ "Content-Type": "application/json",+ },+ cache: "no-store",+ }+ ).then((res) => res.json());++ if (projectResponse.domains) {+ const projectDomain = projectResponse.domains.find(+ (d: any) => d.name === domain+ );+ if (projectDomain?.apexValue) {+ response.aValues = [projectDomain.apexValue];+ }+ }+ }++ return response;+};++export const checkDomainStatus = async (domain: string) => {+ try {+ const [domainJson, configJson, requiredConfigJson] = await Promise.all([+ getDomainResponse(domain),+ getConfigResponse(domain),+ getRequiredConfig(domain),+ ]);++ let verified = false;++ if (configJson.misconfigured || domainJson?.error?.code === "not_found") {+ verified = false;+ } else if (domainJson.verified) {+ verified = true;+ } else {+ const verificationJson = await verifyDomain(domain);+ verified = verificationJson && verificationJson.verified;+ }++ // Get the current and required A records+ const currentAValues = configJson.aValues || [];+ const requiredAValue = requiredConfigJson.aValues?.[0];++ return {+ verified,+ config: {+ ...configJson,+ verification: domainJson?.verification || [],+ currentAValues,+ requiredAValue,+ },+ status: domainJson,+ };+ } catch (error) {+ return {+ verified: false,+ error: "Failed to check domain status",+ };+ }+};\ No newline at end of filediff --git a/apps/web/actions/workspace/get-space.ts b/apps/web/actions/workspace/get-space.tsnew file mode 100644index 000000000..8ea9b235e--- /dev/null+++ b/apps/web/actions/workspace/get-space.ts@@ -0,0 +1,30 @@+"use server";++import { db } from "@cap/database";+import { spaces } from "@cap/database/schema";+import { eq } from "drizzle-orm";++export async function getSpace(spaceId: string) {+ if (!spaceId) {+ throw new Error("Space ID is required");+ }++ const [space] = await db+ .select({+ workosOrganizationId: spaces.workosOrganizationId,+ workosConnectionId: spaces.workosConnectionId,+ name: spaces.name,+ })+ .from(spaces)+ .where(eq(spaces.id, spaceId));++ if (!space || !space.workosOrganizationId || !space.workosConnectionId) {+ throw new Error("Space not found or SSO not configured");+ }++ return {+ organizationId: space.workosOrganizationId,+ connectionId: space.workosConnectionId,+ name: space.name,+ };+}\ No newline at end of filediff --git a/apps/web/actions/workspace/manage-billing.ts b/apps/web/actions/workspace/manage-billing.tsnew file mode 100644index 000000000..6f91cb77d--- /dev/null+++ b/apps/web/actions/workspace/manage-billing.ts@@ -0,0 +1,42 @@+'use server';++import { stripe } from "@cap/utils";+import { getCurrentUser } from "@cap/database/auth/session";+import { eq } from "drizzle-orm";+import { db } from "@cap/database";+import { users } from "@cap/database/schema";+import { clientEnv } from "@cap/env";++export async function manageBilling() {+ const user = await getCurrentUser();+ let customerId = user?.stripeCustomerId;++ if (!user) {+ throw new Error("Unauthorized");+ }++ if (!user.stripeCustomerId) {+ const customer = await stripe.customers.create({+ email: user.email,+ metadata: {+ userId: user.id,+ },+ });++ await db+ .update(users)+ .set({+ stripeCustomerId: customer.id,+ })+ .where(eq(users.id, user.id));++ customerId = customer.id;+ }++ const { url } = await stripe.billingPortal.sessions.create({+ customer: customerId as string,+ return_url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/settings/workspace`,+ });++ return url;+}\ No newline at end of filediff --git a/apps/web/actions/workspace/remove-domain.ts b/apps/web/actions/workspace/remove-domain.tsnew file mode 100644index 000000000..ec8196905--- /dev/null+++ b/apps/web/actions/workspace/remove-domain.ts@@ -0,0 +1,56 @@+'use server';++import { getCurrentUser } from "@cap/database/auth/session";+import { spaces } from "@cap/database/schema";+import { db } from "@cap/database";+import { eq } from "drizzle-orm";+import { revalidatePath } from "next/cache";++export async function removeWorkspaceDomain(spaceId: string) {+ const user = await getCurrentUser();++ if (!user) {+ throw new Error("Unauthorized");+ }++ const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));++ if (!space || space.ownerId !== user.id) {+ throw new Error("Only the owner can remove the custom domain");+ }++ try {+ if (space.customDomain) {+ await fetch(+ `https://api.vercel.com/v9/projects/${+ process.env.VERCEL_PROJECT_ID+ }/domains/${space.customDomain.toLowerCase()}?teamId=${+ process.env.VERCEL_TEAM_ID+ }`,+ {+ method: "DELETE",+ headers: {+ Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,+ },+ }+ );+ }++ await db+ .update(spaces)+ .set({+ customDomain: null,+ domainVerified: null,+ })+ .where(eq(spaces.id, spaceId));++ revalidatePath('/dashboard/settings/workspace');++ return { success: true };+ } catch (error) {+ if (error instanceof Error) {+ throw new Error(error.message);+ }+ throw new Error("Failed to remove domain");+ }+}\ No newline at end of filediff --git a/apps/web/actions/workspace/remove-invite.ts b/apps/web/actions/workspace/remove-invite.tsnew file mode 100644index 000000000..58d0e2f95--- /dev/null+++ b/apps/web/actions/workspace/remove-invite.ts@@ -0,0 +1,46 @@+'use 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";+import { revalidatePath } from "next/cache";++export async function removeWorkspaceInvite(+ inviteId: string,+ spaceId: string+) {+ const user = await getCurrentUser();++ if (!user) {+ throw new Error("Unauthorized");+ }++ const space = await db+ .select()+ .from(spaces)+ .where(eq(spaces.id, spaceId))+ .limit(1);++ if (!space || space.length === 0) {+ throw new Error("Workspace not found");+ }++ if (space[0]?.ownerId !== user.id) {+ throw new Error("Only the owner can remove workspace invites");+ }++ const result = await db+ .delete(spaceInvites)+ .where(+ and(eq(spaceInvites.id, inviteId), eq(spaceInvites.spaceId, spaceId))+ );++ if (result.rowsAffected === 0) {+ throw new Error("Invite not found");+ }++ revalidatePath('/dashboard/settings/workspace');++ return { success: true };+}\ No newline at end of filediff --git a/apps/web/app/api/settings/workspace/invite/send/route.ts b/apps/web/actions/workspace/send-invites.tssimilarity index 59%rename from apps/web/app/api/settings/workspace/invite/send/route.tsrename to apps/web/actions/workspace/send-invites.tsindex ad41a97a4..5ce774527 100644--- a/apps/web/app/api/settings/workspace/invite/send/route.ts+++ b/apps/web/actions/workspace/send-invites.ts@@ -1,4 +1,5 @@-import { type NextRequest } from "next/server";+'use server';+import { getCurrentUser } from "@cap/database/auth/session";import { spaces, spaceInvites } from "@cap/database/schema";import { db } from "@cap/database";@@ -7,35 +8,30 @@ import { nanoId } from "@cap/database/helpers";import { sendEmail } from "@cap/database/emails/config";import { WorkspaceInvite } from "@cap/database/emails/workspace-invite";import { clientEnv } from "@cap/env";+import { revalidatePath } from "next/cache";-export async function POST(request: NextRequest) {- console.log("POST request received for workspace invite");+export async function sendWorkspaceInvites(+ invitedEmails: string[],+ spaceId: string+) {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 Response.json({ error: true }, { status: 401 });+ throw new Error("Unauthorized");}- 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 Response.json({ error: true }, { status: 404 });+ throw new Error("Workspace not found");}if (space[0]?.ownerId !== user.id) {- console.error(`User ${user.id} is not the owner of space ${spaceId}`);- return Response.json({ error: true }, { status: 403 });+ throw new Error("Only the owner can send workspace invites");}const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;- const validEmails = invitedEmails.filter((email: string) =>+ const validEmails = invitedEmails.filter((email) =>emailRegex.test(email.trim()));@@ -62,6 +58,7 @@ export async function POST(request: NextRequest) {});}- console.log("Workspace invites created and emails sent successfully");- return Response.json(true, { status: 200 });-}+ revalidatePath('/dashboard/settings/workspace');++ return { success: true };+}\ No newline at end of filediff --git a/apps/web/app/api/settings/workspace/details/route.ts b/apps/web/actions/workspace/update-details.tssimilarity index 50%rename from apps/web/app/api/settings/workspace/details/route.tsrename to apps/web/actions/workspace/update-details.tsindex 074ade52a..20632818b 100644--- a/apps/web/app/api/settings/workspace/details/route.ts+++ b/apps/web/actions/workspace/update-details.ts@@ -1,25 +1,30 @@-import { type NextRequest } from "next/server";+'use server';+import { getCurrentUser } from "@cap/database/auth/session";import { spaces } from "@cap/database/schema";import { db } from "@cap/database";import { eq } from "drizzle-orm";+import { revalidatePath } from "next/cache";-export async function POST(request: NextRequest) {+export async function updateWorkspaceDetails(+ workspaceName: string,+ allowedEmailDomain: string,+ spaceId: string+) {const user = await getCurrentUser();- const { workspaceName, allowedEmailDomain, spaceId } = await request.json();if (!user) {- return Response.json({ error: true }, { status: 401 });+ throw new Error("Unauthorized");}const space = await db.select().from(spaces).where(eq(spaces.id, spaceId));- if (!space) {- return Response.json({ error: true }, { status: 404 });+ if (!space || space.length === 0) {+ throw new Error("Workspace not found");}- if (space.length > 0 && space[0]?.ownerId !== user.id) {- return Response.json({ error: true }, { status: 403 });+ if (space[0]?.ownerId !== user.id) {+ throw new Error("Only the owner can update workspace details");}await db@@ -30,5 +35,7 @@ export async function POST(request: NextRequest) {}).where(eq(spaces.id, spaceId));- return Response.json(true, { status: 200 });-}+ revalidatePath('/dashboard/settings/workspace');++ return { success: true };+}\ No newline at end of filediff --git a/apps/web/actions/workspace/update-domain.ts b/apps/web/actions/workspace/update-domain.tsnew file mode 100644index 000000000..c648deadc--- /dev/null+++ b/apps/web/actions/workspace/update-domain.ts@@ -0,0 +1,58 @@+'use server';++import { getCurrentUser } from "@cap/database/auth/session";+import { spaces } from "@cap/database/schema";+import { db } from "@cap/database";+import { eq } from "drizzle-orm";+import { revalidatePath } from "next/cache";+import { addDomain, checkDomainStatus } from "./domain-utils";++export async function updateDomain(domain: string, spaceId: string) {+ const user = await getCurrentUser();++ if (!user) {+ throw new Error("Unauthorized");+ }++ const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));++ if (!space || space.ownerId !== user.id) {+ throw new Error("Only the owner can update the custom domain");+ }++ try {+ const addDomainResponse = await addDomain(domain);++ if (addDomainResponse.error) {+ throw new Error(addDomainResponse.error.message);+ }++ await db+ .update(spaces)+ .set({+ customDomain: domain,+ domainVerified: null,+ })+ .where(eq(spaces.id, spaceId));++ const status = await checkDomainStatus(domain);++ if (status.verified) {+ await db+ .update(spaces)+ .set({+ domainVerified: new Date(),+ })+ .where(eq(spaces.id, spaceId));+ }++ revalidatePath('/dashboard/settings/workspace');++ return status;+ } catch (error) {+ if (error instanceof Error) {+ throw new Error(error.message);+ }+ throw new Error("Failed to update domain");+ }+}\ No newline at end of filediff --git a/apps/web/app/api/settings/workspace/domain/route.ts b/apps/web/app/api/settings/workspace/domain/route.tsdeleted file mode 100644index a666e601d..000000000--- a/apps/web/app/api/settings/workspace/domain/route.ts+++ /dev/null@@ -1,388 +0,0 @@-export const dynamic = "force-dynamic";-export const revalidate = 0;-export const fetchCache = "force-no-store";--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";--const getConfigResponse = async (domain: string) => {- console.log(`[Domain Config] Fetching config for domain: ${domain}`);- const response = await fetch(- `https://api.vercel.com/v6/domains/${domain.toLowerCase()}/config?teamId=${- process.env.VERCEL_TEAM_ID- }&strict=true`,- {- method: "GET",- headers: {- Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,- "Content-Type": "application/json",- },- cache: "no-store",- }- ).then((res) => res.json());- console.log(`[Domain Config] Response:`, response);- return response;-};--const getDomainResponse = async (domain: string) => {- console.log(`[Domain Status] Checking status for domain: ${domain}`);- const response = await fetch(- `https://api.vercel.com/v9/projects/${- process.env.VERCEL_PROJECT_ID- }/domains/${domain.toLowerCase()}?teamId=${process.env.VERCEL_TEAM_ID}`,- {- method: "GET",- headers: {- Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,- "Content-Type": "application/json",- },- cache: "no-store",- }- ).then((res) => res.json());- console.log(`[Domain Status] Response:`, response);- return response;-};--const verifyDomain = async (domain: string) => {- console.log(`[Domain Verify] Verifying domain: ${domain}`);- const response = await fetch(- `https://api.vercel.com/v9/projects/${- process.env.VERCEL_PROJECT_ID- }/domains/${domain.toLowerCase()}/verify?teamId=${- process.env.VERCEL_TEAM_ID- }&strict=true`,- {- method: "POST",- headers: {- Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,- "Content-Type": "application/json",- },- }- ).then((res) => res.json());- console.log(`[Domain Verify] Response:`, response);- return response;-};--const addDomain = async (domain: string) => {- console.log(`[Domain Add] Adding new domain: ${domain}`);- const response = await fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,- {- method: "POST",- headers: {- Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,- "Content-Type": "application/json",- },- body: JSON.stringify({ name: domain }),- cache: "no-store",- }- ).then((res) => res.json());- console.log(`[Domain Add] Response:`, response);- return response;-};--const getRequiredConfig = async (domain: string) => {- console.log(- `[Required Config] Fetching required config for domain: ${domain}`- );-- // First try to get the records directly- try {- const recordsResponse = await fetch(- `https://api.vercel.com/v4/domains/${domain.toLowerCase()}/records?limit=10&teamId=${- process.env.VERCEL_TEAM_ID- }`,- {- method: "GET",- headers: {- Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,- "Content-Type": "application/json",- },- cache: "no-store",- }- ).then((res) => res.json());-- console.log(`[Required Config] Records Response:`, recordsResponse);-- if (recordsResponse.records) {- const aRecord = recordsResponse.records.find(- (record: any) => record.type === "A" && record.name === ""- );-- if (aRecord) {- return {- configuredBy: "vercel",- aValues: [aRecord.value],- serviceType: "vercel",- };- }- }- } catch (error) {- console.error("[Required Config] Error fetching records:", error);- }-- // Fallback to the old config endpoint- const response = await fetch(- `https://api.vercel.com/v6/domains/${domain.toLowerCase()}/config?teamId=${- process.env.VERCEL_TEAM_ID- }`,- {- method: "GET",- headers: {- Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,- "Content-Type": "application/json",- },- cache: "no-store",- }- ).then((res) => res.json());- console.log(`[Required Config] Fallback Response:`, response);-- // If we still don't have the A record, try the project domains endpoint- if (!response.aValues || response.aValues.length === 0) {- const projectResponse = await fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,- {- method: "GET",- headers: {- Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,- "Content-Type": "application/json",- },- cache: "no-store",- }- ).then((res) => res.json());-- if (projectResponse.domains) {- const projectDomain = projectResponse.domains.find(- (d: any) => d.name === domain- );- if (projectDomain?.apexValue) {- response.aValues = [projectDomain.apexValue];- }- }- }-- return response;-};--async function checkDomainStatus(domain: string) {- console.log(`[Domain Check] Checking domain status for: ${domain}`);- try {- const [domainJson, configJson, requiredConfigJson] = await Promise.all([- getDomainResponse(domain),- getConfigResponse(domain),- getRequiredConfig(domain),- ]);-- let verified = false;-- if (configJson.misconfigured || domainJson?.error?.code === "not_found") {- verified = false;- } else if (domainJson.verified) {- verified = true;- } else {- const verificationJson = await verifyDomain(domain);- verified = verificationJson && verificationJson.verified;- }-- // Get the current and required A records- const currentAValues = configJson.aValues || [];- const requiredAValue = requiredConfigJson.aValues?.[0];-- return {- verified,- config: {- ...configJson,- verification: domainJson?.verification || [],- currentAValues,- requiredAValue,- },- status: domainJson,- };- } catch (error) {- console.error("[Domain Check] Error checking domain status:", error);- return {- verified: false,- error: "Failed to check domain status",- };- }-}--export async function POST(request: NextRequest) {- console.log("[POST] Processing domain addition request");- const user = await getCurrentUser();- const { domain, spaceId } = await request.json();- console.log(- `[POST] Request details - Domain: ${domain}, SpaceId: ${spaceId}`- );-- if (!user) {- console.log("[POST] Unauthorized - No user found");- return Response.json({ error: "Unauthorized" }, { status: 401 });- }-- const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));-- if (!space || space.ownerId !== user.id) {- console.log("[POST] Unauthorized - Invalid space or ownership");- return Response.json({ error: "Unauthorized" }, { status: 403 });- }-- try {- console.log(`[POST] Adding domain to Vercel: ${domain}`);- const addDomainResponse = await addDomain(domain);-- if (addDomainResponse.error) {- console.error("[POST] Error adding domain:", addDomainResponse.error);- return Response.json(- { error: addDomainResponse.error.message },- { status: 400 }- );- }-- console.log(`[POST] Updating space with custom domain: ${domain}`);- await db- .update(spaces)- .set({- customDomain: domain,- domainVerified: null,- })- .where(eq(spaces.id, spaceId));-- console.log("[POST] Checking domain verification status");- const status = await checkDomainStatus(domain);-- if (status.verified) {- console.log(- `[POST] Domain verified, updating verification timestamp: ${domain}`- );- await db- .update(spaces)- .set({- domainVerified: new Date(),- })- .where(eq(spaces.id, spaceId));- }-- return Response.json(status);- } catch (error) {- console.error("[POST] Error in domain verification:", error);- return Response.json({ error: "Failed to verify domain" }, { status: 500 });- }-}--export async function DELETE(request: NextRequest) {- console.log("[DELETE] Processing domain removal request");- const user = await getCurrentUser();- const { spaceId } = await request.json();- console.log(`[DELETE] Request details - SpaceId: ${spaceId}`);-- if (!user) {- console.log("[DELETE] Unauthorized - No user found");- return Response.json({ error: "Unauthorized" }, { status: 401 });- }-- const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));-- if (!space || space.ownerId !== user.id) {- console.log("[DELETE] Unauthorized - Invalid space or ownership");- return Response.json({ error: "Unauthorized" }, { status: 403 });- }-- try {- if (space.customDomain) {- console.log(- `[DELETE] Removing domain from Vercel: ${space.customDomain}`- );- await fetch(- `https://api.vercel.com/v9/projects/${- process.env.VERCEL_PROJECT_ID- }/domains/${space.customDomain.toLowerCase()}?teamId=${- process.env.VERCEL_TEAM_ID- }`,- {- method: "DELETE",- headers: {- Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,- },- }- );- }-- console.log("[DELETE] Updating space to remove custom domain");- await db- .update(spaces)- .set({- customDomain: null,- domainVerified: null,- })- .where(eq(spaces.id, spaceId));-- return Response.json({ success: true });- } catch (error) {- console.error("[DELETE] Error removing domain:", error);- return Response.json({ error: "Failed to remove domain" }, { status: 500 });- }-}--export async function GET(request: NextRequest) {- console.log("[GET] Processing domain status check request");- const searchParams = request.nextUrl.searchParams;- const spaceId = searchParams.get("spaceId");- console.log(`[GET] Request details - SpaceId: ${spaceId}`);- const user = await getCurrentUser();-- if (!user || !spaceId) {- console.log("[GET] Unauthorized - No user or spaceId found");- return Response.json({ error: "Unauthorized" }, { status: 401 });- }-- const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));-- if (!space || space.ownerId !== user.id) {- console.log("[GET] Unauthorized - Invalid space or ownership");- return Response.json({ error: "Unauthorized" }, { status: 403 });- }-- if (!space.customDomain) {- console.log("[GET] No custom domain set for space");- return Response.json({ error: "No custom domain set" }, { status: 400 });- }-- try {- console.log(`[GET] Checking status for domain: ${space.customDomain}`);- const status = await checkDomainStatus(space.customDomain);-- if (status.verified && !space.domainVerified) {- console.log(- `[GET] Updating domain verification timestamp: ${space.customDomain}`- );- await db- .update(spaces)- .set({- domainVerified: new Date(),- })- .where(eq(spaces.id, spaceId));- } else if (!status.verified && space.domainVerified) {- console.log(- `[GET] Removing domain verification timestamp: ${space.customDomain}`- );- await db- .update(spaces)- .set({- domainVerified: null,- })- .where(eq(spaces.id, spaceId));- }-- return Response.json(status);- } catch (error) {- console.error("[GET] Error checking domain status:", error);- return Response.json(- { error: "Failed to check domain status" },- { status: 500 }- );- }-}diff --git a/apps/web/app/api/settings/workspace/invite/remove/route.ts b/apps/web/app/api/settings/workspace/invite/remove/route.tsdeleted file mode 100644index f1cb355e4..000000000--- a/apps/web/app/api/settings/workspace/invite/remove/route.ts+++ /dev/null@@ -1,50 +0,0 @@-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 Response.json({ error: true }, { status: 401 });- }-- 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 Response.json({ error: true }, { status: 404 });- }-- if (space[0]?.ownerId !== user.id) {- console.error(`User ${user.id} is not the owner of space ${spaceId}`);- return Response.json({ error: true }, { status: 403 });- }-- 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 Response.json({ error: true }, { status: 404 });- }-- console.log("Workspace invite removed successfully");- return Response.json({ success: true }, { status: 200 });-}diff --git a/apps/web/app/api/settings/workspace/lookup/route.ts b/apps/web/app/api/settings/workspace/lookup/route.tsdeleted file mode 100644index 1004e34c0..000000000--- a/apps/web/app/api/settings/workspace/lookup/route.ts+++ /dev/null@@ -1,48 +0,0 @@-import { type NextRequest } from "next/server";-import { db } from "@cap/database";-import { spaces } from "@cap/database/schema";-import { eq } from "drizzle-orm";--export async function GET(request: NextRequest) {- console.log("[workspace/lookup] Received request");- const searchParams = new URL(request.url).searchParams;- const spaceId = searchParams.get("spaceId");-- if (!spaceId) {- console.log("[workspace/lookup] Missing spaceId parameter");- return Response.json(- { error: "Space ID parameter is required" },- { status: 400 }- );- }-- console.log("[workspace/lookup] Looking up space:", spaceId);- const [space] = await db- .select({- workosOrganizationId: spaces.workosOrganizationId,- workosConnectionId: spaces.workosConnectionId,- name: spaces.name,- })- .from(spaces)- .where(eq(spaces.id, spaceId));-- console.log("[workspace/lookup] Found space:", space);-- if (!space || !space.workosOrganizationId || !space.workosConnectionId) {- console.log("[workspace/lookup] Space not found or missing SSO config");- return Response.json(- { error: "Space not found or SSO not configured" },- { status: 404 }- );- }-- console.log("[workspace/lookup] Found space:", space.name);- return Response.json(- {- organizationId: space.workosOrganizationId,- connectionId: space.workosConnectionId,- name: space.name,- },- { status: 200 }- );-}diff --git a/apps/web/app/api/settings/workspace/sso/route.ts b/apps/web/app/api/settings/workspace/sso/route.tsdeleted file mode 100644index 49caad572..000000000--- a/apps/web/app/api/settings/workspace/sso/route.ts+++ /dev/null@@ -1,31 +0,0 @@-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) {- const user = await getCurrentUser();- const { spaceId, workosOrganizationId, workosConnectionId } =- await request.json();-- if (!user) {- return Response.json({ error: "Unauthorized" }, { status: 401 });- }-- const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));-- if (!space || space.ownerId !== user.id) {- return Response.json({ error: "Unauthorized" }, { status: 403 });- }-- await db- .update(spaces)- .set({- workosOrganizationId,- workosConnectionId,- })- .where(eq(spaces.id, spaceId));-- return Response.json({ success: true }, { status: 200 });-}diff --git a/apps/web/app/dashboard/settings/workspace/Workspace.tsx b/apps/web/app/dashboard/settings/workspace/Workspace.tsxindex bddbfce61..ff89986ac 100644--- a/apps/web/app/dashboard/settings/workspace/Workspace.tsx+++ b/apps/web/app/dashboard/settings/workspace/Workspace.tsx@@ -30,6 +30,10 @@ import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayouimport { format } from "date-fns";import { Tooltip } from "react-tooltip";import { CustomDomain } from "./components/CustomDomain";+import { updateWorkspaceDetails } from "@/actions/workspace/update-details";+import { sendWorkspaceInvites } from "@/actions/workspace/send-invites";+import { removeWorkspaceInvite } from "@/actions/workspace/remove-invite";+import { manageBilling } from "@/actions/workspace/manage-billing";export const Workspace = () => {const { spaceData, activeSpace, user } = useSharedContext();@@ -65,24 +69,13 @@ export const Workspace = () => {const allowedEmailDomain = formData.get("allowedEmailDomain") as string;try {- const response = await fetch("/api/settings/workspace/details", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- workspaceName,- allowedEmailDomain,- spaceId: activeSpace?.space.id,- }),- });-- if (response.ok) {- toast.success("Settings updated successfully");- router.refresh();- } else {- toast.error("Failed to update settings");- }+ await updateWorkspaceDetails(+ workspaceName,+ allowedEmailDomain,+ activeSpace?.space.id as string+ );+ toast.success("Settings updated successfully");+ router.refresh();} catch (error) {console.error("Error updating settings:", error);toast.error("An error occurred while updating settings");@@ -109,25 +102,11 @@ export const Workspace = () => {}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");- }+ await sendWorkspaceInvites(inviteEmails, activeSpace?.space.id as string);+ toast.success("Invites sent successfully");+ setInviteEmails([]);+ setIsInviteDialogOpen(false);+ router.refresh();} catch (error) {console.error("Error sending invites:", error);toast.error("An error occurred while sending invites");@@ -141,29 +120,32 @@ export const Workspace = () => {}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");- }+ await removeWorkspaceInvite(inviteId, activeSpace?.space.id as string);+ toast.success("Invite deleted successfully");+ router.refresh();} catch (error) {console.error("Error deleting invite:", error);toast.error("An error occurred while deleting invite");}};+ const handleManageBilling = async () => {+ if (!isOwner) {+ showOwnerToast();+ return;+ }++ setLoading(true);+ try {+ const url = await manageBilling();+ router.push(url);+ } catch (error) {+ console.error("Error managing billing:", error);+ toast.error("An error occurred while managing billing");+ setLoading(false);+ }+ };+return (<form onSubmit={handleSubmit}>{isOwner === false && (@@ -271,24 +253,7 @@ export const Workspace = () => {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);- });- }}+ onClick={handleManageBilling}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.'>@@ -390,24 +355,7 @@ export const Workspace = () => {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);- });- }}+ onClick={handleManageBilling}disabled={!isOwner}>{loading ? "Loading..." : "Manage Billing"}diff --git a/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx b/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsxindex 9dbb976b6..7f48c18e4 100644--- a/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx+++ b/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx@@ -8,6 +8,9 @@ import { toast } from "react-hot-toast";import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";import { RefreshCw, CheckCircle, XCircle, Copy, Check } from "lucide-react";import { useRouter } from "next/navigation";+import { updateDomain } from "@/actions/workspace/update-domain";+import { checkWorkspaceDomain } from "@/actions/workspace/check-domain";+import { removeWorkspaceDomain } from "@/actions/workspace/remove-domain";type DomainVerification = {type: string;@@ -90,20 +93,7 @@ export function CustomDomain() {if (!activeSpace?.space.id || !activeSpace?.space.customDomain) return;setVerifying(true);try {- const response = await fetch(- `/api/settings/workspace/domain?spaceId=${activeSpace.space.id}`,- {- cache: "no-store",- next: {- revalidate: 0,- },- }- );- const data = await response.json();-- if (!response.ok) {- throw new Error(data.error || "Failed to check domain verification");- }+ const data = await checkWorkspaceDomain(activeSpace.space.id);setIsVerified(data.verified);setDomainConfig(data.config);@@ -204,20 +194,10 @@ export function CustomDomain() {setDomain(cleanedDomain); // Update the input to show the cleaned domaintry {- const response = await fetch("/api/settings/workspace/domain", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- domain: cleanedDomain,- spaceId: activeSpace?.space.id,- }),- });-- const data = await response.json();-- if (!response.ok) {- throw new Error(data.error || "Failed to update domain");- }+ const data = await updateDomain(+ cleanedDomain,+ activeSpace?.space.id as string+ );toast.success("Domain settings updated");router.refresh();@@ -273,17 +253,7 @@ export function CustomDomain() {setLoading(true);try {- const response = await fetch("/api/settings/workspace/domain", {- method: "DELETE",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- spaceId: activeSpace?.space.id,- }),- });-- if (!response.ok) {- throw new Error("Failed to remove domain");- }+ await removeWorkspaceDomain(activeSpace?.space.id as string);// Clear polling when domain is removedif (pollInterval.current) {diff --git a/apps/web/app/login/form.tsx b/apps/web/app/login/form.tsxindex de23eabae..3e27df2cc 100644--- a/apps/web/app/login/form.tsx+++ b/apps/web/app/login/form.tsx@@ -8,6 +8,7 @@ import { toast } from "react-hot-toast";import { Input, Label } from "@cap/ui";import { NODE_ENV } from "@cap/env";import { trackEvent } from "../utils/analytics";+import { getSpace } from "@/actions/workspace/get-space";export function LoginForm() {const searchParams = useSearchParams();@@ -84,14 +85,8 @@ export function LoginForm() {}try {- const response = await fetch(- `/api/settings/workspace/lookup?spaceId=${encodeURIComponent(spaceId)}`- );- const data = await response.json();-- if (!response.ok) {- throw new Error(data.error || "Failed to look up workspace");- }+ const data = await getSpace(spaceId);+ setSpaceName(data.name);signIn("workos", undefined, {organization: data.organizationId,