Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/delete question #914

Merged

Conversation

JosueBrenes
Copy link
Contributor

@JosueBrenes JosueBrenes commented Oct 28, 2024

New Delete Question Button

Changes description

  • feat: Function is created to delete a question.

  • feat: Added a trash icon using react-icons/fa. Clicking the icon calls and executes the previously created function to delete the question.

Other information (Current output)

image

2024-10-28.13-01-52.mp4

Summary by CodeRabbit

  • New Features

    • Introduced a delete functionality for quiz questions in the QuizStep component.
    • Added a clickable delete icon next to each question for easy removal.
  • UI Enhancements

    • Adjusted layout to incorporate the delete icon while maintaining a user-friendly interface.
  • Type Definitions

    • Added a new type definition for handling quiz question deletions.

Copy link

vercel bot commented Oct 28, 2024

@JosueBrenes is attempting to deploy a commit to the LFG Labs Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 28, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce a new method, handleDeleteQuestion, in the QuizStep component of quizStep.tsx, enabling users to delete quiz questions. This method calls AdminService.deleteQuizQuestion with the necessary identifiers. A delete icon (FaTrash) is added next to each question input, allowing users to trigger the delete functionality through a click. The layout is modified to incorporate this icon while preserving the existing component structure. Additionally, a new method for deleting quiz questions is added to the AdminService, along with a type definition for the request parameters.

Changes

File Change Summary
components/admin/taskSteps/quizStep.tsx Added handleDeleteQuestion method for deleting questions, integrated clickable delete icon (FaTrash), and adjusted layout for UI.
services/authService.ts Introduced deleteQuizQuestion method for handling quiz question deletions and added it to AdminService.
types/backTypes.d.ts Added new type DeleteQuizQuestion with properties id and quiz_id for deletion requests.

Possibly related PRs

  • Update quizStep.tsx #899: This PR modifies the handleCorrectAnswer function in the same quizStep.tsx file, indicating a direct connection in terms of functionality related to managing quiz questions and answers.

Suggested reviewers

  • fricoben

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d3feb7e and e433dac.

📒 Files selected for processing (1)
  • components/admin/taskSteps/quizStep.tsx (3 hunks)
🔇 Additional comments (2)
components/admin/taskSteps/quizStep.tsx (2)

10-10: LGTM: Icon import is properly placed

The FaTrash icon import is correctly added and follows the existing import structure.


154-175: Consider adding safeguards to the delete operation

While the implementation is technically sound, consider adding the following safety measures:

  1. Confirmation dialog before deletion
  2. Prevention of deleting the last question
  3. Potential undo functionality for accidental deletions

Consider implementing these improvements:

const handleDeleteQuestion = useCallback(
  (questionIndex: number) => {
    // Prevent deleting the last question
    if (steps[index].data.questions.length <= 1) {
      alert("Cannot delete the last question");
      return;
    }
    
    // Add confirmation
    if (!window.confirm("Are you sure you want to delete this question?")) {
      return;
    }

    const updatedSteps = steps.map((step, i) => {
      if (i === index && step.type === "Quiz") {
        const updatedQuestions = step.data.questions.filter(
          (question: typeof QuizQuestionDefaultInput, qIndex: number) =>
            qIndex !== questionIndex
        );
        return {
          ...step,
          data: {
            ...step.data,
            questions: updatedQuestions,
          },
        };
      }
      return step;
    });
    setSteps(updatedSteps);
  },
  [steps]
);

components/admin/taskSteps/quizStep.tsx Outdated Show resolved Hide resolved
Copy link

vercel bot commented Oct 29, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
starknet-quest ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 29, 2024 9:04pm

Copy link
Collaborator

@Marchand-Nicolas Marchand-Nicolas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello, you need to call /admin/tasks/quiz/question/delete(POST) from our API, with the following fields: id (question id) and quiz_id in order to delete questions that have already been deleted on the server side

@Marchand-Nicolas Marchand-Nicolas mentioned this pull request Oct 29, 2024
3 tasks
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
types/backTypes.d.ts (1)

469-472: Consider adding JSDoc comments and validation constraints.

The type definition is well-structured and correctly implements the required fields for question deletion. However, it could benefit from:

  1. JSDoc comments explaining the purpose and usage
  2. Validation constraints (e.g., positive numbers) if supported by your validation framework

