Add BotonManager and BotonDTO for button management; update UserController and userPage.html for user registration handling

This commit is contained in:
jon ander 2025-05-08 20:04:14 +02:00
parent 8b14a236a2
commit 3d3549a39f
5 changed files with 146 additions and 68 deletions

View File

@ -1,6 +1,7 @@
package com.ieslamar.GestionInventario.controllers; package com.ieslamar.GestionInventario.controllers;
import com.ieslamar.GestionInventario.dto.BotonDTO; import com.ieslamar.GestionInventario.dto.BotonDTO;
import com.ieslamar.GestionInventario.dto.BotonManager;
import com.ieslamar.GestionInventario.entities.*; import com.ieslamar.GestionInventario.entities.*;
import com.ieslamar.GestionInventario.repos.GenericEntityService; import com.ieslamar.GestionInventario.repos.GenericEntityService;
import com.ieslamar.GestionInventario.services.CategoriaService; import com.ieslamar.GestionInventario.services.CategoriaService;
@ -31,27 +32,14 @@ public class UserController {
private final DepartamentoService departamentoService; private final DepartamentoService departamentoService;
private final CategoriaService categoriaService; private final CategoriaService categoriaService;
private static final Logger logger = LoggerFactory.getLogger(UserController.class); private static final Logger logger = LoggerFactory.getLogger(UserController.class);
private final BotonManager botonManager;
public UserController(UserService userService, DepartamentoService departamentoService, CategoriaService categoriaService) { public UserController(UserService userService, DepartamentoService departamentoService, CategoriaService categoriaService, BotonManager botonManager) {
this.userService = userService; this.userService = userService;
this.departamentoService = departamentoService; this.departamentoService = departamentoService;
this.categoriaService = categoriaService; this.categoriaService = categoriaService;
this.botonManager = botonManager;
} }
private final BotonDTO gestionUsuarios = new BotonDTO("Gestión de usuarios", "/user_list", true, null);
// private final BotonDTO gestionDepartamentosTest = new BotonDTO("Gestión de departamentos generica", "/list/" + Categoria.class.getSimpleName(), true, null);
private final BotonDTO gestionProductos = new BotonDTO("Gestión de Productos", "/user_management", true, null);
private final BotonDTO gestionDepartamentos = new BotonDTO("Gestión de Departamentos", "/departamento_list", true, null);
private final BotonDTO gestionCategorias = new BotonDTO("Gestión de Categorías", "/user_management", true, null);
private final BotonDTO gestionUbicaciones = new BotonDTO("Gestión de Ubicaciones", "/user_management", true, null);
private final BotonDTO gestionInventario = new BotonDTO("Gestión de Inventario", "/inventario", true, null);
private final BotonDTO gestionTiposDatos = new BotonDTO("Gestión de Tipos de dato", "/user_management", true, null);
private final BotonDTO inventario = new BotonDTO("Inventario", "/management", false, null);
private final BotonDTO gestion = new BotonDTO("Gestión", "/management", true, null);
private final BotonDTO home = new BotonDTO("Salir", "/home", false, "button_salir");
private List<BotonDTO> filtrarBotones(Authentication auth, List<BotonDTO> botones) { private List<BotonDTO> filtrarBotones(Authentication auth, List<BotonDTO> botones) {
List<BotonDTO> botones_response = new ArrayList<>(); List<BotonDTO> botones_response = new ArrayList<>();
List<String> roles = auth.getAuthorities() List<String> roles = auth.getAuthorities()
@ -78,8 +66,8 @@ public class UserController {
public String homePage(Model model) { public String homePage(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<BotonDTO> botones = filtrarBotones(auth, new ArrayList<>(List.of( List<BotonDTO> botones = filtrarBotones(auth, new ArrayList<>(List.of(
inventario, botonManager.getInventario(),
gestion botonManager.getGestion()
))); )));
model.addAttribute("buttons", botones); model.addAttribute("buttons", botones);
return "home"; return "home";
@ -89,16 +77,15 @@ public class UserController {
public String managementPage(Model model) { public String managementPage(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<BotonDTO> botones = filtrarBotones(auth, new ArrayList<>(List.of( List<BotonDTO> botones = filtrarBotones(auth, new ArrayList<>(List.of(
gestionUsuarios, botonManager.getGestionUsuarios(),
gestionProductos, botonManager.getGestionProductos(),
gestionDepartamentos, botonManager.getGestionDepartamentos(),
gestionCategorias, botonManager.getGestionCategorias(),
gestionUbicaciones, botonManager.getGestionUbicaciones(),
gestionInventario, botonManager.getGestionInventario(),
gestionCategorias, botonManager.getGestionCategorias(),
gestionTiposDatos, botonManager.getGestionTiposDatos(),
// gestionDepartamentosTest, botonManager.getHome()
home
))); )));
model.addAttribute("buttons", botones); model.addAttribute("buttons", botones);
return "management"; return "management";
@ -108,37 +95,53 @@ public class UserController {
//USERS-------------------------------------------------------------------------------------------------------- //USERS--------------------------------------------------------------------------------------------------------
@GetMapping("/userPage") @GetMapping("/userPage")
public String userPage(Model model) { public String userPage(@RequestParam(required = false) Long id, Model model) {
model.addAttribute("departamentos", departamentoService.getAllDepartamentos()); model.addAttribute("departamentos", departamentoService.getAllDepartamentos());
return "userPage"; // Retorna la vista register.html if (id != null) {
} User usuario = userService.getUserById(id);
@PostMapping("/userPage") if (usuario != null) {
public String userPage(@RequestParam(required = false) Long id, model.addAttribute("user", usuario);
@RequestParam String username, } else {
@RequestParam String password, model.addAttribute("error", "Usuario no encontrado con ID: " + id);
@RequestParam String role,
@RequestParam String mail,
@RequestParam(required = false) Integer iddepartamento) {
Departamento departamento = iddepartamento != null ? departamentoService.getDepartamentoById(iddepartamento) : null;
if (id != null) {
// Editar usuario existente
User user = userService.getUserById(id);
if (user != null) {
user.setNombre(username);
if (!password.isEmpty()) {
user.setPassword(password);
} }
user.setRole(Role.valueOf(role)); } else {
user.setMail(mail); model.addAttribute("user", new User());
user.setDepartamento(departamento);
userService.saveUser(user);
} }
} else { return "userPage";
// Crear nuevo usuario }
userService.registerUser(username, password, role, mail, departamento);
// POST: Registrar nuevo usuario
@PostMapping("/register")
public String registerUser(@RequestParam String username,
@RequestParam String password,
@RequestParam String role,
@RequestParam String mail,
@RequestParam(required = false) Integer iddepartamento,
@RequestParam(required = false) Long id) {
Departamento departamento = null;
if (iddepartamento != null) {
departamento = departamentoService.getDepartamentoById(iddepartamento);
}
Role userRole;
try {
userRole = Role.valueOf(role.toUpperCase());
} catch (IllegalArgumentException e) {
throw new RuntimeException("Rol no válido: " + role);
}
if (id != null) {
User Old = userService.getUserById(id);
Old.setNombre(username);
if(password != null)
Old.setPassword(password);
Old.setRole(Role.valueOf(role));
Old.setMail(mail);
Old.setDepartamento(departamento);
userService.saveUser(Old);
} else {
userService.registerUser(username, password, userRole.toString(), mail, departamento);
}
return "redirect:/user_list"; // redirige a lista o página deseada
} }
return "redirect:/user_list";
}
@PostMapping("/delete_user") @PostMapping("/delete_user")
public String deleteUser(@RequestParam("id") Long id) { public String deleteUser(@RequestParam("id") Long id) {
User user = userService.getUserById(id); User user = userService.getUserById(id);

View File

@ -2,6 +2,7 @@ package com.ieslamar.GestionInventario.dto;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.stereotype.Component;
public class BotonDTO { public class BotonDTO {
private String texto; private String texto;

View File

@ -0,0 +1,64 @@
package com.ieslamar.GestionInventario.dto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class BotonManager {
private final BotonDTO gestionUsuarios = new BotonDTO("Gestión de usuarios", "/user_list", true, null);
private final BotonDTO gestionProductos = new BotonDTO("Gestión de Productos", "/user_management", true, null);
private final BotonDTO gestionDepartamentos = new BotonDTO("Gestión de Departamentos", "/departamento_list", true, null);
private final BotonDTO gestionCategorias = new BotonDTO("Gestión de Categorías", "/user_management", true, null);
private final BotonDTO gestionUbicaciones = new BotonDTO("Gestión de Ubicaciones", "/user_management", true, null);
private final BotonDTO gestionInventario = new BotonDTO("Gestión de Inventario", "/inventario", true, null);
private final BotonDTO gestionTiposDatos = new BotonDTO("Gestión de Tipos de dato", "/user_management", true, null);
private final BotonDTO inventario = new BotonDTO("Inventario", "/management", false, null);
private final BotonDTO gestion = new BotonDTO("Gestión", "/management", true, null);
private final BotonDTO home = new BotonDTO("Salir", "/home", false, "button_salir");
public BotonManager() {
}
public BotonDTO getGestionUsuarios() {
return gestionUsuarios;
}
public BotonDTO getGestionProductos() {
return gestionProductos;
}
public BotonDTO getGestionDepartamentos() {
return gestionDepartamentos;
}
public BotonDTO getGestionCategorias() {
return gestionCategorias;
}
public BotonDTO getGestionUbicaciones() {
return gestionUbicaciones;
}
public BotonDTO getGestionInventario() {
return gestionInventario;
}
public BotonDTO getGestionTiposDatos() {
return gestionTiposDatos;
}
public BotonDTO getInventario() {
return inventario;
}
public BotonDTO getGestion() {
return gestion;
}
public BotonDTO getHome() {
return home;
}
}

View File

@ -35,7 +35,9 @@
<td th:each="value : ${item.values}" th:text="${value}"></td> <td th:each="value : ${item.values}" th:text="${value}"></td>
<td> <td>
<div class="celda-acciones"> <div class="celda-acciones">
<button th:if="${actionsUrl.edit}" th:href="${actionsUrl.edit} + '/' + ${item.id}" th:title="Editar">✏️</button> <a th:href="@{/userPage(id=${item.id})}">
<button type="button" th:title="Editar">✏️</button>
</a>
<form th:if="${actionsUrl.delete}" th:action="@{/delete_user}" method="post" style="display:inline;"> <form th:if="${actionsUrl.delete}" th:action="@{/delete_user}" method="post" style="display:inline;">
<input type="hidden" name="id" th:value="${item.id}" /> <input type="hidden" name="id" th:value="${item.id}" />
<button type="submit" th:title="Borrar" onclick="return confirm('¿Estás seguro de que deseas borrar este elemento?');"> <button type="submit" th:title="Borrar" onclick="return confirm('¿Estás seguro de que deseas borrar este elemento?');">

View File

@ -7,37 +7,39 @@
<body> <body>
<h2>Registro</h2> <h2>Registro</h2>
<div class="container1"> <div class="container1">
<form th:action="@{/userPage}" method="post"> <form th:action="@{/register}" th:object="${user}" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/> <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<div class="input-group"> <div class="input-group">
<label>Usuario:</label> <label>Usuario:</label>
<input type="text" name="username" th:value="${user != null ? user.nombre : ''}" required> <input type="text" th:field="*{nombre}" required>
</div>
<div class="input-group">
<label for="password">Contraseña:</label>
<input type="password" id="password" name="password" th:value="${user.password != null ? '' : user.password}" />
<small th:if="${user.password != null}">Dejar en blanco para mantener la contraseña actual</small>
</div> </div>
<div class="input-group"> <div class="input-group">
<label>Mail:</label> <label>Mail:</label>
<input type="text" name="mail" th:value="${user != null ? user.mail : ''}" required> <input type="text" th:field="*{mail}" required>
</div> </div>
<div class="input-group"> <div class="input-group">
<label>Rol:</label> <label>Rol:</label>
<select name="role"> <select th:field="*{role}">
<option value="USER" th:selected="${user != null and user.role.name() == 'USER'}">Usuario</option> <option value="USER">Usuario</option>
<option value="ADMIN" th:selected="${user != null and user.role.name() == 'ADMIN'}">Administrador</option> <option value="ADMIN">Administrador</option>
</select> </select>
</div> </div>
<div class="input-group"> <div class="input-group">
<label for="departamento">Departamento:</label> <label for="departamento">Departamento:</label>
<select id="departamento" name="iddepartamento"> <select th:field="*{departamento.id}">
<option value="">-- Sin departamento --</option> <option value="">-- Sin departamento --</option>
<option th:each="departamento : ${departamentos}" <option th:each="departamento : ${departamentos}"
th:value="${departamento.id}" th:value="${departamento.id}"
th:text="${departamento.nombre}" th:text="${departamento.nombre}">
th:selected="${user != null and user.departamento != null and user.departamento.id == departamento.id}">
</option> </option>
</select> </select>
</div> </div>
<button type="submit">Registrar</button> <button type="submit" th:text="${user.id != null ? 'Actualizar' : 'Registrar'}"></button>
</form> </form>
<a href="/Inventario/home"> <a href="/Inventario/home">
<button class="button_salir">Volver al inicio</button> <button class="button_salir">Volver al inicio</button>
@ -45,3 +47,9 @@
</div> </div>
</body> </body>
</html> </html>