* theming improvements * border style improvements * refactor: migrate org routes to server-side data fetching Move client-side API calls to server-side load functions for better performance, security, and SEO. Implement permission-based course filtering * refactor: clean up course and community components This commit removes unused components and files related to courses and community features, streamlining the codebase. It also updates various routes to enhance performance and maintainability. Additionally, it introduces new types and constants for better type safety and organization. * refactor: fix video formatting on website and other styles * refactor: update course and dashboard components for improved styling and functionality * more icon improvements * refactor: streamline course and dashboard components This commit updates various course and dashboard components for improved styling and functionality. It includes the removal of unused files, updates to imports and exports, and enhancements to type safety. Additionally, it introduces new routes and optimizes existing ones for better performance and maintainability. * refactor: enhance lesson completion logic * chore: delete all emails on dashboard and move other api routes to backend. move all emails to the backend and * feat: Refactor API and database queries for courses, quizzes, and lessons, migrating Supabase functions and schema management. * get app loading * fix ui and build error of cio/api * refactor: move direct database queries to query layer - Create query functions: getCourseWithOrgData, getOrganizationByCourseId, updateCourseVersion, updateLessonsSectionId, getProfileByGroupMemberId, getQuestionTypesByIds - Refactor services to use query functions instead of direct db queries - Add transaction support to updateCourseVersion and updateLessonsSectionId - Fix getProfileByGroupMemberId to return profile directly (not nested) - Fix updateLessonsSectionId to use .returning() instead of rowCount This aligns services with architecture pattern where services orchestrate queries rather than executing them directly. * exercise saving improvements * fix and optimise exercise creation * refactor: update dialog components for improved styling and functionality - Adjusted dialog content width and maximum constraints for better responsiveness. - Changed heading font size for consistency in the new exercise modal. - Replaced CloseIcon with CrossIcon for a more modern appearance in dialog close button. * refactor: enhance course and exercise management components - Introduced new components for exercise creation, editing, and viewing, improving user experience. - Refactored existing lesson and exercise components for better organization and maintainability. - Updated routing for exercises and lessons to streamline navigation within the course structure. - Added new utility functions and constants to support content management across the application. * feat: implement course content management API and UI components - Added new API routes for updating and deleting course content, enhancing content management capabilities. - Introduced new Svelte components for displaying and managing course content, including content lists and action handlers. - Updated existing course routing to integrate new content management features. - Refactored content-related utility functions for improved organization and maintainability. * refactor: remove Supabase references and implement course section management - Removed Supabase-related environment variables and Dockerfile arguments to streamline configuration. - Introduced a new section management API with routes for creating, updating, deleting, and reordering course sections. - Updated course services to handle section operations, ensuring consistency in course content management. - Refactored existing lesson section logic to align with the new course section structure, enhancing maintainability. * chore: update .prettierignore to exclude additional file types - Added exclusions for SQL and environment files to the Prettier ignore list. - Included Dockerfile and .prettierignore itself to prevent formatting issues. * feat: enhance course content management with translation support and UI improvements - Added translation keys for user-facing text in course-related components, ensuring all UI copy is sourced from translation files. - Updated lesson and exercise creation components to utilize translation keys for success and error messages, improving localization. - Refactored course content management components to streamline the creation and editing process, enhancing user experience. - Introduced new constants for content options and stepper states to standardize component behavior and improve maintainability. - Improved styling and functionality of course content modals and steppers for better user interaction. * feat: enhance course content management and UI components - Updated .prettierignore to exclude storybook-static directory. - Improved exercise creation logic by refining option handling and adding UUID support for option values. - Enhanced navigation component with debugging output for custom links. - Introduced a new method in CourseApi to update content items locally, improving state management during navigation. - Added caching for exercise templates by tag in ExerciseTemplateApi to optimize performance. - Refactored lesson and exercise components for better organization and maintainability, including updates to modal styling and functionality. - Implemented local patching for lesson and exercise list items to ensure UI consistency after updates. * student + teacher invite (not fully tested) * refactor: streamline course team member middleware - Removed unnecessary console logging and timing for checking user permissions. - Simplified the logic for determining if a user is a course team member or organization admin. * reorder course sidebar to move content to its own page. * feat: implement unified course enrollment route and API - Introduced a new enrollment route `/course/:slug/enroll` to replace the previous invite system. - Unified enrollment logic for free and paid courses, allowing direct enrollment for free courses and invite token validation for paid courses. - Updated course landing page to redirect to the new enrollment route for free courses. - Removed obsolete invite routes and related logic, streamlining the enrollment process. - Enhanced API with a new `POST /course/:courseId/enroll` endpoint for handling enrollments. - Added rate limiting for enrollment requests to prevent abuse. - Updated UI components to reflect changes in enrollment flow and messaging. * chore: update docker stack, docs, and auth token automation * chore: make prettier check ignore unknown file types * fix: avoid using authClient on server file and keep authClient client focused * chore: always get the server on demand depending on the environment * chore: update dashboard configuration and Docker setup for environment variables - Modified the Svelte configuration to directly use the PUBLIC_SERVER_URL environment variable. - Enhanced the Docker Compose file to include health check formatting and added environment variable arguments for the dashboard build. - Updated the Dockerfile to echo environment variable values during the build process, ensuring clarity on the configuration being used. * chore: enhance Docker setup and documentation for production deployment - Added a new production Docker Compose file and example environment file for published images. - Updated README and usage documentation to include instructions for deploying with production images. - Modified Svelte configuration to standardize the use of the posthog domain. - Removed unnecessary console logs from the API client and layout server files for cleaner output. - Improved overall clarity in Docker documentation regarding self-hosting and image publishing. * chore(db): log function name in query catch blocks (console.error 'funcName error:', error) Co-authored-by: Cursor <cursoragent@cursor.com> * fix: multiple refresh issue * fix: server key not passed to api * fix: clarify usage of PRIVATE_SERVER_KEY and AUTH_BEARER_TOKEN in documentation - Updated documentation to specify that PRIVATE_SERVER_KEY is used for server-to-server API key authentication and is validated by API key middleware. - Clarified that AUTH_BEARER_TOKEN is a separate token not utilized by apiKeyMiddleware. - Adjusted examples in Docker setup and self-hosting documentation to reflect these changes. * fix migration script * fix: improve language handling and add database reset script - Updated language extraction to handle potential undefined values, defaulting to 'en' if necessary. - Added a new script for resetting the database, including functionality to truncate public tables and run setup with optional seeding. * feat: add promote ungrouped section functionality and enhance document handling in dashboard - Implemented a new API endpoint to promote synthetic "Ungrouped" content into a real persisted section, allowing for better organization of course materials. - Updated the dashboard to include a new component for displaying content count badges for lessons and exercises. - Enhanced document management features, including a new document card component with dropdown actions for viewing, downloading, and removing documents. - Improved file upload handling with a dedicated file drop zone and error handling for file type and size restrictions. - Refactored existing components for better readability and maintainability, including updates to lesson and document lists. * chore: use root env file for docker compose * docs: document docker no-build startup flow * chore: add no-build option to docker full stack script * fix(email): handle SMTP TLS mode by port * feat(auth): add configurable cookie domain env and docs * apps/dashboard/src/lib/utils/services/auth/session.ts * fix(email): make sender configurable via SMTP_SENDER * chore(i18n): regenerate locale translations and support language targeting * chore(config): switch api to PUBLIC_SERVER_URL * fix(i18n): persist selected locale across navigation * feat(assets): implement organization asset management routes and services - Added new routes for managing organization assets, including listing, creating, updating, deleting, and exporting assets. - Introduced asset-related services for handling asset operations such as creation, retrieval, and deletion. - Integrated YouTube metadata resolution and asset attachment/detachment functionalities. - Updated organization routes to include the new asset management routes. - Enhanced error handling for asset-related operations. * fix(document-list): update conditional rendering for edit mode in document list * debug self hosted layout setup * refactor(sidebar): simplify lms sidebar footer and improve navigation item rendering * feat: tags * chore: tags roadmap + translations * fix(api): add authMiddleware to exercise, invites, and content routers - exerciseRouter: apply authMiddleware before courseMemberMiddleware on all 10 routes - invitesRouter: apply authMiddleware before courseTeamMemberMiddleware on all 4 routes - contentRouter: add authMiddleware to PUT route (DELETE already had it) Both courseMemberMiddleware and courseTeamMemberMiddleware document requiring authMiddleware to be applied first. This aligns with lessonRouter pattern and ensures explicit middleware contract regardless of global session middleware. Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * fix(course): use courseTeamMemberMiddleware for PUT, DELETE, and analytics routes These routes require admin/tutor role per JSDoc but were using courseMemberMiddleware which allows any course member including students. Switch to courseTeamMemberMiddleware to restrict access to ADMIN/TUTOR group members and org admins. Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * chore: unify pricing component between dashboard and website (#630) * feat: modularize pricing card * feat: initia implementation of pricing togge * fix: minor amendment * refactor: update pricing components for improved layout and styling - Adjusted spacing in the pricing card layout for better visual consistency. - Modified button styles and sizes for enhanced usability. - Cleaned up the pricing toggle component by removing unnecessary console logs and restructuring the button rendering logic. * add handle click * chore(css): update Tailwind CSS output with new utility classes and theme variables * fix(api): enable orgMemberMiddleware for stats route This change ensures that the stats route is protected by orgMemberMiddleware, aligning access control with other routes. Additionally, removed unnecessary console log from the layout server file to clean up the code. --------- Co-authored-by: Rotimi Best <best@classroomio.com> * pass query parameter to signup from pricing page * ui updates to pricing cards * commit all PRDs * add open api spec to api prd * make blue default theme * more prds * sync option id sequence on question update * docs: more classroomio features * chore: more ui improvements * docs: new component docs * chore: CSP Configuration (#638) * feat(validation): add GitHub repository name validation - Add ZRepositoryName schema for validating GitHub repo names - Add ZRepositoryOwner for owner/username validation - Add ZRepositoryIdentifier for owner/repo format - Follow GitHub rules: A-Za-z0-9_.-, 1-100 chars, reserved names - Add translation keys for validation messages Fixes #637 Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * Revert "feat(validation): add GitHub repository name validation" This reverts commit 3436536bb17a0f05b3a9fe8dd7682cde64dd1dce. * feat(dashboard): make CSP external domains configurable via env Move hardcoded external domains from svelte.config.js to .env configuration for on-premise deployments with strict security policies, data residency constraints, or CISO-driven allowlists. - ALLOWED_EXTERNAL_DOMAINS: single list for all CSP directives - CSP_SCRIPT_SRC_DOMAINS, CSP_STYLE_SRC_DOMAINS, CSP_CONNECT_SRC_DOMAINS, CSP_FRAME_SRC_DOMAINS, CSP_FONT_SRC_DOMAINS: per-directive override - When unset, defaults retain current SaaS behavior (backward compatible) Fixes #637 Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * fix(dashboard): self-hosted CSP uses only env vars, no defaults Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * fix(dashboard): add all classroomio.com domains to CSP defaults Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * docs: add CSP ALLOWED_EXTERNAL_DOMAINS to self-hosting guides Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat(docker): pass CSP domain env vars as build args to dashboard Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat: add SSO and token authentication routes and services - Introduced new routes for SSO and token authentication under the organization namespace. - Implemented SSO connection management including creation, update, activation, and deletion. - Added token authentication configuration with support for secret rotation and status retrieval. - Enhanced error handling for SSO and token authentication processes. - Updated existing routes and services to integrate new functionalities. - Improved gradebook service to fetch student marks and exercises. - Refactored API structure for better organization and maintainability. * update translations * fix: add PUBLIC_SERVER_URL to .env.example to prevent localhost fallback in production (#641) Co-authored-by: Cursor Agent <cursoragent@cursor.com> * feat: new exercise question types * MinIO S3 storage backend (#639) * feat(storage): add MinIO/S3-compatible object storage backend - Add OBJECT_STORAGE_* env vars for generic S3-compatible backends (MinIO, AWS S3) - Create storage config module with Cloudflare R2 fallback for backward compatibility - Refactor s3.ts to use configurable client and bucket names from config - Update media.ts to use provider-neutral public URL (OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL or CLOUDFLARE_IMAGE_BUCKET_DOMAIN) - Add MinIO service and init to docker-compose (profile: minio) with videos/documents/media buckets - Add localhost:9000 to dashboard CSP for local MinIO presigned URL uploads - Update self-hosting and Cloudflare docs with MinIO option - Update .env examples and docker USAGE.md Fixes #635 Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * docs: add MINIO_ROOT_USER and MINIO_ROOT_PASSWORD to self-hosting guides Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat(media): refactor media management and integrate MinIO support - Updated media API to use a new `mediaApi` module, replacing `mediaManagerApi` references across components. - Added MinIO configuration options to the Docker setup, allowing for optional object storage exclusion. - Enhanced environment variable management for MinIO in the `.env.example` file. - Updated Content Security Policy (CSP) to allow local MinIO access in the dashboard. - Introduced new media components for asset management, including asset cards and usage dialogs. This refactor improves the modularity of the media handling system and provides better support for S3-compatible storage solutions. * feat(dashboard): enhance logging and refactor auth session handling - Added console logging for event and environment variables in hooks.server.ts to aid debugging. - Refactored auth session handling to use authServerClient instead of authClient in session.ts for improved consistency. - Updated Dockerfile to ensure the dashboard build output is present before starting the application. - Expanded self-hosting documentation to include troubleshooting steps for disk space issues in PostgreSQL and Docker. These changes improve the observability of the application and streamline the authentication process. * refactor(dashboard): remove debug logging and enhance Postgres healthcheck - Removed console logging for event and environment variables in hooks.server.ts to clean up the code. - Updated Postgres healthcheck in docker-compose.yaml to require a successful `SELECT 1` query, ensuring dependent services only start once the database is ready. - Expanded self-hosting documentation to include troubleshooting steps for database recovery issues. These changes improve code clarity and reliability in service startup sequences. --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat: add Plyr media player icons and PDF.js integration - Introduced new Plyr SVG icons for media player controls in both course and dashboard applications. - Updated Plyr player configuration to use local icon assets. - Integrated PDF.js for document viewing, replacing external CDN links with local paths for improved performance and reliability. - Enhanced PDF viewer modal z-index for better visibility. This update improves the media player experience and ensures consistent access to necessary resources. * feat: enhance account and organization services with type definitions and promise return types - Updated `getAccountData` to return a structured result type including profile and organizations. - Modified `getOrganizationsWithFilters` to specify a promise return type for better type safety. - Added new type imports for organization-related data structures to improve clarity and maintainability. These changes improve type safety and enhance the overall structure of the account and organization services. * feat: implement Redis caching for presigned URLs and refactor API interactions - Added Redis caching for presigned download URLs in the API to reduce redundant S3 calls, improving performance. - Introduced a new `PresignApi` class in the frontend to centralize presigned URL requests, enhancing code maintainability. - Updated various components to utilize the new `presignApi` methods for document and video upload/download operations. - Enhanced error handling for Redis operations to ensure graceful degradation in case of cache failures. These changes optimize the presigned URL generation process and streamline API interactions across the application. * fix: add better-auth dependency to dashboard (#645) * chore: unify exercise answer data format * feat: make selfhosting run under one org for simplicity (#647) * feat: implement self-hosting PRD + license key system Self-hosting single-org: - Add PUBLIC_IS_SELFHOSTED to API env, block org creation when org exists - Auto-add non-members as students in GET /account bootstrap - getOrgSiteInfo: root domain returns single org for self-hosted - App init: route to /lms when self-hosted + no orgs - Hide org switcher and Add Org modal when self-hosted Invite-only signup: - Add settings.signup.inviteOnly via ZUpdateOrganization - Allow public signups toggle in org auth settings - Signup page: hide form when invite-only and no invite context - Landing page nav: respect inviteOnly for signup link First signup auto-verify: - Self-hosted first signup (no orgs) auto-verifies email in createProfileHook License key system: - LICENSE_KEY, LICENSE_VERIFICATION_URL for external verification API - Feature gates: SSO, token-auth, no-tracking (PostHog/Senja) - requireLicense middleware for API routes - Dashboard: license store, gate PostHog/Senja/SSO/token-auth UI - docs/LICENSE_API_CONTRACT.md for external API spec Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat: get rid of carbon completely * chore: license verification happens only for selfhosted instance * fix: in self hosted instance, orgSite is the default * docs: how to write math in cio editor * Update packages/db/src/queries/organization/organization.ts Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * Update apps/api/src/services/license.ts Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * fix: translations, cursor pr reviews, simplify license fetching and check * refactor: update analytics setup for cloud and self-hosted deployments; enhance settings merge logic * refactor: update license fetching URL for development environment; optimize organization query to prevent plan row loss * more selfhosting improvements * feat: enhance signup guard for self-hosted instances by requiring organization context when no org ID is provided * pr reviews * fix: correct query parameter handling in course navigation * pr reviews --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> Co-authored-by: Abdulmuizz Hamzat <103611443+buildwithhamzat@users.noreply.github.com> Co-authored-by: Adeyemi Adetunji <tvnji01@gmail.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
44 KiB
Classes PRD
Purpose
Enable instructors and org admins to group multiple courses — along with shared announcements, files, and community discussions — into a single class. Enrolling a student in a class auto-enrolls them in every course inside it, eliminating the need to manage per-course enrollment manually when delivering a structured program.
Problem Statement
Currently, ClassroomIO has no entity above the individual course. Every course has its own independent enrollment roster. This creates several pain points:
- An instructor running a program (e.g., a bootcamp, onboarding track, or certification pathway) must enroll students in each constituent course one by one.
- There is no shared space for class-wide announcements, files, or discussions that span multiple courses.
- Students cannot see a unified "program" view in the LMS — they only see a flat list of individual courses.
- Org admins have no way to bundle courses for a specific cohort of learners (e.g., "Q1 2026 New Hire Onboarding") without creating separate organizations or duplicating content.
Confirmed Decisions
- Terminology: "Class" in both the instructor-facing admin UI and the student-facing LMS.
- Auto-enrollment: Joining a class automatically creates
groupmemberrecords for every course inside the class. Removing a student from a class does not remove them from individual course groups, preserving their submission and progress data. - Shared materials: Each class has three shared material surfaces: announcements (instructor-authored posts), a file library, and a community Q&A board.
- Many-to-many courses: A course can belong to multiple classes. Courses and classes are independent entities linked by a join table.
- LMS visibility: Classes are visible to students in the LMS under a dedicated "Classes" section. Students see enrolled classes and can navigate courses from within a class hub page.
- Roles: Class roles mirror the existing system (
ADMIN/roleId 1,TUTOR/roleId 2,STUDENT/roleId 3). Class admins and tutors can manage the class; class students get read access to materials. - Class status: Classes can be
ACTIVE,INACTIVE, orARCHIVED.INACTIVEclasses are hidden from students in the LMS but preserved for instructors.ARCHIVEDclasses are soft-deleted and hidden everywhere. - Course independence: Courses in a class remain fully independent. A student enrolled in a class is a regular
groupmemberin each course — existing course pages, progress tracking, submissions, and grading are unchanged. - Community reuse: The existing
community_questiontable gains a nullableclassIdFK. Class-level Q&A behaves identically to course-level community Q&A but scoped to the class.
Current-State Audit
| Capability | Current State | Notes |
|---|---|---|
| Organization structure | organization → group (1:1 with course) → course |
No intermediate grouping layer above course |
| Course enrollment | groupmember rows per course's group |
Per-course, no bulk enrollment mechanism |
| Student LMS view | Flat list of enrolled courses under /lms/mylearning |
No program/class concept |
| Community Q&A | community_question.courseId scoped |
Reusable with additional classId FK |
| Shared file library | Per-course via assets table; no org-wide shared files |
New class_file table needed |
| Announcements | Per-course course_newsfeed |
New class_announcement table needed |
| Org admin navigation | "Courses" section listing all courses | "Classes" nav item needed |
| LMS navigation | Home, My Learning, Exercises, Community, Explore, Settings | "Classes" nav item needed |
| Enrollment service | enrollInCourse() in apps/api/src/services/course/invite.ts |
Must be called per-course when adding class member |
Key insight: Because enrollment = groupmember rows per course, adding a student to a class is purely a matter of calling the existing enrollment logic for each course in the class within a single transaction. No course-level schema changes are needed.
Product Goals
- Org admins and instructors can create a class, add courses to it, and manage class membership from the admin dashboard.
- Adding a student to a class auto-enrolls them in all courses currently in the class.
- Adding a new course to an existing class auto-enrolls all current class students in that course.
- Each class has a shared announcements feed, file library, and community board visible to all class members.
- Students can see their enrolled classes in the LMS with a unified hub view showing all courses, announcements, and files.
- Classes without students, and courses outside any class, continue to work exactly as they do today (zero regression).
Non-Goals (v1)
- Class-level invite links (v1 enrollment is admin-managed; students cannot self-enroll in a class via a token).
- Class-specific exercise deadlines or content overrides (courses are shared as-is).
- Class progress analytics aggregated across all courses (available per-course; cross-course aggregation is a future improvement).
- Removing a student from a class also unenrolling them from individual courses (data preservation is the default).
- Class templates or class cloning.
- Public/discoverable class landing pages (classes are private to org members).
- Billing or pricing at the class level.
- Class-level attendance tracking separate from per-course attendance.
Data Sources Checked
packages/db/src/schema.ts— all table definitions and constraint patternsapps/api/src/services/course/course.ts— course creation flowapps/api/src/services/course/invite.ts— enrollment flow (enrollInCourse)apps/api/src/routes/course/course.ts— course router and sub-router mountingapps/api/src/app.ts— top-level router registrationpackages/db/src/queries/course/people.ts— group member managementpackages/db/src/queries/group/group.ts— group/member queriespackages/db/src/queries/community/community.ts— community Q&A patternapps/dashboard/src/lib/features/lms/— LMS navigation and pagesapps/dashboard/src/lib/features/org/— org admin navigationapps/dashboard/src/routes/lms/— LMS SvelteKit routesapps/dashboard/src/routes/courses/— course admin SvelteKit routes
Functional Requirements
1. Class CRUD (Admin)
- Org admins can create a class with: name (required), description (optional), cover image (optional).
- Classes can be updated (name, description, cover image, status).
- Archiving a class sets
status = 'ARCHIVED'and hides it from all views. Archived classes can be restored. - A class belongs to exactly one organization.
- Class names do not need to be unique within an org (unlike course slugs), but should be descriptive.
2. Course Management in a Class (Admin)
- Org admins and class tutors can add existing org courses to a class.
- A course can belong to multiple classes simultaneously.
- Adding a course to a class triggers auto-enrollment: all existing
STUDENTclass members are enrolled in the new course (agroupmemberrow is created in the course'sgroupfor each student not already enrolled). - Removing a course from a class does not unenroll any students from that course. Their progress and submissions are preserved.
- Courses within a class are ordered (integer
orderfield) so instructors can sequence them.
3. Class Membership (Admin)
- Org admins can add members to a class by profile ID or email, assigning them a role (ADMIN, TUTOR, or STUDENT).
- Adding a STUDENT member triggers auto-enrollment: a
groupmemberrow is created in every course currently in the class (skipping courses the student is already enrolled in; idempotent). - Adding an ADMIN or TUTOR member does not auto-enroll them in courses (their course-level permissions are managed separately via course membership).
- Removing a member from a class removes the
class_memberrow only. Individualgroupmemberrows in courses are left intact, preserving submissions, grades, and progress. - Batch add: admins can add multiple members at once (array of
{ email, roleId }pairs).
4. Class Announcements (Admin + LMS)
- Class admins and tutors can post announcements to the class feed.
- Announcements have a title and a rich-text body.
- Announcements are visible to all class members (students, tutors, and admins) in both the admin class view and the LMS class hub.
- Students cannot post announcements (read-only for students).
- Announcements are ordered by
createdAtdescending (newest first).
5. Class File Library (Admin + LMS)
- Class admins and tutors can upload files to the class file library.
- Each file record stores: name, URL (stored via the existing presigned upload flow), MIME type, size, uploader profile ID.
- All class members can view and download files.
- Only class admins and tutors can delete files.
6. Class Community (Admin + LMS)
- Class-level community Q&A reuses the existing
community_question/community_answerinfrastructure. - A nullable
classIdFK is added tocommunity_question. Questions withclassIdset are class-scoped (not visible on the course-level community board). - All class members can post questions and answers in the class community.
- The existing voting, commenting, and answer-acceptance behavior is unchanged.
7. LMS — My Classes (Student)
- A "Classes" nav item appears in the LMS sidebar when the student is enrolled in at least one class.
- The
/lms/classespage lists all classes the student is enrolled in. - Each class card shows: class name, cover image, number of courses, brief description.
- Clicking a class opens the class hub page.
8. LMS — Class Hub (Student)
- The class hub at
/lms/classes/[classId]is the student's central page for a class. - It is divided into three tabs or sections:
- Courses: All courses in the class, each with the student's individual progress bar and a direct link to the course. Courses are shown in the instructor-defined order.
- Announcements: Class announcements in reverse-chronological order (read-only for students).
- Resources: The class file library (download only) and a link to the class community board.
- The class community board lives at
/lms/classes/[classId]/communityand behaves identically to the existing course community pages.
9. Admin — Classes Section
- "Classes" is added as a top-level nav item in the org admin sidebar, alongside "Courses".
- The
/courses/classespage lists all org classes with name, course count, student count, and status badge. - A "Create Class" button opens a creation form.
- Each class links to a class detail view with sub-pages: Overview, Courses, People, Announcements, Files.
10. Access Control
- Only
ADMINandTUTORrole members of a class (or org admins) can manage class content and membership. - Students can read announcements and files, participate in the community, and view the course list.
- A student who is removed from the org loses access to all class content.
- An
INACTIVEclass is hidden from students in the LMS but all data is preserved.
Technical Design
Data Model
New Enum: CLASS_STATUS
// packages/db/src/schema.ts
export const classStatus = pgEnum('CLASS_STATUS', ['ACTIVE', 'INACTIVE', 'ARCHIVED']);
New Table: class
// packages/db/src/schema.ts
export const lmsClass = pgTable(
'class',
{
id: uuid()
.default(sql`gen_random_uuid()`)
.primaryKey()
.notNull(),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'string' }).defaultNow(),
organizationId: uuid('organization_id').notNull(),
name: varchar().notNull(),
description: text(),
coverImage: text('cover_image'),
status: classStatus().default('ACTIVE').notNull(),
createdByProfileId: uuid('created_by_profile_id')
},
(table) => [
foreignKey({
columns: [table.organizationId],
foreignColumns: [organization.id],
name: 'class_organization_id_fkey'
}).onDelete('cascade'),
foreignKey({
columns: [table.createdByProfileId],
foreignColumns: [profile.id],
name: 'class_created_by_profile_id_fkey'
}),
index('idx_class_organization_id').on(table.organizationId)
]
);
New Table: class_course
Many-to-many join between class and course, with an instructor-controlled display order.
// packages/db/src/schema.ts
export const classCourse = pgTable(
'class_course',
{
id: uuid()
.default(sql`gen_random_uuid()`)
.primaryKey()
.notNull(),
classId: uuid('class_id').notNull(),
courseId: uuid('course_id').notNull(),
order: integer().default(0).notNull(),
addedAt: timestamp('added_at', { withTimezone: true, mode: 'string' }).defaultNow().notNull()
},
(table) => [
foreignKey({
columns: [table.classId],
foreignColumns: [lmsClass.id],
name: 'class_course_class_id_fkey'
}).onDelete('cascade'),
foreignKey({
columns: [table.courseId],
foreignColumns: [course.id],
name: 'class_course_course_id_fkey'
}).onDelete('cascade'),
unique('class_course_class_id_course_id_unique').on(table.classId, table.courseId),
index('idx_class_course_class_id').on(table.classId)
]
);
New Table: class_member
Membership roster for a class. Does not replace groupmember — it is a separate layer.
// packages/db/src/schema.ts
export const classMember = pgTable(
'class_member',
{
id: uuid()
.default(sql`gen_random_uuid()`)
.primaryKey()
.notNull(),
classId: uuid('class_id').notNull(),
profileId: uuid('profile_id'),
roleId: integer('role_id').notNull(),
email: text(),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).defaultNow().notNull()
},
(table) => [
foreignKey({
columns: [table.classId],
foreignColumns: [lmsClass.id],
name: 'class_member_class_id_fkey'
}).onDelete('cascade'),
foreignKey({
columns: [table.profileId],
foreignColumns: [profile.id],
name: 'class_member_profile_id_fkey'
}),
foreignKey({
columns: [table.roleId],
foreignColumns: [role.id],
name: 'class_member_role_id_fkey'
}),
unique('class_member_class_id_profile_id_unique').on(table.classId, table.profileId),
index('idx_class_member_class_id').on(table.classId),
index('idx_class_member_profile_id').on(table.profileId)
]
);
New Table: class_announcement
// packages/db/src/schema.ts
export const classAnnouncement = pgTable(
'class_announcement',
{
id: uuid()
.default(sql`gen_random_uuid()`)
.primaryKey()
.notNull(),
classId: uuid('class_id').notNull(),
authorProfileId: uuid('author_profile_id'),
title: varchar().notNull(),
body: text(),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'string' }).defaultNow()
},
(table) => [
foreignKey({
columns: [table.classId],
foreignColumns: [lmsClass.id],
name: 'class_announcement_class_id_fkey'
}).onDelete('cascade'),
foreignKey({
columns: [table.authorProfileId],
foreignColumns: [profile.id],
name: 'class_announcement_author_profile_id_fkey'
}),
index('idx_class_announcement_class_id').on(table.classId)
]
);
New Table: class_file
// packages/db/src/schema.ts
export const classFile = pgTable(
'class_file',
{
id: uuid()
.default(sql`gen_random_uuid()`)
.primaryKey()
.notNull(),
classId: uuid('class_id').notNull(),
uploadedByProfileId: uuid('uploaded_by_profile_id'),
name: varchar().notNull(),
url: text().notNull(),
mimeType: varchar('mime_type'),
size: integer(),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).defaultNow().notNull()
},
(table) => [
foreignKey({
columns: [table.classId],
foreignColumns: [lmsClass.id],
name: 'class_file_class_id_fkey'
}).onDelete('cascade'),
foreignKey({
columns: [table.uploadedByProfileId],
foreignColumns: [profile.id],
name: 'class_file_uploaded_by_profile_id_fkey'
}),
index('idx_class_file_class_id').on(table.classId)
]
);
Modified Table: community_question
Add a nullable classId FK so community questions can be scoped to a class:
// Add to community_question table columns:
classId: uuid('class_id')
// Add to community_question table constraints:
foreignKey({
columns: [table.classId],
foreignColumns: [lmsClass.id],
name: 'community_question_class_id_fkey'
}).onDelete('cascade')
When classId is set, the question is class-scoped. When courseId is set, it is course-scoped. The two are mutually exclusive in practice (enforced at the service layer).
Relationship Diagram
organization
└── class
├── class_course ──────────────────────→ course
│ (order, addedAt) └── group → groupmember ← (auto-created)
├── class_member ──────────────────────→ profile
│ (roleId: ADMIN/TUTOR/STUDENT)
├── class_announcement
│ (title, body, authorProfileId)
├── class_file
│ (name, url, mimeType, size)
└── community_question (classId set)
└── community_answer
Migration
File: packages/db/src/migrations/XXXX_add_classes.sql
-- 1. Create CLASS_STATUS enum
CREATE TYPE "CLASS_STATUS" AS ENUM ('ACTIVE', 'INACTIVE', 'ARCHIVED');
-- 2. Create class table
CREATE TABLE class (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
organization_id UUID NOT NULL REFERENCES organization(id) ON DELETE CASCADE,
name VARCHAR NOT NULL,
description TEXT,
cover_image TEXT,
status "CLASS_STATUS" NOT NULL DEFAULT 'ACTIVE',
created_by_profile_id UUID REFERENCES profile(id)
);
CREATE INDEX idx_class_organization_id ON class(organization_id);
-- 3. Create class_course join table
CREATE TABLE class_course (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
class_id UUID NOT NULL REFERENCES class(id) ON DELETE CASCADE,
course_id UUID NOT NULL REFERENCES course(id) ON DELETE CASCADE,
"order" INTEGER NOT NULL DEFAULT 0,
added_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(class_id, course_id)
);
CREATE INDEX idx_class_course_class_id ON class_course(class_id);
-- 4. Create class_member table
CREATE TABLE class_member (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
class_id UUID NOT NULL REFERENCES class(id) ON DELETE CASCADE,
profile_id UUID REFERENCES profile(id),
role_id INTEGER NOT NULL REFERENCES role(id),
email TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(class_id, profile_id)
);
CREATE INDEX idx_class_member_class_id ON class_member(class_id);
CREATE INDEX idx_class_member_profile_id ON class_member(profile_id);
-- 5. Create class_announcement table
CREATE TABLE class_announcement (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
class_id UUID NOT NULL REFERENCES class(id) ON DELETE CASCADE,
author_profile_id UUID REFERENCES profile(id),
title VARCHAR NOT NULL,
body TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_class_announcement_class_id ON class_announcement(class_id);
-- 6. Create class_file table
CREATE TABLE class_file (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
class_id UUID NOT NULL REFERENCES class(id) ON DELETE CASCADE,
uploaded_by_profile_id UUID REFERENCES profile(id),
name VARCHAR NOT NULL,
url TEXT NOT NULL,
mime_type VARCHAR,
size INTEGER,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_class_file_class_id ON class_file(class_id);
-- 7. Add classId to community_question
ALTER TABLE community_question ADD COLUMN class_id UUID REFERENCES class(id) ON DELETE CASCADE;
Access Control Logic
Two middleware functions are needed in apps/api/src/middleware/:
classAccessMiddleware (read access)
Verifies the caller is either an org admin or a class_member for the given :classId. Used on all GET /class/:classId/* routes.
// apps/api/src/middleware/class-access.ts
export async function classAccessMiddleware(c, next) {
const { classId } = c.req.param();
const user = c.get('user')!;
const isMember = await isClassMember(classId, user.profileId);
const isOrgAdmin = await isOrgAdminByClassId(classId, user.profileId);
if (!isMember && !isOrgAdmin) throw new AppError('Forbidden', ErrorCodes.FORBIDDEN, 403);
await next();
}
classAdminMiddleware (write access)
Verifies the caller has roleId 1 (ADMIN) or 2 (TUTOR) within the class, or is an org admin. Used on all mutating routes.
// apps/api/src/middleware/class-admin.ts
export async function classAdminMiddleware(c, next) {
const { classId } = c.req.param();
const user = c.get('user')!;
const role = await getClassMemberRole(classId, user.profileId);
const isOrgAdmin = await isOrgAdminByClassId(classId, user.profileId);
if (!isOrgAdmin && (!role || role > 2)) throw new AppError('Forbidden', ErrorCodes.FORBIDDEN, 403);
await next();
}
API and Route Plan
Validation Layer
File: packages/utils/src/validation/class/class.ts
import { z } from 'zod';
export const ZCreateClass = z.object({
name: z.string().min(1).max(255),
description: z.string().max(2000).optional(),
coverImage: z.string().url().optional()
});
export type TCreateClass = z.infer<typeof ZCreateClass>;
export const ZUpdateClass = z.object({
name: z.string().min(1).max(255).optional(),
description: z.string().max(2000).nullable().optional(),
coverImage: z.string().url().nullable().optional(),
status: z.enum(['ACTIVE', 'INACTIVE', 'ARCHIVED']).optional()
});
export type TUpdateClass = z.infer<typeof ZUpdateClass>;
export const ZAddCourseToClass = z.object({
courseId: z.string().uuid(),
order: z.number().int().min(0).optional()
});
export type TAddCourseToClass = z.infer<typeof ZAddCourseToClass>;
export const ZAddClassMembers = z.object({
members: z.array(
z.object({
email: z.string().email(),
roleId: z.number().int().min(1).max(3)
})
).min(1)
});
export type TAddClassMembers = z.infer<typeof ZAddClassMembers>;
export const ZUpdateClassMember = z.object({
roleId: z.number().int().min(1).max(3)
});
export type TUpdateClassMember = z.infer<typeof ZUpdateClassMember>;
export const ZCreateClassAnnouncement = z.object({
title: z.string().min(1).max(500),
body: z.string().max(10000).optional()
});
export type TCreateClassAnnouncement = z.infer<typeof ZCreateClassAnnouncement>;
export const ZUpdateClassAnnouncement = z.object({
title: z.string().min(1).max(500).optional(),
body: z.string().max(10000).nullable().optional()
});
export type TUpdateClassAnnouncement = z.infer<typeof ZUpdateClassAnnouncement>;
export const ZAddClassFile = z.object({
name: z.string().min(1).max(255),
url: z.string().url(),
mimeType: z.string().optional(),
size: z.number().int().positive().optional()
});
export type TAddClassFile = z.infer<typeof ZAddClassFile>;
Export from: packages/utils/src/validation/class/index.ts and re-export from packages/utils/src/validation/index.ts.
Query Layer
File: packages/db/src/queries/class/class.ts
| Function | Description |
|---|---|
createClass(data) |
Insert into class, return created row |
getClassById(classId) |
Single class with member count and course count |
getClassesByOrg(orgId) |
All non-archived classes for org, ordered by createdAt desc |
updateClass(classId, data) |
Update name, description, coverImage, status |
getClassMemberRole(classId, profileId) |
Return roleId for the given profile in the class, or null |
isClassMember(classId, profileId) |
Boolean check |
isOrgAdminByClassId(classId, profileId) |
Joins class → organization → organizationmember to check admin role |
addClassMember(classId, profileId, roleId, email) |
Insert class_member row (upsert on conflict) |
removeClassMember(classId, memberId) |
Delete class_member by id |
getClassMembers(classId) |
All members joined to profile for display |
getEnrolledClassesByProfile(orgId, profileId) |
All ACTIVE classes where profile is a class member, for LMS |
addCourseToClass(classId, courseId, order) |
Insert class_course row |
removeCourseFromClass(classId, courseId) |
Delete class_course row |
getCoursesByClass(classId) |
All courses in class ordered by order, joined to course |
getStudentMemberIdsByClass(classId) |
All profileId values with roleId = 3 in class (for auto-enrollment) |
createClassAnnouncement(data) |
Insert class_announcement |
getClassAnnouncements(classId) |
All announcements ordered by createdAt desc, joined to profile |
updateClassAnnouncement(announcementId, data) |
Update title/body |
deleteClassAnnouncement(announcementId) |
Delete row |
addClassFile(data) |
Insert class_file |
getClassFiles(classId) |
All files ordered by createdAt desc |
deleteClassFile(fileId) |
Delete class_file by id |
Export from: packages/db/src/queries/class/index.ts
Service Layer
File: apps/api/src/services/class/class.ts
createClass(orgId, profileId, data: TCreateClass)
- Insert
classrow. - Add creator as
class_memberwithroleId = 1(ADMIN). - Return the new class.
addCourseToClass(classId, courseId)
- Verify class exists and course belongs to the same org.
- Insert
class_courserow (error if already linked). - Fetch all current STUDENT class members (
getStudentMemberIdsByClass). - For each student profile, look up their
groupmemberstatus in the course's group; if not already enrolled, callenrollInCourse(or insertgroupmemberdirectly if the course is free and no invite is needed). - All writes in a single transaction.
- Return updated course list for the class.
removeCourseFromClass(classId, courseId)
- Delete
class_courserow. - No changes to
groupmemberrecords. - Return updated course list.
addMembersToClass(classId, members: TAddClassMembers['members'])
Transaction:
- For each member in the batch, resolve
profileIdfromemail(look upprofileby email, create if none exists as an invited-but-unregistered user following the same pattern asaddGroupMember). - Insert
class_memberrow (skip if already a member of the class). - If
roleId = 3(STUDENT), fetch all courses in the class (getCoursesByClass). For each course, check if the student is already agroupmember; if not, insert agroupmemberrow withroleId = 3.
removeMemberFromClass(classId, memberId)
- Delete
class_memberrow byid. - Leave all
groupmemberrows in individual courses intact.
createAnnouncement(classId, profileId, data: TCreateClassAnnouncement)
- Verify caller is class admin or tutor.
- Insert
class_announcementrow. - Return new announcement.
addFile(classId, profileId, data: TAddClassFile)
- Insert
class_filerow. - Return new file record.
deleteFile(fileId, profileId)
- Verify caller is class admin or tutor.
- Delete
class_filerow.
Route Layer
File: apps/api/src/routes/class/class.ts
All routes require authMiddleware. Routes scoped to a :classId also apply classAccessMiddleware (read) or classAdminMiddleware (write) as noted.
| Method | Path | Middleware | Description |
|---|---|---|---|
GET |
/class |
authMiddleware |
List org's classes (org admin sees all; tutors/students see their own) |
POST |
/class |
authMiddleware + orgAdmin |
Create class |
GET |
/class/:classId |
classAccessMiddleware |
Get class with member/course counts |
PUT |
/class/:classId |
classAdminMiddleware |
Update class name, description, cover, status |
DELETE |
/class/:classId |
orgAdmin | Archive class (status = 'ARCHIVED') |
GET |
/class/:classId/courses |
classAccessMiddleware |
List courses in class (ordered) |
POST |
/class/:classId/courses |
classAdminMiddleware |
Add course to class + auto-enroll students |
DELETE |
/class/:classId/courses/:courseId |
classAdminMiddleware |
Remove course from class |
GET |
/class/:classId/members |
classAdminMiddleware |
List class members with profile info |
POST |
/class/:classId/members |
classAdminMiddleware |
Batch-add members + auto-enroll students |
PUT |
/class/:classId/members/:memberId |
classAdminMiddleware |
Update member role |
DELETE |
/class/:classId/members/:memberId |
classAdminMiddleware |
Remove member from class |
GET |
/class/:classId/announcements |
classAccessMiddleware |
List announcements |
POST |
/class/:classId/announcements |
classAdminMiddleware |
Create announcement |
PUT |
/class/:classId/announcements/:announcementId |
classAdminMiddleware |
Update announcement |
DELETE |
/class/:classId/announcements/:announcementId |
classAdminMiddleware |
Delete announcement |
GET |
/class/:classId/files |
classAccessMiddleware |
List files |
POST |
/class/:classId/files |
classAdminMiddleware |
Add file record |
DELETE |
/class/:classId/files/:fileId |
classAdminMiddleware |
Delete file |
Route Registration
// apps/api/src/routes/class/index.ts
export * from './class';
// apps/api/src/app.ts
import { classRouter } from '@api/routes/class';
export const app = new Hono()
// ... existing routes ...
.route('/class', classRouter);
LMS Enrolled Classes Route
Add to apps/api/src/routes/organization/organization.ts:
GET /organization/classes/enrolled
Returns all ACTIVE classes where the current user is a STUDENT class_member, including the course list with per-course progress. Used by the LMS "My Classes" and "Class Hub" pages.
Build Verification
pnpm --filter @cio/utils build
pnpm --filter @cio/db build
pnpm --filter @cio/api build
Frontend Plan (Dashboard)
Request Types
File: apps/dashboard/src/lib/features/class/utils/types.ts
import { classroomio, type InferResponseType } from '$lib/utils/services/api';
export type ListClassesRequest = typeof classroomio.class.$get;
export type CreateClassRequest = typeof classroomio.class.$post;
export type GetClassRequest = typeof classroomio.class[':classId']['$get'];
export type UpdateClassRequest = typeof classroomio.class[':classId']['$put'];
export type ListClassCoursesRequest = typeof classroomio.class[':classId']['courses']['$get'];
export type AddCourseToClassRequest = typeof classroomio.class[':classId']['courses']['$post'];
export type ListClassMembersRequest = typeof classroomio.class[':classId']['members']['$get'];
export type AddClassMembersRequest = typeof classroomio.class[':classId']['members']['$post'];
export type ListAnnouncementsRequest = typeof classroomio.class[':classId']['announcements']['$get'];
export type CreateAnnouncementRequest = typeof classroomio.class[':classId']['announcements']['$post'];
export type ListClassFilesRequest = typeof classroomio.class[':classId']['files']['$get'];
export type ListClassesSuccess = Extract<InferResponseType<ListClassesRequest>, { success: true }>;
export type ClassItem = ListClassesSuccess['data'][number];
export type GetClassSuccess = Extract<InferResponseType<GetClassRequest>, { success: true }>;
export type ClassDetail = GetClassSuccess['data'];
export type ListClassCoursesSuccess = Extract<InferResponseType<ListClassCoursesRequest>, { success: true }>;
export type ClassCourse = ListClassCoursesSuccess['data'][number];
export type ListClassMembersSuccess = Extract<InferResponseType<ListClassMembersRequest>, { success: true }>;
export type ClassMember = ListClassMembersSuccess['data'][number];
export type ListAnnouncementsSuccess = Extract<InferResponseType<ListAnnouncementsRequest>, { success: true }>;
export type ClassAnnouncement = ListAnnouncementsSuccess['data'][number];
export type ListClassFilesSuccess = Extract<InferResponseType<ListClassFilesRequest>, { success: true }>;
export type ClassFile = ListClassFilesSuccess['data'][number];
// LMS enrolled classes
export type EnrolledClassesRequest = typeof classroomio.organization.classes.enrolled['$get'];
export type EnrolledClassesSuccess = Extract<InferResponseType<EnrolledClassesRequest>, { success: true }>;
export type EnrolledClass = EnrolledClassesSuccess['data'][number];
API Class
File: apps/dashboard/src/lib/features/class/api/class.svelte.ts
class ClassApi extends BaseApiWithErrors {
classes = $state<ClassItem[]>([]);
currentClass = $state<ClassDetail | null>(null);
courses = $state<ClassCourse[]>([]);
members = $state<ClassMember[]>([]);
announcements = $state<ClassAnnouncement[]>([]);
files = $state<ClassFile[]>([]);
loading = $state(false);
async list() { /* GET /class */ }
async get(classId: string) { /* GET /class/:classId */ }
async create(data: TCreateClass) { /* POST /class */ }
async update(classId: string, data: TUpdateClass) { /* PUT /class/:classId */ }
async archive(classId: string) { /* DELETE /class/:classId */ }
async listCourses(classId: string) { /* GET /class/:classId/courses */ }
async addCourse(classId: string, data: TAddCourseToClass) { /* POST /class/:classId/courses */ }
async removeCourse(classId: string, courseId: string) { /* DELETE /class/:classId/courses/:courseId */ }
async listMembers(classId: string) { /* GET /class/:classId/members */ }
async addMembers(classId: string, data: TAddClassMembers) { /* POST /class/:classId/members */ }
async removeMember(classId: string, memberId: string) { /* DELETE /class/:classId/members/:memberId */ }
async listAnnouncements(classId: string) { /* GET /class/:classId/announcements */ }
async createAnnouncement(classId: string, data: TCreateClassAnnouncement) { /* POST */ }
async deleteAnnouncement(classId: string, announcementId: string) { /* DELETE */ }
async listFiles(classId: string) { /* GET /class/:classId/files */ }
async addFile(classId: string, data: TAddClassFile) { /* POST /class/:classId/files */ }
async deleteFile(classId: string, fileId: string) { /* DELETE /class/:classId/files/:fileId */ }
}
export const classApi = new ClassApi();
LMS API Class
File: apps/dashboard/src/lib/features/lms/api/class.svelte.ts
class LmsClassApi extends BaseApiWithErrors {
enrolledClasses = $state<EnrolledClass[]>([]);
loading = $state(false);
async listEnrolled() { /* GET /organization/classes/enrolled */ }
}
export const lmsClassApi = new LmsClassApi();
Admin Pages
| Route | File | Purpose |
|---|---|---|
/courses/classes |
apps/dashboard/src/routes/courses/classes/+page.svelte |
List all org classes |
/courses/classes/new |
apps/dashboard/src/routes/courses/classes/new/+page.svelte |
Create class form |
/courses/classes/[classId] |
apps/dashboard/src/routes/courses/classes/[classId]/+page.svelte |
Class overview |
/courses/classes/[classId]/courses |
.../courses/+page.svelte |
Manage courses |
/courses/classes/[classId]/people |
.../people/+page.svelte |
Manage members |
/courses/classes/[classId]/announcements |
.../announcements/+page.svelte |
Manage announcements |
/courses/classes/[classId]/files |
.../files/+page.svelte |
File library management |
Feature pages live in: apps/dashboard/src/lib/features/class/pages/
LMS Pages
| Route | File | Purpose |
|---|---|---|
/lms/classes |
apps/dashboard/src/routes/lms/classes/+page.svelte |
My enrolled classes |
/lms/classes/[classId] |
apps/dashboard/src/routes/lms/classes/[classId]/+page.svelte |
Class hub (courses + announcements + files) |
/lms/classes/[classId]/community |
.../community/+page.svelte |
Class community Q&A |
Feature pages live in: apps/dashboard/src/lib/features/lms/pages/class/
Navigation Updates
Org admin sidebar (apps/dashboard/src/lib/features/org/):
- Add "Classes" nav item at the same level as "Courses", linking to
/courses/classes. - Use a suitable icon (e.g., a group/layers icon).
LMS sidebar (apps/dashboard/src/lib/features/lms/):
- Add "Classes" nav item (shown conditionally: only when
enrolledClasses.length > 0). - Position between "My Learning" and "Exercises".
Translations
File: apps/dashboard/src/lib/utils/translations/en.json
Add keys under class:
{
"class": {
"title": "Classes",
"my_classes": "My Classes",
"create": "Create Class",
"create_description": "Group multiple courses and materials under one class for your students.",
"name": "Class Name",
"description": "Description",
"cover_image": "Cover Image",
"status": "Status",
"active": "Active",
"inactive": "Inactive",
"archived": "Archived",
"courses": "Courses",
"people": "People",
"announcements": "Announcements",
"files": "Files",
"community": "Community",
"add_course": "Add Course",
"remove_course": "Remove Course",
"add_members": "Add Members",
"remove_member": "Remove Member",
"course_count": "{count} courses",
"student_count": "{count} students",
"new_announcement": "New Announcement",
"announcement_title": "Announcement Title",
"announcement_body": "Write your announcement...",
"upload_file": "Upload File",
"no_classes": "No classes yet. Create one to get started.",
"no_courses": "No courses in this class yet.",
"no_members": "No members yet. Add students or tutors.",
"no_announcements": "No announcements yet.",
"no_files": "No files uploaded yet.",
"archive_confirm": "Archiving this class will hide it from all views. Are you sure?",
"auto_enroll_note": "Adding this course will enroll all current class students in it.",
"remove_course_note": "Removing this course will not unenroll any students.",
"remove_member_note": "Removing this member will not unenroll them from individual courses."
}
}
Frontend Build Verification
pnpm --filter @cio/dashboard build
Implementation Order
Phase 1: Database + Schema
- Add
classStatusenum topackages/db/src/schema.ts. - Add
lmsClass,classCourse,classMember,classAnnouncement,classFiletables to schema. - Add
classIdFK column tocommunityQuestiontable in schema. - Write and apply migration SQL:
packages/db/src/migrations/XXXX_add_classes.sql. - Run
pnpm --filter @cio/db build.
Phase 2: Validation + Queries
- Create
packages/utils/src/validation/class/class.tswith all Zod schemas. - Export from
packages/utils/src/validation/class/index.tsand re-export frompackages/utils/src/validation/index.ts. - Run
pnpm --filter @cio/utils build. - Create
packages/db/src/queries/class/class.tswith all query functions. - Create
packages/db/src/queries/class/index.tsand export. - Run
pnpm --filter @cio/db build.
Phase 3: Service + Routes
- Create
apps/api/src/services/class/class.tswith all service functions (auto-enrollment transactions are the most complex part). - Create access control utilities:
apps/api/src/middleware/class-access.tsandapps/api/src/middleware/class-admin.ts. - Add new error codes to
apps/api/src/utils/errors.ts:CLASS_NOT_FOUND,CLASS_FORBIDDEN,COURSE_ALREADY_IN_CLASS,MEMBER_ALREADY_IN_CLASS. - Create
apps/api/src/routes/class/class.tswith all route handlers. - Create
apps/api/src/routes/class/index.tsand register inapps/api/src/app.ts. - Add
GET /organization/classes/enrolledto the organization router. - Run
pnpm --filter @cio/api build.
Phase 4: Admin Frontend
- Add request/response types to
apps/dashboard/src/lib/features/class/utils/types.ts. - Create
apps/dashboard/src/lib/features/class/api/class.svelte.tsAPI class. - Add translation keys to
en.json. - Create admin feature pages under
apps/dashboard/src/lib/features/class/pages/. - Create SvelteKit route files under
apps/dashboard/src/routes/courses/classes/. - Add "Classes" nav item to the org admin sidebar.
- Run
pnpm --filter @cio/dashboard build.
Phase 5: LMS Frontend
- Create
apps/dashboard/src/lib/features/lms/api/class.svelte.ts. - Create LMS feature pages under
apps/dashboard/src/lib/features/lms/pages/class/. - Create SvelteKit route files under
apps/dashboard/src/routes/lms/classes/. - Add "Classes" nav item to the LMS sidebar (conditional on having enrolled classes).
- Run
pnpm --filter @cio/dashboard build.
Acceptance Criteria
- Org admin can create a class, add courses to it, and add students — all from the admin dashboard.
- When a student is added to a class,
groupmemberrows are automatically created for every course in the class. - When a course is added to an existing class that already has students, all those students are enrolled in the new course.
- Removing a student from a class does not remove their
groupmemberrecords in individual courses. - Removing a course from a class does not unenroll any students.
- Students see a "Classes" section in the LMS sidebar (only when enrolled in at least one class).
- The class hub page shows all courses with per-course progress bars, the announcements feed, and the file library.
- Class admins and tutors can post announcements and upload files; students can only view them.
- Class community Q&A is scoped to the class and does not appear on course community boards.
INACTIVEclasses are hidden from the student LMS but remain fully accessible to admins and tutors.ARCHIVEDclasses are hidden from all views.- Courses that are not in any class, and courses whose students were enrolled independently, continue to work exactly as they do today (zero regression on existing
groupmemberand course data). - All user-facing strings use translation keys (no hardcoded English).
pnpm --filter @cio/api buildandpnpm --filter @cio/dashboard buildpass after implementation.
Risks and Mitigations
-
Risk: Auto-enrollment transaction for large classes (hundreds of students, tens of courses) times out or partially fails.
- Mitigation: Process auto-enrollment in the service layer using a single transaction with batch inserts (insert multiple
groupmemberrows in one query using Drizzle's batch insert). For very large classes (> 500 students), offload to a background job via the existing email job queue or a new async task runner, and return a202 Acceptedwith a polling endpoint.
- Mitigation: Process auto-enrollment in the service layer using a single transaction with batch inserts (insert multiple
-
Risk: A student is already enrolled in a course independently before being added to a class. Duplicate
groupmemberrows violate the(groupId, profileId)unique constraint.- Mitigation: The enrollment logic in
addMembersToClassmust check for existing membership before inserting. UseINSERT ... ON CONFLICT DO NOTHINGor check withisUserCourseMemberbefore inserting. This is already idempotent in the existing enrollment service.
- Mitigation: The enrollment logic in
-
Risk: The
community_question.classIdcolumn causes existing community queries to break if they don't filter byclassId IS NULLfor course-scoped questions.- Mitigation: Add
classId IS NULLto all existing community query filters wherecourseIdis used. The column is nullable so existing rows default to NULL and behavior is unchanged. Updatepackages/db/src/queries/community/community.tsalongside the schema migration.
- Mitigation: Add
-
Risk: Removing a course from a class causes confusion: students are still enrolled in the course but it no longer appears in the class hub.
- Mitigation: Show a confirmation dialog in the admin UI with the note: "Removing this course will not unenroll any students. They will still have access to it via My Learning." Use the
class.remove_course_notetranslation key already specified.
- Mitigation: Show a confirmation dialog in the admin UI with the note: "Removing this course will not unenroll any students. They will still have access to it via My Learning." Use the
-
Risk: Org nav gets crowded with a new "Classes" top-level item.
- Mitigation: Place "Classes" directly below "Courses" in the sidebar. Consider grouping them under a "Learning" section header if more items are added in future.