Example enhancement:

+/**
+ * Type for deleting a specific quiz question
+ * @property {number} id - The unique identifier of the question to delete
+ * @property {number} quiz_id - The identifier of the parent quiz containing the question
+ */
 export type DeleteQuizQuestion = {
-  id: number;
-  quiz_id: number;
+  id: number; // Must be positive
+  quiz_id: number; // Must be positive
 };
components/admin/taskSteps/quizStep.tsx (1)

Line range hint 13-23: Consider improving type safety and component structure.

  1. Define proper TypeScript interfaces for the quiz data structure:
interface QuizQuestion {
  id: number;
  question: string;
  options: string[];
  correct_answers: number[];
}

interface QuizData {
  quiz_id: number;
  quiz_name: string;
  quiz_desc: string;
  quiz_intro: string;
  quiz_cta: string;
  quiz_help_link: string;
  questions: QuizQuestion[];
}

interface StepMap {
  type: 'Quiz';
  data: QuizData;
}
  1. Consider splitting the component into smaller, more focused components:
    • QuizMetadata (for quiz name, description, etc.)
    • QuestionList (for managing questions)
    • QuestionEditor (for individual questions)

This would improve maintainability and make the code easier to test.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e433dac and 77b49c8.

📒 Files selected for processing (3)
  • components/admin/taskSteps/quizStep.tsx (3 hunks)
  • services/authService.ts (3 hunks)
  • types/backTypes.d.ts (1 hunks)
🔇 Additional comments (6)
components/admin/taskSteps/quizStep.tsx (2)

10-10: LGTM: Import statement is correctly placed.

The FaTrash icon import is appropriately added for the delete functionality.


238-250: Previous accessibility concerns still apply.

The current implementation of the delete button still needs accessibility improvements as mentioned in the previous review.

services/authService.ts (4)

18-18: LGTM! Type import follows conventions

The DeleteQuizQuestion type import is properly placed and follows the established naming pattern.


618-618: LGTM! Export follows existing pattern

The deleteQuizQuestion method is properly exported in the AdminService object.


496-513: Consider implementing safeguards for question deletion

As deletion is a destructive operation, consider implementing these safeguards:

  1. Soft delete pattern instead of hard delete
  2. Audit logging for tracking who deleted what and when
  3. Validation to prevent deletion of questions that are part of active quizzes

Let's check if soft delete is used elsewhere in the codebase:

#!/bin/bash
# Look for soft delete patterns
rg "deleted_at|is_deleted|soft.?delete" --type ts

# Check for audit logging patterns
rg "audit|log.*delete|track.*change" --type ts

496-513: ⚠️ Potential issue

Enhance error handling and response validation

While the implementation follows the service's pattern, there are several areas for improvement:

  1. Add error return value and improve error handling:
 const deleteQuizQuestion = async (params: DeleteQuizQuestion) => {
   try {
     const response = await fetch(
-      `${baseurl}/admin/tasks/quiz/question/delete`,
+      `${baseurl}/admin/tasks/quiz/question/delete`,
       {
         method: "POST",
         headers: {
           "Content-Type": "application/json",
           Authorization: `Bearer ${localStorage.getItem("token")}`,
         },
         body: JSON.stringify(params),
       }
     );
+    const data = await response.json();
+    if (!response.ok) {
+      throw new Error(data.message || 'Failed to delete quiz question');
+    }
-    return await response.json();
+    return data;
   } catch (err) {
     console.log("Error while deleting quiz question", err);
+    return { error: 'Failed to delete quiz question' };
   }
 };
  1. Consider adding input validation:
if (!params.id || !params.quiz_id) {
  return { error: 'Invalid parameters: id and quiz_id are required' };
}

Let's verify the error handling pattern across the codebase:

components/admin/taskSteps/quizStep.tsx Outdated Show resolved Hide resolved
Copy link
Collaborator

@Marchand-Nicolas Marchand-Nicolas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The API call is working perfectly, but you also need to delete the task locally (As you did in your first commit) so that we see that it effectively deleted the tasl

Copy link
Collaborator

@Marchand-Nicolas Marchand-Nicolas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lgtm!

@Marchand-Nicolas Marchand-Nicolas merged commit f2b90f7 into lfglabs-dev:testnet Oct 29, 2024
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants