Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0817e8e72b | ||
|
|
b1f01208fa | ||
|
|
d112dbb122 | ||
|
|
7043487fc2 | ||
|
|
bb9c675421 | ||
|
|
624cdfc45c | ||
|
|
16217f46ff | ||
|
|
cc2dbc3423 | ||
|
|
b1d6489c70 | ||
|
|
0abb41f573 | ||
|
|
02c9681aca | ||
|
|
912981e3f3 | ||
|
|
963404434a | ||
|
|
7f22a39886 | ||
|
|
0776517fb7 |
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_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_PATH=./fitai.db
|
||||
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,167 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import { successResponse } from "@/lib/api/responses";
|
||||
import { db as rawDb, sql } from "@fitai/database";
|
||||
import { getUsersByGym, getClientsByGym } from "@/lib/gym-context";
|
||||
|
||||
interface UserGrowthPoint {
|
||||
label: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
interface MembershipDistributionPoint {
|
||||
label: string;
|
||||
value: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
interface RevenuePoint {
|
||||
label: string;
|
||||
value: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
interface AnalyticsData {
|
||||
userGrowth: UserGrowthPoint[];
|
||||
membershipDistribution: MembershipDistributionPoint[];
|
||||
revenue: RevenuePoint[];
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const database = await getDatabase();
|
||||
const user = await ensureUserSynced(userId, database);
|
||||
|
||||
if (!user || (user.role !== "admin" && user.role !== "superAdmin")) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
const url = new URL(req.url);
|
||||
const months = parseInt(url.searchParams.get("months") || "6");
|
||||
|
||||
// Get target gym based on role
|
||||
const targetGymId =
|
||||
user.role === "superAdmin"
|
||||
? (url.searchParams.get("gymId") ?? undefined)
|
||||
: (user.gymId ?? undefined);
|
||||
|
||||
// Validate gym access for non-superAdmins
|
||||
if (user.role !== "superAdmin" && !targetGymId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden - No gym assigned" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
// Get gym-scoped data
|
||||
const allUsers = targetGymId
|
||||
? await getUsersByGym(targetGymId)
|
||||
: await database.getAllUsers();
|
||||
|
||||
const allClients = targetGymId
|
||||
? await getClientsByGym(targetGymId)
|
||||
: await database.getAllClients();
|
||||
|
||||
// For payments, we'd need a similar filter - for now, skip payments if gym-scoped
|
||||
// TODO: Add getPaymentsByGym when needed
|
||||
const paymentsRaw = targetGymId
|
||||
? [] // Skip payments for gym-scoped for now
|
||||
: await rawDb.all(
|
||||
sql`SELECT * FROM payments WHERE status = 'completed' AND paid_at IS NOT NULL`,
|
||||
);
|
||||
const payments: any[] = paymentsRaw || [];
|
||||
|
||||
const now = new Date();
|
||||
const userGrowth: UserGrowthPoint[] = [];
|
||||
|
||||
for (let i = months - 1; i >= 0; i--) {
|
||||
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
const monthLabel = date.toLocaleDateString("en-US", { month: "short" });
|
||||
|
||||
const usersCreatedByMonth = allUsers.filter((u: any) => {
|
||||
const createdAt = new Date(u.createdAt);
|
||||
return (
|
||||
createdAt.getFullYear() === date.getFullYear() &&
|
||||
createdAt.getMonth() === date.getMonth()
|
||||
);
|
||||
});
|
||||
|
||||
userGrowth.push({
|
||||
label: monthLabel,
|
||||
value: usersCreatedByMonth.length,
|
||||
});
|
||||
}
|
||||
|
||||
let runningTotal = 0;
|
||||
for (const point of userGrowth) {
|
||||
runningTotal += point.value;
|
||||
point.value = runningTotal;
|
||||
}
|
||||
|
||||
const membershipCounts: Record<string, number> = {
|
||||
basic: 0,
|
||||
premium: 0,
|
||||
vip: 0,
|
||||
};
|
||||
|
||||
for (const client of allClients) {
|
||||
const membershipType = (client as any).membershipType || "basic";
|
||||
if (membershipCounts[membershipType] !== undefined) {
|
||||
membershipCounts[membershipType]++;
|
||||
}
|
||||
}
|
||||
|
||||
const membershipDistribution: MembershipDistributionPoint[] = [
|
||||
{ label: "Basic", value: membershipCounts.basic, color: "#6b7280" },
|
||||
{ label: "Premium", value: membershipCounts.premium, color: "#3b82f6" },
|
||||
{ label: "VIP", value: membershipCounts.vip, color: "#f59e0b" },
|
||||
];
|
||||
|
||||
const revenue: RevenuePoint[] = [];
|
||||
|
||||
for (let i = months - 1; i >= 0; i--) {
|
||||
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
const monthLabel = date.toLocaleDateString("en-US", { month: "short" });
|
||||
const nextMonthDate = new Date(
|
||||
now.getFullYear(),
|
||||
now.getMonth() - i + 1,
|
||||
1,
|
||||
);
|
||||
|
||||
const monthlyRevenue = payments
|
||||
.filter((p: any) => {
|
||||
const paidAt = p.paid_at ? new Date(p.paid_at) : null;
|
||||
if (!paidAt) return false;
|
||||
return paidAt >= date && paidAt < nextMonthDate;
|
||||
})
|
||||
.reduce((sum: number, p: any) => sum + (p.amount || 0), 0);
|
||||
|
||||
revenue.push({
|
||||
label: monthLabel,
|
||||
value: monthlyRevenue,
|
||||
color: "#10b981",
|
||||
});
|
||||
}
|
||||
|
||||
const analyticsData: AnalyticsData = {
|
||||
userGrowth,
|
||||
membershipDistribution,
|
||||
revenue,
|
||||
};
|
||||
|
||||
return successResponse({ analytics: analyticsData });
|
||||
} catch (error) {
|
||||
console.error("Analytics error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,42 @@
|
||||
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 { NextRequest, NextResponse } from "next/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import { successResponse } from "@/lib/api/responses";
|
||||
import { getAttendanceByGym } from "@/lib/gym-context";
|
||||
|
||||
export async function GET(req: Request) {
|
||||
try {
|
||||
const { userId } = await auth()
|
||||
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase()
|
||||
const db = await getDatabase();
|
||||
const user = await ensureUserSynced(userId, db);
|
||||
|
||||
// Ensure user is synced (handles seed script ID mismatch)
|
||||
// We need to import ensureUserSynced
|
||||
const user = await ensureUserSynced(userId, db)
|
||||
|
||||
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
|
||||
return new NextResponse('Forbidden', { status: 403 })
|
||||
}
|
||||
|
||||
const attendance = await db.getAllAttendance()
|
||||
return NextResponse.json(attendance)
|
||||
} catch (error) {
|
||||
console.error('Admin attendance error:', error)
|
||||
return new NextResponse('Internal Server Error', { status: 500 })
|
||||
if (!user || (user.role !== "admin" && user.role !== "superAdmin")) {
|
||||
return new NextResponse("Forbidden", { status: 403 });
|
||||
}
|
||||
|
||||
// Get target gym based on role
|
||||
const url = new URL(req.url);
|
||||
const targetGymId =
|
||||
user.role === "superAdmin"
|
||||
? (url.searchParams.get("gymId") ?? undefined)
|
||||
: (user.gymId ?? undefined);
|
||||
|
||||
// Validate gym access for non-superAdmins
|
||||
if (user.role !== "superAdmin" && !targetGymId) {
|
||||
return new NextResponse("Forbidden - No gym assigned", { status: 403 });
|
||||
}
|
||||
|
||||
// Get attendance filtered by gym
|
||||
const attendance = targetGymId
|
||||
? await getAttendanceByGym(targetGymId)
|
||||
: await db.getAllAttendance();
|
||||
|
||||
return successResponse({ records: attendance });
|
||||
} catch (error) {
|
||||
console.error("Admin attendance error:", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { auth } from "@clerk/nextjs/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import { successResponse } from "@/lib/api/responses";
|
||||
|
||||
export async function GET(req: Request) {
|
||||
try {
|
||||
@@ -51,7 +52,7 @@ export async function GET(req: Request) {
|
||||
revenueGrowth: 0,
|
||||
};
|
||||
|
||||
return NextResponse.json(stats);
|
||||
return successResponse({ stats });
|
||||
} catch (error) {
|
||||
console.error("Dashboard stats error:", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
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";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
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
|
||||
)
|
||||
`);
|
||||
}
|
||||
|
||||
// DELETE /api/gyms/[id]
|
||||
// Delete a gym (soft delete - mark as inactive)
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id: gymId } = await params;
|
||||
const { userId } = await auth();
|
||||
|
||||
if (!userId) {
|
||||
return new NextResponse("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
// Ensure user is synced
|
||||
const currentUser = await ensureUserSynced(userId, {
|
||||
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;
|
||||
},
|
||||
} as any);
|
||||
|
||||
// Only superAdmin can delete gyms
|
||||
if (!currentUser || currentUser.role !== "superAdmin") {
|
||||
return new NextResponse("Forbidden - Only superAdmin can delete gyms", {
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
|
||||
await ensureGymsTable();
|
||||
|
||||
// Check if gym exists
|
||||
const gymRows = await db.all(sql`SELECT * FROM gyms WHERE id = ${gymId}`);
|
||||
if (gymRows.length === 0) {
|
||||
return new NextResponse("Gym not found", { status: 404 });
|
||||
}
|
||||
|
||||
// Soft delete - mark as inactive
|
||||
await db.run(
|
||||
sql`UPDATE gyms SET status = 'inactive', updated_at = ${Date.now()} WHERE id = ${gymId}`,
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: "Gym deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
log.error("Failed to delete gym", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { eq, sql } from "@fitai/database";
|
||||
import { db } from "@fitai/database";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
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/[id]/stats
|
||||
// Get stats for a specific gym
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id: gymId } = await params;
|
||||
await ensureGymsTable();
|
||||
|
||||
// Get gym info
|
||||
const gymRows = await db.all(sql`SELECT * FROM gyms WHERE id = ${gymId}`);
|
||||
if (gymRows.length === 0) {
|
||||
return new NextResponse("Gym not found", { status: 404 });
|
||||
}
|
||||
const gym = gymRows[0];
|
||||
|
||||
// Get user counts
|
||||
const usersResult = await db.all(
|
||||
sql`SELECT role, COUNT(*) as count FROM users WHERE gym_id = ${gymId} GROUP BY role`,
|
||||
);
|
||||
|
||||
const userCounts: Record<string, number> = {
|
||||
admin: 0,
|
||||
trainer: 0,
|
||||
client: 0,
|
||||
};
|
||||
for (const row of usersResult as any[]) {
|
||||
if (row.role in userCounts) {
|
||||
userCounts[row.role] = row.count;
|
||||
}
|
||||
}
|
||||
|
||||
// Get client stats
|
||||
const clientsResult = (await db.all(
|
||||
sql`SELECT
|
||||
membership_type,
|
||||
membership_status,
|
||||
COUNT(*) as count
|
||||
FROM clients
|
||||
WHERE user_id IN (SELECT id FROM users WHERE gym_id = ${gymId})
|
||||
GROUP BY membership_type, membership_status`,
|
||||
)) as any[];
|
||||
|
||||
const membershipStats: Record<string, number> = {
|
||||
basic: 0,
|
||||
premium: 0,
|
||||
vip: 0,
|
||||
};
|
||||
const activeClients = clientsResult.filter(
|
||||
(c: any) => c.membership_status === "active",
|
||||
);
|
||||
for (const row of activeClients) {
|
||||
if (row.membership_type in membershipStats) {
|
||||
membershipStats[row.membership_type] = row.count;
|
||||
}
|
||||
}
|
||||
|
||||
// Get recent activity (attendance in last 30 days)
|
||||
const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;
|
||||
const attendanceResult = (await db.all(
|
||||
sql`SELECT COUNT(*) as count FROM attendance
|
||||
WHERE user_id IN (SELECT id FROM users WHERE gym_id = ${gymId})
|
||||
AND check_in_time > ${thirtyDaysAgo}`,
|
||||
)) as any[];
|
||||
const attendanceCount = attendanceResult[0]?.count || 0;
|
||||
|
||||
const stats = {
|
||||
totalUsers: userCounts.admin + userCounts.trainer + userCounts.client,
|
||||
admins: userCounts.admin,
|
||||
trainers: userCounts.trainer,
|
||||
clients: userCounts.client,
|
||||
membershipStats,
|
||||
activeClients: activeClients.reduce(
|
||||
(sum: number, c: any) => sum + c.count,
|
||||
0,
|
||||
),
|
||||
attendanceLast30Days: attendanceCount,
|
||||
};
|
||||
|
||||
return NextResponse.json({ gym, stats });
|
||||
} catch (error) {
|
||||
log.error("Failed to get gym stats", error);
|
||||
return new NextResponse("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -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 { 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
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getDatabase } from "../../../../lib/database/index";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import log from "@/lib/logger";
|
||||
import { fitnessProfileSchema } from "@/lib/validation/schemas";
|
||||
import {
|
||||
validateRequestBody,
|
||||
validationErrorResponse,
|
||||
} from "@/lib/validation/helpers";
|
||||
import { getFitnessProfilesByGym } from "@/lib/gym-context";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@@ -63,12 +66,47 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const db = await getDatabase();
|
||||
const { searchParams } = new URL(request.url);
|
||||
const userId = searchParams.get("userId");
|
||||
// First authenticate
|
||||
const { userId: clerkUserId } = await auth();
|
||||
if (!clerkUserId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
const profile = await db.getFitnessProfileByUserId(userId);
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(clerkUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const targetUserId = searchParams.get("userId");
|
||||
|
||||
// If accessing another user's profile, verify gym access
|
||||
if (targetUserId && targetUserId !== clerkUserId) {
|
||||
const isStaff =
|
||||
currentUser.role === "admin" ||
|
||||
currentUser.role === "superAdmin" ||
|
||||
currentUser.role === "trainer";
|
||||
|
||||
if (!isStaff) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Staff need to verify target user is in same gym
|
||||
if (currentUser.role !== "superAdmin") {
|
||||
const targetUser = await db.getUserById(targetUserId);
|
||||
if (!targetUser || targetUser.gymId !== currentUser.gymId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden - Cannot access users from other gyms" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targetUserId) {
|
||||
const profile = await db.getFitnessProfileByUserId(targetUserId);
|
||||
if (!profile) {
|
||||
return NextResponse.json(
|
||||
{ error: "Profile not found" },
|
||||
@@ -78,8 +116,28 @@ export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({ profile });
|
||||
}
|
||||
|
||||
const profiles = await db.getAllFitnessProfiles();
|
||||
return NextResponse.json({ profiles });
|
||||
// Staff get gym-scoped profiles
|
||||
const isStaff =
|
||||
currentUser.role === "admin" ||
|
||||
currentUser.role === "superAdmin" ||
|
||||
currentUser.role === "trainer";
|
||||
|
||||
if (isStaff) {
|
||||
const targetGymId =
|
||||
currentUser.role === "superAdmin"
|
||||
? (searchParams.get("gymId") ?? undefined)
|
||||
: (currentUser.gymId ?? undefined);
|
||||
|
||||
const profiles = targetGymId
|
||||
? await getFitnessProfilesByGym(targetGymId)
|
||||
: await db.getAllFitnessProfiles();
|
||||
|
||||
return NextResponse.json({ profiles });
|
||||
}
|
||||
|
||||
// Regular users only get their own
|
||||
const profile = await db.getFitnessProfileByUserId(clerkUserId);
|
||||
return NextResponse.json({ profile: profile ? [profile] : [] });
|
||||
} catch (error) {
|
||||
log.error("Failed to get fitness profiles", error);
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
badRequestResponse,
|
||||
internalErrorResponse,
|
||||
} from "@/lib/api/responses";
|
||||
import { getRecommendationsByGym } from "@/lib/gym-context";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
@@ -25,38 +27,59 @@ export async function GET(request: NextRequest) {
|
||||
return unauthorizedResponse();
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(currentUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return forbiddenResponse("User not found");
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const targetUserId = searchParams.get("userId");
|
||||
|
||||
const db = await getDatabase();
|
||||
|
||||
// If no userId provided, check if staff and return all recommendations
|
||||
// If no userId provided, staff gets gym-scoped recommendations
|
||||
if (!targetUserId) {
|
||||
const currentUser = await db.getUserById(currentUserId);
|
||||
const isStaff =
|
||||
currentUser?.role === "admin" ||
|
||||
currentUser?.role === "superAdmin" ||
|
||||
currentUser?.role === "trainer";
|
||||
currentUser.role === "admin" ||
|
||||
currentUser.role === "superAdmin" ||
|
||||
currentUser.role === "trainer";
|
||||
|
||||
if (!isStaff) {
|
||||
return badRequestResponse("User ID is required");
|
||||
}
|
||||
|
||||
const recommendations = await db.getAllRecommendations();
|
||||
// Get target gym based on role
|
||||
const targetGymId =
|
||||
currentUser.role === "superAdmin"
|
||||
? (searchParams.get("gymId") ?? undefined)
|
||||
: (currentUser.gymId ?? undefined);
|
||||
|
||||
// Get recommendations filtered by gym
|
||||
const recommendations = targetGymId
|
||||
? await getRecommendationsByGym(targetGymId)
|
||||
: await db.getAllRecommendations();
|
||||
|
||||
return successResponse({ recommendations });
|
||||
}
|
||||
|
||||
// Check permissions: Users can view their own, Admins/Trainers can view anyone's
|
||||
const currentUser = await db.getUserById(currentUserId);
|
||||
// Check permissions: Users can view their own, Admins/Trainers can view anyone's in their gym
|
||||
const isStaff =
|
||||
currentUser?.role === "admin" ||
|
||||
currentUser?.role === "superAdmin" ||
|
||||
currentUser?.role === "trainer";
|
||||
currentUser.role === "admin" ||
|
||||
currentUser.role === "superAdmin" ||
|
||||
currentUser.role === "trainer";
|
||||
|
||||
if (currentUserId !== targetUserId) {
|
||||
if (!isStaff) {
|
||||
return forbiddenResponse();
|
||||
}
|
||||
|
||||
// Staff need to verify target user is in same gym
|
||||
if (currentUser.role !== "superAdmin") {
|
||||
const targetUser = await db.getUserById(targetUserId);
|
||||
if (!targetUser || targetUser.gymId !== currentUser.gymId) {
|
||||
return forbiddenResponse("Cannot access users from other gyms");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let recommendations = await db.getRecommendationsByUserId(targetUserId);
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
errorResponse,
|
||||
unauthorizedResponse,
|
||||
} from "@/lib/api/responses";
|
||||
import { getAuthContext } from "@/lib/auth/context";
|
||||
import { getInvitableRoles } from "@/lib/auth/permissions";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
/**
|
||||
@@ -26,6 +28,10 @@ export async function POST(request: NextRequest) {
|
||||
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 validationResult = createUserSchema.safeParse(body);
|
||||
|
||||
@@ -41,6 +47,33 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
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
|
||||
// TODO: Add schema migration to make email optional for direct creation
|
||||
if (!data.email) {
|
||||
@@ -51,18 +84,39 @@ export async function POST(request: NextRequest) {
|
||||
if (data.sendInvitation && data.email) {
|
||||
try {
|
||||
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({
|
||||
emailAddress: data.email,
|
||||
publicMetadata: {
|
||||
role: data.role,
|
||||
gymId: data.gymId,
|
||||
},
|
||||
publicMetadata,
|
||||
redirectUrl,
|
||||
ignoreExisting: true, // Don't fail if invitation already exists
|
||||
});
|
||||
|
||||
log.info("Clerk invitation sent", {
|
||||
email: data.email,
|
||||
role: data.role,
|
||||
gymId: assignedGymId,
|
||||
invitationId: invitation.id,
|
||||
redirectUrl: redirectUrl || "default (mobile app)",
|
||||
});
|
||||
|
||||
// Send custom invitation email (in addition to Clerk's)
|
||||
@@ -83,7 +137,22 @@ export async function POST(request: NextRequest) {
|
||||
} catch (error: unknown) {
|
||||
const errorMessage =
|
||||
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}`, {
|
||||
status: 500,
|
||||
});
|
||||
@@ -106,13 +175,14 @@ export async function POST(request: NextRequest) {
|
||||
lastName: data.lastName,
|
||||
role: data.role,
|
||||
phone: data.phone,
|
||||
gymId: data.gymId,
|
||||
gymId: assignedGymId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
log.info("User created in database", {
|
||||
userId: newUser.id,
|
||||
role: data.role,
|
||||
gymId: assignedGymId,
|
||||
hasEmail: !!data.email,
|
||||
});
|
||||
|
||||
|
||||
@@ -24,14 +24,42 @@ import {
|
||||
internalErrorResponse,
|
||||
badRequestResponse,
|
||||
} from "@/lib/api/responses";
|
||||
import { getUsersByGym } from "@/lib/gym-context";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// First authenticate the user
|
||||
const { userId: clerkUserId } = await auth();
|
||||
if (!clerkUserId) {
|
||||
return unauthorizedResponse();
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(clerkUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return forbiddenResponse("User not found");
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const role = searchParams.get("role");
|
||||
|
||||
let users = await db.getAllUsers();
|
||||
// Get target gym based on role
|
||||
const targetGymId =
|
||||
currentUser.role === "superAdmin"
|
||||
? (searchParams.get("gymId") ?? undefined)
|
||||
: (currentUser.gymId ?? undefined);
|
||||
|
||||
// Validate gym access for non-superAdmins
|
||||
if (currentUser.role !== "superAdmin" && !targetGymId) {
|
||||
return forbiddenResponse("No gym assigned");
|
||||
}
|
||||
|
||||
// Get users filtered by gym
|
||||
let users = targetGymId
|
||||
? await getUsersByGym(targetGymId)
|
||||
: await db.getAllUsers();
|
||||
|
||||
// Hydrate gymId from raw DB to ensure consistency with writes
|
||||
const rawUserRows = await rawDb.all(sql`SELECT id, gym_id FROM users`);
|
||||
@@ -303,8 +331,17 @@ export async function PUT(request: NextRequest) {
|
||||
return validationErrorResponse(validation.errors);
|
||||
}
|
||||
|
||||
const { id, email, firstName, lastName, role, phone, gymId } =
|
||||
validation.data;
|
||||
const {
|
||||
id,
|
||||
email,
|
||||
firstName,
|
||||
lastName,
|
||||
role,
|
||||
phone,
|
||||
gymId,
|
||||
membershipType,
|
||||
membershipStatus,
|
||||
} = validation.data;
|
||||
|
||||
log.debug("Updating user", {
|
||||
id,
|
||||
@@ -314,6 +351,8 @@ export async function PUT(request: NextRequest) {
|
||||
role,
|
||||
phone,
|
||||
gymId,
|
||||
membershipType,
|
||||
membershipStatus,
|
||||
});
|
||||
|
||||
const db = await getDatabase();
|
||||
@@ -335,6 +374,27 @@ export async function PUT(request: NextRequest) {
|
||||
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
|
||||
const requesterRole = requester.role;
|
||||
const allowedByRole: Record<string, string[]> = {
|
||||
@@ -345,10 +405,27 @@ export async function PUT(request: NextRequest) {
|
||||
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}'`);
|
||||
}
|
||||
|
||||
// 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
|
||||
if (email && email !== existingUser.email) {
|
||||
const userWithEmail = await db.getUserByEmail(email);
|
||||
@@ -359,24 +436,27 @@ export async function PUT(request: NextRequest) {
|
||||
|
||||
// Update Clerk publicMetadata (role/gymId) to propagate via webhook
|
||||
// Note: Only update metadata when a change is requested
|
||||
try {
|
||||
const client = await clerkClient();
|
||||
const publicMetadata: Record<string, unknown> = {};
|
||||
log.debug("Preparing Clerk metadata update", {
|
||||
targetUserId: id,
|
||||
role,
|
||||
gymId,
|
||||
});
|
||||
const client = await clerkClient();
|
||||
const publicMetadata: Record<string, unknown> = {};
|
||||
log.debug("Preparing Clerk metadata update", {
|
||||
targetUserId: id,
|
||||
role,
|
||||
gymId,
|
||||
});
|
||||
|
||||
if (role) {
|
||||
publicMetadata.role = role;
|
||||
}
|
||||
if (gymId !== undefined) {
|
||||
publicMetadata.gymId = gymId === null ? null : String(gymId);
|
||||
}
|
||||
if (role) {
|
||||
publicMetadata.role = role;
|
||||
}
|
||||
if (gymId !== undefined) {
|
||||
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, {
|
||||
publicMetadata,
|
||||
});
|
||||
@@ -385,14 +465,20 @@ export async function PUT(request: NextRequest) {
|
||||
role: clerkResult.publicMetadata?.role,
|
||||
gymId: clerkResult.publicMetadata?.gymId,
|
||||
});
|
||||
} else {
|
||||
log.debug("No Clerk metadata changes requested");
|
||||
} catch (clerkErr: any) {
|
||||
// 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)
|
||||
@@ -414,6 +500,43 @@ export async function PUT(request: NextRequest) {
|
||||
);
|
||||
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 = {
|
||||
...existingUser,
|
||||
email: email ?? existingUser.email,
|
||||
|
||||
@@ -1,96 +1,102 @@
|
||||
'use client'
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { format } from 'date-fns'
|
||||
|
||||
interface Attendance {
|
||||
id: string
|
||||
clientId: string
|
||||
checkInTime: string
|
||||
checkOutTime?: string
|
||||
type: string
|
||||
notes?: string
|
||||
}
|
||||
import { useAttendance } from "@/hooks/use-api";
|
||||
import { PageHeader } from "@/components/ui/PageHeader";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export default function AttendancePage() {
|
||||
const [attendance, setAttendance] = useState<Attendance[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const fetchAttendance = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/admin/attendance')
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setAttendance(data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching attendance:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
fetchAttendance()
|
||||
}, [])
|
||||
|
||||
if (loading) {
|
||||
return <div className="p-8">Loading...</div>
|
||||
}
|
||||
const { data: attendance = [], isLoading } = useAttendance();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="p-8">
|
||||
<h1 className="text-2xl font-bold mb-6">Attendance Monitoring</h1>
|
||||
|
||||
<div className="bg-white rounded-lg shadow overflow-hidden">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Client ID
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Type
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Check In
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Check Out
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Status
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{attendance.map((record) => (
|
||||
<tr key={record.id}>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
|
||||
{record.clientId}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 capitalize">
|
||||
{record.type}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{format(new Date(record.checkInTime), 'PP p')}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{record.checkOutTime ? format(new Date(record.checkOutTime), 'PP p') : '-'}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${record.checkOutTime
|
||||
? 'bg-gray-100 text-gray-800'
|
||||
: 'bg-green-100 text-green-800'
|
||||
}`}>
|
||||
{record.checkOutTime ? 'Completed' : 'Active'}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Attendance"
|
||||
description="Monitor gym check-ins and check-outs"
|
||||
breadcrumbs={[{ label: "Attendance" }]}
|
||||
/>
|
||||
<div className="card-modern">
|
||||
<div className="animate-pulse space-y-4">
|
||||
{[...Array(5)].map((_, i) => (
|
||||
<div key={i} className="h-12 bg-muted rounded" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Attendance"
|
||||
description="Monitor gym check-ins and check-outs"
|
||||
breadcrumbs={[{ label: "Attendance" }]}
|
||||
/>
|
||||
|
||||
<div className="card-modern">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b border-border">
|
||||
<th className="text-left py-3 px-4 text-sm font-medium text-muted-foreground">
|
||||
Client
|
||||
</th>
|
||||
<th className="text-left py-3 px-4 text-sm font-medium text-muted-foreground">
|
||||
Type
|
||||
</th>
|
||||
<th className="text-left py-3 px-4 text-sm font-medium text-muted-foreground">
|
||||
Check In
|
||||
</th>
|
||||
<th className="text-left py-3 px-4 text-sm font-medium text-muted-foreground">
|
||||
Check Out
|
||||
</th>
|
||||
<th className="text-left py-3 px-4 text-sm font-medium text-muted-foreground">
|
||||
Status
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{attendance.map((record) => (
|
||||
<tr
|
||||
key={record.id}
|
||||
className="border-b border-border/50 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<td className="py-3 px-4 text-sm">
|
||||
{record.userId.substring(0, 8)}...
|
||||
</td>
|
||||
<td className="py-3 px-4 text-sm capitalize text-muted-foreground">
|
||||
{record.type}
|
||||
</td>
|
||||
<td className="py-3 px-4 text-sm text-muted-foreground">
|
||||
{new Date(record.checkIn).toLocaleString()}
|
||||
</td>
|
||||
<td className="py-3 px-4 text-sm text-muted-foreground">
|
||||
{record.checkOut
|
||||
? new Date(record.checkOut).toLocaleString()
|
||||
: "-"}
|
||||
</td>
|
||||
<td className="py-3 px-4">
|
||||
<Badge variant={record.checkOut ? "gray" : "success"}>
|
||||
{record.checkOut ? "Completed" : "Active"}
|
||||
</Badge>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{attendance.length === 0 && (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={5}
|
||||
className="py-8 text-center text-muted-foreground"
|
||||
>
|
||||
No attendance records found
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+202
-30
@@ -1,76 +1,248 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--background: 0 0% 98%;
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
|
||||
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 222.2 84% 4.9%;
|
||||
|
||||
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 222.2 84% 4.9%;
|
||||
|
||||
--primary: 222.2 47.4% 11.2%;
|
||||
|
||||
--primary: 221.2 83.2% 53.3%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
|
||||
|
||||
--secondary: 210 40% 96.1%;
|
||||
--secondary-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
|
||||
--muted: 210 40% 96.1%;
|
||||
--muted-foreground: 215.4 16.3% 46.9%;
|
||||
|
||||
|
||||
--accent: 210 40% 96.1%;
|
||||
--accent-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
|
||||
|
||||
--success: 142.1 76.2% 36.3%;
|
||||
--success-foreground: 355.7 100% 97.3%;
|
||||
|
||||
--warning: 37.7 93.1% 50.2%;
|
||||
--warning-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
--info: 199.4 86.4% 48.4%;
|
||||
--info-foreground: 210 40% 98%;
|
||||
|
||||
--border: 214.3 31.8% 91.4%;
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
--ring: 222.2 84% 4.9%;
|
||||
|
||||
--radius: 0.5rem;
|
||||
--ring: 221.2 83.2% 53.3%;
|
||||
|
||||
--radius: 0.625rem;
|
||||
|
||||
--sidebar-background: 222.2 47.4% 7.8%;
|
||||
--sidebar-foreground: 210 40% 98%;
|
||||
--sidebar-primary: 221.2 83.2% 53.3%;
|
||||
--sidebar-primary-foreground: 210 40% 98%;
|
||||
--sidebar-accent: 217.2 32.6% 17.5%;
|
||||
--sidebar-accent-foreground: 210 40% 98%;
|
||||
--sidebar-border: 217.2 32.6% 17.5%;
|
||||
--sidebar-ring: 217.2 91.6% 59.8%;
|
||||
}
|
||||
|
||||
|
||||
.dark {
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 98%;
|
||||
|
||||
--card: 222.2 84% 4.9%;
|
||||
|
||||
--card: 222.2 47.4% 10.2%;
|
||||
--card-foreground: 210 40% 98%;
|
||||
|
||||
--popover: 222.2 84% 4.9%;
|
||||
|
||||
--popover: 222.2 47.4% 10.2%;
|
||||
--popover-foreground: 210 40% 98%;
|
||||
|
||||
--primary: 210 40% 98%;
|
||||
|
||||
--primary: 217.2 91.2% 59.8%;
|
||||
--primary-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 98%;
|
||||
|
||||
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
|
||||
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
|
||||
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
|
||||
|
||||
--success: 142.1 76.2% 36.3%;
|
||||
--success-foreground: 355.7 100% 97.3%;
|
||||
|
||||
--warning: 37.7 93.1% 50.2%;
|
||||
--warning-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
--info: 199.4 86.4% 48.4%;
|
||||
--info-foreground: 210 40% 98%;
|
||||
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
--ring: 212.7 26.8% 83.9%;
|
||||
--ring: 224.3 76.3% 48%;
|
||||
|
||||
--sidebar-background: 222.2 47.4% 7.8%;
|
||||
--sidebar-foreground: 210 40% 98%;
|
||||
--sidebar-primary: 217.2 91.2% 59.8%;
|
||||
--sidebar-primary-foreground: 222.2 47.4% 11.2%;
|
||||
--sidebar-accent: 217.2 32.6% 17.5%;
|
||||
--sidebar-accent-foreground: 210 40% 98%;
|
||||
--sidebar-border: 217.2 32.6% 17.5%;
|
||||
--sidebar-ring: 217.2 91.6% 59.8%;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
@apply bg-background text-foreground antialiased;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.gradient-mesh {
|
||||
background:
|
||||
radial-gradient(
|
||||
at 40% 20%,
|
||||
hsla(221, 83%, 53%, 0.1) 0px,
|
||||
transparent 50%
|
||||
),
|
||||
radial-gradient(at 80% 0%, hsla(189, 97%, 66%, 0.1) 0px, transparent 50%),
|
||||
radial-gradient(at 0% 50%, hsla(355, 85%, 93%, 0.3) 0px, transparent 50%),
|
||||
radial-gradient(
|
||||
at 80% 50%,
|
||||
hsla(240, 75%, 98%, 0.3) 0px,
|
||||
transparent 50%
|
||||
),
|
||||
radial-gradient(at 0% 100%, hsla(22, 100%, 92%, 0.2) 0px, transparent 50%);
|
||||
}
|
||||
|
||||
.glass {
|
||||
@apply backdrop-blur-xl bg-white/70 dark:bg-black/70;
|
||||
}
|
||||
|
||||
.text-gradient {
|
||||
@apply bg-clip-text text-transparent bg-gradient-to-r from-primary to-primary/60;
|
||||
}
|
||||
|
||||
.animate-fade-in {
|
||||
animation: fadeIn 0.5s ease-out forwards;
|
||||
}
|
||||
|
||||
.animate-slide-up {
|
||||
animation: slideUp 0.5s ease-out forwards;
|
||||
}
|
||||
|
||||
.animate-scale-in {
|
||||
animation: scaleIn 0.3s ease-out forwards;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes scaleIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.95);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.stagger-1 {
|
||||
animation-delay: 0.1s;
|
||||
}
|
||||
.stagger-2 {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
.stagger-3 {
|
||||
animation-delay: 0.3s;
|
||||
}
|
||||
.stagger-4 {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
.stagger-5 {
|
||||
animation-delay: 0.5s;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.btn-primary {
|
||||
@apply inline-flex items-center justify-center rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow-sm transition-all duration-200 hover:bg-primary/90 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
@apply inline-flex items-center justify-center rounded-lg bg-secondary px-4 py-2 text-sm font-medium text-secondary-foreground shadow-sm transition-all duration-200 hover:bg-secondary/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50;
|
||||
}
|
||||
|
||||
.btn-ghost {
|
||||
@apply inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium text-muted-foreground transition-all duration-200 hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
@apply inline-flex items-center justify-center rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground shadow-sm transition-all duration-200 hover:bg-destructive/90 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50;
|
||||
}
|
||||
|
||||
.card-modern {
|
||||
@apply rounded-xl border border-border/50 bg-card p-6 shadow-sm transition-all duration-200 hover:shadow-md;
|
||||
}
|
||||
|
||||
.card-elevated {
|
||||
@apply rounded-xl border border-border/50 bg-card p-6 shadow-lg transition-all duration-200 hover:shadow-xl hover:-translate-y-0.5;
|
||||
}
|
||||
|
||||
.input-modern {
|
||||
@apply flex h-10 w-full rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-200;
|
||||
}
|
||||
|
||||
.badge-success {
|
||||
@apply inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800 dark:bg-green-900/30 dark:text-green-400;
|
||||
}
|
||||
|
||||
.badge-warning {
|
||||
@apply inline-flex items-center rounded-full bg-yellow-100 px-2.5 py-0.5 text-xs font-medium text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400;
|
||||
}
|
||||
|
||||
.badge-error {
|
||||
@apply inline-flex items-center rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-medium text-red-800 dark:bg-red-900/30 dark:text-red-400;
|
||||
}
|
||||
|
||||
.badge-info {
|
||||
@apply inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900/30 dark:text-blue-400;
|
||||
}
|
||||
|
||||
.badge-default {
|
||||
@apply inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-800 dark:bg-gray-800 dark:text-gray-300;
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ import {
|
||||
UserButton,
|
||||
} from "@clerk/nextjs";
|
||||
import { Sidebar } from "@/components/ui/Sidebar";
|
||||
import { Toaster } from "sonner";
|
||||
import { ToasterProvider } from "@/components/providers/ToasterProvider";
|
||||
import { QueryProvider } from "@/components/providers/QueryProvider";
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] });
|
||||
|
||||
@@ -25,15 +26,19 @@ export default function RootLayout({
|
||||
}) {
|
||||
return (
|
||||
<ClerkProvider>
|
||||
<html lang="en">
|
||||
<body className={inter.className}>
|
||||
<div className="flex min-h-screen bg-slate-50">
|
||||
<Sidebar />
|
||||
<main className="flex-1 ml-20 p-8">{children}</main>
|
||||
</div>
|
||||
<Toaster richColors position="top-right" />
|
||||
</body>
|
||||
</html>
|
||||
<QueryProvider>
|
||||
<html lang="en">
|
||||
<body className={inter.className}>
|
||||
<div className="flex min-h-screen bg-background">
|
||||
<Sidebar />
|
||||
<main className="flex-1 p-6 lg:p-8 min-h-screen">
|
||||
<div className="max-w-7xl mx-auto space-y-8">{children}</div>
|
||||
</main>
|
||||
</div>
|
||||
<ToasterProvider />
|
||||
</body>
|
||||
</html>
|
||||
</QueryProvider>
|
||||
</ClerkProvider>
|
||||
);
|
||||
}
|
||||
+127
-77
@@ -1,100 +1,150 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Users, CreditCard, CalendarCheck, TrendingUp } from "lucide-react";
|
||||
import { StatsCard } from "@/components/ui/StatsCard";
|
||||
import {
|
||||
Users,
|
||||
CreditCard,
|
||||
CalendarCheck,
|
||||
TrendingUp,
|
||||
RefreshCw,
|
||||
} from "lucide-react";
|
||||
import { StatsCard, StatsCardSkeleton } from "@/components/ui/StatsCard";
|
||||
import { PageHeader } from "@/components/ui/PageHeader";
|
||||
import { UserManagement } from "@/components/users/UserManagement";
|
||||
import { AnalyticsDashboard } from "@/components/analytics/AnalyticsDashboard";
|
||||
import axios from "axios";
|
||||
|
||||
interface DashboardStats {
|
||||
totalUsers: number;
|
||||
activeClients: number;
|
||||
totalRevenue: number;
|
||||
revenueGrowth: number;
|
||||
}
|
||||
import { useDashboardStats } from "@/hooks/use-api";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useUser } from "@clerk/nextjs";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { GymSelector } from "@/components/gym/GymSelector";
|
||||
|
||||
export default function Home() {
|
||||
const [stats, setStats] = useState<DashboardStats>({
|
||||
totalUsers: 0,
|
||||
activeClients: 0,
|
||||
totalRevenue: 0,
|
||||
revenueGrowth: 0,
|
||||
});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const { user } = useUser();
|
||||
const searchParams = useSearchParams();
|
||||
const gymId = searchParams.get("gymId") ?? undefined;
|
||||
|
||||
useEffect(() => {
|
||||
const fetchStats = async () => {
|
||||
try {
|
||||
const response = await axios.get("/api/admin/stats");
|
||||
setStats(response.data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch dashboard stats:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
const {
|
||||
data: stats,
|
||||
isLoading,
|
||||
refetch,
|
||||
isFetching,
|
||||
} = useDashboardStats(gymId);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
fetchStats();
|
||||
}, []);
|
||||
// Get user role from metadata
|
||||
const userRole = (user?.publicMetadata?.role as string) ?? "client";
|
||||
|
||||
const handleRefresh = () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard-stats"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["analytics"] });
|
||||
refetch();
|
||||
};
|
||||
|
||||
const formatCurrency = (value: number) => {
|
||||
return new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
}).format(value);
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 0,
|
||||
}).format(value || 0);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-slate-900">Dashboard</h2>
|
||||
<p className="text-slate-500 mt-2">Welcome back, here's what's happening today.</p>
|
||||
<PageHeader
|
||||
title="Dashboard"
|
||||
description="Welcome back! Here's what's happening with your gym today."
|
||||
actions={
|
||||
<div className="flex items-center gap-3">
|
||||
<GymSelector userRole={userRole} />
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleRefresh}
|
||||
disabled={isFetching}
|
||||
className="gap-2"
|
||||
>
|
||||
<RefreshCw
|
||||
className={`h-4 w-4 ${isFetching ? "animate-spin" : ""}`}
|
||||
/>
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Stats Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{isLoading ? (
|
||||
<>
|
||||
<StatsCardSkeleton />
|
||||
<StatsCardSkeleton />
|
||||
<StatsCardSkeleton />
|
||||
<StatsCardSkeleton />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<StatsCard
|
||||
title="Total Users"
|
||||
value={stats?.totalUsers ?? 0}
|
||||
change="+12%"
|
||||
trend="up"
|
||||
icon={Users}
|
||||
color="blue"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Active Clients"
|
||||
value={stats?.activeClients ?? 0}
|
||||
change="+5%"
|
||||
trend="up"
|
||||
icon={CalendarCheck}
|
||||
color="green"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Revenue"
|
||||
value={formatCurrency(stats?.totalRevenue ?? 0)}
|
||||
change={`${(stats?.revenueGrowth ?? 0) > 0 ? "+" : ""}${stats?.revenueGrowth ?? 0}%`}
|
||||
trend={(stats?.revenueGrowth ?? 0) >= 0 ? "up" : "down"}
|
||||
icon={CreditCard}
|
||||
color="purple"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Growth"
|
||||
value="24%"
|
||||
change="-2%"
|
||||
trend="down"
|
||||
icon={TrendingUp}
|
||||
color="orange"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
<StatsCard
|
||||
title="Total Users"
|
||||
value={loading ? "..." : stats.totalUsers}
|
||||
change="+12%" // Placeholder for now as we don't track historical growth yet
|
||||
trend="up"
|
||||
icon={Users}
|
||||
color="blue"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Active Clients"
|
||||
value={loading ? "..." : stats.activeClients}
|
||||
change="+5%"
|
||||
trend="up"
|
||||
icon={CalendarCheck}
|
||||
color="green"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Revenue"
|
||||
value={loading ? "..." : formatCurrency(stats.totalRevenue)}
|
||||
change={`${stats.revenueGrowth > 0 ? "+" : ""}${stats.revenueGrowth}%`}
|
||||
trend={stats.revenueGrowth >= 0 ? "up" : "down"}
|
||||
icon={CreditCard}
|
||||
color="purple"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Growth"
|
||||
value="24%" // Placeholder
|
||||
change="-2%"
|
||||
trend="down"
|
||||
icon={TrendingUp}
|
||||
color="orange"
|
||||
/>
|
||||
</div>
|
||||
{/* Main Content Grid */}
|
||||
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
|
||||
{/* <div className="xl:col-span-2"> */}
|
||||
{/* <div className="card-modern"> */}
|
||||
{/* <div className="mb-6"> */}
|
||||
{/* <h3 className="text-lg font-semibold">Recent Activity</h3> */}
|
||||
{/* <p className="text-sm text-muted-foreground"> */}
|
||||
{/* Manage and view your users */}
|
||||
{/* </p> */}
|
||||
{/* </div> */}
|
||||
{/* <UserManagement /> */}
|
||||
{/* </div> */}
|
||||
{/* </div> */}
|
||||
|
||||
<div className="flex flex-col gap-8">
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
|
||||
<h3 className="text-xl font-bold text-slate-900 mb-6">Recent Activity</h3>
|
||||
<UserManagement />
|
||||
</div>
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
|
||||
<h3 className="text-xl font-bold text-slate-900 mb-6">Quick Analytics</h3>
|
||||
<AnalyticsDashboard />
|
||||
{/* Analytics Sidebar */}
|
||||
<div className="xl:col-span-3">
|
||||
<div className="card-modern">
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-semibold">Quick Analytics</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Overview of your gym metrics
|
||||
</p>
|
||||
</div>
|
||||
<AnalyticsDashboard gymId={gymId} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function ProfilePage() {
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h1 className="text-2xl font-bold">Profile</h1>
|
||||
<Button
|
||||
variant={isEditing ? "primary" : "secondary"}
|
||||
variant={isEditing ? "default" : "secondary"}
|
||||
onClick={() => setIsEditing(!isEditing)}
|
||||
>
|
||||
{isEditing ? "Cancel" : "Edit Profile"}
|
||||
|
||||
@@ -1,86 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useUser } from "@clerk/nextjs";
|
||||
import log from "@/lib/logger";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface Recommendation {
|
||||
id: string;
|
||||
userId: string;
|
||||
content: string;
|
||||
recommendationText: string;
|
||||
activityPlan: string;
|
||||
dietPlan: string;
|
||||
status: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
import {
|
||||
useUsers,
|
||||
useRecommendations,
|
||||
useGenerateRecommendations,
|
||||
useApproveRecommendation,
|
||||
useUpdateRecommendation,
|
||||
type Recommendation,
|
||||
} from "@/hooks/use-api";
|
||||
import { PageHeader } from "@/components/ui/PageHeader";
|
||||
|
||||
export default function RecommendationsPage() {
|
||||
const { user } = useUser();
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [pendingRecommendations, setPendingRecommendations] = useState<
|
||||
Recommendation[]
|
||||
>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [generating, setGenerating] = useState<string | null>(null);
|
||||
const [useExternalModel, setUseExternalModel] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
const { data: users = [], isLoading: usersLoading } = useUsers();
|
||||
const { data: allRecommendations = [], isLoading: recsLoading } =
|
||||
useRecommendations();
|
||||
const pendingRecommendations = allRecommendations.filter(
|
||||
(r) => r.status === "pending",
|
||||
);
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
// Fetch users - API returns { success: true, data: { users: [...] }, meta: {...} }
|
||||
const usersRes = await fetch("/api/users");
|
||||
const usersResult = await usersRes.json();
|
||||
const usersArray = usersResult.data?.users || usersResult.users || [];
|
||||
setUsers(usersArray);
|
||||
|
||||
// Fetch pending recommendations - API returns { success: true, data: { recommendations: [...] }, meta: {...} }
|
||||
const recsRes = await fetch("/api/recommendations");
|
||||
const recsResult = await recsRes.json();
|
||||
const allRecs =
|
||||
recsResult.data?.recommendations || recsResult.recommendations || [];
|
||||
setPendingRecommendations(
|
||||
allRecs.filter((r: Recommendation) => r.status === "pending"),
|
||||
);
|
||||
} catch (error) {
|
||||
log.error("Failed to fetch data", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
const generateRec = useGenerateRecommendations();
|
||||
const approveRec = useApproveRecommendation();
|
||||
const updateRec = useUpdateRecommendation();
|
||||
|
||||
const handleGenerate = async (userId: string) => {
|
||||
setGenerating(userId);
|
||||
try {
|
||||
const res = await fetch("/api/recommendations/generate", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ userId, useExternalModel }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
toast.error(`Error: ${error.error}`);
|
||||
} else {
|
||||
toast.success("Recommendation generated successfully!");
|
||||
fetchData(); // Refresh data
|
||||
}
|
||||
await generateRec.mutateAsync(userId);
|
||||
toast.success("Recommendation generated successfully!");
|
||||
} catch (error) {
|
||||
log.error("Failed to generate recommendation", error);
|
||||
toast.error("Failed to generate recommendation.");
|
||||
} finally {
|
||||
setGenerating(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -89,25 +44,11 @@ export default function RecommendationsPage() {
|
||||
status: "approved" | "rejected",
|
||||
) => {
|
||||
try {
|
||||
const res = await fetch("/api/recommendations/approve", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
recommendationId,
|
||||
status,
|
||||
approvedBy: user?.id || "admin",
|
||||
}),
|
||||
await approveRec.mutateAsync({
|
||||
recommendationId,
|
||||
approved: status === "approved",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json();
|
||||
toast.error(
|
||||
`Failed to update status: ${errorData.error || "Unknown error"}`,
|
||||
);
|
||||
} else {
|
||||
toast.success("Recommendation status updated");
|
||||
fetchData(); // Refresh data
|
||||
}
|
||||
toast.success("Recommendation status updated");
|
||||
} catch (error) {
|
||||
log.error("Failed to approve recommendation", error);
|
||||
toast.error("Error processing request");
|
||||
@@ -124,168 +65,137 @@ export default function RecommendationsPage() {
|
||||
newActivityPlan === null ||
|
||||
newDietPlan === null
|
||||
) {
|
||||
// User cancelled one of the prompts
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/recommendations", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
id: rec.id,
|
||||
content: newContent,
|
||||
activityPlan: newActivityPlan,
|
||||
dietPlan: newDietPlan,
|
||||
}),
|
||||
await updateRec.mutateAsync({
|
||||
id: rec.id,
|
||||
content: newContent,
|
||||
activityPlan: newActivityPlan,
|
||||
dietPlan: newDietPlan,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json();
|
||||
toast.error(
|
||||
`Failed to update recommendation: ${errorData.error || "Unknown error"}`,
|
||||
);
|
||||
} else {
|
||||
toast.success("Recommendation updated successfully!");
|
||||
fetchData(); // Refresh data
|
||||
}
|
||||
toast.success("Recommendation updated successfully!");
|
||||
} catch (error) {
|
||||
log.error("Failed to update recommendation", error);
|
||||
toast.error("Failed to update recommendation.");
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
if (usersLoading || recsLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-screen">
|
||||
<div className="text-xl">Loading...</div>
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="text-lg">Loading...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-10 px-4">
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<h1 className="text-3xl font-bold">AI Recommendations</h1>
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="AI Recommendations"
|
||||
description="Generate and manage AI-powered fitness recommendations"
|
||||
breadcrumbs={[{ label: "AI Recommendations" }]}
|
||||
/>
|
||||
|
||||
{/* Model Selection Toggle */}
|
||||
<div className="flex items-center gap-3 bg-white px-4 py-2 rounded-lg shadow">
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{useExternalModel ? "DeepSeek AI" : "Local Ollama"}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setUseExternalModel(!useExternalModel)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
|
||||
useExternalModel ? "bg-blue-600" : "bg-gray-300"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
useExternalModel ? "translate-x-6" : "translate-x-1"
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
<span className="text-xs text-gray-500">
|
||||
{useExternalModel ? "External" : "Local"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Generate Section */}
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold mb-4">
|
||||
Generate Recommendations
|
||||
</h2>
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<p className="mb-4 text-gray-600">
|
||||
<div className="card-modern">
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-semibold">Generate Recommendations</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Select a user to generate a new daily recommendation.
|
||||
</p>
|
||||
<ul className="space-y-4">
|
||||
{users.map((user) => (
|
||||
<li
|
||||
key={user.id}
|
||||
className="flex items-center justify-between border-b pb-2"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">
|
||||
{user.firstName} {user.lastName}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">{user.email}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleGenerate(user.id)}
|
||||
disabled={generating === user.id}
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 disabled:opacity-50"
|
||||
>
|
||||
{generating === user.id ? "Generating..." : "Generate"}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{users.length === 0 && (
|
||||
<p className="text-gray-500 italic">No users found.</p>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
<ul className="space-y-4">
|
||||
{users.map((user) => (
|
||||
<li
|
||||
key={user.id}
|
||||
className="flex items-center justify-between border-b border-border/50 pb-4 last:border-0 last:pb-0"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">
|
||||
{user.firstName} {user.lastName}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">{user.email}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleGenerate(user.id)}
|
||||
disabled={generateRec.isPending}
|
||||
className="btn-primary"
|
||||
>
|
||||
{generateRec.isPending ? "Generating..." : "Generate"}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{users.length === 0 && (
|
||||
<p className="text-muted-foreground italic">No users found.</p>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Pending Approvals Section */}
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold mb-4">Pending Approvals</h2>
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
{pendingRecommendations.length === 0 ? (
|
||||
<p className="text-gray-500 italic">
|
||||
No pending recommendations.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-6">
|
||||
{pendingRecommendations.map((rec) => (
|
||||
<li key={rec.id} className="border rounded p-4">
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<h3 className="font-bold">For: User {rec.userId}</h3>
|
||||
<span className="text-xs text-gray-500">
|
||||
{new Date(rec.createdAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm mb-4">
|
||||
<div>
|
||||
<span className="font-semibold">Advice:</span>{" "}
|
||||
{rec.recommendationText}
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-semibold">Activity:</span>{" "}
|
||||
{rec.activityPlan}
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-semibold">Diet:</span>{" "}
|
||||
{rec.dietPlan}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
<button
|
||||
onClick={() => handleEdit(rec)}
|
||||
className="flex-1 bg-blue-500 text-white py-2 rounded hover:bg-blue-600"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleApprove(rec.id, "approved")}
|
||||
className="flex-1 bg-green-600 text-white py-2 rounded hover:bg-green-700"
|
||||
>
|
||||
Approve
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleApprove(rec.id, "rejected")}
|
||||
className="flex-1 bg-red-600 text-white py-2 rounded hover:bg-red-700"
|
||||
>
|
||||
Reject
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="card-modern">
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-semibold">Pending Approvals</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Review and approve AI-generated recommendations
|
||||
</p>
|
||||
</div>
|
||||
{pendingRecommendations.length === 0 ? (
|
||||
<p className="text-muted-foreground italic">
|
||||
No pending recommendations.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-4">
|
||||
{pendingRecommendations.map((rec) => (
|
||||
<li
|
||||
key={rec.id}
|
||||
className="border border-border rounded-lg p-4"
|
||||
>
|
||||
<div className="flex justify-between items-start mb-3">
|
||||
<h4 className="font-semibold">For: User {rec.userId}</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(rec.createdAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm mb-4">
|
||||
<div>
|
||||
<span className="font-medium">Advice:</span>{" "}
|
||||
{rec.recommendationText}
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-medium">Activity:</span>{" "}
|
||||
{rec.activityPlan}
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-medium">Diet:</span> {rec.dietPlan}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => handleEdit(rec)}
|
||||
className="btn-secondary flex-1"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleApprove(rec.id, "approved")}
|
||||
className="btn-primary flex-1 bg-emerald-600 hover:bg-emerald-700"
|
||||
>
|
||||
Approve
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleApprove(rec.id, "rejected")}
|
||||
className="btn-danger flex-1"
|
||||
>
|
||||
Reject
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -9,6 +9,10 @@ import {
|
||||
AlertTriangle,
|
||||
Check,
|
||||
Loader2,
|
||||
Trash2,
|
||||
Users,
|
||||
CalendarCheck,
|
||||
TrendingUp,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useUser } from "@clerk/nextjs";
|
||||
@@ -26,6 +30,21 @@ interface Gym {
|
||||
location?: string | null;
|
||||
status: "active" | "inactive";
|
||||
adminUserId: string;
|
||||
createdAt?: number;
|
||||
}
|
||||
|
||||
interface GymStats {
|
||||
totalUsers: number;
|
||||
admins: number;
|
||||
trainers: number;
|
||||
clients: number;
|
||||
membershipStats: {
|
||||
basic: number;
|
||||
premium: number;
|
||||
vip: number;
|
||||
};
|
||||
activeClients: number;
|
||||
attendanceLast30Days: number;
|
||||
}
|
||||
|
||||
export default function SettingsPage() {
|
||||
@@ -46,6 +65,13 @@ export default function SettingsPage() {
|
||||
type: "success" | "error";
|
||||
text: string;
|
||||
} | null>(null);
|
||||
|
||||
// Selected gym for details
|
||||
const [selectedGym, setSelectedGym] = useState<Gym | null>(null);
|
||||
const [gymStats, setGymStats] = useState<GymStats | null>(null);
|
||||
const [statsLoading, setStatsLoading] = useState(false);
|
||||
const [deletingGym, setDeletingGym] = useState(false);
|
||||
|
||||
// Create Gym modal state
|
||||
const [showCreateGym, setShowCreateGym] = useState(false);
|
||||
const [gymName, setGymName] = useState("");
|
||||
@@ -77,11 +103,33 @@ export default function SettingsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const fetchGymStats = async (gymId: string) => {
|
||||
setStatsLoading(true);
|
||||
try {
|
||||
const res = await axios.get(`/api/gyms/${gymId}/stats`);
|
||||
if (res.data?.stats) {
|
||||
setGymStats(res.data.stats);
|
||||
}
|
||||
} catch (error) {
|
||||
log.error("Failed to fetch gym stats", error);
|
||||
} finally {
|
||||
setStatsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchBackups();
|
||||
fetchGyms();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedGym) {
|
||||
fetchGymStats(selectedGym.id);
|
||||
} else {
|
||||
setGymStats(null);
|
||||
}
|
||||
}, [selectedGym]);
|
||||
|
||||
const handleCreateBackup = async () => {
|
||||
setCreatingBackup(true);
|
||||
setMessage(null);
|
||||
@@ -111,7 +159,6 @@ export default function SettingsPage() {
|
||||
try {
|
||||
await axios.post("/api/admin/backups/restore", { filename });
|
||||
setMessage({ type: "success", text: "Database restored successfully" });
|
||||
// Optional: Refresh page or force re-login if session is invalidated
|
||||
} catch (error) {
|
||||
log.error("Failed to restore backup", error);
|
||||
setMessage({ type: "error", text: "Failed to restore backup" });
|
||||
@@ -135,21 +182,39 @@ export default function SettingsPage() {
|
||||
return new Date(dateString).toLocaleString();
|
||||
};
|
||||
|
||||
const handleSelectGym = async (gymId: string | null) => {
|
||||
const handleSelectGym = async (gym: Gym | null) => {
|
||||
setSelectedGym(gym);
|
||||
setGymStats(null);
|
||||
};
|
||||
|
||||
const handleDeleteGym = async (gymId: string) => {
|
||||
if (
|
||||
!window.confirm(
|
||||
"Are you sure you want to delete this gym? This action cannot be undone.",
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDeletingGym(true);
|
||||
setGymMessage(null);
|
||||
try {
|
||||
// Update current user's gym selection
|
||||
await axios.patch("/api/users/gym", { gymId });
|
||||
setGymMessage({
|
||||
type: "success",
|
||||
text: gymId ? "Gym selected successfully" : "Proceeding without gym",
|
||||
});
|
||||
await axios.delete(`/api/gyms/${gymId}`);
|
||||
setGymMessage({ type: "success", text: "Gym deleted successfully" });
|
||||
setSelectedGym(null);
|
||||
setGymStats(null);
|
||||
fetchGyms();
|
||||
} catch (error) {
|
||||
log.error("Failed to set gym", error);
|
||||
setGymMessage({ type: "error", text: "Failed to set gym" });
|
||||
log.error("Failed to delete gym", error);
|
||||
setGymMessage({ type: "error", text: "Failed to delete gym" });
|
||||
} finally {
|
||||
setDeletingGym(false);
|
||||
}
|
||||
};
|
||||
|
||||
const userRole = (user?.publicMetadata?.role as string) ?? "client";
|
||||
const isSuperAdmin = userRole === "superAdmin";
|
||||
|
||||
return (
|
||||
<div className="space-y-8 p-8">
|
||||
<div>
|
||||
@@ -159,7 +224,7 @@ export default function SettingsPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Gym Picker */}
|
||||
{/* Gym Management */}
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -168,10 +233,12 @@ export default function SettingsPage() {
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-slate-900">
|
||||
Gym Selection
|
||||
Gym Management
|
||||
</h3>
|
||||
<p className="text-sm text-slate-500">
|
||||
Select your gym or proceed without a gym
|
||||
{isSuperAdmin
|
||||
? "Select a gym to view details, create or delete gyms"
|
||||
: "Select your gym or proceed without a gym"}
|
||||
</p>
|
||||
<p className="text-xs text-blue-600 mt-1">
|
||||
{user ? (
|
||||
@@ -180,11 +247,6 @@ export default function SettingsPage() {
|
||||
<span className="font-medium">
|
||||
{String(user.publicMetadata?.role ?? "unknown")}
|
||||
</span>
|
||||
{" • "}
|
||||
Gym ID:{" "}
|
||||
<span className="font-medium">
|
||||
{String(user.publicMetadata?.gymId ?? "none")}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
"Loading user metadata..."
|
||||
@@ -196,6 +258,8 @@ export default function SettingsPage() {
|
||||
<Button
|
||||
onClick={fetchGyms}
|
||||
disabled={gymsLoading}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{gymsLoading ? (
|
||||
@@ -203,14 +267,17 @@ export default function SettingsPage() {
|
||||
) : (
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
)}
|
||||
Refresh Gyms
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setShowCreateGym(true)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
Create Gym
|
||||
Refresh
|
||||
</Button>
|
||||
{isSuperAdmin && (
|
||||
<Button
|
||||
onClick={() => setShowCreateGym(true)}
|
||||
size="sm"
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
Create Gym
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -226,6 +293,7 @@ export default function SettingsPage() {
|
||||
{gymMessage.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showCreateGym && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white p-6 rounded-lg shadow-lg max-w-md w-full">
|
||||
@@ -310,59 +378,191 @@ export default function SettingsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
<div className="border rounded-lg p-4 flex flex-col justify-between">
|
||||
<div>
|
||||
<h4 className="font-semibold text-slate-900">
|
||||
Proceed without gym
|
||||
</h4>
|
||||
<p className="text-sm text-slate-600 mt-1">
|
||||
You can select a gym later.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="mt-4"
|
||||
onClick={() => handleSelectGym(null)}
|
||||
>
|
||||
Proceed without gym
|
||||
</Button>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Gym List */}
|
||||
<div className="lg:col-span-1 space-y-4">
|
||||
<h4 className="font-semibold text-slate-900">Gyms</h4>
|
||||
{gymsLoading ? (
|
||||
<div className="flex items-center justify-center p-8 text-slate-500">
|
||||
<Loader2 className="w-5 h-5 animate-spin mr-2" />
|
||||
Loading...
|
||||
</div>
|
||||
) : gyms.length === 0 ? (
|
||||
<div className="p-4 text-center text-slate-500">
|
||||
No active gyms found.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 max-h-96 overflow-y-auto">
|
||||
{gyms.map((gym) => (
|
||||
<div
|
||||
key={gym.id}
|
||||
className={`border rounded-lg p-3 cursor-pointer transition-colors ${
|
||||
selectedGym?.id === gym.id
|
||||
? "border-blue-500 bg-blue-50"
|
||||
: "hover:bg-slate-50"
|
||||
}`}
|
||||
onClick={() => handleSelectGym(gym)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h5 className="font-medium text-slate-900">
|
||||
{gym.name}
|
||||
</h5>
|
||||
<p className="text-xs text-slate-500">
|
||||
{gym.location || "No location"}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
className={`text-xs px-2 py-1 rounded ${
|
||||
gym.status === "active"
|
||||
? "bg-green-100 text-green-700"
|
||||
: "bg-red-100 text-red-700"
|
||||
}`}
|
||||
>
|
||||
{gym.status}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{gymsLoading ? (
|
||||
<div className="col-span-full flex items-center justify-center p-8 text-slate-500">
|
||||
<Loader2 className="w-5 h-5 animate-spin mr-2" />
|
||||
Loading gyms...
|
||||
</div>
|
||||
) : gyms.length === 0 ? (
|
||||
<div className="col-span-full p-8 text-center text-slate-500">
|
||||
No active gyms found.
|
||||
</div>
|
||||
) : (
|
||||
gyms.map((gym) => (
|
||||
<div
|
||||
key={gym.id}
|
||||
className="border rounded-lg p-4 flex flex-col justify-between"
|
||||
>
|
||||
<div>
|
||||
<h4 className="font-semibold text-slate-900">{gym.name}</h4>
|
||||
<p className="text-sm text-slate-600 mt-1">
|
||||
{gym.location || "No location provided"}
|
||||
</p>
|
||||
{/* Gym Details / Stats */}
|
||||
<div className="lg:col-span-2">
|
||||
{selectedGym ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="font-semibold text-slate-900">
|
||||
{selectedGym.name} - Details
|
||||
</h4>
|
||||
{isSuperAdmin && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||
onClick={() => handleDeleteGym(selectedGym.id)}
|
||||
disabled={deletingGym}
|
||||
>
|
||||
{deletingGym ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="w-4 h-4 mr-1" />
|
||||
)}
|
||||
Delete Gym
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="default"
|
||||
className="mt-4"
|
||||
onClick={() => handleSelectGym(gym.id)}
|
||||
>
|
||||
Select this gym
|
||||
</Button>
|
||||
|
||||
{/* Gym Info */}
|
||||
<div className="grid grid-cols-2 gap-4 p-4 bg-slate-50 rounded-lg">
|
||||
<div>
|
||||
<p className="text-xs text-slate-500">Location</p>
|
||||
<p className="font-medium">
|
||||
{selectedGym.location || "Not specified"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-slate-500">Status</p>
|
||||
<p className="font-medium capitalize">
|
||||
{selectedGym.status}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
{statsLoading ? (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-slate-400" />
|
||||
</div>
|
||||
) : gymStats ? (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="p-4 bg-blue-50 rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Users className="w-4 h-4 text-blue-600" />
|
||||
<span className="text-xs text-blue-600">
|
||||
Total Users
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-blue-700">
|
||||
{gymStats.totalUsers}
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-4 bg-green-50 rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<CalendarCheck className="w-4 h-4 text-green-600" />
|
||||
<span className="text-xs text-green-600">
|
||||
Active Clients
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-green-700">
|
||||
{gymStats.activeClients}
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-4 bg-purple-50 rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<TrendingUp className="w-4 h-4 text-purple-600" />
|
||||
<span className="text-xs text-purple-600">
|
||||
Check-ins (30d)
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-purple-700">
|
||||
{gymStats.attendanceLast30Days}
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-4 bg-orange-50 rounded-lg">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Users className="w-4 h-4 text-orange-600" />
|
||||
<span className="text-xs text-orange-600">
|
||||
Trainers
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-orange-700">
|
||||
{gymStats.trainers}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Membership Distribution */}
|
||||
{gymStats && (
|
||||
<div className="mt-4">
|
||||
<h5 className="text-sm font-medium text-slate-700 mb-2">
|
||||
Membership Distribution
|
||||
</h5>
|
||||
<div className="flex gap-4">
|
||||
<div className="flex-1 p-3 bg-slate-100 rounded-lg text-center">
|
||||
<p className="text-2xl font-bold text-slate-700">
|
||||
{gymStats.membershipStats.basic}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">Basic</p>
|
||||
</div>
|
||||
<div className="flex-1 p-3 bg-blue-50 rounded-lg text-center">
|
||||
<p className="text-2xl font-bold text-blue-700">
|
||||
{gymStats.membershipStats.premium}
|
||||
</p>
|
||||
<p className="text-xs text-blue-500">Premium</p>
|
||||
</div>
|
||||
<div className="flex-1 p-3 bg-yellow-50 rounded-lg text-center">
|
||||
<p className="text-2xl font-bold text-yellow-700">
|
||||
{gymStats.membershipStats.vip}
|
||||
</p>
|
||||
<p className="text-xs text-yellow-600">VIP</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-64 bg-slate-50 rounded-lg">
|
||||
<p className="text-slate-500">Select a gym to view details</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Database Management */}
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -1,11 +1,30 @@
|
||||
import { UserManagement } from '@/components/users/UserManagement'
|
||||
"use client";
|
||||
|
||||
import { UserManagement } from "@/components/users/UserManagement";
|
||||
import { PageHeader } from "@/components/ui/PageHeader";
|
||||
import { useUser } from "@clerk/nextjs";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { GymSelector } from "@/components/gym/GymSelector";
|
||||
|
||||
export default function UsersPage() {
|
||||
const { user } = useUser();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const userRole = (user?.publicMetadata?.role as string) ?? "client";
|
||||
const gymId = searchParams.get("gymId") ?? undefined;
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-gray-50">
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<UserManagement />
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Users"
|
||||
description="Manage your gym members, trainers, and administrators"
|
||||
breadcrumbs={[{ label: "Users", href: "/users" }]}
|
||||
actions={<GymSelector userRole={userRole} />}
|
||||
/>
|
||||
|
||||
<div className="card-modern">
|
||||
<UserManagement gymId={gymId} />
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -71,11 +71,11 @@ export function Navigation(): ReactElement {
|
||||
<li key={item.href}>
|
||||
<Link href={item.href} className="flex items-center gap-2">
|
||||
<Button
|
||||
variant={pathname === item.href ? "primary" : "secondary"}
|
||||
variant={pathname === item.href ? "default" : "secondary"}
|
||||
className={cn(
|
||||
"h-9 px-4 py-2",
|
||||
pathname === item.href &&
|
||||
"bg-primary text-primary-foreground",
|
||||
"bg-primary text-primary-foreground",
|
||||
)}
|
||||
aria-current={pathname === item.href ? "page" : undefined}
|
||||
>
|
||||
|
||||
@@ -1,75 +1,38 @@
|
||||
'use client'
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { UserGrowthChart } from '@/components/charts/UserGrowthChart'
|
||||
import { MembershipDistributionChart } from '@/components/charts/MembershipDistributionChart'
|
||||
import { RevenueChart } from '@/components/charts/RevenueChart'
|
||||
import { Card, CardHeader, CardContent } from '@/components/ui/card'
|
||||
import { UserGrowthChart } from "@/components/charts/UserGrowthChart";
|
||||
import { MembershipDistributionChart } from "@/components/charts/MembershipDistributionChart";
|
||||
import { RevenueChart } from "@/components/charts/RevenueChart";
|
||||
import { Card, CardHeader, CardContent } from "@/components/ui/card";
|
||||
import { useAnalytics } from "@/hooks/use-api";
|
||||
|
||||
interface ChartData {
|
||||
label: string
|
||||
value: number
|
||||
color?: string
|
||||
interface AnalyticsDashboardProps {
|
||||
gymId?: string;
|
||||
}
|
||||
|
||||
export function AnalyticsDashboard() {
|
||||
const [userGrowthData, setUserGrowthData] = useState<ChartData[]>([])
|
||||
const [membershipData, setMembershipData] = useState<ChartData[]>([])
|
||||
const [revenueData, setRevenueData] = useState<ChartData[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
export function AnalyticsDashboard({ gymId }: AnalyticsDashboardProps) {
|
||||
const { data: analytics, isLoading } = useAnalytics(6, gymId);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAnalyticsData()
|
||||
}, [])
|
||||
const userGrowthData = analytics?.userGrowth ?? [];
|
||||
const membershipData = analytics?.membershipDistribution ?? [];
|
||||
const revenueData = analytics?.revenue ?? [];
|
||||
|
||||
const fetchAnalyticsData = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
// Mock data for demonstration - replace with real API calls
|
||||
const mockUserGrowth = [
|
||||
{ label: 'Jan', value: 45 },
|
||||
{ label: 'Feb', value: 52 },
|
||||
{ label: 'Mar', value: 61 },
|
||||
{ label: 'Apr', value: 58 },
|
||||
{ label: 'May', value: 67 },
|
||||
{ label: 'Jun', value: 74 },
|
||||
]
|
||||
const totalUsers =
|
||||
userGrowthData.length > 0
|
||||
? userGrowthData[userGrowthData.length - 1].value
|
||||
: 0;
|
||||
const totalRevenue = revenueData.reduce((sum, item) => sum + item.value, 0);
|
||||
const activeMembers = membershipData.reduce(
|
||||
(sum, item) => sum + item.value,
|
||||
0,
|
||||
);
|
||||
|
||||
const mockMembershipData = [
|
||||
{ label: 'Basic', value: 45, color: '#6b7280' },
|
||||
{ label: 'Premium', value: 28, color: '#3b82f6' },
|
||||
{ label: 'VIP', value: 12, color: '#f59e0b' },
|
||||
]
|
||||
|
||||
const mockRevenueData = [
|
||||
{ label: 'Jan', value: 12500, color: '#10b981' },
|
||||
{ label: 'Feb', value: 14200, color: '#10b981' },
|
||||
{ label: 'Mar', value: 16800, color: '#10b981' },
|
||||
{ label: 'Apr', value: 15900, color: '#10b981' },
|
||||
{ label: 'May', value: 18200, color: '#10b981' },
|
||||
{ label: 'Jun', value: 19400, color: '#10b981' },
|
||||
]
|
||||
|
||||
setUserGrowthData(mockUserGrowth)
|
||||
setMembershipData(mockMembershipData)
|
||||
setRevenueData(mockRevenueData)
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch analytics data:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const totalUsers = userGrowthData.length > 0 ? userGrowthData[userGrowthData.length - 1].value : 0
|
||||
const totalRevenue = revenueData.reduce((sum, item) => sum + item.value, 0)
|
||||
const activeMembers = membershipData.reduce((sum, item) => sum + item.value, 0)
|
||||
|
||||
if (loading) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="text-lg">Loading analytics...</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -81,7 +44,9 @@ export function AnalyticsDashboard() {
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold text-blue-600">{totalUsers}</div>
|
||||
<div className="text-3xl font-bold text-blue-600">
|
||||
{totalUsers}
|
||||
</div>
|
||||
<div className="text-gray-600">Total Users</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -90,7 +55,9 @@ export function AnalyticsDashboard() {
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold text-green-600">${totalRevenue.toLocaleString()}</div>
|
||||
<div className="text-3xl font-bold text-green-600">
|
||||
${totalRevenue.toLocaleString()}
|
||||
</div>
|
||||
<div className="text-gray-600">Total Revenue</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -99,7 +66,9 @@ export function AnalyticsDashboard() {
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold text-purple-600">{activeMembers}</div>
|
||||
<div className="text-3xl font-bold text-purple-600">
|
||||
{activeMembers}
|
||||
</div>
|
||||
<div className="text-gray-600">Active Members</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -133,14 +102,14 @@ export function AnalyticsDashboard() {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<RevenueChart
|
||||
data={revenueData.map(item => ({
|
||||
data={revenueData.map((item) => ({
|
||||
category: item.label,
|
||||
value: item.value,
|
||||
color: item.color
|
||||
color: item.color,
|
||||
}))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
interface Gym {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface GymSelectorProps {
|
||||
currentGymId?: string;
|
||||
userRole: string;
|
||||
}
|
||||
|
||||
export function GymSelector({ userRole }: GymSelectorProps) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [gyms, setGyms] = useState<Gym[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
// Only fetch gyms for superAdmin
|
||||
if (userRole !== "superAdmin") {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
async function fetchGyms() {
|
||||
try {
|
||||
const response = await fetch("/api/gyms");
|
||||
const data = await response.json();
|
||||
|
||||
// API returns array directly
|
||||
if (Array.isArray(data)) {
|
||||
setGyms(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch gyms:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchGyms();
|
||||
}, [userRole]);
|
||||
|
||||
const handleGymChange = (gymId: string) => {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
|
||||
if (gymId === "all") {
|
||||
params.delete("gymId");
|
||||
} else {
|
||||
params.set("gymId", gymId);
|
||||
}
|
||||
|
||||
router.push(`?${params.toString()}`);
|
||||
};
|
||||
|
||||
// Only show for superAdmin
|
||||
if (userRole !== "superAdmin") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const selectedGymId = searchParams.get("gymId") ?? "all";
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-9 w-40 animate-pulse rounded-md bg-muted" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<select
|
||||
value={selectedGymId}
|
||||
onChange={(e) => handleGymChange(e.target.value)}
|
||||
className="h-9 rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
>
|
||||
<option value="all">All Gyms</option>
|
||||
{gyms.map((gym) => (
|
||||
<option key={gym.id} value={gym.id}>
|
||||
{gym.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useState, type ReactNode } from "react";
|
||||
|
||||
interface QueryProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function QueryProvider({ children }: QueryProviderProps) {
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 60 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Toaster } from "sonner";
|
||||
|
||||
export function ToasterProvider() {
|
||||
return <Toaster richColors position="top-right" />;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ChevronRight, Home } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
interface Breadcrumb {
|
||||
label: string;
|
||||
href?: string;
|
||||
}
|
||||
|
||||
interface PageHeaderProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
breadcrumbs?: Breadcrumb[];
|
||||
actions?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function PageHeader({
|
||||
title,
|
||||
description,
|
||||
breadcrumbs,
|
||||
actions,
|
||||
className,
|
||||
}: PageHeaderProps) {
|
||||
return (
|
||||
<div className={cn("space-y-4", className)}>
|
||||
{breadcrumbs && breadcrumbs.length > 0 && (
|
||||
<nav className="flex items-center gap-1 text-sm">
|
||||
<Link
|
||||
href="/"
|
||||
className="flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Home className="h-4 w-4" />
|
||||
<span>Home</span>
|
||||
</Link>
|
||||
{breadcrumbs.map((crumb, index) => (
|
||||
<span key={index} className="flex items-center gap-1">
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
{crumb.href ? (
|
||||
<Link
|
||||
href={crumb.href}
|
||||
className="text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{crumb.label}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="font-medium text-foreground">
|
||||
{crumb.label}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-3xl font-bold tracking-tight">{title}</h1>
|
||||
{description && (
|
||||
<p className="text-muted-foreground">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
{actions && <div className="flex items-center gap-3">{actions}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface PageSectionProps {
|
||||
title?: string;
|
||||
description?: string;
|
||||
children: React.ReactNode;
|
||||
actions?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function PageSection({
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
actions,
|
||||
className,
|
||||
}: PageSectionProps) {
|
||||
return (
|
||||
<section className={cn("space-y-4", className)}>
|
||||
{(title || actions) && (
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
{title && (
|
||||
<h2 className="text-xl font-semibold tracking-tight">{title}</h2>
|
||||
)}
|
||||
{description && (
|
||||
<p className="text-sm text-muted-foreground">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
{actions && <div className="flex items-center gap-2">{actions}</div>}
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -9,60 +9,48 @@ import {
|
||||
CalendarCheck,
|
||||
CreditCard,
|
||||
Settings,
|
||||
LogOut,
|
||||
Brain,
|
||||
ChevronLeft,
|
||||
Activity,
|
||||
} from "lucide-react";
|
||||
import { UserButton, useUser } from "@clerk/nextjs";
|
||||
import { usePendingRecommendationsCount } from "@/hooks/use-api";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface Recommendation {
|
||||
id: string;
|
||||
status: string;
|
||||
interface NavItem {
|
||||
icon: React.ElementType;
|
||||
label: string;
|
||||
href: string;
|
||||
badge?: number;
|
||||
}
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const { user } = useUser();
|
||||
const [pendingCount, setPendingCount] = useState(0);
|
||||
const { data: pendingCount = 0 } = usePendingRecommendationsCount();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [isCollapsed, setIsCollapsed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
const saved = localStorage.getItem("sidebar-collapsed");
|
||||
if (saved) setIsCollapsed(JSON.parse(saved));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPending = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/recommendations");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const pending = (data.recommendations || []).filter(
|
||||
(r: Recommendation) => r.status === "pending",
|
||||
);
|
||||
setPendingCount(pending.length);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch pending recommendations", e);
|
||||
}
|
||||
};
|
||||
fetchPending();
|
||||
}, []);
|
||||
const handleToggle = () => {
|
||||
const newState = !isCollapsed;
|
||||
setIsCollapsed(newState);
|
||||
localStorage.setItem("sidebar-collapsed", JSON.stringify(newState));
|
||||
};
|
||||
|
||||
const menuItems = [
|
||||
const navItems: NavItem[] = [
|
||||
{ icon: LayoutDashboard, label: "Dashboard", href: "/" },
|
||||
{ icon: Users, label: "Users", href: "/users" },
|
||||
{
|
||||
icon: Brain,
|
||||
label: (
|
||||
<span className="flex items-center">
|
||||
AI Recommendations
|
||||
{pendingCount > 0 && (
|
||||
<span className="ml-2 inline-block bg-red-600 text-xs rounded-full px-2 py-0.5">
|
||||
{pendingCount}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
),
|
||||
label: "AI Recommendations",
|
||||
href: "/recommendations",
|
||||
badge: pendingCount > 0 ? pendingCount : undefined,
|
||||
},
|
||||
{ icon: CalendarCheck, label: "Attendance", href: "/attendance" },
|
||||
{ icon: CreditCard, label: "Payments", href: "/payments" },
|
||||
@@ -70,59 +58,126 @@ export function Sidebar() {
|
||||
];
|
||||
|
||||
return (
|
||||
<aside className="w-20 hover:w-64 bg-slate-900 text-white h-screen fixed left-0 top-0 flex flex-col border-r border-slate-800 transition-all duration-300 z-50 group overflow-hidden">
|
||||
<div className="p-6 border-b border-slate-800 flex items-center overflow-hidden whitespace-nowrap">
|
||||
<h1 className="text-2xl font-bold bg-gradient-to-r from-blue-400 to-indigo-400 bg-clip-text text-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300">
|
||||
FitAI Admin
|
||||
</h1>
|
||||
</div>
|
||||
<aside
|
||||
className={cn(
|
||||
"fixed left-0 top-0 z-40 h-screen transition-all duration-300 ease-in-out",
|
||||
isCollapsed ? "w-[72px]" : "w-[260px]",
|
||||
"bg-gradient-to-b from-[var(--sidebar-background)] to-[#0f172a]",
|
||||
)}
|
||||
>
|
||||
<div className="flex h-full flex-col border-r border-white/5">
|
||||
{/* Logo */}
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-16 items-center border-b border-white/5 px-4",
|
||||
isCollapsed ? "justify-center" : "justify-between",
|
||||
)}
|
||||
>
|
||||
{!isCollapsed && (
|
||||
<Link href="/" className="flex items-center gap-2">
|
||||
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg shadow-blue-500/25">
|
||||
<Activity className="h-5 w-5 text-white" />
|
||||
</div>
|
||||
<span className="text-lg font-bold text-white">FitAI</span>
|
||||
</Link>
|
||||
)}
|
||||
{isCollapsed && (
|
||||
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg shadow-blue-500/25">
|
||||
<Activity className="h-5 w-5 text-white" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 p-4 space-y-2">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = pathname === item.href;
|
||||
const label =
|
||||
typeof item.label === "string" ? item.label : item.label;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={`flex items-center gap-3 px-4 py-3 rounded-lg transition-all duration-200 ${
|
||||
isActive
|
||||
? "bg-blue-600 text-white shadow-lg shadow-blue-900/20"
|
||||
: "text-slate-400 hover:bg-slate-800 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
<div className="min-w-[20px]">
|
||||
{/* Toggle Button */}
|
||||
<button
|
||||
onClick={handleToggle}
|
||||
className={cn(
|
||||
"absolute -right-3 top-20 z-50 flex h-6 w-6 items-center justify-center rounded-full border border-white/10 bg-slate-800 text-white/60 shadow-lg transition-all hover:bg-slate-700 hover:text-white",
|
||||
isCollapsed ? "left-[60px]" : "left-[244px]",
|
||||
)}
|
||||
>
|
||||
<ChevronLeft
|
||||
className={cn(
|
||||
"h-3.5 w-3.5 transition-transform",
|
||||
isCollapsed && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="flex-1 space-y-1 overflow-y-auto p-3">
|
||||
{navItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive =
|
||||
pathname === item.href ||
|
||||
(item.href !== "/" && pathname.startsWith(item.href));
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={cn(
|
||||
"group flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",
|
||||
isActive
|
||||
? "bg-gradient-to-r from-blue-600 to-blue-500 text-white shadow-lg shadow-blue-500/25"
|
||||
: "text-slate-400 hover:bg-white/5 hover:text-white",
|
||||
isCollapsed && "justify-center px-2",
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
size={20}
|
||||
className={
|
||||
className={cn(
|
||||
"h-5 w-5 flex-shrink-0 transition-colors",
|
||||
isActive
|
||||
? "text-white"
|
||||
: "text-slate-500 group-hover:text-white"
|
||||
}
|
||||
: "text-slate-500 group-hover:text-white",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<span className="font-medium opacity-0 group-hover:opacity-100 transition-opacity duration-300 whitespace-nowrap overflow-hidden">
|
||||
{label}
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
{!isCollapsed && (
|
||||
<>
|
||||
<span className="flex-1">{item.label}</span>
|
||||
{item.badge !== undefined && (
|
||||
<span className="flex h-5 min-w-[20px] items-center justify-center rounded-full bg-red-500 px-1.5 text-xs font-bold text-white">
|
||||
{item.badge > 99 ? "99+" : item.badge}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{isCollapsed && item.badge !== undefined && (
|
||||
<span className="absolute -right-1 -top-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-bold text-white">
|
||||
{item.badge > 9 ? "9+" : item.badge}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<div className="p-4 border-t border-slate-800">
|
||||
<div className="flex items-center gap-3 px-2 py-3 rounded-lg bg-slate-800/50 overflow-hidden whitespace-nowrap">
|
||||
<div className="min-w-[32px]">
|
||||
{mounted && <UserButton afterSignOutUrl="/" />}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
|
||||
<p className="text-sm font-medium text-white truncate">
|
||||
{user?.fullName || "Admin User"}
|
||||
</p>
|
||||
<p className="text-xs text-slate-400 truncate">
|
||||
{user?.primaryEmailAddress?.emailAddress}
|
||||
</p>
|
||||
{/* User Section */}
|
||||
<div
|
||||
className={cn(
|
||||
"border-t border-white/5 p-3",
|
||||
isCollapsed && "flex justify-center",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-lg bg-white/5 p-2 transition-colors hover:bg-white/10",
|
||||
isCollapsed && "justify-center p-2",
|
||||
)}
|
||||
>
|
||||
<div className={cn("flex-shrink-0", isCollapsed ? "" : "ml-1")}>
|
||||
{mounted && <UserButton afterSignOutUrl="/" />}
|
||||
</div>
|
||||
{!isCollapsed && (
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium text-white">
|
||||
{user?.fullName || "Admin"}
|
||||
</p>
|
||||
<p className="truncate text-xs text-slate-400">
|
||||
{user?.primaryEmailAddress?.emailAddress}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,51 +1,139 @@
|
||||
import { LucideIcon } from "lucide-react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { TrendingUp, TrendingDown, Minus } from "lucide-react";
|
||||
|
||||
interface StatsCardProps {
|
||||
title: string;
|
||||
value: string | number;
|
||||
change?: string;
|
||||
trend?: "up" | "down" | "neutral";
|
||||
icon: LucideIcon;
|
||||
color?: "blue" | "green" | "purple" | "orange";
|
||||
title: string;
|
||||
value: string | number;
|
||||
change?: string;
|
||||
trend?: "up" | "down" | "neutral";
|
||||
icon: LucideIcon;
|
||||
color?: "blue" | "green" | "purple" | "orange" | "red";
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function StatsCard({ title, value, change, trend, icon: Icon, color = "blue" }: StatsCardProps) {
|
||||
const colorStyles = {
|
||||
blue: "bg-blue-50 text-blue-600",
|
||||
green: "bg-green-50 text-green-600",
|
||||
purple: "bg-purple-50 text-purple-600",
|
||||
orange: "bg-orange-50 text-orange-600",
|
||||
};
|
||||
export function StatsCard({
|
||||
title,
|
||||
value,
|
||||
change,
|
||||
trend,
|
||||
icon: Icon,
|
||||
color = "blue",
|
||||
className,
|
||||
}: StatsCardProps) {
|
||||
const colorStyles = {
|
||||
blue: {
|
||||
gradient: "from-blue-500/10 to-blue-600/5",
|
||||
iconBg: "bg-gradient-to-br from-blue-500 to-blue-600",
|
||||
iconShadow: "shadow-blue-500/25",
|
||||
text: "text-blue-600",
|
||||
trendUp: "text-emerald-600",
|
||||
trendDown: "text-red-600",
|
||||
},
|
||||
green: {
|
||||
gradient: "from-emerald-500/10 to-emerald-600/5",
|
||||
iconBg: "bg-gradient-to-br from-emerald-500 to-emerald-600",
|
||||
iconShadow: "shadow-emerald-500/25",
|
||||
text: "text-emerald-600",
|
||||
trendUp: "text-emerald-600",
|
||||
trendDown: "text-red-600",
|
||||
},
|
||||
purple: {
|
||||
gradient: "from-violet-500/10 to-violet-600/5",
|
||||
iconBg: "bg-gradient-to-br from-violet-500 to-violet-600",
|
||||
iconShadow: "shadow-violet-500/25",
|
||||
text: "text-violet-600",
|
||||
trendUp: "text-emerald-600",
|
||||
trendDown: "text-red-600",
|
||||
},
|
||||
orange: {
|
||||
gradient: "from-amber-500/10 to-amber-600/5",
|
||||
iconBg: "bg-gradient-to-br from-amber-500 to-orange-600",
|
||||
iconShadow: "shadow-amber-500/25",
|
||||
text: "text-amber-600",
|
||||
trendUp: "text-emerald-600",
|
||||
trendDown: "text-red-600",
|
||||
},
|
||||
red: {
|
||||
gradient: "from-rose-500/10 to-rose-600/5",
|
||||
iconBg: "bg-gradient-to-br from-rose-500 to-rose-600",
|
||||
iconShadow: "shadow-rose-500/25",
|
||||
text: "text-rose-600",
|
||||
trendUp: "text-emerald-600",
|
||||
trendDown: "text-red-600",
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
{title}
|
||||
</CardTitle>
|
||||
<div className={`p-2 rounded-lg ${colorStyles[color]}`}>
|
||||
<Icon size={16} />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{value}</div>
|
||||
{change && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
<span
|
||||
className={`font-medium ${trend === "up"
|
||||
? "text-green-600"
|
||||
: trend === "down"
|
||||
? "text-red-600"
|
||||
: "text-slate-600"
|
||||
}`}
|
||||
>
|
||||
{change}
|
||||
</span>{" "}
|
||||
vs last month
|
||||
</p>
|
||||
const styles = colorStyles[color];
|
||||
const TrendIcon =
|
||||
trend === "up" ? TrendingUp : trend === "down" ? TrendingDown : Minus;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group relative overflow-hidden rounded-2xl border border-border/50 bg-gradient-to-br p-6 transition-all duration-300 hover:shadow-lg hover:-translate-y-1",
|
||||
styles.gradient,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-muted-foreground">{title}</p>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-3xl font-bold tracking-tight">{value}</span>
|
||||
</div>
|
||||
{change && (
|
||||
<div className="flex items-center gap-1 text-sm">
|
||||
<TrendIcon
|
||||
className={cn(
|
||||
"h-4 w-4",
|
||||
trend === "up" && styles.trendUp,
|
||||
trend === "down" && styles.trendDown,
|
||||
trend === "neutral" && "text-muted-foreground",
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
/>
|
||||
<span
|
||||
className={cn(
|
||||
"font-medium",
|
||||
trend === "up" && styles.trendUp,
|
||||
trend === "down" && styles.trendDown,
|
||||
trend === "neutral" && "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{change}
|
||||
</span>
|
||||
<span className="text-muted-foreground">vs last month</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br shadow-lg transition-transform duration-300 group-hover:scale-110",
|
||||
styles.iconBg,
|
||||
styles.iconShadow,
|
||||
)}
|
||||
>
|
||||
<Icon className="h-6 w-6 text-white" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Decorative corner gradient */}
|
||||
<div className="absolute -right-8 -top-8 h-32 w-32 rounded-full bg-gradient-to-br from-white/20 to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatsCardSkeleton() {
|
||||
return (
|
||||
<div className="animate-pulse rounded-2xl border border-border/50 bg-gradient-to-br from-muted/30 to-muted/20 p-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="space-y-3">
|
||||
<div className="h-4 w-24 rounded bg-muted" />
|
||||
<div className="h-9 w-32 rounded bg-muted" />
|
||||
<div className="h-4 w-20 rounded bg-muted" />
|
||||
</div>
|
||||
<div className="h-12 w-12 rounded-xl bg-muted" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary/10 text-primary",
|
||||
secondary: "bg-secondary text-secondary-foreground",
|
||||
success:
|
||||
"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-400",
|
||||
warning:
|
||||
"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",
|
||||
destructive:
|
||||
"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400",
|
||||
info: "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400",
|
||||
outline: "border border-input text-foreground",
|
||||
gray: "bg-slate-100 text-slate-800 dark:bg-slate-800 dark:text-slate-300",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
export function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return (
|
||||
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
export function StatusBadge({ status }: { status: string }) {
|
||||
const statusConfig: Record<
|
||||
string,
|
||||
{ variant: BadgeProps["variant"]; label: string }
|
||||
> = {
|
||||
active: { variant: "success", label: "Active" },
|
||||
inactive: { variant: "gray", label: "Inactive" },
|
||||
pending: { variant: "warning", label: "Pending" },
|
||||
approved: { variant: "success", label: "Approved" },
|
||||
rejected: { variant: "destructive", label: "Rejected" },
|
||||
completed: { variant: "success", label: "Completed" },
|
||||
failed: { variant: "destructive", label: "Failed" },
|
||||
suspended: { variant: "destructive", label: "Suspended" },
|
||||
basic: { variant: "default", label: "Basic" },
|
||||
premium: { variant: "info", label: "Premium" },
|
||||
vip: { variant: "warning", label: "VIP" },
|
||||
};
|
||||
|
||||
const config = statusConfig[status.toLowerCase()] || {
|
||||
variant: "outline",
|
||||
label: status,
|
||||
};
|
||||
|
||||
return <Badge variant={config.variant}>{config.label}</Badge>;
|
||||
}
|
||||
@@ -1,49 +1,60 @@
|
||||
import React from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: 'primary' | 'secondary' | 'ghost' | 'destructive' | 'outline' | 'default'
|
||||
size?: 'default' | 'sm' | 'lg' | 'icon'
|
||||
isLoading?: boolean
|
||||
children: React.ReactNode
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-lg text-sm font-medium transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 hover:shadow",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90 hover:shadow",
|
||||
outline:
|
||||
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export function Button({
|
||||
variant = 'primary',
|
||||
size = 'default',
|
||||
isLoading = false,
|
||||
children,
|
||||
className = '',
|
||||
disabled,
|
||||
...props
|
||||
}: ButtonProps) {
|
||||
const baseClasses = 'inline-flex items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50'
|
||||
|
||||
const variantClasses = {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700 shadow hover:bg-blue-700/90',
|
||||
default: 'bg-blue-600 text-white hover:bg-blue-700 shadow hover:bg-blue-700/90',
|
||||
secondary: 'bg-slate-100 text-slate-900 hover:bg-slate-200/80',
|
||||
ghost: 'hover:bg-slate-100 hover:text-slate-900',
|
||||
destructive: 'bg-red-500 text-white hover:bg-red-600/90',
|
||||
outline: 'border border-input bg-transparent shadow-sm hover:bg-slate-100 hover:text-slate-900'
|
||||
}
|
||||
|
||||
const sizeClasses = {
|
||||
default: 'h-9 px-4 py-2',
|
||||
sm: 'h-8 rounded-md px-3 text-xs',
|
||||
lg: 'h-10 rounded-md px-8',
|
||||
icon: 'h-9 w-9'
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
className={cn(baseClasses, variantClasses[variant], sizeClasses[size], className)}
|
||||
disabled={disabled || isLoading}
|
||||
{...props}
|
||||
>
|
||||
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
(
|
||||
{ className, variant, size, isLoading, children, disabled, ...props },
|
||||
ref,
|
||||
) => {
|
||||
return (
|
||||
<button
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
disabled={disabled || isLoading}
|
||||
{...props}
|
||||
>
|
||||
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
},
|
||||
);
|
||||
Button.displayName = "Button";
|
||||
@@ -0,0 +1,57 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface SkeletonProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Skeleton({ className }: SkeletonProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"animate-pulse rounded-md bg-slate-200 dark:bg-slate-700",
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatsCardSkeleton() {
|
||||
return (
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Skeleton className="h-12 w-12 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-20" />
|
||||
<Skeleton className="h-8 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TableSkeleton({ rows = 5 }: { rows?: number }) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: rows }).map((_, i) => (
|
||||
<div key={i} className="flex gap-4">
|
||||
<Skeleton className="h-12 flex-1" />
|
||||
<Skeleton className="h-12 w-32" />
|
||||
<Skeleton className="h-12 w-24" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CardSkeleton() {
|
||||
return (
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6 space-y-4">
|
||||
<Skeleton className="h-6 w-40" />
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-5/6" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useUser } from "@clerk/nextjs";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -26,6 +27,9 @@ import {
|
||||
type InvitationOptionsData,
|
||||
} from "@/lib/validation/user-schemas";
|
||||
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 {
|
||||
open: boolean;
|
||||
@@ -45,6 +49,15 @@ export function CreateUserModal({
|
||||
const [basicInfo, setBasicInfo] = useState<BasicInfoData | null>(null);
|
||||
const [clientInfo, setClientInfo] = useState<ClientInfoData | null>(null);
|
||||
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
|
||||
const roleForm = useForm<RoleSelectionData>({
|
||||
@@ -136,10 +149,18 @@ export function CreateUserModal({
|
||||
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", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
body: JSON.stringify(finalPayload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -259,7 +280,7 @@ export function CreateUserModal({
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Role *</label>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{(["admin", "trainer", "client"] as const).map((role) => (
|
||||
{invitableRoles.map((role) => (
|
||||
<label
|
||||
key={role}
|
||||
className={`flex items-center justify-center p-4 border-2 rounded-lg cursor-pointer transition-colors ${
|
||||
@@ -461,6 +482,39 @@ export function CreateUserModal({
|
||||
</p>
|
||||
</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">
|
||||
<Button type="button" variant="outline" onClick={handleBack}>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -9,9 +9,10 @@ import { formatDate } from "@/lib/utils";
|
||||
|
||||
ModuleRegistry.registerModules([AllCommunityModule]);
|
||||
|
||||
function getTimeAgo(date: Date): string {
|
||||
function getTimeAgo(date: Date | string): string {
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const d = typeof date === "string" ? new Date(date) : date;
|
||||
const diffMs = now.getTime() - d.getTime();
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
const diffHours = Math.floor(diffMins / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
@@ -22,7 +23,7 @@ function getTimeAgo(date: Date): string {
|
||||
return `${diffDays}d ago`;
|
||||
}
|
||||
|
||||
interface User {
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
@@ -31,15 +32,18 @@ interface User {
|
||||
phone?: string;
|
||||
gymId?: string;
|
||||
gymName?: string | null;
|
||||
createdAt: Date;
|
||||
createdAt?: string | Date;
|
||||
isCheckedIn?: boolean;
|
||||
checkInTime?: Date;
|
||||
checkInTime?: string | Date;
|
||||
lastCheckInTime?: string | Date;
|
||||
checkInsThisWeek?: number;
|
||||
checkInsThisMonth?: number;
|
||||
client?: {
|
||||
id: string;
|
||||
membershipType: string;
|
||||
membershipStatus: string;
|
||||
joinDate: Date;
|
||||
lastVisit?: Date;
|
||||
joinDate: string | Date;
|
||||
lastVisit?: string | Date;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,44 +1,33 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { UserGrid } from "@/components/users/UserGrid";
|
||||
// import { Button } from "@/components/ui/button";
|
||||
import { useState } from "react";
|
||||
import { UserGrid, type User } from "@/components/users/UserGrid";
|
||||
import { InvitationsGrid } from "@/components/users/InvitationsGrid";
|
||||
import { Card, CardHeader, CardContent } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useUser } from "@clerk/nextjs";
|
||||
import { getGymIdFromUser } from "@/lib/error-helpers";
|
||||
import log from "@/lib/logger";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { CreateUserModal } from "./CreateUserModal";
|
||||
import {
|
||||
useUsers,
|
||||
useGyms,
|
||||
useUpdateUser,
|
||||
useDeleteUser,
|
||||
useSendInvitation,
|
||||
useInvitations,
|
||||
} from "@/hooks/use-api";
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
role: string;
|
||||
phone?: string;
|
||||
interface UserManagementProps {
|
||||
gymId?: string;
|
||||
createdAt: Date;
|
||||
isCheckedIn?: boolean;
|
||||
checkInTime?: Date;
|
||||
lastCheckInTime?: Date;
|
||||
checkInsThisWeek?: number;
|
||||
checkInsThisMonth?: number;
|
||||
client?: {
|
||||
id: string;
|
||||
membershipType: string;
|
||||
membershipStatus: string;
|
||||
joinDate: Date;
|
||||
lastVisit?: Date;
|
||||
};
|
||||
}
|
||||
|
||||
export function UserManagement() {
|
||||
export function UserManagement({ gymId }: UserManagementProps) {
|
||||
const { user } = useUser();
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [filter, setFilter] = useState<string>("all");
|
||||
const [viewFilter, setViewFilter] = useState<"all" | "active" | "pending">(
|
||||
"all",
|
||||
);
|
||||
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
@@ -50,70 +39,33 @@ export function UserManagement() {
|
||||
role: string;
|
||||
phone: string;
|
||||
gymId: string;
|
||||
membershipType?: string;
|
||||
membershipStatus?: string;
|
||||
} | null>(null);
|
||||
|
||||
// Active gyms for dropdown
|
||||
const [gyms, setGyms] = useState<Array<{ id: string; name: string }>>([]);
|
||||
const {
|
||||
data: users = [],
|
||||
isLoading: usersLoading,
|
||||
refetch: refetchUsers,
|
||||
} = useUsers({
|
||||
role: filter !== "all" ? filter : undefined,
|
||||
gymId,
|
||||
});
|
||||
|
||||
// Load gyms when modal opens or refreshes
|
||||
useEffect(() => {
|
||||
if (isEditing) {
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/gyms");
|
||||
const data = await res.json();
|
||||
if (Array.isArray(data)) {
|
||||
// map down to id and name to avoid extra payload use here
|
||||
setGyms(data.map((g: any) => ({ id: g.id, name: g.name })));
|
||||
} else {
|
||||
setGyms([]);
|
||||
}
|
||||
} catch {
|
||||
setGyms([]);
|
||||
}
|
||||
})();
|
||||
}
|
||||
}, [isEditing]);
|
||||
const {
|
||||
data: invitations = [],
|
||||
isLoading: invitationsLoading,
|
||||
refetch: refetchInvitations,
|
||||
} = useInvitations(gymId);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, [filter]);
|
||||
const { data: gyms = [] } = useGyms();
|
||||
const updateUser = useUpdateUser();
|
||||
const deleteUser = useDeleteUser();
|
||||
const sendInvitation = useSendInvitation();
|
||||
|
||||
const fetchUsers = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const ts = Date.now();
|
||||
const url =
|
||||
filter === "all"
|
||||
? `/api/users?ts=${ts}`
|
||||
: `/api/users?role=${filter}&ts=${ts}`;
|
||||
|
||||
log.debug("Fetching users", { url });
|
||||
const response = await fetch(url, { cache: "no-store" });
|
||||
log.debug("Users fetch response", {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
});
|
||||
const responseData = await response.json();
|
||||
const data = responseData.data || responseData; // Handle both old and new API response formats
|
||||
log.debug("Received users data", {
|
||||
count: Array.isArray(data.users) ? data.users.length : 0,
|
||||
sample:
|
||||
data.users && data.users[0]
|
||||
? {
|
||||
id: data.users[0].id,
|
||||
gymId: data.users[0].gymId,
|
||||
role: data.users[0].role,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
setUsers(data.users || []);
|
||||
} catch (error) {
|
||||
log.error("Failed to fetch users", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
const isLoading =
|
||||
viewFilter === "pending" ? invitationsLoading : usersLoading;
|
||||
const refetch = viewFilter === "pending" ? refetchInvitations : refetchUsers;
|
||||
|
||||
const handleUserSelect = (user: User | null) => {
|
||||
setSelectedUser(user);
|
||||
@@ -128,6 +80,8 @@ export function UserManagement() {
|
||||
role: user.role,
|
||||
phone: user.phone || "",
|
||||
gymId: user.gymId || "",
|
||||
membershipType: user.client?.membershipType || "basic",
|
||||
membershipStatus: user.client?.membershipStatus || "active",
|
||||
});
|
||||
setIsEditing(true);
|
||||
};
|
||||
@@ -144,17 +98,12 @@ export function UserManagement() {
|
||||
return;
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/users", {
|
||||
method: "DELETE",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ ids: users.map((u) => u.id) }),
|
||||
});
|
||||
if (response.ok) {
|
||||
fetchUsers();
|
||||
toast.success("Users deleted successfully");
|
||||
} else {
|
||||
toast.error("Error deleting users");
|
||||
}
|
||||
const deletePromises = users.map((u) =>
|
||||
fetch(`/api/users?id=${u.id}`, { method: "DELETE" }),
|
||||
);
|
||||
await Promise.all(deletePromises);
|
||||
refetch();
|
||||
toast.success("Users deleted successfully");
|
||||
} catch (error) {
|
||||
log.error("Failed to delete users", error);
|
||||
}
|
||||
@@ -196,7 +145,7 @@ export function UserManagement() {
|
||||
};
|
||||
|
||||
const handleRefresh = () => {
|
||||
fetchUsers();
|
||||
refetch();
|
||||
};
|
||||
|
||||
const handleSaveEdit = async () => {
|
||||
@@ -204,8 +153,7 @@ export function UserManagement() {
|
||||
|
||||
try {
|
||||
if (selectedUser) {
|
||||
// Update existing user
|
||||
const payload = {
|
||||
const payload: any = {
|
||||
id: selectedUser.id,
|
||||
email: editForm.email,
|
||||
firstName: editForm.firstName,
|
||||
@@ -214,80 +162,27 @@ export function UserManagement() {
|
||||
phone: editForm.phone,
|
||||
gymId: editForm.gymId === "" ? null : editForm.gymId,
|
||||
};
|
||||
log.debug("Updating user", payload);
|
||||
const response = await fetch("/api/users", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
log.debug("User update response", {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
});
|
||||
if (response.ok) {
|
||||
// Optimistically update local state so grid reflects changes immediately
|
||||
setUsers((prev) =>
|
||||
prev.map((u) =>
|
||||
u.id === selectedUser.id
|
||||
? {
|
||||
...u,
|
||||
email: editForm.email,
|
||||
firstName: editForm.firstName,
|
||||
lastName: editForm.lastName,
|
||||
role: editForm.role,
|
||||
phone: editForm.phone || undefined,
|
||||
gymId: editForm.gymId === "" ? undefined : editForm.gymId,
|
||||
}
|
||||
: u,
|
||||
),
|
||||
);
|
||||
setSelectedUser((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
email: editForm.email,
|
||||
firstName: editForm.firstName,
|
||||
lastName: editForm.lastName,
|
||||
role: editForm.role,
|
||||
phone: editForm.phone || undefined,
|
||||
gymId: editForm.gymId === "" ? undefined : editForm.gymId,
|
||||
}
|
||||
: prev,
|
||||
);
|
||||
setIsEditing(false);
|
||||
setEditForm(null);
|
||||
// Still re-fetch from server to ensure consistency
|
||||
log.debug("Re-fetching users after successful edit");
|
||||
fetchUsers();
|
||||
toast.success("User updated successfully");
|
||||
} else {
|
||||
const errText = await response.text().catch(() => "");
|
||||
log.error("User update failed", new Error(errText), {
|
||||
status: response.status,
|
||||
});
|
||||
toast.error("Error updating user");
|
||||
}
|
||||
} else {
|
||||
// Create (Invite) new user
|
||||
const response = await fetch("/api/invitations", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
inviteeEmail: editForm.email,
|
||||
roleAssigned: editForm.role,
|
||||
gymId: editForm.gymId || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
setIsEditing(false);
|
||||
setEditForm(null);
|
||||
fetchUsers();
|
||||
toast.success("Invitation sent successfully!");
|
||||
} else {
|
||||
const errorData = await response.json();
|
||||
toast.error(`Error sending invitation: ${errorData.error}`);
|
||||
// Include membership fields if user is a client
|
||||
if (editForm.role === "client") {
|
||||
payload.membershipType = editForm.membershipType;
|
||||
payload.membershipStatus = editForm.membershipStatus;
|
||||
}
|
||||
|
||||
await updateUser.mutateAsync(payload);
|
||||
setIsEditing(false);
|
||||
setEditForm(null);
|
||||
refetch();
|
||||
toast.success("User updated successfully");
|
||||
} else {
|
||||
await sendInvitation.mutateAsync({
|
||||
email: editForm.email,
|
||||
role: editForm.role,
|
||||
});
|
||||
setIsEditing(false);
|
||||
setEditForm(null);
|
||||
refetch();
|
||||
toast.success("Invitation sent successfully!");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@@ -299,17 +194,11 @@ export function UserManagement() {
|
||||
if (!selectedUser) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/users?id=${selectedUser.id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (response.ok) {
|
||||
setIsDeleting(false);
|
||||
setSelectedUser(null);
|
||||
fetchUsers();
|
||||
toast.success("User deleted successfully");
|
||||
} else {
|
||||
toast.error("Error deleting user");
|
||||
}
|
||||
await deleteUser.mutateAsync(selectedUser.id);
|
||||
setIsDeleting(false);
|
||||
setSelectedUser(null);
|
||||
refetch();
|
||||
toast.success("User deleted successfully");
|
||||
} catch (error) {
|
||||
log.error("Failed to delete user", error);
|
||||
}
|
||||
@@ -320,6 +209,19 @@ export function UserManagement() {
|
||||
<div className="flex justify-between items-center">
|
||||
<h2 className="text-2xl font-bold">User Management</h2>
|
||||
<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
|
||||
variant={filter === "all" ? "default" : "outline"}
|
||||
onClick={() => setFilter("all")}
|
||||
@@ -347,7 +249,7 @@ export function UserManagement() {
|
||||
variant={filter === "client" ? "default" : "outline"}
|
||||
onClick={() => setFilter("client")}
|
||||
>
|
||||
Clientsa
|
||||
Clients
|
||||
</Button>
|
||||
<Button
|
||||
variant={filter === "trainer" ? "default" : "outline"}
|
||||
@@ -372,33 +274,48 @@ export function UserManagement() {
|
||||
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="text-sm text-gray-600">
|
||||
Showing {users.length} users
|
||||
{selectedUser && (
|
||||
<span className="ml-4 text-blue-600">
|
||||
Selected: {selectedUser.firstName} {selectedUser.lastName}
|
||||
</span>
|
||||
{viewFilter === "pending" ? (
|
||||
<>Showing {invitations.length} pending invitations</>
|
||||
) : (
|
||||
<>
|
||||
Showing {users.length} users
|
||||
{selectedUser && (
|
||||
<span className="ml-4 text-blue-600">
|
||||
Selected: {selectedUser.firstName} {selectedUser.lastName}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="default" onClick={handleRefresh}>
|
||||
Refresh
|
||||
</Button>
|
||||
<Button variant="default" onClick={handleExport}>
|
||||
Export CSV
|
||||
</Button>
|
||||
{viewFilter !== "pending" && (
|
||||
<Button variant="default" onClick={handleExport}>
|
||||
Export CSV
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<UserGrid
|
||||
users={users}
|
||||
onUserSelect={(user) => handleUserSelect(user)}
|
||||
onEditUser={handleEditUser}
|
||||
onDeleteUser={handleDeleteUser}
|
||||
onBulkDelete={handleBulkDelete}
|
||||
loading={loading}
|
||||
/>
|
||||
{viewFilter === "pending" ? (
|
||||
<InvitationsGrid
|
||||
invitations={invitations}
|
||||
onRefetch={refetchInvitations}
|
||||
/>
|
||||
) : (
|
||||
<UserGrid
|
||||
users={users}
|
||||
onUserSelect={(user) => handleUserSelect(user)}
|
||||
onEditUser={handleEditUser}
|
||||
onDeleteUser={handleDeleteUser}
|
||||
onBulkDelete={handleBulkDelete}
|
||||
loading={isLoading}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -488,26 +405,78 @@ export function UserManagement() {
|
||||
className="w-full border border-gray-300 rounded px-3 py-2"
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm font-medium mb-1">Gym</label>
|
||||
<select
|
||||
value={editForm.gymId}
|
||||
onChange={(e) =>
|
||||
setEditForm({ ...editForm, gymId: e.target.value })
|
||||
}
|
||||
className="w-full border border-gray-300 rounded px-3 py-2"
|
||||
>
|
||||
<option value="">Proceed without gym</option>
|
||||
{gyms.map((g) => (
|
||||
<option key={g.id} value={g.id}>
|
||||
{g.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Select an active gym or proceed without a gym.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Only superAdmins can reassign gyms */}
|
||||
{(() => {
|
||||
const currentRole = user?.publicMetadata?.role;
|
||||
console.log("Current user role for gym selector:", currentRole);
|
||||
return currentRole === "superAdmin";
|
||||
})() && (
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm font-medium mb-1">Gym</label>
|
||||
<select
|
||||
value={editForm.gymId}
|
||||
onChange={(e) =>
|
||||
setEditForm({ ...editForm, gymId: e.target.value })
|
||||
}
|
||||
className="w-full border border-gray-300 rounded px-3 py-2"
|
||||
>
|
||||
<option value="">Proceed without gym</option>
|
||||
{gyms.map((g) => (
|
||||
<option key={g.id} value={g.id}>
|
||||
{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">
|
||||
<button
|
||||
type="button"
|
||||
@@ -591,7 +560,9 @@ export function UserManagement() {
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-medium">Joined:</span>{" "}
|
||||
{new Date(selectedUser.createdAt).toLocaleDateString()}
|
||||
{selectedUser.createdAt
|
||||
? new Date(selectedUser.createdAt).toLocaleDateString()
|
||||
: "N/A"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -653,7 +624,10 @@ export function UserManagement() {
|
||||
<CreateUserModal
|
||||
open={createModalOpen}
|
||||
onOpenChange={setCreateModalOpen}
|
||||
onSuccess={() => fetchUsers()}
|
||||
onSuccess={() => {
|
||||
refetchUsers();
|
||||
refetchInvitations();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
export interface DashboardStats {
|
||||
totalUsers: number;
|
||||
activeClients: number;
|
||||
totalRevenue: number;
|
||||
revenueGrowth: number;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
role: string;
|
||||
phone?: string;
|
||||
gymId?: string;
|
||||
gymName?: string | null;
|
||||
createdAt?: string;
|
||||
isCheckedIn?: boolean;
|
||||
checkInTime?: string;
|
||||
lastCheckInTime?: string;
|
||||
checkInsThisWeek?: number;
|
||||
checkInsThisMonth?: number;
|
||||
client?: {
|
||||
id: string;
|
||||
membershipType: string;
|
||||
membershipStatus: string;
|
||||
joinDate: string;
|
||||
lastVisit?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Recommendation {
|
||||
id: string;
|
||||
userId: string;
|
||||
type: string;
|
||||
title: string;
|
||||
description: string;
|
||||
content?: string;
|
||||
recommendationText?: string;
|
||||
activityPlan?: string;
|
||||
dietPlan?: string;
|
||||
status: "pending" | "approved" | "rejected";
|
||||
createdAt: string;
|
||||
user?: User;
|
||||
}
|
||||
|
||||
export interface Gym {
|
||||
id: string;
|
||||
name: string;
|
||||
address?: string;
|
||||
}
|
||||
|
||||
export interface AttendanceRecord {
|
||||
id: string;
|
||||
userId: string;
|
||||
checkIn: string;
|
||||
checkOut?: string;
|
||||
date: 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> {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options?.headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response
|
||||
.json()
|
||||
.catch(() => ({ error: "Request failed" }));
|
||||
throw new Error(error.error || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export function useDashboardStats(gymId?: string) {
|
||||
return useQuery({
|
||||
queryKey: ["dashboard-stats", gymId],
|
||||
queryFn: () => {
|
||||
const url = gymId
|
||||
? `/api/admin/stats?gymId=${gymId}`
|
||||
: "/api/admin/stats";
|
||||
return fetchApi<{ data: { stats: DashboardStats } }>(url).then(
|
||||
(res) => res.data?.stats,
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUsers(filters?: {
|
||||
role?: string;
|
||||
gymId?: string;
|
||||
search?: string;
|
||||
}) {
|
||||
const params = new URLSearchParams();
|
||||
if (filters?.role) params.set("role", filters.role);
|
||||
if (filters?.gymId) params.set("gymId", filters.gymId);
|
||||
if (filters?.search) params.set("search", filters.search);
|
||||
|
||||
const queryString = params.toString();
|
||||
const url = queryString ? `/api/users?${queryString}` : "/api/users";
|
||||
|
||||
return useQuery({
|
||||
queryKey: ["users", filters],
|
||||
queryFn: () =>
|
||||
fetchApi<{ data: { users: User[] } }>(url).then(
|
||||
(res) => res.data?.users ?? [],
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUser(userId: string) {
|
||||
return useQuery({
|
||||
queryKey: ["user", userId],
|
||||
queryFn: () =>
|
||||
fetchApi<{ data: { user: User } }>(`/api/users?id=${userId}`).then(
|
||||
(res) => res.data?.user,
|
||||
),
|
||||
enabled: !!userId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useRecommendations(filters?: {
|
||||
userId?: string;
|
||||
status?: string;
|
||||
}) {
|
||||
const params = new URLSearchParams();
|
||||
if (filters?.userId) params.set("userId", filters.userId);
|
||||
if (filters?.status) params.set("status", filters.status);
|
||||
|
||||
const queryString = params.toString();
|
||||
const url = queryString
|
||||
? `/api/recommendations?${queryString}`
|
||||
: "/api/recommendations";
|
||||
|
||||
return useQuery({
|
||||
queryKey: ["recommendations", filters],
|
||||
queryFn: () =>
|
||||
fetchApi<{ data: { recommendations: Recommendation[] } }>(url).then(
|
||||
(res) => res.data?.recommendations ?? [],
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function usePendingRecommendationsCount() {
|
||||
return useQuery({
|
||||
queryKey: ["pending-recommendations-count"],
|
||||
queryFn: () =>
|
||||
fetchApi<{ data: { recommendations: Recommendation[] } }>(
|
||||
"/api/recommendations",
|
||||
).then(
|
||||
(res) =>
|
||||
(res.data?.recommendations ?? []).filter(
|
||||
(r) => r.status === "pending",
|
||||
).length,
|
||||
),
|
||||
refetchInterval: 30000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useGyms() {
|
||||
return useQuery({
|
||||
queryKey: ["gyms"],
|
||||
queryFn: () =>
|
||||
fetchApi<{ data: { gyms: Gym[] } }>("/api/gyms").then(
|
||||
(res) => res.data?.gyms ?? (Array.isArray(res) ? res : []),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAttendance(filters?: { userId?: string; date?: string }) {
|
||||
const params = new URLSearchParams();
|
||||
if (filters?.userId) params.set("userId", filters.userId);
|
||||
if (filters?.date) params.set("date", filters.date);
|
||||
|
||||
const queryString = params.toString();
|
||||
const url = queryString
|
||||
? `/api/admin/attendance?${queryString}`
|
||||
: "/api/admin/attendance";
|
||||
|
||||
return useQuery({
|
||||
queryKey: ["attendance", filters],
|
||||
queryFn: () =>
|
||||
fetchApi<{ data: { records: AttendanceRecord[] } }>(url).then(
|
||||
(res) => res.data?.records ?? [],
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateUser() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
role: string;
|
||||
phone?: string;
|
||||
gymId?: string;
|
||||
}) =>
|
||||
fetchApi<{ data: { userId: string } }>("/api/users/create", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
}).then((res) => res.data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["users"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard-stats"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateUser() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: { id: string; [key: string]: unknown }) =>
|
||||
fetchApi<{ data: { success: boolean } }>(`/api/users?id=${data.id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ["users"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["user", variables.id] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteUser() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
fetchApi<{ data: { success: boolean } }>(`/api/users?id=${userId}`, {
|
||||
method: "DELETE",
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["users"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard-stats"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useGenerateRecommendations() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userId?: string) =>
|
||||
fetchApi<{
|
||||
data: { success: boolean; recommendations?: Recommendation[] };
|
||||
}>("/api/recommendations/generate", {
|
||||
method: "POST",
|
||||
body: userId ? JSON.stringify({ userId }) : undefined,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["recommendations"] });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["pending-recommendations-count"],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useApproveRecommendation() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: { recommendationId: string; approved: boolean }) =>
|
||||
fetchApi<{ data: { success: boolean } }>("/api/recommendations/approve", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["recommendations"] });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["pending-recommendations-count"],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateRecommendation() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: {
|
||||
id: string;
|
||||
content?: string;
|
||||
activityPlan?: string;
|
||||
dietPlan?: string;
|
||||
}) =>
|
||||
fetchApi<{ data: { success: boolean } }>("/api/recommendations", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["recommendations"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCheckIn() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
fetchApi<{ data: { success: boolean; record: AttendanceRecord } }>(
|
||||
"/api/attendance/check-in",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ userId }),
|
||||
},
|
||||
),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["attendance"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCheckOut() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
fetchApi<{ data: { success: boolean } }>("/api/attendance/check-out", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ userId }),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["attendance"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useInvitations(gymId?: string) {
|
||||
return useQuery({
|
||||
queryKey: ["invitations", gymId],
|
||||
queryFn: () => {
|
||||
const url = gymId
|
||||
? `/api/invitations?gymId=${gymId}`
|
||||
: "/api/invitations";
|
||||
return fetchApi<{ data: { invitations: Invitation[] } }>(url).then(
|
||||
(res) => res.data?.invitations ?? [],
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSendInvitation() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: { email: string; role: string }) =>
|
||||
fetchApi<{ data: { success: boolean } }>("/api/invitations", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["invitations"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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 {
|
||||
userGrowth: { label: string; value: number }[];
|
||||
membershipDistribution: { label: string; value: number; color: string }[];
|
||||
revenue: { label: string; value: number; color: string }[];
|
||||
}
|
||||
|
||||
export function useAnalytics(months: number = 6, gymId?: string) {
|
||||
return useQuery({
|
||||
queryKey: ["analytics", months, gymId],
|
||||
queryFn: () => {
|
||||
const url = gymId
|
||||
? `/api/admin/analytics?months=${months}&gymId=${gymId}`
|
||||
: `/api/admin/analytics?months=${months}`;
|
||||
return fetchApi<{ data: { analytics: AnalyticsData } }>(url).then(
|
||||
(res) => res.data?.analytics,
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { USER_ROLES, type UserRole } from "@fitai/shared";
|
||||
import { getDatabase } from "../database";
|
||||
|
||||
export interface AuthContext {
|
||||
userId: string;
|
||||
role: UserRole;
|
||||
gymId: string | null;
|
||||
}
|
||||
|
||||
export interface AuthResult extends AuthContext {}
|
||||
|
||||
/**
|
||||
* Get the full authentication context including gymId
|
||||
* Combines Clerk session claims with database lookup for accurate gym assignment
|
||||
*
|
||||
* @returns AuthContext with userId, role, and gymId
|
||||
*
|
||||
* @example
|
||||
* const { userId, role, gymId } = await getAuthContext();
|
||||
* // userId: "user_abc123"
|
||||
* // role: "admin"
|
||||
* // gymId: "gym_xyz"
|
||||
*/
|
||||
export async function getAuthContext(): Promise<AuthContext> {
|
||||
const { userId, sessionClaims } = await auth();
|
||||
|
||||
if (!userId) {
|
||||
throw new Error("Unauthorized: No authenticated user");
|
||||
}
|
||||
|
||||
// Try to get role from Clerk metadata (could be in publicMetadata or metadata)
|
||||
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)) {
|
||||
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
|
||||
let gymId: string | null = null;
|
||||
|
||||
// First try Clerk publicMetadata (faster path)
|
||||
const clerkGymId = (sessionClaims?.publicMetadata as { gymId?: string })
|
||||
?.gymId;
|
||||
if (clerkGymId) {
|
||||
gymId = clerkGymId;
|
||||
} else {
|
||||
// Try metadata field
|
||||
const metadataGymId = (sessionClaims?.metadata as { gymId?: string })
|
||||
?.gymId;
|
||||
if (metadataGymId) {
|
||||
gymId = metadataGymId;
|
||||
} else {
|
||||
// Fallback to database lookup
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { userId, role, gymId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware to require authentication and optionally check user role
|
||||
* Enhanced version that also retrieves gymId
|
||||
*
|
||||
* @param allowedRoles - Array of roles allowed to access the endpoint (optional)
|
||||
* @returns Authentication result with userId, role, and gymId, or NextResponse error
|
||||
*
|
||||
* @example
|
||||
* export async function DELETE(request: NextRequest) {
|
||||
* const authResult = await requireAuth(["admin", "superAdmin"]);
|
||||
* if (authResult instanceof NextResponse) return authResult;
|
||||
* const { userId, role, gymId } = authResult;
|
||||
* // ... proceed with authorized logic
|
||||
* }
|
||||
*/
|
||||
export async function requireAuth(
|
||||
allowedRoles?: UserRole[],
|
||||
): Promise<AuthResult | NextResponse> {
|
||||
try {
|
||||
const context = await getAuthContext();
|
||||
|
||||
// Check if user has required role
|
||||
if (allowedRoles && allowedRoles.length > 0) {
|
||||
if (!allowedRoles.includes(context.role)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `Forbidden - Requires one of: ${allowedRoles.join(", ")}`,
|
||||
requiredRoles: allowedRoles,
|
||||
userRole: context.role,
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return context;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
|
||||
if (message.includes("Unauthorized")) {
|
||||
return NextResponse.json(
|
||||
{ error: "Unauthorized - Authentication required" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
if (message.includes("Forbidden")) {
|
||||
return NextResponse.json({ error: message }, { status: 403 });
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Require authentication with gym access validation
|
||||
* Use this for endpoints that need to verify the user can access a specific gym
|
||||
*
|
||||
* @param allowedRoles - Roles allowed to access this endpoint
|
||||
* @param requiredGymId - Gym ID that must be accessed (optional - uses user's gym if not provided)
|
||||
* @returns AuthResult with full context, or NextResponse error
|
||||
*
|
||||
* @example
|
||||
* // Admin accessing their own gym
|
||||
* const result = await requireGymAccess(["admin"]);
|
||||
*
|
||||
* // SuperAdmin accessing specific gym
|
||||
* const result = await requireGymAccess(["superAdmin"], "gym_123");
|
||||
*/
|
||||
export async function requireGymAccess(
|
||||
allowedRoles: UserRole[],
|
||||
requiredGymId?: string,
|
||||
): Promise<AuthResult | NextResponse> {
|
||||
const authResult = await requireAuth(allowedRoles);
|
||||
|
||||
if (authResult instanceof NextResponse) {
|
||||
return authResult;
|
||||
}
|
||||
|
||||
const { role, gymId: userGymId } = authResult;
|
||||
|
||||
// Determine target gym
|
||||
const targetGymId = requiredGymId ?? userGymId;
|
||||
|
||||
// SuperAdmin can access any gym
|
||||
if (role === "superAdmin") {
|
||||
return { ...authResult, gymId: targetGymId };
|
||||
}
|
||||
|
||||
// Other roles must have matching gym
|
||||
if (!targetGymId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden - User is not assigned to a gym" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
if (userGymId !== targetGymId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden - Cannot access other gym's data" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
return { ...authResult, gymId: targetGymId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the target gym ID from request for superAdmin context switching
|
||||
* SuperAdmins can pass ?gymId to view specific gym data
|
||||
*
|
||||
* @param request - NextRequest with query params
|
||||
* @param userRole - Current user's role
|
||||
* @param userGymId - Current user's gym ID
|
||||
* @returns Target gym ID or undefined for superAdmin viewing all
|
||||
*
|
||||
* @example
|
||||
* const targetGymId = getTargetGymId(request, role, gymId);
|
||||
* // For superAdmin with ?gymId=abc -> "abc"
|
||||
* // For superAdmin without param -> undefined (all gyms)
|
||||
* // For admin -> always returns their gymId
|
||||
*/
|
||||
export function getTargetGymId(
|
||||
request: NextRequest,
|
||||
userRole: UserRole,
|
||||
userGymId: string | null,
|
||||
): string | undefined {
|
||||
// For superAdmin, allow gymId query param for context switching
|
||||
if (userRole === "superAdmin") {
|
||||
const queryGymId = request.nextUrl.searchParams.get("gymId");
|
||||
return queryGymId ?? undefined;
|
||||
}
|
||||
|
||||
// For other roles, they can only access their own gym
|
||||
return userGymId ?? undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the authenticated user is trying to modify their own account
|
||||
* Useful for preventing self-deletion or self-demotion
|
||||
*/
|
||||
export function isSelfModification(
|
||||
userId: string,
|
||||
targetUserId: string,
|
||||
): boolean {
|
||||
return userId === targetUserId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that an admin isn't demoting themselves or deleting their own account
|
||||
*/
|
||||
export function preventSelfModification(
|
||||
userId: string,
|
||||
targetUserId: string,
|
||||
action: string,
|
||||
): NextResponse | undefined {
|
||||
if (isSelfModification(userId, targetUserId)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `Cannot ${action} your own account`,
|
||||
hint: "Ask another administrator to perform this action",
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import type { UserRole } from "@fitai/shared";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
/**
|
||||
* Check if a user can access data from a specific gym
|
||||
*
|
||||
* @param userRole - The role of the requesting user
|
||||
* @param userGymId - The gym ID of the requesting user (null for superAdmin)
|
||||
* @param targetGymId - The gym ID being accessed (undefined means all gyms)
|
||||
* @returns true if access is allowed
|
||||
*
|
||||
* @example
|
||||
* // SuperAdmin accessing any gym
|
||||
* canAccessGym("superAdmin", null, "gym_123") // true
|
||||
*
|
||||
* // Admin accessing their own gym
|
||||
* canAccessGym("admin", "gym_abc", "gym_abc") // true
|
||||
*
|
||||
* // Admin trying to access other gym
|
||||
* canAccessGym("admin", "gym_abc", "gym_xyz") // false
|
||||
*/
|
||||
export function canAccessGym(
|
||||
userRole: UserRole,
|
||||
userGymId: string | null,
|
||||
targetGymId: string | undefined,
|
||||
): boolean {
|
||||
// SuperAdmin can access any gym
|
||||
if (userRole === "superAdmin") {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If no target gym specified, allow access to own gym
|
||||
if (targetGymId === undefined) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Non-superAdmins must have a gymId
|
||||
if (!userGymId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Must match the gym
|
||||
return userGymId === targetGymId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a user can manage (create/update/delete) another user
|
||||
* Based on role hierarchy and gym membership
|
||||
*
|
||||
* @param requesterRole - Role of the user making the request
|
||||
* @param requesterGymId - Gym ID of the requesting user
|
||||
* @param targetRole - Role of the user being managed
|
||||
* @param targetGymId - Gym ID of the user being managed
|
||||
* @returns true if management is allowed
|
||||
*
|
||||
* @example
|
||||
* // SuperAdmin can manage anyone
|
||||
* canManageUser("superAdmin", null, "admin", "gym_abc") // true
|
||||
*
|
||||
* // Admin can manage trainers and clients in their gym
|
||||
* canManageUser("admin", "gym_abc", "trainer", "gym_abc") // true
|
||||
* canManageUser("admin", "gym_abc", "client", "gym_abc") // true
|
||||
*
|
||||
* // Admin cannot manage users in other gyms
|
||||
* canManageUser("admin", "gym_abc", "trainer", "gym_xyz") // false
|
||||
*
|
||||
* // Trainer can manage clients in their gym
|
||||
* canManageUser("trainer", "gym_abc", "client", "gym_abc") // true
|
||||
*/
|
||||
export function canManageUser(
|
||||
requesterRole: UserRole,
|
||||
requesterGymId: string | null,
|
||||
targetRole: UserRole,
|
||||
targetGymId: string | null,
|
||||
): boolean {
|
||||
// SuperAdmin can manage anyone
|
||||
if (requesterRole === "superAdmin") {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Role hierarchy: admin > trainer > client
|
||||
const roleHierarchy: Record<UserRole, number> = {
|
||||
superAdmin: 4,
|
||||
admin: 3,
|
||||
trainer: 2,
|
||||
client: 1,
|
||||
};
|
||||
|
||||
const requesterLevel = roleHierarchy[requesterRole];
|
||||
const targetLevel = roleHierarchy[targetRole];
|
||||
|
||||
// Cannot manage users at same or higher level
|
||||
if (requesterLevel <= targetLevel) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Must have gym access
|
||||
if (!requesterGymId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// For admin/trainer, target must be in same gym
|
||||
if (requesterRole === "admin" || requesterRole === "trainer") {
|
||||
return requesterGymId === targetGymId;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a trainer can access a specific client's data
|
||||
* Trainer must be assigned to that client via trainerClients table
|
||||
*
|
||||
* @param trainerGymId - Gym ID of the trainer
|
||||
* @param clientGymId - Gym ID of the client
|
||||
* @returns true if in same gym
|
||||
*
|
||||
* @note In a more complex system, this would query trainerClients table
|
||||
* For now, we use gym-based access (trainer and client in same gym)
|
||||
*/
|
||||
export function canTrainerAccessClient(
|
||||
trainerGymId: string | null,
|
||||
clientGymId: string | null,
|
||||
): boolean {
|
||||
if (!trainerGymId || !clientGymId) {
|
||||
return false;
|
||||
}
|
||||
return trainerGymId === clientGymId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the roles that a specific role can invite
|
||||
* Based on role hierarchy
|
||||
*
|
||||
* @param role - The role wanting to invite
|
||||
* @returns Array of roles that can be invited
|
||||
*
|
||||
* @example
|
||||
* getInvitableRoles("superAdmin") // ["admin", "trainer", "client"]
|
||||
* getInvitableRoles("admin") // ["trainer", "client"]
|
||||
* getInvitableRoles("trainer") // ["client"]
|
||||
* getInvitableRoles("client") // []
|
||||
*/
|
||||
export function getInvitableRoles(role: UserRole): UserRole[] {
|
||||
const invitationRules: Record<UserRole, UserRole[]> = {
|
||||
superAdmin: ["admin", "trainer", "client"],
|
||||
admin: ["trainer", "client"],
|
||||
trainer: ["client"],
|
||||
client: [],
|
||||
};
|
||||
|
||||
return invitationRules[role] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate gym access and return error response if denied
|
||||
* Use this in API routes to enforce gym-based access control
|
||||
*
|
||||
* @param request - NextRequest for getting query params
|
||||
* @param userRole - Current user's role
|
||||
* @param userGymId - Current user's gym ID
|
||||
* @param targetGymId - Gym being accessed (optional)
|
||||
* @returns NextResponse if denied, undefined if allowed
|
||||
*
|
||||
* @example
|
||||
* export async function GET(request: NextRequest) {
|
||||
* const error = await validateGymAccess(request, role, gymId);
|
||||
* if (error) return error;
|
||||
* // ... proceed
|
||||
* }
|
||||
*/
|
||||
export function validateGymAccess(
|
||||
userRole: UserRole,
|
||||
userGymId: string | null,
|
||||
targetGymId?: string,
|
||||
): NextResponse | undefined {
|
||||
if (!canAccessGym(userRole, userGymId, targetGymId)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden - Cannot access this gym's data" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get filter condition for gym-scoped queries
|
||||
* Returns appropriate filter based on user role
|
||||
*
|
||||
* @param userRole - Current user's role
|
||||
* @param userGymId - Current user's gym ID
|
||||
* @returns Filter object or undefined (no filter = all gyms)
|
||||
*
|
||||
* @example
|
||||
* // For superAdmin: returns undefined (no filter)
|
||||
* getGymFilter("superAdmin", null) // undefined
|
||||
*
|
||||
* // For admin: returns { gymId: "gym_abc" }
|
||||
* getGymFilter("admin", "gym_abc") // { gymId: "gym_abc" }
|
||||
*/
|
||||
export function getGymFilter(
|
||||
userRole: UserRole,
|
||||
userGymId: string | null,
|
||||
): { gymId: string } | undefined {
|
||||
// SuperAdmin sees all gyms
|
||||
if (userRole === "superAdmin") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Other roles filtered by their gym
|
||||
if (userGymId) {
|
||||
return { gymId: userGymId };
|
||||
}
|
||||
|
||||
// No gym assigned - return filter that matches nothing
|
||||
return { gymId: "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all gym IDs a user can access
|
||||
* SuperAdmin gets all gyms, others get only their own
|
||||
*
|
||||
* @param userRole - Current user's role
|
||||
* @param userGymId - Current user's gym ID
|
||||
* @param allGymIds - List of all gym IDs in system (for superAdmin)
|
||||
* @returns Array of accessible gym IDs
|
||||
*
|
||||
* @example
|
||||
* getAccessibleGymIds("admin", "gym_abc", ["gym_abc", "gym_xyz"])
|
||||
* // Returns: ["gym_abc"]
|
||||
*
|
||||
* getAccessibleGymIds("superAdmin", null, ["gym_abc", "gym_xyz"])
|
||||
* // Returns: ["gym_abc", "gym_xyz"]
|
||||
*/
|
||||
export function getAccessibleGymIds(
|
||||
userRole: UserRole,
|
||||
userGymId: string | null,
|
||||
allGymIds: string[],
|
||||
): string[] {
|
||||
if (userRole === "superAdmin") {
|
||||
return allGymIds;
|
||||
}
|
||||
|
||||
if (userGymId) {
|
||||
return [userGymId];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { getDatabase } from "@/lib/database";
|
||||
|
||||
/**
|
||||
* Get users filtered by gym ID
|
||||
*
|
||||
* @param gymId - Gym ID to filter by (undefined returns all users for superAdmin)
|
||||
* @returns Array of users in the gym
|
||||
*/
|
||||
export async function getUsersByGym(gymId?: string) {
|
||||
const db = await getDatabase();
|
||||
const allUsers = await db.getAllUsers();
|
||||
|
||||
if (!gymId) {
|
||||
return allUsers;
|
||||
}
|
||||
|
||||
return allUsers.filter((u) => u.gymId === gymId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get clients filtered by gym ID
|
||||
*
|
||||
* @param gymId - Gym ID to filter by
|
||||
* @returns Array of clients in the gym
|
||||
*/
|
||||
export async function getClientsByGym(gymId: string) {
|
||||
const db = await getDatabase();
|
||||
const allUsers = await db.getAllUsers();
|
||||
const allClients = await db.getAllClients();
|
||||
|
||||
const gymClientUserIds = allUsers
|
||||
.filter((u) => u.gymId === gymId && u.role === "client")
|
||||
.map((u) => u.id);
|
||||
|
||||
if (gymClientUserIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return allClients.filter((c) => gymClientUserIds.includes(c.userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get trainers filtered by gym ID
|
||||
*
|
||||
* @param gymId - Gym ID to filter by
|
||||
* @returns Array of trainers in the gym
|
||||
*/
|
||||
export async function getTrainersByGym(gymId: string) {
|
||||
const db = await getDatabase();
|
||||
const allUsers = await db.getAllUsers();
|
||||
|
||||
return allUsers.filter((u) => u.gymId === gymId && u.role === "trainer");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get attendance filtered by gym ID
|
||||
*
|
||||
* @param gymId - Gym ID to filter by
|
||||
* @returns Array of attendance records in the gym
|
||||
*/
|
||||
export async function getAttendanceByGym(gymId: string) {
|
||||
const db = await getDatabase();
|
||||
const allUsers = await db.getAllUsers();
|
||||
const allAttendance = await db.getAllAttendance();
|
||||
|
||||
const gymUserIds = allUsers.filter((u) => u.gymId === gymId).map((u) => u.id);
|
||||
|
||||
if (gymUserIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return allAttendance.filter((a) => gymUserIds.includes(a.userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recommendations filtered by gym ID
|
||||
*
|
||||
* @param gymId - Gym ID to filter by
|
||||
* @returns Array of recommendations in the gym
|
||||
*/
|
||||
export async function getRecommendationsByGym(gymId: string) {
|
||||
const db = await getDatabase();
|
||||
const allUsers = await db.getAllUsers();
|
||||
const allRecommendations = await db.getAllRecommendations();
|
||||
|
||||
const gymUserIds = allUsers.filter((u) => u.gymId === gymId).map((u) => u.id);
|
||||
|
||||
if (gymUserIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return allRecommendations.filter((r) => gymUserIds.includes(r.userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get fitness profiles filtered by gym ID
|
||||
*
|
||||
* @param gymId - Gym ID to filter by
|
||||
* @returns Array of fitness profiles in the gym
|
||||
*/
|
||||
export async function getFitnessProfilesByGym(gymId: string) {
|
||||
const db = await getDatabase();
|
||||
const allUsers = await db.getAllUsers();
|
||||
const allProfiles = await db.getAllFitnessProfiles();
|
||||
|
||||
const gymUserIds = allUsers.filter((u) => u.gymId === gymId).map((u) => u.id);
|
||||
|
||||
if (gymUserIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return allProfiles.filter((p) => gymUserIds.includes(p.userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get fitness goals filtered by gym ID
|
||||
*
|
||||
* @param gymId - Gym ID to filter by
|
||||
* @returns Array of fitness goals in the gym
|
||||
*/
|
||||
export async function getFitnessGoalsByGym(gymId: string) {
|
||||
const db = await getDatabase();
|
||||
const allUsers = await db.getAllUsers();
|
||||
|
||||
const gymUserIds = allUsers.filter((u) => u.gymId === gymId).map((u) => u.id);
|
||||
|
||||
if (gymUserIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const allGoals: any[] = [];
|
||||
for (const userId of gymUserIds) {
|
||||
const goals = await db.getFitnessGoalsByUserId(userId);
|
||||
allGoals.push(...goals);
|
||||
}
|
||||
|
||||
return allGoals.sort(
|
||||
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user by ID and check if they belong to a specific gym
|
||||
*/
|
||||
export async function getUserGymId(userId: string): Promise<string | null> {
|
||||
const db = await getDatabase();
|
||||
const user = await db.getUserById(userId);
|
||||
return user?.gymId ?? null;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Migration Script: Fix gym assignments for users without gymId
|
||||
*
|
||||
* This script:
|
||||
* 1. Finds all users with null gymId
|
||||
* 2. For admins: Assigns them to gym where they are adminUserId
|
||||
* 3. For trainers: Gets gymId from their trainerClients records
|
||||
* 4. For clients: Gets gymId from trainerClients or leaves as null for manual review
|
||||
*
|
||||
* Run with: node apps/admin/src/lib/migrations/fix-gym-assignments.js
|
||||
*
|
||||
* Note: Run this AFTER setting up the database, before starting the app
|
||||
*/
|
||||
|
||||
const Database = require("better-sqlite3");
|
||||
|
||||
// Use absolute path to the database - this is where the app stores data
|
||||
const dbPath = "/home/echo/dev/prototype/apps/admin/data/fitai.db";
|
||||
|
||||
function fixGymAssignments() {
|
||||
console.log("Starting gym assignment migration...\n");
|
||||
console.log(`Database path: ${dbPath}\n`);
|
||||
|
||||
const db = new Database(dbPath);
|
||||
|
||||
// Step 1: Find all users without gymId
|
||||
const usersWithoutGym = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT id, email, role FROM users WHERE gym_id IS NULL
|
||||
`,
|
||||
)
|
||||
.all();
|
||||
|
||||
console.log(`Found ${usersWithoutGym.length} users without gymId`);
|
||||
|
||||
let adminsFixed = 0;
|
||||
let trainersFixed = 0;
|
||||
let clientsFixed = 0;
|
||||
const unableToFix = [];
|
||||
|
||||
for (const user of usersWithoutGym) {
|
||||
try {
|
||||
if (user.role === "admin") {
|
||||
// Find gym where this user is admin
|
||||
const gym = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT id, name FROM gyms WHERE admin_user_id = ?
|
||||
`,
|
||||
)
|
||||
.get(user.id);
|
||||
|
||||
if (gym) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE users SET gym_id = ? WHERE id = ?
|
||||
`,
|
||||
).run(gym.id, user.id);
|
||||
|
||||
console.log(` ✓ Fixed admin ${user.email} -> gym ${gym.name}`);
|
||||
adminsFixed++;
|
||||
} else {
|
||||
unableToFix.push(`Admin ${user.email} (no gym found)`);
|
||||
}
|
||||
} else if (user.role === "trainer") {
|
||||
// Get gym from trainerClients
|
||||
const tc = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT gym_id FROM trainer_clients WHERE trainer_user_id = ? LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(user.id);
|
||||
|
||||
if (tc) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE users SET gym_id = ? WHERE id = ?
|
||||
`,
|
||||
).run(tc.gym_id, user.id);
|
||||
|
||||
console.log(` ✓ Fixed trainer ${user.email} -> gym ${tc.gym_id}`);
|
||||
trainersFixed++;
|
||||
} else {
|
||||
unableToFix.push(`Trainer ${user.email} (no trainerClients record)`);
|
||||
}
|
||||
} else if (user.role === "client") {
|
||||
// Get gym from trainerClients
|
||||
const tc = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT gym_id FROM trainer_clients WHERE client_user_id = ? LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(user.id);
|
||||
|
||||
if (tc) {
|
||||
db.prepare(
|
||||
`
|
||||
UPDATE users SET gym_id = ? WHERE id = ?
|
||||
`,
|
||||
).run(tc.gym_id, user.id);
|
||||
|
||||
console.log(` ✓ Fixed client ${user.email} -> gym ${tc.gym_id}`);
|
||||
clientsFixed++;
|
||||
} else {
|
||||
unableToFix.push(`Client ${user.email} (no trainer assignment)`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(` ✗ Error fixing user ${user.email}:`, error.message);
|
||||
unableToFix.push(`User ${user.email} (error: ${error.message})`);
|
||||
}
|
||||
}
|
||||
|
||||
db.close();
|
||||
|
||||
console.log("\n=== Migration Summary ===");
|
||||
console.log(`Admins fixed: ${adminsFixed}`);
|
||||
console.log(`Trainers fixed: ${trainersFixed}`);
|
||||
console.log(`Clients fixed: ${clientsFixed}`);
|
||||
console.log(`Unable to fix: ${unableToFix.length}`);
|
||||
|
||||
if (unableToFix.length > 0) {
|
||||
console.log("\nUsers requiring manual review:");
|
||||
unableToFix.forEach((u) => console.log(` - ${u}`));
|
||||
}
|
||||
|
||||
console.log("\nMigration complete!");
|
||||
}
|
||||
|
||||
// Run if called directly
|
||||
if (require.main === module) {
|
||||
fixGymAssignments();
|
||||
}
|
||||
|
||||
module.exports = { fixGymAssignments };
|
||||
@@ -15,8 +15,13 @@ export const passwordSchema = z
|
||||
|
||||
export const phoneSchema = z
|
||||
.string()
|
||||
.regex(/^\+?[1-9]\d{1,14}$/, "Invalid phone number format")
|
||||
.optional();
|
||||
.optional()
|
||||
.refine(
|
||||
(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");
|
||||
|
||||
@@ -31,6 +36,14 @@ export const userRoleSchema = z.enum([
|
||||
"superAdmin",
|
||||
]);
|
||||
|
||||
export const membershipTypeSchema = z.enum(["basic", "premium", "vip"]);
|
||||
|
||||
export const membershipStatusSchema = z.enum([
|
||||
"active",
|
||||
"inactive",
|
||||
"suspended",
|
||||
]);
|
||||
|
||||
export const userSchema = z.object({
|
||||
email: emailSchema,
|
||||
password: passwordSchema,
|
||||
@@ -63,6 +76,8 @@ export const userUpdateWithIdSchema = z.object({
|
||||
role: userRoleSchema.optional(),
|
||||
phone: phoneSchema,
|
||||
gymId: z.string().nullable().optional(),
|
||||
membershipType: membershipTypeSchema.optional(),
|
||||
membershipStatus: membershipStatusSchema.optional(),
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
@@ -333,6 +348,8 @@ export type User = z.infer<typeof userSchema>;
|
||||
export type UserUpdate = z.infer<typeof userUpdateSchema>;
|
||||
export type UserLogin = z.infer<typeof userLoginSchema>;
|
||||
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 FitnessGoalUpdate = z.infer<typeof fitnessGoalUpdateSchema>;
|
||||
|
||||
@@ -96,9 +96,13 @@ export default function OnboardingScreen() {
|
||||
|
||||
const fitnessData = {
|
||||
userId: user.id,
|
||||
height: parseFloat(fitnessProfile.height),
|
||||
weight: parseFloat(fitnessProfile.weight),
|
||||
age: parseInt(fitnessProfile.age),
|
||||
height: fitnessProfile.height
|
||||
? parseFloat(fitnessProfile.height)
|
||||
: undefined,
|
||||
weight: fitnessProfile.weight
|
||||
? parseFloat(fitnessProfile.weight)
|
||||
: undefined,
|
||||
age: fitnessProfile.age ? parseInt(fitnessProfile.age, 10) : undefined,
|
||||
fitnessGoals: fitnessProfile.goals ? [fitnessProfile.goals] : [],
|
||||
medicalConditions: fitnessProfile.medicalConditions || undefined,
|
||||
allergies: fitnessProfile.dietaryRestrictions || undefined,
|
||||
|
||||
@@ -13,8 +13,10 @@ import {
|
||||
import { useRouter, Stack } from "expo-router";
|
||||
import { useAuth } from "@clerk/clerk-expo";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { LinearGradient } from "expo-linear-gradient";
|
||||
import { theme } from "../styles/theme";
|
||||
import { useTheme } from "../contexts/ThemeContext";
|
||||
import { MinimalCard } from "../components/MinimalCard";
|
||||
import { MinimalButton } from "../components/MinimalButton";
|
||||
import { IconContainer } from "../components/IconContainer";
|
||||
import { API_BASE_URL } from "../config/api";
|
||||
|
||||
interface FitnessProfileData {
|
||||
@@ -30,13 +32,13 @@ interface FitnessProfileData {
|
||||
}
|
||||
|
||||
const GENDER_OPTIONS = [
|
||||
{ label: "Male", value: "male", icon: "male" },
|
||||
{ label: "Female", value: "female", icon: "female" },
|
||||
{ label: "Other", value: "other", icon: "transgender" },
|
||||
{ label: "Male", value: "male", icon: "male-outline" },
|
||||
{ label: "Female", value: "female", icon: "female-outline" },
|
||||
{ label: "Other", value: "other", icon: "transgender-outline" },
|
||||
{
|
||||
label: "Prefer not to say",
|
||||
value: "prefer_not_to_say",
|
||||
icon: "help-circle",
|
||||
icon: "help-circle-outline",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -45,31 +47,26 @@ const FITNESS_GOAL_OPTIONS = [
|
||||
label: "Weight Loss",
|
||||
value: "weight_loss",
|
||||
icon: "trending-down",
|
||||
color: theme.colors.danger,
|
||||
color: "#FF3B3B",
|
||||
},
|
||||
{
|
||||
label: "Muscle Gain",
|
||||
value: "muscle_gain",
|
||||
icon: "barbell",
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
{
|
||||
label: "Endurance",
|
||||
value: "endurance",
|
||||
icon: "bicycle",
|
||||
color: theme.colors.success,
|
||||
color: "#0066FF",
|
||||
},
|
||||
{ label: "Endurance", value: "endurance", icon: "bicycle", color: "#00D26A" },
|
||||
{
|
||||
label: "Flexibility",
|
||||
value: "flexibility",
|
||||
icon: "body",
|
||||
color: theme.colors.purple,
|
||||
color: "#7B2CBF",
|
||||
},
|
||||
{
|
||||
label: "General Fitness",
|
||||
value: "general_fitness",
|
||||
icon: "fitness",
|
||||
color: theme.colors.warning,
|
||||
color: "#FFB800",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -99,6 +96,7 @@ const ACTIVITY_LEVEL_OPTIONS = [
|
||||
|
||||
export default function FitnessProfileScreen() {
|
||||
const router = useRouter();
|
||||
const { colors, typography } = useTheme();
|
||||
const { userId, getToken } = useAuth();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [fetchingProfile, setFetchingProfile] = useState(true);
|
||||
@@ -124,7 +122,6 @@ export default function FitnessProfileScreen() {
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.profile) {
|
||||
// Normalize old activity level values to new schema
|
||||
let activityLevel = data.profile.activityLevel || "";
|
||||
if (activityLevel === "light") activityLevel = "lightly_active";
|
||||
if (activityLevel === "moderate") activityLevel = "moderately_active";
|
||||
@@ -159,8 +156,6 @@ export default function FitnessProfileScreen() {
|
||||
setLoading(true);
|
||||
const token = await getToken();
|
||||
|
||||
// Prepare data with userId and convert fitnessGoal to fitnessGoals array
|
||||
// Convert empty strings to undefined for optional enum fields
|
||||
const dataToSave = {
|
||||
userId: userId,
|
||||
height: profileData.height,
|
||||
@@ -205,8 +200,13 @@ export default function FitnessProfileScreen() {
|
||||
|
||||
if (fetchingProfile) {
|
||||
return (
|
||||
<View style={styles.loadingContainer}>
|
||||
<ActivityIndicator size="large" color={theme.colors.primary} />
|
||||
<View
|
||||
style={[
|
||||
styles.loadingContainer,
|
||||
{ backgroundColor: colors.background },
|
||||
]}
|
||||
>
|
||||
<ActivityIndicator size="large" color={colors.primary} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -214,18 +214,28 @@ export default function FitnessProfileScreen() {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={{ headerShown: false }} />
|
||||
<View style={styles.container}>
|
||||
<View style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
{/* Header */}
|
||||
<LinearGradient colors={theme.gradients.primary} style={styles.header}>
|
||||
<View
|
||||
style={[
|
||||
styles.header,
|
||||
{
|
||||
backgroundColor: colors.primary,
|
||||
paddingTop: Platform.OS === "ios" ? 60 : 40,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<TouchableOpacity
|
||||
style={styles.backButton}
|
||||
onPress={() => router.back()}
|
||||
>
|
||||
<Ionicons name="arrow-back" size={24} color="#fff" />
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.headerTitle}>Fitness Profile</Text>
|
||||
<Text style={[typography.h2, { color: "#fff" }]}>
|
||||
Fitness Profile
|
||||
</Text>
|
||||
<View style={{ width: 40 }} />
|
||||
</LinearGradient>
|
||||
</View>
|
||||
|
||||
<ScrollView
|
||||
style={styles.scrollView}
|
||||
@@ -234,19 +244,41 @@ export default function FitnessProfileScreen() {
|
||||
>
|
||||
{/* Basic Information */}
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Basic Information</Text>
|
||||
<View style={styles.card}>
|
||||
<View style={styles.row}>
|
||||
<Text
|
||||
style={[
|
||||
typography.h3,
|
||||
{ color: colors.textPrimary, marginBottom: 16 },
|
||||
]}
|
||||
>
|
||||
Basic Information
|
||||
</Text>
|
||||
<MinimalCard variant="elevated" style={styles.card}>
|
||||
<View style={styles.inputRow}>
|
||||
<View style={styles.inputGroup}>
|
||||
<Text style={styles.label}>Height (cm)</Text>
|
||||
<View style={styles.inputContainer}>
|
||||
<Text
|
||||
style={[
|
||||
typography.label,
|
||||
{ color: colors.textSecondary, marginBottom: 8 },
|
||||
]}
|
||||
>
|
||||
HEIGHT (CM)
|
||||
</Text>
|
||||
<View
|
||||
style={[
|
||||
styles.inputContainer,
|
||||
{
|
||||
backgroundColor: colors.surfaceElevated,
|
||||
borderColor: colors.border,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name="resize-outline"
|
||||
name="resize"
|
||||
size={20}
|
||||
color={theme.colors.gray400}
|
||||
color={colors.textTertiary}
|
||||
/>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
style={[styles.input, { color: colors.textPrimary }]}
|
||||
value={profileData.height?.toString() || ""}
|
||||
onChangeText={(text) =>
|
||||
updateField(
|
||||
@@ -256,20 +288,35 @@ export default function FitnessProfileScreen() {
|
||||
}
|
||||
keyboardType="decimal-pad"
|
||||
placeholder="175"
|
||||
placeholderTextColor={theme.colors.gray400}
|
||||
placeholderTextColor={colors.textTertiary}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.inputGroup}>
|
||||
<Text style={styles.label}>Weight (kg)</Text>
|
||||
<View style={styles.inputContainer}>
|
||||
<Text
|
||||
style={[
|
||||
typography.label,
|
||||
{ color: colors.textSecondary, marginBottom: 8 },
|
||||
]}
|
||||
>
|
||||
WEIGHT (KG)
|
||||
</Text>
|
||||
<View
|
||||
style={[
|
||||
styles.inputContainer,
|
||||
{
|
||||
backgroundColor: colors.surfaceElevated,
|
||||
borderColor: colors.border,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name="scale-outline"
|
||||
name="scale"
|
||||
size={20}
|
||||
color={theme.colors.gray400}
|
||||
color={colors.textTertiary}
|
||||
/>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
style={[styles.input, { color: colors.textPrimary }]}
|
||||
value={profileData.weight?.toString() || ""}
|
||||
onChangeText={(text) =>
|
||||
updateField(
|
||||
@@ -279,45 +326,75 @@ export default function FitnessProfileScreen() {
|
||||
}
|
||||
keyboardType="decimal-pad"
|
||||
placeholder="70"
|
||||
placeholderTextColor={theme.colors.gray400}
|
||||
placeholderTextColor={colors.textTertiary}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.inputGroup}>
|
||||
<Text style={styles.label}>Age</Text>
|
||||
<View style={styles.inputContainer}>
|
||||
<Text
|
||||
style={[
|
||||
typography.label,
|
||||
{ color: colors.textSecondary, marginBottom: 8 },
|
||||
]}
|
||||
>
|
||||
AGE
|
||||
</Text>
|
||||
<View
|
||||
style={[
|
||||
styles.inputContainer,
|
||||
{
|
||||
backgroundColor: colors.surfaceElevated,
|
||||
borderColor: colors.border,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name="calendar-outline"
|
||||
name="calendar"
|
||||
size={20}
|
||||
color={theme.colors.gray400}
|
||||
color={colors.textTertiary}
|
||||
/>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
style={[styles.input, { color: colors.textPrimary }]}
|
||||
value={profileData.age?.toString() || ""}
|
||||
onChangeText={(text) =>
|
||||
updateField("age", text ? parseInt(text, 10) : undefined)
|
||||
}
|
||||
keyboardType="number-pad"
|
||||
placeholder="25"
|
||||
placeholderTextColor={theme.colors.gray400}
|
||||
placeholderTextColor={colors.textTertiary}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</MinimalCard>
|
||||
</View>
|
||||
|
||||
{/* Gender Selection */}
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Gender</Text>
|
||||
<View style={styles.optionsRow}>
|
||||
<Text
|
||||
style={[
|
||||
typography.h3,
|
||||
{ color: colors.textPrimary, marginBottom: 16 },
|
||||
]}
|
||||
>
|
||||
Gender
|
||||
</Text>
|
||||
<View style={styles.genderRow}>
|
||||
{GENDER_OPTIONS.map((option) => (
|
||||
<TouchableOpacity
|
||||
key={option.value}
|
||||
style={[
|
||||
styles.optionCard,
|
||||
profileData.gender === option.value &&
|
||||
styles.optionCardActive,
|
||||
styles.genderCard,
|
||||
{
|
||||
backgroundColor:
|
||||
profileData.gender === option.value
|
||||
? colors.primary
|
||||
: colors.surfaceElevated,
|
||||
borderColor:
|
||||
profileData.gender === option.value
|
||||
? colors.primary
|
||||
: colors.border,
|
||||
},
|
||||
]}
|
||||
onPress={() => updateField("gender", option.value)}
|
||||
>
|
||||
@@ -326,15 +403,22 @@ export default function FitnessProfileScreen() {
|
||||
size={24}
|
||||
color={
|
||||
profileData.gender === option.value
|
||||
? theme.colors.primary
|
||||
: theme.colors.gray400
|
||||
? "#fff"
|
||||
: colors.textTertiary
|
||||
}
|
||||
/>
|
||||
<Text
|
||||
style={[
|
||||
styles.optionLabel,
|
||||
profileData.gender === option.value &&
|
||||
styles.optionLabelActive,
|
||||
typography.caption,
|
||||
{
|
||||
color:
|
||||
profileData.gender === option.value
|
||||
? "#fff"
|
||||
: colors.textSecondary,
|
||||
fontWeight:
|
||||
profileData.gender === option.value ? "700" : "500",
|
||||
marginTop: 6,
|
||||
},
|
||||
]}
|
||||
>
|
||||
{option.label}
|
||||
@@ -346,8 +430,15 @@ export default function FitnessProfileScreen() {
|
||||
|
||||
{/* Fitness Goal */}
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Primary Fitness Goal</Text>
|
||||
<View style={styles.card}>
|
||||
<Text
|
||||
style={[
|
||||
typography.h3,
|
||||
{ color: colors.textPrimary, marginBottom: 16 },
|
||||
]}
|
||||
>
|
||||
Primary Fitness Goal
|
||||
</Text>
|
||||
<MinimalCard variant="elevated" style={styles.card}>
|
||||
{FITNESS_GOAL_OPTIONS.map((option, index) => (
|
||||
<React.Fragment key={option.value}>
|
||||
<TouchableOpacity
|
||||
@@ -366,27 +457,46 @@ export default function FitnessProfileScreen() {
|
||||
color={option.color}
|
||||
/>
|
||||
</View>
|
||||
<Text style={styles.listItemText}>{option.label}</Text>
|
||||
<Text
|
||||
style={[
|
||||
typography.bodyEmphasis,
|
||||
{ color: colors.textPrimary, flex: 1 },
|
||||
]}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
{profileData.fitnessGoal === option.value && (
|
||||
<Ionicons
|
||||
name="checkmark-circle"
|
||||
size={24}
|
||||
color={theme.colors.primary}
|
||||
color={colors.primary}
|
||||
/>
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
{index < FITNESS_GOAL_OPTIONS.length - 1 && (
|
||||
<View style={styles.divider} />
|
||||
<View
|
||||
style={[
|
||||
styles.divider,
|
||||
{ backgroundColor: colors.border },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</View>
|
||||
</MinimalCard>
|
||||
</View>
|
||||
|
||||
{/* Activity Level */}
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Activity Level</Text>
|
||||
<View style={styles.card}>
|
||||
<Text
|
||||
style={[
|
||||
typography.h3,
|
||||
{ color: colors.textPrimary, marginBottom: 16 },
|
||||
]}
|
||||
>
|
||||
Activity Level
|
||||
</Text>
|
||||
<MinimalCard variant="elevated" style={styles.card}>
|
||||
{ACTIVITY_LEVEL_OPTIONS.map((option, index) => (
|
||||
<React.Fragment key={option.value}>
|
||||
<TouchableOpacity
|
||||
@@ -394,8 +504,20 @@ export default function FitnessProfileScreen() {
|
||||
onPress={() => updateField("activityLevel", option.value)}
|
||||
>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={styles.listItemText}>{option.label}</Text>
|
||||
<Text style={styles.listItemDescription}>
|
||||
<Text
|
||||
style={[
|
||||
typography.bodyEmphasis,
|
||||
{ color: colors.textPrimary },
|
||||
]}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
<Text
|
||||
style={[
|
||||
typography.caption,
|
||||
{ color: colors.textTertiary, marginTop: 2 },
|
||||
]}
|
||||
>
|
||||
{option.description}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -403,90 +525,141 @@ export default function FitnessProfileScreen() {
|
||||
<Ionicons
|
||||
name="checkmark-circle"
|
||||
size={24}
|
||||
color={theme.colors.primary}
|
||||
color={colors.primary}
|
||||
/>
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
{index < ACTIVITY_LEVEL_OPTIONS.length - 1 && (
|
||||
<View style={styles.divider} />
|
||||
<View
|
||||
style={[
|
||||
styles.divider,
|
||||
{ backgroundColor: colors.border },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</View>
|
||||
</MinimalCard>
|
||||
</View>
|
||||
|
||||
{/* Health Information */}
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>
|
||||
Health Information (Optional)
|
||||
<Text
|
||||
style={[
|
||||
typography.h3,
|
||||
{ color: colors.textPrimary, marginBottom: 16 },
|
||||
]}
|
||||
>
|
||||
Health Information
|
||||
</Text>
|
||||
<View style={styles.card}>
|
||||
<MinimalCard variant="elevated" style={styles.card}>
|
||||
<View style={styles.inputGroup}>
|
||||
<Text style={styles.label}>Medical Conditions</Text>
|
||||
<Text
|
||||
style={[
|
||||
typography.label,
|
||||
{ color: colors.textSecondary, marginBottom: 8 },
|
||||
]}
|
||||
>
|
||||
MEDICAL CONDITIONS
|
||||
</Text>
|
||||
<TextInput
|
||||
style={[styles.textArea]}
|
||||
style={[
|
||||
styles.textArea,
|
||||
{
|
||||
backgroundColor: colors.surfaceElevated,
|
||||
borderColor: colors.border,
|
||||
color: colors.textPrimary,
|
||||
},
|
||||
]}
|
||||
value={profileData.medicalConditions || ""}
|
||||
onChangeText={(text) =>
|
||||
updateField("medicalConditions", text)
|
||||
}
|
||||
placeholder="e.g., Asthma, diabetes..."
|
||||
placeholderTextColor={theme.colors.gray400}
|
||||
placeholderTextColor={colors.textTertiary}
|
||||
multiline
|
||||
numberOfLines={3}
|
||||
textAlignVertical="top"
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.inputGroup}>
|
||||
<Text style={styles.label}>Allergies</Text>
|
||||
<Text
|
||||
style={[
|
||||
typography.label,
|
||||
{ color: colors.textSecondary, marginBottom: 8 },
|
||||
]}
|
||||
>
|
||||
ALLERGIES
|
||||
</Text>
|
||||
<TextInput
|
||||
style={[styles.textArea]}
|
||||
style={[
|
||||
styles.textArea,
|
||||
{
|
||||
backgroundColor: colors.surfaceElevated,
|
||||
borderColor: colors.border,
|
||||
color: colors.textPrimary,
|
||||
},
|
||||
]}
|
||||
value={profileData.allergies || ""}
|
||||
onChangeText={(text) => updateField("allergies", text)}
|
||||
placeholder="e.g., Peanuts, latex..."
|
||||
placeholderTextColor={theme.colors.gray400}
|
||||
placeholderTextColor={colors.textTertiary}
|
||||
multiline
|
||||
numberOfLines={3}
|
||||
textAlignVertical="top"
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.inputGroup}>
|
||||
<Text style={styles.label}>Injuries</Text>
|
||||
<Text
|
||||
style={[
|
||||
typography.label,
|
||||
{ color: colors.textSecondary, marginBottom: 8 },
|
||||
]}
|
||||
>
|
||||
INJURIES
|
||||
</Text>
|
||||
<TextInput
|
||||
style={[styles.textArea]}
|
||||
style={[
|
||||
styles.textArea,
|
||||
{
|
||||
backgroundColor: colors.surfaceElevated,
|
||||
borderColor: colors.border,
|
||||
color: colors.textPrimary,
|
||||
},
|
||||
]}
|
||||
value={profileData.injuries || ""}
|
||||
onChangeText={(text) => updateField("injuries", text)}
|
||||
placeholder="e.g., Previous knee injury..."
|
||||
placeholderTextColor={theme.colors.gray400}
|
||||
placeholderTextColor={colors.textTertiary}
|
||||
multiline
|
||||
numberOfLines={3}
|
||||
textAlignVertical="top"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</MinimalCard>
|
||||
</View>
|
||||
|
||||
<View style={{ height: 120 }} />
|
||||
</ScrollView>
|
||||
|
||||
{/* Save Button */}
|
||||
<View style={styles.footer}>
|
||||
<TouchableOpacity
|
||||
style={[styles.saveButton, loading && styles.saveButtonDisabled]}
|
||||
<View
|
||||
style={[
|
||||
styles.footer,
|
||||
{
|
||||
backgroundColor: colors.background,
|
||||
borderTopColor: colors.border,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<MinimalButton
|
||||
title="Save Profile"
|
||||
onPress={handleSave}
|
||||
disabled={loading}
|
||||
>
|
||||
<LinearGradient
|
||||
colors={theme.gradients.primary}
|
||||
style={styles.saveButtonGradient}
|
||||
>
|
||||
{loading ? (
|
||||
<ActivityIndicator color="#fff" />
|
||||
) : (
|
||||
<>
|
||||
<Ionicons name="checkmark-circle" size={20} color="#fff" />
|
||||
<Text style={styles.saveButtonText}>Save Profile</Text>
|
||||
</>
|
||||
)}
|
||||
</LinearGradient>
|
||||
</TouchableOpacity>
|
||||
variant="primary"
|
||||
size="xl"
|
||||
fullWidth
|
||||
loading={loading}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</>
|
||||
@@ -496,35 +669,27 @@ export default function FitnessProfileScreen() {
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: theme.colors.background,
|
||||
},
|
||||
loadingContainer: {
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
backgroundColor: theme.colors.background,
|
||||
},
|
||||
header: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
paddingTop: Platform.OS === "ios" ? 60 : 40,
|
||||
paddingBottom: 20,
|
||||
paddingHorizontal: 20,
|
||||
},
|
||||
backButton: {
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 20,
|
||||
borderRadius: 12,
|
||||
backgroundColor: "rgba(255, 255, 255, 0.2)",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
headerTitle: {
|
||||
fontSize: theme.typography.fontSize["2xl"],
|
||||
fontWeight: theme.typography.fontWeight.bold,
|
||||
color: "#fff",
|
||||
},
|
||||
scrollView: {
|
||||
flex: 1,
|
||||
},
|
||||
@@ -533,118 +698,69 @@ const styles = StyleSheet.create({
|
||||
paddingBottom: 100,
|
||||
},
|
||||
section: {
|
||||
marginBottom: 24,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: theme.typography.fontSize.lg,
|
||||
fontWeight: theme.typography.fontWeight.bold,
|
||||
color: theme.colors.gray900,
|
||||
marginBottom: 12,
|
||||
marginBottom: 28,
|
||||
},
|
||||
card: {
|
||||
backgroundColor: "#fff",
|
||||
borderRadius: theme.borderRadius.xl,
|
||||
padding: 16,
|
||||
...theme.shadows.subtle,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.gray100,
|
||||
padding: 4,
|
||||
},
|
||||
row: {
|
||||
inputRow: {
|
||||
flexDirection: "row",
|
||||
gap: 12,
|
||||
marginBottom: 16,
|
||||
},
|
||||
inputGroup: {
|
||||
flex: 1,
|
||||
marginBottom: 16,
|
||||
},
|
||||
label: {
|
||||
fontSize: theme.typography.fontSize.sm,
|
||||
fontWeight: theme.typography.fontWeight.semibold,
|
||||
color: theme.colors.gray700,
|
||||
marginBottom: 8,
|
||||
marginBottom: 4,
|
||||
},
|
||||
inputContainer: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
backgroundColor: theme.colors.gray50,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.gray200,
|
||||
paddingHorizontal: 12,
|
||||
gap: 8,
|
||||
borderRadius: 14,
|
||||
borderWidth: 1.5,
|
||||
paddingHorizontal: 14,
|
||||
gap: 10,
|
||||
},
|
||||
input: {
|
||||
flex: 1,
|
||||
paddingVertical: 12,
|
||||
fontSize: theme.typography.fontSize.base,
|
||||
color: theme.colors.gray900,
|
||||
paddingVertical: 14,
|
||||
fontSize: 16,
|
||||
fontWeight: "600",
|
||||
},
|
||||
textArea: {
|
||||
backgroundColor: theme.colors.gray50,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.gray200,
|
||||
padding: 12,
|
||||
fontSize: theme.typography.fontSize.base,
|
||||
color: theme.colors.gray900,
|
||||
minHeight: 80,
|
||||
borderRadius: 14,
|
||||
borderWidth: 1.5,
|
||||
padding: 14,
|
||||
fontSize: 16,
|
||||
minHeight: 90,
|
||||
},
|
||||
optionsRow: {
|
||||
genderRow: {
|
||||
flexDirection: "row",
|
||||
gap: 12,
|
||||
gap: 10,
|
||||
},
|
||||
optionCard: {
|
||||
genderCard: {
|
||||
flex: 1,
|
||||
backgroundColor: "#fff",
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
padding: 16,
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
paddingVertical: 16,
|
||||
paddingHorizontal: 8,
|
||||
borderRadius: 14,
|
||||
borderWidth: 2,
|
||||
borderColor: theme.colors.gray200,
|
||||
...theme.shadows.subtle,
|
||||
},
|
||||
optionCardActive: {
|
||||
borderColor: theme.colors.primary,
|
||||
backgroundColor: `${theme.colors.primary}10`,
|
||||
},
|
||||
optionLabel: {
|
||||
fontSize: theme.typography.fontSize.sm,
|
||||
fontWeight: theme.typography.fontWeight.medium,
|
||||
color: theme.colors.gray600,
|
||||
},
|
||||
optionLabelActive: {
|
||||
color: theme.colors.primary,
|
||||
fontWeight: theme.typography.fontWeight.bold,
|
||||
alignItems: "center",
|
||||
},
|
||||
listItem: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingVertical: 12,
|
||||
gap: 12,
|
||||
paddingVertical: 14,
|
||||
paddingHorizontal: 12,
|
||||
gap: 14,
|
||||
},
|
||||
iconCircle: {
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 20,
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 12,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
listItemText: {
|
||||
flex: 1,
|
||||
fontSize: theme.typography.fontSize.base,
|
||||
fontWeight: theme.typography.fontWeight.medium,
|
||||
color: theme.colors.gray900,
|
||||
},
|
||||
listItemDescription: {
|
||||
fontSize: theme.typography.fontSize.xs,
|
||||
color: theme.colors.gray500,
|
||||
marginTop: 2,
|
||||
},
|
||||
divider: {
|
||||
height: 1,
|
||||
backgroundColor: theme.colors.gray100,
|
||||
marginLeft: 58,
|
||||
},
|
||||
footer: {
|
||||
position: "absolute",
|
||||
@@ -652,29 +768,7 @@ const styles = StyleSheet.create({
|
||||
left: 0,
|
||||
right: 0,
|
||||
padding: 20,
|
||||
paddingBottom: Platform.OS === "ios" ? 40 : 20,
|
||||
backgroundColor: "#fff",
|
||||
paddingBottom: 34,
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: theme.colors.gray100,
|
||||
...theme.shadows.medium,
|
||||
},
|
||||
saveButton: {
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
overflow: "hidden",
|
||||
},
|
||||
saveButtonGradient: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingVertical: 16,
|
||||
gap: 8,
|
||||
},
|
||||
saveButtonDisabled: {
|
||||
opacity: 0.6,
|
||||
},
|
||||
saveButtonText: {
|
||||
fontSize: theme.typography.fontSize.base,
|
||||
fontWeight: theme.typography.fontWeight.bold,
|
||||
color: "#fff",
|
||||
},
|
||||
});
|
||||
Whitespace-only changes.
Reference in new issue
Block a user