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,24 +1,58 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import { getProfileById, updateProfile } from '@cio/db/queries/auth';
|
||||
import { getProfileByEmail, getProfileById, updateProfile } from '@cio/db/queries/auth';
|
||||
import { getLicenseStatus } from '@api/services/license';
|
||||
|
||||
import type { OrganizationWithMemberAndPlans } from '@cio/db/queries/organization/types';
|
||||
import type { TProfile } from '@cio/db/types';
|
||||
import { getOrganizationByProfileId } from '@cio/db/queries/organization';
|
||||
import {
|
||||
createOrganizationMember,
|
||||
getFirstOrganization,
|
||||
getOrganizationByProfileId
|
||||
} from '@cio/db/queries/organization';
|
||||
import { env } from '@api/config/env';
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
|
||||
export type GetAccountDataResult = {
|
||||
profile: TProfile;
|
||||
organizations: OrganizationWithMemberAndPlans[];
|
||||
licenseFeatures: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches account data including profile and organizations for a user
|
||||
* In self-hosted mode: auto-adds non-member users as students to the single org
|
||||
* @param userId - The user ID to fetch account data for
|
||||
* @returns Account data with profile and organizations
|
||||
*/
|
||||
export async function getAccountData(userId: string) {
|
||||
const [profile, organizations] = await Promise.all([getProfileById(userId), getOrganizationByProfileId(userId)]);
|
||||
export async function getAccountData(userId: string): Promise<GetAccountDataResult> {
|
||||
let [profile, organizations, licenseStatus] = await Promise.all([
|
||||
getProfileById(userId),
|
||||
getOrganizationByProfileId(userId),
|
||||
getLicenseStatus()
|
||||
]);
|
||||
|
||||
if (!profile) {
|
||||
throw new AppError(`Account not found for user ID: ${userId}`, ErrorCodes.ACCOUNT_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
// Self-hosted: auto-add user as student to the single org if they are not a member
|
||||
if (env.PUBLIC_IS_SELFHOSTED === 'true' && organizations.length === 0) {
|
||||
const firstOrg = await getFirstOrganization();
|
||||
if (firstOrg) {
|
||||
await createOrganizationMember({
|
||||
organizationId: firstOrg.id,
|
||||
profileId: userId,
|
||||
roleId: ROLE.STUDENT,
|
||||
verified: true
|
||||
});
|
||||
organizations = await getOrganizationByProfileId(userId);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
profile,
|
||||
organizations
|
||||
organizations,
|
||||
licenseFeatures: licenseStatus.features
|
||||
};
|
||||
}
|
||||
|
||||
@@ -57,3 +91,21 @@ export async function updateUser(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets profile by email
|
||||
* @param email - The email address
|
||||
* @returns Profile or null if not found
|
||||
*/
|
||||
export async function getProfileByEmailService(email: string): Promise<TProfile | null> {
|
||||
try {
|
||||
const profile = await getProfileByEmail(email);
|
||||
return profile;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch profile by email',
|
||||
ErrorCodes.PROFILE_NOT_FOUND,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type {
|
||||
TAssetAttach,
|
||||
TAssetCreateUpload,
|
||||
TAssetDetach,
|
||||
TAssetExportQuery,
|
||||
TAssetListQuery,
|
||||
TAssetStorageQuery,
|
||||
TAssetUpdate,
|
||||
TYouTubeMetadataQuery
|
||||
} from '@cio/utils/validation/assets';
|
||||
import {
|
||||
countAssetUsagesByAsset,
|
||||
createAssetUsage,
|
||||
createOrGetAssetByStorageKey,
|
||||
deleteAsset,
|
||||
deleteAssetUsage,
|
||||
getAssetById,
|
||||
getAssetStorageSummaryByOrg,
|
||||
listAssetsByOrg,
|
||||
listAssetsForExport,
|
||||
listAssetUsagesByAsset,
|
||||
updateAsset
|
||||
} from '@cio/db/queries/assets';
|
||||
|
||||
const YOUTUBE_VIDEO_ID_REGEX = /^[a-zA-Z0-9_-]{11}$/;
|
||||
|
||||
type YouTubeOEmbedResponse = {
|
||||
title?: unknown;
|
||||
thumbnail_url?: unknown;
|
||||
};
|
||||
|
||||
type YouTubeWatchPageMetadata = {
|
||||
title: string | null;
|
||||
durationSeconds: number | null;
|
||||
thumbnailUrl: string | null;
|
||||
};
|
||||
|
||||
function assertAssetExists<T>(asset: T | null): T {
|
||||
if (!asset) {
|
||||
throw new AppError('Asset not found', ErrorCodes.ASSET_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return asset;
|
||||
}
|
||||
|
||||
function normalizeUrl(url: string): URL | null {
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new URL(trimmed);
|
||||
} catch {
|
||||
try {
|
||||
return new URL(`https://${trimmed}`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function extractYouTubeVideoId(url: string): string | null {
|
||||
const parsedUrl = normalizeUrl(url);
|
||||
if (!parsedUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const host = parsedUrl.hostname.toLowerCase();
|
||||
let videoId: string | null = null;
|
||||
|
||||
if (host === 'youtu.be' || host === 'www.youtu.be') {
|
||||
const [pathSegment] = parsedUrl.pathname.split('/').filter(Boolean);
|
||||
videoId = pathSegment ?? null;
|
||||
} else if (
|
||||
host === 'youtube.com' ||
|
||||
host === 'www.youtube.com' ||
|
||||
host === 'm.youtube.com' ||
|
||||
host === 'music.youtube.com' ||
|
||||
host === 'youtube-nocookie.com' ||
|
||||
host === 'www.youtube-nocookie.com'
|
||||
) {
|
||||
if (parsedUrl.pathname === '/watch') {
|
||||
videoId = parsedUrl.searchParams.get('v');
|
||||
} else {
|
||||
const [firstSegment, secondSegment] = parsedUrl.pathname.split('/').filter(Boolean);
|
||||
if (firstSegment === 'embed' || firstSegment === 'shorts' || firstSegment === 'live') {
|
||||
videoId = secondSegment ?? null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!videoId || !YOUTUBE_VIDEO_ID_REGEX.test(videoId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return videoId;
|
||||
}
|
||||
|
||||
function decodeHtmlEntities(value: string): string {
|
||||
return value
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll(''', "'")
|
||||
.replaceAll(''', "'")
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>');
|
||||
}
|
||||
|
||||
function extractMetaContent(html: string, pattern: RegExp): string | null {
|
||||
const match = html.match(pattern);
|
||||
const value = match?.[1];
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const decoded = decodeHtmlEntities(value.trim());
|
||||
return decoded.length ? decoded : null;
|
||||
}
|
||||
|
||||
function extractDurationSeconds(html: string): number | null {
|
||||
const lengthSecondsMatch = html.match(/"lengthSeconds":"(\d+)"/);
|
||||
if (lengthSecondsMatch?.[1]) {
|
||||
const parsed = Number.parseInt(lengthSecondsMatch[1], 10);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
const approxDurationMsMatch = html.match(/"approxDurationMs":"(\d+)"/);
|
||||
if (approxDurationMsMatch?.[1]) {
|
||||
const parsed = Number.parseInt(approxDurationMsMatch[1], 10);
|
||||
if (Number.isFinite(parsed) && parsed >= 0) {
|
||||
return Math.round(parsed / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function fetchYouTubeOEmbed(videoUrl: string): Promise<{ title: string | null; thumbnailUrl: string | null }> {
|
||||
try {
|
||||
const response = await fetch(`https://www.youtube.com/oembed?format=json&url=${encodeURIComponent(videoUrl)}`);
|
||||
if (!response.ok) {
|
||||
return {
|
||||
title: null,
|
||||
thumbnailUrl: null
|
||||
};
|
||||
}
|
||||
|
||||
const data = (await response.json()) as YouTubeOEmbedResponse;
|
||||
const title = typeof data.title === 'string' && data.title.trim().length ? data.title.trim() : null;
|
||||
const thumbnailUrl =
|
||||
typeof data.thumbnail_url === 'string' && data.thumbnail_url.trim().length ? data.thumbnail_url.trim() : null;
|
||||
|
||||
return {
|
||||
title,
|
||||
thumbnailUrl
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
title: null,
|
||||
thumbnailUrl: null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchYouTubeWatchPageMetadata(videoId: string): Promise<YouTubeWatchPageMetadata> {
|
||||
try {
|
||||
const response = await fetch(`https://www.youtube.com/watch?v=${videoId}`);
|
||||
if (!response.ok) {
|
||||
return {
|
||||
title: null,
|
||||
durationSeconds: null,
|
||||
thumbnailUrl: null
|
||||
};
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
const title =
|
||||
extractMetaContent(html, /<meta\s+property="og:title"\s+content="([^"]+)"/i) ??
|
||||
extractMetaContent(html, /<meta\s+name="title"\s+content="([^"]+)"/i);
|
||||
const thumbnailUrl = extractMetaContent(html, /<meta\s+property="og:image"\s+content="([^"]+)"/i);
|
||||
const durationSeconds = extractDurationSeconds(html);
|
||||
|
||||
return {
|
||||
title,
|
||||
durationSeconds,
|
||||
thumbnailUrl
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
title: null,
|
||||
durationSeconds: null,
|
||||
thumbnailUrl: null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function listOrganizationAssetsService(orgId: string, query: TAssetListQuery) {
|
||||
try {
|
||||
return await listAssetsByOrg(orgId, query);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list assets',
|
||||
ErrorCodes.ASSET_LIST_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createAssetFromUploadService(orgId: string, profileId: string, data: TAssetCreateUpload) {
|
||||
try {
|
||||
return await createOrGetAssetByStorageKey({
|
||||
organizationId: orgId,
|
||||
kind: data.kind,
|
||||
provider: data.provider,
|
||||
storageProvider: data.storageProvider,
|
||||
storageKey: data.storageKey ?? null,
|
||||
sourceUrl: data.sourceUrl ?? null,
|
||||
mimeType: data.mimeType ?? null,
|
||||
byteSize: data.byteSize ?? null,
|
||||
checksum: data.checksum ?? null,
|
||||
title: data.title ?? null,
|
||||
description: data.description ?? null,
|
||||
thumbnailUrl: data.thumbnailUrl ?? null,
|
||||
durationSeconds: data.durationSeconds ?? null,
|
||||
aspectRatio: data.aspectRatio ?? null,
|
||||
isExternal: data.isExternal,
|
||||
status: 'active',
|
||||
metadata: data.metadata ?? {},
|
||||
createdByProfileId: profileId
|
||||
});
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create asset',
|
||||
ErrorCodes.ASSET_CREATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAssetService(orgId: string, assetId: string) {
|
||||
try {
|
||||
const asset = await getAssetById(assetId, orgId);
|
||||
return assertAssetExists(asset);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch asset',
|
||||
ErrorCodes.ASSET_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateAssetService(orgId: string, assetId: string, data: TAssetUpdate) {
|
||||
try {
|
||||
const updated = await updateAsset(assetId, orgId, data);
|
||||
return assertAssetExists(updated);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update asset',
|
||||
ErrorCodes.ASSET_UPDATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteAssetService(orgId: string, assetId: string) {
|
||||
try {
|
||||
await getAssetService(orgId, assetId);
|
||||
|
||||
const usageCount = await countAssetUsagesByAsset(assetId, orgId);
|
||||
if (usageCount > 0) {
|
||||
throw new AppError('Asset is still in use', ErrorCodes.ASSET_IN_USE, 409);
|
||||
}
|
||||
|
||||
const deleted = await deleteAsset(assetId, orgId);
|
||||
return assertAssetExists(deleted);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete asset',
|
||||
ErrorCodes.ASSET_DELETE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAssetUsageGraphService(orgId: string, assetId: string) {
|
||||
try {
|
||||
await getAssetService(orgId, assetId);
|
||||
const [usages, usageCount] = await Promise.all([
|
||||
listAssetUsagesByAsset(assetId, orgId),
|
||||
countAssetUsagesByAsset(assetId, orgId)
|
||||
]);
|
||||
|
||||
return {
|
||||
usageCount,
|
||||
usages
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch asset usage',
|
||||
ErrorCodes.ASSET_USAGE_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function attachAssetService(orgId: string, assetId: string, profileId: string, input: TAssetAttach) {
|
||||
try {
|
||||
await getAssetService(orgId, assetId);
|
||||
return await createAssetUsage({
|
||||
organizationId: orgId,
|
||||
assetId,
|
||||
targetType: input.targetType,
|
||||
targetId: input.targetId,
|
||||
slotType: input.slotType,
|
||||
slotKey: input.slotKey ?? null,
|
||||
position: input.position ?? null,
|
||||
createdByProfileId: profileId
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to attach asset',
|
||||
ErrorCodes.ASSET_ATTACH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function detachAssetService(orgId: string, assetId: string, input: TAssetDetach) {
|
||||
try {
|
||||
await getAssetService(orgId, assetId);
|
||||
const detached = await deleteAssetUsage(orgId, assetId, input);
|
||||
if (!detached) {
|
||||
throw new AppError('Asset usage not found', ErrorCodes.ASSET_USAGE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return detached;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to detach asset',
|
||||
ErrorCodes.ASSET_DETACH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportOrganizationAssetsService(orgId: string, query: TAssetExportQuery) {
|
||||
try {
|
||||
return await listAssetsForExport(orgId, query);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to export assets',
|
||||
ErrorCodes.ASSET_EXPORT_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getOrganizationAssetStorageService(orgId: string, query: TAssetStorageQuery) {
|
||||
try {
|
||||
return await getAssetStorageSummaryByOrg(orgId, query);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch asset storage summary',
|
||||
ErrorCodes.ASSET_STORAGE_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getYouTubeMetadataService(_orgId: string, query: TYouTubeMetadataQuery) {
|
||||
const videoId = extractYouTubeVideoId(query.url);
|
||||
if (!videoId) {
|
||||
throw new AppError('Invalid YouTube URL', ErrorCodes.VALIDATION_ERROR, 400, 'url');
|
||||
}
|
||||
|
||||
const sourceUrl = `https://www.youtube.com/watch?v=${videoId}`;
|
||||
|
||||
try {
|
||||
const [oembed, watchPageMetadata] = await Promise.all([
|
||||
fetchYouTubeOEmbed(sourceUrl),
|
||||
fetchYouTubeWatchPageMetadata(videoId)
|
||||
]);
|
||||
|
||||
return {
|
||||
videoId,
|
||||
sourceUrl,
|
||||
title: oembed.title ?? watchPageMetadata.title ?? 'YouTube video',
|
||||
durationSeconds: watchPageMetadata.durationSeconds,
|
||||
thumbnailUrl:
|
||||
oembed.thumbnailUrl ?? watchPageMetadata.thumbnailUrl ?? `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`
|
||||
};
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch YouTube metadata',
|
||||
ErrorCodes.ASSET_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './assets';
|
||||
@@ -0,0 +1,46 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import { getAttendanceByCourseId, getAttendanceByStudentAndLesson, upsertAttendance } from '@cio/db/queries/attendance';
|
||||
import type { TGroupAttendance, TNewGroupAttendance } from '@cio/db/types';
|
||||
import type { TAttendanceUpsert } from '@cio/utils/validation/attendance';
|
||||
|
||||
/**
|
||||
* Lists attendance records for a course
|
||||
* @param courseId Course ID
|
||||
* @param lessonId Optional lesson ID filter
|
||||
* @returns Array of attendance records
|
||||
*/
|
||||
export async function listAttendance(courseId: string, lessonId?: string): Promise<TGroupAttendance[]> {
|
||||
try {
|
||||
return await getAttendanceByCourseId(courseId, lessonId);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list attendance',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or updates an attendance record
|
||||
* @param data Attendance data
|
||||
* @returns Created or updated attendance record
|
||||
*/
|
||||
export async function upsertAttendanceService(data: TAttendanceUpsert): Promise<TGroupAttendance> {
|
||||
try {
|
||||
const attendanceData: TNewGroupAttendance = {
|
||||
courseId: data.courseId,
|
||||
lessonId: data.lessonId,
|
||||
studentId: data.studentId,
|
||||
isPresent: data.isPresent
|
||||
};
|
||||
|
||||
return await upsertAttendance(attendanceData);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to upsert attendance',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './attendance';
|
||||
@@ -0,0 +1,133 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import {
|
||||
getOrganizationAuthPolicy,
|
||||
getOrganizationSsoConfig,
|
||||
getOrganizationSsoConfigByDomain
|
||||
} from '@cio/db/queries/organization/sso';
|
||||
|
||||
// Extract domain from email
|
||||
function getDomainFromEmail(email: string): string {
|
||||
const parts = email.toLowerCase().split('@');
|
||||
if (parts.length !== 2) {
|
||||
throw new AppError('Invalid email format', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
return parts[1];
|
||||
}
|
||||
|
||||
// SSO Discovery result
|
||||
interface SsoDiscoveryResult {
|
||||
ssoRequired: boolean;
|
||||
ssoAvailable: boolean;
|
||||
redirectUrl: string | null;
|
||||
allowPassword: boolean;
|
||||
providerName: string | null;
|
||||
providerId: string | null;
|
||||
}
|
||||
|
||||
// Discover SSO for email
|
||||
export async function discoverSso(email: string): Promise<SsoDiscoveryResult> {
|
||||
const domain = getDomainFromEmail(email);
|
||||
|
||||
// Find SSO config by domain
|
||||
const config = await getOrganizationSsoConfigByDomain(domain);
|
||||
|
||||
if (!config || !config.isActive) {
|
||||
// No SSO found for this domain
|
||||
return {
|
||||
ssoRequired: false,
|
||||
ssoAvailable: false,
|
||||
redirectUrl: null,
|
||||
allowPassword: true,
|
||||
providerName: null,
|
||||
providerId: null
|
||||
};
|
||||
}
|
||||
|
||||
// Get policy
|
||||
const policy = await getOrganizationAuthPolicy(config.organizationId);
|
||||
|
||||
// Build Better Auth SSO URL
|
||||
// Note: Better Auth handles the actual flow, we just provide the entry point
|
||||
const redirectUrl = `/api/auth/sso/authorize/${config.betterAuthProviderId}`;
|
||||
|
||||
return {
|
||||
ssoRequired: policy?.forceSso ?? false,
|
||||
ssoAvailable: true,
|
||||
redirectUrl,
|
||||
allowPassword: !(policy?.forceSso ?? false),
|
||||
providerName: config.displayName,
|
||||
providerId: config.betterAuthProviderId
|
||||
};
|
||||
}
|
||||
|
||||
// Check if user can use password login for org
|
||||
export async function canUsePasswordLogin(orgId: string, isBreakGlassUser: boolean = false): Promise<boolean> {
|
||||
const policy = await getOrganizationAuthPolicy(orgId);
|
||||
|
||||
if (!policy) {
|
||||
return true; // No policy = no restrictions
|
||||
}
|
||||
|
||||
// If Force SSO is not enabled, password is allowed
|
||||
if (!policy.forceSso) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Force SSO is enabled - check break glass
|
||||
if (isBreakGlassUser && policy.breakGlassEnabled) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Force SSO active, not break glass
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get SSO info for org (used in login page when org context is known)
|
||||
export async function getOrgSsoInfo(orgId: string) {
|
||||
const config = await getOrganizationSsoConfig(orgId);
|
||||
|
||||
if (!config || !config.isActive) {
|
||||
return {
|
||||
hasSso: false,
|
||||
ssoRequired: false,
|
||||
redirectUrl: null,
|
||||
providerName: null,
|
||||
providerId: null
|
||||
};
|
||||
}
|
||||
|
||||
const policy = await getOrganizationAuthPolicy(orgId);
|
||||
|
||||
return {
|
||||
hasSso: true,
|
||||
ssoRequired: policy?.forceSso ?? false,
|
||||
redirectUrl: `/api/auth/sso/authorize/${config.betterAuthProviderId}`,
|
||||
providerName: config.displayName,
|
||||
providerId: config.betterAuthProviderId
|
||||
};
|
||||
}
|
||||
|
||||
// JIT provisioning: Get role mapping for user
|
||||
export async function getSsoRoleMapping(orgId: string, groups: string[]): Promise<number> {
|
||||
const policy = await getOrganizationAuthPolicy(orgId);
|
||||
|
||||
if (!policy) {
|
||||
return 3; // Default to STUDENT
|
||||
}
|
||||
|
||||
const roleMapping = policy.roleMapping as Record<string, number> | null;
|
||||
|
||||
if (!roleMapping) {
|
||||
return policy.defaultRoleId ?? 3;
|
||||
}
|
||||
|
||||
// Check each group for a mapping
|
||||
for (const group of groups) {
|
||||
const mappedRole = roleMapping[group];
|
||||
if (mappedRole) {
|
||||
return mappedRole;
|
||||
}
|
||||
}
|
||||
|
||||
return policy.defaultRoleId ?? 3;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type { TCommunityAnswer, TCommunityQuestion, TCourse } from '@db/types';
|
||||
import type { TCommunityAnswer, TCommunityQuestion, TNewCommunityQuestion } from '@db/types';
|
||||
import {
|
||||
createCommunityQuestion,
|
||||
deleteCommentById,
|
||||
@@ -10,32 +10,57 @@ import {
|
||||
getCommunityQuestions,
|
||||
submitComment,
|
||||
upvoteAnswer,
|
||||
upvoteQuestion
|
||||
upvoteQuestion,
|
||||
type CommunityQuestionQueryResult
|
||||
} from '@cio/db/queries/community';
|
||||
import { getEnrolledCourses, getOrgCourses } from '@cio/db/queries/course';
|
||||
|
||||
import { getCoursesByOrgId } from './organization';
|
||||
|
||||
export async function fetchCommunityQuestions(orgId: string): Promise<Partial<TCommunityQuestion>[]> {
|
||||
let discussions: Partial<TCommunityQuestion>[] = [];
|
||||
|
||||
let courses: TCourse[];
|
||||
|
||||
if (orgId) {
|
||||
courses = await getCoursesByOrgId(orgId);
|
||||
} else {
|
||||
throw new AppError(
|
||||
'Organization not found for the given site name',
|
||||
ErrorCodes.COMMUNITY_QUESTIONS_FETCH_FAILED,
|
||||
404
|
||||
);
|
||||
}
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
|
||||
export async function fetchCommunityQuestions(
|
||||
orgId: string,
|
||||
userId: string,
|
||||
userRole: number
|
||||
): Promise<CommunityQuestionQueryResult[]> {
|
||||
try {
|
||||
const courseIds = courses.map((course) => course.id);
|
||||
discussions = await getCommunityQuestions(courseIds);
|
||||
if (!orgId) {
|
||||
throw new AppError(
|
||||
'Organization not found for the given site name',
|
||||
ErrorCodes.COMMUNITY_QUESTIONS_FETCH_FAILED,
|
||||
404
|
||||
);
|
||||
}
|
||||
|
||||
if (userRole === null) {
|
||||
throw new AppError('User is not a member of this organization', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
|
||||
let discussions: CommunityQuestionQueryResult[];
|
||||
|
||||
switch (userRole) {
|
||||
case ROLE.ADMIN:
|
||||
// Admins can see all questions in the organization - no need to fetch courses
|
||||
discussions = await getCommunityQuestions({ orgId });
|
||||
break;
|
||||
case ROLE.TUTOR:
|
||||
// Tutors can see questions in courses they have access to
|
||||
const tutorCourses = await getOrgCourses({ orgId, profileId: userId });
|
||||
const tutorCourseIds = tutorCourses.map((course) => course.id);
|
||||
discussions = await getCommunityQuestions({ courseIds: tutorCourseIds });
|
||||
break;
|
||||
case ROLE.STUDENT:
|
||||
// Students can see questions in courses they are enrolled in
|
||||
const studentCourses = await getEnrolledCourses({ orgId, profileId: userId });
|
||||
const studentCourseIds = studentCourses.map((course) => course.id);
|
||||
discussions = await getCommunityQuestions({ courseIds: studentCourseIds });
|
||||
break;
|
||||
default:
|
||||
throw new AppError('Invalid role', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
|
||||
return discussions;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) throw error;
|
||||
console.error('Failed to fetch community questions:', error);
|
||||
throw new AppError('Failed to fetch community questions', ErrorCodes.COMMUNITY_QUESTIONS_FETCH_FAILED, 500);
|
||||
}
|
||||
@@ -43,6 +68,9 @@ export async function fetchCommunityQuestions(orgId: string): Promise<Partial<TC
|
||||
|
||||
export async function fetchCommunityQuestion({ slug }: Partial<TCommunityQuestion>) {
|
||||
try {
|
||||
if (!slug) {
|
||||
throw new AppError('Slug is required', ErrorCodes.COMMUNITY_QUESTION_NOT_FOUND, 400);
|
||||
}
|
||||
const result = await getCommunityQuestion(slug);
|
||||
|
||||
if (!result) {
|
||||
@@ -81,6 +109,9 @@ export async function createQuestion({
|
||||
slug
|
||||
}: Partial<TCommunityQuestion>) {
|
||||
try {
|
||||
if (!courseId || !organizationId || !authorProfileId) {
|
||||
throw new AppError('Missing required fields', ErrorCodes.ADD_COMMUNITY_QUESTION_FAILED, 400);
|
||||
}
|
||||
const result = await createCommunityQuestion({
|
||||
title,
|
||||
body,
|
||||
@@ -115,7 +146,10 @@ export async function createQuestion({
|
||||
|
||||
export async function editQuestion({ id, title, body, courseId }: Partial<TCommunityQuestion>) {
|
||||
try {
|
||||
const result = await editCommunityQuestion({ id, title, body, courseId: courseId });
|
||||
if (!id || !courseId) {
|
||||
throw new AppError('Question ID and Course ID are required', ErrorCodes.UPDATE_COMMUNITY_QUESTION_FAILED, 400);
|
||||
}
|
||||
const result = await editCommunityQuestion({ id, title, body, courseId });
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
@@ -127,7 +161,10 @@ export async function editQuestion({ id, title, body, courseId }: Partial<TCommu
|
||||
|
||||
export async function createComment({ body, questionId, authorProfileId, votes }: Partial<TCommunityAnswer>) {
|
||||
try {
|
||||
const result = await submitComment({ body, questionId, authorProfileId, votes });
|
||||
if (!body || !questionId || !authorProfileId) {
|
||||
throw new AppError('Missing required fields', ErrorCodes.COMMENT_SUBMISSION_FAILED, 400);
|
||||
}
|
||||
const result = await submitComment({ body, questionId, authorProfileId, votes: votes ?? 0 });
|
||||
|
||||
if (!result) {
|
||||
throw new AppError('Comment submission failed', ErrorCodes.COMMENT_SUBMISSION_FAILED, 404);
|
||||
@@ -165,7 +202,7 @@ export async function upvote({ id, isQuestion }: { id: string | number; isQuesti
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteQuestion({ id }: Partial<TCommunityQuestion>) {
|
||||
export async function deleteQuestion({ id }: { id: number }) {
|
||||
try {
|
||||
// Delete all comments first, then delete the question
|
||||
await deleteCommentByQuestionId(id);
|
||||
@@ -179,7 +216,7 @@ export async function deleteQuestion({ id }: Partial<TCommunityQuestion>) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteComment({ id }: Partial<TCommunityAnswer>) {
|
||||
export async function deleteComment({ id }: { id: string }) {
|
||||
try {
|
||||
const result = await deleteCommentById(id);
|
||||
|
||||
@@ -191,7 +228,7 @@ export async function deleteComment({ id }: Partial<TCommunityAnswer>) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteCommentsByQuestionId({ questionId }: Partial<TCommunityAnswer>) {
|
||||
export async function deleteCommentsByQuestionId({ questionId }: { questionId: number }) {
|
||||
try {
|
||||
const result = await deleteCommentByQuestionId(questionId);
|
||||
|
||||
|
||||
@@ -1,26 +1,25 @@
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
import { TCourse, TCourseSection, TLesson } from '@db/types';
|
||||
import {
|
||||
addGroupMember,
|
||||
createCourse,
|
||||
createGroup,
|
||||
createLessons,
|
||||
createLessonSections,
|
||||
getCourseById,
|
||||
getLessonsByCourseId,
|
||||
getSectionsByCourseId,
|
||||
getLessonLanguagesByLessonIds,
|
||||
createLessonLanguages,
|
||||
getExercisesByLessonIds,
|
||||
createExercises,
|
||||
getQuestionsByExerciseIds,
|
||||
createGroup,
|
||||
createLessonLanguages,
|
||||
createCourseSections,
|
||||
createLessons,
|
||||
createOptions,
|
||||
createQuestions,
|
||||
getCourseById,
|
||||
getExercisesByLessonIds,
|
||||
getLessonLanguagesByLessonIds,
|
||||
getLessonsByCourseId,
|
||||
getOptionsByQuestionIds,
|
||||
createOptions
|
||||
getQuestionsByExerciseIds,
|
||||
getCourseSectionsByCourseId
|
||||
} from '@db/queries';
|
||||
import { TCourse, TLesson, TLessonSection } from '@db/types';
|
||||
|
||||
// Constants
|
||||
const QUESTION_TYPE_TEXTAREA = 2; // Paragraph question type
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
import { QUESTION_TYPE_IDS } from '@cio/question-types';
|
||||
|
||||
async function cloneLessonLanguages(newLessons: TLesson[], oldLessons: TLesson[]): Promise<void> {
|
||||
// Extract old lesson IDs
|
||||
@@ -99,6 +98,7 @@ async function cloneExercises(newLessons: TLesson[], oldLessons: TLesson[]): Pro
|
||||
points: question.points,
|
||||
order: question.order,
|
||||
questionTypeId: question.questionTypeId,
|
||||
settings: question.settings,
|
||||
exerciseId: exerciseIdMap.get(question.exerciseId)!
|
||||
}))
|
||||
);
|
||||
@@ -106,11 +106,18 @@ async function cloneExercises(newLessons: TLesson[], oldLessons: TLesson[]): Pro
|
||||
// 8. Create question ID map
|
||||
const questionIdMap = new Map<number, number>();
|
||||
oldQuestions.forEach((oldQuestion, index) => {
|
||||
questionIdMap.set(oldQuestion.id, newQuestions[index].id);
|
||||
const newQuestionId = newQuestions[index]?.id;
|
||||
const oldQuestionId = oldQuestion.id;
|
||||
if (newQuestionId !== undefined && oldQuestionId !== undefined) {
|
||||
questionIdMap.set(oldQuestionId, newQuestionId);
|
||||
}
|
||||
});
|
||||
|
||||
// 9. Fetch all options for old questions (except for paragraph type questions)
|
||||
const oldQuestionIds = oldQuestions.filter((q) => q.questionTypeId !== QUESTION_TYPE_TEXTAREA).map((q) => q.id);
|
||||
const oldQuestionIds = oldQuestions
|
||||
.filter((q) => q.questionTypeId !== QUESTION_TYPE_IDS.TEXTAREA)
|
||||
.map((q) => q.id)
|
||||
.filter((id) => id !== undefined);
|
||||
|
||||
if (oldQuestionIds.length === 0) {
|
||||
return;
|
||||
@@ -124,12 +131,21 @@ async function cloneExercises(newLessons: TLesson[], oldLessons: TLesson[]): Pro
|
||||
|
||||
// 10. Insert options with new question IDs
|
||||
await createOptions(
|
||||
oldOptions.map((option) => ({
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
isCorrect: option.isCorrect,
|
||||
questionId: questionIdMap.get(option.questionId)!
|
||||
}))
|
||||
oldOptions
|
||||
.map((option) => {
|
||||
const newQuestionId = questionIdMap.get(option.questionId);
|
||||
if (newQuestionId === undefined) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
isCorrect: option.isCorrect,
|
||||
settings: option.settings,
|
||||
questionId: newQuestionId
|
||||
};
|
||||
})
|
||||
.filter((opt) => opt !== null)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -169,8 +185,7 @@ export async function cloneCourse(
|
||||
isCertificateDownloadable: course.isCertificateDownloadable,
|
||||
certificateTheme: course.certificateTheme,
|
||||
status: course.status,
|
||||
type: course.type,
|
||||
version: course.version
|
||||
type: course.type
|
||||
});
|
||||
|
||||
// 4. add group member
|
||||
@@ -182,23 +197,23 @@ export async function cloneCourse(
|
||||
});
|
||||
|
||||
// 5. clone sections
|
||||
const oldSections = await getSectionsByCourseId(courseId);
|
||||
const oldSections = await getCourseSectionsByCourseId(courseId);
|
||||
|
||||
// Only create sections if there are any
|
||||
let newSections: TLessonSection[] = [];
|
||||
let newSections: TCourseSection[] = [];
|
||||
let sectionMap = new Map<string, string>();
|
||||
|
||||
if (oldSections.length > 0) {
|
||||
newSections = await createLessonSections(
|
||||
oldSections.map((sec) => ({
|
||||
title: sec.title,
|
||||
order: sec.order,
|
||||
newSections = await createCourseSections(
|
||||
oldSections.map((section) => ({
|
||||
title: section.title,
|
||||
order: section.order,
|
||||
courseId: newCourse.id
|
||||
}))
|
||||
);
|
||||
|
||||
// create map
|
||||
sectionMap = new Map(oldSections.map((old, i) => [old.id, newSections[i].id]));
|
||||
sectionMap = new Map(oldSections.map((section, index) => [section.id, newSections[index].id]));
|
||||
}
|
||||
|
||||
// 6. clone lessons
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import { ContentType } from '@cio/utils/constants';
|
||||
import { db } from '@cio/db/drizzle';
|
||||
import { sql, inArray } from 'drizzle-orm';
|
||||
import { lesson, exercise } from '@cio/db/schema';
|
||||
import { getCourseContentItems, type CourseContentItemRow } from '@cio/db/queries/course/content';
|
||||
import { deleteLesson } from '@cio/db/queries/lesson';
|
||||
import { deleteCourseSection, getCourseSectionById } from '@cio/db/queries/course';
|
||||
import { deleteExercise } from '@cio/db/queries/exercise/exercise';
|
||||
import type { TCourseContentDelete, TCourseContentUpdate } from '@cio/utils/validation/course';
|
||||
|
||||
function buildUpdatePayload(item: TCourseContentUpdate['items'][number]) {
|
||||
const payload: Record<string, unknown> = {};
|
||||
|
||||
if (item.isUnlocked !== undefined) {
|
||||
payload.isUnlocked = item.isUnlocked;
|
||||
}
|
||||
|
||||
if (item.order !== undefined) {
|
||||
payload.order = item.order;
|
||||
}
|
||||
|
||||
if (item.sectionId !== undefined) {
|
||||
payload.sectionId = item.sectionId;
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
function buildContentKey(item: { id: string; type: string }) {
|
||||
return `${item.type}-${item.id}`;
|
||||
}
|
||||
|
||||
async function getCourseContentMap(courseId: string) {
|
||||
const contentItems = await getCourseContentItems(courseId);
|
||||
const contentMap = new Map<string, CourseContentItemRow>();
|
||||
|
||||
contentItems.forEach((item) => {
|
||||
if (item.type === ContentType.Lesson || item.type === ContentType.Exercise) {
|
||||
contentMap.set(buildContentKey(item), item);
|
||||
}
|
||||
});
|
||||
|
||||
return contentMap;
|
||||
}
|
||||
|
||||
async function assertCourseContentItems(courseId: string, items: TCourseContentUpdate['items']) {
|
||||
const contentMap = await getCourseContentMap(courseId);
|
||||
|
||||
items.forEach((item) => {
|
||||
const key = buildContentKey({ id: item.id, type: item.type });
|
||||
|
||||
if (!contentMap.has(key)) {
|
||||
if (item.type === ContentType.Lesson) {
|
||||
throw new AppError('Lesson does not belong to this course', ErrorCodes.LESSON_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
if (item.type === ContentType.Exercise) {
|
||||
throw new AppError('Exercise does not belong to this course', ErrorCodes.EXERCISE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
throw new AppError('Invalid content type', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateCourseContent(courseId: string, items: TCourseContentUpdate['items']) {
|
||||
try {
|
||||
await assertCourseContentItems(courseId, items);
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
const updates = items
|
||||
.map((item) => ({
|
||||
item,
|
||||
payload: buildUpdatePayload(item)
|
||||
}))
|
||||
.filter(({ payload }) => Object.keys(payload).length > 0);
|
||||
|
||||
if (updates.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedAt = new Date().toISOString();
|
||||
|
||||
const lessonUpdates = updates.filter(({ item }) => item.type === ContentType.Lesson);
|
||||
const exerciseUpdates = updates.filter(({ item }) => item.type === ContentType.Exercise);
|
||||
|
||||
if (lessonUpdates.length > 0) {
|
||||
const lessonIds = lessonUpdates.map(({ item }) => item.id);
|
||||
const lessonOrderUpdates = lessonUpdates
|
||||
.filter(({ payload }) => payload.order !== undefined)
|
||||
.map(({ item, payload }) => ({ id: item.id, value: payload.order }));
|
||||
const lessonSectionUpdates = lessonUpdates
|
||||
.filter(({ payload }) => payload.sectionId !== undefined)
|
||||
.map(({ item, payload }) => ({ id: item.id, value: payload.sectionId }));
|
||||
const lessonUnlockUpdates = lessonUpdates
|
||||
.filter(({ payload }) => payload.isUnlocked !== undefined)
|
||||
.map(({ item, payload }) => ({ id: item.id, value: payload.isUnlocked }));
|
||||
|
||||
const lessonSet: Record<string, unknown> = {
|
||||
updatedAt
|
||||
};
|
||||
|
||||
if (lessonOrderUpdates.length > 0) {
|
||||
lessonSet.order = sql`case ${lesson.id} ${sql.join(
|
||||
lessonOrderUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
|
||||
sql` `
|
||||
)} else ${lesson.order} end`;
|
||||
}
|
||||
|
||||
if (lessonSectionUpdates.length > 0) {
|
||||
lessonSet.sectionId = sql`case ${lesson.id} ${sql.join(
|
||||
lessonSectionUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
|
||||
sql` `
|
||||
)} else ${lesson.sectionId} end`;
|
||||
}
|
||||
|
||||
if (lessonUnlockUpdates.length > 0) {
|
||||
lessonSet.isUnlocked = sql`case ${lesson.id} ${sql.join(
|
||||
lessonUnlockUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
|
||||
sql` `
|
||||
)} else ${lesson.isUnlocked} end`;
|
||||
}
|
||||
|
||||
const updatedLessons = await tx
|
||||
.update(lesson)
|
||||
.set(lessonSet)
|
||||
.where(inArray(lesson.id, lessonIds))
|
||||
.returning({ id: lesson.id });
|
||||
|
||||
if (updatedLessons.length !== lessonIds.length) {
|
||||
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
|
||||
}
|
||||
}
|
||||
|
||||
if (exerciseUpdates.length > 0) {
|
||||
const exerciseIds = exerciseUpdates.map(({ item }) => item.id);
|
||||
const exerciseOrderUpdates = exerciseUpdates
|
||||
.filter(({ payload }) => payload.order !== undefined)
|
||||
.map(({ item, payload }) => ({ id: item.id, value: payload.order }));
|
||||
const exerciseSectionUpdates = exerciseUpdates
|
||||
.filter(({ payload }) => payload.sectionId !== undefined)
|
||||
.map(({ item, payload }) => ({ id: item.id, value: payload.sectionId }));
|
||||
const exerciseUnlockUpdates = exerciseUpdates
|
||||
.filter(({ payload }) => payload.isUnlocked !== undefined)
|
||||
.map(({ item, payload }) => ({ id: item.id, value: payload.isUnlocked }));
|
||||
|
||||
const exerciseSet: Record<string, unknown> = {
|
||||
updatedAt
|
||||
};
|
||||
|
||||
if (exerciseOrderUpdates.length > 0) {
|
||||
exerciseSet.order = sql`case ${exercise.id} ${sql.join(
|
||||
exerciseOrderUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
|
||||
sql` `
|
||||
)} else ${exercise.order} end`;
|
||||
}
|
||||
|
||||
if (exerciseSectionUpdates.length > 0) {
|
||||
exerciseSet.sectionId = sql`case ${exercise.id} ${sql.join(
|
||||
exerciseSectionUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
|
||||
sql` `
|
||||
)} else ${exercise.sectionId} end`;
|
||||
}
|
||||
|
||||
if (exerciseUnlockUpdates.length > 0) {
|
||||
exerciseSet.isUnlocked = sql`case ${exercise.id} ${sql.join(
|
||||
exerciseUnlockUpdates.map((update) => sql`when ${update.id} then ${update.value}`),
|
||||
sql` `
|
||||
)} else ${exercise.isUnlocked} end`;
|
||||
}
|
||||
|
||||
const updatedExercises = await tx
|
||||
.update(exercise)
|
||||
.set(exerciseSet)
|
||||
.where(inArray(exercise.id, exerciseIds))
|
||||
.returning({ id: exercise.id });
|
||||
|
||||
if (updatedExercises.length !== exerciseIds.length) {
|
||||
throw new AppError('Exercise not found', ErrorCodes.EXERCISE_NOT_FOUND, 404);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update course content',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteCourseContent(courseId: string, payload: TCourseContentDelete) {
|
||||
try {
|
||||
if (payload.sectionId) {
|
||||
const sectionId = payload.sectionId;
|
||||
const section = await getCourseSectionById(sectionId);
|
||||
if (!section || section.courseId !== courseId) {
|
||||
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const contentItems = await getCourseContentItems(courseId);
|
||||
const itemsToDelete = contentItems.filter(
|
||||
(item) =>
|
||||
(item.type === ContentType.Lesson || item.type === ContentType.Exercise) && item.sectionId === sectionId
|
||||
);
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
for (const item of itemsToDelete) {
|
||||
if (item.type === ContentType.Lesson) {
|
||||
const deleted = await deleteLesson(item.id, tx);
|
||||
if (!deleted) {
|
||||
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const deleted = await deleteExercise(item.id, tx);
|
||||
if (!deleted) {
|
||||
throw new AppError('Exercise not found', ErrorCodes.EXERCISE_NOT_FOUND, 404);
|
||||
}
|
||||
}
|
||||
|
||||
const deletedSection = await deleteCourseSection(sectionId, tx);
|
||||
if (!deletedSection) {
|
||||
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
|
||||
}
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!payload.items) {
|
||||
throw new AppError('Content items are required', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
const items = payload.items;
|
||||
await assertCourseContentItems(courseId, items);
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
for (const item of items) {
|
||||
if (item.type === ContentType.Lesson) {
|
||||
const deleted = await deleteLesson(item.id, tx);
|
||||
if (!deleted) {
|
||||
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const deleted = await deleteExercise(item.id, tx);
|
||||
if (!deleted) {
|
||||
throw new AppError('Exercise not found', ErrorCodes.EXERCISE_NOT_FOUND, 404);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete course content',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import { addGroupMember, createGroup } from '@cio/db/queries/group';
|
||||
import {
|
||||
createCourseNewsfeed,
|
||||
createCourse as createCourseQuery,
|
||||
createCourseSections,
|
||||
deleteCourse as deleteCourseQuery,
|
||||
getCourseProgress as getCourseProgressQuery,
|
||||
getCourseWithRelations,
|
||||
updateCourse as updateCourseQuery,
|
||||
updateLessonsSectionId
|
||||
} from '@cio/db/queries/course';
|
||||
import {
|
||||
getLastLogin,
|
||||
getLessonsWithCompletion,
|
||||
getProfileCourseProgress,
|
||||
getUserExercisesStats
|
||||
} from '@cio/db/queries/analytics/analytics';
|
||||
|
||||
import { ContentType, ROLE } from '@cio/utils/constants';
|
||||
import type { TCourse } from '@cio/db/types';
|
||||
import { db } from '@cio/db/drizzle';
|
||||
import { updateExercisesSectionId } from '@cio/db/queries/exercise/exercise';
|
||||
import { getProfileById } from '@cio/db/queries/auth';
|
||||
import { buildCourseContent, calcPercentageWithRounding, formatLastSeen, type CourseContent } from './utils';
|
||||
|
||||
const DEFAULT_CONTENT_GROUPING = true;
|
||||
const DEFAULT_SECTION_TITLE = 'First Section [edit me]';
|
||||
|
||||
/**
|
||||
* Gets a course by ID or slug with all related data
|
||||
* @param courseId Course ID (optional if slug provided)
|
||||
* @param slug Course slug (optional if courseId provided)
|
||||
* @param profileId Profile ID of the current user (optional, for computing lesson completion)
|
||||
* @returns Course with all related data
|
||||
*/
|
||||
export async function getCourse(courseId?: string, slug?: string, profileId?: string) {
|
||||
try {
|
||||
if (!courseId && !slug) {
|
||||
throw new AppError('Either courseId or slug must be provided', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
const course = await getCourseWithRelations(courseId, slug, profileId);
|
||||
if (!course) {
|
||||
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const isContentGroupingEnabled = course.metadata?.isContentGroupingEnabled ?? DEFAULT_CONTENT_GROUPING;
|
||||
const content = buildCourseContent(course.contentItems, isContentGroupingEnabled);
|
||||
|
||||
const { contentItems, org: courseOrg, ...rest } = course;
|
||||
|
||||
const base = {
|
||||
...rest,
|
||||
content
|
||||
};
|
||||
|
||||
if (courseOrg) {
|
||||
return {
|
||||
...base,
|
||||
org: {
|
||||
id: courseOrg.id,
|
||||
name: courseOrg.name,
|
||||
siteName: courseOrg.siteName ?? '',
|
||||
theme: courseOrg.theme ?? undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return base;
|
||||
} catch (error) {
|
||||
console.error('Error getting course:', error);
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch course',
|
||||
ErrorCodes.COURSE_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new course with group, group member, and default newsfeed
|
||||
* @param profileId Profile ID of the creator
|
||||
* @param data Course creation data
|
||||
* @returns Created course with group and member information
|
||||
*/
|
||||
export async function createCourse(
|
||||
profileId: string,
|
||||
data: { title: string; description: string; type: 'LIVE_CLASS' | 'SELF_PACED'; organizationId: string }
|
||||
): Promise<{ course: TCourse; groupId: string; memberId: string }> {
|
||||
try {
|
||||
const result = await db.transaction(async () => {
|
||||
// 1. Create group
|
||||
const [newGroup] = await createGroup({
|
||||
name: data.title,
|
||||
description: data.description,
|
||||
organizationId: data.organizationId
|
||||
});
|
||||
|
||||
if (!newGroup) {
|
||||
throw new AppError('Failed to create group', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
// 2. Create course with group_id
|
||||
const [newCourse] = await createCourseQuery({
|
||||
title: data.title,
|
||||
description: data.description,
|
||||
type: data.type,
|
||||
groupId: newGroup.id
|
||||
});
|
||||
|
||||
if (!newCourse) {
|
||||
throw new AppError('Failed to create course', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
// 3. Add group member (creator as TUTOR)
|
||||
const [newMember] = await addGroupMember({
|
||||
profileId,
|
||||
groupId: newGroup.id,
|
||||
roleId: ROLE.TUTOR
|
||||
});
|
||||
|
||||
if (!newMember) {
|
||||
throw new AppError('Failed to add group member', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
// 4. Add default news feed
|
||||
await createCourseNewsfeed({
|
||||
content: `<h2>Welcome to this course 🎉 </h2>
|
||||
<p>Thank you for joining this course and I hope you get the best out of it.</p>`,
|
||||
courseId: newCourse.id,
|
||||
isPinned: true,
|
||||
authorId: newMember.id
|
||||
});
|
||||
|
||||
return {
|
||||
course: newCourse,
|
||||
groupId: newGroup.id,
|
||||
memberId: newMember.id
|
||||
};
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create course',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a course
|
||||
* @param courseId Course ID
|
||||
* @param data Course update data
|
||||
* @returns Updated course
|
||||
*/
|
||||
export async function updateCourse(courseId: string, data: Partial<TCourse>) {
|
||||
try {
|
||||
const updated = await updateCourseQuery(courseId, data);
|
||||
if (!updated) {
|
||||
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const isContentGroupingEnabled = (updated.metadata?.isContentGroupingEnabled ?? DEFAULT_CONTENT_GROUPING) === true;
|
||||
|
||||
if (isContentGroupingEnabled) {
|
||||
const courseWithRelations = await getCourseWithRelations(courseId);
|
||||
if (courseWithRelations) {
|
||||
const contentItems = courseWithRelations.contentItems;
|
||||
const hasSections = contentItems.some((item) => item.type === ContentType.Section);
|
||||
const hasUngroupedItems = contentItems.some(
|
||||
(item) => (item.type === ContentType.Lesson || item.type === ContentType.Exercise) && item.sectionId === null
|
||||
);
|
||||
|
||||
if (!hasSections && hasUngroupedItems) {
|
||||
await db.transaction(async (tx) => {
|
||||
const [section] = await createCourseSections(
|
||||
[
|
||||
{
|
||||
title: DEFAULT_SECTION_TITLE,
|
||||
order: 1,
|
||||
courseId
|
||||
}
|
||||
],
|
||||
tx
|
||||
);
|
||||
|
||||
if (!section) {
|
||||
throw new AppError('Failed to create course section', ErrorCodes.COURSE_SECTION_NOT_FOUND, 500);
|
||||
}
|
||||
|
||||
await updateLessonsSectionId(courseId, section.id, tx);
|
||||
await updateExercisesSectionId(courseId, section.id, tx);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update course',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft deletes a course by setting status to 'DELETED'
|
||||
* @param courseId Course ID
|
||||
* @returns Deleted course
|
||||
*/
|
||||
export async function deleteCourse(courseId: string) {
|
||||
try {
|
||||
const deleted = await deleteCourseQuery(courseId);
|
||||
if (!deleted) {
|
||||
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
|
||||
}
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete course',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets course progress for a profile
|
||||
* @param courseId Course ID
|
||||
* @param profileId Profile ID
|
||||
* @returns Course progress with counts
|
||||
*/
|
||||
export async function getCourseProgress(courseId: string, profileId: string) {
|
||||
try {
|
||||
const progress = await getCourseProgressQuery(courseId, profileId);
|
||||
return progress;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to get course progress',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets course analytics including student progress, completion rates, and grades
|
||||
* @param courseId Course ID
|
||||
* @returns Course analytics data
|
||||
*/
|
||||
export async function getCourseAnalytics(courseId: string) {
|
||||
try {
|
||||
// Get course with members (no profileId needed for analytics)
|
||||
const course = await getCourseWithRelations(courseId);
|
||||
if (!course) {
|
||||
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
// Get all members
|
||||
const members = course.group?.members || [];
|
||||
|
||||
// Filter students and tutors
|
||||
const students = members.filter((member) => member.roleId === ROLE.STUDENT);
|
||||
const tutors = members.filter((member) => member.roleId === ROLE.ADMIN || member.roleId === ROLE.TUTOR);
|
||||
|
||||
// Get lessons and exercises
|
||||
const lessons = course.contentItems.filter((item) => item.type === ContentType.Lesson);
|
||||
const exercises = course.contentItems.filter((item) => item.type === ContentType.Exercise);
|
||||
|
||||
// Get student analytics
|
||||
const studentAnalytics = await Promise.all(
|
||||
students
|
||||
.filter((student) => student.profileId !== null)
|
||||
.map(async (student) => {
|
||||
try {
|
||||
const [courseProgress, userExercisesStats, lastLoginDate] = await Promise.all([
|
||||
getCourseProgressQuery(courseId, student.profileId!),
|
||||
getUserExercisesStats(courseId, student.profileId!),
|
||||
getLastLogin(student.profileId!)
|
||||
]);
|
||||
|
||||
if (!courseProgress) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const completedExercises = userExercisesStats?.filter((exercise) => exercise.isCompleted)?.length || 0;
|
||||
const totalExercises = userExercisesStats?.length || 0;
|
||||
|
||||
const totalEarnedPoints = userExercisesStats?.reduce((sum, exercise) => sum + exercise.score, 0) || 0;
|
||||
const totalPoints = userExercisesStats?.reduce((sum, exercise) => sum + exercise.totalPoints, 0) || 0;
|
||||
const averageGrade = calcPercentageWithRounding(totalEarnedPoints, totalPoints);
|
||||
|
||||
const lessonsCompleted = courseProgress.lessonsCompleted || 0;
|
||||
const totalLessons = courseProgress.lessonsCount || 0;
|
||||
const progressPercentage = calcPercentageWithRounding(lessonsCompleted, totalLessons);
|
||||
|
||||
return {
|
||||
id: student.profileId,
|
||||
profile: {
|
||||
fullname: student.profile?.fullname || 'Unknown',
|
||||
email: student.profile?.email || '',
|
||||
avatar_url: student.profile?.avatarUrl || ''
|
||||
},
|
||||
lessonsCompleted,
|
||||
totalLessons,
|
||||
exercisesSubmitted: completedExercises,
|
||||
totalExercises,
|
||||
averageGrade,
|
||||
lastSeen: formatLastSeen(lastLoginDate),
|
||||
progressPercentage
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error getting student overview:', error);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const validStudentAnalytics = studentAnalytics.filter(
|
||||
(student): student is NonNullable<typeof student> => student !== null
|
||||
);
|
||||
|
||||
// Calculate aggregated metrics
|
||||
let lessonCompletionRate = 0;
|
||||
let exerciseCompletionRate = 0;
|
||||
let averageGrade = 0;
|
||||
|
||||
if (validStudentAnalytics.length > 0) {
|
||||
lessonCompletionRate = Math.round(
|
||||
validStudentAnalytics.reduce((sum, student) => sum + student.progressPercentage, 0) /
|
||||
validStudentAnalytics.length
|
||||
);
|
||||
|
||||
exerciseCompletionRate = Math.round(
|
||||
validStudentAnalytics.reduce((sum, student) => {
|
||||
const completionRate =
|
||||
student.totalExercises > 0 ? (student.exercisesSubmitted / student.totalExercises) * 100 : 0;
|
||||
return sum + completionRate;
|
||||
}, 0) / validStudentAnalytics.length
|
||||
);
|
||||
|
||||
averageGrade = Math.round(
|
||||
validStudentAnalytics.reduce((sum, student) => sum + student.averageGrade, 0) / validStudentAnalytics.length
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
totalTutors: tutors.length,
|
||||
totalStudents: students.length,
|
||||
totalLessons: lessons.length,
|
||||
totalExercises: exercises.length,
|
||||
lessonCompletionRate,
|
||||
exerciseCompletionRate,
|
||||
averageGrade,
|
||||
students: validStudentAnalytics
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to get course analytics',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets user course analytics for a specific course
|
||||
* @param courseId Course ID
|
||||
* @param userId User ID (profile ID)
|
||||
* @returns User course analytics data
|
||||
*/
|
||||
export async function getUserCourseAnalytics(courseId: string, userId: string) {
|
||||
try {
|
||||
// Get user profile
|
||||
const profile = await getProfileById(userId);
|
||||
if (!profile) {
|
||||
throw new AppError('User profile not found', ErrorCodes.PROFILE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
// Get last login
|
||||
const lastLoginDate = await getLastLogin(userId);
|
||||
|
||||
// Fetch user exercises stats, lessons with completion, and course progress
|
||||
const [userExercisesStats, lessons, courseProgress] = await Promise.all([
|
||||
getUserExercisesStats(courseId, userId),
|
||||
getLessonsWithCompletion(courseId, userId),
|
||||
getProfileCourseProgress(courseId, userId)
|
||||
]);
|
||||
|
||||
if (!userExercisesStats || !lessons || !courseProgress) {
|
||||
throw new AppError('Failed to fetch course analytics data', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
// Calculate metrics
|
||||
const totalEarnedPoints = userExercisesStats.reduce((sum, exercise) => sum + exercise.score, 0);
|
||||
const totalPoints = userExercisesStats.reduce((sum, exercise) => sum + exercise.totalPoints, 0);
|
||||
const averageGrade = calcPercentageWithRounding(totalEarnedPoints, totalPoints);
|
||||
|
||||
const completedLessons = lessons.filter((lesson) => lesson.completed);
|
||||
const progressPercentage = calcPercentageWithRounding(completedLessons.length, lessons.length);
|
||||
|
||||
const completedExercises = userExercisesStats.filter((exercise) => exercise.isCompleted).length;
|
||||
const totalExercises = courseProgress.exercises_count || 0;
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: userId,
|
||||
fullName: profile.fullname || '',
|
||||
email: profile.email || '',
|
||||
avatarUrl: profile.avatarUrl || '',
|
||||
lastSeen: formatLastSeen(lastLoginDate)
|
||||
},
|
||||
averageGrade,
|
||||
userExercisesStats,
|
||||
totalExercises,
|
||||
completedExercises,
|
||||
progressPercentage
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError('Failed to get user exercises stats', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
}
|
||||
|
||||
export type { CourseContent, CourseContentItem } from './utils';
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,92 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
|
||||
import { getCourseTeachers } from '@cio/db/queries/course/people';
|
||||
import { getCourseWithOrgData } from '@cio/db/queries/course';
|
||||
import { buildEmailFromName, sendEmail } from '@cio/email';
|
||||
|
||||
export interface PaymentRequestData {
|
||||
courseId: string;
|
||||
studentEmail: string;
|
||||
studentFullname: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a payment request and sends emails to teacher and student
|
||||
* @param data Payment request data
|
||||
*/
|
||||
export async function createPaymentRequest(data: PaymentRequestData) {
|
||||
try {
|
||||
// Get course and organization data
|
||||
const course = await getCourseWithOrgData(data.courseId);
|
||||
|
||||
if (!course) {
|
||||
throw new AppError('Course not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const courseName = course.courseTitle || '';
|
||||
const orgName = course.orgName || 'ClassroomIO';
|
||||
const groupId = course.groupId;
|
||||
|
||||
if (!groupId) {
|
||||
throw new AppError('Course group not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
// Get first teacher (TUTOR or ADMIN) email
|
||||
const teacherResult = await getCourseTeachers({ groupId, limit: 1 });
|
||||
|
||||
if (teacherResult.length === 0 || !teacherResult[0]?.email) {
|
||||
throw new AppError('No teacher found for this course', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const teacherEmail = teacherResult[0].email;
|
||||
|
||||
// Send email to teacher about student buy request
|
||||
try {
|
||||
await sendEmail('teacherStudentBuyRequest', {
|
||||
to: teacherEmail,
|
||||
fields: {
|
||||
courseName,
|
||||
studentEmail: data.studentEmail,
|
||||
studentFullname: data.studentFullname
|
||||
},
|
||||
from: buildEmailFromName('ClassroomIO')
|
||||
});
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send teacher buy request email:', emailError);
|
||||
// Don't fail the request if email fails
|
||||
}
|
||||
|
||||
// Send email to student with payment instructions
|
||||
try {
|
||||
await sendEmail('studentProvePayment', {
|
||||
to: data.studentEmail,
|
||||
fields: {
|
||||
courseName,
|
||||
teacherEmail,
|
||||
studentFullname: data.studentFullname,
|
||||
orgName
|
||||
},
|
||||
from: buildEmailFromName(`${orgName} - ClassroomIO`),
|
||||
replyTo: teacherEmail
|
||||
});
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send student payment proof email:', emailError);
|
||||
// Don't fail the request if email fails
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
courseName,
|
||||
teacherEmail
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create payment request',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import {
|
||||
addCourseMember,
|
||||
deleteCourseMember,
|
||||
getCourseMember,
|
||||
getCourseMembers,
|
||||
getCourseTeachers,
|
||||
updateCourseMember
|
||||
} from '@cio/db/queries/course/people';
|
||||
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
import type { TAddCourseMembers } from '@cio/utils/validation/course/people';
|
||||
import type { TGroupmember } from '@cio/db/types';
|
||||
import { env } from '@api/config/env';
|
||||
import { getCourseWithOrgData } from '@cio/db/queries/course';
|
||||
import { getProfileById } from '@cio/db/queries/auth';
|
||||
import { buildEmailFromName, sendEmail } from '@cio/email';
|
||||
|
||||
/**
|
||||
* Gets all course members (people) for a course
|
||||
* @param courseId Course ID
|
||||
* @returns Array of course members with profile data
|
||||
*/
|
||||
export async function listCourseMembers(courseId: string) {
|
||||
try {
|
||||
return getCourseMembers(courseId);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list course members',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a course member (person) to a course
|
||||
* @param courseId Course ID
|
||||
* @param data Member data (profileId, roleId, email, name)
|
||||
* @returns Created member
|
||||
*/
|
||||
export async function addMember(
|
||||
courseId: string,
|
||||
data: { profileId?: string; roleId: number; email?: string; name?: string }
|
||||
) {
|
||||
try {
|
||||
if (!data.profileId && !data.email) {
|
||||
throw new AppError('Either profileId or email must be provided', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
const addedMember = await addCourseMember(courseId, data);
|
||||
|
||||
// Send emails when a student joins
|
||||
if (data.roleId === ROLE.STUDENT) {
|
||||
try {
|
||||
// Get course and organization data
|
||||
const courseOrgData = await getCourseWithOrgData(courseId);
|
||||
|
||||
if (courseOrgData) {
|
||||
const courseName = courseOrgData.courseTitle || '';
|
||||
const orgName = courseOrgData.orgName || 'ClassroomIO';
|
||||
|
||||
// Get student profile data
|
||||
let studentEmail: string | null = null;
|
||||
let studentName: string | null = null;
|
||||
|
||||
if (data.profileId) {
|
||||
const studentProfile = await getProfileById(data.profileId);
|
||||
|
||||
if (studentProfile) {
|
||||
studentEmail = studentProfile.email;
|
||||
studentName = studentProfile.fullname;
|
||||
}
|
||||
} else if (data.email) {
|
||||
studentEmail = data.email;
|
||||
studentName = data.name || null;
|
||||
}
|
||||
|
||||
// Send welcome email to student
|
||||
if (studentEmail) {
|
||||
try {
|
||||
await sendEmail('studentCourseWelcome', {
|
||||
to: studentEmail,
|
||||
fields: {
|
||||
orgName,
|
||||
courseName
|
||||
},
|
||||
from: buildEmailFromName(`${orgName} (via ClassroomIO.com)`)
|
||||
});
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send student welcome email:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
// Get all teachers (ADMIN or TUTOR) in the course
|
||||
const teachersResult = await getCourseTeachers({ courseId });
|
||||
|
||||
// Send notification to all teachers
|
||||
if (teachersResult.length > 0 && studentEmail && studentName) {
|
||||
const teacherEmails = teachersResult.map((t) => t.email).filter((email): email is string => email !== null);
|
||||
|
||||
await Promise.all(
|
||||
teacherEmails.map((teacherEmail) =>
|
||||
sendEmail('teacherStudentJoined', {
|
||||
to: teacherEmail,
|
||||
fields: {
|
||||
courseName,
|
||||
studentName,
|
||||
studentEmail
|
||||
},
|
||||
from: buildEmailFromName('ClassroomIO')
|
||||
}).catch((emailError) => {
|
||||
console.error(`Failed to send teacher notification email to ${teacherEmail}:`, emailError);
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (emailError) {
|
||||
// Log but don't fail the request if email fails
|
||||
console.error('Failed to send student join emails:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return addedMember;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to add course member',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds multiple course members to a course and optionally sends welcome emails
|
||||
* @param courseId Course ID
|
||||
* @param members Array of member data
|
||||
* @returns Array of created members
|
||||
*/
|
||||
export async function addMembers(courseId: string, members: TAddCourseMembers) {
|
||||
try {
|
||||
if (members.length === 0) {
|
||||
throw new AppError('At least one member must be provided', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
// Validate all members
|
||||
for (const member of members) {
|
||||
if (!member.profileId && !member.email) {
|
||||
throw new AppError(
|
||||
'Either profileId or email must be provided for each member',
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Get course title and organization data for emails (simple query, no expensive joins)
|
||||
const courseOrgData = await getCourseWithOrgData(courseId);
|
||||
|
||||
if (!courseOrgData) {
|
||||
throw new AppError('Course not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const courseName = courseOrgData.courseTitle || '';
|
||||
const orgName = courseOrgData.orgName || 'ClassroomIO';
|
||||
const orgSiteName = courseOrgData.orgSiteName || '';
|
||||
|
||||
// Add all members
|
||||
const addedMembers = await Promise.all(members.map((member) => addCourseMember(courseId, member)));
|
||||
|
||||
// Send welcome emails for teachers (TUTOR role = 2, ADMIN role = 1)
|
||||
const baseUrl = env.NODE_ENV === 'development' ? 'http://localhost:5173' : 'https://app.classroomio.com';
|
||||
const inviteLink = `${baseUrl}/org/${orgSiteName}/courses`;
|
||||
|
||||
// Send welcome emails to teachers
|
||||
const teacherEmailPromises: Promise<unknown>[] = [];
|
||||
|
||||
addedMembers.forEach((member, index) => {
|
||||
const memberData = members[index];
|
||||
// Only send emails to teachers (TUTOR or ADMIN role) who have email
|
||||
const roleId = memberData.roleId;
|
||||
const email = memberData.email;
|
||||
const name = memberData.name;
|
||||
|
||||
if ((roleId === ROLE.ADMIN || roleId === ROLE.TUTOR) && email && name) {
|
||||
teacherEmailPromises.push(
|
||||
sendEmail('teacherCourseWelcome', {
|
||||
to: email,
|
||||
fields: {
|
||||
name,
|
||||
orgName,
|
||||
courseName,
|
||||
inviteLink
|
||||
},
|
||||
from: buildEmailFromName(`${orgName} (via ClassroomIO.com)`)
|
||||
}).catch((emailError) => {
|
||||
console.error(`Failed to send welcome email to ${email}:`, emailError);
|
||||
return [];
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (teacherEmailPromises.length > 0) {
|
||||
try {
|
||||
await Promise.all(teacherEmailPromises);
|
||||
} catch (emailError) {
|
||||
// Log but don't fail the request if email fails
|
||||
console.error('Failed to send welcome emails:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return addedMembers;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to add course members',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a course member
|
||||
* @param courseId Course ID
|
||||
* @param memberId Member ID
|
||||
* @param data Partial member data to update
|
||||
* @returns Updated member
|
||||
*/
|
||||
export async function updateMember(courseId: string, memberId: string, data: Partial<TGroupmember>) {
|
||||
try {
|
||||
const updated = await updateCourseMember(courseId, memberId, data);
|
||||
if (!updated) {
|
||||
throw new AppError('Course member not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update course member',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a course member
|
||||
* @param courseId Course ID
|
||||
* @param memberId Member ID
|
||||
* @returns Deleted member
|
||||
*/
|
||||
export async function deleteMember(courseId: string, memberId: string) {
|
||||
try {
|
||||
const deleted = await deleteCourseMember(courseId, memberId);
|
||||
if (!deleted) {
|
||||
throw new AppError('Course member not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete course member',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import type { TCourseSection } from '@cio/db/types';
|
||||
import {
|
||||
createCourseSections,
|
||||
deleteCourseSection,
|
||||
getCourseSectionById,
|
||||
getCourseSectionsByCourseId,
|
||||
updateCourseSection,
|
||||
updateUngroupedLessonsSectionId
|
||||
} from '@cio/db/queries/course';
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type {
|
||||
TCourseSectionCreate,
|
||||
TCourseSectionPromoteUngrouped,
|
||||
TCourseSectionReorder,
|
||||
TCourseSectionUpdate
|
||||
} from '@cio/utils/validation/course/section';
|
||||
import { updateUngroupedExercisesSectionId } from '@cio/db/queries/exercise/exercise';
|
||||
import { db } from '@cio/db/drizzle';
|
||||
|
||||
/**
|
||||
* Creates a new course section
|
||||
* @param courseId Course ID
|
||||
* @param data Section creation data
|
||||
* @returns Created section
|
||||
*/
|
||||
export async function createCourseSection(courseId: string, data: TCourseSectionCreate): Promise<TCourseSection> {
|
||||
try {
|
||||
const sectionData = {
|
||||
...data,
|
||||
courseId
|
||||
};
|
||||
|
||||
const [section] = await createCourseSections([sectionData]);
|
||||
if (!section) {
|
||||
throw new AppError('Failed to create course section', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
return section;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create course section',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Promotes synthetic "Ungrouped" content into a real persisted section.
|
||||
* Creates a section and reassigns all ungrouped lessons/exercises to it transactionally.
|
||||
*/
|
||||
export async function promoteUngroupedSection(
|
||||
courseId: string,
|
||||
data: TCourseSectionPromoteUngrouped
|
||||
): Promise<{ section: TCourseSection; movedLessons: number; movedExercises: number }> {
|
||||
try {
|
||||
const existingSections = await getCourseSectionsByCourseId(courseId);
|
||||
const nextOrder = Math.max(...existingSections.map((section) => section.order ?? 0), 0) + 1;
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const [section] = await createCourseSections(
|
||||
[
|
||||
{
|
||||
title: data.title,
|
||||
courseId,
|
||||
order: nextOrder
|
||||
}
|
||||
],
|
||||
tx
|
||||
);
|
||||
|
||||
if (!section) {
|
||||
throw new AppError('Failed to create course section', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
const [movedLessons, movedExercises] = await Promise.all([
|
||||
updateUngroupedLessonsSectionId(courseId, section.id, tx),
|
||||
updateUngroupedExercisesSectionId(courseId, section.id, tx)
|
||||
]);
|
||||
|
||||
if (movedLessons + movedExercises === 0) {
|
||||
throw new AppError('No ungrouped content found', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
return {
|
||||
section,
|
||||
movedLessons,
|
||||
movedExercises
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to promote ungrouped content',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a course section by ID
|
||||
* @param sectionId Section ID
|
||||
* @returns Section or throws error if not found
|
||||
*/
|
||||
export async function getCourseSection(sectionId: string): Promise<TCourseSection> {
|
||||
try {
|
||||
const section = await getCourseSectionById(sectionId);
|
||||
if (!section) {
|
||||
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return section;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch course section',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a course section
|
||||
* @param sectionId Section ID
|
||||
* @param data Partial section update data
|
||||
* @returns Updated section
|
||||
*/
|
||||
export async function updateCourseSectionService(
|
||||
sectionId: string,
|
||||
data: TCourseSectionUpdate
|
||||
): Promise<TCourseSection> {
|
||||
try {
|
||||
const section = await getCourseSectionById(sectionId);
|
||||
if (!section) {
|
||||
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const updated = await updateCourseSection(sectionId, data);
|
||||
if (!updated) {
|
||||
throw new AppError('Failed to update course section', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update course section',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a course section
|
||||
* @param sectionId Section ID
|
||||
* @returns Deleted section
|
||||
*/
|
||||
export async function deleteCourseSectionService(sectionId: string): Promise<TCourseSection> {
|
||||
try {
|
||||
const section = await getCourseSectionById(sectionId);
|
||||
if (!section) {
|
||||
throw new AppError('Course section not found', ErrorCodes.COURSE_SECTION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const deleted = await deleteCourseSection(sectionId);
|
||||
if (!deleted) {
|
||||
throw new AppError('Failed to delete course section', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete course section',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists course sections for a course
|
||||
* @param courseId Course ID
|
||||
* @returns Array of sections
|
||||
*/
|
||||
export async function listCourseSections(courseId: string): Promise<TCourseSection[]> {
|
||||
try {
|
||||
return await getCourseSectionsByCourseId(courseId);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list course sections',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reorders course sections
|
||||
* @param sections Array of section IDs and orders
|
||||
* @returns Updated sections
|
||||
*/
|
||||
export async function reorderCourseSections(sections: TCourseSectionReorder['sections']): Promise<TCourseSection[]> {
|
||||
try {
|
||||
const updatePromises = sections.map(({ id, order }) => updateCourseSection(id, { order }));
|
||||
|
||||
const updated = await Promise.all(updatePromises);
|
||||
return updated.filter((section): section is TCourseSection => section !== null);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to reorder course sections',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { ContentType } from '@cio/utils/constants';
|
||||
import type { CourseContentItemRow } from '@cio/db/queries/course';
|
||||
|
||||
export type CourseContentItem = {
|
||||
id: string;
|
||||
type: ContentType;
|
||||
title: string;
|
||||
order: number | null;
|
||||
createdAt: string | null;
|
||||
sectionId: string | null;
|
||||
isUnlocked: boolean | null;
|
||||
isComplete: boolean | null;
|
||||
lessonAt: string | null;
|
||||
callUrl: string | null;
|
||||
hasNoteContent: boolean | null;
|
||||
hasSlideContent: boolean | null;
|
||||
videosCount: number | null;
|
||||
documentsCount: number | null;
|
||||
questionCount: number | null;
|
||||
dueBy: string | null;
|
||||
};
|
||||
|
||||
export type CourseContentSection = {
|
||||
id: string;
|
||||
title: string;
|
||||
order: number | null;
|
||||
items: CourseContentItem[];
|
||||
};
|
||||
|
||||
export type CourseContent = {
|
||||
grouped: boolean;
|
||||
sections: CourseContentSection[];
|
||||
items: CourseContentItem[];
|
||||
};
|
||||
|
||||
const CONTENT_TYPE_PRIORITY: Record<ContentType, number> = {
|
||||
[ContentType.Section]: -1,
|
||||
[ContentType.Lesson]: 0,
|
||||
[ContentType.Exercise]: 1
|
||||
};
|
||||
|
||||
function sortContentItems(items: CourseContentItem[]): CourseContentItem[] {
|
||||
return [...items].sort((a, b) => {
|
||||
const orderDiff = (a.order ?? 0) - (b.order ?? 0);
|
||||
if (orderDiff !== 0) return orderDiff;
|
||||
|
||||
const typeDiff = CONTENT_TYPE_PRIORITY[a.type] - CONTENT_TYPE_PRIORITY[b.type];
|
||||
if (typeDiff !== 0) return typeDiff;
|
||||
|
||||
return new Date(a.createdAt || 0).getTime() - new Date(b.createdAt || 0).getTime();
|
||||
});
|
||||
}
|
||||
|
||||
function sortContentSections(sections: CourseContentSection[]): CourseContentSection[] {
|
||||
return [...sections].sort((a, b) => {
|
||||
const orderDiff = (a.order ?? 0) - (b.order ?? 0);
|
||||
if (orderDiff !== 0) return orderDiff;
|
||||
|
||||
return a.title.localeCompare(b.title);
|
||||
});
|
||||
}
|
||||
|
||||
function mapCourseContentItems(rows: CourseContentItemRow[]): CourseContentItem[] {
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
type: row.type as ContentType,
|
||||
title: row.title ?? '',
|
||||
order: row.order ?? null,
|
||||
createdAt: row.createdAt ?? null,
|
||||
sectionId: row.sectionId ?? null,
|
||||
isUnlocked: row.isUnlocked ?? null,
|
||||
isComplete: row.isComplete ?? null,
|
||||
lessonAt: row.lessonAt ?? null,
|
||||
callUrl: row.callUrl ?? null,
|
||||
hasNoteContent: row.hasNoteContent ?? null,
|
||||
hasSlideContent: row.hasSlideContent ?? null,
|
||||
videosCount: row.videosCount ?? null,
|
||||
documentsCount: row.documentsCount ?? null,
|
||||
questionCount: row.questionCount ?? null,
|
||||
dueBy: row.dueBy ?? null
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildCourseContent(rows: CourseContentItemRow[], isContentGroupingEnabled: boolean): CourseContent {
|
||||
const items = mapCourseContentItems(rows);
|
||||
const contentItems = items.filter((item) => item.type !== ContentType.Section);
|
||||
|
||||
if (!isContentGroupingEnabled) {
|
||||
return {
|
||||
grouped: false,
|
||||
sections: [],
|
||||
items: sortContentItems(contentItems)
|
||||
};
|
||||
}
|
||||
|
||||
const sectionItems = items.filter((item) => item.type === ContentType.Section);
|
||||
const sectionMap = new Map<string, CourseContentItem[]>();
|
||||
const ungroupedItems: CourseContentItem[] = [];
|
||||
|
||||
for (const item of contentItems) {
|
||||
if (!item.sectionId) {
|
||||
ungroupedItems.push(item);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!sectionMap.has(item.sectionId)) {
|
||||
sectionMap.set(item.sectionId, []);
|
||||
}
|
||||
|
||||
sectionMap.get(item.sectionId)!.push(item);
|
||||
}
|
||||
|
||||
const sections = sortContentSections(
|
||||
sectionItems.map((section) => ({
|
||||
id: section.id,
|
||||
title: section.title || 'Untitled section',
|
||||
order: section.order ?? null,
|
||||
items: sortContentItems(sectionMap.get(section.id) ?? [])
|
||||
}))
|
||||
);
|
||||
|
||||
if (ungroupedItems.length > 0) {
|
||||
sections.push({
|
||||
id: 'ungrouped',
|
||||
title: 'Ungrouped',
|
||||
order: sections.length + 1,
|
||||
items: sortContentItems(ungroupedItems)
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
grouped: true,
|
||||
sections,
|
||||
items: []
|
||||
};
|
||||
}
|
||||
|
||||
export function calcPercentageWithRounding(a: number, b: number): number {
|
||||
if (b === 0) return 0;
|
||||
return Math.round((a / b) * 100);
|
||||
}
|
||||
|
||||
export function formatLastSeen(lastLoginDate: string | null | undefined): string {
|
||||
if (!lastLoginDate) return 'Never';
|
||||
|
||||
const lastLogin = new Date(lastLoginDate);
|
||||
const now = new Date();
|
||||
const diffInHours = Math.floor((now.getTime() - lastLogin.getTime()) / (1000 * 60 * 60));
|
||||
|
||||
if (diffInHours < 1) {
|
||||
return 'Just now';
|
||||
}
|
||||
if (diffInHours < 24) {
|
||||
return `${diffInHours} hours ago`;
|
||||
}
|
||||
|
||||
const diffInDays = Math.floor(diffInHours / 24);
|
||||
return `${diffInDays} days ago`;
|
||||
}
|
||||
@@ -49,7 +49,7 @@ export async function getOrganisationAnalytics(orgId?: string, siteName?: string
|
||||
name: e.fullname,
|
||||
courseId: e.courseId,
|
||||
course: e.courseTitle,
|
||||
date: e.enrolledAt
|
||||
date: e.enrolledAt ?? ''
|
||||
}));
|
||||
|
||||
return analytics;
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type { TExercise, TExerciseTemplate, TNewOption, TNewQuestion } from '@cio/db/types';
|
||||
import type { TExerciseCreate, TExerciseUpdate } from '@cio/utils/validation/exercise';
|
||||
import {
|
||||
createExercises,
|
||||
syncOptionIdSequence,
|
||||
createOptions,
|
||||
createQuestions,
|
||||
deleteExercise,
|
||||
deleteOptionsByIds,
|
||||
deleteQuestionsByIds,
|
||||
getExerciseById,
|
||||
getExerciseCompletionByProfile,
|
||||
getExerciseCompletionsByProfile,
|
||||
getExerciseWithRelationsOptimized,
|
||||
getExercisesByCourseId,
|
||||
getLMSExercises,
|
||||
updateExercise,
|
||||
updateOptions,
|
||||
updateQuestions
|
||||
} from '@cio/db/queries/exercise';
|
||||
|
||||
import { db } from '@cio/db/drizzle';
|
||||
import type { DbOrTxClient } from '@cio/db/drizzle';
|
||||
import {
|
||||
buildExerciseUpdateFields,
|
||||
computeExerciseDiff,
|
||||
createNewQuestionsWithOptions,
|
||||
fetchQuestionsAndOptions,
|
||||
transformQuestions,
|
||||
type QuestionWithRelations
|
||||
} from './utils';
|
||||
|
||||
type ExerciseWithQuestions = TExercise & {
|
||||
isComplete: boolean;
|
||||
questions?: QuestionWithRelations[];
|
||||
};
|
||||
|
||||
type ExerciseWithCompletion = TExercise & {
|
||||
isComplete: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new exercise with optional questions and options
|
||||
* @param data Exercise creation data
|
||||
* @returns Created exercise
|
||||
*/
|
||||
export async function createExercise(data: TExerciseCreate): Promise<TExercise> {
|
||||
try {
|
||||
const exerciseData = {
|
||||
title: data.title,
|
||||
description: data.description ?? null,
|
||||
lessonId: data.lessonId || null,
|
||||
courseId: data.courseId,
|
||||
sectionId: data.sectionId || null,
|
||||
order: data.order ?? null,
|
||||
dueBy: data.dueBy || null
|
||||
};
|
||||
|
||||
const [exercise] = await createExercises([exerciseData]);
|
||||
if (!exercise) {
|
||||
throw new AppError('Failed to create exercise', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
// Create questions and options if provided
|
||||
if (data.questions && data.questions.length > 0) {
|
||||
await db.transaction(async (tx) => {
|
||||
const txClient = tx as DbOrTxClient;
|
||||
const questionsData: TNewQuestion[] = data.questions!.map((q) => ({
|
||||
exerciseId: exercise.id,
|
||||
title: q.question,
|
||||
questionTypeId: q.questionTypeId || 1,
|
||||
points: q.points || 0,
|
||||
settings: q.settings ?? {}
|
||||
}));
|
||||
|
||||
const questions = await createQuestions(questionsData, txClient);
|
||||
|
||||
// Create options for each question
|
||||
const optionsPromises = data.questions!.map(async (q, index) => {
|
||||
const question = questions[index];
|
||||
if (!question) return;
|
||||
|
||||
const optionsData: TNewOption[] = q.options.map((opt) => ({
|
||||
questionId: question.id,
|
||||
label: opt.label,
|
||||
isCorrect: opt.isCorrect,
|
||||
settings: opt.settings ?? {}
|
||||
}));
|
||||
|
||||
return createOptions(optionsData, txClient);
|
||||
});
|
||||
|
||||
await Promise.all(optionsPromises);
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch the complete exercise with questions and options
|
||||
return await getExercise(exercise.id);
|
||||
} catch (error) {
|
||||
console.error('createExercise error:', error);
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create exercise',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an exercise by ID with questions and options
|
||||
* @param exerciseId Exercise ID
|
||||
* @returns Exercise with questions and options
|
||||
*/
|
||||
export async function getExercise(
|
||||
exerciseId: string,
|
||||
dbClient?: DbOrTxClient,
|
||||
profileId?: string
|
||||
): Promise<ExerciseWithQuestions> {
|
||||
try {
|
||||
// Optimized: Fetch exercise + questions + questionTypes + options in one JOIN query
|
||||
const { exercise, questions } = await getExerciseWithRelationsOptimized(exerciseId, dbClient);
|
||||
|
||||
const isComplete = profileId ? await getExerciseCompletionByProfile(exerciseId, profileId, dbClient) : false;
|
||||
|
||||
// Build questionTypeMap from questions (already fetched with questionType)
|
||||
const questionTypeMap = new Map(questions.map((q) => [q.questionType.id, q.questionType]));
|
||||
|
||||
// Extract options from questions and transform
|
||||
const allOptions = questions.flatMap((q) => q.options || []);
|
||||
|
||||
// Transform questions (strip questionType and options since they're handled in transform)
|
||||
const questionsForTransform = questions.map(({ questionType, options, ...q }) => q);
|
||||
const questionsWithOptions = transformQuestions(questionsForTransform, allOptions, questionTypeMap);
|
||||
|
||||
return {
|
||||
...exercise,
|
||||
isComplete,
|
||||
questions: questionsWithOptions
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch exercise',
|
||||
ErrorCodes.EXERCISE_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates an exercise with questions and options.
|
||||
* Only updates what has changed by querying the current state first and computing a diff.
|
||||
* @param exerciseId Exercise ID
|
||||
* @param data Partial exercise update data
|
||||
* @returns Updated exercise
|
||||
*/
|
||||
export async function updateExerciseService(exerciseId: string, data: TExerciseUpdate): Promise<TExercise> {
|
||||
try {
|
||||
return await db.transaction(async (tx) => {
|
||||
const txClient = tx as DbOrTxClient;
|
||||
|
||||
// Update exercise basic fields only if they changed
|
||||
const exerciseUpdate = buildExerciseUpdateFields(data);
|
||||
if (Object.keys(exerciseUpdate).length > 0) {
|
||||
const updated = await updateExercise(exerciseId, exerciseUpdate, txClient);
|
||||
if (!updated) {
|
||||
throw new AppError('Failed to update exercise', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
}
|
||||
|
||||
// Process questions - only update what changed
|
||||
if (data.questions && data.questions.length > 0) {
|
||||
// Query current state from DB
|
||||
const { questions: currentQuestions, options: currentOptions } = await fetchQuestionsAndOptions(
|
||||
exerciseId,
|
||||
txClient
|
||||
);
|
||||
|
||||
// Build current state with options mapped to their questions
|
||||
const currentQuestionsWithOptions = currentQuestions.map((q) => ({
|
||||
...q,
|
||||
options: currentOptions.filter((opt) => opt.questionId === q.id)
|
||||
}));
|
||||
|
||||
// Compute diff between current DB state and incoming data
|
||||
const diff = computeExerciseDiff(currentQuestionsWithOptions, data.questions);
|
||||
|
||||
// Sync option id sequence so next inserts get ids > max(id) (avoids option_pkey duplicate)
|
||||
if (
|
||||
diff.options.creates.length > 0 ||
|
||||
diff.questions.newQuestions.length > 0 ||
|
||||
diff.questions.updates.length > 0
|
||||
) {
|
||||
await syncOptionIdSequence(txClient);
|
||||
}
|
||||
|
||||
// Apply all changes in parallel (they operate on different records)
|
||||
await Promise.all([
|
||||
// Delete questions marked for deletion (cascade deletes their options)
|
||||
diff.questions.deletedIds.length > 0 && deleteQuestionsByIds(diff.questions.deletedIds, txClient),
|
||||
// Update only questions that have changed fields
|
||||
diff.questions.updates.length > 0 && updateQuestions(diff.questions.updates, txClient),
|
||||
// Delete options marked for deletion
|
||||
diff.options.deletedIds.length > 0 && deleteOptionsByIds(diff.options.deletedIds, txClient),
|
||||
// Update only options that have changed fields
|
||||
diff.options.updates.length > 0 && updateOptions(diff.options.updates, txClient),
|
||||
// Create new options for existing questions
|
||||
diff.options.creates.length > 0 && createOptions(diff.options.creates, txClient),
|
||||
// Create new questions with their options
|
||||
diff.questions.newQuestions.length > 0 &&
|
||||
createNewQuestionsWithOptions(exerciseId, diff.questions.newQuestions, txClient)
|
||||
]);
|
||||
}
|
||||
|
||||
// Return the updated exercise
|
||||
return await getExercise(exerciseId, txClient);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('updateExerciseService error:', error);
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError('Failed to update exercise', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an exercise (cascade deletes questions and options)
|
||||
* @param exerciseId Exercise ID
|
||||
* @returns Deleted exercise
|
||||
*/
|
||||
export async function deleteExerciseService(exerciseId: string): Promise<TExercise> {
|
||||
try {
|
||||
const exercise = await getExerciseById(exerciseId);
|
||||
if (!exercise) {
|
||||
throw new AppError('Exercise not found', ErrorCodes.EXERCISE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const deleted = await deleteExercise(exerciseId);
|
||||
if (!deleted) {
|
||||
throw new AppError('Failed to delete exercise', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete exercise',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists exercises for a course
|
||||
* @param courseId Course ID
|
||||
* @param lessonId Optional lesson ID filter
|
||||
* @returns Array of exercises
|
||||
*/
|
||||
export async function listExercises(
|
||||
courseId: string,
|
||||
filters: { lessonId?: string; sectionId?: string } = {},
|
||||
profileId?: string
|
||||
): Promise<ExerciseWithCompletion[]> {
|
||||
try {
|
||||
const exercises = await getExercisesByCourseId(courseId, filters);
|
||||
|
||||
if (!profileId) {
|
||||
return exercises.map((exercise) => ({
|
||||
...exercise,
|
||||
isComplete: false
|
||||
}));
|
||||
}
|
||||
|
||||
const completedIds = await getExerciseCompletionsByProfile(
|
||||
exercises.map((exercise) => exercise.id),
|
||||
profileId
|
||||
);
|
||||
const completedSet = new Set(completedIds);
|
||||
|
||||
return exercises.map((exercise) => ({
|
||||
...exercise,
|
||||
isComplete: completedSet.has(exercise.id)
|
||||
}));
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list exercises',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an exercise from a template
|
||||
* @param courseId Course ID
|
||||
* @param lessonId Lesson ID
|
||||
* @param template Exercise template with questionnaire
|
||||
* @returns Created exercise with questions and options
|
||||
*/
|
||||
export async function createExerciseFromTemplate(
|
||||
courseId: string,
|
||||
lessonId: string | undefined,
|
||||
sectionId: string | undefined,
|
||||
order: number | undefined,
|
||||
template: TExerciseTemplate
|
||||
): Promise<TExercise> {
|
||||
try {
|
||||
// Create the exercise
|
||||
const exerciseData: TExerciseCreate = {
|
||||
title: template.title!,
|
||||
description: template.description ?? undefined,
|
||||
lessonId,
|
||||
sectionId,
|
||||
order,
|
||||
courseId
|
||||
};
|
||||
|
||||
const exercise = await createExercise(exerciseData);
|
||||
|
||||
// Process the questionnaire to create questions and options
|
||||
const { questions } = template.questionnaire!;
|
||||
|
||||
if (questions && questions.length > 0) {
|
||||
await db.transaction(async (tx) => {
|
||||
const txClient = tx as DbOrTxClient;
|
||||
for (const question of questions) {
|
||||
const { title, question_type, options, order, points } = question;
|
||||
const questionSettings = (question as { settings?: Record<string, unknown> }).settings ?? {};
|
||||
|
||||
// Create question
|
||||
const [newQuestion] = await createQuestions(
|
||||
[
|
||||
{
|
||||
exerciseId: exercise.id,
|
||||
title,
|
||||
questionTypeId: question_type.id,
|
||||
points: points || 0,
|
||||
order: order || 0,
|
||||
settings: questionSettings
|
||||
}
|
||||
],
|
||||
txClient
|
||||
);
|
||||
|
||||
if (!newQuestion) continue;
|
||||
|
||||
// Create options if not TEXTAREA type
|
||||
if (question_type.id !== 3 && options && options.length > 0) {
|
||||
// Filter out deleted options
|
||||
|
||||
// value column is UUID (default gen_random_uuid()); label is the display text only
|
||||
const optionsData: TNewOption[] = options.map((opt) => ({
|
||||
questionId: newQuestion.id,
|
||||
label: opt.label || '',
|
||||
isCorrect: opt.is_correct || false,
|
||||
settings: (opt as { settings?: Record<string, unknown> }).settings ?? {}
|
||||
}));
|
||||
|
||||
await createOptions(optionsData, txClient);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch the complete exercise with questions and options
|
||||
return await getExercise(exercise.id);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create exercise from template',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets LMS exercises for a student in an organization
|
||||
* Returns exercises from unlocked lessons in courses where the student is a member
|
||||
* @param profileId - The profile ID of the student
|
||||
* @param orgId - The organization ID
|
||||
* @returns Array of exercises with related data
|
||||
*/
|
||||
export async function getLMSExercisesService(profileId: string, orgId: string) {
|
||||
try {
|
||||
const exercises = await getLMSExercises(profileId, orgId);
|
||||
return exercises;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch LMS exercises',
|
||||
ErrorCodes.EXERCISE_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './exercise';
|
||||
@@ -1,10 +1,14 @@
|
||||
import { calculateTotalPoints } from '@api/utils/template';
|
||||
import { TExerciseTemplate, TNewExerciseTemplate } from '@db/types';
|
||||
import { getAllTemplates, getTemplateById, getTemplateByTag } from '@db/queries/template/template';
|
||||
import { TNewExerciseTemplate, TExerciseTemplate } from '@db/types';
|
||||
|
||||
import { calculateTotalPoints } from '@api/utils/template';
|
||||
|
||||
function mapTemplateToMetadata(templates: TNewExerciseTemplate[]) {
|
||||
return templates.map((template) => {
|
||||
const questionnaire = template.questionnaire;
|
||||
if (!questionnaire) {
|
||||
throw new Error(`Template ${template.id} is missing questionnaire`);
|
||||
}
|
||||
|
||||
return {
|
||||
id: template.id,
|
||||
@@ -29,16 +33,13 @@ export async function fetchAllTemplatesMetadata() {
|
||||
return mapTemplateToMetadata(templates);
|
||||
}
|
||||
|
||||
export async function fetchTemplateById(id: number): Promise<TExerciseTemplate> {
|
||||
let template: TExerciseTemplate;
|
||||
export async function fetchTemplateById(id: number): Promise<TExerciseTemplate | undefined> {
|
||||
try {
|
||||
template = await getTemplateById(id);
|
||||
return getTemplateById(id);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch template from DB:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
return template;
|
||||
}
|
||||
|
||||
export async function fetchTemplatesByTag(tag: string) {
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type { TExercise, TNewOption, TNewQuestion, TQuestionAnswer, TQuestionType } from '@cio/db/types';
|
||||
import {
|
||||
createOptions,
|
||||
createQuestions,
|
||||
deleteOptionsByIds,
|
||||
deleteQuestionsByIds,
|
||||
getOptionsByQuestionIds,
|
||||
getQuestionTypesByIds,
|
||||
getQuestionsByExerciseIds,
|
||||
updateOptions,
|
||||
updateQuestions
|
||||
} from '@cio/db/queries/exercise';
|
||||
|
||||
import type { DbOrTxClient } from '@cio/db/drizzle';
|
||||
import type { TExerciseUpdate } from '@cio/utils/validation/exercise';
|
||||
|
||||
type CurrentQuestion = TNewQuestion & { options?: TNewOption[] };
|
||||
type CurrentOption = TNewOption;
|
||||
|
||||
type ExerciseAnswer = Pick<
|
||||
TQuestionAnswer,
|
||||
'id' | 'answerData' | 'point' | 'questionId' | 'submissionId' | 'groupMemberId'
|
||||
> & { id?: number };
|
||||
|
||||
export type QuestionWithRelations = {
|
||||
id: number | string;
|
||||
value: string;
|
||||
name: string;
|
||||
title: string;
|
||||
type: number;
|
||||
points: number;
|
||||
order: number;
|
||||
questionType: {
|
||||
id: number;
|
||||
label: string;
|
||||
};
|
||||
questionTypeId: number;
|
||||
settings?: Record<string, unknown>;
|
||||
code?: string;
|
||||
answers?: ExerciseAnswer[];
|
||||
deletedAt?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
options: {
|
||||
id: number | string;
|
||||
label: string | null;
|
||||
value: string | null;
|
||||
isCorrect: boolean;
|
||||
settings?: Record<string, unknown>;
|
||||
deletedAt?: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
function normalizeSettings(value: unknown): Record<string, unknown> {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
function areSettingsEqual(left: unknown, right: unknown): boolean {
|
||||
const leftNormalized = normalizeSettings(left);
|
||||
const rightNormalized = normalizeSettings(right);
|
||||
|
||||
return JSON.stringify(leftNormalized) === JSON.stringify(rightNormalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts exercise-level fields from the update payload
|
||||
*/
|
||||
export function buildExerciseUpdateFields(data: TExerciseUpdate): Partial<TExercise> {
|
||||
const exerciseUpdate: Partial<TExercise> = {};
|
||||
if (data.title !== undefined) exerciseUpdate.title = data.title;
|
||||
if (data.description !== undefined) exerciseUpdate.description = data.description;
|
||||
if (data.lessonId !== undefined) exerciseUpdate.lessonId = data.lessonId || null;
|
||||
if (data.sectionId !== undefined) exerciseUpdate.sectionId = data.sectionId || null;
|
||||
if (data.order !== undefined) exerciseUpdate.order = data.order;
|
||||
if (data.isUnlocked !== undefined) exerciseUpdate.isUnlocked = data.isUnlocked;
|
||||
if (data.dueBy !== undefined) exerciseUpdate.dueBy = data.dueBy || null;
|
||||
return exerciseUpdate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Categorizes questions into deleted, existing, and new
|
||||
*/
|
||||
export function categorizeQuestions(questions: NonNullable<TExerciseUpdate['questions']>) {
|
||||
const deletedIds: number[] = [];
|
||||
const existingQuestions: typeof questions = [];
|
||||
const newQuestions: typeof questions = [];
|
||||
const questionUpdates: Array<{ id: number; data: Partial<TNewQuestion> }> = [];
|
||||
|
||||
for (const q of questions) {
|
||||
if (q.deletedAt && q.id) {
|
||||
deletedIds.push(q.id);
|
||||
} else if (q.id) {
|
||||
existingQuestions.push(q);
|
||||
questionUpdates.push({
|
||||
id: q.id,
|
||||
data: {
|
||||
title: q.question,
|
||||
points: q.points,
|
||||
questionTypeId: q.questionTypeId,
|
||||
settings: normalizeSettings(q.settings)
|
||||
}
|
||||
});
|
||||
} else {
|
||||
newQuestions.push(q);
|
||||
}
|
||||
}
|
||||
|
||||
return { deletedIds, existingQuestions, newQuestions, questionUpdates };
|
||||
}
|
||||
|
||||
/**
|
||||
* Categorizes options for a single question into deleted, existing, and new
|
||||
*/
|
||||
export function categorizeOptions(
|
||||
questionId: number,
|
||||
options: NonNullable<TExerciseUpdate['questions']>[number]['options']
|
||||
) {
|
||||
const deletedIds: number[] = [];
|
||||
const existingUpdates: Array<{ id: number; data: Partial<TNewOption> }> = [];
|
||||
const newOptions: TNewOption[] = [];
|
||||
|
||||
if (!options || options.length === 0) {
|
||||
return { deletedIds, existingUpdates, newOptions };
|
||||
}
|
||||
|
||||
for (const opt of options) {
|
||||
if (opt.deletedAt && opt.id) {
|
||||
deletedIds.push(opt.id);
|
||||
} else if (opt.id) {
|
||||
existingUpdates.push({
|
||||
id: opt.id,
|
||||
data: {
|
||||
label: opt.label,
|
||||
isCorrect: opt.isCorrect,
|
||||
settings: normalizeSettings(opt.settings)
|
||||
}
|
||||
});
|
||||
} else {
|
||||
newOptions.push({
|
||||
questionId,
|
||||
label: opt.label,
|
||||
isCorrect: opt.isCorrect,
|
||||
settings: normalizeSettings(opt.settings)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { deletedIds, existingUpdates, newOptions };
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares current question with incoming question data and returns only changed fields
|
||||
*/
|
||||
function diffQuestion(
|
||||
current: CurrentQuestion,
|
||||
incoming: NonNullable<TExerciseUpdate['questions']>[number]
|
||||
): Partial<TNewQuestion> | null {
|
||||
const changes: Partial<TNewQuestion> = {};
|
||||
let hasChanges = false;
|
||||
|
||||
if (incoming.question !== current.title) {
|
||||
changes.title = incoming.question;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (incoming.points !== undefined && incoming.points !== current.points) {
|
||||
changes.points = incoming.points;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (incoming.questionTypeId !== undefined && incoming.questionTypeId !== current.questionTypeId) {
|
||||
changes.questionTypeId = incoming.questionTypeId;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (incoming.order !== undefined && incoming.order !== (current.order ?? undefined)) {
|
||||
changes.order = incoming.order;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (!areSettingsEqual(current.settings, incoming.settings)) {
|
||||
changes.settings = normalizeSettings(incoming.settings);
|
||||
hasChanges = true;
|
||||
}
|
||||
|
||||
return hasChanges ? changes : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares current option with incoming option data and returns only changed fields
|
||||
*/
|
||||
function diffOption(
|
||||
current: CurrentOption,
|
||||
incoming: NonNullable<NonNullable<TExerciseUpdate['questions']>[number]['options']>[number]
|
||||
): Partial<TNewOption> | null {
|
||||
const changes: Partial<TNewOption> = {};
|
||||
let hasChanges = false;
|
||||
|
||||
if (incoming.label !== current.label) {
|
||||
changes.label = incoming.label;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (incoming.isCorrect !== current.isCorrect) {
|
||||
changes.isCorrect = incoming.isCorrect;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (!areSettingsEqual(current.settings, incoming.settings)) {
|
||||
changes.settings = normalizeSettings(incoming.settings);
|
||||
hasChanges = true;
|
||||
}
|
||||
|
||||
return hasChanges ? changes : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes diff between current exercise state and incoming update data
|
||||
* Returns only the changes that need to be applied
|
||||
*/
|
||||
export function computeExerciseDiff(
|
||||
currentQuestions: CurrentQuestion[],
|
||||
incomingQuestions: NonNullable<TExerciseUpdate['questions']>
|
||||
) {
|
||||
const questionMap = new Map(currentQuestions.map((q) => [q.id, q]));
|
||||
|
||||
const deletedQuestionIds: number[] = [];
|
||||
const questionUpdates: Array<{ id: number; data: Partial<TNewQuestion> }> = [];
|
||||
const newQuestions: NonNullable<TExerciseUpdate['questions']> = [];
|
||||
|
||||
// Process incoming questions
|
||||
for (const incoming of incomingQuestions) {
|
||||
if (incoming.deletedAt && incoming.id) {
|
||||
deletedQuestionIds.push(incoming.id);
|
||||
} else if (incoming.id) {
|
||||
const current = questionMap.get(incoming.id);
|
||||
if (current) {
|
||||
const changes = diffQuestion(current, incoming);
|
||||
if (changes) {
|
||||
questionUpdates.push({ id: incoming.id, data: changes });
|
||||
}
|
||||
} else {
|
||||
// Question ID exists but not in current state - treat as new
|
||||
newQuestions.push(incoming);
|
||||
}
|
||||
} else {
|
||||
newQuestions.push(incoming);
|
||||
}
|
||||
}
|
||||
|
||||
// Compute option diffs for existing questions
|
||||
const optionDeletes: number[] = [];
|
||||
const optionUpdates: Array<{ id: number; data: Partial<TNewOption> }> = [];
|
||||
const optionCreates: TNewOption[] = [];
|
||||
|
||||
for (const incoming of incomingQuestions) {
|
||||
if (!incoming.id || incoming.deletedAt) continue;
|
||||
|
||||
const current = questionMap.get(incoming.id);
|
||||
if (!current) continue;
|
||||
|
||||
const currentOptionMap = new Map((current.options || []).map((opt) => [opt.id, opt]));
|
||||
const incomingOptions = incoming.options || [];
|
||||
const processedIncomingOptionIds = new Set<number>();
|
||||
|
||||
for (const incomingOpt of incomingOptions) {
|
||||
if (incomingOpt.deletedAt && incomingOpt.id) {
|
||||
optionDeletes.push(incomingOpt.id);
|
||||
|
||||
processedIncomingOptionIds.add(incomingOpt.id);
|
||||
} else if (incomingOpt.id) {
|
||||
processedIncomingOptionIds.add(incomingOpt.id);
|
||||
|
||||
const currentOpt = currentOptionMap.get(incomingOpt.id);
|
||||
if (currentOpt) {
|
||||
const changes = diffOption(currentOpt, incomingOpt);
|
||||
if (changes) {
|
||||
optionUpdates.push({ id: incomingOpt.id, data: changes });
|
||||
}
|
||||
} else {
|
||||
// Option ID exists in incoming but not in current - treat as create
|
||||
optionCreates.push({
|
||||
questionId: incoming.id,
|
||||
label: incomingOpt.label,
|
||||
isCorrect: incomingOpt.isCorrect,
|
||||
settings: normalizeSettings(incomingOpt.settings),
|
||||
value: crypto.randomUUID()
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// New option without ID
|
||||
optionCreates.push({
|
||||
questionId: incoming.id,
|
||||
label: incomingOpt.label,
|
||||
isCorrect: incomingOpt.isCorrect,
|
||||
settings: normalizeSettings(incomingOpt.settings),
|
||||
value: crypto.randomUUID()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check for options that were deleted (exist in current but not in incoming)
|
||||
for (const [optId] of currentOptionMap) {
|
||||
if (optId !== undefined && !processedIncomingOptionIds.has(optId)) {
|
||||
optionDeletes.push(optId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
questions: {
|
||||
deletedIds: deletedQuestionIds,
|
||||
updates: questionUpdates,
|
||||
newQuestions
|
||||
},
|
||||
options: {
|
||||
deletedIds: optionDeletes,
|
||||
updates: optionUpdates,
|
||||
creates: optionCreates
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates new questions and their options in batch
|
||||
*/
|
||||
export async function createNewQuestionsWithOptions(
|
||||
exerciseId: string,
|
||||
newQuestions: NonNullable<TExerciseUpdate['questions']>,
|
||||
txClient: DbOrTxClient
|
||||
): Promise<void> {
|
||||
const createdQuestions = await createQuestions(
|
||||
newQuestions.map((q) => ({
|
||||
exerciseId,
|
||||
title: q.question,
|
||||
questionTypeId: q.questionTypeId || 1,
|
||||
points: q.points || 0,
|
||||
order: typeof q.order === 'number' ? q.order : undefined,
|
||||
settings: normalizeSettings(q.settings)
|
||||
})),
|
||||
txClient
|
||||
);
|
||||
|
||||
const newOptions: TNewOption[] = [];
|
||||
createdQuestions.forEach((newQuestion, index) => {
|
||||
const questionData = newQuestions[index];
|
||||
if (newQuestion && questionData?.options && questionData.options.length > 0) {
|
||||
// Only include non-deleted options for new questions
|
||||
for (const opt of questionData.options) {
|
||||
if (!opt.deletedAt) {
|
||||
newOptions.push({
|
||||
questionId: newQuestion.id,
|
||||
label: opt.label,
|
||||
isCorrect: opt.isCorrect,
|
||||
settings: normalizeSettings(opt.settings)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (newOptions.length > 0) {
|
||||
await createOptions(newOptions, txClient);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches questions and their options for an exercise
|
||||
*/
|
||||
export async function fetchQuestionsAndOptions(exerciseId: string, dbClient?: DbOrTxClient) {
|
||||
const questions = await getQuestionsByExerciseIds([exerciseId], dbClient);
|
||||
const questionIds = questions.map((q) => q.id).filter((id): id is number => id !== undefined);
|
||||
const options = questionIds.length > 0 ? await getOptionsByQuestionIds(questionIds, dbClient) : [];
|
||||
return { questions, options };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches question types and creates a lookup map
|
||||
*/
|
||||
export async function fetchQuestionTypesMap(
|
||||
questions: TNewQuestion[],
|
||||
dbClient?: DbOrTxClient
|
||||
): Promise<Map<number, TQuestionType>> {
|
||||
const questionTypeIds = [
|
||||
...new Set(questions.map((q) => q.questionTypeId).filter((id): id is number => id !== undefined))
|
||||
];
|
||||
const questionTypes: TQuestionType[] =
|
||||
questionTypeIds.length > 0 ? await getQuestionTypesByIds(questionTypeIds, dbClient) : [];
|
||||
return new Map(questionTypes.map((qt) => [qt.id, qt]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a single question with its options to frontend format
|
||||
*/
|
||||
export function transformQuestion(
|
||||
question: TNewQuestion,
|
||||
options: TNewOption[],
|
||||
questionTypeMap: Map<number, TQuestionType>
|
||||
): QuestionWithRelations {
|
||||
const questionType = questionTypeMap.get(question.questionTypeId);
|
||||
const questionTypeId = question.questionTypeId;
|
||||
const questionOptions = options
|
||||
.filter((opt) => opt.questionId === question.id)
|
||||
.map((opt) => ({
|
||||
id: opt.id!,
|
||||
label: opt.label ?? null,
|
||||
value: opt.value ?? null,
|
||||
isCorrect: opt.isCorrect ?? false,
|
||||
settings: normalizeSettings(opt.settings)
|
||||
}));
|
||||
|
||||
return {
|
||||
id: question.id!,
|
||||
value: question.title || '', // value field defaults to title
|
||||
name: question.name || '',
|
||||
title: question.title,
|
||||
type: questionTypeId, // type field (same as questionTypeId)
|
||||
points: question.points || 0,
|
||||
order: question.order || 0,
|
||||
questionType: questionType
|
||||
? {
|
||||
id: questionType.id,
|
||||
label: questionType.label
|
||||
}
|
||||
: {
|
||||
id: questionTypeId,
|
||||
label: ''
|
||||
},
|
||||
questionTypeId: questionTypeId,
|
||||
settings: normalizeSettings(question.settings),
|
||||
createdAt: question.createdAt || undefined,
|
||||
updatedAt: question.updatedAt || undefined,
|
||||
options: questionOptions
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms all questions to frontend format
|
||||
*/
|
||||
export function transformQuestions(
|
||||
questions: TNewQuestion[],
|
||||
options: TNewOption[],
|
||||
questionTypeMap: Map<number, TQuestionType>
|
||||
): QuestionWithRelations[] {
|
||||
return questions.map((question) => transformQuestion(question, options, questionTypeMap));
|
||||
}
|
||||
@@ -1,4 +1,12 @@
|
||||
export * from './account';
|
||||
export * from './assets';
|
||||
export * from './attendance';
|
||||
export * from './exercise';
|
||||
export * from './lesson';
|
||||
export * from './mark';
|
||||
export * from './media';
|
||||
export * from './newsfeed';
|
||||
export * from './onboarding';
|
||||
export * from './submission';
|
||||
export * from './dash';
|
||||
export * from './course/course';
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type { TLessonLanguage, TLocale, TNewLessonLanguage } from '@db/types';
|
||||
import {
|
||||
getLessonLanguageByLessonIdAndLocale,
|
||||
getLessonLanguagesByLessonId,
|
||||
updateLessonLanguage,
|
||||
upsertLessonLanguage
|
||||
} from '@cio/db/queries/lesson/language';
|
||||
|
||||
import { getLessonById } from '@cio/db/queries/lesson/lesson';
|
||||
|
||||
/**
|
||||
* Gets all language translations for a lesson
|
||||
* @param lessonId - The lesson ID
|
||||
* @returns Array of lesson languages
|
||||
*/
|
||||
export async function listLessonLanguages(lessonId: string): Promise<TLessonLanguage[]> {
|
||||
try {
|
||||
const languages = await getLessonLanguagesByLessonId(lessonId);
|
||||
return languages;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch lesson languages',
|
||||
ErrorCodes.LESSON_LANGUAGE_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a single lesson language by locale
|
||||
* @param lessonId - The lesson ID
|
||||
* @param locale - The locale
|
||||
* @returns Lesson language or null if not found
|
||||
*/
|
||||
export async function getLessonLanguage(lessonId: string, locale: TLocale): Promise<TLessonLanguage | null> {
|
||||
try {
|
||||
const language = await getLessonLanguageByLessonIdAndLocale(lessonId, locale);
|
||||
return language;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch lesson language',
|
||||
ErrorCodes.LESSON_LANGUAGE_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or updates a lesson language translation
|
||||
* @param lessonId - The lesson ID
|
||||
* @param data - Lesson language data
|
||||
* @returns Created or updated lesson language
|
||||
*/
|
||||
export async function upsertLessonLanguageService(
|
||||
lessonId: string,
|
||||
data: Omit<TNewLessonLanguage, 'lessonId'>
|
||||
): Promise<TLessonLanguage> {
|
||||
try {
|
||||
// Verify lesson exists
|
||||
const lesson = await getLessonById(lessonId);
|
||||
if (!lesson) {
|
||||
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const language = await upsertLessonLanguage({
|
||||
...data,
|
||||
lessonId
|
||||
});
|
||||
|
||||
return language;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create or update lesson language',
|
||||
ErrorCodes.LESSON_LANGUAGE_CREATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a lesson language translation
|
||||
* @param lessonId - The lesson ID
|
||||
* @param locale - The locale
|
||||
* @param data - Lesson language update data
|
||||
* @returns Updated lesson language
|
||||
*/
|
||||
export async function updateLessonLanguageService(
|
||||
lessonId: string,
|
||||
locale: TLocale,
|
||||
data: Partial<TNewLessonLanguage>
|
||||
): Promise<TLessonLanguage> {
|
||||
try {
|
||||
// Verify lesson exists
|
||||
const lesson = await getLessonById(lessonId);
|
||||
if (!lesson) {
|
||||
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const existing = await getLessonLanguageByLessonIdAndLocale(lessonId, locale);
|
||||
if (!existing) {
|
||||
throw new AppError('Lesson language not found', ErrorCodes.LESSON_LANGUAGE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const language = await updateLessonLanguage(lessonId, locale, data);
|
||||
return language;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update lesson language',
|
||||
ErrorCodes.LESSON_LANGUAGE_UPDATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './lesson';
|
||||
@@ -0,0 +1,362 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type { TLesson, TNewLessonComment, TNewLessonCompletion } from '@cio/db/types';
|
||||
import type { TLessonCreate, TLessonReorder, TLessonUpdate } from '@cio/utils/validation/lesson';
|
||||
import {
|
||||
createLessonComment,
|
||||
createLessons,
|
||||
deleteLesson,
|
||||
deleteLessonComment,
|
||||
getLessonById,
|
||||
getLessonCommentsByLessonId,
|
||||
getLessonCommentsByLessonIdPaginated,
|
||||
getLessonCompletion,
|
||||
getLessonVersionHistory,
|
||||
getLessonsByCourseId,
|
||||
updateLesson,
|
||||
updateLessonComment,
|
||||
upsertLessonCompletion,
|
||||
type LessonById
|
||||
} from '@cio/db/queries/lesson';
|
||||
import { enrichLessonWithPresignedUrls } from '@api/utils/lesson-media';
|
||||
|
||||
/**
|
||||
* Creates a new lesson
|
||||
* @param courseId Course ID
|
||||
* @param data Lesson creation data
|
||||
* @returns Created lesson
|
||||
*/
|
||||
export async function createLesson(courseId: string, data: TLessonCreate): Promise<TLesson> {
|
||||
try {
|
||||
const lessonData = {
|
||||
...data,
|
||||
courseId
|
||||
};
|
||||
|
||||
const [lesson] = await createLessons([lessonData]);
|
||||
if (!lesson) {
|
||||
throw new AppError('Failed to create lesson', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
return lesson;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create lesson',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a lesson by ID
|
||||
* @param lessonId Lesson ID
|
||||
* @returns Lesson or throws error if not found
|
||||
*/
|
||||
export async function getLesson(lessonId: string): Promise<LessonById> {
|
||||
try {
|
||||
const lesson = await getLessonById(lessonId);
|
||||
if (!lesson) {
|
||||
throw new AppError('Lesson not found', ErrorCodes.LESSON_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return enrichLessonWithPresignedUrls(lesson);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Log error with context for debugging
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to fetch lesson';
|
||||
console.error(`Error fetching lesson ${lessonId}:`, errorMessage, error);
|
||||
|
||||
throw new AppError(errorMessage, ErrorCodes.LESSON_FETCH_FAILED, 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a lesson
|
||||
* @param lessonId Lesson ID
|
||||
* @param data Partial lesson update data
|
||||
* @returns Updated lesson
|
||||
*/
|
||||
export async function updateLessonService(lessonId: string, data: TLessonUpdate): Promise<TLesson> {
|
||||
try {
|
||||
const updated = await updateLesson(lessonId, data);
|
||||
if (!updated) {
|
||||
throw new AppError('Failed to update lesson', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update lesson',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a lesson
|
||||
* @param lessonId Lesson ID
|
||||
* @returns Deleted lesson
|
||||
*/
|
||||
export async function deleteLessonService(lessonId: string): Promise<TLesson> {
|
||||
try {
|
||||
const deleted = await deleteLesson(lessonId);
|
||||
if (!deleted) {
|
||||
throw new AppError('Failed to delete lesson', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete lesson',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists lessons for a course
|
||||
* @param courseId Course ID
|
||||
* @param sectionId Optional section ID filter
|
||||
* @returns Array of lessons
|
||||
*/
|
||||
export async function listLessons(courseId: string, sectionId?: string): Promise<TLesson[]> {
|
||||
try {
|
||||
const lessons = await getLessonsByCourseId(courseId);
|
||||
|
||||
if (sectionId) {
|
||||
return lessons.filter((lesson) => lesson.sectionId === sectionId);
|
||||
}
|
||||
|
||||
return lessons;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list lessons',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reorders lessons
|
||||
* @param lessons Array of lesson IDs, orders, and optional sectionIds
|
||||
* @returns Updated lessons
|
||||
*/
|
||||
export async function reorderLessons(lessons: TLessonReorder['lessons']): Promise<TLesson[]> {
|
||||
try {
|
||||
// Update each lesson's order and optionally sectionId
|
||||
const updatePromises = lessons.map(({ id, order, sectionId }) =>
|
||||
updateLesson(id, { order, ...(sectionId !== undefined && { sectionId }) })
|
||||
);
|
||||
|
||||
const updated = await Promise.all(updatePromises);
|
||||
return updated.filter((l): l is TLesson => l !== null);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to reorder lessons',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Lesson Comment Services
|
||||
|
||||
/**
|
||||
* Gets comments for a lesson
|
||||
* @param lessonId Lesson ID
|
||||
* @returns Array of comments
|
||||
*/
|
||||
export async function getLessonComments(lessonId: string) {
|
||||
try {
|
||||
return getLessonCommentsByLessonId(lessonId);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to get lesson comments',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets paginated comments for a lesson
|
||||
* @param lessonId Lesson ID
|
||||
* @param options Pagination options (cursor, limit)
|
||||
* @returns Paginated comments with metadata
|
||||
*/
|
||||
export async function getLessonCommentsPaginated(lessonId: string, options: { cursor?: string; limit: number }) {
|
||||
try {
|
||||
return getLessonCommentsByLessonIdPaginated(lessonId, options);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to get paginated lesson comments',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a lesson comment
|
||||
* @param lessonId Lesson ID
|
||||
* @param groupMemberId Group member ID (author)
|
||||
* @param comment Comment text
|
||||
* @returns Created comment
|
||||
*/
|
||||
export async function createLessonCommentService(lessonId: string, groupMemberId: string, comment: string) {
|
||||
try {
|
||||
const commentData: TNewLessonComment = {
|
||||
lessonId,
|
||||
groupmemberId: groupMemberId,
|
||||
comment
|
||||
};
|
||||
|
||||
return await createLessonComment(commentData);
|
||||
} catch (error) {
|
||||
console.log('error', error);
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create lesson comment',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a lesson comment
|
||||
* @param commentId Comment ID
|
||||
* @param comment Updated comment text
|
||||
* @returns Updated comment
|
||||
*/
|
||||
export async function updateLessonCommentService(commentId: number, comment: string) {
|
||||
try {
|
||||
const updated = await updateLessonComment(commentId, comment);
|
||||
if (!updated) {
|
||||
throw new AppError('Comment not found', ErrorCodes.LESSON_COMMENT_UPDATE_FAILED, 404);
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update lesson comment',
|
||||
ErrorCodes.LESSON_COMMENT_UPDATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a lesson comment
|
||||
* @param commentId Comment ID
|
||||
* @returns Deleted comment
|
||||
*/
|
||||
export async function deleteLessonCommentService(commentId: number) {
|
||||
try {
|
||||
const deleted = await deleteLessonComment(commentId);
|
||||
if (!deleted) {
|
||||
throw new AppError('Comment not found', ErrorCodes.COMMENT_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete lesson comment',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Lesson Completion Services
|
||||
|
||||
/**
|
||||
* Gets lesson completion status
|
||||
* @param lessonId Lesson ID
|
||||
* @param profileId Profile ID
|
||||
* @returns Completion record or null
|
||||
*/
|
||||
export async function getLessonCompletionService(lessonId: string, profileId: string) {
|
||||
try {
|
||||
return await getLessonCompletion(lessonId, profileId);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to get lesson completion',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or updates lesson completion
|
||||
* @param lessonId Lesson ID
|
||||
* @param profileId Profile ID
|
||||
* @param isComplete Completion status
|
||||
* @returns Completion record
|
||||
*/
|
||||
export async function upsertLessonCompletionService(lessonId: string, profileId: string, isComplete: boolean) {
|
||||
try {
|
||||
const completionData: TNewLessonCompletion = {
|
||||
lessonId,
|
||||
profileId,
|
||||
isComplete
|
||||
};
|
||||
|
||||
return await upsertLessonCompletion(completionData);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update lesson completion',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets lesson version history for a lesson and locale
|
||||
* @param lessonId Lesson ID
|
||||
* @param locale Locale
|
||||
* @param endRange End range for pagination (0-indexed, inclusive)
|
||||
* @returns Array of lesson version history entries
|
||||
*/
|
||||
export async function getLessonHistoryService(lessonId: string, locale: string, endRange: number) {
|
||||
try {
|
||||
return getLessonVersionHistory(lessonId, locale, endRange);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to get lesson history',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { env } from '@api/config/env';
|
||||
import { LICENSE_FEATURE, type LicenseFeatureId } from '@cio/utils/license';
|
||||
|
||||
export type LicenseStatus = {
|
||||
valid: boolean;
|
||||
features: string[];
|
||||
expiresAt?: string;
|
||||
};
|
||||
|
||||
const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
|
||||
let cachedStatus: LicenseStatus | null = null;
|
||||
let cacheExpiry = 0;
|
||||
|
||||
/** All available license features for non-self-hosted (cloud/SaaS) instances */
|
||||
const ALL_FEATURES = Object.values(LICENSE_FEATURE);
|
||||
|
||||
/** Check if running in self-hosted mode */
|
||||
function isSelfHosted(): boolean {
|
||||
return env.PUBLIC_IS_SELFHOSTED === 'true';
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the external license verification API.
|
||||
* or body: { licenseKey: string }.
|
||||
* Expected response: { valid: boolean, features?: string[], expiresAt?: string }
|
||||
*/
|
||||
async function fetchLicenseFromApi(): Promise<LicenseStatus> {
|
||||
const url = 'https://enterprise-api.classroomio.dev';
|
||||
const key = env.LICENSE_KEY?.trim();
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ licenseKey: key })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('License API error:', response.status, await response.text());
|
||||
return { valid: false, features: [] };
|
||||
}
|
||||
|
||||
const data = (await response.json()) as { valid?: boolean; features?: string[]; expiresAt?: string };
|
||||
return {
|
||||
valid: !!data.valid,
|
||||
features: Array.isArray(data.features) ? data.features : [],
|
||||
expiresAt: typeof data.expiresAt === 'string' ? data.expiresAt : undefined
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('License verification failed:', error);
|
||||
return { valid: false, features: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current license status. Uses in-memory cache (1 hour TTL).
|
||||
* For non-self-hosted (cloud/SaaS), returns all features as valid.
|
||||
*/
|
||||
export async function getLicenseStatus(): Promise<LicenseStatus> {
|
||||
const now = Date.now();
|
||||
if (cachedStatus !== null && now < cacheExpiry) {
|
||||
return cachedStatus;
|
||||
}
|
||||
|
||||
// Cloud/SaaS has no license restrictions - all features enabled
|
||||
if (!isSelfHosted()) {
|
||||
const status: LicenseStatus = { valid: true, features: ALL_FEATURES };
|
||||
cachedStatus = status;
|
||||
cacheExpiry = now + CACHE_TTL_MS;
|
||||
return status;
|
||||
}
|
||||
|
||||
const status = await fetchLicenseFromApi();
|
||||
cachedStatus = status;
|
||||
cacheExpiry = now + CACHE_TTL_MS;
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a specific feature is licensed.
|
||||
* @param feature - Feature ID from LICENSE_FEATURE
|
||||
* Non-self-hosted (cloud/SaaS) instances have all features enabled.
|
||||
*/
|
||||
export async function isFeatureLicensed(feature: LicenseFeatureId | string): Promise<boolean> {
|
||||
// Cloud/SaaS has no license restrictions
|
||||
if (!isSelfHosted()) {
|
||||
return true;
|
||||
}
|
||||
const status = await getLicenseStatus();
|
||||
if (!status.valid) return false;
|
||||
return status.features.includes(feature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given feature is licensed. Synchronous version using cached status.
|
||||
* Returns false if cache is cold (first call will populate async).
|
||||
* Use getLicenseStatus() or isFeatureLicensed() for accurate checks.
|
||||
* Non-self-hosted (cloud/SaaS) instances have all features enabled.
|
||||
*/
|
||||
export function isFeatureLicensedSync(feature: LicenseFeatureId | string): boolean {
|
||||
// Cloud/SaaS has no license restrictions
|
||||
if (!isSelfHosted()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (cachedStatus === null || !cachedStatus.valid) return false;
|
||||
|
||||
return cachedStatus.features.includes(feature);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { ContentType, ROLE } from '@cio/utils/constants';
|
||||
import { getMarksByCourseId, type Mark } from '@cio/db/queries/mark';
|
||||
import { getCourseMembers } from '@cio/db/queries/course/people';
|
||||
import { getCourseWithRelations } from '@cio/db/queries/course';
|
||||
import { buildCourseContent, type CourseContentItem } from '@api/services/course/utils';
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
|
||||
export type GradebookExercise = {
|
||||
id: string;
|
||||
title: string;
|
||||
points: number;
|
||||
};
|
||||
|
||||
export type GradebookStudentMarks = Record<string, Record<string, string>>;
|
||||
|
||||
export type GradebookResponse = {
|
||||
students: Awaited<ReturnType<typeof getCourseMembers>>;
|
||||
exercises: GradebookExercise[];
|
||||
studentMarksByExerciseId: GradebookStudentMarks;
|
||||
};
|
||||
|
||||
function buildStudentMarksByExerciseId(marks: Mark[]): GradebookStudentMarks {
|
||||
const result: GradebookStudentMarks = {};
|
||||
for (const mark of marks) {
|
||||
const { groupmemberId, exerciseId, totalPointsGotten } = mark;
|
||||
if (!groupmemberId || !exerciseId) continue;
|
||||
if (!result[groupmemberId]) result[groupmemberId] = {};
|
||||
result[groupmemberId][exerciseId] = totalPointsGotten?.toString() ?? '0';
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function buildExercises(marks: Mark[], contentItems: CourseContentItem[]): GradebookExercise[] {
|
||||
const marksByExerciseId = new Map<string, { title: string; points: number }>();
|
||||
const exerciseOrder: string[] = [];
|
||||
for (const mark of marks) {
|
||||
const { exerciseId, exerciseTitle, exercisePoints } = mark;
|
||||
if (!exerciseId) continue;
|
||||
if (!marksByExerciseId.has(exerciseId)) {
|
||||
exerciseOrder.push(exerciseId);
|
||||
marksByExerciseId.set(exerciseId, {
|
||||
title: exerciseTitle ?? '',
|
||||
points: exercisePoints ?? 0
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const exerciseItems = contentItems.filter((item) => item.type === ContentType.Exercise);
|
||||
if (exerciseItems.length > 0) {
|
||||
return exerciseItems.map((item) => {
|
||||
const fromMarks = marksByExerciseId.get(item.id);
|
||||
return {
|
||||
id: item.id,
|
||||
title: item.title ?? fromMarks?.title ?? '',
|
||||
points: fromMarks?.points ?? 0
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
return exerciseOrder.map((id) => {
|
||||
const fromMarks = marksByExerciseId.get(id)!;
|
||||
return {
|
||||
id,
|
||||
title: fromMarks?.title ?? '',
|
||||
points: fromMarks?.points ?? 0
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all data needed to render the marks gradebook: students, exercises in order, and marks per student per exercise.
|
||||
*/
|
||||
export async function getGradebook(courseId: string): Promise<GradebookResponse> {
|
||||
try {
|
||||
const [marks, members, course] = await Promise.all([
|
||||
getMarksByCourseId(courseId),
|
||||
getCourseMembers(courseId),
|
||||
getCourseWithRelations(courseId)
|
||||
]);
|
||||
|
||||
const students = members.filter((m) => Number(m.roleId) === ROLE.STUDENT);
|
||||
|
||||
let contentItems: CourseContentItem[] = [];
|
||||
if (course?.contentItems != null) {
|
||||
const isGrouping = course.metadata?.isContentGroupingEnabled ?? true;
|
||||
const content = buildCourseContent(course.contentItems, isGrouping);
|
||||
contentItems = content.grouped ? (content.sections ?? []).flatMap((s) => s.items ?? []) : (content.items ?? []);
|
||||
}
|
||||
|
||||
const exercises = buildExercises(marks, contentItems);
|
||||
const studentMarksByExerciseId = buildStudentMarksByExerciseId(marks);
|
||||
|
||||
return {
|
||||
students,
|
||||
exercises,
|
||||
studentMarksByExerciseId
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('getGradebook error:', error);
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to get gradebook',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './mark';
|
||||
@@ -0,0 +1,16 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import { getMarksByCourseId } from '@cio/db/queries/mark';
|
||||
|
||||
/**
|
||||
* Gets marks for a course
|
||||
* Marks are computed from submissions and exercises using a database function
|
||||
* @param courseId Course ID
|
||||
* @returns Array of mark records
|
||||
*/
|
||||
export async function getMarks(courseId: string) {
|
||||
try {
|
||||
return await getMarksByCourseId(courseId);
|
||||
} catch (error) {
|
||||
throw new AppError(error instanceof Error ? error.message : 'Failed to get marks', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,26 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import { BUCKET_NAME, MAX_IMAGE_SIZE } from '@api/constants/upload';
|
||||
import { MAX_IMAGE_SIZE } from '@api/constants/upload';
|
||||
|
||||
import { ALLOWED_IMAGE_TYPES } from '@cio/utils/validation';
|
||||
import { env } from '@api/config/env';
|
||||
import { getStorageConfig } from '@api/config/storage';
|
||||
import { generateFileKey } from '@api/utils/upload';
|
||||
import { uploadToS3 } from '@api/utils/s3';
|
||||
|
||||
/**
|
||||
* Uploads an image file to S3 and returns the public URL
|
||||
* Uploads an image file to object storage and returns the public URL
|
||||
* @param file - The image file to upload
|
||||
* @returns Object containing the public URL and file key
|
||||
*/
|
||||
export async function uploadImage(file: File) {
|
||||
if (!env.CLOUDFLARE_IMAGE_BUCKET_DOMAIN) {
|
||||
throw new AppError(new Error('Image bucket domain not configured'), ErrorCodes.INTERNAL_ERROR, 500);
|
||||
const config = getStorageConfig();
|
||||
if (!config.mediaPublicBaseUrl) {
|
||||
throw new AppError(
|
||||
new Error(
|
||||
'Media public URL not configured. Set OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL or CLOUDFLARE_IMAGE_BUCKET_DOMAIN.'
|
||||
),
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
|
||||
// Validate file type
|
||||
@@ -41,9 +48,9 @@ export async function uploadImage(file: File) {
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
// Upload to S3
|
||||
// Upload to object storage
|
||||
const uploadResult = await uploadToS3({
|
||||
Bucket: BUCKET_NAME.MEDIA,
|
||||
Bucket: config.bucketMedia,
|
||||
Key: fileKey,
|
||||
Body: buffer,
|
||||
ContentType: file.type,
|
||||
@@ -55,7 +62,8 @@ export async function uploadImage(file: File) {
|
||||
}
|
||||
|
||||
// Construct public URL
|
||||
const publicUrl = `${env.CLOUDFLARE_IMAGE_BUCKET_DOMAIN}/${fileKey}`;
|
||||
const baseUrl = config.mediaPublicBaseUrl.replace(/\/$/, '');
|
||||
const publicUrl = `${baseUrl}/${fileKey}`;
|
||||
|
||||
return {
|
||||
url: publicUrl,
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export * from './newsfeed';
|
||||
@@ -0,0 +1,413 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type { TCourseNewsfeed, TNewCourseNewsfeed, TNewCourseNewsfeedComment } from '@cio/db/types';
|
||||
import type { TNewsfeedCreate, TNewsfeedUpdate } from '@cio/utils/validation/newsfeed';
|
||||
import {
|
||||
createNewsfeed,
|
||||
createNewsfeedComment,
|
||||
deleteNewsfeed,
|
||||
deleteNewsfeedComment,
|
||||
getNewsfeedByCourseId,
|
||||
getNewsfeedByCourseIdPaginated,
|
||||
getNewsfeedById,
|
||||
getNewsfeedCommentsByFeedId,
|
||||
getNewsfeedCommentsByFeedIdPaginated,
|
||||
getNewsfeedForEmail,
|
||||
updateNewsfeed,
|
||||
updateNewsfeedComment
|
||||
} from '@cio/db/queries/newsfeed';
|
||||
|
||||
import { env } from '@api/config/env';
|
||||
import { buildEmailFromName, sendEmail } from '@cio/email';
|
||||
|
||||
/**
|
||||
* Lists newsfeed items for a course
|
||||
* @param courseId Course ID
|
||||
* @returns Array of newsfeed items
|
||||
*/
|
||||
export async function listNewsfeed(courseId: string): Promise<TCourseNewsfeed[]> {
|
||||
try {
|
||||
return await getNewsfeedByCourseId(courseId);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list newsfeed',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists paginated newsfeed items for a course
|
||||
* @param courseId Course ID
|
||||
* @param options Pagination options (cursor, limit)
|
||||
* @returns Paginated newsfeed items with metadata and author profile
|
||||
*/
|
||||
export async function listNewsfeedPaginated(courseId: string, options: { cursor?: string; limit: number }) {
|
||||
try {
|
||||
return getNewsfeedByCourseIdPaginated(courseId, options);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list paginated newsfeed',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a newsfeed item by ID
|
||||
* @param feedId Newsfeed ID
|
||||
* @returns Newsfeed item
|
||||
*/
|
||||
export async function getNewsfeedItem(feedId: string): Promise<TCourseNewsfeed> {
|
||||
try {
|
||||
const feed = await getNewsfeedById(feedId);
|
||||
if (!feed) {
|
||||
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
|
||||
}
|
||||
|
||||
return feed;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch newsfeed item',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new newsfeed item
|
||||
* @param courseId Course ID
|
||||
* @param authorId Group member ID (author)
|
||||
* @param data Newsfeed creation data
|
||||
* @returns Created newsfeed item
|
||||
*/
|
||||
export async function createNewsfeedService(
|
||||
courseId: string,
|
||||
authorId: string,
|
||||
data: TNewsfeedCreate
|
||||
): Promise<TCourseNewsfeed> {
|
||||
try {
|
||||
const newsfeedData: TNewCourseNewsfeed = {
|
||||
courseId,
|
||||
authorId,
|
||||
content: data.content,
|
||||
isPinned: data.isPinned || false
|
||||
};
|
||||
|
||||
const feed = await createNewsfeed(newsfeedData);
|
||||
|
||||
// Send email notifications to course members (async, don't wait)
|
||||
sendNewsfeedPostEmail(feed.id, authorId).catch((error) => {
|
||||
console.error('Failed to send newsfeed post email:', error);
|
||||
});
|
||||
|
||||
return feed;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create newsfeed',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a newsfeed item (content and isPinned only)
|
||||
* @param feedId Newsfeed ID
|
||||
* @param data Partial newsfeed update data
|
||||
* @returns Updated newsfeed item
|
||||
*/
|
||||
export async function updateNewsfeedService(feedId: string, data: TNewsfeedUpdate): Promise<TCourseNewsfeed> {
|
||||
try {
|
||||
const updated = await updateNewsfeed(feedId, data);
|
||||
if (!updated) {
|
||||
// If no row was updated, it usually means the feed doesn't exist.
|
||||
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update newsfeed',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a newsfeed item's reaction
|
||||
* @param feedId Newsfeed ID
|
||||
* @param reaction Reaction data
|
||||
* @returns Updated newsfeed item
|
||||
*/
|
||||
export async function updateNewsfeedReactionService(
|
||||
feedId: string,
|
||||
reaction: TCourseNewsfeed['reaction']
|
||||
): Promise<TCourseNewsfeed> {
|
||||
try {
|
||||
const updated = await updateNewsfeed(feedId, { reaction });
|
||||
if (!updated) {
|
||||
// If no row was updated, it usually means the feed doesn't exist.
|
||||
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update newsfeed reaction',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a newsfeed item
|
||||
* @param feedId Newsfeed ID
|
||||
* @returns Deleted newsfeed item
|
||||
*/
|
||||
export async function deleteNewsfeedService(feedId: string): Promise<TCourseNewsfeed> {
|
||||
try {
|
||||
const deleted = await deleteNewsfeed(feedId);
|
||||
if (!deleted) {
|
||||
// If no row was deleted, it usually means the feed doesn't exist.
|
||||
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete newsfeed',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets comments for a newsfeed item
|
||||
* @param feedId Newsfeed ID
|
||||
* @returns Array of comments
|
||||
*/
|
||||
export async function getNewsfeedComments(feedId: string) {
|
||||
try {
|
||||
return await getNewsfeedCommentsByFeedId(feedId);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to get newsfeed comments',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets paginated comments for a newsfeed item
|
||||
* @param feedId Newsfeed ID
|
||||
* @param options Pagination options (cursor, limit)
|
||||
* @returns Paginated comments with metadata
|
||||
*/
|
||||
export async function getNewsfeedCommentsService(feedId: string, options: { cursor?: string; limit: number }) {
|
||||
try {
|
||||
const feed = await getNewsfeedById(feedId);
|
||||
if (!feed) {
|
||||
throw new AppError('Newsfeed item not found', ErrorCodes.INTERNAL_ERROR, 404);
|
||||
}
|
||||
|
||||
return await getNewsfeedCommentsByFeedIdPaginated(feedId, options);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to get paginated newsfeed comments',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a newsfeed comment
|
||||
* @param feedId Newsfeed ID
|
||||
* @param authorId Group member ID (author)
|
||||
* @param content Comment content
|
||||
* @returns Created comment
|
||||
*/
|
||||
export async function createNewsfeedCommentService(feedId: string, authorId: string, content: string) {
|
||||
try {
|
||||
const commentData: TNewCourseNewsfeedComment = {
|
||||
courseNewsfeedId: feedId,
|
||||
authorId,
|
||||
content
|
||||
};
|
||||
|
||||
const comment = await createNewsfeedComment(commentData);
|
||||
|
||||
// Send email notification to feed author (async, don't wait)
|
||||
sendNewsfeedCommentEmail(feedId, content).catch((error) => {
|
||||
console.error('Failed to send newsfeed comment email:', error);
|
||||
});
|
||||
|
||||
return comment;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create newsfeed comment',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a newsfeed comment
|
||||
* @param commentId Comment ID
|
||||
* @param content Updated comment content
|
||||
* @returns Updated comment
|
||||
*/
|
||||
export async function updateNewsfeedCommentService(commentId: number, content: string) {
|
||||
try {
|
||||
const updated = await updateNewsfeedComment(commentId, content);
|
||||
if (!updated) {
|
||||
throw new AppError('Comment not found', ErrorCodes.NEWSFEED_COMMENT_UPDATE_FAILED, 404);
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update newsfeed comment',
|
||||
ErrorCodes.NEWSFEED_COMMENT_UPDATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a newsfeed comment
|
||||
* @param commentId Comment ID
|
||||
* @returns Deleted comment
|
||||
*/
|
||||
export async function deleteNewsfeedCommentService(commentId: number) {
|
||||
try {
|
||||
const deleted = await deleteNewsfeedComment(commentId);
|
||||
if (!deleted) {
|
||||
throw new AppError('Comment not found', ErrorCodes.COMMENT_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete newsfeed comment',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends email notification when a new feed is created
|
||||
* Sends to all course members except the author
|
||||
*/
|
||||
async function sendNewsfeedPostEmail(feedId: string, authorId: string) {
|
||||
try {
|
||||
const feedData = await getNewsfeedForEmail(feedId, authorId);
|
||||
if (!feedData || !feedData.courseId || !feedData.courseTitle || !feedData.organization?.siteName) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (feedData.courseMembers.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const orgName = feedData.organization?.name || 'ClassroomIO';
|
||||
const orgSiteName = feedData.organization?.siteName || 'app';
|
||||
const postLink = `https://${orgSiteName}.classroomio.com/courses/${feedData.courseId}?feedId=${feedData.feedId}`;
|
||||
|
||||
// Send email to all course members
|
||||
const emailPromises = feedData.courseMembers.map((member) => {
|
||||
if (!member.email) return Promise.resolve();
|
||||
|
||||
return sendEmail('newsfeedPost', {
|
||||
to: member.email,
|
||||
fields: {
|
||||
courseTitle: feedData.courseTitle!,
|
||||
teacherName: feedData.author?.fullname || 'A teacher',
|
||||
content: feedData.content || '',
|
||||
postLink,
|
||||
orgName
|
||||
},
|
||||
from: buildEmailFromName(`${orgName} - ClassroomIO`),
|
||||
replyTo: feedData.author?.email || '[email protected]'
|
||||
});
|
||||
});
|
||||
|
||||
await Promise.all(emailPromises);
|
||||
} catch (error) {
|
||||
console.error('Error sending newsfeed post email:', error);
|
||||
// Don't throw - email failures shouldn't break the API
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends email notification when a comment is added to a feed
|
||||
* Sends to the feed author (teacher)
|
||||
*/
|
||||
async function sendNewsfeedCommentEmail(feedId: string, commentContent: string) {
|
||||
try {
|
||||
const feedData = await getNewsfeedForEmail(feedId);
|
||||
if (!feedData || !feedData.courseId || !feedData.courseTitle || !feedData.organization?.siteName) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!feedData.author?.email) {
|
||||
return;
|
||||
}
|
||||
|
||||
const orgName = feedData.organization?.name || 'ClassroomIO';
|
||||
const orgSiteName = feedData.organization?.siteName || 'app';
|
||||
const postLink = `https://${orgSiteName}.classroomio.com/courses/${feedData.courseId}?feedId=${feedData.feedId}`;
|
||||
|
||||
await sendEmail('newsfeedComment', {
|
||||
to: feedData.author.email,
|
||||
fields: {
|
||||
courseTitle: feedData.courseTitle,
|
||||
comment: commentContent,
|
||||
postLink,
|
||||
orgName
|
||||
},
|
||||
from: buildEmailFromName(`${orgName} - ClassroomIO`),
|
||||
replyTo: '[email protected]'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error sending newsfeed comment email:', error);
|
||||
// Don't throw - email failures shouldn't break the API
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,12 @@ import {
|
||||
checkSiteNameExists,
|
||||
createOrganization,
|
||||
createOrganizationMember,
|
||||
getOrganizationByProfileId
|
||||
getOrganizationByProfileId,
|
||||
getOrganizationCount
|
||||
} from '@cio/db/queries';
|
||||
import { getProfileById, updateProfile } from '@cio/db/queries/auth';
|
||||
|
||||
import { env } from '@api/config/env';
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
import { db } from '@cio/db/drizzle';
|
||||
import { sendEmail } from '@cio/email';
|
||||
@@ -20,6 +22,14 @@ export async function createOrganizationWithOwner(
|
||||
siteName: string;
|
||||
}
|
||||
) {
|
||||
// Self-hosted: block org creation when an org already exists
|
||||
if (env.PUBLIC_IS_SELFHOSTED === 'true') {
|
||||
const count = await getOrganizationCount();
|
||||
if (count > 0) {
|
||||
throw new AppError('Self-hosted instances support only one organization', ErrorCodes.VALIDATION_ERROR, 403);
|
||||
}
|
||||
}
|
||||
|
||||
// Business Logic: Check sitename availability
|
||||
const exists = await checkSiteNameExists(input.siteName);
|
||||
if (exists) {
|
||||
@@ -56,10 +66,10 @@ export async function createOrganizationWithOwner(
|
||||
} catch (error) {
|
||||
console.error('Error creating organization:', error);
|
||||
// Handle database constraint violations
|
||||
if (error.code === '23505') {
|
||||
if (error && typeof error === 'object' && 'code' in error && error.code === '23505') {
|
||||
throw new AppError(`Site name '${input.siteName}' already exists`, ErrorCodes.SITENAME_EXISTS, 409);
|
||||
}
|
||||
throw new AppError(error, ErrorCodes.ORG_CREATE_FAILED, 500);
|
||||
throw new AppError(error instanceof Error ? error : new Error('Unknown error'), ErrorCodes.ORG_CREATE_FAILED, 500);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,11 +86,15 @@ export async function updateUserOnboarding(userId: string, data: Partial<TProfil
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(error, ErrorCodes.PROFILE_UPDATE_FAILED, 500);
|
||||
throw new AppError(
|
||||
error instanceof Error ? error : new Error('Unknown error'),
|
||||
ErrorCodes.PROFILE_UPDATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function completeOnboarding(user: Partial<TUser>) {
|
||||
export async function completeOnboarding(user: Partial<TUser> & { id: string; email: string }) {
|
||||
try {
|
||||
const profile = await getProfileById(user.id);
|
||||
if (!profile) {
|
||||
@@ -94,6 +108,9 @@ export async function completeOnboarding(user: Partial<TUser>) {
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
throw new AppError(error, ErrorCodes.INTERNAL_ERROR, 500);
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(error instanceof Error ? error : new Error('Unknown error'), ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// Code from https://github.com/vercel/platforms/blob/1ed55b13bcae97b037c69ec40b4c32df21c2412c/lib/domains.ts
|
||||
|
||||
import { env } from '@api/config/env';
|
||||
|
||||
export const addDomainToVercel = async (domain: string) => {
|
||||
return await fetch(
|
||||
`https://api.vercel.com/v10/projects/${env.PROJECT_ID_VERCEL}/domains${
|
||||
env.TEAM_ID_VERCEL ? `?teamId=${env.TEAM_ID_VERCEL}` : ''
|
||||
}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${env.AUTH_BEARER_TOKEN}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: domain
|
||||
})
|
||||
}
|
||||
).then((res) => res.json());
|
||||
};
|
||||
|
||||
export const removeDomainFromVercelProject = async (domain: string) => {
|
||||
return await fetch(
|
||||
`https://api.vercel.com/v9/projects/${env.PROJECT_ID_VERCEL}/domains/${domain}${
|
||||
env.TEAM_ID_VERCEL ? `?teamId=${env.TEAM_ID_VERCEL}` : ''
|
||||
}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${env.AUTH_BEARER_TOKEN}`
|
||||
},
|
||||
method: 'DELETE'
|
||||
}
|
||||
).then((res) => res.json());
|
||||
};
|
||||
|
||||
export const getConfigResponse = async (domain: string) => {
|
||||
return await fetch(
|
||||
`https://api.vercel.com/v6/domains/${domain}/config${env.TEAM_ID_VERCEL ? `?teamId=${env.TEAM_ID_VERCEL}` : ''}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${env.AUTH_BEARER_TOKEN}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}
|
||||
).then((res) => res.json());
|
||||
};
|
||||
@@ -2,29 +2,36 @@ import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type { TNewOrganizationPlan, TOrganization, TOrganizationPlan, TPlan } from '@db/types';
|
||||
import {
|
||||
cancelOrganizationPlan,
|
||||
checkEmailsExistInOrg,
|
||||
createOrganizationMembers,
|
||||
createOrganizationPlan,
|
||||
deleteOrganizationMember,
|
||||
getOrgIdBySiteName,
|
||||
getFirstOrganizationWithPlans,
|
||||
getOrganizationAudience,
|
||||
getOrganizationById,
|
||||
getOrganizationBySiteName,
|
||||
getOrganizationTeam,
|
||||
getOrganizations,
|
||||
revokeActiveOrganizationInvitesByEmails,
|
||||
updateOrganization,
|
||||
updateOrganizationPlan
|
||||
} from '@cio/db/queries/organization';
|
||||
import { getCourseIdsByTagSlugs, getCourseTagsByCourseIdsForOrganization } from '@cio/db/queries/tag';
|
||||
import {
|
||||
getCoursesById,
|
||||
getCoursesBySiteName,
|
||||
getCoursesBySiteNameForSetup,
|
||||
getEnrolledCourses,
|
||||
getExercisesBySiteName,
|
||||
getLessonsBySiteName
|
||||
getExploreCourses,
|
||||
getLessonsBySiteName,
|
||||
getOrgCourses,
|
||||
getPublishedCoursesBySiteName
|
||||
} from '@cio/db/queries/course';
|
||||
import { getLastLogin, getProfileCourseProgress, getUserExercisesStats } from '@cio/db/queries/analytics';
|
||||
|
||||
import type { OrganizationWithPlans } from '@cio/db/queries/organization/types';
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
import { createOrganizationWithOwner } from '@api/services/onboarding';
|
||||
import { env } from '@api/config/env';
|
||||
import { sendEmail } from '@cio/email';
|
||||
import { getProfileById } from '@cio/db/queries/auth';
|
||||
import { inviteTeamMembers as inviteTeamMembersSecure } from './organization/invite';
|
||||
|
||||
/**
|
||||
* Creates a new organization with the current user as owner
|
||||
@@ -62,7 +69,7 @@ export async function getOrganizationsWithFilters(filters?: {
|
||||
siteName?: string;
|
||||
customDomain?: string;
|
||||
isCustomDomainVerified?: boolean;
|
||||
}) {
|
||||
}): Promise<OrganizationWithPlans[]> {
|
||||
try {
|
||||
const organizations = await getOrganizations(filters);
|
||||
return organizations;
|
||||
@@ -75,6 +82,19 @@ export async function getOrganizationsWithFilters(filters?: {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the first organization with plans - for self-hosted single-org mode
|
||||
* @returns First organization or null
|
||||
*/
|
||||
export async function getFirstOrgForSelfHosted(): Promise<OrganizationWithPlans | null> {
|
||||
try {
|
||||
return await getFirstOrganizationWithPlans();
|
||||
} catch (error) {
|
||||
console.error('getFirstOrgForSelfHosted error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets organization team members (non-students)
|
||||
* @param orgId - The organization ID
|
||||
@@ -112,15 +132,100 @@ export async function getOrgAudience(orgId: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets courses by organization siteName
|
||||
* @param siteName - The organization site name
|
||||
* @returns Array of courses
|
||||
* Gets public courses for an organization (landing page)
|
||||
* @param siteName - The organization siteName
|
||||
* @returns Array of published courses with lesson counts
|
||||
*/
|
||||
export async function getCoursesByOrgSiteName(siteName: string) {
|
||||
export async function getPublicCourses(siteName: string, tagSlugs?: string[]) {
|
||||
try {
|
||||
const courses = await getCoursesBySiteName(siteName);
|
||||
return courses;
|
||||
const orgResult = await getOrgIdBySiteName(siteName);
|
||||
const org = orgResult[0];
|
||||
|
||||
if (!org) {
|
||||
throw new AppError('Organization not found', ErrorCodes.ORG_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
let filteredCourseIds: string[] | undefined = undefined;
|
||||
if (tagSlugs && tagSlugs.length > 0) {
|
||||
filteredCourseIds = await getCourseIdsByTagSlugs(org.id, tagSlugs);
|
||||
if (filteredCourseIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const courses = await getPublishedCoursesBySiteName(siteName, filteredCourseIds);
|
||||
const tagsByCourseId = await getCourseTagsByCourseIdsForOrganization(
|
||||
org.id,
|
||||
courses.map((course) => course.id)
|
||||
);
|
||||
|
||||
return courses.map((course) => ({
|
||||
...course,
|
||||
tags: tagsByCourseId[course.id] ?? []
|
||||
}));
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) throw error;
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch public courses',
|
||||
ErrorCodes.COURSES_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets organization courses with role-based data filtering
|
||||
* @param orgId - The organization ID
|
||||
* @param userId - User ID for role-based filtering (required)
|
||||
* @param userRole - User's role in the organization (from context)
|
||||
* @returns Object with role and courses array
|
||||
* - Admins: all courses with totalStudents
|
||||
* - Tutors: assigned courses with totalStudents
|
||||
*/
|
||||
export async function getOrganizationCourses(orgId: string, userId: string, userRole: number, tagSlugs?: string[]) {
|
||||
try {
|
||||
if (!userRole) {
|
||||
throw new AppError('Invalid permissions', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
|
||||
let filteredCourseIds: string[] | undefined = undefined;
|
||||
if (tagSlugs && tagSlugs.length > 0) {
|
||||
filteredCourseIds = await getCourseIdsByTagSlugs(orgId, tagSlugs);
|
||||
if (filteredCourseIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
switch (userRole) {
|
||||
case ROLE.ADMIN: {
|
||||
const courses = await getOrgCourses({ orgId, courseIds: filteredCourseIds });
|
||||
const tagsByCourseId = await getCourseTagsByCourseIdsForOrganization(
|
||||
orgId,
|
||||
courses.map((course) => course.id)
|
||||
);
|
||||
|
||||
return courses.map((course) => ({
|
||||
...course,
|
||||
tags: tagsByCourseId[course.id] ?? []
|
||||
}));
|
||||
}
|
||||
case ROLE.TUTOR: {
|
||||
const courses = await getOrgCourses({ orgId, profileId: userId, courseIds: filteredCourseIds });
|
||||
const tagsByCourseId = await getCourseTagsByCourseIdsForOrganization(
|
||||
orgId,
|
||||
courses.map((course) => course.id)
|
||||
);
|
||||
|
||||
return courses.map((course) => ({
|
||||
...course,
|
||||
tags: tagsByCourseId[course.id] ?? []
|
||||
}));
|
||||
}
|
||||
default:
|
||||
throw new AppError('Invalid permissions', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) throw error;
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch courses',
|
||||
ErrorCodes.COURSES_FETCH_FAILED,
|
||||
@@ -129,6 +234,47 @@ export async function getCoursesByOrgSiteName(siteName: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets user enrolled courses by organization orgId
|
||||
*
|
||||
* @param orgId - The organization ID
|
||||
* @param userId - User ID for filtering
|
||||
* @returns Array of enrolled courses
|
||||
*/
|
||||
export async function getUserEnrolledCourses(orgId: string, userId: string) {
|
||||
try {
|
||||
return getEnrolledCourses({ orgId, profileId: userId });
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) throw error;
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch enrolled courses',
|
||||
ErrorCodes.COURSES_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets recommended courses (published courses user isn't enrolled in) for an organization
|
||||
* Used in LMS explore page
|
||||
*
|
||||
* @param orgId - The organization ID
|
||||
* @param userId - User ID to exclude enrolled courses
|
||||
* @returns Array of recommended courses
|
||||
*/
|
||||
export async function getRecommendedCourses(orgId: string, userId: string) {
|
||||
try {
|
||||
return getExploreCourses({ orgId, profileId: userId });
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) throw error;
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch recommended courses',
|
||||
ErrorCodes.COURSES_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets courses by organization orgId
|
||||
* @param orgId - The organization orgId
|
||||
@@ -293,65 +439,12 @@ export async function cancelOrgPlan(subscriptionId: string, payload: TOrganizati
|
||||
* @param roleId - Role ID to assign (ADMIN or TUTOR)
|
||||
* @returns Array of created members
|
||||
*/
|
||||
export async function inviteTeamMembers(orgId: string, emails: string[], roleId: number) {
|
||||
const organization = await getOrganizationById(orgId);
|
||||
if (!organization) {
|
||||
throw new AppError('Organization not found', ErrorCodes.ORGANIZATION_NOT_FOUND, 404);
|
||||
export async function inviteTeamMembers(orgId: string, emails: string[], roleId: number, invitedByProfileId?: string) {
|
||||
if (!invitedByProfileId) {
|
||||
throw new AppError('Inviter profile ID is required', ErrorCodes.VALIDATION_ERROR, 400, 'invitedByProfileId');
|
||||
}
|
||||
|
||||
const normalizedEmails = [...new Set(emails.map((email) => email.toLowerCase().trim()))];
|
||||
|
||||
const existingEmails = await checkEmailsExistInOrg(orgId, normalizedEmails);
|
||||
const emailsToInvite = normalizedEmails.filter((email) => !existingEmails.includes(email));
|
||||
|
||||
if (emailsToInvite.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const members = await createOrganizationMembers(
|
||||
emailsToInvite.map((email) => ({
|
||||
organizationId: orgId,
|
||||
email,
|
||||
roleId,
|
||||
verified: false
|
||||
}))
|
||||
);
|
||||
|
||||
const baseUrl = env.NODE_ENV === 'development' ? 'http://localhost:5173' : 'https://app.classroomio.com';
|
||||
|
||||
for (const email of emailsToInvite) {
|
||||
try {
|
||||
const inviteData = JSON.stringify({
|
||||
email,
|
||||
orgId: organization.id,
|
||||
orgSiteName: organization.siteName
|
||||
});
|
||||
const inviteLink = `${baseUrl}/invite/t/${encodeURIComponent(btoa(inviteData))}`;
|
||||
|
||||
await sendEmail('inviteTeacher', {
|
||||
to: email,
|
||||
fields: {
|
||||
email,
|
||||
orgName: organization.name,
|
||||
orgSiteName: organization.siteName,
|
||||
inviteLink
|
||||
}
|
||||
});
|
||||
} catch (emailError) {
|
||||
console.error(`Failed to send invite email to ${email}:`, emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return members;
|
||||
} catch (error) {
|
||||
console.error('Error inviting team members:', error);
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to invite team members',
|
||||
ErrorCodes.ORG_TEAM_INVITE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
return inviteTeamMembersSecure(orgId, emails, roleId, invitedByProfileId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -360,13 +453,17 @@ export async function inviteTeamMembers(orgId: string, emails: string[], roleId:
|
||||
* @param memberId - The member ID to remove
|
||||
* @returns Deleted member
|
||||
*/
|
||||
export async function removeTeamMember(orgId: string, memberId: number) {
|
||||
export async function removeTeamMember(orgId: string, memberId: number, removedByProfileId?: string) {
|
||||
try {
|
||||
const deleted = await deleteOrganizationMember(orgId, memberId);
|
||||
if (!deleted) {
|
||||
throw new AppError('Team member not found', ErrorCodes.ORG_TEAM_REMOVE_FAILED, 404);
|
||||
}
|
||||
|
||||
if (deleted.email && removedByProfileId) {
|
||||
await revokeActiveOrganizationInvitesByEmails(orgId, [deleted.email.toLowerCase()], removedByProfileId);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
@@ -379,3 +476,98 @@ export async function removeTeamMember(orgId: string, memberId: number) {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to sum array object values by key
|
||||
*/
|
||||
function sumArrObject<T>(arr: T[], key: keyof T): number {
|
||||
return arr.reduce((sum, item) => sum + ((item[key] as number) || 0), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to calculate percentage with rounding
|
||||
*/
|
||||
function calcPercentageWithRounding(a: number, b: number): number {
|
||||
if (b === 0) {
|
||||
return 0;
|
||||
}
|
||||
const rawPercentage = (a / b) * 100;
|
||||
const fixedString = rawPercentage.toFixed(1);
|
||||
const roundedNumber = parseFloat(fixedString);
|
||||
return isNaN(roundedNumber) ? 0 : roundedNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets user analytics for an organization
|
||||
* @param userId - The user ID (profile ID)
|
||||
* @param orgId - The organization ID
|
||||
* @returns User analytics data including courses, progress, and grades
|
||||
*/
|
||||
export async function getUserAnalytics(userId: string, orgId: string) {
|
||||
try {
|
||||
// Get user profile
|
||||
const profile = await getProfileById(userId);
|
||||
if (!profile) {
|
||||
throw new AppError('User profile not found', ErrorCodes.PROFILE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
// Get last login
|
||||
const lastSeen = await getLastLogin(userId);
|
||||
|
||||
// Get courses for this org where user is enrolled
|
||||
const courses = await getEnrolledCourses({ orgId, profileId: userId });
|
||||
|
||||
// Build analytics data for each course
|
||||
const coursesWithStats = await Promise.all(
|
||||
courses.map(async (course) => {
|
||||
const [userExercisesStats, courseProgress] = await Promise.all([
|
||||
getUserExercisesStats(course.id, userId),
|
||||
getProfileCourseProgress(course.id, userId)
|
||||
]);
|
||||
|
||||
const totalEarnedPoints = sumArrObject(userExercisesStats, 'score');
|
||||
const totalPoints = sumArrObject(userExercisesStats, 'totalPoints');
|
||||
const averageGrade = calcPercentageWithRounding(totalEarnedPoints, totalPoints);
|
||||
const lessonsCompleted = courseProgress.lessons_completed || 0;
|
||||
const lessonsCount = courseProgress.lessons_count || 0;
|
||||
|
||||
return {
|
||||
...course,
|
||||
...courseProgress,
|
||||
progress_percentage: calcPercentageWithRounding(lessonsCompleted, lessonsCount),
|
||||
average_grade: averageGrade
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// Calculate overall stats
|
||||
const totalLessons = coursesWithStats.reduce((acc, course) => acc + (course.lessons_count || 0), 0);
|
||||
const completedLessons = coursesWithStats.reduce((acc, course) => acc + (course.lessons_completed || 0), 0);
|
||||
const overallCourseProgress = calcPercentageWithRounding(completedLessons, totalLessons);
|
||||
|
||||
const allGrades = sumArrObject(coursesWithStats, 'average_grade');
|
||||
const overallAverageGrade = calcPercentageWithRounding(allGrades, coursesWithStats.length);
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: userId,
|
||||
fullName: profile.fullname || '',
|
||||
email: profile.email || '',
|
||||
avatarUrl: profile.avatarUrl || '',
|
||||
lastSeen: lastSeen || undefined
|
||||
},
|
||||
courses: coursesWithStats,
|
||||
overallCourseProgress,
|
||||
overallAverageGrade
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch user analytics',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import { and, eq, isNull } from 'drizzle-orm';
|
||||
import {
|
||||
checkEmailsExistInOrg,
|
||||
createOrganizationMembers,
|
||||
createOrganizationInvite,
|
||||
createOrganizationInviteAudit,
|
||||
getOrganizationById,
|
||||
getOrganizationInviteByTokenHash,
|
||||
revokeActiveOrganizationInvitesByEmails
|
||||
} from '@cio/db/queries/organization';
|
||||
import { db } from '@cio/db/drizzle';
|
||||
import { env } from '@api/config/env';
|
||||
import { sendEmail } from '@cio/email';
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
import * as schema from '@cio/db/schema';
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
type OrganizationInviteStatus = 'ACTIVE' | 'EXPIRED' | 'REVOKED' | 'ACCEPTED';
|
||||
|
||||
const ORG_INVITE_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
interface TInviteRequestContext {
|
||||
ipAddress?: string | null;
|
||||
userAgent?: string | null;
|
||||
}
|
||||
|
||||
interface TAuthUser {
|
||||
id: string;
|
||||
email?: string | null;
|
||||
}
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return crypto.createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
function generateToken(): string {
|
||||
return crypto.randomBytes(32).toString('base64url');
|
||||
}
|
||||
|
||||
function normalizeEmails(emails: string[]): string[] {
|
||||
return [...new Set(emails.map((email) => email.toLowerCase().trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
function getAppBaseUrl(): string {
|
||||
return env.NODE_ENV === 'development' ? 'http://localhost:5173' : 'https://app.classroomio.com';
|
||||
}
|
||||
|
||||
function buildInviteLink(token: string): string {
|
||||
return `${getAppBaseUrl()}/invite/t/${encodeURIComponent(token)}`;
|
||||
}
|
||||
|
||||
function getRoleLabel(roleId: number): string {
|
||||
if (roleId === ROLE.ADMIN) return 'Admin';
|
||||
if (roleId === ROLE.TUTOR) return 'Tutor';
|
||||
return `Role ${roleId}`;
|
||||
}
|
||||
|
||||
function getInviteStatus(invite: {
|
||||
isRevoked: boolean;
|
||||
expiresAt: string;
|
||||
acceptedAt: string | null;
|
||||
}): OrganizationInviteStatus {
|
||||
if (invite.isRevoked) {
|
||||
return 'REVOKED';
|
||||
}
|
||||
|
||||
if (invite.acceptedAt) {
|
||||
return 'ACCEPTED';
|
||||
}
|
||||
|
||||
if (new Date(invite.expiresAt).getTime() <= Date.now()) {
|
||||
return 'EXPIRED';
|
||||
}
|
||||
|
||||
return 'ACTIVE';
|
||||
}
|
||||
|
||||
function getExpiryLabel(expiresAtIso: string): string {
|
||||
return new Date(expiresAtIso).toLocaleString('en-US', {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
timeZone: 'UTC'
|
||||
});
|
||||
}
|
||||
|
||||
async function recordOrganizationInviteAudit(
|
||||
inviteId: string,
|
||||
organizationId: string,
|
||||
eventType: (typeof schema.organizationInviteEventType.enumValues)[number],
|
||||
context: {
|
||||
actorProfileId?: string | null;
|
||||
targetEmail?: string | null;
|
||||
ipAddress?: string | null;
|
||||
userAgent?: string | null;
|
||||
metadata?: Record<string, unknown>;
|
||||
} = {}
|
||||
) {
|
||||
await createOrganizationInviteAudit({
|
||||
inviteId,
|
||||
organizationId,
|
||||
eventType,
|
||||
actorProfileId: context.actorProfileId ?? null,
|
||||
targetEmail: context.targetEmail ?? null,
|
||||
ipAddress: context.ipAddress ?? null,
|
||||
userAgent: context.userAgent ?? null,
|
||||
metadata: context.metadata ?? {}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates secure organization role invites from org settings.
|
||||
* Invites are role-aware and tokenized; legacy payload links are not used.
|
||||
*/
|
||||
export async function inviteTeamMembers(orgId: string, emails: string[], roleId: number, invitedByProfileId: string) {
|
||||
if (roleId !== ROLE.ADMIN && roleId !== ROLE.TUTOR) {
|
||||
throw new AppError('Invalid organization role for invite', ErrorCodes.VALIDATION_ERROR, 400, 'roleId');
|
||||
}
|
||||
|
||||
const organization = await getOrganizationById(orgId);
|
||||
if (!organization || !organization.siteName) {
|
||||
throw new AppError('Organization not found', ErrorCodes.ORGANIZATION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const normalizedEmails = normalizeEmails(emails);
|
||||
const existingEmails = await checkEmailsExistInOrg(orgId, normalizedEmails);
|
||||
const emailsToInvite = normalizedEmails.filter((email) => !existingEmails.includes(email));
|
||||
|
||||
if (emailsToInvite.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const members = await createOrganizationMembers(
|
||||
emailsToInvite.map((email) => ({
|
||||
organizationId: orgId,
|
||||
email,
|
||||
roleId,
|
||||
verified: false
|
||||
}))
|
||||
);
|
||||
|
||||
const revokedInvites = await revokeActiveOrganizationInvitesByEmails(orgId, emailsToInvite, invitedByProfileId);
|
||||
await Promise.all(
|
||||
revokedInvites.map((invite) =>
|
||||
recordOrganizationInviteAudit(invite.id, orgId, 'REVOKED', {
|
||||
actorProfileId: invitedByProfileId,
|
||||
targetEmail: invite.email,
|
||||
metadata: { reason: 'superseded_by_new_invite' }
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const expiresAt = new Date(Date.now() + ORG_INVITE_EXPIRY_MS).toISOString();
|
||||
const roleName = getRoleLabel(roleId);
|
||||
|
||||
for (const email of emailsToInvite) {
|
||||
try {
|
||||
const token = generateToken();
|
||||
const tokenHash = hashToken(token);
|
||||
|
||||
const invite = await createOrganizationInvite({
|
||||
organizationId: orgId,
|
||||
roleId,
|
||||
email,
|
||||
tokenHash,
|
||||
createdByProfileId: invitedByProfileId,
|
||||
expiresAt,
|
||||
isRevoked: false,
|
||||
metadata: {
|
||||
source: 'ORG_SETTINGS_TEAM_INVITE'
|
||||
}
|
||||
});
|
||||
|
||||
await recordOrganizationInviteAudit(invite.id, orgId, 'CREATED', {
|
||||
actorProfileId: invitedByProfileId,
|
||||
targetEmail: email,
|
||||
metadata: {
|
||||
roleId,
|
||||
roleName,
|
||||
expiresAt
|
||||
}
|
||||
});
|
||||
|
||||
const inviteLink = buildInviteLink(token);
|
||||
|
||||
try {
|
||||
const responses = await sendEmail('inviteTeacher', {
|
||||
to: email,
|
||||
fields: {
|
||||
email,
|
||||
orgName: organization.name,
|
||||
orgSiteName: organization.siteName,
|
||||
roleName,
|
||||
expiresAt: getExpiryLabel(expiresAt),
|
||||
inviteLink
|
||||
}
|
||||
});
|
||||
|
||||
const allSuccessful = responses.every((response) => response.success);
|
||||
if (!allSuccessful) {
|
||||
const message = responses
|
||||
.filter((response) => !response.success)
|
||||
.map((response) => response.error || 'Unknown email error')
|
||||
.join('; ');
|
||||
|
||||
await recordOrganizationInviteAudit(invite.id, orgId, 'EMAIL_FAILED', {
|
||||
actorProfileId: invitedByProfileId,
|
||||
targetEmail: email,
|
||||
metadata: { error: message }
|
||||
});
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
await recordOrganizationInviteAudit(invite.id, orgId, 'EMAIL_SENT', {
|
||||
actorProfileId: invitedByProfileId,
|
||||
targetEmail: email
|
||||
});
|
||||
} catch (emailError) {
|
||||
const message = emailError instanceof Error ? emailError.message : 'Unknown email error';
|
||||
|
||||
await recordOrganizationInviteAudit(invite.id, orgId, 'EMAIL_FAILED', {
|
||||
actorProfileId: invitedByProfileId,
|
||||
targetEmail: email,
|
||||
metadata: { error: message }
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to create org invite for ${email}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return members;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-only invite preview by token (API-key protected at route layer).
|
||||
*/
|
||||
export async function previewOrganizationInvite(token: string, context: TInviteRequestContext = {}) {
|
||||
const tokenHash = hashToken(token);
|
||||
const data = await getOrganizationInviteByTokenHash(tokenHash);
|
||||
|
||||
if (!data) {
|
||||
throw new AppError('Invalid invite link', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
await recordOrganizationInviteAudit(data.invite.id, data.invite.organizationId, 'PREVIEWED', {
|
||||
targetEmail: data.invite.email,
|
||||
ipAddress: context.ipAddress,
|
||||
userAgent: context.userAgent
|
||||
});
|
||||
|
||||
return {
|
||||
invite: {
|
||||
id: data.invite.id,
|
||||
roleId: data.invite.roleId,
|
||||
roleLabel: getRoleLabel(data.invite.roleId),
|
||||
email: data.invite.email,
|
||||
expiresAt: data.invite.expiresAt,
|
||||
status: getInviteStatus(data.invite)
|
||||
},
|
||||
organization: data.organization
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticated acceptance for organization role invites.
|
||||
*/
|
||||
export async function acceptOrganizationInvite(token: string, user: TAuthUser, context: TInviteRequestContext = {}) {
|
||||
if (!user.id || !user.email) {
|
||||
throw new AppError('Authenticated user email is required', ErrorCodes.UNAUTHORIZED, 401);
|
||||
}
|
||||
|
||||
const normalizedEmail = user.email.toLowerCase().trim();
|
||||
const tokenHash = hashToken(token);
|
||||
|
||||
const result = await db.transaction(async (tx) => {
|
||||
const [row] = await tx
|
||||
.select({
|
||||
invite: schema.organizationInvite,
|
||||
organization: {
|
||||
id: schema.organization.id,
|
||||
name: schema.organization.name,
|
||||
siteName: schema.organization.siteName
|
||||
}
|
||||
})
|
||||
.from(schema.organizationInvite)
|
||||
.innerJoin(schema.organization, eq(schema.organizationInvite.organizationId, schema.organization.id))
|
||||
.where(eq(schema.organizationInvite.tokenHash, tokenHash))
|
||||
.limit(1);
|
||||
|
||||
if (!row) {
|
||||
throw new AppError('Invalid invite link', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const status = getInviteStatus(row.invite);
|
||||
if (status === 'REVOKED') {
|
||||
throw new AppError('This invite has been revoked', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
if (status === 'EXPIRED') {
|
||||
throw new AppError('This invite has expired', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
if (row.invite.email.toLowerCase().trim() !== normalizedEmail) {
|
||||
throw new AppError('This invite is for a different email address', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
|
||||
if (status === 'ACCEPTED') {
|
||||
return {
|
||||
organization: row.organization,
|
||||
roleId: row.invite.roleId,
|
||||
alreadyAccepted: true
|
||||
};
|
||||
}
|
||||
|
||||
const [orgMemberByEmail] = await tx
|
||||
.select()
|
||||
.from(schema.organizationmember)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.organizationmember.organizationId, row.invite.organizationId),
|
||||
eq(schema.organizationmember.email, normalizedEmail)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (orgMemberByEmail) {
|
||||
if (orgMemberByEmail.profileId && orgMemberByEmail.profileId !== user.id) {
|
||||
throw new AppError('This invite is linked to another account', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(schema.organizationmember)
|
||||
.set({
|
||||
profileId: user.id,
|
||||
roleId: row.invite.roleId,
|
||||
email: normalizedEmail,
|
||||
verified: true
|
||||
})
|
||||
.where(eq(schema.organizationmember.id, orgMemberByEmail.id));
|
||||
} else {
|
||||
const [orgMemberByProfile] = await tx
|
||||
.select()
|
||||
.from(schema.organizationmember)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.organizationmember.organizationId, row.invite.organizationId),
|
||||
eq(schema.organizationmember.profileId, user.id)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (orgMemberByProfile) {
|
||||
await tx
|
||||
.update(schema.organizationmember)
|
||||
.set({
|
||||
roleId: row.invite.roleId,
|
||||
email: normalizedEmail,
|
||||
verified: true
|
||||
})
|
||||
.where(eq(schema.organizationmember.id, orgMemberByProfile.id));
|
||||
} else {
|
||||
await tx.insert(schema.organizationmember).values({
|
||||
organizationId: row.invite.organizationId,
|
||||
roleId: row.invite.roleId,
|
||||
profileId: user.id,
|
||||
email: normalizedEmail,
|
||||
verified: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const [acceptedInvite] = await tx
|
||||
.update(schema.organizationInvite)
|
||||
.set({
|
||||
acceptedAt: new Date().toISOString(),
|
||||
acceptedByProfileId: user.id,
|
||||
updatedAt: new Date().toISOString()
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(schema.organizationInvite.id, row.invite.id),
|
||||
eq(schema.organizationInvite.isRevoked, false),
|
||||
isNull(schema.organizationInvite.acceptedAt)
|
||||
)
|
||||
)
|
||||
.returning({
|
||||
id: schema.organizationInvite.id
|
||||
});
|
||||
|
||||
if (!acceptedInvite) {
|
||||
throw new AppError('Invite is no longer available', ErrorCodes.VALIDATION_ERROR, 409);
|
||||
}
|
||||
|
||||
return {
|
||||
organization: row.organization,
|
||||
roleId: row.invite.roleId,
|
||||
alreadyAccepted: false
|
||||
};
|
||||
});
|
||||
|
||||
const siteName = result.organization.siteName || '';
|
||||
|
||||
const invite = await getOrganizationInviteByTokenHash(tokenHash);
|
||||
if (invite) {
|
||||
await recordOrganizationInviteAudit(invite.invite.id, invite.invite.organizationId, 'ACCEPTED', {
|
||||
actorProfileId: user.id,
|
||||
targetEmail: normalizedEmail,
|
||||
ipAddress: context.ipAddress,
|
||||
userAgent: context.userAgent,
|
||||
metadata: { alreadyAccepted: result.alreadyAccepted }
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
organizationId: result.organization.id,
|
||||
roleId: result.roleId,
|
||||
alreadyAccepted: result.alreadyAccepted,
|
||||
redirectTo: siteName ? `/org/${siteName}` : '/org'
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type {
|
||||
TCreateSsoConnection,
|
||||
TUpdateSsoConnection,
|
||||
TUpdateSsoPolicy
|
||||
} from '@cio/utils/validation/organization/sso';
|
||||
import {
|
||||
createOrganizationAuthPolicy,
|
||||
createOrganizationSsoConfig,
|
||||
deleteOrganizationSsoConfig,
|
||||
getOrganizationAuthPolicy,
|
||||
getOrganizationSsoConfig,
|
||||
updateOrganizationAuthPolicy,
|
||||
updateOrganizationSsoConfig
|
||||
} from '@cio/db/queries/organization/sso';
|
||||
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
import { db } from '@cio/db/drizzle';
|
||||
import { getOrganizationPlanStatus } from '@cio/db/queries/organization/organization';
|
||||
|
||||
// Check if organization has Enterprise plan
|
||||
async function assertEnterprisePlan(orgId: string): Promise<void> {
|
||||
const plans = await getOrganizationPlanStatus(orgId);
|
||||
const hasEnterprise = plans.some(
|
||||
(p: { planName: string | null; isActive: boolean | null }) => p.planName === 'ENTERPRISE' && p.isActive
|
||||
);
|
||||
|
||||
if (!hasEnterprise) {
|
||||
throw new AppError('SSO requires Enterprise plan', ErrorCodes.UPGRADE_REQUIRED, 403);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a unique provider ID for Better Auth
|
||||
function generateProviderId(orgId: string, provider: string): string {
|
||||
return `org-${orgId.slice(0, 8)}-${provider.toLowerCase()}`;
|
||||
}
|
||||
|
||||
function getSsoRegistrationErrorMessage(error: unknown, issuer?: string): string {
|
||||
const base = 'Failed to register SSO provider. Please check your OIDC configuration.';
|
||||
const err = error as {
|
||||
body?: { message?: string; code?: string };
|
||||
message?: string;
|
||||
} | null;
|
||||
const code = err?.body?.code;
|
||||
|
||||
if (code === 'discovery_not_found' && issuer) {
|
||||
const discoveryUrl = `${issuer.replace(/\/$/, '')}/.well-known/openid-configuration`;
|
||||
return `${base} Discovery endpoint not found. Check that the Issuer URL is correct and supports OIDC (e.g. https://accounts.google.com for Google). Expected: ${discoveryUrl}`;
|
||||
}
|
||||
|
||||
return base;
|
||||
}
|
||||
|
||||
// Create SSO connection
|
||||
export async function createSsoConnection(
|
||||
orgId: string,
|
||||
data: TCreateSsoConnection,
|
||||
createdByProfileId: string,
|
||||
authApi: { registerSSOProvider: (args: unknown) => Promise<unknown> },
|
||||
requestHeaders?: Headers
|
||||
) {
|
||||
// Check Enterprise plan
|
||||
await assertEnterprisePlan(orgId);
|
||||
|
||||
// Check if org already has SSO config
|
||||
const existing = await getOrganizationSsoConfig(orgId);
|
||||
if (existing) {
|
||||
throw new AppError('Organization already has an SSO connection', ErrorCodes.CONFLICT, 409);
|
||||
}
|
||||
|
||||
const providerId = generateProviderId(orgId, data.provider);
|
||||
|
||||
return db.transaction(async () => {
|
||||
// Register with Better Auth (requires session cookies via headers)
|
||||
try {
|
||||
await authApi.registerSSOProvider({
|
||||
body: {
|
||||
providerId,
|
||||
issuer: data.issuer,
|
||||
domain: data.domain,
|
||||
oidcConfig: {
|
||||
clientId: data.clientId,
|
||||
clientSecret: data.clientSecret,
|
||||
scopes: data.scopes.split(' '),
|
||||
mapping: {
|
||||
id: 'sub',
|
||||
email: 'email',
|
||||
emailVerified: 'email_verified',
|
||||
name: 'name',
|
||||
image: 'picture'
|
||||
}
|
||||
}
|
||||
},
|
||||
...(requestHeaders && { headers: requestHeaders })
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to register SSO provider with Better Auth:', error);
|
||||
throw new AppError(getSsoRegistrationErrorMessage(error, data.issuer), ErrorCodes.SSO_REGISTRATION_FAILED, 400);
|
||||
}
|
||||
|
||||
// Create our config record
|
||||
const config = await createOrganizationSsoConfig({
|
||||
organizationId: orgId,
|
||||
betterAuthProviderId: providerId,
|
||||
provider: data.provider,
|
||||
displayName: data.displayName,
|
||||
domain: data.domain.toLowerCase(),
|
||||
isActive: false, // Requires activation after testing
|
||||
createdByProfileId
|
||||
});
|
||||
|
||||
// Create default policy
|
||||
await createOrganizationAuthPolicy({
|
||||
organizationId: orgId,
|
||||
forceSso: false,
|
||||
autoJoinSsoDomains: false,
|
||||
breakGlassEnabled: true,
|
||||
defaultRoleId: ROLE.STUDENT,
|
||||
roleMapping: {}
|
||||
});
|
||||
|
||||
return config;
|
||||
});
|
||||
}
|
||||
|
||||
// Get SSO connection
|
||||
export async function getSsoConnection(orgId: string) {
|
||||
const config = await getOrganizationSsoConfig(orgId);
|
||||
if (!config) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const policy = await getOrganizationAuthPolicy(orgId);
|
||||
|
||||
return {
|
||||
config,
|
||||
policy
|
||||
};
|
||||
}
|
||||
|
||||
// Update SSO connection
|
||||
export async function updateSsoConnection(orgId: string, data: TUpdateSsoConnection, updatedByProfileId: string) {
|
||||
const config = await getOrganizationSsoConfig(orgId);
|
||||
if (!config) {
|
||||
throw new AppError('SSO connection not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
// Note: OIDC config updates (clientId, issuer, etc.) would require
|
||||
// updating Better Auth's stored provider. For now, we only allow
|
||||
// updating our metadata (displayName, isActive).
|
||||
|
||||
const updated = await updateOrganizationSsoConfig(orgId, {
|
||||
...data,
|
||||
updatedByProfileId
|
||||
});
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
// Update SSO policy
|
||||
export async function updateSsoPolicy(orgId: string, data: TUpdateSsoPolicy) {
|
||||
const config = await getOrganizationSsoConfig(orgId);
|
||||
if (!config) {
|
||||
throw new AppError('SSO connection required before updating policy', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
// Validate: forceSso requires active connection
|
||||
if (data.forceSso === true && !config.isActive) {
|
||||
throw new AppError('Cannot enable Force SSO without an active connection', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
let policy = await getOrganizationAuthPolicy(orgId);
|
||||
|
||||
if (policy) {
|
||||
policy = await updateOrganizationAuthPolicy(orgId, data);
|
||||
} else {
|
||||
policy = await createOrganizationAuthPolicy({
|
||||
organizationId: orgId,
|
||||
forceSso: data.forceSso ?? false,
|
||||
autoJoinSsoDomains: data.autoJoinSsoDomains ?? false,
|
||||
breakGlassEnabled: data.breakGlassEnabled ?? true,
|
||||
defaultRoleId: data.defaultRoleId ?? ROLE.STUDENT,
|
||||
roleMapping: data.roleMapping ?? {}
|
||||
});
|
||||
}
|
||||
|
||||
return policy;
|
||||
}
|
||||
|
||||
// Delete SSO connection
|
||||
export async function deleteSsoConnection(
|
||||
orgId: string,
|
||||
authApi: { deleteSSOProvider: (args: unknown) => Promise<unknown> }
|
||||
) {
|
||||
const config = await getOrganizationSsoConfig(orgId);
|
||||
if (!config) {
|
||||
throw new AppError('SSO connection not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return db.transaction(async () => {
|
||||
// Delete from Better Auth
|
||||
try {
|
||||
await authApi.deleteSSOProvider({
|
||||
body: { providerId: config.betterAuthProviderId }
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to delete SSO provider from Better Auth:', error);
|
||||
// Continue to delete our record even if Better Auth fails
|
||||
}
|
||||
|
||||
// Delete our records
|
||||
await deleteOrganizationSsoConfig(orgId);
|
||||
|
||||
return { success: true };
|
||||
});
|
||||
}
|
||||
|
||||
// Activate SSO connection
|
||||
export async function activateSsoConnection(orgId: string, updatedByProfileId: string) {
|
||||
const config = await getOrganizationSsoConfig(orgId);
|
||||
if (!config) {
|
||||
throw new AppError('SSO connection not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
// Could add a test connection check here before activating
|
||||
|
||||
const updated = await updateOrganizationSsoConfig(orgId, {
|
||||
isActive: true,
|
||||
updatedByProfileId
|
||||
});
|
||||
|
||||
return updated;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import {
|
||||
createTokenAuth,
|
||||
deleteTokenAuth,
|
||||
getTokenAuthByOrgId,
|
||||
updateTokenAuth
|
||||
} from '@cio/db/queries/organization/token-auth';
|
||||
import { getOrganizationPlanStatus } from '@cio/db/queries/organization/organization';
|
||||
import type { TOrganizationTokenAuth } from '@db/types';
|
||||
import { randomBytes } from 'crypto';
|
||||
|
||||
async function assertEnterprisePlan(orgId: string): Promise<void> {
|
||||
const plans = await getOrganizationPlanStatus(orgId);
|
||||
const hasEnterprise = plans.some(
|
||||
(p: { planName: string | null; isActive: boolean | null }) => p.planName === 'ENTERPRISE' && p.isActive
|
||||
);
|
||||
|
||||
if (!hasEnterprise) {
|
||||
throw new AppError('Token auth requires Enterprise plan', ErrorCodes.UPGRADE_REQUIRED, 403);
|
||||
}
|
||||
}
|
||||
|
||||
function generateSigningSecret(): string {
|
||||
return randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
export interface TokenAuthStatus {
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
secretLast4: string | null;
|
||||
}
|
||||
|
||||
export async function getTokenAuthStatus(orgId: string): Promise<TokenAuthStatus | null> {
|
||||
const row = await getTokenAuthByOrgId(orgId);
|
||||
if (!row) return null;
|
||||
|
||||
const secretLast4 = row.signingSecret.length >= 4 ? row.signingSecret.slice(-4) : null;
|
||||
|
||||
return {
|
||||
isActive: row.isActive,
|
||||
createdAt: row.createdAt,
|
||||
secretLast4
|
||||
};
|
||||
}
|
||||
|
||||
export async function createTokenAuthConfig(
|
||||
orgId: string,
|
||||
createdByProfileId: string
|
||||
): Promise<{ secret: string; config: TOrganizationTokenAuth }> {
|
||||
await assertEnterprisePlan(orgId);
|
||||
|
||||
const existing = await getTokenAuthByOrgId(orgId);
|
||||
if (existing) {
|
||||
throw new AppError('Organization already has token auth configured', ErrorCodes.TOKEN_AUTH_ALREADY_EXISTS, 409);
|
||||
}
|
||||
|
||||
const secret = generateSigningSecret();
|
||||
const config = await createTokenAuth({
|
||||
organizationId: orgId,
|
||||
signingSecret: secret,
|
||||
isActive: false,
|
||||
createdByProfileId
|
||||
});
|
||||
|
||||
return { secret, config };
|
||||
}
|
||||
|
||||
export async function rotateTokenAuthSecret(orgId: string): Promise<{ secret: string }> {
|
||||
const existing = await getTokenAuthByOrgId(orgId);
|
||||
if (!existing) {
|
||||
throw new AppError('Token auth not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const secret = generateSigningSecret();
|
||||
await updateTokenAuth(orgId, { signingSecret: secret });
|
||||
return { secret };
|
||||
}
|
||||
|
||||
export async function deleteTokenAuthConfig(orgId: string): Promise<void> {
|
||||
const existing = await getTokenAuthByOrgId(orgId);
|
||||
if (!existing) {
|
||||
throw new AppError('Token auth not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
await deleteTokenAuth(orgId);
|
||||
}
|
||||
|
||||
export async function activateTokenAuth(orgId: string, isActive: boolean): Promise<TOrganizationTokenAuth | null> {
|
||||
const existing = await getTokenAuthByOrgId(orgId);
|
||||
if (!existing) {
|
||||
throw new AppError('Token auth not found', ErrorCodes.NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return updateTokenAuth(orgId, { isActive });
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type { TNewQuiz, TQuiz } from '@db/types';
|
||||
import {
|
||||
createQuiz,
|
||||
deleteQuiz,
|
||||
getQuizById,
|
||||
getQuizzesByOrganizationId,
|
||||
updateQuiz
|
||||
} from '@cio/db/queries/organization/quiz';
|
||||
|
||||
/**
|
||||
* Gets all quizzes for an organization
|
||||
* @param orgId - The organization ID
|
||||
* @returns Array of quizzes
|
||||
*/
|
||||
export async function listQuizzes(orgId: string): Promise<TQuiz[]> {
|
||||
try {
|
||||
const quizzes = await getQuizzesByOrganizationId(orgId);
|
||||
return quizzes;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch quizzes',
|
||||
ErrorCodes.QUIZ_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a single quiz by ID
|
||||
* @param quizId - The quiz ID
|
||||
* @returns Quiz or null if not found
|
||||
*/
|
||||
export async function getQuiz(quizId: string): Promise<TQuiz | null> {
|
||||
try {
|
||||
const quiz = await getQuizById(quizId);
|
||||
return quiz;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch quiz',
|
||||
ErrorCodes.QUIZ_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new quiz
|
||||
* @param orgId - The organization ID
|
||||
* @param data - Quiz creation data
|
||||
* @returns Created quiz
|
||||
*/
|
||||
export async function createQuizService(orgId: string, data: Omit<TNewQuiz, 'organizationId'>): Promise<TQuiz> {
|
||||
try {
|
||||
const quiz = await createQuiz({
|
||||
...data,
|
||||
organizationId: orgId
|
||||
});
|
||||
return quiz;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create quiz',
|
||||
ErrorCodes.QUIZ_CREATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a quiz
|
||||
* @param quizId - The quiz ID
|
||||
* @param data - Quiz update data
|
||||
* @returns Updated quiz
|
||||
*/
|
||||
export async function updateQuizService(quizId: string, data: Partial<TNewQuiz>): Promise<TQuiz> {
|
||||
try {
|
||||
const quiz = await getQuizById(quizId);
|
||||
if (!quiz) {
|
||||
throw new AppError('Quiz not found', ErrorCodes.QUIZ_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const updatedQuiz = await updateQuiz(quizId, data);
|
||||
return updatedQuiz;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update quiz',
|
||||
ErrorCodes.QUIZ_UPDATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a quiz
|
||||
* @param quizId - The quiz ID
|
||||
*/
|
||||
export async function deleteQuizService(quizId: string): Promise<void> {
|
||||
try {
|
||||
const quiz = await getQuizById(quizId);
|
||||
if (!quiz) {
|
||||
throw new AppError('Quiz not found', ErrorCodes.QUIZ_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
await deleteQuiz(quizId);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete quiz',
|
||||
ErrorCodes.QUIZ_DELETE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './submission';
|
||||
@@ -0,0 +1,882 @@
|
||||
import type { AnswerData, FileUploadAnswerData } from '@cio/question-types';
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
import type { TNewSubmission, TSubmission } from '@cio/db/types';
|
||||
import type {
|
||||
TSubmissionAnswerUpdate,
|
||||
TSubmissionGradesUpdate,
|
||||
TSubmissionUpdate
|
||||
} from '@cio/utils/validation/submission';
|
||||
import { buildEmailFromName, deliverEmail } from '@cio/email';
|
||||
import {
|
||||
createSubmission,
|
||||
deleteSubmission,
|
||||
getQuestionAnswersBySubmissionId,
|
||||
getSubmissionById,
|
||||
getSubmissionsByCourseIdWithDetails,
|
||||
getSubmissionsForGrading,
|
||||
updateQuestionAnswer,
|
||||
updateSubmission,
|
||||
updateSubmissionGrades,
|
||||
upsertQuestionAnswer
|
||||
} from '@cio/db/queries/submission';
|
||||
import {
|
||||
fromApiPayload,
|
||||
getQuestionTypeById,
|
||||
getQuestionTypeByTypename,
|
||||
requiresManualGrading
|
||||
} from '@cio/question-types';
|
||||
import { getCourseById, getOrganizationByCourseId } from '@cio/db/queries/course';
|
||||
import { getCourseTeachers, getProfileByGroupMemberId } from '@cio/db/queries/course/people';
|
||||
import { getExerciseById, getExerciseWithRelationsOptimized } from '@cio/db/queries/exercise';
|
||||
import { getGroupMemberIdByCourseAndProfile, isCourseTeamMemberOrOrgAdmin } from '@cio/db/queries/group';
|
||||
|
||||
import { QUESTION_TYPE_ID_TO_KEY } from '@cio/question-types';
|
||||
import { db } from '@cio/db/drizzle';
|
||||
import { env } from '@api/config/env';
|
||||
import { generateDocumentDownloadPresignedUrls } from '@api/utils/s3';
|
||||
|
||||
type SubmissionGradingState = 'queued' | 'processing' | 'awaiting_manual' | 'completed' | 'failed';
|
||||
type SubmissionOverallStatus = 'auto_graded' | 'manual_required' | 'hybrid';
|
||||
|
||||
const LEGACY_BOARD_STATUS_LABELS: Record<number, string> = {
|
||||
1: 'Submitted',
|
||||
2: 'In Progress',
|
||||
3: 'Graded'
|
||||
};
|
||||
|
||||
const LEGACY_STATUS_TO_GRADING_STATE: Record<number, SubmissionGradingState> = {
|
||||
1: 'queued',
|
||||
2: 'processing',
|
||||
3: 'completed'
|
||||
};
|
||||
|
||||
const GRADING_STATE_TO_LEGACY_STATUS: Record<SubmissionGradingState, number> = {
|
||||
queued: 1,
|
||||
processing: 2,
|
||||
awaiting_manual: 2,
|
||||
failed: 2,
|
||||
completed: 3
|
||||
};
|
||||
|
||||
const ALLOWED_GRADING_TRANSITIONS: Record<SubmissionGradingState, SubmissionGradingState[]> = {
|
||||
queued: ['processing'],
|
||||
processing: ['completed', 'awaiting_manual', 'failed'],
|
||||
awaiting_manual: ['completed'],
|
||||
failed: ['queued'],
|
||||
completed: []
|
||||
};
|
||||
|
||||
function projectLegacyStatusId(gradingState: SubmissionGradingState): number {
|
||||
return GRADING_STATE_TO_LEGACY_STATUS[gradingState];
|
||||
}
|
||||
|
||||
function resolveSubmissionGradingState(submission: Partial<TSubmission>): SubmissionGradingState {
|
||||
const rawState = typeof submission.gradingState === 'string' ? submission.gradingState : '';
|
||||
if (rawState && rawState in GRADING_STATE_TO_LEGACY_STATUS) {
|
||||
return rawState as SubmissionGradingState;
|
||||
}
|
||||
|
||||
const legacyStatusId = Number(submission.statusId ?? 1);
|
||||
return LEGACY_STATUS_TO_GRADING_STATE[legacyStatusId] ?? 'queued';
|
||||
}
|
||||
|
||||
function resolveOverallStatusFromTypenames(typenames: string[]): SubmissionOverallStatus {
|
||||
const manualFlags = typenames.map((typename) => {
|
||||
const metadata = getQuestionTypeByTypename(typename);
|
||||
if (!metadata) return true;
|
||||
return requiresManualGrading(metadata.key);
|
||||
});
|
||||
|
||||
const hasManual = manualFlags.some(Boolean);
|
||||
const hasAuto = manualFlags.some((value) => !value);
|
||||
|
||||
if (hasManual && hasAuto) return 'hybrid';
|
||||
if (hasManual) return 'manual_required';
|
||||
return 'auto_graded';
|
||||
}
|
||||
|
||||
function resolveOverallStatusFromQuestionTypeIds(questionTypeIds: number[]): SubmissionOverallStatus {
|
||||
const manualFlags = questionTypeIds.map((questionTypeId) => {
|
||||
const metadata = getQuestionTypeById(questionTypeId);
|
||||
if (!metadata) return true;
|
||||
return requiresManualGrading(metadata.key);
|
||||
});
|
||||
|
||||
const hasManual = manualFlags.some(Boolean);
|
||||
const hasAuto = manualFlags.some((value) => !value);
|
||||
|
||||
if (hasManual && hasAuto) return 'hybrid';
|
||||
if (hasManual) return 'manual_required';
|
||||
return 'auto_graded';
|
||||
}
|
||||
|
||||
function resolveRequestedGradingState(data: TSubmissionUpdate): SubmissionGradingState | null {
|
||||
if (data.gradingState) {
|
||||
return data.gradingState;
|
||||
}
|
||||
|
||||
if (data.statusId === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const mapped = LEGACY_STATUS_TO_GRADING_STATE[Number(data.statusId)];
|
||||
if (!mapped) {
|
||||
throw new AppError('Invalid submission status', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
return mapped;
|
||||
}
|
||||
|
||||
function isAllowedGradingTransition(from: SubmissionGradingState, to: SubmissionGradingState): boolean {
|
||||
if (from === to) return true;
|
||||
return ALLOWED_GRADING_TRANSITIONS[from]?.includes(to) ?? false;
|
||||
}
|
||||
|
||||
function isFileUpload(data: unknown): data is FileUploadAnswerData {
|
||||
return !!data && typeof data === 'object' && (data as { type: string }).type === 'FILE_UPLOAD';
|
||||
}
|
||||
|
||||
/**
|
||||
* Enriches FILE_UPLOAD answers from DB rows (question_answer[]) with presigned download URLs.
|
||||
* Used by getSubmission and listSubmissionsByExercise.
|
||||
*/
|
||||
async function enrichFileUploadAnswersArray<T extends { answerData?: unknown }>(answers: T[]): Promise<T[]> {
|
||||
const fileKeys = answers
|
||||
.map((a) => a.answerData)
|
||||
.filter(isFileUpload)
|
||||
.map((d) => d.fileKey);
|
||||
|
||||
if (fileKeys.length === 0) return answers;
|
||||
|
||||
try {
|
||||
const urls = await generateDocumentDownloadPresignedUrls(fileKeys);
|
||||
return answers.map((answer) => {
|
||||
if (!isFileUpload(answer.answerData)) return answer;
|
||||
const url = urls[answer.answerData.fileKey];
|
||||
return url ? { ...answer, answerData: { ...answer.answerData, fileUrl: url } } : answer;
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('enrichFileUploadAnswersArray error:', error);
|
||||
return answers;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enriches FILE_UPLOAD entries in a { questionName → AnswerData } map with presigned download URLs.
|
||||
* Used by getSubmissionsForGradingEmail to build the grading email payload.
|
||||
*/
|
||||
async function enrichFileUploadAnswersObject(answers: Record<string, AnswerData>): Promise<Record<string, AnswerData>> {
|
||||
const fileKeys = Object.values(answers)
|
||||
.filter(isFileUpload)
|
||||
.map((d) => d.fileKey);
|
||||
|
||||
if (fileKeys.length === 0) return answers;
|
||||
|
||||
try {
|
||||
const urls = await generateDocumentDownloadPresignedUrls(fileKeys);
|
||||
return Object.fromEntries(
|
||||
Object.entries(answers).map(([key, data]) => {
|
||||
if (!isFileUpload(data)) return [key, data];
|
||||
const url = urls[data.fileKey];
|
||||
return url ? [key, { ...data, fileUrl: url }] : [key, data];
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('enrichFileUploadAnswersObject error:', error);
|
||||
return answers;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a submission by ID with question answers
|
||||
* @param submissionId Submission ID
|
||||
* @returns Submission with question answers
|
||||
*/
|
||||
export async function getSubmission(submissionId: string): Promise<TSubmission & { answers?: any[] }> {
|
||||
try {
|
||||
const submission = await getSubmissionById(submissionId);
|
||||
if (!submission) {
|
||||
throw new AppError('Submission not found', ErrorCodes.SUBMISSION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
let answers = await getQuestionAnswersBySubmissionId(submissionId);
|
||||
if (answers.length > 0) {
|
||||
answers = await enrichFileUploadAnswersArray(answers);
|
||||
}
|
||||
|
||||
return {
|
||||
...submission,
|
||||
answers
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch submission',
|
||||
ErrorCodes.SUBMISSION_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Submission with answers + groupmember (when listing by exercise). Used for route typing. */
|
||||
type SubmissionWithDetails = Awaited<ReturnType<typeof getSubmissionsByCourseIdWithDetails>>[number];
|
||||
|
||||
/**
|
||||
* Lists submissions for a course filtered by exercise (with answers, groupmember, enriched file URLs)
|
||||
* @param courseId Course ID
|
||||
* @param exerciseId Exercise ID (required)
|
||||
* @param submittedBy Optional group member ID filter
|
||||
*/
|
||||
export async function listSubmissionsByExercise(
|
||||
courseId: string,
|
||||
exerciseId: string,
|
||||
submittedBy?: string
|
||||
): Promise<SubmissionWithDetails[]> {
|
||||
try {
|
||||
const submissions = await getSubmissionsByCourseIdWithDetails(courseId, exerciseId, submittedBy);
|
||||
const enriched = await Promise.all(
|
||||
submissions.map(async (s) =>
|
||||
s.answers?.length ? { ...s, answers: await enrichFileUploadAnswersArray(s.answers) } : s
|
||||
)
|
||||
);
|
||||
return enriched;
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list submissions by exercise',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export type ExerciseSubmissionsOverview = {
|
||||
mySubmission: Awaited<ReturnType<typeof listSubmissionsByExercise>>;
|
||||
allSubmissions: Awaited<ReturnType<typeof listSubmissionsByExercise>>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns submission overview for an exercise based on user role.
|
||||
* - Students: mySubmission = their submission(s), allSubmissions = []
|
||||
* - Instructors: mySubmission = [], allSubmissions = all submissions in exercise
|
||||
*/
|
||||
export async function listExerciseSubmissionsOverview(
|
||||
courseId: string,
|
||||
exerciseId: string,
|
||||
profileId: string
|
||||
): Promise<ExerciseSubmissionsOverview> {
|
||||
try {
|
||||
const [groupMemberId, isInstructor] = await Promise.all([
|
||||
getGroupMemberIdByCourseAndProfile(courseId, profileId),
|
||||
isCourseTeamMemberOrOrgAdmin(courseId, profileId)
|
||||
]);
|
||||
|
||||
if (isInstructor) {
|
||||
const allSubmissions = await listSubmissionsByExercise(courseId, exerciseId);
|
||||
return { mySubmission: [], allSubmissions };
|
||||
}
|
||||
|
||||
const mySubmission = groupMemberId ? await listSubmissionsByExercise(courseId, exerciseId, groupMemberId) : [];
|
||||
|
||||
return { mySubmission, allSubmissions: [] };
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list exercise submissions overview',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists submissions for grading with pre-processed data
|
||||
* @param courseId Course ID
|
||||
* @returns Processed submissions organized by status sections
|
||||
*/
|
||||
export async function listSubmissionsForGrading(courseId: string) {
|
||||
try {
|
||||
const rawSubmissions = await getSubmissionsForGrading(courseId);
|
||||
const course = await getCourseById(courseId);
|
||||
|
||||
type SubmissionItem = {
|
||||
id: string;
|
||||
statusId: number;
|
||||
gradingState: SubmissionGradingState;
|
||||
overallStatus: SubmissionOverallStatus;
|
||||
isEarly: boolean;
|
||||
feedback: string | null;
|
||||
submittedAt: string;
|
||||
exercise: {
|
||||
id: string;
|
||||
title: string;
|
||||
};
|
||||
answers: any[];
|
||||
student: any | null;
|
||||
lesson: {
|
||||
id: string;
|
||||
title: string;
|
||||
} | null;
|
||||
};
|
||||
|
||||
const sections: Array<{ id: number; title: string; value: number; items: SubmissionItem[] }> = [
|
||||
{ id: 1, title: LEGACY_BOARD_STATUS_LABELS[1], value: 0, items: [] },
|
||||
{ id: 2, title: LEGACY_BOARD_STATUS_LABELS[2], value: 0, items: [] },
|
||||
{ id: 3, title: LEGACY_BOARD_STATUS_LABELS[3], value: 0, items: [] }
|
||||
];
|
||||
|
||||
const submissionIdData: { [key: string]: any } = {};
|
||||
|
||||
// Process each submission
|
||||
for (const submission of rawSubmissions) {
|
||||
const gradingState = resolveSubmissionGradingState(submission);
|
||||
const statusId = projectLegacyStatusId(gradingState);
|
||||
const storedOverallStatus = typeof submission.overallStatus === 'string' ? submission.overallStatus : '';
|
||||
const fallbackOverallStatus = resolveOverallStatusFromQuestionTypeIds(
|
||||
(submission.exercise.questions || [])
|
||||
.map((question: any) => Number(question.questionTypeId))
|
||||
.filter((questionTypeId: number) => Number.isFinite(questionTypeId))
|
||||
);
|
||||
const overallStatus: SubmissionOverallStatus =
|
||||
storedOverallStatus === 'auto_graded' ||
|
||||
storedOverallStatus === 'manual_required' ||
|
||||
storedOverallStatus === 'hybrid'
|
||||
? (storedOverallStatus as SubmissionOverallStatus)
|
||||
: fallbackOverallStatus;
|
||||
const isEarly = submission.exercise.dueBy
|
||||
? new Date(submission.createdAt!).getTime() <= new Date(submission.exercise.dueBy).getTime()
|
||||
: true;
|
||||
|
||||
const submittedAt = new Intl.DateTimeFormat('en-US', {
|
||||
dateStyle: 'full',
|
||||
timeStyle: 'medium'
|
||||
}).format(new Date(submission.createdAt!));
|
||||
|
||||
// Format answers
|
||||
const questionByIdAndName: { [id: number]: string } = {};
|
||||
const questionTypeById: { [id: number]: number } = {};
|
||||
for (const question of submission.exercise.questions || []) {
|
||||
questionByIdAndName[question.id] = question.name ?? '';
|
||||
questionTypeById[question.id] = question.questionTypeId;
|
||||
}
|
||||
|
||||
const formattedAnswers: { [questionName: string]: AnswerData } = {};
|
||||
const questionAnswerByPoint: { [questionId: number]: number } = {};
|
||||
|
||||
for (const answer of submission.answers || []) {
|
||||
const questionName = questionByIdAndName[answer.questionId];
|
||||
if (
|
||||
questionName &&
|
||||
answer.answerData &&
|
||||
typeof answer.answerData === 'object' &&
|
||||
answer.answerData !== null &&
|
||||
'type' in answer.answerData
|
||||
) {
|
||||
formattedAnswers[questionName] = answer.answerData as AnswerData;
|
||||
}
|
||||
questionAnswerByPoint[answer.questionId] = answer.point || 0;
|
||||
}
|
||||
|
||||
const enrichedFormattedAnswers = await enrichFileUploadAnswersObject(formattedAnswers);
|
||||
|
||||
// Create submission item for sections
|
||||
const submissionItem = {
|
||||
id: submission.id,
|
||||
statusId,
|
||||
gradingState,
|
||||
overallStatus,
|
||||
isEarly,
|
||||
feedback: submission.feedback,
|
||||
submittedAt,
|
||||
exercise: {
|
||||
id: submission.exercise.id,
|
||||
title: submission.exercise.title
|
||||
},
|
||||
answers: submission.answers || [],
|
||||
student: submission.groupmember?.profile || null,
|
||||
lesson: submission.lesson
|
||||
? {
|
||||
id: submission.lesson.id,
|
||||
title: submission.lesson.title
|
||||
}
|
||||
: null
|
||||
};
|
||||
|
||||
// Add to appropriate section
|
||||
const sectionIndex = statusId - 1;
|
||||
if (sectionIndex >= 0 && sectionIndex < sections.length) {
|
||||
sections[sectionIndex].items.push(submissionItem);
|
||||
sections[sectionIndex].value = sections[sectionIndex].items.length;
|
||||
}
|
||||
|
||||
// Create detailed data for modal
|
||||
submissionIdData[submission.id] = {
|
||||
id: submission.id,
|
||||
statusId,
|
||||
gradingState,
|
||||
overallStatus,
|
||||
feedback: submission.feedback,
|
||||
isEarly,
|
||||
title: submission.exercise.title,
|
||||
student: submission.groupmember?.profile || null,
|
||||
questions: (submission.exercise.questions || []).map((q: any) => ({
|
||||
id: q.id,
|
||||
title: q.title,
|
||||
name: q.name,
|
||||
order: q.order,
|
||||
points: q.points,
|
||||
questionTypeId: q.questionTypeId,
|
||||
settings: q.settings ?? {},
|
||||
options: (q.options || []).map((opt: any) => ({
|
||||
id: opt.id,
|
||||
label: opt.label,
|
||||
value: opt.value,
|
||||
isCorrect: opt.isCorrect,
|
||||
settings: opt.settings ?? {}
|
||||
}))
|
||||
})),
|
||||
answers: enrichedFormattedAnswers,
|
||||
questionAnswers: (submission.answers || []).map((answer: any) => ({
|
||||
questionId: answer.questionId,
|
||||
answerData: answer.answerData
|
||||
})),
|
||||
questionAnswerByPoint
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
sections,
|
||||
submissionIdData
|
||||
};
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to list submissions for grading',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new submission with question answers
|
||||
* @param courseId Course ID
|
||||
* @param exerciseId Exercise ID
|
||||
* @param submittedBy Group member ID
|
||||
* @param answers Array of question answers
|
||||
* @returns Created submission
|
||||
*/
|
||||
export async function createSubmissionService(
|
||||
courseId: string,
|
||||
exerciseId: string,
|
||||
submittedBy: string,
|
||||
answers: Array<{ questionId: number; optionId?: number; answer?: string }>
|
||||
): Promise<TSubmission> {
|
||||
try {
|
||||
const exerciseWithRelations = await getExerciseWithRelationsOptimized(exerciseId);
|
||||
const overallStatus = resolveOverallStatusFromTypenames(
|
||||
exerciseWithRelations.questions
|
||||
.map((question) => question.questionType?.typename ?? '')
|
||||
.filter((typename) => typename.length > 0)
|
||||
);
|
||||
const gradingState: SubmissionGradingState = 'queued';
|
||||
|
||||
const submissionData: TNewSubmission = {
|
||||
courseId,
|
||||
exerciseId,
|
||||
submittedBy,
|
||||
statusId: projectLegacyStatusId(gradingState),
|
||||
gradingState,
|
||||
overallStatus,
|
||||
total: 0 // Will be calculated during grading
|
||||
};
|
||||
|
||||
const submission = await createSubmission(submissionData);
|
||||
|
||||
// Create question answers
|
||||
if (answers.length > 0) {
|
||||
const questionById = new Map(
|
||||
exerciseWithRelations.questions.map((q) => {
|
||||
const questionTypeKey = QUESTION_TYPE_ID_TO_KEY[q.questionTypeId] ?? 'TEXTAREA';
|
||||
return [
|
||||
q.id,
|
||||
{
|
||||
id: q.id,
|
||||
title: q.title ?? '',
|
||||
questionType: questionTypeKey,
|
||||
options: (q.options ?? []).map((o) => ({
|
||||
id: o.id,
|
||||
label: o.label ?? '',
|
||||
value: o.value ?? undefined,
|
||||
isCorrect: o.isCorrect
|
||||
}))
|
||||
}
|
||||
];
|
||||
})
|
||||
);
|
||||
|
||||
await db.transaction(async () => {
|
||||
for (const ans of answers) {
|
||||
const question = questionById.get(ans.questionId);
|
||||
if (!question) continue;
|
||||
|
||||
const answerData = fromApiPayload(
|
||||
question.questionType,
|
||||
{ questionId: ans.questionId, optionId: ans.optionId, answer: ans.answer },
|
||||
question
|
||||
);
|
||||
if (!answerData) continue;
|
||||
|
||||
await upsertQuestionAnswer({
|
||||
submissionId: submission.id,
|
||||
questionId: ans.questionId,
|
||||
groupMemberId: submittedBy,
|
||||
answerData
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Send email notification to teachers
|
||||
try {
|
||||
await sendExerciseSubmissionUpdateEmail(courseId, exerciseId, submittedBy);
|
||||
} catch (emailError) {
|
||||
// Log but don't fail the request if email fails
|
||||
console.error('Failed to send exercise submission update email:', emailError);
|
||||
}
|
||||
|
||||
return submission;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create submission',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a submission
|
||||
* @param submissionId Submission ID
|
||||
* @param data Partial submission update data
|
||||
* @returns Updated submission
|
||||
*/
|
||||
export async function updateSubmissionService(submissionId: string, data: TSubmissionUpdate): Promise<TSubmission> {
|
||||
try {
|
||||
const submission = await getSubmissionById(submissionId);
|
||||
if (!submission) {
|
||||
throw new AppError('Submission not found', ErrorCodes.SUBMISSION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const currentGradingState = resolveSubmissionGradingState(submission);
|
||||
const requestedGradingState = resolveRequestedGradingState(data);
|
||||
if (requestedGradingState && !isAllowedGradingTransition(currentGradingState, requestedGradingState)) {
|
||||
throw new AppError('Invalid submission workflow transition', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
const previousLegacyStatusId = projectLegacyStatusId(currentGradingState);
|
||||
const updatePayload: Partial<TSubmission> = { ...data };
|
||||
if (requestedGradingState) {
|
||||
updatePayload.gradingState = requestedGradingState;
|
||||
updatePayload.statusId = projectLegacyStatusId(requestedGradingState);
|
||||
}
|
||||
|
||||
const nextLegacyStatusId = Number(updatePayload.statusId ?? previousLegacyStatusId);
|
||||
const statusChanged = nextLegacyStatusId !== previousLegacyStatusId;
|
||||
|
||||
const updated = await updateSubmission(submissionId, updatePayload);
|
||||
if (!updated) {
|
||||
throw new AppError('Failed to update submission', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
// Send email notification if status changed
|
||||
if (statusChanged) {
|
||||
try {
|
||||
await sendSubmissionUpdateEmail(submissionId, nextLegacyStatusId);
|
||||
} catch (emailError) {
|
||||
// Log but don't fail the request if email fails
|
||||
console.error('Failed to send submission update email:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update submission',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a question answer in a submission
|
||||
* @param submissionId Submission ID
|
||||
* @param questionId Question ID
|
||||
* @param data Question answer update data
|
||||
* @returns Updated question answer
|
||||
*/
|
||||
export async function updateSubmissionAnswer(
|
||||
submissionId: string,
|
||||
questionId: number,
|
||||
data: TSubmissionAnswerUpdate
|
||||
): Promise<any> {
|
||||
try {
|
||||
const submission = await getSubmissionById(submissionId);
|
||||
if (!submission) {
|
||||
throw new AppError('Submission not found', ErrorCodes.SUBMISSION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const updateData: { point?: number } = {};
|
||||
if (data.points !== undefined) updateData.point = data.points;
|
||||
if (Object.keys(updateData).length === 0) return null;
|
||||
|
||||
const updated = await updateQuestionAnswer(submissionId, questionId, updateData);
|
||||
if (!updated) {
|
||||
throw new AppError('Question answer not found', ErrorCodes.INTERNAL_ERROR, 404);
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update question answer',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates all question answer points and submission total/feedback in a single transaction.
|
||||
* Submitting grades automatically transitions status to Graded (statusId 3, gradingState completed).
|
||||
*/
|
||||
export async function updateSubmissionGradesBatch(
|
||||
submissionId: string,
|
||||
data: TSubmissionGradesUpdate
|
||||
): Promise<TSubmission> {
|
||||
try {
|
||||
const submission = await getSubmissionById(submissionId);
|
||||
if (!submission) {
|
||||
throw new AppError('Submission not found', ErrorCodes.SUBMISSION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const currentGradingState = resolveSubmissionGradingState(submission);
|
||||
const targetGradingState: SubmissionGradingState = 'completed';
|
||||
const targetStatusId = projectLegacyStatusId(targetGradingState);
|
||||
|
||||
if (!isAllowedGradingTransition(currentGradingState, targetGradingState)) {
|
||||
throw new AppError('Invalid submission workflow transition', ErrorCodes.VALIDATION_ERROR, 400);
|
||||
}
|
||||
|
||||
const previousLegacyStatusId = projectLegacyStatusId(currentGradingState);
|
||||
const statusChanged = targetStatusId !== previousLegacyStatusId;
|
||||
|
||||
const updated = await updateSubmissionGrades(submissionId, {
|
||||
answers: data.answers,
|
||||
total: data.total,
|
||||
feedback: data.feedback,
|
||||
statusId: targetStatusId,
|
||||
gradingState: targetGradingState
|
||||
});
|
||||
|
||||
if (!updated) {
|
||||
throw new AppError('Failed to update grades', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
if (statusChanged) {
|
||||
try {
|
||||
await sendSubmissionUpdateEmail(submissionId, targetStatusId);
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send submission update email:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update submission grades',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a submission
|
||||
* @param submissionId Submission ID
|
||||
* @returns Deleted submission
|
||||
*/
|
||||
export async function deleteSubmissionService(submissionId: string): Promise<TSubmission> {
|
||||
try {
|
||||
const submission = await getSubmissionById(submissionId);
|
||||
if (!submission) {
|
||||
throw new AppError('Submission not found', ErrorCodes.SUBMISSION_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const deleted = await deleteSubmission(submissionId);
|
||||
if (!deleted) {
|
||||
throw new AppError('Failed to delete submission', ErrorCodes.INTERNAL_ERROR, 500);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to delete submission',
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends email notification to student when submission status changes
|
||||
*/
|
||||
async function sendSubmissionUpdateEmail(submissionId: string, newStatusId: number) {
|
||||
const submission = await getSubmissionById(submissionId);
|
||||
if (!submission || !submission.courseId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const submissionData = await getSubmissionsForGrading(submission.courseId);
|
||||
const fullSubmission = submissionData.find((s) => s.id === submissionId);
|
||||
if (!fullSubmission || !fullSubmission.groupmember?.profile?.email) {
|
||||
return;
|
||||
}
|
||||
|
||||
const courseResult = await getCourseById(fullSubmission.courseId || '');
|
||||
const course = courseResult[0];
|
||||
if (!course) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get organization name
|
||||
const orgResult = await getOrganizationByCourseId(fullSubmission.courseId || '');
|
||||
|
||||
const orgName = orgResult?.orgName || 'ClassroomIO';
|
||||
|
||||
const statusText = LEGACY_BOARD_STATUS_LABELS[newStatusId] || 'Updated';
|
||||
const baseUrl = env.NODE_ENV === 'development' ? 'http://localhost:5173' : 'https://app.classroomio.com';
|
||||
const exerciseLink = `${baseUrl}/courses/${fullSubmission.courseId}/exercises/${fullSubmission.exercise.id}`;
|
||||
|
||||
// Calculate total and max points
|
||||
const answers = fullSubmission.answers || [];
|
||||
const totalMark = answers.reduce((sum: number, a: any) => sum + (a.point || 0), 0);
|
||||
const maxMark = (fullSubmission.exercise.questions || []).reduce((sum: number, q: any) => sum + (q.points || 0), 0);
|
||||
|
||||
let content = `
|
||||
<p>Hello ${fullSubmission.groupmember.profile.fullname || 'Student'},</p>
|
||||
<p>The status of your submitted exercise on <strong>${fullSubmission.exercise.title}</strong> has been updated to ${statusText}</p>
|
||||
`;
|
||||
|
||||
if (newStatusId === 3) {
|
||||
content += `
|
||||
<p>Your score was ${totalMark}/${maxMark}</p>
|
||||
<a class="button" href="${exerciseLink}">View your Result</a>
|
||||
`;
|
||||
} else {
|
||||
content += `<a class="button" href="${exerciseLink}">Open Exercise</a>`;
|
||||
}
|
||||
|
||||
if (fullSubmission.lesson?.title) {
|
||||
content += `
|
||||
<p>This exercise is for <strong>${fullSubmission.lesson.title}</strong> in a course you are taking titled <strong>${course.title}</strong></p>
|
||||
`;
|
||||
} else {
|
||||
content += `
|
||||
<p>This exercise is in a course you are taking titled <strong>${course.title}</strong></p>
|
||||
`;
|
||||
}
|
||||
|
||||
await deliverEmail([
|
||||
{
|
||||
from: buildEmailFromName(`${orgName} (via ClassroomIO.com)`),
|
||||
to: fullSubmission.groupmember.profile.email,
|
||||
subject: 'Submission Update',
|
||||
content
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends email notification to teachers when a student submits an exercise
|
||||
*/
|
||||
async function sendExerciseSubmissionUpdateEmail(courseId: string, exerciseId: string, submittedBy: string) {
|
||||
// Get course and exercise data
|
||||
const course = await getCourseById(courseId);
|
||||
if (!course) {
|
||||
return;
|
||||
}
|
||||
|
||||
const exercise = await getExerciseById(exerciseId);
|
||||
|
||||
if (!exercise) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get student info
|
||||
const student = await getProfileByGroupMemberId(submittedBy);
|
||||
|
||||
if (!student) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get tutors (ADMIN or TUTOR role) from the course's group
|
||||
const tutorsResult = await getCourseTeachers({ courseId });
|
||||
|
||||
if (tutorsResult.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get organization name
|
||||
const orgResult = await getOrganizationByCourseId(courseId);
|
||||
|
||||
const orgName = orgResult?.orgName || 'ClassroomIO';
|
||||
|
||||
const baseUrl = env.NODE_ENV === 'development' ? 'http://localhost:5173' : 'https://app.classroomio.com';
|
||||
const exerciseLink = `${baseUrl}/courses/${courseId}/exercises/${exerciseId}`;
|
||||
const submissionLink = `${baseUrl}/courses/${courseId}/submissions`;
|
||||
|
||||
const content = `
|
||||
<p>Hello,</p>
|
||||
<p>A student ${student.fullname || student.username} just submitted an exercise <a href="${exerciseLink}">${exercise.title}</a></p>
|
||||
<p>You can get started grading by clicking "Open Submissions"</p>
|
||||
<div>
|
||||
<a class="button" href="${submissionLink}">Open Submissions</a>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Send email to all tutors
|
||||
const emailPromises = tutorsResult.map((tutor) => {
|
||||
if (!tutor.email) return Promise.resolve();
|
||||
return deliverEmail([
|
||||
{
|
||||
from: buildEmailFromName(`${orgName} (via ClassroomIO.com)`),
|
||||
to: tutor.email,
|
||||
subject: `[Submitted]: ${exercise.title}`,
|
||||
content
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
await Promise.all(emailPromises);
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import type {
|
||||
TCourseTagAssignment,
|
||||
TTagCreate,
|
||||
TTagGroupCreate,
|
||||
TTagGroupUpdate,
|
||||
TTagUpdate
|
||||
} from '@cio/utils/validation/tag';
|
||||
import {
|
||||
createTag,
|
||||
createTagGroup,
|
||||
generateUniqueTagGroupSlug,
|
||||
generateUniqueTagSlug,
|
||||
getCourseOrganizationId,
|
||||
getCourseTagsForOrganization,
|
||||
getTagById,
|
||||
getTagGroupById,
|
||||
getTagGroupsWithTags,
|
||||
getTagsByIds,
|
||||
replaceCourseTagAssignments,
|
||||
updateTag,
|
||||
updateTagGroup
|
||||
} from '@cio/db/queries/tag';
|
||||
import { getOrgIdBySiteName, isUserOrgAdmin } from '@cio/db/queries/organization';
|
||||
|
||||
import { AppError, ErrorCodes } from '@api/utils/errors';
|
||||
|
||||
function normalizeOptionalText(value: string | undefined): string | null | undefined {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const normalized = value.trim();
|
||||
|
||||
return normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
export async function getOrganizationTagGroups(orgId: string) {
|
||||
try {
|
||||
return getTagGroupsWithTags(orgId);
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch tag groups',
|
||||
ErrorCodes.TAG_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPublicOrganizationTagGroups(siteName: string) {
|
||||
try {
|
||||
const orgResult = await getOrgIdBySiteName(siteName);
|
||||
const org = orgResult[0];
|
||||
|
||||
if (!org) {
|
||||
throw new AppError('Organization not found', ErrorCodes.ORG_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const groups = await getTagGroupsWithTags(org.id, {
|
||||
onlyPublishedCourses: true
|
||||
});
|
||||
|
||||
const tagsByGroupId = new Map<string, (typeof groups)[number]['tags']>();
|
||||
|
||||
for (const group of groups) {
|
||||
for (const tag of group.tags) {
|
||||
const groupId = tag.groupId || group.id;
|
||||
const existing = tagsByGroupId.get(groupId) ?? [];
|
||||
|
||||
if (!existing.some((item) => item.id === tag.id)) {
|
||||
existing.push(tag);
|
||||
tagsByGroupId.set(groupId, existing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return groups.map((group) => ({
|
||||
...group,
|
||||
tags: tagsByGroupId.get(group.id) ?? []
|
||||
}));
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch public tag groups',
|
||||
ErrorCodes.TAG_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createOrganizationTagGroup(orgId: string, data: TTagGroupCreate) {
|
||||
try {
|
||||
const slug = await generateUniqueTagGroupSlug(orgId, data.name);
|
||||
|
||||
return createTagGroup({
|
||||
organizationId: orgId,
|
||||
name: data.name.trim(),
|
||||
slug,
|
||||
description: normalizeOptionalText(data.description),
|
||||
order: data.order ?? 0
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create tag group',
|
||||
ErrorCodes.TAG_CREATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateOrganizationTagGroup(orgId: string, groupId: string, data: TTagGroupUpdate) {
|
||||
try {
|
||||
const existing = await getTagGroupById(orgId, groupId);
|
||||
|
||||
if (!existing) {
|
||||
throw new AppError('Tag group not found', ErrorCodes.TAG_GROUP_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
const nextName = data.name?.trim();
|
||||
const slug = nextName && nextName !== existing.name ? await generateUniqueTagGroupSlug(orgId, nextName) : undefined;
|
||||
|
||||
const updated = await updateTagGroup(orgId, groupId, {
|
||||
...(nextName ? { name: nextName } : {}),
|
||||
...(slug ? { slug } : {}),
|
||||
...(data.description !== undefined ? { description: normalizeOptionalText(data.description) } : {}),
|
||||
...(data.order !== undefined ? { order: data.order } : {})
|
||||
});
|
||||
|
||||
if (!updated) {
|
||||
throw new AppError('Tag group not found', ErrorCodes.TAG_GROUP_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update tag group',
|
||||
ErrorCodes.TAG_UPDATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createOrganizationTag(orgId: string, data: TTagCreate) {
|
||||
try {
|
||||
const group = await getTagGroupById(orgId, data.groupId);
|
||||
|
||||
if (!group) {
|
||||
throw new AppError('Tag group not found', ErrorCodes.TAG_GROUP_NOT_FOUND, 404, 'groupId');
|
||||
}
|
||||
|
||||
const slug = await generateUniqueTagSlug(orgId, data.name);
|
||||
|
||||
return createTag({
|
||||
organizationId: orgId,
|
||||
groupId: data.groupId,
|
||||
name: data.name.trim(),
|
||||
slug,
|
||||
description: normalizeOptionalText(data.description),
|
||||
color: data.color
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to create tag',
|
||||
ErrorCodes.TAG_CREATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateOrganizationTag(orgId: string, tagId: string, data: TTagUpdate) {
|
||||
try {
|
||||
const existing = await getTagById(orgId, tagId);
|
||||
|
||||
if (!existing) {
|
||||
throw new AppError('Tag not found', ErrorCodes.TAG_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
if (data.groupId) {
|
||||
const group = await getTagGroupById(orgId, data.groupId);
|
||||
if (!group) {
|
||||
throw new AppError('Tag group not found', ErrorCodes.TAG_GROUP_NOT_FOUND, 404, 'groupId');
|
||||
}
|
||||
}
|
||||
|
||||
const nextName = data.name?.trim();
|
||||
const slug = nextName && nextName !== existing.name ? await generateUniqueTagSlug(orgId, nextName) : undefined;
|
||||
|
||||
const updated = await updateTag(orgId, tagId, {
|
||||
...(nextName ? { name: nextName } : {}),
|
||||
...(slug ? { slug } : {}),
|
||||
...(data.description !== undefined ? { description: normalizeOptionalText(data.description) } : {}),
|
||||
...(data.groupId ? { groupId: data.groupId } : {}),
|
||||
...(data.color ? { color: data.color } : {})
|
||||
});
|
||||
|
||||
if (!updated) {
|
||||
throw new AppError('Tag not found', ErrorCodes.TAG_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to update tag',
|
||||
ErrorCodes.TAG_UPDATE_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCourseTags(orgId: string, courseId: string) {
|
||||
try {
|
||||
const courseOrgId = await getCourseOrganizationId(courseId);
|
||||
|
||||
if (!courseOrgId) {
|
||||
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
if (courseOrgId !== orgId) {
|
||||
throw new AppError('Invalid permissions', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
|
||||
return getCourseTagsForOrganization(orgId, courseId);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to fetch course tags',
|
||||
ErrorCodes.TAG_FETCH_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function replaceCourseTags(
|
||||
orgId: string,
|
||||
courseId: string,
|
||||
data: TCourseTagAssignment,
|
||||
options: {
|
||||
updatedByUserId?: string;
|
||||
} = {}
|
||||
) {
|
||||
try {
|
||||
if (options.updatedByUserId) {
|
||||
const isAdmin = await isUserOrgAdmin(orgId, options.updatedByUserId);
|
||||
if (!isAdmin) {
|
||||
throw new AppError('Only organization admins can update course tags', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
}
|
||||
|
||||
const courseOrgId = await getCourseOrganizationId(courseId);
|
||||
|
||||
if (!courseOrgId) {
|
||||
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
|
||||
}
|
||||
|
||||
if (courseOrgId !== orgId) {
|
||||
throw new AppError('Invalid permissions', ErrorCodes.UNAUTHORIZED, 403);
|
||||
}
|
||||
|
||||
const uniqueTagIds = Array.from(new Set(data.tagIds));
|
||||
|
||||
if (uniqueTagIds.length > 0) {
|
||||
const validTags = await getTagsByIds(orgId, uniqueTagIds);
|
||||
if (validTags.length !== uniqueTagIds.length) {
|
||||
throw new AppError('One or more tags are invalid', ErrorCodes.VALIDATION_ERROR, 400, 'tagIds');
|
||||
}
|
||||
}
|
||||
|
||||
await replaceCourseTagAssignments(courseId, uniqueTagIds);
|
||||
|
||||
return getCourseTagsForOrganization(orgId, courseId);
|
||||
} catch (error) {
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
error instanceof Error ? error.message : 'Failed to assign course tags',
|
||||
ErrorCodes.TAG_ASSIGNMENT_FAILED,
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user