Acabando ocultadno iconos para que el usuario normal, no administrador solo puede editar sus skills, una cosa adicional que queda hacer es para asegurar es editar los metdos de cotroladores para que no era posible acceder otras funcciones de ninguna manera.

master
vicsash 6 months ago
parent c1ab8f5a41
commit 624094c58a

@ -1,5 +1,4 @@
package com.example.proyectofinal; package com.example.proyectofinal;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -9,5 +8,4 @@ public class ProyectoFinalApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(ProyectoFinalApplication.class, args); SpringApplication.run(ProyectoFinalApplication.class, args);
} }
} }

@ -1,4 +1,5 @@
package com.example.proyectofinal.component; package com.example.proyectofinal.component;
import com.example.proyectofinal.models.login.Usuario; import com.example.proyectofinal.models.login.Usuario;
import com.example.proyectofinal.servicios.user.UsuarioService; import com.example.proyectofinal.servicios.user.UsuarioService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -7,12 +8,17 @@ import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
@Component @Component
public class CustomAuth implements AuthenticationProvider{ public class CustomAuth implements AuthenticationProvider {
@Autowired @Autowired
private UsuarioService usuarioService; private UsuarioService usuarioService;
@ -20,11 +26,13 @@ public class CustomAuth implements AuthenticationProvider{
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String nombreLogIn = authentication.getName(); String nombreLogIn = authentication.getName();
String password = authentication.getCredentials().toString(); String password = authentication.getCredentials().toString();
Usuario usuario = usuarioService.login(nombreLogIn, password); Usuario usuario = usuarioService.login(nombreLogIn, password);
if (usuario != null) { if (usuario != null) {
return new UsernamePasswordAuthenticationToken(nombreLogIn, password, new ArrayList<>()); List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(usuario.getRol().getNombre()));
User userDetails = new User(nombreLogIn, password, authorities);
return new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
} else { } else {
throw new BadCredentialsException("External system authentication failed"); throw new BadCredentialsException("External system authentication failed");
} }
@ -34,4 +42,4 @@ public class CustomAuth implements AuthenticationProvider{
public boolean supports(Class<?> authentication) { public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class); return authentication.equals(UsernamePasswordAuthenticationToken.class);
} }
} }

