Skip to content

Commit

Permalink
[Refactor] todo와 todolist 연관관계 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
jiyunio committed Dec 26, 2024
1 parent c53cb46 commit 07c4ad0
Show file tree
Hide file tree
Showing 19 changed files with 91 additions and 103 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@
import com.jiyunio.todolist.domain.member.Member;
import com.jiyunio.todolist.domain.member.MemberRepository;
import com.jiyunio.todolist.domain.todo.TodoListRepository;
import com.jiyunio.todolist.domain.todo.TodoRepository;
import com.jiyunio.todolist.domain.todo.TodoService;
import com.jiyunio.todolist.domain.todo.domain.TodoList;
import com.jiyunio.todolist.domain.todo.dto.TodoListRes;
import com.jiyunio.todolist.domain.todo.dto.TodoRes;
import com.jiyunio.todolist.global.customError.CustomException;
import com.jiyunio.todolist.global.customError.ErrorCode;
import lombok.RequiredArgsConstructor;
Expand All @@ -19,7 +16,6 @@

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
Expand Down Expand Up @@ -88,7 +84,7 @@ public void deleteCategory(String userId, Long categoryId) {
throw new CustomException(HttpStatus.BAD_REQUEST, ErrorCode.NO_ANYMORE_CATEGORY);
}
// 카테고리 삭제시, 관련 todo도 함께 삭제
List<TodoList> todoList = todoListRepository.findAllByUserIdANDCategoryId(userId, categoryId);
List<TodoList> todoList = todoListRepository.findAllByUserIdAndCategoryId(userId, categoryId);
todoListRepository.deleteAll(todoList);
categoryRepository.deleteById(categoryId);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,20 @@

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.*;

