# WEEK 9: Result Management & Analytics API Documentation

This document provides comprehensive documentation for all Week 9 endpoints with Postman cURL examples.

## Table of Contents
1. [Day 1-2: Batch Analytics](#day-1-2-batch-analytics)
2. [Day 3: Leaderboards](#day-3-leaderboards)
3. [Day 4: Excel Export](#day-4-excel-export)
4. [Day 5: Performance Trends](#day-5-performance-trends)

---

## Day 1-2: Batch Analytics

### Endpoint: Get Batch Analytics

**GET** `/api/v2/tutor/analytics/batch/{batch_id}/test/{test_id}`

Retrieves comprehensive analytics for a specific batch and test combination.

#### Features:
- Overall statistics (average, highest/lowest scores, pass percentage, completion rate)
- Score distribution (0-25%, 26-50%, 51-75%, 76-100%)
- Topic-wise performance with accuracy percentages
- Time analysis (average, fastest, slowest completion times)
- Results cached for 1 hour

#### Request Parameters:
- `batch_id` (path parameter, required): The batch/group ID
- `test_id` (path parameter, required): The test series ID

#### Headers:
```
Authorization: Bearer {your_auth_token}
Content-Type: application/json
```

#### cURL Example:
```bash
curl --location 'http://127.0.0.1:8000/api/v2/tutor/analytics/batch/5/test/12' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--header 'Accept: application/json'
```

#### Response Example:
```json
{
    "status": true,
    "message": "Analytics retrieved successfully",
    "data": {
        "batch_id": 5,
        "test_id": 12,
        "overall_statistics": {
            "total_participants": 45,
            "average_score": 72.5,
            "highest_score": 95.0,
            "lowest_score": 35.0,
            "pass_percentage": 82.22,
            "completion_rate": 95.56,
            "passed_students": 37,
            "failed_students": 8
        },
        "score_distribution": {
            "ranges": [
                {
                    "range": "0-25%",
                    "count": 2,
                    "percentage": 4.44
                },
                {
                    "range": "26-50%",
                    "count": 6,
                    "percentage": 13.33
                },
                {
                    "range": "51-75%",
                    "count": 18,
                    "percentage": 40.0
                },
                {
                    "range": "76-100%",
                    "count": 19,
                    "percentage": 42.22
                }
            ],
            "chart_labels": ["0-25%", "26-50%", "51-75%", "76-100%"],
            "chart_data": [2, 6, 18, 19]
        },
        "topic_wise_performance": {
            "topics": [
                {
                    "topic_name": "Algebra",
                    "accuracy": 75.5,
                    "total_questions": 120,
                    "correct_answers": 91
                },
                {
                    "topic_name": "Geometry",
                    "accuracy": 68.2,
                    "total_questions": 110,
                    "correct_answers": 75
                }
            ],
            "weak_topics": [
                {
                    "topic_name": "Trigonometry",
                    "accuracy": 45.3,
                    "total_questions": 95,
                    "correct_answers": 43
                }
            ],
            "chart_labels": ["Algebra", "Geometry", "Trigonometry"],
            "chart_data": [75.5, 68.2, 45.3]
        },
        "time_analysis": {
            "average_time_seconds": 2700,
            "average_time_formatted": "00:45:00",
            "fastest_time_seconds": 1800,
            "fastest_time_formatted": "00:30:00",
            "slowest_time_seconds": 4200,
            "slowest_time_formatted": "01:10:00"
        },
        "generated_at": "2025-01-14 10:30:00"
    }
}
```

---

## Day 3: Leaderboards

### Endpoint 1: Get Global Leaderboard

**GET** `/api/v2/tutor/leaderboard/test/{test_id}?limit=50`

Retrieves the global leaderboard for a specific test across all students.

#### Features:
- Ranked by score (highest first)
- Tie-breaker: faster completion time
- Shows current user's rank
- Pagination support (10, 20, 50, 100)
- Results cached for 30 minutes

#### Request Parameters:
- `test_id` (path parameter, required): The test series ID
- `limit` (query parameter, optional): Number of results (default: 50, options: 10, 20, 50, 100)

#### cURL Example:
```bash
curl --location 'http://127.0.0.1:8000/api/v2/tutor/leaderboard/test/12?limit=50' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--header 'Accept: application/json'
```

#### Response Example:
```json
{
    "status": true,
    "message": "Leaderboard retrieved successfully",
    "data": {
        "leaderboard": [
            {
                "rank": 1,
                "student_id": 123,
                "student_name": "John Doe",
                "score": 95.0,
                "obtained_marks": 95,
                "total_marks": 100,
                "time_taken_seconds": 2100,
                "time_taken": "00:35:00",
                "attempted_at": "2025-01-10 14:30:00"
            },
            {
                "rank": 2,
                "student_id": 456,
                "student_name": "Jane Smith",
                "score": 92.5,
                "obtained_marks": 92.5,
                "total_marks": 100,
                "time_taken_seconds": 2400,
                "time_taken": "00:40:00",
                "attempted_at": "2025-01-10 15:00:00"
            }
        ],
        "my_rank": 15,
        "total_participants": 120
    }
}
```

### Endpoint 2: Get Batch Leaderboard

**GET** `/api/v2/tutor/leaderboard/batch/{batch_id}/test/{test_id}?limit=50`

Retrieves the leaderboard for a specific batch and test.

#### Request Parameters:
- `batch_id` (path parameter, required): The batch/group ID
- `test_id` (path parameter, required): The test series ID
- `limit` (query parameter, optional): Number of results (default: 50, options: 10, 20, 50, 100)

#### cURL Example:
```bash
curl --location 'http://127.0.0.1:8000/api/v2/tutor/leaderboard/batch/5/test/12?limit=50' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--header 'Accept: application/json'
```

#### Response Example:
Same format as global leaderboard, but filtered to batch students only.

---

## Day 4: Excel Export

### Endpoint: Export Batch Results to Excel

**POST** `/api/v2/tutor/results/export-excel`

Generates an Excel file (.xlsx) with batch results and analytics.

#### Features:
- **Sheet 1**: Student results with rankings, scores, time taken, pass/fail status
- **Sheet 2**: Topic-wise analysis (if `include_analysis=true`)
- **Sheet 3**: Summary statistics and score distribution
- Color-coded formatting (green for pass, red for fail)
- Handles large datasets (1000+ students)

#### Request Body:
```json
{
    "batch_id": 5,
    "test_id": 12,
    "include_analysis": true
}
```

#### cURL Example:
```bash
curl --location 'http://127.0.0.1:8000/api/v2/tutor/results/export-excel' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--header 'Content-Type: application/json' \
--data '{
    "batch_id": 5,
    "test_id": 12,
    "include_analysis": true
}'
```

#### Response Example:
```json
{
    "status": true,
    "message": "Excel file generated successfully",
    "data": {
        "download_url": "http://127.0.0.1:8000/storage/exports/batch_5_test_12_results_1705234567.xlsx",
        "file_name": "batch_5_test_12_results_1705234567.xlsx",
        "file_path": "/home/user/pathshalaa_api/storage/app/public/exports/batch_5_test_12_results_1705234567.xlsx"
    }
}
```

#### Excel File Structure:

**Sheet 1: Student Results**
| Rank | Student Name | Roll No | Score (%) | Obtained Marks | Total Marks | Time Taken | Status |
|------|--------------|---------|-----------|----------------|-------------|------------|--------|
| 1    | John Doe     | 123     | 95.00     | 95             | 100         | 00:35:00   | Pass   |
| 2    | Jane Smith   | 456     | 92.50     | 92.5           | 100         | 00:40:00   | Pass   |

**Sheet 2: Topic Analysis**
| Topic Name | Total Questions | Correct Answers | Accuracy (%) |
|------------|-----------------|-----------------|--------------|
| Algebra    | 120             | 91              | 75.50        |
| Geometry   | 110             | 75              | 68.20        |

**Sheet 3: Summary**
- Test name and batch details
- Overall statistics
- Score distribution

---

## Day 5: Performance Trends

### Endpoint: Get Student Performance Trends

**GET** `/api/v2/tutor/trends/student/{student_id}?period=3months&batch_id=5`

Retrieves comprehensive performance trends for a student over time.

#### Features:
- Score progression (test-by-test)
- Topic-wise accuracy trends
- Time management trends
- Consistency score (standard deviation)
- Improvement rate (percentage change)
- Batch comparison (if batch_id provided)

#### Request Parameters:
- `student_id` (path parameter, required): The student's user ID
- `period` (query parameter, optional): Time period (options: `3months`, `6months`, `1year`, `all`, default: `3months`)
- `batch_id` (query parameter, optional): Batch ID for comparison with batch average

#### cURL Example:
```bash
curl --location 'http://127.0.0.1:8000/api/v2/tutor/trends/student/123?period=3months&batch_id=5' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--header 'Accept: application/json'
```

#### Response Example:
```json
{
    "status": true,
    "message": "Student trends retrieved successfully",
    "data": {
        "student_id": 123,
        "period": "3months",
        "date_range": {
            "start": "2024-10-14",
            "end": "2025-01-14"
        },
        "total_tests_taken": 12,
        "score_trend": {
            "data": [
                {
                    "test_date": "2024-10-15",
                    "test_name": "Unit 1 Test",
                    "score": 75.0,
                    "obtained_marks": 75,
                    "total_marks": 100
                },
                {
                    "test_date": "2024-11-05",
                    "test_name": "Unit 2 Test",
                    "score": 82.0,
                    "obtained_marks": 82,
                    "total_marks": 100
                },
                {
                    "test_date": "2024-12-10",
                    "test_name": "Unit 3 Test",
                    "score": 88.5,
                    "obtained_marks": 88.5,
                    "total_marks": 100
                }
            ],
            "chart_labels": ["2024-10-15", "2024-11-05", "2024-12-10"],
            "chart_data": [75.0, 82.0, 88.5]
        },
        "topic_trends": {
            "topics": {
                "Algebra": [65.0, 70.0, 75.0, 80.0],
                "Geometry": [80.0, 78.0, 85.0, 90.0],
                "Trigonometry": [55.0, 60.0, 65.0, 70.0]
            },
            "chart_data": {
                "Algebra": [65.0, 70.0, 75.0, 80.0],
                "Geometry": [80.0, 78.0, 85.0, 90.0],
                "Trigonometry": [55.0, 60.0, 65.0, 70.0]
            }
        },
        "time_trends": {
            "data": [
                {
                    "test_date": "2024-10-15",
                    "time_seconds": 3000,
                    "time_formatted": "00:50:00"
                },
                {
                    "test_date": "2024-11-05",
                    "time_seconds": 2700,
                    "time_formatted": "00:45:00"
                },
                {
                    "test_date": "2024-12-10",
                    "time_seconds": 2400,
                    "time_formatted": "00:40:00"
                }
            ],
            "chart_labels": ["2024-10-15", "2024-11-05", "2024-12-10"],
            "chart_data": [3000, 2700, 2400],
            "average_time": "00:45:00"
        },
        "consistency_score": {
            "score": 78.5,
            "standard_deviation": 8.2,
            "interpretation": "Moderately Consistent"
        },
        "improvement_rate": "+18.0%",
        "batch_comparison": {
            "batch_average": 72.5,
            "student_average": 81.8,
            "difference": 9.3,
            "performance": "Above Average"
        },
        "generated_at": "2025-01-14 10:30:00"
    }
}
```

#### Consistency Score Interpretation:
- **80-100**: Highly Consistent
- **60-79**: Moderately Consistent
- **40-59**: Variable Performance
- **0-39**: Inconsistent

---

## Error Responses

All endpoints return consistent error responses:

### 401 Unauthorized
```json
{
    "status": false,
    "message": "Unauthenticated."
}
```

### 404 Not Found
```json
{
    "status": false,
    "message": "Batch not found or you do not have permission to access it"
}
```

### 422 Validation Error
```json
{
    "status": false,
    "message": "Validation error",
    "errors": {
        "batch_id": ["The batch id field is required."]
    }
}
```

### 500 Internal Server Error
```json
{
    "status": false,
    "message": "Failed to retrieve analytics",
    "error": "Error details here"
}
```

---

## Caching Strategy

### Analytics Endpoint
- **Cache Duration**: 1 hour (3600 seconds)
- **Cache Key Format**: `analytics_batch_{batch_id}_test_{test_id}`
- **Refresh**: Automatic after cache expiration

### Leaderboard Endpoints
- **Cache Duration**: 30 minutes (1800 seconds)
- **Cache Key Format**:
  - Global: `leaderboard_global_test_{test_id}_limit_{limit}`
  - Batch: `leaderboard_batch_{batch_id}_test_{test_id}_limit_{limit}`
- **Refresh**: Automatic after cache expiration

---

## Testing Checklist

- [ ] Test analytics endpoint with valid batch and test IDs
- [ ] Test analytics with empty results (no students attempted test)
- [ ] Test global leaderboard with different limits (10, 20, 50, 100)
- [ ] Test batch leaderboard with valid batch ownership
- [ ] Test leaderboard with tie scenarios (same score, different times)
- [ ] Test Excel export with analysis enabled
- [ ] Test Excel export with analysis disabled
- [ ] Verify Excel file formatting and color coding
- [ ] Test trends with different periods (3months, 6months, 1year, all)
- [ ] Test trends with and without batch_id
- [ ] Verify cache functionality (check response times)
- [ ] Test permission controls (tutor can only access their own batches)
- [ ] Test with large datasets (1000+ students)

---

## Performance Optimization

All services use:
- **Efficient Aggregate Queries**: Minimizes database round trips
- **Eager Loading**: Prevents N+1 query problems
- **Caching**: Reduces computation for frequently accessed data
- **Indexed Queries**: Uses database indexes on foreign keys

---

## Chart Integration

The API responses are designed to be chart-ready for frontend integration:

### For Chart.js / Recharts:
```javascript
// Score Distribution
{
    labels: data.score_distribution.chart_labels,
    datasets: [{
        data: data.score_distribution.chart_data
    }]
}

// Score Trend
{
    labels: data.score_trend.chart_labels,
    datasets: [{
        data: data.score_trend.chart_data
    }]
}

// Topic Performance
{
    labels: data.topic_wise_performance.chart_labels,
    datasets: [{
        data: data.topic_wise_performance.chart_data
    }]
}
```

---

## Additional Notes

1. **Authentication**: All endpoints require Bearer token authentication via `auth:sanctum` middleware
2. **Authorization**: Tutors can only access batches they own
3. **Data Privacy**: Student data is only accessible to authorized tutors
4. **File Storage**: Excel exports are stored in `storage/app/public/exports/`
5. **Cleanup**: Consider implementing a scheduled job to delete old Excel exports

---

**Week 9 Implementation Complete! ✅**

All endpoints are production-ready with comprehensive error handling, caching, and optimization.
