Skip to content

Commit

Permalink
Merge pull request #70 from mju-likelion/feature/comment-#69
Browse files Browse the repository at this point in the history
Feature/#69 주석 작업
  • Loading branch information
rnqhstmd authored Jul 30, 2024
2 parents b6e73d8 + a2005d2 commit edc6b79
Show file tree
Hide file tree
Showing 12 changed files with 111 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,23 @@
public class JwtEncoder {
public static final String TOKEN_TYPE = "Bearer ";

/**
* 토큰에 Bearer 형식 적용 후 인코딩
* 공백은 '+' 대신 '%20'으로 치환
* @param token 인코딩할 JWT 토큰
* @return 인코딩된 JWT 토큰
*/
public static String encode(String token) {
String cookieValue = TOKEN_TYPE + token;
return URLEncoder.encode(cookieValue, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
}

/**
* Bearer 형식 적용된 쿠키 값 디코딩
* @param cookieValue 디코딩할 쿠키 값
* @return 디코딩된 JWT 토큰
* @throws UnauthorizedException Bearer 형식이 적용된 값이 아닐 경우 발생
*/
public static String decode(String cookieValue) {
String value = URLDecoder.decode(cookieValue, StandardCharsets.UTF_8);
if (value.startsWith(TOKEN_TYPE)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@ public class AuthController {

private final AuthService authService;

// 회원가입
@PostMapping("/signup")
public ResponseEntity<ResponseDto<Void>> signup(@RequestBody @Valid SignupDto signupDto, HttpServletResponse response) {
TokenResponseDto tokenResponseDto = authService.signup(signupDto);
setCookie(response, JwtEncoder.encode(tokenResponseDto.getAccessToken()));
return new ResponseEntity<>(ResponseDto.res(HttpStatus.CREATED, "회원가입 완료"), HttpStatus.CREATED);
}

// 로그인
@PostMapping("/login")
public ResponseEntity<ResponseDto<Void>> login(@RequestBody @Valid LoginDto loginDto, HttpServletResponse response) {
TokenResponseDto tokenResponseDto = authService.login(loginDto);
Expand All @@ -49,6 +51,7 @@ private static void setCookie(HttpServletResponse response, String accessToken)
response.addHeader("set-cookie", cookie.toString());
}

// 로그아웃
@GetMapping("/logout")
public ResponseEntity<ResponseDto<Void>> logout(final HttpServletResponse response) {
ResponseCookie cookie = ResponseCookie.from("AccessToken", null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
@RestController
@RequestMapping("/health")
public class HealthController {

// 대상그룹 상태 검사
@GetMapping
public ResponseEntity<String> checkHealth() {
return ResponseEntity.ok("OK");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,42 +23,42 @@
public class PlannerController {
private final PlannerService plannerService;

// 모든 미완료 상태의 planner 조회하기
// 미완료 상태의 플래너 전체 조회
@GetMapping
public ResponseEntity<ResponseDto<PlannerListResponseData>> getAllPlanners(@AuthenticatedUser User user) {
PlannerListResponseData planners = plannerService.getAllPlanners(user);
return new ResponseEntity<>(ResponseDto.res(HttpStatus.OK, "미완료 상태 플래너 전체 조회", planners), HttpStatus.OK);
}

// 새 planner 생성
// 플래너 생성
@PostMapping
public ResponseEntity<ResponseDto<Void>> createPlanner(@AuthenticatedUser User user, @RequestBody @Valid PlannerDto plannerDto) {
plannerService.createPlanner(user, plannerDto);
return new ResponseEntity<>(ResponseDto.res(HttpStatus.CREATED, "플래너 생성"), HttpStatus.CREATED);
}

// planner 수정
// 플래너 수정
@PatchMapping("/{plannerId}")
public ResponseEntity<ResponseDto<Void>> updatePlanner(@AuthenticatedUser User user, @RequestBody @Valid PlannerDto plannerDto, @PathVariable UUID plannerId) {
plannerService.updatePlanner(user, plannerId, plannerDto);
return new ResponseEntity<>(ResponseDto.res(HttpStatus.OK, "플랜 수정 완료"), HttpStatus.OK);
}

// 완료 상태의 planner들 조회하기
// 완료 상태의 플래너 전체 목록 조회
@GetMapping("/completed")
public ResponseEntity<ResponseDto<GroupedCompletedPlannerResponse>> getAllCompletedPlanners(@AuthenticatedUser User user) {
GroupedCompletedPlannerResponse completedPlanners = plannerService.getCompletedPlannersGroupedByDate(user);
return new ResponseEntity<>(ResponseDto.res(HttpStatus.OK, "완료된 플래너 전체 조회", completedPlanners), HttpStatus.OK);
}

// planner 삭제
// 플래너 삭제
@DeleteMapping("/{plannerId}")
public ResponseEntity<ResponseDto<Void>> deletePlanner(@AuthenticatedUser User user, @PathVariable UUID plannerId) {
plannerService.deletePlanner(user, plannerId);
return new ResponseEntity<>(ResponseDto.res(HttpStatus.OK, "플랜 삭제 완료"), HttpStatus.OK);
}

// planner 완료하기
// 플래너 완료
@PutMapping("/{plannerId}")
public ResponseEntity<ResponseDto<Void>> completePlannerById(
@AuthenticatedUser User user,
Expand All @@ -68,6 +68,7 @@ public ResponseEntity<ResponseDto<Void>> completePlannerById(
return new ResponseEntity<>(ResponseDto.res(HttpStatus.OK, "플래너 완료 상태로 변경"), HttpStatus.OK);
}

// 월별 플래너 잔디 타입 조회
@GetMapping("/calendars")
public ResponseEntity<ResponseDto<DailyPlannerCompletionDataList>> getMonthlyPlannersStats(
@AuthenticatedUser User user,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class SurveyController {
private final SurveyService surveyService;
private final UserService userService;

// 설문조사 응답
@PostMapping
public ResponseEntity<ResponseDto<UserGradeResponseDto>> saveSurveyResults(@AuthenticatedUser User user,
@RequestBody @Valid SurveyResultListDto surveyResultListDto) {
Expand All @@ -30,6 +31,7 @@ public ResponseEntity<ResponseDto<UserGradeResponseDto>> saveSurveyResults(@Auth
return new ResponseEntity<>(ResponseDto.res(HttpStatus.OK, "설문조사 저장 및 유저 등급 반환 완료", userGradeResponseDto), HttpStatus.OK);
}

// 설문조사 질문 전체 조회
@GetMapping
public ResponseEntity<ResponseDto<SurveyQuestionListResponseDto>> getAllSurveyQuestions() {
SurveyQuestionListResponseDto surveyList = surveyService.getAllSurveyQuestions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,22 @@
public class UserController {
private final UserService userService;

// 유저 등급 조회
@GetMapping("/grade")
public ResponseEntity<ResponseDto<UserGradeResponseDto>> getUserGrade(@AuthenticatedUser User user) {
UserGradeResponseDto userGradeResponseDto = userService.getUserGrade(user);
return new ResponseEntity<>(ResponseDto.res(HttpStatus.OK, "유저 등급 조회 완료", userGradeResponseDto), HttpStatus.OK);
}

// 유저 정보 수정
@PatchMapping
public ResponseEntity<ResponseDto<UserGradeResponseDto>> updateUser(@AuthenticatedUser User user,
@RequestBody @Valid UpdateUserDto updateUserDto) {
userService.updateUser(user, updateUserDto);
return new ResponseEntity<>(ResponseDto.res(HttpStatus.OK, "유저 정보 수정 완료"), HttpStatus.OK);
}

// 유저 탈퇴
@DeleteMapping
public ResponseEntity<ResponseDto<UserGradeResponseDto>> deleteUser(@AuthenticatedUser User user,
@RequestBody @Valid DeleteUserDto deleteUserDto) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ public Map<String, Long> getCompletedPlannersStats(UUID userId, LocalDate startD
planner.user.id.eq(userId)
// 이미 완료된 플래너들을 선택
.and(planner.isCompleted.isTrue())
// modifiedDate 가 startDate 자정 ~ endDate 23시 59분 59초 사이인 플래너들을 선택
// modifiedDate가 startDate 자정 ~ endDate 23시 59분 59초 사이인 플래너들을 선택
.and(planner.modifiedDate.between(startDate.atStartOfDay(), endDate.atTime(23, 59, 59))))
// modifiedDate 년,월,일을 기준으로 그룹화 후 카운트
// modifiedDate 년,월,일을 기준으로 그룹화 후 카운트
.groupBy(planner.modifiedDate.year(),
planner.modifiedDate.month(),
planner.modifiedDate.dayOfMonth())
Expand Down
23 changes: 17 additions & 6 deletions src/main/java/com/example/mutsideout_mju/service/DiaryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,16 @@ public class DiaryService {

private final DiaryRepository diaryRepository;

//감정일기 전체 목록 조회
/**
* 감정일기 전체 목록 조회
*/
public DiaryListResponseData getDiaryList(User user, PaginationDto paginationDto) {

//요청받은 페이지 번호, 페이지 크기, 작성순으로 정렬
Pageable pageable = PageRequest.of(paginationDto.getPage(), paginationDto.getPAGE_SIZE(), Sort.by(Sort.Order.desc("createdAt")));

Page<Diary> diaryPage = diaryRepository.findByUserId(user.getId(), pageable); //특정 유저의 해당 페이지 데이터를 모두 가져옴
//특정 유저의 해당 페이지 데이터를 모두 가져옴
Page<Diary> diaryPage = diaryRepository.findByUserId(user.getId(), pageable);

if (diaryPage.getTotalPages() <= paginationDto.getPage() && paginationDto.getPage() != 0) {
throw new NotFoundException(ErrorCode.NOT_FOUND_PAGE);
Expand All @@ -40,7 +43,9 @@ public DiaryListResponseData getDiaryList(User user, PaginationDto paginationDto
return DiaryListResponseData.from(diaryPage);
}

//감정일기 상세 조회
/**
* 감정일기 상세 조회
*/
public DiaryResponseData getDiaryById(User user, UUID diaryId) {
Diary diary = findDiary(user.getId(), diaryId);
return DiaryResponseData.from(diary);
Expand All @@ -51,7 +56,9 @@ private Diary findDiary(UUID userId, UUID diaryId) {
.orElseThrow(() -> new NotFoundException(ErrorCode.DIARY_NOT_FOUND));
}

//감정일기 작성
/**
* 감정일기 생성
*/
public void writeDiary(User user, WriteDiaryDto writeDiaryDto) {
Diary diary = Diary.builder()
.user(user)
Expand All @@ -61,15 +68,19 @@ public void writeDiary(User user, WriteDiaryDto writeDiaryDto) {
diaryRepository.save(diary);
}

//감정일기 수정
/**
* 감정일기 수정
*/
public void updateDiaryById(User user, UUID diaryId, UpdateDiaryDto updateDiaryDto) {
Diary newDiary = findDiary(user.getId(), diaryId);
newDiary.setTitle(updateDiaryDto.getTitle())
.setContent(updateDiaryDto.getContent());
diaryRepository.save(newDiary);
}

//감정일기 삭제
/**
* 감정일기 삭제
*/
public void deleteDiaryById(User user, UUID diaryId){
Diary diary = findDiary(user.getId(), diaryId);
diaryRepository.delete(diary);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
public class PlannerService {
private final PlannerRepository plannerRepository;

/**
* 미완료 상태의 플래너 전체 조회
*/
public PlannerListResponseData getAllPlanners(User user) {
List<Planner> allPlanners = plannerRepository.findAllByUserId(user.getId());

Expand All @@ -36,6 +39,9 @@ public PlannerListResponseData getAllPlanners(User user) {
return new PlannerListResponseData(plannerResponseDataList);
}

/**
* 플래너 생성
*/
public void createPlanner(User user, PlannerDto plannerDto) {
Planner planner = Planner.builder()
.content(plannerDto.getContent())
Expand All @@ -45,6 +51,9 @@ public void createPlanner(User user, PlannerDto plannerDto) {
this.plannerRepository.save(planner);
}

/**
* 플래너 수정
*/
public void updatePlanner(User user, UUID plannerId, PlannerDto plannerDto) {
Planner planner = findPlanner(user.getId(), plannerId);
if (planner.isCompleted()) {
Expand All @@ -55,6 +64,9 @@ public void updatePlanner(User user, UUID plannerId, PlannerDto plannerDto) {
plannerRepository.save(planner);
}

/**
* 플래너 완료
*/
public void completePlannerById(User user, UUID plannerId, CompletePlannerRequestDto requestDto) {
Planner planner = findPlanner(user.getId(), plannerId);
if (!requestDto.getIsCompleted() || planner.isCompleted()) {
Expand All @@ -65,6 +77,9 @@ public void completePlannerById(User user, UUID plannerId, CompletePlannerReques
plannerRepository.save(planner);
}

/**
* 완료 상태의 플래너 전체 목록 조회
*/
public GroupedCompletedPlannerResponse getCompletedPlannersGroupedByDate(User user) {
CompletedPlannerListResponseData completedPlannerList = getAllCompletedPlanners(user);

Expand All @@ -87,6 +102,9 @@ public GroupedCompletedPlannerResponse getCompletedPlannersGroupedByDate(User us
return new GroupedCompletedPlannerResponse(sortedGroupedPlanners);
}

/**
* 완료된 플래너 전체 목록 조회
*/
private CompletedPlannerListResponseData getAllCompletedPlanners(User user) {
List<Planner> completedPlanners = plannerRepository.findByIsCompletedAndUser(true, user);
List<CompletedPlannerResponse> completedPlannerResponses = completedPlanners.stream()
Expand All @@ -96,6 +114,9 @@ private CompletedPlannerListResponseData getAllCompletedPlanners(User user) {
return new CompletedPlannerListResponseData(completedPlannerResponses);
}

/**
* 월별 완료된 플래너 잔디 타입 조회
*/
public DailyPlannerCompletionDataList getMonthlyPlannerStats(User user, String month) {
LocalDate startDate = LocalDate.parse(month + "-01");
LocalDate endDate = startDate.with(TemporalAdjusters.lastDayOfMonth());
Expand All @@ -111,6 +132,9 @@ public DailyPlannerCompletionDataList getMonthlyPlannerStats(User user, String m
return DailyPlannerCompletionDataList.from(dailyCounts);
}

/**
* 플래너 삭제
*/
public void deletePlanner(User user, UUID plannerId) {
Planner planner = findPlanner(user.getId(), plannerId);
if(planner.isCompleted()){
Expand Down
25 changes: 18 additions & 7 deletions src/main/java/com/example/mutsideout_mju/service/RoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,18 @@ public class RoomService {
private final RoomRepository roomRepository;
private final S3Service s3Service;

// 24시간 지난 방 삭제 (한 시간마다 실행)
/**
* 24시간 지난 방 삭제 (한 시간마다 실행)
*/
@Scheduled(fixedRate = 3600000)
public void deleteOldRooms() {
LocalDateTime cutoffTime = LocalDateTime.now().minusHours(24);
roomRepository.deleteByCreatedAtBefore(cutoffTime);
}

//집중 세션 방 전체 목록 조회
/**
* 집중 세션 방 전체 목록 조회
*/
public RoomListResponseData getRoomList(PaginationDto paginationDto) {
// 요청받은 페이지 번호, 페이지 크기, 작성순으로 정렬
Pageable pageable = PageRequest.of(paginationDto.getPage(), paginationDto.getPAGE_SIZE(), Sort.by(Sort.Order.desc("createdAt")));
Expand All @@ -59,7 +63,9 @@ public RoomListResponseData getRoomList(PaginationDto paginationDto) {
return new RoomListResponseData(roomResponseList, pagination);
}

//집중 세션 방 상세 조회
/**
* 집중 세션 방 상세 조회
*/
public RoomResponseData getRoomById(UUID roomId) {
Room room = findExistingRoom(roomId);
//현재 시각으로 부터 방 생성 시간이 24시간 이후이면 false(비활성화)로 방 삭제
Expand All @@ -70,7 +76,9 @@ public RoomResponseData getRoomById(UUID roomId) {
return RoomResponseData.from(room);
}

//집중 세션 방 생성
/**
* 집중 세션 방 생성
*/
public void createRoom(User user, CreateRoomDto createRoomDto) {
Room room = Room.builder()
.title(createRoomDto.getTitle())
Expand All @@ -81,7 +89,9 @@ public void createRoom(User user, CreateRoomDto createRoomDto) {
roomRepository.save(room);
}

//집중 세션 방 수정
/**
* 집중 세션 방 수정
*/
public void updateRoomById(User user, UUID roomId, UpdateRoomDto updateRoomDto) {
Room updateRoom = findRoomByUserIdAndRoomId(user.getId(), roomId);
updateRoom.setTitle(updateRoomDto.getTitle())
Expand All @@ -90,7 +100,9 @@ public void updateRoomById(User user, UUID roomId, UpdateRoomDto updateRoomDto)
roomRepository.save(updateRoom);
}

//집중 세션 방 삭제
/**
* 집중 세션 방 삭제
*/
public void deleteRoomById(User user, UUID roomId) {
Room room = findRoomByUserIdAndRoomId(user.getId(), roomId);
roomRepository.delete(room);
Expand All @@ -101,7 +113,6 @@ private Room findRoomByUserIdAndRoomId(UUID userId, UUID roomId) {
.orElseThrow(() -> new ForbiddenException(ErrorCode.NO_ACCESS));
}

//방 존재 여부 확인
private Room findExistingRoom(UUID roomId) {
return roomRepository.findById(roomId)
.orElseThrow(() -> new NotFoundException(ErrorCode.ROOM_NOT_FOUND));
Expand Down
Loading

0 comments on commit edc6b79

Please sign in to comment.