basic stracture and auth

in memory db :)
This commit is contained in:
dimitar committed 2025-11-07 20:59:56 +01:00
commit 3a554ba434
71 files changed
+28535

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
{
"root": true,
"extends": [
"next/core-web-vitals",
"@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-explicit-any": "warn",
"prefer-const": "error",
"no-var": "error"
},
"ignorePatterns": ["node_modules", ".next", "dist"]
}
+45
View File
@@ -0,0 +1,45 @@
# Admin app specific
.next/
out/
.env.local
# Mobile app specific
.expo/
.expo-shared/
web-build/
*.jks
*.p8
*.p12
*.key
*.mobileprovision
.metro-health-check*
# iOS
ios/Pods/
*.xcode.env
ios/Pods/Flipper*
ios/Pods/Flipper-Folly
ios/Pods/Flipper-Glog
ios/Pods/Flipper-PeerTalk
ios/Pods/Flipper-RSocket
# Android
android/app/build/
android/gradle/
android/gradlew
android/gradlew.bat
android/local.properties
android/*.iml
android/.gradle/
android/app/release/
android/app/debug/
android/app/build/generated/
# Fastlane
*/fastlane/report.xml
*/fastlane/Preview.html
*/fastlane/screenshots
*/fastlane/test_output
# Bundle artifact
*.jsbundle
+15
View File
@@ -0,0 +1,15 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapping: {
'^@/(.*)$': '<rootDir>/src/$1',
},
testMatch: [
'**/__tests__/**/*.(ts|tsx|js)',
'**/*.(test|spec).(ts|tsx|js)',
],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
}
+1
View File
@@ -0,0 +1 @@
import '@testing-library/jest-dom'
+5
View File
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
+8
View File
@@ -0,0 +1,8 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
typescript: {
ignoreBuildErrors: false,
},
}
module.exports = nextConfig
+10176
View File
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
{
"name": "@fitai/admin",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"typecheck": "tsc --noEmit",
"test": "jest"
},
"dependencies": {
"@fitai/shared": "file:../../packages/shared",
"@hookform/resolvers": "^3.3.0",
"@tanstack/react-query": "^5.0.0",
"@types/bcryptjs": "^2.4.6",
"autoprefixer": "^10.4.0",
"axios": "^1.6.0",
"bcryptjs": "^2.4.3",
"lucide-react": "^0.294.0",
"next": "^14.0.0",
"postcss": "^8.4.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-hook-form": "^7.47.0",
"recharts": "^2.8.0",
"tailwindcss": "^3.3.0",
"zod": "^3.22.0",
"ag-grid-community": "^32.0.0",
"ag-grid-react": "^32.0.0",
"ag-charts-community": "^9.0.0",
"ag-charts-react": "^9.0.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.1.0",
"@testing-library/react": "^13.4.0",
"@types/node": "^20.0.0",
"@types/react": "18.3.26",
"@types/react-dom": "^18.0.0",
"eslint": "^8.45.0",
"eslint-config-next": "^14.0.0",
"jest": "^29.7.0",
"typescript": "^5.0.0"
}
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+11
View File
@@ -0,0 +1,11 @@
import { AnalyticsDashboard } from '@/components/analytics/AnalyticsDashboard'
export default function AnalyticsPage() {
return (
<main className="min-h-screen bg-gray-50">
<div className="container mx-auto px-4 py-8">
<AnalyticsDashboard />
</div>
</main>
)
}
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import { users } from '../../../../lib/database'
export async function POST(request: NextRequest) {
try {
const { email, password } = await request.json()
if (!email || !password) {
return NextResponse.json(
{ error: 'Email and password are required' },
{ status: 400 }
)
}
const user = users.find(u => u.email === email)
if (!user) {
return NextResponse.json(
{ error: 'Invalid credentials' },
{ status: 401 }
)
}
const isValidPassword = await bcrypt.compare(password, user.password)
if (!isValidPassword) {
return NextResponse.json(
{ error: 'Invalid credentials' },
{ status: 401 }
)
}
const { password: _, ...userWithoutPassword } = user
return NextResponse.json({
message: 'Login successful',
user: userWithoutPassword
})
} catch (error) {
console.error('Login error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
@@ -0,0 +1,73 @@
import { NextRequest, NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import { users, clients } from '../../../../lib/database'
export async function POST(request: NextRequest) {
try {
const { email, password, firstName, lastName, phone } = await request.json()
if (!email || !password || !firstName || !lastName) {
return NextResponse.json(
{ error: 'Missing required fields' },
{ status: 400 }
)
}
const existingUser = users.find(u => u.email === email)
if (existingUser) {
return NextResponse.json(
{ error: 'User already exists' },
{ status: 409 }
)
}
const hashedPassword = await bcrypt.hash(password, 10)
const userId = Math.random().toString(36).substr(2, 9)
const newUser = {
id: userId,
email,
firstName,
lastName,
password: hashedPassword,
phone,
role: 'client',
createdAt: new Date(),
updatedAt: new Date(),
}
users.push(newUser)
const newClient = {
id: Math.random().toString(36).substr(2, 9),
userId,
membershipType: 'basic',
membershipStatus: 'active',
joinDate: new Date(),
}
clients.push(newClient)
const { password: _, ...userWithoutPassword } = newUser
return NextResponse.json(
{
message: 'User registered successfully',
user: { ...userWithoutPassword, client: newClient }
},
{ status: 201 }
)
} catch (error) {
console.error('Registration error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
export async function GET() {
const usersWithoutPassword = users.map(({ password: _, ...user }) => user)
return NextResponse.json({ users: usersWithoutPassword })
}
+28
View File
@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server'
import { users, clients } from '../../../lib/database'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const role = searchParams.get('role')
let filteredUsers = users
if (role) {
filteredUsers = users.filter(user => user.role === role)
}
const usersWithClients = filteredUsers.map(({ password: _, ...user }) => {
const client = clients.find(c => c.userId === user.id)
return { ...user, client }
})
return NextResponse.json({ users: usersWithClients })
} catch (error) {
console.error('Get users error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
+3
View File
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
+22
View File
@@ -0,0 +1,22 @@
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'FitAI Admin',
description: 'Fitness management admin dashboard',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
)
}
+64
View File
@@ -0,0 +1,64 @@
'use client'
import Link from 'next/link'
import { UserManagement } from '@/components/users/UserManagement'
import { AnalyticsDashboard } from '@/components/analytics/AnalyticsDashboard'
export default function Home() {
return (
<main className="min-h-screen bg-gray-50">
<div className="container mx-auto px-4 py-8">
<div className="flex justify-between items-center mb-8">
<h1 className="text-4xl font-bold text-gray-900">
FitAI Admin Dashboard
</h1>
<nav className="flex gap-4">
<Link
href="/users"
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
>
User Management
</Link>
<Link
href="/analytics"
className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors"
>
Analytics
</Link>
</nav>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
<div className="bg-white rounded-lg shadow p-6">
<h2 className="text-xl font-semibold mb-4">Client Management</h2>
<p className="text-gray-600">Manage fitness clients and their profiles</p>
</div>
<div className="bg-white rounded-lg shadow p-6">
<h2 className="text-xl font-semibold mb-4">Payment Tracking</h2>
<p className="text-gray-600">Monitor payments and subscriptions</p>
</div>
<div className="bg-white rounded-lg shadow p-6">
<h2 className="text-xl font-semibold mb-4">Attendance</h2>
<p className="text-gray-600">Track client attendance and habits</p>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-white rounded-lg shadow p-6">
<h2 className="text-2xl font-semibold mb-6">Recent User Activity</h2>
<div className="h-96">
<UserManagement />
</div>
</div>
<div className="bg-white rounded-lg shadow p-6">
<h2 className="text-2xl font-semibold mb-6">Quick Analytics</h2>
<div className="h-96">
<AnalyticsDashboard />
</div>
</div>
</div>
</div>
</main>
)
}
+11
View File
@@ -0,0 +1,11 @@
import { UserManagement } from '@/components/users/UserManagement'
export default function UsersPage() {
return (
<main className="min-h-screen bg-gray-50">
<div className="container mx-auto px-4 py-8">
<UserManagement />
</div>
</main>
)
}
@@ -0,0 +1,140 @@
'use client'
import { useState, useEffect } from 'react'
import { UserGrowthChart } from '@/components/charts/UserGrowthChart'
import { MembershipDistributionChart } from '@/components/charts/MembershipDistributionChart'
import { RevenueChart } from '@/components/charts/RevenueChart'
import { Card, CardHeader, CardContent } from '@/components/ui/Card'
interface ChartData {
label: string
value: number
color?: string
}
export function AnalyticsDashboard() {
const [userGrowthData, setUserGrowthData] = useState<ChartData[]>([])
const [membershipData, setMembershipData] = useState<ChartData[]>([])
const [revenueData, setRevenueData] = useState<ChartData[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
fetchAnalyticsData()
}, [])
const fetchAnalyticsData = async () => {
setLoading(true)
try {
// Mock data for demonstration - replace with real API calls
const mockUserGrowth = [
{ label: 'Jan', value: 45 },
{ label: 'Feb', value: 52 },
{ label: 'Mar', value: 61 },
{ label: 'Apr', value: 58 },
{ label: 'May', value: 67 },
{ label: 'Jun', value: 74 },
]
const mockMembershipData = [
{ label: 'Basic', value: 45, color: '#6b7280' },
{ label: 'Premium', value: 28, color: '#3b82f6' },
{ label: 'VIP', value: 12, color: '#f59e0b' },
]
const mockRevenueData = [
{ label: 'Jan', value: 12500, color: '#10b981' },
{ label: 'Feb', value: 14200, color: '#10b981' },
{ label: 'Mar', value: 16800, color: '#10b981' },
{ label: 'Apr', value: 15900, color: '#10b981' },
{ label: 'May', value: 18200, color: '#10b981' },
{ label: 'Jun', value: 19400, color: '#10b981' },
]
setUserGrowthData(mockUserGrowth)
setMembershipData(mockMembershipData)
setRevenueData(mockRevenueData)
} catch (error) {
console.error('Failed to fetch analytics data:', error)
} finally {
setLoading(false)
}
}
const totalUsers = userGrowthData.length > 0 ? userGrowthData[userGrowthData.length - 1].value : 0
const totalRevenue = revenueData.reduce((sum, item) => sum + item.value, 0)
const activeMembers = membershipData.reduce((sum, item) => sum + item.value, 0)
if (loading) {
return (
<div className="flex justify-center items-center h-64">
<div className="text-lg">Loading analytics...</div>
</div>
)
}
return (
<div className="space-y-6">
<h2 className="text-2xl font-bold">Analytics Dashboard</h2>
{/* Key Metrics */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<Card>
<CardContent>
<div className="text-center">
<div className="text-3xl font-bold text-blue-600">{totalUsers}</div>
<div className="text-gray-600">Total Users</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent>
<div className="text-center">
<div className="text-3xl font-bold text-green-600">${totalRevenue.toLocaleString()}</div>
<div className="text-gray-600">Total Revenue</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent>
<div className="text-center">
<div className="text-3xl font-bold text-purple-600">{activeMembers}</div>
<div className="text-gray-600">Active Members</div>
</div>
</CardContent>
</Card>
</div>
{/* Charts */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card>
<CardHeader>
<h3 className="text-lg font-semibold">User Growth</h3>
</CardHeader>
<CardContent>
<UserGrowthChart data={userGrowthData} />
</CardContent>
</Card>
<Card>
<CardHeader>
<h3 className="text-lg font-semibold">Membership Distribution</h3>
</CardHeader>
<CardContent>
<MembershipDistributionChart data={membershipData} />
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<h3 className="text-lg font-semibold">Monthly Revenue</h3>
</CardHeader>
<CardContent>
<RevenueChart data={revenueData} />
</CardContent>
</Card>
</div>
)
}
@@ -0,0 +1,88 @@
'use client'
import React, { useMemo } from 'react'
import { AgChartsReact } from 'ag-charts-react'
import { AgChartOptions } from 'ag-charts-community'
interface PieData {
label: string
value: number
color?: string
}
interface MembershipDistributionChartProps {
data: PieData[]
title?: string
}
export function MembershipDistributionChart({ data, title = 'Membership Distribution' }: MembershipDistributionChartProps) {
const chartOptions: AgChartOptions = useMemo(() => ({
title: {
text: title,
fontSize: 18,
fontWeight: 'bold',
},
data,
series: [
{
type: 'pie',
calloutLabelKey: 'label',
angleKey: 'value',
sectorLabelKey: 'label',
fills: data.map(item => item.color || '#3b82f6'),
strokes: ['#ffffff'],
strokeWidth: 2,
calloutLabel: {
enabled: true,
fontSize: 12,
fontWeight: 'bold',
},
sectorLabel: {
enabled: true,
fontSize: 14,
fontWeight: 'bold',
color: '#ffffff',
formatter: (params: any) => {
const percentage = ((params.datum.value / data.reduce((sum, item) => sum + item.value, 0)) * 100).toFixed(1)
return `${params.datum.label}: ${percentage}%`
},
},
highlightStyle: {
item: {
fillOpacity: 0.8,
stroke: '#000000',
strokeWidth: 2,
},
},
tooltip: {
enabled: true,
renderer: (params: any) => {
const percentage = ((params.datum.value / data.reduce((sum, item) => sum + item.value, 0)) * 100).toFixed(1)
return `<div class="bg-white p-2 rounded shadow-lg border">
<div class="font-bold">${params.datum.label}</div>
<div class="text-sm">Count: ${params.datum.value}</div>
<div class="text-sm">Percentage: ${percentage}%</div>
</div>`
},
},
},
],
legend: {
enabled: true,
position: 'right',
fontSize: 12,
marker: {
shape: 'square',
size: 12,
},
},
padding: {
top: 20,
right: 20,
bottom: 20,
left: 20,
},
}), [data, title])
return <AgChartsReact options={chartOptions} />
}
@@ -0,0 +1,99 @@
'use client'
import React, { useMemo } from 'react'
import { AgChartsReact } from 'ag-charts-react'
import { AgChartOptions } from 'ag-charts-community'
interface BarData {
category: string
value: number
color?: string
}
interface RevenueChartProps {
data: BarData[]
title?: string
}
export function RevenueChart({ data, title = 'Monthly Revenue' }: RevenueChartProps) {
const chartOptions: AgChartOptions = useMemo(() => ({
title: {
text: title,
fontSize: 18,
fontWeight: 'bold',
},
data,
series: [
{
type: 'bar',
xKey: 'category',
yKey: 'value',
fills: data.map(item => item.color || '#10b981'),
strokes: ['#ffffff'],
strokeWidth: 2,
cornerRadius: 4,
highlightStyle: {
item: {
fill: '#059669',
stroke: '#ffffff',
strokeWidth: 2,
},
},
label: {
enabled: true,
position: 'top',
fontSize: 12,
fontWeight: 'bold',
color: '#374151',
formatter: (params: any) => `$${params.value.toLocaleString()}`,
},
tooltip: {
enabled: true,
renderer: (params: any) => {
return `<div class="bg-white p-2 rounded shadow-lg border">
<div class="font-bold">${params.datum.category}</div>
<div class="text-sm">Revenue: $${params.datum.value.toLocaleString()}</div>
</div>`
},
},
},
],
axes: [
{
type: 'category',
position: 'bottom',
title: {
text: 'Month',
fontSize: 14,
},
label: {
fontSize: 12,
rotation: 45,
},
},
{
type: 'number',
position: 'left',
title: {
text: 'Revenue ($)',
fontSize: 14,
},
label: {
fontSize: 12,
formatter: (params: any) => `$${params.value.toLocaleString()}`,
},
},
],
legend: {
enabled: false,
},
padding: {
top: 20,
right: 20,
bottom: 60,
left: 80,
},
}), [data, title])
return <AgChartsReact options={chartOptions} />
}
@@ -0,0 +1,78 @@
'use client'
import React, { useMemo } from 'react'
import { AgChartsReact } from 'ag-charts-react'
import { AgChartOptions } from 'ag-charts-community'
interface ChartData {
label: string
value: number
color?: string
}
interface UserGrowthChartProps {
data: ChartData[]
title?: string
}
export function UserGrowthChart({ data, title = 'User Growth' }: UserGrowthChartProps) {
const chartOptions: AgChartOptions = useMemo(() => ({
title: {
text: title,
fontSize: 18,
fontWeight: 'bold',
},
data,
series: [
{
type: 'line',
xKey: 'label',
yKey: 'value',
stroke: '#3b82f6',
strokeWidth: 3,
marker: {
size: 6,
fill: '#3b82f6',
stroke: '#ffffff',
strokeWidth: 2,
},
highlightStyle: {
item: {
fill: '#1d4ed8',
stroke: '#ffffff',
strokeWidth: 2,
},
},
},
],
axes: [
{
type: 'category',
position: 'bottom',
title: {
text: 'Time Period',
fontSize: 14,
},
},
{
type: 'number',
position: 'left',
title: {
text: 'Number of Users',
fontSize: 14,
},
},
],
legend: {
enabled: false,
},
padding: {
top: 20,
right: 20,
bottom: 20,
left: 20,
},
}), [data, title])
return <AgChartsReact options={chartOptions} />
}
+23
View File
@@ -0,0 +1,23 @@
import React from 'react'
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary'
children: React.ReactNode
}
export function Button({ variant = 'primary', children, className = '', ...props }: ButtonProps) {
const baseClasses = 'px-4 py-2 rounded-md font-medium transition-colors'
const variantClasses = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300',
}
return (
<button
className={`${baseClasses} ${variantClasses[variant]} ${className}`}
{...props}
>
{children}
</button>
)
}
+30
View File
@@ -0,0 +1,30 @@
import React from 'react'
interface CardProps {
children: React.ReactNode
className?: string
}
export function Card({ children, className = '' }: CardProps) {
return (
<div className={`bg-white rounded-lg shadow-md p-6 ${className}`}>
{children}
</div>
)
}
export function CardHeader({ children, className = '' }: CardProps) {
return (
<div className={`mb-4 ${className}`}>
{children}
</div>
)
}
export function CardContent({ children, className = '' }: CardProps) {
return (
<div className={className}>
{children}
</div>
)
}
@@ -0,0 +1,167 @@
'use client'
import React, { useState, useMemo } from 'react'
import { AgGridReact } from 'ag-grid-react'
import { ColDef } from 'ag-grid-community'
import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-alpine.css'
import { formatDate } from '@/lib/utils'
interface User {
id: string
email: string
firstName: string
lastName: string
role: string
phone?: string
createdAt: Date
client?: {
id: string
membershipType: string
membershipStatus: string
joinDate: Date
lastVisit?: Date
}
}
interface UserGridProps {
users: User[]
onUserSelect?: (user: User) => void
loading?: boolean
}
export function UserGrid({ users, onUserSelect, loading = false }: UserGridProps) {
const [selectedUser, setSelectedUser] = useState<User | null>(null)
const columnDefs: ColDef<User>[] = useMemo(() => [
{
headerName: 'Name',
valueGetter: (params) => `${params.data?.firstName} ${params.data?.lastName}`,
filter: 'agTextColumnFilter',
sortable: true,
minWidth: 150,
},
{
headerName: 'Email',
field: 'email',
filter: 'agTextColumnFilter',
sortable: true,
minWidth: 200,
},
{
headerName: 'Role',
field: 'role',
filter: 'agSetColumnFilter',
sortable: true,
cellRenderer: (params: any) => {
const roleColors = {
admin: 'bg-purple-100 text-purple-800',
trainer: 'bg-blue-100 text-blue-800',
client: 'bg-green-100 text-green-800',
}
const colorClass = roleColors[params.value as keyof typeof roleColors] || 'bg-gray-100 text-gray-800'
return `<span class="px-2 py-1 rounded text-xs font-medium ${colorClass}">${params.value}</span>`
},
minWidth: 120,
},
{
headerName: 'Phone',
field: 'phone',
filter: 'agTextColumnFilter',
sortable: true,
minWidth: 130,
},
{
headerName: 'Membership',
valueGetter: (params) => params.data?.client?.membershipType || 'N/A',
filter: 'agSetColumnFilter',
sortable: true,
cellRenderer: (params: any) => {
if (!params.value || params.value === 'N/A') return 'N/A'
const membershipColors = {
vip: 'bg-yellow-100 text-yellow-800',
premium: 'bg-blue-100 text-blue-800',
basic: 'bg-gray-100 text-gray-800',
}
const colorClass = membershipColors[params.value as keyof typeof membershipColors] || 'bg-gray-100 text-gray-800'
return `<span class="px-2 py-1 rounded text-xs font-medium ${colorClass}">${params.value}</span>`
},
minWidth: 120,
},
{
headerName: 'Status',
valueGetter: (params) => params.data?.client?.membershipStatus || 'N/A',
filter: 'agSetColumnFilter',
sortable: true,
cellRenderer: (params: any) => {
if (!params.value || params.value === 'N/A') return 'N/A'
const statusColors = {
active: 'bg-green-100 text-green-800',
inactive: 'bg-red-100 text-red-800',
suspended: 'bg-yellow-100 text-yellow-800',
}
const colorClass = statusColors[params.value as keyof typeof statusColors] || 'bg-gray-100 text-gray-800'
return `<span class="px-2 py-1 rounded text-xs font-medium ${colorClass}">${params.value}</span>`
},
minWidth: 120,
},
{
headerName: 'Join Date',
valueGetter: (params) => params.data?.client?.joinDate || params.data?.createdAt,
filter: 'agDateColumnFilter',
sortable: true,
valueFormatter: (params: any) => formatDate(new Date(params.value)),
minWidth: 120,
},
{
headerName: 'Last Visit',
valueGetter: (params) => params.data?.client?.lastVisit,
filter: 'agDateColumnFilter',
sortable: true,
valueFormatter: (params: any) => params.value ? formatDate(new Date(params.value)) : 'Never',
minWidth: 120,
},
], [])
const defaultColDef: ColDef = useMemo(() => ({
flex: 1,
resizable: true,
floatingFilter: true,
suppressMenu: true,
}), [])
const onSelectionChanged = () => {
const selectedNodes = gridRef.current?.api.getSelectedNodes()
if (selectedNodes?.length > 0) {
const user = selectedNodes[0].data
setSelectedUser(user)
onUserSelect?.(user)
}
}
const gridRef = React.useRef<AgGridReact<User>>(null)
const gridOptions = {
columnDefs,
defaultColDef,
rowData: users,
rowSelection: 'single',
onSelectionChanged,
enableRangeSelection: true,
enableCellTextSelection: true,
suppressRowClickSelection: false,
animateRows: true,
loading: loading,
pagination: true,
paginationPageSize: 20,
paginationPageSizeSelector: [10, 20, 50, 100],
}
return (
<div className="ag-theme-alpine" style={{ height: '600px', width: '100%' }}>
<AgGridReact<User> {...gridOptions} ref={gridRef} />
</div>
)
}
@@ -0,0 +1,180 @@
'use client'
import { useState, useEffect } from 'react'
import { UserGrid } from '@/components/users/UserGrid'
import { Button } from '@/components/ui/Button'
import { Card, CardHeader, CardContent } from '@/components/ui/Card'
interface User {
id: string
email: string
firstName: string
lastName: string
role: string
phone?: string
createdAt: Date
client?: {
id: string
membershipType: string
membershipStatus: string
joinDate: Date
lastVisit?: Date
}
}
export function UserManagement() {
const [users, setUsers] = useState<User[]>([])
const [loading, setLoading] = useState(true)
const [filter, setFilter] = useState<string>('all')
const [selectedUser, setSelectedUser] = useState<User | null>(null)
useEffect(() => {
fetchUsers()
}, [filter])
const fetchUsers = async () => {
setLoading(true)
try {
const url = filter === 'all'
? '/api/users'
: `/api/users?role=${filter}`
const response = await fetch(url)
const data = await response.json()
setUsers(data.users || [])
} catch (error) {
console.error('Failed to fetch users:', error)
} finally {
setLoading(false)
}
}
const handleUserSelect = (user: User) => {
setSelectedUser(user)
}
const handleExport = () => {
const csvContent = [
['Name', 'Email', 'Role', 'Phone', 'Membership', 'Status', 'Join Date', 'Last Visit'],
...users.map(user => [
`${user.firstName} ${user.lastName}`,
user.email,
user.role,
user.phone || '',
user.client?.membershipType || '',
user.client?.membershipStatus || '',
user.client?.joinDate || user.createdAt,
user.client?.lastVisit || ''
])
].map(row => row.join(',')).join('\n')
const blob = new Blob([csvContent], { type: 'text/csv' })
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `users_${new Date().toISOString().split('T')[0]}.csv`
a.click()
window.URL.revokeObjectURL(url)
}
const handleRefresh = () => {
fetchUsers()
}
return (
<div className="space-y-6">
<div className="flex justify-between items-center">
<h2 className="text-2xl font-bold">User Management</h2>
<div className="flex gap-2">
<Button
variant={filter === 'all' ? 'primary' : 'secondary'}
onClick={() => setFilter('all')}
>
All Users
</Button>
<Button
variant={filter === 'client' ? 'primary' : 'secondary'}
onClick={() => setFilter('client')}
>
Clients
</Button>
<Button
variant={filter === 'trainer' ? 'primary' : 'secondary'}
onClick={() => setFilter('trainer')}
>
Trainers
</Button>
<Button
variant={filter === 'admin' ? 'primary' : 'secondary'}
onClick={() => setFilter('admin')}
>
Admins
</Button>
</div>
</div>
<div className="flex justify-between items-center">
<div className="text-sm text-gray-600">
Showing {users.length} users
{selectedUser && (
<span className="ml-4 text-blue-600">
Selected: {selectedUser.firstName} {selectedUser.lastName}
</span>
)}
</div>
<div className="flex gap-2">
<Button variant="secondary" onClick={handleRefresh}>
Refresh
</Button>
<Button variant="secondary" onClick={handleExport}>
Export CSV
</Button>
</div>
</div>
<Card>
<CardContent className="p-0">
<UserGrid
users={users}
onUserSelect={handleUserSelect}
loading={loading}
/>
</CardContent>
</Card>
{selectedUser && (
<Card>
<CardHeader>
<h3 className="text-lg font-semibold">User Details</h3>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-4">
<div>
<h4 className="font-medium mb-2">Basic Information</h4>
<div className="space-y-1 text-sm">
<p><span className="font-medium">Name:</span> {selectedUser.firstName} {selectedUser.lastName}</p>
<p><span className="font-medium">Email:</span> {selectedUser.email}</p>
<p><span className="font-medium">Phone:</span> {selectedUser.phone || 'N/A'}</p>
<p><span className="font-medium">Role:</span> {selectedUser.role}</p>
<p><span className="font-medium">Joined:</span> {selectedUser.createdAt.toLocaleDateString()}</p>
</div>
</div>
{selectedUser.client && (
<div>
<h4 className="font-medium mb-2">Client Information</h4>
<div className="space-y-1 text-sm">
<p><span className="font-medium">Membership:</span> {selectedUser.client.membershipType}</p>
<p><span className="font-medium">Status:</span> {selectedUser.client.membershipStatus}</p>
<p><span className="font-medium">Member Since:</span> {selectedUser.client.joinDate.toLocaleDateString()}</p>
<p><span className="font-medium">Last Visit:</span> {selectedUser.client.lastVisit?.toLocaleDateString() || 'Never'}</p>
</div>
</div>
)}
</div>
</CardContent>
</Card>
)}
</div>
)
}
+23
View File
@@ -0,0 +1,23 @@
export interface User {
id: string
email: string
firstName: string
lastName: string
password: string
phone?: string
role: 'admin' | 'client'
createdAt: Date
updatedAt: Date
}
export interface Client {
id: string
userId: string
membershipType: 'basic' | 'premium' | 'vip'
membershipStatus: 'active' | 'inactive' | 'expired'
joinDate: Date
}
// In-memory database
export const users: User[] = []
export const clients: Client[] = []
+26
View File
@@ -0,0 +1,26 @@
export const formatDate = (date: Date): string => {
return new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
}).format(date)
}
export const formatCurrency = (
amount: number,
currency: string = 'USD'
): string => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
}).format(amount)
}
export const calculateDaysBetween = (startDate: Date, endDate: Date): number => {
const timeDiff = endDate.getTime() - startDate.getTime()
return Math.ceil(timeDiff / (1000 * 3600 * 24))
}
export const generateId = (): string => {
return Math.random().toString(36).substr(2, 9)
}
+21
View File
@@ -0,0 +1,21 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/pages/**/*.{js,ts,jsx,tsx,mdx}',
'./src/components/**/*.{js,ts,jsx,tsx,mdx}',
'./src/app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
colors: {
primary: {
50: '#eff6ff',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
},
},
},
},
plugins: [],
}
+51
View File
@@ -0,0 +1,51 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"es6"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
],
"@/components/*": [
"./src/components/*"
],
"@/lib/*": [
"./src/lib/*"
],
"@/types/*": [
"./src/types/*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}