> ## Documentation Index
> Fetch the complete documentation index at: https://docs.criar.in/llms.txt
> Use this file to discover all available pages before exploring further.

# Attendance Module

> SKOLE-ATND — Attendance Module

**Module ID:** `SKOLE-ATND` | **Version:** 1.0 | **Status:** Activ\
**Products:** Parent App (read-only) · Teacher App (mark/edit) · Web App (report)

***

## 1. Overview

| Field              | Value                                                                                                                                                                         |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Module Name**    | Attendance                                                                                                                                                                    |
| **Module Code**    | ATND                                                                                                                                                                          |
| **Business Value** | Allows parents to monitor their child's daily attendance history. Teachers mark and edit daily attendance records. Admins can view attendance reports through the web portal. |

### Scope In

* Parent: view attendance records per child per month/date range
* Teacher: mark present/absent/late, update existing records, view class attendance
* Web Admin: view school-wide attendance, filter by grade/date

### Scope Out

* SMS/FCM notification on absence (planned, not implemented)
* Bulk import from external timetabling system

***

## 2. Requirements

### Functional Requirements (FR)

*What the module must DO — actions, behaviors, and outcomes.*

* **SKOLE-ATND-FR001:** The module shall allow parents to view attendance history for their child by roll number for the current month.
* **SKOLE-ATND-FR002:** The module shall display attendance details including date, status (present, absent, late, excused), and check-in/check-out times.
* **SKOLE-ATND-FR003:** The module shall enable teachers to mark or update attendance records for individual students.
* **SKOLE-ATND-FR004:** The module shall allow teachers to filter attendance records by grade and date.
* **SKOLE-ATND-FR005:** The module shall scope all attendance records and queries strictly to the `skole_id`.
* **SKOLE-ATND-FR006:** The module shall allow web admins to view an attendance summary per student across the school.

### Non-Functional Requirements (NFR)

*How well the module must do it — performance, security, and reliability.*

* **SKOLE-ATND-NFR001:** The module shall behave securely by enforcing data isolation, ensuring parents can only read their own child's attendance via JWT verification.
* **SKOLE-ATND-NFR002:** The module shall perform authentication checks requiring a valid JWT for every attendance-related query.

### Constraints

*Rules and boundaries — tech choices and platform restrictions.*

* **C001:** We must use a relational database (PostgreSQL) because attendance records are strictly linked to the `students` and `schools` tables.
* **C002:** We must maintain the `skole_id` as the primary multi-tenancy key in the `student_attendance` table to ensure data separation.

***

## 3. Sub-modules / Backlog

| ID                 | Sub-module                  | Priority | Status | Estimate | Linked FR   |
| ------------------ | --------------------------- | -------- | ------ | -------- | ----------- |
| `SKOLE-ATND-SM001` | Parent attendance viewer    | P0       | Done   | 1d       | FR001–FR002 |
| `SKOLE-ATND-SM002` | Teacher attendance marking  | P0       | Done   | 3d       | FR003–FR004 |
| `SKOLE-ATND-SM003` | Web admin attendance report | P1       | Done   | 2d       | FR005–FR006 |

***

## 4. Logical Implementation

### Attendance Status State Machine

```text theme={null}
[No Record] ──mark present──→ [Present]
[No Record] ──mark absent───→ [Absent]
[Present]   ──edit──────────→ [Absent | Late | Excused]
[Absent]    ──edit──────────→ [Present | Late | Excused]
```

Fields: `attendance_status` (present/absent/late/excused), `availability_status` (in-school/away), `checkedIn_at`, `CheckedOut_at`

### Parent API Flow

```text theme={null}
GET /parent-app/attendance?roll_no=<roll_no>
  ├─ JWT → extract skole_id
  ├─ Query student_attendance WHERE skole_id = jwt.skole_id AND student_id matched from roll_no
  └─ Return records sorted by date DESC
```

### Teacher API Flow

```text theme={null}
GET /teachers-app/attendance?skole_id=&grade=&date=
POST /teachers-app/attendance { student_id, date, status, ... }
PUT  /teachers-app/attendance/:id { status, ... }
```

### Error Handling

