kolibri icon indicating copy to clipboard operation
kolibri copied to clipboard

Add REST API endpoints for attendance tracking

Open akolson opened this issue 9 months ago • 5 comments

Overview

Add REST API endpoints for attendance data, exposing AttendanceSession and AttendanceRecord to the frontend. Coaches and admins can create, read, and update sessions with nested attendance records. Builds on the models added in #14229.

Complexity: Medium Target branch: release-v0.19.x

Context

The AttendanceSession and AttendanceRecord models (added in #14229) have no API surface yet. Without endpoints, the coach UI has no way to create or retrieve attendance data. This issue adds that layer.

The Change

Serializers (kolibri/core/attendance/serializers.py):

  • AttendanceRecordSerializer — fields: id, user, present
  • AttendanceSessionSerializer — nested records; atomic create and update (records created/updated via update_or_create on PUT)

ViewSet (AttendanceSessionViewSet):

  • Full CRUD on sessions; records are passed as a nested list in the session payload
  • Custom AttendanceSessionPermissions (extends KolibriAuthPermissions) — validates that the requesting user can create a session for the given collection
  • Filters: collection, start_date, end_date
  • Default ordering: -session_start_datetime
  • Pagination: OptionalPageNumberPagination
  • Extra action GET /attendancesession/recent/ — returns the N most recent sessions (default 5, max 50) with present_count and total_count per session

URL routing:

  • kolibri/core/attendance/api_urls.py registers AttendanceSessionViewSet at attendancesession/
  • kolibri/core/api_urls.py includes kolibri.core.attendance.api_urls at attendance/

Out of Scope

  • Learner-facing endpoints (learners have no attendance write access)
  • Bulk delete of sessions

Acceptance Criteria

General

  • [ ] AttendanceSessionViewSet exposes full CRUD at attendance/attendancesession/
  • [ ] Creating a session atomically creates its nested AttendanceRecord entries
  • [ ] Updating a session upserts attendance records without duplicating them
  • [ ] created_by is set from the request user on create, not accepted from the client
  • [ ] Sessions can be filtered by collection, start_date, and end_date
  • [ ] Sessions are returned ordered by -session_start_datetime by default
  • [ ] Pagination uses OptionalPageNumberPagination
  • [ ] GET /attendancesession/recent/ returns up to 50 sessions with present_count and total_count
  • [ ] Anonymous users receive no data; learners cannot create or delete sessions; coaches can create and update but not delete; only admins can delete
  • [ ] kolibri.core.attendance.api_urls is included in kolibri/core/api_urls.py at attendance/

Testing

  • [ ] CRUD operations and permission rules are tested for coach, admin, learner, and anonymous roles
  • [ ] Date range filter and recent endpoint are tested
  • [ ] Nested record creation and update behaviour is tested

References

  • Issue #14229 — AttendanceSession and AttendanceRecord models
  • MembershipViewSet — example of a ModelViewSet with KolibriAuthPermissions and filtering

🤖 This issue was written with AI assistance, under supervision, review and final edits by [@akolson] 🤖

akolson avatar Feb 23 '26 15:02 akolson

Some small additions that would be helpful here:

  • API URL registration in kolibri/core/api_urls.py
  • What pagination style/class should we use? Page based, cursor based? OptionalPageNumberPagination will probably be sufficient
  • Default ordering? Presumably -session_start_datetime?

rtibbles avatar Mar 02 '26 03:03 rtibbles

Implementation Plan for #14230 — Attendance REST API

Acknowledging @rtibbles' feedback: Incorporated all three points:

  • API URL registration in kolibri/core/api_urls.py at attendance/ (Phase 3)
  • Pagination: OptionalPageNumberPagination (Phase 2)
  • Default ordering: -session_start_datetime (Phase 2)

Architecture

  • ViewSet: AttendanceSessionViewSet extends ValuesViewset (per project conventions)
  • Serializer: AttendanceSessionSerializer with nested AttendanceRecordSerializer — handles atomic create and upsert (via update_or_create) of records
  • Permissions: AttendanceSessionPermissions extends KolibriAuthPermissions — strips nested records before validation, sets created_by from request user
  • Filters: AttendanceSessionFilter with collection, start_date, end_date
  • Recent action: GET /attendancesession/recent/ annotates with present_count/total_count

Phases

Phase Description Files
1 Serializers kolibri/core/attendance/serializers.py (create)
2 ViewSet + Permissions + Filters kolibri/core/attendance/api.py (create)
3 URL Registration kolibri/core/attendance/api_urls.py (create), kolibri/core/api_urls.py (modify)
4 Tests kolibri/core/attendance/test/test_api.py (create)

Permission Matrix

Action Admin Coach Learner Anonymous
Create Yes Yes No No
Read Yes Yes No No
Update Yes Yes No No
Delete Yes No No No

(Matches RoleBasedPermissions already defined on the models)

Key Patterns Followed

  • ValuesViewset (not ModelViewSet) per AGENTS.md
  • KolibriAuthPermissions + KolibriAuthPermissionsFilter for object-level security
  • OptionalPageNumberPagination (as suggested by @rtibbles)
  • Default ordering -session_start_datetime (as suggested by @rtibbles)
  • SimpleRouter registration pattern (matches exams, lessons)
  • TDD approach for tests covering all permission roles

Environment Note

Current environment has Python 3.14 (kolibri requires <3.14), so tests may need a compatible Python to run. Linting (black) works.

rtibblesbot avatar Mar 06 '26 00:03 rtibblesbot

Progress Update: Attendance REST API Implementation (Phases 1-4 Complete)

Acknowledging @rtibbles' feedback: All three suggestions have been incorporated:

  • ✅ API URL registration in kolibri/core/api_urls.py at attendance/
  • ✅ Pagination: OptionalPageNumberPagination
  • ✅ Default ordering: -session_start_datetime

What was implemented

Serializers (kolibri/core/attendance/serializers.py):

  • AttendanceRecordSerializer — nested record serialization
  • AttendanceSessionSerializer — handles atomic create with nested records, upsert on update via update_or_create, sets created_by from request user

ViewSet (kolibri/core/attendance/api.py):

  • AttendanceSessionViewSet extends ValuesViewset with KolibriAuthPermissions
  • AttendanceSessionFilter with collection, start_date, end_date filters
  • Custom AttendanceSessionPermissions that strips nested records before validation and handles anonymous users
  • GET /recent/ action with present_count/total_count annotations

URL Registration:

  • kolibri/core/attendance/api_urls.py — SimpleRouter with attendancesession route
  • Registered in kolibri/core/api_urls.py at attendance/

Test Summary

25 API tests all passing, covering:

  • CRUD operations (create, read list/detail, update with upsert, delete)
  • Permission matrix (admin, coach, learner, anonymous) for all operations
  • Filters (collection, start_date, end_date)
  • Default ordering (-session_start_datetime)
  • Recent endpoint with present/total counts and limit parameter
  • Pagination with page_size
44 passed (25 API + 19 model tests)

Code quality improvements from review

  • Used _ensure_raw_dict from kolibri.core.auth.api (matching exams/lessons pattern)
  • Fixed potential slice-before-annotate issue in recent action
  • Added input validation for limit parameter
  • Imported DUMMY_PASSWORD from test helpers instead of redefining

🤖 Generated with Claude Code

rtibblesbot avatar Mar 06 '26 00:03 rtibblesbot

Self-Review Progress Update

Completed self-review of the attendance REST API implementation (diff: release-v0.19.x...HEAD).

Stakeholder Feedback (@rtibbles)

All three points from @rtibbles' comment have been addressed:

  • API URL registration: kolibri.core.attendance.api_urls is included in kolibri/core/api_urls.py at the attendance/ prefix
  • Pagination: Uses OptionalPageNumberPagination
  • Default ordering: -session_start_datetime via get_queryset()

Findings & Fixes (all resolved)

Severity Finding Status
suggestion Serializer update() only handled session_start_datetime, silently ignoring other writable fields on PUT Fixed — now iterates all validated_data fields
suggestion Test class used django.test.TestCase instead of APITestCase (project convention) Fixed
suggestion Imports inside test methods instead of at file top Fixed

Acceptance Criteria

All 13 acceptance criteria verified and met (10 general + 3 testing). See PLAN/self-review.md for the full checklist.

Test Results

All 25 tests pass. No external calls requiring mocks — pure Django integration tests against test DB.

rtibblesbot avatar Mar 06 '26 00:03 rtibblesbot

Fixed in #14332

rtibbles avatar Mar 06 '26 18:03 rtibbles