fitaiProto/docs/TESTING_GUIDE.md
2026-03-19 03:37:15 +01:00

529 lines
12 KiB
Markdown

# FitAI Report Generation System - Testing Guide
## Overview
This document provides comprehensive testing procedures for the FitAI Report Generation System, covering:
- API endpoints
- Access control
- PDF generation
- Mobile-to-admin data flow
- Edge cases
## Prerequisites
1. **Admin App Running**
```bash
cd apps/admin
npm run dev
# Should be running on http://localhost:3000
```
2. **Database Populated**
- Ensure test users exist with different roles
- Ensure attendance, nutrition, and hydration data exists
## 1. API Endpoint Testing
### 1.1 Trainer-Client Assignment API
#### Test: Create Assignment
```bash
# As Admin
curl -X POST http://localhost:3000/api/trainer-client \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <ADMIN_TOKEN>" \
-d '{
"trainerId": "user_trainer_123",
"clientId": "user_client_456"
}'
```
**Expected Response (201):**
```json
{
"assignment": {
"id": "assignment_...",
"trainerId": "user_trainer_123",
"clientId": "user_client_456",
"assignedAt": "2024-01-15T...",
"isActive": true
}
}
```
#### Test: Get Assignments
```bash
# Get all assignments
curl http://localhost:3000/api/trainer-client \
-H "Authorization: Bearer <ADMIN_TOKEN>"
# Filter by trainer
curl "http://localhost:3000/api/trainer-client?trainerId=user_trainer_123" \
-H "Authorization: Bearer <ADMIN_TOKEN>"
```
#### Test: Delete Assignment
```bash
curl -X DELETE http://localhost:3000/api/trainer-client/<ASSIGNMENT_ID> \
-H "Authorization: Bearer <ADMIN_TOKEN>"
```
**Expected Response (200):**
```json
{
"success": true,
"message": "Assignment deactivated successfully"
}
```
### 1.2 Report Generation API
#### Test: Get JSON Report
```bash
curl "http://localhost:3000/api/reports/user/<USER_ID>?startDate=2024-01-01&endDate=2024-01-31" \
-H "Authorization: Bearer <TOKEN>"
```
**Expected Response (200):**
```json
{
"userId": "...",
"user": { ... },
"weeklyCheckIns": [ ... ],
"nutrition": { ... },
"hydration": { ... },
"goals": { ... },
"recommendations": { ... },
"generatedAt": "..."
}
```
#### Test: Get PDF Report
```bash
curl "http://localhost:3000/api/reports/user/<USER_ID>?startDate=2024-01-01&endDate=2024-01-31&format=pdf" \
-H "Authorization: Bearer <TOKEN>" \
--output report.pdf
```
**Validation:**
- File should download as `FitAI_Report_<Name>_<Dates>.pdf`
- File should be valid PDF (starts with `%PDF`)
- File should contain all sections
#### Test: Access Control
**As Client (own report only):**
```bash
# Should succeed - own report
curl "http://localhost:3000/api/reports/user/<CLIENT_ID>" \
-H "Authorization: Bearer <CLIENT_TOKEN>"
# Should fail - other's report
curl "http://localhost:3000/api/reports/user/<OTHER_ID>" \
-H "Authorization: Bearer <CLIENT_TOKEN>"
```
**Expected:** 403 Forbidden
**As Trainer (assigned clients only):**
```bash
# Should succeed - assigned client
curl "http://localhost:3000/api/reports/user/<ASSIGNED_CLIENT_ID>" \
-H "Authorization: Bearer <TRAINER_TOKEN>"
# Should fail - non-assigned client
curl "http://localhost:3000/api/reports/user/<NON_ASSIGNED_CLIENT_ID>" \
-H "Authorization: Bearer <TRAINER_TOKEN>"
```
**Expected:** 403 Forbidden
**As Admin (gym users only):**
```bash
# Should succeed - same gym
curl "http://localhost:3000/api/reports/user/<SAME_GYM_CLIENT_ID>" \
-H "Authorization: Bearer <ADMIN_TOKEN>"
# Should fail - different gym
curl "http://localhost:3000/api/reports/user/<DIFFERENT_GYM_CLIENT_ID>" \
-H "Authorization: Bearer <ADMIN_TOKEN>"
```
**Expected:** 403 Forbidden
### 1.3 Nutrition API
#### Test: Save Daily Nutrition
```bash
curl -X POST http://localhost:3000/api/nutrition \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <TOKEN>" \
-d '{
"date": "2024-01-15",
"totalCalories": 2100,
"calorieGoal": 2000,
"meals": [
{ "type": "breakfast", "name": "Oatmeal", "calories": 300 },
{ "type": "lunch", "name": "Salad", "calories": 500 }
]
}'
```
**Expected Response (200):**
```json
{
"id": "nutrition_...",
"userId": "...",
"date": "2024-01-15",
"totalCalories": 2100,
"calorieGoal": 2000
}
```
#### Test: Get Nutrition by Date
```bash
curl "http://localhost:3000/api/nutrition?date=2024-01-15" \
-H "Authorization: Bearer <TOKEN>"
```
#### Test: Get Nutrition Range
```bash
curl "http://localhost:3000/api/nutrition?startDate=2024-01-01&endDate=2024-01-31" \
-H "Authorization: Bearer <TOKEN>"
```
### 1.4 Hydration API
#### Test: Save Daily Hydration
```bash
curl -X POST http://localhost:3000/api/hydration \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <TOKEN>" \
-d '{
"date": "2024-01-15",
"totalWater": 2500,
"waterGoal": 2000,
"entries": [
{ "amount": 250, "time": "08:00" },
{ "amount": 500, "time": "10:30" }
]
}'
```
#### Test: Get Hydration
```bash
curl "http://localhost:3000/api/hydration?date=2024-01-15" \
-H "Authorization: Bearer <TOKEN>"
```
## 2. Web UI Testing
### 2.1 Reports Page
**URL:** `http://localhost:3000/reports`
**Test Scenarios:**
1. **Admin View**
- Should see all clients in dropdown
- Should be able to select any client
- Should see all report sections
- Should see "Export PDF" button
2. **Trainer View**
- Should only see assigned clients in dropdown
- Should see message if no clients assigned
- Should be able to generate reports for assigned clients
3. **Client View**
- Should only see own name in dropdown
- Should be auto-selected
- Should be able to view own report
### 2.2 Trainer-Client Assignments Page
**URL:** `http://localhost:3000/trainer-clients`
**Test Scenarios:**
1. **Create Assignment**
- Select trainer from dropdown
- Select client from dropdown
- Click "Assign"
- Should see new assignment in Active list
2. **Remove Assignment**
- Click remove button on assignment
- Confirm deletion
- Assignment should move to Inactive list
3. **Validation**
- Cannot assign trainer to non-trainer
- Cannot assign client to non-client
- Cannot create duplicate active assignments
## 3. ISO Week Calculations
### Test Week Boundaries
| Date | Monday | Sunday |
| ---------------- | ---------- | ---------- |
| 2024-01-01 (Mon) | 2024-01-01 | 2024-01-07 |
| 2024-01-02 (Tue) | 2024-01-01 | 2024-01-07 |
| 2024-01-07 (Sun) | 2024-01-01 | 2024-01-07 |
| 2024-01-08 (Mon) | 2024-01-08 | 2024-01-14 |
### Test Weekly Stats Calculation
**Test Data:**
- Monday: 2 check-ins, 120 minutes total
- Tuesday: 1 check-in, 60 minutes
- Wednesday: 0 check-ins
- Thursday: 3 check-ins, 180 minutes
- Friday: 2 check-ins, 100 minutes
- Saturday: 0 check-ins
- Sunday: 1 check-in, 45 minutes
**Expected Results:**
```typescript
{
weekStart: "2024-01-01",
weekEnd: "2024-01-07",
totalCheckIns: 9,
totalTimeMinutes: 505,
averageDurationMinutes: 63 // 505 / 8 (only completed sessions)
}
```
## 4. PDF Generation Testing
### Test: Generate PDF with All Sections
1. Navigate to Reports page
2. Select user with:
- At least 1 week of attendance data
- At least 3 days of nutrition data
- At least 3 days of hydration data
- At least 1 active goal
- At least 1 recommendation
3. Set date range to 30 days
4. Click "Export PDF"
5. Validate PDF contains:
- [ ] Header with "FitAI User Report"
- [ ] User information section
- [ ] Report period section
- [ ] Weekly check-ins table
- [ ] Nutrition summary with daily breakdown
- [ ] Hydration summary with daily breakdown
- [ ] Active goals with progress
- [ ] Completed goals
- [ ] Profile changes (if any)
- [ ] Recommendations
- [ ] Footer with page numbers
### Test: Generate PDF with No Data
1. Select user with no activity
2. Set date range to 30 days
3. Export PDF
4. Validate:
- [ ] All sections show "No data available"
- [ ] Charts/tables are empty
- [ ] PDF still generates successfully
### Test: Generate PDF with Large Date Range
1. Set date range to 90 days
2. Export PDF
3. Validate:
- [ ] PDF contains summary data (not all 90 days)
- [ ] Charts are readable
- [ ] No performance issues
## 5. Mobile-to-Admin Data Flow
### Test: Nutrition Data Flow
1. **Mobile App:**
```typescript
// Add nutrition data
await saveDailyNutrition({
date: "2024-01-15",
totalCalories: 2200,
calorieGoal: 2000,
meals: [...]
});
```
2. **Verify in Database:**
```sql
SELECT * FROM daily_nutrition
WHERE user_id = '<USER_ID>'
AND date = '2024-01-15';
```
3. **Verify in Admin Reports:**
- Navigate to Reports page
- Select same user
- Set date range to include 2024-01-15
- Check Nutrition Summary section
- Should show 2200 calories, 2000 goal
### Test: Hydration Data Flow
1. **Mobile App:**
```typescript
await saveDailyHydration({
date: "2024-01-15",
totalWater: 2500,
waterGoal: 2000,
entries: [...]
});
```
2. **Verify in Admin Reports:**
- Check Hydration Summary section
- Should show 2500ml, 2000ml goal
## 6. Edge Cases
### 6.1 Empty Data
- [ ] User with no attendance
- [ ] User with no nutrition
- [ ] User with no hydration
- [ ] User with no goals
- [ ] User with no recommendations
### 6.2 Invalid Inputs
- [ ] Invalid date format → 400 Bad Request
- [ ] Future dates → Should work (no validation)
- [ ] Date range > 1 year → Should work
- [ ] Missing userId → 400 Bad Request
- [ ] Non-existent userId → 404 Not Found
### 6.3 Access Control
- [ ] Expired token → 401 Unauthorized
- [ ] Invalid token → 401 Unauthorized
- [ ] User accessing another user → 403 Forbidden
- [ ] Deleted user → 404 Not Found
### 6.4 Performance
- [ ] 100 days of data → Should load < 5 seconds
- [ ] PDF with 100 days Should generate < 10 seconds
- [ ] Multiple concurrent requests Should handle gracefully
## 7. Automated Tests
Run automated tests:
```bash
cd apps/admin
# Run all tests
npm test
# Run specific test file
npx jest src/app/api/reports/__tests__/report-generation.test.ts
# Run with coverage
npm test -- --coverage
```
## 8. Troubleshooting
### Common Issues
1. **"Unauthorized" Error**
- Ensure Clerk authentication is working
- Check token is being passed correctly
- Verify user exists in database
2. **"Forbidden" Error**
- Check user role permissions
- For trainers: ensure assignment exists
- For admins: ensure same gym
3. **Empty Report Data**
- Check data exists in database
- Verify date range includes data dates
- Check API endpoints return data
4. **PDF Not Downloading**
- Check browser console for errors
- Ensure PDF generation completes
- Try different browser
## 9. Test Users
Create test users for manual testing:
```typescript
const testUsers = {
superAdmin: {
id: "user_test_superadmin",
email: "superadmin@test.com",
role: "superAdmin",
},
admin: {
id: "user_test_admin",
email: "admin@test.com",
role: "admin",
gymId: "gym_test",
},
trainer: {
id: "user_test_trainer",
email: "trainer@test.com",
role: "trainer",
gymId: "gym_test",
},
client: {
id: "user_test_client",
email: "client@test.com",
role: "client",
gymId: "gym_test",
},
};
```
## 10. Success Criteria
All tests should pass:
- [ ] Trainer-client CRUD operations work
- [ ] Role-based access control enforced
- [ ] Reports generate with all sections
- [ ] PDF export works correctly
- [ ] Mobile data syncs to admin
- [ ] ISO week calculations correct
- [ ] Edge cases handled gracefully
- [ ] Performance acceptable