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 <cursoragent@cursor.com>

* fix: multiple refresh issue

* fix: server key not passed to api

* fix: clarify usage of PRIVATE_SERVER_KEY and AUTH_BEARER_TOKEN in documentation

- Updated documentation to specify that PRIVATE_SERVER_KEY is used for server-to-server API key authentication and is validated by API key middleware.
- Clarified that AUTH_BEARER_TOKEN is a separate token not utilized by apiKeyMiddleware.
- Adjusted examples in Docker setup and self-hosting documentation to reflect these changes.

* fix migration script

* fix: improve language handling and add database reset script

- Updated language extraction to handle potential undefined values, defaulting to 'en' if necessary.
- Added a new script for resetting the database, including functionality to truncate public tables and run setup with optional seeding.

* feat: add promote ungrouped section functionality and enhance document handling in dashboard

- Implemented a new API endpoint to promote synthetic "Ungrouped" content into a real persisted section, allowing for better organization of course materials.
- Updated the dashboard to include a new component for displaying content count badges for lessons and exercises.
- Enhanced document management features, including a new document card component with dropdown actions for viewing, downloading, and removing documents.
- Improved file upload handling with a dedicated file drop zone and error handling for file type and size restrictions.
- Refactored existing components for better readability and maintainability, including updates to lesson and document lists.

* chore: use root env file for docker compose

* docs: document docker no-build startup flow

* chore: add no-build option to docker full stack script

* fix(email): handle SMTP TLS mode by port

* feat(auth): add configurable cookie domain env and docs

* apps/dashboard/src/lib/utils/services/auth/session.ts

* fix(email): make sender configurable via SMTP_SENDER

* chore(i18n): regenerate locale translations and support language targeting

* chore(config): switch api to PUBLIC_SERVER_URL

* fix(i18n): persist selected locale across navigation

* feat(assets): implement organization asset management routes and services

- Added new routes for managing organization assets, including listing, creating, updating, deleting, and exporting assets.
- Introduced asset-related services for handling asset operations such as creation, retrieval, and deletion.
- Integrated YouTube metadata resolution and asset attachment/detachment functionalities.
- Updated organization routes to include the new asset management routes.
- Enhanced error handling for asset-related operations.

* fix(document-list): update conditional rendering for edit mode in document list

* debug self hosted layout setup

* refactor(sidebar): simplify lms sidebar footer and improve navigation item rendering

* feat: tags

* chore: tags roadmap + translations

* fix(api): add authMiddleware to exercise, invites, and content routers

- exerciseRouter: apply authMiddleware before courseMemberMiddleware on all 10 routes
- invitesRouter: apply authMiddleware before courseTeamMemberMiddleware on all 4 routes
- contentRouter: add authMiddleware to PUT route (DELETE already had it)

Both courseMemberMiddleware and courseTeamMemberMiddleware document requiring
authMiddleware to be applied first. This aligns with lessonRouter pattern and
ensures explicit middleware contract regardless of global session middleware.

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* fix(course): use courseTeamMemberMiddleware for PUT, DELETE, and analytics routes

