Skip to content

Commit

Permalink
refactor: 상위 목표 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
jemin committed May 2, 2024
1 parent 4277d2a commit 6bba2cc
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 81 deletions.
88 changes: 37 additions & 51 deletions src/main/java/com/backend/goal/application/GoalService.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
package com.backend.goal.application;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.backend.global.common.code.ErrorCode;
import com.backend.global.exception.BusinessException;
import com.backend.goal.application.dto.response.GoalCountResponse;
import com.backend.goal.application.dto.response.GoalListResponse;
import com.backend.goal.application.dto.response.RetrospectEnabledGoalCountResponse;
import com.backend.goal.domain.*;
import com.backend.goal.application.dto.response.GoalResponse;
import com.backend.goal.application.dto.response.RetrospectEnabledGoalCountResponse;
import com.backend.goal.domain.Goal;
import com.backend.goal.domain.enums.GoalStatus;
import com.backend.goal.domain.enums.RewardType;
import com.backend.goal.domain.event.RemoveRelatedDetailGoalEvent;
import com.backend.goal.domain.repository.GoalListResponseDto;
import com.backend.goal.domain.repository.GoalQueryRepository;
Expand All @@ -19,20 +30,8 @@
import com.backend.goal.presentation.dto.GoalUpdateRequest;
import com.backend.member.domain.Member;
import com.backend.member.domain.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
Expand All @@ -49,48 +48,35 @@ public class GoalService {

private final ApplicationEventPublisher applicationEventPublisher;

public GoalListResponse getGoalList(final String uid, final Long goalId, final Pageable pageable,
final String goalStatus) {

public GoalListResponse getGoalList(final String uid, final Long goalId, final Pageable pageable, final String goalStatus)
{
Member member = memberRepository.findByUid(uid).orElseThrow(() -> {
throw new BusinessException(ErrorCode.MEMBER_NOT_FOUND);
});
Member member = memberRepository.findByUid(uid).orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND));
Slice<Goal> goalList = goalQueryRepository.getGoalList(member.getId(), goalId, pageable, GoalStatus.from(goalStatus));
Slice<GoalListResponseDto> result = goalList.map(GoalListResponseDto::from);
List<GoalListResponseDto> contents = result.getContent();

Boolean next = goalList.hasNext();
return new GoalListResponse(contents, next);
return new GoalListResponse(contents, goalList.hasNext());
}