@ -12,7 +12,7 @@ import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
@Configuration @Configuration
public class SecurityConfig { public class SecurityConfig{
@Autowired @Autowired
private JdbcTemplate jdbcTemplate; private JdbcTemplate jdbcTemplate;
@ -28,15 +28,17 @@ public class SecurityConfig {
} }
@Bean @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
initializeAutoridadAndRolTables();
http http
.sessionManagement(sessionManagement -> sessionManagement .sessionManagement(sessionManagement -> sessionManagement
.invalidSessionUrl("/logout") // Redirect to /logout when session is invalid .invalidSessionUrl("/login") // Redirect to /logout when session is invalid
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.sessionFixation().migrateSession() .sessionFixation().migrateSession()
.maximumSessions(1).expiredUrl("/logout")) // Redirect to /logout when session expires .maximumSessions(1).expiredUrl("/logout")) // Redirect to /logout when session expires
.authorizeRequests(authorize -> authorize .authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated() .anyRequest().authenticated()
) )
.formLogin(formLogin -> formLogin .formLogin(formLogin -> formLogin
.successHandler(customAuthenticacionHandler()) .successHandler(customAuthenticacionHandler())
) )

@ -3,11 +3,15 @@ package com.example.proyectofinal.controllers;
import com.example.proyectofinal.models.empresas.*; import com.example.proyectofinal.models.empresas.*;
import com.example.proyectofinal.repositories.empresas.*; import com.example.proyectofinal.repositories.empresas.*;
import com.example.proyectofinal.servicios.*;
import com.example.proyectofinal.interfaces.IPagination; import com.example.proyectofinal.interfaces.IPagination;
import org.springframework.context.annotation.Role; import com.example.proyectofinal.servicios.empresa.*;
import com.example.proyectofinal.servicios.user.UsuarioService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@ -23,8 +27,6 @@ import java.util.*;
@RequestMapping("/buscador") @RequestMapping("/buscador")
public class BuscadorController { public class BuscadorController {
@Autowired
private EmpressaRepository empressaRepository;
@Autowired @Autowired
private AlumnoService alumnoService; private AlumnoService alumnoService;
@Autowired @Autowired
@ -47,12 +49,15 @@ public class BuscadorController {
private OfertaRepository ofertaRepository; private OfertaRepository ofertaRepository;
@Autowired @Autowired
private EmpresaService empresaService; private EmpresaService empresaService;
@Autowired
private UsuarioService usuarioService;
@GetMapping @GetMapping
public String buscador(){ public String buscador(){
return "buscador_admin"; return "buscador_admin";
} }
@GetMapping("/empresas/page/{pageNum}") @GetMapping("/empresas/page/{pageNum}")
public String searchEmpresasList(@PathVariable int pageNum, public String searchEmpresasList(@PathVariable int pageNum,
@RequestParam(defaultValue = "") String query, @RequestParam(defaultValue = "") String query,
@ -82,6 +87,7 @@ public class BuscadorController {
model.addAttribute("empresas", empresas); model.addAttribute("empresas", empresas);
model.addAttribute("query", query); model.addAttribute("query", query);
model.addAttribute("secondaryOption", secondaryOption); model.addAttribute("secondaryOption", secondaryOption);
model.addAttribute("isAdmin", usuarioService.isAdmin());
} }
return "/list/empresas"; return "/list/empresas";
} }
@ -102,9 +108,11 @@ public class BuscadorController {
model.addAttribute(entry.getKey(), entry.getValue()); model.addAttribute(entry.getKey(), entry.getValue());
} }
model.addAttribute("secondaryOption",secondaryOption); model.addAttribute("secondaryOption",secondaryOption);
model.addAttribute("isAdmin", usuarioService.isAdmin());
return "/list/sectores"; return "/list/sectores";
} }
@GetMapping("/contactos/page/{pageNum}") @GetMapping("/contactos/page/{pageNum}")
public String searchContactosList(@PathVariable int pageNum, public String searchContactosList(@PathVariable int pageNum,
@RequestParam(defaultValue = "") String query, @RequestParam(defaultValue = "") String query,
@ -134,10 +142,12 @@ public class BuscadorController {
model.addAttribute("contactos", contactos); model.addAttribute("contactos", contactos);
model.addAttribute("query", query); model.addAttribute("query", query);
model.addAttribute("secondaryOption", secondaryOption); model.addAttribute("secondaryOption", secondaryOption);
model.addAttribute("isAdmin", usuarioService.isAdmin());
} }
return "/list/contactos"; return "/list/contactos";
} }
@GetMapping("/sucursales/page/{pageNum}") @GetMapping("/sucursales/page/{pageNum}")
public String searchSucursalesList(@PathVariable int pageNum, public String searchSucursalesList(@PathVariable int pageNum,
@RequestParam(defaultValue = "") String query, @RequestParam(defaultValue = "") String query,
@ -168,10 +178,12 @@ public class BuscadorController {
model.addAttribute("sucursales", sucursales); model.addAttribute("sucursales", sucursales);
model.addAttribute("query", query); model.addAttribute("query", query);
model.addAttribute("secondaryOption", secondaryOption); model.addAttribute("secondaryOption", secondaryOption);
model.addAttribute("isAdmin", usuarioService.isAdmin());
} }
return "/list/sucursales"; return "/list/sucursales";
} }
@GetMapping("/ofertas/page/{pageNum}") @GetMapping("/ofertas/page/{pageNum}")
public String searchOfertasList(@PathVariable int pageNum, public String searchOfertasList(@PathVariable int pageNum,
@RequestParam(defaultValue = "") String query, @RequestParam(defaultValue = "") String query,
@ -203,10 +215,12 @@ public class BuscadorController {
model.addAttribute("ofertas", ofertas); model.addAttribute("ofertas", ofertas);
model.addAttribute("query", query); model.addAttribute("query", query);
model.addAttribute("secondaryOption", secondaryOption); model.addAttribute("secondaryOption", secondaryOption);
model.addAttribute("isAdmin", usuarioService.isAdmin());
} }
return "/list/ofertas"; return "/list/ofertas";
} }
@GetMapping("/familias/page/{pageNum}") @GetMapping("/familias/page/{pageNum}")
public String searchFamiliasList(@PathVariable int pageNum, public String searchFamiliasList(@PathVariable int pageNum,
@RequestParam(defaultValue = "") String query, @RequestParam(defaultValue = "") String query,
@ -218,18 +232,18 @@ public class BuscadorController {
String[] word = query.split("\\b(y|o)\\b|[,/]"); String[] word = query.split("\\b(y|o)\\b|[,/]");
List<Integer> itemsPage = Arrays.asList(5, 10, 15, 20, 25, 50); List<Integer> itemsPage = Arrays.asList(5, 10, 15, 20, 25, 50);
Map<String, Object> attributes = new HashMap<>(); Map<String, Object> attributes = new HashMap<>();
if (secondaryOption.equalsIgnoreCase("Todo")) { if (secondaryOption.equalsIgnoreCase("Todo")){
sortField = "nombre";
sortDir = "asc";
attributes = getPaginatedAttributes(pageNum, query, size, sortField, sortDir, familiaService, itemsPage); attributes = getPaginatedAttributes(pageNum, query, size, sortField, sortDir, familiaService, itemsPage);
} }
for (Map.Entry<String, Object> entry : attributes.entrySet()) { for (Map.Entry<String, Object> entry : attributes.entrySet()) {
model.addAttribute(entry.getKey(), entry.getValue()); model.addAttribute(entry.getKey(), entry.getValue());
} }
model.addAttribute("secondaryOption",secondaryOption); model.addAttribute("secondaryOption",secondaryOption);
model.addAttribute("isAdmin", usuarioService.isAdmin());
return "/list/familias"; return "/list/familias";
} }
@GetMapping("/ciclos/page/{pageNum}") @GetMapping("/ciclos/page/{pageNum}")
public String searchCiclosList(@PathVariable int pageNum, public String searchCiclosList(@PathVariable int pageNum,
@RequestParam(defaultValue = "") String query, @RequestParam(defaultValue = "") String query,
@ -261,10 +275,12 @@ public class BuscadorController {
model.addAttribute("ciclos", ciclos); model.addAttribute("ciclos", ciclos);
model.addAttribute("query", query); model.addAttribute("query", query);
model.addAttribute("secondaryOption", secondaryOption); model.addAttribute("secondaryOption", secondaryOption);
model.addAttribute("isAdmin", usuarioService.isAdmin());
} }
return "/list/ciclos"; return "/list/ciclos";
} }
@GetMapping("/alumnos/page/{pageNum}") @GetMapping("/alumnos/page/{pageNum}")
public String searchAlumnosList(@PathVariable int pageNum, public String searchAlumnosList(@PathVariable int pageNum,
@RequestParam(defaultValue = "") String query, @RequestParam(defaultValue = "") String query,
@ -298,6 +314,7 @@ public class BuscadorController {
model.addAttribute("alumnos", alumnos); model.addAttribute("alumnos", alumnos);
model.addAttribute("query", query); model.addAttribute("query", query);
model.addAttribute("secondaryOption", secondaryOption); model.addAttribute("secondaryOption", secondaryOption);
model.addAttribute("isAdmin", usuarioService.isAdmin());
} }
return "/list/alumnos"; return "/list/alumnos";
@ -315,8 +332,6 @@ public class BuscadorController {
List<Integer> itemsPage = Arrays.asList(5, 10, 15, 20, 25, 50); List<Integer> itemsPage = Arrays.asList(5, 10, 15, 20, 25, 50);
Map<String, Object> attributes = new HashMap<>(); Map<String, Object> attributes = new HashMap<>();
if (secondaryOption.equalsIgnoreCase("Todo")) { if (secondaryOption.equalsIgnoreCase("Todo")) {
sortField = "nombre";
sortDir = "asc";
attributes = getPaginatedAttributes(pageNum, query, size, sortField, sortDir, skillService, itemsPage); attributes = getPaginatedAttributes(pageNum, query, size, sortField, sortDir, skillService, itemsPage);
} }
@ -324,6 +339,7 @@ public class BuscadorController {
model.addAttribute(entry.getKey(), entry.getValue()); model.addAttribute(entry.getKey(), entry.getValue());
} }
model.addAttribute("secondaryOption",secondaryOption); model.addAttribute("secondaryOption",secondaryOption);
model.addAttribute("isAdmin", usuarioService.isAdmin());
return "/list/skills"; return "/list/skills";
} }
public <T> Map<String, Object> getPaginatedAttributes(int pageNum, String query, int size, String sortField, String sortDir, IPagination<T> service, List<Integer> itemsPage) { public <T> Map<String, Object> getPaginatedAttributes(int pageNum, String query, int size, String sortField, String sortDir, IPagination<T> service, List<Integer> itemsPage) {
@ -361,6 +377,7 @@ public class BuscadorController {
* @param querySearchBar the text in searchbar from the lsit a String * @param querySearchBar the text in searchbar from the lsit a String
* @return a list of entities that match the query * @return a list of entities that match the query
*/ */
@GetMapping("/empresas/search") @GetMapping("/empresas/search")
public ResponseEntity<List<Empresa>> searchEmpresas(@RequestParam String querySearchBar, @RequestParam String query, @RequestParam String secondaryOption) { public ResponseEntity<List<Empresa>> searchEmpresas(@RequestParam String querySearchBar, @RequestParam String query, @RequestParam String secondaryOption) {
if(secondaryOption.equalsIgnoreCase("Todo")){ if(secondaryOption.equalsIgnoreCase("Todo")){
@ -373,6 +390,7 @@ public class BuscadorController {
} }
@GetMapping("/sectores/search") @GetMapping("/sectores/search")
public ResponseEntity<List<Sector>> searchSectores(@RequestParam String query) { public ResponseEntity<List<Sector>> searchSectores(@RequestParam String query) {
List<Sector> sectors = sectorService.search(query); List<Sector> sectors = sectorService.search(query);
@ -391,6 +409,7 @@ public class BuscadorController {
} }
} }
@GetMapping("/sucursales/search") @GetMapping("/sucursales/search")
public ResponseEntity<List<Sucursal>> searchSucursales(@RequestParam String querySearchBar, @RequestParam String query, @RequestParam String secondaryOption) { public ResponseEntity<List<Sucursal>> searchSucursales(@RequestParam String querySearchBar, @RequestParam String query, @RequestParam String secondaryOption) {
if(secondaryOption.equalsIgnoreCase("Todo")){ if(secondaryOption.equalsIgnoreCase("Todo")){
@ -402,12 +421,14 @@ public class BuscadorController {
} }
} }
@GetMapping("/familias/search") @GetMapping("/familias/search")
public ResponseEntity<List<Familia>> searchFamilias(@RequestParam String query) { public ResponseEntity<List<Familia>> searchFamilias(@RequestParam String query) {
List<Familia> familias = familiaService.search(query); List<Familia> familias = familiaService.search(query);
return ResponseEntity.ok(familias); return ResponseEntity.ok(familias);
} }
@GetMapping("/ciclos/search") @GetMapping("/ciclos/search")
public ResponseEntity<List<Ciclo>> searchCiclos(@RequestParam String querySearchBar, @RequestParam String query, @RequestParam String secondaryOption) { public ResponseEntity<List<Ciclo>> searchCiclos(@RequestParam String querySearchBar, @RequestParam String query, @RequestParam String secondaryOption) {
if(secondaryOption.equalsIgnoreCase("Todo")){ if(secondaryOption.equalsIgnoreCase("Todo")){
@ -419,12 +440,14 @@ public class BuscadorController {
} }
} }
@GetMapping("/skills/search") @GetMapping("/skills/search")
public ResponseEntity<List<Skill>> searchSkills(@RequestParam String query) { public ResponseEntity<List<Skill>> searchSkills(@RequestParam String query) {
List<Skill> ciclos = skillService.search(query); List<Skill> ciclos = skillService.search(query);
return ResponseEntity.ok(ciclos); return ResponseEntity.ok(ciclos);
} }
@GetMapping("/alumnos/search") @GetMapping("/alumnos/search")
public ResponseEntity<List<Alumno>> searchAlumnos(@RequestParam String querySearchBar, @RequestParam String query, @RequestParam String secondaryOption) { public ResponseEntity<List<Alumno>> searchAlumnos(@RequestParam String querySearchBar, @RequestParam String query, @RequestParam String secondaryOption) {
List<Alumno> alumnos; List<Alumno> alumnos;
@ -470,5 +493,4 @@ public class BuscadorController {
} }
return ResponseEntity.ok(ofertas); return ResponseEntity.ok(ofertas);
} }
} }

@ -1,6 +1,7 @@
package com.example.proyectofinal.controllers; package com.example.proyectofinal.controllers;
import com.example.proyectofinal.servicios.user.UsuarioService; import com.example.proyectofinal.servicios.user.UsuarioService;
import jakarta.annotation.security.RolesAllowed;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -18,6 +19,8 @@ public class LogOutController {
private UsuarioService usuarioService; private UsuarioService usuarioService;
private static final Logger logger = LoggerFactory.getLogger(LogOutController.class); private static final Logger logger = LoggerFactory.getLogger(LogOutController.class);
@RolesAllowed({"ADMIN","USER"})
@RequestMapping("/logout") @RequestMapping("/logout")
public String logout(HttpServletRequest request) { public String logout(HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication();

@ -1,9 +1,12 @@
package com.example.proyectofinal.controllers.modelControllers; package com.example.proyectofinal.controllers.modelControllers;
import com.example.proyectofinal.models.empresas.*; import com.example.proyectofinal.models.empresas.*;
import com.example.proyectofinal.servicios.AlumnoService; import com.example.proyectofinal.models.login.Usuario;
import com.example.proyectofinal.servicios.CicloService; import com.example.proyectofinal.servicios.empresa.AlumnoService;
import com.example.proyectofinal.servicios.SkillService; import com.example.proyectofinal.servicios.empresa.CicloService;
import com.example.proyectofinal.servicios.empresa.SkillService;
import com.example.proyectofinal.servicios.user.UsuarioService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -12,6 +15,7 @@ import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
@Controller @Controller
@ -26,6 +30,10 @@ public class AlumnoController {
@Autowired @Autowired
private CicloService cicloService; private CicloService cicloService;
@Autowired
UsuarioService usuarioService;
@GetMapping("/admin/alumno/create") @GetMapping("/admin/alumno/create")
public String showCreateForm(Model model) { public String showCreateForm(Model model) {
Alumno alumno = new Alumno(); Alumno alumno = new Alumno();
@ -37,6 +45,7 @@ public class AlumnoController {
return "admin/alumno/create"; return "admin/alumno/create";
} }
@PostMapping("/alumno/save") @PostMapping("/alumno/save")
public ResponseEntity<String> saveAlumno(Alumno alumno, @RequestParam("ciclo") Long ciclo, @RequestParam("skills") List<Long> skills){ public ResponseEntity<String> saveAlumno(Alumno alumno, @RequestParam("ciclo") Long ciclo, @RequestParam("skills") List<Long> skills){
try{ try{
@ -48,6 +57,26 @@ public class AlumnoController {
if(testIfExist != null){ if(testIfExist != null){
return new ResponseEntity<>("El alumno ya existe", HttpStatus.BAD_REQUEST); return new ResponseEntity<>("El alumno ya existe", HttpStatus.BAD_REQUEST);
} }
String password = "1234";
StringBuilder nombreUsuarioBuilder = new StringBuilder();
nombreUsuarioBuilder.append(alumno.getNombre().toLowerCase());
nombreUsuarioBuilder.append(" ");
nombreUsuarioBuilder.append(alumno.getApellido().toLowerCase());
if (alumno.getApellido2() != null) {
if (!nombreUsuarioBuilder.isEmpty()) {
nombreUsuarioBuilder.append(" ");
}
nombreUsuarioBuilder.append(alumno.getApellido2().toLowerCase());
}
String nombreUsuario = nombreUsuarioBuilder.toString();
String nia = alumno.getNia();
String firstThreeLetters = nia.substring(0, 3);
String nombreLogIn="alu." +alumno.getNombre()+firstThreeLetters;
String email = Optional.of(alumno.getCorreo()).orElse(alumno.getCorreo2());
boolean isLogged = false;
Long newUser = usuarioService.findRolByName("USER");
usuarioService.createUsuario(nombreUsuario, nombreLogIn, email, password, isLogged, newUser);
alumnoService.save(alumno); alumnoService.save(alumno);
return new ResponseEntity<>("El alumno fue guardado con exito", HttpStatus.OK); return new ResponseEntity<>("El alumno fue guardado con exito", HttpStatus.OK);
}catch (Exception e) { }catch (Exception e) {
@ -55,6 +84,7 @@ public class AlumnoController {
} }
} }
@GetMapping("/admin/alumno/update/{id}") @GetMapping("/admin/alumno/update/{id}")
public String showUpdateForm(Model model, @PathVariable Long id) { public String showUpdateForm(Model model, @PathVariable Long id) {
Alumno alumno = alumnoService.findById(id); Alumno alumno = alumnoService.findById(id);
@ -66,6 +96,7 @@ public class AlumnoController {
return "admin/alumno/update"; return "admin/alumno/update";
} }
@PostMapping("/alumno/update") @PostMapping("/alumno/update")
public ResponseEntity<String> updateAlumno(Alumno alumno, @RequestParam("ciclo") Long ciclo, @RequestParam("skills") List<Long> skills){ public ResponseEntity<String> updateAlumno(Alumno alumno, @RequestParam("ciclo") Long ciclo, @RequestParam("skills") List<Long> skills){
try{ try{
@ -83,6 +114,12 @@ public class AlumnoController {
@GetMapping("/alumno/delete/{id}") @GetMapping("/alumno/delete/{id}")
public ResponseEntity<String> deleteAlumno(@PathVariable Long id){ public ResponseEntity<String> deleteAlumno(@PathVariable Long id){
try{ try{
Alumno alumno = alumnoService.findById(id);
String logIn = "alu." + alumno.getNombre() + alumno.getNia().substring(0, 3);
Usuario usuario = usuarioService.findByLogInName(logIn);
if(usuario != null){
usuarioService.deleteById(usuario.getId());
}
alumnoService.deleteById(id); alumnoService.deleteById(id);
return new ResponseEntity<>("El alumno ha sido eliminado", HttpStatus.OK); return new ResponseEntity<>("El alumno ha sido eliminado", HttpStatus.OK);
}catch (Exception e){ }catch (Exception e){

@ -2,8 +2,9 @@ package com.example.proyectofinal.controllers.modelControllers;
import com.example.proyectofinal.models.empresas.Ciclo; import com.example.proyectofinal.models.empresas.Ciclo;
import com.example.proyectofinal.models.empresas.Familia; import com.example.proyectofinal.models.empresas.Familia;
import com.example.proyectofinal.servicios.CicloService; import com.example.proyectofinal.servicios.empresa.CicloService;
import com.example.proyectofinal.servicios.FamiliaService; import com.example.proyectofinal.servicios.empresa.FamiliaService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -23,10 +24,11 @@ public class CicloController {
@Autowired @Autowired
private FamiliaService familiaService; private FamiliaService familiaService;
@GetMapping("/admin/ciclo/create") @GetMapping("/admin/ciclo/create")
public String showCreateForm(Model model) { public String showCreateForm(Model model) {
Ciclo ciclo = new Ciclo(); Ciclo ciclo = new Ciclo();
List<Familia> familias = familiaService.findAll(); List<Familia> familias = familiaService.findAllFamilias();
Familia familia = new Familia(); Familia familia = new Familia();
model.addAttribute("ciclo", ciclo); model.addAttribute("ciclo", ciclo);
model.addAttribute("familias", familias); model.addAttribute("familias", familias);
@ -52,10 +54,11 @@ public class CicloController {
} }
} }
@GetMapping("/admin/ciclo/update/{id}") @GetMapping("/admin/ciclo/update/{id}")
public String showUpdateForm(Model model, @PathVariable Long id) { public String showUpdateForm(Model model, @PathVariable Long id) {
Ciclo ciclo = cicloService.findById(id); Ciclo ciclo = cicloService.findById(id);
List<Familia> familias = familiaService.findAll(); List<Familia> familias = familiaService.findAllFamilias();
Familia familia = new Familia(); Familia familia = new Familia();
model.addAttribute("ciclo", ciclo); model.addAttribute("ciclo", ciclo);
model.addAttribute("familias", familias); model.addAttribute("familias", familias);
@ -63,6 +66,7 @@ public class CicloController {
return "admin/ciclo/update"; return "admin/ciclo/update";
} }
@PostMapping("/ciclo/update") @PostMapping("/ciclo/update")
public ResponseEntity<String> updateCiclo(Ciclo ciclo, @RequestParam("familia.id") Long familiaId){ public ResponseEntity<String> updateCiclo(Ciclo ciclo, @RequestParam("familia.id") Long familiaId){
try{ try{
@ -75,6 +79,7 @@ public class CicloController {
} }
} }
@GetMapping("/ciclo/delete/{id}") @GetMapping("/ciclo/delete/{id}")
public ResponseEntity<String> deleteCiclo(@PathVariable Long id){ public ResponseEntity<String> deleteCiclo(@PathVariable Long id){
try{ try{

@ -2,8 +2,9 @@ package com.example.proyectofinal.controllers.modelControllers;
import com.example.proyectofinal.models.empresas.Contacto; import com.example.proyectofinal.models.empresas.Contacto;
import com.example.proyectofinal.models.empresas.Empresa; import com.example.proyectofinal.models.empresas.Empresa;
import com.example.proyectofinal.servicios.ContactosService; import com.example.proyectofinal.servicios.empresa.ContactosService;
import com.example.proyectofinal.servicios.EmpresaService; import com.example.proyectofinal.servicios.empresa.EmpresaService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -54,6 +55,8 @@ public class ContactoController {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@RolesAllowed({"ADMIN"})
@GetMapping("/admin/contacto/update/{id}") @GetMapping("/admin/contacto/update/{id}")
public String showUpdateForm(Model model, @PathVariable Long id) { public String showUpdateForm(Model model, @PathVariable Long id) {
Contacto contacto = contactosService.findById(id); Contacto contacto = contactosService.findById(id);
@ -65,6 +68,7 @@ public class ContactoController {
return "admin/contacto/update"; return "admin/contacto/update";
} }
@PostMapping("/contacto/update") @PostMapping("/contacto/update")
public ResponseEntity<String> updateContacto(Contacto contacto, @RequestParam("empresa.id") Long empresaId){ public ResponseEntity<String> updateContacto(Contacto contacto, @RequestParam("empresa.id") Long empresaId){
try{ try{
@ -81,6 +85,7 @@ public class ContactoController {
} }
} }
@GetMapping("/contacto/delete/{id}") @GetMapping("/contacto/delete/{id}")
public ResponseEntity<String> deleteContacto(@PathVariable Long id){ public ResponseEntity<String> deleteContacto(@PathVariable Long id){
try{ try{

@ -6,6 +6,7 @@ import com.example.proyectofinal.models.empresas.Sector;
import com.example.proyectofinal.repositories.empresas.ContactoRepository; import com.example.proyectofinal.repositories.empresas.ContactoRepository;
import com.example.proyectofinal.servicios.implemetations.IEmpresa; import com.example.proyectofinal.servicios.implemetations.IEmpresa;
import com.example.proyectofinal.servicios.implemetations.ISector; import com.example.proyectofinal.servicios.implemetations.ISector;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -29,6 +30,7 @@ public class EmpressaController {
@Autowired @Autowired
ISector sectorService; ISector sectorService;
@GetMapping("/empresas/{id}") @GetMapping("/empresas/{id}")
public String getEmpressaContacts(@PathVariable Long id, Model model) { public String getEmpressaContacts(@PathVariable Long id, Model model) {
Set<Contacto> contactoSet = new HashSet<>(contactoRepository.findBySector(id)); Set<Contacto> contactoSet = new HashSet<>(contactoRepository.findBySector(id));
@ -36,6 +38,7 @@ public class EmpressaController {
return "contactos"; return "contactos";
} }
@GetMapping("/admin/empresa/create") @GetMapping("/admin/empresa/create")
public String showCreateForm(Model model) { public String showCreateForm(Model model) {
Empresa empresa = new Empresa(); Empresa empresa = new Empresa();
@ -63,6 +66,7 @@ public class EmpressaController {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@GetMapping("/admin/empresa/update/{id}") @GetMapping("/admin/empresa/update/{id}")
public String showUpdateForm(Model model, @PathVariable Long id) { public String showUpdateForm(Model model, @PathVariable Long id) {
Empresa empresa = empresaService.findById(id); Empresa empresa = empresaService.findById(id);
@ -78,6 +82,7 @@ public class EmpressaController {
return "admin/empresa/update"; return "admin/empresa/update";
} }
@PostMapping("/empresa/update") @PostMapping("/empresa/update")
public ResponseEntity<String> updateEmpresa(Empresa empresa, @RequestParam("sector.id") Long sectorId){ public ResponseEntity<String> updateEmpresa(Empresa empresa, @RequestParam("sector.id") Long sectorId){
try{ try{
@ -94,6 +99,7 @@ public class EmpressaController {
} }
} }
@GetMapping("/empresa/delete/{id}") @GetMapping("/empresa/delete/{id}")
public ResponseEntity<String> deleteEmpresa(@PathVariable Long id){ public ResponseEntity<String> deleteEmpresa(@PathVariable Long id){
try{ try{

@ -1,10 +1,12 @@
package com.example.proyectofinal.controllers.modelControllers; package com.example.proyectofinal.controllers.modelControllers;
import com.example.proyectofinal.models.empresas.Familia; import com.example.proyectofinal.models.empresas.Familia;
import com.example.proyectofinal.servicios.FamiliaService; import com.example.proyectofinal.servicios.empresa.FamiliaService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -15,6 +17,7 @@ public class FamiliaController {
@Autowired @Autowired
private FamiliaService familiaService; private FamiliaService familiaService;
@GetMapping("/admin/familia/create") @GetMapping("/admin/familia/create")
public String showCreateForm(Model model) { public String showCreateForm(Model model) {
Familia familia = new Familia(); Familia familia = new Familia();
@ -22,6 +25,7 @@ public class FamiliaController {
return "admin/familia/create"; return "admin/familia/create";
} }
@PostMapping("/familia/save") @PostMapping("/familia/save")
public ResponseEntity<String> saveFamilia(Familia familia){ public ResponseEntity<String> saveFamilia(Familia familia){
try{ try{
@ -36,6 +40,8 @@ public class FamiliaController {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@GetMapping("/admin/familia/update/{id}") @GetMapping("/admin/familia/update/{id}")
public String showUpdateForm(Model model, @PathVariable Long id) { public String showUpdateForm(Model model, @PathVariable Long id) {
Familia familia = familiaService.findById(id); Familia familia = familiaService.findById(id);
@ -43,6 +49,7 @@ public class FamiliaController {
return "admin/familia/update"; return "admin/familia/update";
} }
@PostMapping("/familia/update") @PostMapping("/familia/update")
public ResponseEntity<String> updateFamilia(Familia familia){ public ResponseEntity<String> updateFamilia(Familia familia){
try{ try{
@ -53,6 +60,7 @@ public class FamiliaController {
} }
} }
@GetMapping("/familia/delete/{id}") @GetMapping("/familia/delete/{id}")
public ResponseEntity<String> deleteFamilia(@PathVariable Long id){ public ResponseEntity<String> deleteFamilia(@PathVariable Long id){
try{ try{

@ -1,5 +0,0 @@
package com.example.proyectofinal.controllers.modelControllers;
//@RestController
public class LogInController {
}

@ -1,10 +1,11 @@
package com.example.proyectofinal.controllers.modelControllers; package com.example.proyectofinal.controllers.modelControllers;
import com.example.proyectofinal.models.empresas.*; import com.example.proyectofinal.models.empresas.*;
import com.example.proyectofinal.servicios.CicloService; import com.example.proyectofinal.servicios.empresa.CicloService;
import com.example.proyectofinal.servicios.OfertaService; import com.example.proyectofinal.servicios.empresa.OfertaService;
import com.example.proyectofinal.servicios.SkillService; import com.example.proyectofinal.servicios.empresa.SkillService;
import com.example.proyectofinal.servicios.SucursalService; import com.example.proyectofinal.servicios.empresa.SucursalService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -12,7 +13,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -31,6 +31,7 @@ public class OfertaController {
@Autowired @Autowired
private CicloService cicloService; private CicloService cicloService;
@GetMapping("/admin/oferta/create") @GetMapping("/admin/oferta/create")
public String showCreateForm(Model model) { public String showCreateForm(Model model) {
Oferta oferta = new Oferta(); Oferta oferta = new Oferta();
@ -44,6 +45,7 @@ public class OfertaController {
return "admin/oferta/create"; return "admin/oferta/create";
} }
@PostMapping("/oferta/save") @PostMapping("/oferta/save")
public ResponseEntity<String> saveOferta(Oferta oferta, @RequestParam("ciclo") Long ciclo, @RequestParam("sucursal") Long sucursal, @RequestParam("skills") List<Long> skills){ public ResponseEntity<String> saveOferta(Oferta oferta, @RequestParam("ciclo") Long ciclo, @RequestParam("sucursal") Long sucursal, @RequestParam("skills") List<Long> skills){
try{ try{
@ -64,6 +66,8 @@ public class OfertaController {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@GetMapping("/admin/oferta/update/{id}") @GetMapping("/admin/oferta/update/{id}")
public String showUpdateForm(Model model, @PathVariable Long id) { public String showUpdateForm(Model model, @PathVariable Long id) {
Oferta oferta = ofertaService.findById(id); Oferta oferta = ofertaService.findById(id);
@ -77,6 +81,7 @@ public class OfertaController {
return "admin/oferta/update"; return "admin/oferta/update";
} }
@PostMapping("/oferta/update") @PostMapping("/oferta/update")
public ResponseEntity<String> updateOferta(Oferta oferta, @RequestParam("ciclo") Long ciclo, @RequestParam("sucursal") Long sucursal, @RequestParam("skills") List<Long> skills){ public ResponseEntity<String> updateOferta(Oferta oferta, @RequestParam("ciclo") Long ciclo, @RequestParam("sucursal") Long sucursal, @RequestParam("skills") List<Long> skills){
System.out.println("UPDATE TEST"); System.out.println("UPDATE TEST");
@ -94,6 +99,7 @@ public class OfertaController {
} }
} }
@GetMapping("/oferta/delete/{id}") @GetMapping("/oferta/delete/{id}")
public ResponseEntity<String> deleteOferta(@PathVariable Long id){ public ResponseEntity<String> deleteOferta(@PathVariable Long id){
try{ try{

@ -3,7 +3,8 @@ package com.example.proyectofinal.controllers.modelControllers;
import com.example.proyectofinal.models.empresas.Empresa; import com.example.proyectofinal.models.empresas.Empresa;
import com.example.proyectofinal.models.empresas.Sector; import com.example.proyectofinal.models.empresas.Sector;
import com.example.proyectofinal.repositories.empresas.EmpressaRepository; import com.example.proyectofinal.repositories.empresas.EmpressaRepository;
import com.example.proyectofinal.servicios.SectorService; import com.example.proyectofinal.servicios.empresa.SectorService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -23,6 +24,7 @@ public class SectorController {
@Autowired @Autowired
private SectorService sectorService; private SectorService sectorService;
@GetMapping("sector/{id}") @GetMapping("sector/{id}")
public String getEmpressaBySector(@PathVariable Long id, Model model) { public String getEmpressaBySector(@PathVariable Long id, Model model) {
Set<Empresa> empresaSet = new HashSet<>(empressaRepository.findBySector(id)); Set<Empresa> empresaSet = new HashSet<>(empressaRepository.findBySector(id));
@ -30,6 +32,7 @@ public class SectorController {
return "empresas"; return "empresas";
} }
@GetMapping("/admin/sector/create") @GetMapping("/admin/sector/create")
public String showCreateForm(Model model) { public String showCreateForm(Model model) {
Sector sectores = new Sector(); Sector sectores = new Sector();
@ -37,6 +40,7 @@ public class SectorController {
return "admin/sector/create"; return "admin/sector/create";
} }
@PostMapping("/sector/save") @PostMapping("/sector/save")
public ResponseEntity<String> saveSector(Sector sector){ public ResponseEntity<String> saveSector(Sector sector){
try{ try{
@ -51,6 +55,7 @@ public class SectorController {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@GetMapping("/admin/sector/update/{id}") @GetMapping("/admin/sector/update/{id}")
public String showUpdateForm(Model model, @PathVariable Long id) { public String showUpdateForm(Model model, @PathVariable Long id) {
Sector sector = sectorService.findById(id); Sector sector = sectorService.findById(id);
@ -58,6 +63,7 @@ public class SectorController {
return "admin/sector/update"; return "admin/sector/update";
} }
@PostMapping("/sector/update") @PostMapping("/sector/update")
public ResponseEntity<String> updateSector(Sector sector){ public ResponseEntity<String> updateSector(Sector sector){
try{ try{
@ -68,6 +74,7 @@ public class SectorController {
} }
} }
@GetMapping("/sector/delete/{id}") @GetMapping("/sector/delete/{id}")
public ResponseEntity<String> deleteSector(@PathVariable Long id){ public ResponseEntity<String> deleteSector(@PathVariable Long id){
try{ try{

@ -1,7 +1,8 @@
package com.example.proyectofinal.controllers.modelControllers; package com.example.proyectofinal.controllers.modelControllers;
import com.example.proyectofinal.models.empresas.Skill; import com.example.proyectofinal.models.empresas.Skill;
import com.example.proyectofinal.servicios.SkillService; import com.example.proyectofinal.servicios.empresa.SkillService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -15,6 +16,7 @@ public class SkillController {
@Autowired @Autowired
private SkillService skillService; private SkillService skillService;
@GetMapping("/admin/skill/create") @GetMapping("/admin/skill/create")
public String showCreateForm(Model model) { public String showCreateForm(Model model) {
Skill skill = new Skill(); Skill skill = new Skill();
@ -22,6 +24,7 @@ public class SkillController {
return "admin/skill/create"; return "admin/skill/create";
} }
@PostMapping("/skill/save") @PostMapping("/skill/save")
public ResponseEntity<String> saveSkill(Skill skill){ public ResponseEntity<String> saveSkill(Skill skill){
try{ try{
@ -36,6 +39,7 @@ public class SkillController {
} }
} }
@GetMapping("/admin/skill/update/{id}") @GetMapping("/admin/skill/update/{id}")
public String showUpdateForm(Model model, @PathVariable Long id) { public String showUpdateForm(Model model, @PathVariable Long id) {
Skill skill = skillService.findById(id); Skill skill = skillService.findById(id);
@ -43,6 +47,7 @@ public class SkillController {
return "admin/skill/update"; return "admin/skill/update";
} }
@PostMapping("/skill/update") @PostMapping("/skill/update")
public ResponseEntity<String> updateSkill(Skill skill){ public ResponseEntity<String> updateSkill(Skill skill){
try{ try{
@ -53,6 +58,7 @@ public class SkillController {
} }
} }
@GetMapping("/skill/delete/{id}") @GetMapping("/skill/delete/{id}")
public ResponseEntity<String> deleteSkill(@PathVariable Long id){ public ResponseEntity<String> deleteSkill(@PathVariable Long id){
try{ try{

@ -2,8 +2,9 @@ package com.example.proyectofinal.controllers.modelControllers;
import com.example.proyectofinal.models.empresas.Empresa; import com.example.proyectofinal.models.empresas.Empresa;
import com.example.proyectofinal.models.empresas.Sucursal; import com.example.proyectofinal.models.empresas.Sucursal;
import com.example.proyectofinal.servicios.EmpresaService; import com.example.proyectofinal.servicios.empresa.EmpresaService;
import com.example.proyectofinal.servicios.SucursalService; import com.example.proyectofinal.servicios.empresa.SucursalService;
import jakarta.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -24,6 +25,7 @@ public class SucursalController {
@Autowired @Autowired
private EmpresaService empresaService; private EmpresaService empresaService;
@GetMapping("/admin/sucursal/create") @GetMapping("/admin/sucursal/create")
public String showCreateForm(Model model) { public String showCreateForm(Model model) {
Sucursal sucursal = new Sucursal(); Sucursal sucursal = new Sucursal();
@ -51,6 +53,8 @@ public class SucursalController {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@GetMapping("/admin/sucursal/update/{id}") @GetMapping("/admin/sucursal/update/{id}")
public String showUpdateForm(Model model, @PathVariable Long id) { public String showUpdateForm(Model model, @PathVariable Long id) {
Sucursal sucursal = sucursalService.findById(id); Sucursal sucursal = sucursalService.findById(id);
@ -63,6 +67,7 @@ public class SucursalController {
return "admin/sucursal/update"; return "admin/sucursal/update";
} }
@PostMapping("/sucursal/update") @PostMapping("/sucursal/update")
public ResponseEntity<String> updateSucursal(Sucursal sucursal, @RequestParam("empresa.id") Long sectorId){ public ResponseEntity<String> updateSucursal(Sucursal sucursal, @RequestParam("empresa.id") Long sectorId){
try{ try{
@ -75,6 +80,7 @@ public class SucursalController {
} }
} }
@GetMapping("/sucursal/delete/{id}") @GetMapping("/sucursal/delete/{id}")
public ResponseEntity<String> deleteSucursal(@PathVariable Long id){ public ResponseEntity<String> deleteSucursal(@PathVariable Long id){
System.out.println("Attempting to delete Sucursal with ID: " + id); System.out.println("Attempting to delete Sucursal with ID: " + id);

@ -1,5 +1,6 @@
package com.example.proyectofinal.models.empresas; package com.example.proyectofinal.models.empresas;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*; import jakarta.persistence.*;
import jdk.jfr.Name; import jdk.jfr.Name;
import lombok.*; import lombok.*;
@ -67,7 +68,7 @@ public class Alumno {
@Column(length = 2500) @Column(length = 2500)
private String keywords; private String keywords;
@JsonManagedReference
@ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH},fetch = FetchType.EAGER) @ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH},fetch = FetchType.EAGER)
@OnDelete(action = OnDeleteAction.CASCADE) @OnDelete(action = OnDeleteAction.CASCADE)
@JoinTable( @JoinTable(

@ -1,5 +1,6 @@
package com.example.proyectofinal.models.empresas; package com.example.proyectofinal.models.empresas;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
@ -45,6 +46,7 @@ public class Oferta {
@OnDelete(action = OnDeleteAction.CASCADE) @OnDelete(action = OnDeleteAction.CASCADE)
private Ciclo ciclo; private Ciclo ciclo;
@JsonManagedReference
@ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH},fetch = FetchType.EAGER) @ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH},fetch = FetchType.EAGER)
@OnDelete(action = OnDeleteAction.CASCADE) @OnDelete(action = OnDeleteAction.CASCADE)
@JoinTable( @JoinTable(

@ -1,12 +1,12 @@
package com.example.proyectofinal.models.empresas; package com.example.proyectofinal.models.empresas;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.NonNull; import lombok.NonNull;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
@ -25,9 +25,11 @@ public class Skill {
@Column(length = 75) @Column(length = 75)
private String nombre; private String nombre;
@JsonBackReference
@ManyToMany(mappedBy = "skills") @ManyToMany(mappedBy = "skills")
private Set<Alumno> alumnos; private Set<Alumno> alumnos;
@JsonBackReference
@ManyToMany(mappedBy = "skills") @ManyToMany(mappedBy = "skills")
private Set<Oferta> ofertas; private Set<Oferta> ofertas;

@ -7,6 +7,8 @@ import lombok.NoArgsConstructor;
import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction; import org.hibernate.annotations.OnDeleteAction;
import java.util.List;
@Entity @Entity
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@ -37,4 +39,5 @@ public class Usuario {
@JoinColumn(name = "fk_rol", referencedColumnName = "id") @JoinColumn(name = "fk_rol", referencedColumnName = "id")
@OnDelete(action = OnDeleteAction.CASCADE) @OnDelete(action = OnDeleteAction.CASCADE)
private Rol rol; private Rol rol;
} }

@ -18,4 +18,7 @@ public interface RolRepository extends JpaRepository<Rol, Long> {
@Query(value = "SELECT a.* FROM autoridad a JOIN rol_autoridad ra ON a.id = ra.fk_autoridad WHERE ra.fk_rol = ?1", nativeQuery = true) @Query(value = "SELECT a.* FROM autoridad a JOIN rol_autoridad ra ON a.id = ra.fk_autoridad WHERE ra.fk_rol = ?1", nativeQuery = true)
ArrayList<Autoridad> findAutoridadesByRolId(Long rolId); ArrayList<Autoridad> findAutoridadesByRolId(Long rolId);
@Query("select r.id from Rol r where r.nombre = ?1")
Long findRoleById(String user);
} }

@ -20,4 +20,11 @@ public interface UserRepository extends JpaRepository<Usuario, Long>{
@Modifying @Modifying
@Query("UPDATE Usuario u SET u.logedIn = false WHERE u.id = ?1") @Query("UPDATE Usuario u SET u.logedIn = false WHERE u.id = ?1")
void resetLogedIn(Long id); void resetLogedIn(Long id);
@Query("SELECT u FROM Usuario u WHERE u.nombreLogIn = ?1")
Optional<Usuario> findByNombreUsuarioLogIn(String logIn);
@Modifying
@Query("UPDATE Usuario u SET u.logedIn = false")
void resetAllLogedIn();
} }

@ -1,7 +1,6 @@
package com.example.proyectofinal.servicios; package com.example.proyectofinal.servicios.empresa;
import com.example.proyectofinal.models.empresas.Alumno; import com.example.proyectofinal.models.empresas.Alumno;
import com.example.proyectofinal.models.empresas.Ciclo;
import com.example.proyectofinal.repositories.empresas.AlumnoRepository; import com.example.proyectofinal.repositories.empresas.AlumnoRepository;
import com.example.proyectofinal.servicios.implemetations.IAlumno; import com.example.proyectofinal.servicios.implemetations.IAlumno;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;

@ -1,4 +1,4 @@
package com.example.proyectofinal.servicios; package com.example.proyectofinal.servicios.empresa;
import com.example.proyectofinal.models.empresas.Ciclo; import com.example.proyectofinal.models.empresas.Ciclo;
import com.example.proyectofinal.models.empresas.Familia; import com.example.proyectofinal.models.empresas.Familia;

@ -1,8 +1,7 @@
package com.example.proyectofinal.servicios; package com.example.proyectofinal.servicios.empresa;
import com.example.proyectofinal.models.empresas.Contacto; import com.example.proyectofinal.models.empresas.Contacto;
import com.example.proyectofinal.models.empresas.Empresa; import com.example.proyectofinal.models.empresas.Empresa;
import com.example.proyectofinal.repositories.empresas.EmpressaRepository;
import com.example.proyectofinal.servicios.implemetations.IContactos; import com.example.proyectofinal.servicios.implemetations.IContactos;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*; import org.springframework.data.domain.*;

@ -1,4 +1,4 @@
package com.example.proyectofinal.servicios; package com.example.proyectofinal.servicios.empresa;
import com.example.proyectofinal.models.empresas.Empresa; import com.example.proyectofinal.models.empresas.Empresa;
import com.example.proyectofinal.models.empresas.Oferta; import com.example.proyectofinal.models.empresas.Oferta;
import com.example.proyectofinal.models.empresas.Sucursal; import com.example.proyectofinal.models.empresas.Sucursal;

@ -1,8 +1,6 @@
package com.example.proyectofinal.servicios; package com.example.proyectofinal.servicios.empresa;
import com.example.proyectofinal.models.empresas.Empresa;
import com.example.proyectofinal.models.empresas.Familia; import com.example.proyectofinal.models.empresas.Familia;
import com.example.proyectofinal.models.empresas.Oferta;
import com.example.proyectofinal.repositories.empresas.FamiliaRepository; import com.example.proyectofinal.repositories.empresas.FamiliaRepository;
import com.example.proyectofinal.servicios.implemetations.IFamilia; import com.example.proyectofinal.servicios.implemetations.IFamilia;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -10,7 +8,6 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
@ -21,19 +18,11 @@ public class FamiliaService implements IFamilia {
@Autowired @Autowired
private CicloService cicloService; private CicloService cicloService;
@Override
public List<Familia> findAll() {
return familiaRepository.findAll();
}
@Override @Override
public Page<Familia> findAllPaginated(int pageNum, int pageSize, String sortField, String sortDir) { public Page<Familia> findAllPaginated(int pageNum, int pageSize, String sortField, String sortDir) {
Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending(); Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending();
PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, sort); PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);
Page<Familia> result = familiaRepository.findAll(pageRequest); return familiaRepository.findAll(pageRequest);
return result;
} }
@Override @Override
@ -67,4 +56,8 @@ public class FamiliaService implements IFamilia {
public List<Familia> search(String query) { public List<Familia> search(String query) {
return familiaRepository.search(query); return familiaRepository.search(query);
} }
public List<Familia> findAllFamilias() {
return familiaRepository.findAll();
}
} }

@ -1,6 +1,5 @@
package com.example.proyectofinal.servicios; package com.example.proyectofinal.servicios.empresa;
import com.example.proyectofinal.models.empresas.Ciclo;
import com.example.proyectofinal.models.empresas.Oferta; import com.example.proyectofinal.models.empresas.Oferta;
import com.example.proyectofinal.models.empresas.Skill; import com.example.proyectofinal.models.empresas.Skill;
import com.example.proyectofinal.models.empresas.Sucursal; import com.example.proyectofinal.models.empresas.Sucursal;

@ -1,9 +1,7 @@
package com.example.proyectofinal.servicios; package com.example.proyectofinal.servicios.empresa;
import com.example.proyectofinal.models.empresas.Empresa; import com.example.proyectofinal.models.empresas.Empresa;
import com.example.proyectofinal.models.empresas.Oferta;
import com.example.proyectofinal.models.empresas.Sector; import com.example.proyectofinal.models.empresas.Sector;
import com.example.proyectofinal.models.empresas.Sucursal;
import com.example.proyectofinal.repositories.empresas.OfertaRepository; import com.example.proyectofinal.repositories.empresas.OfertaRepository;
import com.example.proyectofinal.repositories.empresas.SectorRepository; import com.example.proyectofinal.repositories.empresas.SectorRepository;
import com.example.proyectofinal.servicios.implemetations.ISector; import com.example.proyectofinal.servicios.implemetations.ISector;

@ -1,4 +1,4 @@
package com.example.proyectofinal.servicios; package com.example.proyectofinal.servicios.empresa;
import com.example.proyectofinal.models.empresas.Skill; import com.example.proyectofinal.models.empresas.Skill;
import com.example.proyectofinal.repositories.empresas.SkillRepository; import com.example.proyectofinal.repositories.empresas.SkillRepository;

@ -1,4 +1,4 @@
package com.example.proyectofinal.servicios; package com.example.proyectofinal.servicios.empresa;
import com.example.proyectofinal.models.empresas.Empresa; import com.example.proyectofinal.models.empresas.Empresa;
import com.example.proyectofinal.models.empresas.Oferta; import com.example.proyectofinal.models.empresas.Oferta;

@ -6,7 +6,6 @@ import com.example.proyectofinal.models.empresas.Familia;
import java.util.List; import java.util.List;
public interface IFamilia extends IPagination<Familia> { public interface IFamilia extends IPagination<Familia> {
List<Familia> findAll();
Familia findById(Long id); Familia findById(Long id);

@ -12,6 +12,9 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -45,9 +48,6 @@ public class UsuarioService {
public Usuario login(String nombreLogIn, String password) { public Usuario login(String nombreLogIn, String password) {
Usuario usuario = userRepository.findByNombreUsuario(nombreLogIn) Usuario usuario = userRepository.findByNombreUsuario(nombreLogIn)
.orElseThrow(() -> new UsernameNotFoundException("Usuario no encontrado")); .orElseThrow(() -> new UsernameNotFoundException("Usuario no encontrado"));
if (usuario.isLogedIn()) {
throw new AlreadyLoggedInException("User is already logged in");
}
if (passwordEncoder.matches(password, usuario.getPassword())) { if (passwordEncoder.matches(password, usuario.getPassword())) {
userRepository.updateLogedIn( usuario.getId()); userRepository.updateLogedIn( usuario.getId());
return usuario; return usuario;
@ -55,11 +55,6 @@ public class UsuarioService {
throw new BadCredentialsException("Invalid password"); throw new BadCredentialsException("Invalid password");
} }
} }
private static class AlreadyLoggedInException extends RuntimeException {
public AlreadyLoggedInException(String message) {
super(message);
}
}
@Transactional @Transactional
public void logout(String nombreLogIn) { public void logout(String nombreLogIn) {
@ -77,19 +72,22 @@ public class UsuarioService {
Rol adminRole = rolRepository.findByName("ADMIN"); Rol adminRole = rolRepository.findByName("ADMIN");
createUsuario("admin", "admin", createUsuario("admin", "admin",
"admin@example.com", "admin@example.com",
"$2a$10$uTJY6B1H7MzEFrv2MX9K2uBgk1crVMtnuHgUgbTaQ/Cv7O.k0kUi2", "1234",
false, adminRole.getId()); false, adminRole.getId());
} }
} catch (Exception e) { } catch (Exception e) {
System.out.println("Exception in createDefaultRolesAuthoritiesAndAdmin: " + e.getMessage()); System.out.println("Exepcion en crearUsuarioPorDefecto: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
} }
public Usuario createUsuario(String nombreUsuario, String nombreLogIn, String email, String password, boolean loged, Long rolId) { public Usuario createUsuario(String nombreUsuario, String nombreLogIn, String email, String password, boolean loged, Long rolId) {
// Insert into usuario table // Insert into usuario table
//System.out.println("TEST: BEFORE"+ password);
String encodedPassword = passwordEncoder.encode(password);
//System.out.println("TEST AFTER: "+ encodedPassword);
String insertUsuarioSql = "INSERT INTO usuario (nombre_usuario, nombre_log_in, email, password, loged_in, fk_rol) VALUES (?, ?, ?, ?, ?, ?)"; String insertUsuarioSql = "INSERT INTO usuario (nombre_usuario, nombre_log_in, email, password, loged_in, fk_rol) VALUES (?, ?, ?, ?, ?, ?)";
jdbcTemplate.update(insertUsuarioSql, nombreUsuario, nombreLogIn, email, password, loged, rolId); jdbcTemplate.update(insertUsuarioSql, nombreUsuario, nombreLogIn, email, encodedPassword, loged, rolId);
// Get the last inserted id // Get the last inserted id
Long usuarioId = jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Long.class); Long usuarioId = jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Long.class);
@ -112,4 +110,30 @@ public class UsuarioService {
return usuario; return usuario;
} }
public Long findRolByName(String user) {
return rolRepository.findRoleById(user);
}
public Usuario findByLogInName(String logIn) {
return userRepository.findByNombreUsuarioLogIn(logIn).orElse(null);
}
public void deleteById(Long id) {
userRepository.deleteById(id);
}
public void logoutAllUsers() {
userRepository.resetAllLogedIn();
}
public boolean isAdmin() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
for (GrantedAuthority authority : authentication.getAuthorities()) {
if (authority.getAuthority().equals("ADMIN")) {
return true;
}
}
return false;
}
} }

@ -217,6 +217,9 @@ html, body {
} }
.scrollable-table { .scrollable-table {
overflow-x: auto; overflow-x: auto;
}
.hide-icon {
display: none;
} }

@ -0,0 +1,147 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Creacion: Empresa</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" th:href="@{/top.css}">
<style>
form {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
width: 100%;
max-width: none;
margin: auto;
padding: 25px;
margin-top: 100px;
}
.btn {
margin-top: 25px;
margin-right: 5px;
width: 120px;
height: 40px;
font-family: Verdana;
}
form input[type="submit"], form input[type="button"] {
width: 100px;
}
form input[type="text"]{
width: 75%;
}
form label{
font-size: 20px;
margin-bottom: 10px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
body, h1 {
margin: 0;
padding: 0;
width: 100%;
box-sizing: border-box;
}
</style>
</head>
<body>
<h1>Añadir Empresa<a href="/logout" class="logout-button"><i class="fas fa-door-open"></i></a></h1>
<form th:action="@{/empresa/save}" method="post" enctype="multipart/form-data" th:object="${empresa}">
<!--<input type="hidden" th:field="*{id}"/>-->
<div class="p-3">
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="nombre">Nombre</label>
<div class = "col-sm-9">
<input type="text" th:field="*{nombre}" required minlength="2" maxlength="128" class="form-control" id="nombre">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="cif">Cif</label>
<div class = "col-sm-9">
<input type="text" th:field="*{cif}" required pattern="^[A-HJ-NP-SUVW]{1}[0-9]{7}[0-9A-J]{1}$" title="Entra un cif valido eje W12345678" class="form-control" id="cif">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="correo">Correo</label>
<div class = "col-sm-9">
<input type="text" th:field="*{correo}" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="Entra en correo valido." class="form-control" id="correo">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="telefono">Telefono</label>
<div class = "col-sm-9">
<input type="text" th:field="*{telefono}" required pattern="^\d{10}$" title="Entra un numero de telefono valido de 10 digitos" class="form-control" id="telefono">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="keywords">Keywords</label>
<div class = "col-sm-9">
<input type="text" th:field="*{keywords}" required pattern="([a-zA-Z0-9]+,)*[a-zA-Z0-9]+" title="Los keywords tiene que ser separados por una ," class="form-control" id="keywords">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="sector">Sector</label>
<div class = "col-sm-9">
<select th:field="*{sector.id}" class="form-control" id="sector">
<option th:each="sector : ${sectores}" th:value="${sector.id}" th:text="${sector.nombre}"></option>
</select>
</div>
</div>
<div class="text-center">
<input type="submit" value="Guardar" class="btn"/>
<input type="button" value="Cancelar" id="btnCancelar" class="btn" onclick="goBack()"/>
</div>
</div>
</form>
<script>
function goBack() {
console.log("goBack function called");
window.history.back();
}
$(document).ready(function () {
$("form").on("submit", function (event) {
event.preventDefault();
var formData = $(this).serialize();
var sectorId = $('#sector').val();
formData += '&empresa=' + encodeURIComponent(sectorId);
$.ajax({
url: '/empresa/save',
type: 'post',
data: formData,
success: function (message) {
if(message === "La empresa fue guardado con exito") {
alert("La empresa fue guardado con exito")
window.history.go(-1); // Go back two pages
} else if(message === "Este empresa ya existe en la base de datos"){
alert("Este empresa ya existe en la base de datos");
window.history.go(-1);
}else{
alert("Error, consulata a los informaticos")
window.history.go(-1)
}
},
error: function (jqXHR) {
alert(jqXHR.responseText);
window.history.back();
}
});
});
});
</script>
</body>
</html>

@ -0,0 +1,145 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update: Empresa</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" th:href="@{/top.css}">
<style>
form {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
width: 100%;
max-width: none;
margin: auto;
padding: 25px;
margin-top: 100px;
}
.btn {
margin-top: 25px;
margin-right: 5px;
width: 120px;
height: 40px;
font-family: Verdana;
}
form input[type="submit"], form input[type="button"] {
width: 100px;
}
form input[type="text"]{
width: 75%;
}
form label{
font-size: 20px;
margin-bottom: 10px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
body, h1 {
margin: 0;
padding: 0;
width: 100%;
box-sizing: border-box;
}
</style>
</head>
<body>
<h1>Editar datos de Empresa<a href="/logout" class="logout-button"><i class="fas fa-door-open"></i></a></h1>
<form th:action="@{/empresa/update}" method="post" enctype="multipart/form-data" th:object="${empresa}">
<input type="hidden" th:field="*{id}"/>
<div class="p-3">
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="nombre">Nombre</label>
<div class = "col-sm-9">
<input type="text" th:field="*{nombre}" th:value="*{nombre}" required minlength="2" maxlength="128" class="form-control" id="nombre">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="cif">Cif</label>
<div class = "col-sm-9">
<input type="text" th:field="*{cif}" th:value="*{cif}" required pattern="^[A-HJ-NP-SUVW]{1}[0-9]{7}[0-9A-J]{1}$" title="Entra un cif valido eje. W12345678" class="form-control" id="cif">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="correo">Correo</label>
<div class = "col-sm-9">
<input type="text" th:field="*{correo}" th:value="*{correo}" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="Entra en correo valido." class="form-control" id="correo">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="telefono">Telefono</label>
<div class = "col-sm-9">
<input type="text" th:field="*{telefono}" th:value="*{telefono}" required pattern="^\d{10}$" title="Entra un numero de telefono valido de 10 digitos" class="form-control" id="telefono">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="keywords">Keywords</label>
<div class = "col-sm-9">
<input type="text" th:field="*{keywords}" th:value="*{keywords}" required pattern="([a-zA-Z0-9]+,)*[a-zA-Z0-9]+" title="Los keywords tiene que ser separados por una ," class="form-control" id="keywords">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="sector">Sector</label>
<div class = "col-sm-9">
<select th:field="*{sector.id}" class="form-control" id="sector">
<option th:each="sector : ${sectores}" th:value="${sector.id}" th:text="${sector.nombre}" th:selected="${sector.id == empresa.sector.id}"></option>
</select>
</div>
</div>
<div class="text-center">
<input type="submit" value="Guardar" class="btn"/>
<input type="button" value="Cancelar" id="btnCancelar" class="btn" onclick="goBack()"/>
</div>
</div>
</form>
<script>
function goBack() {
console.log("goBack function called");
window.history.back();
}
$(document).ready(function () {
$("form").on("submit", function (event) {
event.preventDefault();
var formData = $(this).serialize();
var sectorId = $('#sector').val();
formData += '&sector=' + encodeURIComponent(sectorId);
$.ajax({
url: '/empresa/update',
type: 'post',
data: formData,
success: function (message) {
if(message === "Los datos de la empresa fue renovados con exito") {
alert("Los datos de la empresa fue renovada con exito")
window.history.go(-1); // Go back two pages
}else{
alert("Error, consulata a los informaticos")
window.history.go(-1)
}
},
error: function (jqXHR) {
alert(jqXHR.responseText);
window.history.back();
}
});
});
});
</script>
</body>
</html>

@ -123,6 +123,15 @@
var searchBar = document.querySelector('input[name="query"]'); var searchBar = document.querySelector('input[name="query"]');
var secondaryDropdown = document.getElementById('secondaryDropdown'); var secondaryDropdown = document.getElementById('secondaryDropdown');
primaryDropdown.addEventListener('change', function() {
if (primaryDropdown.value === 'YourCondition') { // replace 'YourCondition' with the actual condition
secondaryDropdown.style.display = 'none';
} else {
secondaryDropdown.style.display = 'block';
}
});
secondaryDropdown.addEventListener('change', function() { secondaryDropdown.addEventListener('change', function() {
var datePicker = document.getElementById('datePicker'); var datePicker = document.getElementById('datePicker');
if (['Fecha antes', 'Fecha despues', 'Año'].includes(secondaryDropdown.value)) { if (['Fecha antes', 'Fecha despues', 'Año'].includes(secondaryDropdown.value)) {
@ -239,11 +248,6 @@
// Reset the form // Reset the form
document.querySelector('form').reset(); document.querySelector('form').reset();
// Get reference to the search bar
var secondaryDropdown = document.getElementById('secondaryDropdown');
secondaryDropdown.value = 'Todo';
var searchBar = document.querySelector('input[name="query"]');
// Set the value of the search bar to "Todo" and disable it // Set the value of the search bar to "Todo" and disable it
searchBar.value = 'Todo'; searchBar.value = 'Todo';
searchBar.disabled = true; searchBar.disabled = true;

@ -1,10 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> <html xmlns:th="http://www.thymeleaf.org">
<head> <head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css">
<link rel="stylesheet" type="text/css" th:href="@{/style.css}">
<link rel="stylesheet" type="text/css" th:href="@{/form.css}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Buscador</title> <title>Buscador</title>
<style> <style>
body { body {
display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
height: 100vh; height: 100vh;
@ -12,45 +15,262 @@
background-color: #f0f0f0; background-color: #f0f0f0;
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
} }
form {
.header {
display: flex; display: flex;
flex-direction: column;
align-items: center; align-items: center;
width: 50%; background-color: #007BFF;
justify-content: space-between;
padding: 0;
box-sizing: border-box;
} }
.search-container { .header h1 {
display: flex; margin: 0;
width: 100%; width: 100%;
justify-content: space-between; text-align: center;
}
.header button {
margin-right: auto;
} }
input[type="text"] {
flex-grow: 1; .logout-button {
padding: 15px; position: relative;
margin-right: 10px;
font-size: 18px;
} }
.checkboxes {
html, body {
margin: 0;
padding: 0;
}
.dropdown-container {
display: flex; display: flex;
flex-direction: row;
justify-content: space-between; justify-content: space-between;
align-items: center; width: 100%;
width: 50%; }
margin-top: 20px; #date{
margin-top: 15px;
} }
</style> </style>
</head> </head>
<body> <body >
<form action="#" method="get"> <div class="header">
<div class="search-container"> <h1>PAGINA PRINCIPAL</h1>
<input type="text" name="query" placeholder="Buscar..."> <a href="/logout" class="logout-button"><i class="fas fa-door-open"></i></a>
<input type="submit" value="Buscar"> </div>
</div>
<div class="checkboxes"> <div class="form-container" style="display: flex; justify-content: center; align-items: center; height: calc(100vh - 60px);">
<input type="checkbox" id="optionSkill" name="optskill" value="OptEmpresa"> <form action="/buscador/" method="get" id="searchForm" onsubmit="submitForm()">
<label for="optionSkill"> Skill</label><br> <div class="search-container" id="searchContainer">
<input type="checkbox" id="optionOferta" name="optoferta" value="OptOferta"> <input type="text" name="query" placeholder="Buscar...">
<label for="optionOferta"> Oferta</label><br> <input type="submit" value="Buscar">
</div> </div>
</form> <div class="dropdown-container">
<select name="searchOption" id="searchOption">
<option value="empresas">Empresa</option>
<option value="sectores">Sectores</option>
<option value="alumnos" >Alumnos</option>
<option value="ofertas">Ofertas</option>
<option value="sucursales">Sucursales</option>
<option value="skills">Skills</option>
<option value="contactos">Contactos</option>
<option value="familias">Familias</option>
<option value="ciclos">Ciclos</option>
</select>
<select id="secondaryDropdown"></select>
<input type="hidden" name="secondaryOption" id="hiddenSecondaryOption">
</div>
<div id="date">
<input type="date" id="datePicker" name="query" style="display: none;">
</div>
</form>
</div>
<script>
// Get reference to the date picker
var datePicker = document.getElementById('datePicker');
// Add an event listener to the date picker
datePicker.addEventListener('change', function() {
var searchBar = document.querySelector('input[name="query"]');
var secondaryOption = document.getElementById('secondaryDropdown').value;
// If the selected option is 'Fecha antes', 'Fecha despues', or 'Año', set the value of the search bar to the value of the date picker
if (['Fecha antes', 'Fecha despues', 'Año'].includes(secondaryOption)) {
searchBar.value = datePicker.value;
}
// Log the value of the search bar to the console
//console.log("Query: " + searchBar.value);
});
document.getElementById('searchForm').addEventListener('submit', function() {
var searchOption = document.getElementById('searchOption').value;
var secondaryOption = document.getElementById('secondaryDropdown').value;
var datePicker = document.getElementById('datePicker');
var searchBar = document.querySelector('input[name="query"]');
// If the selected option is 'Fecha antes', 'Fecha despues', or 'Año', set the value of the search bar to the value of the date picker
if (['Fecha antes', 'Fecha despues', 'Año'].includes(secondaryOption)) {
searchBar.value = datePicker.value;
}
// Update the value of the hidden input field
document.getElementById('hiddenSecondaryOption').value = secondaryOption;
this.action = "/buscador/" + searchOption + "/page/1";
});
// Get references to the primary dropdown, the search bar, and the secondary dropdown
var primaryDropdown = document.getElementById('searchOption');
var searchBar = document.querySelector('input[name="query"]');
var secondaryDropdown = document.getElementById('secondaryDropdown');
secondaryDropdown.addEventListener('change', function() {
var datePicker = document.getElementById('datePicker');
if (['Fecha antes', 'Fecha despues', 'Año'].includes(secondaryDropdown.value)) {
searchBar.value = '';
searchBar.disabled = true;
datePicker.style.display = 'block';
} else if (secondaryDropdown.value === 'Todo') {
searchBar.value = 'Todo';
searchBar.disabled = true;
datePicker.style.display = 'none';
} else {
searchBar.value = '';
searchBar.disabled = false;
datePicker.style.display = 'none';
}
});
primaryDropdown.addEventListener('change', function() {
// Clear the secondary dropdown
secondaryDropdown.innerHTML = '';
// Determine what to add to the secondary dropdown based on the selected option of the primary dropdown
var options;
switch (primaryDropdown.value) {
case 'empresas':
options = ['Todo', 'Nombre', 'Sector','Keywords'];
break;
case 'sectores':
options = ['Todo'];
break;
case 'contactos':
options = ['Todo', 'Nombre', 'Empresa'];
break;
case'ofertas':
options = ['Todo', 'Nombre', 'Empresa','Fecha'];
break;
case'sucursales':
options = ['Todo', 'Nombre', 'Empresa','Localidad'];
break;
case'skills':
options = ['Todo'];
break;
case'familias':
options = ['Todo'];
break;
case'ciclos':
options = ['Todo','Familia'];
break;
case'alumnos':
options = ['Todo', 'Nombre', 'Apellidos','Ciclo','Keywords'];
break;
default:
options = [];
}
//console.log("Primary dropdown value: " + primaryDropdown.value); // Add this line
//console.log("Options to add to secondary dropdown: " + options); // Add this line
// Add the new options to the secondary dropdown
for (var i = 0; i < options.length; i++) {
var option = document.createElement('option');
option.text = options[i];
secondaryDropdown.add(option);
}
});// Add an event listener to the primary dropdown
primaryDropdown.addEventListener('change', function() {
// Clear the secondary dropdown
secondaryDropdown.innerHTML = '';
// Determine what to add to the secondary dropdown based on the selected option of the primary dropdown
var options;
switch (primaryDropdown.value) {
case 'empresas':
options = ['Todo', 'Nombre', 'Sector','Keywords'];
break;
case 'sectores':
options = ['Todo'];
break;
case 'contactos':
options = ['Todo', 'Nombre', 'Empresa'];
break;
case'ofertas':
options = ['Todo', 'Nombre', 'Empresa','Fecha antes','Fecha despues','Año','Skill'];
break;
case'sucursales':
options = ['Todo', 'Nombre', 'Empresa','Localidad'];
break;
case'skills':
options = ['Todo'];
break;
case'familias':
options = ['Todo'];
break;
case'ciclos':
options = ['Todo','Familia','Codigo'];
break;
case'alumnos':
options = ['Todo', 'Nombre', 'Apellido','Ciclo','Keywords','Nia' ,'Dni'];
break;
default:
options = [];
}
// Add the new options to the secondary dropdown
for (var i = 0; i < options.length; i++) {
var option = document.createElement('option');
option.text = options[i];
secondaryDropdown.add(option);
}
});
// Trigger the change event manually to populate the secondary dropdown when the page loads
primaryDropdown.dispatchEvent(new Event('change'));
// Reset the form
document.querySelector('form').reset();
// Get reference to the search bar
var secondaryDropdown = document.getElementById('secondaryDropdown');
secondaryDropdown.value = 'Todo';
var searchBar = document.querySelector('input[name="query"]');
// Set the value of the search bar to "Todo" and disable it
searchBar.value = 'Todo';
searchBar.disabled = true;
function submitForm() {
var searchOption = document.getElementById('searchOption').value;
var secondaryOption = document.getElementById('secondaryDropdown').value;
var datePicker = document.getElementById('datePicker');
// If the selected option is 'Fecha antes', 'Fecha despues', or 'Año', set the value of the search bar to the value of the date picker
if (['Fecha antes', 'Fecha despues', 'Año'].includes(secondaryOption)) {
datePicker.name = "query";
} else {
datePicker.name = "";
}
// Log the query to the console
//console.log("Query SENT TEST: " + datePicker.value);
// Update the value of the hidden input field
document.getElementById('hiddenSecondaryOption').value = secondaryOption;
this.action = "/buscador/" + searchOption + "/page/1";
return true;
}
window.onload = function() {
primaryDropdown.dispatchEvent(new Event('change'));
};
</script>
</body> </body>
</html> </html>

@ -1,10 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Primer Usuario</title>
</head>
<body>
</body>
</html>

@ -19,69 +19,69 @@
</div> </div>
<input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus" id="create-icon"></i> <input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus hide-icon" id="create-icon" th:if="${isAdmin}"></i>
<div class="scrollable-table"> <div class="scrollable-table">
<table class="table" id="table"> <table class="table" id="table">
<thead class="thread-light"> <thead class="thread-light">
<tr> <tr>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Nombre Nombre
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=apellido&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=apellido&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Apellido Apellido
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=apellido2&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=apellido2&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Apellido2 Apellido2
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=fechaNacimiento&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=fechaNacimiento&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Fecha Nacimeinto Fecha Nacimeinto
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=genero&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=genero&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Genero Genero
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=nia&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=nia&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
NIA NIA
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=dni&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=dni&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
DNI/NIE/Numero de pasaporte DNI/NIE/Numero de pasaporte
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=correo&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=correo&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Correo Correo
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=correo2&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=correo2&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Correo2 Correo2
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=nacionalidad&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=nacionalidad&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Nacionalidad Nacionalidad
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=keywords&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=keywords&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Keywords Keywords
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=ciclo.nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/alumnos/page/' + ${currentPage} + '?sortField=ciclo.nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Ciclo Ciclo
</a> </a>
</th> </th>
@ -94,9 +94,9 @@
<tbody> <tbody>
<tr class="cell" th:each="alumno :${alumnos}" th:data-id="${alumno.id}"> <tr class="cell" th:each="alumno :${alumnos}" th:data-id="${alumno.id}">
<td> <td>
[[${alumno.nombre}]]
<i class="edit-icon fas fa-pen-square"></i> <i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i> <i class="delete-icon fas fa-ban hide-icon"></i>
[[${alumno.nombre}]]
</td> </td>
<td>[[${alumno.apellido}]]</td> <td>[[${alumno.apellido}]]</td>
<td>[[${alumno.apellido2}]]</td> <td>[[${alumno.apellido2}]]</td>
@ -164,6 +164,20 @@
var $createIcon = $('#create-icon'); var $createIcon = $('#create-icon');
var isSearchBarUsed = false; var isSearchBarUsed = false;
/*<![CDATA[*/
var isAdmin = [[${isAdmin}]];
/*]]>*/
//console.log(isAdmin);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
$table.on('click', '.edit-icon', function(event) { $table.on('click', '.edit-icon', function(event) {
//console.log("Edit icon clicked"); //console.log("Edit icon clicked");
handleEdit(event); handleEdit(event);
@ -238,6 +252,12 @@
/* rest of your JavaScript code */ /* rest of your JavaScript code */
/*]]>*/ /*]]>*/
if (isAdmin) {
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
fetch('/buscador/alumnos/search?querySearchBar=' + querySearchBar + '&query=' + query + '&secondaryOption=' + secondaryOption) fetch('/buscador/alumnos/search?querySearchBar=' + querySearchBar + '&query=' + query + '&secondaryOption=' + secondaryOption)
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
@ -246,11 +266,14 @@
data.forEach(alumno => { data.forEach(alumno => {
var row = document.createElement('tr'); var row = document.createElement('tr');
row.dataset.id = alumno.id; row.dataset.id = alumno.id;
if (isAdmin) {
iconHtml = `<i class="delete-icon fas fa-ban"></i> `;
}
row.innerHTML = ` row.innerHTML = `
<td> <td>
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban hide-icon" th:if="${isAdmin}"></i>
${alumno.nombre} ${alumno.nombre}
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>${alumno.apellido}</td> <td>${alumno.apellido}</td>
<td>${alumno.apellido2}</td> <td>${alumno.apellido2}</td>
@ -308,9 +331,13 @@
// Start observing the document with the configured parameters // Start observing the document with the configured parameters
observer.observe(document.querySelector('#table tbody'), { childList: true }); observer.observe(document.querySelector('#table tbody'), { childList: true });
document.getElementById('create-icon').addEventListener('click', function() { document.addEventListener('DOMContentLoaded', (event) => {
//console.log("Create button clicked : TEST"); var createIcon = document.getElementById('create-icon');
window.location = "/admin/alumno/create"; if (createIcon) {
createIcon.addEventListener('click', function() {
window.location = "/admin/alumno/create";
});
}
}); });
var tableHeaders = document.querySelectorAll('.table-header'); var tableHeaders = document.querySelectorAll('.table-header');

@ -19,24 +19,24 @@
</div> </div>
<input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus" id="create-icon"></i> <input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus hide-icon" id="create-icon" th:if="${isAdmin}"></i>
<div class="table-container"> <div class="table-container">
<table class="table" id="table"> <table class="table" id="table">
<thead class="thread-light"> <thead class="thread-light">
<tr> <tr>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/ciclos/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/ciclos/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Nombre Nombre
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/ciclos/page/' + ${currentPage} + '?sortField=codigo&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/ciclos/page/' + ${currentPage} + '?sortField=codigo&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Codigo Codigo
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/ciclos/page/' + ${currentPage} + '?sortField=familia.nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/ciclos/page/' + ${currentPage} + '?sortField=familia.nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Familia Familia
</a> </a>
</th> </th>
@ -44,9 +44,9 @@
<tbody> <tbody>
<tr class="cell" th:each="ciclo :${ciclos}" th:data-id="${ciclo.id}"> <tr class="cell" th:each="ciclo :${ciclos}" th:data-id="${ciclo.id}">
<td> <td>
<i class="edit-icon fas fa-pen-square hide-icon"></i>
<i class="delete-icon fas fa-ban hide-icon"></i>
[[${ciclo.nombre}]] [[${ciclo.nombre}]]
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>[[${ciclo.codigo}]]</td> <td>[[${ciclo.codigo}]]</td>
<td>[[${ciclo.familia.nombre}]]</td> <td>[[${ciclo.familia.nombre}]]</td>
@ -95,6 +95,21 @@
function goBack() { function goBack() {
window.history.back(); window.history.back();
} }
/*<![CDATA[*/
var isAdmin = [[${isAdmin}]];
/*]]>*/
//console.log(isAdmin);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
var $table = $('#table'); var $table = $('#table');
var $modalDelete = $('#modalDelete'); var $modalDelete = $('#modalDelete');
var $myInput = $('#myInput'); var $myInput = $('#myInput');
@ -102,26 +117,26 @@
var isSearchBarUsed = false; var isSearchBarUsed = false;
$table.on('click', '.edit-icon', function(event) { $table.on('click', '.edit-icon', function(event) {
console.log("Edit icon clicked"); //console.log("Edit icon clicked");
handleEdit(event); handleEdit(event);
}); });
$table.on('click', '.delete-icon', function(event) { $table.on('click', '.delete-icon', function(event) {
console.log("Delete icon clicked"); //console.log("Delete icon clicked");
handleDelete(event); handleDelete(event);
}); });
function handleEdit(event) { function handleEdit(event) {
console.log("handleEdit function called"); // console.log("handleEdit function called");
const row = event.target.closest('tr'); const row = event.target.closest('tr');
const rowId = row.dataset.id; const rowId = row.dataset.id;
console.log("Row ID: " + rowId); //console.log("Row ID: " + rowId);
window.location = "/admin/ciclo/update/" + rowId; window.location = "/admin/ciclo/update/" + rowId;
} }
function handleDelete(event) { function handleDelete(event) {
console.log("handleDelete function called"); //console.log("handleDelete function called");
console.log("Delete icon clicked"); //console.log("Delete icon clicked");
const row = event.target.closest('tr'); const row = event.target.closest('tr');
const rowId = row.dataset.id; const rowId = row.dataset.id;
var modal = document.getElementById("modalDelete"); var modal = document.getElementById("modalDelete");
@ -175,6 +190,16 @@
/* rest of your JavaScript code */ /* rest of your JavaScript code */
/*]]>*/ /*]]>*/
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
fetch('/buscador/ciclos/search?querySearchBar=' + querySearchBar + '&query=' + query + '&secondaryOption=' + secondaryOption) fetch('/buscador/ciclos/search?querySearchBar=' + querySearchBar + '&query=' + query + '&secondaryOption=' + secondaryOption)
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
@ -183,11 +208,15 @@
data.forEach(ciclo => { data.forEach(ciclo => {
var row = document.createElement('tr'); var row = document.createElement('tr');
row.dataset.id = ciclo.id; row.dataset.id = ciclo.id;
var iconHtml = '';
if (isAdmin) {
iconHtml = `<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i> `;
}
row.innerHTML = ` row.innerHTML = `
<td> <td>
${iconHtml}
${ciclo.nombre} ${ciclo.nombre}
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>${ciclo.codigo}</td> <td>${ciclo.codigo}</td>
<td>${ciclo.familia.nombre}</td> <td>${ciclo.familia.nombre}</td>
@ -211,8 +240,6 @@
} }
}); });
document.querySelector('#table').addEventListener('click', function(event) { document.querySelector('#table').addEventListener('click', function(event) {
if (event.target.matches('.edit-icon')) { if (event.target.matches('.edit-icon')) {
handleEdit(event); handleEdit(event);
@ -235,9 +262,13 @@
// Start observing the document with the configured parameters // Start observing the document with the configured parameters
observer.observe(document.querySelector('#table tbody'), { childList: true }); observer.observe(document.querySelector('#table tbody'), { childList: true });
document.getElementById('create-icon').addEventListener('click', function() { document.addEventListener('DOMContentLoaded', (event) => {
console.log("Create button clicked : TEST"); var createIcon = document.getElementById('create-icon');
window.location = "/admin/ciclo/create"; if (createIcon) {
createIcon.addEventListener('click', function() {
window.location = "/admin/ciclo/create";
});
}
}); });
var tableHeaders = document.querySelectorAll('.table-header'); var tableHeaders = document.querySelectorAll('.table-header');

@ -19,39 +19,39 @@
</div> </div>
<input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus" id="create-icon"></i> <input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus hide-icon" id="create-icon"></i>
<div class="table-container"> <div class="table-container">
<table class="table" id="table"> <table class="table" id="table">
<thead class="thread-light"> <thead class="thread-light">
<tr> <tr>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Nombre Nombre
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=apellido&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=apellido&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Apellido Apellido
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=apellido2&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=apellido2&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Apellido2 Apellido2
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=correo&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=correo&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Correo Correo
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=telefono&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=telefono&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Telefono Telefono
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=empresa.nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/contactos/page/' + ${currentPage} + '?sortField=empresa.nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Empresa Empresa
</a> </a>
</th> </th>
@ -60,9 +60,9 @@
<tbody> <tbody>
<tr class="cell" th:each="contacto :${contactos}" th:data-id="${contacto.id}"> <tr class="cell" th:each="contacto :${contactos}" th:data-id="${contacto.id}">
<td> <td>
<i class="edit-icon fas fa-pen-square hide-icon"></i>
<i class="delete-icon fas fa-ban hide-icon"></i>
[[${contacto.nombre}]] [[${contacto.nombre}]]
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>[[${contacto.apellido}]]</td> <td>[[${contacto.apellido}]]</td>
<td>[[${contacto.apellido2}]]</td> <td>[[${contacto.apellido2}]]</td>
@ -115,6 +115,21 @@
function goBack() { function goBack() {
window.history.back(); window.history.back();
} }
/*<![CDATA[*/
var isAdmin = [[${isAdmin}]];
/*]]>*/
//console.log(isAdmin);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
var $table = $('#table'); var $table = $('#table');
var $modalDelete = $('#modalDelete'); var $modalDelete = $('#modalDelete');
var $myInput = $('#myInput'); var $myInput = $('#myInput');
@ -195,6 +210,16 @@
/* rest of your JavaScript code */ /* rest of your JavaScript code */
/*]]>*/ /*]]>*/
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
fetch('/buscador/contactos/search?querySearchBar=' + querySearchBar+ '&query=' + query + '&secondaryOption=' + secondaryOption) fetch('/buscador/contactos/search?querySearchBar=' + querySearchBar+ '&query=' + query + '&secondaryOption=' + secondaryOption)
.then(response => response.json()) .then(response => response.json())
@ -204,11 +229,15 @@
data.forEach(contacto => { data.forEach(contacto => {
var row = document.createElement('tr'); var row = document.createElement('tr');
row.dataset.id = contacto.id; row.dataset.id = contacto.id;
var iconHtml = '';
if (isAdmin) {
iconHtml = `<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i> `;
}
row.innerHTML = ` row.innerHTML = `
<td> <td>
${iconHtml}
${contacto.nombre} ${contacto.nombre}
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>${contacto.apellido}</td> <td>${contacto.apellido}</td>
<td>${contacto.apellido2}</td> <td>${contacto.apellido2}</td>
@ -257,9 +286,13 @@
// Start observing the document with the configured parameters // Start observing the document with the configured parameters
observer.observe(document.querySelector('#table tbody'), { childList: true }); observer.observe(document.querySelector('#table tbody'), { childList: true });
document.getElementById('create-icon').addEventListener('click', function() { document.addEventListener('DOMContentLoaded', (event) => {
console.log("Create button clicked : TEST"); var createIcon = document.getElementById('create-icon');
window.location = "/admin/contacto/create"; if (createIcon) {
createIcon.addEventListener('click', function() {
window.location = "/admin/contacto/create";
});
}
}); });
var tableHeaders = document.querySelectorAll('.table-header'); var tableHeaders = document.querySelectorAll('.table-header');

@ -15,43 +15,43 @@
<div class="header"> <div class="header">
<button onclick="goBack()">Atras</button> <button onclick="goBack()">Atras</button>
<h1>Listado de Empresas</h1> <h1>Listado de Empresas</h1>
<a href="/logout" class="logout-button"><i class="fas fa-door-open"></i></a> <a href="/logout" class="logout-button"><i class="fas fa-door-open "></i></a>
</div> </div>
<input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus" id="create-icon"></i> <input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus hide-icon" id="create-icon" ></i>
<div class="table-container"> <div class="table-container">
<table class="table" id="table"> <table class="table" id="table">
<thead class="thread-light"> <thead class="thread-light">
<tr> <tr>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Nombre Nombre
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=cif&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=cif&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Cif Cif
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=correo&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=correo&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Correo Correo
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=telefono&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=telefono&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Telefono Telefono
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=keywords&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=keywords&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Keywords Keywords
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=sector.nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/empresas/page/' + ${currentPage} + '?sortField=sector.nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Sector Sector
</a> </a>
</th> </th>
@ -61,9 +61,9 @@
<tr class="cell" th:each="empresa :${empresas}" th:data-id="${empresa.id}"> <tr class="cell" th:each="empresa :${empresas}" th:data-id="${empresa.id}">
<td> <td>
<i class="edit-icon fas fa-pen-square hide-icon"></i>
<i class="delete-icon fas fa-ban hide-icon"></i>
<a th:href="@{/templates/admin/empresa/{id}(id=${empresa.id})}">[[${empresa.nombre}]]</a> <a th:href="@{/templates/admin/empresa/{id}(id=${empresa.id})}">[[${empresa.nombre}]]</a>
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>[[${empresa.cif}]]</td> <td>[[${empresa.cif}]]</td>
<td>[[${empresa.correo}]]</td> <td>[[${empresa.correo}]]</td>
@ -114,6 +114,19 @@
function goBack() { function goBack() {
window.history.back(); window.history.back();
} }
/*<![CDATA[*/
var isAdmin = [[${isAdmin}]];
/*]]>*/
//console.log(isAdmin);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
var $table = $('#table'); var $table = $('#table');
var $modalDelete = $('#modalDelete'); var $modalDelete = $('#modalDelete');
@ -195,10 +208,19 @@
var secondaryOption = /*[[${secondaryOption}]]*/ 'defaultSecondaryOption'; var secondaryOption = /*[[${secondaryOption}]]*/ 'defaultSecondaryOption';
/* rest of your JavaScript code */ /* rest of your JavaScript code */
/*]]>*/ /*]]>*/
//console.log("Query: " + query); //console.log("Query: " + query);
//console.log("Secondary Option: " + secondaryOption); //console.log("Secondary Option: " + secondaryOption);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
fetch('/buscador/empresas/search?querySearchBar=' + querySearchBar + '&query=' + query + '&secondaryOption=' + secondaryOption) fetch('/buscador/empresas/search?querySearchBar=' + querySearchBar + '&query=' + query + '&secondaryOption=' + secondaryOption)
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
@ -207,12 +229,16 @@
data.forEach(empresa => { data.forEach(empresa => {
var row = document.createElement('tr'); var row = document.createElement('tr');
row.dataset.id = empresa.id; row.dataset.id = empresa.id;
var iconHtml = '';
if (isAdmin) {
iconHtml = `<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i> `;
}
row.innerHTML = ` row.innerHTML = `
<td> <td>
${empresa.nombre} ${iconHtml}
<i class="edit-icon fas fa-pen-square"></i> ${empresa.nombre}
<i class="delete-icon fas fa-ban"></i> </td>
</td>
<td>${empresa.cif}</td> <td>${empresa.cif}</td>
<td>${empresa.correo}</td> <td>${empresa.correo}</td>
<td>${empresa.telefono}</td> <td>${empresa.telefono}</td>
@ -256,9 +282,13 @@
}); });
observer.observe(document.querySelector('#table tbody'), {childList: true}); observer.observe(document.querySelector('#table tbody'), {childList: true});
document.getElementById('create-icon').addEventListener('click', function () { document.addEventListener('DOMContentLoaded', (event) => {
//console.log("Create button clicked : TEST"); var createIcon = document.getElementById('create-icon');
window.location = "/admin/empresa/create"; if (createIcon) {
createIcon.addEventListener('click', function() {
window.location = "/admin/empresa/create";
});
}
}); });
var tableHeaders = document.querySelectorAll('.table-header'); var tableHeaders = document.querySelectorAll('.table-header');

@ -19,14 +19,14 @@
</div> </div>
<input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus" id="create-icon"></i> <input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus hide-icon" id="create-icon" th:if="${isAdmin}"></i>
<div class="table-container"> <div class="table-container">
<table class="table" id="table"> <table class="table" id="table">
<thead class="thread-light"> <thead class="thread-light">
<tr> <tr>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/familias/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/familias/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Nombre Nombre
</a> </a>
</th> </th>
@ -35,9 +35,9 @@
<tr class="cell" th:each="familia :${items}" th:data-id="${familia.id}"> <tr class="cell" th:each="familia :${items}" th:data-id="${familia.id}">
<td> <td>
<i class="edit-icon fas fa-pen-square hide-icon"></i>
<i class="delete-icon fas fa-ban hide-icon"></i>
[[${familia.nombre}]] [[${familia.nombre}]]
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
</tr> </tr>
</tbody> </tbody>
@ -84,6 +84,20 @@
function goBack() { function goBack() {
window.history.back(); window.history.back();
} }
/*<![CDATA[*/
var isAdmin = [[${isAdmin}]];
/*]]>*/
//console.log(isAdmin);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
var $table = $('#table'); var $table = $('#table');
var $modalDelete = $('#modalDelete'); var $modalDelete = $('#modalDelete');
var $myInput = $('#myInput'); var $myInput = $('#myInput');
@ -146,7 +160,7 @@
var paginationControls = document.querySelector('#paginationControls'); var paginationControls = document.querySelector('#paginationControls');
var entriesCountDropdown = document.querySelector('#entriesCount'); var entriesCountDropdown = document.querySelector('#entriesCount');
if (query == '') { if (query === '') {
isSearchBarUsed = false; isSearchBarUsed = false;
paginationControls.style.display = ''; paginationControls.style.display = '';
entriesCountDropdown.style.display = ''; entriesCountDropdown.style.display = '';
@ -158,6 +172,16 @@
entriesCountDropdown.style.display = 'none'; entriesCountDropdown.style.display = 'none';
table.style.pointerEvents = 'none'; table.style.pointerEvents = 'none';
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
fetch('/buscador/familias/search?query=' + query) fetch('/buscador/familias/search?query=' + query)
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
@ -166,11 +190,15 @@
data.forEach(familia => { data.forEach(familia => {
var row = document.createElement('tr'); var row = document.createElement('tr');
row.dataset.id = familia.id; row.dataset.id = familia.id;
var iconHtml = '';
if (isAdmin) {
iconHtml = `<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i> `;
}
row.innerHTML = ` row.innerHTML = `
<td> <td>
${iconHtml}
${familia.nombre} ${familia.nombre}
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
`; `;
tableBody.appendChild(row); tableBody.appendChild(row);
@ -214,9 +242,13 @@
// Start observing the document with the configured parameters // Start observing the document with the configured parameters
observer.observe(document.querySelector('#table tbody'), { childList: true }); observer.observe(document.querySelector('#table tbody'), { childList: true });
document.getElementById('create-icon').addEventListener('click', function() { document.addEventListener('DOMContentLoaded', (event) => {
console.log("Create button clicked : TEST"); var createIcon = document.getElementById('create-icon');
window.location = "/admin/familia/create"; if (createIcon) {
createIcon.addEventListener('click', function() {
window.location = "/admin/familia/create";
});
}
}); });
var tableHeaders = document.querySelectorAll('.table-header'); var tableHeaders = document.querySelectorAll('.table-header');

@ -19,34 +19,34 @@
</div> </div>
<input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus" id="create-icon"></i> <input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus hide-icon" id="create-icon"></i>
<div class="scrollable-table"> <div class="scrollable-table">
<table class="table" id="table"> <table class="table" id="table">
<thead class="thread-light"> <thead class="thread-light">
<tr> <tr>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir} + '&secondaryOption=' + ${secondaryOption}}">
Nombre Nombre
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=fecha&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=fecha&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Fecha Fecha
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=descripcion&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=descripcion&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Descripcion Descripcion
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=sucursal.nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=sucursal.nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Sucursal Sucursal
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=ciclo.nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/ofertas/page/' + ${currentPage} + '?sortField=ciclo.nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Ciclo Ciclo
</a> </a>
</th> </th>
@ -58,9 +58,9 @@
<tbody> <tbody>
<tr class="cell" th:each="oferta :${ofertas}" th:data-id="${oferta.id}"> <tr class="cell" th:each="oferta :${ofertas}" th:data-id="${oferta.id}">
<td> <td>
<i class="edit-icon fas fa-pen-square hide-icon"></i>
<i class="delete-icon fas fa-ban hide-icon"></i>
[[${oferta.nombre}]] [[${oferta.nombre}]]
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>[[${oferta.fecha}]]</td> <td>[[${oferta.fecha}]]</td>
<td>[[${oferta.descripcion}]]</td> <td>[[${oferta.descripcion}]]</td>
@ -114,6 +114,21 @@
function goBack() { function goBack() {
window.history.back(); window.history.back();
} }
/*<![CDATA[*/
var isAdmin = [[${isAdmin}]];
/*]]>*/
//console.log(isAdmin);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
var $table = $('#table'); var $table = $('#table');
var $modalDelete = $('#modalDelete'); var $modalDelete = $('#modalDelete');
var $myInput = $('#myInput'); var $myInput = $('#myInput');
@ -183,6 +198,16 @@
/* rest of your JavaScript code */ /* rest of your JavaScript code */
/*]]>*/ /*]]>*/
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
if (querySearchBar === '') { if (querySearchBar === '') {
isSearchBarUsed = false; isSearchBarUsed = false;
paginationControls.style.display = ''; paginationControls.style.display = '';
@ -203,11 +228,15 @@
data.forEach(oferta => { data.forEach(oferta => {
var row = document.createElement('tr'); var row = document.createElement('tr');
row.dataset.id = oferta.id; row.dataset.id = oferta.id;
var iconHtml = '';
if (isAdmin) {
iconHtml = `<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i> `;
}
row.innerHTML = ` row.innerHTML = `
<td> <td>
${iconHtml}
${oferta.nombre} ${oferta.nombre}
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>${oferta.fecha}</td> <td>${oferta.fecha}</td>
<td>${oferta.descripcion}</td> <td>${oferta.descripcion}</td>
@ -258,9 +287,13 @@
// Start observing the document with the configured parameters // Start observing the document with the configured parameters
observer.observe(document.querySelector('#table tbody'), { childList: true }); observer.observe(document.querySelector('#table tbody'), { childList: true });
document.getElementById('create-icon').addEventListener('click', function() { document.addEventListener('DOMContentLoaded', (event) => {
//console.log("Create button clicked : TEST"); var createIcon = document.getElementById('create-icon');
window.location = "/admin/oferta/create"; if (createIcon) {
createIcon.addEventListener('click', function() {
window.location = "/admin/oferta/create";
});
}
}); });
var tableHeaders = document.querySelectorAll('.table-header'); var tableHeaders = document.querySelectorAll('.table-header');

@ -19,14 +19,14 @@
</div> </div>
<input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus" id="create-icon"></i> <input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus hide-icon" id="create-icon" th:if="${isAdmin}"></i>
<div class="table-container"> <div class="table-container">
<table class="table" id="table"> <table class="table" id="table">
<thead class="thread-light"> <thead class="thread-light">
<tr> <tr>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/sectores/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/sectores/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Nombre Nombre
</a> </a>
</th> </th>
@ -34,9 +34,9 @@
<tbody> <tbody>
<tr class="cell" th:each="sector :${items}" th:data-id="${sector.id}"> <tr class="cell" th:each="sector :${items}" th:data-id="${sector.id}">
<td> <td>
<i class="edit-icon fas fa-pen-square hide-icon"></i>
<i class="delete-icon fas fa-ban hide-icon"></i>
[[${sector.nombre}]] [[${sector.nombre}]]
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
</tr> </tr>
</tbody> </tbody>
@ -83,6 +83,20 @@
function goBack() { function goBack() {
window.history.back(); window.history.back();
} }
/*<![CDATA[*/
var isAdmin = [[${isAdmin}]];
/*]]>*/
//console.log(isAdmin);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
var $table = $('#table'); var $table = $('#table');
var $modalDelete = $('#modalDelete'); var $modalDelete = $('#modalDelete');
var $myInput = $('#myInput'); var $myInput = $('#myInput');
@ -90,12 +104,12 @@
var isSearchBarUsed = false; var isSearchBarUsed = false;
$table.on('click', '.edit-icon', function(event) { $table.on('click', '.edit-icon', function(event) {
console.log("Edit icon clicked"); //console.log("Edit icon clicked");
handleEdit(event); handleEdit(event);
}); });
$table.on('click', '.delete-icon', function(event) { $table.on('click', '.delete-icon', function(event) {
console.log("Delete icon clicked"); //console.log("Delete icon clicked");
handleDelete(event); handleDelete(event);
}); });
@ -103,13 +117,13 @@
console.log("handleEdit function called"); console.log("handleEdit function called");
const row = event.target.closest('tr'); const row = event.target.closest('tr');
const rowId = row.dataset.id; const rowId = row.dataset.id;
console.log("Row ID: " + rowId); //console.log("Row ID: " + rowId);
window.location = "/admin/sector/update/" + rowId; window.location = "/admin/sector/update/" + rowId;
} }
function handleDelete(event) { function handleDelete(event) {
console.log("handleDelete function called"); //console.log("handleDelete function called");
console.log("Delete icon clicked"); //console.log("Delete icon clicked");
const row = event.target.closest('tr'); const row = event.target.closest('tr');
const rowId = row.dataset.id; const rowId = row.dataset.id;
var modal = document.getElementById("modalDelete"); var modal = document.getElementById("modalDelete");
@ -145,7 +159,17 @@
var paginationControls = document.querySelector('#paginationControls'); var paginationControls = document.querySelector('#paginationControls');
var entriesCountDropdown = document.querySelector('#entriesCount'); var entriesCountDropdown = document.querySelector('#entriesCount');
if (query == '') { if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
if (query === '') {
isSearchBarUsed = false; isSearchBarUsed = false;
paginationControls.style.display = ''; paginationControls.style.display = '';
entriesCountDropdown.style.display = ''; entriesCountDropdown.style.display = '';
@ -165,13 +189,15 @@
data.forEach(sector => { data.forEach(sector => {
var row = document.createElement('tr'); var row = document.createElement('tr');
row.dataset.id = sector.id; row.dataset.id = sector.id;
var iconHtml = '';
if (isAdmin) {
iconHtml = `<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i> `;
}
row.innerHTML = ` row.innerHTML = `
<td> <td>
${sector.id} ${iconHtml}
<i class="edit-icon fas fa-pen-square"></i> ${sector.nombre}</td>
<i class="delete-icon fas fa-ban"></i>
</td>
<td>${sector.nombre}</td>
`; `;
tableBody.appendChild(row); tableBody.appendChild(row);
}); });
@ -179,12 +205,12 @@
document.querySelectorAll('.edit-icon').forEach(function(icon) { document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.removeEventListener('click', handleEdit); icon.removeEventListener('click', handleEdit);
icon.addEventListener('click', handleEdit); icon.addEventListener('click', handleEdit);
console.log("Edit icon event listener attached"); //console.log("Edit icon event listener attached");
}); });
document.querySelectorAll('.delete-icon').forEach(function(icon) { document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.removeEventListener('click', handleDelete); icon.removeEventListener('click', handleDelete);
icon.addEventListener('click', handleDelete); icon.addEventListener('click', handleDelete);
console.log("Delete icon event listener attached"); //console.log("Delete icon event listener attached");
}); });
table.style.pointerEvents = 'auto'; table.style.pointerEvents = 'auto';
@ -214,9 +240,13 @@
// Start observing the document with the configured parameters // Start observing the document with the configured parameters
observer.observe(document.querySelector('#table tbody'), { childList: true }); observer.observe(document.querySelector('#table tbody'), { childList: true });
document.getElementById('create-icon').addEventListener('click', function() { document.addEventListener('DOMContentLoaded', (event) => {
console.log("Create button clicked : TEST"); var createIcon = document.getElementById('create-icon');
window.location = "/admin/sector/create"; if (createIcon) {
createIcon.addEventListener('click', function() {
window.location = "/admin/sector/create";
});
}
}); });
var tableHeaders = document.querySelectorAll('.table-header'); var tableHeaders = document.querySelectorAll('.table-header');

@ -19,14 +19,14 @@
</div> </div>
<input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus" id="create-icon"></i> <input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus hide-icon" id="create-icon" th:if="${isAdmin}"></i>
<div class="table-container"> <div class="table-container">
<table class="table" id="table"> <table class="table" id="table">
<thead class="thread-light"> <thead class="thread-light">
<tr> <tr>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/skills/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/skills/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}+ '&secondaryOption=' + ${secondaryOption}}">
Nombre Nombre
</a> </a>
</th> </th>
@ -34,9 +34,9 @@
<tbody> <tbody>
<tr class="cell" th:each="skill :${items}" th:data-id="${skill.id}"> <tr class="cell" th:each="skill :${items}" th:data-id="${skill.id}">
<td> <td>
<i class="edit-icon fas fa-pen-square hide-icon"></i>
<i class="delete-icon fas fa-ban hide-icon"></i>
[[${skill.nombre}]] [[${skill.nombre}]]
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
</tr> </tr>
</tbody> </tbody>
@ -83,6 +83,20 @@
function goBack() { function goBack() {
window.history.back(); window.history.back();
} }
/*<![CDATA[*/
var isAdmin = [[${isAdmin}]];
/*]]>*/
//console.log(isAdmin);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
var $table = $('#table'); var $table = $('#table');
var $modalDelete = $('#modalDelete'); var $modalDelete = $('#modalDelete');
var $myInput = $('#myInput'); var $myInput = $('#myInput');
@ -145,7 +159,17 @@
var paginationControls = document.querySelector('#paginationControls'); var paginationControls = document.querySelector('#paginationControls');
var entriesCountDropdown = document.querySelector('#entriesCount'); var entriesCountDropdown = document.querySelector('#entriesCount');
if (query == '') { if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
if (query === '') {
isSearchBarUsed = false; isSearchBarUsed = false;
paginationControls.style.display = ''; paginationControls.style.display = '';
entriesCountDropdown.style.display = ''; entriesCountDropdown.style.display = '';
@ -165,11 +189,15 @@
data.forEach(skill => { data.forEach(skill => {
var row = document.createElement('tr'); var row = document.createElement('tr');
row.dataset.id = skill.id; row.dataset.id = skill.id;
var iconHtml = '';
if (isAdmin) {
iconHtml = `<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i> `;
}
row.innerHTML = ` row.innerHTML = `
<td> <td>
${iconHtml}
${skill.nombre} ${skill.nombre}
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
`; `;
tableBody.appendChild(row); tableBody.appendChild(row);
@ -213,9 +241,13 @@
// Start observing the document with the configured parameters // Start observing the document with the configured parameters
observer.observe(document.querySelector('#table tbody'), { childList: true }); observer.observe(document.querySelector('#table tbody'), { childList: true });
document.getElementById('create-icon').addEventListener('click', function() { document.addEventListener('DOMContentLoaded', (event) => {
console.log("Create button clicked : TEST"); var createIcon = document.getElementById('create-icon');
window.location = "/admin/skill/create"; if (createIcon) {
createIcon.addEventListener('click', function() {
window.location = "/admin/skill/create";
});
}
}); });
var tableHeaders = document.querySelectorAll('.table-header'); var tableHeaders = document.querySelectorAll('.table-header');

@ -19,34 +19,34 @@
</div> </div>
<input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus" id="create-icon"></i> <input type="text" id="myInput" placeholder="Buscar por...."> <i class="fas fa-plus hide-icon" id="create-icon"></i>
<div class="table-container"> <div class="table-container">
<table class="table" id="table"> <table class="table" id="table">
<thead class="thread-light"> <thead class="thread-light">
<tr> <tr>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=nombre&sortDir=' + ${reverseSortDir} + '&secondaryOption=' + ${secondaryOption}}">
Nombre Nombre
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=localidad&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=localidad&sortDir=' + ${reverseSortDir} + '&secondaryOption=' + ${secondaryOption}}">
Localidad Localidad
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=direccion&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=direccion&sortDir=' + ${reverseSortDir} + '&secondaryOption=' + ${secondaryOption}}">
Direccion Direccion
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=sedeCentral&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=sedeCentral&sortDir=' + ${reverseSortDir} + '&secondaryOption=' + ${secondaryOption}}">
Sede Central Sede Central
</a> </a>
</th> </th>
<th class="table-header"> <th class="table-header">
<a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=empresa.nombre&sortDir=' + ${reverseSortDir}}"> <a th:href="@{'/buscador/sucursales/page/' + ${currentPage} + '?sortField=empresa.nombre&sortDir=' + ${reverseSortDir} + '&secondaryOption=' + ${secondaryOption}}">
Empresa Empresa
</a> </a>
</th> </th>
@ -55,9 +55,9 @@
<tbody> <tbody>
<tr class="cell" th:each="sucursal :${sucursales}" th:data-id="${sucursal.id}"> <tr class="cell" th:each="sucursal :${sucursales}" th:data-id="${sucursal.id}">
<td> <td>
<i class="edit-icon fas fa-pen-square hide-icon"></i>
<i class="delete-icon fas fa-ban hide-icon"></i>
[[${sucursal.nombre}]] [[${sucursal.nombre}]]
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>[[${sucursal.localidad}]]</td> <td>[[${sucursal.localidad}]]</td>
<td>[[${sucursal.direccion}]]</td> <td>[[${sucursal.direccion}]]</td>
@ -108,6 +108,21 @@
function goBack() { function goBack() {
window.history.back(); window.history.back();
} }
/*<![CDATA[*/
var isAdmin = [[${isAdmin}]];
/*]]>*/
//console.log(isAdmin);
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
var $table = $('#table'); var $table = $('#table');
var $modalDelete = $('#modalDelete'); var $modalDelete = $('#modalDelete');
var $myInput = $('#myInput'); var $myInput = $('#myInput');
@ -188,6 +203,16 @@
/* rest of your JavaScript code */ /* rest of your JavaScript code */
/*]]>*/ /*]]>*/
if (isAdmin) {
document.querySelectorAll('.edit-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelectorAll('.delete-icon').forEach(function(icon) {
icon.classList.remove('hide-icon');
});
document.querySelector('#create-icon').classList.remove('hide-icon');
}
fetch('/buscador/sucursales/search?querySearchBar=' + querySearchBar + '&query=' + query + '&secondaryOption=' + secondaryOption) fetch('/buscador/sucursales/search?querySearchBar=' + querySearchBar + '&query=' + query + '&secondaryOption=' + secondaryOption)
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
@ -196,11 +221,15 @@
data.forEach(sucursal => { data.forEach(sucursal => {
var row = document.createElement('tr'); var row = document.createElement('tr');
row.dataset.id = sucursal.id; row.dataset.id = sucursal.id;
var iconHtml = '';
if (isAdmin) {
iconHtml = `<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i> `;
}
row.innerHTML = ` row.innerHTML = `
<td> <td>
${iconHtml}
${sucursal.nombre} ${sucursal.nombre}
<i class="edit-icon fas fa-pen-square"></i>
<i class="delete-icon fas fa-ban"></i>
</td> </td>
<td>${sucursal.localidad}</td> <td>${sucursal.localidad}</td>
<td>${sucursal.direccion}</td> <td>${sucursal.direccion}</td>
@ -248,9 +277,13 @@
// Start observing the document with the configured parameters // Start observing the document with the configured parameters
observer.observe(document.querySelector('#table tbody'), { childList: true }); observer.observe(document.querySelector('#table tbody'), { childList: true });
document.getElementById('create-icon').addEventListener('click', function() { document.addEventListener('DOMContentLoaded', (event) => {
//console.log("Create button clicked : TEST"); var createIcon = document.getElementById('create-icon');
window.location = "/admin/sucursal/create"; if (createIcon) {
createIcon.addEventListener('click', function() {
window.location = "/admin/sucursal/create";
});
}
}); });
var tableHeaders = document.querySelectorAll('.table-header'); var tableHeaders = document.querySelectorAll('.table-header');

@ -0,0 +1,203 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update: Alumno</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" th:href="@{/top.css}">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<style>
form {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
width: 100%;
max-width: none;
margin: auto;
padding: 25px;
margin-top: 100px;
}
.btn {
margin-top: 25px;
margin-right: 5px;
width: 120px;
height: 40px;
font-family: Verdana;
}
form input[type="submit"], form input[type="button"] {
width: 100px;
}
form input[type="text"]{
width: 75%;
}
form label{
font-size: 20px;
margin-bottom: 10px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
body, h1 {
margin: 0;
padding: 0;
width: 100%;
box-sizing: border-box;
}
</style>
</head>
<body>
<h1>Editar datos de Alumno<a href="/logout" class="logout-button"><i class="fas fa-door-open"></i></a></h1>
<form th:action="@{/alumno/update}" method="post" enctype="multipart/form-data" th:object="${alumno}">
<input type="hidden" th:field="*{id}"/>
<div class="p-3">
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="nombre">Nombre</label>
<div class = "col-sm-9">
<input type="text" th:field="*{nombre}" required minlength="2" maxlength="75" class="form-control" id="nombre">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="cif">Apellido</label>
<div class = "col-sm-9">
<input type="text" th:field="*{apellido}" required minlength="2" maxlength="75" title="Entra un nombre" class="form-control" id="cif">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="apellido2">Apellido2</label>
<div class = "col-sm-9">
<input type="text" th:field="*{apellido2}" minlength="2" maxlength="75" class="form-control" id="apellido2">
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="fechaNacimiento">Fecha de Nacimiento</label>
<div class = "col-sm-9">
<input type="date" th:field="*{fechaNacimiento}" required class="form-control" id="fechaNacimiento" title="Introduce fecha">
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="genero">Genero</label>
<div class="col-sm-9">
<select th:field="*{genero}" class="form-control" id="genero" required>
<option value="">Selecciona un genero</option>
<option value="Mujer">Mujer</option>
<option value="Varon">Varon</option>
</select>
</div>
</div>
<div class ="form-group row">
<label class="col-sm-3 col-form-label" for="nia">Nia</label>
<div class = "col-sm-9">
<!--TODO: Añadir validacion de nia-->
<input type="text" th:field="*{nia}" title="Entra un nia correcto" class="form-control" id="nia">
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="dni">DNI/NIE</label>
<div class="col-sm-9">
<input type="text" th:field="*{dni}" required class="form-control" id="dni" title="Introduce DNI/NIE">
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="correo">Correo</label>
<div class="col-sm-9">
<input type="email" th:field="*{correo}" required class="form-control" id="correo" title="Introduce correo">
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="correo2">Correo2</label>
<div class="col-sm-9">
<input type="email" th:field="*{correo2}" class="form-control" id="correo2" title="Introduce correo alternativo">
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="nacionalidad">Nacionalidad</label>
<div class="col-sm-9">
<input type="text" th:field="*{nacionalidad}" class="form-control" id="nacionalidad" title="Introduce nacionalidad">
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="keywords">Keywords</label>
<div class="col-sm-9">
<input type="text" th:field="*{keywords}" class="form-control" id="keywords" title="Introduce keywords">
</div>
</div>
<!-- Ciclos -->
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="ciclo">Ciclo</label>
<div class="col-sm-9">
<select th:field="*{ciclo.id}" class="form-control" id="ciclo">
<option th:each="ciclo : ${ciclos}" th:value="${ciclo.id}" th:text="${ciclo.nombre}"></option>
</select>
</div>
</div>
<div class="skills-container">
<h2>Select Skills</h2>
<select id="skills" multiple>
<option th:each="skill : ${skills}" th:value="${skill.id}" th:text="${skill.nombre}" th:selected="${alumno.skills.contains(skill)}"></option>
</select>
</div>
<div class="text-center">
<input type="submit" value="Guardar" class="btn"/>
<input type="button" value="Cancelar" id="btnCancelar" class="btn" onclick="goBack()"/>
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#skills').select2();
});
function goBack() {
window.history.back();
}
$(document).ready(function () {
$("form").on("submit", function (event) {
event.preventDefault();
var formDataArray = $(this).serializeArray();
formDataArray.push({name: 'ciclo', value: $('#ciclo').val()});
formDataArray.push({name: 'skills', value: $('#skills').val()});
$.ajax({
url: '/alumno/update',
type: 'post',
data: $.param(formDataArray),
success: function (message) {
if(message === "El alumno fue actualizado con exito") {
alert("El alumno fue actualizado con exito")
window.history.go(-1);
} else {
alert("Error, consulte a los informaticos")
window.history.go(-1)
}
},
error: function (jqXHR) {
alert(jqXHR.responseText);
window.history.back();
}
});
});
});
</script>
</body>
</html>
Loading…
Cancel
Save

Powered by INFORMATICA.FP.EDU.ES.