* 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * fix(dashboard): self-hosted CSP uses only env vars, no defaults Co-authored-by: Rotimi Best <[email protected]> * fix(dashboard): add all classroomio.com domains to CSP defaults Co-authored-by: Rotimi Best <[email protected]> * docs: add CSP ALLOWED_EXTERNAL_DOMAINS to self-hosting guides Co-authored-by: Rotimi Best <[email protected]> * feat(docker): pass CSP domain env vars as build args to dashboard Co-authored-by: Rotimi Best <[email protected]> --------- Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: Rotimi Best <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * docs: add MINIO_ROOT_USER and MINIO_ROOT_PASSWORD to self-hosting guides Co-authored-by: Rotimi Best <[email protected]> * 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 <[email protected]> Co-authored-by: Rotimi Best <[email protected]> * 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 <[email protected]> * 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 <[email protected]> Co-authored-by: Rotimi Best <[email protected]> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --------- Co-authored-by: Cursor <[email protected]> Co-authored-by: Rotimi Best <[email protected]> Co-authored-by: Abdulmuizz Hamzat <[email protected]> Co-authored-by: Adeyemi Adetunji <[email protected]> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Course Templates PRD
Purpose
Enable instructors to create reusable course blueprints (templates) that can be used to quickly spin up new courses with pre-built structure, content, and settings. Templates reduce repetitive setup work and help organizations standardize course quality.
Problem Statement
Currently, the only way to reuse course content in ClassroomIO is the clone feature, which creates a full copy of a specific course. This has limitations:
- No discoverability: There is no way to browse reusable starting points when creating a course. Instructors must know which existing course to clone.
- No separation of blueprint vs live course: Cloned courses immediately become live courses with active status, mixing templates with real courses in the listing.
- No selective content inclusion: Clone copies everything — there is no way to include structure but exclude detailed content, or include exercises but exclude lesson notes.
- No organizational template library: Organizations cannot curate a set of approved course structures for their instructors to use.
isTemplatefield is unused: Thecoursetable already has anisTemplateboolean (defaults totrue), but it is never meaningfully filtered on — every course has it set totrue.
Confirmed Decisions
- Templates are courses: A template is a
courserow withisTemplate = trueandstatus = 'TEMPLATE'. No new content tables are needed. The existing course editor is reused for building templates. - Org-scoped: Templates belong to an organization (via the existing
group→organizationIdrelationship). Each org has its own template library. - Built on clone infrastructure: Creating a course from a template reuses the existing
cloneCourse()service with modifications to mark the result as a real course (isTemplate = false). - Templates are never published: Templates do not appear in public course listings, student-facing pages, or enrollment flows. They are instructor-only blueprints.
- Non-destructive: Deleting a template does not affect courses already created from it. Courses created from a template become fully independent copies.
- Selective content: When saving an existing course as a template, instructors can choose which content types to include (structure, lesson content, exercises, settings).
Current-State Audit
| Capability | Current State | Notes |
|---|---|---|
isTemplate field |
Exists on course table, defaults to true |
Never filtered on — effectively unused |
| Course cloning | Full deep-copy via cloneCourse() service |
Copies sections, lessons, exercises, questions, options, translations |
| Clone UI | "Clone" option in course card dropdown menu | Component: copy-course-modal.svelte |
| Clone endpoint | POST /course/:courseId/clone |
Accepts title, description, slug, organizationId |
| Course creation | Two-step modal: type selection → title/description | Component: new-course-modal.svelte |
| Exercise templates | Separate exercise_template table |
Existing pattern for template-based creation at exercise level |
| Course listing filter | Queries getOrgCourses() with filters for title, tags, sort |
No filter for isTemplate or status = 'TEMPLATE' |
| Course status | Text field, default 'ACTIVE' |
Used for soft delete ('DELETED'), no 'TEMPLATE' value |
Data Sources Checked
packages/db/src/schema.ts— course table definition,isTemplatefieldapps/api/src/services/course/clone.ts— full clone implementationapps/api/src/services/course/course.ts— course creation flowapps/api/src/routes/course/course.ts— course routes including cloneapps/dashboard/src/lib/features/course/components/new-course-modal.svelte— creation UIapps/dashboard/src/lib/features/course/components/copy-course-modal.svelte— clone UIapps/dashboard/src/lib/features/course/api/course.svelte.ts— frontend course APIapps/dashboard/src/lib/features/course/api/course-clone.svelte.ts— frontend clone APIapps/dashboard/src/routes/org/[slug]/courses/+page.svelte— course listing pagepackages/db/src/queries/course/course.ts— course queriesapps/dashboard/src/lib/features/ui/navigation/org-navigation.ts— org navigation
Product Goals
- Instructors can save any existing course as a reusable template with selective content inclusion.
- Instructors can create templates from scratch using the existing course editor.
- When creating a new course, instructors can choose to start from a template instead of a blank course.
- Organizations have a template library (tab on the courses page) where templates are managed.
- Templates are cleanly separated from live courses in all listings and queries.
- Courses created from templates are fully independent — no ongoing link or sync.
- The existing course creation and clone flows remain unchanged for users who do not use templates.
Non-Goals (v1)
- Platform-wide template marketplace (orgs sharing templates publicly).
- ClassroomIO-provided starter templates (curated by the platform team).
- AI-generated templates (e.g., "Generate a template for a 4-week React course").
- Template versioning or change tracking.
- Syncing updates from a template to courses already created from it.
- Template access control (e.g., restricting which instructors can use which templates).
- Template analytics beyond usage count.
UX Flow
Flow 1: Creating a Template from an Existing Course
Entry points:
- Course card dropdown menu → "Save as Template" (alongside existing "Clone" option)
- Course Settings page → "Save as Template" button
Steps:
- User clicks "Save as Template."
- A modal appears with:
- Template name — pre-filled with
"{course title} Template", editable. - Description — pre-filled from course description, editable.
- Category — optional free-text or select from existing categories (e.g., "Onboarding", "Compliance", "Technical").
- What to include — checkboxes:
- Sections & structure (always on, disabled)
- Lesson content (notes, videos, documents) — default on
- Exercises & quizzes — default on
- Course settings (grading, certificates, metadata) — default on
- Landing page content — default off
- Info note: "Student data, submissions, and enrollments are never included."
- Template name — pre-filled with
- User confirms → system clones the course into a new
courserow withisTemplate = true,status = 'TEMPLATE',isPublished = false. - Success snackbar: "Template created" with a link to the templates tab.
Flow 2: Creating a Template from Scratch
Entry point: Templates tab on the courses page → "Create Template" button.
Steps:
- User clicks "Create Template."
- Same two-step modal as course creation (type selection → title/description), but the resulting course is marked as a template.
- Navigates to the course editor with a "Template" badge in the header.
- User builds out the structure (sections, lessons, exercises) using the existing editor.
- Template never appears in student-facing listings.
Flow 3: Creating a Course from a Template
Entry point: Existing "Create Course" button on the courses page.
Steps:
- User clicks "Create Course."
- Step 1 — Choose starting point (replaces the current type selection step):
- Two cards: "Blank Course" and "From Template".
- "Blank Course" proceeds to the existing flow (type → title/description).
- "From Template" opens the template picker (step 1b).
- Step 1b — Template picker:
- Search bar to filter templates by name.
- Category filter tabs (if categories exist).
- Grid of template cards showing: name, description snippet, lesson count, exercise count, course type badge.
- Each card has a "Preview" action that expands a panel showing the full section/lesson outline (read-only).
- User selects a template and clicks "Use Template."
- Step 2 — Customize:
- Title — pre-filled from template, editable.
- Description — pre-filled from template, editable.
- Type — inherited from template, overridable (Live Class / Self-paced).
- Subtitle: "Based on: {template name}".
- User clicks "Create Course" → system clones the template into a real course (
isTemplate = false,status = 'ACTIVE') → navigates to the new course editor with all template content pre-populated.
Flow 4: Managing Templates
Entry point: Courses page → "Templates" tab.
The courses page (/org/[slug]/courses) gets a tab bar: [My Courses] | [Templates].
Templates tab features:
- Grid of template cards with: name, description, course type, lesson count, exercise count, usage count ("Used N times").
- Card dropdown menu: Edit, Duplicate, Delete.
- "Create Template" button.
- Edit: Opens the course editor with a "Template" badge. Same editing experience as a real course.
- Duplicate: Clones the template into another template.
- Delete: Soft-deletes the template (
status = 'DELETED'). Confirmation dialog: "This will not affect courses already created from this template."
Technical Design
Data Model Changes
Modified Table: course
- Fix
isTemplatedefault fromtruetofalse. New courses should not be flagged as templates by default. - Add
templateSourceId— nullable UUID FK tocourse.id. Tracks which template a course was created from. Used for usage count analytics ("12 courses created from this template"). - Add
templateCategory— nullable varchar. Optional category for organizing templates in the picker.
// packages/db/src/schema.ts — additions to course table
isTemplate: boolean('is_template').default(false), // changed from true to false
templateSourceId: uuid('template_source_id'),
templateCategory: varchar('template_category'),
// Add to constraints:
foreignKey({
columns: [table.templateSourceId],
foreignColumns: [table.id],
name: 'course_template_source_id_fkey'
}).onDelete('set null')
No new tables needed. Templates are courses filtered by isTemplate = true and status = 'TEMPLATE'.
Backward Compatibility
Existing courses all have isTemplate = true due to the current default. A data migration will set isTemplate = false for all existing courses (they are real courses, not templates). The migration is safe because the field is not currently used in any queries or business logic.
Migration
Create migration file: packages/db/src/migrations/XXXX_add_course_templates.sql
-- 1. Fix isTemplate for all existing courses (they are real courses, not templates)
UPDATE course SET is_template = false WHERE is_template = true;
-- 2. Change default for is_template to false
ALTER TABLE course ALTER COLUMN is_template SET DEFAULT false;
-- 3. Add template_source_id column
ALTER TABLE course ADD COLUMN template_source_id UUID REFERENCES course(id) ON DELETE SET NULL;
-- 4. Add template_category column
ALTER TABLE course ADD COLUMN template_category VARCHAR(255);
-- 5. Add index for template queries
CREATE INDEX idx_course_is_template ON course(is_template) WHERE is_template = true;
-- 6. Add index for template usage count
CREATE INDEX idx_course_template_source_id ON course(template_source_id) WHERE template_source_id IS NOT NULL;
Validation Layer
File: packages/utils/src/validation/course/template.ts
import { z } from 'zod';
export const ZSaveAsTemplate = z.object({
title: z.string().min(1).max(255),
description: z.string().min(1),
category: z.string().max(100).optional(),
includeLessonContent: z.boolean().default(true),
includeExercises: z.boolean().default(true),
includeSettings: z.boolean().default(true),
includeLandingPage: z.boolean().default(false)
});
export type TSaveAsTemplate = z.infer<typeof ZSaveAsTemplate>;
export const ZCreateFromTemplate = z.object({
templateId: z.string().uuid(),
title: z.string().min(1),
description: z.string().min(1),
type: z.enum(['LIVE_CLASS', 'SELF_PACED']).optional(),
organizationId: z.string().min(1)
});
export type TCreateFromTemplate = z.infer<typeof ZCreateFromTemplate>;
export const ZCreateTemplate = z.object({
title: z.string().min(1),
description: z.string().min(1),
type: z.enum(['LIVE_CLASS', 'SELF_PACED']),
category: z.string().max(100).optional(),
organizationId: z.string().min(1)
});
export type TCreateTemplate = z.infer<typeof ZCreateTemplate>;
export const ZUpdateTemplate = z.object({
title: z.string().min(1).max(255).optional(),
description: z.string().min(1).optional(),
category: z.string().max(100).nullable().optional()
});
export type TUpdateTemplate = z.infer<typeof ZUpdateTemplate>;
Export from: packages/utils/src/validation/course/index.ts
Query Layer
File: packages/db/src/queries/course/template.ts
Functions:
getOrgTemplates(organizationId)— list all templates for an org. Returns templates with lesson count, exercise count, and usage count (number of courses withtemplateSourceIdpointing to this template). Ordered bycreatedAtdesc.getTemplateById(templateId)— single template with full details and usage count.getTemplateUsageCount(templateId)— count of courses created from this template.
Export from: packages/db/src/queries/course/index.ts
Service Layer
File: apps/api/src/services/course/template.ts
saveAsTemplate(courseId, userId, data: TSaveAsTemplate)
- Fetch the source course.
- Clone it via a modified
cloneCourse()that respects theinclude*flags:- Always clone sections (structure).
- Skip lesson content (notes, videos, documents) if
includeLessonContent = false— create lessons with title and order only. - Skip exercises if
includeExercises = false. - Skip metadata fields if
includeSettings = false. - Skip landing page fields (bannerImage, metadata.videoUrl, etc.) if
includeLandingPage = false.
- Set
isTemplate = true,status = 'TEMPLATE',isPublished = falseon the new course. - Set
templateCategoryif provided. - Return the new template.
createTemplate(userId, data: TCreateTemplate)
- Create a new course with
isTemplate = true,status = 'TEMPLATE',isPublished = false. - Follow the same transaction as
createCourse()(create group → course → add creator as TUTOR). - Set
templateCategoryif provided. - Return the new template.
createFromTemplate(templateId, userId, data: TCreateFromTemplate)
- Fetch the template. Verify
isTemplate = true. - Clone via
cloneCourse()with all content included. - Override:
isTemplate = false,status = 'ACTIVE',isPublished = false. - Override:
title,description,typefrom user input. - Set
templateSourceId = templateIdon the new course. - Return the new course.
deleteTemplate(templateId)
- Verify the course is a template (
isTemplate = true). - Soft delete: set
status = 'DELETED'. - Does not affect courses with
templateSourceId = templateId.
Route Layer
File: apps/api/src/routes/course/template.ts
All routes nested under /course/template and require authMiddleware + admin/tutor role.
| Method | Path | Description |
|---|---|---|
GET |
/course/template |
List org templates (query param: organizationId) |
POST |
/course/template |
Create blank template |
GET |
/course/template/:templateId |
Get template details |
PUT |
/course/template/:templateId |
Update template metadata |
DELETE |
/course/template/:templateId |
Soft-delete template |
POST |
/course/:courseId/save-as-template |
Save existing course as template |
POST |
/course/template/:templateId/create-course |
Create new course from template |
POST |
/course/template/:templateId/duplicate |
Duplicate a template |
Route Registration
// apps/api/src/routes/course/index.ts
export * from './template';
// Registration in course router
.route('/template', templateRouter)
Modified Existing Queries
getOrgCourses(organizationId, ...)
Add filter: WHERE is_template = false AND status != 'TEMPLATE' to exclude templates from the normal course listing. This ensures the "My Courses" tab only shows real courses.
Error Codes
Add to apps/api/src/utils/errors.ts:
TEMPLATE_NOT_FOUND: 'TEMPLATE_NOT_FOUND',
NOT_A_TEMPLATE: 'NOT_A_TEMPLATE',
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/course/utils/types.ts
export type ListTemplatesRequest = typeof classroomio.course.template.$get;
export type CreateTemplateRequest = typeof classroomio.course.template.$post;
export type GetTemplateRequest = typeof classroomio.course.template[':templateId']['$get'];
export type UpdateTemplateRequest = typeof classroomio.course.template[':templateId']['$put'];
export type DeleteTemplateRequest = typeof classroomio.course.template[':templateId']['$delete'];
export type SaveAsTemplateRequest = typeof classroomio.course[':courseId']['save-as-template']['$post'];
export type CreateFromTemplateRequest = typeof classroomio.course.template[':templateId']['create-course']['$post'];
export type ListTemplatesSuccess = Extract<InferResponseType<ListTemplatesRequest>, { success: true }>;
export type CourseTemplate = ListTemplatesSuccess['data'][number];
API Class
File: apps/dashboard/src/lib/features/course/api/template.svelte.ts
class TemplateApi extends BaseApiWithErrors {
templates = $state<CourseTemplate[]>([]);
loading = $state(false);
async list(organizationId: string) { ... }
async create(data: TCreateTemplate) { ... }
async update(templateId: string, data: TUpdateTemplate) { ... }
async remove(templateId: string) { ... }
async saveAsTemplate(courseId: string, data: TSaveAsTemplate) { ... }
async createFromTemplate(templateId: string, data: TCreateFromTemplate) { ... }
async duplicate(templateId: string) { ... }
}
New/Modified Components
save-as-template-modal.svelte
Location: apps/dashboard/src/lib/features/course/components/save-as-template-modal.svelte
Modal with: title, description, category, content inclusion checkboxes, confirm button.
template-picker.svelte
Location: apps/dashboard/src/lib/features/course/components/template-picker.svelte
Grid of template cards with search, category filters, preview panel, and "Use Template" action.
Modified: new-course-modal.svelte
Add a new initial step: "Blank Course" vs "From Template" card selection. "Blank" proceeds to existing flow. "From Template" shows template-picker.svelte, then proceeds to the customize step.
Modified: Course card dropdown
Add "Save as Template" option alongside existing "Clone" option.
Modified: Courses page
Add tab bar: [My Courses] | [Templates]. The templates tab renders the template management grid.
Template Badge
When editing a template in the course editor, show a persistent badge in the header: a colored pill reading "Template" (e.g., bg-blue-100 text-blue-800). This makes it clear the user is editing a blueprint, not a live course.
Routes
| Route | Page |
|---|---|
/org/[slug]/courses?tab=templates |
Templates tab on courses page (no new route file — tab state via query param) |
No new route files needed — the templates tab lives on the existing courses page, controlled by a tab query parameter.
Translations
File: apps/dashboard/src/lib/utils/translations/en.json
Add keys under course.templates:
{
"course": {
"templates": {
"title": "Templates",
"create": "Create Template",
"save_as_template": "Save as Template",
"from_template": "From Template",
"blank_course": "Blank Course",
"blank_course_description": "Start with an empty course",
"from_template_description": "Choose from your template library",
"choose_starting_point": "How would you like to start?",
"choose_template": "Choose a template",
"customize_course": "Customize your course",
"based_on": "Based on: {name}",
"use_template": "Use Template",
"preview": "Preview",
"template_name": "Template Name",
"category": "Category",
"what_to_include": "What to include",
"sections_structure": "Sections & structure",
"lesson_content": "Lesson content (notes, videos, documents)",
"exercises_quizzes": "Exercises & quizzes",
"course_settings": "Course settings (grading, certificates)",
"landing_page_content": "Landing page content",
"student_data_note": "Student data, submissions, and enrollments are never included.",
"template_created": "Template created",
"view_templates": "View in Templates",
"template_badge": "Template",
"used_times": "Used {count} times",
"no_templates": "No templates yet. Save an existing course as a template or create one from scratch.",
"delete_confirm": "This will not affect courses already created from this template.",
"lessons_count": "{count} lessons",
"exercises_count": "{count} exercises",
"search_templates": "Search templates..."
}
}
}
Frontend Build Verification
pnpm --filter @cio/dashboard build
Implementation Order
Phase 1: Database + Schema
- Update
isTemplatedefault fromtruetofalsein schema. - Add
templateSourceIdandtemplateCategorycolumns tocoursetable in schema. - Create migration: fix existing data, add columns, add indexes.
- Run
pnpm --filter @cio/db build.
Phase 2: Validation + Queries
- Create
packages/utils/src/validation/course/template.tswith all Zod schemas. - Export from
packages/utils/src/validation/course/index.ts. - Create
packages/db/src/queries/course/template.tswith query functions. - Update
getOrgCoursesto exclude templates. - Export from
packages/db/src/queries/course/index.ts. - Run
pnpm --filter @cio/utils buildandpnpm --filter @cio/db build.
Phase 3: Service + Routes
- Create
apps/api/src/services/course/template.tswith all service functions. - Refactor
cloneCourse()to accept an options object for selective content cloning. - Create
apps/api/src/routes/course/template.tswith all route handlers. - Register template router in course route index.
- Add error codes to
apps/api/src/utils/errors.ts. - Run
pnpm --filter @cio/api build.
Phase 4: Frontend — Template Management
- Add request types to
apps/dashboard/src/lib/features/course/utils/types.ts. - Create
apps/dashboard/src/lib/features/course/api/template.svelte.tsAPI class. - Add translation keys to
en.json. - Add "Templates" tab to courses page.
- Create template card component for the grid.
- Add "Save as Template" to course card dropdown and course settings.
- Create
save-as-template-modal.svelte. - Run
pnpm --filter @cio/dashboard build.
Phase 5: Frontend — Create from Template
- Modify
new-course-modal.svelteto add "Blank" vs "From Template" step. - Create
template-picker.sveltewith search, categories, preview. - Add customize step with template-prefilled fields.
- Add "Template" badge to course editor header when editing a template.
- Run
pnpm --filter @cio/dashboard build.
Acceptance Criteria
- Instructor can save an existing course as a template with selective content inclusion.
- Instructor can create a blank template from the templates tab.
- Templates appear in the "Templates" tab and do not appear in the "My Courses" tab.
- Instructor can create a new course from a template via the "Create Course" flow.
- Courses created from templates are fully independent — editing the template does not affect the course and vice versa.
- Template cards show lesson count, exercise count, and usage count.
- Template picker supports search and category filtering.
- Template preview shows the section/lesson outline in a read-only view.
- Existing course creation flow ("Blank Course") is unchanged.
- Existing clone functionality is unchanged.
- Deleting a template does not affect courses created from it.
- Templates are not visible to students in any listing or enrollment flow.
- Editing a template uses the same course editor with a "Template" badge.
- All existing courses have
isTemplate = falseafter migration. - All new UI strings use translation keys (no hardcoded English).
pnpm --filter @cio/api buildandpnpm --filter @cio/dashboard buildpass after implementation.
Risks and Mitigations
-
Risk: Changing
isTemplatedefault fromtruetofalseand bulk-updating existing courses could cause issues if any code relies onisTemplate = true.- Mitigation: Codebase search confirms
isTemplateis never used in filtering or conditional logic — it is only copied during clone. The migration is safe.
- Mitigation: Codebase search confirms
-
Risk: Refactoring
cloneCourse()to support selective content could break existing clone functionality.- Mitigation: The refactor adds an optional
optionsparameter. When not provided, all content is cloned (current behavior). Existing clone callers are not affected.
- Mitigation: The refactor adds an optional
-
Risk: Templates accumulate and become hard to find.
- Mitigation: Category filtering and search are built into the template picker from v1. Categories can be extended to tags in a future iteration.
Future Considerations
- Platform starter templates: ClassroomIO-provided templates shown in a separate "ClassroomIO Templates" section of the picker.
- AI-generated templates: "Generate with AI" as a third option in the course creation flow alongside "Blank" and "From Template."
- Template marketplace: Orgs opt-in to share templates publicly.
- Template versioning: Track changes and allow courses to "pull updates" from the source template.
- Template access control: Restrict which instructors can use or edit certain templates.
- Cohort integration: When course cohorts ship, templates could include default cohort configuration.