Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/i31 [REST] - Criação de Novo Endpoint para Listagem de Abrigos com Paginação. #84

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -18,6 +20,7 @@
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.server.ResponseStatusException;


/**
* Interface que define as operações de gerenciamento de abrigos.
* <p>
Expand Down Expand Up @@ -169,4 +172,44 @@ public interface ShelterController {
})
ResponseEntity<ShelterInformationResponse> findShelterByUserResponsibleEmail(@PathVariable("userResponsibleEmail") String userResponsibleEmail);

/**
* Método GET para encontrar todos os abrigos cadastrados.
* <p>
* Este método recebe um {@link Pageable} que para que seja feito a paginação da pagina
* e retorna como resposta todos os {@link ShelterInformationResponse} cadastrados com paginação.
* </p>
* <p>
* O método retornará um objeto JSON com os seguintes campos:
* <ul>
* <li> {@code shelterName}: O nome do abrigo.</li>
* <li> {@code responsibleName}: O nome da pessoa que está gerenciando as doações no abrigo.</li>
* <li> {@code responsibleEmail}: O e-mail do responsável pelo recebimento das doações.</li>
* <li> {@code donationDTOS}: Uma lista de objetos representando as doações recebidas.</li>
* </ul>
* </p>
*
* @return Retorna um {@link ResponseEntity} que encapsula a resposta do abrigo encontrado. Esta
* resposta inclui o status HTTP da operação, bem como um corpo que é uma representação JSON
* do abrigo.
*
* @see Pageable
* @see Page
*/

@GetMapping
@Operation(
summary = "Encontra todos os abrigos cadastrados",
description = "Este endpoint é responsável por encontrar todos os abrigos cadastrados e paginá-los, " +
"utilizando os dados recebidos por meio de uma requisição do tipo GET.",
tags = "Abrigos"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "Abrigos encontrados com sucesso!",
content = @Content(schema = @Schema(implementation = ShelterInformationResponse.class))
)
})
ResponseEntity<Page<ShelterInformationResponse>> findAll(Pageable pageable);

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
import diegosneves.github.conectardoacoes.adapters.rest.exception.ShelterEntityFailuresException;
import diegosneves.github.conectardoacoes.adapters.rest.request.ReceiveDonationRequest;
import diegosneves.github.conectardoacoes.adapters.rest.request.ShelterCreationRequest;
import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterInformationResponse;
import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterCreatedResponse;
import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterInformationResponse;
import diegosneves.github.conectardoacoes.adapters.rest.service.ShelterEntityService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
Expand Down Expand Up @@ -56,4 +58,10 @@ public ResponseEntity<ShelterInformationResponse> findShelterByUserResponsibleEm
shelterEntityService.findShelterByUserResponsibleEmail(userResponsibleEmail);
return ResponseEntity.ok(shelterRecoveryByUserResponsibleEmail);
}

