Skip to content

Commit f4383e0

Browse files
committed
version 0.4
1 parent 008d043 commit f4383e0

File tree

10 files changed

+315
-4
lines changed

10 files changed

+315
-4
lines changed

pom.xml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@
2525
<groupId>org.springframework.boot</groupId>
2626
<artifactId>spring-boot-starter-web</artifactId>
2727
</dependency>
28-
28+
<dependency>
29+
<groupId>org.springframework.boot</groupId>
30+
<artifactId>spring-boot-starter-validation</artifactId>
31+
</dependency>
2932
<dependency>
3033
<groupId>org.springframework.boot</groupId>
3134
<artifactId>spring-boot-devtools</artifactId>

src/main/java/com/cibertec/shoesformen_api/a_empresa/EmpresaController.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,18 @@
66
import java.util.List;
77

88
@RestController
9+
@RequestMapping("/empresa")
910
public class EmpresaController {
1011

1112
@Autowired
1213
private EmpresaRepository empresaRepo;
1314

14-
@GetMapping("/empresa")
15+
@GetMapping
1516
public List<Empresa> all() {
1617
return empresaRepo.findAll();
1718
}
1819

19-
@PutMapping("/empresa/{id}") // ACTUALIZACION
20+
@PutMapping("/{id}") // ACTUALIZACION
2021
public Empresa replaceEmpresa(@RequestBody Empresa newEmpresa, @PathVariable String id){
2122

2223
return empresaRepo.findById(id) // actualizacion pero si no encuentra con el id lo crea

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import com.cibertec.shoesformen_api.repository.DistritoRepository;
55
import org.springframework.beans.factory.annotation.Autowired;
66
import org.springframework.web.bind.annotation.GetMapping;
7-
import org.springframework.web.bind.annotation.RequestMapping;
87
import org.springframework.web.bind.annotation.RestController;
98

109
import java.util.List;
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.cibertec.shoesformen_api.controller;
2+
3+
import com.cibertec.shoesformen_api.exception.EmpleadoNotFoundException;
4+
import com.cibertec.shoesformen_api.model.Empleado;
5+
import com.cibertec.shoesformen_api.model.dto.EmpleadoDTO;
6+
import com.cibertec.shoesformen_api.repository.DistritoRepository;
7+
import com.cibertec.shoesformen_api.repository.EmpleadoRepository;
8+
import com.cibertec.shoesformen_api.repository.EstadoRepository;
9+
import com.cibertec.shoesformen_api.service.EmpleadoService;
10+
import jakarta.validation.Valid;
11+
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.http.HttpStatus;
13+
import org.springframework.http.ResponseEntity;
14+
import org.springframework.stereotype.Controller;
15+
import org.springframework.web.bind.annotation.*;
16+
17+
import java.util.List;
18+
19+
@Controller
20+
@RequestMapping("/empleados")
21+
public class EmpleadoController {
22+
23+
/*
24+
* 200 -> OK
25+
* 204 -> OK pero sin contenido
26+
* */
27+
28+
@Autowired
29+
private EmpleadoService empleadoServ;
30+
@Autowired
31+
private EmpleadoRepository empleadoRepo;
32+
33+
@Autowired
34+
private DistritoRepository distritoRepo;
35+
@Autowired
36+
private EstadoRepository estadoRepo;
37+
38+
@GetMapping() // al entrar a la ruta principal "/empleados" se activa el metodo GET sin ruta especificada.
39+
public ResponseEntity<List<Empleado>> getAll() throws EmpleadoNotFoundException {
40+
return ResponseEntity.ok(empleadoServ.listar());
41+
}
42+
43+
44+
@PostMapping // post por defecto
45+
public ResponseEntity<Empleado> newEmpleado (@RequestBody @Valid EmpleadoDTO dto){ /** sda **/
46+
return new ResponseEntity<>(empleadoServ.guardar(dto), HttpStatus.CREATED);
47+
}
48+
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+
// }
68+
69+
70+
71+
72+
/* Configurar la respuesta HTTP
73+
* ResponseEntity: representa la respuesta completa HTTP: status code, headers y body.
74+
* @ResponseBody: por defecto en un @Controller devuelve un HTML, pero con esta anotacion permite devolver directamente el resultado del metodo como respuesta HTTP.
75+
* @ResponseStatus: permite personalizar el status de la respuesta en caso de ERROR
76+
* */
77+
78+
79+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.cibertec.shoesformen_api.exception;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.http.ResponseEntity;
5+
import org.springframework.web.bind.MethodArgumentNotValidException;
6+
import org.springframework.web.bind.annotation.ExceptionHandler;
7+
import org.springframework.web.bind.annotation.ResponseStatus;
8+
import org.springframework.web.bind.annotation.RestController;
9+
import org.springframework.web.bind.annotation.RestControllerAdvice;
10+
11+
import java.util.HashMap;
12+
import java.util.Map;
13+
import java.util.Objects;
14+
15+
@RestControllerAdvice
16+
public class ApplicationExceptionHandler {
17+
18+
//@ResponseStatus(HttpStatus.NO_CONTENT)
19+
@ExceptionHandler({EmpleadoNotFoundException.class})
20+
public ResponseEntity<Objects> handleBusinessException(EmpleadoNotFoundException ex) {
21+
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
22+
}
23+
24+
@ResponseStatus(HttpStatus.BAD_REQUEST)
25+
@ExceptionHandler(MethodArgumentNotValidException.class)
26+
public Map<String, String> handleInvalidArgument(MethodArgumentNotValidException ex) {
27+
Map<String, String> errorMap = new HashMap<>();
28+
ex.getBindingResult().getFieldErrors().forEach(error -> {
29+
errorMap.put(error.getField(), error.getDefaultMessage());
30+
});
31+
return errorMap;
32+
}
33+
34+
}
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 EmpleadoNotFoundException extends Exception{
4+
public EmpleadoNotFoundException(String message){
5+
super(message);
6+
}
7+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.cibertec.shoesformen_api.model.dto;
2+
3+
import jakarta.validation.constraints.Email;
4+
import jakarta.validation.constraints.NotBlank;
5+
import jakarta.validation.constraints.Pattern;
6+
import jakarta.validation.constraints.Size;
7+
import lombok.AllArgsConstructor;
8+
import lombok.Data;
9+
10+
import java.util.Collection;
11+
12+
@Data
13+
@AllArgsConstructor()
14+
public class EmpleadoDTO {
15+
16+
@NotBlank(message = "el COD_DISTRITO es obligatorio") // ** no NULL y no vacio
17+
private String codDistrito;
18+
@NotBlank(message = "el COD_ESTADO es obligatorio") // **
19+
private String codEstado;
20+
@NotBlank(message = "el NOMBRE es obligatorio") // **
21+
private String nombre;
22+
@NotBlank(message = "el APELLIDO es obligatorio") // **
23+
private String apellidos;
24+
@Pattern(regexp = "^\\d{8}$", message = "DNI invalido")
25+
private String dni;
26+
@Size(min=5, message = "la DIRECCION no debe tener un tamaño menor a 5")
27+
@Size(max=45, message = "la DIRECCION no debe tener un tamaño mayor a 45")
28+
private String direccion;
29+
@Pattern(regexp = "^\\d{7}$", message = "numero de TELEFONO invalido")
30+
private String telefono;
31+
@Email(message = "EMAIL invalido")
32+
private String email;
33+
@NotBlank(message = "el USUARIO es obligatorio") // **
34+
private String usuario;
35+
@NotBlank(message = "la CONTRASEÑA es obligatorio") // **
36+
private String contrasena;
37+
//private Collection<String> codRoles;
38+
39+
//
40+
// no encuentra el estado ni el distrito con le codigo enviado
41+
// datos, validador, codigo existentes, pero la BD detecta campos que deberia ser unico repetidos.
42+
43+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.cibertec.shoesformen_api.repository;
2+
3+
import com.cibertec.shoesformen_api.model.Empleado;
4+
import org.springframework.data.jpa.repository.JpaRepository;
5+
import org.springframework.data.jpa.repository.Query;
6+
import org.springframework.stereotype.Repository;
7+
8+
@Repository
9+
public interface EmpleadoRepository extends JpaRepository<Empleado, String> {
10+
11+
// CONSULTA NATIVA
12+
@Query(value="SELECT CONCAT('EM',CAST(SUBSTRING(MAX(e.cod_empleado),3) AS INT) + 1) FROM empleado AS e", nativeQuery = true)
13+
public abstract String getUltimoCodigo();
14+
15+
// Automatico
16+
public abstract Empleado findByUsuario(String usuario);
17+
18+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.cibertec.shoesformen_api.service;
2+
3+
import com.cibertec.shoesformen_api.exception.EmpleadoNotFoundException;
4+
import com.cibertec.shoesformen_api.model.Empleado;
5+
import com.cibertec.shoesformen_api.model.dto.EmpleadoDTO;
6+
import org.springframework.http.ResponseEntity;
7+
8+
import java.util.List;
9+
import java.util.Optional;
10+
11+
public interface EmpleadoService {
12+
13+
public List<Empleado> listar() throws EmpleadoNotFoundException;
14+
public void eliminar(Empleado empleado);
15+
public void eliminarByCodigo(String codigo);
16+
public Empleado guardar(EmpleadoDTO dto) throws IllegalArgumentException;
17+
public Optional<Empleado> getEmpleadoByCodigo(String codigo);
18+
public String getUltimoCodigo();
19+
20+
21+
}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package com.cibertec.shoesformen_api.service;
2+
3+
import com.cibertec.shoesformen_api.exception.EmpleadoNotFoundException;
4+
import com.cibertec.shoesformen_api.model.Distrito;
5+
import com.cibertec.shoesformen_api.model.Empleado;
6+
import com.cibertec.shoesformen_api.model.Estado;
7+
import com.cibertec.shoesformen_api.model.Rol;
8+
import com.cibertec.shoesformen_api.model.dto.EmpleadoDTO;
9+
import com.cibertec.shoesformen_api.repository.DistritoRepository;
10+
import com.cibertec.shoesformen_api.repository.EmpleadoRepository;
11+
import com.cibertec.shoesformen_api.repository.EstadoRepository;
12+
import com.cibertec.shoesformen_api.repository.RolRepository;
13+
import org.springframework.beans.factory.annotation.Autowired;
14+
import org.springframework.http.HttpStatus;
15+
import org.springframework.http.ResponseEntity;
16+
import org.springframework.stereotype.Service;
17+
18+
import java.util.ArrayList;
19+
import java.util.Arrays;
20+
import java.util.List;
21+
import java.util.Optional;
22+
23+
@Service
24+
public class EmpleadoServiceImpl implements EmpleadoService{
25+
26+
@Autowired
27+
private EmpleadoRepository empleadoRepo;
28+
@Autowired
29+
private DistritoRepository distritoRepo;
30+
@Autowired
31+
private EstadoRepository estadoRepo;
32+
@Autowired
33+
private RolRepository rolRepo;
34+
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+
44+
45+
@Override
46+
public List<Empleado> listar() throws EmpleadoNotFoundException {
47+
List<Empleado> lista = empleadoRepo.findAll();
48+
if(lista.isEmpty()){
49+
throw new EmpleadoNotFoundException("lista vacia");
50+
}
51+
return lista;
52+
}
53+
54+
@Override
55+
public void eliminar(Empleado empleado) {
56+
empleadoRepo.delete(empleado);
57+
}
58+
59+
@Override
60+
public void eliminarByCodigo(String codigo) {
61+
empleadoRepo.deleteById(codigo);
62+
}
63+
64+
@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);
88+
return empleadoRepo.save(empleado);
89+
}
90+
91+
@Override
92+
public Optional<Empleado> getEmpleadoByCodigo(String codigo) {
93+
return empleadoRepo.findById(codigo);
94+
}
95+
96+
@Override
97+
public String getUltimoCodigo() {
98+
String codigo_ultimo = empleadoRepo.getUltimoCodigo();
99+
String codigo_nuevo = "EM10001";
100+
if(codigo_ultimo != null){
101+
return codigo_ultimo;
102+
}
103+
return codigo_nuevo;
104+
}
105+
106+
}

0 commit comments

Comments
 (0)