Commit acbc5337 authored by André Luiz Marques Macrini Leite's avatar André Luiz Marques Macrini Leite
Browse files

refactor task completion

parent a23fb8b2
Showing with 116 additions and 20 deletions
+116 -20
...@@ -59,5 +59,4 @@ public class EventController { ...@@ -59,5 +59,4 @@ public class EventController {
public EventDetailsResponseDTO cancelParticipate(@PathVariable String id) { return this.service.cancelParticipate(id); public EventDetailsResponseDTO cancelParticipate(@PathVariable String id) { return this.service.cancelParticipate(id);
} }
} }
...@@ -33,4 +33,10 @@ public class TaskController { ...@@ -33,4 +33,10 @@ public class TaskController {
@PutMapping("/leave-task/{id}") @PutMapping("/leave-task/{id}")
public void leaveTask(@PathVariable String id, @RequestBody TaskDTO dto) { this.service.leaveTask(id, dto); public void leaveTask(@PathVariable String id, @RequestBody TaskDTO dto) { this.service.leaveTask(id, dto);
} }
@PutMapping("/evaluation-task/{id}")
public void evaluationTask(@PathVariable String id, @RequestBody TaskDTO dto) {
this.service.evaluationTask(id, dto);
}
} }
package br.com.ages.mutiraodobemback.domain; package br.com.ages.mutiraodobemback.domain;
import br.com.ages.mutiraodobemback.enums.EvaluationType;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Data; import lombok.Data;
...@@ -26,4 +27,7 @@ public class TaskEntity { ...@@ -26,4 +27,7 @@ public class TaskEntity {
@NonNull @NonNull
private LocalDateTime createDate; private LocalDateTime createDate;
private LocalDateTime endDate; private LocalDateTime endDate;
private EvaluationType evaluationType;
private UserEntity userConclusion;
} }
package br.com.ages.mutiraodobemback.dto; package br.com.ages.mutiraodobemback.dto;
import br.com.ages.mutiraodobemback.enums.EvaluationType;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Data; import lombok.Data;
...@@ -12,4 +13,5 @@ import lombok.NoArgsConstructor; ...@@ -12,4 +13,5 @@ import lombok.NoArgsConstructor;
public class TaskDTO { public class TaskDTO {
private String id; private String id;
private String description; private String description;
private EvaluationType evaluationType;
} }
package br.com.ages.mutiraodobemback.enums;
public enum EvaluationType {
POSITIVE,
NEGATIVE
}
...@@ -28,5 +28,10 @@ public class Message { ...@@ -28,5 +28,10 @@ public class Message {
public static final String TAREFA_JA_POSSUI_VOLUNTARIO = "Ação inválida. A tarefa já possuí voluntário."; public static final String TAREFA_JA_POSSUI_VOLUNTARIO = "Ação inválida. A tarefa já possuí voluntário.";
public static final String TAREFA_NAO_PODE_SER_CONCLUIDA = "Ação inválida. A tarefa não pode ser concluída."; public static final String TAREFA_NAO_PODE_SER_CONCLUIDA = "Ação inválida. A tarefa não pode ser concluída.";
public static final String TAREFA_NAO_PODE_SER_ABANDONADA = "Ação inválida. Não foi possível abandonar a tarefa.."; public static final String TAREFA_NAO_PODE_SER_ABANDONADA = "Ação inválida. Não foi possível abandonar a tarefa..";
public static final String TAREFA_NAO_ENCONTRADA = "Tarefa não encontrada.";
public static final String AVALIACAO_EH_OBRIGATORIA = "A avaliação é obrigatória.";
public static final String TAREFA_NAO_POSSUI_USUARIO_DE_CONCLUSAO = "A tarefa não possui usuário de conclusão.";
public static final String NAO_FOI_VOCE_QUEM_CONCLUIU_A_TAREFA = "Não foi você quem concluiu a tarefa.";
public static final String TAREFA_JA_CONCLUIDA = "Ação inválida. A tarefa já está concluída.";
} }
...@@ -101,8 +101,8 @@ public class EventServiceImpl implements IEventService { ...@@ -101,8 +101,8 @@ public class EventServiceImpl implements IEventService {
String loggedUserId = userService.getLoggedUser().getId(); String loggedUserId = userService.getLoggedUser().getId();
if (event.getVolunteer() != null) { if (event.getVolunteer() != null) {
event.setLoggedUserParticipate(event.getVolunteer() event.setLoggedUserParticipate(event.getVolunteer()
.stream() .stream()
.anyMatch(volunteer -> loggedUserId.equalsIgnoreCase(volunteer.getId()))); .anyMatch(volunteer -> loggedUserId.equalsIgnoreCase(volunteer.getId())));
} }
if (event.getTasks() != null) { if (event.getTasks() != null) {
...@@ -112,8 +112,8 @@ public class EventServiceImpl implements IEventService { ...@@ -112,8 +112,8 @@ public class EventServiceImpl implements IEventService {
double percentFinished = ((double) completedTasks / (double) totalTasks) * 100; double percentFinished = ((double) completedTasks / (double) totalTasks) * 100;
double taskProgress = Double.isInfinite(percentFinished) || Double.isNaN(percentFinished) ? 0 : BigDecimal.valueOf(percentFinished) double taskProgress = Double.isInfinite(percentFinished) || Double.isNaN(percentFinished) ? 0 : BigDecimal.valueOf(percentFinished)
.setScale(1, RoundingMode.HALF_UP) .setScale(1, RoundingMode.HALF_UP)
.doubleValue(); .doubleValue();
event.setTaskProgress(taskProgress); event.setTaskProgress(taskProgress);
} }
...@@ -135,22 +135,22 @@ public class EventServiceImpl implements IEventService { ...@@ -135,22 +135,22 @@ public class EventServiceImpl implements IEventService {
} }
private void validateFields(EventRequestDTO event) { private void validateFields(EventRequestDTO event) {
if (Validations.isEmptyOrisBlank(event.getTitle())) if (Validations.isEmptyOrIsBlank(event.getTitle()))
throw new CustomIllegalArgumentException(NOME_OBRIGATORIO); throw new CustomIllegalArgumentException(NOME_OBRIGATORIO);
// if (Validations.isEmptyOrisBlank(event.getStreet())) // if (Validations.isEmptyOrisBlank(event.getStreet()))
// throw new CustomIllegalArgumentException(ENDERECO_OBRIGATORIO); // throw new CustomIllegalArgumentException(ENDERECO_OBRIGATORIO);
if (Validations.isEmptyOrisBlank(event.getStartDate().toString())) if (Validations.isEmptyOrIsBlank(event.getStartDate().toString()))
throw new CustomIllegalArgumentException(DATA_INICIAL_OBRIGATORIO); throw new CustomIllegalArgumentException(DATA_INICIAL_OBRIGATORIO);
if (Validations.isEmptyOrisBlank(event.getEndDate().toString())) if (Validations.isEmptyOrIsBlank(event.getEndDate().toString()))
throw new CustomIllegalArgumentException(DATA_FINAL_OBRIGATORIO); throw new CustomIllegalArgumentException(DATA_FINAL_OBRIGATORIO);
if (Validations.isAfter(event.getStartDate(), event.getEndDate())) if (Validations.isAfter(event.getStartDate(), event.getEndDate()))
throw new CustomIllegalArgumentException(DATA_INICIAL_MAIOR_QUE_DATA_FINAL); throw new CustomIllegalArgumentException(DATA_INICIAL_MAIOR_QUE_DATA_FINAL);
if (Validations.isEmptyOrisBlank(event.getDescription())) if (Validations.isEmptyOrIsBlank(event.getDescription()))
throw new CustomIllegalArgumentException(DESCRICAO_OBRIGATORIO); throw new CustomIllegalArgumentException(DESCRICAO_OBRIGATORIO);
// if (Validations.isEmptyOrisBlank(event.getLatitude())) // if (Validations.isEmptyOrisBlank(event.getLatitude()))
......
...@@ -12,4 +12,6 @@ public interface ITaskService { ...@@ -12,4 +12,6 @@ public interface ITaskService {
void completeTask(String id, TaskDTO dto); void completeTask(String id, TaskDTO dto);
void leaveTask(String id, TaskDTO dto); void leaveTask(String id, TaskDTO dto);
void evaluationTask(String id, TaskDTO dto);
} }
...@@ -8,14 +8,15 @@ import br.com.ages.mutiraodobemback.service.event.IEventService; ...@@ -8,14 +8,15 @@ import br.com.ages.mutiraodobemback.service.event.IEventService;
import br.com.ages.mutiraodobemback.service.user.IUserService; import br.com.ages.mutiraodobemback.service.user.IUserService;
import br.com.ages.mutiraodobemback.util.Validations; import br.com.ages.mutiraodobemback.util.Validations;
import br.com.ages.mutiraodobemback.util.exceptions.CustomIllegalArgumentException; import br.com.ages.mutiraodobemback.util.exceptions.CustomIllegalArgumentException;
import br.com.ages.mutiraodobemback.util.exceptions.TaskNotFoundException;
import br.com.ages.mutiraodobemback.util.exceptions.UserAlreadyParticipate; import br.com.ages.mutiraodobemback.util.exceptions.UserAlreadyParticipate;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PutMapping;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional;
import static br.com.ages.mutiraodobemback.message.Message.*; import static br.com.ages.mutiraodobemback.message.Message.*;
import static br.com.ages.mutiraodobemback.message.Message.NAO_FOI_POSSIVEL_REMOVER_A_TAREFA; import static br.com.ages.mutiraodobemback.message.Message.NAO_FOI_POSSIVEL_REMOVER_A_TAREFA;
...@@ -36,7 +37,7 @@ public class TaskServiceImpl implements ITaskService { ...@@ -36,7 +37,7 @@ public class TaskServiceImpl implements ITaskService {
@Override @Override
public void createTask(String id, TaskDTO dto) { public void createTask(String id, TaskDTO dto) {
if(Validations.isNull(dto.getDescription()) || Validations.isEmptyOrisBlank(dto.getDescription())) if(Validations.isNull(dto.getDescription()) || Validations.isEmptyOrIsBlank(dto.getDescription()))
throw new CustomIllegalArgumentException(DESCRICAO_EH_OBRIGATORIA); throw new CustomIllegalArgumentException(DESCRICAO_EH_OBRIGATORIA);
EventEntity event = this.eventService.findEntityById(id); EventEntity event = this.eventService.findEntityById(id);
List<TaskEntity> list = event.getTasks() != null ? event.getTasks() : new ArrayList<>(); List<TaskEntity> list = event.getTasks() != null ? event.getTasks() : new ArrayList<>();
...@@ -62,13 +63,19 @@ public class TaskServiceImpl implements ITaskService { ...@@ -62,13 +63,19 @@ public class TaskServiceImpl implements ITaskService {
String loggedUserId = userService.getLoggedUser().getId(); String loggedUserId = userService.getLoggedUser().getId();
boolean isEventOwner = loggedUserId.equalsIgnoreCase(event.getUser().getId()); boolean isEventOwner = loggedUserId.equalsIgnoreCase(event.getUser().getId());
boolean isDeleted = event.getTasks().removeIf(task -> TaskEntity taskToDelete = event.getTasks().stream()
(isEventOwner || loggedUserId.equalsIgnoreCase(task.getOwner().getId())) .filter(task -> (isEventOwner || loggedUserId.equalsIgnoreCase(task.getOwner().getId()))
&& dto.getId().equalsIgnoreCase(task.getId()) && dto.getId().equalsIgnoreCase(task.getId()))
); .findFirst()
.orElse(null);
if (Validations.isNull(taskToDelete))
throw new TaskNotFoundException();
if (Validations.isNotNull(taskToDelete.getEndDate()))
throw new CustomIllegalArgumentException(TAREFA_JA_CONCLUIDA);
if (!isDeleted) event.getTasks().remove(taskToDelete);
throw new CustomIllegalArgumentException(NAO_FOI_POSSIVEL_REMOVER_A_TAREFA);
eventService.save(event); eventService.save(event);
} }
...@@ -98,15 +105,18 @@ public class TaskServiceImpl implements ITaskService { ...@@ -98,15 +105,18 @@ public class TaskServiceImpl implements ITaskService {
throw new CustomIllegalArgumentException(ID_EH_OBRIGATORIO); throw new CustomIllegalArgumentException(ID_EH_OBRIGATORIO);
EventEntity event = this.eventService.findEntityById(id); EventEntity event = this.eventService.findEntityById(id);
String loggedUserId = userService.getLoggedUser().getId(); UserEntity loggedUser = userService.getLoggedUser();
TaskEntity taskToComplete = event.getTasks() TaskEntity taskToComplete = event.getTasks()
.stream() .stream()
.filter(task -> Validations.isNotNull(task.getVolunteer()) && loggedUserId.equalsIgnoreCase(task.getVolunteer().getId()) && dto.getId().equalsIgnoreCase(task.getId())) .filter(task -> Validations.isNotNull(task.getVolunteer()) &&
!loggedUser.getId().equalsIgnoreCase(task.getVolunteer().getId()) &&
dto.getId().equalsIgnoreCase(task.getId()))
.findFirst() .findFirst()
.orElseThrow(() -> new UserAlreadyParticipate(TAREFA_NAO_PODE_SER_CONCLUIDA)); .orElseThrow(() -> new UserAlreadyParticipate(TAREFA_NAO_PODE_SER_CONCLUIDA));
taskToComplete.setEndDate(LocalDateTime.now()); taskToComplete.setEndDate(LocalDateTime.now());
taskToComplete.setUserConclusion(loggedUser);
eventService.save(event); eventService.save(event);
} }
...@@ -127,4 +137,36 @@ public class TaskServiceImpl implements ITaskService { ...@@ -127,4 +137,36 @@ public class TaskServiceImpl implements ITaskService {
taskToLeave.setVolunteer(null); taskToLeave.setVolunteer(null);
eventService.save(event); eventService.save(event);
} }
@Override
public void evaluationTask(String id, TaskDTO dto) {
if (Validations.isNull(dto.getId()))
throw new CustomIllegalArgumentException(ID_EH_OBRIGATORIO);
if (Validations.isNull(dto.getEvaluationType()))
throw new CustomIllegalArgumentException(AVALIACAO_EH_OBRIGATORIA);
EventEntity event = this.eventService.findEntityById(id);
TaskEntity task = this.findTaskById(event.getTasks(), dto.getId());
if (Validations.isNull(task))
throw new TaskNotFoundException();
if (Validations.isNull(task.getUserConclusion()))
throw new CustomIllegalArgumentException(TAREFA_NAO_POSSUI_USUARIO_DE_CONCLUSAO);
String loggedUserId = userService.getLoggedUser().getId();
if (!task.getUserConclusion().getId().equalsIgnoreCase(loggedUserId) &&
!event.getUser().getId().equalsIgnoreCase(loggedUserId))
throw new CustomIllegalArgumentException(NAO_FOI_VOCE_QUEM_CONCLUIU_A_TAREFA);
task.setEvaluationType(dto.getEvaluationType());
this.eventService.save(event);
}
private TaskEntity findTaskById(List<TaskEntity> tasks, String taskId) {
return tasks.stream()
.filter(task -> task.getId().equalsIgnoreCase(taskId)).findFirst()
.orElse(null);
}
} }
...@@ -4,7 +4,7 @@ import java.time.LocalDateTime; ...@@ -4,7 +4,7 @@ import java.time.LocalDateTime;
public class Validations { public class Validations {
public static boolean isEmptyOrisBlank(String value) { public static boolean isEmptyOrIsBlank(String value) {
return (value.isBlank() || value.isEmpty()); return (value.isBlank() || value.isEmpty());
} }
......
package br.com.ages.mutiraodobemback.util.exceptions;
import static br.com.ages.mutiraodobemback.message.Message.TAREFA_NAO_ENCONTRADA;
public class TaskNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TaskNotFoundException() {
super(TAREFA_NAO_ENCONTRADA);
}
}
package br.com.ages.mutiraodobemback.util.handlers;
import br.com.ages.mutiraodobemback.util.exceptions.TaskNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class TaskExceptionHandler {
@ExceptionHandler(value = TaskNotFoundException.class)
public ResponseEntity<Object> handleException(TaskNotFoundException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment