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] 시험 문제 생성, 수정, 삭제 기능 구현 #74

Merged
merged 16 commits into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 44 additions & 24 deletions src/main/java/com/example/epari/exam/controller/ExamController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import java.util.List;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -15,7 +18,6 @@
import com.example.epari.exam.dto.request.ExamRequestDto;
import com.example.epari.exam.dto.response.ExamResponseDto;
import com.example.epari.exam.service.ExamService;
import com.example.epari.exam.service.InstructorExamService;
import com.example.epari.global.annotation.CurrentUserEmail;

import lombok.RequiredArgsConstructor;
Expand All @@ -30,52 +32,70 @@ public class ExamController {

private final ExamService examService;

private final InstructorExamService instructorExamService;

// 시험 생성
@PostMapping
public ResponseEntity<Long> createExam(
// 시험 목록 조회
@GetMapping
@PreAuthorize("hasAnyRole('INSTRUCTOR', 'STUDENT')")
public ResponseEntity<List<ExamResponseDto>> getExams(
@PathVariable Long courseId,
@RequestBody ExamRequestDto examRequestDto,
@CurrentUserEmail String instructorEmail) {
Long examId = instructorExamService.createExam(courseId, examRequestDto, instructorEmail);
return ResponseEntity.ok(examId);
}
@CurrentUserEmail String email,
Authentication authentication) {
String role = authentication.getAuthorities().stream()
.findFirst()
.map(GrantedAuthority::getAuthority)
.orElseThrow(() -> new IllegalStateException("권한 정보를 찾을 수 없습니다."));

// 특정 강의에 해당하는 시험 정보 조회
@GetMapping
public ResponseEntity<List<ExamResponseDto>> getExams(@PathVariable Long courseId) {
List<ExamResponseDto> exams = examService.getExamByCourse(courseId);
List<ExamResponseDto> exams = examService.getExams(courseId, email, role);
return ResponseEntity.ok(exams);
}

// 특정 강의에 속한 시험 상세 조회
// 시험 조회
@GetMapping("/{examId}")
@PreAuthorize("hasAnyRole('INSTRUCTOR', 'STUDENT')")
public ResponseEntity<ExamResponseDto> getExam(
@PathVariable Long courseId,
@PathVariable("examId") Long id) {
ExamResponseDto exam = examService.getExam(courseId, id);
@PathVariable Long examId,
@CurrentUserEmail String email,
Authentication authentication) {
String role = authentication.getAuthorities().stream()
Copy link
Member

Choose a reason for hiding this comment

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

역할을 추출하는 코드가 중복되고 있네요!
만약 역할을 추출해야하는 상황이 반복된다면, 커스텀 어노테이션을 정의해보시는 것도 좋은 방법일 것 같습니다!

@CurrentUserEmail과 같은 방식으로요!

.findFirst()
.map(GrantedAuthority::getAuthority)
.orElseThrow(() -> new IllegalStateException("권한 정보를 찾을 수 없습니다."));

ExamResponseDto exam = examService.getExam(courseId, examId, email, role);
return ResponseEntity.ok(exam);
}

// 특정 강의에 속한 시험 수정
// 시험 생성
@PostMapping
@PreAuthorize("hasRole('INSTRUCTOR') and @courseSecurityChecker.checkInstructorAccess(#courseId, #instructorEmail)")
public ResponseEntity<Long> createExam(
@PathVariable Long courseId,
@RequestBody ExamRequestDto examRequestDto,
@CurrentUserEmail String instructorEmail) {
Long examId = examService.createExam(courseId, examRequestDto, instructorEmail);
return ResponseEntity.ok(examId);
}

// 시험 수정
@PutMapping("/{examId}")
@PreAuthorize("hasRole('INSTRUCTOR') and @courseSecurityChecker.checkInstructorAccess(#courseId, #instructorEmail)")
public ResponseEntity<ExamResponseDto> updateExam(
@PathVariable Long courseId,
@PathVariable("examId") Long id,
@PathVariable Long examId,
@RequestBody ExamRequestDto examRequestDto,
@CurrentUserEmail String instructorEmail) {
ExamResponseDto updateExam = instructorExamService.updateExam(courseId, id, examRequestDto, instructorEmail);
ExamResponseDto updateExam = examService.updateExam(courseId, examId, examRequestDto, instructorEmail);
return ResponseEntity.ok(updateExam);
}

// 특정 강의에 속한 시험 삭제
// 시험 삭제
@DeleteMapping("/{examId}")
@PreAuthorize("hasRole('INSTRUCTOR') and @courseSecurityChecker.checkInstructorAccess(#courseId, #instructorEmail)")
public ResponseEntity<Void> deleteExam(
@PathVariable Long courseId,
@PathVariable("examId") Long id,
@PathVariable Long examId,
@CurrentUserEmail String instructorEmail) {
instructorExamService.deleteExam(courseId, id, instructorEmail);
examService.deleteExam(courseId, examId, instructorEmail);
return ResponseEntity.noContent().build();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.example.epari.exam.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.epari.exam.dto.request.CreateQuestionRequestDto;
import com.example.epari.exam.dto.request.UpdateQuestionRequestDto;
import com.example.epari.exam.dto.response.ExamQuestionResponseDto;
import com.example.epari.exam.service.ExamQuestionService;
import com.example.epari.global.annotation.CurrentUserEmail;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;

/**
* 시험 문제 관련 HTTP 요청을 처리하는 Controller 클래스
*/
@RestController
@RequestMapping("/api/courses/{courseId}/exams/{examId}/questions")
@RequiredArgsConstructor
public class ExamQuestionController {

private final ExamQuestionService examQuestionService;

// 시험 문제 생성
@PostMapping
@PreAuthorize("hasRole('INSTRUCTOR') and @courseSecurityChecker.checkInstructorAccess(#courseId, #instructorEmail)")
public ResponseEntity<Long> createQuestion(
@PathVariable Long courseId,
@PathVariable Long examId,
@RequestBody @Valid CreateQuestionRequestDto request,
@CurrentUserEmail String instructorEmail) {
Long questionId = examQuestionService.addQuestion(courseId, examId, request, instructorEmail);
return ResponseEntity.ok(questionId);
}

// 시험 문제 재정렬
@PutMapping("/{questionId}/order")
@PreAuthorize("hasRole('INSTRUCTOR') and @courseSecurityChecker.checkInstructorAccess(#courseId, #instructorEmail)")
public ResponseEntity<Void> reorderQuestion(
@PathVariable Long courseId,
@PathVariable Long examId,
@PathVariable Long questionId,
@RequestParam int newNumber,
@CurrentUserEmail String instructorEmail) {
examQuestionService.reorderQuestions(courseId, examId, questionId, newNumber, instructorEmail);
return ResponseEntity.ok().build();
}

// 시험 문제 수정
@PutMapping("/{questionId}")
@PreAuthorize("hasRole('INSTRUCTOR') and @courseSecurityChecker.checkInstructorAccess(#courseId, #instructorEmail)")
public ResponseEntity<ExamQuestionResponseDto> updateQuestion(
@PathVariable Long courseId,
@PathVariable Long examId,
@PathVariable Long questionId,
@RequestBody @Valid UpdateQuestionRequestDto requestDto,
@CurrentUserEmail String instructorEmail) {

ExamQuestionResponseDto updatedQuestion = examQuestionService.updateQuestion(
courseId, examId, questionId, requestDto, instructorEmail);
return ResponseEntity.ok(updatedQuestion);
}

// 시험 문제 삭제
@DeleteMapping("/{questionId}")
@PreAuthorize("hasRole('INSTRUCTOR') and @courseSecurityChecker.checkInstructorAccess(#courseId, #instructorEmail)")
public ResponseEntity<Void> deleteQuestion(
@PathVariable Long courseId,
@PathVariable Long examId,
@PathVariable Long questionId,
@CurrentUserEmail String instructorEmail) {

examQuestionService.deleteQuestion(courseId, examId, questionId, instructorEmail);
return ResponseEntity.noContent().build();
}

}

This file was deleted.

This file was deleted.

44 changes: 41 additions & 3 deletions src/main/java/com/example/epari/exam/domain/Exam.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import java.util.ArrayList;
import java.util.List;

import com.example.epari.global.common.base.BaseTimeEntity;
import com.example.epari.course.domain.Course;
import com.example.epari.global.common.base.BaseTimeEntity;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
Expand Down Expand Up @@ -59,8 +59,8 @@ public class Exam extends BaseTimeEntity {
private List<ExamQuestion> questions = new ArrayList<>();

@Builder
private Exam(String title, LocalDateTime examDateTime, Integer duration,
Integer totalScore, String description, Course course) {
private Exam(String title, LocalDateTime examDateTime,
Integer duration, Integer totalScore, String description, Course course) {
this.title = title;
this.examDateTime = examDateTime;
this.duration = duration;
Expand All @@ -83,4 +83,42 @@ public void addQuestion(ExamQuestion question) {
question.setExam(this);
}

public void reorderQuestions(Long questionId, int newNumber) {
// 1. 이동할 문제 찾기
ExamQuestion targetQuestion = questions.stream()
.filter(q -> q.getId().equals(questionId))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("문제를 찾을 수 없습니다. ID: " + questionId));
Copy link
Member

Choose a reason for hiding this comment

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

추후 커스텀 예외를 생성하여 예외 처리를 일관성 있게 유지해주시면 좋겠습니다!


// 2. 현재 문제 번호
int currentNumber = targetQuestion.getExamNumber();

// 3. 유효성 검사
if (newNumber < 1 || newNumber > questions.size()) {
throw new IllegalArgumentException("유효하지 않은 문제 번호입니다: " + newNumber);
}

// 4. 문제 번호 재정렬
if (currentNumber < newNumber) {
// 현재 위치에서 뒤로 이동하는 경우
questions.stream()
.filter(q -> q.getExamNumber() > currentNumber && q.getExamNumber() <= newNumber)
.forEach(q -> q.updateExamNumber(q.getExamNumber() - 1));
} else if (currentNumber > newNumber) {
// 현재 위치에서 앞으로 이동하는 경우
questions.stream()
.filter(q -> q.getExamNumber() >= newNumber && q.getExamNumber() < currentNumber)
.forEach(q -> q.updateExamNumber(q.getExamNumber() + 1));
}

// 5. 대상 문제의 번호 업데이트
targetQuestion.updateExamNumber(newNumber);
}

public void reorderQuestionsAfterDelete(int deletedNumber) {
questions.stream()
.filter(q -> q.getExamNumber() > deletedNumber)
.forEach(q -> q.updateExamNumber(q.getExamNumber() - 1));
}

}
22 changes: 20 additions & 2 deletions src/main/java/com/example/epari/exam/domain/ExamQuestion.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import jakarta.persistence.Column;
import jakarta.persistence.DiscriminatorColumn;
import jakarta.persistence.DiscriminatorType;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
Expand All @@ -30,7 +31,7 @@
@Entity
@Table(name = "exam_questions")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "question_type")
@DiscriminatorColumn(name = "question_type", discriminatorType = DiscriminatorType.STRING)
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class ExamQuestion extends BaseTimeEntity {
Expand All @@ -52,6 +53,9 @@ public abstract class ExamQuestion extends BaseTimeEntity {
@Column(nullable = false)
private ExamQuestionType type;

@Column(name = "correct_answer", nullable = false) // 단일 정답 필드
private String correctAnswer;

@Embedded
private QuestionImage image;

Expand All @@ -60,14 +64,18 @@ public abstract class ExamQuestion extends BaseTimeEntity {
private Exam exam;

protected ExamQuestion(String questionText, int examNumber, int score,
ExamQuestionType type, Exam exam) {
ExamQuestionType type, Exam exam, String correctAnswer) { // 생성자 수정
this.questionText = questionText;
this.examNumber = examNumber;
this.score = score;
this.type = type;
this.exam = exam;
this.correctAnswer = correctAnswer;
}

// 정답 검증을 위한 추상 메소드
public abstract boolean validateAnswer(String studentAnswer);

public void setImage(QuestionImage image) {
this.image = image;
}
Expand All @@ -76,4 +84,14 @@ void setExam(Exam exam) {
this.exam = exam;
}

public void updateExamNumber(int newNumber) {
this.examNumber = newNumber;
}

public void updateQuestion(String questionText, int score, String correctAnswer) {
this.questionText = questionText;
this.score = score;
this.correctAnswer = correctAnswer;
}

}
Loading