feat: complete rewrite of course (#622)

* 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>
This commit is contained in:
Rotimi Best
2026-03-09 11:18:22 +01:00
committed by GitHub
co-authored by Rotimi Best greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> Cursor Agent Abdulmuizz Hamzat Adeyemi Adetunji
parent a42565ad82
commit 1e9a82e912
1196 changed files with 118809 additions and 74705 deletions
@@ -0,0 +1,626 @@
---
name: AI assistant PRD
overview: Write a new PRD from scratch for the AI Course Assistant feature, replacing the existing placeholder at prd/ai-course-assistant/README.md. The PRD will document a hybrid execution model, configurable LLM providers, streaming chat, and the full package/API/UI architecture.
todos:
- id: write-prd
content: "Write the full PRD markdown file at prd/ai-course-assistant/README.md with all sections: purpose, architecture, execution model, package design, tools, safeguards, UI spec, self-host gating, streaming, API routes, and implementation phases"
status: pending
isProject: false
---
# AI Course Assistant PRD
## What We're Writing
Replace [prd/ai-course-assistant/README.md](prd/ai-course-assistant/README.md) with a comprehensive PRD for an AI assistant embedded in the course UI. The PRD will be a single markdown file covering architecture, UI, safeguards, package design, and implementation phases.
## Key Architectural Decisions
### Execution Model: Hybrid (Local Reads, API Writes)
The client already has course content loaded in Svelte stores (`lessonApi`, exercise `questionnaire`, etc.) when the teacher is on a page. The agent should:
- **Read context from the client** — pass the current lesson text, exercise questions, course structure to the agent as context with each message. No extra API calls to "read" content.
- **Write through the API** — all mutations route through existing API endpoints (`/course/:courseId/lesson`, `/course/:courseId/exercise`, etc.) using the full middleware stack (`authMiddleware` -> `orgMemberMiddleware` -> `courseTeamMemberMiddleware`). This gives us permission enforcement, single source of truth, and auditability for free.
- **Preview for destructive changes** — when the agent rewrites a lesson or makes a large edit, show a diff/preview in the chat with an "Apply" button. For additive actions (generate 5 questions), execute directly and confirm.
### Agent Architecture: Tool-Calling Pattern
The agent uses LLM function/tool calling (not free-form text parsing):
```mermaid
sequenceDiagram
participant Teacher
participant ChatUI as Chat UI
participant AgentAPI as Agent API
participant LLM
participant Services as Existing Services
Teacher->>ChatUI: "Generate 5 MCQ questions from this lesson"
ChatUI->>AgentAPI: POST /agent/chat (message + context)
AgentAPI->>LLM: System prompt + tools + conversation
LLM->>AgentAPI: tool_call: add_questions(exerciseId, questions[])
AgentAPI->>Services: exerciseService.addQuestions()
Services->>AgentAPI: Success
AgentAPI->>LLM: Tool result
LLM->>AgentAPI: "Done! I added 5 questions to..."
AgentAPI-->>ChatUI: SSE stream response
ChatUI->>Teacher: Shows confirmation + refreshes exercise
```
The LLM sees a set of **tools** (mapped to existing service functions) and decides which to call based on the teacher's message. The agent API executes the tool with full permission checks, then feeds the result back to the LLM for a human-friendly summary.
### SDK: Vercel AI SDK
The **Vercel AI SDK** (`ai` + `@ai-sdk/svelte` + provider packages) is the right fit:
- `@ai-sdk/svelte` provides a `Chat` class that uses Svelte 5 runes internally — same class-based reactive pattern as the project's existing `LessonApi` / `BaseApiWithErrors` ([base.svelte.ts](apps/dashboard/src/lib/utils/services/api/base.svelte.ts)).
- `streamText()` returns `toUIMessageStreamResponse()` which works directly as a Hono response — zero glue code ([Hono cookbook](https://sdk.vercel.ai/cookbook/api-servers/hono)).
- Tool calling is built-in with Zod schemas (already used everywhere in the project). The SDK handles the function-calling protocol, multi-step execution, and streaming tool results.
- Provider abstraction lets us swap between `@ai-sdk/openai` and `@ai-sdk/anthropic` by changing one line.
- The wire protocol carries text chunks, tool call events, tool results, and finish signals. The `Chat` class on the client parses all of this automatically.
**Packages to install:**
- `ai` — core (`streamText`, `tool`, types) — in `packages/ai-assistant` and `apps/api`
- `@ai-sdk/svelte` — Svelte 5 `Chat` class — in `apps/dashboard`
- `@ai-sdk/openai` — OpenAI provider — in `packages/ai-assistant`
- `@ai-sdk/anthropic` — Anthropic provider — in `packages/ai-assistant`
- `zod` — already installed everywhere
### Package: `packages/ai-assistant`
A thin, backend-focused package consumed by `apps/api`. No UI code. The heavy lifting is done by the Vercel AI SDK; this package provides project-specific configuration on top.
Responsibilities:
- **Provider factory** — creates the right AI SDK `LanguageModel` from env vars (`AI_PROVIDER`, `AI_API_KEY`, `AI_MODEL`). Wraps `@ai-sdk/openai` and `@ai-sdk/anthropic`.
- **Role-aware tool registry** — `getToolSchemas(role)` returns the right Zod schemas per role. No implementations — those live in the API.
- **Role-aware system prompt** — `buildSystemPrompt(context)` generates different LLM instructions for teachers vs students.
- **Shared types** — `AgentRole`, `AgentContext`, tool names, config types. Used by both `apps/api` and `apps/dashboard`.
Suggested structure:
```
packages/ai-assistant/
src/
index.ts # Public exports
types.ts # AgentRole, AgentContext, AIProviderConfig, tool name constants
providers/
index.ts # createModel(config) factory
tools/
index.ts # getToolSchemas(role) registry
shared.ts # Read-only tool schemas (both roles)
teacher.ts # Mutation tool schemas (teacher only, v1)
student.ts # Learning tool schemas (student only, v2 stubs)
prompt/
system-prompt.ts # buildSystemPrompt(context) — role-aware
teacher.ts # Teacher prompt template
student.ts # Student prompt template (v2 stub)
package.json
tsconfig.json
```
Note: the agent loop itself is NOT in this package — `streamText()` from the `ai` core package handles the full loop (prompt -> LLM -> tool call -> execute -> respond -> repeat). The Hono route assembles tools (schema from package + execute from services) and calls `streamText`.
### Foundation Layer: Role-Aware Design
The agent is not just a teacher tool — it's a **course assistant** that behaves differently per role. The foundation must support this from day one, even though students are gated off in v1.
`**AgentRole`** — the core discriminator:
- `'teacher'` — can read AND mutate course content (update lessons, generate questions, create drafts)
- `'student'` — can only read and discuss content (explain concepts, answer questions, quiz on material)
**Role detection** — server-side, automatic:
- The API route checks the user's course membership via existing queries (`isCourseTeamMemberOrOrgAdmin`)
- Team members (ADMIN/TUTOR role in `groupmember`) get `role: 'teacher'`
- Regular course members (STUDENT role) get `role: 'student'`
- In v1, `role: 'student'` returns a 403. In v2, it loads the student tool set.
**Tool registry** — `getToolSchemas(role)` returns the right set:
- `shared` tools (read-only): `get_course_structure`, `get_lesson_content`, `get_exercise_questions` — available to both roles
- `teacher` tools (mutations): `update_lesson_content`, `create_lesson_draft`, `add_exercise_questions` — teacher only
- `student` tools (v2): `explain_concept`, `quiz_me`, `clarify_exercise` — student only, stubs for now
Teachers get `shared + teacher`. Students get `shared + student`. This ensures students can never access mutation tools, even via prompt injection.
**System prompt** — role-aware via `buildSystemPrompt(context)`:
- Teacher: "You are helping a teacher organize and author course content. You can update lessons, create new content, and generate questions."
- Student (v2): "You are helping a student learn. You can explain concepts, answer questions about the material, and help with exercises. You cannot modify any course content."
**Single API endpoint** — `/agent/chat` serves both roles. Role is detected server-side (not passed by the client, preventing spoofing). The endpoint loads tools and prompt based on the detected role.
### Agent Tools
#### V1 Core Tools (7 tools)
Start small with the essentials for content authoring. Additional tools are added in later phases.
| Tool | Type | Description | Service |
| ----------------------- | ----- | ---------------------------------------------------- | ----------------------------------------------------- |
| `get_course_structure` | read | Get sections, lessons, exercises tree | `getCourseContentItems` + `listCourseSections` |
| `get_lesson_content` | read | Get a specific lesson's note/text | `getLesson` |
| `get_exercise_details` | read | Get exercise with all questions and options | `getExercise` |
| `create_lesson` | write | Create a new lesson in a section (title + content) | `createLesson` |
| `update_lesson_content` | write | Update the note/text content of a lesson | `updateLessonService` + `upsertLessonLanguageService` |
| `create_exercise` | write | Create a new exercise with questions and options | `createExercise` |
| `add_questions` | write | Add questions (with options) to an existing exercise | `updateExerciseService` (diff-based) |
#### Phase 2+ Tools (added after v1 is stable)
**Lessons**: `update_lesson_metadata`, `delete_lesson`, `reorder_lessons`, `update_lesson_translation`
**Sections**: `create_section`, `update_section`, `reorder_sections`, `delete_section`
**Exercises**: `update_exercise_metadata`, `update_question`, `delete_question`, `delete_exercise`, `create_exercise_from_template`
**Other**: `update_course_tags`, `create_newsfeed_post`, `list_exercise_templates`
#### Phase 4 Student Tools (v2)
`explain_concept`, `quiz_me`, `clarify_exercise`, `get_my_progress`, `get_my_submissions`
#### Tool Execution Rules
Each tool handler in the API will:
1. Extract IDs from tool arguments
2. Verify the target resource belongs to the course/org in context
3. Verify user is course team member or org admin (teacher tools)
4. **Check token balance** before LLM call (see Token Usage section)
5. Call the existing service function
6. Return structured result to the agent
#### No-Hallucination Boundary
The system prompt includes an explicit list of what the agent CANNOT do. When a user asks for any of these, the agent responds with a clear, helpful decline and suggests the closest available action. The agent must **never**:
- Pretend to perform an action it doesn't have a tool for
- Fabricate data it hasn't retrieved via a tool call
- Claim to have made a change unless a tool call succeeded
**Explicit CANNOT-do list (included verbatim in system prompt):**
- Cannot create, delete, or clone courses
- Cannot update course-level settings (title, description, logo, status)
- Cannot manage course members, invitations, or roles
- Cannot grade submissions or assign marks
- Cannot handle payments or attendance
- Cannot upload files, images, videos, or documents
- Cannot manage sections, reorder content, or delete content (v1 — added in Phase 2)
- Cannot manage org settings, members, or billing
- Cannot access data from other courses or organizations
- Cannot browse the internet or fetch external URLs
- Cannot send emails or notifications
**System prompt template:**
```
You are an AI assistant for ClassroomIO. You help teachers create and organize
course content.
You have access to specific tools listed below. If a user asks you to do something
NOT covered by your tools, respond clearly:
"I can't do that yet. [Brief reason]. Here's what I can help with: [closest action]."
NEVER pretend to perform an action you don't have a tool for.
NEVER fabricate data you haven't retrieved via a tool.
NEVER claim to have made a change unless a tool call returned success.
When drafting new content, always present it for review before creating.
Things you explicitly CANNOT do:
[list from above]
```
### Token-Based Usage Tracking
AI usage is metered by tokens. Each org gets a monthly base allowance from their plan, with the option to buy extra credit packs when exhausted.
#### How It Works
```mermaid
flowchart LR
subgraph check [Before LLM Call]
CheckBalance["Check: monthly_allowance\n+ credit_balance\n- tokens_used > 0?"]
end
subgraph call [LLM Call]
StreamText["streamText() executes"]
Usage["AI SDK returns\npromptTokens + completionTokens"]
end
subgraph record [After LLM Call]
RecordUsage["Record usage in\nai_token_usage table"]
UpdateBalance["Deduct from monthly\nallowance first,\nthen credits"]
end
CheckBalance -->|"Yes"| StreamText
CheckBalance -->|"No"| Reject["Return 402:\nToken limit reached"]
StreamText --> Usage
Usage --> RecordUsage
RecordUsage --> UpdateBalance
```
#### Plan-Based Allowances
Tied to the existing `organization_plan` table ([schema.ts](packages/db/src/schema.ts) line 1324). Each plan gets a monthly token allowance:
- **BASIC**: 0 tokens (AI assistant not available on free plan — or a small trial allowance, TBD)
- **EARLY_ADOPTER**: X tokens/month (e.g. 500K tokens — roughly 50-100 conversations)
- **ENTERPRISE**: Y tokens/month (higher, e.g. 2M tokens — or unlimited)
Allowance resets on the 1st of each month (or billing cycle start).
#### Extra Credit Packs
When the monthly allowance is exhausted, the org can buy credit packs:
- Credits are one-time purchases, do NOT expire, do NOT reset monthly
- Deduction order: monthly allowance first, then credits
- Purchase flow: upgrade modal / settings page -> payment -> credits added to `ai_credit_balance`
#### Database Design
New table: `ai_token_usage` — tracks per-request usage for auditing and aggregation.
```sql
CREATE TABLE ai_token_usage (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
org_id UUID NOT NULL REFERENCES organization(id),
user_id UUID NOT NULL,
course_id UUID NOT NULL,
prompt_tokens INTEGER NOT NULL,
completion_tokens INTEGER NOT NULL,
total_tokens INTEGER GENERATED ALWAYS AS (prompt_tokens + completion_tokens) STORED,
model TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_ai_token_usage_org_month ON ai_token_usage (org_id, created_at);
```
New table: `ai_credit_balance` — tracks purchased credits per org.
```sql
CREATE TABLE ai_credit_balance (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
org_id UUID NOT NULL REFERENCES organization(id) UNIQUE,
balance INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
```
Allowances live in a config constant (or the plan's `payload` JSONB field), not a separate table. The plan already has `payload: jsonb()` which can store `{ "aiTokenAllowance": 500000 }`.
#### Token Tracking Flow (in the agent route)
1. **Before LLM call**: query `ai_token_usage` for current month + `ai_credit_balance`. Calculate: `remaining = (allowance - used_this_month) + credit_balance`. If `remaining <= 0`, return 402 with `{ error: "Token limit reached", upgradeUrl: "..." }`.
2. **After LLM call**: the Vercel AI SDK's `streamText()` result exposes `usage` with `promptTokens` and `completionTokens`. Insert a row into `ai_token_usage`.
3. **Deduction logic**: monthly allowance is consumed first (it's implicit — just the sum of usage this month vs the allowance). Credits are only touched when `used_this_month > allowance`. The credit deduction is: `max(0, total_tokens - max(0, allowance - used_before_this_request))`.
#### API Endpoints for Token Management
- `GET /agent/usage` — returns `{ used, allowance, creditBalance, remaining }` for the current org. Used by dashboard to show usage meter.
- `POST /agent/credits` — purchase credits (integrates with payment provider). Protected by `orgAdminMiddleware`.
#### Dashboard UI
- **Usage meter**: in the AI assistant sidebar header or org settings, show a progress bar: "X / Y tokens used this month" with remaining count.
- **Exhausted state**: when tokens run out, the chat input is disabled with a message: "Monthly AI token limit reached. [Buy more credits] or wait for reset on [date]."
- **Credits section**: in org settings, show credit balance and "Buy more" button.
### Safeguards
Four layers of protection:
1. **Route-level middleware** — agent API route uses `authMiddleware` + `orgMemberMiddleware` + at minimum `courseMemberMiddleware`. Role detection happens inside the handler. Defined in [apps/api/src/middlewares/](apps/api/src/middlewares/).
2. **Tool-level permission checks** — the tool set itself is the primary guard. Students physically cannot call `update_lesson_content` because it's not in their tool set. Additionally, each tool's execute function re-verifies resource ownership to prevent prompt injection (LLM tricked into passing a different `courseId`).
3. **Token budget enforcement** — every LLM call checks the org's remaining token balance. If exhausted, returns 402 before any LLM call is made. Usage is recorded after each call for accurate tracking.
4. **Rate limiting** — per-user, per-org rate limits on agent API calls (requests/minute). Prevents abuse even within token budget. Self-hosted is uncapped (user's own API key, their cost).
### Self-Hosted vs Cloud
- **Cloud**: AI assistant enabled by default. ClassroomIO provides the LLM API key server-side. Teachers see the button, no setup needed. Usage may be metered per plan tier.
- **Self-hosted**: AI assistant **disabled by default**. To enable, the self-hosted admin sets `AI_API_KEY` and optionally `AI_PROVIDER` / `AI_MODEL` in their environment. When configured, the assistant becomes available. When not configured, the button is hidden (check via a server-side flag exposed to the client, e.g. a `GET /agent/status` endpoint or a field in the org config response).
This is simpler than storing API keys in the database and avoids security concerns around key storage.
### UI Specification
- **Trigger**: "AI Assistant" button in the course sidebar navigation ([course-sidebar-navigation.svelte](apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte)), below the existing nav items. In v1, only visible to teachers/admins (not students). Hidden when self-hosted and no AI key configured.
- **Panel**: Right sidebar using `@cio/ui` Sheet (`side="right"`, ~420px). Does NOT replace the left sidebar — both can be open simultaneously.
- **Chat interface**: Message list (user/assistant turns), text input with send button, streaming token display, quick-action chips.
- **Role-aware quick actions**: The chat panel accepts the detected `role` to show the right chips:
- Teacher (v1): "Draft a lesson", "Generate questions", "Improve this text"
- Student (v2): "Explain this lesson", "Quiz me on this topic", "Help me with this exercise"
- **Context awareness**: Client passes `courseId`, current `lessonId` or `exerciseId`. The role is NOT sent from the client — it's detected server-side to prevent spoofing.
- **Apply flow**: For large content changes (teacher only), the agent response includes a structured preview. The chat UI renders a diff with "Apply" / "Discard" buttons. Applying triggers the API write and refreshes the relevant store.
- **Existing `ai-button.svelte`**: The hidden [ai-button.svelte](apps/dashboard/src/lib/features/course/components/lesson/ai-button.svelte) component in the lesson editor can be removed or repurposed — the new sidebar chat replaces its functionality.
- **v2 student surface**: The same chat panel component can be rendered in the student course view (course-app). The `Chat` class and Sheet are identical — only the quick-action chips differ, and the server loads different tools/prompts based on role.
### Streaming
The Vercel AI SDK provides a structured SSE protocol via `toUIMessageStreamResponse()`. It carries:
- Text chunks (tokens stream one by one — ChatGPT-like typing)
- Tool call events (when the LLM decides to call a tool)
- Tool results (when the tool execution completes)
- Finish signals
On the frontend, the `Chat` class from `@ai-sdk/svelte` consumes this protocol automatically. No manual SSE parsing needed.
### How the Backend Code Works
The Hono route assembles everything:
1. **Provider factory** (`packages/ai-assistant`) creates a `LanguageModel` from env vars
2. **Tool schemas** (`packages/ai-assistant`) define Zod input schemas for each tool
3. **Tool execute functions** (inline in the Hono route) call existing services from `apps/api/src/services/`
4. `**streamText()`** (from `ai` core) runs the agent loop: sends system prompt + tools + messages to LLM, executes tool calls, feeds results back, repeats up to `stopWhen: stepCountIs(5)`, streams everything to the client
The route returns `result.toUIMessageStreamResponse()` directly as the Hono response.
### How the Frontend Code Works
The `Chat` class from `@ai-sdk/svelte` is instantiated once per chat panel. It:
1. Manages `messages` array as reactive `$state` (same pattern as `LessonApi`)
2. `sendMessage({ text })` sends a POST to the Hono endpoint, starts consuming the SSE stream
3. Updates `messages` reactively as tokens arrive — the UI re-renders automatically
4. Exposes `status` (`'idle'` | `'streaming'`) and `stop()` for abort
5. Each message has a `parts` array — `{ type: 'text', text }` for text, `{ type: 'tool-{name}', state: 'call' | 'result', result? }` for tool calls
The `Chat` class accepts:
- `api` — URL of the Hono endpoint (e.g., `${PUBLIC_API_URL}/agent/chat`)
- `headers` — we pass `{ 'cio-org-id': orgId }` via a reactive getter
- `body` — extra data merged into every request: `{ courseId, context: { lessonId, exerciseId } }`
- `credentials: 'include'` — sends auth cookies for Better Auth session
- `onFinish` — callback to refresh page data after the agent completes
### What the Chat UI Looks Like
**Empty state**: welcome message + quick-action chips ("Draft a lesson", "Generate questions", "Improve this text"). Clicking a chip fills the input and sends.
**During conversation**:
- User messages appear right-aligned with `bg-primary` styling
- Assistant messages appear left-aligned with `bg-muted` styling
- Text streams in token by token (automatic via `Chat` class)
- Tool calls render as inline status cards inside the assistant bubble:
- `state: 'call'` shows spinner + "Generating questions..."
- `state: 'result'` shows checkmark + "5 questions added"
- Stop button replaces send button while streaming
**After agent completes a mutation**:
- `onFinish` callback fires
- The relevant store refreshes (e.g., `lessonApi.get()` or exercise reload)
- Teacher sees updated content on the page without manual refresh
**Tool part rendering**: The AI SDK names tool parts as `tool-{toolName}`. In the Svelte template:
```svelte
{#each message.parts as part}
{#if part.type === 'text'}
<div class="prose">{@html renderMarkdown(part.text)}</div>
{:else if part.type === 'tool-update_lesson_content'}
<ToolStatusCard label="Updating lesson" state={part.state} />
{:else if part.type === 'tool-add_exercise_questions'}
<ToolStatusCard label="Generating questions" state={part.state}
successText={part.state === 'result' ? `${part.result.count} questions added` : undefined} />
{/if}
{/each}
```
### Example Agent Flows
These walk through what actually happens end-to-end for each key use case — which tools fire, what the teacher sees, and design decisions involved.
#### Flow 1: "Research photosynthesis and write a first draft lesson for Section 2"
```mermaid
sequenceDiagram
participant Teacher
participant Chat as Chat UI
participant API as Agent API
participant LLM
participant Svc as Services
Teacher->>Chat: "Research photosynthesis and write a first draft for Section 2"
Chat->>API: POST /agent/chat
API->>LLM: system prompt + tools + message
Note over LLM: Step 1 - Understand course context
LLM->>API: tool_call: get_course_structure(courseId)
API->>Svc: getCourseStructure()
Svc-->>API: sections, lessons, exercises tree
API->>LLM: tool result
Note over LLM: Step 2 - Read existing style
LLM->>API: tool_call: get_lesson_content(lessonId)
API->>Svc: getLessonById()
Svc-->>API: lesson HTML content
API->>LLM: tool result
Note over LLM: Step 3 - Present draft for review
LLM-->>Chat: Streams draft text inline in chat
LLM-->>Chat: "Here's a draft... shall I create it?"
Teacher->>Chat: "Looks good, create it"
Chat->>API: POST /agent/chat (follow-up)
API->>LLM: conversation continues
Note over LLM: Step 4 - Create after confirmation
LLM->>API: tool_call: create_lesson_draft(title, content, sectionId)
API->>Svc: createLessonService()
Svc-->>API: { lessonId, title }
API->>LLM: tool result
LLM-->>Chat: "Created 'Photosynthesis' in Section 2"
Note over Chat: onFinish -> content tree refreshes
Chat->>Teacher: New lesson appears in sidebar
```
**What "research" means**: The agent does NOT have internet access. "Research" means two things:
1. The LLM uses its training data knowledge about the topic (extensive for most academic subjects)
2. The agent reads existing course content via `get_course_structure` and `get_lesson_content` to understand the teacher's style, depth, and what's already been covered
**Confirmation before creation**: The system prompt instructs the LLM to present the draft in the chat first and ask for confirmation before calling `create_lesson_draft`. This is a prompt-engineering pattern, not a code constraint — the system prompt will say: "When drafting a new lesson, first present the full draft in your response and ask the teacher to confirm before creating it. Only call create_lesson_draft after the teacher approves." This gives a natural review gate via multi-turn conversation without requiring a custom "preview mode" in the API.
**Future consideration**: If real web research is needed, a `web_search` tool can be added to the tool registry. The foundation supports it cleanly — just another tool schema + execute function. Not in v1.
**What the teacher sees in the chat**:
1. User bubble: their request
2. Assistant bubble starts streaming:
- Tool card: "Getting course structure..." -> checkmark
- Tool card: "Reading existing lesson..." -> checkmark
- Text streams in: the full draft lesson content, rendered as markdown
- Text: "Would you like me to create this as a lesson in Section 2?"
3. Teacher types "yes" or "looks good, but change X"
4. Assistant bubble:
- Tool card: "Creating lesson draft..." -> checkmark
- Text: "Created 'Photosynthesis: Converting Light to Energy' in Section 2. You can find it in the content tree."
5. Content tree refreshes, new lesson appears
#### Flow 2: "Generate 5 MCQ questions from this lesson"
The teacher is viewing a lesson and opens the AI assistant.
1. Teacher sends: "Generate 5 multiple choice questions from this lesson"
2. The `Chat` class sends `{ courseId, messages, context: { lessonId: 'current-lesson-id' } }`
3. The system prompt includes: "The teacher is currently viewing lesson ID: {lessonId}"
4. LLM calls `get_lesson_content(lessonId)` to read the lesson text
5. LLM generates 5 questions based on the content
6. LLM calls `add_exercise_questions(exerciseId, questions)` — if there's a linked exercise, it adds there. If not, it tells the teacher there's no exercise linked and asks if it should create one.
7. Result streams back with tool status cards and a summary
**What the teacher sees**:
- Tool card: "Reading lesson content..." -> checkmark
- Tool card: "Adding 5 questions..." -> checkmark
- Text: "I've added 5 multiple-choice questions to the exercise. Here's a summary: 1. What is the primary function of... [etc]"
- Exercise data refreshes automatically
#### Flow 3: "Update the introduction paragraph of this lesson"
The teacher is editing a lesson and wants the AI to improve specific text.
1. Teacher sends: "Rewrite the introduction paragraph to be more engaging"
2. Context includes the current `lessonId`
3. LLM calls `get_lesson_content(lessonId)` to read the full lesson
4. LLM identifies the introduction paragraph, rewrites it
5. **System prompt instructs**: "When updating existing lesson content, show the proposed changes and ask for confirmation before applying." — this is the "preview for destructive changes" pattern
6. LLM presents the new introduction in the chat
7. Teacher says "apply it" or "make it shorter"
8. LLM calls `update_lesson_content(lessonId, fullUpdatedContent)`
9. Lesson store refreshes, teacher sees the updated text in the editor
**Important**: `update_lesson_content` replaces the full lesson note. The LLM must reconstruct the complete lesson HTML with only the introduction changed. The system prompt will instruct: "When updating lesson content, always preserve all existing content. Only modify the specific section the teacher asked about."
#### Flow 4 (v2): Student asks "I don't understand the Calvin cycle"
1. Student is viewing a lesson about photosynthesis
2. Student sends: "I don't understand the Calvin cycle, can you explain it more simply?"
3. Role detected as `'student'` — student tool set loaded (read-only)
4. LLM calls `get_lesson_content(lessonId)` to read what the lesson says about the Calvin cycle
5. LLM generates a simplified explanation based on the lesson content + its training knowledge
6. Response streams back — pure text, no tool mutations, no changes to any data
**Key difference from teacher flow**: No mutation tools are available. The agent can only read course content and generate text responses. The tool set IS the security boundary.
### LLM Provider Abstraction
Configurable via environment variables:
- `AI_PROVIDER` — `openai` | `anthropic` (default: `openai`)
- `AI_API_KEY` — the provider API key
- `AI_MODEL` — model name override (default: provider's recommended model)
The provider factory in `packages/ai-assistant` normalizes this into a single `LanguageModel` instance that `streamText()` consumes. Both OpenAI and Anthropic support function/tool calling natively through the AI SDK.
### Conversation Persistence
For v1, conversation history is **session-scoped** — managed entirely in-memory by the `Chat` class on the client. When the teacher closes the sidebar or navigates away, the conversation resets. No database table needed.
v2 consideration: persist conversations per course in the database for history/continuity.
## API Routes
New route domain: `/agent`
- `GET /agent/status` — returns `{ enabled, role, usage: { used, allowance, creditBalance, remaining } }`. Used by client to show/hide the button, configure chips, and display usage meter.
- `POST /agent/chat` — the single chat endpoint. Accepts `{ courseId, messages, context }`. Checks token balance, detects role, loads tools/prompt, returns SSE stream. Records token usage after completion.
- `GET /agent/usage` — returns detailed usage stats for the current org (current month usage, allowance, credit balance, history).
- `POST /agent/credits` — purchase additional credits. Protected by `orgAdminMiddleware`.
Registered in [apps/api/src/app.ts](apps/api/src/app.ts) as `.route('/agent', agentRouter)`.
## Implementation Phases
### Phase 1: Foundation (scaffold + role-aware chat shell + token tables)
- Create `packages/ai-assistant` with `AgentRole`, `AgentContext` types, provider factory, role-aware tool registry (v1: 7 core tools), and role-aware system prompt with no-hallucination boundary
- Add `ai_token_usage` and `ai_credit_balance` tables to DB schema, add token allowance to plan payload
- Add `GET /agent/status` and `POST /agent/chat` route skeleton in `apps/api` with role detection (students get 403 in v1) and token balance check
- Add "AI Assistant" button to course sidebar (gated on status endpoint + plan check)
- Build right sidebar Sheet with basic chat UI (hardcoded echo responses)
### Phase 2: Agent Core (LLM integration + v1 tools + usage tracking)
- Implement provider factory (OpenAI + Anthropic) using `createModel(config)`
- Wire v1 core tools (7 tools) to existing services via `streamText()` with `stopWhen: stepCountIs(5)`
- Record `promptTokens` + `completionTokens` after each call; enforce balance check before each call
- Connect chat UI to streaming API via `@ai-sdk/svelte` `Chat` class; render streamed tokens and tool status cards
- Add usage meter to AI assistant sidebar header
- Implement `onFinish` store refresh for lesson/exercise data
### Phase 3: Polish + Safeguards + Credits
- Add tool-level permission re-validation (verify resource belongs to course/org)
- Add rate limiting (per-user, per-org, requests/minute)
- Add quick-action chips and context-aware suggestions
- Self-host env var detection and `GET /agent/status` logic
- Add conversation context windowing (trim long histories)
- Implement `POST /agent/credits` for purchasing credit packs
- Add credit purchase UI in org settings + exhausted-state UI in chat
- Add `GET /agent/usage` for detailed usage dashboard
### Phase 4: More Tools
- Add Phase 2+ tools (sections, reorder, delete, translations, templates, tags, newsfeed)
- Update no-hallucination boundary to remove "cannot manage sections" etc.
### Phase 5: Student Assistant (v2)
- Implement student tool schemas and execute functions
- Write student system prompt template
- Remove the v1 student 403 gate
- Add student quick-action chips
- Surface the AI assistant button in the student course view (course-app)
- Student usage counts against the org's token budget (same pool)
## Files to Create / Modify
**New files:**
- `prd/ai-course-assistant/README.md` — this PRD (replace existing)
**Files referenced (not modified in PRD phase):**
- [packages/db/src/schema.ts](packages/db/src/schema.ts) — where `ai_token_usage` and `ai_credit_balance` tables will be added (near `organizationPlan` at line 1324)
- [packages/utils/src/plans/constants.ts](packages/utils/src/plans/constants.ts) — where AI token allowance feature constants will be added
- [apps/api/src/app.ts](apps/api/src/app.ts) — where agent route will be registered
- [apps/api/src/middlewares/](apps/api/src/middlewares/) — existing middleware to reuse
- [apps/api/src/services/](apps/api/src/services/) — existing services the agent will call
- [apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte](apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte) — where the AI button goes
- [apps/dashboard/src/lib/utils/store/org.ts](apps/dashboard/src/lib/utils/store/org.ts) — where plan-based derived stores live (e.g., `isFreePlan`, `currentOrgPlan`)
@@ -0,0 +1,199 @@
---
name: Course Enroll Route Migration
overview: "Replace `/invite/s/:token` with `/course/:slug/enroll`. One unified enrollment endpoint: free courses enroll directly (no invite); paid courses require invite_token. Remove public-link and invite creation for free enrollment."
todos: []
isProject: false
---
# Course Enroll Route Migration Plan
## Summary
Migrate from `/invite/s/:token` to a course-scoped enroll route. **One request for both flows:**
- **Free courses:** `/course/:slug/enroll` – Join calls `POST /course/:courseId/enroll` (no token). User is enrolled directly; no invite creation.
- **Paid/invited:** `/course/:slug/enroll?invite_token=xxx` – Join calls `POST /course/:courseId/enroll` with `inviteToken`. Without token, request fails.
## Architecture
```mermaid
flowchart TB
subgraph free [Free Course Flow]
A1[Landing: Enroll click] --> A2[goto /course/slug/enroll]
A2 --> A3[Page loads, validates free]
A3 --> A4[User auths if needed]
A4 --> A5[Join click]
A5 --> A6["POST /course/:id/enroll (no token)"]
A6 --> A7[Direct enroll: add to org + group]
A7 --> A8[Redirect to LMS]
end
subgraph paid [Paid/Invited Flow]
B1[Email link] --> B2[course/slug/enroll?invite_token=xxx]
B2 --> B3[Page loads, validates token]
B3 --> B4[User auths if needed]
B4 --> B5[Join click]
B5 --> B6["POST /course/:id/enroll with inviteToken"]
B6 --> B7[Validate token, consume invite, enroll]
B7 --> B8[Redirect to LMS]
end
```
---
## Part 1: New Enroll Route
### 1.1 Create route files
**Add:** [apps/dashboard/src/routes/course/[slug]/enroll/+page.server.ts](apps/dashboard/src/routes/course/[slug]/enroll/+page.server.ts)
**Add:** [apps/dashboard/src/routes/course/[slug]/enroll/+page.svelte](apps/dashboard/src/routes/course/[slug]/enroll/+page.svelte)
**Server load logic – one request per branch:**
- **With `invite_token`:** Single call to `GET /invite/student/:token`. Response must include course (slug, cost, title, description, allowNewStudent, status, isPublished), organization (siteName, name, theme), invite (status, etc.). No separate course or org fetch. Extend the invite API response to be self-contained (add course.slug, course.cost, org.theme to the query/response).
- **Without `invite_token` (free):** Single call to `GET /course/slug/:slug` (or a dedicated enroll-context endpoint). Response must include course and org (with theme). Extend the course-by-slug response to include org if it does not already, so no separate OrgApiServer.getOrgBySiteName call.
- **Validation rules:** Same as before – 404, requiresPaymentOrInvite, etc. Determine "free" via `isCourseFree(calculatedCost)`.
**Page component logic:**
- When `requiresPaymentOrInvite: true`: render message "You need to pay for this course or be invited to get access" with link back to `/course/:slug`
- When `invite` present or free (no invite): show course info + Join button
- On Join:
1. If not logged in → `goto(/signup?redirect=/course/:slug/enroll)` (preserve redirect, append `?invite_token=` if present)
2. If logged in → call `**POST /course/:courseId/enroll`** with body `{ inviteToken?: string }`:
- **Free:** no `inviteToken`, backend enrolls directly
- **Paid/invited:** pass `inviteToken` from URL; backend validates and consumes invite
3. Redirect to `result.data.redirectTo || '/lms'`
- Set theme and currentOrg from load data
### 1.2 Add route to PUBLIC_ROUTES
**File:** [apps/dashboard/src/lib/utils/constants/routes.ts](apps/dashboard/src/lib/utils/constants/routes.ts)
- Add `^/course/.*/enroll` to `PUBLIC_ROUTES` so unauthenticated users can load the enroll page (they will be prompted to auth when clicking Join)
---
## Part 2: Update Landing Page Enroll Flow
**File:** [apps/dashboard/src/lib/features/ui/course-landing-page/components/pricing-section.svelte](apps/dashboard/src/lib/features/ui/course-landing-page/components/pricing-section.svelte)
- For **free** course: remove `POST /invite/student/public-link` call; change to `goto(\`/course/${courseData.slug}/enroll)`
---
## Part 3: New Unified Enrollment API
**Add:** `POST /course/:courseId/enroll` (authenticated). Body: `{ inviteToken?: string }`
**Logic:** With `inviteToken` → reuse `acceptStudentInvite`; without token → only free courses, direct enroll (no invite). Remove public-link and accept routes.
**Part 3b – Build Enroll URL for emails:** [apps/api/src/services/course/invite.ts](apps/api/src/services/course/invite.ts)
- Add `buildEnrollLink(courseSlug: string, token: string, orgSiteName?: string): string`
- Construct: `https://${orgSiteName || 'app'}.classroomio.com/course/${courseSlug}/enroll?invite_token=${encodeURIComponent(token)}`
- Use same base-URL logic as elsewhere (dev vs prod; see [newsfeed](apps/api/src/services/newsfeed/newsfeed.ts) for org subdomain pattern)
- Replace `buildInviteLink` with `buildEnrollLink` in createSingleInvite/email flow; remove buildInviteLink
- Pass `courseSlug` and `orgSiteName` from course/org data in createStudentInvite and createEmailInviteAndSend
- createPublicStudentInvite removed; email flow uses buildEnrollLink for invite URLs in emails
---
## Part 4: Redirect Preservation (from earlier discussion)
**Files:** [apps/dashboard/src/routes/(auth)/login/+page.svelte](apps/dashboard/src/routes/(auth)/login/+page.svelte), [apps/dashboard/src/routes/(auth)/signup/+page.svelte](apps/dashboard/src/routes/(auth)/signup/+page.svelte)
- On successful auth, preserve `redirect` query param: `window.location.href = redirect ? \`/?redirect=${encodeURIComponent(redirect)} : '/'`
**File:** [apps/dashboard/src/lib/features/app/init.svelte.ts](apps/dashboard/src/lib/features/app/init.svelte.ts)
- In `routeUserToNextPage`, move the `redirect` check **before** the `isOrgSite && pathname === '/'` early return so redirect is honored on org sites
---
## Part 5: Delete invite/s Route and Remove Obsolete Code
All logic from the old invite page moves to the new enroll route. Delete the invite/s route entirely.
### 5.1 Delete invite/s route files
**Delete:**
- [apps/dashboard/src/routes/invite/s/[hash]/+page.svelte](apps/dashboard/src/routes/invite/s/[hash]/+page.svelte)
- [apps/dashboard/src/routes/invite/s/[hash]/+layout.server.ts](apps/dashboard/src/routes/invite/s/[hash]/+layout.server.ts)
- [apps/dashboard/src/routes/invite/s/](apps/dashboard/src/routes/invite/s/) directory (delete if empty after removing [hash])
If [invite/t](apps/dashboard/src/routes/invite/t/) (teacher invite) exists, keep it; only student invite s/ is removed.
### 5.2 Remove obsolete constants
**File:** [apps/dashboard/src/lib/utils/constants/routes.ts](apps/dashboard/src/lib/utils/constants/routes.ts)
- Remove `INVITE_STUDENT: '/invite/s'` from `ROUTE`
- Remove `^${ROUTE.INVITE_STUDENT}/.`* from `ROUTES_TO_HIDE_NAV`
- Add enroll route to `PUBLIC_ROUTES`: `^/course/.*/enroll` (or equivalent)
### 5.3 Remove obsolete backend function
**File:** [apps/api/src/services/course/invite.ts](apps/api/src/services/course/invite.ts)
- Remove `buildInviteLink(token)` (replaced by `buildEnrollLink`)
- Ensure no remaining callers of `buildInviteLink`; update all to use `buildEnrollLink(courseSlug, token, orgSiteName)`
### 5.4 API routes – add, remove, rename, extend
- **Add:** `POST /course/:courseId/enroll` (unified endpoint; see Part 3)
- **Remove:** `POST /invite/student/public-link`, `POST /invite/student/:token/accept`
- **Rename:** `GET /invite/student/:token/preview` → `GET /invite/student/:token`
- **Extend** `GET /invite/student/:token` response: include `course.slug`, `course.cost`, `org.theme` so enroll page needs no extra fetches
- **Extend** `GET /course/slug/:slug` response: include `org` (id, name, siteName, theme) so free-enroll page needs no separate org fetch
---
## Part 6: People Page – Email Invite Links
When teachers send email invites, the link in the email must use the new format. The backend change in Part 3 covers this: `buildEnrollLink(courseSlug, token, orgSiteName)` will be used when generating links for `studentCourseInvite` email.
---
## Part 7: Email-Only Invites Plan (from planning doc)
Per [email-only-invites-plan.md](planning/secure-student-invites/email-only-invites-plan.md):
- Add Zod refine to `ZCreateCourseInvite`: require `recipientEmails` or `recipientCsv` (broad scope)
- Remove quick-link tab/section from People invite modal; make email the default
- Update `invitation-modal.svelte` to remove QuickLinkSection and set `activeStudentTab = 'email'`
---
## File Change Summary
| File | Action |
| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `routes/course/[slug]/enroll/+page.server.ts` | Create – load course, invite preview, validation |
| `routes/course/[slug]/enroll/+page.svelte` | Create – enroll UI, Join flow |
| `lib/utils/constants/routes.ts` | Add enroll to PUBLIC_ROUTES; remove INVITE_STUDENT |
| `features/ui/course-landing-page/.../pricing-section.svelte` | Free: goto `/course/:slug/enroll` |
| `api/services/course/invite.ts` | Add enrollInCourse, buildEnrollLink; extend previewStudentInvite with slug, cost, org.theme; remove public-link, accept, buildInviteLink |
| `routes/(auth)/login/+page.svelte` | Preserve redirect param |
| `routes/(auth)/signup/+page.svelte` | Preserve redirect param |
| `features/app/init.svelte.ts` | Honor redirect before org-site early return |
| `routes/invite/s/[hash]/+page.svelte` | Delete |
| `routes/invite/s/[hash]/+layout.server.ts` | Delete |
| `packages/utils/validation/course/invite.ts` | Zod refine for recipients |
| `features/course/people/invitation-modal.svelte` | Remove quick-link, default to email |
| `features/course/people/quick-link-section.svelte` | Delete |
| `api/routes/invite/invite.ts` | Rename GET /student/:token/preview to GET /student/:token; remove public-link, accept |
| `api/services/course/course.ts` or course route | Extend getCourse (slug) response to include org with theme for enroll page |
---
## Dependency Notes
- Course slug available from `getCourseById`/`getCourseWithOrgData`; ensure slug is selected in queries.
- `acceptStudentInvite` logic is reused when enroll is called with `inviteToken`.
@@ -0,0 +1,511 @@
---
name: ""
overview: ""
todos: []
isProject: false
---
# Course Page UI Extraction and Storybook Integration (Detailed Plan)
## Overview
Extract the course page UI (sidebar + content shell) into a reusable `CoursePage` component in `packages/ui`, add a Storybook story under `Pages/CoursePage` that accepts JSON to form the whole page, and wire the dashboard layout to use it. **Content rendering in Storybook is view-mode only** (lesson and exercise). Edit mode stays in the dashboard and is out of scope.
---
## Part 0: Prerequisites and Reference Files to Read
Before starting, a junior dev should read these files to understand the patterns:
1. **Exercise Question pattern** (how JSON fixtures drive UI):
- `[packages/storybook/src/molecules/exercise-question/exercise-question.stories.svelte](packages/storybook/src/molecules/exercise-question/exercise-question.stories.svelte)`
- `[packages/storybook/src/molecules/exercise-question/question-fixtures.ts](packages/storybook/src/molecules/exercise-question/question-fixtures.ts)`
- `[packages/ui/src/custom/exercise-question/question-renderer.svelte](packages/ui/src/custom/exercise-question/question-renderer.svelte)`
2. **Current course layout** (what we are extracting):
- `[apps/dashboard/src/routes/courses/[id]/+layout.svelte](apps/dashboard/src/routes/courses/[id]/+layout.svelte)`
- `[apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte](apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte)`
3. **View vs Edit mode** (view mode only in Storybook):
- Exercise view: `[apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte](apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte)` uses `ExerciseQuestion.QuestionList` with `mode: 'view'`
- Lesson view: `[apps/dashboard/src/lib/features/course/components/lesson/utils.ts](apps/dashboard/src/lib/features/course/components/lesson/utils.ts)` – Note, Slide, Video, Document in view mode
---
## Part 1: Define the JSON Config Schema
### Step 1.1: Create the types file
**Create file**: `packages/ui/src/custom/course-page/course-page-types.ts`
**Purpose**: Define the shape of the JSON that drives the CoursePage. No imports from dashboard or API.
**Contents** (copy and adapt):
```typescript
/**
* JSON config for CoursePage. Used by Storybook (fixtures) and Dashboard (built from course/org state).
*/
export interface CoursePageConfig {
course: { id: string; title: string };
sidebar: CourseSidebarConfig;
/** Used by Storybook for view-mode content. Dashboard uses content snippet instead. */
content?: CourseContentViewConfig;
}
export interface CourseSidebarConfig {
backUrl: string;
backLabel: string;
navItems: CourseNavItem[];
}
export interface CourseNavItem {
id: string;
title: string;
url: string;
isActive: boolean;
isLesson?: boolean;
icon?: CourseNavIconKey;
contentTree?: CourseContentTreeSection[];
contentCount?: { lessons: number; exercises: number };
}
export type CourseNavIconKey =
| 'newsfeed'
| 'content'
| 'analytics'
| 'attendance'
| 'submissions'
| 'marks'
| 'certificates'
| 'landingpage'
| 'people'
| 'settings'
| 'section';
export interface CourseContentTreeSection {
id: string;
title: string;
items: CourseContentTreeItem[];
}
export interface CourseContentTreeItem {
id: string;
title: string;
type: 'LESSON' | 'EXERCISE';
url?: string;
isComplete?: boolean;
isUnlocked?: boolean;
}
/**
* View-mode content config for Storybook. Dashboard does NOT use this – it renders route children.
*/
export type CourseContentViewConfig =
| { type: 'lesson'; data: LessonViewData }
| { type: 'exercise'; data: ExerciseViewData }
| { type: 'placeholder'; data: { label: string } };
export interface LessonViewData {
title: string;
note?: string; // HTML string
slideUrl?: string;
videos?: { link: string; type: string; metadata?: Record<string, unknown> }[];
documents?: { title: string; url: string }[];
}
export interface ExerciseViewData {
title: string;
questions: Record<string, unknown>[];
answersByKey?: Record<string, unknown>;
}
```
**Check**: File compiles with `pnpm exec tsc --noEmit` in `packages/ui`.
---
## Part 2: Create the CoursePage UI Components
### Step 2.1: Icon lookup map
**Create file**: `packages/ui/src/custom/course-page/icon-map.ts`
**Purpose**: Map string keys from config to the actual icon components.
**Contents**:
```typescript
import type { Component } from 'svelte';
import TableOfContentsIcon from '@lucide/svelte/icons/table-of-contents';
import {
NewsFeedIcon,
ContentIcon,
AnalyticsIcon,
AttendanceIcon,
SubmissionIcon,
MarksIcon,
CertificateIcon,
LandingPageIcon,
PeopleIcon,
SettingsIcon
} from '@cio/ui/custom/moving-icons';
import type { CourseNavIconKey } from './course-page-types';
export const COURSE_NAV_ICON_MAP: Record<CourseNavIconKey, Component> = {
section: TableOfContentsIcon,
newsfeed: NewsFeedIcon,
content: ContentIcon,
analytics: AnalyticsIcon,
attendance: AttendanceIcon,
submissions: SubmissionIcon,
marks: MarksIcon,
certificates: CertificateIcon,
landingpage: LandingPageIcon,
people: PeopleIcon,
settings: SettingsIcon
};
export function getCourseNavIcon(key: CourseNavIconKey | undefined): Component | null {
if (!key) return null;
return COURSE_NAV_ICON_MAP[key] ?? null;
}
```
**Check**: Imports resolve. Moving-icons live at `packages/ui/src/custom/moving-icons`.
---
### Step 2.2: Course page sidebar
**Create file**: `packages/ui/src/custom/course-page/course-page-sidebar.svelte`
**Purpose**: Renders the sidebar from `CourseSidebarConfig`. No dashboard/API deps.
**Logic**:
- Use `@cio/ui/base/sidebar` primitives: `Sidebar.Root`, `Sidebar.Header`, `Sidebar.Content`, `Sidebar.Group`, `Sidebar.Menu`, `Sidebar.MenuItem`, `Sidebar.MenuButton`, `Sidebar.MenuSub`, `Sidebar.MenuSubItem`, `Sidebar.MenuSubButton`, `Sidebar.Rail`.
- For each `navItem`: if `isLesson` and `contentTree` exists and item `isActive`, render the collapsible tree; otherwise render a simple link.
- Use `getCourseNavIcon(navItem.icon)` for icons.
- Back button: link to `config.sidebar.backUrl` with label `config.sidebar.backLabel`.
- Sidebar header: render a simple "Course" placeholder (or accept a `sidebarHeader` snippet later).
- Use `resolve` from `$app/paths` for URLs – but CoursePage is in packages/ui which may not have SvelteKit. **Alternative**: pass `basePath` or use plain `href={item.url}` since URLs come from config.
**Note**: `packages/ui` typically does NOT have `$app/paths` (SvelteKit). Use `item.url` directly as `href={item.url}` since config supplies full URLs.
**Content tree for Lessons**: Use `Collapsible.Root` + `Collapsible.Trigger` + `Collapsible.Content` from `@cio/ui/base/collapsible`. Each section maps to a collapsible; items inside link to `item.url`. Reuse `LessonIcon` and `ExerciseIcon` from `@cio/ui/custom/moving-icons` for item types.
**Structure** (pseudocode):
```
Sidebar.Root collapsible="icon"
Sidebar.Header
slot or "Course"
Sidebar.Content
Sidebar.Group
Button/link back: backLabel -> backUrl
Sidebar.Menu
for each navItem
if isLesson && isActive && contentTree
render link + CourseContentTree (collapsible sections)
else
render link only
Sidebar.Rail
```
**CourseContentTree for config**: Create a small component that renders sections/items from `contentTree` (from config, not courseApi). Each item links to `item.url` or builds path from `courseId` + `item.id` + `item.type`. For Storybook we can use `item.url` from the fixture.
---
### Step 2.3: Course page header
**Create file**: `packages/ui/src/custom/course-page/course-page-header.svelte`
**Purpose**: Simple header: Sidebar.Trigger + course title. No Search/notifications (dashboard keeps those).
**Props**: `title: string`
**Contents**:
```svelte
<script lang="ts">
import * as Sidebar from '@cio/ui/base/sidebar';
import { Separator } from '@cio/ui/base/separator';
interface Props { title?: string; }
let { title = '' }: Props = $props();
</script>
<header class="...">
<Sidebar.Trigger />
<Separator orientation="vertical" />
<p class="...">{title}</p>
</header>
```
Copy classes from `[CourseHeader](apps/dashboard/src/lib/features/course/components/course-header.svelte)`.
---
### Step 2.4: View-mode content renderer (Lesson + Exercise)
**Create file**: `packages/ui/src/custom/course-page/course-content-view.svelte`
**Purpose**: Renders view-mode content from `CourseContentViewConfig`. Used only in Storybook.
**Props**: `config: CourseContentViewConfig`
**Logic**:
- If `config.type === 'lesson'`: render `LessonViewContent` with `config.data`
- If `config.type === 'exercise'`: render `ExerciseQuestion.QuestionList` (or `QuestionRenderer` per question) with `mode: 'view'`, `questions`, `answersByKey`, `disabled: true`
- If `config.type === 'placeholder'`: render a simple card with `config.data.label`
**Create file**: `packages/ui/src/custom/course-page/lesson-view-content.svelte`
**Purpose**: Read-only lesson view. Accepts `LessonViewData` as props.
**Rendering** (copy structure from dashboard view mode, but data-driven):
- **Note**: Use `sanitizeHtml` from `@cio/ui/tools/sanitize` + `<div>{@html sanitized}</div>`. If `!data.note`, render nothing.
- **Slide**: If `data.slideUrl`, render `<iframe src={slideUrl} title="Slides" width="100%" height="569" class="..." allowfullscreen />`. Add `?embed` for Canva URLs (see `slide.svelte`).
- **Videos**: For each `data.videos`, render `MediaPlayer` with `source: { type: video.type, url: video.link, metadata: video.metadata }`, `options: { maxHeight: '569px', width: '100%', controls: true }`.
- **Documents**: Simple list: for each `data.documents`, render `<a href={doc.url}>{doc.title}</a>`. No inline PDF viewer (dashboard keeps that).
Keep it minimal – we are matching view-mode output, not edit UI.
**Exercise view**: Use `ExerciseQuestion.QuestionList` with:
- `contract: { mode: 'view', questions: data.questions, answersByKey: data.answersByKey ?? buildFromAnswers(data), labels, disabled: true }`
- `questions` must be `ExerciseQuestionModel[]` (same shape as `[question-fixtures](packages/storybook/src/molecules/exercise-question/question-fixtures.ts)` – id, key, title, questionType, options, settings).
- `answersByKey`: map from `getExerciseQuestionContractKey(question, index)` to answer value. Either pass in fixture or build from `{ questionKey: answer }` map.
- `labels`: Use empty object `{}` – `getExerciseQuestionLabel` in `@cio/question-types` has fallbacks. Alternatively add `labels?: ExerciseQuestionLabels` to `ExerciseViewData` so fixtures can override.
---
### Step 2.5: Main CoursePage component
**Create file**: `packages/ui/src/custom/course-page/course-page.svelte`
**Purpose**: Root layout. `Sidebar.Provider` → `CoursePageSidebar` + `Sidebar.Inset` (header + content).
**Props**:
- `config: CoursePageConfig` (required)
- `content?: Snippet` (optional) – when provided, render this instead of `CourseContentView`. Dashboard passes `{@render children()}`.
- `sidebarHeader?: Snippet` (optional) – override header inside sidebar
- `sidebarFooter?: Snippet` (optional)
**Structure**:
```svelte
<Sidebar.Provider>
<CoursePageSidebar config={config.sidebar} {sidebarHeader} {sidebarFooter} />
<Sidebar.Inset>
<CoursePageHeader title={config.course.title} />
<Page.Root class="...">
{#if content}
{@render content()}
{:else if config.content}
<CourseContentView config={config.content} />
{:else}
<Empty variant="page" ... />
{/if}
</Page.Root>
</Sidebar.Inset>
</Sidebar.Provider>
```
---
### Step 2.6: Index and exports
**Create file**: `packages/ui/src/custom/course-page/index.ts`
```typescript
export { default as CoursePage } from './course-page.svelte';
export { default as CoursePageSidebar } from './course-page-sidebar.svelte';
export { default as CoursePageHeader } from './course-page-header.svelte';
export { default as CourseContentView } from './course-content-view.svelte';
export { default as LessonViewContent } from './lesson-view-content.svelte';
export * from './course-page-types';
export * from './icon-map';
```
**Update**: `packages/ui/src/index.ts` – add:
```typescript
export * as CoursePage from './custom/course-page';
```
---
## Part 3: Storybook Fixtures and Stories
### Step 3.1: Create course page fixtures
**Create file**: `packages/storybook/src/pages/course-page/course-page-fixtures.ts`
**Purpose**: JSON configs that form the whole course page. Include sidebar + view-mode content.
**Fixtures**:
1. `LESSON_VIEW_FIXTURE`: `content.type === 'lesson'` with sample note HTML, 1 video, 1 document.
2. `EXERCISE_VIEW_FIXTURE`: `content.type === 'exercise'` with 2–3 questions from `question-fixtures` (reuse RADIO_FIXTURE, CHECKBOX_FIXTURE questions) and matching answers.
3. `FULL_INSTRUCTOR_FIXTURE`: All nav items, Lessons active with content tree, `content.type === 'placeholder'` with label "Lessons list" (actual list rendering deferred).
4. `STUDENT_MINIMAL_FIXTURE`: News Feed, Lessons (with tree), Certificates. Content = placeholder.
**Example** (LESSON_VIEW_FIXTURE):
```typescript
import type { CoursePageConfig } from '@cio/ui/custom/course-page';
export const LESSON_VIEW_FIXTURE: CoursePageConfig = {
course: { id: 'course-1', title: 'Introduction to Svelte' },
sidebar: {
backUrl: '/org/acme/courses',
backLabel: 'Courses',
navItems: [
{ id: 'newsfeed', title: 'News Feed', url: '/courses/course-1', isActive: false, icon: 'newsfeed' },
{ id: 'lessons', title: 'Content', url: '/courses/course-1/lessons', isActive: true, isLesson: true, icon: 'content', contentTree: [...], contentCount: { lessons: 3, exercises: 2 } }
]
},
content: {
type: 'lesson',
data: {
title: 'Getting Started',
note: '<p>Welcome to the course...</p>',
videos: [{ link: 'https://...', type: 'youtube', metadata: {} }],
documents: [{ title: 'PDF', url: '#' }]
}
}
};
```
---
### Step 3.2: Create Storybook stories
**Create file**: `packages/storybook/src/pages/course-page/course-page.stories.svelte`
**Structure**:
- Title: `Pages/CoursePage`
- Parameters: `layout: 'fullscreen'`
- Stories:
1. **LessonView** – uses `LESSON_VIEW_FIXTURE`, no content snippet → `CourseContentView` renders lesson view.
2. **ExerciseView** – uses `EXERCISE_VIEW_FIXTURE`, no content snippet → `CourseContentView` renders exercise view (QuestionList with mode 'view').
3. **InstructorFull** – uses `FULL_INSTRUCTOR_FIXTURE`, content placeholder.
4. **StudentMinimal** – uses `STUDENT_MINIMAL_FIXTURE`.
**Pattern** (same as exercise-question):
```svelte
<script module lang="ts">
import { defineMeta } from '@storybook/addon-svelte-csf';
import { CoursePage } from '@cio/ui';
import { LESSON_VIEW_FIXTURE } from './course-page-fixtures';
const { Story } = defineMeta({
title: 'Pages/CoursePage',
component: CoursePage.CoursePage,
parameters: { layout: 'fullscreen' },
tags: ['autodocs']
});
</script>
<Story name="LessonView">
{#snippet template()}
<CoursePage.CoursePage config={LESSON_VIEW_FIXTURE} />
{/snippet}
</Story>
```
**Important**: Do NOT pass a content snippet for Lesson/Exercise stories – the config drives `CourseContentView` in view mode only. Edit mode is not in scope.
---
## Part 4: Dashboard Integration
### Step 4.1: Config adapter
**Create file**: `apps/dashboard/src/lib/features/course/utils/course-page-config.ts`
**Purpose**: Build `CoursePageConfig` from real course/org state.
**Function**: `buildCoursePageConfig(params: { course, path, courseId, isStudent, ... }): CoursePageConfig`
**Logic**:
- Copy the nav item logic from `course-sidebar-navigation.svelte` (which items to show, `isActive`, urls).
- Use `getNavItemRoute`, `getLessonsRoute` from `$features/course/utils/functions`.
- Use `getCourseContent(course)` for content tree and counts.
- `content` in config: leave undefined (dashboard uses content snippet, not config.content).
- Use `$t(...)` for labels.
---
### Step 4.2: Update layout
**Update file**: `apps/dashboard/src/routes/courses/[id]/+layout.svelte`
**Changes**:
- When `isCourseReady`: call `buildCoursePageConfig(...)` to get config.
- Import `CoursePage` from `@cio/ui`.
- Replace the current layout structure with:
```svelte
<CoursePage.CoursePage config={config} content={children}>
{@render children?.()}
</CoursePage.CoursePage>
```
(Or pass `content` as a snippet that renders `children`.)
- Keep: `Dialog.Root` (not permitted), `ContentCreateModal`, `Confetti` for exercise page.
- Pass `sidebarHeader` = OrgLogo, `sidebarFooter` = UpgradePoweredBy when applicable.
**Alternative (incremental)**: Keep `CourseSidebar` and `CourseHeader` in the dashboard initially. Only replace the shell (Provider + Inset + Page.Root) with `CoursePage` and pass the existing sidebar as a slot. Then migrate sidebar to use config in a follow-up.
---
## Part 5: Out of Scope (Document for Later)
- **Edit mode**: Lesson edit (Note, Slide, Video, Document tabs) and Exercise edit (EditMode, add question, etc.) remain in dashboard only. Do not add edit UI to `CoursePage` or Storybook.
- **ContentCreateModal**: Stays in dashboard. Optional: add a placeholder in CoursePage for "add content" if config says so.
- **Search / Notifications**: Stay in dashboard header.
- **Actual Lessons list page** (list of sections/items): Can be a placeholder in Storybook for now. Full rendering can be broken down later.
---
## Part 6: Verification Checklist
- `pnpm --filter @cio/ui build` passes
- `pnpm --filter @cio/storybook dev` runs, story `Pages/CoursePage` shows all 4 stories
- LessonView story shows sanitized note, video, document in view mode
- ExerciseView story shows questions in view mode (read-only, with sample answers)
- Dashboard `courses/[id]` layout uses `CoursePage` and renders correctly
- No edit-mode UI (pencil, add question, etc.) in Storybook
---
## File Summary (Execution Order)
| Order | Action | Path |
| ----- | ------ | --------------------------------------------------------------------- |
| 1 | Create | `packages/ui/src/custom/course-page/course-page-types.ts` |
| 2 | Create | `packages/ui/src/custom/course-page/icon-map.ts` |
| 3 | Create | `packages/ui/src/custom/course-page/lesson-view-content.svelte` |
| 4 | Create | `packages/ui/src/custom/course-page/course-content-view.svelte` |
| 5 | Create | `packages/ui/src/custom/course-page/course-page-sidebar.svelte` |
| 6 | Create | `packages/ui/src/custom/course-page/course-page-header.svelte` |
| 7 | Create | `packages/ui/src/custom/course-page/course-page.svelte` |
| 8 | Create | `packages/ui/src/custom/course-page/index.ts` |
| 9 | Update | `packages/ui/src/index.ts` |
| 10 | Create | `packages/storybook/src/pages/course-page/course-page-fixtures.ts` |
| 11 | Create | `packages/storybook/src/pages/course-page/course-page.stories.svelte` |
| 12 | Create | `apps/dashboard/src/lib/features/course/utils/course-page-config.ts` |
| 13 | Update | `apps/dashboard/src/routes/courses/[id]/+layout.svelte` |
@@ -0,0 +1,180 @@
---
name: Course Page UI Storybook
overview: Extract the course page UI (sidebar + content shell) into a reusable `CoursePage` component in `packages/ui`, add a Storybook story under `Pages/CoursePage` that accepts JSON to form the whole page, and wire the dashboard layout to use it by passing data.
todos: []
isProject: false
---
# Course Page UI Extraction and Storybook Integration
## Current State
- **Layout**: `[apps/dashboard/src/routes/courses/[id]/+layout.svelte](apps/dashboard/src/routes/courses/[id]/+layout.svelte)` uses `Sidebar.Provider` → `CourseSidebar` + `Sidebar.Inset` (CourseHeader + children in `Page.Root`)
- **Sidebar**: `[course-sidebar-navigation.svelte](apps/dashboard/src/lib/features/course/components/sidebar/course-sidebar-navigation.svelte)` has nav items (News Feed, Lessons + content tree, Analytics, Attendance, Submissions, Marks, Certificates, Landing Page, People, Settings) with conditional visibility via `courseApi`, `$currentOrg`, `$globalStore`, etc.
- **Pattern reference**: Exercise questions use `packages/ui` components + `packages/storybook` fixtures (JSON) and `QuestionTypeModes` for different modes; stories under `Molecules/ExerciseQuestion`
## Architecture
```mermaid
flowchart TB
subgraph packages_ui [packages/ui]
CoursePage[CoursePage Component]
CoursePageSidebar[CoursePageSidebar]
CoursePageTypes[course-page-types.ts]
end
subgraph packages_storybook [packages/storybook]
CoursePageStories[Pages/CoursePage Stories]
CoursePageFixtures[course-page-fixtures.ts]
end
subgraph dashboard [apps/dashboard]
Layout[courses/[id]/+layout.svelte]
ConfigAdapter[Config Adapter - build config from course/org state]
end
CoursePageFixtures -->|JSON config| CoursePageStories
CoursePageStories -->|renders| CoursePage
ConfigAdapter -->|JSON config| Layout
Layout -->|passes config + children| CoursePage
```
## 1. Define JSON Config Schema
Create `[packages/ui/src/custom/course-page/course-page-types.ts](packages/ui/src/custom/course-page/course-page-types.ts)` with a config-driven shape:
```ts
// Core types - no dashboard/API imports
export interface CoursePageConfig {
course: { id: string; title: string };
sidebar: CourseSidebarConfig;
/** Optional - used by Storybook for mock content; dashboard uses children instead */
content?: { type: string; data?: unknown };
}
export interface CourseSidebarConfig {
backUrl: string;
backLabel: string;
navItems: CourseNavItem[];
}
export interface CourseNavItem {
id: string;
title: string;
url: string;
isActive: boolean;
isLesson?: boolean;
icon?: 'newsfeed' | 'content' | 'analytics' | 'attendance' | 'submissions' | 'marks' | 'certificates' | 'landingpage' | 'people' | 'settings' | 'section';
contentTree?: CourseContentTreeSection[];
contentCount?: { lessons: number; exercises: number };
}
export interface CourseContentTreeSection {
id: string;
title: string;
items: { id: string; title: string; type: 'LESSON' | 'EXERCISE'; url?: string; isComplete?: boolean; isUnlocked?: boolean }[];
}
```
Icon mapping: string keys → existing `@cio/ui/custom/moving-icons` (NewsFeedIcon, ContentIcon, etc.)
## 2. Create CoursePage Component in packages/ui
**Location**: `packages/ui/src/custom/course-page/`
**Components**:
- `course-page.svelte` – Root: `Sidebar.Provider` + `CoursePageSidebar` + `Sidebar.Inset` (header + content slot)
- `course-page-sidebar.svelte` – Renders sidebar from `CourseSidebarConfig` (no `courseApi`, org stores, or translations – uses config only)
- `course-page-header.svelte` – Simple header: Sidebar.Trigger + course title (Search/notifications stay in dashboard for now)
**Props**:
- `config: CoursePageConfig` (required)
- `content` snippet (optional) – dashboard passes `{@render children()}`, Storybook passes a mock renderer
**Sidebar behavior**:
- Uses `@cio/ui/base/sidebar` primitives
- Renders nav items from `config.sidebar.navItems`
- For `isLesson` items, renders expandable content tree from `contentTree`
- No OrgLogo/UpgradePoweredBy in the UI package – use placeholder (e.g. "Org Logo") or accept optional `sidebarHeader` snippet for customization
## 3. Placeholder for Dashboard-Specific Pieces
The current sidebar uses:
- `OrgLogo` (from `$features/ui/sidebar`)
- `UpgradePoweredBy` (org plan)
- `ContentCreateModal`, `ContentCountBadges`, `IconButton` for add content
**Approach**: CoursePage accepts optional snippets:
- `sidebarHeader` – default: simple "Course" text; dashboard overrides with OrgLogo
- `sidebarFooter` – default: empty; dashboard overrides with UpgradePoweredBy when free plan
- For add-content button and ContentCountBadges on the Lessons item: include in config (`showAddButton`, `contentCount`) and render when present; dashboard passes these, Storybook omits or mocks
## 4. Storybook Integration
**New folder**: `packages/storybook/src/pages/course-page/`
**Files**:
- `course-page-fixtures.ts` – JSON fixtures defining full course page configs:
- `FULL_INSTRUCTOR_FIXTURE` – all nav items, Lessons expanded with 2 sections and sample lessons/exercises
- `STUDENT_MINIMAL_FIXTURE` – News Feed, Lessons, Certificates only
- `CONTENT_FOCUS_FIXTURE` – Lessons active with rich content tree
- `course-page.stories.svelte` – Stories under `Pages/CoursePage`:
- **Default** – uses FULL_INSTRUCTOR_FIXTURE, content area shows placeholder based on `config.content.type`
- **Student view** – uses STUDENT_MINIMAL_FIXTURE
- **Lessons expanded** – uses CONTENT_FOCUS_FIXTURE
**Content placeholder**: For Storybook, when `config.content` is present, render a simple card: "Content: {type}" and optionally stringify `data` for inspection. Actual content rendering is out of scope.
## 5. Dashboard Integration
**Adapter**: Create `apps/dashboard/src/lib/features/course/utils/course-page-config.ts`:
- `buildCoursePageConfig(course, path, { isStudent, ... })` – maps real course/org state to `CoursePageConfig`
- Reuses `getCourseContent`, `getNavItemRoute`, `getLessonsRoute`, `NAV_IDS`, translation keys
**Layout update**: `[apps/dashboard/src/routes/courses/[id]/+layout.svelte](apps/dashboard/src/routes/courses/[id]/+layout.svelte)`:
- When `isCourseReady`: compute config via `buildCoursePageConfig`
- Render `CoursePage` from `@cio/ui` with `config` and `content` snippet = `{@render children()}`
- Keep existing logic: `Dialog.Root` (not permitted), `ContentCreateModal`, `Confetti`, loading state
- Dashboard-specific pieces (OrgLogo, UpgradePoweredBy, add-content button) passed as snippets where the adapter indicates they should show
**Alternative (simpler first pass)**: Keep `CourseSidebar` and `CourseHeader` in the dashboard; extract only a "shell" that accepts config. The shell would be the `Sidebar.Provider` + `Sidebar.Inset` + `Page.Root` structure, with sidebar and header as slots. That allows incremental migration.
## 6. Exports and Wiring
- Add `packages/ui/src/custom/course-page/index.ts` and export from `packages/ui/src/index.ts`
- Ensure `packages/storybook` depends on `@cio/ui` (already does)
- Storybook stories path: `../src/pages/course-page/*.stories.svelte` (covered by existing `../src/**/*.stories.@(js|ts|svelte)`)
## 7. Out of Scope (Deferred)
- Actual content renderers (News Feed, Lessons list, Analytics, etc.) driven by JSON – user said "can be broken down later"
- `ContentCreateModal` integration in the CoursePage component
- Search and notifications in the header – remain dashboard-specific for now
## File Summary
| Action | Path |
| ------ | --------------------------------------------------------------------- |
| Create | `packages/ui/src/custom/course-page/course-page-types.ts` |
| Create | `packages/ui/src/custom/course-page/course-page-sidebar.svelte` |
| Create | `packages/ui/src/custom/course-page/course-page-header.svelte` |
| Create | `packages/ui/src/custom/course-page/course-page.svelte` |
| Create | `packages/ui/src/custom/course-page/index.ts` |
| Update | `packages/ui/src/index.ts` (export CoursePage) |
| Create | `packages/storybook/src/pages/course-page/course-page-fixtures.ts` |
| Create | `packages/storybook/src/pages/course-page/course-page.stories.svelte` |
| Create | `apps/dashboard/src/lib/features/course/utils/course-page-config.ts` |
| Update | `apps/dashboard/src/routes/courses/[id]/+layout.svelte` |
@@ -0,0 +1,156 @@
---
name: Global presigned URL strategy
overview: Add Redis caching for presigned download URLs on the API, and introduce a PresignApi class on the frontend so all presign requests go through one API class instead of calling classroomio.course.presign directly.
todos: []
isProject: false
---
# Global Presigned URL Strategy – Redis Cache
## Current state
Every place that needs a presigned download URL calls S3 `getSignedUrl` with no caching:
| Caller | When | Goes through |
| ----------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| [lesson-media.ts](apps/api/src/utils/lesson-media.ts) | Enrich single lesson (documents/videos) | `generateDocumentDownloadPresignedUrls` / `generateVideoDownloadPresignedUrls` |
| [presign.ts](apps/api/src/routes/course/presign.ts) | Client calls `POST /presign/document/download` or `/video/download` | Same S3 utils |
| Client `enrichFileUploadAnswersWithUrls` | Open exercise submission | Client → `POST presign/document/download` |
**Problem**: Same fileKey generates a new presigned URL every time—whether loading a lesson again, opening the grading modal again, or re-requesting media. Server-side enrichment for lessons does not cache; each lesson load hits S3 again.
---
## Proposed approach: Redis cache in API
Cache presigned URLs in Redis at the S3 utils layer so all callers benefit without changes.
```mermaid
flowchart TB
subgraph callers [Callers]
LessonMedia[lesson-media.ts]
PresignRoute[presign routes]
Future[future submission enrichment]
end
subgraph s3Utils [apps/api/src/utils/s3.ts]
GenUrls[generateDownloadPresignedUrls]
end
subgraph cache [Redis Cache]
Check["GET presign:download:{bucket}:{key}"]
Store["SETEX TTL 50min"]
end
LessonMedia --> GenUrls
PresignRoute --> GenUrls
Future --> GenUrls
GenUrls --> Check
Check -->|"hit"| Return[Return cached URL]
Check -->|"miss"| S3[getSignedUrl from AWS SDK]
S3 --> Store
Store --> Return
```
---
## Part A: Redis cache (API)
### 1. Add Redis cache inside presigned URL logic
**File**: [apps/api/src/utils/s3.ts](apps/api/src/utils/s3.ts)
- Import `redis` from [redis/redis.ts](apps/api/src/utils/redis/redis.ts)
- Inside `generateDownloadPresignedUrls`:
- Cache key: `presign:download:{bucketName}:{fileKey}` (bucket distinguishes documents vs videos)
- TTL: 3000 seconds (50 min); presigned URLs are typically valid 1 hour
- Use `redis.mget()` for batch lookup of cache keys before generating
- For cache hits: add to result
- For misses: generate via `getSignedUrl`, store with `redis.setex()`, add to result
- `generateVideoDownloadPresignedUrls` and `generateDocumentDownloadPresignedUrls` call `generateDownloadPresignedUrls`, so they automatically use the cache; no changes needed
### 2. Graceful Redis failure
- If Redis is down or `mget`/`setex` fails, fall back to generating URLs without cache (current behavior)
- Log the error but do not fail the request
---
## Part B: PresignApi class (frontend)
Create a single API class responsible for all presigned URL requests so components never call `classroomio.course.presign...` directly.
### 1. PresignApi class
**New file**: [apps/dashboard/src/lib/features/course/api/presign.svelte.ts](apps/dashboard/src/lib/features/course/api/presign.svelte.ts)
- Extend `BaseApiWithErrors`, use `this.execute<RequestType>()` per AGENTS.md
- Methods:
- `getDocumentUploadUrl(fileName: string, fileType: string)` → `{ url, fileKey }`
- `getDocumentDownloadUrls(keys: string[])` → `Record<string, string>`
- `getVideoUploadUrl(fileName: string, fileType: string)` → `{ url, fileKey }`
- `getVideoDownloadUrls(keys: string[])` → `Record<string, string>`
- Each method wraps `classroomio.course.presign.document.upload`, `document.download`, `video.upload`, or `video.download`
- Export singleton: `export const presignApi = new PresignApi()`
### 2. Types in `utils/types.ts`
**File**: [apps/dashboard/src/lib/features/course/utils/types.ts](apps/dashboard/src/lib/features/course/utils/types.ts)
- Add request types inferred from API: `DocumentUploadPresignRequest`, `DocumentDownloadPresignRequest`, etc.
### 3. Export from course api
**File**: [apps/dashboard/src/lib/features/course/api/index.ts](apps/dashboard/src/lib/features/course/api/index.ts)
- Export `presignApi` from presign.svelte.ts
### 4. Callers to update
| Caller | Current | Change |
| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| [view-mode.svelte](apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte) | `classroomio.course.presign.document.upload.$post` and `document.download.$post` in `handleFileUpload` | Use `presignApi.getDocumentUploadUrl` and `presignApi.getDocumentDownloadUrls`; remove `classroomio` import |
| [functions.ts](apps/dashboard/src/lib/features/course/utils/functions.ts) `enrichFileUploadAnswersWithUrls` | `classroomio.course.presign.document.download.$post` | Use `presignApi.getDocumentDownloadUrls` (needs access to presignApi singleton) |
| [media-manager.svelte.ts](apps/dashboard/src/lib/features/media/api/media-manager.svelte.ts) `getAssetDownloadUrl` | `classroomio.course.presign.document.download` or `video.download` | Use `presignApi.getDocumentDownloadUrls` or `presignApi.getVideoDownloadUrls` |
| [presign.ts](apps/dashboard/src/lib/utils/services/courses/presign.ts) `GenericUploader` | Calls `classroomio.course.presign...` in `getPresignedUrl` and `getDownloadPresignedUrl` | Use `presignApi` methods instead |
**Note**: `enrichFileUploadAnswersWithUrls` is a pure function in `functions.ts`. It would need to either:
- Accept `presignApi` (or a fetch function) as a parameter, or
- Import `presignApi` directly from `$features/course/api`
The latter is simpler; we import presignApi where needed.
---
## Files to change
| File | Change |
| ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| [apps/api/src/utils/s3.ts](apps/api/src/utils/s3.ts) | Add Redis cache check/store inside `generateDownloadPresignedUrls` |
| [apps/dashboard/src/lib/features/course/api/presign.svelte.ts](apps/dashboard/src/lib/features/course/api/presign.svelte.ts) | New: PresignApi class |
| [apps/dashboard/src/lib/features/course/utils/types.ts](apps/dashboard/src/lib/features/course/utils/types.ts) | Add presign request types |
| [apps/dashboard/src/lib/features/course/api/index.ts](apps/dashboard/src/lib/features/course/api/index.ts) | Export presignApi |
| [view-mode.svelte](apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte) | Use presignApi; remove classroomio import |
| [functions.ts](apps/dashboard/src/lib/features/course/utils/functions.ts) | Use presignApi.getDocumentDownloadUrls |
| [media-manager.svelte.ts](apps/dashboard/src/lib/features/media/api/media-manager.svelte.ts) | Use presignApi for download URLs |
| [presign.ts](apps/dashboard/src/lib/utils/services/courses/presign.ts) | GenericUploader uses presignApi |
---
## Benefits
- **Lesson documents/videos**: Re-loading the same lesson uses cached URLs
- **Presign API**: Repeated client calls for same keys hit cache
- **Exercise submissions**: When client calls `enrichFileUploadAnswersWithUrls` (or future server enrichment), cache reduces S3 calls
- **Media manager**: Same pattern—shared cache across the app
@@ -0,0 +1,292 @@
---
name: JWT Token Exchange
overview: Implement a JWT token exchange endpoint that lets customers automatically log their users into ClassroomIO from their own app -- no re-login required. This uses a per-org signing secret and Better Auth's `setSessionCookie` to create sessions from externally-signed JWTs.
todos:
- id: db-schema
content: Add `organization_token_auth` table to schema.ts and create migration 0008
status: pending
- id: db-queries
content: Create token-auth.ts queries (get, create, rotate, delete, toggle active)
status: pending
- id: validation
content: Add Zod schemas for token exchange (ZTokenExchangeQuery, ZTokenExchangePayload) and token auth admin operations
status: pending
- id: extract-provisioning
content: Extract reusable `ensureOrgMembership(userId, email, orgId, roleId?)` from sso-provisioning.ts
status: pending
- id: token-exchange-service
content: "Create token-exchange.ts service: decode JWT, verify signature, find/create user, ensure membership"
status: pending
- id: better-auth-plugin
content: Create Better Auth plugin with `createAuthEndpoint` for `/token-exchange` using `setSessionCookie`
status: pending
- id: admin-service
content: Create token-auth.ts service (enterprise plan check, secret generation, conflict checks) and route (HTTP concerns only, delegates to service, uses handleError)
status: pending
- id: admin-routes
content: Create token-auth route file, export, and register in app.ts
status: pending
- id: error-codes
content: Add token exchange and token auth error codes to errors.ts
status: pending
- id: frontend-types
content: Add request types for token auth endpoints in org/utils/types.ts (infer from RPC client)
status: pending
- id: frontend-api
content: Create TokenAuthApi class extending BaseApiWithErrors in org/api/token-auth.svelte.ts
status: pending
- id: frontend-ui
content: Create token-auth.svelte settings page, route page, navigation entry, and settings index registration
status: pending
- id: translations
content: Add en.json translation keys for all token auth UI strings (no hardcoded English)
status: pending
- id: build-verify
content: Run build, check types, verify migration
status: pending
isProject: false
---
# JWT Token Exchange for Seamless Auto-Login
## Architecture
```mermaid
sequenceDiagram
participant CustomerApp as Customer App
participant CustomerBackend as Customer Backend
participant CIO as ClassroomIO API
participant BetterAuth as Better Auth
participant DB as Database
CustomerApp->>CustomerBackend: User wants to access ClassroomIO
CustomerBackend->>CustomerBackend: Sign JWT with org secret
CustomerBackend->>CustomerApp: Return signed JWT
CustomerApp->>CIO: GET /auth/token-exchange?token=xxx&redirect=/courses
CIO->>DB: Look up org signing secret by org_id from JWT
CIO->>CIO: Verify JWT signature + expiry with jose
CIO->>DB: Find user by email
alt User does not exist
CIO->>BetterAuth: Create user via auth.api.signUpEmail (internal)
BetterAuth->>DB: Insert user + account
Note over CIO: createProfileHook fires automatically
end
CIO->>DB: Ensure org membership (reuse provisioning logic)
CIO->>BetterAuth: setSessionCookie(ctx, session/user)
CIO->>CustomerApp: 302 Redirect to target page (with session cookie)
```
## Step 1: Database -- Add `organization_token_auth` table
Create a new table rather than overloading `organization_sso_config`, since token exchange is conceptually separate from OIDC SSO and should work independently (an org might want token exchange without configuring Okta/Auth0).
**New table: `organization_token_auth`**
- `id` (uuid, PK)
- `organization_id` (uuid, unique FK to organization, cascade delete)
- `signing_secret` (text, not null) -- HMAC secret for HS256 JWT verification
- `is_active` (boolean, default false)
- `created_by_profile_id` (uuid FK to profile)
- `created_at`, `updated_at` (timestamptz)
Files to change:
- [packages/db/src/schema.ts](packages/db/src/schema.ts) -- add `organizationTokenAuth` table definition after line 1934
- New migration file: `packages/db/src/migrations/0008_add_token_auth_table.sql`
- [packages/db/src/types.ts](packages/db/src/types.ts) -- add inferred types
## Step 2: Database Queries
**Location**: `packages/db/src/queries/organization/token-auth.ts` (per ARCHITECTURE.md Layer 1 pattern)
Create [packages/db/src/queries/organization/token-auth.ts](packages/db/src/queries/organization/token-auth.ts) with pure DB functions -- no business logic, no HTTP calls, no transactions (those belong in the service layer):
- `getTokenAuthByOrgId(orgId)` -- look up signing secret for an org
- `createTokenAuth(data: TNewOrganizationTokenAuth)` -- insert new record, use `.returning()`
- `updateTokenAuth(orgId, data: Partial<TOrganizationTokenAuth>)` -- update fields, use `.returning()`
- `deleteTokenAuth(orgId)` -- remove the record
Every `catch` block must log with function name for traceability: `console.error('getTokenAuthByOrgId error:', error)`.
## Step 3: Validation Schemas
**Location**: `packages/utils/src/validation/organization/token-auth.ts` (per ARCHITECTURE.md -- shared validation in `@cio/utils/validation`, used by both API and frontend)
Create [packages/utils/src/validation/organization/token-auth.ts](packages/utils/src/validation/organization/token-auth.ts):
- `ZTokenExchangeQuery` -- validates the `token` (string, min 1) and optional `redirect` (string) query params
- `ZTokenExchangePayload` -- validates the decoded JWT payload: `sub` (string), `email` (email), `name` (string, optional), `org_id` (uuid), `iat` (number), `exp` (number)
Export `T`* inferred types alongside each schema (`export type TTokenExchangeQuery = z.infer<typeof ZTokenExchangeQuery>`).
## Step 4: Service -- Token Exchange Logic
**Location**: `apps/api/src/services/auth/token-exchange.ts` (per ARCHITECTURE.md Layer 2 -- business logic lives in services, throws `AppError` with error codes and status codes, returns structured data not HTTP responses)
Create [apps/api/src/services/auth/token-exchange.ts](apps/api/src/services/auth/token-exchange.ts):
```typescript
export async function exchangeToken(token: string): Promise<{ user: User; orgId: string; }>
```
This function:
1. Decode JWT **without** verifying to extract `org_id` from payload
2. Look up signing secret via `getTokenAuthByOrgId(orgId)` -- throw `AppError(ErrorCodes.TOKEN_EXCHANGE_ORG_NOT_FOUND, 404)` if not found or `AppError(ErrorCodes.TOKEN_EXCHANGE_NOT_ENABLED, 403)` if inactive
3. Verify JWT with `jose.jwtVerify(token, secret, { algorithms: ['HS256'] })` -- validates signature + expiry
4. Reject tokens older than 5 minutes (`maxTokenAge: '5m'`)
5. Validate payload against `ZTokenExchangePayload`
6. Find existing user by email in the `user` table (Better Auth's table)
7. If no user exists, create one via `auth.api.signUpEmail` with a random password (the user will never use it -- they always come through token exchange). The `createProfileHook` fires automatically and `ssoProvisioningHook` handles org membership
8. If user exists but is not an org member, run the provisioning logic from [packages/db/src/auth/hooks/sso-provisioning.ts](packages/db/src/auth/hooks/sso-provisioning.ts) (extracted into a reusable function that accepts userId + orgId rather than relying on email domain matching)
9. Return the user object and orgId
## Step 5: Provisioning -- Extract Reusable Function
Refactor [packages/db/src/auth/hooks/sso-provisioning.ts](packages/db/src/auth/hooks/sso-provisioning.ts) to extract a reusable `ensureOrgMembership(userId, email, orgId, roleId?)` function that:
- Checks if membership already exists
- If not, checks for pending invite (accept it) or creates membership with default role
The existing `ssoProvisioningHook` continues to call this function (it just adds the domain-lookup step on top). The new token exchange service also calls it directly with the `org_id` from the JWT.
## Step 6: Route -- Public Token Exchange Endpoint
Create [apps/api/src/routes/auth/token-exchange.ts](apps/api/src/routes/auth/token-exchange.ts):
```
GET /auth/token-exchange?token=<jwt>&redirect=<url>
```
This is a **public** endpoint (no `authMiddleware`). Flow:
1. Validate query params with `ZTokenExchangeQuery`
2. Call `exchangeToken(token)` from the service
3. Create a Better Auth session using internal API (see below)
4. Set the session cookie using `setSessionCookie` from `better-auth/cookies`
5. Redirect (302) to the `redirect` param or default to `/`
**Session creation approach** -- Based on the [Better Auth discussion #2125](https://github.com/better-auth/better-auth/discussions/2125), use `setSessionCookie` from `better-auth/cookies` combined with creating the session through Better Auth's internal context. The route will be implemented as a Better Auth plugin endpoint using `createAuthEndpoint` from `better-auth/api` to get access to the auth context needed by `setSessionCookie`.
Register as a Better Auth plugin in [packages/db/src/auth.ts](packages/db/src/auth.ts) (not as a regular Hono route) so it gets the internal context:
```typescript
import { tokenExchange } from './auth/plugins/token-exchange';
// in plugins array:
plugins: [admin(), anonymous(), jwt(), sso({}), tokenExchange()]
```
This means the endpoint lives at `/api/auth/token-exchange` (under Better Auth's route namespace).
## Step 7: Admin Routes -- Secret Management
**Location**: `apps/api/src/routes/organization/token-auth.ts` (per ARCHITECTURE.md Layer 3 -- routes handle HTTP concerns only: validation, auth, serialization)
Create [apps/api/src/routes/organization/token-auth.ts](apps/api/src/routes/organization/token-auth.ts). Routes delegate to the service layer and use `handleError` in catch blocks. Use `authMiddleware` + `orgAdminMiddleware`. Non-null assert `user` (`c.get('user')!`) since `authMiddleware` guarantees it.
- `POST /organization/token-auth` -- generate signing secret (requires admin + enterprise plan). Returns `201` with secret shown once
- `GET /organization/token-auth` -- get token auth status (active/inactive, created date -- **never** returns the full secret, only last 4 chars). Returns `200`
- `POST /organization/token-auth/rotate` -- rotate the secret (returns new secret once). Returns `200`
- `DELETE /organization/token-auth` -- delete token auth config. Returns `200`
- `PUT /organization/token-auth/activate` -- toggle active/inactive. Returns `200`
Create the corresponding service [apps/api/src/services/organization/token-auth.ts](apps/api/src/services/organization/token-auth.ts) for business logic (enterprise plan check, secret generation via `crypto.randomBytes(32).toString('hex')`, conflict checks). Routes must not contain business logic.
Export and register in [apps/api/src/app.ts](apps/api/src/app.ts):
```typescript
.route('/organization/token-auth', organizationTokenAuthRouter)
```
## Step 8: Error Codes
Add to [apps/api/src/utils/errors.ts](apps/api/src/utils/errors.ts):
- `TOKEN_EXCHANGE_INVALID_TOKEN`
- `TOKEN_EXCHANGE_EXPIRED`
- `TOKEN_EXCHANGE_ORG_NOT_FOUND`
- `TOKEN_EXCHANGE_NOT_ENABLED`
- `TOKEN_AUTH_ALREADY_EXISTS`
## Step 9: Frontend -- Request Types
**Location**: `apps/dashboard/src/lib/features/org/utils/types.ts` (per AGENTS.md -- define request types in `{domain}/utils/types.ts` for reusability)
Add request types for all token auth endpoints:
```typescript
export type CreateTokenAuthRequest = (typeof classroomio.organization)['token-auth']['$post'];
export type GetTokenAuthRequest = (typeof classroomio.organization)['token-auth']['$get'];
export type RotateTokenAuthRequest = (typeof classroomio.organization)['token-auth']['rotate']['$post'];
export type DeleteTokenAuthRequest = (typeof classroomio.organization)['token-auth']['$delete'];
export type ActivateTokenAuthRequest = (typeof classroomio.organization)['token-auth']['activate']['$put'];
```
Never import types from `@cio/db/queries` into dashboard code -- infer everything from the RPC client.
## Step 10: Frontend API Class
**Location**: `apps/dashboard/src/lib/features/org/api/token-auth.svelte.ts` (per AGENTS.md -- API class pattern: extends `BaseApiWithErrors`, handles all logic so components are thin)
Create [apps/dashboard/src/lib/features/org/api/token-auth.svelte.ts](apps/dashboard/src/lib/features/org/api/token-auth.svelte.ts):
- Class `TokenAuthApi extends BaseApiWithErrors`
- Reactive state: `tokenAuth = $state<TokenAuthStatus | null>(null)`, `generatedSecret = $state<string | null>(null)`
- Methods using `this.execute<RequestType>()` (never call RPC directly):
- `getStatus()` -- fetch token auth status
- `generateSecret()` -- create new config, store returned secret in `generatedSecret`
- `rotateSecret()` -- rotate, store new secret in `generatedSecret`
- `deleteTokenAuth()` -- delete config
- `activateTokenAuth()` -- toggle active
Use Zod client-side validation where applicable. Use `snackbar.success('translation.key')` with translation keys (not raw English strings).
Export singleton: `export const tokenAuthApi = new TokenAuthApi()`
## Step 11: Frontend -- Admin UI Component
**Location**: `apps/dashboard/src/lib/features/settings/pages/token-auth.svelte` (kebab-case per AGENTS.md naming convention)
Create [apps/dashboard/src/lib/features/settings/pages/token-auth.svelte](apps/dashboard/src/lib/features/settings/pages/token-auth.svelte) as a separate settings page (not inlined into sso.svelte -- keeps components focused):
- Import `tokenAuthApi` from `$features/org/api/token-auth.svelte`
- Use `$t('key.path')` for all user-facing text (no hardcoded English in markup)
- Use `t('key.path')` in script blocks, `t.get('key.path')` outside Svelte components
- Use UI components from `@cio/ui`:
- `@cio/ui/base/button` for actions (Generate, Rotate, Delete)
- `@cio/ui/base/badge` for active/inactive status
- `@cio/ui/base/switch` for activate toggle
- `@cio/ui/base/field` for form layout (`Field.Group`, `Field.Set`, `Field.Legend`, `Field.Description`)
- Do NOT use native `<input>`, `<label>`, `<textarea>` -- use `@cio/ui` equivalents
- Theme color classes must use `ui:` prefix in dashboard code (e.g. `ui:text-muted-foreground`, `ui:text-primary`)
- Component should be thin -- call API methods, render UI, no business logic
- `UpgradeBanner` for enterprise plan gating (same pattern as sso.svelte)
- Integration Guide section with a code snippet block showing the customer-facing JWT signing example
Create route page at [apps/dashboard/src/routes/org/[slug]/settings/token-auth/+page.svelte](apps/dashboard/src/routes/org/[slug]/settings/token-auth/+page.svelte) as a thin wrapper.
Add navigation entry in [apps/dashboard/src/lib/features/ui/navigation/org-navigation.ts](apps/dashboard/src/lib/features/ui/navigation/org-navigation.ts) and register the page in [apps/dashboard/src/lib/features/settings/pages/index.ts](apps/dashboard/src/lib/features/settings/pages/index.ts).
## Step 12: Translations
Add keys to [apps/dashboard/src/lib/utils/translations/en.json](apps/dashboard/src/lib/utils/translations/en.json) for all UI strings in the token auth section. All user-facing copy must go through translations -- snackbar messages use keys directly (e.g. `snackbar.success('snackbar.token_auth.created')`).
## Step 12: Build and Verify
Run `pnpm --filter @cio/api build` to verify types compile. Run the migration against a dev database.
## Dependencies
- `jose` npm package -- for JWT verification. Check if already installed; if not, add to `apps/api` or `packages/db`.
## Security Considerations
- Tokens must be short-lived (max 5 minutes, recommend 60 seconds)
- Signing secrets are 256-bit random hex strings
- HMAC-SHA256 (HS256) is used -- simple symmetric signing, appropriate for server-to-server where both parties share the secret
- The secret is shown to the admin exactly once on generation/rotation
- Rate limiting on the `/auth/token-exchange` endpoint (already covered by the global rate limiter, but consider stricter limits)
- Enterprise plan gating on secret generation (same as SSO)
@@ -0,0 +1,300 @@
---
name: ""
overview: ""
todos: []
isProject: false
---
# Unify Renderer Format with AnswerData
## Overview
Eliminate the impedance mismatch between UI (ExerciseAnswerValue) and storage (AnswerData) by having renderers emit and consume AnswerData directly. This removes the need for `serialize` and `toRendererValue` in the codec.
## Current State
- **Renderers** emit `ExerciseAnswerValue` (heterogeneous: optionId, boolean, string, string[], etc.)
- **Storage** uses `AnswerData` (discriminated union)
- **serialize** converts ExerciseAnswerValue → AnswerData
- **toRendererValue** converts AnswerData → ExerciseAnswerValue (for display)
## Target State
- **Renderers** emit and consume `AnswerData` directly
- **Storage** uses `AnswerData`
- **Codec** only has `toApiPayload` and `fromApiPayload` (for API flat format)
- No serialize, no toRendererValue
---
## Phase 1: Update Types and Contracts
### 1.1 exercise-types.ts
- Add `AnswerData` to imports/re-exports (or keep in answer-data.ts)
- Change `ExerciseQuestionRendererProps.answer` from `ExerciseAnswerValue` to `AnswerData | null`
- Change `onAnswerChange` from `(answer: ExerciseAnswerValue) => void` to `(answer: AnswerData) => void`
- Optionally deprecate or remove `ExerciseAnswerValue` from renderer contracts (it may still be used internally in some components)
### 1.2 render-contract.ts
- Change `ExerciseQuestionRenderContract.answer` to `AnswerData | null`
- Change `ExerciseQuestionListRenderContract.answersByKey` to `Record<string, AnswerData>`
### 1.3 form-state.ts
- Change `answers: Record<string, ExerciseAnswerValue>` to `answers: Record<string, AnswerData>`
---
## Phase 2: Update Take Renderers (12 files)
Each take renderer must:
1. Accept `answer?: AnswerData` (typed for its question type)
2. Extract display value from AnswerData (e.g. `answer?.optionId` for RADIO)
3. Call `onAnswerChange(AnswerData)` when user submits, constructing the correct AnswerData shape
| Renderer | Current emit | New emit (AnswerData) |
| ----------------- | -------------------------- | ------------------------------------------------- |
| radio/take | optionId (number) | `{ type: 'RADIO', optionId }` |
| checkbox/take | optionIds (number[]) | `{ type: 'CHECKBOX', optionIds }` |
| true-false/take | boolean | `{ type: 'TRUE_FALSE', value: boolean }` |
| textarea/take | string | `{ type: 'TEXTAREA', text }` |
| short-answer/take | string | `{ type: 'SHORT_ANSWER', text }` |
| numeric/take | number | `{ type: 'NUMERIC', value }` |
| fill-blank/take | string | string[] |
| file-upload/take | { fileKey, fileName, ... } | `{ type: 'FILE_UPLOAD', fileKey, fileName, ... }` |
| matching/take | pairs[] | `{ type: 'MATCHING', pairs }` |
| ordering/take | string[] | `{ type: 'ORDERING', orderedValues }` |
| link/take | string[] | `{ type: 'LINK', urls }` |
| hotspot/take | coordinates[] | `{ type: 'HOTSPOT', coordinates }` |
### Per-renderer pattern
```svelte
<!-- Before -->
let { answer, onAnswerChange } = $props();
onAnswerChange(selectedOptionId);
<!-- After -->
let { answer, onAnswerChange } = $props();
// answer is RadioAnswerData | undefined
const displayValue = answer?.optionId;
onAnswerChange({ type: 'RADIO', optionId: selectedOptionId });
```
---
## Phase 3: Update Preview Renderers (10 files)
Preview renderers display the answer in read-only mode. They receive `answer` and render it.
- **radio/preview**, **checkbox/preview**, **true-false/preview**: Extract optionId/optionIds/value from AnswerData for display
- **textarea/preview**, **short-answer/preview**: Extract text
- **numeric/preview**: Extract value
- **fill-blank/preview**: Extract values
- **file-upload/preview**: Extract fileKey, fileName, etc.
- **matching/preview**, **ordering/preview**, **link/preview**, **hotspot/preview**: Extract pairs/orderedValues/urls/coordinates
Preview components need the question (with options) for RADIO/CHECKBOX/TRUE_FALSE to resolve ids to labels for display. The AnswerData gives the structure; options give the labels.
---
## Phase 4: Update Dashboard Components
### 4.1 view-mode.svelte
- Change `questionnaireMetaData.answers` to `Record<string, AnswerData>`
- Replace `mapAnswerToApiPayload` usage: call `toApiPayload(answer, questionId)` directly (answer is already AnswerData)
- Remove `serializeAnswer` call from the submit flow
- `onSharedAnswerChange` receives AnswerData
- `checkForSubmission` / `formatAnswers`: answers from API are AnswerData → pass through to questionnaireMetaData
### 4.2 preview.svelte
- `grades`, `answers` in questionnaireMetaData: use AnswerData
- Pass AnswerData to QuestionRenderer contract
### 4.3 individual.svelte
- `getStudentAnswerForQuestion` returns `AnswerData` (or the raw answerData from API)
- Pass to QuestionRenderer as answer prop
### 4.4 formatAnswers (functions.ts)
- Returns `Record<string, AnswerData>` instead of `Record<string, ExerciseAnswerValue>`
- Or keep as-is if consumers expect AnswerData
### 4.5 mark-exercise-modal.svelte
- `answersToDisplay` becomes `Record<string, AnswerData>`
- Preview receives AnswerData
- `enrichFileUploadAnswersWithUrls` may need to accept AnswerData and enrich FILE_UPLOAD entries
### 4.6 summary.svelte
- `getAnswerToQuestionOfStudent` returns AnswerData
- Chart logic extracts values from AnswerData (e.g. optionIds for option-based, text for text)
### 4.7 Store (store.ts)
- `answers` in questionnaireMetaData: `Record<string, AnswerData>`
---
## Phase 5: Simplify Answer Codec
### 5.1 Remove from AnswerCodec interface
- Remove `serialize`
- Remove `toRendererValue`
### 5.2 Remove from each codec implementation
- Delete serialize implementation
- Delete toRendererValue implementation
### 5.3 Remove exported functions
- Remove `serializeAnswer`
- Remove `deserializeAnswer` (or rename to `toDisplayValue` if still needed for enrichFileUploadAnswersWithUrls, etc.)
### 5.4 Keep
- `toApiPayload` – for API submission
- `fromApiPayload` – for API write path (payload → AnswerData)
- `ANSWER_CODECS` – lookup by type
### 5.5 Add helper if needed
- `toApiPayload(data: AnswerData, questionId: number)` – already exists
- For submission: frontend has AnswerData → toApiPayload → API
- For display: AnswerData goes directly to renderer, no conversion
---
## Phase 6: Update API and Submission Flow
### 6.1 createSubmissionService
- Already uses `fromApiPayload` to convert API payload → AnswerData
- No change if API still receives flat format
### 6.2 Optional: Accept AnswerData in API
- If we change the submission API to accept `AnswerData` directly (e.g. `answers: AnswerData[]`), we can skip `fromApiPayload` and `toApiPayload` for submission. But the current API uses flat `{ questionId, optionId?, answer? }`. Plan assumes we keep that for now.
---
## Phase 7: enrichFileUploadAnswersWithUrls
- Currently expects `Record<string, unknown>` and looks for `fileKey` in values
- With AnswerData, FILE_UPLOAD answers are `{ type: 'FILE_UPLOAD', fileKey, fileName, ... }`
- Update to detect `value?.type === 'FILE_UPLOAD'` and use `value.fileKey`
- Return enriched AnswerData (add fileUrl to the object)
---
## Phase 8: Migration / Compatibility
- **No DB migration** – AnswerData format is unchanged
- **Existing data** – Already AnswerData in answer_data column
- **ExerciseAnswerValue** – Can be deprecated or removed from exercise-types once all consumers are updated
---
## Phase 9: Update ADDING_A_QUESTION_TYPE.md
**File:** `packages/question-types/ADDING_A_QUESTION_TYPE.md`
Update the guide so new question types follow the AnswerData-only flow.
### 9.1 Step 3 — Answer data type and codec
**3a. answer-data.ts** — No change; still add the AnswerData type and union.
**3b. answer-codecs.ts** — Simplify the codec example:
- Remove `serialize` — renderers emit AnswerData directly
- Remove `toRendererValue` — renderers consume AnswerData directly
- Keep only `toApiPayload` and `fromApiPayload`
Example to replace the current Step 3b block:
```typescript
const MY_NEW_TYPE_CODEC: AnswerCodec<MyNewAnswerData> = {
type: 'MY_NEW_TYPE',
toApiPayload(data, questionId) {
return { questionId, answer: JSON.stringify({ type: 'MY_NEW_TYPE', value: data.value }) };
},
fromApiPayload(payload) {
if (!payload.answer) return null;
const { value } = JSON.parse(payload.answer) as { type: 'MY_NEW_TYPE'; value: string };
return { type: 'MY_NEW_TYPE', value };
}
};
```
### 9.2 Step 7 — Implement renderers
Update the renderer section to state:
- `answer` prop is `AnswerData | null` (typed for the question type, e.g. `MyNewAnswerData`)
- `onAnswerChange` receives `AnswerData` — renderers must emit the full AnswerData shape, e.g. `onAnswerChange({ type: 'MY_NEW_TYPE', value })`
- Take renderer: extract display value from `answer?.value` (or relevant field), emit `{ type: 'MY_NEW_TYPE', value }` on change
- Preview renderer: read from `answer` (AnswerData) for display
### 9.3 Checklist
- Update checklist item for the codec to say "`AnswerCodec` (toApiPayload, fromApiPayload)" — no serialize/toRendererValue
### 9.4 Step 9 — Verify
- Update the test bullet to mention: "codec (toApiPayload ↔ fromApiPayload)"
- Remove references to "serialize" in the verification steps
---
## Files to Modify (Summary)
| Area | Files |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Types | `exercise-types.ts`, `render-contract.ts`, `form-state.ts` |
| Codec | `answer-codecs.ts` (remove serialize, toRendererValue) |
| Take renderers | 12× `packages/ui/.../renderers/*/take.svelte` |
| Preview renderers | 10× `packages/ui/.../renderers/*/preview.svelte` |
| Dashboard | `view-mode.svelte`, `preview.svelte`, `individual.svelte`, `summary.svelte`, `mark-exercise-modal.svelte`, `store.ts`, `functions.ts` |
| Utils | `enrichFileUploadAnswersWithUrls` in functions.ts |
| Storybook | `question-type-modes.svelte`, `question-fixtures.ts` if they use answer |
| ordering-utils | `applyOrderingAnswer` – change to accept AnswerData (OrderingAnswerData) |
| Docs | `packages/question-types/ADDING_A_QUESTION_TYPE.md` |
---
## Estimated Effort
- Phase 1: ~30 min
- Phase 2: ~2–3 hours (12 renderers, each ~10–15 min)
- Phase 3: ~1–2 hours (10 preview components)
- Phase 4: ~1–2 hours (dashboard)
- Phase 5: ~30 min (codec cleanup)
- Phase 6: minimal
- Phase 7: ~15 min
- Phase 8: N/A
- Phase 9: ~15 min (update ADDING_A_QUESTION_TYPE.md)
**Total: ~6–8 hours**
---
## Risks
- **Preview mode** for edit: Edit renderers may not use answer; verify which modes each renderer supports
- **ordering-utils**: `applyOrderingAnswer` merges initial items with answer; ensure it works with `OrderingAnswerData`
- **Storybook**: Update fixtures and stories to pass AnswerData
+1
View File
@@ -46,6 +46,7 @@ yarn-error.log*
**/build
**/.next
**/.svelte-kit
**/tsconfig.tsbuildinfo
**/coverage
**/.nyc_output
**/test-results
+12 -2
View File
@@ -7,12 +7,22 @@ supabase
static
dist
docker
packages/storybook/storybook-static
**/course-app
apps/docs
apps/api/static
pnpm-lock.yaml
*.md
**/*.md
output.css
packages/ui/src/output.css
*.sql
*.env*
# No parser for these
.prettierignore
.dockerignore
**/Dockerfile
+6
View File
@@ -0,0 +1,6 @@
services:
- domain: cio-fe
port: 5173
- domain: cio-be
port: 3002
log_mode: minimal
+275
View File
@@ -0,0 +1,275 @@
# Agent Guidance
This document collects implementation rules and workflow conventions for code changes.
## Naming Convention
- Use kebab-case for files (e.g. `user-profile.svelte`, `org.svelte.ts`).
## Creating a New Route
### Step 1: Validation Schema
```typescript
// packages/utils/src/validation/account/account.ts
export const ZUpdateProfile = z.object({
fullname: z.string().min(5).optional(),
username: z.string().min(1).optional()
});
export type TUpdateProfile = z.infer<typeof ZUpdateProfile>;
```
### Step 2: Service
```typescript
// apps/api/src/services/account.ts
export async function updateUser(userId: string, data: Partial<TProfile>) {
const updated = await updateProfile(userId, data);
if (!updated) throw new AppError('Profile not found', ErrorCodes.PROFILE_NOT_FOUND, 404);
return updated;
}
```
### Step 3: Route
Routes must return a single type (or a response shape whose `data` is a single type). If multiple shapes are needed, use separate endpoints or a keyed structure (e.g. `data` indexed by a key) so clients get one type per endpoint or key. Do not return a union of shapes from one route based on query parameters.
```typescript
// apps/api/src/routes/account/account.ts
export const accountRouter = new Hono().put(
'/user',
authMiddleware,
zValidator('json', ZUpdateProfile),
async (c) => {
try {
const user = c.get('user')!;
const data = c.req.valid('json');
const result = await updateUser(user.id, data);
return c.json({ success: true, data: result });
} catch (error) {
return handleError(c, error, 'Failed to update profile');
}
}
);
```
### Step 4: Register
```typescript
// apps/api/src/routes/account/index.ts
export * from './account';
// apps/api/src/app.ts
import { accountRouter } from '@api/routes/account';
export const app = new Hono().route('/account', accountRouter);
```
### Step 5: Build
```bash
pnpm --filter @cio/api build
```
### Step 6: Frontend Types & API Class
```typescript
// apps/dashboard/src/lib/features/account/utils/types.ts
import { classroomio } from '$lib/utils/services/api';
export type UpdateProfileRequest = typeof classroomio.account.user.$put;
```
```typescript
// apps/dashboard/src/lib/features/account/api/account.svelte.ts
import type { UpdateProfileRequest } from '../utils/types';
class AccountApi extends BaseApiWithErrors {
async updateProfile(fields: TUpdateProfile) {
const result = ZUpdateProfile.safeParse(fields);
if (!result.success) {
this.errors = mapZodErrorsToTranslations(result.error);
return;
}
await this.execute<UpdateProfileRequest>({
requestFn: () => classroomio.account.user.$put({ json: result.data }),
logContext: 'updating profile',
onSuccess: () => {
snackbar.success('Profile updated');
this.success = true;
},
onError: (result) => {
if ('field' in result) this.errors[result.field] = result.error;
}
});
}
}
```
## Frontend Conventions
### Request Types and Where Types Live
Define all request and response-related types in the feature’s `utils/types.ts` file. **Do not define types or interfaces in `.svelte.ts` files** (e.g. `api/*.svelte.ts` or `store/*.svelte.ts`). Infer types from the API: request type from the RPC call, then success/data from the response type.
```typescript
// apps/dashboard/src/lib/features/org/utils/types.ts
import { classroomio, type InferResponseType } from '$lib/utils/services/api';
export type GetTeamRequest = typeof classroomio.organization.team.$get;
export type CreateOrgRequest = typeof classroomio.organization.$post;
export type UpdateOrgRequest = typeof classroomio.organization.$put;
export type DeleteTeamRequest = (typeof classroomio.organization)['team'][':memberId']['$delete'];
export type GetTeamSuccess = Extract<InferResponseType<GetTeamRequest>, { success: true }>;
export type OrganizationTeamMembers = GetTeamSuccess['data'];
```
### Type Inference Rules
**Never import types from `@cio/db/queries` into dashboard code.**
**Never define types in `.svelte.ts` files.** Put them in `{domain}/utils/types.ts` and infer from API return types.
Pattern:
1. Define request type: `typeof classroomio.{route}.$method`
2. Infer response type: `InferResponseType<RequestType>`
3. Extract success response: `Extract<ResponseType, { success: true }>`
4. Extract data type: `SuccessType['data']`
For response shapes that need a small normalization (e.g. API returns `JSONValue`, app needs `Record<string, number>`), derive a normalized type in `types.ts` from the success `data` type (e.g. `Omit<Data, 'roleMapping'> & { roleMapping: Record<string, number> }`).
**Do not export custom types from `apps/api/src/rpc-types.ts`.** Only re-export Hono client types (e.g. `InferRequestType`, `InferResponseType`) and the typed client (`Client`, `hcWithType`). All feature-specific types belong in the dashboard's feature `utils/types.ts`, inferred from the API.
### API Class Pattern
API classes handle all logic; components should be thin.
### Translations (UI copy)
- No hardcoded user-facing text in components.
- Strings live in `apps/dashboard/src/lib/utils/translations/en.json`.
- Use `$t('key.path')` in markup and `t('key.path')` in script.
Example:
```svelte
<script lang="ts">
import { t } from '$lib/utils/functions/translations';
</script>
<h1>{$t('course.navItem.lessons.heading_v2')}</h1>
```
Snackbar:
- Use translation keys directly (e.g. `snackbar.success('snackbar.profile.updated')`).
- Only use `t(...)` when combining keys or building dynamic strings.
Outside Svelte components:
- Use `t.get('key.path')` inside plain functions or utilities.
### Utility Functions Pattern
- Extract reusable transformations to `apps/dashboard/src/lib/features/{domain}/utils/{feature}-utils.ts`.
- Keep functions pure and accept all required data as parameters.
### Svelte store binding
You can bind form controls directly to a writable store’s properties. Svelte compiles `bind:value={$store.someProp}` so that reads come from the store and writes go back through the store (via `set`/`update`). Prefer this over duplicating state in the component and syncing with `$effect` (which can cause infinite loops or redundant updates).
```svelte
<script lang="ts">
import { inviteSettingsStore } from './store';
</script>
<InputField bind:value={$inviteSettingsStore.customExpiresAt} />
<Select.Root type="single" bind:value={$inviteSettingsStore.preset}>
```
### Server-Side API Calls
Use `.server.ts` files for server-side code to isolate API keys.
### UI Components
- Add new UI components under `packages/ui/src` following existing folder patterns.
- Document component usage and props in `packages/ui/README.md`.
- Add example usages and variants in Storybook stories under `packages/storybook/src`.
- See `packages/ui/README.md` and `packages/storybook/README.md` for full guidance.
- For dashboard forms, prefer `@cio/ui/custom/*-field` wrappers (for example `InputField`, `TextareaField`, `CheckboxField`) so label/error/spacing behavior stays consistent.
- Use base primitives (`@cio/ui/base/input`, `@cio/ui/base/textarea`, `@cio/ui/base/checkbox`, `@cio/ui/base/label`) only when creating/updating reusable UI components or when no custom field wrapper exists.
- In app-level form UIs, do not introduce native form controls (`<input>`, `<textarea>`, `<label>`) when equivalent `packages/ui` components exist.
- **Theme color classes:** Classes that use colors from `packages/ui/src/index.css` (e.g. `text-muted-foreground`, `text-primary`) must be prefixed with `ui:` in dashboard code so they resolve against the UI theme (e.g. `ui:text-muted-foreground`, `ui:text-primary`). Only color-related utilities need the prefix; layout/sizing classes like `rounded`, `border`, `p-4` stay unprefixed (Tailwind defaults).
## Best Practices Summary
### ✅ DO
- Use `AppError` with error codes and status codes
- Handle transactions in services
- Use `handleError` utility in route catch blocks
- Validate with Zod on both client and server
- Define request types in `{domain}/utils/types.ts` for reusability
- Use `this.execute<RequestType>()` in API classes (never call RPC directly)
- Keep components thin - only render UI and call API methods
- Use `.server.ts` for server-side API calls with API keys
- Use non-null assertion (`!`) for `user` when `authMiddleware` is present
- Put all user-facing copy in translations and reference by key
### ❌ DON'T
- Put business logic in routes or queries
- Include validation in queries (belongs in routes)
- Handle HTTP concerns in services
- Skip client-side validation
- Let components handle validation, navigation, or snackbar
- Include API key logic in `.svelte.ts` files
- **Define types or interfaces in `.svelte.ts` files** — use `{domain}/utils/types.ts` and infer from API types
- Call RPC client directly in server files (use `.server.ts` classes)
- Add unnecessary null checks for `user` when `authMiddleware` is present
- Write plain English strings in components
- **Use inline type imports** (e.g. `import('Package').Type` in type positions) — use top-level `import type` instead
## Checklist for New Routes
- [ ] **Validation**: Schema in `packages/utils/src/validation/{entity}/`
- [ ] **Query**: Pure functions in `packages/db/src/queries/{domain}/`
- [ ] **Service**: Business logic in `apps/api/src/services/`
- [ ] **Route**: Handler in `apps/api/src/routes/{domain}/` (each route returns a single type)
- [ ] **Registration**: Export and register in `app.ts`
- [ ] **Build**: Run `pnpm --filter @cio/api build`
- [ ] **Frontend Types**: Request types in `apps/dashboard/src/lib/features/{domain}/utils/types.ts` (infer from API; do not import from `rpc-types`)
- [ ] **Frontend API**: API class in `apps/dashboard/src/lib/features/{domain}/api/`
## Common Patterns
### Query error logging (`packages/db/src/queries`)
In every `catch` block, log the original error with the function name so logs are traceable:
```typescript
} catch (error) {
console.error('functionName error:', error);
throw new Error(`Failed to ...`);
}
```
### Transactions
```typescript
const result = await db.transaction(async (tx) => {
const org = await createOrganization({ name, siteName });
const member = await createOrganizationMember({ orgId: org.id, userId });
return { org, member };
});
```
### Pagination
```typescript
const paginationSchema = z.object({
page: z.string().transform(Number).pipe(z.number().min(1)).default('1'),
limit: z.string().transform(Number).pipe(z.number().min(1).max(100)).default('20')
});
return c.json({
success: true,
data: items,
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) }
});
```
## Refactoring Components to Features/UI
When moving from `apps/dashboard/src/lib/components/` to `apps/dashboard/src/lib/features/ui/`:
1. **Single-file**: `components/CodeSnippet/index.svelte` → `features/ui/code-snippet.svelte`
2. **Multi-file**: `components/Confetti/` → `features/ui/confetti/confetti.svelte`
3. **Update exports** in `features/ui/index.ts`
4. **Update imports**: `import { Component } from '$features/ui';`
5. **Delete old files** and verify no remaining references
+106 -2698
View File
File diff suppressed because it is too large Load Diff
+37
View File
@@ -0,0 +1,37 @@
# PRD Tracker
Use this file to keep a single prioritized view of all PRDs.
## TODO (Pending PRDs)
| Rank | List # | PRD | Status |
| --- | --- | --- | --- |
| 1 | - | `prd/notification-system` | todo |
| 2 | 14 | `prd/course-templates` | todo |
| 3 | 5 | `prd/course-import` | todo |
| 4 | 8 | `prd/exercise-question-types` | in-progress (A3, A6, A7, C3, C7, C13, C14 done) |
| 5 | 3 | `prd/course-cohorts` | todo |
| 6 | - | `prd/classes` | todo |
| 7 | 13 | `prd/self-host-single-org.md` | done |
| 8 | 7 | `prd/email-template-customization` | todo |
| 9 | - | `prd/selective-exercise-assignment` | todo |
| - | 1 | `prd/ai-course-assistant` | todo |
| - | 2 | `prd/compliance-training-platform` | todo |
| - | 4 | `prd/course-content-search` | todo |
| - | 6 | `prd/course-widget-embed` | todo |
| - | 9 | `prd/onboarding-ai-bootstrap` | todo |
| - | 10 | `prd/pricing-improvements` | todo |
| - | 11 | `prd/public-api` | todo |
| - | 12 | `prd/public-courses` | todo |
| - | 15 | `prd/webhooks` | todo |
## DONE (Completed PRDs)
| PRD | Status |
| --- | --- |
| `prd/enterprise-sso` | done |
| `prd/lesson-edit [DONE]` | done |
| `prd/lessons-list [DONE]` | done |
| `prd/media-manager [DONE]` | done |
| `prd/secure-student-invites [DONE]` | done |
| `prd/tags-feature [DONE]` | done |
+73 -62
View File
@@ -41,7 +41,9 @@ Please reach out to me on [twitter](https://x.com/rotimi_best) if you have any f
## Built With
- [SvelteKit](https://kit.svelte.dev/?ref=classroomio.com)
- [Supabase](https://supabase.com/?ref=classroomio.com)
- [Hono](https://hono.dev/)
- [PostgreSQL](https://www.postgresql.org/)
- [Better Auth](https://www.better-auth.com/)
- [TailwindCSS](https://tailwindcss.com/?ref=classroomio.com)
## Get a Demo
@@ -62,37 +64,38 @@ To get a local copy up and running, please follow these simple steps.
Here is what you need to be able to run ClassroomIO.com
- [Node.js](https://nodejs.org/) (Version: >=22.x)
- [Supabase CLI](https://github.com/supabase/cli)
- [Node.js](https://nodejs.org/) (Version: >=20.19.3)
- [pnpm](https://pnpm.io/installation)
- [Docker](https://docs.docker.com/engine/install/)
- [NPM](https://www.npmjs.com/)
### Project Structure
This repo is a mono repo that consists of 3 projects:
This repo is a monorepo that consists of these primary apps:
1. `website`: The landing page of ClassroomIO hosted [here](https://classroomio.com)
2. `api`: The api service that handles PDF, video processing, Emailing and Notifications.
3. `dashboard`: The web application that runs the learning management system hosted [here](https://app.classroomio.com).
4. `docs`: Official documentation of ClassroomIO hosted [here](https://classroomio.com/docs)
The repository also contains shared packages under `packages/` (for example `packages/db`, `packages/utils`, and `packages/ui`).
## Development
### Local Setup
1. Fork the repo, then clone it using the following command (remember to replace the url with the url from your forked repo)
1. Fork the repo, then clone it:
```bash
git clone https://github.com/classroomio/classroomio.git
```
2. Go to project folder
2. Go to project folder:
```bash
cd classroomio
```
3. Set up Node if your Node version does not meet the project's requirements, as instructed by the documentation., "nvm" (Node Version Manager) allows using Node at the version required by the project:
3. Set up Node (using `nvm`):
```bash
nvm use
@@ -106,81 +109,89 @@ This repo is a mono repo that consists of 3 projects:
You can install nvm from [here](https://github.com/nvm-sh/nvm).
You also need to have pnpm installed, you can find the installation guide [here](https://pnpm.io/installation#using-npm)
4. Set up your `.env` file
- Go to `apps/dashboard` and `apps/api`.
- Duplicate the `.env.example` file and rename it to `.env`
- Populate your .env files with the neccessary variables
To get the environmental variables for supabase continue to step(5)
1. Install all dependencies
4. Install dependencies:
```bash
pnpm i
```
2. Setup Supabase.
5. Set up your `.env` files:
- Install and Start [docker](https://docs.docker.com/engine/install/)
- Install [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started) on your computer
- Go to the project directory in your terminal and start Supabase
- Go to `apps/dashboard` and `apps/api`.
- Duplicate the `.env.example` file and rename it to `.env`
- Populate them with required values (at minimum):
- `apps/api/.env`: `DATABASE_URL`, `REDIS_URL`, `AUTH_BEARER_TOKEN`, `BETTER_AUTH_SECRET`
- `apps/dashboard/.env`: `PUBLIC_SERVER_URL`, `PRIVATE_SERVER_KEY`, `PUBLIC_IS_SELFHOSTED`
- Optional for self-hosted Enterprise-only features (SSO, token-auth, no-tracking): set `LICENSE_KEY` in `apps/api/.env`
```bash
supabase start
```
- You should get a result like this
```bash
supabase local development setup is running.
API URL: http://127.0.0.1:54321
GraphQL URL: http://127.0.0.1:54321/graphql/v1
DB URL: postgresql://postgres:[email protected]:54322/postgres
Studio URL: http://127.0.0.1:54323
Inbucket URL: http://127.0.0.1:54324
JWT secret: super-secret-jwt-token-with-at-least-32-characters-long
anon key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
service_role key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU
```
- Add Supabase environment variables into `app/dashboard` folder, which should be taken from the result of `supabase start`
```env
PUBLIC_SUPABASE_URL=<API URL>
PUBLIC_SUPABASE_ANON_KEY=<anon key>
PRIVATE_SUPABASE_SERVICE_ROLE=<service_role key>
```
- To view the Supabase studio, open the Studio URL from the result of `supabase start`
3. Run all projects (in development mode)
6. Start local infrastructure for API (Postgres + Redis + db-init):
```bash
pnpm dev
docker compose -f docker/docker-compose.yaml up -d postgres redis db-init
```
4. All projects should start running
7. Run the local app services in separate terminals:
```bash
pnpm api:dev
```
```bash
pnpm dashboard:dev
```
8. Default local URLs:
- `website`: [http://localhost:5174](http://localhost:5174)
- `api`: [http://localhost:3002](http://localhost:3002)
- `dashboard`: [http://localhost:5173](http://localhost:5173)
- `docs`: [http://localhost:3000](http://localhost:3000)
5. Running a specific project
9. Optional: run other apps:
- **website**: `pnpm dev --filter=@cio/website`
- **api**: `pnpm dev --filter=@cio/api`
- **dashboard**: `pnpm dev --filter=@cio/dashboard`
- **website**: `pnpm website:dev`
- **docs**: `pnpm dev --filter=@cio/docs`
6. Login into `dashboard`
10. Login into `dashboard`:
- Visit [http://localhost:5173/login](http://localhost:5173/login)
- Enter email: `admin@test.com`
- Enter password: `123456`
To learn more about how to login with a dummy account, [go here.](https://classroomio.com/docs/contributor-guides/demo-accounts)
### Docker Compose (Full Stack)
To run the Dockerized stack (including API + dashboard):
```bash
./run-docker-full-stack.sh
```
Start without rebuilding images:
```bash
./run-docker-full-stack.sh --no-build
```
The script always reads root `.env` via `docker compose --env-file .env`, and it auto-generates secure local values for `PRIVATE_SERVER_KEY` (and `AUTH_BEARER_TOKEN`) when they are missing/insecure. API key middleware validation for dashboard server-side calls uses `PRIVATE_SERVER_KEY`.
For production deployments from published images, use `docker/docker-compose.prod.yaml` with `docker/.env.prod.example` as your template.
Enterprise-only self-hosted features (SSO, token-auth, no-tracking) require a license key from us. Set `LICENSE_KEY` in:
- `apps/api/.env` for local non-Docker development
- root `.env` for Docker Compose self-hosting
- `docker/.env.prod` for published-image deployments
If you do not use Enterprise-only features, you do not need `LICENSE_KEY`.
URL routing for dashboard API calls:
- Browser requests use `PUBLIC_SERVER_URL` (must be your public API domain in hosted environments, not `localhost`).
- Server-side dashboard requests (SSR/load functions) use `PRIVATE_SERVER_URL` when set, and fallback to `PUBLIC_SERVER_URL`.
- In Docker Compose, use `PRIVATE_SERVER_URL=http://api:3081` so dashboard SSR calls stay on the internal Docker network.
- Set `AUTH_COOKIE_DOMAIN` for Better Auth cookie domain control (`your-domain.com` for shared subdomains, or your exact API host).
For Docker details and troubleshooting, see:
- `docker/docs/USAGE.md`
- `docker/docs/commands.md`
- `docker/docs/PUBLISHING_IMAGES.md`
-12
View File
@@ -1,12 +0,0 @@
# Prompt
This prompt is used to give any AI chat bot context about ClassroomIO
```txt
I am building a LMS for teachers and students to collaborate on a course. Students can enroll in a course or be giving access to a course. Teachers can be invited into an org by an admin to create courses and manage students. For auth we support Email/Password and Google.
The tech stack is
- Sveltekit - dashboard (teacher view) and lms (student view)
- Supabase - Auth, DB requests, Storage
- Hono - API for long running processes like video uploads
```
+25 -10
View File
@@ -1,25 +1,40 @@
DATABASE_URL=
## Supabase - DB
PUBLIC_SUPABASE_ANON_KEY=
PUBLIC_SUPABASE_URL=
PRIVATE_SUPABASE_SERVICE_ROLE=
## Object storage - choose one option below
## Cloudflare - Video uploads
# Not required - https://cdn.example.com
CLOUDFLARE_BUCKET_DOMAIN=
# Option A: Cloudflare R2 (legacy)
# CLOUDFLARE_BUCKET_DOMAIN=https://cdn.example.com
# CLOUDFLARE_ACCESS_KEY=
# CLOUDFLARE_SECRET_ACCESS_KEY=
# CLOUDFLARE_ACCOUNT_ID=
# CLOUDFLARE_IMAGE_BUCKET_DOMAIN=https://media.example.com
CLOUDFLARE_ACCESS_KEY=
CLOUDFLARE_SECRET_ACCESS_KEY=
CLOUDFLARE_ACCOUNT_ID=
# Option B: MinIO or other S3-compatible storage (on-premise, data residency)
# When API runs locally: use localhost. When API runs in Docker: use http://minio:9000
# OBJECT_STORAGE_ENDPOINT=http://localhost:9000
# OBJECT_STORAGE_PUBLIC_ENDPOINT=http://localhost:9000
# OBJECT_STORAGE_ACCESS_KEY_ID=minioadmin
# OBJECT_STORAGE_SECRET_ACCESS_KEY=minioadmin
# OBJECT_STORAGE_FORCE_PATH_STYLE=true
# OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL=http://localhost:9000/media
# Email
SMTP_HOST=
SMTP_USER=
SMTP_PASSWORD=
SMTP_PORT=
SMTP_SENDER=
# Enterprise features (optional for self-hosted deployments)
# Request a key from ClassroomIO. Leave empty if you do not use Enterprise-only features.
LICENSE_KEY=
# Sentry DNS
SENTRY_DNS=
OPENAPI_URL=
PRIVATE_SERVER_KEY=
# Public API URL (used for absolute URLs in emails, redirects, etc.)
PUBLIC_SERVER_URL=
-4
View File
@@ -1,8 +1,6 @@
FROM node:slim AS app
# Add build arguments
ARG PUBLIC_SUPABASE_ANON_KEY
ARG PUBLIC_SUPABASE_URL
ARG CLOUDFLARE_BUCKET_DOMAIN
ARG CLOUDFLARE_ACCESS_KEY
ARG CLOUDFLARE_SECRET_ACCESS_KEY
@@ -57,8 +55,6 @@ COPY . /app
# Set environment variables from build args
ENV NODE_ENV=production \
PUBLIC_SUPABASE_ANON_KEY=$PUBLIC_SUPABASE_ANON_KEY \
PUBLIC_SUPABASE_URL=$PUBLIC_SUPABASE_URL \
CLOUDFLARE_BUCKET_DOMAIN=$CLOUDFLARE_BUCKET_DOMAIN \
CLOUDFLARE_ACCESS_KEY=$CLOUDFLARE_ACCESS_KEY \
CLOUDFLARE_SECRET_ACCESS_KEY=$CLOUDFLARE_SECRET_ACCESS_KEY \
+7 -5
View File
@@ -8,7 +8,8 @@
"dist"
],
"scripts": {
"build": "rm -rf dist tsconfig.tsbuildinfo && tsc --build && tsc-alias",
"build": "tsc && tsc-alias",
"build:clean": "rm -rf dist tsconfig.tsbuildinfo && pnpm run build",
"dev": "pnpm --filter @cio/api --parallel \"/^dev:.*/\"",
"dev:server": "tsx watch src/index.ts",
"dev:tsc": "tsc -p tsconfig.json --watch",
@@ -41,18 +42,19 @@
"@aws-sdk/s3-request-presigner": "^3.675.0",
"@cio/db": "workspace:*",
"@cio/email": "workspace:*",
"@cio/question-types": "workspace:*",
"@cio/utils": "workspace:*",
"@hono/node-server": "^1.8.2",
"@hono/node-server": "^1.19.7",
"@hono/standard-validator": "^0.1.5",
"@hono/zod-validator": "^0.7.2",
"@hono/zod-validator": "^0.7.6",
"@scalar/hono-api-reference": "^0.9.18",
"@sentry/profiling-node": "^7.110.1",
"axios": "^1.4.0",
"dotenv": "^16.3.1",
"hono": "^4.9.7",
"hono": "^4.11.3",
"hono-openapi": "^1.0.8",
"hono-rate-limiter": "^0.4.2",
"ioredis": "^5.7.0",
"redis": "^4.7.0",
"katex": "^0.16.10",
"marked": "^7.0.3",
"nanoid": "^5.1.5",
-2
View File
@@ -61,8 +61,6 @@ The GitHub Action runs on:
- `CLOUDFLARE_ACCESS_KEY`
- `CLOUDFLARE_SECRET_ACCESS_KEY`
- `CLOUDFLARE_ACCOUNT_ID`
- `PUBLIC_SUPABASE_URL`
- `PUBLIC_SUPABASE_ANON_KEY`
## Features
+27 -13
View File
@@ -1,24 +1,31 @@
import 'dotenv/config';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { prettyJSON } from 'hono/pretty-json';
import { secureHeaders } from 'hono/secure-headers';
import { auth } from '@cio/db/auth';
import { Hono } from '@api/utils/hono';
import rateLimiter from '@api/middlewares/rate-limiter';
import { API_SERVER_URL, TRUSTED_ORIGINS } from '@api/constants';
// --- routes
import { mailRouter } from '@api/routes/mail';
import { courseRouter } from '@api/routes/course';
import { Hono } from '@api/utils/hono';
import { accountRouter } from '@api/routes/account';
import { auth } from '@cio/db/auth';
import { communityRouter } from '@api/routes/community';
import { cors } from 'hono/cors';
import { courseRouter } from '@api/routes/course';
import { dashAnalyticsRouter } from '@api/routes/dash';
import { domainRouter } from '@api/routes/domain/domain';
import { inviteRouter } from '@api/routes/invite';
import { logger } from 'hono/logger';
// ROUTES
import { mailRouter } from '@api/routes/mail';
import { mediaRouter } from '@api/routes/media';
import { onboardingRouter } from '@api/routes/onboarding';
import { organizationRouter } from '@api/routes/organization';
import { exerciseRouter } from '@api/routes/exercise';
import { communityRouter } from '@api/routes/community';
import { licenseRouter } from '@api/routes/license';
import { organizationSsoRouter } from '@api/routes/organization/sso';
import { organizationTokenAuthRouter } from '@api/routes/organization/token-auth';
import { ssoDiscoveryRouter } from '@api/routes/sso/discovery';
import { prettyJSON } from 'hono/pretty-json';
import rateLimiter from '@api/middlewares/rate-limiter';
import { secureHeaders } from 'hono/secure-headers';
import { signupGuard } from '@api/middlewares/signup-guard';
import { unsplashRouter } from '@api/routes/unsplash/unsplash';
// Create Hono app with chaining for RPC support
export const app = new Hono()
@@ -60,6 +67,7 @@ export const app = new Hono()
message: `"Welcome to Classroomio.com API - docs are at ${API_SERVER_URL}/docs"`
})
)
.use('/api/auth/sign-up/*', signupGuard)
.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw))
.get('/session', async (c) => {
const session = c.get('session');
@@ -75,12 +83,18 @@ export const app = new Hono()
.route('/onboarding', onboardingRouter)
.route('/account', accountRouter)
.route('/course', courseRouter)
.route('/domain', domainRouter)
.route('/mail', mailRouter)
.route('/media', mediaRouter)
.route('/license', licenseRouter)
.route('/organization', organizationRouter)
.route('/organization/sso', organizationSsoRouter)
.route('/organization/token-auth', organizationTokenAuthRouter)
.route('/sso', ssoDiscoveryRouter)
.route('/dash', dashAnalyticsRouter)
.route('/exercise', exerciseRouter)
.route('/community', communityRouter)
.route('/invite', inviteRouter)
.route('/unsplash', unsplashRouter)
// Error handling
.onError((err, c) => {
+24 -5
View File
@@ -1,20 +1,31 @@
import * as z from 'zod';
const envSchema = z.object({
// Legacy Cloudflare R2 config (used when OBJECT_STORAGE_* vars are absent)
CLOUDFLARE_ACCESS_KEY: z.string().optional(),
CLOUDFLARE_ACCOUNT_ID: z.string().optional(),
CLOUDFLARE_BUCKET_DOMAIN: z.string().optional(),
CLOUDFLARE_RENDERING_API_KEY: z.string().optional(),
CLOUDFLARE_SECRET_ACCESS_KEY: z.string().optional(),
CLOUDFLARE_IMAGE_BUCKET_DOMAIN: z.string().optional(),
// S3-compatible storage (MinIO, AWS S3, or other S3-compatible backends)
OBJECT_STORAGE_ENDPOINT: z.string().optional(),
OBJECT_STORAGE_REGION: z.string().optional(),
OBJECT_STORAGE_ACCESS_KEY_ID: z.string().optional(),
OBJECT_STORAGE_SECRET_ACCESS_KEY: z.string().optional(),
OBJECT_STORAGE_FORCE_PATH_STYLE: z.string().optional(),
OBJECT_STORAGE_BUCKET_VIDEOS: z.string().optional(),
OBJECT_STORAGE_BUCKET_DOCUMENTS: z.string().optional(),
OBJECT_STORAGE_BUCKET_MEDIA: z.string().optional(),
/** Public URL base for media bucket (images, thumbnails). Required for image uploads. */
OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL: z.string().optional(),
/** Optional: endpoint for presigned URLs when different from internal (e.g. browser-reachable) */
OBJECT_STORAGE_PUBLIC_ENDPOINT: z.string().optional(),
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
OPENAPI_URL: z.string().optional(),
PORT: z.string().optional(),
PRIVATE_SUPABASE_SERVICE_ROLE: z.string(),
PUBLIC_SUPABASE_ANON_KEY: z.string(),
PUBLIC_SUPABASE_URL: z.string(),
REDIS_URL: z.string().optional(),
SERVER_URL: z.string().optional(),
PUBLIC_SERVER_URL: z.string().optional(),
SMTP_HOST: z.string().optional(),
SMTP_PASSWORD: z.string().optional(),
SMTP_PORT: z.string().optional(),
@@ -22,7 +33,15 @@ const envSchema = z.object({
SMTP_USER: z.string().optional(),
ZOHO_TOKEN: z.string().optional(),
TRUSTED_ORIGINS: z.string().optional(),
SERVER_KEY: z.string().optional()
PRIVATE_SERVER_KEY: z.string().optional(),
PROJECT_ID_VERCEL: z.string().optional(),
TEAM_ID_VERCEL: z.string().optional(),
AUTH_BEARER_TOKEN: z.string().optional(),
UNSPLASH_API_KEY: z.string().optional(),
/** When 'true', instance runs in self-hosted mode: single org, auto-enroll as student, no org switching */
PUBLIC_IS_SELFHOSTED: z.string().optional(),
/** License key for enterprise features (SSO, token-auth, no-tracking, etc.) */
LICENSE_KEY: z.string().optional()
});
export const env = envSchema.parse(process.env);
+136
View File
@@ -0,0 +1,136 @@
/**
* Object storage configuration for S3-compatible backends (Cloudflare R2, MinIO, AWS S3).
* Supports both generic OBJECT_STORAGE_* vars and backward-compatible CLOUDFLARE_* fallback.
*/
import { S3Client } from '@aws-sdk/client-s3';
import { env } from '@api/config/env';
const BUCKET_DEFAULTS = {
VIDEOS: 'videos',
DOCUMENTS: 'documents',
MEDIA: 'media'
} as const;
/** Whether we're using the generic S3-compatible config (MinIO, etc.) vs Cloudflare R2 fallback */
export function useS3CompatibleConfig(): boolean {
return Boolean(
env.OBJECT_STORAGE_ENDPOINT && env.OBJECT_STORAGE_ACCESS_KEY_ID && env.OBJECT_STORAGE_SECRET_ACCESS_KEY
);
}
function isCloudflareConfigured(): boolean {
return Boolean(env.CLOUDFLARE_ACCOUNT_ID && env.CLOUDFLARE_ACCESS_KEY && env.CLOUDFLARE_SECRET_ACCESS_KEY);
}
export interface StorageConfig {
endpoint: string;
region: string;
accessKeyId: string;
secretAccessKey: string;
forcePathStyle: boolean;
bucketVideos: string;
bucketDocuments: string;
bucketMedia: string;
mediaPublicBaseUrl: string | null;
presignUploadExpiresSeconds: number;
presignDownloadExpiresSeconds: number;
}
function resolveStorageConfig(): StorageConfig {
if (useS3CompatibleConfig()) {
const forcePathStyle =
env.OBJECT_STORAGE_FORCE_PATH_STYLE === 'true' || env.OBJECT_STORAGE_FORCE_PATH_STYLE === '1';
return {
endpoint: env.OBJECT_STORAGE_ENDPOINT!,
region: env.OBJECT_STORAGE_REGION || 'us-east-1',
accessKeyId: env.OBJECT_STORAGE_ACCESS_KEY_ID!,
secretAccessKey: env.OBJECT_STORAGE_SECRET_ACCESS_KEY!,
forcePathStyle,
bucketVideos: env.OBJECT_STORAGE_BUCKET_VIDEOS || BUCKET_DEFAULTS.VIDEOS,
bucketDocuments: env.OBJECT_STORAGE_BUCKET_DOCUMENTS || BUCKET_DEFAULTS.DOCUMENTS,
bucketMedia: env.OBJECT_STORAGE_BUCKET_MEDIA || BUCKET_DEFAULTS.MEDIA,
mediaPublicBaseUrl: env.OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL || null,
presignUploadExpiresSeconds: 60 * 60, // 1 hour
presignDownloadExpiresSeconds: 60 * 60 // 1 hour
};
}
if (isCloudflareConfigured()) {
return {
endpoint: `https://${env.CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com`,
region: 'auto',
accessKeyId: env.CLOUDFLARE_ACCESS_KEY!,
secretAccessKey: env.CLOUDFLARE_SECRET_ACCESS_KEY!,
forcePathStyle: false,
bucketVideos: BUCKET_DEFAULTS.VIDEOS,
bucketDocuments: BUCKET_DEFAULTS.DOCUMENTS,
bucketMedia: BUCKET_DEFAULTS.MEDIA,
mediaPublicBaseUrl: env.CLOUDFLARE_IMAGE_BUCKET_DOMAIN || null,
presignUploadExpiresSeconds: 60 * 60,
presignDownloadExpiresSeconds: 60 * 60
};
}
throw new Error(
'Object storage not configured. Set either OBJECT_STORAGE_ENDPOINT, OBJECT_STORAGE_ACCESS_KEY_ID, OBJECT_STORAGE_SECRET_ACCESS_KEY (for MinIO/S3) or CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_ACCESS_KEY, CLOUDFLARE_SECRET_ACCESS_KEY (for Cloudflare R2).'
);
}
let cachedConfig: StorageConfig | null = null;
export function getStorageConfig(): StorageConfig {
if (!cachedConfig) {
cachedConfig = resolveStorageConfig();
if (useS3CompatibleConfig()) {
console.log('[storage] Using S3-compatible object storage');
} else {
console.log('[storage] Using Cloudflare R2 (fallback)');
}
}
return cachedConfig;
}
/** S3 client for API operations (upload, get, delete). Uses internal endpoint. */
let s3ClientInstance: S3Client | null = null;
export function getS3Client(): S3Client {
if (!s3ClientInstance) {
const config = getStorageConfig();
s3ClientInstance = new S3Client({
region: config.region,
endpoint: config.endpoint,
credentials: {
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey
},
forcePathStyle: config.forcePathStyle
});
}
return s3ClientInstance;
}
/**
* S3 client for generating presigned URLs. Uses public endpoint when configured
* (e.g. when internal endpoint like minio:9000 is not reachable by browser).
*/
let presignClientInstance: S3Client | null = null;
export function getPresignS3Client(): S3Client {
if (!presignClientInstance) {
const config = getStorageConfig();
const endpoint = env.OBJECT_STORAGE_PUBLIC_ENDPOINT || config.endpoint;
presignClientInstance = new S3Client({
region: config.region,
endpoint,
credentials: {
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey
},
forcePathStyle: config.forcePathStyle
});
}
return presignClientInstance;
}
export { BUCKET_DEFAULTS };
+1 -1
View File
@@ -3,7 +3,7 @@ import { env } from '@api/config/env';
export * from './rate-limiter';
export const API_PORT = env.PORT ? parseInt(env.PORT) : 3002;
export const API_SERVER_URL = env.SERVER_URL || `http://localhost:${API_PORT}`;
export const API_SERVER_URL = env.PUBLIC_SERVER_URL || `http://localhost:${API_PORT}`;
export const TRUSTED_ORIGINS = env.TRUSTED_ORIGINS
? env.TRUSTED_ORIGINS.split(',')
: ['http://localhost:5173', 'http://*.classroomio.*'];
+10 -2
View File
@@ -5,11 +5,16 @@ import { app } from '@api/app';
import { configureOpenAPI } from '@api/utils/openapi';
import { serve } from '@hono/node-server';
import { showRoutes } from 'hono/dev';
import { connectRedis } from '@api/utils/redis/redis';
// Start server
function startServer() {
async function startServer() {
console.log('Starting server on port:', API_PORT);
// Connect to Redis before starting the server
await connectRedis();
console.log('Redis connected successfully');
serve({ fetch: app.fetch, port: API_PORT });
showRoutes(app, { colorize: true });
@@ -17,4 +22,7 @@ function startServer() {
configureOpenAPI(app);
startServer();
startServer().catch((error) => {
console.error('Failed to start server:', error);
process.exit(1);
});
+3 -3
View File
@@ -5,7 +5,7 @@ import { env } from '@api/config/env';
/**
* Middleware to authenticate requests using API key
* Checks for Authorization: Bearer <api-key> header
* Used for server-to-server communication (webhooks, etc.)
* Used for server-to-server communication (webhooks, dashboard SSR, etc.)
*/
export const apiKeyMiddleware = async (c: Context, next: Next) => {
try {
@@ -21,10 +21,10 @@ export const apiKeyMiddleware = async (c: Context, next: Next) => {
}
const apiKey = authHeader.replace('Bearer ', '').trim();
const expectedApiKey = env.SERVER_KEY;
const expectedApiKey = env.PRIVATE_SERVER_KEY;
if (!expectedApiKey) {
console.error('SERVER_KEY not configured in environment');
console.error('PRIVATE_SERVER_KEY not configured in environment');
return c.json(
{
success: false,
+12 -15
View File
@@ -1,7 +1,7 @@
import { Context, Next } from 'hono';
import { ErrorCodes } from '@api/utils/errors';
import { isUserCourseMember } from '@cio/db/queries/group';
import { isUserCourseMemberOrOrgAdmin } from '@cio/db/queries/group';
/**
* Middleware to check if the authenticated user is a member of a course's group
@@ -22,10 +22,7 @@ export const courseMemberMiddleware = async (c: Context, next: Next) => {
);
}
// Try to get courseId from params or query
// Note: Body parsing should happen after validation middleware
const courseId = c.req.param('courseId') || c.req.query('courseId');
if (!courseId) {
return c.json(
{
@@ -37,19 +34,19 @@ export const courseMemberMiddleware = async (c: Context, next: Next) => {
);
}
const isMember = await isUserCourseMember(courseId, user.id);
if (!isMember) {
return c.json(
{
success: false,
error: 'You must be a member of this course to perform this action',
code: ErrorCodes.ORG_TEAM_NOT_AUTHORIZED
},
403
);
const isAllowed = await isUserCourseMemberOrOrgAdmin(courseId, user.id);
if (isAllowed) {
return next();
}
await next();
return c.json(
{
success: false,
error: 'You must be a member of this course to perform this action',
code: ErrorCodes.ORG_TEAM_NOT_AUTHORIZED
},
403
);
} catch (error) {
console.error('Error in courseMemberMiddleware:', error);
return c.json(
@@ -0,0 +1,63 @@
import { Context, Next } from 'hono';
import { ErrorCodes } from '@api/utils/errors';
import { isCourseTeamMemberOrOrgAdmin } from '@cio/db/queries/group';
/**
* Middleware to check if the authenticated user is a team member (ADMIN or TUTOR) of a course
* Also allows organization admins
* Requires authMiddleware to be applied first
* Extracts courseId from request params
*/
export const courseTeamMemberMiddleware = async (c: Context, next: Next) => {
try {
const user = c.get('user');
if (!user) {
return c.json(
{
success: false,
error: 'Unauthorized',
code: 'UNAUTHORIZED'
},
401
);
}
const courseId = c.req.param('courseId');
if (!courseId) {
return c.json(
{
success: false,
error: 'Course ID is required',
code: 'COURSE_ID_REQUIRED'
},
400
);
}
// Check if user is a team member (ADMIN or TUTOR) or org admin
const isAllowed = await isCourseTeamMemberOrOrgAdmin(courseId, user.id);
if (isAllowed) {
return next();
}
return c.json(
{
success: false,
error: 'Unauthorized',
code: ErrorCodes.UNAUTHORIZED
},
403
);
} catch (error) {
console.error('Error in courseTeamMemberMiddleware:', error);
return c.json(
{
success: false,
error: 'Unauthorized',
code: ErrorCodes.UNAUTHORIZED
},
500
);
}
};
+34
View File
@@ -0,0 +1,34 @@
import type { Context, Next } from 'hono';
import type { LicenseFeatureId } from '@cio/utils/license';
import { env } from '@api/config/env';
import { isFeatureLicensed } from '@api/services/license';
/**
* Middleware that returns 403 if the given feature is not licensed.
* Use for routes that require a license key (SSO, token-auth, etc.).
* License check is skipped when not self-hosted (cloud/SaaS has no license restrictions).
*/
export function requireLicense(feature: LicenseFeatureId | string) {
return async (c: Context, next: Next) => {
// No license restrictions for cloud/SaaS (non-self-hosted instances)
const isSelfHosted = env.PUBLIC_IS_SELFHOSTED === 'true';
if (!isSelfHosted) {
await next();
return;
}
const licensed = await isFeatureLicensed(feature);
if (!licensed) {
return c.json(
{
success: false,
error: 'FEATURE_REQUIRES_LICENSE',
message: `This feature requires a valid license. Please add a license key.`
},
403
);
}
await next();
};
}
@@ -0,0 +1,85 @@
import { Context, Next } from 'hono';
import { getGroupMemberIdByCourseAndProfile, isCourseTeamMemberOrOrgAdmin } from '@cio/db/queries/group';
import { ErrorCodes } from '@api/utils/errors';
import { getNewsfeedCommentAuthorAndCourse } from '@cio/db/queries/newsfeed';
/**
* Middleware to check if user is comment author OR tutor/admin in course
* Requires authMiddleware to be applied first
* Expects commentId in route params as 'commentId'
*/
export const newsfeedCommentAuthorOrTeamMiddleware = async (c: Context, next: Next) => {
try {
const user = c.get('user');
if (!user) {
return c.json(
{
success: false,
error: 'Unauthorized',
code: 'UNAUTHORIZED'
},
401
);
}
const commentId = c.req.param('commentId');
if (!commentId) {
return c.json(
{
success: false,
error: 'Comment ID is required',
code: 'COMMENT_ID_REQUIRED'
},
400
);
}
const commentInfo = await getNewsfeedCommentAuthorAndCourse(Number(commentId));
if (!commentInfo || !commentInfo.courseId) {
return c.json(
{
success: false,
error: 'Comment not found',
code: ErrorCodes.COMMENT_NOT_FOUND
},
404
);
}
// Check if user is the author of the comment
const userGroupMemberId = await getGroupMemberIdByCourseAndProfile(commentInfo.courseId, user.id);
const isAuthor = commentInfo.authorId === userGroupMemberId;
if (isAuthor) {
await next();
return;
}
// Check if user is a team member (ADMIN or TUTOR) or org admin
const isAllowed = await isCourseTeamMemberOrOrgAdmin(commentInfo.courseId, user.id);
if (isAllowed) {
await next();
return;
}
return c.json(
{
success: false,
error: 'Only the author or course team members can perform this action',
code: ErrorCodes.ORG_TEAM_NOT_AUTHORIZED
},
403
);
} catch (error) {
console.error('Error in newsfeedCommentAuthorOrTeamMiddleware:', error);
return c.json(
{
success: false,
error: 'Failed to verify comment authorization',
code: 'COMMENT_AUTH_CHECK_FAILED'
},
500
);
}
};
+8 -4
View File
@@ -1,12 +1,12 @@
import { Context, Next } from 'hono';
import { ErrorCodes } from '@api/utils/errors';
import { isUserOrgMember } from '@cio/db/queries/organization';
import { getUserOrgRole } from '@cio/db/queries/organization';
/**
* Middleware to check if the authenticated user is a member of the organization
* Requires authMiddleware to be applied first
* Expects orgId in the 'cio-org-id' header
* Stores orgRole and orgId in context for use in route handlers
*/
export const orgMemberMiddleware = async (c: Context, next: Next) => {
try {
@@ -35,8 +35,8 @@ export const orgMemberMiddleware = async (c: Context, next: Next) => {
);
}
const isMember = await isUserOrgMember(orgId, user.id);
if (!isMember) {
const roleId = await getUserOrgRole(orgId, user.id);
if (roleId === null) {
return c.json(
{
success: false,
@@ -47,6 +47,10 @@ export const orgMemberMiddleware = async (c: Context, next: Next) => {
);
}
// Store orgRole and orgId in context for use in route handlers
c.set('userRole', roleId);
c.set('orgId', orgId);
await next();
} catch (error) {
console.error('Error in orgMemberMiddleware:', error);
+4 -2
View File
@@ -6,9 +6,10 @@ import {
} from '@api/constants/rate-limiter';
import type { MiddlewareHandler } from 'hono';
import { rateLimiter } from '@api/utils/redis/limiter';
import { RedisRateLimiter } from '@api/utils/redis/limiter';
import { userKeyGenerator } from '../utils/redis/key-generators';
import { env } from '@api/config/env';
import { redis } from '@api/utils/redis/redis';
export interface RateLimiterOptions {
windowMs?: number;
@@ -28,6 +29,7 @@ const defaultOptions: Required<RateLimiterOptions> = {
export const createRateLimiter = (options: RateLimiterOptions = {}): MiddlewareHandler => {
const opts = { ...defaultOptions, ...options };
const limiter = new RedisRateLimiter(redis, opts.windowMs, opts.maxRequests);
return async (c, next) => {
// Skip rate limiting if not in production
@@ -40,7 +42,7 @@ export const createRateLimiter = (options: RateLimiterOptions = {}): MiddlewareH
const key = opts.keyGenerator(c);
// Check rate limit
const result = await rateLimiter.isAllowed(key);
const result = await limiter.isAllowed(key);
// Set rate limit headers
if (opts.standardHeaders) {
+88
View File
@@ -0,0 +1,88 @@
import {
getFirstOrganization,
getOrganizationById,
hasActiveOrganizationInviteForEmail
} from '@cio/db/queries/organization';
import type { MiddlewareHandler } from 'hono';
import { env } from '@api/config/env';
type OrgSettings = {
signup?: {
inviteOnly?: boolean;
};
};
/**
* Enforces organization-level signup restrictions server-side.
*
* When the `cio-org-id` header is present the middleware looks up the org and
* rejects the request when:
* - `disableSignup` is true, or
* - `settings.signup.inviteOnly` is true and the email has no active invite.
*
* When the `cio-org-id` header is absent:
* - Non-self-hosted: pass through (header optional).
* - Self-hosted: require the header unless no orgs exist yet (bootstrap). Otherwise
* auto-enrollment in getAccountData would add unauthorized users as students,
* bypassing invite-only checks.
*/
export const signupGuard: MiddlewareHandler = async (c, next) => {
const orgId = c.req.header('cio-org-id');
if (!orgId) {
if (env.PUBLIC_IS_SELFHOSTED === 'true') {
const firstOrg = await getFirstOrganization();
if (firstOrg) {
return c.json(
{
code: 'ORG_CONTEXT_REQUIRED',
message: 'Organization context is required for signup on self-hosted instances'
},
400
);
}
}
return next();
}
let org: Awaited<ReturnType<typeof getOrganizationById>>;
try {
org = await getOrganizationById(orgId);
} catch {
return next();
}
if (!org) {
return next();
}
if (org.disableSignup) {
return c.json({ code: 'SIGNUP_DISABLED', message: 'Signup is disabled for this organization' }, 403);
}
const settings = org.settings as OrgSettings | null;
const inviteOnly = settings?.signup?.inviteOnly ?? false;
if (!inviteOnly) {
return next();
}
let body: { email?: string } | undefined;
try {
body = await c.req.raw.clone().json();
} catch {
return c.json({ code: 'INVALID_REQUEST', message: 'Could not parse request body' }, 400);
}
const email = body?.email?.toLowerCase().trim();
if (!email) {
return c.json({ code: 'INVALID_REQUEST', message: 'Email is required' }, 400);
}
const hasInvite = await hasActiveOrganizationInviteForEmail(orgId, email);
if (!hasInvite) {
return c.json({ code: 'INVITE_REQUIRED', message: 'This organization requires an invitation to sign up' }, 403);
}
return next();
};
+32 -3
View File
@@ -3,12 +3,13 @@ import { getAccountData, updateUser } from '@api/services/account';
import { Hono } from '@api/utils/hono';
import { ZUpdateProfile } from '@cio/utils/validation/account';
import { authMiddleware } from '@api/middlewares/auth';
import { getProfileById } from '@cio/db/queries/auth';
import { handleError } from '@api/utils/errors';
import { zValidator } from '@hono/zod-validator';
export const accountRouter = new Hono()
.get('/', authMiddleware, async (c) => {
const user = c.get('user');
const user = c.get('user')!;
try {
console.time('accountRouter');
@@ -20,7 +21,8 @@ export const accountRouter = new Hono()
success: true,
user,
profile: accountData.profile,
organizations: accountData.organizations
organizations: accountData.organizations,
licenseFeatures: accountData.licenseFeatures
},
200
);
@@ -29,7 +31,7 @@ export const accountRouter = new Hono()
}
})
.put('/profile', authMiddleware, zValidator('json', ZUpdateProfile), async (c) => {
const user = c.get('user');
const user = c.get('user')!;
try {
const validatedData = c.req.valid('json');
@@ -46,4 +48,31 @@ export const accountRouter = new Hono()
} catch (error) {
return handleError(c, error, 'Failed to update profile');
}
})
.get('/profile', authMiddleware, async (c) => {
const user = c.get('user')!;
try {
const profile = await getProfileById(user.id);
if (!profile) {
return c.json(
{
success: false,
error: 'Profile not found'
},
404
);
}
return c.json(
{
success: true,
profile
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch profile');
}
});
+14 -1
View File
@@ -35,8 +35,21 @@ export const communityRouter = new Hono()
.get('/', authMiddleware, orgMemberMiddleware, zValidator('query', ZCommunityQuestions), async (c) => {
try {
const { orgId } = c.req.valid('query');
const user = c.get('user')!;
const userRole = c.get('userRole');
const result = await fetchCommunityQuestions(orgId);
if (userRole === null) {
return c.json(
{
success: false,
error: 'Organization context not available',
code: 'ORG_CONTEXT_MISSING'
},
500
);
}
const result = await fetchCommunityQuestions(orgId, user.id, userRole);
return c.json({ success: true, data: result }, 200);
} catch (error) {
@@ -2,7 +2,7 @@ import { Context, Next } from 'hono';
import { ErrorCodes } from '@api/utils/errors';
import { getCommentAuthorAndCourse } from '@cio/db/queries/community';
import { isUserCourseTeamMember } from '@cio/db/queries/group';
import { isCourseTeamMemberOrOrgAdmin } from '@cio/db/queries/group';
/**
* Middleware to check if user is comment author OR tutor/admin in course
@@ -53,7 +53,7 @@ export const commentAuthorOrTeamMiddleware = async (c: Context, next: Next) => {
return;
}
const isTeamMember = await isUserCourseTeamMember(comment.courseId, user.id);
const isTeamMember = await isCourseTeamMemberOrOrgAdmin(comment.courseId, user.id);
if (!isTeamMember) {
return c.json(
@@ -2,7 +2,7 @@ import { Context, Next } from 'hono';
import { ErrorCodes } from '@api/utils/errors';
import { getQuestionAuthorAndCourse } from '@cio/db/queries/community';
import { isUserCourseTeamMember } from '@cio/db/queries/group';
import { isCourseTeamMemberOrOrgAdmin } from '@cio/db/queries/group';
/**
* Middleware to check if user is question author OR tutor/admin in course
@@ -48,7 +48,7 @@ export const questionAuthorOrTeamMiddleware = async (c: Context, next: Next) =>
}
const isAuthor = question.authorId === user.id;
const isTeamMember = await isUserCourseTeamMember(question.courseId, user.id);
const isTeamMember = await isCourseTeamMemberOrOrgAdmin(question.courseId, user.id);
if (!isAuthor && !isTeamMember) {
return c.json(
+24
View File
@@ -0,0 +1,24 @@
import { Hono } from '@api/utils/hono';
import { ZAttendanceUpsert } from '@cio/utils/validation/attendance';
import { authMiddleware } from '@api/middlewares/auth';
import { courseMemberMiddleware } from '@api/middlewares/course-member';
import { handleError } from '@api/utils/errors';
import { upsertAttendanceService } from '@api/services/attendance';
import { zValidator } from '@hono/zod-validator';
export const attendanceRouter = new Hono().post(
'/',
authMiddleware,
courseMemberMiddleware,
zValidator('json', ZAttendanceUpsert),
async (c) => {
try {
const data = c.req.valid('json');
const attendance = await upsertAttendanceService(data);
return c.json({ success: true, data: attendance }, 201);
} catch (error) {
return handleError(c, error, 'Failed to upsert attendance');
}
}
);
+34
View File
@@ -0,0 +1,34 @@
import { ZCourseContentDelete, ZCourseContentUpdate } from '@cio/utils/validation/course';
import { deleteCourseContent, updateCourseContent } from '@api/services/course/content';
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { courseTeamMemberMiddleware } from '@api/middlewares/course-team-member';
import { handleError } from '@api/utils/errors';
import { zValidator } from '@hono/zod-validator';
export const contentRouter = new Hono()
.put('/', authMiddleware, courseTeamMemberMiddleware, zValidator('json', ZCourseContentUpdate), async (c) => {
try {
const courseId = c.req.param('courseId')!;
const { items } = c.req.valid('json');
await updateCourseContent(courseId, items);
return c.json({ success: true }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update course content');
}
})
.delete('/', authMiddleware, courseTeamMemberMiddleware, zValidator('json', ZCourseContentDelete), async (c) => {
try {
const courseId = c.req.param('courseId')!;
const payload = c.req.valid('json');
await deleteCourseContent(courseId, payload);
return c.json({ success: true }, 200);
} catch (error) {
return handleError(c, error, 'Failed to delete course content');
}
});
+368 -2
View File
@@ -2,24 +2,380 @@ import {
ZCertificateDownload,
ZCourseClone,
ZCourseCloneParam,
ZCourseCreate,
ZCourseDeleteParam,
ZCourseDownloadContent,
ZCourseDownloadParam
ZCourseDownloadParam,
ZCourseEnrollBody,
ZCourseEnrollParam,
ZCourseGetBySlugParam,
ZCourseGetParam,
ZCourseGetQuery,
ZCourseProgressParam,
ZCourseProgressQuery,
ZCourseUpdate,
ZCourseUpdateParam
} from '@cio/utils/validation/course';
import { ZCourseTagAssignment, ZCourseTagParam } from '@cio/utils/validation/tag';
import {
createCourse,
deleteCourse,
getCourse,
getCourseAnalytics,
getCourseProgress,
updateCourse
} from '@api/services/course/course';
import { enrollInCourse } from '@api/services/course/invite';
import { getCourseTags, replaceCourseTags } from '@api/services/tag';
import { createRateLimiter } from '@api/middlewares/rate-limiter';
import { extractClientIp } from '@api/utils/redis/key-generators';
import { Hono } from '@api/utils/hono';
import { attendanceRouter } from '@api/routes/course/attendance';
import { authMiddleware } from '@api/middlewares/auth';
import { cloneCourse } from '@api/services/course/clone';
import { courseMemberMiddleware } from '@api/middlewares/course-member';
import { courseTeamMemberMiddleware } from '@api/middlewares/course-team-member';
import { contentRouter } from '@api/routes/course/content';
import { exerciseRouter } from '@api/routes/course/exercise';
import { generateCertificate } from '@api/utils/certificate';
import { generateCoursePdf } from '@api/utils/course';
import { handleError } from '@api/utils/errors';
import { katexRouter } from '@api/routes/course/katex';
import { lessonRouter } from '@api/routes/course/lesson';
import { markRouter } from '@api/routes/course/mark';
import { sectionRouter } from '@api/routes/course/section';
import { membersRouter } from '@api/routes/course/people';
import { invitesRouter } from '@api/routes/course/invite';
import { newsfeedRouter } from '@api/routes/course/newsfeed';
import { orgAdminMiddleware } from '@api/middlewares/org-admin';
import { orgMemberMiddleware } from '@api/middlewares/org-member';
import { paymentRequestRouter } from '@api/routes/course/payment-request';
import { presignRouter } from '@api/routes/course/presign';
import { submissionRouter } from '@api/routes/course/submission';
import { zValidator } from '@hono/zod-validator';
const enrollRateLimit = createRateLimiter({
windowMs: 60 * 60 * 1000,
maxRequests: 20,
message: 'Too many enrollment attempts. Please try again later.',
keyGenerator: (c) => {
const user = c.get('user');
const actor = user?.id ? `user:${user.id}` : `ip:${extractClientIp(c)}`;
return `enroll:${actor}:${c.req.param('courseId')}`;
}
});
export const courseRouter = new Hono()
/**
* GET /course/slug/:slug
* Gets a course by slug (public route, no authentication required)
* Used for public course landing pages
*/
.get('/slug/:slug', zValidator('param', ZCourseGetBySlugParam), async (c) => {
try {
const { slug } = c.req.valid('param');
const course = await getCourse(undefined, slug);
return c.json(
{
success: true,
data: course
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch course by slug');
}
})
/**
* POST /course
* Creates a new course with group, group member, and default newsfeed
* Requires authentication and organization membership
*/
.post('/', authMiddleware, orgAdminMiddleware, zValidator('json', ZCourseCreate), async (c) => {
try {
const user = c.get('user')!;
const validatedData = c.req.valid('json');
const result = await createCourse(user.id, validatedData);
return c.json(
{
success: true,
data: result
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to create course');
}
})
/**
* POST /course/:courseId/enroll
* Unified enrollment: free courses enroll directly; paid/invited require inviteToken.
*/
.post(
'/:courseId/enroll',
authMiddleware,
enrollRateLimit,
zValidator('param', ZCourseEnrollParam),
zValidator('json', ZCourseEnrollBody),
async (c) => {
try {
const { courseId } = c.req.valid('param');
const body = c.req.valid('json');
const user = c.get('user')!;
const result = await enrollInCourse(
courseId,
{
id: user.id,
email: user.email,
emailVerified: user.emailVerified
},
body,
{
ipAddress: extractClientIp(c),
userAgent: c.req.header('user-agent') || null
}
);
return c.json(
{
success: true,
data: result
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to enroll');
}
}
)
/**
* GET /course/:courseId/tags
* Gets tags assigned to a course (organization admin only)
*/
.get('/:courseId/tags', authMiddleware, orgAdminMiddleware, zValidator('param', ZCourseTagParam), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { courseId } = c.req.valid('param');
const tags = await getCourseTags(orgId, courseId);
return c.json(
{
success: true,
data: tags
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch course tags');
}
})
/**
* PUT /course/:courseId/tags
* Replaces all tags assigned to a course (organization admin only)
*/
.put(
'/:courseId/tags',
authMiddleware,
orgAdminMiddleware,
zValidator('param', ZCourseTagParam),
zValidator('json', ZCourseTagAssignment),
async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { courseId } = c.req.valid('param');
const data = c.req.valid('json');
const tags = await replaceCourseTags(orgId, courseId, data);
return c.json(
{
success: true,
data: tags
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to assign course tags');
}
}
)
/**
* GET /course/:courseId
* Gets a course by ID or slug with all related data (group, members, lessons, sections, attendance)
* Query param: slug (optional) - if provided, courseId is ignored and course is fetched by slug
* Requires authentication and course membership
*/
.get(
'/:courseId',
courseMemberMiddleware,
zValidator('param', ZCourseGetParam),
zValidator('query', ZCourseGetQuery),
async (c) => {
try {
const { courseId } = c.req.valid('param');
const { slug } = c.req.valid('query');
const user = c.get('user')!;
const course = await getCourse(slug ? undefined : courseId, slug, user.id);
return c.json(
{
success: true,
data: course
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch course');
}
}
)
/**
* PUT /course/:courseId
* Updates a course
* Requires authentication and course membership (admin/tutor role)
*/
.put(
'/:courseId',
authMiddleware,
courseTeamMemberMiddleware,
zValidator('param', ZCourseUpdateParam),
zValidator('json', ZCourseUpdate),
async (c) => {
try {
const { courseId } = c.req.valid('param');
const validatedData = c.req.valid('json');
const { tagIds, ...courseData } = validatedData;
const result = await updateCourse(courseId, courseData);
if (tagIds !== undefined) {
const orgId = c.req.header('cio-org-id');
if (!orgId) {
return c.json(
{
success: false,
error: 'Organization context not available',
code: 'ORG_CONTEXT_MISSING'
},
500
);
}
const user = c.get('user')!;
const tags = await replaceCourseTags(orgId, courseId, { tagIds }, { updatedByUserId: user.id });
return c.json(
{
success: true,
data: {
...result,
tags
}
},
200
);
}
return c.json(
{
success: true,
data: result
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to update course');
}
}
)
/**
* DELETE /course/:courseId
* Soft deletes a course by setting status to 'DELETED'
* Requires authentication and course membership (admin/tutor role)
*/
.delete(
'/:courseId',
authMiddleware,
courseTeamMemberMiddleware,
zValidator('param', ZCourseDeleteParam),
async (c) => {
try {
const { courseId } = c.req.valid('param');
const result = await deleteCourse(courseId);
return c.json(
{
success: true,
data: result
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to delete course');
}
}
)
/**
* GET /course/:courseId/progress
* Gets course progress for a profile
* Query param: profileId (required)
* Requires authentication and course membership
*/
.get(
'/:courseId/progress',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZCourseProgressParam),
zValidator('query', ZCourseProgressQuery),
async (c) => {
try {
const { courseId } = c.req.valid('param');
const { profileId } = c.req.valid('query');
const progress = await getCourseProgress(courseId, profileId);
return c.json(
{
success: true,
data: progress
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch course progress');
}
}
)
/**
* GET /course/:courseId/analytics
* Gets course analytics including student progress, completion rates, and grades
* Requires authentication and course membership (admin/tutor role)
*/
.get(
'/:courseId/analytics',
authMiddleware,
courseTeamMemberMiddleware,
zValidator('param', ZCourseProgressParam),
async (c) => {
try {
const { courseId } = c.req.valid('param');
const analytics = await getCourseAnalytics(courseId);
return c.json(
{
success: true,
data: analytics
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch course analytics');
}
}
)
.post(
'/:courseId/download/certificate',
authMiddleware,
@@ -79,7 +435,7 @@ export const courseRouter = new Hono()
const validatedData = c.req.valid('json');
const { title, description, slug, organizationId } = validatedData;
const user = c.get('user');
const user = c.get('user')!;
// Clone the course
const newCourse = await cloneCourse(courseId, title, user.id, description, slug, organizationId);
@@ -97,5 +453,15 @@ export const courseRouter = new Hono()
}
)
.route('/katex', katexRouter)
.route('/:courseId/payment-request', paymentRequestRouter)
.route('/:courseId/content', contentRouter)
.route('/:courseId/section', sectionRouter)
.route('/:courseId/lesson', lessonRouter)
.route('/:courseId/exercise', exerciseRouter)
.route('/:courseId/submission', submissionRouter)
.route('/:courseId/attendance', attendanceRouter)
.route('/:courseId/mark', markRouter)
.route('/:courseId/newsfeed', newsfeedRouter)
.route('/:courseId/members', membersRouter)
.route('/:courseId/invites', invitesRouter)
.route('/presign', presignRouter);
+211
View File
@@ -0,0 +1,211 @@
import { ErrorCodes, handleError } from '@api/utils/errors';
import {
ZExerciseCreate,
ZExerciseFromTemplate,
ZExerciseGetParam,
ZExerciseListQuery,
ZExerciseSubmissionCreate,
ZExerciseUpdate
} from '@cio/utils/validation/exercise';
import { ZTemplateById, ZTemplateByTag } from '@cio/utils/validation/mocks';
import {
createExercise,
createExerciseFromTemplate,
deleteExerciseService,
getExercise,
listExercises,
updateExerciseService
} from '@api/services/exercise/exercise';
import { fetchAllTemplatesMetadata, fetchTemplateById, fetchTemplatesByTag } from '@api/services/exercise/template';
import { getGroupMemberIdByCourseAndProfile, isCourseTeamMemberOrOrgAdmin } from '@cio/db/queries/group';
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { courseMemberMiddleware } from '@api/middlewares/course-member';
import { createSubmissionService, listExerciseSubmissionsOverview } from '@api/services/submission';
import { zValidator } from '@hono/zod-validator';
export const exerciseRouter = new Hono()
// Exercise CRUD routes
.get('/', authMiddleware, courseMemberMiddleware, zValidator('query', ZExerciseListQuery), async (c) => {
try {
const courseId = c.req.param('courseId')!;
const user = c.get('user')!;
const { lessonId, sectionId } = c.req.valid('query');
const exercises = await listExercises(courseId, { lessonId, sectionId }, user.id);
return c.json({ success: true, data: exercises }, 200);
} catch (error) {
return handleError(c, error, 'Failed to list exercises');
}
})
.get('/:exerciseId/submissions', authMiddleware, courseMemberMiddleware, async (c) => {
try {
const courseId = c.req.param('courseId')!;
const exerciseId = c.req.param('exerciseId')!;
const user = c.get('user')!;
const data = await listExerciseSubmissionsOverview(courseId, exerciseId, user.id);
return c.json({ success: true, data }, 200);
} catch (error) {
return handleError(c, error, 'Failed to fetch exercise submissions overview');
}
})
.get('/:exerciseId', authMiddleware, courseMemberMiddleware, zValidator('param', ZExerciseGetParam), async (c) => {
try {
const { exerciseId } = c.req.valid('param');
const user = c.get('user')!;
const exercise = await getExercise(exerciseId, undefined, user.id);
return c.json({ success: true, data: exercise }, 200);
} catch (error) {
return handleError(c, error, 'Failed to fetch exercise');
}
})
.post('/', authMiddleware, courseMemberMiddleware, zValidator('json', ZExerciseCreate), async (c) => {
try {
const data = c.req.valid('json');
const exercise = await createExercise(data);
return c.json({ success: true, data: exercise }, 201);
} catch (error) {
return handleError(c, error, 'Failed to create exercise');
}
})
/**
* POST /course/:courseId/exercise/from-template
* Creates an exercise from a template
* Requires authentication and course membership (admin/tutor role)
*/
.post(
'/from-template',
authMiddleware,
courseMemberMiddleware,
zValidator('json', ZExerciseFromTemplate),
async (c) => {
try {
const courseId = c.req.param('courseId')!;
const { lessonId, sectionId, order, templateId } = c.req.valid('json');
// Fetch template from database
const template = await fetchTemplateById(templateId);
if (!template) {
return c.json({ success: false, error: 'Template not found' }, 404);
}
if (!template.questionnaire) {
return c.json({ success: false, error: 'Template is missing questionnaire data' }, 400);
}
const exercise = await createExerciseFromTemplate(courseId, lessonId, sectionId, order, template);
return c.json({ success: true, data: exercise }, 201);
} catch (error) {
return handleError(c, error, 'Failed to create exercise from template');
}
}
)
.put(
'/:exerciseId',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZExerciseGetParam),
zValidator('json', ZExerciseUpdate),
async (c) => {
try {
const { exerciseId } = c.req.valid('param');
const data = c.req.valid('json');
const courseId = c.req.param('courseId')!;
const user = c.get('user')!;
if (data.isUnlocked !== undefined) {
const isAuthorized = await isCourseTeamMemberOrOrgAdmin(courseId, user.id);
if (!isAuthorized) {
return c.json(
{
success: false,
error: 'Unauthorized',
code: ErrorCodes.UNAUTHORIZED
},
403
);
}
}
const exercise = await updateExerciseService(exerciseId, data);
return c.json({ success: true, data: exercise }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update exercise');
}
}
)
.delete('/:exerciseId', authMiddleware, courseMemberMiddleware, zValidator('param', ZExerciseGetParam), async (c) => {
try {
const { exerciseId } = c.req.valid('param');
const exercise = await deleteExerciseService(exerciseId);
return c.json({ success: true, data: exercise }, 200);
} catch (error) {
return handleError(c, error, 'Failed to delete exercise');
}
})
// Exercise Submission routes
.post(
'/:exerciseId/submission',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZExerciseGetParam),
zValidator('json', ZExerciseSubmissionCreate),
async (c) => {
try {
const user = c.get('user')!;
const courseId = c.req.param('courseId')!;
const { exerciseId } = c.req.valid('param');
const { answers } = c.req.valid('json');
const groupMemberId = await getGroupMemberIdByCourseAndProfile(courseId, user.id);
if (!groupMemberId) {
return c.json({ success: false, error: 'User is not a member of this course' }, 403);
}
const submission = await createSubmissionService(courseId, exerciseId, groupMemberId, answers);
return c.json({ success: true, data: submission }, 201);
} catch (error) {
return handleError(c, error, 'Failed to submit exercise');
}
}
)
// Template routes
.get('/template', authMiddleware, courseMemberMiddleware, async (c) => {
try {
const result = await fetchAllTemplatesMetadata();
return c.json({ success: true, data: result }, 200);
} catch (error) {
return handleError(c, error, 'Failed to load template metadata');
}
})
.get('/template/:id', authMiddleware, courseMemberMiddleware, zValidator('param', ZTemplateById), async (c) => {
try {
const { id } = c.req.valid('param');
const result = await fetchTemplateById(id);
return c.json({ success: true, data: result }, 200);
} catch (error) {
return handleError(c, error, 'Failed to load template');
}
})
.get('/template/tag/:tag', authMiddleware, courseMemberMiddleware, zValidator('param', ZTemplateByTag), async (c) => {
try {
const { tag } = c.req.valid('param');
const result = await fetchTemplatesByTag(tag);
return c.json({ success: true, data: result }, 200);
} catch (error) {
return handleError(c, error, 'Failed to load template');
}
});
+123
View File
@@ -0,0 +1,123 @@
import {
ZCourseInviteAuditParam,
ZCourseInviteParam,
ZCourseInviteRevokeParam,
ZCreateCourseInvite
} from '@cio/utils/validation/course/invite';
import {
createStudentInvite,
getStudentInviteAuditTrail,
listStudentInvites,
revokeStudentInvite
} from '@api/services/course/invite';
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { courseTeamMemberMiddleware } from '@api/middlewares/course-team-member';
import { handleError } from '@api/utils/errors';
import { zValidator } from '@hono/zod-validator';
export const invitesRouter = new Hono()
/**
* GET /course/:courseId/invites
* Lists secure invites for a course (team/admin only)
*/
.get('/', authMiddleware, courseTeamMemberMiddleware, zValidator('param', ZCourseInviteParam), async (c) => {
try {
const { courseId } = c.req.valid('param');
const invites = await listStudentInvites(courseId);
return c.json(
{
success: true,
data: invites
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to list invites');
}
})
/**
* POST /course/:courseId/invites
* Creates a secure student invite token for a course (team/admin only)
*/
.post(
'/',
authMiddleware,
courseTeamMemberMiddleware,
zValidator('param', ZCourseInviteParam),
zValidator('json', ZCreateCourseInvite),
async (c) => {
try {
const user = c.get('user')!;
const { courseId } = c.req.valid('param');
const payload = c.req.valid('json');
const invite = await createStudentInvite(courseId, user.id, payload);
return c.json(
{
success: true,
data: invite
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to create invite');
}
}
)
/**
* POST /course/:courseId/invites/:inviteId/revoke
* Revokes a secure invite (team/admin only)
*/
.post(
'/:inviteId/revoke',
authMiddleware,
courseTeamMemberMiddleware,
zValidator('param', ZCourseInviteRevokeParam),
async (c) => {
try {
const { courseId, inviteId } = c.req.valid('param');
const user = c.get('user')!;
const revoked = await revokeStudentInvite(courseId, inviteId, user.id);
return c.json(
{
success: true,
data: revoked
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to revoke invite');
}
}
)
/**
* GET /course/:courseId/invites/:inviteId/audit
* Lists audit trail for an invite (team/admin only)
*/
.get(
'/:inviteId/audit',
authMiddleware,
courseTeamMemberMiddleware,
zValidator('param', ZCourseInviteAuditParam),
async (c) => {
try {
const { courseId, inviteId } = c.req.valid('param');
const audit = await getStudentInviteAuditTrail(courseId, inviteId);
return c.json(
{
success: true,
data: audit
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to load invite audit');
}
}
);
+1 -1
View File
@@ -31,7 +31,7 @@ export const katexRouter = new Hono().get('/', async (c) => {
return c.json(
{
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
error: 'Failed to render LaTeX'
},
500
);
@@ -0,0 +1,139 @@
import {
ZLessonLanguageCreate,
ZLessonLanguageGetByLocaleParam,
ZLessonLanguageGetParam,
ZLessonLanguageUpdate
} from '@cio/utils/validation/lesson';
import {
getLessonLanguage,
listLessonLanguages,
updateLessonLanguageService,
upsertLessonLanguageService
} from '@api/services/lesson-language';
import { Hono } from '@api/utils/hono';
import type { TLocale } from '@db/types';
import { authMiddleware } from '@api/middlewares/auth';
import { courseMemberMiddleware } from '@api/middlewares/course-member';
import { handleError } from '@api/utils/errors';
import { zValidator } from '@hono/zod-validator';
export const lessonLanguageRouter = new Hono()
/**
* GET /course/:courseId/lesson/:lessonId/language
* Gets all language translations for a lesson
* Requires authentication and course membership
*/
.get('/', authMiddleware, courseMemberMiddleware, zValidator('param', ZLessonLanguageGetParam), async (c) => {
try {
const { lessonId } = c.req.valid('param');
const languages = await listLessonLanguages(lessonId);
return c.json(
{
success: true,
data: languages
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch lesson languages');
}
})
/**
* GET /course/:courseId/lesson/:lessonId/language/:locale
* Gets a single lesson language by locale
* Requires authentication and course membership
*/
.get(
'/:locale',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonLanguageGetByLocaleParam),
async (c) => {
try {
const { lessonId, locale } = c.req.valid('param');
const language = await getLessonLanguage(lessonId, locale as TLocale);
if (!language) {
return c.json(
{
success: false,
error: 'Lesson language not found'
},
404
);
}
return c.json(
{
success: true,
data: language
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch lesson language');
}
}
)
/**
* POST /course/:courseId/lesson/:lessonId/language
* Creates or updates a lesson language translation (upsert)
* Requires authentication and course membership
*/
.post(
'/',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonLanguageGetParam),
zValidator('json', ZLessonLanguageCreate),
async (c) => {
try {
const { lessonId } = c.req.valid('param');
const data = c.req.valid('json');
const language = await upsertLessonLanguageService(lessonId, data);
return c.json(
{
success: true,
data: language
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to create or update lesson language');
}
}
)
/**
* PUT /course/:courseId/lesson/:lessonId/language/:locale
* Updates a lesson language translation
* Requires authentication and course membership
*/
.put(
'/:locale',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonLanguageGetByLocaleParam),
zValidator('json', ZLessonLanguageUpdate),
async (c) => {
try {
const { lessonId, locale } = c.req.valid('param');
const data = c.req.valid('json');
const language = await updateLessonLanguageService(lessonId, locale as TLocale, data);
return c.json(
{
success: true,
data: language
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to update lesson language');
}
}
);
+261 -7
View File
@@ -1,14 +1,268 @@
import {
ZLessonCommentCreate,
ZLessonCommentGetParam,
ZLessonCommentUpdate,
ZLessonCommentsQuery,
ZLessonCompletionUpdate,
ZLessonCreate,
ZLessonGetParam,
ZLessonHistoryParam,
ZLessonHistoryQuery,
ZLessonListQuery,
ZLessonReorder,
ZLessonUpdate
} from '@cio/utils/validation/lesson';
import {
createLesson,
createLessonCommentService,
deleteLessonCommentService,
deleteLessonService,
getLesson,
getLessonCommentsPaginated,
getLessonCompletionService,
getLessonHistoryService,
listLessons,
reorderLessons,
updateLessonCommentService,
updateLessonService,
upsertLessonCompletionService
} from '@api/services/lesson';
import { Hono } from '@api/utils/hono';
import { ZLessonDownloadContent } from '@cio/utils/validation/course';
import { authMiddleware } from '@api/middlewares/auth';
import { courseMemberMiddleware } from '@api/middlewares/course-member';
import { generateLessonPdf } from '@api/utils/lesson';
import { getGroupMemberIdByCourseAndProfile } from '@cio/db/queries/group';
import { handleError } from '@api/utils/errors';
import { lessonLanguageRouter } from '@api/routes/course/lesson-language';
import { zValidator } from '@hono/zod-validator';
export const lessonRouter = new Hono().post(
'/download/pdf',
courseMemberMiddleware,
zValidator('json', ZLessonDownloadContent),
async (c) => {
export const lessonRouter = new Hono()
// Lesson CRUD routes
.get('/', authMiddleware, courseMemberMiddleware, zValidator('query', ZLessonListQuery), async (c) => {
try {
const { courseId, sectionId } = c.req.valid('query');
const lessons = await listLessons(courseId, sectionId);
return c.json({ success: true, data: lessons }, 200);
} catch (error) {
return handleError(c, error, 'Failed to list lessons');
}
})
.post('/reorder', authMiddleware, courseMemberMiddleware, zValidator('json', ZLessonReorder), async (c) => {
try {
const { lessons } = c.req.valid('json');
const updated = await reorderLessons(lessons);
return c.json({ success: true, data: updated }, 200);
} catch (error) {
return handleError(c, error, 'Failed to reorder lessons');
}
})
.get('/:lessonId', authMiddleware, courseMemberMiddleware, zValidator('param', ZLessonGetParam), async (c) => {
try {
const { lessonId } = c.req.valid('param');
const lesson = await getLesson(lessonId);
return c.json({ success: true, data: lesson }, 200);
} catch (error) {
return handleError(c, error, 'Failed to fetch lesson');
}
})
.post('/', authMiddleware, courseMemberMiddleware, zValidator('json', ZLessonCreate), async (c) => {
try {
const courseId = c.req.param('courseId')!;
const data = c.req.valid('json');
const lesson = await createLesson(courseId, { ...data, courseId });
return c.json({ success: true, data: lesson }, 201);
} catch (error) {
return handleError(c, error, 'Failed to create lesson');
}
})
.put(
'/:lessonId',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonGetParam),
zValidator('json', ZLessonUpdate),
async (c) => {
try {
const { lessonId } = c.req.valid('param');
const data = c.req.valid('json');
const lesson = await updateLessonService(lessonId, data);
return c.json({ success: true, data: lesson }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update lesson');
}
}
)
.delete('/:lessonId', authMiddleware, courseMemberMiddleware, zValidator('param', ZLessonGetParam), async (c) => {
try {
const { lessonId } = c.req.valid('param');
const lesson = await deleteLessonService(lessonId);
return c.json({ success: true, data: lesson }, 200);
} catch (error) {
return handleError(c, error, 'Failed to delete lesson');
}
})
// Lesson Comment routes
.get(
'/:lessonId/comment',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonGetParam),
zValidator('query', ZLessonCommentsQuery),
async (c) => {
try {
const { lessonId } = c.req.valid('param');
const { cursor, limit = 10 } = c.req.valid('query');
const result = await getLessonCommentsPaginated(lessonId, { cursor, limit });
return c.json({ success: true, data: result }, 200);
} catch (error) {
return handleError(c, error, 'Failed to get lesson comments');
}
}
)
.post(
'/:lessonId/comment',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonGetParam),
zValidator('json', ZLessonCommentCreate),
async (c) => {
try {
const user = c.get('user')!;
const courseId = c.req.param('courseId')!;
const { lessonId } = c.req.valid('param');
const { comment } = c.req.valid('json');
const groupMemberId = await getGroupMemberIdByCourseAndProfile(courseId, user.id);
if (!groupMemberId) {
return c.json({ success: false, error: 'User is not a member of this course' }, 403);
}
const commentData = await createLessonCommentService(lessonId, groupMemberId, comment);
return c.json({ success: true, data: commentData }, 201);
} catch (error) {
return handleError(c, error, 'Failed to create lesson comment');
}
}
)
.put(
'/comment/:commentId',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonCommentGetParam),
zValidator('json', ZLessonCommentUpdate),
async (c) => {
try {
const { commentId } = c.req.valid('param');
const { comment } = c.req.valid('json');
const updated = await updateLessonCommentService(Number(commentId), comment);
return c.json({ success: true, data: updated }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update lesson comment');
}
}
)
.delete(
'/comment/:commentId',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonCommentGetParam),
async (c) => {
try {
const { commentId } = c.req.valid('param');
const comment = await deleteLessonCommentService(Number(commentId));
return c.json({ success: true, data: comment }, 200);
} catch (error) {
return handleError(c, error, 'Failed to delete lesson comment');
}
}
)
// Lesson Completion routes
.get(
'/:lessonId/completion',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonGetParam),
async (c) => {
try {
const user = c.get('user')!;
const { lessonId } = c.req.valid('param');
const completion = await getLessonCompletionService(lessonId, user.id);
return c.json({ success: true, data: completion }, 200);
} catch (error) {
return handleError(c, error, 'Failed to get lesson completion');
}
}
)
.put(
'/:lessonId/completion',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonGetParam),
zValidator('json', ZLessonCompletionUpdate),
async (c) => {
try {
const user = c.get('user')!;
const { lessonId } = c.req.valid('param');
const { isComplete } = c.req.valid('json');
const completion = await upsertLessonCompletionService(lessonId, user.id, isComplete);
return c.json({ success: true, data: completion }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update lesson completion');
}
}
)
/**
* GET /course/:courseId/lesson/:lessonId/history
* Gets lesson version history for a lesson and locale
* Query params: locale (required), endRange (optional, default 9)
* Requires authentication and course membership
*/
.get(
'/:lessonId/history',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZLessonHistoryParam),
zValidator('query', ZLessonHistoryQuery),
async (c) => {
try {
const { lessonId } = c.req.valid('param');
const { locale, endRange } = c.req.valid('query');
const history = await getLessonHistoryService(lessonId, locale, endRange);
return c.json(
{
success: true,
data: history
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch lesson history');
}
}
)
// PDF download route (existing)
.post('/download/pdf', courseMemberMiddleware, zValidator('json', ZLessonDownloadContent), async (c) => {
const validatedData = c.req.valid('json');
const pdfBuffer = await generateLessonPdf(validatedData);
@@ -22,5 +276,5 @@ export const lessonRouter = new Hono().post(
}
})
);
}
);
})
.route('/:lessonId/language', lessonLanguageRouter);
+27
View File
@@ -0,0 +1,27 @@
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { courseMemberMiddleware } from '@api/middlewares/course-member';
import { getGradebook } from '@api/services/mark/gradebook';
import { getMarks } from '@api/services/mark';
import { handleError } from '@api/utils/errors';
export const markRouter = new Hono()
.get('/gradebook', authMiddleware, courseMemberMiddleware, async (c) => {
try {
const courseId = c.req.param('courseId')!;
const gradebook = await getGradebook(courseId);
return c.json({ success: true, data: gradebook }, 200);
} catch (error) {
return handleError(c, error, 'Failed to get gradebook');
}
})
.get('/', authMiddleware, courseMemberMiddleware, async (c) => {
try {
const courseId = c.req.param('courseId')!;
const marks = await getMarks(courseId);
return c.json({ success: true, data: marks }, 200);
} catch (error) {
return handleError(c, error, 'Failed to get marks');
}
});
+202
View File
@@ -0,0 +1,202 @@
import {
ZNewsfeedCommentCreate,
ZNewsfeedCommentGetParam,
ZNewsfeedCommentUpdate,
ZNewsfeedCommentsQuery,
ZNewsfeedCreate,
ZNewsfeedGetParam,
ZNewsfeedListQuery,
ZNewsfeedReactionUpdate,
ZNewsfeedUpdate
} from '@cio/utils/validation/newsfeed';
import {
createNewsfeedCommentService,
createNewsfeedService,
deleteNewsfeedCommentService,
deleteNewsfeedService,
getNewsfeedCommentsService,
getNewsfeedItem,
listNewsfeedPaginated,
updateNewsfeedCommentService,
updateNewsfeedReactionService,
updateNewsfeedService
} from '@api/services/newsfeed';
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { courseMemberMiddleware } from '@api/middlewares/course-member';
import { courseTeamMemberMiddleware } from '@api/middlewares/course-team-member';
import { getGroupMemberIdByCourseAndProfile } from '@cio/db/queries/group';
import { handleError } from '@api/utils/errors';
import { newsfeedCommentAuthorOrTeamMiddleware } from '@api/middlewares/newsfeed-comment-author-or-team';
import { zValidator } from '@hono/zod-validator';
export const newsfeedRouter = new Hono()
// Newsfeed CRUD routes
.get('/', authMiddleware, courseMemberMiddleware, zValidator('query', ZNewsfeedListQuery), async (c) => {
try {
const courseId = c.req.param('courseId')!;
const { cursor, limit = 10 } = c.req.valid('query');
const result = await listNewsfeedPaginated(courseId, { cursor, limit });
return c.json({ success: true, data: result }, 200);
} catch (error) {
return handleError(c, error, 'Failed to list newsfeed');
}
})
.get('/:feedId', authMiddleware, courseMemberMiddleware, zValidator('param', ZNewsfeedGetParam), async (c) => {
try {
const { feedId } = c.req.valid('param');
const feed = await getNewsfeedItem(feedId);
return c.json({ success: true, data: feed }, 200);
} catch (error) {
return handleError(c, error, 'Failed to fetch newsfeed item');
}
})
.post('/', authMiddleware, courseTeamMemberMiddleware, zValidator('json', ZNewsfeedCreate), async (c) => {
try {
const user = c.get('user')!;
const courseId = c.req.param('courseId')!;
const data = c.req.valid('json');
const groupMemberId = await getGroupMemberIdByCourseAndProfile(courseId, user.id);
if (!groupMemberId) {
return c.json({ success: false, error: 'User is not a member of this course' }, 403);
}
const feed = await createNewsfeedService(courseId, groupMemberId, data);
return c.json({ success: true, data: feed }, 201);
} catch (error) {
return handleError(c, error, 'Failed to create newsfeed');
}
})
.put(
'/:feedId',
authMiddleware,
courseTeamMemberMiddleware,
zValidator('param', ZNewsfeedGetParam),
zValidator('json', ZNewsfeedUpdate),
async (c) => {
try {
const { feedId } = c.req.valid('param');
const data = c.req.valid('json');
const feed = await updateNewsfeedService(feedId, data);
return c.json({ success: true, data: feed }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update newsfeed');
}
}
)
.put(
'/:feedId/react',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZNewsfeedGetParam),
zValidator('json', ZNewsfeedReactionUpdate),
async (c) => {
try {
const { feedId } = c.req.valid('param');
const { reaction } = c.req.valid('json');
const feed = await updateNewsfeedReactionService(feedId, reaction);
return c.json({ success: true, data: feed }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update newsfeed reaction');
}
}
)
.delete('/:feedId', authMiddleware, courseTeamMemberMiddleware, zValidator('param', ZNewsfeedGetParam), async (c) => {
try {
const { feedId } = c.req.valid('param');
const feed = await deleteNewsfeedService(feedId);
return c.json({ success: true, data: feed }, 200);
} catch (error) {
return handleError(c, error, 'Failed to delete newsfeed');
}
})
// Newsfeed Comment routes
.get(
'/:feedId/comments',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZNewsfeedGetParam),
zValidator('query', ZNewsfeedCommentsQuery),
async (c) => {
try {
const { feedId } = c.req.valid('param');
const { cursor, limit = 5 } = c.req.valid('query');
const result = await getNewsfeedCommentsService(feedId, { cursor, limit });
return c.json({ success: true, data: result }, 200);
} catch (error) {
return handleError(c, error, 'Failed to fetch newsfeed comments');
}
}
)
.post(
'/:feedId/comment',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZNewsfeedGetParam),
zValidator('json', ZNewsfeedCommentCreate),
async (c) => {
try {
const user = c.get('user')!;
const courseId = c.req.param('courseId')!;
const { feedId } = c.req.valid('param');
const { content } = c.req.valid('json');
const groupMemberId = await getGroupMemberIdByCourseAndProfile(courseId, user.id);
if (!groupMemberId) {
return c.json({ success: false, error: 'User is not a member of this course' }, 403);
}
const comment = await createNewsfeedCommentService(feedId, groupMemberId, content);
return c.json({ success: true, data: comment }, 201);
} catch (error) {
return handleError(c, error, 'Failed to create newsfeed comment');
}
}
)
.put(
'/comment/:commentId',
authMiddleware,
newsfeedCommentAuthorOrTeamMiddleware,
zValidator('param', ZNewsfeedCommentGetParam),
zValidator('json', ZNewsfeedCommentUpdate),
async (c) => {
try {
const { commentId } = c.req.valid('param');
const { content } = c.req.valid('json');
const updated = await updateNewsfeedCommentService(Number(commentId), content);
return c.json({ success: true, data: updated }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update newsfeed comment');
}
}
)
.delete(
'/comment/:commentId',
authMiddleware,
newsfeedCommentAuthorOrTeamMiddleware,
zValidator('param', ZNewsfeedCommentGetParam),
async (c) => {
try {
const { commentId } = c.req.valid('param');
const comment = await deleteNewsfeedCommentService(Number(commentId));
return c.json({ success: true, data: comment }, 200);
} catch (error) {
return handleError(c, error, 'Failed to delete newsfeed comment');
}
}
);
@@ -0,0 +1,39 @@
import { Hono } from '@api/utils/hono';
import { createPaymentRequest } from '@api/services/course/payment-request';
import { handleError } from '@api/utils/errors';
import { z } from 'zod';
import { zValidator } from '@hono/zod-validator';
const ZPaymentRequest = z.object({
studentEmail: z.string().email(),
studentFullname: z.string().min(1)
});
export const paymentRequestRouter = new Hono()
/**
* POST /course/:courseId/payment-request
* Creates a payment request and sends emails to teacher and student
* No authentication required - public route for course landing pages
*/
.post('/', zValidator('json', ZPaymentRequest), async (c) => {
try {
const courseId = c.req.param('courseId')!;
const data = c.req.valid('json');
const result = await createPaymentRequest({
courseId,
studentEmail: data.studentEmail,
studentFullname: data.studentFullname
});
return c.json(
{
success: true,
data: result
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to create payment request');
}
});
+138
View File
@@ -0,0 +1,138 @@
import {
ZAddCourseMembers,
ZCourseMembersMemberParam,
ZCourseMembersParam,
ZUpdateCourseMember
} from '@cio/utils/validation/course/people';
import { addMembers, deleteMember, listCourseMembers, updateMember } from '@api/services/course/people';
import { Hono } from '@api/utils/hono';
import { ZCourseUserAnalyticsParam } from '@cio/utils/validation/course';
import { courseTeamMemberMiddleware } from '@api/middlewares/course-team-member';
import { getUserCourseAnalytics } from '@api/services/course/course';
import { handleError } from '@api/utils/errors';
import { zValidator } from '@hono/zod-validator';
export const membersRouter = new Hono()
/**
* GET /course/:courseId/members
* Gets all course members for a course
* Requires authentication and course team membership (admin/tutor role)
*/
.get('/', courseTeamMemberMiddleware, zValidator('param', ZCourseMembersParam), async (c) => {
try {
const { courseId } = c.req.valid('param');
const members = await listCourseMembers(courseId);
return c.json(
{
success: true,
data: members
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch course members');
}
})
/**
* POST /course/:courseId/members
* Adds one or more course members to a course
* Accepts either a single member (ZAddCourseMember) or multiple members (ZAddCourseMembers)
* Requires authentication and course team membership (admin/tutor role)
*/
.post(
'/',
courseTeamMemberMiddleware,
zValidator('param', ZCourseMembersParam),
zValidator('json', ZAddCourseMembers),
async (c) => {
try {
const { courseId } = c.req.valid('param');
const members = c.req.valid('json');
const addedMembers = await addMembers(courseId, members);
return c.json(
{
success: true,
data: addedMembers
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to add course member(s)');
}
}
)
/**
* PUT /course/:courseId/members/:memberId
* Updates a course member
* Requires authentication and course team membership (admin/tutor role)
*/
.put(
'/:memberId',
courseTeamMemberMiddleware,
zValidator('param', ZCourseMembersMemberParam),
zValidator('json', ZUpdateCourseMember),
async (c) => {
try {
const { courseId, memberId } = c.req.valid('param');
const validatedData = c.req.valid('json');
const member = await updateMember(courseId, memberId, validatedData);
return c.json(
{
success: true,
data: member
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to update course member');
}
}
)
/**
* DELETE /course/:courseId/members/:memberId
* Deletes a course member
* Requires authentication and course team membership (admin/tutor role)
*/
.delete('/:memberId', courseTeamMemberMiddleware, zValidator('param', ZCourseMembersMemberParam), async (c) => {
try {
const { courseId, memberId } = c.req.valid('param');
const member = await deleteMember(courseId, memberId);
return c.json(
{
success: true,
data: member
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to delete course member');
}
})
/**
* GET /course/:courseId/members/:userId/analytics
* Gets user course analytics for a specific course
* Requires authentication and course membership
*/
.get('/:userId/analytics', courseTeamMemberMiddleware, zValidator('param', ZCourseUserAnalyticsParam), async (c) => {
try {
const { courseId, userId } = c.req.valid('param');
const analytics = await getUserCourseAnalytics(courseId, userId);
return c.json(
{
success: true,
data: analytics
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch user course analytics');
}
});
+10 -64
View File
@@ -1,19 +1,19 @@
import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import {
ZCourseDocumentPresignUrlUpload,
ZCourseDownloadPresignedUrl,
ZCoursePresignUrlUpload
} from '@cio/utils/validation/course';
import { describeRoute, validator } from 'hono-openapi';
import {
generateDocumentDownloadPresignedUrls,
generateDocumentUploadPresignedUrl,
generateVideoDownloadPresignedUrls,
generateVideoUploadPresignedUrl
} from '@api/utils/s3';
import { BUCKET_NAME } from '@api/constants/upload';
import { CLOUDFLARE } from '@api/constants';
import type { GetSignedUrlParameters } from '@api/utils/s3';
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { generateFileKey } from '@api/utils/upload';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { s3Client } from '@api/utils/s3';
// Response schemas for OpenAPI documentation
const PresignUploadResponse = {
@@ -71,15 +71,7 @@ export const presignRouter = new Hono()
const { fileName, fileType } = body;
const fileKey = generateFileKey(fileName);
const command = new PutObjectCommand({
Bucket: BUCKET_NAME.VIDEOS,
Key: fileKey,
ContentType: fileType
}) as GetSignedUrlParameters[1];
const presignedUrl = await getSignedUrl(s3Client as GetSignedUrlParameters[0], command, {
expiresIn: CLOUDFLARE.R2.PRESIGN_EXPIRATION_TIME
});
const presignedUrl = await generateVideoUploadPresignedUrl(fileKey, fileType);
return c.json({
success: true,
@@ -119,15 +111,7 @@ export const presignRouter = new Hono()
const { fileName, fileType } = body;
const fileKey = generateFileKey(fileName);
const command = new PutObjectCommand({
Bucket: BUCKET_NAME.DOCUMENTS,
Key: fileKey,
ContentType: fileType
}) as GetSignedUrlParameters[1];
const presignedUrl = await getSignedUrl(s3Client as GetSignedUrlParameters[0], command, {
expiresIn: CLOUDFLARE.R2.PRESIGN_EXPIRATION_TIME
});
const presignedUrl = await generateDocumentUploadPresignedUrl(fileKey, fileType);
return c.json({
success: true,
@@ -166,26 +150,7 @@ export const presignRouter = new Hono()
const { keys } = body;
const signedUrls: Record<string, string> = {};
const urlPromises = keys.map(async (key) => {
const command = new GetObjectCommand({
Bucket: BUCKET_NAME.VIDEOS,
Key: key
}) as GetSignedUrlParameters[1];
const presignedUrl = await getSignedUrl(s3Client as GetSignedUrlParameters[0], command, {
expiresIn: CLOUDFLARE.R2.DOWNLOAD_EXPIRATION_TIME
});
return { key, presignedUrl };
});
const results = await Promise.all(urlPromises);
results.forEach(({ key, presignedUrl }) => {
signedUrls[key] = presignedUrl;
});
const signedUrls = await generateVideoDownloadPresignedUrls(keys);
return c.json({
success: true,
@@ -223,26 +188,7 @@ export const presignRouter = new Hono()
const { keys } = body;
const signedUrls: Record<string, string> = {};
const urlPromises = keys.map(async (key) => {
const command = new GetObjectCommand({
Bucket: BUCKET_NAME.DOCUMENTS,
Key: key
}) as GetSignedUrlParameters[1];
const presignedUrl = await getSignedUrl(s3Client as GetSignedUrlParameters[0], command, {
expiresIn: CLOUDFLARE.R2.DOWNLOAD_EXPIRATION_TIME
});
return { key, presignedUrl };
});
const results = await Promise.all(urlPromises);
results.forEach(({ key, presignedUrl }) => {
signedUrls[key] = presignedUrl;
});
const signedUrls = await generateDocumentDownloadPresignedUrls(keys);
return c.json({
success: true,
+97
View File
@@ -0,0 +1,97 @@
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { courseMemberMiddleware } from '@api/middlewares/course-member';
import { handleError } from '@api/utils/errors';
import {
createCourseSection,
deleteCourseSectionService,
promoteUngroupedSection,
reorderCourseSections,
updateCourseSectionService
} from '@api/services/course/section';
import {
ZCourseSectionCreate,
ZCourseSectionGetParam,
ZCourseSectionPromoteUngrouped,
ZCourseSectionReorder,
ZCourseSectionUpdate
} from '@cio/utils/validation/course/section';
import { zValidator } from '@hono/zod-validator';
export const sectionRouter = new Hono()
.post('/', authMiddleware, courseMemberMiddleware, zValidator('json', ZCourseSectionCreate), async (c) => {
try {
const courseId = c.req.param('courseId')!;
const data = c.req.valid('json');
const section = await createCourseSection(courseId, { ...data, courseId });
return c.json({ success: true, data: section }, 201);
} catch (error) {
return handleError(c, error, 'Failed to create course section');
}
})
.post(
'/promote-ungrouped',
authMiddleware,
courseMemberMiddleware,
zValidator('json', ZCourseSectionPromoteUngrouped),
async (c) => {
try {
const courseId = c.req.param('courseId')!;
const data = c.req.valid('json');
const result = await promoteUngroupedSection(courseId, data);
return c.json({ success: true, data: result }, 201);
} catch (error) {
return handleError(c, error, 'Failed to promote ungrouped section');
}
}
)
.put(
'/:sectionId',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZCourseSectionGetParam),
zValidator('json', ZCourseSectionUpdate),
async (c) => {
try {
const { sectionId } = c.req.valid('param');
const data = c.req.valid('json');
const section = await updateCourseSectionService(sectionId, data);
return c.json({ success: true, data: section }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update course section');
}
}
)
.delete(
'/:sectionId',
authMiddleware,
courseMemberMiddleware,
zValidator('param', ZCourseSectionGetParam),
async (c) => {
try {
const { sectionId } = c.req.valid('param');
const section = await deleteCourseSectionService(sectionId);
return c.json({ success: true, data: section }, 200);
} catch (error) {
return handleError(c, error, 'Failed to delete course section');
}
}
)
.post('/reorder', authMiddleware, courseMemberMiddleware, zValidator('json', ZCourseSectionReorder), async (c) => {
try {
const { sections } = c.req.valid('json');
const updated = await reorderCourseSections(sections);
return c.json({ success: true, data: updated }, 200);
} catch (error) {
return handleError(c, error, 'Failed to reorder course sections');
}
});
+94
View File
@@ -0,0 +1,94 @@
import {
ZSubmissionAnswerUpdate,
ZSubmissionGetParam,
ZSubmissionGradesUpdate,
ZSubmissionUpdate
} from '@cio/utils/validation/submission';
import {
deleteSubmissionService,
listSubmissionsForGrading,
updateSubmissionAnswer,
updateSubmissionGradesBatch,
updateSubmissionService
} from '@api/services/submission';
import { Hono } from '@api/utils/hono';
import { courseTeamMemberMiddleware } from '@api/middlewares/course-team-member';
import { handleError } from '@api/utils/errors';
import { zValidator } from '@hono/zod-validator';
export const submissionRouter = new Hono()
.get('/for-grading', courseTeamMemberMiddleware, async (c) => {
try {
const courseId = c.req.param('courseId')!;
const data = await listSubmissionsForGrading(courseId);
return c.json({ success: true, data }, 200);
} catch (error) {
return handleError(c, error, 'Failed to list submissions for grading');
}
})
.put(
'/:submissionId',
courseTeamMemberMiddleware,
zValidator('param', ZSubmissionGetParam),
zValidator('json', ZSubmissionUpdate),
async (c) => {
try {
const { submissionId } = c.req.valid('param');
const data = c.req.valid('json');
const submission = await updateSubmissionService(submissionId, data);
return c.json({ success: true, data: submission }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update submission');
}
}
)
.delete('/:submissionId', courseTeamMemberMiddleware, zValidator('param', ZSubmissionGetParam), async (c) => {
try {
const { submissionId } = c.req.valid('param');
const submission = await deleteSubmissionService(submissionId);
return c.json({ success: true, data: submission }, 200);
} catch (error) {
return handleError(c, error, 'Failed to delete submission');
}
})
.put(
'/:submissionId/answer',
courseTeamMemberMiddleware,
zValidator('param', ZSubmissionGetParam),
zValidator('json', ZSubmissionAnswerUpdate),
async (c) => {
try {
const { submissionId } = c.req.valid('param');
const { questionId, ...data } = c.req.valid('json');
const answer = await updateSubmissionAnswer(submissionId, questionId, { questionId, ...data });
return c.json({ success: true, data: answer }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update submission answer');
}
}
)
.put(
'/:submissionId/grades',
courseTeamMemberMiddleware,
zValidator('param', ZSubmissionGetParam),
zValidator('json', ZSubmissionGradesUpdate),
async (c) => {
try {
const { submissionId } = c.req.valid('param');
const data = c.req.valid('json');
const submission = await updateSubmissionGradesBatch(submissionId, data);
return c.json({ success: true, data: submission }, 200);
} catch (error) {
return handleError(c, error, 'Failed to update submission grades');
}
}
);
+51
View File
@@ -0,0 +1,51 @@
import { addDomainToVercel, getConfigResponse, removeDomainFromVercelProject } from '@api/services/org/domain';
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { handleError } from '@api/utils/errors';
import { z } from 'zod';
const ZDomainRequest = z.object({
params: z.object({
key: z.enum(['verify_domain', 'add_domain', 'remove_domain']),
domain: z.string().min(1)
})
});
export const domainRouter = new Hono()
/**
* POST /domain
* Handles domain operations: verify, add, or remove domain
* Requires authentication
*/
.post('/', authMiddleware, async (c) => {
try {
const body = await c.req.json();
const validatedData = ZDomainRequest.parse(body);
const { key, domain } = validatedData.params;
if (domain.includes('classroomio.com')) {
return c.json({ success: false }, 400);
}
switch (key) {
case 'verify_domain': {
const configResponse = await getConfigResponse(domain);
return c.json({ success: true, verified: !configResponse.misconfigured }, 200);
}
case 'add_domain': {
const addDomainResponse = await addDomainToVercel(domain);
return c.json({ success: true, data: addDomainResponse }, 200);
}
case 'remove_domain': {
const removeDomainResponse = await removeDomainFromVercelProject(domain);
return c.json({ success: true, data: removeDomainResponse }, 200);
}
default:
return c.json({ success: false, message: 'Invalid request' }, 400);
}
} catch (error) {
return handleError(c, error, 'Failed to process domain request');
}
});
-1
View File
@@ -1 +0,0 @@
export * from './template';
-38
View File
@@ -1,38 +0,0 @@
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { ZTemplateById, ZTemplateByTag } from '@cio/utils/validation/mocks';
import { handleError } from '@api/utils/errors';
import { zValidator } from '@hono/zod-validator';
import { fetchAllTemplatesMetadata, fetchTemplateById, fetchTemplatesByTag } from '@api/services/exercise/template';
export const exerciseRouter = new Hono()
.get('/template', authMiddleware, async (c) => {
try {
const result = await fetchAllTemplatesMetadata();
return c.json({ success: true, data: result }, 200);
} catch (error) {
return handleError(c, error, 'Failed to load template metadata');
}
})
.get('/template/:id', authMiddleware, zValidator('param', ZTemplateById), async (c) => {
try {
const { id } = c.req.valid('param');
const result = await fetchTemplateById(id);
return c.json({ success: true, data: result }, 200);
} catch (error) {
return handleError(c, error, 'Failed to load template');
}
})
.get('/template/tag/:tag', authMiddleware, zValidator('param', ZTemplateByTag), async (c) => {
try {
const { tag } = c.req.valid('param');
const result = await fetchTemplatesByTag(tag);
return c.json({ success: true, data: result }, 200);
} catch (error) {
return handleError(c, error, 'Failed to load template');
}
});
+1
View File
@@ -0,0 +1 @@
export * from './invite';
+134
View File
@@ -0,0 +1,134 @@
import { ZCourseInviteTokenParam } from '@cio/utils/validation/course/invite';
import { previewStudentInvite } from '@api/services/course/invite';
import { ZOrganizationInviteTokenParam } from '@cio/utils/validation/organization/invite';
import { acceptOrganizationInvite, previewOrganizationInvite } from '@api/services/organization/invite';
import { Hono } from '@api/utils/hono';
import { apiKeyMiddleware } from '@api/middlewares/api-key';
import { authMiddleware } from '@api/middlewares/auth';
import { createRateLimiter } from '@api/middlewares/rate-limiter';
import { handleError } from '@api/utils/errors';
import { extractClientIp } from '@api/utils/redis/key-generators';
import { zValidator } from '@hono/zod-validator';
const previewInviteRateLimit = createRateLimiter({
windowMs: 60 * 1000,
maxRequests: 30,
message: 'Too many invite preview requests. Please try again later.',
keyGenerator: (c) => `invite_preview:${extractClientIp(c)}:${c.req.param('token')}`
});
const previewOrganizationInviteRateLimit = createRateLimiter({
windowMs: 60 * 1000,
maxRequests: 30,
message: 'Too many organization invite preview requests. Please try again later.',
keyGenerator: (c) => `org_invite_preview:${extractClientIp(c)}:${c.req.param('token')}`
});
const acceptOrganizationInviteRateLimit = createRateLimiter({
windowMs: 60 * 60 * 1000,
maxRequests: 20,
message: 'Too many organization invite join attempts. Please try again later.',
keyGenerator: (c) => {
const user = c.get('user');
const actor = user?.id ? `user:${user.id}` : `ip:${extractClientIp(c)}`;
return `org_invite_accept:${actor}:${c.req.param('token')}`;
}
});
export const inviteRouter = new Hono()
/**
* GET /invite/student/:token
* Server-only preview for secure invite links (API key). Returns course, org, invite for enroll page.
*/
.get(
'/student/:token',
apiKeyMiddleware,
previewInviteRateLimit,
zValidator('param', ZCourseInviteTokenParam),
async (c) => {
try {
const { token } = c.req.valid('param');
const preview = await previewStudentInvite(token, {
ipAddress: extractClientIp(c),
userAgent: c.req.header('user-agent') || null
});
return c.json(
{
success: true,
data: preview
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to load invite');
}
}
)
/**
* GET /invite/organization/:token/preview
* Server-only preview for organization role invites (API key)
*/
.get(
'/organization/:token/preview',
apiKeyMiddleware,
previewOrganizationInviteRateLimit,
zValidator('param', ZOrganizationInviteTokenParam),
async (c) => {
try {
const { token } = c.req.valid('param');
const preview = await previewOrganizationInvite(token, {
ipAddress: extractClientIp(c),
userAgent: c.req.header('user-agent') || null
});
return c.json(
{
success: true,
data: preview
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to load organization invite');
}
}
)
/**
* POST /invite/organization/:token/accept
* Authenticated organization role invite acceptance
*/
.post(
'/organization/:token/accept',
authMiddleware,
acceptOrganizationInviteRateLimit,
zValidator('param', ZOrganizationInviteTokenParam),
async (c) => {
try {
const { token } = c.req.valid('param');
const user = c.get('user')!;
const result = await acceptOrganizationInvite(
token,
{
id: user.id,
email: user.email
},
{
ipAddress: extractClientIp(c),
userAgent: c.req.header('user-agent') || null
}
);
return c.json(
{
success: true,
data: result
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to accept organization invite');
}
}
);
+30
View File
@@ -0,0 +1,30 @@
import { getLicenseStatus } from '@api/services/license';
import { Hono } from '@api/utils/hono';
import { authOrApiKeyMiddleware } from '@api/middlewares/auth-or-api-key';
import { handleError } from '@api/utils/errors';
export const licenseRouter = new Hono()
/**
* GET /license/features
* Returns the list of licensed features for the current instance.
* Used by the dashboard to gate UI (PostHog, Senja, SSO, token-auth, etc.).
* Accepts: User session OR API key (for server-side layout load)
*/
.get('/features', authOrApiKeyMiddleware, async (c) => {
try {
const status = await getLicenseStatus();
return c.json(
{
success: true,
data: {
valid: status.valid,
features: status.features,
expiresAt: status.expiresAt
}
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch license features');
}
});
+3 -3
View File
@@ -9,7 +9,7 @@ import { zValidator } from '@hono/zod-validator';
export const onboardingRouter = new Hono()
.post('/create-org', authMiddleware, zValidator('json', ZOnboardingCreateOrg), async (c) => {
try {
const user = c.get('user');
const user = c.get('user')!;
const { fullname, orgName, siteName } = c.req.valid('json');
const result = await createOrganizationWithOwner(user.id, { fullname, orgName, siteName });
@@ -21,7 +21,7 @@ export const onboardingRouter = new Hono()
})
.post('/update-metadata', authMiddleware, zValidator('json', ZOnboardingUpdateMetadata), async (c) => {
try {
const user = c.get('user');
const user = c.get('user')!;
const { goal, source, fullname } = c.req.valid('json');
const result = await updateUserOnboarding(user.id, { goal, source, fullname });
@@ -33,7 +33,7 @@ export const onboardingRouter = new Hono()
})
.post('/complete', authMiddleware, async (c) => {
try {
const user = c.get('user');
const user = c.get('user')!;
await completeOnboarding(user);
+303
View File
@@ -0,0 +1,303 @@
import {
ZAssetAttach,
ZAssetCreateUpload,
ZAssetDetach,
ZAssetExportQuery,
ZAssetGetParam,
ZAssetListQuery,
ZAssetStorageQuery,
ZAssetUpdate,
ZAssetUsageParams,
ZYouTubeMetadataQuery
} from '@cio/utils/validation/assets';
import {
attachAssetService,
createAssetFromUploadService,
deleteAssetService,
detachAssetService,
exportOrganizationAssetsService,
getAssetService,
getAssetUsageGraphService,
getOrganizationAssetStorageService,
getYouTubeMetadataService,
listOrganizationAssetsService,
updateAssetService
} from '@api/services/assets';
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { handleError } from '@api/utils/errors';
import { orgAdminMiddleware } from '@api/middlewares/org-admin';
import { orgMemberMiddleware } from '@api/middlewares/org-member';
import { zValidator } from '@hono/zod-validator';
export const assetsRouter = new Hono()
/**
* GET /organization/assets
* List organization assets
*/
.get('/', authMiddleware, orgMemberMiddleware, zValidator('query', ZAssetListQuery), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const query = c.req.valid('query');
const result = await listOrganizationAssetsService(orgId, query);
return c.json(
{
success: true,
data: result.items,
pagination: {
page: result.page,
limit: result.limit,
total: result.total,
totalPages: result.totalPages
}
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to list assets');
}
})
/**
* POST /organization/assets
* Create or reuse an organization asset
*/
.post('/', authMiddleware, orgMemberMiddleware, zValidator('json', ZAssetCreateUpload), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const user = c.get('user')!;
const data = c.req.valid('json');
const asset = await createAssetFromUploadService(orgId, user.id, data);
return c.json(
{
success: true,
data: asset
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to create asset');
}
})
/**
* GET /organization/assets/export
* Export organization assets with usage graph
*/
.get('/export', authMiddleware, orgAdminMiddleware, zValidator('query', ZAssetExportQuery), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const query = c.req.valid('query');
const result = await exportOrganizationAssetsService(orgId, query);
return c.json(
{
success: true,
data: result
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to export assets');
}
})
/**
* GET /organization/assets/storage
* Return storage metrics for the current organization
*/
.get('/storage', authMiddleware, orgMemberMiddleware, zValidator('query', ZAssetStorageQuery), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const query = c.req.valid('query');
const summary = await getOrganizationAssetStorageService(orgId, query);
return c.json(
{
success: true,
data: summary
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch asset storage summary');
}
})
/**
* GET /organization/assets/youtube-metadata
* Resolve YouTube metadata (title, duration, thumbnail) for a URL
*/
.get(
'/youtube-metadata',
authMiddleware,
orgMemberMiddleware,
zValidator('query', ZYouTubeMetadataQuery),
async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const query = c.req.valid('query');
const metadata = await getYouTubeMetadataService(orgId, query);
return c.json(
{
success: true,
data: metadata
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to resolve YouTube metadata');
}
}
)
/**
* GET /organization/assets/:assetId
* Get a single asset by id
*/
.get('/:assetId', authMiddleware, orgMemberMiddleware, zValidator('param', ZAssetGetParam), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { assetId } = c.req.valid('param');
const asset = await getAssetService(orgId, assetId);
return c.json(
{
success: true,
data: asset
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch asset');
}
})
/**
* PUT /organization/assets/:assetId
* Update asset metadata
*/
.put(
'/:assetId',
authMiddleware,
orgMemberMiddleware,
zValidator('param', ZAssetGetParam),
zValidator('json', ZAssetUpdate),
async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { assetId } = c.req.valid('param');
const data = c.req.valid('json');
const updated = await updateAssetService(orgId, assetId, data);
return c.json(
{
success: true,
data: updated
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to update asset');
}
}
)
/**
* DELETE /organization/assets/:assetId
* Delete an unused asset
*/
.delete('/:assetId', authMiddleware, orgAdminMiddleware, zValidator('param', ZAssetGetParam), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { assetId } = c.req.valid('param');
const deleted = await deleteAssetService(orgId, assetId);
return c.json(
{
success: true,
data: deleted
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to delete asset');
}
})
/**
* GET /organization/assets/:assetId/usage
* Get usage graph for an asset
*/
.get('/:assetId/usage', authMiddleware, orgMemberMiddleware, zValidator('param', ZAssetUsageParams), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { assetId } = c.req.valid('param');
const usage = await getAssetUsageGraphService(orgId, assetId);
return c.json(
{
success: true,
data: usage
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch asset usage');
}
})
/**
* POST /organization/assets/:assetId/attach
* Attach asset to a target location
*/
.post(
'/:assetId/attach',
authMiddleware,
orgMemberMiddleware,
zValidator('param', ZAssetUsageParams),
zValidator('json', ZAssetAttach),
async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const user = c.get('user')!;
const { assetId } = c.req.valid('param');
const data = c.req.valid('json');
const usage = await attachAssetService(orgId, assetId, user.id, data);
return c.json(
{
success: true,
data: usage
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to attach asset');
}
}
)
/**
* POST /organization/assets/:assetId/detach
* Remove an asset usage link
*/
.post(
'/:assetId/detach',
authMiddleware,
orgMemberMiddleware,
zValidator('param', ZAssetUsageParams),
zValidator('json', ZAssetDetach),
async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { assetId } = c.req.valid('param');
const data = c.req.valid('json');
const usage = await detachAssetService(orgId, assetId, data);
return c.json(
{
success: true,
data: usage
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to detach asset');
}
}
);
@@ -1 +1,4 @@
export * from './organization';
export * from './assets';
export * from './tags';
export * from './token-auth';
+259 -93
View File
@@ -4,25 +4,29 @@ import {
ZCreateOrganization,
ZGetCoursesBySiteName,
ZGetOrgSetup,
ZGetOrganizationAudience,
ZGetOrganizationTeam,
ZGetOrganizationCoursesQuery,
ZGetOrganizations,
ZGetUserAnalytics,
ZInviteTeamMembers,
ZLMSExercisesParam,
ZRemoveTeamMember,
ZUpdateOrgPlan,
ZUpdateOrganization,
ZUpdateOrganizationParam
ZUpdateOrganization
} from '@cio/utils/validation/organization';
import {
cancelOrgPlan,
createOrg,
createOrgPlan,
getCoursesByOrgSiteName,
getFirstOrgForSelfHosted,
getOrgAudience,
getOrgSetupData,
getOrgTeam,
getOrganizationCourses,
getOrganizationsWithFilters,
inviteTeamMembers,
getPublicCourses,
getRecommendedCourses,
getUserAnalytics,
getUserEnrolledCourses,
removeTeamMember,
updateOrg,
updateOrgPlan
@@ -30,11 +34,16 @@ import {
import { Hono } from '@api/utils/hono';
import { TOrganization } from '@db/types';
import { assetsRouter } from '@api/routes/organization/assets';
import { authMiddleware } from '@api/middlewares/auth';
import { authOrApiKeyMiddleware } from '@api/middlewares/auth-or-api-key';
import { getLMSExercisesService } from '@api/services/exercise';
import { handleError } from '@api/utils/errors';
import { inviteTeamMembers } from '@api/services/organization/invite';
import { orgAdminMiddleware } from '@api/middlewares/org-admin';
import { orgMemberMiddleware } from '@api/middlewares/org-member';
import { quizRouter } from '@api/routes/organization/quiz';
import { tagsRouter } from '@api/routes/organization/tags';
import { zValidator } from '@hono/zod-validator';
export const organizationRouter = new Hono()
@@ -47,7 +56,6 @@ export const organizationRouter = new Hono()
.get('/', authOrApiKeyMiddleware, zValidator('query', ZGetOrganizations), async (c) => {
try {
const filters = c.req.valid('query');
console.log('filters', filters);
const organizations = await getOrganizationsWithFilters(filters);
return c.json(
@@ -63,13 +71,32 @@ export const organizationRouter = new Hono()
}
})
/**
* GET /organization/:orgId/team
* GET /organization/first
* Gets the first organization (for self-hosted single-org mode). Requires API key.
*/
.get('/first', authOrApiKeyMiddleware, async (c) => {
try {
const org = await getFirstOrgForSelfHosted();
return c.json(
{
success: true,
data: org ? [org] : []
},
200
);
} catch (error) {
console.error('Error fetching first organization:', error);
return handleError(c, error, 'Failed to fetch first organization');
}
})
/**
* GET /organization/team
* Gets organization team members (non-students)
* Requires authentication
*/
.get('/:orgId/team', authMiddleware, orgMemberMiddleware, zValidator('param', ZGetOrganizationTeam), async (c) => {
.get('/team', authMiddleware, orgMemberMiddleware, async (c) => {
try {
const { orgId } = c.req.valid('param');
const orgId = c.req.header('cio-org-id')!;
const team = await getOrgTeam(orgId);
return c.json(
@@ -84,111 +111,217 @@ export const organizationRouter = new Hono()
}
})
/**
* POST /organization/:orgId/team/invite
* POST /organization/team/invite
* Invites team members to an organization
* Requires authentication and admin role
*/
.post(
'/:orgId/team/invite',
authMiddleware,
orgAdminMiddleware,
zValidator('param', ZGetOrganizationTeam),
zValidator('json', ZInviteTeamMembers),
async (c) => {
try {
const { orgId } = c.req.valid('param');
const { emails, roleId } = c.req.valid('json');
.post('/team/invite', authMiddleware, orgAdminMiddleware, zValidator('json', ZInviteTeamMembers), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const user = c.get('user')!;
const { emails, roleId } = c.req.valid('json');
const members = await inviteTeamMembers(orgId, emails, roleId);
const members = await inviteTeamMembers(orgId, emails, roleId, user.id);
return c.json(
{
success: true,
data: members
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to invite team members');
}
return c.json(
{
success: true,
data: members
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to invite team members');
}
)
})
/**
* DELETE /organization/:orgId/team/:memberId
* DELETE /organization/team/:memberId
* Removes a team member from an organization
* Requires authentication and admin role
*/
.delete(
'/:orgId/team/:memberId',
authMiddleware,
orgAdminMiddleware,
zValidator('param', ZRemoveTeamMember),
async (c) => {
try {
const { orgId, memberId } = c.req.valid('param');
.delete('/team/:memberId', authMiddleware, orgAdminMiddleware, zValidator('param', ZRemoveTeamMember), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const user = c.get('user')!;
const { memberId } = c.req.valid('param');
await removeTeamMember(orgId, memberId);
await removeTeamMember(orgId, memberId, user.id);
return c.json(
{
success: true
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to remove team member');
}
return c.json(
{
success: true
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to remove team member');
}
)
})
/**
* GET /organization/:orgId/audience
* GET /organization/audience
* Gets organization audience (students)
* Requires authentication
*/
.get('/audience', authMiddleware, orgMemberMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const audience = await getOrgAudience(orgId);
return c.json(
{
success: true,
data: audience
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch organization audience');
}
})
/**
* GET /organization/audience/:userId/analytics
* Gets user analytics for a specific user in an organization
* Requires authentication and organization membership
*/
.get(
'/:orgId/audience',
'/audience/:userId/analytics',
authMiddleware,
orgMemberMiddleware,
zValidator('param', ZGetOrganizationAudience),
zValidator('param', ZGetUserAnalytics),
async (c) => {
try {
const { orgId } = c.req.valid('param');
const audience = await getOrgAudience(orgId);
const orgId = c.req.header('cio-org-id')!;
const { userId } = c.req.valid('param');
const analytics = await getUserAnalytics(userId, orgId);
return c.json(
{
success: true,
data: audience
data: analytics
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch organization audience');
return handleError(c, error, 'Failed to fetch user analytics');
}
}
)
/**
* GET /organization/courses
* Gets courses by organization siteName
* GET /organization/courses/public
* Gets published courses for an organization (public landing page)
* Query params: siteName (string)
* No authentication required - returns only published courses
*/
.get('/courses/public', zValidator('query', ZGetCoursesBySiteName), async (c) => {
try {
const { siteName, tags } = c.req.valid('query');
const tagSlugs = tags
?.split(',')
.map((value) => value.trim())
.filter(Boolean);
const courses = await getPublicCourses(siteName, tagSlugs && tagSlugs.length > 0 ? tagSlugs : undefined);
return c.json(
{
success: true,
data: courses
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch public courses');
}
})
/**
* GET /organization/courses/enrolled
* Gets enrolled courses for a user in an organization (used in lms)
* Requires authentication and organization membership
*/
.get('/courses/enrolled', authMiddleware, orgMemberMiddleware, async (c) => {
try {
const user = c.get('user')!;
const orgId = c.req.header('cio-org-id')!;
const result = await getUserEnrolledCourses(orgId, user.id);
return c.json(
{
success: true,
data: result
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch courses');
}
})
/**
* GET /organization/courses/recommended
* Gets recommended courses (published courses user isn't enrolled in) for a user in an organization (used in lms)
* Requires authentication and organization membership
*/
.get('/courses/recommended', authMiddleware, orgMemberMiddleware, async (c) => {
try {
const user = c.get('user')!;
const orgId = c.req.header('cio-org-id')!;
const result = await getRecommendedCourses(orgId, user.id);
return c.json(
{
success: true,
data: result
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch recommended courses');
}
})
/**
* GET /organization/courses
* Gets courses for an organization with role-based filtering (used in dashboard)
* Requires authentication and organization membership
*/
.get(
'/courses',
// TODO: Ratelimit this endpoint
// TODO: Add cache
// TODO: Add pagination
// TODO: Add sorting
// TODO: Add filtering
zValidator('query', ZGetCoursesBySiteName),
authMiddleware,
orgMemberMiddleware,
zValidator('query', ZGetOrganizationCoursesQuery),
async (c) => {
try {
const { siteName } = c.req.valid('query');
const courses = await getCoursesByOrgSiteName(siteName);
const user = c.get('user')!;
const orgId = c.get('orgId');
const userRole = c.get('userRole');
const { tags } = c.req.valid('query');
if (!orgId || userRole === null) {
return c.json(
{
success: false,
error: 'Organization context not available',
code: 'ORG_CONTEXT_MISSING'
},
500
);
}
const tagSlugs = tags
?.split(',')
.map((value) => value.trim())
.filter(Boolean);
const result = await getOrganizationCourses(
orgId,
user.id,
userRole,
tagSlugs && tagSlugs.length > 0 ? tagSlugs : undefined
);
return c.json(
{
success: true,
data: courses
data: result
},
200
);
@@ -288,7 +421,7 @@ export const organizationRouter = new Hono()
*/
.post('/', authMiddleware, zValidator('json', ZCreateOrganization), async (c) => {
try {
const user = c.get('user');
const user = c.get('user')!;
const data = c.req.valid('json');
const result = await createOrg(user.id, data);
@@ -305,36 +438,69 @@ export const organizationRouter = new Hono()
}
})
/**
* PUT /organization/:orgId
* PUT /organization
* Updates an organization (name, avatarUrl)
* Requires authentication
*/
.put(
'/:orgId',
authMiddleware,
orgAdminMiddleware,
zValidator('param', ZUpdateOrganizationParam),
zValidator('json', ZUpdateOrganization),
async (c) => {
try {
console.log('updateOrg');
console.log(c.req.valid('param'));
console.log(c.req.valid('json'));
const { orgId } = c.req.valid('param');
.put('/', authMiddleware, orgAdminMiddleware, zValidator('json', ZUpdateOrganization), async (c) => {
try {
console.log('updateOrg');
console.log(c.req.valid('json'));
const orgId = c.req.header('cio-org-id')!;
const data = c.req.valid('json') as Partial<TOrganization>;
const data = c.req.valid('json') as Partial<TOrganization>;
const organization = await updateOrg(orgId, data);
const organization = await updateOrg(orgId, data);
return c.json(
{
success: true,
data: organization
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to update organization');
}
})
/**
* GET /organization/:orgId/exercises/lms
* Gets exercises with submissions for a student in an organization
* Returns exercises from unlocked lessons in courses where the student is a member
* Requires authentication and organization membership
*/
.get('/:orgId/exercises/lms', authMiddleware, zValidator('param', ZLMSExercisesParam), async (c) => {
try {
const { orgId } = c.req.valid('param');
const user = c.get('user')!;
// Check org membership manually since middleware expects header
const { getUserOrgRole } = await import('@cio/db/queries/organization');
const roleId = await getUserOrgRole(orgId, user.id);
if (roleId === null) {
return c.json(
{
success: true,
data: organization
success: false,
error: 'UNAUTHORIZED',
code: 'UNAUTHORIZED'
},
200
403
);
} catch (error) {
return handleError(c, error, 'Failed to update organization');
}
const exercises = await getLMSExercisesService(user.id, orgId);
return c.json(
{
success: true,
data: exercises
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch LMS exercises');
}
);
})
.route('/tags', tagsRouter)
.route('/assets', assetsRouter)
.route('/:orgId/quiz', quizRouter);
+143
View File
@@ -0,0 +1,143 @@
import { ZQuizCreate, ZQuizGetParam, ZQuizListParam, ZQuizUpdate } from '@cio/utils/validation/organization';
import { createQuizService, deleteQuizService, getQuiz, listQuizzes, updateQuizService } from '@api/services/quiz';
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { handleError } from '@api/utils/errors';
import { orgMemberMiddleware } from '@api/middlewares/org-member';
import { zValidator } from '@hono/zod-validator';
export const quizRouter = new Hono()
/**
* GET /organization/:orgId/quiz
* Gets all quizzes for an organization
* Requires authentication and organization membership
*/
.get('/', authMiddleware, orgMemberMiddleware, zValidator('param', ZQuizListParam), async (c) => {
try {
const { orgId } = c.req.valid('param');
const quizzes = await listQuizzes(orgId);
return c.json(
{
success: true,
data: quizzes
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch quizzes');
}
})
/**
* GET /organization/:orgId/quiz/:quizId
* Gets a single quiz by ID
* Requires authentication and organization membership
*/
.get('/:quizId', authMiddleware, orgMemberMiddleware, zValidator('param', ZQuizGetParam), async (c) => {
try {
const { quizId } = c.req.valid('param');
const quiz = await getQuiz(quizId);
if (!quiz) {
return c.json(
{
success: false,
error: 'Quiz not found'
},
404
);
}
return c.json(
{
success: true,
data: quiz
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch quiz');
}
})
/**
* POST /organization/:orgId/quiz
* Creates a new quiz
* Requires authentication and organization membership
*/
.post(
'/',
authMiddleware,
orgMemberMiddleware,
zValidator('param', ZQuizListParam),
zValidator('json', ZQuizCreate),
async (c) => {
try {
const { orgId } = c.req.valid('param');
const data = c.req.valid('json');
const quiz = await createQuizService(orgId, data);
return c.json(
{
success: true,
data: quiz
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to create quiz');
}
}
)
/**
* PUT /organization/:orgId/quiz/:quizId
* Updates a quiz
* Requires authentication and organization membership
*/
.put(
'/:quizId',
authMiddleware,
orgMemberMiddleware,
zValidator('param', ZQuizGetParam),
zValidator('json', ZQuizUpdate),
async (c) => {
try {
const { quizId } = c.req.valid('param');
const data = c.req.valid('json');
const quiz = await updateQuizService(quizId, data);
return c.json(
{
success: true,
data: quiz
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to update quiz');
}
}
)
/**
* DELETE /organization/:orgId/quiz/:quizId
* Deletes a quiz
* Requires authentication and organization membership
*/
.delete('/:quizId', authMiddleware, orgMemberMiddleware, zValidator('param', ZQuizGetParam), async (c) => {
try {
const { quizId } = c.req.valid('param');
await deleteQuizService(quizId);
return c.json(
{
success: true
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to delete quiz');
}
});
+175
View File
@@ -0,0 +1,175 @@
import { ZCreateSsoConnection, ZUpdateSsoConnection, ZUpdateSsoPolicy } from '@cio/utils/validation/organization/sso';
import {
activateSsoConnection,
createSsoConnection,
deleteSsoConnection,
getSsoConnection,
updateSsoConnection,
updateSsoPolicy
} from '@api/services/organization/sso';
import { Hono } from '@api/utils/hono';
import { auth } from '@cio/db/auth';
import { LICENSE_FEATURE } from '@cio/utils/license';
import { authMiddleware } from '@api/middlewares/auth';
import { handleError } from '@api/utils/errors';
import { requireLicense } from '@api/middlewares/license';
import { orgAdminMiddleware } from '@api/middlewares/org-admin';
import { zValidator } from '@hono/zod-validator';
export const organizationSsoRouter = new Hono()
.use('*', requireLicense(LICENSE_FEATURE.SSO))
/**
* GET /organization/sso
* Get SSO connection and policy for current org
* Requires: Admin role
*/
.get('/', authMiddleware, orgAdminMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const result = await getSsoConnection(orgId);
return c.json({
success: true,
data: result
});
} catch (error) {
return handleError(c, error, 'Failed to fetch SSO configuration');
}
})
/**
* POST /organization/sso
* Create new SSO connection
* Requires: Admin role
*/
.post('/', authMiddleware, orgAdminMiddleware, zValidator('json', ZCreateSsoConnection), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const user = c.get('user')!;
const data = c.req.valid('json');
const result = await createSsoConnection(
orgId,
data,
user.id,
auth.api as unknown as { registerSSOProvider: (args: unknown) => Promise<unknown> },
c.req.raw.headers
);
return c.json(
{
success: true,
data: result
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to create SSO connection');
}
})
/**
* PUT /organization/sso
* Update SSO connection metadata
* Requires: Admin role
*/
.put('/', authMiddleware, orgAdminMiddleware, zValidator('json', ZUpdateSsoConnection), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const user = c.get('user')!;
const data = c.req.valid('json');
const result = await updateSsoConnection(orgId, data, user.id);
return c.json({
success: true,
data: result
});
} catch (error) {
return handleError(c, error, 'Failed to update SSO connection');
}
})
/**
* DELETE /organization/sso
* Delete SSO connection
* Requires: Admin role
*/
.delete('/', authMiddleware, orgAdminMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
await deleteSsoConnection(
orgId,
auth.api as unknown as { deleteSSOProvider: (args: unknown) => Promise<unknown> }
);
return c.json({
success: true
});
} catch (error) {
return handleError(c, error, 'Failed to delete SSO connection');
}
})
/**
* POST /organization/sso/activate
* Activate SSO connection
* Requires: Admin role
*/
.post('/activate', authMiddleware, orgAdminMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const user = c.get('user')!;
const result = await activateSsoConnection(orgId, user.id);
return c.json({
success: true,
data: result
});
} catch (error) {
return handleError(c, error, 'Failed to activate SSO connection');
}
})
/**
* GET /organization/sso/policy
* Get SSO policy for current org
* Requires: Admin role
*/
.get('/policy', authMiddleware, orgAdminMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const result = await getSsoConnection(orgId);
return c.json({
success: true,
data: result?.policy ?? null
});
} catch (error) {
return handleError(c, error, 'Failed to fetch SSO policy');
}
})
/**
* PUT /organization/sso/policy
* Update SSO policy
* Requires: Admin role
*/
.put('/policy', authMiddleware, orgAdminMiddleware, zValidator('json', ZUpdateSsoPolicy), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const data = c.req.valid('json');
const result = await updateSsoPolicy(orgId, data);
return c.json({
success: true,
data: result
});
} catch (error) {
return handleError(c, error, 'Failed to update SSO policy');
}
});
+141
View File
@@ -0,0 +1,141 @@
import {
ZTagCreate,
ZTagGroupCreate,
ZTagGroupParam,
ZTagGroupUpdate,
ZTagParam,
ZTagUpdate
} from '@cio/utils/validation/tag';
import {
createOrganizationTag,
createOrganizationTagGroup,
getPublicOrganizationTagGroups,
getOrganizationTagGroups,
updateOrganizationTag,
updateOrganizationTagGroup
} from '@api/services/tag';
import { ZGetCoursesBySiteName } from '@cio/utils/validation/organization';
import { Hono } from '@api/utils/hono';
import { authMiddleware } from '@api/middlewares/auth';
import { handleError } from '@api/utils/errors';
import { orgAdminMiddleware } from '@api/middlewares/org-admin';
import { zValidator } from '@hono/zod-validator';
export const tagsRouter = new Hono()
.get('/public', zValidator('query', ZGetCoursesBySiteName), async (c) => {
try {
const { siteName } = c.req.valid('query');
const groups = await getPublicOrganizationTagGroups(siteName);
return c.json(
{
success: true,
data: groups
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch public tags');
}
})
.get('/', authMiddleware, orgAdminMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const groups = await getOrganizationTagGroups(orgId);
return c.json(
{
success: true,
data: groups
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch tags');
}
})
.post('/groups', authMiddleware, orgAdminMiddleware, zValidator('json', ZTagGroupCreate), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const data = c.req.valid('json');
const group = await createOrganizationTagGroup(orgId, data);
return c.json(
{
success: true,
data: group
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to create tag group');
}
})
.put(
'/groups/:groupId',
authMiddleware,
orgAdminMiddleware,
zValidator('param', ZTagGroupParam),
zValidator('json', ZTagGroupUpdate),
async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { groupId } = c.req.valid('param');
const data = c.req.valid('json');
const group = await updateOrganizationTagGroup(orgId, groupId, data);
return c.json(
{
success: true,
data: group
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to update tag group');
}
}
)
.post('/', authMiddleware, orgAdminMiddleware, zValidator('json', ZTagCreate), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const data = c.req.valid('json');
const tag = await createOrganizationTag(orgId, data);
return c.json(
{
success: true,
data: tag
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to create tag');
}
})
.put(
'/:tagId',
authMiddleware,
orgAdminMiddleware,
zValidator('param', ZTagParam),
zValidator('json', ZTagUpdate),
async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { tagId } = c.req.valid('param');
const data = c.req.valid('json');
const tag = await updateOrganizationTag(orgId, tagId, data);
return c.json(
{
success: true,
data: tag
},
200
);
} catch (error) {
return handleError(c, error, 'Failed to update tag');
}
}
);
@@ -0,0 +1,116 @@
import {
activateTokenAuth,
createTokenAuthConfig,
deleteTokenAuthConfig,
getTokenAuthStatus,
rotateTokenAuthSecret
} from '@api/services/organization/token-auth';
import { Hono } from '@api/utils/hono';
import { LICENSE_FEATURE } from '@cio/utils/license';
import { authMiddleware } from '@api/middlewares/auth';
import { handleError } from '@api/utils/errors';
import { requireLicense } from '@api/middlewares/license';
import { orgAdminMiddleware } from '@api/middlewares/org-admin';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
const ZActivateBody = z.object({ isActive: z.boolean() });
export const organizationTokenAuthRouter = new Hono()
.use('*', requireLicense(LICENSE_FEATURE.TOKEN_AUTH))
/**
* GET /organization/token-auth
* Get token auth status (never returns full secret)
*/
.get('/', authMiddleware, orgAdminMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const result = await getTokenAuthStatus(orgId);
if (!result) {
return c.json({ success: true, data: null });
}
return c.json({ success: true, data: result });
} catch (error) {
return handleError(c, error, 'Failed to fetch token auth status');
}
})
/**
* POST /organization/token-auth
* Create token auth config (generate secret). Returns secret once.
*/
.post('/', authMiddleware, orgAdminMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const user = c.get('user')!;
const { secret, config } = await createTokenAuthConfig(orgId, user.id);
return c.json(
{
success: true,
data: {
id: config.id,
organizationId: config.organizationId,
isActive: config.isActive,
createdAt: config.createdAt,
secret
}
},
201
);
} catch (error) {
return handleError(c, error, 'Failed to create token auth');
}
})
/**
* POST /organization/token-auth/rotate
* Rotate signing secret. Returns new secret once.
*/
.post('/rotate', authMiddleware, orgAdminMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { secret } = await rotateTokenAuthSecret(orgId);
return c.json({ success: true, data: { secret } });
} catch (error) {
return handleError(c, error, 'Failed to rotate token auth secret');
}
})
/**
* DELETE /organization/token-auth
* Remove token auth config
*/
.delete('/', authMiddleware, orgAdminMiddleware, async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
await deleteTokenAuthConfig(orgId);
return c.json({ success: true });
} catch (error) {
return handleError(c, error, 'Failed to delete token auth');
}
})
/**
* PUT /organization/token-auth/activate
* Toggle active/inactive
*/
.put('/activate', authMiddleware, orgAdminMiddleware, zValidator('json', ZActivateBody), async (c) => {
try {
const orgId = c.req.header('cio-org-id')!;
const { isActive } = c.req.valid('json');
const result = await activateTokenAuth(orgId, isActive);
return c.json({ success: true, data: result });
} catch (error) {
return handleError(c, error, 'Failed to update token auth activation');
}
});
+44
View File
@@ -0,0 +1,44 @@
import { ZSsoDiscoveryQuery } from '@cio/utils/validation/organization/sso';
import { discoverSso, getOrgSsoInfo } from '@api/services/auth/sso';
import { Hono } from '@api/utils/hono';
import { handleError } from '@api/utils/errors';
import { zValidator } from '@hono/zod-validator';
export const ssoDiscoveryRouter = new Hono()
/**
* GET /sso/[email protected]
* Public endpoint to discover SSO for an email address
*/
.get('/discover', zValidator('query', ZSsoDiscoveryQuery), async (c) => {
try {
const { email } = c.req.valid('query');
const result = await discoverSso(email);
return c.json({
success: true,
data: result
});
} catch (error) {
return handleError(c, error, 'Failed to discover SSO');
}
})
/**
* GET /sso/org/:orgId
* Get SSO info for a specific organization
* Used when org context is known (e.g., custom domain login)
*/
.get('/org/:orgId', async (c) => {
try {
const orgId = c.req.param('orgId');
const result = await getOrgSsoInfo(orgId);
return c.json({
success: true,
data: result
});
} catch (error) {
return handleError(c, error, 'Failed to get organization SSO info');
}
});
+42
View File
@@ -0,0 +1,42 @@
import { Hono } from '@api/utils/hono';
import { env } from '@api/config/env';
import { handleError } from '@api/utils/errors';
import { z } from 'zod';
const ZUnsplashRequest = z.object({
searchQuery: z.string().optional()
});
export const unsplashRouter = new Hono()
/**
* POST /unsplash
* Fetches photos from Unsplash API
* No authentication required - public route
*/
.post('/', async (c) => {
try {
const body = await c.req.json();
const validatedData = ZUnsplashRequest.parse(body);
const query = validatedData.searchQuery || 'rocks';
const UNSPLASH_API_URL = `https://api.unsplash.com/search/photos?page=2&per_page=15&auto=format&fit=crop&w=2970&q=80&client_id=${env.UNSPLASH_API_KEY}`;
const response = await fetch(`${UNSPLASH_API_URL}&query=${encodeURIComponent(query)}`, {
method: 'GET'
});
if (!response.ok) {
throw new Error('Unable to fetch photos from Unsplash API');
}
const data = await response.json();
return c.json({
success: true,
photos: data.results
});
} catch (error) {
console.error('Error fetching photos from Unsplash', error);
return handleError(c, error, 'Error fetching photos from Unsplash');
}
});
+57 -5
View File
@@ -1,24 +1,58 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import { getProfileById, updateProfile } from '@cio/db/queries/auth';
import { getProfileByEmail, getProfileById, updateProfile } from '@cio/db/queries/auth';
import { getLicenseStatus } from '@api/services/license';
import type { OrganizationWithMemberAndPlans } from '@cio/db/queries/organization/types';
import type { TProfile } from '@cio/db/types';
import { getOrganizationByProfileId } from '@cio/db/queries/organization';
import {
createOrganizationMember,
getFirstOrganization,
getOrganizationByProfileId
} from '@cio/db/queries/organization';
import { env } from '@api/config/env';
import { ROLE } from '@cio/utils/constants';
export type GetAccountDataResult = {
profile: TProfile;
organizations: OrganizationWithMemberAndPlans[];
licenseFeatures: string[];
};
/**
* Fetches account data including profile and organizations for a user
* In self-hosted mode: auto-adds non-member users as students to the single org
* @param userId - The user ID to fetch account data for
* @returns Account data with profile and organizations
*/
export async function getAccountData(userId: string) {
const [profile, organizations] = await Promise.all([getProfileById(userId), getOrganizationByProfileId(userId)]);
export async function getAccountData(userId: string): Promise<GetAccountDataResult> {
let [profile, organizations, licenseStatus] = await Promise.all([
getProfileById(userId),
getOrganizationByProfileId(userId),
getLicenseStatus()
]);
if (!profile) {
throw new AppError(`Account not found for user ID: ${userId}`, ErrorCodes.ACCOUNT_NOT_FOUND, 404);
}
// Self-hosted: auto-add user as student to the single org if they are not a member
if (env.PUBLIC_IS_SELFHOSTED === 'true' && organizations.length === 0) {
const firstOrg = await getFirstOrganization();
if (firstOrg) {
await createOrganizationMember({
organizationId: firstOrg.id,
profileId: userId,
roleId: ROLE.STUDENT,
verified: true
});
organizations = await getOrganizationByProfileId(userId);
}
}
return {
profile,
organizations
organizations,
licenseFeatures: licenseStatus.features
};
}
@@ -57,3 +91,21 @@ export async function updateUser(
);
}
}
/**
* Gets profile by email
* @param email - The email address
* @returns Profile or null if not found
*/
export async function getProfileByEmailService(email: string): Promise<TProfile | null> {
try {
const profile = await getProfileByEmail(email);
return profile;
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch profile by email',
ErrorCodes.PROFILE_NOT_FOUND,
500
);
}
}
+426
View File
@@ -0,0 +1,426 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import type {
TAssetAttach,
TAssetCreateUpload,
TAssetDetach,
TAssetExportQuery,
TAssetListQuery,
TAssetStorageQuery,
TAssetUpdate,
TYouTubeMetadataQuery
} from '@cio/utils/validation/assets';
import {
countAssetUsagesByAsset,
createAssetUsage,
createOrGetAssetByStorageKey,
deleteAsset,
deleteAssetUsage,
getAssetById,
getAssetStorageSummaryByOrg,
listAssetsByOrg,
listAssetsForExport,
listAssetUsagesByAsset,
updateAsset
} from '@cio/db/queries/assets';
const YOUTUBE_VIDEO_ID_REGEX = /^[a-zA-Z0-9_-]{11}$/;
type YouTubeOEmbedResponse = {
title?: unknown;
thumbnail_url?: unknown;
};
type YouTubeWatchPageMetadata = {
title: string | null;
durationSeconds: number | null;
thumbnailUrl: string | null;
};
function assertAssetExists<T>(asset: T | null): T {
if (!asset) {
throw new AppError('Asset not found', ErrorCodes.ASSET_NOT_FOUND, 404);
}
return asset;
}
function normalizeUrl(url: string): URL | null {
const trimmed = url.trim();
if (!trimmed) {
return null;
}
try {
return new URL(trimmed);
} catch {
try {
return new URL(`https://${trimmed}`);
} catch {
return null;
}
}
}
function extractYouTubeVideoId(url: string): string | null {
const parsedUrl = normalizeUrl(url);
if (!parsedUrl) {
return null;
}
const host = parsedUrl.hostname.toLowerCase();
let videoId: string | null = null;
if (host === 'youtu.be' || host === 'www.youtu.be') {
const [pathSegment] = parsedUrl.pathname.split('/').filter(Boolean);
videoId = pathSegment ?? null;
} else if (
host === 'youtube.com' ||
host === 'www.youtube.com' ||
host === 'm.youtube.com' ||
host === 'music.youtube.com' ||
host === 'youtube-nocookie.com' ||
host === 'www.youtube-nocookie.com'
) {
if (parsedUrl.pathname === '/watch') {
videoId = parsedUrl.searchParams.get('v');
} else {
const [firstSegment, secondSegment] = parsedUrl.pathname.split('/').filter(Boolean);
if (firstSegment === 'embed' || firstSegment === 'shorts' || firstSegment === 'live') {
videoId = secondSegment ?? null;
}
}
}
if (!videoId || !YOUTUBE_VIDEO_ID_REGEX.test(videoId)) {
return null;
}
return videoId;
}
function decodeHtmlEntities(value: string): string {
return value
.replaceAll('&amp;', '&')
.replaceAll('&quot;', '"')
.replaceAll('&#39;', "'")
.replaceAll('&#x27;', "'")
.replaceAll('&lt;', '<')
.replaceAll('&gt;', '>');
}
function extractMetaContent(html: string, pattern: RegExp): string | null {
const match = html.match(pattern);
const value = match?.[1];
if (!value) {
return null;
}
const decoded = decodeHtmlEntities(value.trim());
return decoded.length ? decoded : null;
}
function extractDurationSeconds(html: string): number | null {
const lengthSecondsMatch = html.match(/"lengthSeconds":"(\d+)"/);
if (lengthSecondsMatch?.[1]) {
const parsed = Number.parseInt(lengthSecondsMatch[1], 10);
return Number.isFinite(parsed) ? parsed : null;
}
const approxDurationMsMatch = html.match(/"approxDurationMs":"(\d+)"/);
if (approxDurationMsMatch?.[1]) {
const parsed = Number.parseInt(approxDurationMsMatch[1], 10);
if (Number.isFinite(parsed) && parsed >= 0) {
return Math.round(parsed / 1000);
}
}
return null;
}
async function fetchYouTubeOEmbed(videoUrl: string): Promise<{ title: string | null; thumbnailUrl: string | null }> {
try {
const response = await fetch(`https://www.youtube.com/oembed?format=json&url=${encodeURIComponent(videoUrl)}`);
if (!response.ok) {
return {
title: null,
thumbnailUrl: null
};
}
const data = (await response.json()) as YouTubeOEmbedResponse;
const title = typeof data.title === 'string' && data.title.trim().length ? data.title.trim() : null;
const thumbnailUrl =
typeof data.thumbnail_url === 'string' && data.thumbnail_url.trim().length ? data.thumbnail_url.trim() : null;
return {
title,
thumbnailUrl
};
} catch {
return {
title: null,
thumbnailUrl: null
};
}
}
async function fetchYouTubeWatchPageMetadata(videoId: string): Promise<YouTubeWatchPageMetadata> {
try {
const response = await fetch(`https://www.youtube.com/watch?v=${videoId}`);
if (!response.ok) {
return {
title: null,
durationSeconds: null,
thumbnailUrl: null
};
}
const html = await response.text();
const title =
extractMetaContent(html, /<meta\s+property="og:title"\s+content="([^"]+)"/i) ??
extractMetaContent(html, /<meta\s+name="title"\s+content="([^"]+)"/i);
const thumbnailUrl = extractMetaContent(html, /<meta\s+property="og:image"\s+content="([^"]+)"/i);
const durationSeconds = extractDurationSeconds(html);
return {
title,
durationSeconds,
thumbnailUrl
};
} catch {
return {
title: null,
durationSeconds: null,
thumbnailUrl: null
};
}
}
export async function listOrganizationAssetsService(orgId: string, query: TAssetListQuery) {
try {
return await listAssetsByOrg(orgId, query);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to list assets',
ErrorCodes.ASSET_LIST_FAILED,
500
);
}
}
export async function createAssetFromUploadService(orgId: string, profileId: string, data: TAssetCreateUpload) {
try {
return await createOrGetAssetByStorageKey({
organizationId: orgId,
kind: data.kind,
provider: data.provider,
storageProvider: data.storageProvider,
storageKey: data.storageKey ?? null,
sourceUrl: data.sourceUrl ?? null,
mimeType: data.mimeType ?? null,
byteSize: data.byteSize ?? null,
checksum: data.checksum ?? null,
title: data.title ?? null,
description: data.description ?? null,
thumbnailUrl: data.thumbnailUrl ?? null,
durationSeconds: data.durationSeconds ?? null,
aspectRatio: data.aspectRatio ?? null,
isExternal: data.isExternal,
status: 'active',
metadata: data.metadata ?? {},
createdByProfileId: profileId
});
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to create asset',
ErrorCodes.ASSET_CREATE_FAILED,
500
);
}
}
export async function getAssetService(orgId: string, assetId: string) {
try {
const asset = await getAssetById(assetId, orgId);
return assertAssetExists(asset);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch asset',
ErrorCodes.ASSET_FETCH_FAILED,
500
);
}
}
export async function updateAssetService(orgId: string, assetId: string, data: TAssetUpdate) {
try {
const updated = await updateAsset(assetId, orgId, data);
return assertAssetExists(updated);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update asset',
ErrorCodes.ASSET_UPDATE_FAILED,
500
);
}
}
export async function deleteAssetService(orgId: string, assetId: string) {
try {
await getAssetService(orgId, assetId);
const usageCount = await countAssetUsagesByAsset(assetId, orgId);
if (usageCount > 0) {
throw new AppError('Asset is still in use', ErrorCodes.ASSET_IN_USE, 409);
}
const deleted = await deleteAsset(assetId, orgId);
return assertAssetExists(deleted);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete asset',
ErrorCodes.ASSET_DELETE_FAILED,
500
);
}
}
export async function getAssetUsageGraphService(orgId: string, assetId: string) {
try {
await getAssetService(orgId, assetId);
const [usages, usageCount] = await Promise.all([
listAssetUsagesByAsset(assetId, orgId),
countAssetUsagesByAsset(assetId, orgId)
]);
return {
usageCount,
usages
};
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch asset usage',
ErrorCodes.ASSET_USAGE_FETCH_FAILED,
500
);
}
}
export async function attachAssetService(orgId: string, assetId: string, profileId: string, input: TAssetAttach) {
try {
await getAssetService(orgId, assetId);
return await createAssetUsage({
organizationId: orgId,
assetId,
targetType: input.targetType,
targetId: input.targetId,
slotType: input.slotType,
slotKey: input.slotKey ?? null,
position: input.position ?? null,
createdByProfileId: profileId
});
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to attach asset',
ErrorCodes.ASSET_ATTACH_FAILED,
500
);
}
}
export async function detachAssetService(orgId: string, assetId: string, input: TAssetDetach) {
try {
await getAssetService(orgId, assetId);
const detached = await deleteAssetUsage(orgId, assetId, input);
if (!detached) {
throw new AppError('Asset usage not found', ErrorCodes.ASSET_USAGE_NOT_FOUND, 404);
}
return detached;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to detach asset',
ErrorCodes.ASSET_DETACH_FAILED,
500
);
}
}
export async function exportOrganizationAssetsService(orgId: string, query: TAssetExportQuery) {
try {
return await listAssetsForExport(orgId, query);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to export assets',
ErrorCodes.ASSET_EXPORT_FAILED,
500
);
}
}
export async function getOrganizationAssetStorageService(orgId: string, query: TAssetStorageQuery) {
try {
return await getAssetStorageSummaryByOrg(orgId, query);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch asset storage summary',
ErrorCodes.ASSET_STORAGE_FETCH_FAILED,
500
);
}
}
export async function getYouTubeMetadataService(_orgId: string, query: TYouTubeMetadataQuery) {
const videoId = extractYouTubeVideoId(query.url);
if (!videoId) {
throw new AppError('Invalid YouTube URL', ErrorCodes.VALIDATION_ERROR, 400, 'url');
}
const sourceUrl = `https://www.youtube.com/watch?v=${videoId}`;
try {
const [oembed, watchPageMetadata] = await Promise.all([
fetchYouTubeOEmbed(sourceUrl),
fetchYouTubeWatchPageMetadata(videoId)
]);
return {
videoId,
sourceUrl,
title: oembed.title ?? watchPageMetadata.title ?? 'YouTube video',
durationSeconds: watchPageMetadata.durationSeconds,
thumbnailUrl:
oembed.thumbnailUrl ?? watchPageMetadata.thumbnailUrl ?? `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`
};
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch YouTube metadata',
ErrorCodes.ASSET_FETCH_FAILED,
500
);
}
}
+1
View File
@@ -0,0 +1 @@
export * from './assets';
@@ -0,0 +1,46 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import { getAttendanceByCourseId, getAttendanceByStudentAndLesson, upsertAttendance } from '@cio/db/queries/attendance';
import type { TGroupAttendance, TNewGroupAttendance } from '@cio/db/types';
import type { TAttendanceUpsert } from '@cio/utils/validation/attendance';
/**
* Lists attendance records for a course
* @param courseId Course ID
* @param lessonId Optional lesson ID filter
* @returns Array of attendance records
*/
export async function listAttendance(courseId: string, lessonId?: string): Promise<TGroupAttendance[]> {
try {
return await getAttendanceByCourseId(courseId, lessonId);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to list attendance',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Creates or updates an attendance record
* @param data Attendance data
* @returns Created or updated attendance record
*/
export async function upsertAttendanceService(data: TAttendanceUpsert): Promise<TGroupAttendance> {
try {
const attendanceData: TNewGroupAttendance = {
courseId: data.courseId,
lessonId: data.lessonId,
studentId: data.studentId,
isPresent: data.isPresent
};
return await upsertAttendance(attendanceData);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to upsert attendance',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
@@ -0,0 +1 @@
export * from './attendance';
+133
View File
@@ -0,0 +1,133 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import {
getOrganizationAuthPolicy,
getOrganizationSsoConfig,
getOrganizationSsoConfigByDomain
} from '@cio/db/queries/organization/sso';
// Extract domain from email
function getDomainFromEmail(email: string): string {
const parts = email.toLowerCase().split('@');
if (parts.length !== 2) {
throw new AppError('Invalid email format', ErrorCodes.VALIDATION_ERROR, 400);
}
return parts[1];
}
// SSO Discovery result
interface SsoDiscoveryResult {
ssoRequired: boolean;
ssoAvailable: boolean;
redirectUrl: string | null;
allowPassword: boolean;
providerName: string | null;
providerId: string | null;
}
// Discover SSO for email
export async function discoverSso(email: string): Promise<SsoDiscoveryResult> {
const domain = getDomainFromEmail(email);
// Find SSO config by domain
const config = await getOrganizationSsoConfigByDomain(domain);
if (!config || !config.isActive) {
// No SSO found for this domain
return {
ssoRequired: false,
ssoAvailable: false,
redirectUrl: null,
allowPassword: true,
providerName: null,
providerId: null
};
}
// Get policy
const policy = await getOrganizationAuthPolicy(config.organizationId);
// Build Better Auth SSO URL
// Note: Better Auth handles the actual flow, we just provide the entry point
const redirectUrl = `/api/auth/sso/authorize/${config.betterAuthProviderId}`;
return {
ssoRequired: policy?.forceSso ?? false,
ssoAvailable: true,
redirectUrl,
allowPassword: !(policy?.forceSso ?? false),
providerName: config.displayName,
providerId: config.betterAuthProviderId
};
}
// Check if user can use password login for org
export async function canUsePasswordLogin(orgId: string, isBreakGlassUser: boolean = false): Promise<boolean> {
const policy = await getOrganizationAuthPolicy(orgId);
if (!policy) {
return true; // No policy = no restrictions
}
// If Force SSO is not enabled, password is allowed
if (!policy.forceSso) {
return true;
}
// Force SSO is enabled - check break glass
if (isBreakGlassUser && policy.breakGlassEnabled) {
return true;
}
// Force SSO active, not break glass
return false;
}
// Get SSO info for org (used in login page when org context is known)
export async function getOrgSsoInfo(orgId: string) {
const config = await getOrganizationSsoConfig(orgId);
if (!config || !config.isActive) {
return {
hasSso: false,
ssoRequired: false,
redirectUrl: null,
providerName: null,
providerId: null
};
}
const policy = await getOrganizationAuthPolicy(orgId);
return {
hasSso: true,
ssoRequired: policy?.forceSso ?? false,
redirectUrl: `/api/auth/sso/authorize/${config.betterAuthProviderId}`,
providerName: config.displayName,
providerId: config.betterAuthProviderId
};
}
// JIT provisioning: Get role mapping for user
export async function getSsoRoleMapping(orgId: string, groups: string[]): Promise<number> {
const policy = await getOrganizationAuthPolicy(orgId);
if (!policy) {
return 3; // Default to STUDENT
}
const roleMapping = policy.roleMapping as Record<string, number> | null;
if (!roleMapping) {
return policy.defaultRoleId ?? 3;
}
// Check each group for a mapping
for (const group of groups) {
const mappedRole = roleMapping[group];
if (mappedRole) {
return mappedRole;
}
}
return policy.defaultRoleId ?? 3;
}
+62 -25
View File
@@ -1,5 +1,5 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import type { TCommunityAnswer, TCommunityQuestion, TCourse } from '@db/types';
import type { TCommunityAnswer, TCommunityQuestion, TNewCommunityQuestion } from '@db/types';
import {
createCommunityQuestion,
deleteCommentById,
@@ -10,32 +10,57 @@ import {
getCommunityQuestions,
submitComment,
upvoteAnswer,
upvoteQuestion
upvoteQuestion,
type CommunityQuestionQueryResult
} from '@cio/db/queries/community';
import { getEnrolledCourses, getOrgCourses } from '@cio/db/queries/course';
import { getCoursesByOrgId } from './organization';
export async function fetchCommunityQuestions(orgId: string): Promise<Partial<TCommunityQuestion>[]> {
let discussions: Partial<TCommunityQuestion>[] = [];
let courses: TCourse[];
if (orgId) {
courses = await getCoursesByOrgId(orgId);
} else {
throw new AppError(
'Organization not found for the given site name',
ErrorCodes.COMMUNITY_QUESTIONS_FETCH_FAILED,
404
);
}
import { ROLE } from '@cio/utils/constants';
export async function fetchCommunityQuestions(
orgId: string,
userId: string,
userRole: number
): Promise<CommunityQuestionQueryResult[]> {
try {
const courseIds = courses.map((course) => course.id);
discussions = await getCommunityQuestions(courseIds);
if (!orgId) {
throw new AppError(
'Organization not found for the given site name',
ErrorCodes.COMMUNITY_QUESTIONS_FETCH_FAILED,
404
);
}
if (userRole === null) {
throw new AppError('User is not a member of this organization', ErrorCodes.UNAUTHORIZED, 403);
}
let discussions: CommunityQuestionQueryResult[];
switch (userRole) {
case ROLE.ADMIN:
// Admins can see all questions in the organization - no need to fetch courses
discussions = await getCommunityQuestions({ orgId });
break;
case ROLE.TUTOR:
// Tutors can see questions in courses they have access to
const tutorCourses = await getOrgCourses({ orgId, profileId: userId });
const tutorCourseIds = tutorCourses.map((course) => course.id);
discussions = await getCommunityQuestions({ courseIds: tutorCourseIds });
break;
case ROLE.STUDENT:
// Students can see questions in courses they are enrolled in
const studentCourses = await getEnrolledCourses({ orgId, profileId: userId });
const studentCourseIds = studentCourses.map((course) => course.id);
discussions = await getCommunityQuestions({ courseIds: studentCourseIds });
break;
default:
throw new AppError('Invalid role', ErrorCodes.UNAUTHORIZED, 403);
}
return discussions;
} catch (error) {
if (error instanceof AppError) throw error;
console.error('Failed to fetch community questions:', error);
throw new AppError('Failed to fetch community questions', ErrorCodes.COMMUNITY_QUESTIONS_FETCH_FAILED, 500);
}
@@ -43,6 +68,9 @@ export async function fetchCommunityQuestions(orgId: string): Promise<Partial<TC
export async function fetchCommunityQuestion({ slug }: Partial<TCommunityQuestion>) {
try {
if (!slug) {
throw new AppError('Slug is required', ErrorCodes.COMMUNITY_QUESTION_NOT_FOUND, 400);
}
const result = await getCommunityQuestion(slug);
if (!result) {
@@ -81,6 +109,9 @@ export async function createQuestion({
slug
}: Partial<TCommunityQuestion>) {
try {
if (!courseId || !organizationId || !authorProfileId) {
throw new AppError('Missing required fields', ErrorCodes.ADD_COMMUNITY_QUESTION_FAILED, 400);
}
const result = await createCommunityQuestion({
title,
body,
@@ -115,7 +146,10 @@ export async function createQuestion({
export async function editQuestion({ id, title, body, courseId }: Partial<TCommunityQuestion>) {
try {
const result = await editCommunityQuestion({ id, title, body, courseId: courseId });
if (!id || !courseId) {
throw new AppError('Question ID and Course ID are required', ErrorCodes.UPDATE_COMMUNITY_QUESTION_FAILED, 400);
}
const result = await editCommunityQuestion({ id, title, body, courseId });
return result;
} catch (error) {
@@ -127,7 +161,10 @@ export async function editQuestion({ id, title, body, courseId }: Partial<TCommu
export async function createComment({ body, questionId, authorProfileId, votes }: Partial<TCommunityAnswer>) {
try {
const result = await submitComment({ body, questionId, authorProfileId, votes });
if (!body || !questionId || !authorProfileId) {
throw new AppError('Missing required fields', ErrorCodes.COMMENT_SUBMISSION_FAILED, 400);
}
const result = await submitComment({ body, questionId, authorProfileId, votes: votes ?? 0 });
if (!result) {
throw new AppError('Comment submission failed', ErrorCodes.COMMENT_SUBMISSION_FAILED, 404);
@@ -165,7 +202,7 @@ export async function upvote({ id, isQuestion }: { id: string | number; isQuesti
}
}
export async function deleteQuestion({ id }: Partial<TCommunityQuestion>) {
export async function deleteQuestion({ id }: { id: number }) {
try {
// Delete all comments first, then delete the question
await deleteCommentByQuestionId(id);
@@ -179,7 +216,7 @@ export async function deleteQuestion({ id }: Partial<TCommunityQuestion>) {
}
}
export async function deleteComment({ id }: Partial<TCommunityAnswer>) {
export async function deleteComment({ id }: { id: string }) {
try {
const result = await deleteCommentById(id);
@@ -191,7 +228,7 @@ export async function deleteComment({ id }: Partial<TCommunityAnswer>) {
}
}
export async function deleteCommentsByQuestionId({ questionId }: Partial<TCommunityAnswer>) {
export async function deleteCommentsByQuestionId({ questionId }: { questionId: number }) {
try {
const result = await deleteCommentByQuestionId(questionId);
+47 -32
View File
@@ -1,26 +1,25 @@
import { ROLE } from '@cio/utils/constants';
import { TCourse, TCourseSection, TLesson } from '@db/types';
import {
addGroupMember,
createCourse,
createGroup,
createLessons,
createLessonSections,
getCourseById,
getLessonsByCourseId,
getSectionsByCourseId,
getLessonLanguagesByLessonIds,
createLessonLanguages,
getExercisesByLessonIds,
createExercises,
getQuestionsByExerciseIds,
createGroup,
createLessonLanguages,
createCourseSections,
createLessons,
createOptions,
createQuestions,
getCourseById,
getExercisesByLessonIds,
getLessonLanguagesByLessonIds,
getLessonsByCourseId,
getOptionsByQuestionIds,
createOptions
getQuestionsByExerciseIds,
getCourseSectionsByCourseId
} from '@db/queries';
import { TCourse, TLesson, TLessonSection } from '@db/types';
// Constants
const QUESTION_TYPE_TEXTAREA = 2; // Paragraph question type
import { ROLE } from '@cio/utils/constants';
import { QUESTION_TYPE_IDS } from '@cio/question-types';
async function cloneLessonLanguages(newLessons: TLesson[], oldLessons: TLesson[]): Promise<void> {
// Extract old lesson IDs
@@ -99,6 +98,7 @@ async function cloneExercises(newLessons: TLesson[], oldLessons: TLesson[]): Pro
points: question.points,
order: question.order,
questionTypeId: question.questionTypeId,
settings: question.settings,
exerciseId: exerciseIdMap.get(question.exerciseId)!
}))
);
@@ -106,11 +106,18 @@ async function cloneExercises(newLessons: TLesson[], oldLessons: TLesson[]): Pro
// 8. Create question ID map
const questionIdMap = new Map<number, number>();
oldQuestions.forEach((oldQuestion, index) => {
questionIdMap.set(oldQuestion.id, newQuestions[index].id);
const newQuestionId = newQuestions[index]?.id;
const oldQuestionId = oldQuestion.id;
if (newQuestionId !== undefined && oldQuestionId !== undefined) {
questionIdMap.set(oldQuestionId, newQuestionId);
}
});
// 9. Fetch all options for old questions (except for paragraph type questions)
const oldQuestionIds = oldQuestions.filter((q) => q.questionTypeId !== QUESTION_TYPE_TEXTAREA).map((q) => q.id);
const oldQuestionIds = oldQuestions
.filter((q) => q.questionTypeId !== QUESTION_TYPE_IDS.TEXTAREA)
.map((q) => q.id)
.filter((id) => id !== undefined);
if (oldQuestionIds.length === 0) {
return;
@@ -124,12 +131,21 @@ async function cloneExercises(newLessons: TLesson[], oldLessons: TLesson[]): Pro
// 10. Insert options with new question IDs
await createOptions(
oldOptions.map((option) => ({
value: option.value,
label: option.label,
isCorrect: option.isCorrect,
questionId: questionIdMap.get(option.questionId)!
}))
oldOptions
.map((option) => {
const newQuestionId = questionIdMap.get(option.questionId);
if (newQuestionId === undefined) {
return null;
}
return {
value: option.value,
label: option.label,
isCorrect: option.isCorrect,
settings: option.settings,
questionId: newQuestionId
};
})
.filter((opt) => opt !== null)
);
}
@@ -169,8 +185,7 @@ export async function cloneCourse(
isCertificateDownloadable: course.isCertificateDownloadable,
certificateTheme: course.certificateTheme,
status: course.status,
type: course.type,
version: course.version
type: course.type
});
// 4. add group member
@@ -182,23 +197,23 @@ export async function cloneCourse(
});
// 5. clone sections
const oldSections = await getSectionsByCourseId(courseId);
const oldSections = await getCourseSectionsByCourseId(courseId);
// Only create sections if there are any
let newSections: TLessonSection[] = [];
let newSections: TCourseSection[] = [];
let sectionMap = new Map<string, string>();
if (oldSections.length > 0) {
newSections = await createLessonSections(
oldSections.map((sec) => ({
title: sec.title,
order: sec.order,
newSections = await createCourseSections(
oldSections.map((section) => ({
title: section.title,
order: section.order,
courseId: newCourse.id
}))
);
// create map
sectionMap = new Map(oldSections.map((old, i) => [old.id, newSections[i].id]));
sectionMap = new Map(oldSections.map((section, index) => [section.id, newSections[index].id]));
}
// 6. clone lessons
+271
View File
@@ -0,0 +1,271 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import { ContentType } from '@cio/utils/constants';
import { db } from '@cio/db/drizzle';
import { sql, inArray } from 'drizzle-orm';
import { lesson, exercise } from '@cio/db/schema';
import { getCourseContentItems, type CourseContentItemRow } from '@cio/db/queries/course/content';
import { deleteLesson } from '@cio/db/queries/lesson';
import { deleteCourseSection, getCourseSectionById } from '@cio/db/queries/course';
import { deleteExercise } from '@cio/db/queries/exercise/exercise';
import type { TCourseContentDelete, TCourseContentUpdate } from '@cio/utils/validation/course';
function buildUpdatePayload(item: TCourseContentUpdate['items'][number]) {
const payload: Record<string, unknown> = {};
if (item.isUnlocked !== undefined) {
payload.isUnlocked = item.isUnlocked;
}
if (item.order !== undefined) {
payload.order = item.order;
}
if (item.sectionId !== undefined) {
payload.sectionId = item.sectionId;
}
return payload;
}
function buildContentKey(item: { id: string; type: string }) {
return `${item.type}-${item.id}`;
}
async function getCourseContentMap(courseId: string) {
const contentItems = await getCourseContentItems(courseId);
const contentMap = new Map<string, CourseContentItemRow>();
contentItems.forEach((item) => {
if (item.type === ContentType.Lesson || item.type === ContentType.Exercise) {
contentMap.set(buildContentKey(item), item);
}
});
return contentMap;
}
async function assertCourseContentItems(courseId: string, items: TCourseContentUpdate['items']) {
const contentMap = await getCourseContentMap(courseId);
items.forEach((item) => {
const key = buildContentKey({ id: item.id, type: item.type });
if (!contentMap.has(key)) {
if (item.type === ContentType.Lesson) {
throw new AppError('Lesson does not belong to this course', ErrorCodes.LESSON_NOT_FOUND, 404);
}
if (item.type === ContentType.Exercise) {
throw new AppError('Exercise does not belong to this course', ErrorCodes.EXERCISE_NOT_FOUND, 404);
}
throw new AppError('Invalid content type', ErrorCodes.VALIDATION_ERROR, 400);
}
});
}
export async function updateCourseContent(courseId: string, items: TCourseContentUpdate['items']) {
try {
await assertCourseContentItems(courseId, items);
await db.transaction(async (tx) => {
const updates = items
.map((item) => ({
item,
payload: buildUpdatePayload(item)
}))
.filter(({ payload }) => Object.keys(payload).length > 0);
if (updates.length === 0) {
return;
}
const updatedAt = new Date().toISOString();
const lessonUpdates = updates.filter(({ item }) => item.type === ContentType.Lesson);
const exerciseUpdates = updates.filter(({ item }) => item.type === ContentType.Exercise);
if (lessonUpdates.length > 0) {
const lessonIds = lessonUpdates.map(({ item }) => item.id);
const lessonOrderUpdates = lessonUpdates
.filter(({ payload }) => payload.order !== undefined)
.map(({ item, payload }) => ({ id: item.id, value: payload.order }));
const lessonSectionUpdates = lessonUpdates
.filter(({ payload }) => payload.sectionId !== undefined)
.map(({ item, payload }) => ({ id: item.id, value: payload.sectionId }));
const lessonUnlockUpdates = lessonUpdates
.filter(({ payload }) => payload.isUnlocked !== undefined)
.map(({ item, payload }) => ({ id: item.id, value: payload.isUnlocked }));
const lessonSet: Record<string, unknown> = {
updatedAt
};
if (lessonOrderUpdates.length > 0) {
lessonSet.order = sql`case ${lesson.id} ${sql.join(
lessonOrderUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
sql` `
)} else ${lesson.order} end`;
}
if (lessonSectionUpdates.length > 0) {
lessonSet.sectionId = sql`case ${lesson.id} ${sql.join(
lessonSectionUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
sql` `
)} else ${lesson.sectionId} end`;
}
if (lessonUnlockUpdates.length > 0) {
lessonSet.isUnlocked = sql`case ${lesson.id} ${sql.join(
lessonUnlockUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
sql` `
)} else ${lesson.isUnlocked} end`;
}
const updatedLessons = await tx
.update(lesson)
.set(lessonSet)
.where(inArray(lesson.id, lessonIds))
.returning({ id: lesson.id });
if (updatedLessons.length !== lessonIds.length) {
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
}
}
if (exerciseUpdates.length > 0) {
const exerciseIds = exerciseUpdates.map(({ item }) => item.id);
const exerciseOrderUpdates = exerciseUpdates
.filter(({ payload }) => payload.order !== undefined)
.map(({ item, payload }) => ({ id: item.id, value: payload.order }));
const exerciseSectionUpdates = exerciseUpdates
.filter(({ payload }) => payload.sectionId !== undefined)
.map(({ item, payload }) => ({ id: item.id, value: payload.sectionId }));
const exerciseUnlockUpdates = exerciseUpdates
.filter(({ payload }) => payload.isUnlocked !== undefined)
.map(({ item, payload }) => ({ id: item.id, value: payload.isUnlocked }));
const exerciseSet: Record<string, unknown> = {
updatedAt
};
if (exerciseOrderUpdates.length > 0) {
exerciseSet.order = sql`case ${exercise.id} ${sql.join(
exerciseOrderUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
sql` `
)} else ${exercise.order} end`;
}
if (exerciseSectionUpdates.length > 0) {
exerciseSet.sectionId = sql`case ${exercise.id} ${sql.join(
exerciseSectionUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
sql` `
)} else ${exercise.sectionId} end`;
}
if (exerciseUnlockUpdates.length > 0) {
exerciseSet.isUnlocked = sql`case ${exercise.id} ${sql.join(
exerciseUnlockUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
sql` `
)} else ${exercise.isUnlocked} end`;
}
const updatedExercises = await tx
.update(exercise)
.set(exerciseSet)
.where(inArray(exercise.id, exerciseIds))
.returning({ id: exercise.id });
if (updatedExercises.length !== exerciseIds.length) {
throw new AppError('Exercise not found', ErrorCodes.EXERCISE_NOT_FOUND, 404);
}
}
});
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update course content',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
export async function deleteCourseContent(courseId: string, payload: TCourseContentDelete) {
try {
if (payload.sectionId) {
const sectionId = payload.sectionId;
const section = await getCourseSectionById(sectionId);
if (!section || section.courseId !== courseId) {
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
}
const contentItems = await getCourseContentItems(courseId);
const itemsToDelete = contentItems.filter(
(item) =>
(item.type === ContentType.Lesson || item.type === ContentType.Exercise) && item.sectionId === sectionId
);
await db.transaction(async (tx) => {
for (const item of itemsToDelete) {
if (item.type === ContentType.Lesson) {
const deleted = await deleteLesson(item.id, tx);
if (!deleted) {
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
}
continue;
}
const deleted = await deleteExercise(item.id, tx);
if (!deleted) {
throw new AppError('Exercise not found', ErrorCodes.EXERCISE_NOT_FOUND, 404);
}
}
const deletedSection = await deleteCourseSection(sectionId, tx);
if (!deletedSection) {
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
}
});
return;
}
if (!payload.items) {
throw new AppError('Content items are required', ErrorCodes.VALIDATION_ERROR, 400);
}
const items = payload.items;
await assertCourseContentItems(courseId, items);
await db.transaction(async (tx) => {
for (const item of items) {
if (item.type === ContentType.Lesson) {
const deleted = await deleteLesson(item.id, tx);
if (!deleted) {
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
}
continue;
}
const deleted = await deleteExercise(item.id, tx);
if (!deleted) {
throw new AppError('Exercise not found', ErrorCodes.EXERCISE_NOT_FOUND, 404);
}
}
});
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete course content',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
+452
View File
@@ -0,0 +1,452 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import { addGroupMember, createGroup } from '@cio/db/queries/group';
import {
createCourseNewsfeed,
createCourse as createCourseQuery,
createCourseSections,
deleteCourse as deleteCourseQuery,
getCourseProgress as getCourseProgressQuery,
getCourseWithRelations,
updateCourse as updateCourseQuery,
updateLessonsSectionId
} from '@cio/db/queries/course';
import {
getLastLogin,
getLessonsWithCompletion,
getProfileCourseProgress,
getUserExercisesStats
} from '@cio/db/queries/analytics/analytics';
import { ContentType, ROLE } from '@cio/utils/constants';
import type { TCourse } from '@cio/db/types';
import { db } from '@cio/db/drizzle';
import { updateExercisesSectionId } from '@cio/db/queries/exercise/exercise';
import { getProfileById } from '@cio/db/queries/auth';
import { buildCourseContent, calcPercentageWithRounding, formatLastSeen, type CourseContent } from './utils';
const DEFAULT_CONTENT_GROUPING = true;
const DEFAULT_SECTION_TITLE = 'First Section [edit me]';
/**
* Gets a course by ID or slug with all related data
* @param courseId Course ID (optional if slug provided)
* @param slug Course slug (optional if courseId provided)
* @param profileId Profile ID of the current user (optional, for computing lesson completion)
* @returns Course with all related data
*/
export async function getCourse(courseId?: string, slug?: string, profileId?: string) {
try {
if (!courseId && !slug) {
throw new AppError('Either courseId or slug must be provided', ErrorCodes.VALIDATION_ERROR, 400);
}
const course = await getCourseWithRelations(courseId, slug, profileId);
if (!course) {
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
}
const isContentGroupingEnabled = course.metadata?.isContentGroupingEnabled ?? DEFAULT_CONTENT_GROUPING;
const content = buildCourseContent(course.contentItems, isContentGroupingEnabled);
const { contentItems, org: courseOrg, ...rest } = course;
const base = {
...rest,
content
};
if (courseOrg) {
return {
...base,
org: {
id: courseOrg.id,
name: courseOrg.name,
siteName: courseOrg.siteName ?? '',
theme: courseOrg.theme ?? undefined
}
};
}
return base;
} catch (error) {
console.error('Error getting course:', error);
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch course',
ErrorCodes.COURSE_FETCH_FAILED,
500
);
}
}
/**
* Creates a new course with group, group member, and default newsfeed
* @param profileId Profile ID of the creator
* @param data Course creation data
* @returns Created course with group and member information
*/
export async function createCourse(
profileId: string,
data: { title: string; description: string; type: 'LIVE_CLASS' | 'SELF_PACED'; organizationId: string }
): Promise<{ course: TCourse; groupId: string; memberId: string }> {
try {
const result = await db.transaction(async () => {
// 1. Create group
const [newGroup] = await createGroup({
name: data.title,
description: data.description,
organizationId: data.organizationId
});
if (!newGroup) {
throw new AppError('Failed to create group', ErrorCodes.INTERNAL_ERROR, 500);
}
// 2. Create course with group_id
const [newCourse] = await createCourseQuery({
title: data.title,
description: data.description,
type: data.type,
groupId: newGroup.id
});
if (!newCourse) {
throw new AppError('Failed to create course', ErrorCodes.INTERNAL_ERROR, 500);
}
// 3. Add group member (creator as TUTOR)
const [newMember] = await addGroupMember({
profileId,
groupId: newGroup.id,
roleId: ROLE.TUTOR
});
if (!newMember) {
throw new AppError('Failed to add group member', ErrorCodes.INTERNAL_ERROR, 500);
}
// 4. Add default news feed
await createCourseNewsfeed({
content: `<h2>Welcome to this course 🎉&nbsp;</h2>
<p>Thank you for joining this course and I hope you get the best out of it.</p>`,
courseId: newCourse.id,
isPinned: true,
authorId: newMember.id
});
return {
course: newCourse,
groupId: newGroup.id,
memberId: newMember.id
};
});
return result;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to create course',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Updates a course
* @param courseId Course ID
* @param data Course update data
* @returns Updated course
*/
export async function updateCourse(courseId: string, data: Partial<TCourse>) {
try {
const updated = await updateCourseQuery(courseId, data);
if (!updated) {
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
}
const isContentGroupingEnabled = (updated.metadata?.isContentGroupingEnabled ?? DEFAULT_CONTENT_GROUPING) === true;
if (isContentGroupingEnabled) {
const courseWithRelations = await getCourseWithRelations(courseId);
if (courseWithRelations) {
const contentItems = courseWithRelations.contentItems;
const hasSections = contentItems.some((item) => item.type === ContentType.Section);
const hasUngroupedItems = contentItems.some(
(item) => (item.type === ContentType.Lesson || item.type === ContentType.Exercise) && item.sectionId === null
);
if (!hasSections && hasUngroupedItems) {
await db.transaction(async (tx) => {
const [section] = await createCourseSections(
[
{
title: DEFAULT_SECTION_TITLE,
order: 1,
courseId
}
],
tx
);
if (!section) {
throw new AppError('Failed to create course section', ErrorCodes.COURSE_SECTION_NOT_FOUND, 500);
}
await updateLessonsSectionId(courseId, section.id, tx);
await updateExercisesSectionId(courseId, section.id, tx);
});
}
}
}
return updated;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update course',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Soft deletes a course by setting status to 'DELETED'
* @param courseId Course ID
* @returns Deleted course
*/
export async function deleteCourse(courseId: string) {
try {
const deleted = await deleteCourseQuery(courseId);
if (!deleted) {
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
}
return deleted;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete course',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets course progress for a profile
* @param courseId Course ID
* @param profileId Profile ID
* @returns Course progress with counts
*/
export async function getCourseProgress(courseId: string, profileId: string) {
try {
const progress = await getCourseProgressQuery(courseId, profileId);
return progress;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to get course progress',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets course analytics including student progress, completion rates, and grades
* @param courseId Course ID
* @returns Course analytics data
*/
export async function getCourseAnalytics(courseId: string) {
try {
// Get course with members (no profileId needed for analytics)
const course = await getCourseWithRelations(courseId);
if (!course) {
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
}
// Get all members
const members = course.group?.members || [];
// Filter students and tutors
const students = members.filter((member) => member.roleId === ROLE.STUDENT);
const tutors = members.filter((member) => member.roleId === ROLE.ADMIN || member.roleId === ROLE.TUTOR);
// Get lessons and exercises
const lessons = course.contentItems.filter((item) => item.type === ContentType.Lesson);
const exercises = course.contentItems.filter((item) => item.type === ContentType.Exercise);
// Get student analytics
const studentAnalytics = await Promise.all(
students
.filter((student) => student.profileId !== null)
.map(async (student) => {
try {
const [courseProgress, userExercisesStats, lastLoginDate] = await Promise.all([
getCourseProgressQuery(courseId, student.profileId!),
getUserExercisesStats(courseId, student.profileId!),
getLastLogin(student.profileId!)
]);
if (!courseProgress) {
return null;
}
const completedExercises = userExercisesStats?.filter((exercise) => exercise.isCompleted)?.length || 0;
const totalExercises = userExercisesStats?.length || 0;
const totalEarnedPoints = userExercisesStats?.reduce((sum, exercise) => sum + exercise.score, 0) || 0;
const totalPoints = userExercisesStats?.reduce((sum, exercise) => sum + exercise.totalPoints, 0) || 0;
const averageGrade = calcPercentageWithRounding(totalEarnedPoints, totalPoints);
const lessonsCompleted = courseProgress.lessonsCompleted || 0;
const totalLessons = courseProgress.lessonsCount || 0;
const progressPercentage = calcPercentageWithRounding(lessonsCompleted, totalLessons);
return {
id: student.profileId,
profile: {
fullname: student.profile?.fullname || 'Unknown',
email: student.profile?.email || '',
avatar_url: student.profile?.avatarUrl || ''
},
lessonsCompleted,
totalLessons,
exercisesSubmitted: completedExercises,
totalExercises,
averageGrade,
lastSeen: formatLastSeen(lastLoginDate),
progressPercentage
};
} catch (error) {
console.error('Error getting student overview:', error);
return null;
}
})
);
const validStudentAnalytics = studentAnalytics.filter(
(student): student is NonNullable<typeof student> => student !== null
);
// Calculate aggregated metrics
let lessonCompletionRate = 0;
let exerciseCompletionRate = 0;
let averageGrade = 0;
if (validStudentAnalytics.length > 0) {
lessonCompletionRate = Math.round(
validStudentAnalytics.reduce((sum, student) => sum + student.progressPercentage, 0) /
validStudentAnalytics.length
);
exerciseCompletionRate = Math.round(
validStudentAnalytics.reduce((sum, student) => {
const completionRate =
student.totalExercises > 0 ? (student.exercisesSubmitted / student.totalExercises) * 100 : 0;
return sum + completionRate;
}, 0) / validStudentAnalytics.length
);
averageGrade = Math.round(
validStudentAnalytics.reduce((sum, student) => sum + student.averageGrade, 0) / validStudentAnalytics.length
);
}
return {
totalTutors: tutors.length,
totalStudents: students.length,
totalLessons: lessons.length,
totalExercises: exercises.length,
lessonCompletionRate,
exerciseCompletionRate,
averageGrade,
students: validStudentAnalytics
};
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to get course analytics',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets user course analytics for a specific course
* @param courseId Course ID
* @param userId User ID (profile ID)
* @returns User course analytics data
*/
export async function getUserCourseAnalytics(courseId: string, userId: string) {
try {
// Get user profile
const profile = await getProfileById(userId);
if (!profile) {
throw new AppError('User profile not found', ErrorCodes.PROFILE_NOT_FOUND, 404);
}
// Get last login
const lastLoginDate = await getLastLogin(userId);
// Fetch user exercises stats, lessons with completion, and course progress
const [userExercisesStats, lessons, courseProgress] = await Promise.all([
getUserExercisesStats(courseId, userId),
getLessonsWithCompletion(courseId, userId),
getProfileCourseProgress(courseId, userId)
]);
if (!userExercisesStats || !lessons || !courseProgress) {
throw new AppError('Failed to fetch course analytics data', ErrorCodes.INTERNAL_ERROR, 500);
}
// Calculate metrics
const totalEarnedPoints = userExercisesStats.reduce((sum, exercise) => sum + exercise.score, 0);
const totalPoints = userExercisesStats.reduce((sum, exercise) => sum + exercise.totalPoints, 0);
const averageGrade = calcPercentageWithRounding(totalEarnedPoints, totalPoints);
const completedLessons = lessons.filter((lesson) => lesson.completed);
const progressPercentage = calcPercentageWithRounding(completedLessons.length, lessons.length);
const completedExercises = userExercisesStats.filter((exercise) => exercise.isCompleted).length;
const totalExercises = courseProgress.exercises_count || 0;
return {
user: {
id: userId,
fullName: profile.fullname || '',
email: profile.email || '',
avatarUrl: profile.avatarUrl || '',
lastSeen: formatLastSeen(lastLoginDate)
},
averageGrade,
userExercisesStats,
totalExercises,
completedExercises,
progressPercentage
};
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError('Failed to get user exercises stats', ErrorCodes.INTERNAL_ERROR, 500);
}
}
export type { CourseContent, CourseContentItem } from './utils';
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,92 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import { getCourseTeachers } from '@cio/db/queries/course/people';
import { getCourseWithOrgData } from '@cio/db/queries/course';
import { buildEmailFromName, sendEmail } from '@cio/email';
export interface PaymentRequestData {
courseId: string;
studentEmail: string;
studentFullname: string;
}
/**
* Creates a payment request and sends emails to teacher and student
* @param data Payment request data
*/
export async function createPaymentRequest(data: PaymentRequestData) {
try {
// Get course and organization data
const course = await getCourseWithOrgData(data.courseId);
if (!course) {
throw new AppError('Course not found', ErrorCodes.NOT_FOUND, 404);
}
const courseName = course.courseTitle || '';
const orgName = course.orgName || 'ClassroomIO';
const groupId = course.groupId;
if (!groupId) {
throw new AppError('Course group not found', ErrorCodes.NOT_FOUND, 404);
}
// Get first teacher (TUTOR or ADMIN) email
const teacherResult = await getCourseTeachers({ groupId, limit: 1 });
if (teacherResult.length === 0 || !teacherResult[0]?.email) {
throw new AppError('No teacher found for this course', ErrorCodes.NOT_FOUND, 404);
}
const teacherEmail = teacherResult[0].email;
// Send email to teacher about student buy request
try {
await sendEmail('teacherStudentBuyRequest', {
to: teacherEmail,
fields: {
courseName,
studentEmail: data.studentEmail,
studentFullname: data.studentFullname
},
from: buildEmailFromName('ClassroomIO')
});
} catch (emailError) {
console.error('Failed to send teacher buy request email:', emailError);
// Don't fail the request if email fails
}
// Send email to student with payment instructions
try {
await sendEmail('studentProvePayment', {
to: data.studentEmail,
fields: {
courseName,
teacherEmail,
studentFullname: data.studentFullname,
orgName
},
from: buildEmailFromName(`${orgName} - ClassroomIO`),
replyTo: teacherEmail
});
} catch (emailError) {
console.error('Failed to send student payment proof email:', emailError);
// Don't fail the request if email fails
}
return {
success: true,
courseName,
teacherEmail
};
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to create payment request',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
+282
View File
@@ -0,0 +1,282 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import {
addCourseMember,
deleteCourseMember,
getCourseMember,
getCourseMembers,
getCourseTeachers,
updateCourseMember
} from '@cio/db/queries/course/people';
import { ROLE } from '@cio/utils/constants';
import type { TAddCourseMembers } from '@cio/utils/validation/course/people';
import type { TGroupmember } from '@cio/db/types';
import { env } from '@api/config/env';
import { getCourseWithOrgData } from '@cio/db/queries/course';
import { getProfileById } from '@cio/db/queries/auth';
import { buildEmailFromName, sendEmail } from '@cio/email';
/**
* Gets all course members (people) for a course
* @param courseId Course ID
* @returns Array of course members with profile data
*/
export async function listCourseMembers(courseId: string) {
try {
return getCourseMembers(courseId);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to list course members',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Adds a course member (person) to a course
* @param courseId Course ID
* @param data Member data (profileId, roleId, email, name)
* @returns Created member
*/
export async function addMember(
courseId: string,
data: { profileId?: string; roleId: number; email?: string; name?: string }
) {
try {
if (!data.profileId && !data.email) {
throw new AppError('Either profileId or email must be provided', ErrorCodes.VALIDATION_ERROR, 400);
}
const addedMember = await addCourseMember(courseId, data);
// Send emails when a student joins
if (data.roleId === ROLE.STUDENT) {
try {
// Get course and organization data
const courseOrgData = await getCourseWithOrgData(courseId);
if (courseOrgData) {
const courseName = courseOrgData.courseTitle || '';
const orgName = courseOrgData.orgName || 'ClassroomIO';
// Get student profile data
let studentEmail: string | null = null;
let studentName: string | null = null;
if (data.profileId) {
const studentProfile = await getProfileById(data.profileId);
if (studentProfile) {
studentEmail = studentProfile.email;
studentName = studentProfile.fullname;
}
} else if (data.email) {
studentEmail = data.email;
studentName = data.name || null;
}
// Send welcome email to student
if (studentEmail) {
try {
await sendEmail('studentCourseWelcome', {
to: studentEmail,
fields: {
orgName,
courseName
},
from: buildEmailFromName(`${orgName} (via ClassroomIO.com)`)
});
} catch (emailError) {
console.error('Failed to send student welcome email:', emailError);
}
}
// Get all teachers (ADMIN or TUTOR) in the course
const teachersResult = await getCourseTeachers({ courseId });
// Send notification to all teachers
if (teachersResult.length > 0 && studentEmail && studentName) {
const teacherEmails = teachersResult.map((t) => t.email).filter((email): email is string => email !== null);
await Promise.all(
teacherEmails.map((teacherEmail) =>
sendEmail('teacherStudentJoined', {
to: teacherEmail,
fields: {
courseName,
studentName,
studentEmail
},
from: buildEmailFromName('ClassroomIO')
}).catch((emailError) => {
console.error(`Failed to send teacher notification email to ${teacherEmail}:`, emailError);
})
)
);
}
}
} catch (emailError) {
// Log but don't fail the request if email fails
console.error('Failed to send student join emails:', emailError);
}
}
return addedMember;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to add course member',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Adds multiple course members to a course and optionally sends welcome emails
* @param courseId Course ID
* @param members Array of member data
* @returns Array of created members
*/
export async function addMembers(courseId: string, members: TAddCourseMembers) {
try {
if (members.length === 0) {
throw new AppError('At least one member must be provided', ErrorCodes.VALIDATION_ERROR, 400);
}
// Validate all members
for (const member of members) {
if (!member.profileId && !member.email) {
throw new AppError(
'Either profileId or email must be provided for each member',
ErrorCodes.VALIDATION_ERROR,
400
);
}
}
// Get course title and organization data for emails (simple query, no expensive joins)
const courseOrgData = await getCourseWithOrgData(courseId);
if (!courseOrgData) {
throw new AppError('Course not found', ErrorCodes.NOT_FOUND, 404);
}
const courseName = courseOrgData.courseTitle || '';
const orgName = courseOrgData.orgName || 'ClassroomIO';
const orgSiteName = courseOrgData.orgSiteName || '';
// Add all members
const addedMembers = await Promise.all(members.map((member) => addCourseMember(courseId, member)));
// Send welcome emails for teachers (TUTOR role = 2, ADMIN role = 1)
const baseUrl = env.NODE_ENV === 'development' ? 'http://localhost:5173' : 'https://app.classroomio.com';
const inviteLink = `${baseUrl}/org/${orgSiteName}/courses`;
// Send welcome emails to teachers
const teacherEmailPromises: Promise<unknown>[] = [];
addedMembers.forEach((member, index) => {
const memberData = members[index];
// Only send emails to teachers (TUTOR or ADMIN role) who have email
const roleId = memberData.roleId;
const email = memberData.email;
const name = memberData.name;
if ((roleId === ROLE.ADMIN || roleId === ROLE.TUTOR) && email && name) {
teacherEmailPromises.push(
sendEmail('teacherCourseWelcome', {
to: email,
fields: {
name,
orgName,
courseName,
inviteLink
},
from: buildEmailFromName(`${orgName} (via ClassroomIO.com)`)
}).catch((emailError) => {
console.error(`Failed to send welcome email to ${email}:`, emailError);
return [];
})
);
}
});
if (teacherEmailPromises.length > 0) {
try {
await Promise.all(teacherEmailPromises);
} catch (emailError) {
// Log but don't fail the request if email fails
console.error('Failed to send welcome emails:', emailError);
}
}
return addedMembers;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to add course members',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Updates a course member
* @param courseId Course ID
* @param memberId Member ID
* @param data Partial member data to update
* @returns Updated member
*/
export async function updateMember(courseId: string, memberId: string, data: Partial<TGroupmember>) {
try {
const updated = await updateCourseMember(courseId, memberId, data);
if (!updated) {
throw new AppError('Course member not found', ErrorCodes.NOT_FOUND, 404);
}
return updated;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update course member',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Deletes a course member
* @param courseId Course ID
* @param memberId Member ID
* @returns Deleted member
*/
export async function deleteMember(courseId: string, memberId: string) {
try {
const deleted = await deleteCourseMember(courseId, memberId);
if (!deleted) {
throw new AppError('Course member not found', ErrorCodes.NOT_FOUND, 404);
}
return deleted;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete course member',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
+235
View File
@@ -0,0 +1,235 @@
import type { TCourseSection } from '@cio/db/types';
import {
createCourseSections,
deleteCourseSection,
getCourseSectionById,
getCourseSectionsByCourseId,
updateCourseSection,
updateUngroupedLessonsSectionId
} from '@cio/db/queries/course';
import { AppError, ErrorCodes } from '@api/utils/errors';
import type {
TCourseSectionCreate,
TCourseSectionPromoteUngrouped,
TCourseSectionReorder,
TCourseSectionUpdate
} from '@cio/utils/validation/course/section';
import { updateUngroupedExercisesSectionId } from '@cio/db/queries/exercise/exercise';
import { db } from '@cio/db/drizzle';
/**
* Creates a new course section
* @param courseId Course ID
* @param data Section creation data
* @returns Created section
*/
export async function createCourseSection(courseId: string, data: TCourseSectionCreate): Promise<TCourseSection> {
try {
const sectionData = {
...data,
courseId
};
const [section] = await createCourseSections([sectionData]);
if (!section) {
throw new AppError('Failed to create course section', ErrorCodes.INTERNAL_ERROR, 500);
}
return section;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to create course section',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Promotes synthetic "Ungrouped" content into a real persisted section.
* Creates a section and reassigns all ungrouped lessons/exercises to it transactionally.
*/
export async function promoteUngroupedSection(
courseId: string,
data: TCourseSectionPromoteUngrouped
): Promise<{ section: TCourseSection; movedLessons: number; movedExercises: number }> {
try {
const existingSections = await getCourseSectionsByCourseId(courseId);
const nextOrder = Math.max(...existingSections.map((section) => section.order ?? 0), 0) + 1;
return db.transaction(async (tx) => {
const [section] = await createCourseSections(
[
{
title: data.title,
courseId,
order: nextOrder
}
],
tx
);
if (!section) {
throw new AppError('Failed to create course section', ErrorCodes.INTERNAL_ERROR, 500);
}
const [movedLessons, movedExercises] = await Promise.all([
updateUngroupedLessonsSectionId(courseId, section.id, tx),
updateUngroupedExercisesSectionId(courseId, section.id, tx)
]);
if (movedLessons + movedExercises === 0) {
throw new AppError('No ungrouped content found', ErrorCodes.VALIDATION_ERROR, 400);
}
return {
section,
movedLessons,
movedExercises
};
});
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to promote ungrouped content',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets a course section by ID
* @param sectionId Section ID
* @returns Section or throws error if not found
*/
export async function getCourseSection(sectionId: string): Promise<TCourseSection> {
try {
const section = await getCourseSectionById(sectionId);
if (!section) {
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
}
return section;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch course section',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Updates a course section
* @param sectionId Section ID
* @param data Partial section update data
* @returns Updated section
*/
export async function updateCourseSectionService(
sectionId: string,
data: TCourseSectionUpdate
): Promise<TCourseSection> {
try {
const section = await getCourseSectionById(sectionId);
if (!section) {
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
}
const updated = await updateCourseSection(sectionId, data);
if (!updated) {
throw new AppError('Failed to update course section', ErrorCodes.INTERNAL_ERROR, 500);
}
return updated;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update course section',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Deletes a course section
* @param sectionId Section ID
* @returns Deleted section
*/
export async function deleteCourseSectionService(sectionId: string): Promise<TCourseSection> {
try {
const section = await getCourseSectionById(sectionId);
if (!section) {
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
}
const deleted = await deleteCourseSection(sectionId);
if (!deleted) {
throw new AppError('Failed to delete course section', ErrorCodes.INTERNAL_ERROR, 500);
}
return deleted;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete course section',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Lists course sections for a course
* @param courseId Course ID
* @returns Array of sections
*/
export async function listCourseSections(courseId: string): Promise<TCourseSection[]> {
try {
return await getCourseSectionsByCourseId(courseId);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to list course sections',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Reorders course sections
* @param sections Array of section IDs and orders
* @returns Updated sections
*/
export async function reorderCourseSections(sections: TCourseSectionReorder['sections']): Promise<TCourseSection[]> {
try {
const updatePromises = sections.map(({ id, order }) => updateCourseSection(id, { order }));
const updated = await Promise.all(updatePromises);
return updated.filter((section): section is TCourseSection => section !== null);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to reorder course sections',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
+159
View File
@@ -0,0 +1,159 @@
import { ContentType } from '@cio/utils/constants';
import type { CourseContentItemRow } from '@cio/db/queries/course';
export type CourseContentItem = {
id: string;
type: ContentType;
title: string;
order: number | null;
createdAt: string | null;
sectionId: string | null;
isUnlocked: boolean | null;
isComplete: boolean | null;
lessonAt: string | null;
callUrl: string | null;
hasNoteContent: boolean | null;
hasSlideContent: boolean | null;
videosCount: number | null;
documentsCount: number | null;
questionCount: number | null;
dueBy: string | null;
};
export type CourseContentSection = {
id: string;
title: string;
order: number | null;
items: CourseContentItem[];
};
export type CourseContent = {
grouped: boolean;
sections: CourseContentSection[];
items: CourseContentItem[];
};
const CONTENT_TYPE_PRIORITY: Record<ContentType, number> = {
[ContentType.Section]: -1,
[ContentType.Lesson]: 0,
[ContentType.Exercise]: 1
};
function sortContentItems(items: CourseContentItem[]): CourseContentItem[] {
return [...items].sort((a, b) => {
const orderDiff = (a.order ?? 0) - (b.order ?? 0);
if (orderDiff !== 0) return orderDiff;
const typeDiff = CONTENT_TYPE_PRIORITY[a.type] - CONTENT_TYPE_PRIORITY[b.type];
if (typeDiff !== 0) return typeDiff;
return new Date(a.createdAt || 0).getTime() - new Date(b.createdAt || 0).getTime();
});
}
function sortContentSections(sections: CourseContentSection[]): CourseContentSection[] {
return [...sections].sort((a, b) => {
const orderDiff = (a.order ?? 0) - (b.order ?? 0);
if (orderDiff !== 0) return orderDiff;
return a.title.localeCompare(b.title);
});
}
function mapCourseContentItems(rows: CourseContentItemRow[]): CourseContentItem[] {
return rows.map((row) => ({
id: row.id,
type: row.type as ContentType,
title: row.title ?? '',
order: row.order ?? null,
createdAt: row.createdAt ?? null,
sectionId: row.sectionId ?? null,
isUnlocked: row.isUnlocked ?? null,
isComplete: row.isComplete ?? null,
lessonAt: row.lessonAt ?? null,
callUrl: row.callUrl ?? null,
hasNoteContent: row.hasNoteContent ?? null,
hasSlideContent: row.hasSlideContent ?? null,
videosCount: row.videosCount ?? null,
documentsCount: row.documentsCount ?? null,
questionCount: row.questionCount ?? null,
dueBy: row.dueBy ?? null
}));
}
export function buildCourseContent(rows: CourseContentItemRow[], isContentGroupingEnabled: boolean): CourseContent {
const items = mapCourseContentItems(rows);
const contentItems = items.filter((item) => item.type !== ContentType.Section);
if (!isContentGroupingEnabled) {
return {
grouped: false,
sections: [],
items: sortContentItems(contentItems)
};
}
const sectionItems = items.filter((item) => item.type === ContentType.Section);
const sectionMap = new Map<string, CourseContentItem[]>();
const ungroupedItems: CourseContentItem[] = [];
for (const item of contentItems) {
if (!item.sectionId) {
ungroupedItems.push(item);
continue;
}
if (!sectionMap.has(item.sectionId)) {
sectionMap.set(item.sectionId, []);
}
sectionMap.get(item.sectionId)!.push(item);
}
const sections = sortContentSections(
sectionItems.map((section) => ({
id: section.id,
title: section.title || 'Untitled section',
order: section.order ?? null,
items: sortContentItems(sectionMap.get(section.id) ?? [])
}))
);
if (ungroupedItems.length > 0) {
sections.push({
id: 'ungrouped',
title: 'Ungrouped',
order: sections.length + 1,
items: sortContentItems(ungroupedItems)
});
}
return {
grouped: true,
sections,
items: []
};
}
export function calcPercentageWithRounding(a: number, b: number): number {
if (b === 0) return 0;
return Math.round((a / b) * 100);
}
export function formatLastSeen(lastLoginDate: string | null | undefined): string {
if (!lastLoginDate) return 'Never';
const lastLogin = new Date(lastLoginDate);
const now = new Date();
const diffInHours = Math.floor((now.getTime() - lastLogin.getTime()) / (1000 * 60 * 60));
if (diffInHours < 1) {
return 'Just now';
}
if (diffInHours < 24) {
return `${diffInHours} hours ago`;
}
const diffInDays = Math.floor(diffInHours / 24);
return `${diffInDays} days ago`;
}
+1 -1
View File
@@ -49,7 +49,7 @@ export async function getOrganisationAnalytics(orgId?: string, siteName?: string
name: e.fullname,
courseId: e.courseId,
course: e.courseTitle,
date: e.enrolledAt
date: e.enrolledAt ?? ''
}));
return analytics;
+412
View File
@@ -0,0 +1,412 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import type { TExercise, TExerciseTemplate, TNewOption, TNewQuestion } from '@cio/db/types';
import type { TExerciseCreate, TExerciseUpdate } from '@cio/utils/validation/exercise';
import {
createExercises,
syncOptionIdSequence,
createOptions,
createQuestions,
deleteExercise,
deleteOptionsByIds,
deleteQuestionsByIds,
getExerciseById,
getExerciseCompletionByProfile,
getExerciseCompletionsByProfile,
getExerciseWithRelationsOptimized,
getExercisesByCourseId,
getLMSExercises,
updateExercise,
updateOptions,
updateQuestions
} from '@cio/db/queries/exercise';
import { db } from '@cio/db/drizzle';
import type { DbOrTxClient } from '@cio/db/drizzle';
import {
buildExerciseUpdateFields,
computeExerciseDiff,
createNewQuestionsWithOptions,
fetchQuestionsAndOptions,
transformQuestions,
type QuestionWithRelations
} from './utils';
type ExerciseWithQuestions = TExercise & {
isComplete: boolean;
questions?: QuestionWithRelations[];
};
type ExerciseWithCompletion = TExercise & {
isComplete: boolean;
};
/**
* Creates a new exercise with optional questions and options
* @param data Exercise creation data
* @returns Created exercise
*/
export async function createExercise(data: TExerciseCreate): Promise<TExercise> {
try {
const exerciseData = {
title: data.title,
description: data.description ?? null,
lessonId: data.lessonId || null,
courseId: data.courseId,
sectionId: data.sectionId || null,
order: data.order ?? null,
dueBy: data.dueBy || null
};
const [exercise] = await createExercises([exerciseData]);
if (!exercise) {
throw new AppError('Failed to create exercise', ErrorCodes.INTERNAL_ERROR, 500);
}
// Create questions and options if provided
if (data.questions && data.questions.length > 0) {
await db.transaction(async (tx) => {
const txClient = tx as DbOrTxClient;
const questionsData: TNewQuestion[] = data.questions!.map((q) => ({
exerciseId: exercise.id,
title: q.question,
questionTypeId: q.questionTypeId || 1,
points: q.points || 0,
settings: q.settings ?? {}
}));
const questions = await createQuestions(questionsData, txClient);
// Create options for each question
const optionsPromises = data.questions!.map(async (q, index) => {
const question = questions[index];
if (!question) return;
const optionsData: TNewOption[] = q.options.map((opt) => ({
questionId: question.id,
label: opt.label,
isCorrect: opt.isCorrect,
settings: opt.settings ?? {}
}));
return createOptions(optionsData, txClient);
});
await Promise.all(optionsPromises);
});
}
// Fetch the complete exercise with questions and options
return await getExercise(exercise.id);
} catch (error) {
console.error('createExercise error:', error);
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to create exercise',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets an exercise by ID with questions and options
* @param exerciseId Exercise ID
* @returns Exercise with questions and options
*/
export async function getExercise(
exerciseId: string,
dbClient?: DbOrTxClient,
profileId?: string
): Promise<ExerciseWithQuestions> {
try {
// Optimized: Fetch exercise + questions + questionTypes + options in one JOIN query
const { exercise, questions } = await getExerciseWithRelationsOptimized(exerciseId, dbClient);
const isComplete = profileId ? await getExerciseCompletionByProfile(exerciseId, profileId, dbClient) : false;
// Build questionTypeMap from questions (already fetched with questionType)
const questionTypeMap = new Map(questions.map((q) => [q.questionType.id, q.questionType]));
// Extract options from questions and transform
const allOptions = questions.flatMap((q) => q.options || []);
// Transform questions (strip questionType and options since they're handled in transform)
const questionsForTransform = questions.map(({ questionType, options, ...q }) => q);
const questionsWithOptions = transformQuestions(questionsForTransform, allOptions, questionTypeMap);
return {
...exercise,
isComplete,
questions: questionsWithOptions
};
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch exercise',
ErrorCodes.EXERCISE_FETCH_FAILED,
500
);
}
}
/**
* Updates an exercise with questions and options.
* Only updates what has changed by querying the current state first and computing a diff.
* @param exerciseId Exercise ID
* @param data Partial exercise update data
* @returns Updated exercise
*/
export async function updateExerciseService(exerciseId: string, data: TExerciseUpdate): Promise<TExercise> {
try {
return await db.transaction(async (tx) => {
const txClient = tx as DbOrTxClient;
// Update exercise basic fields only if they changed
const exerciseUpdate = buildExerciseUpdateFields(data);
if (Object.keys(exerciseUpdate).length > 0) {
const updated = await updateExercise(exerciseId, exerciseUpdate, txClient);
if (!updated) {
throw new AppError('Failed to update exercise', ErrorCodes.INTERNAL_ERROR, 500);
}
}
// Process questions - only update what changed
if (data.questions && data.questions.length > 0) {
// Query current state from DB
const { questions: currentQuestions, options: currentOptions } = await fetchQuestionsAndOptions(
exerciseId,
txClient
);
// Build current state with options mapped to their questions
const currentQuestionsWithOptions = currentQuestions.map((q) => ({
...q,
options: currentOptions.filter((opt) => opt.questionId === q.id)
}));
// Compute diff between current DB state and incoming data
const diff = computeExerciseDiff(currentQuestionsWithOptions, data.questions);
// Sync option id sequence so next inserts get ids > max(id) (avoids option_pkey duplicate)
if (
diff.options.creates.length > 0 ||
diff.questions.newQuestions.length > 0 ||
diff.questions.updates.length > 0
) {
await syncOptionIdSequence(txClient);
}
// Apply all changes in parallel (they operate on different records)
await Promise.all([
// Delete questions marked for deletion (cascade deletes their options)
diff.questions.deletedIds.length > 0 && deleteQuestionsByIds(diff.questions.deletedIds, txClient),
// Update only questions that have changed fields
diff.questions.updates.length > 0 && updateQuestions(diff.questions.updates, txClient),
// Delete options marked for deletion
diff.options.deletedIds.length > 0 && deleteOptionsByIds(diff.options.deletedIds, txClient),
// Update only options that have changed fields
diff.options.updates.length > 0 && updateOptions(diff.options.updates, txClient),
// Create new options for existing questions
diff.options.creates.length > 0 && createOptions(diff.options.creates, txClient),
// Create new questions with their options
diff.questions.newQuestions.length > 0 &&
createNewQuestionsWithOptions(exerciseId, diff.questions.newQuestions, txClient)
]);
}
// Return the updated exercise
return await getExercise(exerciseId, txClient);
});
} catch (error) {
console.error('updateExerciseService error:', error);
if (error instanceof AppError) {
throw error;
}
throw new AppError('Failed to update exercise', ErrorCodes.INTERNAL_ERROR, 500);
}
}
/**
* Deletes an exercise (cascade deletes questions and options)
* @param exerciseId Exercise ID
* @returns Deleted exercise
*/
export async function deleteExerciseService(exerciseId: string): Promise<TExercise> {
try {
const exercise = await getExerciseById(exerciseId);
if (!exercise) {
throw new AppError('Exercise not found', ErrorCodes.EXERCISE_NOT_FOUND, 404);
}
const deleted = await deleteExercise(exerciseId);
if (!deleted) {
throw new AppError('Failed to delete exercise', ErrorCodes.INTERNAL_ERROR, 500);
}
return deleted;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete exercise',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Lists exercises for a course
* @param courseId Course ID
* @param lessonId Optional lesson ID filter
* @returns Array of exercises
*/
export async function listExercises(
courseId: string,
filters: { lessonId?: string; sectionId?: string } = {},
profileId?: string
): Promise<ExerciseWithCompletion[]> {
try {
const exercises = await getExercisesByCourseId(courseId, filters);
if (!profileId) {
return exercises.map((exercise) => ({
...exercise,
isComplete: false
}));
}
const completedIds = await getExerciseCompletionsByProfile(
exercises.map((exercise) => exercise.id),
profileId
);
const completedSet = new Set(completedIds);
return exercises.map((exercise) => ({
...exercise,
isComplete: completedSet.has(exercise.id)
}));
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to list exercises',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Creates an exercise from a template
* @param courseId Course ID
* @param lessonId Lesson ID
* @param template Exercise template with questionnaire
* @returns Created exercise with questions and options
*/
export async function createExerciseFromTemplate(
courseId: string,
lessonId: string | undefined,
sectionId: string | undefined,
order: number | undefined,
template: TExerciseTemplate
): Promise<TExercise> {
try {
// Create the exercise
const exerciseData: TExerciseCreate = {
title: template.title!,
description: template.description ?? undefined,
lessonId,
sectionId,
order,
courseId
};
const exercise = await createExercise(exerciseData);
// Process the questionnaire to create questions and options
const { questions } = template.questionnaire!;
if (questions && questions.length > 0) {
await db.transaction(async (tx) => {
const txClient = tx as DbOrTxClient;
for (const question of questions) {
const { title, question_type, options, order, points } = question;
const questionSettings = (question as { settings?: Record<string, unknown> }).settings ?? {};
// Create question
const [newQuestion] = await createQuestions(
[
{
exerciseId: exercise.id,
title,
questionTypeId: question_type.id,
points: points || 0,
order: order || 0,
settings: questionSettings
}
],
txClient
);
if (!newQuestion) continue;
// Create options if not TEXTAREA type
if (question_type.id !== 3 && options && options.length > 0) {
// Filter out deleted options
// value column is UUID (default gen_random_uuid()); label is the display text only
const optionsData: TNewOption[] = options.map((opt) => ({
questionId: newQuestion.id,
label: opt.label || '',
isCorrect: opt.is_correct || false,
settings: (opt as { settings?: Record<string, unknown> }).settings ?? {}
}));
await createOptions(optionsData, txClient);
}
}
});
}
// Fetch the complete exercise with questions and options
return await getExercise(exercise.id);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to create exercise from template',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets LMS exercises for a student in an organization
* Returns exercises from unlocked lessons in courses where the student is a member
* @param profileId - The profile ID of the student
* @param orgId - The organization ID
* @returns Array of exercises with related data
*/
export async function getLMSExercisesService(profileId: string, orgId: string) {
try {
const exercises = await getLMSExercises(profileId, orgId);
return exercises;
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch LMS exercises',
ErrorCodes.EXERCISE_FETCH_FAILED,
500
);
}
}
+1
View File
@@ -0,0 +1 @@
export * from './exercise';
+8 -7
View File
@@ -1,10 +1,14 @@
import { calculateTotalPoints } from '@api/utils/template';
import { TExerciseTemplate, TNewExerciseTemplate } from '@db/types';
import { getAllTemplates, getTemplateById, getTemplateByTag } from '@db/queries/template/template';
import { TNewExerciseTemplate, TExerciseTemplate } from '@db/types';
import { calculateTotalPoints } from '@api/utils/template';
function mapTemplateToMetadata(templates: TNewExerciseTemplate[]) {
return templates.map((template) => {
const questionnaire = template.questionnaire;
if (!questionnaire) {
throw new Error(`Template ${template.id} is missing questionnaire`);
}
return {
id: template.id,
@@ -29,16 +33,13 @@ export async function fetchAllTemplatesMetadata() {
return mapTemplateToMetadata(templates);
}
export async function fetchTemplateById(id: number): Promise<TExerciseTemplate> {
let template: TExerciseTemplate;
export async function fetchTemplateById(id: number): Promise<TExerciseTemplate | undefined> {
try {
template = await getTemplateById(id);
return getTemplateById(id);
} catch (error) {
console.error('Failed to fetch template from DB:', error);
throw error;
}
return template;
}
export async function fetchTemplatesByTag(tag: string) {
+445
View File
@@ -0,0 +1,445 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import type { TExercise, TNewOption, TNewQuestion, TQuestionAnswer, TQuestionType } from '@cio/db/types';
import {
createOptions,
createQuestions,
deleteOptionsByIds,
deleteQuestionsByIds,
getOptionsByQuestionIds,
getQuestionTypesByIds,
getQuestionsByExerciseIds,
updateOptions,
updateQuestions
} from '@cio/db/queries/exercise';
import type { DbOrTxClient } from '@cio/db/drizzle';
import type { TExerciseUpdate } from '@cio/utils/validation/exercise';
type CurrentQuestion = TNewQuestion & { options?: TNewOption[] };
type CurrentOption = TNewOption;
type ExerciseAnswer = Pick<
TQuestionAnswer,
'id' | 'answerData' | 'point' | 'questionId' | 'submissionId' | 'groupMemberId'
> & { id?: number };
export type QuestionWithRelations = {
id: number | string;
value: string;
name: string;
title: string;
type: number;
points: number;
order: number;
questionType: {
id: number;
label: string;
};
questionTypeId: number;
settings?: Record<string, unknown>;
code?: string;
answers?: ExerciseAnswer[];
deletedAt?: string;
createdAt?: string;
updatedAt?: string;
options: {
id: number | string;
label: string | null;
value: string | null;
isCorrect: boolean;
settings?: Record<string, unknown>;
deletedAt?: string;
}[];
};
function normalizeSettings(value: unknown): Record<string, unknown> {
if (value && typeof value === 'object' && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return {};
}
function areSettingsEqual(left: unknown, right: unknown): boolean {
const leftNormalized = normalizeSettings(left);
const rightNormalized = normalizeSettings(right);
return JSON.stringify(leftNormalized) === JSON.stringify(rightNormalized);
}
/**
* Extracts exercise-level fields from the update payload
*/
export function buildExerciseUpdateFields(data: TExerciseUpdate): Partial<TExercise> {
const exerciseUpdate: Partial<TExercise> = {};
if (data.title !== undefined) exerciseUpdate.title = data.title;
if (data.description !== undefined) exerciseUpdate.description = data.description;
if (data.lessonId !== undefined) exerciseUpdate.lessonId = data.lessonId || null;
if (data.sectionId !== undefined) exerciseUpdate.sectionId = data.sectionId || null;
if (data.order !== undefined) exerciseUpdate.order = data.order;
if (data.isUnlocked !== undefined) exerciseUpdate.isUnlocked = data.isUnlocked;
if (data.dueBy !== undefined) exerciseUpdate.dueBy = data.dueBy || null;
return exerciseUpdate;
}
/**
* Categorizes questions into deleted, existing, and new
*/
export function categorizeQuestions(questions: NonNullable<TExerciseUpdate['questions']>) {
const deletedIds: number[] = [];
const existingQuestions: typeof questions = [];
const newQuestions: typeof questions = [];
const questionUpdates: Array<{ id: number; data: Partial<TNewQuestion> }> = [];
for (const q of questions) {
if (q.deletedAt && q.id) {
deletedIds.push(q.id);
} else if (q.id) {
existingQuestions.push(q);
questionUpdates.push({
id: q.id,
data: {
title: q.question,
points: q.points,
questionTypeId: q.questionTypeId,
settings: normalizeSettings(q.settings)
}
});
} else {
newQuestions.push(q);
}
}
return { deletedIds, existingQuestions, newQuestions, questionUpdates };
}
/**
* Categorizes options for a single question into deleted, existing, and new
*/
export function categorizeOptions(
questionId: number,
options: NonNullable<TExerciseUpdate['questions']>[number]['options']
) {
const deletedIds: number[] = [];
const existingUpdates: Array<{ id: number; data: Partial<TNewOption> }> = [];
const newOptions: TNewOption[] = [];
if (!options || options.length === 0) {
return { deletedIds, existingUpdates, newOptions };
}
for (const opt of options) {
if (opt.deletedAt && opt.id) {
deletedIds.push(opt.id);
} else if (opt.id) {
existingUpdates.push({
id: opt.id,
data: {
label: opt.label,
isCorrect: opt.isCorrect,
settings: normalizeSettings(opt.settings)
}
});
} else {
newOptions.push({
questionId,
label: opt.label,
isCorrect: opt.isCorrect,
settings: normalizeSettings(opt.settings)
});
}
}
return { deletedIds, existingUpdates, newOptions };
}
/**
* Compares current question with incoming question data and returns only changed fields
*/
function diffQuestion(
current: CurrentQuestion,
incoming: NonNullable<TExerciseUpdate['questions']>[number]
): Partial<TNewQuestion> | null {
const changes: Partial<TNewQuestion> = {};
let hasChanges = false;
if (incoming.question !== current.title) {
changes.title = incoming.question;
hasChanges = true;
}
if (incoming.points !== undefined && incoming.points !== current.points) {
changes.points = incoming.points;
hasChanges = true;
}
if (incoming.questionTypeId !== undefined && incoming.questionTypeId !== current.questionTypeId) {
changes.questionTypeId = incoming.questionTypeId;
hasChanges = true;
}
if (incoming.order !== undefined && incoming.order !== (current.order ?? undefined)) {
changes.order = incoming.order;
hasChanges = true;
}
if (!areSettingsEqual(current.settings, incoming.settings)) {
changes.settings = normalizeSettings(incoming.settings);
hasChanges = true;
}
return hasChanges ? changes : null;
}
/**
* Compares current option with incoming option data and returns only changed fields
*/
function diffOption(
current: CurrentOption,
incoming: NonNullable<NonNullable<TExerciseUpdate['questions']>[number]['options']>[number]
): Partial<TNewOption> | null {
const changes: Partial<TNewOption> = {};
let hasChanges = false;
if (incoming.label !== current.label) {
changes.label = incoming.label;
hasChanges = true;
}
if (incoming.isCorrect !== current.isCorrect) {
changes.isCorrect = incoming.isCorrect;
hasChanges = true;
}
if (!areSettingsEqual(current.settings, incoming.settings)) {
changes.settings = normalizeSettings(incoming.settings);
hasChanges = true;
}
return hasChanges ? changes : null;
}
/**
* Computes diff between current exercise state and incoming update data
* Returns only the changes that need to be applied
*/
export function computeExerciseDiff(
currentQuestions: CurrentQuestion[],
incomingQuestions: NonNullable<TExerciseUpdate['questions']>
) {
const questionMap = new Map(currentQuestions.map((q) => [q.id, q]));
const deletedQuestionIds: number[] = [];
const questionUpdates: Array<{ id: number; data: Partial<TNewQuestion> }> = [];
const newQuestions: NonNullable<TExerciseUpdate['questions']> = [];
// Process incoming questions
for (const incoming of incomingQuestions) {
if (incoming.deletedAt && incoming.id) {
deletedQuestionIds.push(incoming.id);
} else if (incoming.id) {
const current = questionMap.get(incoming.id);
if (current) {
const changes = diffQuestion(current, incoming);
if (changes) {
questionUpdates.push({ id: incoming.id, data: changes });
}
} else {
// Question ID exists but not in current state - treat as new
newQuestions.push(incoming);
}
} else {
newQuestions.push(incoming);
}
}
// Compute option diffs for existing questions
const optionDeletes: number[] = [];
const optionUpdates: Array<{ id: number; data: Partial<TNewOption> }> = [];
const optionCreates: TNewOption[] = [];
for (const incoming of incomingQuestions) {
if (!incoming.id || incoming.deletedAt) continue;
const current = questionMap.get(incoming.id);
if (!current) continue;
const currentOptionMap = new Map((current.options || []).map((opt) => [opt.id, opt]));
const incomingOptions = incoming.options || [];
const processedIncomingOptionIds = new Set<number>();
for (const incomingOpt of incomingOptions) {
if (incomingOpt.deletedAt && incomingOpt.id) {
optionDeletes.push(incomingOpt.id);
processedIncomingOptionIds.add(incomingOpt.id);
} else if (incomingOpt.id) {
processedIncomingOptionIds.add(incomingOpt.id);
const currentOpt = currentOptionMap.get(incomingOpt.id);
if (currentOpt) {
const changes = diffOption(currentOpt, incomingOpt);
if (changes) {
optionUpdates.push({ id: incomingOpt.id, data: changes });
}
} else {
// Option ID exists in incoming but not in current - treat as create
optionCreates.push({
questionId: incoming.id,
label: incomingOpt.label,
isCorrect: incomingOpt.isCorrect,
settings: normalizeSettings(incomingOpt.settings),
value: crypto.randomUUID()
});
}
} else {
// New option without ID
optionCreates.push({
questionId: incoming.id,
label: incomingOpt.label,
isCorrect: incomingOpt.isCorrect,
settings: normalizeSettings(incomingOpt.settings),
value: crypto.randomUUID()
});
}
}
// Check for options that were deleted (exist in current but not in incoming)
for (const [optId] of currentOptionMap) {
if (optId !== undefined && !processedIncomingOptionIds.has(optId)) {
optionDeletes.push(optId);
}
}
}
return {
questions: {
deletedIds: deletedQuestionIds,
updates: questionUpdates,
newQuestions
},
options: {
deletedIds: optionDeletes,
updates: optionUpdates,
creates: optionCreates
}
};
}
/**
* Creates new questions and their options in batch
*/
export async function createNewQuestionsWithOptions(
exerciseId: string,
newQuestions: NonNullable<TExerciseUpdate['questions']>,
txClient: DbOrTxClient
): Promise<void> {
const createdQuestions = await createQuestions(
newQuestions.map((q) => ({
exerciseId,
title: q.question,
questionTypeId: q.questionTypeId || 1,
points: q.points || 0,
order: typeof q.order === 'number' ? q.order : undefined,
settings: normalizeSettings(q.settings)
})),
txClient
);
const newOptions: TNewOption[] = [];
createdQuestions.forEach((newQuestion, index) => {
const questionData = newQuestions[index];
if (newQuestion && questionData?.options && questionData.options.length > 0) {
// Only include non-deleted options for new questions
for (const opt of questionData.options) {
if (!opt.deletedAt) {
newOptions.push({
questionId: newQuestion.id,
label: opt.label,
isCorrect: opt.isCorrect,
settings: normalizeSettings(opt.settings)
});
}
}
}
});
if (newOptions.length > 0) {
await createOptions(newOptions, txClient);
}
}
/**
* Fetches questions and their options for an exercise
*/
export async function fetchQuestionsAndOptions(exerciseId: string, dbClient?: DbOrTxClient) {
const questions = await getQuestionsByExerciseIds([exerciseId], dbClient);
const questionIds = questions.map((q) => q.id).filter((id): id is number => id !== undefined);
const options = questionIds.length > 0 ? await getOptionsByQuestionIds(questionIds, dbClient) : [];
return { questions, options };
}
/**
* Fetches question types and creates a lookup map
*/
export async function fetchQuestionTypesMap(
questions: TNewQuestion[],
dbClient?: DbOrTxClient
): Promise<Map<number, TQuestionType>> {
const questionTypeIds = [
...new Set(questions.map((q) => q.questionTypeId).filter((id): id is number => id !== undefined))
];
const questionTypes: TQuestionType[] =
questionTypeIds.length > 0 ? await getQuestionTypesByIds(questionTypeIds, dbClient) : [];
return new Map(questionTypes.map((qt) => [qt.id, qt]));
}
/**
* Transforms a single question with its options to frontend format
*/
export function transformQuestion(
question: TNewQuestion,
options: TNewOption[],
questionTypeMap: Map<number, TQuestionType>
): QuestionWithRelations {
const questionType = questionTypeMap.get(question.questionTypeId);
const questionTypeId = question.questionTypeId;
const questionOptions = options
.filter((opt) => opt.questionId === question.id)
.map((opt) => ({
id: opt.id!,
label: opt.label ?? null,
value: opt.value ?? null,
isCorrect: opt.isCorrect ?? false,
settings: normalizeSettings(opt.settings)
}));
return {
id: question.id!,
value: question.title || '', // value field defaults to title
name: question.name || '',
title: question.title,
type: questionTypeId, // type field (same as questionTypeId)
points: question.points || 0,
order: question.order || 0,
questionType: questionType
? {
id: questionType.id,
label: questionType.label
}
: {
id: questionTypeId,
label: ''
},
questionTypeId: questionTypeId,
settings: normalizeSettings(question.settings),
createdAt: question.createdAt || undefined,
updatedAt: question.updatedAt || undefined,
options: questionOptions
};
}
/**
* Transforms all questions to frontend format
*/
export function transformQuestions(
questions: TNewQuestion[],
options: TNewOption[],
questionTypeMap: Map<number, TQuestionType>
): QuestionWithRelations[] {
return questions.map((question) => transformQuestion(question, options, questionTypeMap));
}
+8
View File
@@ -1,4 +1,12 @@
export * from './account';
export * from './assets';
export * from './attendance';
export * from './exercise';
export * from './lesson';
export * from './mark';
export * from './media';
export * from './newsfeed';
export * from './onboarding';
export * from './submission';
export * from './dash';
export * from './course/course';
+120
View File
@@ -0,0 +1,120 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import type { TLessonLanguage, TLocale, TNewLessonLanguage } from '@db/types';
import {
getLessonLanguageByLessonIdAndLocale,
getLessonLanguagesByLessonId,
updateLessonLanguage,
upsertLessonLanguage
} from '@cio/db/queries/lesson/language';
import { getLessonById } from '@cio/db/queries/lesson/lesson';
/**
* Gets all language translations for a lesson
* @param lessonId - The lesson ID
* @returns Array of lesson languages
*/
export async function listLessonLanguages(lessonId: string): Promise<TLessonLanguage[]> {
try {
const languages = await getLessonLanguagesByLessonId(lessonId);
return languages;
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch lesson languages',
ErrorCodes.LESSON_LANGUAGE_FETCH_FAILED,
500
);
}
}
/**
* Gets a single lesson language by locale
* @param lessonId - The lesson ID
* @param locale - The locale
* @returns Lesson language or null if not found
*/
export async function getLessonLanguage(lessonId: string, locale: TLocale): Promise<TLessonLanguage | null> {
try {
const language = await getLessonLanguageByLessonIdAndLocale(lessonId, locale);
return language;
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch lesson language',
ErrorCodes.LESSON_LANGUAGE_FETCH_FAILED,
500
);
}
}
/**
* Creates or updates a lesson language translation
* @param lessonId - The lesson ID
* @param data - Lesson language data
* @returns Created or updated lesson language
*/
export async function upsertLessonLanguageService(
lessonId: string,
data: Omit<TNewLessonLanguage, 'lessonId'>
): Promise<TLessonLanguage> {
try {
// Verify lesson exists
const lesson = await getLessonById(lessonId);
if (!lesson) {
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
}
const language = await upsertLessonLanguage({
...data,
lessonId
});
return language;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to create or update lesson language',
ErrorCodes.LESSON_LANGUAGE_CREATE_FAILED,
500
);
}
}
/**
* Updates a lesson language translation
* @param lessonId - The lesson ID
* @param locale - The locale
* @param data - Lesson language update data
* @returns Updated lesson language
*/
export async function updateLessonLanguageService(
lessonId: string,
locale: TLocale,
data: Partial<TNewLessonLanguage>
): Promise<TLessonLanguage> {
try {
// Verify lesson exists
const lesson = await getLessonById(lessonId);
if (!lesson) {
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
}
const existing = await getLessonLanguageByLessonIdAndLocale(lessonId, locale);
if (!existing) {
throw new AppError('Lesson language not found', ErrorCodes.LESSON_LANGUAGE_NOT_FOUND, 404);
}
const language = await updateLessonLanguage(lessonId, locale, data);
return language;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update lesson language',
ErrorCodes.LESSON_LANGUAGE_UPDATE_FAILED,
500
);
}
}
+1
View File
@@ -0,0 +1 @@
export * from './lesson';
+362
View File
@@ -0,0 +1,362 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import type { TLesson, TNewLessonComment, TNewLessonCompletion } from '@cio/db/types';
import type { TLessonCreate, TLessonReorder, TLessonUpdate } from '@cio/utils/validation/lesson';
import {
createLessonComment,
createLessons,
deleteLesson,
deleteLessonComment,
getLessonById,
getLessonCommentsByLessonId,
getLessonCommentsByLessonIdPaginated,
getLessonCompletion,
getLessonVersionHistory,
getLessonsByCourseId,
updateLesson,
updateLessonComment,
upsertLessonCompletion,
type LessonById
} from '@cio/db/queries/lesson';
import { enrichLessonWithPresignedUrls } from '@api/utils/lesson-media';
/**
* Creates a new lesson
* @param courseId Course ID
* @param data Lesson creation data
* @returns Created lesson
*/
export async function createLesson(courseId: string, data: TLessonCreate): Promise<TLesson> {
try {
const lessonData = {
...data,
courseId
};
const [lesson] = await createLessons([lessonData]);
if (!lesson) {
throw new AppError('Failed to create lesson', ErrorCodes.INTERNAL_ERROR, 500);
}
return lesson;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to create lesson',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets a lesson by ID
* @param lessonId Lesson ID
* @returns Lesson or throws error if not found
*/
export async function getLesson(lessonId: string): Promise<LessonById> {
try {
const lesson = await getLessonById(lessonId);
if (!lesson) {
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
}
return enrichLessonWithPresignedUrls(lesson);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
// Log error with context for debugging
const errorMessage = error instanceof Error ? error.message : 'Failed to fetch lesson';
console.error(`Error fetching lesson ${lessonId}:`, errorMessage, error);
throw new AppError(errorMessage, ErrorCodes.LESSON_FETCH_FAILED, 500);
}
}
/**
* Updates a lesson
* @param lessonId Lesson ID
* @param data Partial lesson update data
* @returns Updated lesson
*/
export async function updateLessonService(lessonId: string, data: TLessonUpdate): Promise<TLesson> {
try {
const updated = await updateLesson(lessonId, data);
if (!updated) {
throw new AppError('Failed to update lesson', ErrorCodes.INTERNAL_ERROR, 500);
}
return updated;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update lesson',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Deletes a lesson
* @param lessonId Lesson ID
* @returns Deleted lesson
*/
export async function deleteLessonService(lessonId: string): Promise<TLesson> {
try {
const deleted = await deleteLesson(lessonId);
if (!deleted) {
throw new AppError('Failed to delete lesson', ErrorCodes.INTERNAL_ERROR, 500);
}
return deleted;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete lesson',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Lists lessons for a course
* @param courseId Course ID
* @param sectionId Optional section ID filter
* @returns Array of lessons
*/
export async function listLessons(courseId: string, sectionId?: string): Promise<TLesson[]> {
try {
const lessons = await getLessonsByCourseId(courseId);
if (sectionId) {
return lessons.filter((lesson) => lesson.sectionId === sectionId);
}
return lessons;
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to list lessons',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Reorders lessons
* @param lessons Array of lesson IDs, orders, and optional sectionIds
* @returns Updated lessons
*/
export async function reorderLessons(lessons: TLessonReorder['lessons']): Promise<TLesson[]> {
try {
// Update each lesson's order and optionally sectionId
const updatePromises = lessons.map(({ id, order, sectionId }) =>
updateLesson(id, { order, ...(sectionId !== undefined && { sectionId }) })
);
const updated = await Promise.all(updatePromises);
return updated.filter((l): l is TLesson => l !== null);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to reorder lessons',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
// Lesson Comment Services
/**
* Gets comments for a lesson
* @param lessonId Lesson ID
* @returns Array of comments
*/
export async function getLessonComments(lessonId: string) {
try {
return getLessonCommentsByLessonId(lessonId);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to get lesson comments',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets paginated comments for a lesson
* @param lessonId Lesson ID
* @param options Pagination options (cursor, limit)
* @returns Paginated comments with metadata
*/
export async function getLessonCommentsPaginated(lessonId: string, options: { cursor?: string; limit: number }) {
try {
return getLessonCommentsByLessonIdPaginated(lessonId, options);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to get paginated lesson comments',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Creates a lesson comment
* @param lessonId Lesson ID
* @param groupMemberId Group member ID (author)
* @param comment Comment text
* @returns Created comment
*/
export async function createLessonCommentService(lessonId: string, groupMemberId: string, comment: string) {
try {
const commentData: TNewLessonComment = {
lessonId,
groupmemberId: groupMemberId,
comment
};
return await createLessonComment(commentData);
} catch (error) {
console.log('error', error);
throw new AppError(
error instanceof Error ? error.message : 'Failed to create lesson comment',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Updates a lesson comment
* @param commentId Comment ID
* @param comment Updated comment text
* @returns Updated comment
*/
export async function updateLessonCommentService(commentId: number, comment: string) {
try {
const updated = await updateLessonComment(commentId, comment);
if (!updated) {
throw new AppError('Comment not found', ErrorCodes.LESSON_COMMENT_UPDATE_FAILED, 404);
}
return updated;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update lesson comment',
ErrorCodes.LESSON_COMMENT_UPDATE_FAILED,
500
);
}
}
/**
* Deletes a lesson comment
* @param commentId Comment ID
* @returns Deleted comment
*/
export async function deleteLessonCommentService(commentId: number) {
try {
const deleted = await deleteLessonComment(commentId);
if (!deleted) {
throw new AppError('Comment not found', ErrorCodes.COMMENT_NOT_FOUND, 404);
}
return deleted;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete lesson comment',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
// Lesson Completion Services
/**
* Gets lesson completion status
* @param lessonId Lesson ID
* @param profileId Profile ID
* @returns Completion record or null
*/
export async function getLessonCompletionService(lessonId: string, profileId: string) {
try {
return await getLessonCompletion(lessonId, profileId);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to get lesson completion',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Creates or updates lesson completion
* @param lessonId Lesson ID
* @param profileId Profile ID
* @param isComplete Completion status
* @returns Completion record
*/
export async function upsertLessonCompletionService(lessonId: string, profileId: string, isComplete: boolean) {
try {
const completionData: TNewLessonCompletion = {
lessonId,
profileId,
isComplete
};
return await upsertLessonCompletion(completionData);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to update lesson completion',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets lesson version history for a lesson and locale
* @param lessonId Lesson ID
* @param locale Locale
* @param endRange End range for pagination (0-indexed, inclusive)
* @returns Array of lesson version history entries
*/
export async function getLessonHistoryService(lessonId: string, locale: string, endRange: number) {
try {
return getLessonVersionHistory(lessonId, locale, endRange);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to get lesson history',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
+111
View File
@@ -0,0 +1,111 @@
import { env } from '@api/config/env';
import { LICENSE_FEATURE, type LicenseFeatureId } from '@cio/utils/license';
export type LicenseStatus = {
valid: boolean;
features: string[];
expiresAt?: string;
};
const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
let cachedStatus: LicenseStatus | null = null;
let cacheExpiry = 0;
/** All available license features for non-self-hosted (cloud/SaaS) instances */
const ALL_FEATURES = Object.values(LICENSE_FEATURE);
/** Check if running in self-hosted mode */
function isSelfHosted(): boolean {
return env.PUBLIC_IS_SELFHOSTED === 'true';
}
/**
* Calls the external license verification API.
* or body: { licenseKey: string }.
* Expected response: { valid: boolean, features?: string[], expiresAt?: string }
*/
async function fetchLicenseFromApi(): Promise<LicenseStatus> {
const url = 'https://enterprise-api.classroomio.dev';
const key = env.LICENSE_KEY?.trim();
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ licenseKey: key })
});
if (!response.ok) {
console.error('License API error:', response.status, await response.text());
return { valid: false, features: [] };
}
const data = (await response.json()) as { valid?: boolean; features?: string[]; expiresAt?: string };
return {
valid: !!data.valid,
features: Array.isArray(data.features) ? data.features : [],
expiresAt: typeof data.expiresAt === 'string' ? data.expiresAt : undefined
};
} catch (error) {
console.error('License verification failed:', error);
return { valid: false, features: [] };
}
}
/**
* Gets the current license status. Uses in-memory cache (1 hour TTL).
* For non-self-hosted (cloud/SaaS), returns all features as valid.
*/
export async function getLicenseStatus(): Promise<LicenseStatus> {
const now = Date.now();
if (cachedStatus !== null && now < cacheExpiry) {
return cachedStatus;
}
// Cloud/SaaS has no license restrictions - all features enabled
if (!isSelfHosted()) {
const status: LicenseStatus = { valid: true, features: ALL_FEATURES };
cachedStatus = status;
cacheExpiry = now + CACHE_TTL_MS;
return status;
}
const status = await fetchLicenseFromApi();
cachedStatus = status;
cacheExpiry = now + CACHE_TTL_MS;
return status;
}
/**
* Checks if a specific feature is licensed.
* @param feature - Feature ID from LICENSE_FEATURE
* Non-self-hosted (cloud/SaaS) instances have all features enabled.
*/
export async function isFeatureLicensed(feature: LicenseFeatureId | string): Promise<boolean> {
// Cloud/SaaS has no license restrictions
if (!isSelfHosted()) {
return true;
}
const status = await getLicenseStatus();
if (!status.valid) return false;
return status.features.includes(feature);
}
/**
* Checks if the given feature is licensed. Synchronous version using cached status.
* Returns false if cache is cold (first call will populate async).
* Use getLicenseStatus() or isFeatureLicensed() for accurate checks.
* Non-self-hosted (cloud/SaaS) instances have all features enabled.
*/
export function isFeatureLicensedSync(feature: LicenseFeatureId | string): boolean {
// Cloud/SaaS has no license restrictions
if (!isSelfHosted()) {
return true;
}
if (cachedStatus === null || !cachedStatus.valid) return false;
return cachedStatus.features.includes(feature);
}
+106
View File
@@ -0,0 +1,106 @@
import { ContentType, ROLE } from '@cio/utils/constants';
import { getMarksByCourseId, type Mark } from '@cio/db/queries/mark';
import { getCourseMembers } from '@cio/db/queries/course/people';
import { getCourseWithRelations } from '@cio/db/queries/course';
import { buildCourseContent, type CourseContentItem } from '@api/services/course/utils';
import { AppError, ErrorCodes } from '@api/utils/errors';
export type GradebookExercise = {
id: string;
title: string;
points: number;
};
export type GradebookStudentMarks = Record<string, Record<string, string>>;
export type GradebookResponse = {
students: Awaited<ReturnType<typeof getCourseMembers>>;
exercises: GradebookExercise[];
studentMarksByExerciseId: GradebookStudentMarks;
};
function buildStudentMarksByExerciseId(marks: Mark[]): GradebookStudentMarks {
const result: GradebookStudentMarks = {};
for (const mark of marks) {
const { groupmemberId, exerciseId, totalPointsGotten } = mark;
if (!groupmemberId || !exerciseId) continue;
if (!result[groupmemberId]) result[groupmemberId] = {};
result[groupmemberId][exerciseId] = totalPointsGotten?.toString() ?? '0';
}
return result;
}
function buildExercises(marks: Mark[], contentItems: CourseContentItem[]): GradebookExercise[] {
const marksByExerciseId = new Map<string, { title: string; points: number }>();
const exerciseOrder: string[] = [];
for (const mark of marks) {
const { exerciseId, exerciseTitle, exercisePoints } = mark;
if (!exerciseId) continue;
if (!marksByExerciseId.has(exerciseId)) {
exerciseOrder.push(exerciseId);
marksByExerciseId.set(exerciseId, {
title: exerciseTitle ?? '',
points: exercisePoints ?? 0
});
}
}
const exerciseItems = contentItems.filter((item) => item.type === ContentType.Exercise);
if (exerciseItems.length > 0) {
return exerciseItems.map((item) => {
const fromMarks = marksByExerciseId.get(item.id);
return {
id: item.id,
title: item.title ?? fromMarks?.title ?? '',
points: fromMarks?.points ?? 0
};
});
}
return exerciseOrder.map((id) => {
const fromMarks = marksByExerciseId.get(id)!;
return {
id,
title: fromMarks?.title ?? '',
points: fromMarks?.points ?? 0
};
});
}
/**
* Returns all data needed to render the marks gradebook: students, exercises in order, and marks per student per exercise.
*/
export async function getGradebook(courseId: string): Promise<GradebookResponse> {
try {
const [marks, members, course] = await Promise.all([
getMarksByCourseId(courseId),
getCourseMembers(courseId),
getCourseWithRelations(courseId)
]);
const students = members.filter((m) => Number(m.roleId) === ROLE.STUDENT);
let contentItems: CourseContentItem[] = [];
if (course?.contentItems != null) {
const isGrouping = course.metadata?.isContentGroupingEnabled ?? true;
const content = buildCourseContent(course.contentItems, isGrouping);
contentItems = content.grouped ? (content.sections ?? []).flatMap((s) => s.items ?? []) : (content.items ?? []);
}
const exercises = buildExercises(marks, contentItems);
const studentMarksByExerciseId = buildStudentMarksByExerciseId(marks);
return {
students,
exercises,
studentMarksByExerciseId
};
} catch (error) {
console.error('getGradebook error:', error);
throw new AppError(
error instanceof Error ? error.message : 'Failed to get gradebook',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
+1
View File
@@ -0,0 +1 @@
export * from './mark';
+16
View File
@@ -0,0 +1,16 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import { getMarksByCourseId } from '@cio/db/queries/mark';
/**
* Gets marks for a course
* Marks are computed from submissions and exercises using a database function
* @param courseId Course ID
* @returns Array of mark records
*/
export async function getMarks(courseId: string) {
try {
return await getMarksByCourseId(courseId);
} catch (error) {
throw new AppError(error instanceof Error ? error.message : 'Failed to get marks', ErrorCodes.INTERNAL_ERROR, 500);
}
}
+16 -8
View File
@@ -1,19 +1,26 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import { BUCKET_NAME, MAX_IMAGE_SIZE } from '@api/constants/upload';
import { MAX_IMAGE_SIZE } from '@api/constants/upload';
import { ALLOWED_IMAGE_TYPES } from '@cio/utils/validation';
import { env } from '@api/config/env';
import { getStorageConfig } from '@api/config/storage';
import { generateFileKey } from '@api/utils/upload';
import { uploadToS3 } from '@api/utils/s3';
/**
* Uploads an image file to S3 and returns the public URL
* Uploads an image file to object storage and returns the public URL
* @param file - The image file to upload
* @returns Object containing the public URL and file key
*/
export async function uploadImage(file: File) {
if (!env.CLOUDFLARE_IMAGE_BUCKET_DOMAIN) {
throw new AppError(new Error('Image bucket domain not configured'), ErrorCodes.INTERNAL_ERROR, 500);
const config = getStorageConfig();
if (!config.mediaPublicBaseUrl) {
throw new AppError(
new Error(
'Media public URL not configured. Set OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL or CLOUDFLARE_IMAGE_BUCKET_DOMAIN.'
),
ErrorCodes.INTERNAL_ERROR,
500
);
}
// Validate file type
@@ -41,9 +48,9 @@ export async function uploadImage(file: File) {
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
// Upload to S3
// Upload to object storage
const uploadResult = await uploadToS3({
Bucket: BUCKET_NAME.MEDIA,
Bucket: config.bucketMedia,
Key: fileKey,
Body: buffer,
ContentType: file.type,
@@ -55,7 +62,8 @@ export async function uploadImage(file: File) {
}
// Construct public URL
const publicUrl = `${env.CLOUDFLARE_IMAGE_BUCKET_DOMAIN}/${fileKey}`;
const baseUrl = config.mediaPublicBaseUrl.replace(/\/$/, '');
const publicUrl = `${baseUrl}/${fileKey}`;
return {
url: publicUrl,
+1
View File
@@ -0,0 +1 @@
export * from './newsfeed';
+413
View File
@@ -0,0 +1,413 @@
import { AppError, ErrorCodes } from '@api/utils/errors';
import type { TCourseNewsfeed, TNewCourseNewsfeed, TNewCourseNewsfeedComment } from '@cio/db/types';
import type { TNewsfeedCreate, TNewsfeedUpdate } from '@cio/utils/validation/newsfeed';
import {
createNewsfeed,
createNewsfeedComment,
deleteNewsfeed,
deleteNewsfeedComment,
getNewsfeedByCourseId,
getNewsfeedByCourseIdPaginated,
getNewsfeedById,
getNewsfeedCommentsByFeedId,
getNewsfeedCommentsByFeedIdPaginated,
getNewsfeedForEmail,
updateNewsfeed,
updateNewsfeedComment
} from '@cio/db/queries/newsfeed';
import { env } from '@api/config/env';
import { buildEmailFromName, sendEmail } from '@cio/email';
/**
* Lists newsfeed items for a course
* @param courseId Course ID
* @returns Array of newsfeed items
*/
export async function listNewsfeed(courseId: string): Promise<TCourseNewsfeed[]> {
try {
return await getNewsfeedByCourseId(courseId);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to list newsfeed',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Lists paginated newsfeed items for a course
* @param courseId Course ID
* @param options Pagination options (cursor, limit)
* @returns Paginated newsfeed items with metadata and author profile
*/
export async function listNewsfeedPaginated(courseId: string, options: { cursor?: string; limit: number }) {
try {
return getNewsfeedByCourseIdPaginated(courseId, options);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to list paginated newsfeed',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets a newsfeed item by ID
* @param feedId Newsfeed ID
* @returns Newsfeed item
*/
export async function getNewsfeedItem(feedId: string): Promise<TCourseNewsfeed> {
try {
const feed = await getNewsfeedById(feedId);
if (!feed) {
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
}
return feed;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to fetch newsfeed item',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Creates a new newsfeed item
* @param courseId Course ID
* @param authorId Group member ID (author)
* @param data Newsfeed creation data
* @returns Created newsfeed item
*/
export async function createNewsfeedService(
courseId: string,
authorId: string,
data: TNewsfeedCreate
): Promise<TCourseNewsfeed> {
try {
const newsfeedData: TNewCourseNewsfeed = {
courseId,
authorId,
content: data.content,
isPinned: data.isPinned || false
};
const feed = await createNewsfeed(newsfeedData);
// Send email notifications to course members (async, don't wait)
sendNewsfeedPostEmail(feed.id, authorId).catch((error) => {
console.error('Failed to send newsfeed post email:', error);
});
return feed;
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to create newsfeed',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Updates a newsfeed item (content and isPinned only)
* @param feedId Newsfeed ID
* @param data Partial newsfeed update data
* @returns Updated newsfeed item
*/
export async function updateNewsfeedService(feedId: string, data: TNewsfeedUpdate): Promise<TCourseNewsfeed> {
try {
const updated = await updateNewsfeed(feedId, data);
if (!updated) {
// If no row was updated, it usually means the feed doesn't exist.
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
}
return updated;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update newsfeed',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Updates a newsfeed item's reaction
* @param feedId Newsfeed ID
* @param reaction Reaction data
* @returns Updated newsfeed item
*/
export async function updateNewsfeedReactionService(
feedId: string,
reaction: TCourseNewsfeed['reaction']
): Promise<TCourseNewsfeed> {
try {
const updated = await updateNewsfeed(feedId, { reaction });
if (!updated) {
// If no row was updated, it usually means the feed doesn't exist.
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
}
return updated;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update newsfeed reaction',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Deletes a newsfeed item
* @param feedId Newsfeed ID
* @returns Deleted newsfeed item
*/
export async function deleteNewsfeedService(feedId: string): Promise<TCourseNewsfeed> {
try {
const deleted = await deleteNewsfeed(feedId);
if (!deleted) {
// If no row was deleted, it usually means the feed doesn't exist.
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
}
return deleted;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete newsfeed',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets comments for a newsfeed item
* @param feedId Newsfeed ID
* @returns Array of comments
*/
export async function getNewsfeedComments(feedId: string) {
try {
return await getNewsfeedCommentsByFeedId(feedId);
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to get newsfeed comments',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Gets paginated comments for a newsfeed item
* @param feedId Newsfeed ID
* @param options Pagination options (cursor, limit)
* @returns Paginated comments with metadata
*/
export async function getNewsfeedCommentsService(feedId: string, options: { cursor?: string; limit: number }) {
try {
const feed = await getNewsfeedById(feedId);
if (!feed) {
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
}
return await getNewsfeedCommentsByFeedIdPaginated(feedId, options);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to get paginated newsfeed comments',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Creates a newsfeed comment
* @param feedId Newsfeed ID
* @param authorId Group member ID (author)
* @param content Comment content
* @returns Created comment
*/
export async function createNewsfeedCommentService(feedId: string, authorId: string, content: string) {
try {
const commentData: TNewCourseNewsfeedComment = {
courseNewsfeedId: feedId,
authorId,
content
};
const comment = await createNewsfeedComment(commentData);
// Send email notification to feed author (async, don't wait)
sendNewsfeedCommentEmail(feedId, content).catch((error) => {
console.error('Failed to send newsfeed comment email:', error);
});
return comment;
} catch (error) {
throw new AppError(
error instanceof Error ? error.message : 'Failed to create newsfeed comment',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Updates a newsfeed comment
* @param commentId Comment ID
* @param content Updated comment content
* @returns Updated comment
*/
export async function updateNewsfeedCommentService(commentId: number, content: string) {
try {
const updated = await updateNewsfeedComment(commentId, content);
if (!updated) {
throw new AppError('Comment not found', ErrorCodes.NEWSFEED_COMMENT_UPDATE_FAILED, 404);
}
return updated;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to update newsfeed comment',
ErrorCodes.NEWSFEED_COMMENT_UPDATE_FAILED,
500
);
}
}
/**
* Deletes a newsfeed comment
* @param commentId Comment ID
* @returns Deleted comment
*/
export async function deleteNewsfeedCommentService(commentId: number) {
try {
const deleted = await deleteNewsfeedComment(commentId);
if (!deleted) {
throw new AppError('Comment not found', ErrorCodes.COMMENT_NOT_FOUND, 404);
}
return deleted;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(
error instanceof Error ? error.message : 'Failed to delete newsfeed comment',
ErrorCodes.INTERNAL_ERROR,
500
);
}
}
/**
* Sends email notification when a new feed is created
* Sends to all course members except the author
*/
async function sendNewsfeedPostEmail(feedId: string, authorId: string) {
try {
const feedData = await getNewsfeedForEmail(feedId, authorId);
if (!feedData || !feedData.courseId || !feedData.courseTitle || !feedData.organization?.siteName) {
return;
}
if (feedData.courseMembers.length === 0) {
return;
}
const orgName = feedData.organization?.name || 'ClassroomIO';
const orgSiteName = feedData.organization?.siteName || 'app';
const postLink = `https://${orgSiteName}.classroomio.com/courses/${feedData.courseId}?feedId=${feedData.feedId}`;
// Send email to all course members
const emailPromises = feedData.courseMembers.map((member) => {
if (!member.email) return Promise.resolve();
return sendEmail('newsfeedPost', {
to: member.email,
fields: {
courseTitle: feedData.courseTitle!,
teacherName: feedData.author?.fullname || 'A teacher',
content: feedData.content || '',
postLink,
orgName
},
from: buildEmailFromName(`${orgName} - ClassroomIO`),
replyTo: feedData.author?.email || '[email protected]'
});
});
await Promise.all(emailPromises);
} catch (error) {
console.error('Error sending newsfeed post email:', error);
// Don't throw - email failures shouldn't break the API
}
}
/**
* Sends email notification when a comment is added to a feed
* Sends to the feed author (teacher)
*/
async function sendNewsfeedCommentEmail(feedId: string, commentContent: string) {
try {
const feedData = await getNewsfeedForEmail(feedId);
if (!feedData || !feedData.courseId || !feedData.courseTitle || !feedData.organization?.siteName) {
return;
}
if (!feedData.author?.email) {
return;
}
const orgName = feedData.organization?.name || 'ClassroomIO';
const orgSiteName = feedData.organization?.siteName || 'app';
const postLink = `https://${orgSiteName}.classroomio.com/courses/${feedData.courseId}?feedId=${feedData.feedId}`;
await sendEmail('newsfeedComment', {
to: feedData.author.email,
fields: {
courseTitle: feedData.courseTitle,
comment: commentContent,
postLink,
orgName
},
from: buildEmailFromName(`${orgName} - ClassroomIO`),
replyTo: '[email protected]'
});
} catch (error) {
console.error('Error sending newsfeed comment email:', error);
// Don't throw - email failures shouldn't break the API
}
}
+23 -6
View File
@@ -4,10 +4,12 @@ import {
checkSiteNameExists,
createOrganization,
createOrganizationMember,
getOrganizationByProfileId
getOrganizationByProfileId,
getOrganizationCount
} from '@cio/db/queries';
import { getProfileById, updateProfile } from '@cio/db/queries/auth';
import { env } from '@api/config/env';
import { ROLE } from '@cio/utils/constants';
import { db } from '@cio/db/drizzle';
import { sendEmail } from '@cio/email';
@@ -20,6 +22,14 @@ export async function createOrganizationWithOwner(
siteName: string;
}
) {
// Self-hosted: block org creation when an org already exists
if (env.PUBLIC_IS_SELFHOSTED === 'true') {
const count = await getOrganizationCount();
if (count > 0) {
throw new AppError('Self-hosted instances support only one organization', ErrorCodes.VALIDATION_ERROR, 403);
}
}
// Business Logic: Check sitename availability
const exists = await checkSiteNameExists(input.siteName);
if (exists) {
@@ -56,10 +66,10 @@ export async function createOrganizationWithOwner(
} catch (error) {
console.error('Error creating organization:', error);
// Handle database constraint violations
if (error.code === '23505') {
if (error && typeof error === 'object' && 'code' in error && error.code === '23505') {
throw new AppError(`Site name '${input.siteName}' already exists`, ErrorCodes.SITENAME_EXISTS, 409);
}
throw new AppError(error, ErrorCodes.ORG_CREATE_FAILED, 500);
throw new AppError(error instanceof Error ? error : new Error('Unknown error'), ErrorCodes.ORG_CREATE_FAILED, 500);
}
}
@@ -76,11 +86,15 @@ export async function updateUserOnboarding(userId: string, data: Partial<TProfil
if (error instanceof AppError) {
throw error;
}
throw new AppError(error, ErrorCodes.PROFILE_UPDATE_FAILED, 500);
throw new AppError(
error instanceof Error ? error : new Error('Unknown error'),
ErrorCodes.PROFILE_UPDATE_FAILED,
500
);
}
}
export async function completeOnboarding(user: Partial<TUser>) {
export async function completeOnboarding(user: Partial<TUser> & { id: string; email: string }) {
try {
const profile = await getProfileById(user.id);
if (!profile) {
@@ -94,6 +108,9 @@ export async function completeOnboarding(user: Partial<TUser>) {
}
});
} catch (error) {
throw new AppError(error, ErrorCodes.INTERNAL_ERROR, 500);
if (error instanceof AppError) {
throw error;
}
throw new AppError(error instanceof Error ? error : new Error('Unknown error'), ErrorCodes.INTERNAL_ERROR, 500);
}
}
+48
View File
@@ -0,0 +1,48 @@
// Code from https://github.com/vercel/platforms/blob/1ed55b13bcae97b037c69ec40b4c32df21c2412c/lib/domains.ts
import { env } from '@api/config/env';
export const addDomainToVercel = async (domain: string) => {
return await fetch(
`https://api.vercel.com/v10/projects/${env.PROJECT_ID_VERCEL}/domains${
env.TEAM_ID_VERCEL ? `?teamId=${env.TEAM_ID_VERCEL}` : ''
}`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${env.AUTH_BEARER_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: domain
})
}
).then((res) => res.json());
};
export const removeDomainFromVercelProject = async (domain: string) => {
return await fetch(
`https://api.vercel.com/v9/projects/${env.PROJECT_ID_VERCEL}/domains/${domain}${
env.TEAM_ID_VERCEL ? `?teamId=${env.TEAM_ID_VERCEL}` : ''
}`,
{
headers: {
Authorization: `Bearer ${env.AUTH_BEARER_TOKEN}`
},
method: 'DELETE'
}
).then((res) => res.json());
};
export const getConfigResponse = async (domain: string) => {
return await fetch(
`https://api.vercel.com/v6/domains/${domain}/config${env.TEAM_ID_VERCEL ? `?teamId=${env.TEAM_ID_VERCEL}` : ''}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${env.AUTH_BEARER_TOKEN}`,
'Content-Type': 'application/json'
}
}
).then((res) => res.json());
};

Some files were not shown because too many files have changed in this diff Show More