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 14 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
66 changes: 42 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,68 @@ public class ExamController {

private final ExamService examService;

private final InstructorExamService instructorExamService;

// 시험 생성
@PostMapping
public ResponseEntity<Long> createExam(
// 시험 목록 조회
@GetMapping
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}")
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')")
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')")
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')")
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,84 @@
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')")
Copy link
Contributor

Choose a reason for hiding this comment

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

@PreAuthorize이 동작하려면 @EnableMethodSecurity 필요한데 따로 관리하게 하셨나용? 아니시면 SecurityConfig에 SecurityConfig서 전역으로 관리하는게 좋다고 하네요 저도 컨트롤러마다 작성했는데 이 번에 수정할려구요!

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')")
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}")
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}")
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.

64 changes: 55 additions & 9 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,14 +59,22 @@ 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) {
this.title = title;
this.examDateTime = examDateTime;
this.duration = duration;
this.totalScore = totalScore;
this.description = description;
this.course = course;
public static Exam createExam(
String title,
LocalDateTime examDateTime,
Integer duration,
Integer totalScore,
String description,
Course course) {
Exam exam = new Exam();
exam.title = title;
Copy link
Member

Choose a reason for hiding this comment

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

필드를 하나씩 지정하셨는데, 그 이유가 있을까요?

관련 필드를 전달받아 새로운 인스턴스를 반환하는 private 생성자를 사용해보시는방법은 어떻게 생각하시는지 궁금합니다!

exam.examDateTime = examDateTime;
exam.duration = duration;
exam.totalScore = totalScore;
exam.description = description;
exam.course = course;
exam.questions = new ArrayList<>();
return exam;
}

public void updateExam(String title, LocalDateTime examDateTime,
Expand All @@ -83,4 +91,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));
}

}
Loading
Loading