public GoalCountResponse getGoalCounts(final String uid)
{
Member member = memberRepository.findByUid(uid).orElseThrow(() -> {
throw new BusinessException(ErrorCode.MEMBER_NOT_FOUND);
});
public GoalCountResponse getGoalCounts(final String uid) {
Member member = memberRepository.findByUid(uid).orElseThrow(() -> new BusinessException(
ErrorCode.MEMBER_NOT_FOUND));

Map<GoalStatus, Long> statusCounts = goalQueryRepository.getStatusCounts(member.getId());
return new GoalCountResponse(statusCounts);
}

public RetrospectEnabledGoalCountResponse getGoalCountRetrospectEnabled(final String uid)
{
Member member = memberRepository.findByUid(uid).orElseThrow(() -> {
throw new BusinessException(ErrorCode.MEMBER_NOT_FOUND);
});
public RetrospectEnabledGoalCountResponse getGoalCountRetrospectEnabled(final String uid) {
Member member = memberRepository.findByUid(uid).orElseThrow(() -> new BusinessException(
ErrorCode.MEMBER_NOT_FOUND));

Long count = goalQueryRepository.getGoalCountRetrospectEnabled(member.getId());
return new RetrospectEnabledGoalCountResponse(count);
}


@Transactional
public Long saveGoal(final String uid, final GoalSaveRequest goalSaveRequest)
{
Member member = memberRepository.findByUid(uid).orElseThrow(() -> {
throw new BusinessException(ErrorCode.MEMBER_NOT_FOUND);
});

public Long saveGoal(final String uid, final GoalSaveRequest goalSaveRequest) {
Member member = memberRepository.findByUid(uid).orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND));
Goal goal = goalSaveRequest.toEntity(member.getId());
return goalRepository.save(goal).getId();
}
Expand All @@ -99,33 +85,33 @@ public Long saveGoal(final String uid, final GoalSaveRequest goalSaveRequest)
public GoalResponse updateGoal(final Long id, final GoalUpdateRequest goalSaveRequest) {

Goal goal = goalRepository.getByIdAndIsDeletedFalse(id);
goal.update(goalSaveRequest.title(),goalSaveRequest.startDate(),goalSaveRequest.endDate(),goalSaveRequest.reminderEnabled());
goal.update(goalSaveRequest.title(), goalSaveRequest.startDate(), goalSaveRequest.endDate(),
goalSaveRequest.reminderEnabled());
return GoalResponse.from(goal, goal.calculateDday(LocalDate.now()));
}

@Transactional
public void removeGoal(final Long goalId)
{
public void removeGoal(final Long goalId) {
Goal goal = goalRepository.getByIdAndIsDeletedFalse(goalId);
goal.remove();

applicationEventPublisher.publishEvent(new RemoveRelatedDetailGoalEvent(goal.getId()));
}

@Transactional
public void recoverGoal(final Long goalId, final GoalRecoverRequest goalRecoverRequest)
{
public void recoverGoal(final Long goalId, final GoalRecoverRequest goalRecoverRequest) {
Goal goal = goalRepository.getByIdAndIsDeletedFalse(goalId);
goal.recover(goalRecoverRequest.startDate(), goalRecoverRequest.endDate(), goalRecoverRequest.reminderEnabled());
goal.recover(goalRecoverRequest.startDate(), goalRecoverRequest.endDate(),
goalRecoverRequest.reminderEnabled());
}

public List<GoalListResponseDto> getStoredGoalList(final String uid) {

Member member = memberRepository.findByUid(uid).orElseThrow(() -> {
throw new BusinessException(ErrorCode.MEMBER_NOT_FOUND);
});
Member member = memberRepository.findByUid(uid).orElseThrow(() -> new BusinessException(
ErrorCode.MEMBER_NOT_FOUND));

List<Goal> storedGoalList = goalRepository.getGoalsByGoalStatusAndMemberIdAndIsDeletedFalse(GoalStatus.STORE, member.getId());
List<Goal> storedGoalList = goalRepository.getGoalsByGoalStatusAndMemberIdAndIsDeletedFalse(GoalStatus.STORE,
member.getId());

Random random = new Random();

Expand Down
38 changes: 15 additions & 23 deletions src/main/java/com/backend/goal/domain/Goal.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

import static com.backend.global.common.code.ErrorCode.RECOVER_GOAL_IMPOSSIBLE;
Expand All @@ -30,7 +31,7 @@ public class Goal extends BaseEntity {
private Long id;

@Column(name = "member_id")
private Long memberId; // 상위 목표를 작성한 사용자의 ID
private Long memberId;

@Column(name = "title", nullable = false)
private String title;
Expand All @@ -40,10 +41,10 @@ public class Goal extends BaseEntity {
private GoalStatus goalStatus;

@Column(name = "entire_detail_goal_cnt", nullable = false)
private Integer entireDetailGoalCnt;
private int entireDetailGoalCnt;

@Column(name = "completed_detail_goal_cnt", nullable = false)
private Integer completedDetailGoalCnt;
private int completedDetailGoalCnt;

@Column(name = "start_date", nullable = false)
private LocalDate startDate;
Expand All @@ -54,32 +55,25 @@ public class Goal extends BaseEntity {
@Column(name = "reminder_enabled", nullable = false)
private Boolean reminderEnabled;

@Column(name = "last_remind_date")
private LocalDate lastRemindDate;

@Column(name = "has_retrospect", nullable = false)
private Boolean hasRetrospect;

@Column(name = "is_deleted", nullable = false)
private Boolean isDeleted;
@Column(name = "deleted_at", nullable = false)
private LocalDateTime deletedAt;

@Column(name = "reward")
private RewardType reward;

public void remove()
{
this.isDeleted = Boolean.TRUE;
this.deletedAt = LocalDateTime.now();
}

public void writeRetrospect()
{
this.hasRetrospect = Boolean.TRUE;
}

public void updateLastRemindDate(LocalDate now)
{
this.lastRemindDate = now;
}

public void store()
{
Expand All @@ -89,7 +83,6 @@ public void store()
@PrePersist
private void init()
{
isDeleted = Boolean.FALSE;
hasRetrospect = Boolean.FALSE;
entireDetailGoalCnt = 0;
completedDetailGoalCnt = 0;
Expand All @@ -107,8 +100,7 @@ public void increaseEntireDetailGoalCnt()

public void decreaseEntireDetailGoalCnt()
{
if(entireDetailGoalCnt < 1)
{
if(entireDetailGoalCnt < 1) {
throw new BusinessException(ErrorCode.ENTIRE_DETAIL_GOAL_CNT_INVALID);
}

Expand Down Expand Up @@ -147,15 +139,15 @@ public void achieveReward(RewardType reward)
this.reward = reward;
}

public void update(final String title, final LocalDate startDate, final LocalDate endDate, final Boolean reminderEnabled)
public void update(String title, LocalDate startDate, LocalDate endDate, boolean reminderEnabled)
{
this.title = title;
this.startDate = startDate;
this.endDate = endDate;
this.reminderEnabled = reminderEnabled;
}

public Goal(final Long memberId, final String title, final LocalDate startDate, final LocalDate endDate, final Boolean reminderEnabled, final GoalStatus goalStatus)
public Goal(Long memberId, String title, LocalDate startDate, LocalDate endDate, boolean reminderEnabled, GoalStatus goalStatus)
{
validateTitleLength(title);
validatePeriod(startDate, endDate);
Expand All @@ -167,7 +159,7 @@ public Goal(final Long memberId, final String title, final LocalDate startDate,
this.goalStatus = goalStatus;
}

public void recover(final LocalDate startDate, final LocalDate endDate, final Boolean reminderEnabled)
public void recover(LocalDate startDate, LocalDate endDate, Boolean reminderEnabled)
{
if(!isRecoveringEnable())
{
Expand All @@ -181,14 +173,14 @@ public void recover(final LocalDate startDate, final LocalDate endDate, final Bo
}


private void validateTitleLength(final String title) {
private void validateTitleLength(String title) {

if (title.length() > MAX_TITLE_LENGTH) {
throw new IllegalArgumentException(String.format("상위 목표 제목의 길이는 %d을 초과할 수 없습니다.", MAX_TITLE_LENGTH));
}
}

private void validatePeriod(final LocalDate startDate, final LocalDate endDate) {
private void validatePeriod(LocalDate startDate, LocalDate endDate) {

if (startDate.isAfter(endDate)) {
throw new IllegalArgumentException("종료일시가 시작일시보다 이전일 수 없습니다.");
Expand All @@ -200,7 +192,7 @@ private void validatePeriod(final LocalDate startDate, final LocalDate endDate)
}
}

public Long calculateDday(final LocalDate now)
public Long calculateDday(LocalDate now)
{
if(now.isAfter(endDate))
{
Expand All @@ -210,7 +202,7 @@ public Long calculateDday(final LocalDate now)
return ChronoUnit.DAYS.between(now, endDate);
}

private boolean isNotValidDateTimeRange(final LocalDate date) {
private boolean isNotValidDateTimeRange(LocalDate date) {
return date.isBefore(MIN_DATE) || date.isAfter(MAX_DATE);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@
public interface GoalRepository extends JpaRepository<Goal, Long> {

default Goal getByIdAndIsDeletedFalse(Long id){

return findById(id).orElseThrow(() -> {throw new BusinessException(ErrorCode.GOAL_NOT_FOUND);
});
return findById(id).orElseThrow(() -> new BusinessException(ErrorCode.GOAL_NOT_FOUND));
}

int countByGoalStatusAndMemberIdAndIsDeletedFalse(GoalStatus goalStatus, Long memberId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,10 @@ public ResponseEntity<CustomResponse<GoalResponse>> updateGoal(@Parameter(descri
@Operation(summary = "상위 목표 생성", description = "상위 목표를 생성하는 API 입니다.")
@ApiResponse(responseCode = "201", description = "code : 201, message : INSERT_SUCCESS")
@PostMapping
public ResponseEntity<CustomResponse<Void>> saveGoal(@AuthenticationPrincipal UserDetails userDetails, @RequestBody @Valid GoalSaveRequest goalSaveRequest)
{
// 아직 유저 식별 값으로 뭐가 들어올지 몰라 1L로 설정해놨습니다.
public ResponseEntity<CustomResponse<Void>> saveGoal(
@AuthenticationPrincipal UserDetails userDetails,
@RequestBody @Valid GoalSaveRequest goalSaveRequest
) {
goalService.saveGoal(userDetails.getUsername(), goalSaveRequest);
return CustomResponse.success(INSERT_SUCCESS);
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/config

0 comments on commit 6bba2cc

Please sign in to comment.