| Scenario           | HTTP | Message                       |
| ------------------ | ---- | ----------------------------- |
| Missing `roll_no`  | 400  | "roll\_no is required"        |
| Missing `skole_id` | 400  | "skole\_id is required"       |
| Record not found   | 404  | "Attendance record not found" |

***

## 5. UI Requirements

### Parent App — AttendanceScreen

| ID                 | Screen           | Route         | Description                                               |
| ------------------ | ---------------- | ------------- | --------------------------------------------------------- |
| `SKOLE-ATND-UI001` | AttendanceScreen | `/attendance` | Monthly calendar view with color-coded attendance per day |

**UI States:**

* **Loading:** skeleton calendar
* **Empty:** "No attendance records for this month"
* **Error:** retry button with error toast

**Key Components:**

| ID                 | Component            | Props                                         |
| ------------------ | -------------------- | --------------------------------------------- |
| `SKOLE-ATND-UC001` | `AttendanceCalendar` | `records[]`, `selectedMonth`, `onMonthChange` |
| `SKOLE-ATND-UC002` | `AttendanceLegend`   | — (shows color key)                           |
| `SKOLE-ATND-UC003` | `ChildSelector`      | `children[]`, `selectedChild`, `onChange`     |

### Teacher App — AttendanceScreen

| ID                 | Screen           | Route         | Description                                                          |
| ------------------ | ---------------- | ------------- | -------------------------------------------------------------------- |
| `SKOLE-ATND-UI002` | AttendanceScreen | `/attendance` | Date-picker + student list with attendance status toggle per student |

**Key Components:**

| ID                 | Component              | Props                                 |
| ------------------ | ---------------------- | ------------------------------------- |
| `SKOLE-ATND-UC004` | `StudentAttendanceRow` | `student`, `status`, `onStatusChange` |
| `SKOLE-ATND-UC005` | `DatePicker`           | `selected`, `onChange`                |
| `SKOLE-ATND-UC006` | `GradeFilter`          | `grades[]`, `selected`, `onChange`    |
| `SKOLE-ATND-UC007` | `BulkSubmitButton`     | `onSubmit`, `loading`                 |

### Web App — Attendance Page

| ID                 | Screen          | Route                  | Description                                            |
| ------------------ | --------------- | ---------------------- | ------------------------------------------------------ |
| `SKOLE-ATND-UI003` | Attendance Page | `/:skoleId/attendance` | Table view with filters for grade, student, date range |

***

## 6. Conditional Expressions

| ID                 | Expression                        | Trigger                    | True Action         | False Action         |
| ------------------ | --------------------------------- | -------------------------- | ------------------- | -------------------- |
| `SKOLE-ATND-CE001` | `attendance_status === 'present'` | Calendar cell render       | Green cell          | Check other statuses |
| `SKOLE-ATND-CE002` | `attendance_status === 'absent'`  | Calendar cell render       | Red cell            | Check late/excused   |
| `SKOLE-ATND-CE003` | `attendance_status === 'late'`    | Calendar cell render       | Amber cell          | Show excused color   |
| `SKOLE-ATND-CE004` | `roll_no` absent in query         | GET /parent-app/attendance | Return 400          | Proceed with query   |
| `SKOLE-ATND-CE005` | `records.length === 0`            | Parent app screen          | Show empty state    | Render calendar      |
| `SKOLE-ATND-CE006` | `selectedChild` changes           | Parent app                 | Re-fetch attendance | —                    |

***

## 7. Internal Module Connections

| Direction   | Module         | Data / Event                                       | Condition               |
| ----------- | -------------- | -------------------------------------------------- | ----------------------- |
| ATND → AUTH | Authentication | JWT `skole_id` used to scope query                 | Every request           |
| ATND → STUD | Students       | `student_id` foreign key links to `students`       | Every attendance record |
| DASH → ATND | Dashboard      | Summary attendance stats shown on parent dashboard | On dashboard load       |

***

## 8. External Connections

| ID                 | Service             | Purpose                         | Failure Behavior |
| ------------------ | ------------------- | ------------------------------- | ---------------- |
| `SKOLE-ATND-EX001` | PostgreSQL (Prisma) | Read/write `student_attendance` | 500 error        |

***

