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

308 lines
12 KiB
Java

package com.ieslamar.GestionInventario.controllers;
import com.ieslamar.GestionInventario.dto.BotonDTO;
import com.ieslamar.GestionInventario.dto.BotonManager;
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;
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.*;
@Controller
public class UserController {
@Autowired
private ApplicationContext context;
private final UserService userService;
private final DepartamentoService departamentoService;
private final CategoriaService categoriaService;
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
private final BotonManager botonManager;
public UserController(UserService userService, DepartamentoService departamentoService, CategoriaService categoriaService, BotonManager botonManager) {
this.userService = userService;
this.departamentoService = departamentoService;
this.categoriaService = categoriaService;
this.botonManager = botonManager;
}
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;
}
@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(
botonManager.getInventario(),
botonManager.getGestion()
)));
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(
botonManager.getGestionUsuarios(),
botonManager.getGestionProductos(),
botonManager.getGestionDepartamentos(),
botonManager.getGestionCategorias(),
botonManager.getGestionUbicaciones(),
botonManager.getGestionInventario(),
botonManager.getGestionCategorias(),
botonManager.getGestionTiposDatos(),
botonManager.getHome()
)));
model.addAttribute("buttons", botones);
return "management";
}
//USERS--------------------------------------------------------------------------------------------------------
@GetMapping("/userPage")
public String userPage(@RequestParam(required = false) Long id, Model model) {
model.addAttribute("departamentos", departamentoService.getAllDepartamentos());
if (id != null) {
User usuario = userService.getUserById(id);
if (usuario != null) {
model.addAttribute("user", usuario);
} else {
model.addAttribute("error", "Usuario no encontrado con ID: " + id);
}
} else {
model.addAttribute("user", new User());
}
return "userPage";
}
// 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
}
@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;
}
}
**/
}