@Override
public ResponseEntity<Page<ShelterInformationResponse>> findAll(Pageable pageable) {
Page<ShelterInformationResponse> allPageableShelters = shelterEntityService.findAll(pageable);
return ResponseEntity.ok(allPageableShelters);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import diegosneves.github.conectardoacoes.core.exception.UuidUtilsException;
import diegosneves.github.conectardoacoes.core.utils.UuidUtils;
import diegosneves.github.conectardoacoes.core.utils.ValidationUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

Expand Down Expand Up @@ -212,4 +214,16 @@ default void deleteEntityById(String id) {
*/
Optional<ShelterEntity> findShelterEntitiesByResponsibleUser_Email(String responsibleUserEmail);

/**
* Este método é usado para buscar todos os abrigos cadastrados e devolvê-los paginados.
* <p>
* Esse método recupera todas as entidades de {@link ShelterEntity} presentes no banco de dados, usando o método semelhante ao {@code findAll}.
* No entanto, ele recebe um parâmetro {@link Pageable} para que possa ser feita a paginação e também a ordenação (sort) de todos os shelters.
* <p>
*
* @return Um {@link Page} de todos os {@link ShelterEntity} registrados no banco de dados. Se não houver entidades de abrigo no banco de dados, retorna uma lista vazia.
*/

Page<ShelterEntity> findAll(Pageable pageable);

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
import diegosneves.github.conectardoacoes.adapters.rest.model.DonationEntity;
import diegosneves.github.conectardoacoes.adapters.rest.request.ReceiveDonationRequest;
import diegosneves.github.conectardoacoes.adapters.rest.request.ShelterCreationRequest;
import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterInformationResponse;
import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterCreatedResponse;
import diegosneves.github.conectardoacoes.adapters.rest.response.ShelterInformationResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

/**
* Interface para a criação de um novo abrigo no sistema.
Expand Down Expand Up @@ -71,4 +73,17 @@ public interface ShelterEntityService {

ShelterInformationResponse findShelterByUserResponsibleEmail(String userResponsibleEmail);

/**
* Método utilizado para encontrar todos os abrigos com paginação.
* Recupera uma página de informações de abrigos do sistema com base nas informações de paginação fornecidas.
* Este método é responsável por retornar uma lista paginada de {@link ShelterInformationResponse},
* que contém detalhes sobre os abrigos registrados no sistema.
*
* @param pageable um objeto {@link Pageable} que define as informações de paginação, como número da página
* e tamanho da página, para controlar o retorno das informações de abrigos.
* @return uma página de objetos {@link ShelterInformationResponse} contendo as informações dos abrigos.
*/

Page<ShelterInformationResponse> findAll(Pageable pageable);

}
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,12 @@
import diegosneves.github.conectardoacoes.core.utils.ValidationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -308,6 +312,17 @@ public ShelterInformationResponse findShelterByUserResponsibleEmail(String userR
return BuilderMapper.mapTo(getShelterInformationResponseMapper(), currentShelterByResponsibleEmail);
}

@Override
public Page<ShelterInformationResponse> findAll(Pageable pageable) {

Page<ShelterEntity> allShelterWithPageable = repository.findAll(pageable);
List<ShelterEntity> content = allShelterWithPageable.getContent();
List<ShelterInformationResponse> informationResponses = content.stream()
.map(getShelterInformationResponseMapper()::mapFrom).toList();

return new PageImpl<>(informationResponses, pageable, allShelterWithPageable.getTotalElements());
}

/**
* Este método é responsável por criar uma nova instância de um objeto {@link ShelterInformationResponseFromShelterEntityMapper}.
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.lang.reflect.Method;
Expand Down Expand Up @@ -438,4 +440,24 @@ void shouldNotFindShelterEntityByUserEmailWhenEmailIsIncorrect() {

}

@Test
void shouldReturnFindAllWithAllOfPagedShelterEntity(){

persistEntity(new AddressEntityMapper(), this.address);
persistEntity(new UserEntityMapper(), this.user);
persistEntity(new ShelterEntityMapper(), this.shelter);
Pageable pageable = Pageable.ofSize(10);

Page<ShelterEntity> allShelters = shelterRepository.findAll(pageable);

ShelterEntity shelterEntityRecovery = allShelters.getContent().get(0);
assertNotNull(allShelters);
assertEquals(this.shelter.getId(), shelterEntityRecovery.getId());
assertEquals(this.shelter.getShelterName(), shelterEntityRecovery.getShelterName());
assertNotNull(this.shelter.getUser());
assertNotNull(this.shelter.getAddress());


}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,34 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.*;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(SpringExtension.class)
class ShelterEntityServiceImplTest {
Expand Down Expand Up @@ -501,5 +519,39 @@ void shouldThrowShelterEntityFailuresExceptionWhenTheEmailPassIsNull(){

}

@Test
void testFindAll_When_WithPageable_ShouldReturnAPageableOfAllShelterInformationResponse(){

DonationEntity firstDonation = new DonationEntity();
firstDonation.setDescription(DESCRIPTION);
firstDonation.setAmount(AMOUNT);

List<DonationEntity> donations = List.of(firstDonation);

ShelterEntity shelterEntity = generateShelterEntity();
shelterEntity.setDonations(donations);

List<ShelterEntity> shelterEntityList = List.of(shelterEntity);

when(repository.findAll(any(Pageable.class))).thenReturn(new PageImpl<>(shelterEntityList));

Page<ShelterInformationResponse> allShelters = service.findAll(PageRequest.of(0, 10));

verify(repository,times(1)).findAll(any(Pageable.class));

ShelterInformationResponse shelterInformationResponse = allShelters.getContent().get(0);

assertNotNull(allShelters);
assertEquals(1, allShelters.getTotalElements());

assertEquals(SHELTER_NAME, shelterInformationResponse.getShelterName());
assertEquals(USER_NAME, shelterInformationResponse.getResponsibleName());
assertEquals(USER_EMAIL, shelterInformationResponse.getResponsibleEmail());
assertEquals(1, shelterInformationResponse.getDonationDTOS().size());
assertEquals(DESCRIPTION, shelterInformationResponse.getDonationDTOS().get(0).getDescription());
assertEquals(AMOUNT, shelterInformationResponse.getDonationDTOS().get(0).getAmount());

}


}
Loading