Skip to content

Commit

Permalink
Merge pull request #232 from MOONSHOT-Team/feature/#231
Browse files Browse the repository at this point in the history
[Feat] #231 - User, Log, Task Validator 분리
  • Loading branch information
0lynny authored Feb 29, 2024
2 parents 3c54146 + cb57fd7 commit 43a6391
Show file tree
Hide file tree
Showing 11 changed files with 152 additions and 98 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package org.moonshot.keyresult.service;

import static org.moonshot.keyresult.service.validator.KeyResultValidator.*;
import static org.moonshot.log.service.validator.LogValidator.validateLogNum;
import static org.moonshot.task.service.validator.TaskValidator.validateTaskIndex;
import static org.moonshot.user.service.validator.UserValidator.validateUserAuthorization;
import static org.moonshot.validator.IndexValidator.isIndexIncreased;
import static org.moonshot.validator.IndexValidator.isSameIndex;

import java.time.LocalDate;
import java.util.List;
Expand All @@ -12,7 +17,6 @@
import org.moonshot.exception.keyresult.KeyResultRequiredException;
import org.moonshot.exception.log.LogNotFoundException;
import org.moonshot.exception.objective.ObjectiveNotFoundException;
import org.moonshot.exception.task.TaskInvalidIndexException;
import org.moonshot.keyresult.dto.request.KeyResultCreateRequestDto;
import org.moonshot.keyresult.dto.request.KeyResultCreateRequestInfoDto;
import org.moonshot.keyresult.dto.request.KeyResultModifyRequestDto;
Expand Down Expand Up @@ -149,13 +153,13 @@ public Optional<AchieveResponseDto> modifyKeyResult(final KeyResultModifyRequest
}

Log updateLog = logService.createUpdateLog(request, keyResult.getId());
validateLogValue(request.target(), updateLog.getKeyResult().getTarget());
validateLogNum(request.target(), updateLog.getKeyResult().getTarget());

Log prevLog = logRepository.findLatestLogByKeyResultId(LogState.RECORD, request.keyResultId())
.orElseThrow(LogNotFoundException::new);
Optional<Log> prevLog = logRepository.findLatestLogByKeyResultId(LogState.RECORD, request.keyResultId());
keyResult.modifyTarget(request.target());
keyResult.modifyProgress(logService.calculateKRProgressBar(prevLog, keyResult.getTarget()));

if(prevLog.isPresent()) {
keyResult.modifyProgress(logService.calculateKRProgressBar(prevLog.get(), keyResult.getTarget()));
}
short progress = logService.calculateOProgressBar(keyResult.getObjective());
keyResult.getObjective().modifyProgress(progress);