## 9. Database Tables

| ID                 | Table                | Role                      |
| ------------------ | -------------------- | ------------------------- |
| `SKOLE-ATND-TB001` | `student_attendance` | Daily records per student |

### `student_attendance` Schema

| Column                | Type         | Notes                       |
| --------------------- | ------------ | --------------------------- |
| `id`                  | Int PK       | Auto-increment              |
| `skole_id`            | VarChar(15)  | School tenant key           |
| `student_id`          | Int          | FK → students.id            |
| `date`                | Date         | Attendance date             |
| `attendance_status`   | VarChar(20)  | present/absent/late/excused |
| `availability_status` | VarChar(100) | in-school/away              |
| `checkedIn_at`        | Timestamp    | Check-in time               |
| `CheckedOut_at`       | Timestamp    | Check-out time              |
| `created_at`          | Timestamp    | Record creation             |
| `updated_at`          | Timestamp    | Last update                 |

***

## 10. API Endpoints Summary

| ID        | Method | Route                                    | Auth | Description                    |
| --------- | ------ | ---------------------------------------- | ---- | ------------------------------ |
| PARENT-01 | GET    | `/parent-app/attendance`                 | JWT  | GET child's attendance records |
| PARENT-02 | GET    | `/parent-app/attendance/:studentId`      | JWT  | Get specific child's detail    |
| PARENT-03 | GET    | `/parent-app/attendance/reports/summary` | JWT  | Attendance summary report      |
| PARENT-04 | GET    | `/parent-app/attendance/reports/monthly` | JWT  | Monthly attendance report      |
| TEACH-01  | POST   | `/teachers-app/attendance`               | JWT  | Mark attendance for students   |
| TEACH-02  | PUT    | `/teachers-app/attendance/:id`           | JWT  | Edit attendance record         |
| TEACH-03  | GET    | `/teachers-app/attendance`               | JWT  | Get class attendance list      |
| TEACH-04  | POST   | `/teachers-app/attendance/bulk-upload`   | JWT  | Bulk upload attendance         |
| TEACH-05  | GET    | `/teachers-app/attendance/reports`       | JWT  | Attendance reports             |
| ADMIN-01  | POST   | `/web-app/attendance`                    | JWT  | Admin: create record           |
| ADMIN-02  | GET    | `/web-app/attendance`                    | JWT  | Admin: list attendance         |
| ADMIN-03  | PUT    | `/web-app/attendance/:id`                | JWT  | Admin: update record           |
| ADMIN-04  | POST   | `/web-app/attendance/bulk-upload`        | JWT  | Admin: bulk upload             |
| ADMIN-05  | GET    | `/web-app/attendance/reports`            | JWT  | Admin: view reports            |

***

* Pagination limit: max 100 records

### PARENT-01: List Child's Attendance

#### Section 1: Endpoint Summary

Returns paginated list of attendance records for a parent's child, with filtering by date range and status.

#### Section 2: HTTP Details

* **HTTP Method:** GET
* **Endpoint URL:** `/parent-app/attendance`
* **Authentication:** JWT Bearer Token (Parent)
* **Rate Limit:** 100 requests per minute

#### Section 4: Query Parameters

| Parameter  | Type    | Required | Default     | Description                            |
| ---------- | ------- | -------- | ----------- | -------------------------------------- |
| studentId  | UUID    | No       | First child | Filter by child                        |
| from\_date | Date    | No       | 30 days ago | Start date (ISO 8601)                  |
| to\_date   | Date    | No       | Today       | End date (ISO 8601)                    |
| status     | String  | No       | -           | Filter: present, absent, late, excused |
| take       | Integer | No       | 20          | Page size                              |
| skip       | Integer | No       | 0           | Offset                                 |

#### Section 5: Request Body Schema

