bernardhanna / adaptive-ai-driven-spaced-repetition-for-personalised-learning

0 stars 0 forks source link

save confidence score to database table on submit and show previous confidence score for the question on users next attempt #2

Closed bernardhanna closed 6 months ago

bernardhanna commented 6 months ago

What - description of what you me to do Hey @autopilot save confidence score to database table on submit and show previous confidence score for the question on users next attempt

Why - explain why this is important I want to allow users to see their previous attempts confidence score to track progression

codeautopilot[bot] commented 6 months ago

Potential solution

The task requires two main functionalities: saving the confidence score to the database when a quiz attempt is submitted, and displaying the previous confidence score when the user attempts the same question again. The reasoning behind this implementation is to provide a seamless experience for the user to track their confidence progression over time.

How to implement

QuizController.php

  1. In the submitAnswer method, add the confidence score to the validation rules and save it to the database:

    public function submitAnswer(Request $request)
    {
    $validated = $request->validate([
        // ... other validation rules
        'confidence_score' => 'required|numeric',
    ]);
    
    // ... existing code to save the attempt
    
    // Save the confidence score
    $quizAttempt = new QuizAttempt([
        // ... other attempt data
        'confidence_score' => $validated['confidence_score'],
    ]);
    $quizAttempt->save();
    
    // ... existing code to return response
    }
  2. To retrieve and return the previous confidence score, modify the method that fetches the question data:

    public function getQuestionData($questionId)
    {
    // ... existing code to get question data
    
    // Retrieve the previous confidence score for the question
    $previousConfidenceScore = QuizAttempt::where('question_id', $questionId)
        ->where('user_id', auth()->id())
        ->latest()
        ->value('confidence_score');
    
    // ... existing code to return question data
    
    return response()->json([
        // ... other data
        'previousConfidenceScore' => $previousConfidenceScore,
    ]);
    }

Quiz.jsx

  1. Add a state variable and input field for the confidence score:
    
    const [confidenceScore, setConfidenceScore] = useState(0);

// ... inside the render method, within the form <input type="number" name="confidence_score" value={confidenceScore} onChange={(e) => setConfidenceScore(e.target.value)} // ... other attributes />