These routes require admin/tutor role per JSDoc but were using
courseMemberMiddleware which allows any course member including students.
Switch to courseTeamMemberMiddleware to restrict access to ADMIN/TUTOR
group members and org admins.

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* chore: unify pricing component between dashboard and website (#630)

* feat: modularize pricing card

* feat: initia implementation of pricing togge

* fix: minor amendment

* refactor: update pricing components for improved layout and styling

- Adjusted spacing in the pricing card layout for better visual consistency.
- Modified button styles and sizes for enhanced usability.
- Cleaned up the pricing toggle component by removing unnecessary console logs and restructuring the button rendering logic.

* add handle click

* chore(css): update Tailwind CSS output with new utility classes and theme variables

* fix(api): enable orgMemberMiddleware for stats route

This change ensures that the stats route is protected by orgMemberMiddleware, aligning access control with other routes. Additionally, removed unnecessary console log from the layout server file to clean up the code.

---------

Co-authored-by: Rotimi Best <best@classroomio.com>

* pass query parameter to signup from pricing page

* ui updates to pricing cards

* commit all PRDs

* add open api spec to api prd

* make blue default theme

* more prds

* sync option id sequence on question update

* docs: more classroomio features

* chore: more ui improvements

* docs: new component docs

* chore: CSP Configuration (#638)

* feat(validation): add GitHub repository name validation

- Add ZRepositoryName schema for validating GitHub repo names
- Add ZRepositoryOwner for owner/username validation
- Add ZRepositoryIdentifier for owner/repo format
- Follow GitHub rules: A-Za-z0-9_.-, 1-100 chars, reserved names
- Add translation keys for validation messages

Fixes #637

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* Revert "feat(validation): add GitHub repository name validation"

This reverts commit 3436536bb17a0f05b3a9fe8dd7682cde64dd1dce.

* feat(dashboard): make CSP external domains configurable via env

Move hardcoded external domains from svelte.config.js to .env configuration
for on-premise deployments with strict security policies, data residency
constraints, or CISO-driven allowlists.

- ALLOWED_EXTERNAL_DOMAINS: single list for all CSP directives
- CSP_SCRIPT_SRC_DOMAINS, CSP_STYLE_SRC_DOMAINS, CSP_CONNECT_SRC_DOMAINS,
  CSP_FRAME_SRC_DOMAINS, CSP_FONT_SRC_DOMAINS: per-directive override
- When unset, defaults retain current SaaS behavior (backward compatible)

Fixes #637

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* fix(dashboard): self-hosted CSP uses only env vars, no defaults

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* fix(dashboard): add all classroomio.com domains to CSP defaults

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* docs: add CSP ALLOWED_EXTERNAL_DOMAINS to self-hosting guides

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat(docker): pass CSP domain env vars as build args to dashboard

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat: add SSO and token authentication routes and services

- Introduced new routes for SSO and token authentication under the organization namespace.
- Implemented SSO connection management including creation, update, activation, and deletion.
- Added token authentication configuration with support for secret rotation and status retrieval.
- Enhanced error handling for SSO and token authentication processes.
- Updated existing routes and services to integrate new functionalities.
- Improved gradebook service to fetch student marks and exercises.
- Refactored API structure for better organization and maintainability.

* update translations

* fix: add PUBLIC_SERVER_URL to .env.example to prevent localhost fallback in production (#641)

Co-authored-by: Cursor Agent <cursoragent@cursor.com>

* feat: new exercise question types

* MinIO S3 storage backend (#639)

* feat(storage): add MinIO/S3-compatible object storage backend

- Add OBJECT_STORAGE_* env vars for generic S3-compatible backends (MinIO, AWS S3)
- Create storage config module with Cloudflare R2 fallback for backward compatibility
- Refactor s3.ts to use configurable client and bucket names from config
- Update media.ts to use provider-neutral public URL (OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL or CLOUDFLARE_IMAGE_BUCKET_DOMAIN)
- Add MinIO service and init to docker-compose (profile: minio) with videos/documents/media buckets
- Add localhost:9000 to dashboard CSP for local MinIO presigned URL uploads
- Update self-hosting and Cloudflare docs with MinIO option
- Update .env examples and docker USAGE.md

Fixes #635

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* docs: add MINIO_ROOT_USER and MINIO_ROOT_PASSWORD to self-hosting guides

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat(media): refactor media management and integrate MinIO support

- Updated media API to use a new `mediaApi` module, replacing `mediaManagerApi` references across components.
- Added MinIO configuration options to the Docker setup, allowing for optional object storage exclusion.
- Enhanced environment variable management for MinIO in the `.env.example` file.
- Updated Content Security Policy (CSP) to allow local MinIO access in the dashboard.
- Introduced new media components for asset management, including asset cards and usage dialogs.

This refactor improves the modularity of the media handling system and provides better support for S3-compatible storage solutions.

* feat(dashboard): enhance logging and refactor auth session handling

- Added console logging for event and environment variables in hooks.server.ts to aid debugging.
- Refactored auth session handling to use authServerClient instead of authClient in session.ts for improved consistency.
- Updated Dockerfile to ensure the dashboard build output is present before starting the application.
- Expanded self-hosting documentation to include troubleshooting steps for disk space issues in PostgreSQL and Docker.

These changes improve the observability of the application and streamline the authentication process.

* refactor(dashboard): remove debug logging and enhance Postgres healthcheck

- Removed console logging for event and environment variables in hooks.server.ts to clean up the code.
- Updated Postgres healthcheck in docker-compose.yaml to require a successful `SELECT 1` query, ensuring dependent services only start once the database is ready.
- Expanded self-hosting documentation to include troubleshooting steps for database recovery issues.

These changes improve code clarity and reliability in service startup sequences.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat: add Plyr media player icons and PDF.js integration

- Introduced new Plyr SVG icons for media player controls in both course and dashboard applications.
- Updated Plyr player configuration to use local icon assets.
- Integrated PDF.js for document viewing, replacing external CDN links with local paths for improved performance and reliability.
- Enhanced PDF viewer modal z-index for better visibility.

This update improves the media player experience and ensures consistent access to necessary resources.

* feat: enhance account and organization services with type definitions and promise return types

- Updated `getAccountData` to return a structured result type including profile and organizations.
- Modified `getOrganizationsWithFilters` to specify a promise return type for better type safety.
- Added new type imports for organization-related data structures to improve clarity and maintainability.

These changes improve type safety and enhance the overall structure of the account and organization services.

* feat: implement Redis caching for presigned URLs and refactor API interactions

- Added Redis caching for presigned download URLs in the API to reduce redundant S3 calls, improving performance.
- Introduced a new `PresignApi` class in the frontend to centralize presigned URL requests, enhancing code maintainability.
- Updated various components to utilize the new `presignApi` methods for document and video upload/download operations.
- Enhanced error handling for Redis operations to ensure graceful degradation in case of cache failures.

These changes optimize the presigned URL generation process and streamline API interactions across the application.

* fix: add better-auth dependency to dashboard (#645)

* chore: unify exercise answer data format

* feat: make selfhosting run under one org for simplicity (#647)

* feat: implement self-hosting PRD + license key system

Self-hosting single-org:
- Add PUBLIC_IS_SELFHOSTED to API env, block org creation when org exists
- Auto-add non-members as students in GET /account bootstrap
- getOrgSiteInfo: root domain returns single org for self-hosted
- App init: route to /lms when self-hosted + no orgs
- Hide org switcher and Add Org modal when self-hosted

Invite-only signup:
- Add settings.signup.inviteOnly via ZUpdateOrganization
- Allow public signups toggle in org auth settings
- Signup page: hide form when invite-only and no invite context
- Landing page nav: respect inviteOnly for signup link

First signup auto-verify:
- Self-hosted first signup (no orgs) auto-verifies email in createProfileHook

License key system:
- LICENSE_KEY, LICENSE_VERIFICATION_URL for external verification API
- Feature gates: SSO, token-auth, no-tracking (PostHog/Senja)
- requireLicense middleware for API routes
- Dashboard: license store, gate PostHog/Senja/SSO/token-auth UI
- docs/LICENSE_API_CONTRACT.md for external API spec

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat: get rid of carbon completely

* chore: license verification happens only for selfhosted instance

* fix: in self hosted instance, orgSite is the default

* docs: how to write math in cio editor

* Update packages/db/src/queries/organization/organization.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update apps/api/src/services/license.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: translations, cursor pr reviews, simplify license fetching and check

* refactor: update analytics setup for cloud and self-hosted deployments; enhance settings merge logic

* refactor: update license fetching URL for development environment; optimize organization query to prevent plan row loss

* more selfhosting improvements

* feat: enhance signup guard for self-hosted instances by requiring organization context when no org ID is provided

* pr reviews

* fix: correct query parameter handling in course navigation

* pr reviews

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>
Co-authored-by: Abdulmuizz Hamzat <103611443+buildwithhamzat@users.noreply.github.com>
Co-authored-by: Adeyemi Adetunji <tvnji01@gmail.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
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
@@ -1 +1,2 @@
export * from './account';
export * from './profile';
@@ -0,0 +1,7 @@
import * as z from 'zod';
export const ZGetProfileByEmail = z.object({
email: z.email()
});
export type TGetProfileByEmail = z.infer<typeof ZGetProfileByEmail>;
@@ -0,0 +1,121 @@
import * as z from 'zod';
const AssetKind = z.enum(['video', 'document', 'image', 'audio', 'other']);
const AssetProvider = z.enum(['upload', 'youtube', 'generic', 'external_url']);
const AssetStatus = z.enum(['active', 'archived']);
const AssetTargetType = z.enum(['lesson', 'exercise', 'question']);
export const ZAssetListQuery = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
kind: AssetKind.optional(),
status: AssetStatus.optional(),
search: z.string().trim().optional(),
includeExternal: z.coerce.boolean().optional().default(true)
});
export type TAssetListQuery = z.infer<typeof ZAssetListQuery>;
export const ZAssetCreateUpload = z
.object({
kind: AssetKind.default('video'),
provider: AssetProvider.default('upload'),
storageProvider: z.string().default('s3'),
storageKey: z.string().min(1).optional(),
sourceUrl: z.string().url().optional(),
mimeType: z.string().optional(),
byteSize: z.coerce.number().int().min(0).optional(),
checksum: z.string().optional(),
title: z.string().optional(),
description: z.string().optional(),
thumbnailUrl: z.string().url().optional(),
durationSeconds: z.coerce.number().int().min(0).optional(),
aspectRatio: z.string().optional(),
isExternal: z.boolean().optional().default(false),
metadata: z.record(z.string(), z.unknown()).optional()
})
.superRefine((value, ctx) => {
if (value.provider === 'upload' && !value.storageKey) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'storageKey is required for upload assets',
path: ['storageKey']
});
}
if (!value.isExternal && value.provider === 'upload' && value.byteSize == null) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'byteSize is required for uploaded internal assets',
path: ['byteSize']
});
}
});
export type TAssetCreateUpload = z.infer<typeof ZAssetCreateUpload>;
export const ZAssetGetParam = z.object({
assetId: z.string().min(1)
});
export type TAssetGetParam = z.infer<typeof ZAssetGetParam>;
export const ZAssetUpdate = z.object({
title: z.string().optional(),
description: z.string().optional(),
thumbnailUrl: z.string().url().optional(),
durationSeconds: z.coerce.number().int().min(0).optional(),
aspectRatio: z.string().optional(),
status: AssetStatus.optional(),
metadata: z.record(z.string(), z.unknown()).optional()
});
export type TAssetUpdate = z.infer<typeof ZAssetUpdate>;
export const ZAssetAttach = z.object({
targetType: AssetTargetType,
targetId: z.string().min(1),
slotType: z.string().min(1),
slotKey: z.string().optional(),
position: z.coerce.number().int().min(0).optional()
});
export type TAssetAttach = z.infer<typeof ZAssetAttach>;
export const ZAssetDetach = z
.object({
usageId: z.string().uuid().optional(),
targetType: AssetTargetType.optional(),
targetId: z.string().optional(),
slotType: z.string().optional(),
slotKey: z.string().optional(),
position: z.coerce.number().int().min(0).optional()
})
.superRefine((value, ctx) => {
if (!value.usageId) {
if (!value.targetType || !value.targetId || !value.slotType) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'usageId or targetType/targetId/slotType is required'
});
}
}
});
export type TAssetDetach = z.infer<typeof ZAssetDetach>;
export const ZAssetUsageParams = z.object({
assetId: z.string().min(1)
});
export type TAssetUsageParams = z.infer<typeof ZAssetUsageParams>;
export const ZAssetExportQuery = z.object({
includeArchived: z.coerce.boolean().optional().default(false),
includeExternal: z.coerce.boolean().optional().default(true)
});
export type TAssetExportQuery = z.infer<typeof ZAssetExportQuery>;
export const ZAssetStorageQuery = z.object({
includeArchived: z.coerce.boolean().optional().default(false),
includeExternal: z.coerce.boolean().optional().default(true)
});
export type TAssetStorageQuery = z.infer<typeof ZAssetStorageQuery>;
export const ZYouTubeMetadataQuery = z.object({
url: z.string().url()
});
export type TYouTubeMetadataQuery = z.infer<typeof ZYouTubeMetadataQuery>;
@@ -0,0 +1 @@
export * from './assets';
@@ -0,0 +1,15 @@
import * as z from 'zod';
export const ZAttendanceUpsert = z.object({
courseId: z.string().min(1),
lessonId: z.string().min(1),
studentId: z.string().min(1),
isPresent: z.boolean()
});
export type TAttendanceUpsert = z.infer<typeof ZAttendanceUpsert>;
export const ZAttendanceListQuery = z.object({
courseId: z.string().min(1),
lessonId: z.string().optional()
});
export type TAttendanceListQuery = z.infer<typeof ZAttendanceListQuery>;
@@ -0,0 +1 @@
export * from './attendance';
@@ -1,3 +1,5 @@
import { QUESTION_TYPE_IDS } from '@cio/question-types';
/**
* Validation Constants
*
@@ -14,3 +16,9 @@ export const ALLOWED_DOCUMENT_TYPES = [
] as const;
export const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'] as const;
/**
* Question Type Constants
* These match canonical question type ids.
*/
export const QUESTION_TYPE = QUESTION_TYPE_IDS;
@@ -15,6 +15,31 @@ export const ZCourseCloneParam = z.object({
});
export type TCourseCloneParam = z.infer<typeof ZCourseCloneParam>;
export const ZCourseGetParam = z.object({
courseId: z.string().min(1)
});
export type TCourseGetParam = z.infer<typeof ZCourseGetParam>;
export const ZCourseGetQuery = z.object({
slug: z.string().optional()
});
export type TCourseGetQuery = z.infer<typeof ZCourseGetQuery>;
export const ZCourseGetBySlugParam = z.object({
slug: z.string().min(1)
});
export type TCourseGetBySlugParam = z.infer<typeof ZCourseGetBySlugParam>;
export const ZCourseEnrollParam = z.object({
courseId: z.string().min(1)
});
export type TCourseEnrollParam = z.infer<typeof ZCourseEnrollParam>;
export const ZCourseEnrollBody = z.object({
inviteToken: z.string().min(1).optional()
});
export type TCourseEnrollBody = z.infer<typeof ZCourseEnrollBody>;
export const ZCourseDownloadParam = z.object({
courseId: z.string().min(1)
});
@@ -74,3 +99,141 @@ export const ZCourseDownloadPresignedUrl = z.object({
keys: z.array(z.string().min(1)).min(1)
});
export type TCourseDownloadPresignedUrl = z.infer<typeof ZCourseDownloadPresignedUrl>;
export const ZCourseContentUpdateItem = z.object({
id: z.string().min(1),
type: z.enum(['LESSON', 'EXERCISE']),
isUnlocked: z.boolean().optional(),
order: z.number().int().min(0).optional(),
sectionId: z.string().nullable().optional()
});
export type TCourseContentUpdateItem = z.infer<typeof ZCourseContentUpdateItem>;
export const ZCourseContentUpdate = z.object({
items: z.array(ZCourseContentUpdateItem).min(1)
});
export type TCourseContentUpdate = z.infer<typeof ZCourseContentUpdate>;
export const ZCourseContentDeleteItem = z.object({
id: z.string().min(1),
type: z.enum(['LESSON', 'EXERCISE'])
});
export type TCourseContentDeleteItem = z.infer<typeof ZCourseContentDeleteItem>;
export const ZCourseContentDelete = z
.object({
sectionId: z.string().min(1).optional(),
items: z.array(ZCourseContentDeleteItem).min(1).optional()
})
.refine((data) => Boolean(data.sectionId) !== Boolean(data.items), {
message: 'Provide either sectionId or items',
path: ['sectionId']
});
export type TCourseContentDelete = z.infer<typeof ZCourseContentDelete>;
export const ZCourseCreate = z.object({
title: z.string().min(1),
description: z.string().min(1),
type: z.enum(['LIVE_CLASS', 'SELF_PACED']),
organizationId: z.string().min(1)
});
export type TCourseCreate = z.infer<typeof ZCourseCreate>;
// Course metadata schema matching the database structure
export const ZCourseMetadata = z.object({
requirements: z.string().optional(),
description: z.string().optional(),
goals: z.string().optional(),
videoUrl: z.string().optional(),
showDiscount: z.boolean().optional(),
discount: z.number().optional(),
paymentLink: z.string().optional(),
reward: z
.object({
show: z.boolean(),
description: z.string()
})
.optional(),
instructor: z
.object({
name: z.string(),
role: z.string(),
coursesNo: z.number(),
description: z.string(),
imgUrl: z.string()
})
.optional(),
certificate: z
.object({
templateUrl: z.string()
})
.optional(),
reviews: z
.array(
z.object({
id: z.number(),
hide: z.boolean(),
name: z.string(),
avatar_url: z.string(),
rating: z.number(),
created_at: z.number(),
description: z.string()
})
)
.optional(),
lessonTabsOrder: z
.array(
z.object({
id: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]),
name: z.string()
})
)
.optional(),
grading: z.boolean().optional(),
lessonDownload: z.boolean().optional(),
allowNewStudent: z.boolean(),
sectionDisplay: z.record(z.string(), z.boolean()).optional(),
isContentGroupingEnabled: z.boolean().optional()
});
export type TCourseMetadata = z.infer<typeof ZCourseMetadata>;
export const ZCourseUpdate = z.object({
title: z.string().min(1).optional(),
description: z.string().min(1).optional(),
type: z.enum(['LIVE_CLASS', 'SELF_PACED']).optional(),
logo: z.string().optional(),
slug: z.string().optional(),
isPublished: z.boolean().optional(),
overview: z.string().optional(),
metadata: ZCourseMetadata.optional(),
isCertificateDownloadable: z.boolean().optional(),
certificateTheme: z.string().optional(),
tagIds: z.array(z.uuid()).max(100).optional()
});
export type TCourseUpdate = z.infer<typeof ZCourseUpdate>;
export const ZCourseUpdateParam = z.object({
courseId: z.string().min(1)
});
export type TCourseUpdateParam = z.infer<typeof ZCourseUpdateParam>;
export const ZCourseDeleteParam = z.object({
courseId: z.string().min(1)
});
export type TCourseDeleteParam = z.infer<typeof ZCourseDeleteParam>;
export const ZCourseProgressParam = z.object({
courseId: z.string().min(1)
});
export type TCourseProgressParam = z.infer<typeof ZCourseProgressParam>;
export const ZCourseProgressQuery = z.object({
profileId: z.string().uuid()
});
export type TCourseProgressQuery = z.infer<typeof ZCourseProgressQuery>;
export const ZCourseUserAnalyticsParam = z.object({
courseId: z.string().min(1),
userId: z.string().uuid()
});
export type TCourseUserAnalyticsParam = z.infer<typeof ZCourseUserAnalyticsParam>;
@@ -6,3 +6,6 @@
*/
export * from './course';
export * from './section';
export * from './invite';
export { ZCourseGetParam, type TCourseGetParam } from './course';
@@ -0,0 +1,53 @@
import * as z from 'zod';
export const ZCourseInviteParam = z.object({
courseId: z.string().min(1)
});
export type TCourseInviteParam = z.infer<typeof ZCourseInviteParam>;
export const ZCourseInviteRevokeParam = z.object({
courseId: z.string().min(1),
inviteId: z.string().uuid()
});
export type TCourseInviteRevokeParam = z.infer<typeof ZCourseInviteRevokeParam>;
export const ZCourseInviteAuditParam = z.object({
courseId: z.string().min(1),
inviteId: z.string().uuid()
});
export type TCourseInviteAuditParam = z.infer<typeof ZCourseInviteAuditParam>;
export const ZCourseInviteTokenParam = z.object({
token: z.string().min(1)
});
export type TCourseInviteTokenParam = z.infer<typeof ZCourseInviteTokenParam>;
export const ZCreatePublicCourseInviteLink = z.object({
courseId: z.uuid()
});
export type TCreatePublicCourseInviteLink = z.infer<typeof ZCreatePublicCourseInviteLink>;
export const ZCourseInvitePreset = z.enum(['ONE_TIME_24H', 'MULTI_USE_7D', 'MULTI_USE_30D', 'CUSTOM']);
export type TCourseInvitePreset = z.infer<typeof ZCourseInvitePreset>;
export const ZCreateCourseInvite = z
.object({
preset: ZCourseInvitePreset.default('MULTI_USE_30D'),
expiresAt: z.string().min(1).optional(),
maxUses: z.number().int().min(1).max(1000).optional(),
allowedEmails: z.array(z.string().email()).max(100).optional(),
allowedDomains: z.array(z.string().min(1)).max(100).optional(),
recipientEmails: z.array(z.string().email()).max(500).optional(),
recipientCsv: z.string().max(25000).optional(),
sendEmail: z.boolean().default(false),
metadata: z.record(z.string(), z.unknown()).optional()
})
.refine(
(data) => {
const hasEmails = (data.recipientEmails?.length ?? 0) > 0;
const hasCsv = typeof data.recipientCsv === 'string' && data.recipientCsv.trim().length > 0;
return hasEmails || hasCsv;
},
{ message: 'recipientEmails or recipientCsv is required', path: ['recipientEmails'] }
);
export type TCreateCourseInvite = z.infer<typeof ZCreateCourseInvite>;
@@ -0,0 +1,28 @@
import * as z from 'zod';
export const ZCourseMembersParam = z.object({
courseId: z.string().min(1)
});
export type TCourseMembersParam = z.infer<typeof ZCourseMembersParam>;
export const ZCourseMembersMemberParam = z.object({
courseId: z.string().min(1),
memberId: z.string().min(1)
});
export type TCourseMembersMemberParam = z.infer<typeof ZCourseMembersMemberParam>;
export const ZAddCourseMembers = z.array(
z.object({
profileId: z.uuid().optional(),
roleId: z.number().int().min(1),
email: z.email().optional(),
name: z.string().optional() // For email sending
})
);
export type TAddCourseMembers = z.infer<typeof ZAddCourseMembers>;
export const ZUpdateCourseMember = z.object({
roleId: z.number().int().min(1).optional(),
email: z.email().optional()
});
export type TUpdateCourseMember = z.infer<typeof ZUpdateCourseMember>;
@@ -0,0 +1,37 @@
import * as z from 'zod';
// Course Section Schemas
export const ZCourseSectionCreate = z.object({
title: z.string().min(1),
courseId: z.string().min(1),
order: z.number().int().min(0).optional()
});
export type TCourseSectionCreate = z.infer<typeof ZCourseSectionCreate>;
export const ZCourseSectionUpdate = z.object({
title: z.string().min(1).optional(),
order: z.number().int().min(0).optional()
});
export type TCourseSectionUpdate = z.infer<typeof ZCourseSectionUpdate>;
export const ZCourseSectionPromoteUngrouped = z.object({
title: z.string().min(1)
});
export type TCourseSectionPromoteUngrouped = z.infer<typeof ZCourseSectionPromoteUngrouped>;
export const ZCourseSectionGetParam = z.object({
sectionId: z.string().min(1)
});
export type TCourseSectionGetParam = z.infer<typeof ZCourseSectionGetParam>;
export const ZCourseSectionReorder = z.object({
sections: z
.array(
z.object({
id: z.string().min(1),
order: z.number().int().min(0)
})
)
.min(1)
});
export type TCourseSectionReorder = z.infer<typeof ZCourseSectionReorder>;
@@ -0,0 +1,177 @@
import * as z from 'zod';
import { QUESTION_TYPE } from '../constants';
const QUESTION_VALIDATION_RULES: Record<
number,
Array<(question: { options?: Array<{ isCorrect: boolean }> }) => string | null>
> = {
[QUESTION_TYPE.RADIO]: [
(question) => {
const options = question.options || [];
if (options.length > 0 && options.length < 2) {
return 'Options must have at least 2 items for RADIO/CHECKBOX questions';
}
return null;
},
(question) => {
const options = question.options || [];
if (options.length > 0 && !options.some((opt) => opt.isCorrect === true)) {
return 'Please mark an option as the correct answer';
}
return null;
}
],
[QUESTION_TYPE.CHECKBOX]: [
(question) => {
const options = question.options || [];
if (options.length > 0 && options.length < 2) {
return 'Options must have at least 2 items for RADIO/CHECKBOX questions';
}
return null;
},
(question) => {
const options = question.options || [];
if (options.length > 0 && !options.some((opt) => opt.isCorrect === true)) {
return 'Please mark an option as the correct answer';
}
return null;
}
],
[QUESTION_TYPE.TRUE_FALSE]: [
(question) => {
const options = question.options || [];
if (options.length > 0 && options.length < 2) {
return 'True/False questions need both True and False options';
}
return null;
},
(question) => {
const options = question.options || [];
if (options.length > 0 && !options.some((opt) => opt.isCorrect === true)) {
return 'Please mark an option as the correct answer';
}
return null;
}
],
[QUESTION_TYPE.TEXTAREA]: []
};
// Base schema for exercise update question (without refinement)
const ZExerciseUpdateQuestionBase = z.object({
id: z.number().int().optional(),
question: z.string().min(1),
questionTypeId: z.number().int().min(1).optional(), // Added to support question type updates
points: z.number().int().min(0).optional(),
order: z.number().int().min(0).optional(),
settings: z.record(z.string(), z.unknown()).optional(),
deletedAt: z.string().optional(), // Marks question as deleted
options: z
.array(
z.object({
id: z.number().int().optional(),
label: z.string().min(1),
isCorrect: z.boolean(),
settings: z.record(z.string(), z.unknown()).optional(),
deletedAt: z.string().optional() // Marks option as deleted
})
)
.optional()
});
function validateQuestionOptions(question: z.infer<typeof ZExerciseUpdateQuestionBase>, ctx: z.core.$RefinementCtx) {
// Skip validation for deleted questions
if (question.deletedAt) return;
const rules = QUESTION_VALIDATION_RULES[question.questionTypeId ?? -1] ?? [];
for (const rule of rules) {
const message = rule(question);
if (!message) continue;
ctx.addIssue({
code: 'custom',
message,
path: ['options']
});
}
}
// Final schema with validation refinement
const ZExerciseUpdateQuestion = ZExerciseUpdateQuestionBase.superRefine(validateQuestionOptions);
export const ZExerciseCreate = z.object({
title: z.string().min(1),
description: z.string().optional(),
lessonId: z.string().optional(),
sectionId: z.string().optional(),
order: z.number().int().optional(),
courseId: z.string().min(1),
dueBy: z.string().optional(),
questions: z
.array(
z.object({
question: z.string().min(1),
questionTypeId: z.number().int().min(1).optional(),
points: z.number().int().min(0).optional(),
settings: z.record(z.string(), z.unknown()).optional(),
options: z
.array(
z.object({
label: z.string().min(1),
isCorrect: z.boolean(),
settings: z.record(z.string(), z.unknown()).optional()
})
)
.min(2)
})
)
.optional()
});
export type TExerciseCreate = z.infer<typeof ZExerciseCreate>;
export const ZExerciseUpdate = z.object({
title: z.string().min(1).optional(),
description: z.string().optional(),
lessonId: z.string().optional(),
sectionId: z.string().optional(),
order: z.number().int().optional(),
isUnlocked: z.boolean().optional(),
dueBy: z.string().optional(), // Changed from iso.datetime() to string to match frontend format
questions: z.array(ZExerciseUpdateQuestion).optional()
});
export type TExerciseUpdate = z.infer<typeof ZExerciseUpdate>;
export const ZExerciseGetParam = z.object({
exerciseId: z.string().min(1)
});
export type TExerciseGetParam = z.infer<typeof ZExerciseGetParam>;
export const ZExerciseListQuery = z.object({
lessonId: z.string().optional(),
sectionId: z.string().optional()
});
export type TExerciseListQuery = z.infer<typeof ZExerciseListQuery>;
// Exercise Submission Schemas
export const ZExerciseSubmissionCreate = z.object({
exerciseId: z.string().min(1),
answers: z
.array(
z.object({
questionId: z.number().int(),
optionId: z.number().int().optional(),
answer: z.string().optional()
})
)
.min(1)
});
export type TExerciseSubmissionCreate = z.infer<typeof ZExerciseSubmissionCreate>;
// Exercise Template Schemas
export const ZExerciseFromTemplate = z.object({
lessonId: z.string().optional(),
sectionId: z.string().optional(),
order: z.number().int().optional(),
templateId: z.number().int().min(1)
});
export type TExerciseFromTemplate = z.infer<typeof ZExerciseFromTemplate>;
@@ -0,0 +1 @@
export * from './exercise';
+7
View File
@@ -1,9 +1,16 @@
export * from './constants';
export * from './account';
export * from './attendance';
export * from './assets';
export * from './course';
export * from './exercise';
export * from './lesson';
export * from './mail';
export * from './media';
export * from './newsfeed';
export * from './onboarding';
export * from './organization';
export * from './submission';
export * from './dash';
export * from './tag';
@@ -0,0 +1,2 @@
export * from './lesson';
export * from './language';
@@ -0,0 +1,29 @@
import * as z from 'zod';
export const ZLessonLanguageGetParam = z.object({
courseId: z.uuid(),
lessonId: z.uuid()
});
export type TLessonLanguageGetParam = z.infer<typeof ZLessonLanguageGetParam>;
export const ZLessonLanguageGetByLocaleParam = z.object({
courseId: z.uuid(),
lessonId: z.uuid(),
locale: z.enum(['en', 'hi', 'fr', 'pt', 'de', 'vi', 'ru', 'es', 'pl', 'da'])
});
export type TLessonLanguageGetByLocaleParam = z.infer<typeof ZLessonLanguageGetByLocaleParam>;
export const ZLessonLanguageCreate = z.object({
locale: z.enum(['en', 'hi', 'fr', 'pt', 'de', 'vi', 'ru', 'es', 'pl', 'da']),
content: z.string().optional()
});
export type TLessonLanguageCreate = z.infer<typeof ZLessonLanguageCreate>;
export const ZLessonLanguageUpdate = z.object({
content: z.string().optional()
});
export type TLessonLanguageUpdate = z.infer<typeof ZLessonLanguageUpdate>;
@@ -0,0 +1,126 @@
import * as z from 'zod';
// Lesson Schemas
export const ZLessonCreate = z.object({
title: z.string().min(1),
note: z.string().optional(),
courseId: z.string().min(1),
sectionId: z.string().optional(),
order: z.number().int().min(0).optional(),
lessonAt: z.string().optional(),
teacherId: z.string().optional(),
isUnlocked: z.boolean().optional(),
public: z.boolean().optional()
});
export type TLessonCreate = z.infer<typeof ZLessonCreate>;
export const ZLessonUpdate = z.object({
title: z.string().min(1).optional(),
note: z.string().optional(),
sectionId: z.string().optional(),
order: z.number().int().min(0).optional(),
callUrl: z.string().optional(),
lessonAt: z.string().optional(),
teacherId: z.string().optional(),
isUnlocked: z.boolean().optional(),
public: z.boolean().optional(),
isComplete: z.boolean().optional(),
videoUrl: z.url().optional(),
slideUrl: z.url().optional(),
videos: z
.array(
z.object({
type: z.enum(['youtube', 'generic', 'upload']),
link: z.string(),
key: z.string().optional(),
assetId: z.string().uuid().optional(),
fileName: z.string().optional(),
metadata: z.record(z.string(), z.unknown()).optional()
})
)
.optional(),
documents: z
.array(
z.object({
type: z.string(),
name: z.string(),
link: z.string(),
size: z.number().optional(),
key: z.string(),
assetId: z.string().uuid().optional()
})
)
.optional()
});
export type TLessonUpdate = z.infer<typeof ZLessonUpdate>;
export const ZLessonGetParam = z.object({
lessonId: z.string().min(1)
});
export type TLessonGetParam = z.infer<typeof ZLessonGetParam>;
export const ZLessonListQuery = z.object({
sectionId: z.string().optional(),
courseId: z.string().min(1)
});
export const ZLessonHistoryParam = z.object({
courseId: z.string().min(1),
lessonId: z.string().min(1)
});
export type TLessonHistoryParam = z.infer<typeof ZLessonHistoryParam>;
export const ZLessonHistoryQuery = z.object({
locale: z.string().min(1),
endRange: z.string().transform(Number).pipe(z.number().int().min(0))
});
export type TLessonHistoryQuery = z.infer<typeof ZLessonHistoryQuery>;
export type TLessonListQuery = z.infer<typeof ZLessonListQuery>;
export const ZLessonReorder = z.object({
lessons: z
.array(
z.object({
id: z.string().min(1),
order: z.number().int().min(0),
sectionId: z.string().optional()
})
)
.min(1)
});
export type TLessonReorder = z.infer<typeof ZLessonReorder>;
// Lesson Comment Schemas
export const ZLessonCommentCreate = z.object({
lessonId: z.string().min(1),
comment: z.string().min(1)
});
export type TLessonCommentCreate = z.infer<typeof ZLessonCommentCreate>;
export const ZLessonCommentGetParam = z.object({
commentId: z.string().min(1)
});
export type TLessonCommentGetParam = z.infer<typeof ZLessonCommentGetParam>;
export const ZLessonCommentUpdate = z.object({
comment: z.string().min(1)
});
export type TLessonCommentUpdate = z.infer<typeof ZLessonCommentUpdate>;
export const ZLessonCommentsQuery = z.object({
cursor: z.string().optional(),
limit: z.coerce.number().min(1).max(50).optional().default(10)
});
export type TLessonCommentsQuery = z.infer<typeof ZLessonCommentsQuery>;
// Lesson Completion Schemas
export const ZLessonCompletionCreate = z.object({
lessonId: z.string().min(1),
isComplete: z.boolean()
});
export type TLessonCompletionCreate = z.infer<typeof ZLessonCompletionCreate>;
export const ZLessonCompletionUpdate = z.object({
isComplete: z.boolean()
});
export type TLessonCompletionUpdate = z.infer<typeof ZLessonCompletionUpdate>;
@@ -0,0 +1 @@
export * from './newsfeed';
@@ -0,0 +1,53 @@
import * as z from 'zod';
export const ZNewsfeedCreate = z.object({
courseId: z.string().min(1),
content: z.string().min(1),
isPinned: z.boolean().optional()
});
export type TNewsfeedCreate = z.infer<typeof ZNewsfeedCreate>;
export const ZNewsfeedUpdate = z.object({
content: z.string().min(1).optional(),
isPinned: z.boolean().optional()
});
export type TNewsfeedUpdate = z.infer<typeof ZNewsfeedUpdate>;
export const ZNewsfeedReactionUpdate = z.object({
reaction: z.record(z.enum(['clap', 'smile', 'thumbsup', 'thumbsdown']), z.array(z.string()))
});
export type TNewsfeedReactionUpdate = z.infer<typeof ZNewsfeedReactionUpdate>;
export const ZNewsfeedGetParam = z.object({
feedId: z.string().min(1)
});
export type TNewsfeedGetParam = z.infer<typeof ZNewsfeedGetParam>;
export const ZNewsfeedListQuery = z.object({
cursor: z.string().optional(),
limit: z.coerce.number().int().min(1).max(50).optional().default(10)
});
export type TNewsfeedListQuery = z.infer<typeof ZNewsfeedListQuery>;
// Newsfeed Comment Schemas
export const ZNewsfeedCommentCreate = z.object({
courseNewsfeedId: z.string().min(1),
content: z.string().min(1)
});
export type TNewsfeedCommentCreate = z.infer<typeof ZNewsfeedCommentCreate>;
export const ZNewsfeedCommentGetParam = z.object({
commentId: z.string().min(1)
});
export type TNewsfeedCommentGetParam = z.infer<typeof ZNewsfeedCommentGetParam>;
export const ZNewsfeedCommentUpdate = z.object({
content: z.string().min(1)
});
export type TNewsfeedCommentUpdate = z.infer<typeof ZNewsfeedCommentUpdate>;
export const ZNewsfeedCommentsQuery = z.object({
cursor: z.string().optional(),
limit: z.coerce.number().int().min(1).max(50).optional().default(5)
});
export type TNewsfeedCommentsQuery = z.infer<typeof ZNewsfeedCommentsQuery>;
@@ -0,0 +1,7 @@
import * as z from 'zod';
export const ZLMSExercisesParam = z.object({
orgId: z.uuid()
});
export type TLMSExercisesParam = z.infer<typeof ZLMSExercisesParam>;
@@ -1 +1,6 @@
export * from './organization';
export * from './quiz';
export * from './exercise';
export * from './invite';
export * from './sso';
export * from './token-auth';
@@ -0,0 +1,7 @@
import * as z from 'zod';
export const ZOrganizationInviteTokenParam = z.object({
token: z.string().min(10).max(512)
});
export type TOrganizationInviteTokenParam = z.infer<typeof ZOrganizationInviteTokenParam>;
@@ -10,30 +10,19 @@ export const ZGetOrganizations = z.object({
export type TGetOrganizations = z.infer<typeof ZGetOrganizations>;
export const ZGetOrganizationTeam = z.object({
orgId: z.uuid()
});
export type TGetOrganizationTeam = z.infer<typeof ZGetOrganizationTeam>;
export const ZUpdateOrganizationParam = z.object({
orgId: z.uuid()
});
export type TUpdateOrganizationParam = z.infer<typeof ZUpdateOrganizationParam>;
export const ZGetOrganizationAudience = z.object({
orgId: z.uuid()
});
export type TGetOrganizationAudience = z.infer<typeof ZGetOrganizationAudience>;
export const ZGetCoursesBySiteName = z.object({
siteName: z.string().min(1)
siteName: z.string().min(1),
tags: z.string().optional()
});
export type TGetCoursesBySiteName = z.infer<typeof ZGetCoursesBySiteName>;
export const ZGetOrganizationCoursesQuery = z.object({
tags: z.string().optional()
});
export type TGetOrganizationCoursesQuery = z.infer<typeof ZGetOrganizationCoursesQuery>;
export const ZGetOrgSetup = z.object({
siteName: z.string().min(1)
});
@@ -98,7 +87,21 @@ export const ZUpdateOrganization = z.object({
siteName: z.string().min(1).optional(),
customDomain: z.string().nullable().optional(),
isCustomDomainVerified: z.boolean().optional(),
customization: z.record(z.string(), z.unknown()).optional()
customization: z.record(z.string(), z.unknown()).optional(),
disableSignup: z.boolean().optional(),
disableSignupMessage: z.string().optional(),
disableEmailPassword: z.boolean().optional(),
disableGoogleAuth: z.boolean().optional(),
/** Nested settings (stored in organization.settings JSONB). signup.inviteOnly = true means invite-only signup. */
settings: z
.object({
signup: z
.object({
inviteOnly: z.boolean().optional()
})
.optional()
})
.optional()
});
export type TUpdateOrganization = z.infer<typeof ZUpdateOrganization>;
@@ -111,8 +114,13 @@ export const ZInviteTeamMembers = z.object({
export type TInviteTeamMembers = z.infer<typeof ZInviteTeamMembers>;
export const ZRemoveTeamMember = z.object({
orgId: z.uuid(),
memberId: z.number().int().positive()
memberId: z.coerce.number().int().positive()
});
export type TRemoveTeamMember = z.infer<typeof ZRemoveTeamMember>;
export const ZGetUserAnalytics = z.object({
userId: z.uuid()
});
export type TGetUserAnalytics = z.infer<typeof ZGetUserAnalytics>;
@@ -0,0 +1,32 @@
import * as z from 'zod';
export const ZQuizGetParam = z.object({
orgId: z.uuid(),
quizId: z.uuid()
});
export type TQuizGetParam = z.infer<typeof ZQuizGetParam>;
export const ZQuizListParam = z.object({
orgId: z.uuid()
});
export type TQuizListParam = z.infer<typeof ZQuizListParam>;
export const ZQuizCreate = z.object({
title: z.string().min(1),
questions: z.array(z.any()).optional(),
timelimit: z.string().optional(),
theme: z.string().optional()
});
export type TQuizCreate = z.infer<typeof ZQuizCreate>;
export const ZQuizUpdate = z.object({
title: z.string().min(1).optional(),
questions: z.array(z.any()).optional(),
timelimit: z.string().optional(),
theme: z.string().optional()
});
export type TQuizUpdate = z.infer<typeof ZQuizUpdate>;
@@ -0,0 +1,58 @@
import * as z from 'zod';
// SSO Provider enum values
export const SSO_PROVIDERS = ['OKTA', 'GOOGLE_WORKSPACE', 'AUTH0'] as const;
// Create SSO connection
export const ZCreateSsoConnection = z.object({
provider: z.enum(SSO_PROVIDERS),
displayName: z.string().min(1, 'Display name is required'),
issuer: z.url('Must be a valid URL'),
domain: z
.string()
.min(1, 'Domain is required')
.regex(/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/, 'Invalid domain format'),
clientId: z.string().min(1, 'Client ID is required'),
clientSecret: z.string().min(1, 'Client secret is required'),
scopes: z.string().default('openid profile email')
});
export type TCreateSsoConnection = z.infer<typeof ZCreateSsoConnection>;
// Update SSO connection
export const ZUpdateSsoConnection = z.object({
displayName: z.string().min(1).optional(),
issuer: z.url().optional(),
domain: z.string().optional(),
clientId: z.string().optional(),
clientSecret: z.string().optional(),
scopes: z.string().optional(),
isActive: z.boolean().optional()
});
export type TUpdateSsoConnection = z.infer<typeof ZUpdateSsoConnection>;
// Update SSO policy
export const ZUpdateSsoPolicy = z.object({
forceSso: z.boolean().optional(),
autoJoinSsoDomains: z.boolean().optional(),
breakGlassEnabled: z.boolean().optional(),
defaultRoleId: z.number().int().positive().optional(),
roleMapping: z.record(z.string(), z.number()).optional()
});
export type TUpdateSsoPolicy = z.infer<typeof ZUpdateSsoPolicy>;
// SSO Discovery query
export const ZSsoDiscoveryQuery = z.object({
email: z.email('Valid email is required')
});
export type TSsoDiscoveryQuery = z.infer<typeof ZSsoDiscoveryQuery>;
// Get SSO config by org (param)
export const ZGetSsoConfig = z.object({
orgId: z.uuid()
});
export type TGetSsoConfig = z.infer<typeof ZGetSsoConfig>;
@@ -0,0 +1,19 @@
import { z } from 'zod';
export const ZTokenExchangeQuery = z.object({
token: z.string().min(1),
redirect: z.string().optional()
});
export type TTokenExchangeQuery = z.infer<typeof ZTokenExchangeQuery>;
export const ZTokenExchangePayload = z.object({
sub: z.string(),
email: z.email(),
name: z.string().optional(),
avatar: z.url().optional(),
iat: z.number(),
exp: z.number()
});
export type TTokenExchangePayload = z.infer<typeof ZTokenExchangePayload>;
@@ -0,0 +1 @@
export * from './submission';
@@ -0,0 +1,44 @@
import * as z from 'zod';
export const ZSubmissionGradingState = z.enum(['queued', 'processing', 'awaiting_manual', 'completed', 'failed']);
export type TSubmissionGradingState = z.infer<typeof ZSubmissionGradingState>;
export const ZSubmissionOverallStatus = z.enum(['auto_graded', 'manual_required', 'hybrid']);
export type TSubmissionOverallStatus = z.infer<typeof ZSubmissionOverallStatus>;
export const ZSubmissionGetParam = z.object({
submissionId: z.string().min(1)
});
export type TSubmissionGetParam = z.infer<typeof ZSubmissionGetParam>;
export const ZSubmissionUpdate = z.object({
statusId: z.number().int().optional(),
gradingState: ZSubmissionGradingState.optional(),
total: z.number().int().min(0).optional(),
feedback: z.string().optional(),
reviewerId: z.number().int().optional()
});
export type TSubmissionUpdate = z.infer<typeof ZSubmissionUpdate>;
export const ZSubmissionAnswerUpdate = z.object({
questionId: z.number().int(),
optionId: z.number().int().optional(),
answer: z.string().optional(),
points: z.number().int().min(0).optional()
});
export type TSubmissionAnswerUpdate = z.infer<typeof ZSubmissionAnswerUpdate>;
/** Batch update for grading: all answer points + submission total/feedback in one request */
export const ZSubmissionGradeItem = z.object({
questionId: z.number().int(),
points: z.number().int().min(0)
});
export type TSubmissionGradeItem = z.infer<typeof ZSubmissionGradeItem>;
export const ZSubmissionGradesUpdate = z.object({
answers: z.array(ZSubmissionGradeItem),
total: z.number().int().min(0),
feedback: z.string().optional(),
statusId: z.number().int().min(1).max(3).optional()
});
export type TSubmissionGradesUpdate = z.infer<typeof ZSubmissionGradesUpdate>;
@@ -0,0 +1 @@
export * from './tag';
+69
View File
@@ -0,0 +1,69 @@
import * as z from 'zod';
export const TAG_COLOR_OPTIONS = [
'#EF4444',
'#F97316',
'#F59E0B',
'#84CC16',
'#22C55E',
'#14B8A6',
'#06B6D4',
'#3B82F6',
'#8B5CF6',
'#EC4899'
] as const;
export const ZTagColor = z.enum(TAG_COLOR_OPTIONS);
export type TTagColor = z.infer<typeof ZTagColor>;
export const ZTagGroupParam = z.object({
groupId: z.uuid()
});
export type TTagGroupParam = z.infer<typeof ZTagGroupParam>;
export const ZTagGroupCreate = z.object({
name: z.string().min(1).max(80),
description: z.string().max(240).optional(),
order: z.number().int().min(0).optional()
});
export type TTagGroupCreate = z.infer<typeof ZTagGroupCreate>;
export const ZTagGroupUpdate = ZTagGroupCreate.partial().refine((value) => Object.keys(value).length > 0, {
message: 'At least one field is required'
});
export type TTagGroupUpdate = z.infer<typeof ZTagGroupUpdate>;
export const ZTagParam = z.object({
tagId: z.uuid()
});
export type TTagParam = z.infer<typeof ZTagParam>;
export const ZTagCreate = z.object({
name: z.string().min(1).max(80),
description: z.string().max(240).optional(),
groupId: z.uuid(),
color: ZTagColor
});
export type TTagCreate = z.infer<typeof ZTagCreate>;
export const ZTagUpdate = z
.object({
name: z.string().min(1).max(80).optional(),
description: z.string().max(240).optional(),
groupId: z.uuid().optional(),
color: ZTagColor.optional()
})
.refine((value) => Object.keys(value).length > 0, {
message: 'At least one field is required'
});
export type TTagUpdate = z.infer<typeof ZTagUpdate>;
export const ZCourseTagParam = z.object({
courseId: z.uuid()
});
export type TCourseTagParam = z.infer<typeof ZCourseTagParam>;
export const ZCourseTagAssignment = z.object({
tagIds: z.array(z.uuid()).max(100).default([])
});
export type TCourseTagAssignment = z.infer<typeof ZCourseTagAssignment>;