Expand All @@ -176,12 +180,12 @@ public void modifyIdx(final ModifyIndexRequestDto request, final Long userId) {
validateIndex(krCount, request.idx());

Integer prevIdx = keyResult.getIdx();
if (prevIdx.equals(request.idx())) {
if (isSameIndex(prevIdx, request.idx())) {
return;
}

keyResult.modifyIdx(request.idx());
if (prevIdx < request.idx()) {
if (isIndexIncreased(prevIdx, request.idx())) {
keyResultRepository.bulkUpdateIdxDecrease(prevIdx + 1, request.idx(), keyResult.getObjective().getId(), keyResult.getId());
} else {
keyResultRepository.bulkUpdateIdxIncrease(request.idx(), prevIdx, keyResult.getObjective().getId(), keyResult.getId());
Expand Down Expand Up @@ -216,9 +220,7 @@ private void saveTasks(final KeyResult keyResult, final List<TaskCreateRequestDt
List<TaskCreateRequestDto> nonNullTaskList = taskList.stream().filter(Objects::nonNull).toList();
for (int i = 0; i < nonNullTaskList.size(); i++) {
TaskCreateRequestDto taskDto = nonNullTaskList.get(i);
if (i != taskDto.idx()) {
throw new TaskInvalidIndexException();
}
validateTaskIndex(i, taskDto.idx());
taskService.saveTask(keyResult, taskDto);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,14 @@
import java.time.LocalDate;
import java.util.List;
import org.moonshot.common.model.Period;
import org.moonshot.exception.global.auth.AccessDeniedException;
import org.moonshot.exception.keyresult.KeyResultInvalidIndexException;
import org.moonshot.exception.keyresult.KeyResultInvalidPeriodException;
import org.moonshot.exception.keyresult.KeyResultNumberExceededException;
import org.moonshot.exception.log.InvalidLogValueException;

public class KeyResultValidator {

private static final int ACTIVE_KEY_RESULT_NUMBER = 3;

public static void validateUserAuthorization(final Long userEntityId, final Long userId) {
if (!userEntityId.equals(userId)) {
throw new AccessDeniedException();
}
}

public static void validateKeyResultIndex(final int index, final int requestIndex) {
if (index != requestIndex) {
throw new KeyResultInvalidIndexException();
Expand All @@ -44,14 +36,8 @@ public static void validateIndexUnderMaximum(final int requestIndex, final int t
}
}

public static void validateLogValue(Long requestTarget, Long originTarget) {
if (requestTarget.equals(originTarget)) {
throw new InvalidLogValueException();
}
}

public static void validateKeyResultPeriod(final Period objPeriod, final LocalDate start, final LocalDate end) {
if (start.isAfter(end) || start.isBefore(objPeriod.getStartAt()) || start.isAfter(objPeriod.getStartAt())
if (start.isAfter(end) || start.isBefore(objPeriod.getStartAt()) || start.isAfter(objPeriod.getExpireAt())
|| end.isBefore(start) || end.isBefore(objPeriod.getStartAt()) || end.isAfter(objPeriod.getExpireAt())) {
throw new KeyResultInvalidPeriodException();
}
Expand Down
23 changes: 10 additions & 13 deletions moonshot-api/src/main/java/org/moonshot/log/service/LogService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.moonshot.exception.log.InvalidLogValueException;
import org.moonshot.exception.global.auth.AccessDeniedException;
import org.moonshot.exception.keyresult.KeyResultNotFoundException;
import org.moonshot.keyresult.dto.request.KeyResultCreateRequestDto;
import org.moonshot.keyresult.dto.request.KeyResultCreateRequestInfoDto;
Expand All @@ -23,6 +21,12 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static org.moonshot.keyresult.service.validator.KeyResultValidator.isKeyResultAchieved;
import static org.moonshot.log.service.validator.LogValidator.isCreateLog;
import static org.moonshot.log.service.validator.LogValidator.validateLogNum;
import static org.moonshot.user.service.validator.UserValidator.validateUserAuthorization;


@Service
@Transactional
@RequiredArgsConstructor
Expand All @@ -34,17 +38,10 @@ public class LogService {
public Optional<AchieveResponseDto> createRecordLog(final Long userId, final LogCreateRequestDto request) {
KeyResult keyResult = keyResultRepository.findKeyResultAndObjective(request.keyResultId())
.orElseThrow(KeyResultNotFoundException::new);
if (!keyResult.getObjective().getUser().getId().equals(userId)) {
throw new AccessDeniedException();
}
validateUserAuthorization(keyResult.getObjective().getUser().getId(), userId);
Optional<Log> prevLog = logRepository.findLatestLogByKeyResultId(LogState.RECORD, request.keyResultId());
long prevNum = -1;
if (prevLog.isPresent()) {
prevNum = prevLog.get().getCurrNum();
if(request.logNum() == prevNum) {
throw new InvalidLogValueException();
}
}
prevLog.ifPresent(log -> validateLogNum(request.logNum(), log.getCurrNum()));
Log log = logRepository.save(Log.builder()
.date(LocalDateTime.now())
.state(LogState.RECORD)
Expand All @@ -55,7 +52,7 @@ public Optional<AchieveResponseDto> createRecordLog(final Long userId, final Log
.build());
keyResult.modifyProgress(calculateKRProgressBar(log, keyResult.getTarget()));
keyResult.getObjective().modifyProgress(calculateOProgressBar(keyResult.getObjective()));
if (keyResult.getObjective().getProgress() == 100) {
if (isKeyResultAchieved(keyResult.getObjective().getProgress())) {
return Optional.of(AchieveResponseDto.of(keyResult.getObjective().getId(), keyResult.getObjective().getUser().getNickname(), calculateOProgressBar(keyResult.getObjective())));
}
return Optional.empty();
Expand Down Expand Up @@ -116,7 +113,7 @@ public List<LogResponseDto> getLogResponseDto(final List<Log> logList, final Key
}

private String setTitle(final long prevNum, final long currNum, final Log log, final KeyResult keyResult) {
if (log.getState() == LogState.CREATE) {
if (isCreateLog(log.getState())) {
return keyResult.getTitle() + " : " + keyResult.getTarget() + keyResult.getMetric();
} else {
return (prevNum == -1 ? "0" : NumberFormat.getNumberInstance().format(prevNum)) + keyResult.getMetric()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.moonshot.log.service.validator;

import org.moonshot.exception.log.InvalidLogValueException;
import org.moonshot.log.model.LogState;

public class LogValidator {

public static void validateLogNum(Long requestNum, Long originNum) {
if (requestNum.equals(originNum)) {
throw new InvalidLogValueException();
}
}

public static boolean isCreateLog(LogState state) {
return state == LogState.CREATE;
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package org.moonshot.objective.service;

import static org.moonshot.objective.service.validator.ObjectiveValidator.*;
import static org.moonshot.user.service.validator.UserValidator.*;
import static org.moonshot.validator.IndexValidator.isIndexIncreased;
import static org.moonshot.validator.IndexValidator.isSameIndex;

import java.time.LocalDate;
import java.util.Comparator;
Expand All @@ -13,7 +16,6 @@
import org.moonshot.exception.objective.DateInputRequiredException;
import org.moonshot.exception.objective.InvalidExpiredAtException;
import org.moonshot.exception.objective.ObjectiveNotFoundException;
import org.moonshot.exception.objective.ObjectiveNumberExceededException;
import org.moonshot.exception.user.UserNotFoundException;
import org.moonshot.keyresult.service.KeyResultService;
import org.moonshot.objective.dto.request.ModifyIndexRequestDto;
Expand All @@ -34,8 +36,6 @@
@RequiredArgsConstructor
public class ObjectiveService implements IndexService {

private static final int ACTIVE_OBJECTIVE_NUMBER = 10;

private final KeyResultService keyResultService;
private final UserRepository userRepository;
private final ObjectiveRepository objectiveRepository;
Expand All @@ -45,9 +45,7 @@ public void createObjective(final Long userId, final OKRCreateRequestDto request
.orElseThrow(UserNotFoundException::new);

List<Objective> objectives = objectiveRepository.findAllByUserId(userId);
if (objectives.size() >= ACTIVE_OBJECTIVE_NUMBER) {
throw new ObjectiveNumberExceededException();
}
validateActiveObjectiveSizeExceeded(objectives.size());
objectiveRepository.bulkUpdateIdxIncrease(userId);

Objective newObjective = objectiveRepository.save(Objective.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,22 @@
package org.moonshot.objective.service.validator;

import org.moonshot.exception.global.auth.AccessDeniedException;
import org.moonshot.exception.objective.ObjectiveInvalidIndexException;
import org.moonshot.exception.objective.ObjectiveNumberExceededException;

public class ObjectiveValidator {

public static void validateUserAuthorization(Long userEntityId, Long userId) {
if (!userEntityId.equals(userId)) {
throw new AccessDeniedException();
}
}
private static final int ACTIVE_OBJECTIVE_NUMBER = 10;

public static void validateIndexWithInRange(final Long objectiveCount, final int idx) {
if ((objectiveCount <= idx) || (idx < 0)) {
throw new ObjectiveInvalidIndexException();
}
}

public static boolean isSameIndex(final int prevIdx, final int idx) {
return prevIdx == idx;
}

public static boolean isIndexIncreased(final int prevIdx, final int idx) {
return prevIdx < idx;
public static void validateActiveObjectiveSizeExceeded(final int objListSize) {
if (objListSize >= ACTIVE_OBJECTIVE_NUMBER) {
throw new ObjectiveNumberExceededException();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

import java.util.List;
import lombok.RequiredArgsConstructor;
import org.moonshot.exception.global.auth.AccessDeniedException;
import org.moonshot.exception.keyresult.KeyResultInvalidIndexException;
import org.moonshot.exception.task.TaskNotFoundException;
import org.moonshot.exception.task.TaskNumberExceededException;
import org.moonshot.keyresult.model.KeyResult;
import org.moonshot.keyresult.repository.KeyResultRepository;
import org.moonshot.objective.dto.request.ModifyIndexRequestDto;
Expand All @@ -17,29 +14,26 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static org.moonshot.task.service.validator.TaskValidator.*;
import static org.moonshot.user.service.validator.UserValidator.validateUserAuthorization;
import static org.moonshot.validator.IndexValidator.isIndexIncreased;
import static org.moonshot.validator.IndexValidator.isSameIndex;

@Service
@Transactional
@RequiredArgsConstructor
public class TaskService implements IndexService {

private static final int ACTIVE_TASK_NUMBER = 3;

private final KeyResultRepository keyResultRepository;
private final TaskRepository taskRepository;
public void createTask(final TaskSingleCreateRequestDto request, final Long userId) {
KeyResult keyResult = keyResultRepository.findKeyResultAndObjective(request.keyResultId())
.orElseThrow();
if (!keyResult.getObjective().getUser().getId().equals(userId)) {
throw new AccessDeniedException();
}
List<Task> taskList = taskRepository.findAllByKeyResultOrderByIdx(keyResult);
validateUserAuthorization(keyResult.getObjective().getUser().getId(), userId);

if (taskList.size() >= ACTIVE_TASK_NUMBER) {
throw new TaskNumberExceededException();
}
if (request.idx() > taskList.size()) {
throw new KeyResultInvalidIndexException();
}
List<Task> taskList = taskRepository.findAllByKeyResultOrderByIdx(keyResult);
validateActiveTaskSizeExceeded(taskList.size());
validateIndexUnderMaximum(request.idx(), taskList.size());

for (int i = request.idx(); i < taskList.size(); i++) {
taskList.get(i).incrementIdx();
Expand Down Expand Up @@ -69,36 +63,28 @@ public void saveTask(final KeyResult keyResult, final TaskCreateRequestDto reque
public void modifyIdx(final ModifyIndexRequestDto request, final Long userId) {
Task task = taskRepository.findTaskWithFetchJoin(request.id())
.orElseThrow(TaskNotFoundException::new);
if (task.getKeyResult().getObjective().getUser().getId().equals(userId)) {
throw new AccessDeniedException();
}
validateUserAuthorization(task.getKeyResult().getObjective().getUser().getId(), userId);

Long taskCount = taskRepository.countAllByKeyResultId(task.getKeyResult().getId());
if (isInvalidIdx(taskCount, request.idx())) {
throw new KeyResultInvalidIndexException();
}
validateIndex(taskCount, request.idx());
Integer prevIdx = task.getIdx();
if (prevIdx.equals(request.idx())) {
if (isSameIndex(prevIdx, request.idx())) {
return;
}

task.modifyIdx(request.idx());
if (prevIdx < request.idx()) {
if (isIndexIncreased(prevIdx, request.idx())) {
taskRepository.bulkUpdateTaskIdxDecrease(prevIdx + 1, request.idx(), task.getKeyResult().getId(), task.getId());
} else {
taskRepository.bulkUpdateTaskIdxIncrease(request.idx(), prevIdx, task.getKeyResult().getId(), task.getId());
}
}

private boolean isInvalidIdx(final Long taskCount, final int idx) {
return (taskCount <= idx) || (idx < 0);
}

public void deleteTask(final Long userId, Long taskId) {
Task task = taskRepository.findTaskWithFetchJoin(taskId)
.orElseThrow(TaskNotFoundException::new);
if (task.getKeyResult().getObjective().getUser().getId().equals(userId)) {
throw new AccessDeniedException();
}
validateUserAuthorization(task.getKeyResult().getObjective().getUser().getId(), userId);

taskRepository.deleteById(taskId);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.moonshot.task.service.validator;

import org.moonshot.exception.task.TaskInvalidIndexException;
import org.moonshot.exception.task.TaskNumberExceededException;

public class TaskValidator {

private static final int ACTIVE_TASK_NUMBER = 3;

public static void validateTaskIndex(final int index, final int requestIndex) {
if (index != requestIndex) {
throw new TaskInvalidIndexException();
}
}

public static void validateActiveTaskSizeExceeded(final int taskListSize) {
if (taskListSize >= ACTIVE_TASK_NUMBER) {
throw new TaskNumberExceededException();
}
}

public static void validateIndexUnderMaximum(final int requestIndex, final int totalTaskListSize) {
if (requestIndex > totalTaskListSize) {
throw new TaskInvalidIndexException();
}
}

public static void validateIndex(final Long taskCount, final Integer requestIndex) {
if (taskCount <= requestIndex || requestIndex < 0) {
throw new TaskInvalidIndexException();
}
}

}
Loading

0 comments on commit 43a6391

Please sign in to comment.