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,52 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
|
||||
/**
|
||||
* GET /api/fitness-profile/history
|
||||
* Get fitness profile history for a user
|
||||
*
|
||||
* Query params:
|
||||
* - userId: string (required)
|
||||
* - startDate: YYYY-MM-DD (optional)
|
||||
* - endDate: YYYY-MM-DD (optional)
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { userId: authUserId } = await auth();
|
||||
if (!authUserId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const userId = searchParams.get("userId");
|
||||
const startDateStr = searchParams.get("startDate");
|
||||
const endDateStr = searchParams.get("endDate");
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json(
|
||||
{ error: "userId is required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Convert date strings to Date objects if provided
|
||||
const startDate = startDateStr ? new Date(startDateStr) : undefined;
|
||||
const endDate = endDateStr ? new Date(endDateStr) : undefined;
|
||||
|
||||
const db = await getDatabase();
|
||||
const history = await db.getFitnessProfileHistory(
|
||||
userId,
|
||||
startDate,
|
||||
endDate,
|
||||
);
|
||||
|
||||
return NextResponse.json({ history });
|
||||
} catch (error) {
|
||||
console.error("Get fitness profile history error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase();
|
||||
await ensureUserSynced(userId, db);
|
||||
|
||||
const body = await req.json();
|
||||
const { date, entries, totalWater, waterGoal } = body;
|
||||
|
||||
if (!date) {
|
||||
return NextResponse.json({ error: "Date is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if entry already exists for this date
|
||||
const existing = await db.getDailyHydration(userId, date);
|
||||
|
||||
let result;
|
||||
if (existing) {
|
||||
// Update existing entry
|
||||
result = await db.updateDailyHydration(existing.id, {
|
||||
entries,
|
||||
totalWater: totalWater ?? existing.totalWater,
|
||||
waterGoal: waterGoal ?? existing.waterGoal,
|
||||
});
|
||||
} else {
|
||||
// Create new entry
|
||||
result = await db.createDailyHydration({
|
||||
userId,
|
||||
date,
|
||||
entries: entries || [],
|
||||
totalWater: totalWater || 0,
|
||||
waterGoal: waterGoal || 2000,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
log.error("Failed to save hydration data", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase();
|
||||
await ensureUserSynced(userId, db);
|
||||
|
||||
const url = new URL(req.url);
|
||||
const date = url.searchParams.get("date");
|
||||
const startDate = url.searchParams.get("startDate");
|
||||
const endDate = url.searchParams.get("endDate");
|
||||
|
||||
// Single date query
|
||||
if (date) {
|
||||
const result = await db.getDailyHydration(userId, date);
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
|
||||
// Date range query
|
||||
if (startDate && endDate) {
|
||||
const results = await db.getDailyHydrationRange(
|
||||
userId,
|
||||
startDate,
|
||||
endDate,
|
||||
);
|
||||
return NextResponse.json(results);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Either 'date' or 'startDate' and 'endDate' are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
} catch (error) {
|
||||
log.error("Failed to fetch hydration data", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase();
|
||||
await ensureUserSynced(userId, db);
|
||||
|
||||
const url = new URL(req.url);
|
||||
const id = url.searchParams.get("id");
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "ID is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Verify ownership before deletion
|
||||
const existing = await db.getDailyHydrationById(id);
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (existing.userId !== userId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden: You can only delete your own hydration data" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const success = await db.deleteDailyHydration(id);
|
||||
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true });
|
||||
} else {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
} catch (error) {
|
||||
log.error("Failed to delete hydration data", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase();
|
||||
await ensureUserSynced(userId, db);
|
||||
|
||||
const body = await req.json();
|
||||
const {
|
||||
dailyNutritionId,
|
||||
mealType,
|
||||
foodName,
|
||||
calories,
|
||||
protein,
|
||||
carbs,
|
||||
fats,
|
||||
} = body;
|
||||
|
||||
if (!mealType || !foodName || calories === undefined) {
|
||||
return NextResponse.json(
|
||||
{ error: "mealType, foodName, and calories are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const result = await db.createMealEntry({
|
||||
userId,
|
||||
dailyNutritionId,
|
||||
mealType,
|
||||
foodName,
|
||||
calories,
|
||||
protein,
|
||||
carbs,
|
||||
fats,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
log.error("Failed to create meal entry", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase();
|
||||
await ensureUserSynced(userId, db);
|
||||
|
||||
const url = new URL(req.url);
|
||||
const date = url.searchParams.get("date");
|
||||
|
||||
if (!date) {
|
||||
return NextResponse.json(
|
||||
{ error: "date is required (YYYY-MM-DD format)" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const results = await db.getMealEntriesByDate(userId, date);
|
||||
return NextResponse.json(results);
|
||||
} catch (error) {
|
||||
log.error("Failed to fetch meal entries", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase();
|
||||
await ensureUserSynced(userId, db);
|
||||
|
||||
const url = new URL(req.url);
|
||||
const id = url.searchParams.get("id");
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "ID is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Verify ownership before deletion
|
||||
const existing = await db.getMealEntryById(id);
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (existing.userId !== userId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden: You can only delete your own meal entries" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const success = await db.deleteMealEntry(id);
|
||||
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true });
|
||||
} else {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
} catch (error) {
|
||||
log.error("Failed to delete meal entry", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase();
|
||||
await ensureUserSynced(userId, db);
|
||||
|
||||
const body = await req.json();
|
||||
const { date, meals, totalCalories, calorieGoal } = body;
|
||||
|
||||
if (!date) {
|
||||
return NextResponse.json({ error: "Date is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if entry already exists for this date
|
||||
const existing = await db.getDailyNutrition(userId, date);
|
||||
|
||||
let result;
|
||||
if (existing) {
|
||||
// Update existing entry
|
||||
result = await db.updateDailyNutrition(existing.id, {
|
||||
meals,
|
||||
totalCalories: totalCalories ?? existing.totalCalories,
|
||||
calorieGoal: calorieGoal ?? existing.calorieGoal,
|
||||
});
|
||||
} else {
|
||||
// Create new entry
|
||||
result = await db.createDailyNutrition({
|
||||
userId,
|
||||
date,
|
||||
meals: meals || [],
|
||||
totalCalories: totalCalories || 0,
|
||||
calorieGoal: calorieGoal || 2000,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
log.error("Failed to save nutrition data", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase();
|
||||
await ensureUserSynced(userId, db);
|
||||
|
||||
const url = new URL(req.url);
|
||||
const date = url.searchParams.get("date");
|
||||
const startDate = url.searchParams.get("startDate");
|
||||
const endDate = url.searchParams.get("endDate");
|
||||
|
||||
// Single date query
|
||||
if (date) {
|
||||
const result = await db.getDailyNutrition(userId, date);
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
|
||||
// Date range query
|
||||
if (startDate && endDate) {
|
||||
const results = await db.getDailyNutritionRange(
|
||||
userId,
|
||||
startDate,
|
||||
endDate,
|
||||
);
|
||||
return NextResponse.json(results);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Either 'date' or 'startDate' and 'endDate' are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
} catch (error) {
|
||||
log.error("Failed to fetch nutrition data", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const db = await getDatabase();
|
||||
await ensureUserSynced(userId, db);
|
||||
|
||||
const url = new URL(req.url);
|
||||
const id = url.searchParams.get("id");
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "ID is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Verify ownership before deletion
|
||||
const existing = await db.getDailyNutritionById(id);
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (existing.userId !== userId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden: You can only delete your own nutrition data" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const success = await db.deleteDailyNutrition(id);
|
||||
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true });
|
||||
} else {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
} catch (error) {
|
||||
log.error("Failed to delete nutrition data", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
/**
|
||||
* Report Generation API Tests
|
||||
*
|
||||
* Tests for /api/reports/user/[userId] endpoint
|
||||
*
|
||||
* Test Coverage:
|
||||
* 1. Access Control (client, trainer, admin, superAdmin)
|
||||
* 2. Data Aggregation (attendance, nutrition, hydration, goals)
|
||||
* 3. PDF Generation
|
||||
* 4. Date Range Validation
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeAll, afterAll } from "@jest/globals";
|
||||
|
||||
// Mock database
|
||||
const mockDatabase = {
|
||||
getUserById: jest.fn(),
|
||||
getClientByUserId: jest.fn(),
|
||||
getFitnessProfileByUserId: jest.fn(),
|
||||
getAttendanceByWeek: jest.fn(),
|
||||
getDailyNutritionRange: jest.fn(),
|
||||
getDailyHydrationRange: jest.fn(),
|
||||
getFitnessGoalsByUserId: jest.fn(),
|
||||
getFitnessProfileHistory: jest.fn(),
|
||||
getRecommendationsByUserId: jest.fn(),
|
||||
getTrainerClientAssignments: jest.fn(),
|
||||
};
|
||||
|
||||
// Mock user data
|
||||
const mockUsers = {
|
||||
client: {
|
||||
id: "user_client_123",
|
||||
email: "client@example.com",
|
||||
firstName: "John",
|
||||
lastName: "Client",
|
||||
role: "client",
|
||||
gymId: "gym_123",
|
||||
},
|
||||
trainer: {
|
||||
id: "user_trainer_456",
|
||||
email: "trainer@example.com",
|
||||
firstName: "Jane",
|
||||
lastName: "Trainer",
|
||||
role: "trainer",
|
||||
gymId: "gym_123",
|
||||
},
|
||||
admin: {
|
||||
id: "user_admin_789",
|
||||
email: "admin@example.com",
|
||||
firstName: "Admin",
|
||||
lastName: "User",
|
||||
role: "admin",
|
||||
gymId: "gym_123",
|
||||
},
|
||||
superAdmin: {
|
||||
id: "user_superadmin_000",
|
||||
email: "superadmin@example.com",
|
||||
firstName: "Super",
|
||||
lastName: "Admin",
|
||||
role: "superAdmin",
|
||||
gymId: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
describe("Report Generation API", () => {
|
||||
describe("Access Control", () => {
|
||||
it("should allow clients to view their own reports", async () => {
|
||||
const currentUser = mockUsers.client;
|
||||
const targetUserId = mockUsers.client.id;
|
||||
|
||||
// Users can always view their own reports
|
||||
const hasAccess = currentUser.id === targetUserId;
|
||||
expect(hasAccess).toBe(true);
|
||||
});
|
||||
|
||||
it("should allow trainers to view assigned client reports", async () => {
|
||||
const currentUser = mockUsers.trainer;
|
||||
const targetUserId = mockUsers.client.id;
|
||||
|
||||
// Mock assignment exists
|
||||
mockDatabase.getTrainerClientAssignments.mockResolvedValue([
|
||||
{
|
||||
trainerId: currentUser.id,
|
||||
clientId: targetUserId,
|
||||
isActive: true,
|
||||
},
|
||||
]);
|
||||
|
||||
const assignments = await mockDatabase.getTrainerClientAssignments(
|
||||
currentUser.id,
|
||||
);
|
||||
const assignment = assignments.find(
|
||||
(a: any) => a.clientId === targetUserId && a.isActive,
|
||||
);
|
||||
const hasAccess = !!assignment;
|
||||
|
||||
expect(hasAccess).toBe(true);
|
||||
});
|
||||
|
||||
it("should deny trainers access to non-assigned client reports", async () => {
|
||||
const currentUser = mockUsers.trainer;
|
||||
const targetUserId = "user_other_client_999";
|
||||
|
||||
mockDatabase.getTrainerClientAssignments.mockResolvedValue([]);
|
||||
|
||||
const assignments = await mockDatabase.getTrainerClientAssignments(
|
||||
currentUser.id,
|
||||
);
|
||||
const assignment = assignments.find(
|
||||
(a: any) => a.clientId === targetUserId && a.isActive,
|
||||
);
|
||||
const hasAccess = !!assignment;
|
||||
|
||||
expect(hasAccess).toBe(false);
|
||||
});
|
||||
|
||||
it("should allow admins to view clients in their gym", async () => {
|
||||
const currentUser = mockUsers.admin;
|
||||
const targetUser = { ...mockUsers.client, gymId: "gym_123" };
|
||||
|
||||
mockDatabase.getUserById.mockResolvedValue(targetUser);
|
||||
|
||||
const user = await mockDatabase.getUserById(targetUser.id);
|
||||
const hasAccess = user?.gymId === currentUser.gymId;
|
||||
|
||||
expect(hasAccess).toBe(true);
|
||||
});
|
||||
|
||||
it("should deny admins access to clients outside their gym", async () => {
|
||||
const currentUser = mockUsers.admin;
|
||||
const targetUser = { ...mockUsers.client, gymId: "gym_other_999" };
|
||||
|
||||
mockDatabase.getUserById.mockResolvedValue(targetUser);
|
||||
|
||||
const user = await mockDatabase.getUserById(targetUser.id);
|
||||
const hasAccess = user?.gymId === currentUser.gymId;
|
||||
|
||||
expect(hasAccess).toBe(false);
|
||||
});
|
||||
|
||||
it("should allow superAdmins to view any user", async () => {
|
||||
const currentUser = mockUsers.superAdmin;
|
||||
|
||||
// SuperAdmins bypass gym checks
|
||||
const hasAccess = currentUser.role === "superAdmin";
|
||||
|
||||
expect(hasAccess).toBe(true);
|
||||
});
|
||||
|
||||
it("should deny clients access to other users reports", async () => {
|
||||
const currentUser = mockUsers.client;
|
||||
const targetUserId = "user_other_123";
|
||||
|
||||
// Only own ID or specific permissions
|
||||
const hasAccess = currentUser.id === targetUserId;
|
||||
|
||||
expect(hasAccess).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Date Range Validation", () => {
|
||||
it("should accept valid date format YYYY-MM-DD", () => {
|
||||
const validDates = ["2024-01-01", "2024-12-31", "2024-06-15"];
|
||||
|
||||
validDates.forEach((date) => {
|
||||
const parsed = Date.parse(date);
|
||||
expect(isNaN(parsed)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("should reject invalid date formats", () => {
|
||||
const invalidDates = ["01-01-2024", "2024/01/01", "2024-1-1", "invalid"];
|
||||
|
||||
invalidDates.forEach((date) => {
|
||||
const parsed = Date.parse(date);
|
||||
expect(isNaN(parsed)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should default to last 30 days if no dates provided", () => {
|
||||
const endDate = new Date();
|
||||
const startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const daysDiff = Math.ceil(
|
||||
(endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24),
|
||||
);
|
||||
|
||||
expect(daysDiff).toBe(30);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Data Aggregation", () => {
|
||||
it("should aggregate weekly check-ins correctly", () => {
|
||||
const attendanceRecords = [
|
||||
{
|
||||
checkInTime: new Date("2024-01-02T10:00:00"),
|
||||
checkOutTime: new Date("2024-01-02T11:00:00"),
|
||||
type: "gym",
|
||||
},
|
||||
{
|
||||
checkInTime: new Date("2024-01-03T14:00:00"),
|
||||
checkOutTime: new Date("2024-01-03T15:30:00"),
|
||||
type: "gym",
|
||||
},
|
||||
{
|
||||
checkInTime: new Date("2024-01-04T09:00:00"),
|
||||
checkOutTime: null, // Still checked in
|
||||
type: "class",
|
||||
},
|
||||
];
|
||||
|
||||
const totalCheckIns = attendanceRecords.length;
|
||||
const completedCheckIns = attendanceRecords.filter(
|
||||
(r) => r.checkOutTime,
|
||||
).length;
|
||||
|
||||
expect(totalCheckIns).toBe(3);
|
||||
expect(completedCheckIns).toBe(2);
|
||||
});
|
||||
|
||||
it("should calculate total time spent correctly", () => {
|
||||
const attendanceRecords = [
|
||||
{
|
||||
checkInTime: new Date("2024-01-02T10:00:00"),
|
||||
checkOutTime: new Date("2024-01-02T11:30:00"), // 90 minutes
|
||||
},
|
||||
{
|
||||
checkInTime: new Date("2024-01-03T14:00:00"),
|
||||
checkOutTime: new Date("2024-01-03T15:00:00"), // 60 minutes
|
||||
},
|
||||
];
|
||||
|
||||
const totalMinutes = attendanceRecords.reduce((sum, record) => {
|
||||
if (record.checkOutTime) {
|
||||
const duration =
|
||||
record.checkOutTime.getTime() - record.checkInTime.getTime();
|
||||
return sum + Math.floor(duration / 60000);
|
||||
}
|
||||
return sum;
|
||||
}, 0);
|
||||
|
||||
expect(totalMinutes).toBe(150);
|
||||
});
|
||||
|
||||
it("should handle nutrition goal achievement correctly", () => {
|
||||
const nutritionRecords = [
|
||||
{ date: "2024-01-01", totalCalories: 2100, calorieGoal: 2000 },
|
||||
{ date: "2024-01-02", totalCalories: 1900, calorieGoal: 2000 },
|
||||
{ date: "2024-01-03", totalCalories: 2200, calorieGoal: 2000 },
|
||||
];
|
||||
|
||||
const daysMetGoal = nutritionRecords.filter((record) => {
|
||||
const lowerBound = record.calorieGoal * 0.9;
|
||||
const upperBound = record.calorieGoal * 1.1;
|
||||
return (
|
||||
record.totalCalories >= lowerBound &&
|
||||
record.totalCalories <= upperBound
|
||||
);
|
||||
}).length;
|
||||
|
||||
expect(daysMetGoal).toBe(3); // All within ±10%
|
||||
});
|
||||
|
||||
it("should handle hydration goal achievement correctly", () => {
|
||||
const hydrationRecords = [
|
||||
{ date: "2024-01-01", totalWater: 2500, waterGoal: 2000 }, // 125%
|
||||
{ date: "2024-01-02", totalWater: 1800, waterGoal: 2000 }, // 90%
|
||||
{ date: "2024-01-03", totalWater: 2000, waterGoal: 2000 }, // 100%
|
||||
];
|
||||
|
||||
const daysMetGoal = hydrationRecords.filter(
|
||||
(record) => record.totalWater / record.waterGoal >= 1,
|
||||
).length;
|
||||
|
||||
expect(daysMetGoal).toBe(2); // Days 1 and 3 meet goal
|
||||
});
|
||||
});
|
||||
|
||||
describe("Report Structure", () => {
|
||||
it("should include all required sections", () => {
|
||||
const requiredSections = [
|
||||
"userId",
|
||||
"user",
|
||||
"client",
|
||||
"fitnessProfile",
|
||||
"reportPeriod",
|
||||
"weeklyCheckIns",
|
||||
"nutrition",
|
||||
"hydration",
|
||||
"goals",
|
||||
"profileHistory",
|
||||
"recommendations",
|
||||
"generatedAt",
|
||||
];
|
||||
|
||||
// Mock report object
|
||||
const report = {
|
||||
userId: "user_123",
|
||||
user: {},
|
||||
client: null,
|
||||
fitnessProfile: null,
|
||||
reportPeriod: { startDate: "", endDate: "" },
|
||||
weeklyCheckIns: [],
|
||||
nutrition: {
|
||||
dailySummaries: [],
|
||||
averageDailyCalories: 0,
|
||||
totalDays: 0,
|
||||
daysMetGoal: 0,
|
||||
},
|
||||
hydration: {
|
||||
dailySummaries: [],
|
||||
averageDailyWater: 0,
|
||||
totalDays: 0,
|
||||
daysMetGoal: 0,
|
||||
},
|
||||
goals: {
|
||||
active: [],
|
||||
completed: [],
|
||||
totalActive: 0,
|
||||
totalCompleted: 0,
|
||||
averageProgress: 0,
|
||||
},
|
||||
profileHistory: [],
|
||||
recommendations: {
|
||||
accepted: [],
|
||||
rejected: [],
|
||||
pending: [],
|
||||
totalAccepted: 0,
|
||||
totalRejected: 0,
|
||||
totalPending: 0,
|
||||
},
|
||||
generatedAt: new Date(),
|
||||
};
|
||||
|
||||
requiredSections.forEach((section) => {
|
||||
expect(report).toHaveProperty(section);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ISO Week Calculations", () => {
|
||||
it("should start week on Monday", () => {
|
||||
// Test dates
|
||||
const dates = [
|
||||
{ date: "2024-01-01", expectedMonday: "2024-01-01" }, // Monday
|
||||
{ date: "2024-01-02", expectedMonday: "2024-01-01" }, // Tuesday
|
||||
{ date: "2024-01-03", expectedMonday: "2024-01-01" }, // Wednesday
|
||||
{ date: "2024-01-07", expectedMonday: "2024-01-01" }, // Sunday
|
||||
{ date: "2024-01-08", expectedMonday: "2024-01-08" }, // Monday (next week)
|
||||
];
|
||||
|
||||
dates.forEach(({ date, expectedMonday }) => {
|
||||
const current = new Date(date);
|
||||
const day = current.getDay();
|
||||
const diff = current.getDate() - day + (day === 0 ? -6 : 1);
|
||||
const monday = new Date(current);
|
||||
monday.setDate(diff);
|
||||
|
||||
const mondayStr = monday.toISOString().split("T")[0];
|
||||
expect(mondayStr).toBe(expectedMonday);
|
||||
});
|
||||
});
|
||||
|
||||
it("should end week on Sunday", () => {
|
||||
const monday = new Date("2024-01-01");
|
||||
const sunday = new Date(monday);
|
||||
sunday.setDate(sunday.getDate() + 6);
|
||||
|
||||
const sundayStr = sunday.toISOString().split("T")[0];
|
||||
expect(sundayStr).toBe("2024-01-07");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,425 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import log from "@/lib/logger";
|
||||
import type {
|
||||
UserReport,
|
||||
WeeklyCheckInStats,
|
||||
NutritionSummary,
|
||||
HydrationSummary,
|
||||
GoalSummary,
|
||||
ProfileChangeSummary,
|
||||
RecommendationSummary,
|
||||
AttendanceType,
|
||||
} from "@fitai/shared";
|
||||
import { ATTENDANCE_TYPES } from "@fitai/shared";
|
||||
import { generateReportPDFBase64 } from "@/lib/pdf/report-helpers";
|
||||
|
||||
/**
|
||||
* GET /api/reports/user/[userId]
|
||||
* Generate a comprehensive user report
|
||||
*
|
||||
* Query params:
|
||||
* - userId: string (required) - Target user ID
|
||||
* - startDate: YYYY-MM-DD (optional, default: 30 days ago)
|
||||
* - endDate: YYYY-MM-DD (optional, default: today)
|
||||
*
|
||||
* Access Control:
|
||||
* - Admins: Can generate reports for any user in their gym
|
||||
* - Trainers: Can generate reports for their assigned clients only
|
||||
* - Users: Can only generate reports for themselves
|
||||
*/
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ userId: string }> },
|
||||
) {
|
||||
try {
|
||||
const { userId: clerkUserId } = await auth();
|
||||
if (!clerkUserId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(clerkUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
const { userId: targetUserId } = await params;
|
||||
|
||||
// Access Control Check
|
||||
const hasAccess = await checkReportAccess(currentUser, targetUserId, db);
|
||||
if (!hasAccess) {
|
||||
return NextResponse.json(
|
||||
{ error: "You don't have permission to view this report" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
// Parse date range from query params
|
||||
const { searchParams } = new URL(request.url);
|
||||
const endDate =
|
||||
searchParams.get("endDate") || new Date().toISOString().split("T")[0];
|
||||
const startDate =
|
||||
searchParams.get("startDate") ||
|
||||
new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.split("T")[0];
|
||||
const format = searchParams.get("format") || "json";
|
||||
|
||||
// Validate dates
|
||||
if (isNaN(Date.parse(startDate)) || isNaN(Date.parse(endDate))) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid date format. Use YYYY-MM-DD" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch all user data
|
||||
const [user, client, fitnessProfile] = await Promise.all([
|
||||
db.getUserById(targetUserId),
|
||||
db.getClientByUserId(targetUserId),
|
||||
db.getFitnessProfileByUserId(targetUserId),
|
||||
]);
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Aggregate data in parallel
|
||||
const [
|
||||
nutritionRecords,
|
||||
hydrationRecords,
|
||||
fitnessGoals,
|
||||
profileHistory,
|
||||
recommendations,
|
||||
] = await Promise.all([
|
||||
db.getDailyNutritionRange(targetUserId, startDate, endDate),
|
||||
db.getDailyHydrationRange(targetUserId, startDate, endDate),
|
||||
db.getFitnessGoalsByUserId(targetUserId),
|
||||
db.getFitnessProfileHistory(
|
||||
targetUserId,
|
||||
new Date(startDate),
|
||||
new Date(endDate),
|
||||
),
|
||||
db.getRecommendationsByUserId(targetUserId),
|
||||
]);
|
||||
|
||||
// Process and aggregate data
|
||||
const weeklyCheckIns = await processWeeklyCheckIns(
|
||||
db,
|
||||
targetUserId,
|
||||
startDate,
|
||||
endDate,
|
||||
);
|
||||
const nutrition = processNutrition(nutritionRecords);
|
||||
const hydration = processHydration(hydrationRecords);
|
||||
const goals = processGoals(fitnessGoals);
|
||||
const profileChanges = processProfileHistory(profileHistory);
|
||||
const recs = processRecommendations(recommendations);
|
||||
|
||||
const report: UserReport = {
|
||||
userId: targetUserId,
|
||||
user,
|
||||
client,
|
||||
fitnessProfile,
|
||||
reportPeriod: {
|
||||
startDate,
|
||||
endDate,
|
||||
},
|
||||
weeklyCheckIns,
|
||||
nutrition,
|
||||
hydration,
|
||||
goals,
|
||||
profileHistory: profileChanges,
|
||||
recommendations: recs,
|
||||
generatedAt: new Date(),
|
||||
};
|
||||
|
||||
// Return PDF if requested
|
||||
if (format === "pdf") {
|
||||
try {
|
||||
const pdfBase64 = generateReportPDFBase64(report);
|
||||
const pdfBuffer = Buffer.from(pdfBase64, "base64");
|
||||
|
||||
return new NextResponse(pdfBuffer, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": `attachment; filename="FitAI_Report_${report.user.firstName}_${report.user.lastName}_${startDate}_${endDate}.pdf"`,
|
||||
"Content-Length": pdfBuffer.length.toString(),
|
||||
},
|
||||
});
|
||||
} catch (pdfError) {
|
||||
log.error("Failed to generate PDF", pdfError);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to generate PDF" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json(report);
|
||||
} catch (error) {
|
||||
log.error("Failed to generate user report", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current user has access to view the target user's report
|
||||
*/
|
||||
async function checkReportAccess(
|
||||
currentUser: { id: string; role: string; gymId?: string },
|
||||
targetUserId: string,
|
||||
db: Awaited<ReturnType<typeof getDatabase>>,
|
||||
): Promise<boolean> {
|
||||
// Users can always view their own reports
|
||||
if (currentUser.id === targetUserId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Admins can view any user's report in their gym
|
||||
if (currentUser.role === "admin" || currentUser.role === "superAdmin") {
|
||||
const targetUser = await db.getUserById(targetUserId);
|
||||
if (!targetUser) return false;
|
||||
|
||||
// SuperAdmins can view all users
|
||||
if (currentUser.role === "superAdmin") return true;
|
||||
|
||||
// Admins can only view users in their gym
|
||||
if (currentUser.gymId && targetUser.gymId === currentUser.gymId) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Trainers can only view reports for their assigned clients
|
||||
if (currentUser.role === "trainer") {
|
||||
const assignments = await db.getTrainerClientAssignments(currentUser.id);
|
||||
const assignment = assignments.find(
|
||||
(a) => a.clientId === targetUserId && a.isActive,
|
||||
);
|
||||
return !!assignment;
|
||||
}
|
||||
|
||||
// Regular users cannot view other users' reports
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process attendance records into weekly check-in stats
|
||||
*/
|
||||
async function processWeeklyCheckIns(
|
||||
db: Awaited<ReturnType<typeof getDatabase>>,
|
||||
userId: string,
|
||||
startDate: string,
|
||||
endDate: string,
|
||||
): Promise<WeeklyCheckInStats[]> {
|
||||
const weeks: WeeklyCheckInStats[] = [];
|
||||
|
||||
// Generate all weeks in the range
|
||||
const current = new Date(startDate);
|
||||
const end = new Date(endDate);
|
||||
|
||||
while (current <= end) {
|
||||
// Get Monday of current week (ISO week)
|
||||
const monday = new Date(current);
|
||||
const day = monday.getDay();
|
||||
const diff = monday.getDate() - day + (day === 0 ? -6 : 1);
|
||||
monday.setDate(diff);
|
||||
|
||||
const weekStart = monday.toISOString().split("T")[0];
|
||||
const sunday = new Date(monday);
|
||||
sunday.setDate(sunday.getDate() + 6);
|
||||
const weekEnd = sunday.toISOString().split("T")[0];
|
||||
|
||||
weeks.push({
|
||||
weekStart,
|
||||
weekEnd,
|
||||
totalCheckIns: 0,
|
||||
totalTimeMinutes: 0,
|
||||
averageDurationMinutes: 0,
|
||||
checkInsByType: ATTENDANCE_TYPES.map((type) => ({ type, count: 0 })),
|
||||
});
|
||||
|
||||
current.setDate(current.getDate() + 7);
|
||||
}
|
||||
|
||||
// Fetch attendance for each week and aggregate
|
||||
for (let i = 0; i < weeks.length; i++) {
|
||||
const week = weeks[i];
|
||||
const attendanceRecords = await db.getAttendanceByWeek(
|
||||
userId,
|
||||
new Date(week.weekStart),
|
||||
);
|
||||
|
||||
// Filter records to only include those within the week
|
||||
const weekStartDate = new Date(week.weekStart);
|
||||
const weekEndDate = new Date(week.weekEnd);
|
||||
weekEndDate.setHours(23, 59, 59, 999);
|
||||
|
||||
const filteredRecords = attendanceRecords.filter((record) => {
|
||||
const checkInTime = new Date(record.checkInTime);
|
||||
return checkInTime >= weekStartDate && checkInTime <= weekEndDate;
|
||||
});
|
||||
|
||||
week.totalCheckIns = filteredRecords.length;
|
||||
|
||||
// Calculate time spent
|
||||
for (const record of filteredRecords) {
|
||||
if (record.checkOutTime) {
|
||||
const checkIn = new Date(record.checkInTime);
|
||||
const checkOut = new Date(record.checkOutTime);
|
||||
const durationMs = checkOut.getTime() - checkIn.getTime();
|
||||
const durationMinutes = Math.floor(durationMs / 60000);
|
||||
week.totalTimeMinutes += durationMinutes;
|
||||
}
|
||||
|
||||
// Count by type
|
||||
const typeIndex = week.checkInsByType.findIndex(
|
||||
(t) => t.type === record.type,
|
||||
);
|
||||
if (typeIndex !== -1) {
|
||||
week.checkInsByType[typeIndex].count++;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate average duration
|
||||
week.averageDurationMinutes =
|
||||
week.totalCheckIns > 0
|
||||
? Math.round(week.totalTimeMinutes / week.totalCheckIns)
|
||||
: 0;
|
||||
}
|
||||
|
||||
return weeks.sort((a, b) => a.weekStart.localeCompare(b.weekStart));
|
||||
}
|
||||
|
||||
/**
|
||||
* Process nutrition records into summaries
|
||||
*/
|
||||
function processNutrition(records: any[]): UserReport["nutrition"] {
|
||||
const dailySummaries: NutritionSummary[] = records.map((record) => ({
|
||||
date: record.date,
|
||||
totalCalories: record.totalCalories,
|
||||
calorieGoal: record.calorieGoal,
|
||||
caloriesDelta: record.totalCalories - record.calorieGoal,
|
||||
mealsCount: record.meals?.length || 0,
|
||||
}));
|
||||
|
||||
const totalDays = dailySummaries.length;
|
||||
const totalCalories = dailySummaries.reduce(
|
||||
(sum, day) => sum + day.totalCalories,
|
||||
0,
|
||||
);
|
||||
const averageDailyCalories =
|
||||
totalDays > 0 ? Math.round(totalCalories / totalDays) : 0;
|
||||
|
||||
// Count days where calories were within ±10% of goal
|
||||
const daysMetGoal = dailySummaries.filter((day) => {
|
||||
const lowerBound = day.calorieGoal * 0.9;
|
||||
const upperBound = day.calorieGoal * 1.1;
|
||||
return day.totalCalories >= lowerBound && day.totalCalories <= upperBound;
|
||||
}).length;
|
||||
|
||||
return {
|
||||
dailySummaries,
|
||||
averageDailyCalories,
|
||||
totalDays,
|
||||
daysMetGoal,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Process hydration records into summaries
|
||||
*/
|
||||
function processHydration(records: any[]): UserReport["hydration"] {
|
||||
const dailySummaries: HydrationSummary[] = records.map((record) => ({
|
||||
date: record.date,
|
||||
totalWater: record.totalWater,
|
||||
waterGoal: record.waterGoal,
|
||||
hydrationPercentage:
|
||||
record.waterGoal > 0
|
||||
? Math.round((record.totalWater / record.waterGoal) * 100)
|
||||
: 0,
|
||||
}));
|
||||
|
||||
const totalDays = dailySummaries.length;
|
||||
const totalWater = dailySummaries.reduce(
|
||||
(sum, day) => sum + day.totalWater,
|
||||
0,
|
||||
);
|
||||
const averageDailyWater =
|
||||
totalDays > 0 ? Math.round(totalWater / totalDays) : 0;
|
||||
|
||||
// Count days where water goal was met (>= 100%)
|
||||
const daysMetGoal = dailySummaries.filter(
|
||||
(day) => day.hydrationPercentage >= 100,
|
||||
).length;
|
||||
|
||||
return {
|
||||
dailySummaries,
|
||||
averageDailyWater,
|
||||
totalDays,
|
||||
daysMetGoal,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Process fitness goals into summaries
|
||||
*/
|
||||
function processGoals(goals: any[]): GoalSummary {
|
||||
const active = goals.filter((g) => g.status === "active");
|
||||
const completed = goals.filter((g) => g.status === "completed");
|
||||
|
||||
const averageProgress =
|
||||
active.length > 0
|
||||
? Math.round(
|
||||
active.reduce((sum, g) => sum + g.progress, 0) / active.length,
|
||||
)
|
||||
: 0;
|
||||
|
||||
return {
|
||||
active,
|
||||
completed,
|
||||
totalActive: active.length,
|
||||
totalCompleted: completed.length,
|
||||
averageProgress,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Process fitness profile history into summaries
|
||||
*/
|
||||
function processProfileHistory(history: any[]): ProfileChangeSummary[] {
|
||||
return history.map((record) => ({
|
||||
changeType: record.changeType,
|
||||
fieldName: record.fieldName,
|
||||
previousValue: record.previousValue,
|
||||
newValue: record.newValue,
|
||||
changedAt: record.changedAt,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Process recommendations into summaries
|
||||
*/
|
||||
function processRecommendations(recommendations: any[]): RecommendationSummary {
|
||||
const accepted = recommendations.filter((r) => r.status === "accepted");
|
||||
const rejected = recommendations.filter((r) => r.status === "rejected");
|
||||
const pending = recommendations.filter((r) => r.status === "pending");
|
||||
|
||||
return {
|
||||
accepted,
|
||||
rejected,
|
||||
pending,
|
||||
totalAccepted: accepted.length,
|
||||
totalRejected: rejected.length,
|
||||
totalPending: pending.length,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
/**
|
||||
* DELETE /api/trainer-client/[id]
|
||||
* Delete (deactivate) a trainer-client assignment
|
||||
*/
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { userId: authUserId } = await auth();
|
||||
if (!authUserId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(authUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Only admins can delete assignments
|
||||
if (currentUser.role !== "admin" && currentUser.role !== "superAdmin") {
|
||||
return NextResponse.json(
|
||||
{ error: "Only admins can remove trainer-client assignments" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
// Get all assignments for the trainer to find the one with this ID
|
||||
// Note: We need to find the assignment ID, not the trainer or client ID
|
||||
// For now, we'll deactivate by finding the assignment through the trainer
|
||||
// This is a simplified approach - in production you'd want a direct getById method
|
||||
|
||||
const trainerAssignments = await db.getTrainerClientAssignments(
|
||||
currentUser.id,
|
||||
);
|
||||
const assignment = trainerAssignments.find((a) => a.id === id);
|
||||
|
||||
if (!assignment) {
|
||||
// Check if any trainer has this assignment
|
||||
const allAssignments = await db.getTrainerClientAssignments("");
|
||||
const foundAssignment = allAssignments.find((a) => a.id === id);
|
||||
|
||||
if (!foundAssignment) {
|
||||
return NextResponse.json(
|
||||
{ error: "Assignment not found" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
// Deactivate the assignment
|
||||
await db.deactivateTrainerClientAssignment(id);
|
||||
|
||||
log.info("Trainer-client assignment deactivated", {
|
||||
assignmentId: id,
|
||||
deactivatedBy: currentUser.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: "Assignment deactivated successfully",
|
||||
});
|
||||
}
|
||||
|
||||
// Deactivate the assignment
|
||||
const result = await db.deactivateTrainerClientAssignment(id);
|
||||
|
||||
if (!result) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to deactivate assignment" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
log.info("Trainer-client assignment deactivated", {
|
||||
assignmentId: id,
|
||||
deactivatedBy: currentUser.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: "Assignment deactivated successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
log.error("Failed to delete trainer-client assignment", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import log from "@/lib/logger";
|
||||
|
||||
/**
|
||||
* GET /api/trainer-client
|
||||
* Get trainer-client assignments
|
||||
*
|
||||
* Query params:
|
||||
* - trainerId: string (optional) - Filter by trainer
|
||||
* - clientId: string (optional) - Filter by client
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { userId: authUserId } = await auth();
|
||||
if (!authUserId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(authUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Only admins and superadmins can view all assignments
|
||||
if (currentUser.role !== "admin" && currentUser.role !== "superAdmin") {
|
||||
return NextResponse.json(
|
||||
{ error: "Only admins can view trainer-client assignments" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const trainerId = searchParams.get("trainerId");
|
||||
const clientId = searchParams.get("clientId");
|
||||
|
||||
let assignments;
|
||||
|
||||
if (trainerId) {
|
||||
assignments = await db.getTrainerClientAssignments(trainerId);
|
||||
// Filter by clientId if provided
|
||||
if (clientId) {
|
||||
assignments = assignments.filter((a) => a.clientId === clientId);
|
||||
}
|
||||
} else {
|
||||
// Get all assignments (for admins, filtered by gym)
|
||||
assignments = await db.getTrainerClientAssignments("");
|
||||
// TODO: Filter by gym once gymId is properly set
|
||||
}
|
||||
|
||||
return NextResponse.json({ assignments });
|
||||
} catch (error) {
|
||||
log.error("Failed to get trainer-client assignments", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/trainer-client
|
||||
* Create a new trainer-client assignment
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { userId: authUserId } = await auth();
|
||||
if (!authUserId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(authUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Only admins can create assignments
|
||||
if (currentUser.role !== "admin" && currentUser.role !== "superAdmin") {
|
||||
return NextResponse.json(
|
||||
{ error: "Only admins can assign trainers to clients" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { trainerId, clientId } = body;
|
||||
|
||||
if (!trainerId || !clientId) {
|
||||
return NextResponse.json(
|
||||
{ error: "trainerId and clientId are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Verify trainer exists and has trainer role
|
||||
const trainer = await db.getUserById(trainerId);
|
||||
if (!trainer) {
|
||||
return NextResponse.json({ error: "Trainer not found" }, { status: 404 });
|
||||
}
|
||||
if (trainer.role !== "trainer" && trainer.role !== "admin") {
|
||||
return NextResponse.json(
|
||||
{ error: "User must be a trainer or admin" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Verify client exists
|
||||
const client = await db.getUserById(clientId);
|
||||
if (!client) {
|
||||
return NextResponse.json({ error: "Client not found" }, { status: 404 });
|
||||
}
|
||||
if (client.role !== "client") {
|
||||
return NextResponse.json(
|
||||
{ error: "User must be a client" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Check if assignment already exists
|
||||
const existingAssignments = await db.getTrainerClientAssignments(trainerId);
|
||||
const existingAssignment = existingAssignments.find(
|
||||
(a) => a.clientId === clientId && a.isActive,
|
||||
);
|
||||
if (existingAssignment) {
|
||||
return NextResponse.json(
|
||||
{ error: "Trainer is already assigned to this client" },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
// Create the assignment
|
||||
const assignment = await db.createTrainerClientAssignment({
|
||||
trainerId,
|
||||
clientId,
|
||||
assignedAt: new Date(),
|
||||
assignedBy: currentUser.id,
|
||||
isActive: true,
|
||||
});
|
||||
|
||||
log.info("Trainer-client assignment created", {
|
||||
trainerId,
|
||||
clientId,
|
||||
assignedBy: currentUser.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({ assignment }, { status: 201 });
|
||||
} catch (error) {
|
||||
log.error("Failed to create trainer-client assignment", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
/**
|
||||
* GET /api/users/me
|
||||
* Get current authenticated user's information
|
||||
*/
|
||||
export async function GET() {
|
||||
try {
|
||||
const { userId: clerkUserId } = await auth();
|
||||
if (!clerkUserId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const user = await ensureUserSynced(clerkUserId, db);
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ user });
|
||||
} catch (error) {
|
||||
console.error("Failed to get current user:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { UserReport } from "@/components/reports/UserReport";
|
||||
import { ReportFilters } from "@/components/reports/ReportFilters";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
|
||||
export default function ReportsPage() {
|
||||
const [selectedUserId, setSelectedUserId] = useState<string>("");
|
||||
const [dateRange, setDateRange] = useState<{
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
}>({
|
||||
startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.split("T")[0],
|
||||
endDate: new Date().toISOString().split("T")[0],
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="container mx-auto px-4 py-8 space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-3xl font-bold text-gray-900">User Reports</h1>
|
||||
</div>
|
||||
|
||||
<ReportFilters
|
||||
selectedUserId={selectedUserId}
|
||||
onUserChange={setSelectedUserId}
|
||||
dateRange={dateRange}
|
||||
onDateRangeChange={setDateRange}
|
||||
/>
|
||||
|
||||
{selectedUserId ? (
|
||||
<UserReport
|
||||
userId={selectedUserId}
|
||||
startDate={dateRange.startDate}
|
||||
endDate={dateRange.endDate}
|
||||
/>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-center h-64">
|
||||
<p className="text-gray-500 text-lg">
|
||||
Select a user to view their report
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { User, TrainerClientAssignment } from "@fitai/shared";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Plus, Trash2, UserCheck, UserX } from "lucide-react";
|
||||
|
||||
export default function TrainerClientsPage() {
|
||||
const [trainers, setTrainers] = useState<User[]>([]);
|
||||
const [clients, setClients] = useState<User[]>([]);
|
||||
const [assignments, setAssignments] = useState<
|
||||
(TrainerClientAssignment & { trainer?: User; client?: User })[]
|
||||
>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [selectedTrainer, setSelectedTrainer] = useState<string>("");
|
||||
const [selectedClient, setSelectedClient] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// Fetch trainers
|
||||
const trainersRes = await fetch("/api/users?role=trainer");
|
||||
if (trainersRes.ok) {
|
||||
const trainersData = await trainersRes.json();
|
||||
setTrainers(trainersData.users || []);
|
||||
}
|
||||
|
||||
// Fetch clients
|
||||
const clientsRes = await fetch("/api/users?role=client");
|
||||
if (clientsRes.ok) {
|
||||
const clientsData = await clientsRes.json();
|
||||
setClients(clientsData.users || []);
|
||||
}
|
||||
|
||||
// Fetch all assignments
|
||||
const assignmentsRes = await fetch("/api/trainer-client");
|
||||
if (assignmentsRes.ok) {
|
||||
const assignmentsData = await assignmentsRes.json();
|
||||
// Enrich assignments with user data
|
||||
const enrichedAssignments = await Promise.all(
|
||||
(assignmentsData.assignments || []).map(
|
||||
async (assignment: TrainerClientAssignment) => {
|
||||
const trainer = trainers.find(
|
||||
(t: User) => t.id === assignment.trainerId,
|
||||
);
|
||||
const client = clients.find(
|
||||
(c: User) => c.id === assignment.clientId,
|
||||
);
|
||||
return { ...assignment, trainer, client };
|
||||
},
|
||||
),
|
||||
);
|
||||
setAssignments(enrichedAssignments);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch data:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAssign = async () => {
|
||||
if (!selectedTrainer || !selectedClient) {
|
||||
alert("Please select both a trainer and a client");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/trainer-client", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
trainerId: selectedTrainer,
|
||||
clientId: selectedClient,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
alert("Assignment created successfully!");
|
||||
setSelectedTrainer("");
|
||||
setSelectedClient("");
|
||||
fetchData(); // Refresh
|
||||
} else {
|
||||
const error = await response.json();
|
||||
alert(error.error || "Failed to create assignment");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to create assignment:", error);
|
||||
alert("Failed to create assignment");
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveAssignment = async (id: string) => {
|
||||
if (!confirm("Are you sure you want to remove this assignment?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/trainer-client/${id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
alert("Assignment removed successfully!");
|
||||
fetchData(); // Refresh
|
||||
} else {
|
||||
const error = await response.json();
|
||||
alert(error.error || "Failed to remove assignment");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to remove assignment:", error);
|
||||
alert("Failed to remove assignment");
|
||||
}
|
||||
};
|
||||
|
||||
const getActiveAssignments = () => assignments.filter((a) => a.isActive);
|
||||
const getInactiveAssignments = () => assignments.filter((a) => !a.isActive);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="text-lg">Loading...</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="container mx-auto px-4 py-8 space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-3xl font-bold text-gray-900">
|
||||
Trainer-Client Assignments
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{/* Create Assignment Form */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Assign Trainer to Client</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Select Trainer</label>
|
||||
<Select
|
||||
value={selectedTrainer}
|
||||
onValueChange={setSelectedTrainer}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Choose a trainer..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{trainers.map((trainer) => (
|
||||
<SelectItem key={trainer.id} value={trainer.id}>
|
||||
{trainer.firstName} {trainer.lastName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Select Client</label>
|
||||
<Select
|
||||
value={selectedClient}
|
||||
onValueChange={setSelectedClient}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Choose a client..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{clients.map((client) => (
|
||||
<SelectItem key={client.id} value={client.id}>
|
||||
{client.firstName} {client.lastName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-end">
|
||||
<Button onClick={handleAssign} className="w-full">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Assign
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Active Assignments */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-center">
|
||||
<CardTitle>Active Assignments</CardTitle>
|
||||
<Badge variant="default">{getActiveAssignments().length}</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{getActiveAssignments().length === 0 ? (
|
||||
<p className="text-gray-500 text-center py-8">
|
||||
No active assignments
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{getActiveAssignments().map((assignment) => (
|
||||
<div
|
||||
key={assignment.id}
|
||||
className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50"
|
||||
>
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<UserCheck className="w-4 h-4 text-green-600" />
|
||||
<span className="font-medium">
|
||||
{assignment.trainer?.firstName}{" "}
|
||||
{assignment.trainer?.lastName}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-gray-400">→</span>
|
||||
<span>
|
||||
{assignment.client?.firstName}{" "}
|
||||
{assignment.client?.lastName}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-xs text-gray-500">
|
||||
Assigned{" "}
|
||||
{new Date(assignment.assignedAt).toLocaleDateString()}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveAssignment(assignment.id)}
|
||||
>
|
||||
<UserX className="w-4 h-4 text-red-600" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Inactive Assignments */}
|
||||
{getInactiveAssignments().length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-center">
|
||||
<CardTitle className="text-gray-500">
|
||||
Inactive Assignments
|
||||
</CardTitle>
|
||||
<Badge variant="secondary">
|
||||
{getInactiveAssignments().length}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{getInactiveAssignments().map((assignment) => (
|
||||
<div
|
||||
key={assignment.id}
|
||||
className="flex items-center justify-between p-4 border rounded-lg bg-gray-50 opacity-60"
|
||||
>
|
||||
<div className="flex items-center space-x-4">
|
||||
<span className="font-medium text-gray-600">
|
||||
{assignment.trainer?.firstName}{" "}
|
||||
{assignment.trainer?.lastName}
|
||||
</span>
|
||||
<span className="text-gray-400">→</span>
|
||||
<span className="text-gray-600">
|
||||
{assignment.client?.firstName}{" "}
|
||||
{assignment.client?.lastName}
|
||||
</span>
|
||||
</div>
|
||||
<Badge variant="secondary">Inactive</Badge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user