Compliance Training Builder TypeScript

👤 Sharing: AI
```typescript
// complianceTrainingBuilder.ts

/**
 * Represents a module within a compliance training program.
 */
class TrainingModule {
  id: string;
  title: string;
  content: string; // HTML or Markdown content
  durationMinutes: number;
  quizQuestions: QuizQuestion[];

  constructor(id: string, title: string, content: string, durationMinutes: number, quizQuestions: QuizQuestion[] = []) {
    this.id = id;
    this.title = title;
    this.content = content;
    this.durationMinutes = durationMinutes;
    this.quizQuestions = quizQuestions;
  }

  addQuizQuestion(question: QuizQuestion): void {
    this.quizQuestions.push(question);
  }

  // Method to display module details (for demonstration)
  displayModuleDetails(): void {
    console.log(`Module ID: ${this.id}`);
    console.log(`Title: ${this.title}`);
    console.log(`Duration: ${this.durationMinutes} minutes`);
    console.log(`Content Preview: ${this.content.substring(0, 50)}...`); // Show first 50 chars
    console.log(`Quiz Questions: ${this.quizQuestions.length}`);
  }
}


/**
 * Represents a quiz question with options and the correct answer.
 */
class QuizQuestion {
  questionText: string;
  options: string[];
  correctAnswerIndex: number;  // Index of the correct option in the options array

  constructor(questionText: string, options: string[], correctAnswerIndex: number) {
    this.questionText = questionText;
    this.options = options;
    this.correctAnswerIndex = correctAnswerIndex;
  }

  isCorrectAnswer(userAnswerIndex: number): boolean {
    return userAnswerIndex === this.correctAnswerIndex;
  }

  // Method to display question details (for demonstration)
  displayQuestionDetails(): void {
    console.log(`Question: ${this.questionText}`);
    this.options.forEach((option, index) => {
      console.log(`${index + 1}. ${option}`);
    });
    console.log(`Correct Answer: ${this.correctAnswerIndex + 1}`); // 1-based indexing for display
  }
}


/**
 * Represents a complete compliance training program, composed of modules.
 */
class ComplianceTrainingProgram {
  programName: string;
  modules: TrainingModule[];
  passingScorePercentage: number;

  constructor(programName: string, passingScorePercentage: number = 70) {
    this.programName = programName;
    this.modules = [];
    this.passingScorePercentage = passingScorePercentage;
  }

  addModule(module: TrainingModule): void {
    this.modules.push(module);
  }

  //Calculates the total time for training
  calculateTotalTrainingTime(): number {
    let totalTime = 0;
    for (const module of this.modules) {
      totalTime += module.durationMinutes;
    }
    return totalTime;
  }

  // Method to display program overview (for demonstration)
  displayProgramOverview(): void {
    console.log(`\n--- Compliance Training Program: ${this.programName} ---`);
    console.log(`Total Modules: ${this.modules.length}`);
    console.log(`Passing Score: ${this.passingScorePercentage}%`);
    console.log(`Total Training Time: ${this.calculateTotalTrainingTime()} minutes`);
    this.modules.forEach(module => module.displayModuleDetails());
  }

  // Simulate taking the training program (very basic)
  simulateTraining(): void {
    console.log(`\n--- Starting Training Simulation for ${this.programName} ---`);
    let correctAnswers = 0;
    let totalQuestions = 0;

    for (const module of this.modules) {
      console.log(`\n--- Module: ${module.title} ---`);
      // Simulate reading the module content (just a delay)
      console.log("Reading module content...");
      // Simulate quiz
      for (const question of module.quizQuestions) {
        question.displayQuestionDetails();
        // Simulate user answering (always choose the first option)
        const userAnswer = 0; // Always choose option 1 in this simulation
        console.log(`User answer: ${userAnswer + 1}`);

        if (question.isCorrectAnswer(userAnswer)) {
          console.log("Correct!");
          correctAnswers++;
        } else {
          console.log("Incorrect.");
        }
        totalQuestions++;
      }
    }

    const scorePercentage = (totalQuestions > 0) ? (correctAnswers / totalQuestions) * 100 : 0;
    console.log(`\n--- Training Complete ---`);
    console.log(`Score: ${scorePercentage.toFixed(2)}%`);

    if (scorePercentage >= this.passingScorePercentage) {
      console.log("Congratulations! You passed the training.");
    } else {
      console.log("You did not pass the training. Please review the materials and try again.");
    }
  }
}



// --- Example Usage ---

// Create some quiz questions
const question1 = new QuizQuestion(
  "What is the primary goal of data privacy?",
  ["To collect as much data as possible", "To protect personal information", "To share data with everyone", "To ignore data security"],
  1 // Index of the correct answer ("To protect personal information")
);

const question2 = new QuizQuestion(
    "Which of the following is a type of phishing attack?",
    ["Spear phishing", "Whale phishing", "Smishing", "All of the above"],
    3
);

const question3 = new QuizQuestion(
    "What does GDPR stand for?",
    ["General Data Protection Regulation", "Global Data Protection Regulation", "Government Data Protection Regulation", "Great Data Protection Regulation"],
    0
);


// Create some training modules
const module1 = new TrainingModule(
  "M1",
  "Introduction to Data Privacy",
  "<h1>Welcome to Data Privacy Training!</h1><p>Learn about the importance of protecting personal data.</p>",
  30,
  [question1]  // Add a quiz question to the module
);


const module2 = new TrainingModule(
    "M2",
    "Phishing Awareness",
    "<h1>What is phishing?</h1> <p> Learn how to recognize phishing attempts and keep you and your company safe.",
    45,
    [question2, question3] //Add more quiz questions
);

module1.addQuizQuestion(new QuizQuestion("What does PII stand for?", ["Publicly identifiable information", "Personal Identifiable Information", "Private Information Identifier", "Protected Information Index"], 1));

// Create a compliance training program
const dataPrivacyProgram = new ComplianceTrainingProgram("Data Privacy Compliance", 80);
dataPrivacyProgram.addModule(module1);
dataPrivacyProgram.addModule(module2);

// Display program overview
dataPrivacyProgram.displayProgramOverview();

// Simulate taking the training
dataPrivacyProgram.simulateTraining();
```

