Skip to content

Commit

Permalink
[BE] 체크리스트 방 정보 작성 API에 기능을 추가 구현한다 (#189)
Browse files Browse the repository at this point in the history
  • Loading branch information
shin-jisong authored Aug 1, 2024
1 parent ea3a056 commit 2469242
Show file tree
Hide file tree
Showing 42 changed files with 455 additions and 186 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import java.time.LocalDateTime;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDateTime;

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.bang_ggood.category.controller;

import com.bang_ggood.category.dto.response.CategoriesReadResponse;
import com.bang_ggood.category.dto.request.CategoryPriorityCreateRequest;
import com.bang_ggood.category.dto.response.CategoriesReadResponse;
import com.bang_ggood.category.service.CategoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ public enum Badge {
ENVIRONMENT("주거환경", "주거환경이 좋아요", "🌱"),
SECURITY("보안", "안전해요", "🔒"),
ECONOMIC("경제적", "경제적이에요", "💰"),
NONE("", "", "")
;
NONE("", "", "");

private static final String DESCRIPTION_FORMAT = "%s %s";
private final String shortName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
import com.bang_ggood.checklist.dto.response.WrittenQuestionResponse;
import java.util.List;

public record WrittenCategoryQuestionsResponse(Integer categoryId, String categoryName, List<WrittenQuestionResponse> questions) {
public record WrittenCategoryQuestionsResponse(Integer categoryId, String categoryName,
List<WrittenQuestionResponse> questions) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import com.bang_ggood.category.domain.Category;
import com.bang_ggood.category.domain.CategoryPriority;
import com.bang_ggood.category.dto.response.CategoriesReadResponse;
import com.bang_ggood.category.dto.request.CategoryPriorityCreateRequest;
import com.bang_ggood.category.dto.response.CategoriesReadResponse;
import com.bang_ggood.category.dto.response.CategoryReadResponse;
import com.bang_ggood.category.repository.CategoryPriorityRepository;
import com.bang_ggood.exception.BangggoodException;
Expand Down Expand Up @@ -62,7 +62,9 @@ private void validateCategoryId(CategoryPriorityCreateRequest request) {
request.categoryIds().stream()
.filter(id -> !Category.contains(id))
.findAny()
.ifPresent(id -> { throw new BangggoodException(CATEGORY_NOT_FOUND); });
.ifPresent(id -> {
throw new BangggoodException(CATEGORY_NOT_FOUND);
});
}

public CategoriesReadResponse readCategories() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,20 @@

import com.bang_ggood.checklist.dto.request.ChecklistCreateRequest;
import com.bang_ggood.checklist.dto.response.ChecklistQuestionsResponse;
import com.bang_ggood.checklist.dto.response.ChecklistsWithScoreReadResponse;
import com.bang_ggood.checklist.dto.response.UserChecklistsPreviewResponse;
import com.bang_ggood.checklist.dto.response.WrittenChecklistResponse;
import com.bang_ggood.checklist.service.ChecklistService;
import com.bang_ggood.user.domain.User;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;
import com.bang_ggood.checklist.dto.response.ChecklistsWithScoreReadResponse;
import com.bang_ggood.checklist.dto.response.UserChecklistsPreviewResponse;
import com.bang_ggood.checklist.service.ChecklistService;
import com.bang_ggood.user.domain.User;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;
import java.util.List;

@RestController
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,17 @@ public String getRoomAddress() {
return room.getAddress();
}

public Integer getRoomFloor() { return room.getFloor(); }
public Integer getRoomFloor() {
return room.getFloor();
}

public String getRoomStation() { return room.getStation(); }
public String getRoomStation() {
return room.getStation();
}

public Integer getRoomWalkingTime() { return room.getWalkingTime(); }
public Integer getRoomWalkingTime() {
return room.getWalkingTime();
}

public Integer getDeposit() {
return deposit;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,13 @@ public class ChecklistQuestion extends BaseEntity {
@Enumerated(EnumType.STRING)
private Grade grade;

public ChecklistQuestion(Checklist checklist, Question question, Grade grade) {
private String memo;

public ChecklistQuestion(Checklist checklist, Question question, Grade grade, String memo) {
this.checklist = checklist;
this.question = question;
this.grade = grade;
this.memo = memo;
}

protected ChecklistQuestion() {
Expand All @@ -52,6 +55,10 @@ public Grade getGrade() {
return grade;
}

public String getMemo() {
return memo;
}

@Override
public boolean equals(Object o) {
if (this == o) {
Expand All @@ -76,6 +83,7 @@ public String toString() {
", checklist=" + checklist +
", question=" + question +
", grade=" + grade +
", memo='" + memo + '\'' +
'}';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

public class ChecklistScore {

private ChecklistScore() {
}

public static int calculateTotalScore(List<ChecklistQuestion> questions) {
if (questions.isEmpty()) {
return 0;
Expand All @@ -28,7 +31,4 @@ public static int calculateCategoryScore(Category category, List<ChecklistQuesti

return totalScore * 10 / maxScore;
}

private ChecklistScore() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,13 @@ public enum Question {
this.subtitle = subtitle;
}

// TODO 테스트 필요
public static Question fromId(int id) {
return Arrays.stream(values())
.filter(question -> question.id == id)
.findFirst()
.orElseThrow(() -> new BangggoodException(ExceptionCode.QUESTION_INVALID));
}

public static List<ChecklistQuestion> filter(Category category, List<ChecklistQuestion> questions) {
return questions.stream()
.filter(question -> question.getQuestion().isCategory(category) && question.getGrade() != null)
Expand All @@ -74,23 +80,15 @@ public static List<Question> findQuestionsByCategory(Category category) {
.collect(Collectors.toList());
}

private boolean isCategory(Category category) {
return this.category == category;
}

// TODO 테스트 필요
public static Question findById(int id) {
return Arrays.stream(values())
.filter(question -> question.id == id)
.findFirst()
.orElseThrow(() -> new BangggoodException(ExceptionCode.INVALID_QUESTION));
}

public static boolean contains(int id) {
return Arrays.stream(values())
.anyMatch(question -> question.getId() == id);
}

private boolean isCategory(Category category) {
return this.category == category;
}

public int getId() {
return id;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

import jakarta.validation.constraints.NotNull;

public record QuestionCreateRequest(@NotNull Integer questionId, String answer) {
public record QuestionCreateRequest(@NotNull Integer questionId, String grade, String memo) {
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.bang_ggood.checklist.dto.response;

import com.bang_ggood.checklist.domain.Checklist;

import java.util.List;

public record ChecklistWithScoreReadResponse(
Expand All @@ -11,7 +10,8 @@ public record ChecklistWithScoreReadResponse(
Integer optionCount, Integer score,
List<CategoryScoreReadResponse> categories
) {
public static ChecklistWithScoreReadResponse of(Checklist checklist, int checklistOptionCount, int checklistScore, List<CategoryScoreReadResponse> categoryScores) {
public static ChecklistWithScoreReadResponse of(Checklist checklist, int checklistOptionCount, int checklistScore,
List<CategoryScoreReadResponse> categoryScores) {
return new ChecklistWithScoreReadResponse(
checklist.getId(),
checklist.getRoomName(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.bang_ggood.checklist.dto.response;

import com.bang_ggood.checklist.domain.Checklist;

import java.time.LocalDateTime;
import java.util.List;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.bang_ggood.checklist.dto.response;

import com.bang_ggood.checklist.dto.response.UserChecklistPreviewResponse;
import java.util.List;

public record UserChecklistsPreviewResponse(List<UserChecklistPreviewResponse> checklists) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.bang_ggood.checklist.repository;

import com.bang_ggood.checklist.domain.ChecklistQuestion;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface ChecklistQuestionRepository extends JpaRepository<ChecklistQuestion, Long> {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;
import java.util.List;
import java.util.Optional;

public interface ChecklistRepository extends JpaRepository<Checklist, Long> {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -102,27 +100,20 @@ private void validateOptionDuplicate(List<Integer> optionIds) {
private void validateOptionInvalid(List<Integer> optionIds) {
for (Integer optionId : optionIds) {
if (!Option.contains(optionId)) {
throw new BangggoodException(ExceptionCode.INVALID_OPTION);
throw new BangggoodException(ExceptionCode.OPTION_INVALID);
}
}
}

private void createChecklistQuestions(ChecklistCreateRequest checklistCreateRequest, Checklist checklist) {
validateQuestion(checklistCreateRequest.questions());
Map<Integer, String> existQuestions = checklistCreateRequest.questions()
.stream()
.collect(Collectors.toMap(QuestionCreateRequest::questionId, QuestionCreateRequest::answer));

List<ChecklistQuestion> checklistQuestions = Arrays.stream(Question.values())
.map(question -> {
int questionId = question.getId();
return Optional.ofNullable(existQuestions.get(questionId))
.map(answer -> new ChecklistQuestion(checklist, Question.findById(questionId),
Grade.from(answer)))
.orElseGet(() -> new ChecklistQuestion(checklist, Question.findById(questionId), null));
})
List<ChecklistQuestion> checklistQuestions = checklistCreateRequest.questions().stream()
.map(question -> new ChecklistQuestion(
checklist,
Question.fromId(question.questionId()),
Grade.from(question.grade()),
question.memo()))
.collect(Collectors.toList());

checklistQuestionRepository.saveAll(checklistQuestions);
}

Expand Down Expand Up @@ -156,7 +147,7 @@ private void validateQuestionDuplicate(List<QuestionCreateRequest> questions) {
private void validateQuestionInvalid(List<QuestionCreateRequest> questions) {
for (QuestionCreateRequest questionCreateRequest : questions) {
if (!Question.contains(questionCreateRequest.questionId())) {
throw new BangggoodException(ExceptionCode.INVALID_QUESTION);
throw new BangggoodException(ExceptionCode.QUESTION_INVALID);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.List;
import org.springframework.web.filter.CorsFilter;
import java.util.List;

@Configuration
public class CorsConfig {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,44 @@

public enum ExceptionCode {

// 전체
INVALID_PARAMETER(HttpStatus.BAD_REQUEST, "잘못된 인자입니다."),
INVALID_OPTION(HttpStatus.BAD_REQUEST, "잘못된 옵션 ID입니다."),

// Option
OPTION_INVALID(HttpStatus.BAD_REQUEST, "잘못된 옵션 ID입니다."),
OPTION_DUPLICATED(HttpStatus.BAD_REQUEST, "중복된 옵션이 존재합니다."),
INVALID_QUESTION(HttpStatus.BAD_REQUEST, "잘못된 질문 ID입니다."),

// Question
QUESTION_INVALID(HttpStatus.BAD_REQUEST, "잘못된 질문 ID입니다."),
QUESTION_DUPLICATED(HttpStatus.BAD_REQUEST, "중복된 질문이 존재합니다."),

// User
USER_NOT_FOUND(HttpStatus.BAD_REQUEST, "유저가 존재하지 않습니다."),

// Category
CATEGORY_PRIORITY_INVALID_COUNT(HttpStatus.BAD_REQUEST, "카테고리 개수가 유효하지 않습니다."),
CATEGORY_NOT_FOUND(HttpStatus.BAD_REQUEST, "카테코리가 존재하지 않습니다."),
CATEGORY_DUPLICATED(HttpStatus.BAD_REQUEST, "중복된 카테고리가 존재합니다."),

// Grade
GRADE_INVALID(HttpStatus.BAD_REQUEST, "점수가 유효하지 않습니다."),

// Checklist
CHECKLIST_COMPARISON_INVALID_COUNT(HttpStatus.BAD_REQUEST, "비교할 체크리스트 개수가 유효하지 않습니다."),
CHECKLIST_NOT_FOUND(HttpStatus.BAD_REQUEST, "체크리스트가 존재하지 않습니다."),
;

// Type
TYPE_INVALID(HttpStatus.BAD_REQUEST, "타입이 유효하지 않습니다."),

// FloorLevel
FLOOR_LEVEL_INVALID(HttpStatus.BAD_REQUEST, "층 종류가 유효하지 않습니다."),

// Structure
STRUCTURE_INVALID(HttpStatus.BAD_REQUEST, "방 구조가 유효하지 않습니다."),

// Room
ROOM_FLOOR_AND_LEVEL_INVALID(HttpStatus.BAD_REQUEST, "방이 지상층일 경우에만 층수를 입력할 수 있습니다.");


private final HttpStatus httpStatus;
private final String message;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ public ResponseEntity<ExceptionResponse> handleBangggoodException(BangggoodExcep

//TODO 로깅해야함
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<ExceptionResponse> handleRuntimeException(RuntimeException runtimeException, HttpServletRequest request) {
public ResponseEntity<ExceptionResponse> handleRuntimeException(RuntimeException runtimeException,
HttpServletRequest request) {
runtimeException.printStackTrace();
ExceptionResponse response = new ExceptionResponse(
request.getMethod(),
Expand Down
Loading

0 comments on commit 2469242

Please sign in to comment.