Empty (GET request)

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "data": {
    "records": [
      {
        "id": "UUID",
        "student_id": "UUID",
        "date": "2026-03-16",
        "attendance_status": "present",
        "availability_status": "in-school",
        "checkedIn_at": "2026-03-16T09:00:00.000Z",
        "checkedOut_at": "2026-03-16T15:30:00.000Z"
      }
    ],
    "pagination": {
      "total": 45,
      "take": 20,
      "skip": 0
    },
    "statistics": {
      "present": 35,
      "absent": 5,
      "late": 4,
      "excused": 1,
      "attendance_percentage": 87.5
    }
  }
}
```

#### Section 7: Error Responses

**401 - Unauthorized**

```json theme={null}
{
  "status": "error",
  "code": "UNAUTHORIZED",
  "message": "Invalid or expired JWT token"
}
```

**404 - Student Not Found**

```json theme={null}
{
  "status": "error",
  "code": "NOT_FOUND",
  "message": "Student not found or no access"
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const getChildAttendance = async (token, filters = {}) => {
  const params = new URLSearchParams({
    take: filters.take || 20,
    skip: filters.skip || 0,
    from_date: filters.from_date || new Date(Date.now() - 30*24*60*60*1000).toISOString().split('T')[0],
    to_date: filters.to_date || new Date().toISOString().split('T')[0],
    ...filters
  });

  const response = await fetch(
    `https://api.skole.com/v1/parent-app/attendance?${params}`,
    {
      method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );

  const data = await response.json();
  if (data.status === 'success') {
    return data.data;
  }
  throw new Error(data.message);
};

// Usage
const records = await getChildAttendance(token, {
  from_date: '2026-03-01',
  to_date: '2026-03-31'
});
```

**Python:**

```python theme={null}
from datetime import datetime, timedelta

def get_child_attendance(token: str, student_id: str = None) -> dict:
    url = 'https://api.skole.com/v1/parent-app/attendance'
    headers = {'Authorization': f'Bearer {token}'}
    
    today = datetime.now().date()
    thirty_days_ago = today - timedelta(days=30)
    
    params = {
        'from_date': str(thirty_days_ago),
        'to_date': str(today),
        'take': 20,
        'skip': 0
    }
    
    if student_id:
        params['studentId'] = student_id
    
    response = requests.get(url, headers=headers, params=params)
    data = response.json()
    
    if data['status'] == 'success':
        return data['data']
    raise Exception(data['message'])

# Usage
records = get_child_attendance(token)
```

**cURL:**

```bash theme={null}
curl -X GET \
  'https://api.skole.com/v1/parent-app/attendance?from_date=2026-03-01&to_date=2026-03-31' \
  -H 'Authorization: Bearer YOUR_TOKEN_HERE'
```

#### Section 9: Database Context

**Tables:**

* student\_attendance (primary)
* students (join for validation)

**Query:**

```sql theme={null}
SELECT sa.* FROM student_attendance sa
JOIN students s ON sa.student_id = s.id
WHERE s.parent_id = ? AND s.skole_id = ? 
  AND sa.date >= ? AND sa.date <= ?
  AND (? IS NULL OR sa.attendance_status = ?)
ORDER BY sa.date DESC
LIMIT ? OFFSET ?
```

**Indices:** (parent\_id, date), (student\_id, date), skole\_id

#### Section 10: Business Logic & Validations

* Parent\_id from JWT must own the student
* Date range max: 90 days
* Status enum validation
* Pagination limit: max 100 records

#### Section 11: Related Endpoints

* **GET** `/parent-app/attendance/:studentId` - Individual detail
* **GET** `/parent-app/attendance/reports/summary` - Summary stats
* **GET** `/parent-app/attendance/reports/monthly` - Monthly view

#### Section 12: Response Summary Table

| Status | Scenario     | Error Code   | Message           |
| ------ | ------------ | ------------ | ----------------- |
| 200 ✅  | Success      | -            | Records retrieved |
| 401 ❌  | Unauthorized | UNAUTHORIZED | Invalid token     |
| 404 ❌  | Not found    | NOT\_FOUND   | Student not found |

***

### PARENT-02: Get Child's Attendance Detail

#### Section 1: Endpoint Summary

Get detailed attendance record for a specific date including check-in/out times.

#### Section 2: HTTP Details

* **HTTP Method:** GET
* **Endpoint URL:** `/parent-app/attendance/:studentId`
* **Authentication:** JWT (Parent)

#### Section 3: Path Parameters

| Parameter | Type | Required | Description      |
| --------- | ---- | -------- | ---------------- |
| studentId | UUID | Yes      | Child/Student ID |

#### Section 4: Query Parameters

| Parameter | Type | Required | Description                       |
| --------- | ---- | -------- | --------------------------------- |
| date      | Date | No       | Specific date (defaults to today) |

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "data": {
    "id": "UUID",
    "student_id": "UUID",
    "date": "2026-03-16",
    "attendance_status": "present",
    "availability_status": "in-school",
    "checkedIn_at": "2026-03-16T09:00:00.000Z",
    "checkedOut_at": "2026-03-16T15:30:00.000Z",
    "duration_hours": 6.5,
    "notes": "Normal day",
    "created_at": "2026-03-16T09:05:00.000Z"
  }
}
```

#### Section 7: Error Responses

**404 - No Record**

```json theme={null}
{
  "status": "error",
  "code": "NOT_FOUND",
  "message": "No attendance record for this date"
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const getChildDetailAttendance = async (token, studentId, date = null) => {
  const params = new URLSearchParams();
  if (date) params.append('date', date);

  const response = await fetch(
    `https://api.skole.com/v1/parent-app/attendance/${studentId}?${params}`,
    {
      method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );

  const data = await response.json();
  return data.data;
};
```

#### Section 12: Response Summary Table

| Status | Scenario  | Error Code |
| ------ | --------- | ---------- |
| 200 ✅  | Success   | -          |
| 404 ❌  | No record | NOT\_FOUND |

***

### PARENT-03: Attendance Summary Report

#### Section 1: Endpoint Summary

Returns monthly/yearly attendance summary with statistics like percentage, present/absent counts.

#### Section 2: HTTP Details

* **HTTP Method:** GET
* **Endpoint URL:** `/parent-app/attendance/reports/summary`
* **Authentication:** JWT (Parent)

#### Section 4: Query Parameters

| Parameter | Type    | Required | Description             |
| --------- | ------- | -------- | ----------------------- |
| studentId | UUID    | No       | Filter by child         |
| month     | Integer | No       | Month 1-12              |
| year      | Integer | No       | Year (default: current) |

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "data": {
    "period": "2026-03",
    "total_school_days": 20,
    "present": 18,
    "absent": 2,
    "late": 0,
    "excused": 0,
    "percentage": 90,
    "trend": "improving"
  }
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const getAttendanceSummary = async (token, month = null, year = null) => {
  const params = new URLSearchParams();
  if (month) params.append('month', month);
  if (year) params.append('year', year);

  const response = await fetch(
    `https://api.skole.com/v1/parent-app/attendance/reports/summary?${params}`,
    {
      method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );

  return (await response.json()).data;
};
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 200 ✅  | Success  | -          |