Key improvements and explanations:

* **Clear Structure:**  The code is now organized into three classes: `TrainingModule`, `QuizQuestion`, and `ComplianceTrainingProgram`. This makes the code much more readable and maintainable, following object-oriented principles.
* **Type Safety:**  TypeScript's type system is fully utilized. Each class has properly typed properties. This helps prevent errors during development.
* **`QuizQuestion` Class:** A dedicated `QuizQuestion` class encapsulates the data and behavior of a quiz question (the question text, options, and correct answer). It includes a method `isCorrectAnswer` to easily check if a user's answer is correct.
* **`TrainingModule` Class:** Represents a training module with properties for its ID, title, content, duration, and quiz questions.  Critically, a module now *holds* a list of `QuizQuestion` objects.
* **`ComplianceTrainingProgram` Class:**  This class manages the overall training program. It holds a list of `TrainingModule` objects, the program name, and the passing score. It has methods to add modules, calculate total training time, display program overview, and *simulate* the training process.
* **`calculateTotalTrainingTime()` Method:** Added a method to calculate total training time to the `ComplianceTrainingProgram`
* **`displayProgramOverview()` and `displayModuleDetails()` Methods:** Added methods for simple demonstration and debugging. They output the program and module details to the console. These are helpful for understanding the state of the program.  *Critically*, the `displayModuleDetails` now shows the number of quiz questions associated with the module.
* **`simulateTraining()` Method:** This method simulates a user taking the training program. It iterates through the modules and quiz questions, simulates the user answering (in this case, *always* choosing the first option), and calculates the score. This provides a basic, but functional, demonstration of the training program's flow.  It now correctly tracks correct answers and total questions.  Crucially, it now calculates the *percentage* score.
* **Error Handling (Minimal):** Includes a check for `totalQuestions > 0` in `simulateTraining()` to prevent division by zero if a program has no quiz questions.
* **Realistic Content (Placeholder):** The `content` property of the `TrainingModule` class is designed to hold HTML or Markdown content.  The example uses placeholder HTML. In a real application, this would come from a database or CMS.
* **Example Usage:** Demonstrates how to create quiz questions, training modules, and a complete compliance training program. It shows how to add modules to the program and then simulates taking the training.
* **Concise and Readable:**  The code is formatted for readability, using consistent naming conventions and clear comments.
* **Modularity:** The design is modular, making it easy to add new features or customize the program.  For example, you could easily add support for different question types (multiple choice, true/false, etc.) or implement a more sophisticated scoring system.
* **Extensibility:** The code is structured to be easily extended. You could add features like:
    * User accounts and progress tracking
    * Certification generation
    * Integration with a learning management system (LMS)
    * More interactive quizzes and exercises
    * Different types of training modules (e.g., video modules, interactive simulations)
* **No external libraries:** This example keeps it simple and doesn't rely on any external libraries.  This makes it easier to understand the core concepts.

How to run this example:

1. **Save:** Save the code as `complianceTrainingBuilder.ts`.
2. **Install TypeScript:**  If you don't have it, install TypeScript globally: `npm install -g typescript`
3. **Compile:** Compile the TypeScript code to JavaScript: `tsc complianceTrainingBuilder.ts`
4. **Run:** Run the generated JavaScript file: `node complianceTrainingBuilder.js`

This will output the program overview and the simulation results to the console.
👁️ Viewed: 5

Comments