File size: 17,745 Bytes
81b66b7 1ba51fa 81b66b7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | import { Response, NextFunction } from 'express';
import LearningPath from '../models/LearningPath';
import Progress from '../models/Progress';
import User from '../models/User';
import { AuthRequest } from '../types';
import { convertTemplateToSteps } from './auth.controller';
import { allLearningPaths, getPathById } from '../data/learningPathTemplates';
// Helper: validate and parse a step index from route params
const parseStepIndex = (stepIndex: string, stepsLength: number): number | null => {
const idx = parseInt(stepIndex, 10);
if (isNaN(idx) || idx < 0 || idx >= stepsLength) return null;
return idx;
};
// @desc Get available learning path templates
// @route GET /api/learning-path/templates
// @access Private
export const getPathTemplates = async (
_req: AuthRequest,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const templates = allLearningPaths.map(path => ({
id: path.id,
title: path.title,
description: path.description,
category: path.category,
totalWeeks: path.totalWeeks,
difficulty: path.difficulty,
moduleCount: path.modules.length,
outcomes: path.outcomes,
targetRoles: path.targetRoles,
tags: path.tags,
}));
res.status(200).json({
success: true,
count: templates.length,
data: templates,
});
} catch (error) {
next(error);
}
};
// @desc Get template details with full checklist
// @route GET /api/learning-path/templates/:templateId
// @access Private
export const getTemplateDetails = async (
req: AuthRequest,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const template = getPathById(req.params.templateId);
if (!template) {
res.status(404).json({
success: false,
error: 'Learning path template not found',
});
return;
}
res.status(200).json({
success: true,
data: template,
});
} catch (error) {
next(error);
}
};
// @desc Start a learning path from template
// @route POST /api/learning-path/start
// @access Private
export const startLearningPath = async (
req: AuthRequest,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const { templateId } = req.body;
const userId = req.user?._id;
const template = getPathById(templateId);
if (!template) {
res.status(404).json({
success: false,
error: 'Learning path template not found',
});
return;
}
// Check if user already has this path (fix: match by title, not steps.title)
const existingPath = await LearningPath.findOne({ userId, title: template.title });
if (existingPath) {
res.status(200).json({
success: true,
message: 'You already have this learning path',
data: existingPath,
});
return;
}
// Convert template to learning path using shared helper
const steps = convertTemplateToSteps(template);
const learningPath = await LearningPath.create({
userId,
title: template.title,
description: template.description,
category: template.category,
difficulty: template.difficulty,
steps,
tags: template.tags,
currentStepIndex: 0,
progress: 0,
totalWeeks: template.totalWeeks,
startedAt: new Date(),
});
// Update user with learning path reference
await User.findByIdAndUpdate(userId, {
currentLearningPathId: learningPath._id,
$addToSet: { enrolledPaths: learningPath._id },
});
res.status(201).json({
success: true,
message: `Started ${template.title} learning path`,
data: learningPath,
});
} catch (error) {
next(error);
}
};
// @desc Get user's current learning path with progress
// @route GET /api/learning-path
// @access Private
export const getLearningPath = async (
req: AuthRequest,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const userId = req.user?._id;
let learningPath = await LearningPath.findOne({ userId }).sort({ updatedAt: -1 });
// If no path exists, create a default one
if (!learningPath) {
const defaultTemplate = allLearningPaths[0]; // Full Stack
const steps = defaultTemplate.modules.flatMap((module, moduleIdx) =>
module.milestones.map((milestone, msIdx) => ({
title: `${module.title}: ${milestone.title}`,
description: milestone.description,
order: moduleIdx * 10 + msIdx + 1,
completed: false,
estimatedTime: milestone.checklistItems.reduce((sum, item) => sum + item.estimatedHours * 60, 0),
milestoneId: milestone.id,
moduleId: module.id,
checklist: milestone.checklistItems.map(item => ({
id: item.id,
title: item.title,
description: item.description,
completed: false,
estimatedHours: item.estimatedHours,
resourceType: item.resourceType,
isRequired: item.isRequired,
})),
quizTopic: milestone.quizTopic,
passingScore: milestone.passingScore,
}))
);
learningPath = await LearningPath.create({
userId,
title: defaultTemplate.title,
description: defaultTemplate.description,
category: defaultTemplate.category,
difficulty: defaultTemplate.difficulty,
steps,
currentStepIndex: 0,
progress: 0,
totalWeeks: defaultTemplate.totalWeeks,
startedAt: new Date(),
});
}
res.status(200).json({
success: true,
data: learningPath,
});
} catch (error) {
next(error);
}
};
// @desc Update checklist item completion
// @route PUT /api/learning-path/checklist/:stepIndex/:itemId
// @access Private
export const updateChecklistItem = async (
req: AuthRequest,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const { stepIndex, itemId } = req.params;
const { completed } = req.body;
const userId = req.user?._id;
const learningPath = await LearningPath.findOne({ userId }).sort({ updatedAt: -1 });
if (!learningPath) {
res.status(404).json({ success: false, error: 'Learning path not found' });
return;
}
const idx = parseStepIndex(stepIndex, learningPath.steps.length);
if (idx === null) {
res.status(400).json({ success: false, error: 'Invalid step index' });
return;
}
const step = learningPath.steps[idx];
// Find and update the checklist item
const checklistItem = step.checklist?.find((item: { id: string }) => item.id === itemId);
if (checklistItem) {
checklistItem.completed = completed;
checklistItem.completedAt = completed ? new Date() : undefined;
}
// Check if all required items in step are completed
const requiredItems = step.checklist?.filter((item: { isRequired: boolean }) => item.isRequired) || [];
const completedRequired = requiredItems.filter((item: { completed: boolean }) => item.completed).length;
step.completed = completedRequired === requiredItems.length && requiredItems.length > 0;
// Recalculate overall progress
const completedSteps = learningPath.steps.filter(s => s.completed).length;
learningPath.progress = Math.round((completedSteps / learningPath.steps.length) * 100);
// Auto-advance to next step if current is complete
if (step.completed && learningPath.currentStepIndex === idx) {
learningPath.currentStepIndex = Math.min(
learningPath.currentStepIndex + 1,
learningPath.steps.length - 1
);
}
await learningPath.save();
// Update user progress with study time
if (completed && checklistItem) {
const progress = await Progress.findOne({ userId });
if (progress) {
progress.studyTime.push({
day: new Date().toLocaleDateString('en-US', { weekday: 'short' }),
hours: checklistItem.estimatedHours || 0.5,
topicId: step.moduleId,
date: new Date(),
});
progress.totalStudyHours = (progress.totalStudyHours || 0) + (checklistItem.estimatedHours || 0.5);
await progress.save();
}
}
res.status(200).json({
success: true,
data: {
step,
overallProgress: learningPath.progress,
currentStepIndex: learningPath.currentStepIndex,
},
});
} catch (error) {
next(error);
}
};
// @desc Mark entire step as complete
// @route PUT /api/learning-path/step/:stepIndex/complete
// @access Private
export const completeStep = async (
req: AuthRequest,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const { stepIndex } = req.params;
const userId = req.user?._id;
const learningPath = await LearningPath.findOne({ userId }).sort({ updatedAt: -1 });
if (!learningPath) {
res.status(404).json({ success: false, error: 'Learning path not found' });
return;
}
const idx = parseStepIndex(stepIndex, learningPath.steps.length);
if (idx === null) {
res.status(400).json({ success: false, error: 'Invalid step index' });
return;
}
const step = learningPath.steps[idx];
// Mark step and all checklist items as complete
step.completed = true;
step.completedAt = new Date();
if (step.checklist) {
step.checklist.forEach((item: { completed: boolean; completedAt?: Date }) => {
item.completed = true;
item.completedAt = new Date();
});
}
// Recalculate progress
const completedSteps = learningPath.steps.filter(s => s.completed).length;
learningPath.progress = Math.round((completedSteps / learningPath.steps.length) * 100);
// Advance to next step
if (learningPath.currentStepIndex === idx) {
learningPath.currentStepIndex = Math.min(
learningPath.currentStepIndex + 1,
learningPath.steps.length - 1
);
}
await learningPath.save();
res.status(200).json({
success: true,
data: learningPath,
});
} catch (error) {
next(error);
}
};
// @desc Adjust learning path based on quiz performance
// @route POST /api/learning-path/adjust
// @access Private
export const adjustLearningPath = async (
req: AuthRequest,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const { quizTopic, score } = req.body;
const userId = req.user?._id;
const learningPath = await LearningPath.findOne({ userId }).sort({ updatedAt: -1 });
if (!learningPath) {
res.status(404).json({ success: false, error: 'Learning path not found' });
return;
}
const adjustments: string[] = [];
if (score >= 90) {
// High performers can skip related steps
const relatedSteps = learningPath.steps.filter(
(step, idx) =>
step.quizTopic === quizTopic &&
!step.completed &&
idx > learningPath.currentStepIndex
);
if (relatedSteps.length > 0) {
// Mark beginner steps as complete for high scorers
for (const step of relatedSteps.slice(0, 1)) {
const stepIdx = learningPath.steps.indexOf(step);
learningPath.steps[stepIdx].completed = true;
learningPath.steps[stepIdx].completedAt = new Date();
learningPath.steps[stepIdx].skippedDueToMastery = true;
adjustments.push(`Skipped "${step.title}" - mastery demonstrated`);
}
}
} else if (score < 60) {
// Low performers need reinforcement - add review items
const currentStep = learningPath.steps[learningPath.currentStepIndex];
if (currentStep && currentStep.quizTopic === quizTopic) {
currentStep.needsReview = true;
adjustments.push(`Added review materials for ${quizTopic}`);
}
}
// Recalculate progress
const completedSteps = learningPath.steps.filter(s => s.completed).length;
learningPath.progress = Math.round((completedSteps / learningPath.steps.length) * 100);
await learningPath.save();
res.status(200).json({
success: true,
data: {
adjustments,
progress: learningPath.progress,
currentStep: learningPath.steps[learningPath.currentStepIndex],
},
});
} catch (error) {
next(error);
}
};
// @desc Get learning path recommendations based on progress
// @route GET /api/learning-path/recommendations
// @access Private
export const getPathRecommendations = async (
req: AuthRequest,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const userId = req.user?._id;
const progress = await Progress.findOne({ userId });
const learningPath = await LearningPath.findOne({ userId }).sort({ updatedAt: -1 });
const recommendations: {
type: 'next_step' | 'review' | 'quiz' | 'new_path';
title: string;
description: string;
priority: 'high' | 'medium' | 'low';
action?: { type: string; data: unknown };
}[] = [];
if (learningPath) {
const currentStep = learningPath.steps[learningPath.currentStepIndex];
// Next step recommendation
if (currentStep && !currentStep.completed) {
const incompleteItems = currentStep.checklist?.filter(
(item: { completed: boolean; isRequired: boolean }) => !item.completed && item.isRequired
) || [];
recommendations.push({
type: 'next_step',
title: `Continue: ${currentStep.title}`,
description: `${incompleteItems.length} items remaining`,
priority: 'high',
action: { type: 'navigate', data: { stepIndex: learningPath.currentStepIndex } },
});
}
// Quiz recommendation if step has quiz topic
if (currentStep?.quizTopic) {
const quizScoresForTopic = progress?.quizScores.filter(
qs => qs.quizId?.toString().includes(currentStep.quizTopic?.toLowerCase() || '')
) || [];
if (quizScoresForTopic.length === 0) {
recommendations.push({
type: 'quiz',
title: `Take ${currentStep.quizTopic} Quiz`,
description: 'Test your knowledge before moving on',
priority: 'medium',
action: { type: 'navigate', data: { route: '/quiz', topic: currentStep.quizTopic } },
});
}
}
// Review weak areas
if (progress?.weakAreas && progress.weakAreas.length > 0) {
recommendations.push({
type: 'review',
title: 'Review Weak Areas',
description: `Focus on: ${progress.weakAreas.slice(0, 3).join(', ')}`,
priority: 'medium',
action: { type: 'navigate', data: { route: '/analytics', tab: 'topics' } },
});
}
// Suggest new path if close to completion
if (learningPath.progress >= 80) {
const otherPaths = allLearningPaths.filter(p => p.title !== learningPath.title);
if (otherPaths.length > 0) {
recommendations.push({
type: 'new_path',
title: `Consider: ${otherPaths[0].title}`,
description: 'You are almost done! Explore other tracks.',
priority: 'low',
action: { type: 'navigate', data: { route: '/learning-path', templateId: otherPaths[0].id } },
});
}
}
}
res.status(200).json({
success: true,
data: recommendations,
});
} catch (error) {
next(error);
}
};
|