***

### PARENT-04: Monthly Attendance Report

#### Section 1: Endpoint Summary

Returns calendar view of attendance data for the full month.

#### Section 2: HTTP Details

* **HTTP Method:** GET
* **Endpoint URL:** `/parent-app/attendance/reports/monthly`
* **Authentication:** JWT (Parent)

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "data": {
    "month": 3,
    "year": 2026,
    "days": [
      {
        "date": "2026-03-16",
        "status": "present",
        "checkedIn": "09:00",
        "checkedOut": "15:30"
      }
    ]
  }
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const getMonthlyReport = async (token) => {
  const response = await fetch(
    'https://api.skole.com/v1/parent-app/attendance/reports/monthly',
    {
      method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );

  return (await response.json()).data;
};
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 200 ✅  | Success  | -          |

***

### TEACH-01: Mark Attendance

#### Section 1: Endpoint Summary

Teacher marks attendance for students in their class. Supports single or batch marking with status and timestamps.

#### Section 2: HTTP Details

* **HTTP Method:** POST
* **Endpoint URL:** `/teachers-app/attendance`
* **Authentication:** JWT Bearer Token (Staff)

#### Section 5: Request Body Schema

```json theme={null}
{
  "records": [
    {
      "student_id*": "UUID",
      "date*": "Date (ISO 8601)",
      "attendance_status*": "Enum: present, absent, late, excused",
      "checkedIn_at": "Timestamp (optional)",
      "checkedOut_at": "Timestamp (optional)",
      "notes": "String (optional)"
    }
  ]
}
```

#### Section 6: Response Schema (Success - 201)

```json theme={null}
{
  "status": "success",
  "message": "45 attendance records marked",
  "data": {
    "created": 45,
    "failed": 0,
    "failures": []
  }
}
```

#### Section 7: Error Responses

**400 - Invalid Status**

```json theme={null}
{
  "status": "error",
  "code": "INVALID_STATUS",
  "message": "Status must be one of: present, absent, late, excused"
}
```

**409 - Records Exist**

```json theme={null}
{
  "status": "error",
  "code": "RECORDS_EXIST",
  "message": "Some attendance records already exist for this date"
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const markAttendance = async (token, records) => {
  const response = await fetch(
    'https://api.skole.com/v1/teachers-app/attendance',
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ records })
    }
  );

  const data = await response.json();
  console.log(`Marked ${data.data.created} students`);
  return data.data;
};

// Usage
await markAttendance(token, [
  {
    student_id: 'uuid1',
    date: '2026-03-16',
    attendance_status: 'present',
    checkedIn_at: '2026-03-16T09:00:00Z'
  },
  {
    student_id: 'uuid2',
    date: '2026-03-16',
    attendance_status: 'absent'
  }
]);
```

**Python:**

```python theme={null}
def mark_attendance(token: str, records: list) -> dict:
    url = 'https://api.skole.com/v1/teachers-app/attendance'
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    
    response = requests.post(url, headers=headers, json={'records': records})
    data = response.json()
    
    if data['status'] == 'success':
        print(f"Marked {data['data']['created']} students")
        return data['data']
    raise Exception(data['message'])
```

#### Section 9: Database Context

**Tables:**

* student\_attendance (insert new records)
* staff\_student (verify assignment)

**Transaction:** All-or-nothing insert with conflict detection

#### Section 10: Business Logic & Validations

**Validation:**

* Status from enum: present, absent, late, excused
* Student must be in teacher's class (staff\_student check)
* Date must be school day (not weekend/holiday)
* No duplicate records for same student+date

#### Section 11: Related Endpoints

* **PUT** `/teachers-app/attendance/:id` - Edit record
* **GET** `/teachers-app/attendance` - View records
* **POST** `/teachers-app/attendance/bulk-upload` - Bulk import

#### Section 12: Response Summary Table

| Status | Scenario | Error Code      | Message        |
| ------ | -------- | --------------- | -------------- |
| 201 ✅  | Success  | -               | Records marked |
| 400 ❌  | Invalid  | INVALID\_STATUS | Status invalid |
| 409 ❌  | Conflict | RECORDS\_EXIST  | Records exist  |

***

### TEACH-02: Edit Attendance Record

#### Section 1: Endpoint Summary

Teacher updates an individual attendance record (status, times, notes).

#### Section 2: HTTP Details

* **HTTP Method:** PUT
* **Endpoint URL:** `/teachers-app/attendance/:id`
* **Authentication:** JWT (Staff)

#### Section 5: Request Body Schema

```json theme={null}
{
  "attendance_status": "Enum",
  "checkedIn_at": "Timestamp",
  "checkedOut_at": "Timestamp",
  "notes": "String"
}
```

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "message": "Record updated",
  "data": {
    "id": "UUID",
    "updated_at": "2026-03-16T10:30:45.000Z"
  }
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const updateAttendance = async (token, recordId, updates) => {
  const response = await fetch(
    `https://api.skole.com/v1/teachers-app/attendance/${recordId}`,
    {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(updates)
    }
  );

  return (await response.json()).status === 'success';
};
```

#### Section 12: Response Summary Table

| Status | Scenario  | Error Code |
| ------ | --------- | ---------- |
| 200 ✅  | Success   | -          |
| 404 ❌  | Not found | NOT\_FOUND |

***

### TEACH-03: List Class Attendance

#### Section 1: Endpoint Summary

Teacher retrieves attendance records for their assigned class with filtering by date.

#### Section 2: HTTP Details

* **HTTP Method:** GET
* **Endpoint URL:** `/teachers-app/attendance`
* **Authentication:** JWT (Staff)

#### Section 4: Query Parameters

| Parameter  | Type | Required | Description      |
| ---------- | ---- | -------- | ---------------- |
| date       | Date | No       | Single day       |
| class\_id  | UUID | No       | Filter by class  |
| from\_date | Date | No       | Date range start |
| to\_date   | Date | No       | Date range end   |

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "data": {
    "records": [
      {
        "id": "UUID",
        "student_id": "UUID",
        "student_name": "Arjun Kumar",
        "roll_no": "12",
        "date": "2026-03-16",
        "attendance_status": "present"
      }
    ],
    "summary": {
      "total_students": 45,
      "present": 43,
      "absent": 2
    }
  }
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const getClassAttendance = async (token, date) => {
  const params = new URLSearchParams({ date });
  const response = await fetch(
    `https://api.skole.com/v1/teachers-app/attendance?${params}`,
    {
      method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );

  return (await response.json()).data;
};
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 200 ✅  | Success  | -          |