@Getter
@Setter
@Builder
@Schema(description = "category 생성 & 조회 & 수정")
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class CategoryReq {
@NotBlank
@Schema(description = "category 내용", example = "약속")
private String content;
private final String content;

@NotBlank
@Schema(description = "category 색깔 (# 제외)", example = "FFFFFF")
private String color;

@Builder
protected CategoryReq(String content, String color) {
this.content = content;
this.color = color;
}
private final String color;

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
public class CategoryRes {
@NotNull
@Schema(description = "category Id", example = "1")
private Long categoryId;
private final Long categoryId;

@NotBlank
@Schema(description = "category 내용", example = "약속")
private String content;
private final String content;

@NotBlank
@Schema(description = "category 색깔 (# 제외)", example = "FFFFFF")
private String color;
private final String color;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,23 @@
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.Getter;
import lombok.Setter;
import lombok.*;

@Getter
@Setter
@Schema(description = "회원 비밀번호 수정")
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class ChangePwReq {
@NotBlank(message = "비밀번호를 입력하세요.")
@Schema(description = "회원 기존 비밀번호", example = "qwe123!")
private String userPw;
private final String userPw;

@NotBlank(message = "변경 비밀번호를 입력하세요.")
@Pattern(regexp = "(?=.*[0-9])(?=.*[a-zA-Z])(?=.*\\W)(?=\\S+$).{8,16}")
@Schema(description = "회원 변경 비밀번호", example = "qwer1234!")
private String changePw;
private final String changePw;

@NotBlank(message = "확인 비밀번호를 입력하세요.")
@Schema(description = "회원 변경 확인 비밀번호", example = "qwer1234!")
private String confirmChangePw;
private final String confirmChangePw;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;
import lombok.*;

@Getter
@Setter
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class SignInReq {
@NotBlank(message = "아이디를 입력하세요.")
@Schema(description = "회원의 userId", example = "qwe123")
private String userId;
private final String userId;

@NotBlank(message = "비밀번호를 입력하세요.")
@Schema(description = "회원의 비밀번호", example = "qwer123!")
private String userPw;
}
private final String userPw;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,28 @@
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.Getter;
import lombok.Setter;
import lombok.*;

@Getter
@Setter
@Schema(description = "회원가입")
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class SignUpReq {

@NotBlank(message = "아이디를 입력하세요.")
@Pattern(regexp = "(?=.*[a-zA-Z])(?=\\S+$).{5,10}", message = "아이디 : 5~10자")
@Schema(description = "회원의 userId \n\n- 영문 대/소문자 5~10자", example = "qwe123")
private String userId;
private final String userId;

@NotBlank(message = "비밀번호를 입력하세요.")
@Pattern(regexp = "(?=.*[0-9])(?=.*[a-zA-Z])(?=.*\\W)(?=\\S+$).{8,16}", message = "비밀번호: 8~16자의 영문 대/소문자, 숫자, 특수문자를 사용하십쇼.")
@Schema(description = "회원의 비밀번호 \n\n- 8~16자의 영문 대/소문자, 숫자, 특수문자", example = "qwer123!")
private String userPw;
private final String userPw;

@NotBlank(message = "확인 비밀번호를 입력하세요.")
@Schema(description = "회원 확인 비밀번호", example = "qwer123!")
private String confirmUserPw;
private final String confirmUserPw;

@NotBlank(message = "닉네임을 입력하세요.")
@Schema(description = "닉네임", example = "곽두철")
private String nickname;
private final String nickname;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,24 @@
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.*;

@Getter
@Setter
@Builder
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class MemberRes {
@NotNull
@Schema(description = "회원의 Id", example = "1")
private Long memberId;
private final Long memberId;

@NotBlank
@Schema(description = "회원의 userId", example = "jiyun123")
private String userId;
private final String userId;

@NotBlank
@Schema(description = "회원의 userId", example = "jiyun123")
private String nickname;

@Builder
private MemberRes(Long memberId, String userId, String nickname) {
this.memberId = memberId;
this.userId = userId;
this.nickname = nickname;
}
private final String nickname;

public static MemberRes from(Member member) {
return MemberRes.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
public class SignInRes {
@NotBlank
@Schema(description = "회원의 userId", example = "qwe123")
private String nickname;
private final String nickname;

@NotBlank
@Schema(description = "회원의 token")
private String token;
private final String token;
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ public ResponseEntity<TodoRes> createTodo(@AuthenticationPrincipal CustomUserDet
@Operation(summary = "todolist 생성")
@ApiResponse(responseCode = "200", description = "todo 생성 성공", content = @Content(schema = @Schema(implementation = TodoRes.class)))
@ApiResponse(responseCode = "404", description = "회원 X", content = @Content(schema = @Schema(implementation = ErrorDTO.class)))
public ResponseEntity<TodoListRes> createTodo(@AuthenticationPrincipal CustomUserDetails user, LocalDate localDate) {
return new ResponseEntity<>(todoService.createTodoList(user.getUsername(), localDate), HttpStatus.CREATED);
public ResponseEntity<TodoListRes> createTodo(@AuthenticationPrincipal CustomUserDetails user, @RequestParam LocalDate todoListDate) {
return new ResponseEntity<>(todoService.createTodoList(user.getUsername(), todoListDate), HttpStatus.CREATED);
}

@GetMapping("")
Expand Down Expand Up @@ -73,7 +73,7 @@ public ResponseEntity<ResponseDTO> deleteTodo(@Parameter(description = "todo의
.build());
}

@DeleteMapping("/{todoListId}")
@DeleteMapping("/list/{todoListId}")
@Operation(summary = "todo list 삭제")
@ApiResponse(responseCode = "200", description = "todo list 삭제 성공", content = @Content(schema = @Schema(implementation = ResponseDTO.class)))
public ResponseEntity<ResponseDTO> deleteTodoList(@Parameter(description = "todo의 id") @PathVariable Long todoListId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.jiyunio.todolist.domain.todo.domain.TodoList;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
Expand All @@ -15,8 +16,12 @@ public interface TodoListRepository extends JpaRepository<TodoList, Long> {

Optional<TodoList> findByUserIdAndTodoListDate(String userId, LocalDate localDate);

@Query("SELECT tl FROM TodoList tl JOIN tl.todos t WHERE t.categoryId = :categoryId and tl.userId = :userId")
List<TodoList> findAllByUserIdANDCategoryId(String userId, Long categoryId);
@Query("select tl from TodoList tl join Todo t on tl.id = t.todoListId where t.categoryId = :categoryId and tl.userId = :userId")
List<TodoList> findAllByUserIdAndCategoryId(@Param("userId") String userId, @Param("categoryId") Long categoryId);

void deleteAllByUserId(String userId);

@Query("select count(tl) > 0 from TodoList tl where tl.userId = :userId and tl.todoListDate = :todoListDate")
boolean existsByUserIdAndTodoListDate(@Param("userId") String userId, @Param("todoListDate") LocalDate todoListDate);

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.util.List;

public interface TodoRepository extends JpaRepository<Todo, Long> {

List<Todo> findByCategoryId(Long categoryId);

List<Todo> findAllByTodoListId(Long todoListId);
}
33 changes: 19 additions & 14 deletions src/main/java/com/jiyunio/todolist/domain/todo/TodoService.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
Expand All @@ -42,22 +41,21 @@ public TodoRes createTodo(String userId, CreateTodoReq createTodo) {
() -> new CustomException(HttpStatus.NOT_FOUND, ErrorCode.NOT_EXIST_CATEGORY)
);

TodoList todoList = todoListRepository.findByUserIdAndTodoListDate(member.getUserId(), createTodo.getSetDate()).orElseThrow(
() -> new CustomException(HttpStatus.NOT_FOUND, ErrorCode.NOT_EXIST_TODOLIST)
);

Todo todo = Todo.builder()
.content(createTodo.getContent())
.checked(false)
.categoryId(category.getId())
.categoryContent(category.getContent())
.categoryColor(category.getColor())
.todoListId(todoList.getId())
.build();

todoRepository.save(todo);

TodoList todoList = todoListRepository.findByUserIdAndTodoListDate(member.getUserId(), createTodo.getSetDate()).orElseThrow(
() -> new CustomException(HttpStatus.NOT_FOUND, ErrorCode.NOT_EXIST_TODOLIST)
);

todoList.getTodos().add(todo);

return TodoRes.from(todo);
}

Expand All @@ -66,25 +64,32 @@ public TodoListRes createTodoList(String userId, LocalDate todoListDate) {
// 회원 존재 안함
() -> new CustomException(HttpStatus.NOT_FOUND, ErrorCode.NOT_EXIST_MEMBER)
);
log.warn(userId, todoListDate);
if (todoListRepository.existsByUserIdAndTodoListDate(userId, todoListDate)) {
throw new CustomException(HttpStatus.CONFLICT, ErrorCode.EXIST_TODOLIST);
}

TodoList todoList = TodoList.builder()
.userId(member.getUserId())
.todoListDate(todoListDate)
.todos(new ArrayList<>())
.build();

todoListRepository.save(todoList);
return TodoListRes.from(todoList);

return TodoListRes.from(todoList, new ArrayList<>());
}

public List<TodoListRes> getTodos(String userId) {
List<TodoList> todoList = todoListRepository.findAllByUserId(userId);
if (todoList == null) {
throw new CustomException(HttpStatus.NOT_FOUND, ErrorCode.NOT_EXIST_MEMBER);
if (todoList.isEmpty()) {
throw new CustomException(HttpStatus.NOT_FOUND, ErrorCode.NOT_EXIST_TODOLIST);
}

return new ArrayList<>(todoList.stream()
.map(TodoListRes::from).toList());
return todoList.stream().map(
list -> {
List<Todo> todos = todoRepository.findAllByTodoListId(list.getId());
return TodoListRes.from(list, todos);
}
).toList();
}

public TodoRes updateTodo(Long todoId, UpdateTodoReq updateTodo) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,17 @@ public class Todo {

private String categoryContent;

private Long todoListId;

@Builder
private Todo(String content, Boolean checked,
Long categoryId, String categoryContent, String categoryColor) {
Long categoryId, String categoryContent, String categoryColor, Long todoListId) {
this.content = content;
this.checked = checked;
this.categoryId = categoryId;
this.categoryContent = categoryContent;
this.categoryColor = categoryColor;
this.todoListId = todoListId;
}

public void updateTodo(UpdateTodoReq updateTodoReq) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,23 @@
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Entity
@Getter
@NoArgsConstructor
public class TodoList {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "todo_list_id")
private Long id;

private String userId;

private LocalDate todoListDate;

@OneToMany(cascade = CascadeType.ALL)
private List<Todo> todos = new ArrayList<>();

@Builder
private TodoList(LocalDate todoListDate, String userId, List<Todo> todos) {
private TodoList(LocalDate todoListDate, String userId) {
this.todoListDate = todoListDate;
this.userId = userId;
this.todos = todos;
}
}
Loading

0 comments on commit 07c4ad0

Please sign in to comment.