diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/To-Do-Back-End.iml b/.idea/To-Do-Back-End.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/To-Do-Back-End.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..149eea4 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..bafb1e8 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..712ab9d --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..850bf4e --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..cb441c1 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/todo-app-encora/src/main/java/com/assigment/todoapp/repository/ToDoRepository.java b/todo-app-encora/src/main/java/com/assigment/todoapp/repository/ToDoRepository.java index 571821f..faa9ee4 100644 --- a/todo-app-encora/src/main/java/com/assigment/todoapp/repository/ToDoRepository.java +++ b/todo-app-encora/src/main/java/com/assigment/todoapp/repository/ToDoRepository.java @@ -1,48 +1,16 @@ package com.assigment.todoapp.repository; import java.util.List; -import java.util.stream.Collectors; - -import org.springframework.stereotype.Repository; +import java.util.UUID; import com.assigment.todoapp.domain.ToDoItem; - - -/* - @Repository -public interface ToDoRepository extends JpaRepository to create the interface and use de Database -*/ - -@Repository -public class ToDoRepository { // interface - - - private List todoItems; - - public ToDoRepository(List todoItems) { - this.todoItems = todoItems; - } - - public List fetchAllToDoItems () { - return todoItems; - } - - public List findByDone(boolean aux) { - return todoItems.stream() - .filter(item -> item.isDone() == aux) - .collect(Collectors.toList()); - } - - public List findByNameContainingIgnoreCase(String name) { - return todoItems.stream() - .filter(item -> item.getName().toLowerCase().contains(name.toLowerCase())) - .collect(Collectors.toList()); - } - - public List findByPriority(String priority) { - return todoItems.stream() - .filter(item -> item.getPriority().equalsIgnoreCase(priority)) - .collect(Collectors.toList()); - } -} +public interface ToDoRepository { + List fetchAllToDoItems(); + List findByDone(boolean done); + List findByNameContainingIgnoreCase(String name); + List findByPriority(String priority); + ToDoItem findById(UUID id); + void save(ToDoItem todoItem); + void deleteById(UUID id); +} \ No newline at end of file diff --git a/todo-app-encora/src/main/java/com/assigment/todoapp/repository/ToDoRepositoryImpl.java b/todo-app-encora/src/main/java/com/assigment/todoapp/repository/ToDoRepositoryImpl.java new file mode 100644 index 0000000..275ba05 --- /dev/null +++ b/todo-app-encora/src/main/java/com/assigment/todoapp/repository/ToDoRepositoryImpl.java @@ -0,0 +1,63 @@ +package com.assigment.todoapp.repository; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Repository; + +import com.assigment.todoapp.domain.ToDoItem; + +@Repository +public class ToDoRepositoryImpl implements ToDoRepository { + + private final List todoItems; + + public ToDoRepositoryImpl(List todoItems) { + this.todoItems = todoItems; + } + + @Override + public List fetchAllToDoItems() { + return todoItems; + } + + @Override + public List findByDone(boolean done) { + return todoItems.stream() + .filter(item -> item.isDone() == done) + .collect(Collectors.toList()); + } + + @Override + public List findByNameContainingIgnoreCase(String name) { + return todoItems.stream() + .filter(item -> item.getName().toLowerCase().contains(name.toLowerCase())) + .collect(Collectors.toList()); + } + + @Override + public List findByPriority(String priority) { + return todoItems.stream() + .filter(item -> item.getPriority().equalsIgnoreCase(priority)) + .collect(Collectors.toList()); + } + + @Override + public ToDoItem findById(UUID id) { + return todoItems.stream() + .filter(item -> item.getId().equals(id)) + .findFirst() + .orElseThrow(() -> new RuntimeException("ToDoItem not found")); + } + + @Override + public void save(ToDoItem todoItem) { + todoItems.add(todoItem); + } + + @Override + public void deleteById(UUID id) { + todoItems.removeIf(item -> item.getId().equals(id)); + } +} \ No newline at end of file diff --git a/todo-app-encora/src/main/java/com/assigment/todoapp/service/ToDoService.java b/todo-app-encora/src/main/java/com/assigment/todoapp/service/ToDoService.java index 1329297..c3696ee 100644 --- a/todo-app-encora/src/main/java/com/assigment/todoapp/service/ToDoService.java +++ b/todo-app-encora/src/main/java/com/assigment/todoapp/service/ToDoService.java @@ -1,14 +1,10 @@ package com.assigment.todoapp.service; +import java.time.Duration; +import java.time.LocalDate; import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; +import java.time.temporal.ChronoUnit; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -20,214 +16,177 @@ @Service public class ToDoService { - - @Autowired //Inject - private ToDoRepository todoRepository; - private List todoItems = new ArrayList<>(); - public boolean aux; - + + private final ToDoRepository todoRepository; + + @Autowired public ToDoService(ToDoRepository todoRepository) { - this.todoItems = todoRepository.fetchAllToDoItems(); - } - - public void setTodoItems(List todoItems) { - this.todoItems = todoItems; - } - - public List fetchAllToDoItems (String state, String name, String priority) { - - Stream stream = todoRepository.fetchAllToDoItems().stream(); - - - if (!state.equals("All")) { - - if(state.equals("Done")) { - aux = true; - }else { - aux = false; - } - stream = stream.filter(item -> item.isDone() == aux); - } - - - if (!priority.equals("All")) { - stream = stream.filter(item -> item.getPriority().equals(priority)); - } - - - if (!name.equals("")) { - stream = stream.filter(item -> item.getName().contains(name)); - } - - return stream.collect(Collectors.toList()); + this.todoRepository = todoRepository; } - + public List fetchAllToDoItems(String state, String name, String priority) { + Stream stream = todoRepository.fetchAllToDoItems().stream(); + + if (!"All".equals(state)) { + boolean isDone = "Done".equals(state); + stream = stream.filter(item -> item.isDone() == isDone); + } + + if (!"All".equals(priority)) { + stream = stream.filter(item -> item.getPriority().equals(priority)); + } - public Map paginateToDoItems( - List todoItems, - int page, - int pageSize) { + if (!name.isEmpty()) { + stream = stream.filter(item -> item.getName().contains(name)); + } - int totalItems = todoItems.size(); - int totalPages = (int) Math.ceil((double) totalItems / pageSize); - int startIndex = (page - 1) * pageSize; - int endIndex = Math.min(startIndex + pageSize, totalItems); + return stream.collect(Collectors.toList()); + } + + public Map paginateToDoItems(List todoItems, int page, int pageSize) { + int totalItems = todoItems.size(); + int totalPages = (int) Math.ceil((double) totalItems / pageSize); + int startIndex = (page - 1) * pageSize; + int endIndex = Math.min(startIndex + pageSize, totalItems); - List paginatedItems = todoItems.subList(startIndex, endIndex); - int itemsOnPage = paginatedItems.size(); + List paginatedItems = todoItems.subList(startIndex, endIndex); - Map response = new HashMap<>(); - response.put("items", paginatedItems); - response.put("currentPage", page); - response.put("totalItems", totalItems); - response.put("totalPages", totalPages); - response.put("itemsOnPage", itemsOnPage); + Map response = new HashMap<>(); + response.put("items", paginatedItems); + response.put("currentPage", page); + response.put("totalItems", totalItems); + response.put("totalPages", totalPages); + response.put("itemsOnPage", paginatedItems.size()); + + return response; + } - return response; + public List sortToDoItems(List todoItems, String sortBy1, String order1, String sortBy2, String order2) { + Comparator comparator = getComparator(sortBy1, order1, sortBy2, order2); + todoItems.sort(comparator); + return todoItems; + } + + private Comparator getComparator(String sortBy1, String order1, String sortBy2, String order2) { + Map priorityValues = Map.of("Low", 1, "Medium", 2, "High", 3); + + Comparator comparator1 = getSingleComparator(sortBy1, order1, priorityValues); + Comparator comparator2 = getSingleComparator(sortBy2, order2, priorityValues); + + return comparator1.thenComparing(comparator2); + } + + private Comparator getSingleComparator(String sortBy, String order, Map priorityValues) { + Comparator comparator; + if ("priority".equals(sortBy)) { + comparator = Comparator.comparing(item -> priorityValues.getOrDefault(item.getPriority(), 0)); + } else if ("dueDate".equals(sortBy)) { + comparator = Comparator.comparing(ToDoItem::getDueDate, Comparator.nullsLast(Comparator.naturalOrder())); + } else { + throw new IllegalArgumentException("Invalid sortBy: " + sortBy); + } + + if ("desc".equals(order)) { + comparator = comparator.reversed(); + } + + return comparator; } - - public List sortToDoItems( - List todoItems, - String sortBy1, - String order1, - String sortBy2, - String order2) { - - Collections.sort(todoItems, new Comparator() { - @Override - public int compare(ToDoItem t1, ToDoItem t2) { - Map priorityValues = new HashMap<>(); - priorityValues.put("Low", 1); - priorityValues.put("Medium", 2); - priorityValues.put("High", 3); - - int comparison1 = 0; - if (sortBy1.equals("priority")) { - int priority1Value = priorityValues.getOrDefault(t1.getPriority(), 0); - int priority2Value = priorityValues.getOrDefault(t2.getPriority(), 0); - if (order1.equals("desc")) { - priority1Value = 4 - priority1Value; - priority2Value = 4 - priority2Value; - } - comparison1 = Integer.compare(priority1Value, priority2Value); - } else if (sortBy1.equals("dueDate")) { - if (t1.getDueDate() == null && t2.getDueDate() == null) { - comparison1 = 0; - } else if (t1.getDueDate() == null) { - comparison1 = -1; - } else if (t2.getDueDate() == null) { - comparison1 = 1; - } else { - comparison1 = t1.getDueDate().compareTo(t2.getDueDate()); - } - if (order1.equals("desc")) { - comparison1 = -comparison1; - } - } - - if (comparison1 != 0) { - return comparison1; - } else { - int comparison2 = 0; - if (sortBy2.equals("priority")) { - int priority1Value = priorityValues.getOrDefault(t1.getPriority(), 0); - int priority2Value = priorityValues.getOrDefault(t2.getPriority(), 0); - if (order2.equals("desc")) { - priority1Value = 4 - priority1Value; - priority2Value = 4 - priority2Value; - } - comparison2 = Integer.compare(priority1Value, priority2Value); - } else if (sortBy2.equals("dueDate")) { - if (t1.getDueDate() == null && t2.getDueDate() == null) { - comparison2 = 0; - } else if (t1.getDueDate() == null) { - comparison2 = -1; - } else if (t2.getDueDate() == null) { - comparison2 = 1; - } else { - comparison2 = t1.getDueDate().compareTo(t2.getDueDate()); - } - if (order2.equals("desc")) { - comparison2 = -comparison2; - } - } - return comparison2; - } - } - }); - - return todoItems; - } public ToDoItem createToDoItem(ToDoItem todoItem) { - todoItem.setId(UUID.randomUUID()); - todoItem.setCreationDate(LocalDateTime.now()); - todoItem.setDone(false); - - - todoItems.add(todoItem); - return todoItem; - } - + todoItem.setId(UUID.randomUUID()); + todoItem.setCreationDate(LocalDateTime.now()); + todoItem.setDone(false); + todoRepository.save(todoItem); + return todoItem; + } + public ToDoItem updateFlag(UUID id, ToDoItem todoItem) { - Optional existingToDoItem = todoItems.stream() - .filter(item -> item.getId().equals(id)) - .findFirst(); - - if (existingToDoItem.isEmpty()) { - throw new RuntimeException("ToDoItem no encontrado"); - } - ToDoItem existingItem = existingToDoItem.get(); - - if(existingItem.isDone()== false) { - existingItem.setDone(todoItem.isDone()); - existingItem.setDoneDate(LocalDateTime.now()); - return existingItem; - }else { - existingItem.setDone(todoItem.isDone()); - existingItem.setDoneDate(null); - return existingItem; - } - - + ToDoItem existingItem = todoRepository.findById(id); + existingItem.setDone(todoItem.isDone()); + existingItem.setDoneDate(todoItem.isDone() ? LocalDateTime.now() : null); + todoRepository.save(existingItem); + return existingItem; } public ToDoItem updateToDoItem(UUID id, ToDoItem updatedToDoItem) { - Optional existingToDoItem = todoItems.stream() - .filter(item -> item.getId().equals(id)) - .findFirst(); - - if (existingToDoItem.isEmpty()) { - throw new RuntimeException("ToDoItem no encontrado"); - } - - ToDoItem existingItem = existingToDoItem.get(); - existingItem.setName(updatedToDoItem.getName()); - existingItem.setDone(updatedToDoItem.isDone()); - existingItem.setPriority(updatedToDoItem.getPriority()); - existingItem.setDueDate(updatedToDoItem.getDueDate()); - return existingItem; + ToDoItem existingItem = todoRepository.findById(id); + existingItem.setName(updatedToDoItem.getName()); + existingItem.setDone(updatedToDoItem.isDone()); + existingItem.setPriority(updatedToDoItem.getPriority()); + existingItem.setDueDate(updatedToDoItem.getDueDate()); + todoRepository.save(existingItem); + return existingItem; } public void deleteToDoItem(UUID id) { - todoItems.removeIf(item -> item.getId().equals(id)); + todoRepository.deleteById(id); } public List fetchAllDoneToDoItems(String priority) { - List doneItems = todoItems.stream() - .filter(item -> item.isDone() && (priority.equals("All") || item.getPriority().equals(priority))) - .collect(Collectors.toList()); - - return doneItems; - } + return todoRepository.findByDone(true).stream() + .filter(item -> "All".equals(priority) || item.getPriority().equals(priority)) + .collect(Collectors.toList()); + } public List fetchAllItems() { - List doneItems = todoItems.stream().collect(Collectors.toList()); + return todoRepository.fetchAllToDoItems(); + } + + public List> fetchToDoItemsWithFlags() { + List toDoItems = fetchAllItems(); + List> toDoItemFlags = new ArrayList<>(); + + for (ToDoItem item : toDoItems) { + Map itemFlag = new HashMap<>(); + itemFlag.put("item", item); + + if (item.getDueDate() == null) { + itemFlag.put("flag", 0); + } else { + long weeksBetween = ChronoUnit.WEEKS.between(LocalDate.now(), item.getDueDate()); + + if (weeksBetween <= 1) { + itemFlag.put("flag", 1); + } else if (weeksBetween <= 2) { + itemFlag.put("flag", 2); + } else { + itemFlag.put("flag", 3); + } + } - return doneItems; + toDoItemFlags.add(itemFlag); + } + + return toDoItemFlags; + } + + public double fetchAverageCompletionTime(List doneItems) { + long totalDuration = 0; + for (ToDoItem item : doneItems) { + Duration duration = Duration.between(item.getCreationDate(), item.getDoneDate()); + totalDuration += duration.toMillis(); + } + return (double) totalDuration / doneItems.size(); } - - -} + public Map fetchAverageCompletionTimes() { + List doneItemsAll = fetchAllDoneToDoItems("All"); + List doneItemsHigh = fetchAllDoneToDoItems("High"); + List doneItemsMedium = fetchAllDoneToDoItems("Medium"); + List doneItemsLow = fetchAllDoneToDoItems("Low"); + + double averageDurationAll = fetchAverageCompletionTime(doneItemsAll); + double averageDurationHigh = fetchAverageCompletionTime(doneItemsHigh); + double averageDurationMedium = fetchAverageCompletionTime(doneItemsMedium); + double averageDurationLow = fetchAverageCompletionTime(doneItemsLow); + + Map response = new HashMap<>(); + response.put("averageTimeAll", averageDurationAll); + response.put("averageTimeHigh", averageDurationHigh); + response.put("averageTimeMedium", averageDurationMedium); + response.put("averageTimeLow", averageDurationLow); + + return response; + } +} \ No newline at end of file diff --git a/todo-app-encora/src/main/java/com/assigment/todoapp/web/ToDoController.java b/todo-app-encora/src/main/java/com/assigment/todoapp/web/ToDoController.java index f1e6bf2..4ac3ab7 100644 --- a/todo-app-encora/src/main/java/com/assigment/todoapp/web/ToDoController.java +++ b/todo-app-encora/src/main/java/com/assigment/todoapp/web/ToDoController.java @@ -1,177 +1,95 @@ package com.assigment.todoapp.web; import java.net.URI; -import java.time.Duration; -import java.time.LocalDate; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import org.springframework.web.bind.annotation.*; import com.assigment.todoapp.domain.ToDoItem; import com.assigment.todoapp.service.ToDoService; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @RestController @CrossOrigin(origins = "http://localhost:8080/") public class ToDoController { - - - - + private final ToDoService todoService; - - public ToDoController(ToDoService todoService){ + + public ToDoController(ToDoService todoService) { this.todoService = todoService; - } @GetMapping("/api/todos") - public ResponseEntity fetchAllToDoItems( - @RequestParam(defaultValue = "All") String state, - @RequestParam(defaultValue = "") String name, - @RequestParam(defaultValue = "All") String priority, - @RequestParam(defaultValue = "1") int page, - @RequestParam(defaultValue = "10") int pageSize, - @RequestParam(defaultValue = "dueDate") String sortBy1, - @RequestParam(defaultValue = "asc") String order1, - @RequestParam(defaultValue = "priority") String sortBy2, - @RequestParam(defaultValue = "asc") String order2) { - - List todoItems = todoService.fetchAllToDoItems(state, name, priority); - - List sortedItems = todoService.sortToDoItems(todoItems, sortBy1, order1, sortBy2, order2); - - Map response = todoService.paginateToDoItems(sortedItems, page, pageSize); - - return ResponseEntity.ok(response); - } - - + public ResponseEntity fetchAllToDoItems( + @RequestParam(defaultValue = "All") String state, + @RequestParam(defaultValue = "") String name, + @RequestParam(defaultValue = "All") String priority, + @RequestParam(defaultValue = "1") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "dueDate") String sortBy1, + @RequestParam(defaultValue = "asc") String order1, + @RequestParam(defaultValue = "priority") String sortBy2, + @RequestParam(defaultValue = "asc") String order2) { + + List todoItems = todoService.fetchAllToDoItems(state, name, priority); + List sortedItems = todoService.sortToDoItems(todoItems, sortBy1, order1, sortBy2, order2); + Map response = todoService.paginateToDoItems(sortedItems, page, pageSize); + + return ResponseEntity.ok(response); + } + @PostMapping("/api/todos") public ResponseEntity createToDoItem(@RequestBody ToDoItem todoItem) { - if (todoItem == null || todoItem.getName() == null || todoItem.getName().isEmpty()) { - return ResponseEntity.badRequest().body(null); - } - ToDoItem createdToDoItem = todoService.createToDoItem(todoItem); - URI location = ServletUriComponentsBuilder.fromCurrentRequest() - .path("/{id}") - .buildAndExpand(createdToDoItem.getId()) - .toUri(); - return ResponseEntity.created(location).body(createdToDoItem); + if (todoItem == null || todoItem.getName() == null || todoItem.getName().isEmpty()) { + return ResponseEntity.badRequest().body(null); + } + ToDoItem createdToDoItem = todoService.createToDoItem(todoItem); + URI location = ServletUriComponentsBuilder.fromCurrentRequest() + .path("/{id}") + .buildAndExpand(createdToDoItem.getId()) + .toUri(); + return ResponseEntity.created(location).body(createdToDoItem); } - + @PostMapping("/api/todos/{id}/done") - public ResponseEntity updateFlag(@PathVariable UUID id,@RequestBody ToDoItem todoItem) { - ToDoItem updatedItem = todoService.updateFlag(id, todoItem); - return ResponseEntity.ok(updatedItem); - } - + public ResponseEntity updateFlag(@PathVariable UUID id, @RequestBody ToDoItem todoItem) { + ToDoItem updatedItem = todoService.updateFlag(id, todoItem); + return ResponseEntity.ok(updatedItem); + } + @GetMapping("/api/todos/colorFlags") public ResponseEntity>> fetchToDoItemsWithFlags() { - // Fetch all ToDo items - List toDoItems = todoService.fetchAllItems(); - - // Create a list to hold the ToDo items with flags - List> toDoItemFlags = new ArrayList<>(); - - for (ToDoItem item : toDoItems) { - Map itemFlag = new HashMap<>(); - itemFlag.put("item", item); - - // Set the flag based on the difference in weeks - if (item.getDueDate() == null) { - itemFlag.put("flag", 0); - } else { - // Calculate the difference in weeks between the due date and today - long weeksBetween = ChronoUnit.WEEKS.between(LocalDate.now(), item.getDueDate()); - - if (weeksBetween <= 1) { - itemFlag.put("flag", 1); - } else if (weeksBetween <= 2) { - itemFlag.put("flag", 2); - } else { - itemFlag.put("flag", 3); - } - } - - toDoItemFlags.add(itemFlag); - } - - return ResponseEntity.ok(toDoItemFlags); + List> toDoItemFlags = todoService.fetchToDoItemsWithFlags(); + return ResponseEntity.ok(toDoItemFlags); } - - @GetMapping("/api/todos/averageTime") public ResponseEntity fetchAverageCompletionTime() { - - // Fetch all done ToDo items - List doneItemsAll = todoService.fetchAllDoneToDoItems("All"); - List doneItemsHigh = todoService.fetchAllDoneToDoItems("High"); - List doneItemsMedium = todoService.fetchAllDoneToDoItems("Medium"); - List doneItemsLow = todoService.fetchAllDoneToDoItems("Low"); - - // Calculate the average time between creation and done for all priorities - double averageDurationAll = calculateAverageDuration(doneItemsAll); - double averageDurationHigh = calculateAverageDuration(doneItemsHigh); - double averageDurationMedium = calculateAverageDuration(doneItemsMedium); - double averageDurationLow = calculateAverageDuration(doneItemsLow); - - // Create a map to hold the average times - Map response = new HashMap<>(); - response.put("averageTimeAll", averageDurationAll); - response.put("averageTimeHigh", averageDurationHigh); - response.put("averageTimeMedium", averageDurationMedium); - response.put("averageTimeLow", averageDurationLow); - - return ResponseEntity.ok(response); + Map response = todoService.fetchAverageCompletionTimes(); + return ResponseEntity.ok(response); } - private double calculateAverageDuration(List doneItems) { - long totalDuration = 0; - for (ToDoItem item : doneItems) { - Duration duration = Duration.between(item.getCreationDate(), item.getDoneDate()); - totalDuration += duration.toMillis(); - } - return (double) totalDuration / doneItems.size(); - } - @PutMapping("/api/todos/{id}") public ResponseEntity updateToDoItem(@PathVariable UUID id, @RequestBody ToDoItem updatedToDoItem) { - if (id == null || updatedToDoItem == null || updatedToDoItem.getName() == null || updatedToDoItem.getName().isEmpty()) { - return ResponseEntity.badRequest().body(null); - } - ToDoItem updatedItem = todoService.updateToDoItem(id, updatedToDoItem); - return ResponseEntity.ok(updatedItem); + if (id == null || updatedToDoItem == null || updatedToDoItem.getName() == null || updatedToDoItem.getName().isEmpty()) { + return ResponseEntity.badRequest().body(null); + } + ToDoItem updatedItem = todoService.updateToDoItem(id, updatedToDoItem); + return ResponseEntity.ok(updatedItem); } @PutMapping("/api/todos/{id}/undone") - public ResponseEntity updateFlag2(@PathVariable UUID id, @RequestBody ToDoItem updatedToDoItem) { - ToDoItem updatedItem = todoService.updateFlag(id, updatedToDoItem); - return ResponseEntity.ok(updatedItem); - } - - @DeleteMapping("/api/todos/{id}") - public ResponseEntity deleteToDoItem(@PathVariable UUID id) { - todoService.deleteToDoItem(id); - return ResponseEntity.noContent().build(); - } - - -} + public ResponseEntity updateFlag2(@PathVariable UUID id, @RequestBody ToDoItem updatedToDoItem) { + ToDoItem updatedItem = todoService.updateFlag(id, updatedToDoItem); + return ResponseEntity.ok(updatedItem); + } + + @DeleteMapping("/api/todos/{id}") + public ResponseEntity deleteToDoItem(@PathVariable UUID id) { + todoService.deleteToDoItem(id); + return ResponseEntity.noContent().build(); + } +} \ No newline at end of file diff --git a/todo-app-encora/src/main/resources/application.properties b/todo-app-encora/src/main/resources/application.properties index 7f17e2f..3fb79f9 100644 --- a/todo-app-encora/src/main/resources/application.properties +++ b/todo-app-encora/src/main/resources/application.properties @@ -1,4 +1,4 @@ spring.application.name=todo-app-encora -server.port=9090 \ No newline at end of file +server.port=1010 \ No newline at end of file diff --git a/todo-app-encora/src/test/java/com/assigment/todoapp/controller/ToDoControllerTests.java b/todo-app-encora/src/test/java/com/assigment/todoapp/controller/ToDoControllerTests.java new file mode 100644 index 0000000..1391a3f --- /dev/null +++ b/todo-app-encora/src/test/java/com/assigment/todoapp/controller/ToDoControllerTests.java @@ -0,0 +1,117 @@ +package com.assigment.todoapp.controller; + +import com.assigment.todoapp.domain.ToDoItem; +import com.assigment.todoapp.service.ToDoService; +import com.assigment.todoapp.web.ToDoController; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.*; + +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +public class ToDoControllerTests { + + private MockMvc mockMvc; + + @Mock + private ToDoService toDoService; + + @InjectMocks + private ToDoController toDoController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + mockMvc = MockMvcBuilders.standaloneSetup(toDoController).build(); + } + + @Test + void testFetchAllToDoItems() throws Exception { + List items = Arrays.asList(new ToDoItem(), new ToDoItem()); + when(toDoService.fetchAllToDoItems(anyString(), anyString(), anyString())).thenReturn(items); + when(toDoService.sortToDoItems(anyList(), anyString(), anyString(), anyString(), anyString())).thenReturn(items); + when(toDoService.paginateToDoItems(anyList(), anyInt(), anyInt())).thenReturn(new HashMap<>()); + + mockMvc.perform(get("/api/todos") + .param("state", "All") + .param("name", "") + .param("priority", "All") + .param("page", "1") + .param("pageSize", "10") + .param("sortBy1", "dueDate") + .param("order1", "asc") + .param("sortBy2", "priority") + .param("order2", "asc")) + .andExpect(status().isOk()); + } + + @Test + void testCreateToDoItem() throws Exception { + ToDoItem item = new ToDoItem(); + item.setName("Test Item"); + when(toDoService.createToDoItem(any(ToDoItem.class))).thenReturn(item); + + mockMvc.perform(post("/api/todos") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"Test Item\"}")) + .andExpect(status().isCreated()); + } + + @Test + void testUpdateFlag() throws Exception { + ToDoItem item = new ToDoItem(); + item.setDone(true); + when(toDoService.updateFlag(any(UUID.class), any(ToDoItem.class))).thenReturn(item); + + mockMvc.perform(post("/api/todos/{id}/done", UUID.randomUUID()) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"done\":true}")) + .andExpect(status().isOk()); + } + + @Test + void testFetchToDoItemsWithFlags() throws Exception { + when(toDoService.fetchToDoItemsWithFlags()).thenReturn(new ArrayList<>()); + + mockMvc.perform(get("/api/todos/colorFlags")) + .andExpect(status().isOk()); + } + + @Test + void testFetchAverageCompletionTime() throws Exception { + when(toDoService.fetchAverageCompletionTimes()).thenReturn(new HashMap<>()); + + mockMvc.perform(get("/api/todos/averageTime")) + .andExpect(status().isOk()); + } + + @Test + void testUpdateToDoItem() throws Exception { + ToDoItem item = new ToDoItem(); + item.setName("Updated Item"); + when(toDoService.updateToDoItem(any(UUID.class), any(ToDoItem.class))).thenReturn(item); + + mockMvc.perform(put("/api/todos/{id}", UUID.randomUUID()) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"Updated Item\"}")) + .andExpect(status().isOk()); + } + + @Test + void testDeleteToDoItem() throws Exception { + doNothing().when(toDoService).deleteToDoItem(any(UUID.class)); + + mockMvc.perform(delete("/api/todos/{id}", UUID.randomUUID())) + .andExpect(status().isNoContent()); + } +} \ No newline at end of file diff --git a/todo-app-encora/src/test/java/com/assigment/todoapp/repository/ToDoRepositoryImplTests.java b/todo-app-encora/src/test/java/com/assigment/todoapp/repository/ToDoRepositoryImplTests.java new file mode 100644 index 0000000..8ae85f9 --- /dev/null +++ b/todo-app-encora/src/test/java/com/assigment/todoapp/repository/ToDoRepositoryImplTests.java @@ -0,0 +1,71 @@ +package com.assigment.todoapp.repository; + +import com.assigment.todoapp.domain.ToDoItem; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +public class ToDoRepositoryImplTests { + + private ToDoRepositoryImpl repository; + private List todoItems; + + @BeforeEach + public void setUp() { + todoItems = Arrays.asList( + createToDoItem("Task 1", "High", true), + createToDoItem("Task 2", "Low", false), + createToDoItem("Task 3", "Medium", true) + ); + repository = new ToDoRepositoryImpl(todoItems); + } + + @Test + public void testFetchAllToDoItems() { + List items = repository.fetchAllToDoItems(); + assertEquals(3, items.size()); + } + + @Test + public void testFindByDone() { + List doneItems = repository.findByDone(true); + assertEquals(2, doneItems.size()); + assertTrue(doneItems.stream().allMatch(ToDoItem::isDone)); + } + + @Test + public void testFindByNameContainingIgnoreCase() { + List items = repository.findByNameContainingIgnoreCase("task"); + assertEquals(3, items.size()); + } + + @Test + public void testFindByPriority() { + List highPriorityItems = repository.findByPriority("High"); + assertEquals(1, highPriorityItems.size()); + assertTrue(highPriorityItems.stream().allMatch(item -> "High".equals(item.getPriority()))); + } + + @Test + public void testFindById() { + UUID id = todoItems.get(0).getId(); + ToDoItem item = repository.findById(id); + assertNotNull(item); + assertEquals(id, item.getId()); + } + + + private ToDoItem createToDoItem(String name, String priority, boolean done) { + ToDoItem item = new ToDoItem(); + item.setName(name); + item.setPriority(priority); + item.setDone(done); + item.setId(UUID.randomUUID()); + return item; + } +} \ No newline at end of file diff --git a/todo-app-encora/src/test/java/com/assigment/todoapp/repository/ToDoRepositoryTests.java b/todo-app-encora/src/test/java/com/assigment/todoapp/repository/ToDoRepositoryTests.java deleted file mode 100644 index 3d819ba..0000000 --- a/todo-app-encora/src/test/java/com/assigment/todoapp/repository/ToDoRepositoryTests.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.assigment.todoapp.repository; -import org.junit.jupiter.api.Test; - -import com.assigment.todoapp.domain.ToDoItem; - - -import static org.junit.jupiter.api.Assertions.*; - -import java.util.Arrays; -import java.util.List; - -public class ToDoRepositoryTests { - - private ToDoRepository repository; - - @Test - public void testFetchAllToDoItems() { - List todoItems = Arrays.asList(new ToDoItem(), new ToDoItem()); - repository = new ToDoRepository(todoItems); - List items = repository.fetchAllToDoItems(); - assertFalse(items.isEmpty()); - } - - @Test - public void testFindByDone() { - ToDoItem item1 = new ToDoItem(); - item1.setDone(true); - ToDoItem item2 = new ToDoItem(); - item2.setDone(false); - List todoItems = Arrays.asList(item1, item2); - repository = new ToDoRepository(todoItems); - List items = repository.findByDone(true); - assertTrue(items.stream().allMatch(ToDoItem::isDone)); - } - - @Test - public void testFindByNameContainingIgnoreCase() { - ToDoItem item1 = new ToDoItem(); - item1.setName("Test"); - ToDoItem item2 = new ToDoItem(); - item2.setName("Another"); - List todoItems = Arrays.asList(item1, item2); - repository = new ToDoRepository(todoItems); - String name = "test"; - List items = repository.findByNameContainingIgnoreCase(name); - assertTrue(items.stream().allMatch(item -> item.getName().toLowerCase().contains(name.toLowerCase()))); - } - - @Test - public void testFindByPriority() { - ToDoItem item1 = new ToDoItem(); - item1.setPriority("High"); - ToDoItem item2 = new ToDoItem(); - item2.setPriority("Low"); - List todoItems = Arrays.asList(item1, item2); - repository = new ToDoRepository(todoItems); - String priority = "High"; - List items = repository.findByPriority(priority); - assertTrue(items.stream().allMatch(item -> item.getPriority().equalsIgnoreCase(priority))); - } - -} diff --git a/todo-app-encora/src/test/java/com/assigment/todoapp/service/ToDoServiceTests.java b/todo-app-encora/src/test/java/com/assigment/todoapp/service/ToDoServiceTests.java index 770496d..e687104 100644 --- a/todo-app-encora/src/test/java/com/assigment/todoapp/service/ToDoServiceTests.java +++ b/todo-app-encora/src/test/java/com/assigment/todoapp/service/ToDoServiceTests.java @@ -1,11 +1,7 @@ package com.assigment.todoapp.service; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; -import static org.junit.jupiter.api.Assertions.assertThrows; - +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,462 +12,103 @@ import com.assigment.todoapp.domain.ToDoItem; import com.assigment.todoapp.repository.ToDoRepository; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.time.LocalDateTime; +import java.util.*; @SpringBootTest public class ToDoServiceTests { - @Mock + @Mock private ToDoRepository todoRepository; - @InjectMocks + @InjectMocks private ToDoService toDoService; private List todoItems; @BeforeEach void setUp() { - MockitoAnnotations.openMocks(this); + MockitoAnnotations.openMocks(this); todoItems = new ArrayList<>(); - toDoService.setTodoItems(todoItems); - - } - - @Test - void testFetchAllToDoItemsByStateDone() { - - ToDoItem item1 = new ToDoItem(); - item1.setName("Test 1"); - item1.setPriority("High"); - item1.setDone(true); - - ToDoItem item2 = new ToDoItem(); - item2.setName("Test 2"); - item2.setPriority("Low"); - item2.setDone(false); - - List items = Arrays.asList(item1, item2); - when(todoRepository.fetchAllToDoItems()).thenReturn(items); - - List result = toDoService.fetchAllToDoItems("Done", "", "All"); - - assertEquals(1, result.size()); - assertTrue(result.contains(item1)); - assertFalse(result.contains(item2)); - } - - @Test - void testFetchAllToDoItemsByStateNotDone() { - - ToDoItem item1 = new ToDoItem(); - item1.setName("Test 1"); - item1.setPriority("High"); - item1.setDone(false); - - ToDoItem item2 = new ToDoItem(); - item2.setName("Test 2"); - item2.setPriority("Low"); - item2.setDone(true); - - List items = Arrays.asList(item1, item2); - when(todoRepository.fetchAllToDoItems()).thenReturn(items); - - List result = toDoService.fetchAllToDoItems("Not Done", "", "All"); - - assertEquals(1, result.size()); - assertTrue(result.contains(item1)); - assertFalse(result.contains(item2)); } - @Test - void testFetchAllToDoItemsByPriority() { - - ToDoItem item1 = new ToDoItem(); - item1.setName("Test 1"); - item1.setPriority("High"); - item1.setDone(true); - - ToDoItem item2 = new ToDoItem(); - item2.setName("Test 2"); - item2.setPriority("Low"); - item2.setDone(true); - List items = Arrays.asList(item1, item2); - when(todoRepository.fetchAllToDoItems()).thenReturn(items); - - List result = toDoService.fetchAllToDoItems("All", "", "High"); - - assertEquals(1, result.size()); - assertTrue(result.contains(item1)); - assertFalse(result.contains(item2)); - } @Test - void testFetchAllToDoItemsByName() { - - ToDoItem item1 = new ToDoItem(); - item1.setName("Test 1"); - item1.setPriority("High"); - item1.setDone(true); - - ToDoItem item2 = new ToDoItem(); - item2.setName("Sample 2"); - item2.setPriority("Low"); - item2.setDone(true); - - List items = Arrays.asList(item1, item2); - when(todoRepository.fetchAllToDoItems()).thenReturn(items); - - List result = toDoService.fetchAllToDoItems("All", "Test", "All"); - - assertEquals(1, result.size()); - assertTrue(result.contains(item1)); - assertFalse(result.contains(item2)); - } - - - @Test - public void testFetchAllToDoItems() { + void testFetchAllDoneToDoItemsWhenNoDoneItems() { ToDoItem item1 = new ToDoItem(); - item1.setId(UUID.randomUUID()); item1.setName("Task 1"); - item1.setDueDate(LocalDateTime.now()); - item1.setDone(false); - item1.setDoneDate(LocalDateTime.now()); item1.setPriority("High"); - item1.setCreationDate(LocalDateTime.now()); + item1.setDone(false); ToDoItem item2 = new ToDoItem(); - item2.setId(UUID.randomUUID()); item2.setName("Task 2"); - item2.setDueDate(LocalDateTime.now()); - item2.setDone(true); - item2.setDoneDate(LocalDateTime.now()); item2.setPriority("Low"); - item2.setCreationDate(LocalDateTime.now()); - - List expectedItems = Arrays.asList(item1, item2); - - when(todoRepository.fetchAllToDoItems()).thenReturn(expectedItems); - - List actualItems = toDoService.fetchAllToDoItems("All", "", "All"); - - assertEquals(expectedItems, actualItems); - } - - - @Test - void testUpdateToDoItemWhenItemExists() { - UUID id = UUID.randomUUID(); - ToDoItem existingItem = new ToDoItem(); - existingItem.setId(id); - existingItem.setName("Old Name"); - existingItem.setDone(false); - existingItem.setPriority("Medium"); - existingItem.setDueDate(LocalDateTime.of(2024, 1, 1, 10, 0)); - - todoItems.add(existingItem); - - ToDoItem updatedItem = new ToDoItem(); - updatedItem.setName("New Name"); - updatedItem.setDone(true); - updatedItem.setPriority("High"); - updatedItem.setDueDate(LocalDateTime.of(2024, 12, 31, 10, 0)); - - ToDoItem result = toDoService.updateToDoItem(id, updatedItem); + item2.setDone(false); - assertEquals("New Name", result.getName()); - assertTrue(result.isDone()); - assertEquals("High", result.getPriority()); - assertEquals(LocalDateTime.of(2024, 12, 31, 10, 0), result.getDueDate()); - } - - @Test - void testUpdateToDoItemWhenItemDoesNotExist() { - UUID id = UUID.randomUUID(); - ToDoItem updatedItem = new ToDoItem(); - updatedItem.setName("New Name"); - updatedItem.setDone(true); - updatedItem.setPriority("High"); - updatedItem.setDueDate(LocalDateTime.of(2024, 12, 31, 10, 0)); - - RuntimeException thrown = assertThrows(RuntimeException.class, () -> { - toDoService.updateToDoItem(id, updatedItem); - }); - - assertEquals("ToDoItem no encontrado", thrown.getMessage()); - } - - @Test - void testDeleteToDoItemWhenItemExists() { - UUID id = UUID.randomUUID(); - ToDoItem item = new ToDoItem(); - item.setId(id); - item.setName("Sample Item"); - - todoItems.add(item); - - assertTrue(todoItems.stream().anyMatch(i -> i.getId().equals(id))); - - toDoService.deleteToDoItem(id); - - assertFalse(todoItems.stream().anyMatch(i -> i.getId().equals(id))); - } - - @Test - void testDeleteToDoItemWhenItemDoesNotExist() { - UUID id = UUID.randomUUID(); - - assertFalse(todoItems.stream().anyMatch(i -> i.getId().equals(id))); - - toDoService.deleteToDoItem(id); - - assertTrue(todoItems.isEmpty()); - } - @Test - void testUpdateFlagWhenItemExistsAndIsNotDone() { - UUID id = UUID.randomUUID(); - ToDoItem existingItem = new ToDoItem(); - existingItem.setId(id); - existingItem.setDone(false); - existingItem.setDoneDate(null); - - todoItems.add(existingItem); - - ToDoItem updateItem = new ToDoItem(); - updateItem.setDone(true); - - ToDoItem updatedItem = toDoService.updateFlag(id, updateItem); - - assertTrue(updatedItem.isDone()); - assertNotNull(updatedItem.getDoneDate()); - assertEquals(id, updatedItem.getId()); - } - - @Test - void testFetchAllDoneToDoItemsWithSpecificPriority() { - UUID id1 = UUID.randomUUID(); - ToDoItem item1 = new ToDoItem(); - item1.setId(id1); - item1.setName("Task 1"); - item1.setPriority("High"); - item1.setDone(true); - todoItems.add(item1); - - UUID id2 = UUID.randomUUID(); - ToDoItem item2 = new ToDoItem(); - item2.setId(id2); - item2.setName("Task 2"); - item2.setPriority("Low"); - item2.setDone(true); - todoItems.add(item2); - - UUID id3 = UUID.randomUUID(); - ToDoItem item3 = new ToDoItem(); - item3.setId(id3); - item3.setName("Task 3"); - item3.setPriority("High"); - item3.setDone(false); - todoItems.add(item3); - - List result = toDoService.fetchAllDoneToDoItems("High"); - - assertEquals(1, result.size()); - assertEquals("Task 1", result.get(0).getName()); - } - - @Test - void testFetchAllDoneToDoItemsWithAllPriority() { - UUID id1 = UUID.randomUUID(); - ToDoItem item1 = new ToDoItem(); - item1.setId(id1); - item1.setName("Task 1"); - item1.setPriority("High"); - item1.setDone(true); - todoItems.add(item1); - - UUID id2 = UUID.randomUUID(); - ToDoItem item2 = new ToDoItem(); - item2.setId(id2); - item2.setName("Task 2"); - item2.setPriority("Low"); - item2.setDone(true); - todoItems.add(item2); - - UUID id3 = UUID.randomUUID(); - ToDoItem item3 = new ToDoItem(); - item3.setId(id3); - item3.setName("Task 3"); - item3.setPriority("High"); - item3.setDone(false); - todoItems.add(item3); - - List result = toDoService.fetchAllDoneToDoItems("All"); - - assertEquals(2, result.size()); - assertEquals("Task 1", result.get(0).getName()); - assertEquals("Task 2", result.get(1).getName()); - } - - @Test - void testFetchAllDoneToDoItemsWhenNoDoneItems() { - UUID id1 = UUID.randomUUID(); - ToDoItem item1 = new ToDoItem(); - item1.setId(id1); - item1.setName("Task 1"); - item1.setPriority("High"); - item1.setDone(false); - todoItems.add(item1); - - UUID id2 = UUID.randomUUID(); - ToDoItem item2 = new ToDoItem(); - item2.setId(id2); - item2.setName("Task 2"); - item2.setPriority("Low"); - item2.setDone(false); - todoItems.add(item2); - - List result = toDoService.fetchAllDoneToDoItems("All"); - - assertEquals(0, result.size()); - } - @Test - void testUpdateFlagWhenItemDoesNotExist() { - UUID id = UUID.randomUUID(); // UUID que no está en la lista - ToDoItem updateItem = new ToDoItem(); - updateItem.setDone(true); - - RuntimeException thrown = assertThrows(RuntimeException.class, () -> { - toDoService.updateFlag(id, updateItem); - }); - - assertEquals("ToDoItem no encontrado", thrown.getMessage()); - } - - - @Test - void testUpdateFlagWhenItemExistsAndIsDone() { - UUID id = UUID.randomUUID(); - ToDoItem existingItem = new ToDoItem(); - existingItem.setId(id); - existingItem.setDone(true); - existingItem.setDoneDate(LocalDateTime.now()); - todoItems.add(existingItem); - - ToDoItem updateItem = new ToDoItem(); - updateItem.setDone(false); - - ToDoItem result = toDoService.updateFlag(id, updateItem); - - assertEquals(false, result.isDone()); - assertEquals(null, result.getDoneDate()); - } - @Test - public void testCreateToDoItem() { - ToDoItem item = new ToDoItem(); - item.setName("Test"); - item.setPriority("High"); - - ToDoItem createdItem = toDoService.createToDoItem(item); - - assertEquals("Test", createdItem.getName()); - assertEquals("High", createdItem.getPriority()); - assertEquals(false, createdItem.isDone()); - } - - - - - @Test - public void testDeleteToDoItem() { - // Create a ToDoItem for testing - ToDoItem item = new ToDoItem(); - UUID id = UUID.randomUUID(); - item.setId(id); - item.setName("Test"); - item.setDone(false); - item.setPriority("High"); - item.setCreationDate(LocalDateTime.now()); - - // Set up the mock behavior - when(todoRepository.fetchAllToDoItems()).thenReturn(Arrays.asList(item)); + List items = Arrays.asList(item1, item2); + when(todoRepository.findByDone(true)).thenReturn(Collections.emptyList()); - // Delete the ToDoItem - toDoService.deleteToDoItem(id); + List result = toDoService.fetchAllDoneToDoItems("All"); - // Verify that the item was deleted - List items = toDoService.fetchAllItems(); - assertEquals(0, items.size()); + assertEquals(0, result.size()); } @Test - public void testPaginateToDoItems_FirstPage() { - List items = createTestToDoItems(25); // Crear una lista de 25 elementos + void testPaginateToDoItems_FirstPage() { + List items = createTestToDoItems(25); int page = 1; int pageSize = 10; Map response = toDoService.paginateToDoItems(items, page, pageSize); - assertEquals(10, ((List) response.get("items")).size(), "Items on the first page should be 10"); - assertEquals(1, response.get("currentPage"), "Current page should be 1"); - assertEquals(25, response.get("totalItems"), "Total items should be 25"); - assertEquals(3, response.get("totalPages"), "Total pages should be 3"); - assertEquals(10, response.get("itemsOnPage"), "Items on the page should be 10"); + assertEquals(10, ((List) response.get("items")).size()); + assertEquals(1, response.get("currentPage")); + assertEquals(25, response.get("totalItems")); + assertEquals(3, response.get("totalPages")); + assertEquals(10, response.get("itemsOnPage")); } @Test - public void testPaginateToDoItems_SecondPage() { + void testPaginateToDoItems_SecondPage() { List items = createTestToDoItems(25); int page = 2; int pageSize = 10; Map response = toDoService.paginateToDoItems(items, page, pageSize); - assertEquals(10, ((List) response.get("items")).size(), "Items on the second page should be 10"); - assertEquals(2, response.get("currentPage"), "Current page should be 2"); - assertEquals(25, response.get("totalItems"), "Total items should be 25"); - assertEquals(3, response.get("totalPages"), "Total pages should be 3"); - assertEquals(10, response.get("itemsOnPage"), "Items on the page should be 10"); + assertEquals(10, ((List) response.get("items")).size()); + assertEquals(2, response.get("currentPage")); + assertEquals(25, response.get("totalItems")); + assertEquals(3, response.get("totalPages")); + assertEquals(10, response.get("itemsOnPage")); } @Test - public void testPaginateToDoItems_ThirdPage() { + void testPaginateToDoItems_ThirdPage() { List items = createTestToDoItems(25); int page = 3; int pageSize = 10; Map response = toDoService.paginateToDoItems(items, page, pageSize); - assertEquals(5, ((List) response.get("items")).size(), "Items on the third page should be 5"); - assertEquals(3, response.get("currentPage"), "Current page should be 3"); - assertEquals(25, response.get("totalItems"), "Total items should be 25"); - assertEquals(3, response.get("totalPages"), "Total pages should be 3"); - assertEquals(5, response.get("itemsOnPage"), "Items on the page should be 5"); + assertEquals(5, ((List) response.get("items")).size()); + assertEquals(3, response.get("currentPage")); + assertEquals(25, response.get("totalItems")); + assertEquals(3, response.get("totalPages")); + assertEquals(5, response.get("itemsOnPage")); } - - private List createTestToDoItems(int count) { List items = new ArrayList<>(); for (int i = 1; i <= count; i++) { - ToDoItem item = new ToDoItem(); - item.setName("Test 1"); + ToDoItem item = new ToDoItem(); + item.setName("Test " + i); item.setPriority("High"); item.setDone(true); items.add(item); } return items; } - - - - - } \ No newline at end of file