All files / learning learning.service.ts

85.71% Statements 114/133
66.91% Branches 89/133
81.81% Functions 9/11
88.09% Lines 111/126

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3851x 1x 1x 1x                                       1x     1x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x                       2x 2x 2x     2x 2x     2x           2x 1x     1x                   1x     1x                     1x     1x                     1x                           1x 1x 1x 1x   1x           1x     1x 1x 1x   1x 1x 1x 1x       1x 1x     1x 1x 1x         1x 1x               1x 1x 1x 1x     1x       1x       1x 1x 1x   1x           1x 1x 1x 1x     1x 1x         1x     1x                                         1x 1x 1x   1x 1x   1x 1x   1x 1x 2x 2x 2x   2x   2x 3x   2x 2x         1x 1x   1x                   1x     1x 1x     1x                                             1x                                                                                                           1x 1x   1x 1x 1x               1x 1x               1x 1x      
import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import {
  LearningConfiguration,
  LearningCatalog,
  LearningCategory,
  Course,
  CourseVersion,
  CourseModule,
  CourseLesson,
  CourseEnrolment,
  LearnerCourseProgress,
  AssessmentQuestionBank,
  AssessmentQuestion,
  LearningAssessment,
  AssessmentAttempt,
  EmployeeCertification,
  ComplianceTrainingDefinition,
  ComplianceWaiver,
  LearningBadge,
  LearnerPoint
} from './schemas';
import { EventBusService } from '../../platform/events/event-bus.service';
 
@Injectable()
export class LearningService {
  constructor(
    @InjectModel(LearningConfiguration.name) private configModel: Model<LearningConfiguration>,
    @InjectModel(LearningCatalog.name) private catalogModel: Model<LearningCatalog>,
    @InjectModel(LearningCategory.name) private categoryModel: Model<LearningCategory>,
    @InjectModel(Course.name) private courseModel: Model<Course>,
    @InjectModel(CourseVersion.name) private courseVersionModel: Model<CourseVersion>,
    @InjectModel(CourseModule.name) private moduleModel: Model<CourseModule>,
    @InjectModel(CourseLesson.name) private lessonModel: Model<CourseLesson>,
    @InjectModel(CourseEnrolment.name) private enrolmentModel: Model<CourseEnrolment>,
    @InjectModel(LearnerCourseProgress.name) private progressModel: Model<LearnerCourseProgress>,
    @InjectModel(AssessmentQuestionBank.name) private questionBankModel: Model<AssessmentQuestionBank>,
    @InjectModel(AssessmentQuestion.name) private questionModel: Model<AssessmentQuestion>,
    @InjectModel(LearningAssessment.name) private assessmentModel: Model<LearningAssessment>,
    @InjectModel(AssessmentAttempt.name) private attemptModel: Model<AssessmentAttempt>,
    @InjectModel(EmployeeCertification.name) private certificationModel: Model<EmployeeCertification>,
    @InjectModel(ComplianceTrainingDefinition.name) private complianceModel: Model<ComplianceTrainingDefinition>,
    @InjectModel(ComplianceWaiver.name) private waiverModel: Model<ComplianceWaiver>,
    @InjectModel(LearningBadge.name) private badgeModel: Model<LearningBadge>,
    @InjectModel(LearnerPoint.name) private pointModel: Model<LearnerPoint>,
    private readonly eventBus: EventBusService
  ) {}
 
  // ----------------------------------------------------
  // 1. Enrolment Engine
  // ----------------------------------------------------
  async enrolInCourse(
    tenantId: string,
    employeeId: string,
    courseId: string,
    source: string = 'self'
  ): Promise<CourseEnrolment> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const employeeObjId = new Types.ObjectId(employeeId);
    const courseObjId = new Types.ObjectId(courseId);
 
    // Verify course exists
    const course = await this.courseModel.findOne({ _id: courseObjId, tenantId: tenantObjId }).exec();
    Iif (!course) throw new BadRequestException('Course not found');
 
    // Prevent duplicate enrolments
    const existing = await this.enrolmentModel.findOne({
      tenantId: tenantObjId,
      employeeId: employeeObjId,
      courseId: courseObjId
    }).exec();
 
    if (existing) {
      return existing; // idempotent check
    }
 
    const enrolment = new this.enrolmentModel({
      tenantId: tenantObjId,
      employeeId: employeeObjId,
      courseId: courseObjId,
      status: 'enrolled',
      enrolmentSource: source,
      enrolmentDate: new Date(),
      deadline: new Date(Date.now() + (course.validityDays || 365) * 24 * 60 * 60 * 1000)
    });
 
    const savedEnrolment = await enrolment.save();
 
