Compare commits
5
Commits
02c9681aca
...
appFlow
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
624cdfc45c | ||
|
|
16217f46ff | ||
|
|
cc2dbc3423 | ||
|
|
b1d6489c70 | ||
|
|
0abb41f573 |
No files matched your search
Binary file not shown.
@@ -4,6 +4,7 @@ import { getDatabase } from "@/lib/database";
|
|||||||
import { ensureUserSynced } from "@/lib/sync-user";
|
import { ensureUserSynced } from "@/lib/sync-user";
|
||||||
import { successResponse } from "@/lib/api/responses";
|
import { successResponse } from "@/lib/api/responses";
|
||||||
import { db as rawDb, sql } from "@fitai/database";
|
import { db as rawDb, sql } from "@fitai/database";
|
||||||
|
import { getUsersByGym, getClientsByGym } from "@/lib/gym-context";
|
||||||
|
|
||||||
interface UserGrowthPoint {
|
interface UserGrowthPoint {
|
||||||
label: string;
|
label: string;
|
||||||
@@ -45,12 +46,36 @@ export async function GET(req: NextRequest) {
|
|||||||
const url = new URL(req.url);
|
const url = new URL(req.url);
|
||||||
const months = parseInt(url.searchParams.get("months") || "6");
|
const months = parseInt(url.searchParams.get("months") || "6");
|
||||||
|
|
||||||
const allUsers = await database.getAllUsers();
|
// Get target gym based on role
|
||||||
const allClients = await database.getAllClients();
|
const targetGymId =
|
||||||
|
user.role === "superAdmin"
|
||||||
|
? (url.searchParams.get("gymId") ?? undefined)
|
||||||
|
: (user.gymId ?? undefined);
|
||||||
|
|
||||||
const paymentsRaw = await rawDb.all(
|
// Validate gym access for non-superAdmins
|
||||||
sql`SELECT * FROM payments WHERE status = 'completed' AND paid_at IS NOT NULL`,
|
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 payments: any[] = paymentsRaw || [];
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
|
|||||||
@@ -1,27 +1,42 @@
|
|||||||
import { auth } from '@clerk/nextjs/server'
|
import { auth } from "@clerk/nextjs/server";
|
||||||
import { NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getDatabase } from '@/lib/database'
|
import { getDatabase } from "@/lib/database";
|
||||||
import { ensureUserSynced } from '@/lib/sync-user'
|
import { ensureUserSynced } from "@/lib/sync-user";
|
||||||
|
import { successResponse } from "@/lib/api/responses";
|
||||||
|
import { getAttendanceByGym } from "@/lib/gym-context";
|
||||||
|
|
||||||
export async function GET(req: Request) {
|
export async function GET(req: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const { userId } = await auth()
|
const { userId } = await auth();
|
||||||
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
|
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)
|
if (!user || (user.role !== "admin" && user.role !== "superAdmin")) {
|
||||||
// We need to import ensureUserSynced
|
return new NextResponse("Forbidden", { status: 403 });
|
||||||
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 })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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 });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getDatabase } from "../../../../lib/database/index";
|
import { getDatabase } from "../../../../lib/database/index";
|
||||||
|
import { auth } from "@clerk/nextjs/server";
|
||||||
import log from "@/lib/logger";
|
import log from "@/lib/logger";
|
||||||
import { fitnessProfileSchema } from "@/lib/validation/schemas";
|
import { fitnessProfileSchema } from "@/lib/validation/schemas";
|
||||||
import {
|
import {
|
||||||
validateRequestBody,
|
validateRequestBody,
|
||||||
validationErrorResponse,
|
validationErrorResponse,
|
||||||
} from "@/lib/validation/helpers";
|
} from "@/lib/validation/helpers";
|
||||||
|
import { getFitnessProfilesByGym } from "@/lib/gym-context";
|
||||||
|
import { ensureUserSynced } from "@/lib/sync-user";
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
@@ -63,12 +66,47 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const db = await getDatabase();
|
// First authenticate
|
||||||
const { searchParams } = new URL(request.url);
|
const { userId: clerkUserId } = await auth();
|
||||||
const userId = searchParams.get("userId");
|
if (!clerkUserId) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
if (userId) {
|
const db = await getDatabase();
|
||||||
const profile = await db.getFitnessProfileByUserId(userId);
|
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) {
|
if (!profile) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Profile not found" },
|
{ error: "Profile not found" },
|
||||||
@@ -78,8 +116,28 @@ export async function GET(request: NextRequest) {
|
|||||||
return NextResponse.json({ profile });
|
return NextResponse.json({ profile });
|
||||||
}
|
}
|
||||||
|
|
||||||
const profiles = await db.getAllFitnessProfiles();
|
// Staff get gym-scoped profiles
|
||||||
return NextResponse.json({ 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) {
|
} catch (error) {
|
||||||
log.error("Failed to get fitness profiles", error);
|
log.error("Failed to get fitness profiles", error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ import {
|
|||||||
badRequestResponse,
|
badRequestResponse,
|
||||||
internalErrorResponse,
|
internalErrorResponse,
|
||||||
} from "@/lib/api/responses";
|
} from "@/lib/api/responses";
|
||||||
|
import { getRecommendationsByGym } from "@/lib/gym-context";
|
||||||
|
import { ensureUserSynced } from "@/lib/sync-user";
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
@@ -25,38 +27,59 @@ export async function GET(request: NextRequest) {
|
|||||||
return unauthorizedResponse();
|
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 { searchParams } = new URL(request.url);
|
||||||
const targetUserId = searchParams.get("userId");
|
const targetUserId = searchParams.get("userId");
|
||||||
|
|
||||||
const db = await getDatabase();
|
// If no userId provided, staff gets gym-scoped recommendations
|
||||||
|
|
||||||
// If no userId provided, check if staff and return all recommendations
|
|
||||||
if (!targetUserId) {
|
if (!targetUserId) {
|
||||||
const currentUser = await db.getUserById(currentUserId);
|
|
||||||
const isStaff =
|
const isStaff =
|
||||||
currentUser?.role === "admin" ||
|
currentUser.role === "admin" ||
|
||||||
currentUser?.role === "superAdmin" ||
|
currentUser.role === "superAdmin" ||
|
||||||
currentUser?.role === "trainer";
|
currentUser.role === "trainer";
|
||||||
|
|
||||||
if (!isStaff) {
|
if (!isStaff) {
|
||||||
return badRequestResponse("User ID is required");
|
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 });
|
return successResponse({ recommendations });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check permissions: Users can view their own, Admins/Trainers can view anyone's
|
// Check permissions: Users can view their own, Admins/Trainers can view anyone's in their gym
|
||||||
const currentUser = await db.getUserById(currentUserId);
|
|
||||||
const isStaff =
|
const isStaff =
|
||||||
currentUser?.role === "admin" ||
|
currentUser.role === "admin" ||
|
||||||
currentUser?.role === "superAdmin" ||
|
currentUser.role === "superAdmin" ||
|
||||||
currentUser?.role === "trainer";
|
currentUser.role === "trainer";
|
||||||
|
|
||||||
if (currentUserId !== targetUserId) {
|
if (currentUserId !== targetUserId) {
|
||||||
if (!isStaff) {
|
if (!isStaff) {
|
||||||
return forbiddenResponse();
|
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);
|
let recommendations = await db.getRecommendationsByUserId(targetUserId);
|
||||||
|
|||||||
@@ -24,14 +24,42 @@ import {
|
|||||||
internalErrorResponse,
|
internalErrorResponse,
|
||||||
badRequestResponse,
|
badRequestResponse,
|
||||||
} from "@/lib/api/responses";
|
} from "@/lib/api/responses";
|
||||||
|
import { getUsersByGym } from "@/lib/gym-context";
|
||||||
|
import { ensureUserSynced } from "@/lib/sync-user";
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
// First authenticate the user
|
||||||
|
const { userId: clerkUserId } = await auth();
|
||||||
|
if (!clerkUserId) {
|
||||||
|
return unauthorizedResponse();
|
||||||
|
}
|
||||||
|
|
||||||
const db = await getDatabase();
|
const db = await getDatabase();
|
||||||
|
const currentUser = await ensureUserSynced(clerkUserId, db);
|
||||||
|
|
||||||
|
if (!currentUser) {
|
||||||
|
return forbiddenResponse("User not found");
|
||||||
|
}
|
||||||
|
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const role = searchParams.get("role");
|
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
|
// Hydrate gymId from raw DB to ensure consistency with writes
|
||||||
const rawUserRows = await rawDb.all(sql`SELECT id, gym_id FROM users`);
|
const rawUserRows = await rawDb.all(sql`SELECT id, gym_id FROM users`);
|
||||||
|
|||||||
@@ -1,96 +1,102 @@
|
|||||||
'use client'
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from 'react'
|
import { useAttendance } from "@/hooks/use-api";
|
||||||
import { format } from 'date-fns'
|
import { PageHeader } from "@/components/ui/PageHeader";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
interface Attendance {
|
|
||||||
id: string
|
|
||||||
clientId: string
|
|
||||||
checkInTime: string
|
|
||||||
checkOutTime?: string
|
|
||||||
type: string
|
|
||||||
notes?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function AttendancePage() {
|
export default function AttendancePage() {
|
||||||
const [attendance, setAttendance] = useState<Attendance[]>([])
|
const { data: attendance = [], isLoading } = useAttendance();
|
||||||
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>
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="p-8">
|
<div className="space-y-8">
|
||||||
<h1 className="text-2xl font-bold mb-6">Attendance Monitoring</h1>
|
<PageHeader
|
||||||
|
title="Attendance"
|
||||||
<div className="bg-white rounded-lg shadow overflow-hidden">
|
description="Monitor gym check-ins and check-outs"
|
||||||
<table className="min-w-full divide-y divide-gray-200">
|
breadcrumbs={[{ label: "Attendance" }]}
|
||||||
<thead className="bg-gray-50">
|
/>
|
||||||
<tr>
|
<div className="card-modern">
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
<div className="animate-pulse space-y-4">
|
||||||
Client ID
|
{[...Array(5)].map((_, i) => (
|
||||||
</th>
|
<div key={i} className="h-12 bg-muted rounded" />
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
))}
|
||||||
Type
|
</div>
|
||||||
</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>
|
</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>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
:root {
|
:root {
|
||||||
--background: 0 0% 100%;
|
--background: 0 0% 98%;
|
||||||
--foreground: 222.2 84% 4.9%;
|
--foreground: 222.2 84% 4.9%;
|
||||||
|
|
||||||
--card: 0 0% 100%;
|
--card: 0 0% 100%;
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
--popover: 0 0% 100%;
|
--popover: 0 0% 100%;
|
||||||
--popover-foreground: 222.2 84% 4.9%;
|
--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%;
|
--primary-foreground: 210 40% 98%;
|
||||||
|
|
||||||
--secondary: 210 40% 96.1%;
|
--secondary: 210 40% 96.1%;
|
||||||
@@ -28,24 +28,42 @@
|
|||||||
--destructive: 0 84.2% 60.2%;
|
--destructive: 0 84.2% 60.2%;
|
||||||
--destructive-foreground: 210 40% 98%;
|
--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%;
|
--border: 214.3 31.8% 91.4%;
|
||||||
--input: 214.3 31.8% 91.4%;
|
--input: 214.3 31.8% 91.4%;
|
||||||
--ring: 222.2 84% 4.9%;
|
--ring: 221.2 83.2% 53.3%;
|
||||||
|
|
||||||
--radius: 0.5rem;
|
--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 {
|
.dark {
|
||||||
--background: 222.2 84% 4.9%;
|
--background: 222.2 84% 4.9%;
|
||||||
--foreground: 210 40% 98%;
|
--foreground: 210 40% 98%;
|
||||||
|
|
||||||
--card: 222.2 84% 4.9%;
|
--card: 222.2 47.4% 10.2%;
|
||||||
--card-foreground: 210 40% 98%;
|
--card-foreground: 210 40% 98%;
|
||||||
|
|
||||||
--popover: 222.2 84% 4.9%;
|
--popover: 222.2 47.4% 10.2%;
|
||||||
--popover-foreground: 210 40% 98%;
|
--popover-foreground: 210 40% 98%;
|
||||||
|
|
||||||
--primary: 210 40% 98%;
|
--primary: 217.2 91.2% 59.8%;
|
||||||
--primary-foreground: 222.2 47.4% 11.2%;
|
--primary-foreground: 222.2 47.4% 11.2%;
|
||||||
|
|
||||||
--secondary: 217.2 32.6% 17.5%;
|
--secondary: 217.2 32.6% 17.5%;
|
||||||
@@ -60,9 +78,27 @@
|
|||||||
--destructive: 0 62.8% 30.6%;
|
--destructive: 0 62.8% 30.6%;
|
||||||
--destructive-foreground: 210 40% 98%;
|
--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%;
|
--border: 217.2 32.6% 17.5%;
|
||||||
--input: 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%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,6 +107,142 @@
|
|||||||
@apply border-border;
|
@apply border-border;
|
||||||
}
|
}
|
||||||
body {
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,9 +29,11 @@ export default function RootLayout({
|
|||||||
<QueryProvider>
|
<QueryProvider>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<body className={inter.className}>
|
<body className={inter.className}>
|
||||||
<div className="flex min-h-screen bg-slate-50">
|
<div className="flex min-h-screen bg-background">
|
||||||
<Sidebar />
|
<Sidebar />
|
||||||
<main className="flex-1 ml-20 p-8">{children}</main>
|
<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>
|
</div>
|
||||||
<Toaster richColors position="top-right" />
|
<Toaster richColors position="top-right" />
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+84
-23
@@ -1,32 +1,80 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Users, CreditCard, CalendarCheck, TrendingUp } from "lucide-react";
|
import {
|
||||||
import { StatsCard } from "@/components/ui/StatsCard";
|
Users,
|
||||||
import { StatsCardSkeleton } from "@/components/ui/skeleton";
|
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 { UserManagement } from "@/components/users/UserManagement";
|
||||||
import { AnalyticsDashboard } from "@/components/analytics/AnalyticsDashboard";
|
import { AnalyticsDashboard } from "@/components/analytics/AnalyticsDashboard";
|
||||||
import { useDashboardStats } from "@/hooks/use-api";
|
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() {
|
export default function Home() {
|
||||||
const { data: stats, isLoading } = useDashboardStats();
|
const { user } = useUser();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const gymId = searchParams.get("gymId") ?? undefined;
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: stats,
|
||||||
|
isLoading,
|
||||||
|
refetch,
|
||||||
|
isFetching,
|
||||||
|
} = useDashboardStats(gymId);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
// 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) => {
|
const formatCurrency = (value: number) => {
|
||||||
return new Intl.NumberFormat("en-US", {
|
return new Intl.NumberFormat("en-US", {
|
||||||
style: "currency",
|
style: "currency",
|
||||||
currency: "USD",
|
currency: "USD",
|
||||||
|
minimumFractionDigits: 0,
|
||||||
|
maximumFractionDigits: 0,
|
||||||
}).format(value || 0);
|
}).format(value || 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
<div>
|
<PageHeader
|
||||||
<h2 className="text-3xl font-bold text-slate-900">Dashboard</h2>
|
title="Dashboard"
|
||||||
<p className="text-slate-500 mt-2">
|
description="Welcome back! Here's what's happening with your gym today."
|
||||||
Welcome back, here's what's happening today.
|
actions={
|
||||||
</p>
|
<div className="flex items-center gap-3">
|
||||||
</div>
|
<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>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
{/* Stats Grid */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<>
|
<>
|
||||||
<StatsCardSkeleton />
|
<StatsCardSkeleton />
|
||||||
@@ -72,18 +120,31 @@ export default function Home() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col gap-8">
|
{/* Main Content Grid */}
|
||||||
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
|
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
|
||||||
<h3 className="text-xl font-bold text-slate-900 mb-6">
|
{/* <div className="xl:col-span-2"> */}
|
||||||
Recent Activity
|
{/* <div className="card-modern"> */}
|
||||||
</h3>
|
{/* <div className="mb-6"> */}
|
||||||
<UserManagement />
|
{/* <h3 className="text-lg font-semibold">Recent Activity</h3> */}
|
||||||
</div>
|
{/* <p className="text-sm text-muted-foreground"> */}
|
||||||
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
|
{/* Manage and view your users */}
|
||||||
<h3 className="text-xl font-bold text-slate-900 mb-6">
|
{/* </p> */}
|
||||||
Quick Analytics
|
{/* </div> */}
|
||||||
</h3>
|
{/* <UserManagement /> */}
|
||||||
<AnalyticsDashboard />
|
{/* </div> */}
|
||||||
|
{/* </div> */}
|
||||||
|
|
||||||
|
{/* 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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ export default function ProfilePage() {
|
|||||||
<div className="flex justify-between items-center mb-6">
|
<div className="flex justify-between items-center mb-6">
|
||||||
<h1 className="text-2xl font-bold">Profile</h1>
|
<h1 className="text-2xl font-bold">Profile</h1>
|
||||||
<Button
|
<Button
|
||||||
variant={isEditing ? "primary" : "secondary"}
|
variant={isEditing ? "default" : "secondary"}
|
||||||
onClick={() => setIsEditing(!isEditing)}
|
onClick={() => setIsEditing(!isEditing)}
|
||||||
>
|
>
|
||||||
{isEditing ? "Cancel" : "Edit Profile"}
|
{isEditing ? "Cancel" : "Edit Profile"}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
useUpdateRecommendation,
|
useUpdateRecommendation,
|
||||||
type Recommendation,
|
type Recommendation,
|
||||||
} from "@/hooks/use-api";
|
} from "@/hooks/use-api";
|
||||||
|
import { PageHeader } from "@/components/ui/PageHeader";
|
||||||
|
|
||||||
export default function RecommendationsPage() {
|
export default function RecommendationsPage() {
|
||||||
const { user } = useUser();
|
const { user } = useUser();
|
||||||
@@ -83,135 +84,118 @@ export default function RecommendationsPage() {
|
|||||||
|
|
||||||
if (usersLoading || recsLoading) {
|
if (usersLoading || recsLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center h-screen">
|
<div className="flex items-center justify-center h-64">
|
||||||
<div className="text-xl">Loading...</div>
|
<div className="text-lg">Loading...</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="container mx-auto py-10 px-4">
|
<div className="space-y-8">
|
||||||
<div className="flex justify-between items-center mb-8">
|
<PageHeader
|
||||||
<h1 className="text-3xl font-bold">AI Recommendations</h1>
|
title="AI Recommendations"
|
||||||
|
description="Generate and manage AI-powered fitness recommendations"
|
||||||
|
breadcrumbs={[{ label: "AI Recommendations" }]}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Model Selection Toggle */}
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
<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">
|
|
||||||
{/* Generate Section */}
|
{/* Generate Section */}
|
||||||
<div>
|
<div className="card-modern">
|
||||||
<h2 className="text-2xl font-semibold mb-4">
|
<div className="mb-6">
|
||||||
Generate Recommendations
|
<h3 className="text-lg font-semibold">Generate Recommendations</h3>
|
||||||
</h2>
|
<p className="text-sm text-muted-foreground">
|
||||||
<div className="bg-white shadow rounded-lg p-6">
|
|
||||||
<p className="mb-4 text-gray-600">
|
|
||||||
Select a user to generate a new daily recommendation.
|
Select a user to generate a new daily recommendation.
|
||||||
</p>
|
</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={generateRec.isPending}
|
|
||||||
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{generateRec.isPending ? "Generating..." : "Generate"}
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
{users.length === 0 && (
|
|
||||||
<p className="text-gray-500 italic">No users found.</p>
|
|
||||||
)}
|
|
||||||
</ul>
|
|
||||||
</div>
|
</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>
|
</div>
|
||||||
|
|
||||||
{/* Pending Approvals Section */}
|
{/* Pending Approvals Section */}
|
||||||
<div>
|
<div className="card-modern">
|
||||||
<h2 className="text-2xl font-semibold mb-4">Pending Approvals</h2>
|
<div className="mb-6">
|
||||||
<div className="bg-white shadow rounded-lg p-6">
|
<h3 className="text-lg font-semibold">Pending Approvals</h3>
|
||||||
{pendingRecommendations.length === 0 ? (
|
<p className="text-sm text-muted-foreground">
|
||||||
<p className="text-gray-500 italic">
|
Review and approve AI-generated recommendations
|
||||||
No pending recommendations.
|
</p>
|
||||||
</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>
|
</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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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() {
|
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 (
|
return (
|
||||||
<main className="min-h-screen bg-gray-50">
|
<div className="space-y-8">
|
||||||
<div className="container mx-auto px-4 py-8">
|
<PageHeader
|
||||||
<UserManagement />
|
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>
|
</div>
|
||||||
</main>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
@@ -71,11 +71,11 @@ export function Navigation(): ReactElement {
|
|||||||
<li key={item.href}>
|
<li key={item.href}>
|
||||||
<Link href={item.href} className="flex items-center gap-2">
|
<Link href={item.href} className="flex items-center gap-2">
|
||||||
<Button
|
<Button
|
||||||
variant={pathname === item.href ? "primary" : "secondary"}
|
variant={pathname === item.href ? "default" : "secondary"}
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-9 px-4 py-2",
|
"h-9 px-4 py-2",
|
||||||
pathname === item.href &&
|
pathname === item.href &&
|
||||||
"bg-primary text-primary-foreground",
|
"bg-primary text-primary-foreground",
|
||||||
)}
|
)}
|
||||||
aria-current={pathname === item.href ? "page" : undefined}
|
aria-current={pathname === item.href ? "page" : undefined}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -6,8 +6,12 @@ import { RevenueChart } from "@/components/charts/RevenueChart";
|
|||||||
import { Card, CardHeader, CardContent } from "@/components/ui/card";
|
import { Card, CardHeader, CardContent } from "@/components/ui/card";
|
||||||
import { useAnalytics } from "@/hooks/use-api";
|
import { useAnalytics } from "@/hooks/use-api";
|
||||||
|
|
||||||
export function AnalyticsDashboard() {
|
interface AnalyticsDashboardProps {
|
||||||
const { data: analytics, isLoading } = useAnalytics(6);
|
gymId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AnalyticsDashboard({ gymId }: AnalyticsDashboardProps) {
|
||||||
|
const { data: analytics, isLoading } = useAnalytics(6, gymId);
|
||||||
|
|
||||||
const userGrowthData = analytics?.userGrowth ?? [];
|
const userGrowthData = analytics?.userGrowth ?? [];
|
||||||
const membershipData = analytics?.membershipDistribution ?? [];
|
const membershipData = analytics?.membershipDistribution ?? [];
|
||||||
|
|||||||
@@ -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,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,38 +9,48 @@ import {
|
|||||||
CalendarCheck,
|
CalendarCheck,
|
||||||
CreditCard,
|
CreditCard,
|
||||||
Settings,
|
Settings,
|
||||||
LogOut,
|
|
||||||
Brain,
|
Brain,
|
||||||
|
ChevronLeft,
|
||||||
|
Activity,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { UserButton, useUser } from "@clerk/nextjs";
|
import { UserButton, useUser } from "@clerk/nextjs";
|
||||||
import { usePendingRecommendationsCount } from "@/hooks/use-api";
|
import { usePendingRecommendationsCount } from "@/hooks/use-api";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface NavItem {
|
||||||
|
icon: React.ElementType;
|
||||||
|
label: string;
|
||||||
|
href: string;
|
||||||
|
badge?: number;
|
||||||
|
}
|
||||||
|
|
||||||
export function Sidebar() {
|
export function Sidebar() {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const { user } = useUser();
|
const { user } = useUser();
|
||||||
const { data: pendingCount = 0 } = usePendingRecommendationsCount();
|
const { data: pendingCount = 0 } = usePendingRecommendationsCount();
|
||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
|
const [isCollapsed, setIsCollapsed] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setMounted(true);
|
setMounted(true);
|
||||||
|
const saved = localStorage.getItem("sidebar-collapsed");
|
||||||
|
if (saved) setIsCollapsed(JSON.parse(saved));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const menuItems = [
|
const handleToggle = () => {
|
||||||
|
const newState = !isCollapsed;
|
||||||
|
setIsCollapsed(newState);
|
||||||
|
localStorage.setItem("sidebar-collapsed", JSON.stringify(newState));
|
||||||
|
};
|
||||||
|
|
||||||
|
const navItems: NavItem[] = [
|
||||||
{ icon: LayoutDashboard, label: "Dashboard", href: "/" },
|
{ icon: LayoutDashboard, label: "Dashboard", href: "/" },
|
||||||
{ icon: Users, label: "Users", href: "/users" },
|
{ icon: Users, label: "Users", href: "/users" },
|
||||||
{
|
{
|
||||||
icon: Brain,
|
icon: Brain,
|
||||||
label: (
|
label: "AI Recommendations",
|
||||||
<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>
|
|
||||||
),
|
|
||||||
href: "/recommendations",
|
href: "/recommendations",
|
||||||
|
badge: pendingCount > 0 ? pendingCount : undefined,
|
||||||
},
|
},
|
||||||
{ icon: CalendarCheck, label: "Attendance", href: "/attendance" },
|
{ icon: CalendarCheck, label: "Attendance", href: "/attendance" },
|
||||||
{ icon: CreditCard, label: "Payments", href: "/payments" },
|
{ icon: CreditCard, label: "Payments", href: "/payments" },
|
||||||
@@ -48,59 +58,126 @@ export function Sidebar() {
|
|||||||
];
|
];
|
||||||
|
|
||||||
return (
|
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">
|
<aside
|
||||||
<div className="p-6 border-b border-slate-800 flex items-center overflow-hidden whitespace-nowrap">
|
className={cn(
|
||||||
<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">
|
"fixed left-0 top-0 z-40 h-screen transition-all duration-300 ease-in-out",
|
||||||
FitAI Admin
|
isCollapsed ? "w-[72px]" : "w-[260px]",
|
||||||
</h1>
|
"bg-gradient-to-b from-[var(--sidebar-background)] to-[#0f172a]",
|
||||||
</div>
|
)}
|
||||||
|
>
|
||||||
|
<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">
|
{/* Toggle Button */}
|
||||||
{menuItems.map((item) => {
|
<button
|
||||||
const Icon = item.icon;
|
onClick={handleToggle}
|
||||||
const isActive = pathname === item.href;
|
className={cn(
|
||||||
const label =
|
"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",
|
||||||
typeof item.label === "string" ? item.label : item.label;
|
isCollapsed ? "left-[60px]" : "left-[244px]",
|
||||||
return (
|
)}
|
||||||
<Link
|
>
|
||||||
key={item.href}
|
<ChevronLeft
|
||||||
href={item.href}
|
className={cn(
|
||||||
className={`flex items-center gap-3 px-4 py-3 rounded-lg transition-all duration-200 ${
|
"h-3.5 w-3.5 transition-transform",
|
||||||
isActive
|
isCollapsed && "rotate-180",
|
||||||
? "bg-blue-600 text-white shadow-lg shadow-blue-900/20"
|
)}
|
||||||
: "text-slate-400 hover:bg-slate-800 hover:text-white"
|
/>
|
||||||
}`}
|
</button>
|
||||||
>
|
|
||||||
<div className="min-w-[20px]">
|
{/* 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
|
<Icon
|
||||||
size={20}
|
className={cn(
|
||||||
className={
|
"h-5 w-5 flex-shrink-0 transition-colors",
|
||||||
isActive
|
isActive
|
||||||
? "text-white"
|
? "text-white"
|
||||||
: "text-slate-500 group-hover:text-white"
|
: "text-slate-500 group-hover:text-white",
|
||||||
}
|
)}
|
||||||
/>
|
/>
|
||||||
</div>
|
{!isCollapsed && (
|
||||||
<span className="font-medium opacity-0 group-hover:opacity-100 transition-opacity duration-300 whitespace-nowrap overflow-hidden">
|
<>
|
||||||
{label}
|
<span className="flex-1">{item.label}</span>
|
||||||
</span>
|
{item.badge !== undefined && (
|
||||||
</Link>
|
<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>
|
||||||
</nav>
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{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">
|
{/* User Section */}
|
||||||
<div className="flex items-center gap-3 px-2 py-3 rounded-lg bg-slate-800/50 overflow-hidden whitespace-nowrap">
|
<div
|
||||||
<div className="min-w-[32px]">
|
className={cn(
|
||||||
{mounted && <UserButton afterSignOutUrl="/" />}
|
"border-t border-white/5 p-3",
|
||||||
</div>
|
isCollapsed && "flex justify-center",
|
||||||
<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"}
|
<div
|
||||||
</p>
|
className={cn(
|
||||||
<p className="text-xs text-slate-400 truncate">
|
"flex items-center gap-3 rounded-lg bg-white/5 p-2 transition-colors hover:bg-white/10",
|
||||||
{user?.primaryEmailAddress?.emailAddress}
|
isCollapsed && "justify-center p-2",
|
||||||
</p>
|
)}
|
||||||
|
>
|
||||||
|
<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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,51 +1,139 @@
|
|||||||
import { LucideIcon } from "lucide-react";
|
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 {
|
interface StatsCardProps {
|
||||||
title: string;
|
title: string;
|
||||||
value: string | number;
|
value: string | number;
|
||||||
change?: string;
|
change?: string;
|
||||||
trend?: "up" | "down" | "neutral";
|
trend?: "up" | "down" | "neutral";
|
||||||
icon: LucideIcon;
|
icon: LucideIcon;
|
||||||
color?: "blue" | "green" | "purple" | "orange";
|
color?: "blue" | "green" | "purple" | "orange" | "red";
|
||||||
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function StatsCard({ title, value, change, trend, icon: Icon, color = "blue" }: StatsCardProps) {
|
export function StatsCard({
|
||||||
const colorStyles = {
|
title,
|
||||||
blue: "bg-blue-50 text-blue-600",
|
value,
|
||||||
green: "bg-green-50 text-green-600",
|
change,
|
||||||
purple: "bg-purple-50 text-purple-600",
|
trend,
|
||||||
orange: "bg-orange-50 text-orange-600",
|
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 (
|
const styles = colorStyles[color];
|
||||||
<Card>
|
const TrendIcon =
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
trend === "up" ? TrendingUp : trend === "down" ? TrendingDown : Minus;
|
||||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
|
||||||
{title}
|
return (
|
||||||
</CardTitle>
|
<div
|
||||||
<div className={`p-2 rounded-lg ${colorStyles[color]}`}>
|
className={cn(
|
||||||
<Icon size={16} />
|
"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",
|
||||||
</div>
|
styles.gradient,
|
||||||
</CardHeader>
|
className,
|
||||||
<CardContent>
|
)}
|
||||||
<div className="text-2xl font-bold">{value}</div>
|
>
|
||||||
{change && (
|
<div className="flex items-start justify-between">
|
||||||
<p className="text-xs text-muted-foreground mt-1">
|
<div className="space-y-2">
|
||||||
<span
|
<p className="text-sm font-medium text-muted-foreground">{title}</p>
|
||||||
className={`font-medium ${trend === "up"
|
<div className="flex items-baseline gap-2">
|
||||||
? "text-green-600"
|
<span className="text-3xl font-bold tracking-tight">{value}</span>
|
||||||
: trend === "down"
|
</div>
|
||||||
? "text-red-600"
|
{change && (
|
||||||
: "text-slate-600"
|
<div className="flex items-center gap-1 text-sm">
|
||||||
}`}
|
<TrendIcon
|
||||||
>
|
className={cn(
|
||||||
{change}
|
"h-4 w-4",
|
||||||
</span>{" "}
|
trend === "up" && styles.trendUp,
|
||||||
vs last month
|
trend === "down" && styles.trendDown,
|
||||||
</p>
|
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 React from "react";
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from "@/lib/utils";
|
||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from "lucide-react";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
|
||||||
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
const buttonVariants = cva(
|
||||||
variant?: 'primary' | 'secondary' | 'ghost' | 'destructive' | 'outline' | 'default'
|
"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",
|
||||||
size?: 'default' | 'sm' | 'lg' | 'icon'
|
{
|
||||||
isLoading?: boolean
|
variants: {
|
||||||
children: React.ReactNode
|
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({
|
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||||
variant = 'primary',
|
(
|
||||||
size = 'default',
|
{ className, variant, size, isLoading, children, disabled, ...props },
|
||||||
isLoading = false,
|
ref,
|
||||||
children,
|
) => {
|
||||||
className = '',
|
return (
|
||||||
disabled,
|
<button
|
||||||
...props
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
}: ButtonProps) {
|
ref={ref}
|
||||||
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'
|
disabled={disabled || isLoading}
|
||||||
|
{...props}
|
||||||
const variantClasses = {
|
>
|
||||||
primary: 'bg-blue-600 text-white hover:bg-blue-700 shadow hover:bg-blue-700/90',
|
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
default: 'bg-blue-600 text-white hover:bg-blue-700 shadow hover:bg-blue-700/90',
|
{children}
|
||||||
secondary: 'bg-slate-100 text-slate-900 hover:bg-slate-200/80',
|
</button>
|
||||||
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'
|
);
|
||||||
}
|
Button.displayName = "Button";
|
||||||
|
|
||||||
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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -16,7 +16,11 @@ import {
|
|||||||
useSendInvitation,
|
useSendInvitation,
|
||||||
} from "@/hooks/use-api";
|
} from "@/hooks/use-api";
|
||||||
|
|
||||||
export function UserManagement() {
|
interface UserManagementProps {
|
||||||
|
gymId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UserManagement({ gymId }: UserManagementProps) {
|
||||||
const { user } = useUser();
|
const { user } = useUser();
|
||||||
const [filter, setFilter] = useState<string>("all");
|
const [filter, setFilter] = useState<string>("all");
|
||||||
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
||||||
@@ -38,6 +42,7 @@ export function UserManagement() {
|
|||||||
refetch,
|
refetch,
|
||||||
} = useUsers({
|
} = useUsers({
|
||||||
role: filter !== "all" ? filter : undefined,
|
role: filter !== "all" ? filter : undefined,
|
||||||
|
gymId,
|
||||||
});
|
});
|
||||||
const { data: gyms = [] } = useGyms();
|
const { data: gyms = [] } = useGyms();
|
||||||
const updateUser = useUpdateUser();
|
const updateUser = useUpdateUser();
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ export interface AttendanceRecord {
|
|||||||
checkIn: string;
|
checkIn: string;
|
||||||
checkOut?: string;
|
checkOut?: string;
|
||||||
date: string;
|
date: string;
|
||||||
|
type?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchApi<T>(url: string, options?: RequestInit): Promise<T> {
|
async function fetchApi<T>(url: string, options?: RequestInit): Promise<T> {
|
||||||
@@ -369,12 +370,16 @@ export interface AnalyticsData {
|
|||||||
revenue: { label: string; value: number; color: string }[];
|
revenue: { label: string; value: number; color: string }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAnalytics(months: number = 6) {
|
export function useAnalytics(months: number = 6, gymId?: string) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["analytics", months],
|
queryKey: ["analytics", months, gymId],
|
||||||
queryFn: () =>
|
queryFn: () => {
|
||||||
fetchApi<{ data: { analytics: AnalyticsData } }>(
|
const url = gymId
|
||||||
`/api/admin/analytics?months=${months}`,
|
? `/api/admin/analytics?months=${months}&gymId=${gymId}`
|
||||||
).then((res) => res.data?.analytics),
|
: `/api/admin/analytics?months=${months}`;
|
||||||
|
return fetchApi<{ data: { analytics: AnalyticsData } }>(url).then(
|
||||||
|
(res) => res.data?.analytics,
|
||||||
|
);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get role from Clerk metadata
|
||||||
|
const role = (sessionClaims?.metadata as { role?: UserRole })?.role;
|
||||||
|
|
||||||
|
if (!role || !USER_ROLES.includes(role)) {
|
||||||
|
throw new Error(`Forbidden: Invalid or missing role - ${role}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get gymId from Clerk metadata or database
|
||||||
|
let gymId: string | null = null;
|
||||||
|
|
||||||
|
// First try Clerk metadata (faster path)
|
||||||
|
const clerkGymId = (sessionClaims?.metadata as { gymId?: string })?.gymId;
|
||||||
|
if (clerkGymId) {
|
||||||
|
gymId = clerkGymId;
|
||||||
|
} 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,10 @@ export const passwordSchema = z
|
|||||||
|
|
||||||
export const phoneSchema = z
|
export const phoneSchema = z
|
||||||
.string()
|
.string()
|
||||||
.regex(/^\+?[1-9]\d{1,14}$/, "Invalid phone number format")
|
.optional()
|
||||||
.optional();
|
.refine((val) => !val || /^\+?[1-9]\d{1,14}$/.test(val), {
|
||||||
|
message: "Invalid phone number format",
|
||||||
|
});
|
||||||
|
|
||||||
export const dateTimeSchema = z.string().datetime("Invalid datetime format");
|
export const dateTimeSchema = z.string().datetime("Invalid datetime format");
|
||||||
|
|
||||||
|
|||||||
Whitespace-only changes.
Reference in new issue
Block a user