Skip to content

Commit 4bcdb2b

Browse files
committed
version 0.5
1 parent f4383e0 commit 4bcdb2b

File tree

8 files changed

+133
-68
lines changed

8 files changed

+133
-68
lines changed

src/main/java/com/cibertec/shoesformen_api/controller/EmpleadoController.java

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.cibertec.shoesformen_api.controller;
22

33
import com.cibertec.shoesformen_api.exception.EmpleadoNotFoundException;
4+
import com.cibertec.shoesformen_api.exception.EntidadNotFoundException;
5+
import com.cibertec.shoesformen_api.exception.ListEmptyException;
46
import com.cibertec.shoesformen_api.model.Empleado;
57
import com.cibertec.shoesformen_api.model.dto.EmpleadoDTO;
68
import com.cibertec.shoesformen_api.repository.DistritoRepository;
@@ -12,6 +14,7 @@
1214
import org.springframework.http.HttpStatus;
1315
import org.springframework.http.ResponseEntity;
1416
import org.springframework.stereotype.Controller;
17+
import org.springframework.web.bind.MethodArgumentNotValidException;
1518
import org.springframework.web.bind.annotation.*;
1619

1720
import java.util.List;
@@ -35,36 +38,30 @@ public class EmpleadoController {
3538
@Autowired
3639
private EstadoRepository estadoRepo;
3740

41+
3842
@GetMapping() // al entrar a la ruta principal "/empleados" se activa el metodo GET sin ruta especificada.
39-
public ResponseEntity<List<Empleado>> getAll() throws EmpleadoNotFoundException {
43+
public ResponseEntity<List<Empleado>> getAll() throws ListEmptyException{
4044
return ResponseEntity.ok(empleadoServ.listar());
4145
}
4246

43-
4447
@PostMapping // post por defecto
45-
public ResponseEntity<Empleado> newEmpleado (@RequestBody @Valid EmpleadoDTO dto){ /** sda **/
46-
return new ResponseEntity<>(empleadoServ.guardar(dto), HttpStatus.CREATED);
48+
public ResponseEntity<Empleado> newEmpleado (@RequestBody @Valid EmpleadoDTO dto) throws IllegalArgumentException, EntidadNotFoundException {
49+
Empleado empleado = empleadoServ.buildEmpleado(dto); // -> construyo el empleado sin cod_empleado
50+
empleado.setCodEmpleado(empleadoServ.createNewCodigo()); // -> insertamos el codigo que debe tener
51+
return new ResponseEntity<>(empleadoServ.guardar(empleado), HttpStatus.CREATED); // -> insertamos el empleado
4752
}
4853

49-
// @PutMapping("/{id}") // ACTUALIZACION, su objetivo es actualizar no crear, por eso debe verificar si existe.
50-
// public ResponseEntity replaceEmpleado(@RequestBody Empleado newEmpleado, @PathVariable String id){ // imaginate que el id no coincida con el de empleado que envia. Ademas el empleado no deberia venir con ID, ¿porque?
51-
// return empleadoServ.getEmpleadoByCodigo(id)
52-
// .map(empleado ->{
53-
// empleado.setDistrito(newEmpleado.getDistrito());
54-
// empleado.setEstado(newEmpleado.getEstado());
55-
// empleado.setNombre(newEmpleado.getNombre());
56-
// empleado.setApellidos(newEmpleado.getApellidos());
57-
// empleado.setDni(newEmpleado.getDni());
58-
// empleado.setDireccion(newEmpleado.getDireccion());
59-
// empleado.setTelefono(newEmpleado.getTelefono());
60-
// empleado.setEmail(newEmpleado.getEmail());
61-
// empleado.setUsuario(newEmpleado.getUsuario());
62-
// empleado.setContrasena(newEmpleado.getContrasena());
63-
// return new ResponseEntity(empleadoServ.guardar(empleado), HttpStatus.OK);
64-
// }).orElseGet(() -> {
65-
// return new ResponseEntity("Empleado no encontrado", HttpStatus.NOT_FOUND);
66-
// });
67-
// }
54+
@PutMapping("/{id}") // ACTUALIZACION, su objetivo es actualizar no crear, por eso debe verificar si existe.
55+
public ResponseEntity replaceEmpleado(@RequestBody @Valid EmpleadoDTO dto, @PathVariable String id) throws IllegalArgumentException, EntidadNotFoundException{ // imaginate que el id no coincida con el de empleado que envia. Ademas el empleado no deberia venir con ID, ¿porque?
56+
57+
if(empleadoServ.getEmpleadoByCodigo(id).isPresent() ){
58+
Empleado empleado = empleadoServ.buildEmpleado(dto);
59+
empleado.setCodEmpleado(id);
60+
return new ResponseEntity(empleadoServ.guardar(empleado), HttpStatus.OK);
61+
} else {
62+
throw new EntidadNotFoundException("Empleado no encontrado");
63+
}
64+
}
6865

6966

7067

src/main/java/com/cibertec/shoesformen_api/exception/ApplicationExceptionHandler.java

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.cibertec.shoesformen_api.exception;
22

3+
import org.postgresql.util.PSQLException;
34
import org.springframework.http.HttpStatus;
45
import org.springframework.http.ResponseEntity;
56
import org.springframework.web.bind.MethodArgumentNotValidException;
@@ -8,19 +9,44 @@
89
import org.springframework.web.bind.annotation.RestController;
910
import org.springframework.web.bind.annotation.RestControllerAdvice;
1011

12+
import java.sql.SQLException;
1113
import java.util.HashMap;
1214
import java.util.Map;
1315
import java.util.Objects;
1416

1517
@RestControllerAdvice
1618
public class ApplicationExceptionHandler {
1719

18-
//@ResponseStatus(HttpStatus.NO_CONTENT)
1920
@ExceptionHandler({EmpleadoNotFoundException.class})
2021
public ResponseEntity<Objects> handleBusinessException(EmpleadoNotFoundException ex) {
2122
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
2223
}
2324

25+
// Cuando la lista que devuelve esta vacia.
26+
@ExceptionHandler({ListEmptyException.class})
27+
public ResponseEntity<Objects> handleListEmptyException(ListEmptyException ex) {
28+
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
29+
}
30+
31+
// Cuando el ID es NULL
32+
@ResponseStatus(HttpStatus.BAD_REQUEST)
33+
@ExceptionHandler({IllegalArgumentException.class})
34+
public Map<String, String> handleFoundException(IllegalArgumentException ex) {
35+
Map<String, String> errorMap = new HashMap<>();
36+
errorMap.put("errorMessage", ex.getMessage());
37+
return errorMap;
38+
}
39+
40+
// Cuando no encuentra la entidad con el ID proporcionado
41+
@ResponseStatus(HttpStatus.BAD_REQUEST)
42+
@ExceptionHandler({EntidadNotFoundException.class})
43+
public Map<String, String> handleEntityNotFoundException(EntidadNotFoundException ex) {
44+
Map<String, String> errorMap = new HashMap<>();
45+
errorMap.put("errorCodeMessage", ex.getMessage());
46+
return errorMap;
47+
}
48+
49+
// Cuando los campos no cumplen las restricciones
2450
@ResponseStatus(HttpStatus.BAD_REQUEST)
2551
@ExceptionHandler(MethodArgumentNotValidException.class)
2652
public Map<String, String> handleInvalidArgument(MethodArgumentNotValidException ex) {
@@ -31,4 +57,12 @@ public Map<String, String> handleInvalidArgument(MethodArgumentNotValidException
3157
return errorMap;
3258
}
3359

60+
@ResponseStatus(HttpStatus.BAD_REQUEST)
61+
@ExceptionHandler({SQLException.class})
62+
public Map<String, String> handlePSQLException(SQLException ex) {
63+
Map<String, String> errorMap = new HashMap<>();
64+
errorMap.put("errorSQLMessage", ex.getMessage());
65+
return errorMap;
66+
}
67+
3468
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.cibertec.shoesformen_api.exception;
2+
3+
public class EntidadNotFoundException extends Exception{
4+
public EntidadNotFoundException(String message){
5+
super(message);
6+
}
7+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.cibertec.shoesformen_api.exception;
2+
3+
public class ListEmptyException extends Exception{
4+
public ListEmptyException(String message){
5+
super(message);
6+
}
7+
}

src/main/java/com/cibertec/shoesformen_api/model/Empleado.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,21 @@ public class Empleado implements Serializable {
4444
)
4545
private Collection<Rol> roles; // este campo no esta realmente en la tabla
4646

47+
public Empleado(Distrito distrito, Estado estado, String nombre, String apellidos, String dni,
48+
String direccion, String telefono, String email, String usuario, String contrasena, Collection<Rol> roles) {
49+
super();
50+
this.codEmpleado = "";
51+
this.distrito = distrito;
52+
this.estado = estado;
53+
this.nombre = nombre;
54+
this.apellidos = apellidos;
55+
this.dni = dni;
56+
this.direccion = direccion;
57+
this.telefono = telefono;
58+
this.email = email;
59+
this.usuario = usuario;
60+
this.contrasena = contrasena;
61+
this.roles = roles;
62+
}
63+
4764
}

src/main/java/com/cibertec/shoesformen_api/model/dto/EmpleadoDTO.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
@AllArgsConstructor()
1414
public class EmpleadoDTO {
1515

16+
// los que no son @NotBlank pueden ser null o vacio.
1617
@NotBlank(message = "el COD_DISTRITO es obligatorio") // ** no NULL y no vacio
1718
private String codDistrito;
1819
@NotBlank(message = "el COD_ESTADO es obligatorio") // **
Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.cibertec.shoesformen_api.service;
22

33
import com.cibertec.shoesformen_api.exception.EmpleadoNotFoundException;
4+
import com.cibertec.shoesformen_api.exception.EntidadNotFoundException;
5+
import com.cibertec.shoesformen_api.exception.ListEmptyException;
46
import com.cibertec.shoesformen_api.model.Empleado;
57
import com.cibertec.shoesformen_api.model.dto.EmpleadoDTO;
68
import org.springframework.http.ResponseEntity;
@@ -10,12 +12,13 @@
1012

1113
public interface EmpleadoService {
1214

13-
public List<Empleado> listar() throws EmpleadoNotFoundException;
15+
public List<Empleado> listar() throws ListEmptyException;
1416
public void eliminar(Empleado empleado);
1517
public void eliminarByCodigo(String codigo);
16-
public Empleado guardar(EmpleadoDTO dto) throws IllegalArgumentException;
17-
public Optional<Empleado> getEmpleadoByCodigo(String codigo);
18-
public String getUltimoCodigo();
18+
public Empleado guardar(Empleado empleado) throws IllegalArgumentException, EntidadNotFoundException;
19+
public Optional<Empleado> getEmpleadoByCodigo(String codigo) throws EntidadNotFoundException;
20+
public String createNewCodigo();
21+
public Empleado buildEmpleado(EmpleadoDTO dto) throws EntidadNotFoundException;
1922

2023

2124
}
Lines changed: 39 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.cibertec.shoesformen_api.service;
22

3-
import com.cibertec.shoesformen_api.exception.EmpleadoNotFoundException;
3+
import com.cibertec.shoesformen_api.exception.EntidadNotFoundException;
4+
import com.cibertec.shoesformen_api.exception.ListEmptyException;
45
import com.cibertec.shoesformen_api.model.Distrito;
56
import com.cibertec.shoesformen_api.model.Empleado;
67
import com.cibertec.shoesformen_api.model.Estado;
@@ -11,11 +12,8 @@
1112
import com.cibertec.shoesformen_api.repository.EstadoRepository;
1213
import com.cibertec.shoesformen_api.repository.RolRepository;
1314
import org.springframework.beans.factory.annotation.Autowired;
14-
import org.springframework.http.HttpStatus;
15-
import org.springframework.http.ResponseEntity;
1615
import org.springframework.stereotype.Service;
1716

18-
import java.util.ArrayList;
1917
import java.util.Arrays;
2018
import java.util.List;
2119
import java.util.Optional;
@@ -32,21 +30,12 @@ public class EmpleadoServiceImpl implements EmpleadoService{
3230
@Autowired
3331
private RolRepository rolRepo;
3432

35-
//@Override
36-
//public ResponseEntity<Object> listar() {
37-
// List<Empleado> lista = empleadoRepo.findAll();
38-
// if(lista.isEmpty()){
39-
// return new ResponseEntity<>(HttpStatus.NOT_FOUND);
40-
// }
41-
// return new ResponseEntity<>(lista, HttpStatus.OK);
42-
//}
43-
4433

4534
@Override
46-
public List<Empleado> listar() throws EmpleadoNotFoundException {
35+
public List<Empleado> listar() throws ListEmptyException {
4736
List<Empleado> lista = empleadoRepo.findAll();
4837
if(lista.isEmpty()){
49-
throw new EmpleadoNotFoundException("lista vacia");
38+
throw new ListEmptyException("lista Empleado vacio");
5039
}
5140
return lista;
5241
}
@@ -62,39 +51,17 @@ public void eliminarByCodigo(String codigo) {
6251
}
6352

6453
@Override
65-
public Empleado guardar(EmpleadoDTO dto) throws IllegalArgumentException{
66-
67-
// findById cuando el id es null -> IllegalArgumentException [por defecto]
68-
// findById cuando no retorna nada porque no existe nada con ese ID. OPTIONAL -> XXException
69-
// SQL UNIQUE ->
70-
71-
Distrito dis = distritoRepo.findById(dto.getCodDistrito()).orElseThrow(() -> new SecurityException("Invalido id NULL"));
72-
Estado est = estadoRepo.findById(dto.getCodEstado()).orElseThrow(() -> new IllegalArgumentException("Invalido id NULL"));
73-
List<Rol> roles = Arrays.asList(rolRepo.findById("RL02").orElseThrow(() -> new IllegalArgumentException("")));
74-
75-
Empleado empleado = new Empleado(
76-
this.getUltimoCodigo(),
77-
dis,
78-
est,
79-
dto.getNombre(),
80-
dto.getApellidos(),
81-
dto.getDni(),
82-
dto.getDireccion(),
83-
dto.getTelefono(),
84-
dto.getEmail(),
85-
dto.getUsuario(),
86-
dto.getContrasena(),
87-
roles);
54+
public Empleado guardar(Empleado empleado) throws IllegalArgumentException, EntidadNotFoundException{
8855
return empleadoRepo.save(empleado);
8956
}
9057

9158
@Override
92-
public Optional<Empleado> getEmpleadoByCodigo(String codigo) {
59+
public Optional<Empleado> getEmpleadoByCodigo(String codigo) throws EntidadNotFoundException {
9360
return empleadoRepo.findById(codigo);
9461
}
9562

9663
@Override
97-
public String getUltimoCodigo() {
64+
public String createNewCodigo() {
9865
String codigo_ultimo = empleadoRepo.getUltimoCodigo();
9966
String codigo_nuevo = "EM10001";
10067
if(codigo_ultimo != null){
@@ -103,4 +70,36 @@ public String getUltimoCodigo() {
10370
return codigo_nuevo;
10471
}
10572

73+
@Override
74+
public Empleado buildEmpleado(EmpleadoDTO dto) throws IllegalArgumentException, EntidadNotFoundException {
75+
76+
// 1. que todos los datos sean validados -> @Valid
77+
// 1.5. que los ID no sean NULL -> IllegalArgumentException --> NO PASA
78+
// 2. que los codigos permitan encontrar ah las entidades -> EntidadNotFoundException
79+
// 3. que los campos en la BD no se repitan -> SQL
80+
// 4. que Xodo salga correcto -> Controller OK 201.
81+
82+
Optional<Distrito> dis = distritoRepo.findById(dto.getCodDistrito());
83+
Optional<Estado> est = estadoRepo.findById(dto.getCodEstado());
84+
Optional<Rol> rol = rolRepo.findById("RL02");
85+
if(dis.isEmpty() || est.isEmpty() || rol.isEmpty()){
86+
throw new EntidadNotFoundException("Codigos invalidos");
87+
}
88+
89+
Empleado empleado = new Empleado(
90+
//this.getUltimoCodigo(),
91+
dis.get(),
92+
est.get(),
93+
dto.getNombre(),
94+
dto.getApellidos(),
95+
dto.getDni(),
96+
dto.getDireccion(),
97+
dto.getTelefono(),
98+
dto.getEmail(),
99+
dto.getUsuario(),
100+
dto.getContrasena(),
101+
Arrays.asList(rol.get()));
102+
return empleado;
103+
}
104+
106105
}

0 commit comments

Comments
 (0)