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
Expand Up @@ -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;
Expand Down Expand Up @@ -49,10 +51,10 @@ public List<ComponentDTO> findTop3MoreRecent() {
}

@GetMapping("/{id}")
public ResponseEntity<ComponentDTO> getComponent (@PathVariable long id) {
public ResponseEntity<ComponentDTO> getComponent(@PathVariable long id) {

Component component = componentService.getComponent(id);

return ResponseEntity.ok(componentService.toDTO(component));
}

Expand All @@ -68,15 +70,15 @@ public ResponseEntity<Resource> getComponentImage(@PathVariable long id) throws
@PostMapping("/")
public ResponseEntity<ComponentDTO> 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<ImageDTO> addComponentImage(@PathVariable long id, @RequestParam MultipartFile imageFile)
throws IOException {

Expand All @@ -94,4 +96,16 @@ public void deleteComponent(@PathVariable long id) {

}

@PutMapping("/{id}")
public ResponseEntity<ComponentDTO> 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));

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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());

Expand All @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -61,10 +61,10 @@ public Resource getImageFile(long id) throws SQLException {

}

@PreAuthorize ("hasRole('ADMIN')")
@PreAuthorize("hasRole('ADMIN')")
public Component save(Component component) {

List<String> errors = validateComponent(component);
List<String> errors = validateComponent(component, null);

if (!errors.isEmpty()) {
throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors));
Expand All @@ -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);

Expand All @@ -100,20 +106,46 @@ public void delete(long id) {

}

public List<String> validateComponent(Component component) {
@PreAuthorize("hasRole('ADMIN')")
public Component updateComponent(Component newComponentData, long id) {

List<String> 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<String> validateComponent(Component component, Long id) {

List<String> 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 {
Expand All @@ -138,35 +170,38 @@ private void validateRequiredField(String value, String message, List<String> er

}

public void validateName(Component component, List<String> errors) {
public void validateName(Component component, Component originalComponent, List<String> 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<String> errors) {

if (component.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
errors.add("El precio del producto ha de ser mayor de 0.00 €.");
}

}

public void validateStock(Component component, List<String> errors) {

if (component.getStock() < 0) {
errors.add("El stock del producto ha de ser 0 o mayor.");
}

}

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);
}
}
Loading
Loading