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:
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
@@ -1,10 +1,23 @@
|
||||
export const statuses = [
|
||||
{
|
||||
chipClassName: 'bg-green-600 text-white',
|
||||
chipLabel: 'In progress'
|
||||
},
|
||||
{
|
||||
chipClassName: 'bg-red-600 text-white',
|
||||
chipLabel: 'Completed'
|
||||
}
|
||||
];
|
||||
export const ROUTES = {
|
||||
COURSES: 'courses',
|
||||
LESSONS: 'lessons'
|
||||
};
|
||||
|
||||
export const EXERCISE_TEMPLATE_TAGS = {
|
||||
HTML: 'HTML',
|
||||
CSS: 'CSS',
|
||||
JS: 'JS',
|
||||
Typescript: 'Typescript',
|
||||
ReactJS: 'ReactJS',
|
||||
VueJS: 'VueJS',
|
||||
NodeJS: 'NodeJS',
|
||||
Python: 'Python',
|
||||
PHP: 'PHP',
|
||||
GIT: 'GIT'
|
||||
};
|
||||
|
||||
export const COURSE_SORT_OPTIONS = [
|
||||
{ value: '0', label: 'courses.course_filter.date_created' },
|
||||
{ value: '1', label: 'courses.course_filter.published' },
|
||||
{ value: '2', label: 'courses.course_filter.lessons' }
|
||||
] as const;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { Course, CourseContentItem, CourseContentSection } from './types';
|
||||
import { ExerciseIcon, LessonIcon } from '@cio/ui/custom/moving-icons';
|
||||
|
||||
import { ContentType as CourseContentType } from '@cio/utils/constants/content';
|
||||
import TableOfContentsIcon from '@lucide/svelte/icons/table-of-contents';
|
||||
|
||||
export type ContentItem = CourseContentItem;
|
||||
export type ContentSection = CourseContentSection;
|
||||
|
||||
export const CONTENT_DEFINITIONS = {
|
||||
[CourseContentType.Section]: {
|
||||
label: 'Section',
|
||||
icon: TableOfContentsIcon
|
||||
},
|
||||
[CourseContentType.Lesson]: {
|
||||
label: 'Lesson',
|
||||
icon: LessonIcon
|
||||
},
|
||||
[CourseContentType.Exercise]: {
|
||||
label: 'Exercise',
|
||||
icon: ExerciseIcon
|
||||
}
|
||||
} as const;
|
||||
|
||||
const EMPTY_CONTENT = {
|
||||
grouped: false,
|
||||
sections: [] as ContentSection[],
|
||||
items: [] as ContentItem[]
|
||||
};
|
||||
|
||||
export function getContentRoute(courseId: string, item: ContentItem) {
|
||||
if (item.type === CourseContentType.Lesson) {
|
||||
return `/courses/${courseId}/lessons/${item.id}`;
|
||||
}
|
||||
|
||||
if (item.type === CourseContentType.Exercise) {
|
||||
return `/courses/${courseId}/exercises/${item.id}`;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
export function getCourseContent(course: Course | null) {
|
||||
return course?.content ?? EMPTY_CONTENT;
|
||||
}
|
||||
|
||||
const NAVIGABLE_CONTENT_TYPES = [CourseContentType.Lesson, CourseContentType.Exercise] as const;
|
||||
|
||||
export function getOrderedNavigableContent(course: Course | null): ContentItem[] {
|
||||
const content = getCourseContent(course);
|
||||
const items = content.grouped ? content.sections.flatMap((s) => s.items) : content.items;
|
||||
return items.filter((item) =>
|
||||
NAVIGABLE_CONTENT_TYPES.includes(item.type as (typeof NAVIGABLE_CONTENT_TYPES)[number])
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,41 @@
|
||||
export function validateForm(fields) {
|
||||
let hasError = false;
|
||||
const { title, description } = fields;
|
||||
const fieldErrors = {
|
||||
title: '',
|
||||
description: ''
|
||||
};
|
||||
import type { CourseMembers, SubmissionAnswer } from './types';
|
||||
|
||||
if (!title) {
|
||||
fieldErrors.title = 'Title is required';
|
||||
hasError = true;
|
||||
import type { AnswerData } from '@cio/question-types';
|
||||
import type { Question } from '../types';
|
||||
import { ROUTES } from './constants';
|
||||
|
||||
export function getGroupMemberId(people: CourseMembers, profileId: string): string | undefined {
|
||||
const groupMember = people.find((person) => person.profileId === profileId);
|
||||
|
||||
return groupMember?.id;
|
||||
}
|
||||
|
||||
export function getNavItemRoute(courseId, routeId?: string) {
|
||||
const path = `/${ROUTES.COURSES}/${courseId}`;
|
||||
|
||||
if (!routeId) {
|
||||
return path;
|
||||
}
|
||||
|
||||
if (!description) {
|
||||
fieldErrors.description = 'Description is required';
|
||||
hasError = true;
|
||||
return `${path}/${routeId}`;
|
||||
}
|
||||
|
||||
export function getLessonsRoute(courseId, lessonId?: string) {
|
||||
const path = getNavItemRoute(courseId, ROUTES.LESSONS);
|
||||
|
||||
if (!lessonId) {
|
||||
return path;
|
||||
}
|
||||
|
||||
return {
|
||||
hasError,
|
||||
fieldErrors
|
||||
};
|
||||
return `${path}/${lessonId}`;
|
||||
}
|
||||
|
||||
export function getLectureNo(index, initNo = '0') {
|
||||
if (index <= 9) {
|
||||
return `${initNo}${index}`;
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
export function calcProgressRate(progressRate?: number, totalLessons?: number): number {
|
||||
@@ -29,3 +45,44 @@ export function calcProgressRate(progressRate?: number, totalLessons?: number):
|
||||
|
||||
return Math.round((progressRate / totalLessons) * 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates combined course progress from lessons and exercises.
|
||||
* Uses (lessonsCompleted + exercisesCompleted) / (totalLessons + totalExercises) when both exist.
|
||||
* Falls back to lesson-only progress when there are no exercises.
|
||||
*/
|
||||
export function calcCourseProgress(params: {
|
||||
lessonsCompleted: number;
|
||||
totalLessons: number;
|
||||
exercisesCompleted?: number;
|
||||
totalExercises?: number;
|
||||
}): number {
|
||||
const { lessonsCompleted, totalLessons, exercisesCompleted = 0, totalExercises = 0 } = params;
|
||||
const totalItems = totalLessons + totalExercises;
|
||||
if (totalItems === 0) return 0;
|
||||
|
||||
const completedItems = lessonsCompleted + exercisesCompleted;
|
||||
|
||||
return Math.round((completedItems / totalItems) * 100);
|
||||
}
|
||||
|
||||
export function formatAnswers(data: {
|
||||
questions: Question[];
|
||||
answers: SubmissionAnswer[];
|
||||
}): Record<string, AnswerData> {
|
||||
const answers: Record<string, AnswerData> = {};
|
||||
const questionByIdAndName: Record<string, string> = {};
|
||||
|
||||
for (const question of data.questions) {
|
||||
questionByIdAndName[String(question.id)] = question.name ?? '';
|
||||
}
|
||||
|
||||
for (const answer of data.answers) {
|
||||
const questionName = questionByIdAndName[String(answer.questionId)];
|
||||
if (questionName && answer.answerData) {
|
||||
answers[questionName] = answer.answerData;
|
||||
}
|
||||
}
|
||||
|
||||
return answers;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import type { CourseContentItem, CourseMembers } from '$features/course/utils/types';
|
||||
import type { Marks } from './types';
|
||||
import { ContentType } from '@cio/utils/constants/content';
|
||||
import Papa from 'papaparse';
|
||||
import autoTable from 'jspdf-autotable';
|
||||
import jsPDF from 'jspdf';
|
||||
|
||||
/** Exercise information for display in marks table (linear, no lesson grouping) */
|
||||
export interface ExerciseInfo {
|
||||
id: string;
|
||||
title: string;
|
||||
points: number;
|
||||
}
|
||||
|
||||
/** Maps groupMemberId -> exerciseId -> points obtained (as string) */
|
||||
export type StudentMarksByExercise = {
|
||||
[groupMemberId: string]: {
|
||||
[exerciseId: string]: string;
|
||||
};
|
||||
};
|
||||
|
||||
/** Student's exercise data for calculating totals */
|
||||
export type StudentExerciseData =
|
||||
| {
|
||||
[exerciseId: string]: string;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
/** Processed marks data structure returned from server */
|
||||
export interface MarksPageData {
|
||||
studentMarksByExerciseId: StudentMarksByExercise;
|
||||
exercises: ExerciseInfo[];
|
||||
students: CourseMembers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate total points for a student from their exercise data
|
||||
* @param studentExerciseData Student's marks by exercise ID
|
||||
* @returns Total points as number
|
||||
*/
|
||||
export function calculateStudentTotal(studentExerciseData: StudentExerciseData): number {
|
||||
if (!studentExerciseData) return 0;
|
||||
|
||||
return Object.values(studentExerciseData).reduce((total: number, point) => {
|
||||
return (total += parseInt(point as string, 10));
|
||||
}, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate average grade as percentage (points earned / total points possible) for a student
|
||||
* @param studentExerciseData Student's marks by exercise ID
|
||||
* @param exercises Ordered list of exercises with points
|
||||
* @returns Rounded percentage 0-100, or null if no exercises with points
|
||||
*/
|
||||
export function calculateStudentAverage(
|
||||
studentExerciseData: StudentExerciseData,
|
||||
exercises: ExerciseInfo[]
|
||||
): number | null {
|
||||
if (!studentExerciseData || exercises.length === 0) return null;
|
||||
const totalPossible = exercises.reduce((sum, ex) => sum + ex.points, 0);
|
||||
if (totalPossible === 0) return null;
|
||||
const totalEarned = exercises.reduce((sum, ex) => {
|
||||
const pts = studentExerciseData[ex.id];
|
||||
return sum + (pts != null ? parseInt(pts, 10) : 0);
|
||||
}, 0);
|
||||
return Math.round((totalEarned / totalPossible) * 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform marks array into nested object structure mapping groupMemberId -> exerciseId -> points
|
||||
* @param marks Array of mark records from API
|
||||
* @returns Nested object structure for student marks
|
||||
*/
|
||||
export function processMarksIntoStudentMarksByExerciseId(marks: Marks): StudentMarksByExercise {
|
||||
const result: StudentMarksByExercise = {};
|
||||
|
||||
if (!Array.isArray(marks)) return result;
|
||||
|
||||
marks.forEach((mark) => {
|
||||
const { groupmemberId, exerciseId, totalPointsGotten } = mark;
|
||||
|
||||
if (!groupmemberId || !exerciseId) return;
|
||||
|
||||
if (result[groupmemberId]) {
|
||||
result[groupmemberId] = {
|
||||
...result[groupmemberId],
|
||||
[exerciseId]: totalPointsGotten?.toString() || '0'
|
||||
};
|
||||
} else {
|
||||
result[groupmemberId] = {
|
||||
[exerciseId]: totalPointsGotten?.toString() || '0'
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build ordered list of exercises for gradebook from course content and marks.
|
||||
* When contentItems has no exercises (e.g. course fetch failed), derives order from marks.
|
||||
* @param marks Array of mark records from API
|
||||
* @param contentItems Flat or section-flattened content items (lesson + exercise) in display order; may be empty
|
||||
* @returns Ordered ExerciseInfo[] (exercise id, title, points)
|
||||
*/
|
||||
export function processMarksIntoExercises(marks: Marks, contentItems: CourseContentItem[]): ExerciseInfo[] {
|
||||
const marksByExerciseId = new Map<string, { title: string; points: number }>();
|
||||
const exerciseOrder: string[] = [];
|
||||
if (Array.isArray(marks)) {
|
||||
marks.forEach((mark) => {
|
||||
const { exerciseId, exerciseTitle, exercisePoints } = mark;
|
||||
if (!exerciseId) return;
|
||||
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
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// No course content (e.g. course fetch failed): use exercises from marks, order by first appearance
|
||||
return exerciseOrder.map((id) => {
|
||||
const fromMarks = marksByExerciseId.get(id)!;
|
||||
return {
|
||||
id,
|
||||
title: fromMarks?.title ?? '',
|
||||
points: fromMarks?.points ?? 0
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and download CSV export of marks (student by exercise + avg grade)
|
||||
* @param students Array of students
|
||||
* @param exercises Ordered exercises
|
||||
* @param studentMarksByExerciseId Student marks by exercise
|
||||
* @param courseTitle Course title for filename
|
||||
*/
|
||||
export function generateMarksCSV(
|
||||
students: CourseMembers,
|
||||
exercises: ExerciseInfo[],
|
||||
studentMarksByExerciseId: StudentMarksByExercise,
|
||||
courseTitle: string
|
||||
): void {
|
||||
const exportData = students.map((student) => {
|
||||
const marks = studentMarksByExerciseId[student.id] || {};
|
||||
const rowData: Record<string, string | number> = {
|
||||
name: student.profile?.fullname || '',
|
||||
email: student.profile?.email || ''
|
||||
};
|
||||
exercises.forEach((ex) => {
|
||||
rowData[ex.title] = marks[ex.id] ?? '-';
|
||||
});
|
||||
const avg = calculateStudentAverage(marks, exercises);
|
||||
rowData['Avg grade'] = avg != null ? avg : '-';
|
||||
return rowData;
|
||||
});
|
||||
|
||||
const csv = Papa.unparse(exportData);
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
|
||||
const link = document.createElement('a');
|
||||
const url = URL.createObjectURL(blob);
|
||||
link.setAttribute('href', url);
|
||||
link.setAttribute('download', `${courseTitle}.csv`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and download PDF export of marks (student by exercise + avg grade)
|
||||
* @param students Array of students
|
||||
* @param exercises Ordered exercises
|
||||
* @param studentMarksByExerciseId Student marks by exercise
|
||||
* @param courseTitle Course title for filename and header
|
||||
*/
|
||||
export function generateMarksPDF(
|
||||
students: CourseMembers,
|
||||
exercises: ExerciseInfo[],
|
||||
studentMarksByExerciseId: StudentMarksByExercise,
|
||||
courseTitle: string
|
||||
): void {
|
||||
try {
|
||||
const doc = new jsPDF({ orientation: 'landscape' });
|
||||
const head = [['Student', ...exercises.map((ex) => ex.title), 'Avg grade']];
|
||||
|
||||
const body = students.map((student) => {
|
||||
const marks = studentMarksByExerciseId[student.id] || {};
|
||||
const row: string[] = [student?.profile?.fullname ?? ''];
|
||||
exercises.forEach((ex) => {
|
||||
row.push(marks[ex.id] ?? '-');
|
||||
});
|
||||
const avg = calculateStudentAverage(marks, exercises);
|
||||
row.push(avg != null ? String(avg) : '-');
|
||||
return row;
|
||||
});
|
||||
|
||||
autoTable(doc, {
|
||||
head,
|
||||
body,
|
||||
startY: 20,
|
||||
styles: { fontSize: 8 },
|
||||
headStyles: { fillColor: [22, 160, 133] },
|
||||
footStyles: { fillColor: [22, 160, 133] },
|
||||
didDrawPage: function (data) {
|
||||
doc.setFontSize(14);
|
||||
doc.setTextColor(40);
|
||||
doc.text(`${courseTitle} - Marks`, data.settings.margin.left, 10);
|
||||
}
|
||||
});
|
||||
doc.save(`${courseTitle}-marks.pdf`);
|
||||
} catch (error) {
|
||||
console.error('Error generating PDF:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,33 @@
|
||||
import { COURSE_TYPE } from '$lib/utils/types';
|
||||
import type { TCourseType } from '@cio/db/types';
|
||||
import { writable } from 'svelte/store';
|
||||
|
||||
export const settings = writable({
|
||||
type CourseSettings = {
|
||||
logo: string;
|
||||
courseTitle: string;
|
||||
courseDescription: string;
|
||||
grading: boolean;
|
||||
type: 'LIVE_CLASS' | 'SELF_PACED';
|
||||
allowNewStudents: boolean;
|
||||
tabs: { id: number; name: string }[];
|
||||
lessonDownload: boolean;
|
||||
isPublished: boolean;
|
||||
isContentGroupingEnabled: boolean;
|
||||
};
|
||||
|
||||
export const settings = writable<CourseSettings>({
|
||||
logo: '',
|
||||
course_title: '',
|
||||
course_description: '',
|
||||
courseTitle: '',
|
||||
courseDescription: '',
|
||||
grading: false,
|
||||
type: COURSE_TYPE.LIVE_CLASS,
|
||||
allow_new_students: false,
|
||||
type: 'LIVE_CLASS' as TCourseType,
|
||||
allowNewStudents: false,
|
||||
tabs: [
|
||||
{ id: 1, name: 'course.navItem.lessons.materials.tabs.note.title' },
|
||||
{ id: 2, name: 'course.navItem.lessons.materials.tabs.slide.title' },
|
||||
{ id: 3, name: 'course.navItem.lessons.materials.tabs.video.title' },
|
||||
{ id: 4, name: 'course.navItem.lessons.materials.tabs.document.title' }
|
||||
],
|
||||
lesson_download: false,
|
||||
is_published: false
|
||||
lessonDownload: false,
|
||||
isPublished: false,
|
||||
isContentGroupingEnabled: true
|
||||
});
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { ROUTES } from './constants';
|
||||
|
||||
const COURSE_ROOT = `/${ROUTES.COURSES}`;
|
||||
const LESSONS_SEGMENT = `/${ROUTES.LESSONS}`;
|
||||
const EXERCISES_SEGMENT = '/exercises';
|
||||
|
||||
function normalizePath(path = '') {
|
||||
if (!path) return '';
|
||||
|
||||
if (path.startsWith('/')) {
|
||||
return path;
|
||||
}
|
||||
|
||||
return `/${path}`;
|
||||
}
|
||||
|
||||
export function getCourseBaseRoute(courseId: string) {
|
||||
return `${COURSE_ROOT}/${courseId}`;
|
||||
}
|
||||
|
||||
export function isCourseRoute(path = '') {
|
||||
const pathname = normalizePath(path);
|
||||
|
||||
if (!pathname.startsWith(`${COURSE_ROOT}/`)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return pathname.split('/').filter(Boolean).length >= 2;
|
||||
}
|
||||
|
||||
export function isCourseRouteForId(path = '', courseId = '') {
|
||||
if (!courseId) return false;
|
||||
|
||||
const pathname = normalizePath(path);
|
||||
const baseRoute = getCourseBaseRoute(courseId);
|
||||
|
||||
return pathname === baseRoute || pathname.startsWith(`${baseRoute}/`);
|
||||
}
|
||||
|
||||
export function isCourseContentRoute(path = '') {
|
||||
const pathname = normalizePath(path);
|
||||
|
||||
if (!isCourseRoute(pathname)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parts = pathname.split('/').filter(Boolean);
|
||||
const section = parts[2] ? `/${parts[2]}` : '';
|
||||
|
||||
return section === LESSONS_SEGMENT || section === EXERCISES_SEGMENT;
|
||||
}
|
||||
|
||||
export function isCourseContentRouteForId(path = '', courseId = '') {
|
||||
return isCourseRouteForId(path, courseId) && isCourseContentRoute(path);
|
||||
}
|
||||
@@ -1,28 +1,8 @@
|
||||
import { writable, derived } from 'svelte/store';
|
||||
import type { Course } from '$lib/utils/types';
|
||||
import { writable } from 'svelte/store';
|
||||
|
||||
export const courses = writable<Course[]>([]);
|
||||
|
||||
export const view = writable('grid');
|
||||
export const coursesInProgress = derived(courses, ($courses) =>
|
||||
$courses.length > 0
|
||||
? $courses.filter((course) => {
|
||||
return course.total_lessons !== course.progress_rate;
|
||||
})
|
||||
: []
|
||||
);
|
||||
export const coursesComplete = derived(courses, ($courses) =>
|
||||
$courses.length > 0
|
||||
? $courses.filter((course) => {
|
||||
return course.total_lessons === course.progress_rate;
|
||||
})
|
||||
: []
|
||||
);
|
||||
export const courseMetaDeta = writable<{
|
||||
isLoading: boolean;
|
||||
view: 'grid' | 'list';
|
||||
}>({
|
||||
isLoading: true,
|
||||
view: 'grid'
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Determines if a submission was submitted before the due date
|
||||
* @param createdAt Submission creation timestamp
|
||||
* @param dueBy Exercise due date (can be null)
|
||||
* @returns true if submission is early or on time, false if late
|
||||
*/
|
||||
export function isSubmissionEarly(createdAt: string, dueBy: string | null): boolean {
|
||||
if (!dueBy) return true;
|
||||
return new Date(createdAt).getTime() <= new Date(dueBy).getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates total points from a grades map
|
||||
* @param grades Map of question IDs to point values
|
||||
* @returns Sum of all points
|
||||
*/
|
||||
export function calculateTotalPoints(grades: { [questionId: string]: number }): number {
|
||||
if (!grades) return 0;
|
||||
return Object.values(grades).reduce(
|
||||
(acc, grade) => acc + (typeof grade === 'number' ? grade : parseInt(String(grade), 10) || 0),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets maximum possible points from questions array
|
||||
* @param questions Array of questions with points property
|
||||
* @returns Sum of all question points
|
||||
*/
|
||||
export function getMaxPoints(questions: Array<{ points: number }>): number {
|
||||
if (!questions || !Array.isArray(questions)) return 0;
|
||||
return questions.reduce((acc, question) => acc + (question.points || 0), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a date string for display
|
||||
* @param date ISO date string
|
||||
* @returns Formatted date string
|
||||
*/
|
||||
export function formatSubmittedDate(date: string): string {
|
||||
const d = new Date(date);
|
||||
return new Intl.DateTimeFormat('en-US', {
|
||||
dateStyle: 'full',
|
||||
timeStyle: 'medium'
|
||||
}).format(d);
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
import { classroomio, type InferResponseType } from '$lib/utils/services/api';
|
||||
|
||||
// List lessons types
|
||||
export type ListLessonsRequest = (typeof classroomio.course)[':courseId']['lesson']['$get'];
|
||||
export type ListLessonsResponse = InferResponseType<ListLessonsRequest> | null;
|
||||
export type ListLessonsSuccess = Extract<InferResponseType<ListLessonsRequest>, { success: true }>;
|
||||
export type ListLessons = ListLessonsSuccess['data'];
|
||||
|
||||
// Get lesson types
|
||||
export type GetLessonRequest = (typeof classroomio.course)[':courseId']['lesson'][':lessonId']['$get'];
|
||||
export type GetLessonResponse = InferResponseType<GetLessonRequest> | null;
|
||||
export type GetLessonSuccess = Extract<InferResponseType<GetLessonRequest>, { success: true }>;
|
||||
export type Lesson = GetLessonSuccess['data'];
|
||||
|
||||
// Create lesson types
|
||||
export type CreateLessonRequest = (typeof classroomio.course)[':courseId']['lesson']['$post'];
|
||||
export type CreateLessonResponse = InferResponseType<CreateLessonRequest>;
|
||||
export type CreateLessonSuccess = Extract<CreateLessonResponse, { success: true }>;
|
||||
export type CreateLessonData = CreateLessonSuccess['data'];
|
||||
|
||||
// Update lesson types
|
||||
export type UpdateLessonRequest = (typeof classroomio.course)[':courseId']['lesson'][':lessonId']['$put'];
|
||||
export type UpdateLessonResponse = InferResponseType<UpdateLessonRequest>;
|
||||
export type UpdateLessonSuccess = Extract<UpdateLessonResponse, { success: true }>;
|
||||
export type UpdateLessonData = UpdateLessonSuccess['data'];
|
||||
|
||||
// Delete lesson types
|
||||
export type DeleteLessonRequest = (typeof classroomio.course)[':courseId']['lesson'][':lessonId']['$delete'];
|
||||
export type DeleteLessonResponse = InferResponseType<DeleteLessonRequest>;
|
||||
export type DeleteLessonSuccess = Extract<DeleteLessonResponse, { success: true }>;
|
||||
export type DeleteLessonData = DeleteLessonSuccess['data'];
|
||||
|
||||
// Create course section types
|
||||
export type CreateCourseSectionRequest = (typeof classroomio.course)[':courseId']['section']['$post'];
|
||||
export type CreateCourseSectionResponse = InferResponseType<CreateCourseSectionRequest>;
|
||||
export type CreateCourseSectionSuccess = Extract<CreateCourseSectionResponse, { success: true }>;
|
||||
export type CreateCourseSectionData = CreateCourseSectionSuccess['data'];
|
||||
|
||||
// Update course section types
|
||||
export type UpdateCourseSectionRequest = (typeof classroomio.course)[':courseId']['section'][':sectionId']['$put'];
|
||||
export type UpdateCourseSectionResponse = InferResponseType<UpdateCourseSectionRequest>;
|
||||
export type UpdateCourseSectionSuccess = Extract<UpdateCourseSectionResponse, { success: true }>;
|
||||
export type UpdateCourseSectionData = UpdateCourseSectionSuccess['data'];
|
||||
|
||||
// Delete course section types
|
||||
export type DeleteCourseSectionRequest = (typeof classroomio.course)[':courseId']['section'][':sectionId']['$delete'];
|
||||
export type DeleteCourseSectionResponse = InferResponseType<DeleteCourseSectionRequest>;
|
||||
export type DeleteCourseSectionSuccess = Extract<DeleteCourseSectionResponse, { success: true }>;
|
||||
export type DeleteCourseSectionData = DeleteCourseSectionSuccess['data'];
|
||||
|
||||
// Reorder course sections types
|
||||
export type ReorderCourseSectionsRequest = (typeof classroomio.course)[':courseId']['section']['reorder']['$post'];
|
||||
export type ReorderCourseSectionsResponse = InferResponseType<ReorderCourseSectionsRequest>;
|
||||
export type ReorderCourseSectionsSuccess = Extract<ReorderCourseSectionsResponse, { success: true }>;
|
||||
export type ReorderCourseSectionsData = ReorderCourseSectionsSuccess['data'];
|
||||
|
||||
// Promote ungrouped section types
|
||||
export type PromoteUngroupedSectionRequest =
|
||||
(typeof classroomio.course)[':courseId']['section']['promote-ungrouped']['$post'];
|
||||
export type PromoteUngroupedSectionResponse = InferResponseType<PromoteUngroupedSectionRequest>;
|
||||
export type PromoteUngroupedSectionSuccess = Extract<PromoteUngroupedSectionResponse, { success: true }>;
|
||||
export type PromoteUngroupedSectionData = PromoteUngroupedSectionSuccess['data'];
|
||||
|
||||
// Reorder lessons types
|
||||
export type ReorderLessonsRequest = (typeof classroomio.course)[':courseId']['lesson']['reorder']['$post'];
|
||||
export type ReorderLessonsResponse = InferResponseType<ReorderLessonsRequest>;
|
||||
export type ReorderLessonsSuccess = Extract<ReorderLessonsResponse, { success: true }>;
|
||||
export type ReorderLessonsData = ReorderLessonsSuccess['data'];
|
||||
|
||||
// Course Section type (derived from Course API response which includes course_section array)
|
||||
// Since sections are returned as part of Course, we can use CreateCourseSectionData or UpdateCourseSectionData
|
||||
// But for consistency, we'll use the create response as the base type
|
||||
export type CourseSection = CreateCourseSectionData;
|
||||
|
||||
// Course Section with lessons (used when sections are populated with their lessons)
|
||||
export interface CourseSectionWithLessons extends CourseSection {
|
||||
lessons: ListLessons;
|
||||
}
|
||||
|
||||
// Get lesson comments types
|
||||
export type GetLessonCommentsRequest =
|
||||
(typeof classroomio.course)[':courseId']['lesson'][':lessonId']['comment']['$get'];
|
||||
export type GetLessonCommentsResponse = InferResponseType<GetLessonCommentsRequest> | null;
|
||||
export type GetLessonCommentsSuccess = Extract<InferResponseType<GetLessonCommentsRequest>, { success: true }>;
|
||||
export type LessonCommentsData = GetLessonCommentsSuccess['data'];
|
||||
export type LessonComments = LessonCommentsData['items'];
|
||||
|
||||
// Create lesson comment types
|
||||
export type CreateLessonCommentRequest =
|
||||
(typeof classroomio.course)[':courseId']['lesson'][':lessonId']['comment']['$post'];
|
||||
export type CreateLessonCommentResponse = InferResponseType<CreateLessonCommentRequest>;
|
||||
export type CreateLessonCommentSuccess = Extract<CreateLessonCommentResponse, { success: true }>;
|
||||
export type CreateLessonComment = CreateLessonCommentSuccess['data'];
|
||||
|
||||
// Delete lesson comment types
|
||||
export type DeleteLessonCommentRequest =
|
||||
(typeof classroomio.course)[':courseId']['lesson']['comment'][':commentId']['$delete'];
|
||||
export type DeleteLessonCommentResponse = InferResponseType<DeleteLessonCommentRequest>;
|
||||
export type DeleteLessonCommentSuccess = Extract<DeleteLessonCommentResponse, { success: true }>;
|
||||
export type DeleteLessonCommentData = DeleteLessonCommentSuccess['data'];
|
||||
|
||||
// Update lesson comment types
|
||||
export type UpdateLessonCommentRequest =
|
||||
(typeof classroomio.course)[':courseId']['lesson']['comment'][':commentId']['$put'];
|
||||
export type UpdateLessonCommentResponse = InferResponseType<UpdateLessonCommentRequest>;
|
||||
export type UpdateLessonCommentSuccess = Extract<UpdateLessonCommentResponse, { success: true }>;
|
||||
export type UpdateLessonCommentData = UpdateLessonCommentSuccess['data'];
|
||||
|
||||
// Payment request types
|
||||
export type CreatePaymentRequestRequest = (typeof classroomio.course)[':courseId']['payment-request']['$post'];
|
||||
export type CreatePaymentRequestResponse = InferResponseType<CreatePaymentRequestRequest>;
|
||||
export type CreatePaymentRequestSuccess = Extract<CreatePaymentRequestResponse, { success: true }>;
|
||||
export type PaymentRequestData = CreatePaymentRequestSuccess['data'];
|
||||
|
||||
// Get lesson completion types
|
||||
export type GetLessonCompletionRequest =
|
||||
(typeof classroomio.course)[':courseId']['lesson'][':lessonId']['completion']['$get'];
|
||||
export type GetLessonCompletionResponse = InferResponseType<GetLessonCompletionRequest> | null;
|
||||
export type GetLessonCompletionSuccess = Extract<InferResponseType<GetLessonCompletionRequest>, { success: true }>;
|
||||
export type LessonCompletion = GetLessonCompletionSuccess['data'];
|
||||
|
||||
// Update lesson completion types
|
||||
export type UpdateLessonCompletionRequest =
|
||||
(typeof classroomio.course)[':courseId']['lesson'][':lessonId']['completion']['$put'];
|
||||
export type UpdateLessonCompletionResponse = InferResponseType<UpdateLessonCompletionRequest>;
|
||||
export type UpdateLessonCompletionSuccess = Extract<UpdateLessonCompletionResponse, { success: true }>;
|
||||
export type UpdateLessonCompletionData = UpdateLessonCompletionSuccess['data'];
|
||||
|
||||
// Get lesson history types
|
||||
export type GetLessonHistoryRequest =
|
||||
(typeof classroomio.course)[':courseId']['lesson'][':lessonId']['history']['$get'];
|
||||
export type GetLessonHistoryResponse = InferResponseType<GetLessonHistoryRequest> | null;
|
||||
export type GetLessonHistorySuccess = Extract<InferResponseType<GetLessonHistoryRequest>, { success: true }>;
|
||||
export type LessonHistory = GetLessonHistorySuccess['data'];
|
||||
|
||||
// Lesson language types
|
||||
export type GetLessonLanguageRequest =
|
||||
(typeof classroomio.course)[':courseId']['lesson'][':lessonId']['language']['$get'];
|
||||
export type GetLessonLanguageResponse = InferResponseType<GetLessonLanguageRequest> | null;
|
||||
export type GetLessonLanguageSuccess = Extract<InferResponseType<GetLessonLanguageRequest>, { success: true }>;
|
||||
export type LessonLanguage = GetLessonLanguageSuccess['data'];
|
||||
|
||||
// Exercise types
|
||||
export type GetExerciseRequest = (typeof classroomio.course)[':courseId']['exercise'][':exerciseId']['$get'];
|
||||
export type GetExerciseResponse = InferResponseType<GetExerciseRequest> | null;
|
||||
export type GetExerciseSuccess = Extract<InferResponseType<GetExerciseRequest>, { success: true }>;
|
||||
|
||||
type ApiExercise = GetExerciseSuccess['data'];
|
||||
export type Exercise = Omit<ApiExercise, 'courseId' | 'sectionId' | 'order'>;
|
||||
|
||||
// export type UpdateExercisePayload = Omit<ApiExercise, 'courseId' | 'sectionId' | 'order' | 'questions'> & {
|
||||
// courseId?: string | null;
|
||||
// sectionId?: string | null;
|
||||
// order?: number | null;
|
||||
// title?: string;
|
||||
// description?: string;
|
||||
// lessonId?: string;
|
||||
// dueBy?: string;
|
||||
// questions?: Exercise['questions'];
|
||||
// };
|
||||
|
||||
export type CreateExerciseRequest = (typeof classroomio.course)[':courseId']['exercise']['$post'];
|
||||
export type CreateExerciseFromTemplateRequest =
|
||||
(typeof classroomio.course)[':courseId']['exercise']['from-template']['$post'];
|
||||
export type CreateExerciseFromTemplateResponse = InferResponseType<CreateExerciseFromTemplateRequest>;
|
||||
export type CreateExerciseFromTemplateSuccess = Extract<CreateExerciseFromTemplateResponse, { success: true }>;
|
||||
export type CreateExerciseFromTemplateData = CreateExerciseFromTemplateSuccess['data'];
|
||||
|
||||
export type UpdateExerciseRequest = (typeof classroomio.course)[':courseId']['exercise'][':exerciseId']['$put'];
|
||||
export type DeleteExerciseRequest = (typeof classroomio.course)[':courseId']['exercise'][':exerciseId']['$delete'];
|
||||
export type SubmitExerciseRequest =
|
||||
(typeof classroomio.course)[':courseId']['exercise'][':exerciseId']['submission']['$post'];
|
||||
|
||||
// Newsfeed types
|
||||
export type ListNewsfeedRequest = (typeof classroomio.course)[':courseId']['newsfeed']['$get'];
|
||||
export type ListNewsfeedResponse = InferResponseType<ListNewsfeedRequest> | null;
|
||||
export type ListNewsfeedSuccess = Extract<InferResponseType<ListNewsfeedRequest>, { success: true }>;
|
||||
export type ListNewsfeedPaginated = ListNewsfeedSuccess['data'];
|
||||
export type ListNewsfeed = ListNewsfeedPaginated['items'];
|
||||
|
||||
export type GetNewsfeedRequest = (typeof classroomio.course)[':courseId']['newsfeed'][':feedId']['$get'];
|
||||
export type CreateNewsfeedRequest = (typeof classroomio.course)[':courseId']['newsfeed']['$post'];
|
||||
export type UpdateNewsfeedRequest = (typeof classroomio.course)[':courseId']['newsfeed'][':feedId']['$put'];
|
||||
|
||||
export type ReactToNewsfeedRequest = (typeof classroomio.course)[':courseId']['newsfeed'][':feedId']['react']['$put'];
|
||||
export type ReactToNewsfeedResponse = InferResponseType<ReactToNewsfeedRequest>;
|
||||
export type ReactToNewsfeedSuccess = Extract<ReactToNewsfeedResponse, { success: true }>;
|
||||
export type ReactToNewsfeed = ReactToNewsfeedSuccess['data'];
|
||||
|
||||
export type DeleteNewsfeedRequest = (typeof classroomio.course)[':courseId']['newsfeed'][':feedId']['$delete'];
|
||||
export type GetNewsfeedCommentsRequest =
|
||||
(typeof classroomio.course)[':courseId']['newsfeed'][':feedId']['comments']['$get'];
|
||||
export type GetNewsfeedCommentsResponse = InferResponseType<GetNewsfeedCommentsRequest> | null;
|
||||
export type GetNewsfeedCommentsSuccess = Extract<InferResponseType<GetNewsfeedCommentsRequest>, { success: true }>;
|
||||
export type NewsfeedCommentsResponse = GetNewsfeedCommentsSuccess['data'];
|
||||
|
||||
export type CreateNewsfeedCommentRequest =
|
||||
(typeof classroomio.course)[':courseId']['newsfeed'][':feedId']['comment']['$post'];
|
||||
export type UpdateNewsfeedCommentRequest =
|
||||
(typeof classroomio.course)[':courseId']['newsfeed']['comment'][':commentId']['$put'];
|
||||
export type DeleteNewsfeedCommentRequest =
|
||||
(typeof classroomio.course)[':courseId']['newsfeed']['comment'][':commentId']['$delete'];
|
||||
|
||||
// Get single newsfeed response types (includes full structure with author)
|
||||
export type GetNewsfeedResponse = InferResponseType<GetNewsfeedRequest> | null;
|
||||
export type GetNewsfeedSuccess = Extract<InferResponseType<GetNewsfeedRequest>, { success: true }>;
|
||||
export type GetNewsfeedData = GetNewsfeedSuccess['data'];
|
||||
|
||||
// Extract feed types from API responses
|
||||
export type Feed = ListNewsfeed[number];
|
||||
|
||||
export type NewsfeedComment = NewsfeedCommentsResponse['items'][number];
|
||||
export type Reaction = NonNullable<Feed['reaction']>;
|
||||
|
||||
// Attendance types
|
||||
// Note: Only POST (upsert) route exists, no GET or PUT routes
|
||||
export type UpsertAttendanceRequest = (typeof classroomio.course)[':courseId']['attendance']['$post'];
|
||||
|
||||
// Mark types
|
||||
export type GetMarksRequest = (typeof classroomio.course)[':courseId']['mark']['$get'];
|
||||
export type GetMarksResponse = InferResponseType<GetMarksRequest> | null;
|
||||
export type GetMarksSuccess = Extract<InferResponseType<GetMarksRequest>, { success: true }>;
|
||||
export type Marks = GetMarksSuccess['data'];
|
||||
|
||||
// Submission types — from exercise submissions (mySubmission/allSubmissions)
|
||||
export type ListExerciseSubmissionsRequest =
|
||||
(typeof classroomio.course)[':courseId']['exercise'][':exerciseId']['submissions']['$get'];
|
||||
export type ListExerciseSubmissionsSuccess = Extract<
|
||||
InferResponseType<ListExerciseSubmissionsRequest>,
|
||||
{ success: true }
|
||||
>;
|
||||
export type ExerciseSubmissionsData = ListExerciseSubmissionsSuccess['data'];
|
||||
|
||||
/** Submission item with answers, groupmember. Used in exercise submissions UI and ViewMode. */
|
||||
export type SubmissionListItem = ExerciseSubmissionsData['allSubmissions'][number];
|
||||
|
||||
// List submissions for grading types
|
||||
export type ListSubmissionsForGradingRequest =
|
||||
(typeof classroomio.course)[':courseId']['submission']['for-grading']['$get'];
|
||||
export type ListSubmissionsForGradingResponse = InferResponseType<ListSubmissionsForGradingRequest> | null;
|
||||
export type ListSubmissionsForGradingSuccess = Extract<
|
||||
InferResponseType<ListSubmissionsForGradingRequest>,
|
||||
{ success: true }
|
||||
>;
|
||||
export type SubmissionsForGradingData = ListSubmissionsForGradingSuccess['data'];
|
||||
|
||||
// Extract types from SubmissionsForGradingData
|
||||
export type SubmissionSection = SubmissionsForGradingData['sections'][number];
|
||||
export type SubmissionItem = SubmissionSection['items'][number];
|
||||
export type SubmissionIdData = SubmissionsForGradingData['submissionIdData'][string];
|
||||
|
||||
export type UpdateSubmissionRequest = (typeof classroomio.course)[':courseId']['submission'][':submissionId']['$put'];
|
||||
export type DeleteSubmissionRequest =
|
||||
(typeof classroomio.course)[':courseId']['submission'][':submissionId']['$delete'];
|
||||
export type UpdateSubmissionAnswerRequest =
|
||||
(typeof classroomio.course)[':courseId']['submission'][':submissionId']['answer']['$put'];
|
||||
export type UpdateSubmissionGradesRequest =
|
||||
(typeof classroomio.course)[':courseId']['submission'][':submissionId']['grades']['$put'];
|
||||
|
||||
// Course types
|
||||
export type CreateCourseRequest = typeof classroomio.course.$post;
|
||||
export type GetCourseRequest = (typeof classroomio.course)[':courseId']['$get'];
|
||||
export type GetCourseBySlugRequest = (typeof classroomio.course)['slug'][':slug']['$get'];
|
||||
export type UpdateCourseRequest = (typeof classroomio.course)[':courseId']['$put'];
|
||||
export type DeleteCourseRequest = (typeof classroomio.course)[':courseId']['$delete'];
|
||||
export type UpdateCourseContentRequest = (typeof classroomio.course)[':courseId']['content']['$put'];
|
||||
export type DeleteCourseContentRequest = (typeof classroomio.course)[':courseId']['content']['$delete'];
|
||||
export type GetCourseProgressRequest = (typeof classroomio.course)[':courseId']['progress']['$get'];
|
||||
export type CloneCourseRequest = (typeof classroomio.course)[':courseId']['clone']['$post'];
|
||||
export type EnrollCourseRequest = (typeof classroomio.course)[':courseId']['enroll']['$post'];
|
||||
|
||||
// Course response types
|
||||
export type GetCourseResponse = InferResponseType<GetCourseRequest> | null;
|
||||
export type GetCourseSuccess = Extract<InferResponseType<GetCourseRequest>, { success: true }>;
|
||||
|
||||
type ApiCourse = GetCourseSuccess['data'];
|
||||
|
||||
export type CourseMetadata = (NonNullable<ApiCourse['metadata']> extends object
|
||||
? NonNullable<ApiCourse['metadata']>
|
||||
: Record<string, unknown>) & {
|
||||
isContentGroupingEnabled?: boolean;
|
||||
};
|
||||
export type CourseContent = NonNullable<ApiCourse['content']>;
|
||||
export type CourseContentSection = CourseContent['sections'][number];
|
||||
export type CourseContentItem = CourseContent['items'][number];
|
||||
|
||||
export type Course = Omit<ApiCourse, 'metadata' | 'lessons' | 'sections' | 'exercises'> & {
|
||||
metadata?: CourseMetadata | null;
|
||||
content: CourseContent;
|
||||
};
|
||||
|
||||
export type UpdateCourseResponse = InferResponseType<UpdateCourseRequest>;
|
||||
export type UpdateCourseSuccess = Extract<UpdateCourseResponse, { success: true }>;
|
||||
export type UpdateCourseData = UpdateCourseSuccess['data'];
|
||||
|
||||
export type UpdateCourseContentResponse = InferResponseType<UpdateCourseContentRequest>;
|
||||
export type UpdateCourseContentSuccess = Extract<UpdateCourseContentResponse, { success: true }>;
|
||||
|
||||
export type DeleteCourseResponse = InferResponseType<DeleteCourseRequest>;
|
||||
export type DeleteCourseSuccess = Extract<DeleteCourseResponse, { success: true }>;
|
||||
export type DeleteCourseData = DeleteCourseSuccess['data'];
|
||||
|
||||
export type DeleteCourseContentResponse = InferResponseType<DeleteCourseContentRequest>;
|
||||
export type DeleteCourseContentSuccess = Extract<DeleteCourseContentResponse, { success: true }>;
|
||||
|
||||
export type GetCourseProgressResponse = InferResponseType<GetCourseProgressRequest> | null;
|
||||
export type GetCourseProgressSuccess = Extract<InferResponseType<GetCourseProgressRequest>, { success: true }>;
|
||||
export type CourseProgress = GetCourseProgressSuccess['data'];
|
||||
|
||||
// Course Members types
|
||||
export type ListPeopleRequest = (typeof classroomio.course)[':courseId']['members']['$get'];
|
||||
export type ListPeopleResponse = InferResponseType<ListPeopleRequest> | null;
|
||||
export type ListPeopleSuccess = Extract<InferResponseType<ListPeopleRequest>, { success: true }>;
|
||||
export type CourseMembers = ListPeopleSuccess['data'];
|
||||
export type CourseMember = CourseMembers[number];
|
||||
|
||||
export type AddPeopleRequest = (typeof classroomio.course)[':courseId']['members']['$post'];
|
||||
export type AddPeopleResponse = InferResponseType<AddPeopleRequest>;
|
||||
export type AddPeopleSuccess = Extract<AddPeopleResponse, { success: true }>;
|
||||
export type AddPeopleData = AddPeopleSuccess['data'];
|
||||
|
||||
export type CreateStudentInviteRequest = (typeof classroomio.course)[':courseId']['invites']['$post'];
|
||||
export type CreateStudentInviteResponse = InferResponseType<CreateStudentInviteRequest>;
|
||||
export type CreateStudentInviteSuccess = Extract<CreateStudentInviteResponse, { success: true }>;
|
||||
export type CreateStudentInviteData = CreateStudentInviteSuccess['data'];
|
||||
|
||||
export type ListStudentInvitesRequest = (typeof classroomio.course)[':courseId']['invites']['$get'];
|
||||
export type ListStudentInvitesResponse = InferResponseType<ListStudentInvitesRequest>;
|
||||
export type ListStudentInvitesSuccess = Extract<ListStudentInvitesResponse, { success: true }>;
|
||||
export type ListStudentInvitesData = ListStudentInvitesSuccess['data'];
|
||||
export type StudentInviteListItem = ListStudentInvitesData[number];
|
||||
|
||||
export type RevokeStudentInviteRequest =
|
||||
(typeof classroomio.course)[':courseId']['invites'][':inviteId']['revoke']['$post'];
|
||||
export type RevokeStudentInviteResponse = InferResponseType<RevokeStudentInviteRequest>;
|
||||
export type RevokeStudentInviteSuccess = Extract<RevokeStudentInviteResponse, { success: true }>;
|
||||
export type RevokeStudentInviteData = RevokeStudentInviteSuccess['data'];
|
||||
|
||||
export type GetStudentInviteAuditRequest =
|
||||
(typeof classroomio.course)[':courseId']['invites'][':inviteId']['audit']['$get'];
|
||||
export type GetStudentInviteAuditResponse = InferResponseType<GetStudentInviteAuditRequest>;
|
||||
export type GetStudentInviteAuditSuccess = Extract<GetStudentInviteAuditResponse, { success: true }>;
|
||||
export type StudentInviteAuditData = GetStudentInviteAuditSuccess['data'];
|
||||
export type StudentInviteAuditItem = StudentInviteAuditData[number];
|
||||
|
||||
export type UpdatePeopleRequest = (typeof classroomio.course)[':courseId']['members'][':memberId']['$put'];
|
||||
export type UpdatePeopleResponse = InferResponseType<UpdatePeopleRequest>;
|
||||
export type UpdatePeopleSuccess = Extract<UpdatePeopleResponse, { success: true }>;
|
||||
export type UpdatePeopleData = UpdatePeopleSuccess['data'];
|
||||
|
||||
export type DeletePeopleRequest = (typeof classroomio.course)[':courseId']['members'][':memberId']['$delete'];
|
||||
export type DeletePeopleResponse = InferResponseType<DeletePeopleRequest>;
|
||||
export type DeletePeopleSuccess = Extract<DeletePeopleResponse, { success: true }>;
|
||||
export type DeletePeopleData = DeletePeopleSuccess['data'];
|
||||
|
||||
export type GetUserCourseAnalyticsRequest =
|
||||
(typeof classroomio.course)[':courseId']['members'][':userId']['analytics']['$get'];
|
||||
export type GetUserCourseAnalyticsResponse = InferResponseType<GetUserCourseAnalyticsRequest>;
|
||||
export type GetUserCourseAnalyticsSuccess = Extract<GetUserCourseAnalyticsResponse, { success: true }>;
|
||||
export type UserCourseAnalytics = GetUserCourseAnalyticsSuccess['data'];
|
||||
|
||||
export type GetCourseAnalyticsRequest = (typeof classroomio.course)[':courseId']['analytics']['$get'];
|
||||
export type GetCourseAnalyticsResponse = InferResponseType<GetCourseAnalyticsRequest>;
|
||||
export type GetCourseAnalyticsSuccess = Extract<GetCourseAnalyticsResponse, { success: true }>;
|
||||
export type CourseAnalytics = GetCourseAnalyticsSuccess['data'];
|
||||
|
||||
// Derived types from Lesson
|
||||
export type LessonVideoType = NonNullable<Lesson['videos']>[number]['type'];
|
||||
export type LessonDocument = NonNullable<Lesson['documents']>[number];
|
||||
|
||||
// Derived types from Course metadata
|
||||
export type Tabs = NonNullable<NonNullable<Course['metadata']>['lessonTabsOrder']>[number];
|
||||
export type Review = NonNullable<NonNullable<Course['metadata']>['reviews']>[number];
|
||||
|
||||
/** Submission answer element (from API). Used when formatting answers by question name. */
|
||||
export type SubmissionAnswer = NonNullable<SubmissionListItem['answers']>[number];
|
||||
|
||||
// Exercise template types
|
||||
export type GetAllTemplatesMetadataRequest = (typeof classroomio.course)[':courseId']['exercise']['template']['$get'];
|
||||
export type GetAllTemplatesMetadataSuccess = Extract<
|
||||
InferResponseType<GetAllTemplatesMetadataRequest>,
|
||||
{ success: true }
|
||||
>;
|
||||
export type GetAllTemplatesMetadataData = GetAllTemplatesMetadataSuccess['data'];
|
||||
|
||||
export type GetTemplateByTagRequest =
|
||||
(typeof classroomio.course)[':courseId']['exercise']['template']['tag'][':tag']['$get'];
|
||||
export type GetTemplateByTagSuccess = Extract<InferResponseType<GetTemplateByTagRequest>, { success: true }>;
|
||||
export type GetTemplateByTagData = GetTemplateByTagSuccess['data'];
|
||||
|
||||
export type GetTemplateByIdRequest = (typeof classroomio.course)[':courseId']['exercise']['template'][':id']['$get'];
|
||||
export type GetTemplateByIdSuccess = Extract<InferResponseType<GetTemplateByIdRequest>, { success: true }>;
|
||||
export type GetTemplateByIdData = GetTemplateByIdSuccess['data'];
|
||||
|
||||
// Presign types
|
||||
export type DocumentUploadPresignRequest = (typeof classroomio.course)['presign']['document']['upload']['$post'];
|
||||
export type DocumentUploadPresignSuccess = Extract<InferResponseType<DocumentUploadPresignRequest>, { success: true }>;
|
||||
|
||||
export type DocumentDownloadPresignRequest = (typeof classroomio.course)['presign']['document']['download']['$post'];
|
||||
export type DocumentDownloadPresignSuccess = Extract<
|
||||
InferResponseType<DocumentDownloadPresignRequest>,
|
||||
{ success: true }
|
||||
>;
|
||||
|
||||
export type VideoUploadPresignRequest = (typeof classroomio.course)['presign']['video']['upload']['$post'];
|
||||
export type VideoUploadPresignSuccess = Extract<InferResponseType<VideoUploadPresignRequest>, { success: true }>;
|
||||
|
||||
export type VideoDownloadPresignRequest = (typeof classroomio.course)['presign']['video']['download']['$post'];
|
||||
export type VideoDownloadPresignSuccess = Extract<InferResponseType<VideoDownloadPresignRequest>, { success: true }>;
|
||||
Reference in New Issue
Block a user