Skip to content
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
58 changes: 56 additions & 2 deletions src/main/java/br/com/db/petcontrol/controller/PetsController.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
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.RequestMapping;

Expand All @@ -33,10 +34,63 @@ public interface PetsController {
@Content(
mediaType = "application/json",
schema = @Schema(implementation = PetResponseDTO.class)))
@ApiResponse(responseCode = "404", description = "Espécie não encontrada")
@ApiResponse(
responseCode = "400",
description = "Dados inválidos",
content =
@Content(
schema = @Schema(implementation = ErrorResponseDTO.class),
examples =
@ExampleObject(
name = "Dados inválidos",
value =
"{\"messages\": [\"Pet name must not be blank\", \"Specie ID must not be null\"]}")))
@ApiResponse(
responseCode = "404",
description = "Espécie ou Tags não encontradas",
content =
@Content(
schema = @Schema(implementation = ErrorResponseDTO.class),
examples =
@ExampleObject(
name = "Não encontrado",
value = "{\"messages\": [\"Specie not found\"]}")))
@PostMapping
ResponseEntity<PetResponseDTO> create(@Valid @RequestBody PetRequestDTO dto);

@Operation(summary = "Atualizar pet", description = "Atualiza um pet no sistema")
@ApiResponse(
responseCode = "200",
description = "Pet atualizado com sucesso",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = PetResponseDTO.class)))
@ApiResponse(
responseCode = "400",
description = "Dados inválidos",
content =
@Content(
schema = @Schema(implementation = ErrorResponseDTO.class),
examples =
@ExampleObject(
name = "Dados inválidos",
value =
"{\"messages\": [\"Pet name must not be blank\", \"Specie ID must not be null\"]}")))
@ApiResponse(
responseCode = "404",
description = "Pet não encontrado",
content =
@Content(
schema = @Schema(implementation = ErrorResponseDTO.class),
examples =
@ExampleObject(
name = "Não encontrado",
value = "{\"messages\": [\"Pet not found\"]}")))
@PutMapping("/{id}")
ResponseEntity<PetResponseDTO> update(
@PathVariable UUID id, @Valid @RequestBody PetRequestDTO dto);