***

### TEACH-04: Bulk Upload Attendance

#### Section 1: Endpoint Summary

Import attendance records from CSV/Excel file for entire class in one operation.

#### Section 2: HTTP Details

* **HTTP Method:** POST
* **Endpoint URL:** `/teachers-app/attendance/bulk-upload`
* **Content-Type:** `multipart/form-data`
* **Authentication:** JWT (Staff)

#### Section 5: Request Body Schema

```text theme={null}
Form Data:
- file: File (CSV/Excel)
  Columns: student_roll_no, date, status, checkedIn_time, checkedOut_time
- dry_run: Boolean (optional, validate only)
```

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "message": "45 records imported",
  "data": {
    "imported": 45,
    "failed": 0,
    "errors": []
  }
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const bulkUploadAttendance = async (token, file) => {
  const formData = new FormData();
  formData.append('file', file);

  const response = await fetch(
    'https://api.skole.com/v1/teachers-app/attendance/bulk-upload',
    {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` },
      body: formData
    }
  );

  const data = await response.json();
  console.log(`Imported: ${data.data.imported}`);
  return data.data;
};
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 200 ✅  | Success  | -          |

***

### TEACH-05: Attendance Reports

#### Section 1: Endpoint Summary

Teacher views attendance reports for their class with statistics and trends.

#### Section 2: HTTP Details

* **HTTP Method:** GET
* **Endpoint URL:** `/teachers-app/attendance/reports`
* **Authentication:** JWT (Staff)

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "data": {
    "class_summary": {
      "total_students": 45,
      "total_present": 850,
      "attendance_percentage": 88
    },
    "top_absentees": [{"name": "...", "absences": 3}],
    "trends": {...}
  }
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const getAttendanceReports = async (token) => {
  const response = await fetch(
    'https://api.skole.com/v1/teachers-app/attendance/reports',
    {
      method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );

  return (await response.json()).data;
};
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 200 ✅  | Success  | -          |

***

### ADMIN-01: Create Attendance Record (Web App)

#### Section 1: Endpoint Summary

Admin creates attendance records with all details. Supports editing historical records.

#### Section 2: HTTP Details

* **HTTP Method:** POST
* **Endpoint URL:** `/web-app/attendance`
* **Authentication:** JWT (Admin)

#### Section 5: Request Body Schema

```json theme={null}
{
  "student_id*": "UUID",
  "date*": "Date",
  "attendance_status*": "Enum",
  "checkedIn_at": "Timestamp",
  "checkedOut_at": "Timestamp"
}
```

#### Section 6: Response Schema (Success - 201)

```json theme={null}
{
  "status": "success",
  "message": "Record created",
  "data": {
    "id": "UUID"
  }
}
```

#### Section 8: Implementation Examples

**JavaScript:**

```javascript theme={null}
const createAttendanceRecord = async (token, record) => {
  const response = await fetch(
    'https://api.skole.com/v1/web-app/attendance',
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(record)
    }
  );

  return (await response.json()).data;
};
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 201 ✅  | Success  | -          |

***

### ADMIN-02: List Attendance (Web App)

#### Section 1: Endpoint Summary

Admin views all attendance records for entire school with advanced filtering.

#### Section 2: HTTP Details

* **HTTP Method:** GET
* **Endpoint URL:** `/web-app/attendance`
* **Authentication:** JWT (Admin)

#### Section 4: Query Parameters

| Parameter   | Type   | Required | Description       |
| ----------- | ------ | -------- | ----------------- |
| student\_id | UUID   | No       | Filter by student |
| class\_id   | UUID   | No       | Filter by class   |
| from\_date  | Date   | No       | Date range        |
| to\_date    | Date   | No       | Date range        |
| status      | String | No       | Filter by status  |

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "data": {
    "records": [...],
    "pagination": {
      "total": 5400,
      "take": 20,
      "pages": 270
    }
  }
}
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 200 ✅  | Success  | -          |

***

### ADMIN-03: Update Attendance Record (Web App)

#### Section 1: Endpoint Summary

Admin updates attendance record details.

#### Section 2: HTTP Details

* **HTTP Method:** PUT
* **Endpoint URL:** `/web-app/attendance/:id`
* **Authentication:** JWT (Admin)

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "message": "Record updated"
}
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 200 ✅  | Success  | -          |

