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
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
package es.codeurjcstudents.pcmod.controller;

import java.net.URI;
import java.security.Principal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.web.servlet.support.ServletUriComponentsBuilder.fromCurrentRequest;

import es.codeurjcstudents.pcmod.dto.ReviewDTO;
import es.codeurjcstudents.pcmod.model.Review;
import es.codeurjcstudents.pcmod.service.ReviewsService;

@RestController
Expand All @@ -24,6 +33,28 @@ public Page<ReviewDTO> findAllByComponent(@PathVariable long id, Pageable pageab
return reviewsService.findAllByComponent(id, pageable).map(reviewsService::toDTO);
}

@GetMapping("/has-reviewed")
public ResponseEntity<Boolean> hasUserReviewed(@PathVariable long id, Principal principal) {

if (principal == null) {
return ResponseEntity.ok(false);
}

return ResponseEntity.ok(reviewsService.hasUserReviewed(id, Long.parseLong(principal.getName())));
}

@PostMapping("/")
public ResponseEntity<ReviewDTO> createReview(@RequestBody ReviewDTO reviewDTO, @PathVariable long id, Principal principal) {

Review review = reviewsService.toDomain(reviewDTO);

reviewsService.save(review, Long.valueOf(principal.getName()), id);

URI location = fromCurrentRequest().path("/{id}").buildAndExpand(review.getId()).toUri();

return ResponseEntity.created(location).body(reviewsService.toDTO(review));
}

@DeleteMapping("/{reviewId}")
public void deleteReview(@PathVariable long id, @PathVariable long reviewId) {
reviewsService.delete(id, reviewId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ public interface ReviewsRepository extends JpaRepository<Review, Long> {

Page<Review> findAllByComponentId(Long id, Pageable pageable);

boolean existsByComponentIdAndUserId(Long componentId, Long userId);

}
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ SecurityFilterChain securityFilterChain(HttpSecurity http) {
.exceptionHandling(handling -> handling.authenticationEntryPoint(unauthorizedHandlerJwt));

http.authorizeHttpRequests(authorize -> authorize
.requestMatchers(HttpMethod.POST, "/api/v1/components/*/reviews/").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.DELETE, "/api/v1/components/*/reviews/*").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.GET, "/api/v1/users/me").hasRole("REGISTERED_USER")
.requestMatchers(HttpMethod.POST, "/api/v1/users/*/image").hasRole("REGISTERED_USER")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package es.codeurjcstudents.pcmod.service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

Expand Down Expand Up @@ -55,6 +59,70 @@ public Page<Review> findAllByComponent(long id, Pageable pageable) {
return reviewRepository.findAllByComponentId(id, pageable);
}

@PreAuthorize("hasRole('REGISTERED_USER') and (#userId.toString() == principal.username)")
@Transactional
public Review save(Review review, long userId, long componentId) {

if (reviewRepository.existsByComponentIdAndUserId(componentId, userId)) {
throw new IllegalArgumentException("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.");
}

List<String> errors = validateReview(review);

if (!errors.isEmpty()) {
throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors));
}

User user = userRepository.findById(userId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado."));

Component component = componentRepository.findById(componentId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Componente no encontrado."));

review.setDate(LocalDate.now(ZoneId.of("Europe/Madrid")));
user.addReview(review);
component.addReview(review);

return reviewRepository.save(review);
}

public boolean hasUserReviewed(Long componentId, Long userId) {
return reviewRepository.existsByComponentIdAndUserId(componentId, userId);
}

public List<String> validateReview(Review review) {

List<String> errors = new ArrayList<>();

validateRequiredField(review.getTitle(), "El título es obligatorio.", errors);
validateRequiredField(review.getMessage(), "El mensaje es obligatorio.", errors);

if (review.getRating() == null || review.getRating().toString().isEmpty()) {
errors.add("La valoración es obligatoria.");
} else {
validateRating(review, errors);
}

return errors;

}

private void validateRequiredField(String value, String message, List<String> errors) {

if (value == null || value.isEmpty()) {
errors.add(message);
}

}

public void validateRating(Review review, List<String> errors) {

if ((review.getRating() < 1) || (review.getRating() > 5)) {
errors.add("La valoración del producto ha de estar entre 1 y 5.");
}

}

@PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)")
public void delete(long componentId, long reviewId) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.annotation.DirtiesContext;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
Expand All @@ -16,6 +17,7 @@
import java.io.InputStream;

@Tag("server-system")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ComponentsSystemTests {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.annotation.DirtiesContext;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

@Tag("server-system")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class HomePageSystemTests {

@LocalServerPort
Expand Down
Loading
Loading