diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/controller/ComponentsRestController.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/controller/ComponentsRestController.java index a02adcb..930910d 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/controller/ComponentsRestController.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/controller/ComponentsRestController.java @@ -4,8 +4,10 @@ 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; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @@ -49,10 +51,10 @@ public List findTop3MoreRecent() { } @GetMapping("/{id}") - public ResponseEntity getComponent (@PathVariable long id) { + public ResponseEntity getComponent(@PathVariable long id) { Component component = componentService.getComponent(id); - + return ResponseEntity.ok(componentService.toDTO(component)); } @@ -68,15 +70,15 @@ public ResponseEntity getComponentImage(@PathVariable long id) throws @PostMapping("/") public ResponseEntity createComponent(@RequestBody ComponentDTO componentDTO) { - Component component = componentService.toDomain(componentDTO); - componentService.save(component); + Component component = componentService.toDomain(componentDTO); + componentService.save(component); - URI location = fromCurrentRequest().path("/{id}").buildAndExpand(component.getId()).toUri(); + URI location = fromCurrentRequest().path("/{id}").buildAndExpand(component.getId()).toUri(); - return ResponseEntity.created(location).body(componentService.toDTO(component)); + return ResponseEntity.created(location).body(componentService.toDTO(component)); } - @PostMapping("/{id}/image") + @RequestMapping(value = "/{id}/image", method = { RequestMethod.POST, RequestMethod.PUT }) public ResponseEntity addComponentImage(@PathVariable long id, @RequestParam MultipartFile imageFile) throws IOException { @@ -94,4 +96,16 @@ public void deleteComponent(@PathVariable long id) { } + @PutMapping("/{id}") + public ResponseEntity updateUser(@RequestBody ComponentDTO updatedData, @PathVariable long id) { + + Component newComponentData = componentService.toDomain(updatedData); + Component updatedComponent = componentService.updateComponent(newComponentData, id); + + URI location = fromCurrentRequest().buildAndExpand(updatedComponent.getId()).toUri(); + + return ResponseEntity.created(location).body(componentService.toDTO(updatedComponent)); + + } + } diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/security/SecurityConfig.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/security/SecurityConfig.java index 3842421..88419cb 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/security/SecurityConfig.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/security/SecurityConfig.java @@ -46,12 +46,12 @@ public DaoAuthenticationProvider authenticationProvider() { } @Bean - public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception { + public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) { return authConfig.getAuthenticationManager(); } @Bean - SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain securityFilterChain(HttpSecurity http) { http.authenticationProvider(authenticationProvider()); @@ -61,6 +61,7 @@ SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorize -> authorize .requestMatchers(HttpMethod.POST, "/api/v1/components/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/api/v1/components/**").hasRole("ADMIN") + .requestMatchers(HttpMethod.PUT, "/api/v1/components/**").hasRole("ADMIN") .requestMatchers(HttpMethod.GET, "/api/v1/users/**").hasRole("REGISTERED_USER") .requestMatchers(HttpMethod.POST, "/api/v1/users/*/image").hasRole("REGISTERED_USER") .requestMatchers(HttpMethod.DELETE, "/api/v1/users/**").hasRole("REGISTERED_USER") diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java index 9837f3c..107301b 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java @@ -30,8 +30,8 @@ public class ComponentsService { private final ComponentMapper componentMapper; private final ImageService imagesService; - - public ComponentsService(ComponentsRepository componentRepository, ComponentMapper componentMapper, ImageService imagesService) { + public ComponentsService(ComponentsRepository componentRepository, ComponentMapper componentMapper, + ImageService imagesService) { this.componentRepository = componentRepository; this.componentMapper = componentMapper; this.imagesService = imagesService; @@ -61,10 +61,10 @@ public Resource getImageFile(long id) throws SQLException { } - @PreAuthorize ("hasRole('ADMIN')") + @PreAuthorize("hasRole('ADMIN')") public Component save(Component component) { - List errors = validateComponent(component); + List errors = validateComponent(component, null); if (!errors.isEmpty()) { throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); @@ -80,7 +80,13 @@ public Image addComponentImage(long id, MultipartFile imageFile) throws IOExcept Component component = componentRepository.findById(id).orElseThrow(); - Image image = imagesService.createImage(imageFile.getInputStream()); + Image image; + + if (component.getImage() == null) { + image = imagesService.createImage(imageFile.getInputStream()); + } else { + image = imagesService.replaceImageFile(component.getImage().getId(), imageFile.getInputStream()); + } component.setImage(image); @@ -100,20 +106,46 @@ public void delete(long id) { } - public List validateComponent(Component component) { + @PreAuthorize("hasRole('ADMIN')") + public Component updateComponent(Component newComponentData, long id) { + + List errors = validateComponent(newComponentData, id); + + if (!errors.isEmpty()) { + throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); + } + + Component component = componentRepository.findById(id).orElseThrow(); + component.setName(newComponentData.getName()); + component.setDescription(newComponentData.getDescription()); + component.setBrand(newComponentData.getBrand()); + component.setType(newComponentData.getType()); + component.setPrice(newComponentData.getPrice()); + component.setStock(newComponentData.getStock()); + + return componentRepository.save(component); + + } + + public List validateComponent(Component component, Long id) { List errors = new ArrayList<>(); + Component originalComponent = null; + + if (id != null) { + originalComponent = componentRepository.findById(id).orElseThrow(); + } if (component.getName() == null || component.getName().isEmpty()) { errors.add("El nombre del componente es obligatorio."); } else { - validateName(component, errors); + validateName(component, originalComponent, errors); } validateRequiredField(component.getDescription(), "La descripción es obligatoria.", errors); validateRequiredField(component.getBrand(), "La marca es obligatoria.", errors); validateRequiredField(component.getType().toString(), "El tipo es obligatoria.", errors); - + if (component.getPrice() == null || component.getPrice().toString().isEmpty()) { errors.add("El precio es obligatorio."); } else { @@ -138,16 +170,19 @@ private void validateRequiredField(String value, String message, List er } - public void validateName(Component component, List errors) { + public void validateName(Component component, Component originalComponent, List errors) { - if (componentRepository.existsByName(component.getName())) { + boolean isNewComponent = (originalComponent == null); + boolean nameChanged = !isNewComponent && !originalComponent.getName().equals(component.getName()); + + if ((isNewComponent || nameChanged) && componentRepository.existsByName(component.getName())) { errors.add("Ya existe un componente con ese nombre."); } } public void validatePrice(Component component, List errors) { - + if (component.getPrice().compareTo(BigDecimal.ZERO) <= 0) { errors.add("El precio del producto ha de ser mayor de 0.00 €."); } @@ -155,7 +190,7 @@ public void validatePrice(Component component, List errors) { } public void validateStock(Component component, List errors) { - + if (component.getStock() < 0) { errors.add("El stock del producto ha de ser 0 o mayor."); } @@ -163,10 +198,10 @@ public void validateStock(Component component, List errors) { } public ComponentDTO toDTO(Component component) { - return componentMapper.toDTO(component); + return componentMapper.toDTO(component); } public Component toDomain(ComponentDTO componentDTO) { - return componentMapper.toDomain(componentDTO); + return componentMapper.toDomain(componentDTO); } } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java index 978d939..a89ac28 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java @@ -94,7 +94,7 @@ public void postComponentAsNoLoggedIn() { .header("Content-Type", "application/json") .body(""" { - "name": "AMD Ryzen 5 9600X", + "name": "AMD Ryzen 5 9600X", "description": "El AMD Ryzen 5 9600X destaca por su arquitectura de 4 nm y el nuevo socket AM5.", "type" : "CPU", "brand" : "AMD", @@ -153,7 +153,7 @@ public void postComponentAsAdmin() { .then().statusCode(200).contentType(ContentType.JSON) .extract().cookie("AuthToken"); - given() + given() .cookie("AuthToken", authToken) .header("Content-Type", "application/json") .body(""" @@ -257,7 +257,7 @@ public void postExistingComponentData() { .then().statusCode(200).contentType(ContentType.JSON) .extract().cookie("AuthToken"); - given() + given() .cookie("AuthToken", authToken) .header("Content-Type", "application/json") .body(""" @@ -290,7 +290,7 @@ public void postBadNumComponentData() { .then().statusCode(200).contentType(ContentType.JSON) .extract().cookie("AuthToken"); - given() + given() .cookie("AuthToken", authToken) .header("Content-Type", "application/json") .body(""" @@ -324,7 +324,7 @@ public void postBadFormatComponentData() { .then().statusCode(200).contentType(ContentType.JSON) .extract().cookie("AuthToken"); - given() + given() .cookie("AuthToken", authToken) .header("Content-Type", "application/json") .body(""" @@ -490,6 +490,297 @@ public void deleteComponentAsAdmin() { .then().statusCode(200); } + @Test + public void putComponentAsNoLoggedIn() { + + given() + .header("Content-Type", "application/json") + .body(""" + { + "name": "sampleNamePUT", + "description": "samepleDescriptionPUT", + "type" : "CPU", + "brand" : "sampleBrandPUT", + "price" : 100.00, + "stock" : 5 + } + """) + .when().put("components/5") + .then().statusCode(401).contentType(ContentType.JSON) + .body("error", equalTo("Unauthorized")); + } + + @Test + public void putComponentAsRegisteredUserNoAdmin() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "user@example.com", + "password": "userpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "name": "sampleNamePUT", + "description": "samepleDescriptionPUT", + "type" : "CPU", + "brand" : "sampleBrandPUT", + "price" : 100.00, + "stock" : 5 + } + """) + .when().put("components/5") + .then().statusCode(403).contentType(ContentType.JSON) + .body("error", equalTo("Forbidden")); + } + + @Test + public void putComponentAsAdmin() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "name": "sampleNamePUT", + "description": "sampleDescriptionPUT", + "type" : "CPU", + "brand" : "MSI", + "price" : 100.00, + "stock" : 5 + } + """) + .when().put("components/5") + .then().statusCode(201).contentType(ContentType.JSON) + .body("id", notNullValue()) + .body("name", equalTo("sampleNamePUT")) + .body("description", equalTo("sampleDescriptionPUT")) + .body("type", equalTo("CPU")) + .body("brand", equalTo("MSI")) + .body("price", equalTo(100.00F)) + .body("stock", equalTo(5)); + } + + @Test + public void putVoidComponent() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "name": "", + "description": "", + "type": "CPU", + "brand" : "", + "price": "", + "stock": "" + } + """) + .when().put("components/5") + .then().statusCode(500).contentType(ContentType.JSON) + .body("message", equalTo( + "Validación fallida:\n• El nombre del componente es obligatorio.\n• La descripción es obligatoria.\n• La marca es obligatoria.\n• El precio es obligatorio.\n• El stock es obligatorio.")); + } + + @Test + public void putNullComponent() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "name": null, + "description": null, + "type": "CPU", + "brand" : null, + "price": null, + "stock": null + } + """) + .when().put("components/5") + .then().statusCode(500).contentType(ContentType.JSON) + .body("message", equalTo( + "Validación fallida:\n• El nombre del componente es obligatorio.\n• La descripción es obligatoria.\n• La marca es obligatoria.\n• El precio es obligatorio.\n• El stock es obligatorio.")); + } + + @Test + public void putExistingComponent() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "name": "Kingston NV3", + "description": "samepleDescriptionPUT", + "type" : "CPU", + "brand" : "sampleBrandPUT", + "price" : 100.00, + "stock" : 5 + } + """) + .when().put("components/5") + .then().statusCode(500).contentType(ContentType.JSON) + .body("status", equalTo(500)) + .body("message", equalTo("Validación fallida:\n• Ya existe un componente con ese nombre.")); + } + + @Test + public void putBadFormatComponent() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "name": "sampleNamePUT", + "description": "samepleDescriptionPUT", + "type" : "CPU", + "brand" : "sampleBrandPUT", + "price" : -100.00, + "stock" : -5 + } + """) + .when().put("components/5") + .then().statusCode(500).contentType(ContentType.JSON) + .body("status", equalTo(500)) + .body("message", equalTo( + "Validación fallida:\n• El precio del producto ha de ser mayor de 0.00 €.\n• El stock del producto ha de ser 0 o mayor.")); + } + + @Test + public void putComponentImageAsNoLoggedIn() throws IOException { + byte[] updatedImage; + try (InputStream imageResource = getClass().getResourceAsStream("/sample_images/rtx-5060.jpg")) { + updatedImage = imageResource.readAllBytes(); + } + + given() + .multiPart("imageFile", "rtx-5060.jpg", updatedImage, "image/jpeg") + .when().put("components/5/image") + .then().statusCode(401).contentType(ContentType.JSON) + .body("error", equalTo("Unauthorized")); + } + + @Test + public void putComponentImageAsRegisteredUserNoAdmin() throws IOException { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "user@example.com", + "password": "userpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + byte[] updatedImage; + try (InputStream imageResource = getClass().getResourceAsStream("/sample_images/rtx-5060.jpg")) { + updatedImage = imageResource.readAllBytes(); + } + + given() + .cookie("AuthToken", authToken) + .multiPart("imageFile", "rtx-5060.jpg", updatedImage, "image/jpeg") + .when().put("components/5/image") + .then().statusCode(403).contentType(ContentType.JSON) + .body("error", equalTo("Forbidden")); + } + + @Test + public void putComponentImageAsAdmin() throws IOException { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + byte[] updatedImage; + try (InputStream imageResource = getClass().getResourceAsStream("/sample_images/rtx-5060.jpg")) { + updatedImage = imageResource.readAllBytes(); + } + + given() + .cookie("AuthToken", authToken) + .multiPart("imageFile", "rtx-5060.jpg", updatedImage, "image/jpeg") + .when().put("components/5/image") + .then().statusCode(201).contentType(ContentType.JSON); + + } + @Test public void loadComponentTypes() { given() diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/ComponentsSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/ComponentsSystemTests.java index bb9c847..b12df3e 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/ComponentsSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/ComponentsSystemTests.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -581,5 +582,206 @@ public void cancelDeleteComponentClosingModalTest() { assertThat(driver.findElement(By.id("component-1")).getText()) .isEqualTo("AMD Ryzen 7 7800X3D"); + } + + @Test + public void componentUpdateRenderTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/5/update"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("update-component-title"))); + String updateTitle = driver.findElement(By.id("update-component-title")).getText(); + assertThat(updateTitle).isEqualTo("Ingrese los datos del componente:"); + + assertThat(driver.findElement(By.id("name")).getAttribute("value")).isEqualTo("MAG A650BN"); + assertThat(driver.findElement(By.id("description")).getAttribute("value")).contains("Potencia total: 650 W"); + assertThat(driver.findElement(By.id("brand")).getAttribute("value")).isEqualTo("MSI"); + Select typeSelect = new Select(driver.findElement(By.id("type"))); + assertThat(typeSelect.getFirstSelectedOption().getText()).isEqualTo("Fuente de alimentación"); + assertThat(driver.findElement(By.id("price")).getAttribute("value")).isEqualTo(BigDecimal.valueOf(55.90).toString()); + assertThat(driver.findElement(By.id("stock")).getAttribute("value")).isEqualTo("20"); + + assertThat(driver.findElements(By.name("save-component-button"))).isNotEmpty(); + assertThat(driver.findElements(By.id("cancel-component-button"))).isNotEmpty(); + + } + + @Test + public void updateComponentTest() throws Exception { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/5/update"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("name"))); + driver.findElement(By.id("name")).clear(); + driver.findElement(By.id("name")).sendKeys("testUpdateComponent"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("description"))); + driver.findElement(By.id("description")).clear(); + driver.findElement(By.id("description")).sendKeys("testUpdateDescription"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("brand"))); + driver.findElement(By.id("brand")).clear(); + driver.findElement(By.id("brand")).sendKeys("testUpdateBrand"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("type"))); + Select select = new Select(driver.findElement(By.id("type"))); + select.selectByValue("CPU"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("price"))); + driver.findElement(By.id("price")).clear(); + driver.findElement(By.id("price")).sendKeys("5"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("stock"))); + driver.findElement(By.id("stock")).clear(); + driver.findElement(By.id("stock")).sendKeys("10"); + + String imagePath = Files.createTempFile("valid-image", ".png").toString(); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("image"))); + driver.findElement(By.id("image")).sendKeys(imagePath); + + scrollToAndClick(By.name("save-component-button")); + + wait.until(ExpectedConditions.urlMatches("http://localhost:5173/components/5")); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-name"))); + String loadedComponentName = driver.findElement(By.id("component-name")).getText(); + assertThat(loadedComponentName).isEqualTo("testUpdateComponent"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-description"))); + String loadedComponentDescription = driver.findElement(By.id("component-description")).getText(); + assertThat(loadedComponentDescription).contains("testUpdateDescription"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-brand-type"))); + String loadedComponentBrandType = driver.findElement(By.id("component-brand-type")).getText(); + assertThat(loadedComponentBrandType).isEqualTo("testUpdateBrand | CPU"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-price"))); + String loadedComponentPrice = driver.findElement(By.id("component-price")).getText(); + assertThat(loadedComponentPrice).isEqualTo("5.00 €"); + + Files.deleteIfExists(Paths.get(imagePath)); + + } + + @Test + public void updateVoidComponentTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/5/update"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("name"))); + driver.findElement(By.id("name")).clear(); + driver.findElement(By.id("description")).clear(); + driver.findElement(By.id("brand")).clear(); + Select select = new Select(driver.findElement(By.id("type"))); + select.selectByValue(""); + driver.findElement(By.id("price")).clear(); + driver.findElement(By.id("stock")).clear(); + + scrollToAndClick(By.name("save-component-button")); + + assertThat(driver.findElement(By.id("invalid-name")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-name")).getText()) + .isEqualTo("Por favor, ingrese un nombre válido."); + assertThat(driver.findElement(By.id("invalid-description")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-description")).getText()) + .isEqualTo("Por favor, ingrese una descripción válida."); + assertThat(driver.findElement(By.id("invalid-brand")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-brand")).getText()) + .isEqualTo("Por favor, ingrese una marca válida."); + assertThat(driver.findElement(By.id("invalid-type")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-type")).getText()) + .isEqualTo("Por favor, seleccione un tipo válido."); + assertThat(driver.findElement(By.id("invalid-price")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-price")).getText()) + .isEqualTo("Por favor, ingrese un precio válido."); + assertThat(driver.findElement(By.id("invalid-stock")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-stock")).getText()) + .isEqualTo("Por favor, ingrese un stock válido."); + assertThat(driver.getCurrentUrl()).isEqualTo("http://localhost:5173/components/5/update"); + + } + + @Test + public void updateExistingComponentTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/5/update"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("name"))); + driver.findElement(By.id("name")).clear(); + driver.findElement(By.id("name")).sendKeys("Kingston NV3"); + + scrollToAndClick(By.name("save-component-button")); + + WebElement errorMessage = wait.until( + ExpectedConditions.visibilityOfElementLocated(By.id("error-message"))); + assertThat(errorMessage.getText()).contains("Ya existe un componente con ese nombre."); + assertThat(driver.getCurrentUrl()).isEqualTo("http://localhost:5173/components/5/update"); + + } + + @Test + public void updateInvalidFormatComponentTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/5/update"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("price"))); + driver.findElement(By.id("price")).clear(); + driver.findElement(By.id("price")).sendKeys("-5.00"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("stock"))); + driver.findElement(By.id("stock")).clear(); + driver.findElement(By.id("stock")).sendKeys("-10"); + + scrollToAndClick(By.name("save-component-button")); + + assertThat(driver.findElement(By.id("invalid-price")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-price")).getText()) + .isEqualTo("Por favor, ingrese un precio válido."); + assertThat(driver.findElement(By.id("invalid-stock")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-stock")).getText()) + .isEqualTo("Por favor, ingrese un stock válido."); + assertThat(driver.getCurrentUrl()).isEqualTo("http://localhost:5173/components/5/update"); + + } + + @Test + public void updateInvalidImageComponentTest() throws Exception { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/5/update"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("image"))); + Path tempFile = Files.createTempFile("invalid-image", ".txt"); + Files.writeString(tempFile, "invalid file content"); + String imagePath = tempFile.toAbsolutePath().toString(); + driver.findElement(By.id("image")).sendKeys(imagePath); + + scrollToAndClick(By.name("save-component-button")); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("error-message"))); + assertThat(driver.findElement(By.id("error-message")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("error-message")).getText()) + .isEqualTo("Hubo un error al subir la imagen. Solo se permiten imágenes JPEG, PNG y WebP."); + assertThat(driver.getCurrentUrl()).isEqualTo("http://localhost:5173/components/5/update"); + + Files.deleteIfExists(Paths.get(imagePath)); + + } + + @Test + public void cancelUpdateComponentTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/5/update"); + + scrollToAndClick(By.id("cancel-component-button")); + + wait.until(ExpectedConditions.urlToBe("http://localhost:5173/components/5")); + + + } } \ No newline at end of file diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java index 8cf9e97..8113c31 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -102,7 +103,7 @@ void setUp() { passwordEncoder.encode("pass"), "REGISTERED_USER")); usersRepository.save(new User("admin", "test", "adminTest1", "c/testaddress", "testadmin1@example.com", passwordEncoder.encode("adminpass"), "REGISTERED_USER", "ADMIN")); - + } @Test @@ -118,7 +119,8 @@ void loadComponents() { @Test public void testGetComponent() { - Component component = componentsRepository.save(new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14)); + Component component = componentsRepository.save(new Component("Intel i5 12400F", + "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14)); Component loadedComponent = componentsService.getComponent(component.getId()); @@ -156,8 +158,9 @@ public void testGetNullComponentImage() throws SQLException { } @Test - void postComponentAsNoRegisteresUser() { - Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); + void postComponentAsNoRegisteredUser() { + Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); assertThrows(AuthenticationCredentialsNotFoundException.class, () -> componentsService.save(component)); } @@ -170,7 +173,8 @@ void postComponentAsNoAdmin() { .password("").authorities("ROLE_REGISTERED_USER").build(), null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER")))); - Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); + Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); assertThrows(AuthorizationDeniedException.class, () -> componentsService.save(component)); } @@ -184,7 +188,8 @@ void postComponentAsAdmin() { .password("").authorities("ROLE_ADMIN").build(), null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); - Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); + Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); assertDoesNotThrow(() -> componentsService.save(component)); } @@ -197,10 +202,11 @@ void validateComponent() { org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) .password("").authorities("ROLE_ADMIN").build(), null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); - - Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); - List errors = componentsService.validateComponent(component); + Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); + + List errors = componentsService.validateComponent(component, null); assertTrue(errors.isEmpty()); @@ -214,10 +220,10 @@ void validateVoidComponent() { org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) .password("").authorities("ROLE_ADMIN").build(), null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); - + Component component = new Component("", "", ComponentType.CPU, "", BigDecimal.valueOf(153.97), 14); - List errors = componentsService.validateComponent(component); + List errors = componentsService.validateComponent(component, null); assertTrue(errors.contains("El nombre del componente es obligatorio.")); assertTrue(errors.contains("La descripción es obligatoria.")); @@ -233,10 +239,10 @@ void validateNullComponent() { org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) .password("").authorities("ROLE_ADMIN").build(), null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); - + Component component = new Component(null, null, ComponentType.CPU, null, BigDecimal.valueOf(153.97), 14); - List errors = componentsService.validateComponent(component); + List errors = componentsService.validateComponent(component, null); assertTrue(errors.contains("El nombre del componente es obligatorio.")); assertTrue(errors.contains("La descripción es obligatoria.")); @@ -252,10 +258,11 @@ void validateBadNumComponentData() { org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) .password("").authorities("ROLE_ADMIN").build(), null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); - - Component component = new Component("sampleComponent", "sampleDescription", ComponentType.CPU, "sampleBrand", BigDecimal.valueOf(-350.00), -5); - List errors = componentsService.validateComponent(component); + Component component = new Component("sampleComponent", "sampleDescription", ComponentType.CPU, "sampleBrand", + BigDecimal.valueOf(-350.00), -5); + + List errors = componentsService.validateComponent(component, null); assertTrue(errors.contains("El precio del producto ha de ser mayor de 0.00 €.")); assertTrue(errors.contains("El stock del producto ha de ser 0 o mayor.")); @@ -270,10 +277,11 @@ void validateExistingComponentData() { org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) .password("").authorities("ROLE_ADMIN").build(), null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); - - Component component = new Component("AMD Ryzen 7 7800X3D", "Procesador de 8 núcleos y 16 hilos", ComponentType.CPU, "AMD", BigDecimal.valueOf(350.00), 5); - List errors = componentsService.validateComponent(component); + Component component = new Component("AMD Ryzen 7 7800X3D", "Procesador de 8 núcleos y 16 hilos", ComponentType.CPU, + "AMD", BigDecimal.valueOf(350.00), 5); + + List errors = componentsService.validateComponent(component, null); assertTrue(errors.contains("Ya existe un componente con ese nombre.")); @@ -287,8 +295,8 @@ void postComponentImageAsNonRegisteredUser() throws IOException { resource.getInputStream()); Component component = componentsRepository.findAll().get(0); - assertThrows(AuthenticationCredentialsNotFoundException.class, - () -> componentsService.addComponentImage(component.getId(), imageFile)); + assertThrows(AuthenticationCredentialsNotFoundException.class, + () -> componentsService.addComponentImage(component.getId(), imageFile)); } @@ -306,7 +314,8 @@ void postComponentImageAsNoAdmin() throws IOException { expectedImage.getInputStream()); Component component = componentsRepository.findAll().get(0); - assertThrows(AuthorizationDeniedException.class, () -> componentsService.addComponentImage(component.getId(), imageFile)); + assertThrows(AuthorizationDeniedException.class, + () -> componentsService.addComponentImage(component.getId(), imageFile)); } @@ -326,8 +335,8 @@ void postImagesAsAdmin() throws IOException, SQLException { Component component = componentsRepository.findAll().get(0); Image savedComponentImage = componentsService.addComponentImage(component.getId(), imageFile); - assertArrayEquals(expectedImage.getInputStream().readAllBytes(), - savedComponentImage.getImageFile().getBinaryStream().readAllBytes()); + assertArrayEquals(expectedImage.getInputStream().readAllBytes(), + savedComponentImage.getImageFile().getBinaryStream().readAllBytes()); } @Test @@ -343,7 +352,8 @@ void postImageWithInvalidFile() { "image", "image.txt", "text/plain", new byte[1024]); Component component = componentsRepository.findAll().get(0); - assertThrows(IllegalArgumentException.class, () -> componentsService.addComponentImage(component.getId(), invalidTypeImage)); + assertThrows(IllegalArgumentException.class, + () -> componentsService.addComponentImage(component.getId(), invalidTypeImage)); } @@ -386,4 +396,254 @@ void deleteComponentAsAdmin() { } + @Test + void updateImageAsNoRegisteredUser() throws IOException { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User + .withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Resource originalResource = new ClassPathResource("/sample_images/rtx-5060.jpg"); + MockMultipartFile originalImageFile = new MockMultipartFile("imageFile", "rtx-5060.jpg", "image/jpeg", + originalResource.getInputStream()); + componentsService.addComponentImage(component.getId(), originalImageFile); + + SecurityContextHolder.clearContext(); + + Resource newResource = new ClassPathResource("/sample_images/rx-9060.jpg"); + MockMultipartFile newImageFile = new MockMultipartFile("imageFile", "rx-9060.jpg", "image/jpeg", + newResource.getInputStream()); + + assertThrows(AuthenticationCredentialsNotFoundException.class, + () -> componentsService.addComponentImage(component.getId(), newImageFile)); + + } + + @Test + void updateImageAsRegisteredUserNoAdmin() throws IOException { + User user = usersRepository.findByEmail("testuser1@example.com").orElseThrow(); + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User + .withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Resource originalResource = new ClassPathResource("/sample_images/rtx-5060.jpg"); + MockMultipartFile originalImageFile = new MockMultipartFile("imageFile", "rtx-5060.jpg", "image/jpeg", + originalResource.getInputStream()); + componentsService.addComponentImage(component.getId(), originalImageFile); + + SecurityContextHolder.clearContext(); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User + .withUsername(user.getId().toString()) + .password("").authorities("ROLE_REGISTERED_USER").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER")))); + + Resource newResource = new ClassPathResource("/sample_images/rx-9060.jpg"); + MockMultipartFile newImageFile = new MockMultipartFile("imageFile", "rx-9060.jpg", "image/jpeg", + newResource.getInputStream()); + + assertThrows(AuthorizationDeniedException.class, + () -> componentsService.addComponentImage(component.getId(), newImageFile)); + + } + + @Test + void updateImagesAsAdmin() throws IOException, SQLException { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Resource originalResource = new ClassPathResource("/sample_images/rtx-5060.jpg"); + MockMultipartFile originalImageFile = new MockMultipartFile("imageFile", "rtx-5060.jpg", "image/jpeg", + originalResource.getInputStream()); + Image originalImage = componentsService.addComponentImage(component.getId(), originalImageFile); + + Resource newResource = new ClassPathResource("/sample_images/rx-9060.jpg"); + MockMultipartFile newImageFile = new MockMultipartFile("imageFile", "rx-9060.jpg", "image/jpeg", + newResource.getInputStream()); + + Image newImage = componentsService.addComponentImage(component.getId(), newImageFile); + + assertNotEquals(originalImage.getImageFile().getBinaryStream().readAllBytes(), + newImage.getImageFile().getBinaryStream().readAllBytes()); + + } + + @Test + void updateComponentAsNoRegisteredUser() { + Component component = componentsRepository.findAll().get(0); + + Component updatedComponent = new Component("sampleName", "sampleDescription", ComponentType.CPU, "sampleBrand", + BigDecimal.valueOf(100.00), 5); + + assertThrows(AuthenticationCredentialsNotFoundException.class, + () -> componentsService.updateComponent(updatedComponent, component.getId())); + } + + @Test + void updateComponentAsRegisteredUserNoAdmin() { + Component component = componentsRepository.findAll().get(0); + + Component updatedComponent = new Component("sampleName", "sampleDescription", ComponentType.CPU, "sampleBrand", + BigDecimal.valueOf(100.00), 5); + + User user = usersRepository.findByEmail("testuser1@example.com").orElseThrow(); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(user.getId().toString()) + .password("").authorities("ROLE_REGISTERED_USER").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER")))); + + assertThrows(AuthorizationDeniedException.class, + () -> componentsService.updateComponent(updatedComponent, component.getId())); + } + + @Test + void updateComponentAsAdmin() { + Component component = componentsRepository.findAll().get(0); + + Component updatedComponent = new Component("sampleName", "sampleDescription", ComponentType.CPU, "sampleBrand", + BigDecimal.valueOf(100.00), 5); + + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Component savedComponent = componentsService.updateComponent(updatedComponent, component.getId()); + + assertEquals("sampleName", savedComponent.getName()); + assertEquals("sampleDescription", savedComponent.getDescription()); + assertEquals(ComponentType.CPU, savedComponent.getType()); + assertEquals("sampleBrand", savedComponent.getBrand()); + assertEquals(BigDecimal.valueOf(100.00), savedComponent.getPrice()); + assertEquals(5, savedComponent.getStock()); + } + + @Test + void updateVoidComponent() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Component updatedComponent = new Component("", "", ComponentType.CPU, "", BigDecimal.valueOf(100.00), 5); + + assertThrows(IllegalArgumentException.class, + () -> componentsService.updateComponent(updatedComponent, component.getId())); + } + + @Test + void updateNullComponent() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Component updatedComponent = new Component(null, null, ComponentType.CPU, null, BigDecimal.valueOf(100.00), 5); + + assertThrows(IllegalArgumentException.class, + () -> componentsService.updateComponent(updatedComponent, component.getId())); + } + + @Test + void updateExistingComponent() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Component updatedComponent = new Component("NVIDIA GeForce RTX 5060 WINDFORCE MAX OC", "sampleDescription", + ComponentType.CPU, "sampleBrand", BigDecimal.valueOf(100.00), 5); + + assertThrows(IllegalArgumentException.class, + () -> componentsService.updateComponent(updatedComponent, component.getId())); + } + + @Test + void updateBadFormatComponent() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Component updatedComponent = new Component("sampleName", "sampleDescription", ComponentType.CPU, "sampleBrand", + BigDecimal.valueOf(-100.00), -5); + + assertThrows(IllegalArgumentException.class, + () -> componentsService.updateComponent(updatedComponent, component.getId())); + } + + @Test + void updateValidation() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component originalComponent = componentsRepository.findAll().get(0); + Component updatedComponent = new Component("sampleName", "sampleDescription", ComponentType.CPU, "sampleBrand", + BigDecimal.valueOf(100.00), 5); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + List errors = componentsService.validateComponent(updatedComponent, originalComponent.getId()); + + assertTrue(errors.isEmpty()); + } + + @Test + void updateExistingValidationComponent() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component originalComponent = componentsRepository.findAll().get(0); + Component updatedComponent = new Component("NVIDIA GeForce RTX 5060 WINDFORCE MAX OC", "sampleDescription", + ComponentType.CPU, "sampleBrand", BigDecimal.valueOf(100.00), 5); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + List errors = componentsService.validateComponent(updatedComponent, originalComponent.getId()); + + assertTrue(errors.contains("Ya existe un componente con ese nombre.")); + } + } \ No newline at end of file diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java index c131561..5a80d94 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java @@ -8,8 +8,10 @@ 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.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -18,6 +20,7 @@ import java.util.List; import java.util.Optional; import java.io.IOException; +import java.io.InputStream; import java.math.BigDecimal; import javax.sql.rowset.serial.SerialBlob; @@ -66,7 +69,8 @@ public void testGetComponent() { ImageService imageService = mock(ImageService.class); ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); - Component componentToReturn = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); + Component componentToReturn = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", + ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); when(componentsRepository.findById(1L)).thenReturn(Optional.of(componentToReturn)); @@ -130,7 +134,8 @@ public void testCreateComponent() { ImageService imageService = mock(ImageService.class); ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); - Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); + Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); when(componentsRepository.save(any(Component.class))).thenReturn(component); @@ -184,7 +189,8 @@ public void testCreateExistingComponentData() { ImageService imageService = mock(ImageService.class); ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); - Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); + Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); when(componentsRepository.existsByName("Intel i5 12400F")).thenReturn(true); @@ -201,8 +207,9 @@ public void testValidation() { ImageService imageService = mock(ImageService.class); ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); - Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); - List errors = componentsService.validateComponent(component); + Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); + List errors = componentsService.validateComponent(component, null); assertTrue(errors.isEmpty()); @@ -217,7 +224,7 @@ public void testVoidComponentValidation() { ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); Component component = new Component("", "", ComponentType.CPU, "", BigDecimal.valueOf(153.97), 14); - List errors = componentsService.validateComponent(component); + List errors = componentsService.validateComponent(component, null); assertTrue(errors.contains("El nombre del componente es obligatorio.")); assertTrue(errors.contains("La descripción es obligatoria.")); @@ -234,7 +241,7 @@ public void testNullComponentValidation() { ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); Component component = new Component(null, null, ComponentType.CPU, null, BigDecimal.valueOf(153.97), 14); - List errors = componentsService.validateComponent(component); + List errors = componentsService.validateComponent(component, null); assertTrue(errors.contains("El nombre del componente es obligatorio.")); assertTrue(errors.contains("La descripción es obligatoria.")); @@ -250,8 +257,9 @@ public void testBadNumComponentValidation() { ImageService imageService = mock(ImageService.class); ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); - Component component = new Component("sampleComponent", "sampleDescription", ComponentType.CPU, "sampleBrand", BigDecimal.valueOf(-153.97), -14); - List errors = componentsService.validateComponent(component); + Component component = new Component("sampleComponent", "sampleDescription", ComponentType.CPU, "sampleBrand", + BigDecimal.valueOf(-153.97), -14); + List errors = componentsService.validateComponent(component, null); assertTrue(errors.contains("El precio del producto ha de ser mayor de 0.00 €.")); assertTrue(errors.contains("El stock del producto ha de ser 0 o mayor.")); @@ -266,10 +274,11 @@ public void testExistingComponentValidation() { ImageService imageService = mock(ImageService.class); ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); - Component component = new Component("Intel i5 12400F", "Procesado de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); + Component component = new Component("Intel i5 12400F", "Procesado de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); when(componentsRepository.existsByName("Intel i5 12400F")).thenReturn(true); - List errors = componentsService.validateComponent(component); + List errors = componentsService.validateComponent(component, null); assertTrue(errors.contains("Ya existe un componente con ese nombre.")); @@ -283,8 +292,9 @@ public void testAddImageFile() throws Exception { ImageService imageService = mock(ImageService.class); ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); - Component component = new Component("Intel i5 12400F", "Procesado de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); - + Component component = new Component("Intel i5 12400F", "Procesado de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); + Resource expectedImage = new ClassPathResource("/sample_images/i5-12400f.webp"); MockMultipartFile imageFile = new MockMultipartFile( "imageFile", "user.png", "image/png", expectedImage.getInputStream()); @@ -303,13 +313,14 @@ public void testAddImageFile() throws Exception { @Test public void testAddImageWithInvalidFile() throws IOException { - + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); ComponentMapper componentMapper = mock(ComponentMapper.class); ImageService imageService = mock(ImageService.class); ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); - Component component = new Component("Intel i5 12400F", "Procesado de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); + Component component = new Component("Intel i5 12400F", "Procesado de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); MockMultipartFile invalidTypeImage = new MockMultipartFile( @@ -320,6 +331,44 @@ public void testAddImageWithInvalidFile() throws IOException { assertThrows(IllegalArgumentException.class, () -> componentsService.addComponentImage(1L, invalidTypeImage)); } + @Test + public void testUpdateImageFile() throws Exception { + + ComponentsRepository componentRepository = mock(ComponentsRepository.class); + ComponentMapper componentMapper = mock(ComponentMapper.class); + ImageService imageService = mock(ImageService.class); + ComponentsService componentService = new ComponentsService(componentRepository, componentMapper, imageService); + + Resource originalResource = new ClassPathResource("/sample_images/rtx-5060.jpg"); + MockMultipartFile originalImageFile = new MockMultipartFile("imageFile", "rtx-5060.jpg", "image/jpg", + originalResource.getInputStream()); + Image originalImage = new Image(new SerialBlob(originalImageFile.getInputStream().readAllBytes())); + originalImage.setId(1L); + + Resource newResource = new ClassPathResource("/sample_images/rx-9060.jpg"); + MockMultipartFile newImageFile = new MockMultipartFile("imageFile", "rx-9060.jpg", "image/jpg", + newResource.getInputStream()); + Image newImage = new Image(new SerialBlob(newImageFile.getInputStream().readAllBytes())); + newImage.setId(2L); + + when(imageService.createImage(any(InputStream.class))).thenReturn(originalImage); + when(imageService.replaceImageFile(anyLong(), any(InputStream.class))).thenReturn(newImage); + + Component component = new Component("sampleName", "sampleDescription", ComponentType.GPU, "sampleBrand", + BigDecimal.valueOf(5.00), 7); + when(componentRepository.findById(1L)).thenReturn(java.util.Optional.of(component)); + when(componentRepository.save(component)).thenReturn(component); + componentService.addComponentImage(1L, originalImageFile); + + Image actualImage = componentService.addComponentImage(1L, newImageFile); + + verify(componentRepository, times(2)).save(component); + + assertArrayEquals(newResource.getInputStream().readAllBytes(), + actualImage.getImageFile().getBinaryStream().readAllBytes()); + + } + @Test public void testDeleteComponent() { @@ -328,7 +377,8 @@ public void testDeleteComponent() { ImageService imageService = mock(ImageService.class); ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); - Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, "Intel", BigDecimal.valueOf(153.97), 14); + Component component = new Component("Intel i5 12400F", "Procesador de 6 núcleos y 12 hilos", ComponentType.CPU, + "Intel", BigDecimal.valueOf(153.97), 14); when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); @@ -350,7 +400,159 @@ public void testDeleteNonExistentComponent() { componentsService.delete(1L); - verify(componentsRepository, never()).deleteById(1L); + verify(componentsRepository, never()).deleteById(1L); + + } + + @Test + public void testUpdate() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + ComponentMapper componentMapper = mock(ComponentMapper.class); + ImageService imageService = mock(ImageService.class); + ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); + + Component originalComponent = new Component("originalComponent", "originalDescription", + ComponentType.CPU, "originalBrand", BigDecimal.valueOf(100.00), 5); + + Component updatedComponent = new Component("updatedComponent", "updatedDescription", + ComponentType.GPU, "updatedBrand", BigDecimal.valueOf(200.00), 10); + + when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(originalComponent)); + when(componentsRepository.save(any(Component.class))).thenReturn(originalComponent); + + Component componentSaved = componentsService.updateComponent(updatedComponent, 1L); + + assertEquals(updatedComponent.getName(), componentSaved.getName()); + assertEquals(updatedComponent.getDescription(), componentSaved.getDescription()); + assertEquals(updatedComponent.getBrand(), componentSaved.getBrand()); + assertEquals(updatedComponent.getType(), componentSaved.getType()); + assertEquals(updatedComponent.getPrice(), componentSaved.getPrice()); + assertEquals(updatedComponent.getStock(), componentSaved.getStock()); + verify(componentsRepository).save(any(Component.class)); + + } + + @Test + public void testVoidUpdate() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + ComponentMapper componentMapper = mock(ComponentMapper.class); + ImageService imageService = mock(ImageService.class); + ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); + + Component originalComponent = new Component("originalComponent", "originalDescription", + ComponentType.CPU, "originalBrand", BigDecimal.valueOf(100.00), 5); + Component component = new Component("", "", ComponentType.CPU, "", BigDecimal.valueOf(100.00), 5); + + when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(originalComponent)); + + assertThrows(IllegalArgumentException.class, () -> componentsService.updateComponent(component, 1L)); + verify(componentsRepository, never()).save(any(Component.class)); + + } + + @Test + public void testNullUpdate() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + ComponentMapper componentMapper = mock(ComponentMapper.class); + ImageService imageService = mock(ImageService.class); + ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); + + Component originalComponent = new Component("originalComponent", "originalDescription", + ComponentType.CPU, "originalBrand", BigDecimal.valueOf(100.00), 5); + Component component = new Component(null, null, ComponentType.CPU, null, BigDecimal.valueOf(100.00), 10); + + when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(originalComponent)); + + assertThrows(IllegalArgumentException.class, () -> componentsService.updateComponent(component, 1L)); + verify(componentsRepository, never()).save(any(Component.class)); + + } + + @Test + public void testExistingUpdate() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + ComponentMapper componentMapper = mock(ComponentMapper.class); + ImageService imageService = mock(ImageService.class); + ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); + + Component originalComponent = new Component("originalComponent", "originalDescription", + ComponentType.CPU, "originalBrand", BigDecimal.valueOf(100.00), 5); + when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(originalComponent)); + + Component updatedComponent = new Component("existingComponent", "updatedDescription", + ComponentType.GPU, "updatedBrand", BigDecimal.valueOf(200.00), 10); + + when(componentsRepository.existsByName("existingComponent")).thenReturn(true); + + assertThrows(IllegalArgumentException.class, () -> componentsService.updateComponent(updatedComponent, 1L)); + verify(componentsRepository, never()).save(any(Component.class)); + + } + + @Test + public void testBadFormatUpdate() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + ComponentMapper componentMapper = mock(ComponentMapper.class); + ImageService imageService = mock(ImageService.class); + ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); + + Component component = new Component("sampleName", "sampleDescription", ComponentType.CPU, "sampleBrand", + BigDecimal.valueOf(-5.00), -5); + when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(component)); + + assertThrows(IllegalArgumentException.class, () -> componentsService.updateComponent(component, 1L)); + verify(componentsRepository, never()).save(any(Component.class)); + } + + @Test + public void testUpdateValidation() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + ComponentMapper componentMapper = mock(ComponentMapper.class); + ImageService imageService = mock(ImageService.class); + ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); + + Component originalComponent = new Component("originalComponent", "originalDescription", + ComponentType.CPU, "originalBrand", BigDecimal.valueOf(100.00), 5); + + Component updatedComponent = new Component("updatedComponent", "updatedDescription", + ComponentType.GPU, "updatedBrand", BigDecimal.valueOf(200.00), 10); + + when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(originalComponent)); + + List errors = componentsService.validateComponent(updatedComponent, 1L); + + assertTrue(errors.isEmpty()); + + } + + @Test + public void testExistingUpdateValidation() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + ComponentMapper componentMapper = mock(ComponentMapper.class); + ImageService imageService = mock(ImageService.class); + ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); + + Component originalComponent = new Component("originalComponent", "originalDescription", + ComponentType.CPU, "originalBrand", BigDecimal.valueOf(100.00), 5); + + Component updatedComponent = new Component("updatedComponent", "updatedDescription", + ComponentType.GPU, "updatedBrand", BigDecimal.valueOf(200.00), 10); + + when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(originalComponent)); + + when(componentsRepository.existsByName("updatedComponent")).thenReturn(true); + + List errors = componentsService.validateComponent(updatedComponent, 1L); + + assertTrue(errors.contains("Ya existe un componente con ese nombre.")); + verify(componentsRepository).existsByName("updatedComponent"); } diff --git a/frontend/app/app.css b/frontend/app/app.css index 1aaf33c..fc8f06f 100644 --- a/frontend/app/app.css +++ b/frontend/app/app.css @@ -631,6 +631,21 @@ body { min-height: 50px; } +#edit-component-button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.45rem; + height: 50px; + min-height: 50px; + padding: 0.375rem 0.75rem; + border: 1px solid var(--color-line); + border-radius: 8px; + font-family: var(--font-sans); + text-decoration: none; + transition: background-color 160ms ease, border-color 160ms ease, transform 160ms ease; +} + .component-actions .btn-secondary { color: #ffffff; background-color: var(--color-principal); diff --git a/frontend/app/components/componentsForm.tsx b/frontend/app/components/componentsForm.tsx index ba9b845..ee7a008 100644 --- a/frontend/app/components/componentsForm.tsx +++ b/frontend/app/components/componentsForm.tsx @@ -1,9 +1,12 @@ import type { SubmitEvent, RefObject } from "react"; +import { useState } from "react"; import { FormControl, FormLabel, FormSelect, Button } from "react-bootstrap"; import { ArrowLeft, Floppy } from "react-bootstrap-icons"; import { Link } from "react-router"; +import type ComponentDTO from "~/dtos/ComponentDTO"; interface ComponentFormProps { + component?: Partial onSubmit: (event: SubmitEvent) => void; isPending: boolean; wasValidated: boolean; @@ -14,15 +17,19 @@ interface ComponentFormProps { } export default function ComponentForm({ + component, onSubmit, isPending, wasValidated, componentTypes, componentTypeLabels, formRef, - submitLabel = "Guardar componente", + submitLabel, }: Readonly) { +const [selectedType, setSelectedType] = useState(component?.type ?? ""); +const cancelPath = component?.id !== undefined ? `/components/${component.id}` : "/components"; + return (
Nombre: - +
Por favor, ingrese un nombre válido.
@@ -41,7 +48,7 @@ export default function ComponentForm({
Descripción: - +
Por favor, ingrese una descripción válida.
@@ -50,7 +57,7 @@ export default function ComponentForm({
Marca: - +
Por favor, ingrese una marca válida.
@@ -58,7 +65,7 @@ export default function ComponentForm({
Tipo de componente: - + setSelectedType(event.target.value)}> {componentTypes.map(type => (