user report gtound work
This commit is contained in:
1 parent
1be2de05fa
commit
74f0d0dbed
42 files changed
+8127
-5
No files matched your search
@@ -0,0 +1,132 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { AgCharts } from "ag-charts-react";
|
||||
import {
|
||||
AgBarSeriesOptions,
|
||||
AgChartOptions,
|
||||
AgLineSeriesOptions,
|
||||
AgPieSeriesOptions,
|
||||
} from "ag-charts-community";
|
||||
|
||||
export function BarChart({
|
||||
data,
|
||||
xKey,
|
||||
yKey,
|
||||
color = "#3c82e6",
|
||||
height = 300,
|
||||
}: {
|
||||
data: any[];
|
||||
xKey: string;
|
||||
yKey: string;
|
||||
color?: string;
|
||||
height?: number;
|
||||
}) {
|
||||
const options: AgChartOptions = {
|
||||
data,
|
||||
series: [
|
||||
{
|
||||
type: "bar",
|
||||
xKey,
|
||||
yKey,
|
||||
fill: color,
|
||||
} as AgBarSeriesOptions,
|
||||
],
|
||||
height,
|
||||
};
|
||||
|
||||
return <AgCharts options={options} />;
|
||||
}
|
||||
|
||||
export function LineChart({
|
||||
data,
|
||||
xKey,
|
||||
yKey,
|
||||
color = "#3b82f6",
|
||||
height = 300,
|
||||
}: {
|
||||
data: any[];
|
||||
xKey: string;
|
||||
yKey: string;
|
||||
color?: string;
|
||||
height?: number;
|
||||
}) {
|
||||
const options: AgChartOptions = {
|
||||
data,
|
||||
series: [
|
||||
{
|
||||
type: "line",
|
||||
xKey,
|
||||
yKey,
|
||||
stroke: color,
|
||||
strokeWidth: 3,
|
||||
marker: {
|
||||
size: 6,
|
||||
fill: color,
|
||||
stroke: "#ffffff",
|
||||
strokeWidth: 2,
|
||||
},
|
||||
} as AgLineSeriesOptions,
|
||||
],
|
||||
height,
|
||||
};
|
||||
|
||||
return <AgCharts options={options} />;
|
||||
}
|
||||
|
||||
export function PieChart({
|
||||
data,
|
||||
labelKey,
|
||||
valueKey,
|
||||
height = 300,
|
||||
}: {
|
||||
data: any[];
|
||||
labelKey: string;
|
||||
valueKey: string;
|
||||
height?: number;
|
||||
}) {
|
||||
const options: AgChartOptions = {
|
||||
data,
|
||||
series: [
|
||||
{
|
||||
type: "pie",
|
||||
labelKey,
|
||||
angleKey: valueKey,
|
||||
} as AgPieSeriesOptions,
|
||||
],
|
||||
height,
|
||||
};
|
||||
|
||||
return <AgCharts options={options} />;
|
||||
}
|
||||
|
||||
export function AreaChart({
|
||||
data,
|
||||
xKey,
|
||||
yKey,
|
||||
color = "#3b82f6",
|
||||
height = 300,
|
||||
}: {
|
||||
data: any[];
|
||||
xKey: string;
|
||||
yKey: string;
|
||||
color?: string;
|
||||
height?: number;
|
||||
}) {
|
||||
const options: AgChartOptions = {
|
||||
data,
|
||||
series: [
|
||||
{
|
||||
type: "area",
|
||||
xKey,
|
||||
yKey,
|
||||
fill: color,
|
||||
stroke: color,
|
||||
strokeWidth: 2,
|
||||
},
|
||||
],
|
||||
height,
|
||||
};
|
||||
|
||||
return <AgCharts options={options} />;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
"use client";
|
||||
|
||||
import { GoalSummary } from "@fitai/shared";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
interface GoalsSummaryCardProps {
|
||||
goals: GoalSummary;
|
||||
}
|
||||
|
||||
export function GoalsSummaryCard({ goals }: GoalsSummaryCardProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Fitness Goals</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Summary Stats */}
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{goals.totalActive}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Active Goals</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-green-600">
|
||||
{goals.totalCompleted}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Completed</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-purple-600">
|
||||
{goals.averageProgress}%
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Avg Progress</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Active Goals */}
|
||||
{goals.active.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold">Active Goals</h4>
|
||||
<div className="space-y-2">
|
||||
{goals.active.map((goal) => (
|
||||
<div key={goal.id} className="border rounded-lg p-3">
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<div className="font-medium">{goal.title}</div>
|
||||
<Badge
|
||||
variant={
|
||||
goal.priority === "high" ? "destructive" : "secondary"
|
||||
}
|
||||
>
|
||||
{goal.priority}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 mb-2">
|
||||
{goal.goalType.replace("_", " ")}
|
||||
</div>
|
||||
{/* Progress Bar */}
|
||||
<div className="w-full bg-gray-200 rounded-full h-2">
|
||||
<div
|
||||
className="bg-blue-600 h-2 rounded-full transition-all"
|
||||
style={{ width: `${goal.progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 mt-1">
|
||||
{goal.progress}% complete
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Completed Goals */}
|
||||
{goals.completed.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold">Completed Goals</h4>
|
||||
<div className="space-y-1">
|
||||
{goals.completed.map((goal) => (
|
||||
<div
|
||||
key={goal.id}
|
||||
className="flex justify-between items-center text-sm p-2 bg-green-50 rounded"
|
||||
>
|
||||
<span className="font-medium">{goal.title}</span>
|
||||
<span className="text-xs text-green-700">
|
||||
✓{" "}
|
||||
{goal.completedDate
|
||||
? new Date(goal.completedDate).toLocaleDateString()
|
||||
: "N/A"}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty State */}
|
||||
{goals.active.length === 0 && goals.completed.length === 0 && (
|
||||
<div className="text-center text-gray-500 py-8">
|
||||
No goals found for this period
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
"use client";
|
||||
|
||||
import { HydrationSummary } from "@fitai/shared";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
ResponsiveContainer,
|
||||
Legend,
|
||||
Tooltip,
|
||||
} from "recharts";
|
||||
|
||||
interface HydrationSummaryCardProps {
|
||||
hydration: {
|
||||
dailySummaries: HydrationSummary[];
|
||||
averageDailyWater: number;
|
||||
totalDays: number;
|
||||
daysMetGoal: number;
|
||||
};
|
||||
}
|
||||
|
||||
export function HydrationSummaryCard({ hydration }: HydrationSummaryCardProps) {
|
||||
const goalMetPercentage =
|
||||
hydration.totalDays > 0
|
||||
? Math.round((hydration.daysMetGoal / hydration.totalDays) * 100)
|
||||
: 0;
|
||||
|
||||
const chartData = [
|
||||
{ name: "Days Met Goal", value: hydration.daysMetGoal, color: "#06b6d4" },
|
||||
{
|
||||
name: "Days Under Goal",
|
||||
value: hydration.totalDays - hydration.daysMetGoal,
|
||||
color: "#f59e0b",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Hydration Summary</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Summary Stats */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{(hydration.averageDailyWater / 1000).toFixed(1)}L
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Avg Daily Water</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-cyan-600">
|
||||
{hydration.totalDays}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Days Tracked</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Goal Achievement */}
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold text-green-600">
|
||||
{goalMetPercentage}%
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Days Met Hydration Goal</div>
|
||||
</div>
|
||||
|
||||
{/* Chart */}
|
||||
{hydration.totalDays > 0 && (
|
||||
<div className="h-48">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={chartData}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={40}
|
||||
outerRadius={70}
|
||||
paddingAngle={5}
|
||||
dataKey="value"
|
||||
>
|
||||
{chartData.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={entry.color} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recent Days */}
|
||||
{hydration.dailySummaries.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold">Recent Days</h4>
|
||||
<div className="max-h-32 overflow-y-auto space-y-1">
|
||||
{hydration.dailySummaries
|
||||
.slice(-5)
|
||||
.reverse()
|
||||
.map((day) => (
|
||||
<div
|
||||
key={day.date}
|
||||
className="flex justify-between items-center text-sm"
|
||||
>
|
||||
<span className="text-gray-600">{day.date}</span>
|
||||
<span className="font-medium">
|
||||
{day.totalWater}ml / {day.waterGoal}ml (
|
||||
{day.hydrationPercentage}%)
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import { NutritionSummary } from "@fitai/shared";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
ResponsiveContainer,
|
||||
Legend,
|
||||
Tooltip,
|
||||
} from "recharts";
|
||||
|
||||
interface NutritionSummaryCardProps {
|
||||
nutrition: {
|
||||
dailySummaries: NutritionSummary[];
|
||||
averageDailyCalories: number;
|
||||
totalDays: number;
|
||||
daysMetGoal: number;
|
||||
};
|
||||
}
|
||||
|
||||
export function NutritionSummaryCard({ nutrition }: NutritionSummaryCardProps) {
|
||||
const goalMetPercentage =
|
||||
nutrition.totalDays > 0
|
||||
? Math.round((nutrition.daysMetGoal / nutrition.totalDays) * 100)
|
||||
: 0;
|
||||
|
||||
const chartData = [
|
||||
{ name: "Days Met Goal", value: nutrition.daysMetGoal, color: "#10b981" },
|
||||
{
|
||||
name: "Days Over/Under",
|
||||
value: nutrition.totalDays - nutrition.daysMetGoal,
|
||||
color: "#f59e0b",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Nutrition Summary</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Summary Stats */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{nutrition.averageDailyCalories.toLocaleString()}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Avg Daily Calories</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-green-600">
|
||||
{nutrition.totalDays}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Days Tracked</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Goal Achievement */}
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold text-purple-600">
|
||||
{goalMetPercentage}%
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">
|
||||
Days Met Calorie Goal (±10%)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chart */}
|
||||
{nutrition.totalDays > 0 && (
|
||||
<div className="h-48">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={chartData}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={40}
|
||||
outerRadius={70}
|
||||
paddingAngle={5}
|
||||
dataKey="value"
|
||||
>
|
||||
{chartData.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={entry.color} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recent Days */}
|
||||
{nutrition.dailySummaries.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold">Recent Days</h4>
|
||||
<div className="max-h-32 overflow-y-auto space-y-1">
|
||||
{nutrition.dailySummaries
|
||||
.slice(-5)
|
||||
.reverse()
|
||||
.map((day) => (
|
||||
<div
|
||||
key={day.date}
|
||||
className="flex justify-between items-center text-sm"
|
||||
>
|
||||
<span className="text-gray-600">{day.date}</span>
|
||||
<span className="font-medium">
|
||||
{day.totalCalories.toLocaleString()} /{" "}
|
||||
{day.calorieGoal.toLocaleString()} cal
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
"use client";
|
||||
|
||||
import { RecommendationSummary } from "@fitai/shared";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
interface RecommendationsCardProps {
|
||||
recommendations: RecommendationSummary;
|
||||
}
|
||||
|
||||
export function RecommendationsCard({
|
||||
recommendations,
|
||||
}: RecommendationsCardProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>AI Recommendations</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Summary Stats */}
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-green-600">
|
||||
{recommendations.totalAccepted}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Accepted</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-yellow-600">
|
||||
{recommendations.totalPending}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Pending</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-red-600">
|
||||
{recommendations.totalRejected}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Rejected</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Accepted Recommendations */}
|
||||
{recommendations.accepted.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold text-green-700">
|
||||
Accepted Recommendations
|
||||
</h4>
|
||||
<div className="space-y-2">
|
||||
{recommendations.accepted.map((rec) => (
|
||||
<div
|
||||
key={rec.id}
|
||||
className="border border-green-200 bg-green-50 rounded-lg p-3"
|
||||
>
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<Badge variant="default" className="bg-green-600">
|
||||
Accepted
|
||||
</Badge>
|
||||
<span className="text-xs text-gray-500">
|
||||
{new Date(rec.generatedAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm">{rec.recommendationText}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pending Recommendations */}
|
||||
{recommendations.pending.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold text-yellow-700">
|
||||
Pending Recommendations
|
||||
</h4>
|
||||
<div className="space-y-2">
|
||||
{recommendations.pending.map((rec) => (
|
||||
<div
|
||||
key={rec.id}
|
||||
className="border border-yellow-200 bg-yellow-50 rounded-lg p-3"
|
||||
>
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<Badge variant="secondary">Pending</Badge>
|
||||
<span className="text-xs text-gray-500">
|
||||
{new Date(rec.generatedAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm">{rec.recommendationText}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rejected Recommendations */}
|
||||
{recommendations.rejected.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold text-red-700">
|
||||
Rejected Recommendations
|
||||
</h4>
|
||||
<div className="space-y-2">
|
||||
{recommendations.rejected.map((rec) => (
|
||||
<div
|
||||
key={rec.id}
|
||||
className="border border-red-200 bg-red-50 rounded-lg p-3"
|
||||
>
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<Badge variant="destructive">Rejected</Badge>
|
||||
<span className="text-xs text-gray-500">
|
||||
{new Date(rec.generatedAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm">{rec.recommendationText}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty State */}
|
||||
{recommendations.totalAccepted === 0 &&
|
||||
recommendations.totalPending === 0 &&
|
||||
recommendations.totalRejected === 0 && (
|
||||
<div className="text-center text-gray-500 py-8">
|
||||
No recommendations found for this period
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { User, Client } from "@fitai/shared";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { useUser } from "@clerk/nextjs";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
interface ReportFiltersProps {
|
||||
selectedUserId: string;
|
||||
onUserChange: (userId: string) => void;
|
||||
dateRange: {
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
};
|
||||
onDateRangeChange: (range: { startDate: string; endDate: string }) => void;
|
||||
}
|
||||
|
||||
export function ReportFilters({
|
||||
selectedUserId,
|
||||
onUserChange,
|
||||
dateRange,
|
||||
onDateRangeChange,
|
||||
}: ReportFiltersProps) {
|
||||
const { user: clerkUser } = useUser();
|
||||
const [users, setUsers] = useState<(User & { client?: Client | null })[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [currentUser, setCurrentUser] = useState<User | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchCurrentUserAndClients();
|
||||
}, []);
|
||||
|
||||
const fetchCurrentUserAndClients = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// Fetch current user info
|
||||
const userResponse = await fetch("/api/users/me");
|
||||
if (userResponse.ok) {
|
||||
const userData = await userResponse.json();
|
||||
setCurrentUser(userData.user);
|
||||
|
||||
// Determine which clients to show based on role
|
||||
if (userData.user.role === "client") {
|
||||
// Regular users can only view their own report
|
||||
setUsers([userData.user]);
|
||||
onUserChange(userData.user.id);
|
||||
} else if (userData.user.role === "trainer") {
|
||||
// Trainers can only view their assigned clients
|
||||
const assignmentsRes = await fetch("/api/trainer-client");
|
||||
if (assignmentsRes.ok) {
|
||||
const assignmentsData = await assignmentsRes.json();
|
||||
const assignedClientIds = (assignmentsData.assignments || [])
|
||||
.filter((a: any) => a.isActive)
|
||||
.map((a: any) => a.clientId);
|
||||
|
||||
if (assignedClientIds.length > 0) {
|
||||
// Fetch assigned clients
|
||||
const clientsRes = await fetch(
|
||||
`/api/users?role=client&ids=${assignedClientIds.join(",")}`,
|
||||
);
|
||||
if (clientsRes.ok) {
|
||||
const clientsData = await clientsRes.json();
|
||||
setUsers(clientsData.users || []);
|
||||
}
|
||||
} else {
|
||||
setUsers([]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Admins and superadmins can view all clients
|
||||
const clientsRes = await fetch("/api/users?role=client");
|
||||
if (clientsRes.ok) {
|
||||
const clientsData = await clientsRes.json();
|
||||
setUsers(clientsData.users || []);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
log.error("Failed to fetch users:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePresetRange = (days: number) => {
|
||||
const end = new Date();
|
||||
const start = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||||
onDateRangeChange({
|
||||
startDate: start.toISOString().split("T")[0],
|
||||
endDate: end.toISOString().split("T")[0],
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
{/* User Selector */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="user-select">Select User</Label>
|
||||
<Select
|
||||
value={selectedUserId}
|
||||
onValueChange={onUserChange}
|
||||
disabled={loading}
|
||||
>
|
||||
<SelectTrigger id="user-select">
|
||||
<SelectValue placeholder="Choose a user..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{users.map((user) => (
|
||||
<SelectItem key={user.id} value={user.id}>
|
||||
{user.firstName} {user.lastName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Start Date */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="start-date">Start Date</Label>
|
||||
<input
|
||||
id="start-date"
|
||||
type="date"
|
||||
className="flex h-10 w-full rounded-md 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"
|
||||
value={dateRange.startDate}
|
||||
onChange={(e) =>
|
||||
onDateRangeChange({
|
||||
...dateRange,
|
||||
startDate: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* End Date */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="end-date">End Date</Label>
|
||||
<input
|
||||
id="end-date"
|
||||
type="date"
|
||||
className="flex h-10 w-full rounded-md 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"
|
||||
value={dateRange.endDate}
|
||||
onChange={(e) =>
|
||||
onDateRangeChange({
|
||||
...dateRange,
|
||||
endDate: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Preset Ranges */}
|
||||
<div className="space-y-2">
|
||||
<Label>Quick Select</Label>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePresetRange(7)}
|
||||
>
|
||||
7 Days
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePresetRange(30)}
|
||||
>
|
||||
30 Days
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePresetRange(90)}
|
||||
>
|
||||
90 Days
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { UserReport as UserReportType } from "@fitai/shared";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { WeeklyCheckInsCard } from "./WeeklyCheckInsCard";
|
||||
import { NutritionSummaryCard } from "./NutritionSummaryCard";
|
||||
import { HydrationSummaryCard } from "./HydrationSummaryCard";
|
||||
import { GoalsSummaryCard } from "./GoalsSummaryCard";
|
||||
import { RecommendationsCard } from "./RecommendationsCard";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Download } from "lucide-react";
|
||||
|
||||
interface UserReportProps {
|
||||
userId: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
}
|
||||
|
||||
export function UserReport({ userId, startDate, endDate }: UserReportProps) {
|
||||
const [report, setReport] = useState<UserReportType | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchReport();
|
||||
}, [userId, startDate, endDate]);
|
||||
|
||||
const fetchReport = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await fetch(
|
||||
`/api/reports/user/${userId}?startDate=${startDate}&endDate=${endDate}`,
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Failed to fetch report");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setReport(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to load report");
|
||||
console.error("Report fetch error:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportPDF = () => {
|
||||
if (!report) return;
|
||||
|
||||
const filename = `FitAI_Report_${report.user.firstName}_${report.user.lastName}_${startDate}_${endDate}.pdf`;
|
||||
const url = `/api/reports/user/${userId}?startDate=${startDate}&endDate=${endDate}&format=pdf`;
|
||||
|
||||
// Open in new tab to trigger download
|
||||
window.open(url, "_blank");
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-center h-64">
|
||||
<div className="text-lg text-gray-600">Loading report...</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-center h-64">
|
||||
<div className="text-lg text-red-600">{error}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (!report) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-center h-64">
|
||||
<div className="text-lg text-gray-600">No report data available</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Report Header */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<CardTitle className="text-2xl">
|
||||
{report.user.firstName} {report.user.lastName}
|
||||
</CardTitle>
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
{report.user.email} • {report.client?.membershipType || "N/A"}{" "}
|
||||
Member
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Report Period: {report.reportPeriod.startDate} to{" "}
|
||||
{report.reportPeriod.endDate}
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={handleExportPDF} variant="default">
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
Export PDF
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
{/* Report Sections */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<WeeklyCheckInsCard weeklyCheckIns={report.weeklyCheckIns} />
|
||||
<NutritionSummaryCard nutrition={report.nutrition} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<HydrationSummaryCard hydration={report.hydration} />
|
||||
<GoalsSummaryCard goals={report.goals} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6">
|
||||
<RecommendationsCard recommendations={report.recommendations} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import { WeeklyCheckInStats } from "@fitai/shared";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
BarChart,
|
||||
Bar,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
Legend,
|
||||
ResponsiveContainer,
|
||||
} from "recharts";
|
||||
|
||||
interface WeeklyCheckInsCardProps {
|
||||
weeklyCheckIns: WeeklyCheckInStats[];
|
||||
}
|
||||
|
||||
export function WeeklyCheckInsCard({
|
||||
weeklyCheckIns,
|
||||
}: WeeklyCheckInsCardProps) {
|
||||
const totalCheckIns = weeklyCheckIns.reduce(
|
||||
(sum, week) => sum + week.totalCheckIns,
|
||||
0,
|
||||
);
|
||||
const totalTimeMinutes = weeklyCheckIns.reduce(
|
||||
(sum, week) => sum + week.totalTimeMinutes,
|
||||
0,
|
||||
);
|
||||
const avgTimeMinutes =
|
||||
totalCheckIns > 0 ? Math.round(totalTimeMinutes / totalCheckIns) : 0;
|
||||
|
||||
const chartData = weeklyCheckIns.map((week) => ({
|
||||
week: week.weekStart,
|
||||
checkIns: week.totalCheckIns,
|
||||
timeMinutes: week.totalTimeMinutes,
|
||||
}));
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Weekly Check-ins</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{totalCheckIns}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Total Check-ins</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-green-600">
|
||||
{Math.floor(totalTimeMinutes / 60)}h {totalTimeMinutes % 60}m
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Total Time</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-purple-600">
|
||||
{avgTimeMinutes}m
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Avg Duration</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{chartData.length > 0 ? (
|
||||
<div className="h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={chartData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="week" />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
<Bar dataKey="checkIns" fill="#3c82e6" name="Check-ins" />
|
||||
<Bar dataKey="timeMinutes" fill="#10b981" name="Minutes" />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-64 flex items-center justify-center text-gray-500">
|
||||
No check-in data available
|
||||
</div>
|
||||
)}
|
||||
|
||||
{weeklyCheckIns.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-semibold">Weekly Breakdown</h4>
|
||||
<div className="space-y-1">
|
||||
{weeklyCheckIns.slice(-4).map((week) => (
|
||||
<div
|
||||
key={week.weekStart}
|
||||
className="flex justify-between items-center text-sm"
|
||||
>
|
||||
<span className="text-gray-600">
|
||||
{week.weekStart} - {week.weekEnd}
|
||||
</span>
|
||||
<span className="font-medium">
|
||||
{week.totalCheckIns} check-ins • {week.totalTimeMinutes} min
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface LabelProps
|
||||
extends React.LabelHTMLAttributes<HTMLLabelElement> {}
|
||||
|
||||
const Label = React.forwardRef<HTMLLabelElement, LabelProps>(
|
||||
({ className, ...props }, ref) => (
|
||||
<label
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
Label.displayName = "Label";
|
||||
|
||||
export { Label };
|
||||
@@ -0,0 +1,160 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||
import { Check, ChevronDown, ChevronUp } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Select = SelectPrimitive.Root;
|
||||
|
||||
const SelectGroup = SelectPrimitive.Group;
|
||||
|
||||
const SelectValue = SelectPrimitive.Value;
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
));
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
));
|
||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
));
|
||||
SelectScrollDownButton.displayName =
|
||||
SelectPrimitive.ScrollDownButton.displayName;
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = "popper", ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
));
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName;
|
||||
|
||||
const SelectLabel = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectLabel.displayName = SelectPrimitive.Label.displayName;
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
));
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName;
|
||||
|
||||
const SelectSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
};
|
||||
Reference in new issue
Block a user