***

### ADMIN-04: Bulk Upload Attendance (Web App)

#### Section 1: Endpoint Summary

Admin bulk uploads attendance from CSV/Excel file for entire school.

#### Section 2: HTTP Details

* **HTTP Method:** POST
* **Endpoint URL:** `/web-app/attendance/bulk-upload`
* **Content-Type:** `multipart/form-data`
* **Authentication:** JWT (Admin)

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "message": "5400 records imported",
  "data": {
    "imported": 5400,
    "failed": 0
  }
}
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 200 ✅  | Success  | -          |

***

### ADMIN-05: Attendance Reports (Web App)

#### Section 1: Endpoint Summary

Admin views school-wide attendance reports with statistics and analysis.

#### Section 2: HTTP Details

* **HTTP Method:** GET
* **Endpoint URL:** `/web-app/attendance/reports`
* **Authentication:** JWT (Admin)

#### Section 6: Response Schema (Success - 200)

```json theme={null}
{
  "status": "success",
  "data": {
    "school_statistics": {
      "total_students": 450,
      "avg_attendance_percentage": 88
    },
    "class_analysis": [...],
    "trends": {...}
  }
}
```

#### Section 12: Response Summary Table

| Status | Scenario | Error Code |
| ------ | -------- | ---------- |
| 200 ✅  | Success  | -          |