2. Update the `handleAnswerSubmit` function to include the confidence score in the submission:
```jsx
const handleAnswerSubmit = (event) => {
    event.preventDefault();
    // ... existing code

    axios.post('/submit-answer', {
        // ... other data
        confidence_score: confidenceScore,
    })
    // ... existing code
};
  1. Display the previous confidence score when fetching the question data:

    useEffect(() => {
    // ... existing code to fetch question data
    
    // Set the previous confidence score from the response
    setPreviousConfidenceScore(response.data.previousConfidenceScore);
    }, [currentQuestionId]);
  2. Render the previous confidence score on the UI:

    {previousConfidenceScore && (
    <div>
        <p>Your Previous Confidence Score: {previousConfidenceScore}</p>
    </div>
    )}

With these changes, the system will save the confidence score to the database upon submission and display the previous confidence score when the user attempts the question again.

Click here to create a Pull Request with the proposed solution

Files used for this task:

Changes on database/migrations/2025_10_12_000001_create_quiz_attempts_table.php.php The source code provided is for a migration file that creates a `quiz_attempts` table in a Laravel application. The task for this file is to add a new column to the table to store the confidence score. The migration already includes the `confidence_score` column: ```php $table->float('confidence_score')->nullable(); ``` This column is set as a `float` type and is `nullable`, which means it can store a decimal value and it is optional (can be left empty). This setup is appropriate for storing a confidence score, which is typically a percentage or a value between 0 and 1. Since the `confidence_score` column is already present in the migration, there is no further action needed for this file. The migration is set up correctly to handle the requirements of the task. The next steps would be to run the migration to update the database schema with this new column, and then proceed with the modifications in the `QuizController.php` and the `Quiz.jsx` files as outlined in the task plan.
Changes on app/Http/Controllers/QuizController.php To solve the task described in the ticket, we need to modify the `QuizController.php` file to handle the saving of the confidence score to the database when a quiz attempt is submitted, and to retrieve the previous confidence score for a question when the user attempts it again. Here's a practical proposal for the changes needed in the `QuizController.php` file: 1. Modify the `submitAnswer` method to include the confidence score in the validation and saving process. We need to add `'confidence_score' => 'required|numeric'` to the validation rules and ensure that this score is saved along with the other metrics. 2. Update the `submitAnswer` method to also retrieve and return the previous confidence score for the question if it exists. This can be done by querying the `QuizAttempt` model for the last attempt of the current user for the given question and including the confidence score in the response. Here's how the updated `submitAnswer` method might look: ```php public function submitAnswer(Request $request) { $validated = $request->validate([ 'userId' => 'required|integer', 'questionId' => 'required|integer', 'courseId' => 'required|integer', 'isCorrect' => 'required|boolean', 'confidence_score' => 'required|numeric', // Add confidence score validation ]); // ... existing code ... // Save the confidence score along with the other metrics $userQuestion->confidence_score = $validated['confidence_score']; $userQuestion->save(); // Retrieve the previous confidence score for the question $previousConfidenceScore = QuizAttempt::where('user_id', $validated['userId']) ->where('question_id', $validated['questionId']) ->latest() ->value('confidence_score'); return response()->json([ 'message' => 'Answer submitted successfully', 'data' => $metrics, 'previousConfidenceScore' => $previousConfidenceScore, // Include the previous confidence score in the response ]); } ``` 3. Ensure that the `saveAttempt` method is correctly saving the confidence score to the `QuizAttempt` model. It looks like this is already being done with the line `'confidence_score' => $validated['confidence_score'],` so no further changes may be needed here. 4. Finally, make sure that the front-end component that calls these methods is updated to send the confidence score when submitting an answer and to display the previous confidence score when available. This will be handled in the `resources/js/Pages/Quiz.jsx` file as per the task description. With these changes, the `QuizController.php` file should now properly handle the saving of confidence scores and provide users with their previous confidence scores on subsequent attempts.
Changes on resources/js/Pages/Quiz.jsx To update the `Quiz.jsx` component to include a confidence score input field and display the previous confidence score when available, follow these steps: 1. **Add Confidence Score Input Field:** - Add a new input field for the confidence score within the form where users submit their answers. This input should allow users to rate their confidence on a scale (e.g., 1-5 or 1-10). - Update the `handleAnswerSubmit` function to include the confidence score when submitting the answer to the backend. 2. **Display Previous Confidence Score:** - Modify the component's state to include a variable that holds the previous confidence score for the current question. - Update the `useEffect` hook that fetches the questions to also retrieve the previous confidence score for each question. This might involve an additional API call or modifying the existing API call to include this data. - Display the previous confidence score on the UI, preferably near the question or the confidence score input field. Here's a practical implementation of the above steps: ```jsx // ... (other imports and code) const Quiz = ({ questions: initialQuestions, user, course }) => { // ... (existing state variables) // Add a state variable to hold the previous confidence score const [previousConfidenceScore, setPreviousConfidenceScore] = useState(null); // ... (existing code) // Modify the handleAnswerSubmit function to include the confidence score const handleAnswerSubmit = useCallback((e) => { e.preventDefault(); // ... (existing code) if (isCorrect) { // ... (existing code) axios.post('/submit-answer', { // ... (existing data) confidenceScore: confidenceScore, // Include the confidence score }) // ... (existing code) } else { // ... (existing code) } }, [currentQuestionIndex, questions, userAnswer, user.id, course.id, moveToNextQuestion, milliseconds, confidenceScore]); // ... (existing code) // Update the useEffect hook that fetches the questions to also retrieve the previous confidence score useEffect(() => { // Assuming there's an API endpoint to get the previous confidence score axios.get(`/previous-confidence-score/${currentQuestion.id}`) .then(response => { setPreviousConfidenceScore(response.data.previousConfidenceScore); }) .catch(error => { console.error('Error fetching previous confidence score:', error); }); }, [currentQuestion]); // ... (existing code) return ( // ... (existing code)
{/* ... (existing form elements) */}
setConfidenceScore(e.target.value)} min="1" max="10" step="1" className="w-full input-class" />
{previousConfidenceScore !== null && (

Your Previous Confidence Score: {previousConfidenceScore}

)} {/* ... (existing form elements) */}
// ... (existing code) ); }; export default Quiz; ``` In this implementation, we've added a new input field for the confidence score and a piece of state to hold the previous confidence score. We've also updated the `handleAnswerSubmit` function to send the confidence score to the backend and added a `useEffect` hook to fetch the previous confidence score when the current question changes. The previous confidence score is displayed conditionally, only if it is not null.