Gestion-inventario/src/main/java/com/ieslamar/GestionInventario/controllers/UserController.java

305 lines
12 KiB
Java
Raw Normal View History

2025-03-24 18:55:09 +00:00
package com.ieslamar.GestionInventario.controllers;
import com.ieslamar.GestionInventario.dto.BotonDTO;
import com.ieslamar.GestionInventario.entities.*;
import com.ieslamar.GestionInventario.repos.GenericEntityService;
import com.ieslamar.GestionInventario.services.CategoriaService;
import com.ieslamar.GestionInventario.services.DepartamentoService;
import com.ieslamar.GestionInventario.services.UserService;
import jakarta.persistence.Entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
2025-03-24 18:55:09 +00:00
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.GrantedAuthority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
2025-03-24 18:55:09 +00:00
@Controller
public class UserController {
@Autowired
private ApplicationContext context;
2025-03-24 18:55:09 +00:00
private final UserService userService;
private final DepartamentoService departamentoService;
private final CategoriaService categoriaService;
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
2025-03-24 18:55:09 +00:00
public UserController(UserService userService, DepartamentoService departamentoService, CategoriaService categoriaService) {
2025-03-24 18:55:09 +00:00
this.userService = userService;
this.departamentoService = departamentoService;
this.categoriaService = categoriaService;
2025-03-24 18:55:09 +00:00
}
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) {
List<BotonDTO> botones_response = new ArrayList<>();
List<String> roles = auth.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.toList();
if (roles.contains("ROLE_ADMIN")) {
return botones;
}
for (BotonDTO botone : botones) {
if (!botone.isRequireAdmin()) {
botones_response.add(botone);
}
}
return botones_response;
}
2025-03-24 18:55:09 +00:00
@GetMapping("/login")
public String loginPage() {
return "login"; // Retorna la vista login.html
}
@GetMapping("/home")
public String homePage(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<BotonDTO> botones = filtrarBotones(auth, new ArrayList<>(List.of(
inventario,
gestion
)));
model.addAttribute("buttons", botones);
return "home";
}
@GetMapping("/management")
public String managementPage(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<BotonDTO> botones = filtrarBotones(auth, new ArrayList<>(List.of(
gestionUsuarios,
gestionProductos,
gestionDepartamentos,
gestionCategorias,
gestionUbicaciones,
gestionInventario,
gestionCategorias,
gestionTiposDatos,
// gestionDepartamentosTest,
home
)));
model.addAttribute("buttons", botones);
return "management";
}
2025-03-24 18:55:09 +00:00
//USERS--------------------------------------------------------------------------------------------------------
@GetMapping("/userPage")
public String userPage(Model model) {
model.addAttribute("departamentos", departamentoService.getAllDepartamentos());
return "userPage"; // Retorna la vista register.html
2025-03-24 18:55:09 +00:00
}
@PostMapping("/userPage")
public String userPage(@RequestParam(required = false) Long id,
@RequestParam String username,
@RequestParam String password,
@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));
user.setMail(mail);
user.setDepartamento(departamento);
userService.saveUser(user);
}
} else {
// Crear nuevo usuario
userService.registerUser(username, password, role, mail, departamento);
2025-03-24 18:55:09 +00:00
}
return "redirect:/user_list";
}
@PostMapping("/delete_user")
public String deleteUser(@RequestParam("id") Long id) {
User user = userService.getUserById(id);
userService.deleteUser(user); // Llama al servicio para eliminar el usuario
return "redirect:/user_list"; // Redirige a la página de gestión de usuarios
}
@GetMapping("/user_list")
public String userList(Model model) {
return buildUserList(model, userService.getAllUsers());
}
private String buildUserList(Model model, List<User> users) {
model.addAttribute("title", "Gestión de usuarios");
model.addAttribute("headers", List.of("ID", "Nombre", "Rol", "Email", "Departamento"));
model.addAttribute("items", users.stream()
.map(user -> Map.of(
"id", user.getId(),
"values", List.of(
user.getId(),
user.getNombre(),
user.getRole(),
user.getMail(),
user.getDepartamento() != null ? user.getDepartamento().getNombre() : " "
)
))
.toList());
model.addAttribute("actionsUrl", Map.of(
"edit", "/edit_user",
"delete", "/delete_user"
));
model.addAttribute("backUrl", "/Inventario/home");
model.addAttribute("addUrl", "/Inventario/userPage");
return "list";
}
@GetMapping("/edit_user/{id}")
public String editUser(@PathVariable Long id, Model model) {
User user = userService.getUserById(id);
if (user != null) {
model.addAttribute("user", user);
model.addAttribute("departamentos", departamentoService.getAllDepartamentos());
}
return "userPage"; // Redirige a la página de registro
}
//DEPARTAMENTOS--------------------------------------------------------------------------------------------------------
@GetMapping("/departamento_list")
public String genericPageDepartamento(Model model) {
model.addAttribute("title", "Gestión de Departamentos");
model.addAttribute("headers", List.of("ID", "Nombre"));
model.addAttribute(
"items",
departamentoService.getAllDepartamentos().stream().map(departamento -> Map.of("id", departamento.getId(),
"values", List.of(departamento.getId(), departamento.getNombre()))).toList()
);
model.addAttribute("actionsUrl", Map.of(
"edit", "",
"delete", ""
));
model.addAttribute("backUrl", "/Inventario/home");
model.addAttribute("addUrl", "/Inventario/");
return "list";
}
//CATEGORIAS--------------------------------------------------------------------------------------------------------
private String buildCategoriaList(Model model, List<Categoria> categorias) {
model.addAttribute("title", "Gestión de categorías");
model.addAttribute("headers", List.of("ID", "Nombre"));
model.addAttribute("items", categorias.stream()
.map(categoria -> Map.of(
"id", categoria.getId(),
"values", List.of(
categoria.getId(),
categoria.getNombre()
)
))
.toList());
model.addAttribute("actionsUrl", Map.of(
"edit", "",
"delete", "/delete_user"
));
model.addAttribute("backUrl", "/Inventario/home");
model.addAttribute("addUrl", "/Inventario/userPage");
return "list";
}
//GENERICO--------------------------------------------------------------------------------------------------------
/**
@GetMapping("/list/{tabla}")
public String tablaList(Model model, @PathVariable String entity) {
String serviceName = entity.toLowerCase() + "Service";
Object serviceBean = context.getBean(serviceName);
return "";
}
@GetMapping("/list/{entity}")
public String entityList(Model model, @PathVariable String entity) {
//construye el nombre del servicio de la entidad
String serviceName = entity.toLowerCase() + "Service";
try {
//busca el servicio de la entidad
Object serviceBean = context.getBean(serviceName);
//si el Bean es una instancia de GenericEntityService
if (serviceBean instanceof GenericEntityService<?> genericService) {
//genericService es un Servicio de los que hay, eso trae todas las instancias, entities sería por ejemplo user,categoria,etc
List<?> entities = genericService.findAll();
List<Map<String, Object>> items = entities.stream().map(e ->
Map.of(
"id", getId(e),
"values", genericService.getRowValues(e)
)
).toList();
model.addAttribute("title", "Gestión de " + entity);
model.addAttribute("headers", genericService.getHeaders());
model.addAttribute("items", items);
model.addAttribute("actionsUrl", Map.of(
"edit", "",
"delete", "" // puedes personalizar por entidad
));
model.addAttribute("backUrl", "/Inventario/home");
model.addAttribute("addUrl", "/Inventario/");
return "list";
} else {
throw new IllegalArgumentException("No es un GenericEntityService válido");
}
} catch (Exception e) {
model.addAttribute("error", "No se pudo cargar la entidad: " + entity);
return "error";
}
}
private Object getId(Object entity) {
try {
Method method = entity.getClass().getMethod("getId");
return method.invoke(entity);
} catch (Exception e) {
return null;
}
}
**/
2025-03-24 18:55:09 +00:00
}