Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Feat Prioridad del Proyecto #14

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>3.0.0</version>
</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.example.project.management.DTO;

import com.example.project.management.model.PrioridadProyecto;
import lombok.Data;

import java.time.LocalDateTime;

@Data
public class PrioridadProyectoDTO {

private Long id;
private String nombre;
private LocalDateTime fechaEliminacion;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.example.project.management.controller;

import com.example.project.management.DTO.PrioridadProyectoDTO;
import com.example.project.management.exception.BadRequestException;
import com.example.project.management.exception.ResponseService;
import com.example.project.management.mapper.PrioridadProyectoMapper;
import com.example.project.management.model.PrioridadProyecto;
import com.example.project.management.service.PrioridadProyectoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/prioridad-proyecto")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

El nombre de la ruta se deberia ajustar a algo mas acorde como /prioridades

@CrossOrigin (origins = "*")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esto es un riesgo de seguridad, permite todos los dominios de origen y solo estaria medianamente a salvo en una red privada. Dejo como acotacion.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Si, la cuestion es que no sabia si manejaban las cors de forma global ya que no habia mas info sobre el proyecto completo

public class PrioridadProyectoController {
@Autowired
private PrioridadProyectoService modelService;

@Autowired
private ResponseService responseService;

@GetMapping({"/"})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No es necesario agregar la barra si el mapping va al root, nuevamente solo como acotacion.

public ResponseEntity<?> getAll() {
List<PrioridadProyectoDTO> prioridades = modelService.findAllByFechaEliminacionIsNull();
if (prioridades.isEmpty()) {
throw new BadRequestException("No hay roles creados");
}
return responseService.successResponse(prioridades, "OK");
}

@GetMapping("/id/{id}")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esto podria ser solamente /{id} para respetar la convencion de nombre.

public ResponseEntity<?> getPorId(@PathVariable Long id){
PrioridadProyecto model = modelService.findByIdAndFechaEliminacionIsNull(id);
PrioridadProyectoDTO modelDTO = PrioridadProyectoMapper.toDTO(model);
return responseService.successResponse(modelDTO, "OK");
}
@GetMapping("/nombre/{nombre}")
public ResponseEntity<?> getPorNombre(@PathVariable String nombre){
PrioridadProyecto model = modelService.findByNombreAndFechaEliminacionIsNull(nombre);
PrioridadProyectoDTO modelDTO = PrioridadProyectoMapper.toDTO(model);
return responseService.successResponse(modelDTO, "OK");
}


@PostMapping({"/"})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mismo caso que el GET / de arriba.

public ResponseEntity<?> crear(@RequestBody PrioridadProyectoDTO prioridadProyectoDTO) {
return responseService.successResponse(modelService.crear(prioridadProyectoDTO), "Prioridad creada");
}


@DeleteMapping("/id/{id}")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mismo caso que el /{id} arriba.

public ResponseEntity<?> deleteById(@PathVariable Long id) {
modelService.deleteById(id);
return responseService.successResponse(null, "Prioridad eliminada");
}

@DeleteMapping("/nombre/{nombre}")
public ResponseEntity<?> deleteByNombre(@PathVariable String nombre) {
modelService.deleteByNombre(nombre);
return responseService.successResponse(null, "Prioridad eliminada");
}

@PostMapping("/recuperar/id/{id}")
public ResponseEntity<?> recuperarPorId(@PathVariable Long id) {
modelService.recuperarPorId(id);
return responseService.successResponse(null, "Prioridad recuperada");
}

@PostMapping("/recuperar/nombre/{nombre}")
public ResponseEntity<?> recuperarPorNombre(@PathVariable String nombre) {
modelService.recuperarPorNombre(nombre);
return responseService.successResponse(null, "Prioridad recuperada");
}

@PutMapping ("/")
public ResponseEntity<?> update( @RequestBody PrioridadProyectoDTO prioridadProyectoDTO) {
return responseService.successResponse(modelService.update(prioridadProyectoDTO), "Prioridad actualizada");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.example.project.management.exception;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiResponse<T> {
private int status; // Código de estado HTTP
private String message; // Mensaje de estado (éxito o error)
private T data; // Datos relevantes que se devuelven
private String errors; // En caso de error, detalles del mismo
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.example.project.management.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
/*
* El BadRequestException es una excepcion personalizada que se utiliza para manejar
* errores de validaciones de datos.
* Por ejemplo: Cuando un argumento tiene que tener un tipo de dato correcto.
* */
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.project.management.exception;

public class ConflictException extends RuntimeException {
public ConflictException(String message) {
super(message);
}
}
/*
* ConflictException se usa para manejar errores de conflictos
* Por ejemplo: Cuando un recurso ya existe.
* */
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.project.management.exception;

public class ForbiddenException extends RuntimeException {
public ForbiddenException(String message) {
super(message);
}
}
/*
* ForbiddenException sirve para manejar los errores de acceso denegado
* Por ejemplo: Cuando un usuario no tiene permiso para acceder a un recurso.
* */
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.example.project.management.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@RestControllerAdvice
public class GlobalExceptionHandler {

// Manejo de BadRequestException (400)
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<Object> handleBadRequest(BadRequestException ex) {
ApiResponse<Object> response = new ApiResponse<>(
400,
"Error: Bad Request",
null,
ex.getMessage()
);
return ResponseEntity.badRequest().body(response);
}

// Manejo de NotFoundException (404)
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<Object> handleNotFound(NotFoundException ex) {
ApiResponse<Object> response = new ApiResponse<>(
404,
"Error: Not Found",
null,
ex.getMessage()
);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}
@ExceptionHandler(ForbiddenException.class)
public ResponseEntity<Object> handleForbidden(ForbiddenException ex) {
ApiResponse<Object> response = new ApiResponse<>(
403,
"Error: Forbidden",
null,
ex.getMessage()
);
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
}

@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<Object> handleUnauthorized(UnauthorizedException ex) {
ApiResponse<Object> response = new ApiResponse<>(
401,
"Error: Unauthorized",
null,
ex.getMessage()
);
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
}

@ExceptionHandler(ConflictException.class)
public ResponseEntity<Object> handleConflict(ConflictException ex) {
ApiResponse<Object> response = new ApiResponse<>(
409,
"Error: Conflict",
null,
ex.getMessage()
);
return ResponseEntity.status(HttpStatus.CONFLICT).body(response);
}

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<Object> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
// Creamos una respuesta en formato JSON con el error
String error = String.format("El parametro enviado '%s' no es del tipo esperado.", ex.getName());
ApiResponse<Object> response = new ApiResponse<>(
400,
"Error de tipo de argumento",
null,
error
);
return ResponseEntity.badRequest().body(response);
}

// Manejo de cualquier otra excepción no controlada (500)
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleGlobalException(Exception ex) {
ApiResponse<Object> response = new ApiResponse<>(
500,
"Error: Internal Server Error",
null,
"Ocurrió un error inesperado."
);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package com.example.project.management.exception;

import com.tpi_pais.mega_store.utils.ApiResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@RestControllerAdvice
public class GlobalExceptionHandler {

// Manejo de BadRequestException (400)
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<Object> handleBadRequest(BadRequestException ex) {
ApiResponse<Object> response = new ApiResponse<>(
400,
"Error: Bad Request",
null,
ex.getMessage()
);
return ResponseEntity.badRequest().body(response);
}

// Manejo de NotFoundException (404)
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<Object> handleNotFound(NotFoundException ex) {
ApiResponse<Object> response = new ApiResponse<>(
404,
"Error: Not Found",
null,
ex.getMessage()
);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}
@ExceptionHandler(ForbiddenException.class)
public ResponseEntity<Object> handleForbidden(ForbiddenException ex) {
ApiResponse<Object> response = new ApiResponse<>(
403,
"Error: Forbidden",
null,
ex.getMessage()
);
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
}

@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<Object> handleUnauthorized(UnauthorizedException ex) {
ApiResponse<Object> response = new ApiResponse<>(
401,
"Error: Unauthorized",
null,
ex.getMessage()
);
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
}

@ExceptionHandler(ConflictException.class)
public ResponseEntity<Object> handleConflict(ConflictException ex) {
ApiResponse<Object> response = new ApiResponse<>(
409,
"Error: Conflict",
null,
ex.getMessage()
);
return ResponseEntity.status(HttpStatus.CONFLICT).body(response);
}

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<Object> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
// Creamos una respuesta en formato JSON con el error
String error = String.format("El parametro enviado '%s' no es del tipo esperado.", ex.getName());
ApiResponse<Object> response = new ApiResponse<>(
400,
"Error de tipo de argumento",
null,
error
);
return ResponseEntity.badRequest().body(response);
}

// Manejo de cualquier otra excepción no controlada (500)
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleGlobalException(Exception ex) {
ApiResponse<Object> response = new ApiResponse<>(
500,
"Error: Internal Server Error",
null,
"Ocurrió un error inesperado."
);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.project.management.exception;

public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}
/*
* NotFoundException se usa para manejar errores de recursos no encontrados.
* Por ejemplo: Cuando el recurso solicitado no existe.
* */
Loading