Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0817e8e72b | ||
|
|
b1f01208fa | ||
|
|
d112dbb122 | ||
|
|
7043487fc2 |
No files matched your search
@@ -14,6 +14,10 @@ RESEND_API_KEY=re_your_resend_api_key_here
|
|||||||
EMAIL_FROM=FitAI <noreply@yourdomain.com>
|
EMAIL_FROM=FitAI <noreply@yourdomain.com>
|
||||||
EMAIL_REPLY_TO=support@yourdomain.com
|
EMAIL_REPLY_TO=support@yourdomain.com
|
||||||
|
|
||||||
|
# Admin App URL (for invitation redirects)
|
||||||
|
# Set to your production URL in production
|
||||||
|
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||||
|
|
||||||
# Database (optional - defaults to ./fitai.db)
|
# Database (optional - defaults to ./fitai.db)
|
||||||
DATABASE_PATH=./fitai.db
|
DATABASE_PATH=./fitai.db
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -0,0 +1,89 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { auth, clerkClient } from "@clerk/nextjs/server";
|
||||||
|
import log from "@/lib/logger";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/invitations/[id]/resend
|
||||||
|
*
|
||||||
|
* Resend an invitation with same parameters
|
||||||
|
*/
|
||||||
|
export async function POST(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> },
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { userId } = await auth();
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id: invitationId } = await params;
|
||||||
|
|
||||||
|
// Fetch pending invitations to find the one being resent
|
||||||
|
const client = await clerkClient();
|
||||||
|
const invitationList = await client.invitations.getInvitationList({
|
||||||
|
status: "pending",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Find the invitation
|
||||||
|
const invitation = invitationList.data.find(
|
||||||
|
(inv) => inv.id === invitationId,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!invitation) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Invitation not found or already processed" },
|
||||||
|
{ status: 404 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const metadata = invitation.publicMetadata as any;
|
||||||
|
|
||||||
|
// Check if current user created this invitation
|
||||||
|
if (metadata?.createdBy !== userId) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Forbidden - You can only resend invitations you created" },
|
||||||
|
{ status: 403 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create new invitation with same parameters
|
||||||
|
const role = metadata?.role;
|
||||||
|
|
||||||
|
// Determine redirect URL based on role
|
||||||
|
const isStaffRole = ["admin", "trainer", "superAdmin"].includes(role);
|
||||||
|
const redirectUrl = isStaffRole
|
||||||
|
? `${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"}/sign-up`
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const newInvitation = await client.invitations.createInvitation({
|
||||||
|
emailAddress: invitation.emailAddress,
|
||||||
|
publicMetadata: invitation.publicMetadata || undefined,
|
||||||
|
redirectUrl,
|
||||||
|
ignoreExisting: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
log.info("Invitation resent", {
|
||||||
|
originalId: invitationId,
|
||||||
|
newId: newInvitation.id,
|
||||||
|
email: invitation.emailAddress,
|
||||||
|
resentBy: userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
data: {
|
||||||
|
invitation: {
|
||||||
|
id: newInvitation.id,
|
||||||
|
email: newInvitation.emailAddress,
|
||||||
|
status: newInvitation.status,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
log.error("POST /api/invitations/[id]/resend error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to resend invitation" },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { auth, clerkClient } from "@clerk/nextjs/server";
|
||||||
|
import log from "@/lib/logger";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DELETE /api/invitations/[id]
|
||||||
|
*
|
||||||
|
* Revoke a pending invitation (creator-only permission)
|
||||||
|
*/
|
||||||
|
export async function DELETE(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> },
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { userId } = await auth();
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id: invitationId } = await params;
|
||||||
|
|
||||||
|
// Fetch pending invitations to find and verify the one being revoked
|
||||||
|
const client = await clerkClient();
|
||||||
|
const invitationList = await client.invitations.getInvitationList({
|
||||||
|
status: "pending",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Find the invitation
|
||||||
|
const invitation = invitationList.data.find(
|
||||||
|
(inv) => inv.id === invitationId,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!invitation) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Invitation not found or already processed" },
|
||||||
|
{ status: 404 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const metadata = invitation.publicMetadata as any;
|
||||||
|
|
||||||
|
// Check if current user created this invitation
|
||||||
|
if (metadata?.createdBy !== userId) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Forbidden - You can only cancel invitations you created" },
|
||||||
|
{ status: 403 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke the invitation
|
||||||
|
await client.invitations.revokeInvitation(invitationId);
|
||||||
|
|
||||||
|
log.info("Invitation revoked", {
|
||||||
|
invitationId,
|
||||||
|
revokedBy: userId,
|
||||||
|
email: invitation.emailAddress,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
data: { success: true },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
log.error("DELETE /api/invitations/[id] error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to revoke invitation" },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,90 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { auth, clerkClient } from "@clerk/nextjs/server";
|
import { auth, clerkClient } from "@clerk/nextjs/server";
|
||||||
|
import { getAuthContext } from "@/lib/auth/context";
|
||||||
|
import { validateGymAccess } from "@/lib/auth/permissions";
|
||||||
|
import log from "@/lib/logger";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/invitations
|
||||||
|
*
|
||||||
|
* Fetch pending invitations with gym and creator filtering.
|
||||||
|
* Users can only see invitations they created, scoped to their gym access.
|
||||||
|
*
|
||||||
|
* Query params:
|
||||||
|
* - gymId: Optional gym filter (superAdmin only)
|
||||||
|
*/
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const { userId } = await auth();
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get auth context
|
||||||
|
const authContext = await getAuthContext();
|
||||||
|
const { role, gymId: userGymId } = authContext;
|
||||||
|
|
||||||
|
// Get query params
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const gymIdParam = searchParams.get("gymId");
|
||||||
|
|
||||||
|
// Validate gym access
|
||||||
|
const targetGymId = gymIdParam || undefined;
|
||||||
|
const accessError = validateGymAccess(role, userGymId, targetGymId);
|
||||||
|
if (accessError) return accessError;
|
||||||
|
|
||||||
|
// Fetch all pending invitations from Clerk
|
||||||
|
const client = await clerkClient();
|
||||||
|
const invitationList = await client.invitations.getInvitationList({
|
||||||
|
status: "pending",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Filter invitations based on:
|
||||||
|
// 1. Creator (only show invitations created by current user)
|
||||||
|
// 2. Gym (apply gym-scoping rules)
|
||||||
|
const filteredInvitations = invitationList.data
|
||||||
|
.filter((inv) => {
|
||||||
|
const metadata = inv.publicMetadata as any;
|
||||||
|
|
||||||
|
// Creator filter: only show if user created it
|
||||||
|
if (metadata?.createdBy !== userId) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gym filter: SuperAdmin can see all, others only their gym
|
||||||
|
if (role === "superAdmin") {
|
||||||
|
// If gymId param provided, filter by it
|
||||||
|
if (targetGymId && metadata?.gymId !== targetGymId) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
// Non-superAdmins: must match their gym
|
||||||
|
return metadata?.gymId === userGymId;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map((inv) => ({
|
||||||
|
id: inv.id,
|
||||||
|
emailAddress: inv.emailAddress,
|
||||||
|
publicMetadata: inv.publicMetadata,
|
||||||
|
status: inv.status,
|
||||||
|
url: inv.url,
|
||||||
|
createdAt: inv.createdAt,
|
||||||
|
updatedAt: inv.updatedAt,
|
||||||
|
revoked: inv.revoked,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
data: { invitations: filteredInvitations },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
log.error("GET /api/invitations error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Failed to fetch invitations" },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /api/invitations
|
* POST /api/invitations
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import {
|
|||||||
errorResponse,
|
errorResponse,
|
||||||
unauthorizedResponse,
|
unauthorizedResponse,
|
||||||
} from "@/lib/api/responses";
|
} from "@/lib/api/responses";
|
||||||
|
import { getAuthContext } from "@/lib/auth/context";
|
||||||
|
import { getInvitableRoles } from "@/lib/auth/permissions";
|
||||||
import log from "@/lib/logger";
|
import log from "@/lib/logger";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,6 +28,10 @@ export async function POST(request: NextRequest) {
|
|||||||
return unauthorizedResponse("Unauthorized");
|
return unauthorizedResponse("Unauthorized");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get full auth context (role and gymId)
|
||||||
|
const authContext = await getAuthContext();
|
||||||
|
const { role: requesterRole, gymId: requesterGymId } = authContext;
|
||||||
|
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const validationResult = createUserSchema.safeParse(body);
|
const validationResult = createUserSchema.safeParse(body);
|
||||||
|
|
||||||
@@ -41,6 +47,33 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
const data = validationResult.data;
|
const data = validationResult.data;
|
||||||
|
|
||||||
|
// Validate role creation permission
|
||||||
|
const allowedRoles = getInvitableRoles(requesterRole);
|
||||||
|
if (!allowedRoles.includes(data.role)) {
|
||||||
|
const roleMessages: Record<string, string> = {
|
||||||
|
trainer:
|
||||||
|
"Trainers can only create clients. Contact an admin to create other roles.",
|
||||||
|
admin:
|
||||||
|
"Admins can create trainers and clients only. Contact a superAdmin to create other admins.",
|
||||||
|
client: "Clients cannot create users.",
|
||||||
|
};
|
||||||
|
return errorResponse(
|
||||||
|
roleMessages[requesterRole] ||
|
||||||
|
"You are not authorized to create this role",
|
||||||
|
{ status: 403 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-assign gym for non-superAdmins
|
||||||
|
// SuperAdmins can choose any gym, others must use their own gym
|
||||||
|
const assignedGymId =
|
||||||
|
requesterRole === "superAdmin" ? data.gymId : requesterGymId;
|
||||||
|
|
||||||
|
// Validate that non-superAdmins have a gym assigned
|
||||||
|
if (!assignedGymId && requesterRole !== "superAdmin") {
|
||||||
|
return errorResponse("You are not assigned to a gym", { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
// Note: Email is required in current schema
|
// Note: Email is required in current schema
|
||||||
// TODO: Add schema migration to make email optional for direct creation
|
// TODO: Add schema migration to make email optional for direct creation
|
||||||
if (!data.email) {
|
if (!data.email) {
|
||||||
@@ -51,18 +84,39 @@ export async function POST(request: NextRequest) {
|
|||||||
if (data.sendInvitation && data.email) {
|
if (data.sendInvitation && data.email) {
|
||||||
try {
|
try {
|
||||||
const client = await clerkClient();
|
const client = await clerkClient();
|
||||||
|
|
||||||
|
// Build publicMetadata - only include gymId if it exists
|
||||||
|
const publicMetadata: Record<string, any> = {
|
||||||
|
role: data.role,
|
||||||
|
createdBy: userId,
|
||||||
|
};
|
||||||
|
if (assignedGymId) {
|
||||||
|
publicMetadata.gymId = assignedGymId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine redirect URL based on role
|
||||||
|
// Staff (admin, trainer, superAdmin) → Admin web app
|
||||||
|
// Clients → Mobile app (handled by Clerk's default)
|
||||||
|
const isStaffRole = ["admin", "trainer", "superAdmin"].includes(
|
||||||
|
data.role,
|
||||||
|
);
|
||||||
|
const redirectUrl = isStaffRole
|
||||||
|
? `${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"}/sign-up`
|
||||||
|
: undefined; // Clients use default Clerk redirect
|
||||||
|
|
||||||
const invitation = await client.invitations.createInvitation({
|
const invitation = await client.invitations.createInvitation({
|
||||||
emailAddress: data.email,
|
emailAddress: data.email,
|
||||||
publicMetadata: {
|
publicMetadata,
|
||||||
role: data.role,
|
redirectUrl,
|
||||||
gymId: data.gymId,
|
ignoreExisting: true, // Don't fail if invitation already exists
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
log.info("Clerk invitation sent", {
|
log.info("Clerk invitation sent", {
|
||||||
email: data.email,
|
email: data.email,
|
||||||
role: data.role,
|
role: data.role,
|
||||||
|
gymId: assignedGymId,
|
||||||
invitationId: invitation.id,
|
invitationId: invitation.id,
|
||||||
|
redirectUrl: redirectUrl || "default (mobile app)",
|
||||||
});
|
});
|
||||||
|
|
||||||
// Send custom invitation email (in addition to Clerk's)
|
// Send custom invitation email (in addition to Clerk's)
|
||||||
@@ -83,7 +137,22 @@ export async function POST(request: NextRequest) {
|
|||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
const errorMessage =
|
const errorMessage =
|
||||||
error instanceof Error ? error.message : "Unknown error";
|
error instanceof Error ? error.message : "Unknown error";
|
||||||
log.error("Failed to send Clerk invitation", error);
|
|
||||||
|
// Extract Clerk-specific error details
|
||||||
|
const clerkError = error as any;
|
||||||
|
|
||||||
|
log.error("Failed to send Clerk invitation", error, {
|
||||||
|
email: data.email,
|
||||||
|
role: data.role,
|
||||||
|
gymId: assignedGymId,
|
||||||
|
publicMetadata: assignedGymId
|
||||||
|
? { role: data.role, gymId: assignedGymId }
|
||||||
|
: { role: data.role },
|
||||||
|
clerkStatus: clerkError?.status,
|
||||||
|
clerkErrors: clerkError?.errors,
|
||||||
|
clerkTraceId: clerkError?.clerkTraceId,
|
||||||
|
});
|
||||||
|
|
||||||
return errorResponse(`Failed to send invitation: ${errorMessage}`, {
|
return errorResponse(`Failed to send invitation: ${errorMessage}`, {
|
||||||
status: 500,
|
status: 500,
|
||||||
});
|
});
|
||||||
@@ -106,13 +175,14 @@ export async function POST(request: NextRequest) {
|
|||||||
lastName: data.lastName,
|
lastName: data.lastName,
|
||||||
role: data.role,
|
role: data.role,
|
||||||
phone: data.phone,
|
phone: data.phone,
|
||||||
gymId: data.gymId,
|
gymId: assignedGymId,
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
log.info("User created in database", {
|
log.info("User created in database", {
|
||||||
userId: newUser.id,
|
userId: newUser.id,
|
||||||
role: data.role,
|
role: data.role,
|
||||||
|
gymId: assignedGymId,
|
||||||
hasEmail: !!data.email,
|
hasEmail: !!data.email,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -331,8 +331,17 @@ export async function PUT(request: NextRequest) {
|
|||||||
return validationErrorResponse(validation.errors);
|
return validationErrorResponse(validation.errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { id, email, firstName, lastName, role, phone, gymId } =
|
const {
|
||||||
validation.data;
|
id,
|
||||||
|
email,
|
||||||
|
firstName,
|
||||||
|
lastName,
|
||||||
|
role,
|
||||||
|
phone,
|
||||||
|
gymId,
|
||||||
|
membershipType,
|
||||||
|
membershipStatus,
|
||||||
|
} = validation.data;
|
||||||
|
|
||||||
log.debug("Updating user", {
|
log.debug("Updating user", {
|
||||||
id,
|
id,
|
||||||
@@ -342,6 +351,8 @@ export async function PUT(request: NextRequest) {
|
|||||||
role,
|
role,
|
||||||
phone,
|
phone,
|
||||||
gymId,
|
gymId,
|
||||||
|
membershipType,
|
||||||
|
membershipStatus,
|
||||||
});
|
});
|
||||||
|
|
||||||
const db = await getDatabase();
|
const db = await getDatabase();
|
||||||
@@ -363,6 +374,27 @@ export async function PUT(request: NextRequest) {
|
|||||||
return notFoundResponse("User not found");
|
return notFoundResponse("User not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.debug("Edit authorization check", {
|
||||||
|
requesterId,
|
||||||
|
requesterRole: requester.role,
|
||||||
|
requesterGymId: requester.gymId,
|
||||||
|
targetUserId: id,
|
||||||
|
targetRole: existingUser.role,
|
||||||
|
targetGymId: existingUser.gymId,
|
||||||
|
requestedRole: role,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Authorization: check gym-based permissions
|
||||||
|
// Non-superAdmins can only edit users in their own gym
|
||||||
|
if (requester.role !== "superAdmin") {
|
||||||
|
if (!requester.gymId) {
|
||||||
|
return forbiddenResponse("No gym assigned to requester");
|
||||||
|
}
|
||||||
|
if (existingUser.gymId !== requester.gymId) {
|
||||||
|
return forbiddenResponse("Cannot edit users from other gyms");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Authorization: determine allowed role changes
|
// Authorization: determine allowed role changes
|
||||||
const requesterRole = requester.role;
|
const requesterRole = requester.role;
|
||||||
const allowedByRole: Record<string, string[]> = {
|
const allowedByRole: Record<string, string[]> = {
|
||||||
@@ -373,10 +405,27 @@ export async function PUT(request: NextRequest) {
|
|||||||
generalUser: [], // general users cannot change roles
|
generalUser: [], // general users cannot change roles
|
||||||
};
|
};
|
||||||
|
|
||||||
if (role && !allowedByRole[requesterRole]?.includes(role)) {
|
// Only check authorization if the role is actually being changed
|
||||||
|
if (
|
||||||
|
role &&
|
||||||
|
role !== existingUser.role &&
|
||||||
|
!allowedByRole[requesterRole]?.includes(role)
|
||||||
|
) {
|
||||||
return forbiddenResponse(`Not authorized to assign role '${role}'`);
|
return forbiddenResponse(`Not authorized to assign role '${role}'`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Authorization: trainers and admins cannot reassign users to different gyms
|
||||||
|
// Only superAdmins can reassign gyms
|
||||||
|
if (
|
||||||
|
requesterRole !== "superAdmin" &&
|
||||||
|
gymId !== undefined &&
|
||||||
|
gymId !== existingUser.gymId
|
||||||
|
) {
|
||||||
|
return forbiddenResponse(
|
||||||
|
"Only superAdmins can reassign users to different gyms",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Check if email is being changed and if it's already taken
|
// Check if email is being changed and if it's already taken
|
||||||
if (email && email !== existingUser.email) {
|
if (email && email !== existingUser.email) {
|
||||||
const userWithEmail = await db.getUserByEmail(email);
|
const userWithEmail = await db.getUserByEmail(email);
|
||||||
@@ -387,24 +436,27 @@ export async function PUT(request: NextRequest) {
|
|||||||
|
|
||||||
// Update Clerk publicMetadata (role/gymId) to propagate via webhook
|
// Update Clerk publicMetadata (role/gymId) to propagate via webhook
|
||||||
// Note: Only update metadata when a change is requested
|
// Note: Only update metadata when a change is requested
|
||||||
try {
|
const client = await clerkClient();
|
||||||
const client = await clerkClient();
|
const publicMetadata: Record<string, unknown> = {};
|
||||||
const publicMetadata: Record<string, unknown> = {};
|
log.debug("Preparing Clerk metadata update", {
|
||||||
log.debug("Preparing Clerk metadata update", {
|
targetUserId: id,
|
||||||
targetUserId: id,
|
role,
|
||||||
role,
|
gymId,
|
||||||
gymId,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
if (role) {
|
if (role) {
|
||||||
publicMetadata.role = role;
|
publicMetadata.role = role;
|
||||||
}
|
}
|
||||||
if (gymId !== undefined) {
|
if (gymId !== undefined) {
|
||||||
publicMetadata.gymId = gymId === null ? null : String(gymId);
|
publicMetadata.gymId = gymId === null ? null : String(gymId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (Object.keys(publicMetadata).length > 0) {
|
||||||
|
log.debug("Updating Clerk user metadata", { publicMetadata });
|
||||||
|
try {
|
||||||
|
// Check if user exists in Clerk first
|
||||||
|
await client.users.getUser(id);
|
||||||
|
|
||||||
if (Object.keys(publicMetadata).length > 0) {
|
|
||||||
log.debug("Updating Clerk user metadata", { publicMetadata });
|
|
||||||
const clerkResult = await client.users.updateUser(id, {
|
const clerkResult = await client.users.updateUser(id, {
|
||||||
publicMetadata,
|
publicMetadata,
|
||||||
});
|
});
|
||||||
@@ -413,14 +465,20 @@ export async function PUT(request: NextRequest) {
|
|||||||
role: clerkResult.publicMetadata?.role,
|
role: clerkResult.publicMetadata?.role,
|
||||||
gymId: clerkResult.publicMetadata?.gymId,
|
gymId: clerkResult.publicMetadata?.gymId,
|
||||||
});
|
});
|
||||||
} else {
|
} catch (clerkErr: any) {
|
||||||
log.debug("No Clerk metadata changes requested");
|
// User might not exist in Clerk yet - that's OK for local users
|
||||||
|
if (
|
||||||
|
clerkErr?.status === 404 ||
|
||||||
|
clerkErr?.errors?.[0]?.code === "resource_not_found"
|
||||||
|
) {
|
||||||
|
log.debug(
|
||||||
|
"User not found in Clerk, skipping metadata update (local-only user)",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
log.error("Clerk metadata update failed", clerkErr, { userId: id });
|
||||||
|
// Don't fail the whole request - local DB update can still proceed
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (clerkErr: any) {
|
|
||||||
log.error("Clerk metadata update failed", clerkErr, { userId: id });
|
|
||||||
return internalErrorResponse(
|
|
||||||
"Failed to update role/gym in identity provider",
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update local DB for immediate UI feedback (webhook will also sync)
|
// Update local DB for immediate UI feedback (webhook will also sync)
|
||||||
@@ -442,6 +500,43 @@ export async function PUT(request: NextRequest) {
|
|||||||
);
|
);
|
||||||
log.debug("User updated in database", { updatedRow });
|
log.debug("User updated in database", { updatedRow });
|
||||||
|
|
||||||
|
// If the user is a client, update membership fields in clients table
|
||||||
|
const finalRole = role ?? existingUser.role;
|
||||||
|
if (
|
||||||
|
finalRole === "client" &&
|
||||||
|
(membershipType !== undefined || membershipStatus !== undefined)
|
||||||
|
) {
|
||||||
|
log.debug("Updating client membership fields", {
|
||||||
|
userId: id,
|
||||||
|
membershipType,
|
||||||
|
membershipStatus,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Check if client record exists
|
||||||
|
const existingClient = await rawDb.get(
|
||||||
|
sql`SELECT * FROM clients WHERE user_id = ${id}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existingClient) {
|
||||||
|
// Update existing client record
|
||||||
|
await rawDb.run(
|
||||||
|
sql`UPDATE clients
|
||||||
|
SET membership_type = ${membershipType ?? (existingClient as any).membership_type},
|
||||||
|
membership_status = ${membershipStatus ?? (existingClient as any).membership_status},
|
||||||
|
updated_at = ${Date.now()}
|
||||||
|
WHERE user_id = ${id}`,
|
||||||
|
);
|
||||||
|
log.debug("Client membership updated");
|
||||||
|
} else {
|
||||||
|
// Create client record if it doesn't exist
|
||||||
|
await rawDb.run(
|
||||||
|
sql`INSERT INTO clients (id, user_id, membership_type, membership_status, join_date, created_at, updated_at)
|
||||||
|
VALUES (${`client_${id}_${Date.now()}`}, ${id}, ${membershipType ?? "basic"}, ${membershipStatus ?? "active"}, ${Date.now()}, ${Date.now()}, ${Date.now()})`,
|
||||||
|
);
|
||||||
|
log.debug("Client record created");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const updatedUser = {
|
const updatedUser = {
|
||||||
...existingUser,
|
...existingUser,
|
||||||
email: email ?? existingUser.email,
|
email: email ?? existingUser.email,
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
UserButton,
|
UserButton,
|
||||||
} from "@clerk/nextjs";
|
} from "@clerk/nextjs";
|
||||||
import { Sidebar } from "@/components/ui/Sidebar";
|
import { Sidebar } from "@/components/ui/Sidebar";
|
||||||
import { Toaster } from "sonner";
|
import { ToasterProvider } from "@/components/providers/ToasterProvider";
|
||||||
import { QueryProvider } from "@/components/providers/QueryProvider";
|
import { QueryProvider } from "@/components/providers/QueryProvider";
|
||||||
|
|
||||||
const inter = Inter({ subsets: ["latin"] });
|
const inter = Inter({ subsets: ["latin"] });
|
||||||
@@ -35,7 +35,7 @@ export default function RootLayout({
|
|||||||
<div className="max-w-7xl mx-auto space-y-8">{children}</div>
|
<div className="max-w-7xl mx-auto space-y-8">{children}</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
<Toaster richColors position="top-right" />
|
<ToasterProvider />
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
</QueryProvider>
|
</QueryProvider>
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Toaster } from "sonner";
|
||||||
|
|
||||||
|
export function ToasterProvider() {
|
||||||
|
return <Toaster richColors position="top-right" />;
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { useUser } from "@clerk/nextjs";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
@@ -26,6 +27,9 @@ import {
|
|||||||
type InvitationOptionsData,
|
type InvitationOptionsData,
|
||||||
} from "@/lib/validation/user-schemas";
|
} from "@/lib/validation/user-schemas";
|
||||||
import { ChevronLeft, ChevronRight, Check } from "lucide-react";
|
import { ChevronLeft, ChevronRight, Check } from "lucide-react";
|
||||||
|
import { useGyms } from "@/hooks/use-api";
|
||||||
|
import { getInvitableRoles } from "@/lib/auth/permissions";
|
||||||
|
import type { UserRole } from "@fitai/shared";
|
||||||
|
|
||||||
interface CreateUserModalProps {
|
interface CreateUserModalProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -45,6 +49,15 @@ export function CreateUserModal({
|
|||||||
const [basicInfo, setBasicInfo] = useState<BasicInfoData | null>(null);
|
const [basicInfo, setBasicInfo] = useState<BasicInfoData | null>(null);
|
||||||
const [clientInfo, setClientInfo] = useState<ClientInfoData | null>(null);
|
const [clientInfo, setClientInfo] = useState<ClientInfoData | null>(null);
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
const { data: gyms = [] } = useGyms();
|
||||||
|
const { user } = useUser();
|
||||||
|
|
||||||
|
// Get current user's role and gym from Clerk metadata
|
||||||
|
const currentUserRole = (user?.publicMetadata?.role as UserRole) || "client";
|
||||||
|
const currentUserGymId = user?.publicMetadata?.gymId as string | null;
|
||||||
|
|
||||||
|
// Determine which roles the current user can create
|
||||||
|
const invitableRoles = getInvitableRoles(currentUserRole);
|
||||||
|
|
||||||
// Step 1: Role Selection Form
|
// Step 1: Role Selection Form
|
||||||
const roleForm = useForm<RoleSelectionData>({
|
const roleForm = useForm<RoleSelectionData>({
|
||||||
@@ -136,10 +149,18 @@ export function CreateUserModal({
|
|||||||
invitationData,
|
invitationData,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Auto-assign gym for non-superAdmins
|
||||||
|
// SuperAdmins can select gym manually, others use their own gym
|
||||||
|
const finalPayload = {
|
||||||
|
...payload,
|
||||||
|
gymId:
|
||||||
|
currentUserRole === "superAdmin" ? payload.gymId : currentUserGymId,
|
||||||
|
};
|
||||||
|
|
||||||
const response = await fetch("/api/users/create", {
|
const response = await fetch("/api/users/create", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(finalPayload),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
@@ -259,7 +280,7 @@ export function CreateUserModal({
|
|||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Role *</label>
|
<label className="text-sm font-medium">Role *</label>
|
||||||
<div className="grid grid-cols-3 gap-3">
|
<div className="grid grid-cols-3 gap-3">
|
||||||
{(["admin", "trainer", "client"] as const).map((role) => (
|
{invitableRoles.map((role) => (
|
||||||
<label
|
<label
|
||||||
key={role}
|
key={role}
|
||||||
className={`flex items-center justify-center p-4 border-2 rounded-lg cursor-pointer transition-colors ${
|
className={`flex items-center justify-center p-4 border-2 rounded-lg cursor-pointer transition-colors ${
|
||||||
@@ -461,6 +482,39 @@ export function CreateUserModal({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Gym Selector - Only for SuperAdmins */}
|
||||||
|
{currentUserRole === "superAdmin" && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium">
|
||||||
|
Assign to Gym (Optional)
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
{...invitationForm.register("gymId")}
|
||||||
|
className="w-full p-2 border border-gray-300 rounded-md"
|
||||||
|
>
|
||||||
|
<option value="">Select a gym...</option>
|
||||||
|
{gyms.map((gym) => (
|
||||||
|
<option key={gym.id} value={gym.id}>
|
||||||
|
{gym.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<p className="text-xs text-gray-500">
|
||||||
|
If not selected, user will not be assigned to any gym
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Info message for non-superAdmins */}
|
||||||
|
{currentUserRole !== "superAdmin" && currentUserGymId && (
|
||||||
|
<div className="p-4 bg-gray-50 border border-gray-200 rounded-md">
|
||||||
|
<p className="text-sm text-gray-700">
|
||||||
|
User will be automatically assigned to your gym
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<DialogFooter className="flex justify-between">
|
<DialogFooter className="flex justify-between">
|
||||||
<Button type="button" variant="outline" onClick={handleBack}>
|
<Button type="button" variant="outline" onClick={handleBack}>
|
||||||
<ChevronLeft className="mr-2 h-4 w-4" /> Back
|
<ChevronLeft className="mr-2 h-4 w-4" /> Back
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { formatDistanceToNow } from "date-fns";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
|
import {
|
||||||
|
useRevokeInvitation,
|
||||||
|
useResendInvitation,
|
||||||
|
type Invitation,
|
||||||
|
} from "@/hooks/use-api";
|
||||||
|
import { Copy, RefreshCw, Trash2 } from "lucide-react";
|
||||||
|
|
||||||
|
interface InvitationsGridProps {
|
||||||
|
invitations: Invitation[];
|
||||||
|
onRefetch: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function InvitationsGrid({
|
||||||
|
invitations,
|
||||||
|
onRefetch,
|
||||||
|
}: InvitationsGridProps) {
|
||||||
|
const revokeInvitation = useRevokeInvitation();
|
||||||
|
const resendInvitation = useResendInvitation();
|
||||||
|
const [actioningId, setActioningId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const handleCopyUrl = async (url: string) => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(url);
|
||||||
|
toast.success("Invitation link copied to clipboard");
|
||||||
|
} catch (error) {
|
||||||
|
toast.error("Failed to copy link");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRevoke = async (invitation: Invitation) => {
|
||||||
|
if (!confirm(`Cancel invitation for ${invitation.emailAddress}?`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setActioningId(invitation.id);
|
||||||
|
try {
|
||||||
|
await revokeInvitation.mutateAsync(invitation.id);
|
||||||
|
toast.success("Invitation cancelled");
|
||||||
|
onRefetch();
|
||||||
|
} catch (error) {
|
||||||
|
toast.error("Failed to cancel invitation");
|
||||||
|
} finally {
|
||||||
|
setActioningId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleResend = async (invitation: Invitation) => {
|
||||||
|
setActioningId(invitation.id);
|
||||||
|
try {
|
||||||
|
await resendInvitation.mutateAsync(invitation.id);
|
||||||
|
toast.success("Invitation resent");
|
||||||
|
onRefetch();
|
||||||
|
} catch (error) {
|
||||||
|
toast.error("Failed to resend invitation");
|
||||||
|
} finally {
|
||||||
|
setActioningId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (invitations.length === 0) {
|
||||||
|
return (
|
||||||
|
<Card className="p-8 text-center text-muted-foreground">
|
||||||
|
No pending invitations
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{invitations.map((invitation) => {
|
||||||
|
const role = invitation.publicMetadata?.role || "unknown";
|
||||||
|
const createdDate = new Date(invitation.createdAt);
|
||||||
|
const isActioning = actioningId === invitation.id;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card key={invitation.id} className="p-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<h3 className="font-medium">{invitation.emailAddress}</h3>
|
||||||
|
<span className="text-xs px-2 py-1 rounded bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200">
|
||||||
|
Pending
|
||||||
|
</span>
|
||||||
|
<span className="text-xs px-2 py-1 rounded bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
|
||||||
|
{role}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground mt-1">
|
||||||
|
Sent {formatDistanceToNow(createdDate, { addSuffix: true })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{invitation.url && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleCopyUrl(invitation.url!)}
|
||||||
|
>
|
||||||
|
<Copy className="h-4 w-4 mr-1" />
|
||||||
|
Copy Link
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleResend(invitation)}
|
||||||
|
disabled={isActioning}
|
||||||
|
>
|
||||||
|
<RefreshCw
|
||||||
|
className={`h-4 w-4 mr-1 ${isActioning ? "animate-spin" : ""}`}
|
||||||
|
/>
|
||||||
|
Resend
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleRevoke(invitation)}
|
||||||
|
disabled={isActioning}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4 mr-1" />
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { UserGrid, type User } from "@/components/users/UserGrid";
|
import { UserGrid, type User } from "@/components/users/UserGrid";
|
||||||
|
import { InvitationsGrid } from "@/components/users/InvitationsGrid";
|
||||||
import { Card, CardHeader, CardContent } from "@/components/ui/card";
|
import { Card, CardHeader, CardContent } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useUser } from "@clerk/nextjs";
|
import { useUser } from "@clerk/nextjs";
|
||||||
@@ -14,6 +15,7 @@ import {
|
|||||||
useUpdateUser,
|
useUpdateUser,
|
||||||
useDeleteUser,
|
useDeleteUser,
|
||||||
useSendInvitation,
|
useSendInvitation,
|
||||||
|
useInvitations,
|
||||||
} from "@/hooks/use-api";
|
} from "@/hooks/use-api";
|
||||||
|
|
||||||
interface UserManagementProps {
|
interface UserManagementProps {
|
||||||
@@ -23,6 +25,9 @@ interface UserManagementProps {
|
|||||||
export function UserManagement({ gymId }: UserManagementProps) {
|
export function UserManagement({ gymId }: UserManagementProps) {
|
||||||
const { user } = useUser();
|
const { user } = useUser();
|
||||||
const [filter, setFilter] = useState<string>("all");
|
const [filter, setFilter] = useState<string>("all");
|
||||||
|
const [viewFilter, setViewFilter] = useState<"all" | "active" | "pending">(
|
||||||
|
"all",
|
||||||
|
);
|
||||||
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
const [isDeleting, setIsDeleting] = useState(false);
|
const [isDeleting, setIsDeleting] = useState(false);
|
||||||
@@ -34,21 +39,34 @@ export function UserManagement({ gymId }: UserManagementProps) {
|
|||||||
role: string;
|
role: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
gymId: string;
|
gymId: string;
|
||||||
|
membershipType?: string;
|
||||||
|
membershipStatus?: string;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: users = [],
|
data: users = [],
|
||||||
isLoading,
|
isLoading: usersLoading,
|
||||||
refetch,
|
refetch: refetchUsers,
|
||||||
} = useUsers({
|
} = useUsers({
|
||||||
role: filter !== "all" ? filter : undefined,
|
role: filter !== "all" ? filter : undefined,
|
||||||
gymId,
|
gymId,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: invitations = [],
|
||||||
|
isLoading: invitationsLoading,
|
||||||
|
refetch: refetchInvitations,
|
||||||
|
} = useInvitations(gymId);
|
||||||
|
|
||||||
const { data: gyms = [] } = useGyms();
|
const { data: gyms = [] } = useGyms();
|
||||||
const updateUser = useUpdateUser();
|
const updateUser = useUpdateUser();
|
||||||
const deleteUser = useDeleteUser();
|
const deleteUser = useDeleteUser();
|
||||||
const sendInvitation = useSendInvitation();
|
const sendInvitation = useSendInvitation();
|
||||||
|
|
||||||
|
const isLoading =
|
||||||
|
viewFilter === "pending" ? invitationsLoading : usersLoading;
|
||||||
|
const refetch = viewFilter === "pending" ? refetchInvitations : refetchUsers;
|
||||||
|
|
||||||
const handleUserSelect = (user: User | null) => {
|
const handleUserSelect = (user: User | null) => {
|
||||||
setSelectedUser(user);
|
setSelectedUser(user);
|
||||||
};
|
};
|
||||||
@@ -62,6 +80,8 @@ export function UserManagement({ gymId }: UserManagementProps) {
|
|||||||
role: user.role,
|
role: user.role,
|
||||||
phone: user.phone || "",
|
phone: user.phone || "",
|
||||||
gymId: user.gymId || "",
|
gymId: user.gymId || "",
|
||||||
|
membershipType: user.client?.membershipType || "basic",
|
||||||
|
membershipStatus: user.client?.membershipStatus || "active",
|
||||||
});
|
});
|
||||||
setIsEditing(true);
|
setIsEditing(true);
|
||||||
};
|
};
|
||||||
@@ -133,7 +153,7 @@ export function UserManagement({ gymId }: UserManagementProps) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (selectedUser) {
|
if (selectedUser) {
|
||||||
const payload = {
|
const payload: any = {
|
||||||
id: selectedUser.id,
|
id: selectedUser.id,
|
||||||
email: editForm.email,
|
email: editForm.email,
|
||||||
firstName: editForm.firstName,
|
firstName: editForm.firstName,
|
||||||
@@ -143,6 +163,12 @@ export function UserManagement({ gymId }: UserManagementProps) {
|
|||||||
gymId: editForm.gymId === "" ? null : editForm.gymId,
|
gymId: editForm.gymId === "" ? null : editForm.gymId,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Include membership fields if user is a client
|
||||||
|
if (editForm.role === "client") {
|
||||||
|
payload.membershipType = editForm.membershipType;
|
||||||
|
payload.membershipStatus = editForm.membershipStatus;
|
||||||
|
}
|
||||||
|
|
||||||
await updateUser.mutateAsync(payload);
|
await updateUser.mutateAsync(payload);
|
||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
setEditForm(null);
|
setEditForm(null);
|
||||||
@@ -183,6 +209,19 @@ export function UserManagement({ gymId }: UserManagementProps) {
|
|||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<h2 className="text-2xl font-bold">User Management</h2>
|
<h2 className="text-2xl font-bold">User Management</h2>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
|
{/* View Filter: All/Active/Pending */}
|
||||||
|
<select
|
||||||
|
value={viewFilter}
|
||||||
|
onChange={(e) =>
|
||||||
|
setViewFilter(e.target.value as "all" | "active" | "pending")
|
||||||
|
}
|
||||||
|
className="px-3 py-2 border rounded-md bg-white dark:bg-gray-800"
|
||||||
|
>
|
||||||
|
<option value="all">All Users</option>
|
||||||
|
<option value="active">Active Users</option>
|
||||||
|
<option value="pending">Pending Invitations</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant={filter === "all" ? "default" : "outline"}
|
variant={filter === "all" ? "default" : "outline"}
|
||||||
onClick={() => setFilter("all")}
|
onClick={() => setFilter("all")}
|
||||||
@@ -210,7 +249,7 @@ export function UserManagement({ gymId }: UserManagementProps) {
|
|||||||
variant={filter === "client" ? "default" : "outline"}
|
variant={filter === "client" ? "default" : "outline"}
|
||||||
onClick={() => setFilter("client")}
|
onClick={() => setFilter("client")}
|
||||||
>
|
>
|
||||||
Clientsa
|
Clients
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant={filter === "trainer" ? "default" : "outline"}
|
variant={filter === "trainer" ? "default" : "outline"}
|
||||||
@@ -235,33 +274,48 @@ export function UserManagement({ gymId }: UserManagementProps) {
|
|||||||
|
|
||||||
<div className="flex justify-between items-center">
|
<div className="flex justify-between items-center">
|
||||||
<div className="text-sm text-gray-600">
|
<div className="text-sm text-gray-600">
|
||||||
Showing {users.length} users
|
{viewFilter === "pending" ? (
|
||||||
{selectedUser && (
|
<>Showing {invitations.length} pending invitations</>
|
||||||
<span className="ml-4 text-blue-600">
|
) : (
|
||||||
Selected: {selectedUser.firstName} {selectedUser.lastName}
|
<>
|
||||||
</span>
|
Showing {users.length} users
|
||||||
|
{selectedUser && (
|
||||||
|
<span className="ml-4 text-blue-600">
|
||||||
|
Selected: {selectedUser.firstName} {selectedUser.lastName}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Button variant="default" onClick={handleRefresh}>
|
<Button variant="default" onClick={handleRefresh}>
|
||||||
Refresh
|
Refresh
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="default" onClick={handleExport}>
|
{viewFilter !== "pending" && (
|
||||||
Export CSV
|
<Button variant="default" onClick={handleExport}>
|
||||||
</Button>
|
Export CSV
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
<UserGrid
|
{viewFilter === "pending" ? (
|
||||||
users={users}
|
<InvitationsGrid
|
||||||
onUserSelect={(user) => handleUserSelect(user)}
|
invitations={invitations}
|
||||||
onEditUser={handleEditUser}
|
onRefetch={refetchInvitations}
|
||||||
onDeleteUser={handleDeleteUser}
|
/>
|
||||||
onBulkDelete={handleBulkDelete}
|
) : (
|
||||||
loading={isLoading}
|
<UserGrid
|
||||||
/>
|
users={users}
|
||||||
|
onUserSelect={(user) => handleUserSelect(user)}
|
||||||
|
onEditUser={handleEditUser}
|
||||||
|
onDeleteUser={handleDeleteUser}
|
||||||
|
onBulkDelete={handleBulkDelete}
|
||||||
|
loading={isLoading}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
@@ -351,26 +405,78 @@ export function UserManagement({ gymId }: UserManagementProps) {
|
|||||||
className="w-full border border-gray-300 rounded px-3 py-2"
|
className="w-full border border-gray-300 rounded px-3 py-2"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-4">
|
|
||||||
<label className="block text-sm font-medium mb-1">Gym</label>
|
{/* Only superAdmins can reassign gyms */}
|
||||||
<select
|
{(() => {
|
||||||
value={editForm.gymId}
|
const currentRole = user?.publicMetadata?.role;
|
||||||
onChange={(e) =>
|
console.log("Current user role for gym selector:", currentRole);
|
||||||
setEditForm({ ...editForm, gymId: e.target.value })
|
return currentRole === "superAdmin";
|
||||||
}
|
})() && (
|
||||||
className="w-full border border-gray-300 rounded px-3 py-2"
|
<div className="mb-4">
|
||||||
>
|
<label className="block text-sm font-medium mb-1">Gym</label>
|
||||||
<option value="">Proceed without gym</option>
|
<select
|
||||||
{gyms.map((g) => (
|
value={editForm.gymId}
|
||||||
<option key={g.id} value={g.id}>
|
onChange={(e) =>
|
||||||
{g.name}
|
setEditForm({ ...editForm, gymId: e.target.value })
|
||||||
</option>
|
}
|
||||||
))}
|
className="w-full border border-gray-300 rounded px-3 py-2"
|
||||||
</select>
|
>
|
||||||
<p className="text-xs text-gray-500 mt-1">
|
<option value="">Proceed without gym</option>
|
||||||
Select an active gym or proceed without a gym.
|
{gyms.map((g) => (
|
||||||
</p>
|
<option key={g.id} value={g.id}>
|
||||||
</div>
|
{g.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<p className="text-xs text-gray-500 mt-1">
|
||||||
|
Select an active gym or proceed without a gym.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Client-specific fields - only show when role is client */}
|
||||||
|
{editForm.role === "client" && (
|
||||||
|
<>
|
||||||
|
<div className="mb-4">
|
||||||
|
<label className="block text-sm font-medium mb-1">
|
||||||
|
Membership Type
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={editForm.membershipType || "basic"}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm({
|
||||||
|
...editForm,
|
||||||
|
membershipType: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="w-full border border-gray-300 rounded px-3 py-2"
|
||||||
|
>
|
||||||
|
<option value="basic">Basic</option>
|
||||||
|
<option value="premium">Premium</option>
|
||||||
|
<option value="vip">VIP</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="mb-4">
|
||||||
|
<label className="block text-sm font-medium mb-1">
|
||||||
|
Membership Status
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={editForm.membershipStatus || "active"}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm({
|
||||||
|
...editForm,
|
||||||
|
membershipStatus: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="w-full border border-gray-300 rounded px-3 py-2"
|
||||||
|
>
|
||||||
|
<option value="active">Active</option>
|
||||||
|
<option value="inactive">Inactive</option>
|
||||||
|
<option value="suspended">Suspended</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -518,7 +624,10 @@ export function UserManagement({ gymId }: UserManagementProps) {
|
|||||||
<CreateUserModal
|
<CreateUserModal
|
||||||
open={createModalOpen}
|
open={createModalOpen}
|
||||||
onOpenChange={setCreateModalOpen}
|
onOpenChange={setCreateModalOpen}
|
||||||
onSuccess={() => refetch()}
|
onSuccess={() => {
|
||||||
|
refetchUsers();
|
||||||
|
refetchInvitations();
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -61,6 +61,21 @@ export interface AttendanceRecord {
|
|||||||
type?: string;
|
type?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface Invitation {
|
||||||
|
id: string;
|
||||||
|
emailAddress: string;
|
||||||
|
publicMetadata: {
|
||||||
|
role?: string;
|
||||||
|
gymId?: string;
|
||||||
|
createdBy?: string;
|
||||||
|
} | null;
|
||||||
|
status: "pending" | "accepted" | "revoked" | "expired";
|
||||||
|
url?: string;
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
revoked?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchApi<T>(url: string, options?: RequestInit): Promise<T> {
|
async function fetchApi<T>(url: string, options?: RequestInit): Promise<T> {
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
...options,
|
...options,
|
||||||
@@ -170,7 +185,7 @@ export function useGyms() {
|
|||||||
queryKey: ["gyms"],
|
queryKey: ["gyms"],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
fetchApi<{ data: { gyms: Gym[] } }>("/api/gyms").then(
|
fetchApi<{ data: { gyms: Gym[] } }>("/api/gyms").then(
|
||||||
(res) => res.data?.gyms ?? [],
|
(res) => res.data?.gyms ?? (Array.isArray(res) ? res : []),
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -339,13 +354,17 @@ export function useCheckOut() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useInvitations() {
|
export function useInvitations(gymId?: string) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["invitations"],
|
queryKey: ["invitations", gymId],
|
||||||
queryFn: () =>
|
queryFn: () => {
|
||||||
fetchApi<{ data: { invitations: unknown[] } }>("/api/invitations").then(
|
const url = gymId
|
||||||
|
? `/api/invitations?gymId=${gymId}`
|
||||||
|
: "/api/invitations";
|
||||||
|
return fetchApi<{ data: { invitations: Invitation[] } }>(url).then(
|
||||||
(res) => res.data?.invitations ?? [],
|
(res) => res.data?.invitations ?? [],
|
||||||
),
|
);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -364,6 +383,37 @@ export function useSendInvitation() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useRevokeInvitation() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (invitationId: string) =>
|
||||||
|
fetchApi<{ data: { success: boolean } }>(
|
||||||
|
`/api/invitations/${invitationId}`,
|
||||||
|
{ method: "DELETE" },
|
||||||
|
),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["invitations"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["users"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useResendInvitation() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (invitationId: string) =>
|
||||||
|
fetchApi<{ data: { invitation: any } }>(
|
||||||
|
`/api/invitations/${invitationId}/resend`,
|
||||||
|
{ method: "POST" },
|
||||||
|
),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["invitations"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export interface AnalyticsData {
|
export interface AnalyticsData {
|
||||||
userGrowth: { label: string; value: number }[];
|
userGrowth: { label: string; value: number }[];
|
||||||
membershipDistribution: { label: string; value: number; color: string }[];
|
membershipDistribution: { label: string; value: number; color: string }[];
|
||||||
|
|||||||
@@ -30,29 +30,72 @@ export async function getAuthContext(): Promise<AuthContext> {
|
|||||||
throw new Error("Unauthorized: No authenticated user");
|
throw new Error("Unauthorized: No authenticated user");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get role from Clerk metadata
|
// Try to get role from Clerk metadata (could be in publicMetadata or metadata)
|
||||||
const role = (sessionClaims?.metadata as { role?: UserRole })?.role;
|
let role = (sessionClaims?.publicMetadata as { role?: UserRole })?.role;
|
||||||
|
|
||||||
|
// Fallback: Try the metadata field if publicMetadata doesn't have it
|
||||||
|
if (!role) {
|
||||||
|
role = (sessionClaims?.metadata as { role?: UserRole })?.role;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If still no role, try database lookup as last resort
|
||||||
if (!role || !USER_ROLES.includes(role)) {
|
if (!role || !USER_ROLES.includes(role)) {
|
||||||
throw new Error(`Forbidden: Invalid or missing role - ${role}`);
|
console.log("Role not found in session claims, fetching from database", {
|
||||||
|
userId,
|
||||||
|
roleFromPublicMetadata: (
|
||||||
|
sessionClaims?.publicMetadata as { role?: UserRole }
|
||||||
|
)?.role,
|
||||||
|
roleFromMetadata: (sessionClaims?.metadata as { role?: UserRole })?.role,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const db = await getDatabase();
|
||||||
|
const user = await db.getUserById(userId);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
console.error("User not found in database", { userId });
|
||||||
|
throw new Error(`Forbidden: User not found in database - ${userId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.role && USER_ROLES.includes(user.role as UserRole)) {
|
||||||
|
console.log("Role found in database", { userId, role: user.role });
|
||||||
|
role = user.role as UserRole;
|
||||||
|
} else {
|
||||||
|
console.error("Invalid role in database", { userId, role: user.role });
|
||||||
|
throw new Error(`Forbidden: Invalid role in database - ${user.role}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to get role from database:", error);
|
||||||
|
throw new Error(
|
||||||
|
`Forbidden: Could not determine user role - ${error instanceof Error ? error.message : String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get gymId from Clerk metadata or database
|
// Get gymId from Clerk metadata or database
|
||||||
let gymId: string | null = null;
|
let gymId: string | null = null;
|
||||||
|
|
||||||
// First try Clerk metadata (faster path)
|
// First try Clerk publicMetadata (faster path)
|
||||||
const clerkGymId = (sessionClaims?.metadata as { gymId?: string })?.gymId;
|
const clerkGymId = (sessionClaims?.publicMetadata as { gymId?: string })
|
||||||
|
?.gymId;
|
||||||
if (clerkGymId) {
|
if (clerkGymId) {
|
||||||
gymId = clerkGymId;
|
gymId = clerkGymId;
|
||||||
} else {
|
} else {
|
||||||
// Fallback to database lookup
|
// Try metadata field
|
||||||
try {
|
const metadataGymId = (sessionClaims?.metadata as { gymId?: string })
|
||||||
const db = await getDatabase();
|
?.gymId;
|
||||||
const user = await db.getUserById(userId);
|
if (metadataGymId) {
|
||||||
gymId = user?.gymId ?? null;
|
gymId = metadataGymId;
|
||||||
} catch (error) {
|
} else {
|
||||||
console.error("Failed to get gymId from database:", error);
|
// Fallback to database lookup
|
||||||
gymId = null;
|
try {
|
||||||
|
const db = await getDatabase();
|
||||||
|
const user = await db.getUserById(userId);
|
||||||
|
gymId = user?.gymId ?? null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to get gymId from database:", error);
|
||||||
|
gymId = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,9 +16,12 @@ export const passwordSchema = z
|
|||||||
export const phoneSchema = z
|
export const phoneSchema = z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.refine((val) => !val || /^\+?[1-9]\d{1,14}$/.test(val), {
|
.refine(
|
||||||
message: "Invalid phone number format",
|
(val) => !val || val.trim() === "" || /^\+?[1-9]\d{1,14}$/.test(val),
|
||||||
});
|
{
|
||||||
|
message: "Invalid phone number format",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
export const dateTimeSchema = z.string().datetime("Invalid datetime format");
|
export const dateTimeSchema = z.string().datetime("Invalid datetime format");
|
||||||
|
|
||||||
@@ -33,6 +36,14 @@ export const userRoleSchema = z.enum([
|
|||||||
"superAdmin",
|
"superAdmin",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
export const membershipTypeSchema = z.enum(["basic", "premium", "vip"]);
|
||||||
|
|
||||||
|
export const membershipStatusSchema = z.enum([
|
||||||
|
"active",
|
||||||
|
"inactive",
|
||||||
|
"suspended",
|
||||||
|
]);
|
||||||
|
|
||||||
export const userSchema = z.object({
|
export const userSchema = z.object({
|
||||||
email: emailSchema,
|
email: emailSchema,
|
||||||
password: passwordSchema,
|
password: passwordSchema,
|
||||||
@@ -65,6 +76,8 @@ export const userUpdateWithIdSchema = z.object({
|
|||||||
role: userRoleSchema.optional(),
|
role: userRoleSchema.optional(),
|
||||||
phone: phoneSchema,
|
phone: phoneSchema,
|
||||||
gymId: z.string().nullable().optional(),
|
gymId: z.string().nullable().optional(),
|
||||||
|
membershipType: membershipTypeSchema.optional(),
|
||||||
|
membershipStatus: membershipStatusSchema.optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -335,6 +348,8 @@ export type User = z.infer<typeof userSchema>;
|
|||||||
export type UserUpdate = z.infer<typeof userUpdateSchema>;
|
export type UserUpdate = z.infer<typeof userUpdateSchema>;
|
||||||
export type UserLogin = z.infer<typeof userLoginSchema>;
|
export type UserLogin = z.infer<typeof userLoginSchema>;
|
||||||
export type UserRole = z.infer<typeof userRoleSchema>;
|
export type UserRole = z.infer<typeof userRoleSchema>;
|
||||||
|
export type MembershipType = z.infer<typeof membershipTypeSchema>;
|
||||||
|
export type MembershipStatus = z.infer<typeof membershipStatusSchema>;
|
||||||
|
|
||||||
export type FitnessGoal = z.infer<typeof fitnessGoalSchema>;
|
export type FitnessGoal = z.infer<typeof fitnessGoalSchema>;
|
||||||
export type FitnessGoalUpdate = z.infer<typeof fitnessGoalUpdateSchema>;
|
export type FitnessGoalUpdate = z.infer<typeof fitnessGoalUpdateSchema>;
|
||||||
|
|||||||
Reference in new issue
Block a user