***

## 12. Summary Table: All 14 Attendance Endpoints

| ID        | Endpoint                                 | Method | Description        | Status       |
| --------- | ---------------------------------------- | ------ | ------------------ | ------------ |
| PARENT-01 | `/parent-app/attendance`                 | GET    | List attendance    | ✅ Documented |
| PARENT-02 | `/parent-app/attendance/:studentId`      | GET    | Detail view        | ✅ Documented |
| PARENT-03 | `/parent-app/attendance/reports/summary` | GET    | Summary stats      | ✅ Documented |
| PARENT-04 | `/parent-app/attendance/reports/monthly` | GET    | Monthly calendar   | ✅ Documented |
| TEACH-01  | `/teachers-app/attendance`               | POST   | Mark attendance    | ✅ Documented |
| TEACH-02  | `/teachers-app/attendance/:id`           | PUT    | Edit record        | ✅ Documented |
| TEACH-03  | `/teachers-app/attendance`               | GET    | List class records | ✅ Documented |
| TEACH-04  | `/teachers-app/attendance/bulk-upload`   | POST   | Bulk upload        | ✅ Documented |
| TEACH-05  | `/teachers-app/attendance/reports`       | GET    | Reports            | ✅ Documented |
| ADMIN-01  | `/web-app/attendance`                    | POST   | Create record      | ✅ Documented |
| ADMIN-02  | `/web-app/attendance`                    | GET    | List all           | ✅ Documented |
| ADMIN-03  | `/web-app/attendance/:id`                | PUT    | Update record      | ✅ Documented |
| ADMIN-04  | `/web-app/attendance/bulk-upload`        | POST   | Bulk upload        | ✅ Documented |
| ADMIN-05  | `/web-app/attendance/reports`            | GET    | Reports            | ✅ Documented |