@Operation(summary = "Buscar pets", description = "Retorna uma lista paginada de pets")
@ApiResponse(
responseCode = "200",
Expand All @@ -46,7 +100,7 @@ public interface PetsController {
ResponseEntity<PageResponseDTO<PetResponseDTO>> findAll(
@ParameterObject PageableRequestDTO pageable);

@Operation(summary = "Buscar um pet", description = "Busca um pet pelo seu id")
@Operation(summary = "Buscar pet", description = "Busca um pet pelo seu id")
@ApiResponse(
responseCode = "200",
description = "Pet buscado com sucesso",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ public ResponseEntity<PetResponseDTO> create(PetRequestDTO dto) {
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}

@Override
public ResponseEntity<PetResponseDTO> update(UUID id, PetRequestDTO dto) {
PetResponseDTO response = petsService.update(id, dto);
return ResponseEntity.status(HttpStatus.OK).body(response);
}

@Override
public ResponseEntity<PageResponseDTO<PetResponseDTO>> findAll(PageableRequestDTO pageable) {
PageResponseDTO<PetResponseDTO> response = petsService.findAll(pageable);
Expand Down
14 changes: 11 additions & 3 deletions src/main/java/br/com/db/petcontrol/dto/request/PetRequestDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,25 @@
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import java.util.List;
import java.util.UUID;
import lombok.Builder;

@Builder
public record PetRequestDTO(
@NotBlank @Schema(description = "Nome do pet", example = "Lily") String name,
@NotNull
@Pattern(regexp = "^[\\p{L}\\s]+$", message = "The name must contain only letters and spaces")
@NotBlank(message = "Pet name must not be blank")
@Size(max = 20, message = "Pet name must be at most 20 characters long")
@Schema(description = "Nome do pet", example = "Lily")
String name,
@NotNull(message = "Specie ID must not be null")
@Schema(description = "ID da espécie", example = "dd3af030-9823-40ff-bc6e-4de9eae55894")
UUID specieId,
@NotNull @Schema(description = "Status do pet", example = "AVAILABLE") PetStatus status,
@NotNull(message = "Pet status must not be null")
@Schema(description = "Status do pet", example = "AVAILABLE")
PetStatus status,
@Schema(
description = "IDs das tags do pet",
example =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,5 @@ public record PetResponseDTO(
UUID id,
@Schema(description = "Nome do pet", example = "Lily") String name,
@Schema(description = "Status do pet", example = "AVAILABLE") PetStatus status,
@Schema(description = "Espécie do pet", example = "Gato") String species,
@Schema(description = "Tags do pet", example = "[\"castrado\", \"vacinado\"]")
List<String> tags) {}
@Schema(description = "Espécie do pet") SpeciesResponseDTO species,
@Schema(description = "Tags do pet") List<TagsResponseDTO> tags) {}
19 changes: 9 additions & 10 deletions src/main/java/br/com/db/petcontrol/mapper/PetsMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,22 @@
import java.util.List;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;

@Mapper(componentModel = "spring")
@Mapper(
componentModel = "spring",
uses = {SpeciesMapper.class, TagsMapper.class})
public interface PetsMapper {

@Mapping(target = "id", ignore = true)
@Mapping(target = "name", source = "dto.name")
@Mapping(target = "status", source = "dto.status")
Pets toEntity(PetRequestDTO dto, Species species, List<Tags> tags);

@Mapping(target = "species", source = "species.name")
@Mapping(target = "tags", source = "tags")
PetResponseDTO toResponse(Pets pet);
@Mapping(target = "id", ignore = true)
@Mapping(target = "species", ignore = true)
@Mapping(target = "tags", ignore = true)
void toUpdateEntity(PetRequestDTO dto, @MappingTarget Pets pet);

default List<String> map(List<Tags> tags) {
if (tags == null) {
return null;
}
return tags.stream().map(Tags::getName).toList();
}
PetResponseDTO toResponse(Pets pet);
}
3 changes: 3 additions & 0 deletions src/main/java/br/com/db/petcontrol/mapper/TagsMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

import br.com.db.petcontrol.dto.response.TagsResponseDTO;
import br.com.db.petcontrol.model.Tags;
import java.util.List;
import org.mapstruct.Mapper;

@Mapper(componentModel = "spring")
public interface TagsMapper {

TagsResponseDTO toDTO(Tags tags);

List<TagsResponseDTO> toDTOList(List<Tags> tags);
}
2 changes: 2 additions & 0 deletions src/main/java/br/com/db/petcontrol/model/Pets.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Entity
@Table(name = "tb_pets")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/br/com/db/petcontrol/service/PetsService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
public interface PetsService {
PetResponseDTO create(PetRequestDTO dto);

PetResponseDTO update(UUID id, PetRequestDTO dto);

PageResponseDTO<PetResponseDTO> findAll(PageableRequestDTO pageable);

PetResponseDTO find(UUID id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@
import br.com.db.petcontrol.service.PetsService;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
Expand All @@ -35,22 +37,34 @@ public class PetsServiceImpl implements PetsService {
public PetResponseDTO create(PetRequestDTO dto) {
List<String> errors = new ArrayList<>();

Species species = speciesRepository.findById(dto.specieId()).orElse(null);
if (species == null) {
errors.add("Species not found: " + dto.specieId());
}

Species species = findSpeciesOrCollectErrors(dto.specieId(), errors);
List<Tags> tags = findTagsOrCollectErrors(dto.tagsIds(), errors);

if (!errors.isEmpty()) {
throw new NotFoundException(errors);
}
throwingNotFoundException(errors);

Pets pet = petsMapper.toEntity(dto, species, tags);
Pets savedPet = petRepository.saveAndFlush(pet);
return petsMapper.toResponse(savedPet);
}

@Override
@Transactional
public PetResponseDTO update(UUID id, PetRequestDTO dto) {
List<String> errors = new ArrayList<>();

Pets pet = findPet(id);
Species species = findSpeciesOrCollectErrors(dto.specieId(), errors);
List<Tags> tags = findTagsOrCollectErrors(dto.tagsIds(), errors);

throwingNotFoundException(errors);

petsMapper.toUpdateEntity(dto, pet);
updateRelationship(pet, species, tags);

Pets updatedPet = petRepository.saveAndFlush(pet);
return petsMapper.toResponse(updatedPet);
}

@Override
public PageResponseDTO<PetResponseDTO> findAll(PageableRequestDTO pageable) {
Page<PetResponseDTO> page =
Expand All @@ -60,28 +74,51 @@ public PageResponseDTO<PetResponseDTO> findAll(PageableRequestDTO pageable) {

@Override
public PetResponseDTO find(UUID id) {
return petRepository
.findById(id)
.map(petsMapper::toResponse)
.orElseThrow(() -> new NotFoundException("Pet not found"));
return petsMapper.toResponse(findPet(id));
}

private void updateRelationship(Pets pet, Species species, List<Tags> tags) {
pet.setSpecies(species);

pet.getTags().clear();
pet.getTags().addAll(tags);
}

private void throwingNotFoundException(List<String> errors) {
if (!errors.isEmpty()) {
throw new NotFoundException(errors);
}
}

private Species findSpeciesOrCollectErrors(UUID specieId, List<String> errors) {
Species species = speciesRepository.findById(specieId).orElse(null);

if (Objects.isNull(species)) {
errors.add("Species not found: " + specieId);
}

return species;
}

private List<Tags> findTagsOrCollectErrors(List<UUID> ids, List<String> errors) {
if (ids == null || ids.isEmpty()) {
if (Objects.isNull(ids) || ids.isEmpty()) {
return List.of();
}

List<Tags> foundTags = tagRepository.findAllById(ids);

if (foundTags.size() != ids.size()) {
List<UUID> notFoundIds =
ids.stream()
.filter(id -> foundTags.stream().noneMatch(tag -> tag.getId().equals(id)))
.toList();
List<UUID> foundIds = foundTags.stream().map(Tags::getId).toList();

List<UUID> notFoundIds = ids.stream().filter(id -> !foundIds.contains(id)).toList();

errors.add("Tags not found: " + notFoundIds);
}

return foundTags;
}

private Pets findPet(UUID id) {
return petRepository.findById(id).orElseThrow(() -> new NotFoundException("Pet not found"));
}
}
Loading
Loading