    // Create associated progress entry
    const progress = new this.progressModel({
      tenantId: tenantObjId,
      enrolmentId: savedEnrolment._id,
      courseId: courseObjId,
      employeeId: employeeObjId,
      completionPercentage: 0,
      completedLessons: [],
      lessonTimeSpentSeconds: {},
      lastMediaPlaybackPositions: {},
      lastAccessedAt: new Date()
    });
    await progress.save();
 
    // Publish event via transactional outbox
    await this.eventBus.publish(
      'learning.enrolment.created.v1',
      {
        enrolmentId: savedEnrolment._id.toString(),
        employeeId: employeeId,
        courseId: courseId,
        source
      },
      tenantId
    );
 
    return savedEnrolment;
  }
 
  // ----------------------------------------------------
  // 2. Learner Progress Engine
  // ----------------------------------------------------
  async recordLessonProgress(
    tenantId: string,
    employeeId: string,
    courseId: string,
    lessonId: string,
    timeSpentSeconds: number,
    playbackPosition?: number
  ): Promise<LearnerCourseProgress> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const employeeObjId = new Types.ObjectId(employeeId);
    const courseObjId = new Types.ObjectId(courseId);
    const lessonObjId = new Types.ObjectId(lessonId);
 
    const progress = await this.progressModel.findOne({
      tenantId: tenantObjId,
      employeeId: employeeObjId,
      courseId: courseObjId
    }).exec();
 
    Iif (!progress) throw new BadRequestException('Enrolment progress record not found');
 
    // Update lesson time spent safely
    const times = progress.lessonTimeSpentSeconds || {};
    times[lessonId] = (times[lessonId] || 0) + timeSpentSeconds;
    progress.lessonTimeSpentSeconds = times;
 
    Eif (playbackPosition !== undefined) {
      const positions = progress.lastMediaPlaybackPositions || {};
      positions[lessonId] = playbackPosition;
      progress.lastMediaPlaybackPositions = positions;
    }
 
    // Toggle completed status if not already completed
    Eif (!progress.completedLessons.includes(lessonObjId)) {
      progress.completedLessons.push(lessonObjId);
 
      // Find total lessons in the modules to rollup completion percentage
      const modules = await this.moduleModel.find({ tenantId: tenantObjId, courseId: courseObjId }).exec();
      const moduleIds = modules.map(m => m._id);
      const totalLessonsCount = await this.lessonModel.countDocuments({
        tenantId: tenantObjId,
        moduleId: { $in: moduleIds }
      }).exec();
 
      if (totalLessonsCount > 0) {
        progress.completionPercentage = Math.round(
          (progress.completedLessons.length / totalLessonsCount) * 100
        );
      } else E{
        progress.completionPercentage = 100;
      }
    }
 
    progress.lastAccessedAt = new Date();
    progress.markModified('lessonTimeSpentSeconds');
    progress.markModified('lastMediaPlaybackPositions');
    const savedProgress = await progress.save();
 
    // Check if course completed
    Iif (savedProgress.completionPercentage >= 100) {
      await this.completeCourseEnrolment(tenantId, employeeId, courseId);
    }
 
    return savedProgress;
  }
 
  private async completeCourseEnrolment(tenantId: string, employeeId: string, courseId: string): Promise<void> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const employeeObjId = new Types.ObjectId(employeeId);
    const courseObjId = new Types.ObjectId(courseId);
 
    const enrolment = await this.enrolmentModel.findOne({
      tenantId: tenantObjId,
      employeeId: employeeObjId,
      courseId: courseObjId
    }).exec();
 
    Eif (enrolment && enrolment.status !== 'completed') {
      enrolment.status = 'completed';
      enrolment.completionDate = new Date();
      await enrolment.save();
 
      // Issue Certificate if enabled
      const course = await this.courseModel.findById(courseObjId).exec();
      Iif (course && course.certificateEnabled) {
        await this.generateCertificate(tenantId, employeeId, courseId);
      }
 
      // Award Gamification Points
      await this.awardPoints(tenantId, employeeId, 100);
 
      // Publish event
      await this.eventBus.publish(
        'learning.course.completed.v1',
        {
          enrolmentId: enrolment._id.toString(),
          employeeId: employeeId,
          courseId: courseId
        },
        tenantId
      );
    }
  }
 
  // ----------------------------------------------------
  // 3. Quiz & Assessment Evaluator
  // ----------------------------------------------------
  async gradeAssessmentAttempt(
    tenantId: string,
    employeeId: string,
    assessmentId: string,
    answersSubmitted: Record<string, number[]>
  ): Promise<AssessmentAttempt> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const employeeObjId = new Types.ObjectId(employeeId);
    const assessmentObjId = new Types.ObjectId(assessmentId);
 
    const assessment = await this.assessmentModel.findById(assessmentObjId).populate('questionsList').exec();
    Iif (!assessment) throw new BadRequestException('Assessment profile not found');
 
    let totalPoints = 0;
    let earnedPoints = 0;
 
    const questions = assessment.questionsList as unknown as AssessmentQuestion[];
    for (const q of questions) {
      totalPoints += q.points || 10;
      const submitted = answersSubmitted[q._id.toString()];
      Eif (submitted) {
        // Enforce exact matching correct indexes
        const correct = q.correctOptionIndexes || [];
        const isCorrect =
          submitted.length === correct.length &&
          submitted.every(idx => correct.includes(idx));
 
        Eif (isCorrect) {
          earnedPoints += q.points || 10;
        }
      }
    }
 
    const scorePct = totalPoints > 0 ? Math.round((earnedPoints / totalPoints) * 100) : 0;
    const passed = scorePct >= (assessment.passingScorePercentage || 80);
 
    const attempt = new this.attemptModel({
      tenantId: tenantObjId,
      assessmentId: assessmentObjId,
      employeeId: employeeObjId,
      answersSubmitted,
      scorePercentage: scorePct,
      passed,
      status: 'completed'
    });
 
    const savedAttempt = await attempt.save();
 
    // Trigger complete course if assessment is passed and enrolment is active
    if (passed) {
      await this.completeCourseEnrolment(tenantId, employeeId, assessment.courseId.toString());
      
      // Publish event
      await this.eventBus.publish(
        'learning.assessment.completed.v1',
        {
          attemptId: savedAttempt._id.toString(),
          employeeId,
          assessmentId,
          scorePercentage: scorePct
        },
        tenantId
      );
    } else E{
      await this.eventBus.publish(
        'learning.assessment.failed.v1',
        {
          attemptId: savedAttempt._id.toString(),
          employeeId,
          assessmentId,
          scorePercentage: scorePct
        },
        tenantId
      );
    }
 
    return savedAttempt;
  }
 
  // ----------------------------------------------------
  // 4. Certification Engine
  // ----------------------------------------------------
  async generateCertificate(
    tenantId: string,
    employeeId: string,
    courseId: string
  ): Promise<EmployeeCertification> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const employeeObjId = new Types.ObjectId(employeeId);
    const courseObjId = new Types.ObjectId(courseId);
 
    const course = await this.courseModel.findById(courseObjId).exec();
    if (!course) throw new BadRequestException('Course not found');
 
    const token = `verify_${tenantId}_${employeeId}_${courseId}_${Date.now()}`;
 
    const cert = new this.certificationModel({
      tenantId: tenantObjId,
      employeeId: employeeObjId,
      courseId: courseObjId,
      certificateName: `${course.title} - Professional Certificate`,
      verificationToken: token,
      issuedAt: new Date(),
      expiresAt: new Date(Date.now() + (course.validityDays || 365) * 24 * 60 * 60 * 1000),
      status: 'active'
    });
 
    const savedCert = await cert.save();
 
    await this.eventBus.publish(
      'learning.certification.issued.v1',
      {
        certificateId: savedCert._id.toString(),
        employeeId,
        verificationToken: token
      },
      tenantId
    );
 
    return savedCert;
  }
 
  async verifyPublicCertificate(token: string): Promise<EmployeeCertification | null> {
    return this.certificationModel.findOne({ verificationToken: token, status: 'active' }).exec();
  }
 
  // ----------------------------------------------------
  // 5. Gamification Rewards
  // ----------------------------------------------------
  async awardPoints(tenantId: string, employeeId: string, pts: number): Promise<LearnerPoint> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const employeeObjId = new Types.ObjectId(employeeId);
 
    let rec = await this.pointModel.findOne({ tenantId: tenantObjId, employeeId: employeeObjId }).exec();
    Eif (!rec) {
      rec = new this.pointModel({
        tenantId: tenantObjId,
        employeeId: employeeObjId,
        pointsBalance: 0,
        currentStreakDays: 1
      });
    }
 
    rec.pointsBalance += pts;
    return rec.save();
  }
 
  // ----------------------------------------------------
  // 6. Security Media Signatures
  // ----------------------------------------------------
  async getSecureContentUrl(tenantId: string, fileKey: string): Promise<string> {
    // Generate secure expiring signature. Never expose raw local VPS file paths directly.
    const expires = Date.now() + 15 * 60 * 1000; // 15 mins expiry
    return `https://vps-storage.bevision.internal/files/${fileKey}?tenantId=${tenantId}&expires=${expires}&signature=sha256_mock_sig`;
  }
}