diff --git a/backend/app/routers/quizzes.py b/backend/app/routers/quizzes.py index 20f4ef4..2025288 100644 --- a/backend/app/routers/quizzes.py +++ b/backend/app/routers/quizzes.py @@ -441,8 +441,28 @@ def delete_quiz( db: Session = Depends(get_db), current_user: User = Depends(require_moderator), ): + """Delete quiz. Questions shared with other quizzes stay in the bank. + Questions only in this quiz are detached (source_quiz_id cleared) so they + remain in the bank instead of being deleted.""" + from app.models.quiz_question_link import QuizQuestionLink + quiz = db.query(Quiz).filter(Quiz.id == quiz_id).first() if not quiz: raise HTTPException(status_code=404, detail="Quiz not found") - db.delete(quiz) + + # For each question linked to this quiz: if no other quiz uses it, + # detach it (clear source_quiz_id) so it stays as a bank-only question + links = db.query(QuizQuestionLink).filter(QuizQuestionLink.quiz_id == quiz_id).all() + for link in links: + other = db.query(QuizQuestionLink).filter( + QuizQuestionLink.question_id == link.question_id, + QuizQuestionLink.quiz_id != quiz_id, + ).count() + if other == 0: + # Detach from this quiz but keep in bank + db.query(QuestionModel).filter(QuestionModel.id == link.question_id).update( + {"quiz_id": None} # source_quiz_id → null + ) + + db.delete(quiz) # cascades quiz_question_links db.commit()