working on onboarding flow
This commit is contained in:
parent
868eaa5e3d
commit
d3a36b6103
Binary file not shown.
84
apps/admin/src/app/api/admin/clients/route.ts
Normal file
84
apps/admin/src/app/api/admin/clients/route.ts
Normal file
@ -0,0 +1,84 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
/**
|
||||
* GET /api/admin/clients
|
||||
*
|
||||
* Admin:
|
||||
* - Lists clients scoped to the admin's gym (requires admin.gymId).
|
||||
*
|
||||
* SuperAdmin:
|
||||
* - Optional query param ?gymId=<id> to filter clients by a specific gym.
|
||||
* - If no gymId provided, returns all clients across all gyms.
|
||||
*
|
||||
* Response: Array of client users with minimal fields for listing, including membership data.
|
||||
*/
|
||||
export async function GET(req: Request) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) {
|
||||
return new NextResponse("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const user = await ensureUserSynced(userId, db);
|
||||
|
||||
if (!user || (user.role !== "admin" && user.role !== "superAdmin")) {
|
||||
return new NextResponse("Forbidden", { status: 403 });
|
||||
}
|
||||
|
||||
const url = new URL(req.url);
|
||||
const requestedGymId = url.searchParams.get("gymId");
|
||||
|
||||
// Admins must have a gymId; scope to their gym
|
||||
let targetGymId: string | null = null;
|
||||
if (user.role === "admin") {
|
||||
if (!user.gymId) {
|
||||
return new NextResponse("Admin gymId not set", { status: 400 });
|
||||
}
|
||||
targetGymId = user.gymId;
|
||||
} else if (user.role === "superAdmin") {
|
||||
targetGymId = requestedGymId;
|
||||
}
|
||||
|
||||
// Fetch users and clients
|
||||
const allUsers = await db.getAllUsers();
|
||||
const usersById = new Map(allUsers.map((u) => [u.id, u]));
|
||||
const allClients = await db.getAllClients();
|
||||
|
||||
// Scope clients by gym when provided
|
||||
const scopedClients = targetGymId
|
||||
? allClients.filter((c) => {
|
||||
const u = usersById.get(c.userId);
|
||||
return u?.gymId === targetGymId;
|
||||
})
|
||||
: allClients;
|
||||
|
||||
// Compose payload merging user and client info
|
||||
const payload = scopedClients.map((c) => {
|
||||
const u = usersById.get(c.userId);
|
||||
return {
|
||||
id: c.id,
|
||||
userId: c.userId,
|
||||
email: u?.email ?? null,
|
||||
firstName: u?.firstName ?? null,
|
||||
lastName: u?.lastName ?? null,
|
||||
gymId: u?.gymId ?? null,
|
||||
membershipType: c.membershipType,
|
||||
membershipStatus: c.membershipStatus,
|
||||
joinDate: c.joinDate,
|
||||
lastVisit: c.lastVisit ?? null,
|
||||
emergencyContact: c.emergencyContact ?? null,
|
||||
createdAt: u?.createdAt ?? null,
|
||||
updatedAt: u?.updatedAt ?? null,
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json(payload);
|
||||
} catch (error) {
|
||||
console.error("GET /api/admin/clients error:", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
166
apps/admin/src/app/api/admin/set-user-metadata/route.ts
Normal file
166
apps/admin/src/app/api/admin/set-user-metadata/route.ts
Normal file
@ -0,0 +1,166 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth, clerkClient } from "@clerk/nextjs/server";
|
||||
|
||||
/**
|
||||
* POST /api/admin/set-user-metadata
|
||||
*
|
||||
* Sets Clerk publicMetadata.role and publicMetadata.gymId for a target user.
|
||||
*
|
||||
* Authorization:
|
||||
* - Caller must be an admin or superAdmin (based on their Clerk publicMetadata.role).
|
||||
*
|
||||
* Request body:
|
||||
* {
|
||||
* "targetUserId": string, // Clerk user ID of the target
|
||||
* "role": "superAdmin" | "admin" | "trainer" | "client" | "generalUser", // optional
|
||||
* "gymId": string | null // optional; null clears gym assignment
|
||||
* }
|
||||
*
|
||||
* Behavior:
|
||||
* - If "role" is provided, update the target user's publicMetadata.role.
|
||||
* - If "gymId" is provided (including null), update publicMetadata.gymId.
|
||||
* - Validates inputs and permissions.
|
||||
*
|
||||
* Response:
|
||||
* - 200 with updated minimal user data
|
||||
* - 400/401/403/404/500 on errors
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
// Authenticate the requester
|
||||
const { userId } = await auth();
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const client = await clerkClient();
|
||||
|
||||
// Fetch requester from Clerk to verify permissions
|
||||
const requester = await client.users.getUser(userId);
|
||||
const requesterRole =
|
||||
(requester.publicMetadata?.role as
|
||||
| "superAdmin"
|
||||
| "admin"
|
||||
| "trainer"
|
||||
| "client"
|
||||
| "generalUser") ?? "client";
|
||||
|
||||
// Only admin or superAdmin can set metadata
|
||||
if (requesterRole !== "admin" && requesterRole !== "superAdmin") {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden: admin or superAdmin access required" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Parse body
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body || typeof body !== "object") {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid JSON body" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const targetUserId = typeof body.targetUserId === "string" ? body.targetUserId : null;
|
||||
const role = body.role as
|
||||
| "superAdmin"
|
||||
| "admin"
|
||||
| "trainer"
|
||||
| "client"
|
||||
| "generalUser"
|
||||
| undefined;
|
||||
const gymId =
|
||||
body.gymId === null
|
||||
? null
|
||||
: typeof body.gymId === "string"
|
||||
? body.gymId
|
||||
: undefined;
|
||||
|
||||
if (!targetUserId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid or missing targetUserId" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate role if provided
|
||||
const allowedRoles = ["superAdmin", "admin", "trainer", "client", "generalUser"] as const;
|
||||
if (role && !allowedRoles.includes(role)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid role. Must be one of superAdmin, admin, trainer, client, generalUser" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Prevent non-superAdmin from assigning superAdmin
|
||||
if (role === "superAdmin" && requesterRole !== "superAdmin") {
|
||||
return NextResponse.json(
|
||||
{ error: "Only superAdmin can assign superAdmin role" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch target user to ensure they exist
|
||||
let targetUser;
|
||||
try {
|
||||
targetUser = await client.users.getUser(targetUserId);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Target user not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Construct new metadata by merging with existing
|
||||
const newPublicMetadata: Record<string, unknown> = {
|
||||
...(targetUser.publicMetadata || {}),
|
||||
};
|
||||
|
||||
if (role !== undefined) {
|
||||
newPublicMetadata.role = role;
|
||||
}
|
||||
if (gymId !== undefined) {
|
||||
newPublicMetadata.gymId = gymId;
|
||||
}
|
||||
|
||||
// Ensure at least one field to update
|
||||
if (role === undefined && gymId === undefined) {
|
||||
return NextResponse.json(
|
||||
{ error: "Provide at least one of 'role' or 'gymId' to update" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Perform update on Clerk
|
||||
const updatedUser = await client.users.updateUser(targetUserId, {
|
||||
publicMetadata: newPublicMetadata,
|
||||
});
|
||||
|
||||
// Construct response payload
|
||||
const primaryEmail =
|
||||
updatedUser.emailAddresses?.find(
|
||||
(e) => e.id === updatedUser.primaryEmailAddressId
|
||||
)?.emailAddress || updatedUser.emailAddresses?.[0]?.emailAddress || null;
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
message: "User metadata updated",
|
||||
user: {
|
||||
id: updatedUser.id,
|
||||
email: primaryEmail,
|
||||
firstName: updatedUser.firstName,
|
||||
lastName: updatedUser.lastName,
|
||||
role: updatedUser.publicMetadata?.role ?? null,
|
||||
gymId: updatedUser.publicMetadata?.gymId ?? null,
|
||||
},
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error: any) {
|
||||
const message =
|
||||
error?.errors?.[0]?.message ||
|
||||
error?.message ||
|
||||
"Internal server error";
|
||||
console.error("Error setting user metadata:", error);
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@ -1,25 +1,59 @@
|
||||
import { auth } from '@clerk/nextjs/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getDatabase } from '@/lib/database'
|
||||
import { ensureUserSynced } from '@/lib/sync-user'
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const { userId } = await auth()
|
||||
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
|
||||
export async function GET(req: Request) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase()
|
||||
const user = await ensureUserSynced(userId, db)
|
||||
const db = await getDatabase();
|
||||
const user = await ensureUserSynced(userId, db);
|
||||
|
||||
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
|
||||
return new NextResponse('Forbidden', { status: 403 })
|
||||
}
|
||||
|
||||
const stats = await db.getDashboardStats()
|
||||
|
||||
return NextResponse.json(stats)
|
||||
} catch (error) {
|
||||
console.error('Dashboard stats error:', error)
|
||||
return new NextResponse('Internal Server Error', { status: 500 })
|
||||
if (!user || (user.role !== "admin" && user.role !== "superAdmin")) {
|
||||
return new NextResponse("Forbidden", { status: 403 });
|
||||
}
|
||||
if (user.role === "admin" && !user.gymId) {
|
||||
return new NextResponse("Admin gymId not set", { status: 400 });
|
||||
}
|
||||
|
||||
const url = new URL(req.url);
|
||||
const searchParams = url.searchParams;
|
||||
|
||||
let targetGymId: string | null = null;
|
||||
if (user.role === "admin") {
|
||||
targetGymId = user.gymId ?? null;
|
||||
} else if (user.role === "superAdmin") {
|
||||
targetGymId = searchParams.get("gymId");
|
||||
}
|
||||
|
||||
const allUsers = await db.getAllUsers();
|
||||
const allClients = await db.getAllClients();
|
||||
|
||||
const usersById = new Map(allUsers.map((u) => [u.id, u]));
|
||||
const filteredUsers = targetGymId
|
||||
? allUsers.filter((u) => u.gymId === targetGymId)
|
||||
: allUsers;
|
||||
const filteredClients = targetGymId
|
||||
? allClients.filter((c) => {
|
||||
const u = usersById.get(c.userId);
|
||||
return u?.gymId === targetGymId;
|
||||
})
|
||||
: allClients;
|
||||
|
||||
const stats = {
|
||||
totalUsers: filteredUsers.length,
|
||||
activeClients: filteredClients.filter(
|
||||
(c) => c.membershipStatus === "active",
|
||||
).length,
|
||||
totalRevenue: 0,
|
||||
revenueGrowth: 0,
|
||||
};
|
||||
|
||||
return NextResponse.json(stats);
|
||||
} catch (error) {
|
||||
console.error("Dashboard stats error:", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
71
apps/admin/src/app/api/admin/trainers/route.ts
Normal file
71
apps/admin/src/app/api/admin/trainers/route.ts
Normal file
@ -0,0 +1,71 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
/**
|
||||
* GET /api/admin/trainers
|
||||
*
|
||||
* Admin:
|
||||
* - Lists trainers scoped to the admin's gym (requires admin.gymId).
|
||||
*
|
||||
* SuperAdmin:
|
||||
* - Optional query param ?gymId=<id> to filter trainers by a specific gym.
|
||||
* - If no gymId provided, returns all trainers across all gyms.
|
||||
*
|
||||
* Response: Array of trainer users with minimal fields for listing
|
||||
*/
|
||||
export async function GET(req: Request) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) {
|
||||
return new NextResponse("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const user = await ensureUserSynced(userId, db);
|
||||
|
||||
if (!user || (user.role !== "admin" && user.role !== "superAdmin")) {
|
||||
return new NextResponse("Forbidden", { status: 403 });
|
||||
}
|
||||
|
||||
const url = new URL(req.url);
|
||||
const requestedGymId = url.searchParams.get("gymId");
|
||||
|
||||
// Admins must have a gymId; scope to their gym
|
||||
let targetGymId: string | null = null;
|
||||
if (user.role === "admin") {
|
||||
if (!user.gymId) {
|
||||
return new NextResponse("Admin gymId not set", { status: 400 });
|
||||
}
|
||||
targetGymId = user.gymId;
|
||||
} else if (user.role === "superAdmin") {
|
||||
targetGymId = requestedGymId;
|
||||
}
|
||||
|
||||
// Fetch all users and filter to trainers
|
||||
const allUsers = await db.getAllUsers();
|
||||
let trainers = allUsers.filter((u) => u.role === "trainer");
|
||||
|
||||
// Scope by gym when required/provided
|
||||
if (targetGymId) {
|
||||
trainers = trainers.filter((t) => t.gymId === targetGymId);
|
||||
}
|
||||
|
||||
// Minimal payload suitable for listing
|
||||
const payload = trainers.map((t) => ({
|
||||
id: t.id,
|
||||
email: t.email,
|
||||
firstName: t.firstName,
|
||||
lastName: t.lastName,
|
||||
gymId: t.gymId ?? null,
|
||||
createdAt: t.createdAt,
|
||||
updatedAt: t.updatedAt,
|
||||
}));
|
||||
|
||||
return NextResponse.json(payload);
|
||||
} catch (error) {
|
||||
console.error("GET /api/admin/trainers error:", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
174
apps/admin/src/app/api/gyms/route.ts
Normal file
174
apps/admin/src/app/api/gyms/route.ts
Normal file
@ -0,0 +1,174 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { eq, sql } from "@fitai/database";
|
||||
import { db, users as usersTable } from "@fitai/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
async function ensureGymsTable() {
|
||||
await db.run(sql`
|
||||
CREATE TABLE IF NOT EXISTS gyms (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
location TEXT,
|
||||
status TEXT NOT NULL CHECK (status IN ('active','inactive')) DEFAULT 'active',
|
||||
admin_user_id TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`);
|
||||
}
|
||||
|
||||
// GET /api/gyms
|
||||
// Lists active gyms for selection (grid)
|
||||
export async function GET() {
|
||||
try {
|
||||
await ensureGymsTable();
|
||||
const rows = await db.all(
|
||||
sql`SELECT * FROM gyms WHERE status = 'active' ORDER BY created_at DESC`,
|
||||
);
|
||||
|
||||
return NextResponse.json(rows);
|
||||
} catch (error) {
|
||||
console.error("GET /gyms error:", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/gyms
|
||||
// Create a gym. Allowed roles: superAdmin, admin.
|
||||
// - admin: can only create gyms for themselves (adminUserId = current user)
|
||||
// - superAdmin: can create for self or specify adminUserId
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
await ensureGymsTable();
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
// Ensure our local DB has the user synced (role, etc.)
|
||||
const currentUser = await ensureUserSynced(userId, {
|
||||
// minimal facade for ensureUserSynced to work: it expects an object implementing part of IDatabase
|
||||
getUserById: async (id: string) => {
|
||||
const row = await db
|
||||
.select()
|
||||
.from(usersTable)
|
||||
.where(eq(usersTable.id, id))
|
||||
.get();
|
||||
return row
|
||||
? {
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
firstName: row.firstName,
|
||||
lastName: row.lastName,
|
||||
password: row.password ?? "",
|
||||
phone: row.phone ?? undefined,
|
||||
role: row.role,
|
||||
imageUrl: undefined,
|
||||
createdAt: new Date(row.createdAt),
|
||||
updatedAt: new Date(row.updatedAt),
|
||||
}
|
||||
: null;
|
||||
},
|
||||
updateUser: async (id: string, updates: any) => {
|
||||
await db
|
||||
.update(usersTable)
|
||||
.set({
|
||||
...updates,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(usersTable.id, id))
|
||||
.run();
|
||||
const row = await db
|
||||
.select()
|
||||
.from(usersTable)
|
||||
.where(eq(usersTable.id, id))
|
||||
.get();
|
||||
return row
|
||||
? {
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
firstName: row.firstName,
|
||||
lastName: row.lastName,
|
||||
password: row.password ?? "",
|
||||
phone: row.phone ?? undefined,
|
||||
role: row.role,
|
||||
imageUrl: undefined,
|
||||
createdAt: new Date(row.createdAt),
|
||||
updatedAt: new Date(row.updatedAt),
|
||||
}
|
||||
: null;
|
||||
},
|
||||
} as any);
|
||||
|
||||
if (
|
||||
!currentUser ||
|
||||
(currentUser.role !== "admin" && currentUser.role !== "superAdmin")
|
||||
) {
|
||||
return new NextResponse("Forbidden", { status: 403 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body || typeof body !== "object") {
|
||||
return new NextResponse("Invalid JSON body", { status: 400 });
|
||||
}
|
||||
|
||||
const name = String(body.name ?? "").trim();
|
||||
const location = body.location ? String(body.location).trim() : null;
|
||||
let adminUserId: string | null = body.adminUserId
|
||||
? String(body.adminUserId)
|
||||
: null;
|
||||
|
||||
if (!name) {
|
||||
return NextResponse.json({ error: "name is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Enforce admin ownership rules
|
||||
if (currentUser.role === "admin") {
|
||||
adminUserId = currentUser.id;
|
||||
} else if (currentUser.role === "superAdmin") {
|
||||
adminUserId = adminUserId || currentUser.id;
|
||||
}
|
||||
|
||||
// Basic check that adminUserId exists and is an admin or superAdmin
|
||||
const adminRow = await db
|
||||
.select()
|
||||
.from(usersTable)
|
||||
.where(eq(usersTable.id, adminUserId!))
|
||||
.get();
|
||||
if (
|
||||
!adminRow ||
|
||||
(adminRow.role !== "admin" && adminRow.role !== "superAdmin")
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "adminUserId must reference an admin or superAdmin" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const id = generateId();
|
||||
const nowTs = Date.now();
|
||||
|
||||
await db.run(
|
||||
sql`INSERT INTO gyms (id, name, location, status, admin_user_id, created_at, updated_at)
|
||||
VALUES (${id}, ${name}, ${location ?? null}, 'active', ${adminUserId!}, ${nowTs}, ${nowTs})`,
|
||||
);
|
||||
|
||||
// Assign the admin to this gym immediately after creation
|
||||
await db.run(
|
||||
sql`UPDATE users SET gym_id = ${id}, updated_at = ${nowTs} WHERE id = ${adminUserId!}`,
|
||||
);
|
||||
|
||||
const created = await db.get(sql`SELECT * FROM gyms WHERE id = ${id}`);
|
||||
return NextResponse.json(created, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error("POST /gyms error:", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
function generateId(): string {
|
||||
// Simple URL-safe id generator
|
||||
return (
|
||||
Math.random().toString(36).slice(2, 10) +
|
||||
Math.random().toString(36).slice(2, 10)
|
||||
);
|
||||
}
|
||||
148
apps/admin/src/app/api/invitations/route.ts
Normal file
148
apps/admin/src/app/api/invitations/route.ts
Normal file
@ -0,0 +1,148 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth, clerkClient } from "@clerk/nextjs/server";
|
||||
|
||||
/**
|
||||
* POST /api/invitations
|
||||
*
|
||||
* Create a Clerk-managed invitation and store role/gym context in publicMetadata.
|
||||
* This endpoint does not implement invitation acceptance; Clerk’s acceptance link flow and webhooks will handle that.
|
||||
*
|
||||
* Body: {
|
||||
* inviteeEmail: string,
|
||||
* roleAssigned: 'trainer' | 'client' | 'admin'
|
||||
* }
|
||||
*
|
||||
* Rules:
|
||||
* - admin: can invite trainer or client; the gymId is taken from inviter's publicMetadata or user record.
|
||||
* - trainer: can invite client; the gymId is taken from inviter's publicMetadata or user record.
|
||||
* - superAdmin: can invite admin; requires `gymId` in body, or falls back to inviter's `gymId` if present.
|
||||
*
|
||||
* Returns Clerk invitation payload.
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) {
|
||||
return new NextResponse("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body || typeof body !== "object") {
|
||||
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
const inviteeEmail = String(body.inviteeEmail ?? "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const roleAssigned = String(body.roleAssigned ?? "").trim() as
|
||||
| "trainer"
|
||||
| "client"
|
||||
| "admin";
|
||||
let requestedGymId: string | null = body.gymId ? String(body.gymId) : null;
|
||||
|
||||
if (!inviteeEmail || !roleAssigned) {
|
||||
return NextResponse.json(
|
||||
{ error: "inviteeEmail and roleAssigned are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch inviter user from Clerk
|
||||
const client = await clerkClient();
|
||||
const inviter = await client.users.getUser(userId);
|
||||
const inviterRole =
|
||||
(inviter.publicMetadata?.role as
|
||||
| "superAdmin"
|
||||