diff --git a/src/main/bundles/prod.bundle b/src/main/bundles/prod.bundle index 9cf5704..d795b1a 100644 Binary files a/src/main/bundles/prod.bundle and b/src/main/bundles/prod.bundle differ diff --git a/src/main/java/mx/gob/jumapacelaya/models/MantCorrectivosModel.java b/src/main/java/mx/gob/jumapacelaya/models/MantCorrectivosModel.java new file mode 100644 index 0000000..2645f21 --- /dev/null +++ b/src/main/java/mx/gob/jumapacelaya/models/MantCorrectivosModel.java @@ -0,0 +1,91 @@ +package mx.gob.jumapacelaya.models; + +import java.time.LocalDate; + +public class MantCorrectivosModel { + private int mantenimientoId; + private LocalDate fecha; + private String tipo; + private String area; + private String nombre; + private String forma; + private String nomequipo; + private String reparacion; + + public MantCorrectivosModel(int mantenimientoId, LocalDate fecha, String tipo, + String area, String nombre, String forma, String nomequipo, String reparacion) { + + this.mantenimientoId = mantenimientoId; + this.fecha = fecha; + this.tipo = tipo; + this.area = area; + this.nombre = nombre; + this.forma = forma; + this.nomequipo = nomequipo; + this.reparacion = reparacion; + } + + public int getMantenimientoId() { + return mantenimientoId; + } + + public void setMantenimientoId(int mantenimientoId) { + this.mantenimientoId = mantenimientoId; + } + + public LocalDate getFecha() { + return fecha; + } + + public void setFecha(LocalDate fecha) { + this.fecha = fecha; + } + + public String getTipo() { + return tipo; + } + + public void setTipo(String tipo) { + this.tipo = tipo; + } + + public String getArea() { + return area; + } + + public void setArea(String area) { + this.area = area; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getForma() { + return forma; + } + + public void setForma(String forma) { + this.forma = forma; + } + + public String getNomequipo() { + return nomequipo; + } + + public void setNomequipo(String nomequipo) { + this.nomequipo = nomequipo; + } + + public String getReparacion() { + return reparacion; + } + + public void setReparacion(String reparacion) { + this.reparacion = reparacion; + } +} diff --git a/src/main/java/mx/gob/jumapacelaya/services/DatabaseService.java b/src/main/java/mx/gob/jumapacelaya/services/DatabaseService.java index ae212a0..5227ef6 100644 --- a/src/main/java/mx/gob/jumapacelaya/services/DatabaseService.java +++ b/src/main/java/mx/gob/jumapacelaya/services/DatabaseService.java @@ -378,6 +378,54 @@ public class DatabaseService { } + /* ---------------- Obtener los mantenimientos correctivos ---------------- */ + public List getMantenimientosCorrectivos(int tipomantId) { + List mantCorrectivos = new ArrayList<>(); + String query = "select\n" + + "\tm.MANTENIMIENTOID,\n" + + "\tm.FECHA,\n" + + "\tt.NOMBRE TIPO,\n" + + "\td.DESCRIPCION AREA,\n" + + "\tu.NOMBRE,\n" + + "\tCASE\n" + + "\t\tWHEN formamant = 'M' then 'MANUAL'\n" + + "\t\tELSE 'REMOTO'\n" + + "\tEND as FORMA,\n" + + "\tm.NOMBREEQUIPO,\n" + + "\tm.REPARACION\n" + + "from MANTENIMIENTOS m\n" + + "inner join TIPOMANT t on t.TIPOMANTID = m.TIPOMANTID\n" + + "inner join DEPARTAMENTOS d on d.DEPARTAMENTOID = m.DEPARTAMENTOID\n" + + "inner join USUARIOS u on u.EMPLEADOID = m.EMPLEADOID\n" + + "where m.TIPOMANTID = ?"; + + try (Connection conn = getMysqlConnection(); + PreparedStatement statement = conn.prepareStatement(query)) { + + statement.setInt(1, tipomantId); + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { + MantCorrectivosModel model = new MantCorrectivosModel( + rs.getInt("MANTENIMIENTOID"), + rs.getDate("FECHA").toLocalDate(), + rs.getString("TIPO"), + rs.getString("AREA"), + rs.getString("NOMBRE"), + rs.getString("FORMA"), + rs.getString("NOMBREEQUIPO"), + rs.getString("REPARACION") + ); + mantCorrectivos.add(model); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + return mantCorrectivos; + } + + + /*-=iii=<() *-=iii=<() *-=iii=<() *-=iii=<() *-=iii=<() *-=iii=<()*/ /*-=iii=<() *-=iii=<() *-=iii=<() *-=iii=<() *-=iii=<()*/ /*-=iii=<() *-=iii=<() *-=iii=<() *-=iii=<()*/ @@ -387,10 +435,10 @@ public class DatabaseService { // INSERTAR EN TABLA: MANTENIMINETOS public int insertarMantenimiento(LocalDate fecha, String tipoMantId, String departamentoId, String empleadoId, String formaMant, String equipoId, String userSignatureBase64, - String smtSignatureBase64, String planAnualId, String justificacion) { + String smtSignatureBase64, String planAnualId, String justificacion, String reparacion) { String query = "INSERT INTO MANTENIMIENTOS (fecha, tipoMantId, departamentoId, empleadoId, formaMant, nombreequipo," + - " firmaUsuario, firmaSmt, planAnualId, justificacion) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + " firmaUsuario, firmaSmt, planAnualId, justificacion, reparacion) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; String updateStatusQuery = "UPDATE PLANANUAL SET estado = 'REALIZADO' WHERE planAnualId = ?"; @@ -429,8 +477,13 @@ public class DatabaseService { preparedStatement.setNull(8, Types.VARCHAR); } - preparedStatement.setLong(9, Long.parseLong(planAnualId)); + if (planAnualId != null && !planAnualId.isEmpty()) { + preparedStatement.setLong(9, Long.parseLong(planAnualId)); + } else { + preparedStatement.setNull(9, Types.BIGINT); + } preparedStatement.setString(10, justificacion); + preparedStatement.setString(11, reparacion); preparedStatement.executeUpdate(); diff --git a/src/main/java/mx/gob/jumapacelaya/ui/MainLayout.java b/src/main/java/mx/gob/jumapacelaya/ui/MainLayout.java index 128c570..08d4c1a 100644 --- a/src/main/java/mx/gob/jumapacelaya/ui/MainLayout.java +++ b/src/main/java/mx/gob/jumapacelaya/ui/MainLayout.java @@ -88,7 +88,7 @@ public class MainLayout extends AppLayout { nav.addItem(new SideNavItem("Plan Anual", PlanAnualView.class, VaadinIcon.CALENDAR.create())); nav.addItem(new SideNavItem("Listado de Actividades", ActDiariaView.class, VaadinIcon.EDIT.create())); - //nav.addItem(new SideNavItem("Mantenimiento", MantenimientoView.class, VaadinIcon.WRENCH.create())); + nav.addItem(new SideNavItem("Mantenimiento Correctivo", MantCorrectivoView.class, VaadinIcon.WRENCH.create())); nav.getStyle().set("background-color", "white"); nav.getStyle().set("border-radius", "5px"); nav.getStyle().set("opacity", "0.9"); diff --git a/src/main/java/mx/gob/jumapacelaya/ui/MantCorrectivoView.java b/src/main/java/mx/gob/jumapacelaya/ui/MantCorrectivoView.java new file mode 100644 index 0000000..7763a5a --- /dev/null +++ b/src/main/java/mx/gob/jumapacelaya/ui/MantCorrectivoView.java @@ -0,0 +1,693 @@ +package mx.gob.jumapacelaya.ui; + +import com.vaadin.flow.component.Text; +import com.vaadin.flow.component.UI; +import com.vaadin.flow.component.button.Button; +import com.vaadin.flow.component.button.ButtonVariant; +import com.vaadin.flow.component.checkbox.CheckboxGroup; +import com.vaadin.flow.component.combobox.ComboBox; +import com.vaadin.flow.component.datepicker.DatePicker; +import com.vaadin.flow.component.dependency.CssImport; +import com.vaadin.flow.component.dialog.Dialog; +import com.vaadin.flow.component.formlayout.FormLayout; +import com.vaadin.flow.component.grid.Grid; +import com.vaadin.flow.component.grid.GridVariant; +import com.vaadin.flow.component.html.Image; +import com.vaadin.flow.component.html.Span; +import com.vaadin.flow.component.icon.Icon; +import com.vaadin.flow.component.icon.VaadinIcon; +import com.vaadin.flow.component.notification.Notification; +import com.vaadin.flow.component.notification.NotificationVariant; +import com.vaadin.flow.component.orderedlayout.HorizontalLayout; +import com.vaadin.flow.component.orderedlayout.VerticalLayout; +import com.vaadin.flow.component.radiobutton.RadioButtonGroup; +import com.vaadin.flow.component.textfield.TextArea; +import com.vaadin.flow.component.textfield.TextField; +import com.vaadin.flow.data.renderer.ComponentRenderer; +import com.vaadin.flow.function.ValueProvider; +import com.vaadin.flow.router.BeforeEnterEvent; +import com.vaadin.flow.router.BeforeEnterObserver; +import com.vaadin.flow.router.PageTitle; +import com.vaadin.flow.router.Route; +import de.f0rce.signaturepad.SignaturePad; +import jakarta.annotation.security.PermitAll; +import mx.gob.jumapacelaya.models.*; +import mx.gob.jumapacelaya.services.DatabaseService; +import mx.gob.jumapacelaya.services.EmailService; +import mx.gob.jumapacelaya.services.SecurityService; +import mx.gob.jumapacelaya.services.UserService; +import org.vaadin.lineawesome.LineAwesomeIcon; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.*; + +@PermitAll +@PageTitle("Correctivo") +@Route(value = "correctivo", layout = MainLayout.class) +@CssImport("./themes/sistema-mantenimiento/styles.css") +public class MantCorrectivoView extends VerticalLayout { + + private VerticalLayout mainLayout; + private final SecurityService securityService; + private final VerticalLayout controlsLayout; + private final DatabaseService databaseService; + private final VerticalLayout actualizacionesLayout; + //private final VerticalLayout etiquetaLayout; + private final HorizontalLayout firmasLayout; + private final DatePicker fecha; + private final ComboBox tipoMantt; + private final ComboBox area; + private final ComboBox usuario; + private final TextField txtNombreEquipo; + private final UserService userService; + private final EmailService emailService; + private RadioButtonGroup formaGroup; + private CheckboxGroup actualizaciones; + private final HorizontalLayout botonesLayout; + private TextArea txtCuales; + private RadioButtonGroup masActualizacionesGroup; + private SignaturePad userSignPad; + private SignaturePad smtSignPad; + private SignaturePad gciatiSignPad; + private PlanAnual planAnualActual; + private LocalDate fechaProgramada; + private LocalDate fechaSeleccionada; + private TextArea jsutificacion; + Span userSignSpan = new Span("Nombre Usuario"); + private TextArea txtReparacion; + private HorizontalLayout headerLayout; + + public MantCorrectivoView(UserService userService, SecurityService securityService, EmailService emailService, DatabaseService databaseService) { + this.databaseService = databaseService; + this.controlsLayout = new VerticalLayout(); + this.actualizacionesLayout = new VerticalLayout(); + //this.etiquetaLayout = new VerticalLayout(); + this.firmasLayout = new HorizontalLayout(); + this.botonesLayout = new HorizontalLayout(); + this.securityService = securityService; + this.userService = userService; + this.emailService = emailService; + + + headerLayout = new HorizontalLayout(); + headerLayout.setWidthFull(); + headerLayout.setMargin(false); + headerLayout.getStyle() + .set("box-shadow", "0 4px 8px rgba(0,0,0,0.2)") + .set("border-radius", "10px") + .set("background-color", "white") + .set("padding", "1rem") + .set("margin", "1rem auto"); + + + mainLayout = new VerticalLayout(); + mainLayout.setHeightFull(); + mainLayout.setMargin(false); + mainLayout.getStyle() + .set("box-shadow", "0 4px 8px rgba(0,0,0,0.2)") + .set("border-radius", "12px") + .set("background-color", "white") + .set("padding", "1rem") + .set("margin", "1rem auto"); + + + TextField nomenclatura = new TextField("Nomenclatura"); + nomenclatura.setReadOnly(true); + nomenclatura.addClassName("mantenimiento-text-field"); + + Button btnListado = new Button("Mantenimientos realizados", VaadinIcon.CLIPBOARD_CHECK.create()); + btnListado.addClickListener(e -> verListadoMantenimientos()); + + fecha = new DatePicker("Fecha:"); + fecha.setRequired(true); + fecha.setLocale(new Locale("es", "MX")); + DatePicker.DatePickerI18n i18n = new DatePicker.DatePickerI18n() + .setWeekdays(List.of("Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado")) + .setWeekdaysShort(List.of("Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb")) + .setMonthNames(List.of("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre")) + .setFirstDayOfWeek(1) + .setToday("Hoy") + .setCancel("Cancelar") + .setDateFormat("dd/MM/yyyy"); + fecha.setI18n(i18n); + + + tipoMantt = new ComboBox<>("Tipo de Mantenimiento"); + List tiposMantenimiento = databaseService.getTiposDeMantenimientos(); + tipoMantt.setItems(tiposMantenimiento); + tipoMantt.addClassName("mantenimiento-combo"); + // Listener para manejar el cambio en el tipo de mantenimiento + tipoMantt.addValueChangeListener(e -> { + TiposMantenimiento tipoSeleccionado = e.getValue(); + if (tipoSeleccionado != null) { + String nomenclaturaValue = databaseService.getNomenclatura(tipoSeleccionado.getTipomantId()); + nomenclatura.setValue(nomenclaturaValue); + fecha.setValue(LocalDate.now()); + } + }); + + HorizontalLayout fechaLayout = new HorizontalLayout(); + fechaLayout.add(fecha); + fechaLayout.addAndExpand(new HorizontalLayout()); + fechaLayout.add(tipoMantt, nomenclatura); + fechaLayout.setWidthFull(); + + + HorizontalLayout departamentoUsuarioLayout = new HorizontalLayout(); + area = new ComboBox<>("Área o Departamento:"); + area.setRequired(true); + List areas = databaseService.getDepartamentos(); + area.setItems(areas); + + usuario = new ComboBox<>("Usuario:"); + List usuarios = databaseService.getUsuarios(); + usuario.setItems(usuarios); + usuario.setItemLabelGenerator(Usuario::getNombre); + usuario.setRequired(true); + usuario.addValueChangeListener(e -> { + Usuario usuarioSeleccionado = e.getValue(); + if (usuarioSeleccionado != null) { + String empleadoId = usuarioSeleccionado.getEmpleadoId(); + String nombreUsuario = usuarioSeleccionado.getNombre(); + //userSignSpan.setText(nombreUsuario); + } else { + //userSignSpan.setText("S.M.T Nombre"); + } + }); + txtNombreEquipo = new TextField("Nombre del Equipo:"); + departamentoUsuarioLayout.add(area, usuario, txtNombreEquipo); + departamentoUsuarioLayout.setWidthFull(); + + createHardwareSection(databaseService); + addActualizacionesSection(); + signLayout(); + buttons(); + + headerLayout.add(btnListado); + mainLayout.add(fechaLayout, departamentoUsuarioLayout, controlsLayout, actualizacionesLayout, firmasLayout, botonesLayout); + add(headerLayout, mainLayout); + } + + + // Metodo para inicializar el formulario de hardware + private void createHardwareSection(DatabaseService databaseService) { + HorizontalLayout etiquetaLayout = new HorizontalLayout(); + Span etiqueta = new Span("Limpieza de Equipo Realizada"); + + Button btnAgregarTipo = new Button(new Icon(VaadinIcon.PLUS)); + btnAgregarTipo.addThemeVariants(ButtonVariant.LUMO_ICON); + btnAgregarTipo.setAriaLabel("Agregar Equipo"); + btnAgregarTipo.addClickListener(e -> { + addNuevoTipo(); + }); + + etiquetaLayout.add(etiqueta, btnAgregarTipo); + controlsLayout.add(etiquetaLayout); + controlsLayout.setSpacing(false); + + addNuevoTipo(); + } + + + // Método para crear el combo box y campos de texto para eñ hardware en tiempo de ejecución + private List hardwareLayouts = new ArrayList<>(); + + private void addNuevoTipo() { + ComboBox tipoHardware = new ComboBox<>(); + tipoHardware.setPlaceholder("Tipos de Hardware"); + tipoHardware.setItemLabelGenerator(TiposHardware::getNombreHardware); + tipoHardware.setItems(databaseService.getTiposHardware()); + tipoHardware.setSizeFull(); + + TextField noSerie = new TextField(); + noSerie.setEnabled(false); + noSerie.setRequired(true); + noSerie.setPlaceholder("No. de Serie"); + noSerie.setSizeFull(); + noSerie.addValueChangeListener(e -> { + String upperCaseValue = e.getValue().toUpperCase(); + noSerie.setValue(upperCaseValue); + }); + + TextField modelo = new TextField(); + modelo.setEnabled(false); + modelo.setRequired(true); + modelo.setPlaceholder("Modelo"); + modelo.setSizeFull(); + modelo.addValueChangeListener(event -> { + String upperCaseValue = event.getValue().toUpperCase(); + modelo.setValue(upperCaseValue); + }); + + TextField placa = new TextField(); + placa.setEnabled(false); + placa.setRequired(true); + placa.setPlaceholder("Placa"); + placa.setSizeFull(); + // Validacion para que este campo solo acepte numeros + placa.getElement().executeJs( + "this.addEventListener('input', function(e) { " + + " e.target.value = e.target.value.replace(/[^0-9]/g, '');" + // Solo permite dígitos + "});" + ); + + tipoHardware.addValueChangeListener(event -> { + TiposHardware tipoSeleccionado = event.getValue(); + + if (tipoSeleccionado != null) { + String nombreTipo = tipoSeleccionado.getNombreHardware(); + if ("TECLADO".equals(nombreTipo)) { + noSerie.setEnabled(false); + modelo.setEnabled(false); + placa.setEnabled(false); + } else if ("MOUSE".equals(nombreTipo)) { + noSerie.setEnabled(false); + modelo.setEnabled(false); + placa.setEnabled(false); + } else { + noSerie.setEnabled(true); + modelo.setEnabled(true); + placa.setEnabled(true); + } + } else { + noSerie.setEnabled(false); + modelo.setEnabled(false); + placa.setEnabled(false); + } + }); + + Button btnEliminar = new Button(new Icon(VaadinIcon.TRASH)); + btnEliminar.addThemeVariants(ButtonVariant.LUMO_ICON, ButtonVariant.LUMO_ERROR); + btnEliminar.setAriaLabel("Eliminar Tipo"); + + //Crear nuevo layout horizontal con estos campos + HorizontalLayout hardwareDetailsLayout = new HorizontalLayout(); + hardwareDetailsLayout.add(tipoHardware, noSerie, modelo, placa, btnEliminar); + hardwareDetailsLayout.setWidthFull(); + + hardwareLayouts.add(hardwareDetailsLayout); + controlsLayout.add(hardwareDetailsLayout); + + //Listener para eliminar el tipo + btnEliminar.addClickListener(event -> { + controlsLayout.remove(hardwareDetailsLayout); + }); + + controlsLayout.add(hardwareDetailsLayout); + controlsLayout.setSizeFull(); + } + + + private void addActualizacionesSection() { + VerticalLayout etiquetaLayout = new VerticalLayout(); + Span Titulo = new Span("Actualizaciones de Seguridad Informatica:"); + etiquetaLayout.add(Titulo); + + actualizaciones = new CheckboxGroup<>(); + actualizaciones.setLabel("Actualizaciones Necesarias"); + actualizaciones.setItems("S.O", "Antivirus", "Firewall"); + + formaGroup = new RadioButtonGroup<>(); + formaGroup.setLabel("Actividad Realizada de Forma:"); + formaGroup.setRequired(true); + formaGroup.setItems("Remota", "Manual"); + + txtCuales = new TextArea(); + txtCuales.setLabel("¿Cuáles?"); + txtCuales.setEnabled(false); + txtCuales.setWidthFull(); + + masActualizacionesGroup = new RadioButtonGroup<>(); + masActualizacionesGroup.setRequired(true); + masActualizacionesGroup.setLabel("¿Requiere más actualizaciones?"); + masActualizacionesGroup.setItems("Si", "No"); + masActualizacionesGroup.addValueChangeListener(e -> { + if ("Si".equals(e.getValue())) { + txtCuales.setEnabled(true); + txtCuales.setRequired(true); + txtCuales.clear(); + } else { + txtCuales.setEnabled(false); + txtCuales.setRequired(false); + txtCuales.clear(); + } + }); + + txtReparacion = new TextArea("Reparación Realizada:"); + txtReparacion.setWidthFull(); + txtReparacion.setHeight("100px"); + + + HorizontalLayout formasLayout = new HorizontalLayout(); + formasLayout.add(formaGroup, masActualizacionesGroup, txtCuales); + formasLayout.setSizeFull(); + + actualizacionesLayout.add(Titulo, actualizaciones, formasLayout, txtReparacion); + actualizacionesLayout.setSpacing(false); + } + + + private void signLayout() { + VerticalLayout userSignLayout = new VerticalLayout(); + userSignPad = new SignaturePad(); + userSignPad.setBackgroundColor("#FFFFFF"); + userSignPad.setHeight("200px"); + userSignPad.setPenColor("#000000"); + userSignPad.getElement().getStyle().set("border", "1px solid black"); + Span tituloUser = new Span("Usuario Interno"); + userSignLayout.setSizeFull(); + userSignLayout.setSpacing(true); + userSignLayout.setSpacing(false); + userSignLayout.setAlignItems(Alignment.CENTER); + userSignLayout.add(userSignPad, userSignSpan, tituloUser); + + + VerticalLayout smtSignLayout = new VerticalLayout(); + smtSignPad = new SignaturePad(); + smtSignPad.setHeight("200px"); + smtSignPad.setBackgroundColor("#FFFFFF"); + smtSignPad.setPenColor("#000000"); + smtSignPad.getElement().getStyle().set("border", "1px solid black"); + String u = securityService.getAuthenticatedUser(); + Span smtSignSpan = new Span(u); + Span tituloSMT = new Span("Responsable de Soporte"); + smtSignLayout.setSizeFull(); + smtSignLayout.setSpacing(true); + smtSignLayout.setSpacing(false); + smtSignLayout.setAlignItems(Alignment.CENTER); + smtSignLayout.add(smtSignPad, smtSignSpan, tituloSMT); + + VerticalLayout gcialSignLayout = new VerticalLayout(); + Image firmaGcia = new Image("images/FirmaGerenteTI.png", "Firma Gerente de Sistemas"); + firmaGcia.setHeight("200px"); + firmaGcia.setWidthFull(); + Span gciatiSignSpan = new Span("Ing. Javier Patiño Martinez"); + Span tituloGerente = new Span("Gerente de T.I"); + gcialSignLayout.setSizeFull(); + gcialSignLayout.setSpacing(false); + gcialSignLayout.setAlignItems(Alignment.CENTER); + gcialSignLayout.add(firmaGcia, gciatiSignSpan, tituloGerente); + + firmasLayout.add(userSignLayout, smtSignLayout, gcialSignLayout); + firmasLayout.setWidthFull(); + firmasLayout.setSpacing(false); + firmasLayout.setJustifyContentMode(JustifyContentMode.CENTER); + } + + + // Metodo para verificar si la firma corresponde a una cadena de firma vacia + private boolean esFirmaVacia(String firmaBase64) { + + String firmaVacia = "iVBORw0KGgoAAAANSUhEUgAAAXkAAAD8CAYAAACSCdTiAAAIbElEQVR4Xu3UAQ0AIAwDQeZfNCPI+Nwc9Lp07rvjCBAgQCApMEY+2atQBAgQ+AJG3iMQIEAgLGDkw+WKRoAAASPvBwgQIBAWMPLhckUjQICAkfcDBAgQCAsY+XC5ohEgQMDI+wECBAiEBYx8uFzRCBAgYOT9AAEC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Bh5P0CAAIGwgJEPlysaAQIEjLwfIECAQFjAyIfLFY0AAQJG3g8QIEAgLGDkw+WKRoAAASPvBwgQIBAWMPLhckUjQICAkfcDBAgQCAsY+XC5ohEgQMDI+wECBAiEBYx8uFzRCBAgYOT9AAECBMICRj5crmgECBAw8n6AAAECYQEjHy5XNAIECBh5P0CAAIGwgJEPlysaAQIEjLwfIECAQFjAyIfLFY0AAQJG3g8QIEAgLGDkw+WKRoAAASPvBwgQIBAWMPLhckUjQICAkfcDBAgQCAsY+XC5ohEgQMDI+wECBAiEBYx8uFzRCBAgYOT9AAECBMICRj5crmgECBAw8n6AAAECYQEjHy5XNAIECBh5P0CAAIGwgJEPlysaAQIEjLwfIECAQFjAyIfLFY0AAQJG3g8QIEAgLGDkw+WKRoAAASPvBwgQIBAWMPLhckUjQICAkfcDBAgQCAsY+XC5ohEgQMDI+wECBAiEBYx8uFzRCBAgYOT9AAECBMICRj5crmgECBBYAuXtOkIWm1QAAAAASUVORK5CYII="; + return firmaBase64.equals(firmaVacia); + + } + + + private void buttons() { + VerticalLayout buttonsLayout = new VerticalLayout(); + Button btnGuardar = new Button("Guardar", LineAwesomeIcon.SAVE.create()); + btnGuardar.addThemeVariants(ButtonVariant.LUMO_PRIMARY); + btnGuardar.addThemeVariants(ButtonVariant.LUMO_LARGE); + + + btnGuardar.addClickListener(event -> { + fechaSeleccionada = fecha.getValue(); + guardarMantenimiento(); + }); + + buttonsLayout.setSizeFull(); + buttonsLayout.add(btnGuardar); + buttonsLayout.setAlignItems(Alignment.CENTER); + botonesLayout.add(buttonsLayout); + botonesLayout.setSizeFull(); + //botonesLayout.setAlignItems(Alignment.CENTER); + } + + + // METODO PARA ENVIAR CORREOS ELECTRONICOS + private void enviarCorreo() { + Usuario usuarioSeleccionado = usuario.getValue(); + if (usuarioSeleccionado != null && usuarioSeleccionado.getEmail() != null) { + String destinatario = usuarioSeleccionado.getEmail(); + String asunto = "MANTENIMIENTO DE EQUIPO DE COMPUTO REALIZADO"; + + String cuerpo = "" + + "" + + "" + + "" + + ""; + + String imagePath = "META-INF/resources/images/imgCorreo/correoMantt.png"; + + emailService.enviarCorreo(destinatario, asunto, cuerpo, imagePath); + + } else { + Notification.show("Por favor selecciona un usuario", 4000, Notification.Position.MIDDLE); + } + } + + + private void guardarMantenimiento() { + + TiposMantenimiento tiposMantenimiento = tipoMantt.getValue(); + String tipoMantId = tiposMantenimiento != null ? tiposMantenimiento.getTipomantId() : null; + String justificacionValue = jsutificacion != null ? jsutificacion.getValue() : null; + String reparacionValue = txtReparacion != null ? txtReparacion.getValue() : null; + + DepartamentosModel departamentoSeleccionado = area.getValue(); + String departamentoId = departamentoSeleccionado != null ? departamentoSeleccionado.getDepartamentoId().toString() : null; + + Usuario usuarioSeleccionado = usuario.getValue(); + String empleadoId = usuarioSeleccionado != null ? usuarioSeleccionado.getEmpleadoId().toString() : null; + String equipoId = txtNombreEquipo.getValue(); + + String formaSeleccionada = formaGroup.getValue(); + String formaMantt = null; + if ("Remota".equals(formaSeleccionada)) { + formaMantt = "R"; + } else if ("Manual".equals(formaSeleccionada)) { + formaMantt = "M"; + } + + // Validación de campos obligatorios + if (fechaSeleccionada == null || tipoMantId == null || departamentoId == null || empleadoId == null || + equipoId == null || equipoId.trim().isEmpty() || formaMantt == null) { + Notification.show("Por favor, completa todos los campos requeridos", 4000, Notification.Position.MIDDLE); + return; + } + + byte[] userSignatureBytes = userSignPad.getImageBase64(); + byte[] smtSignatureBytes = smtSignPad.getImageBase64(); + //byte[] gciaSignatureBytes = gciatiSignPad.getImageBase64(); + + String userSignatureBase64 = Base64.getEncoder().encodeToString(userSignatureBytes); + String smtSignatureBase64 = Base64.getEncoder().encodeToString(smtSignatureBytes); + //String gciaSignatureBase64 = Base64.getEncoder().encodeToString(gciaSignatureBytes); + + if (esFirmaVacia(userSignatureBase64)) userSignatureBase64 = null; + if (esFirmaVacia(smtSignatureBase64)) smtSignatureBase64 = null; + //if (esFirmaVacia(gciaSignatureBase64)) gciaSignatureBase64 = null; + + + // Validación de campos de hardware + List> detallesHardware = new ArrayList<>(); + for (HorizontalLayout layout : hardwareLayouts) { + ComboBox tipoHardware = (ComboBox) layout.getComponentAt(0); + TextField noSerie = (TextField) layout.getComponentAt(1); + TextField modelo = (TextField) layout.getComponentAt(2); + TextField placa = (TextField) layout.getComponentAt(3); + + TiposHardware tipoSeleccionado = tipoHardware.getValue(); + if (tipoSeleccionado == null) { + Notification.show("Por favor, selecciona un tipo de hardware", 4000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_WARNING); + return; + } + + boolean esOpcional = Arrays.asList("TECLADO", "MOUSE").contains(tipoSeleccionado.getNombreHardware()); + + String numSerie = noSerie.getValue(); + String modeloVal = modelo.getValue(); + String placaVal = placa.getValue(); + + if (!esOpcional && (modeloVal == null || modeloVal.isEmpty() || numSerie == null || numSerie.isEmpty() || placaVal == null || placaVal.isEmpty())) { + Notification.show("Por favor, completa todos los campos de hardware.", 4000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_WARNING); + return; + } + + Map hw = new HashMap<>(); + hw.put("tipoHardwareId", tipoSeleccionado.getTipoHardwareId()); + hw.put("numSerie", numSerie); + hw.put("modelo", modeloVal); + hw.put("placa", placaVal); + detallesHardware.add(hw); + } + + + Set actualizacionesSeleccionadas = actualizaciones.getSelectedItems(); + String otrasActualizaciones = null; + if ("Si".equals(masActualizacionesGroup.getValue())) { + otrasActualizaciones = txtCuales.getValue(); + if (otrasActualizaciones == null || otrasActualizaciones.trim().isEmpty()) { + Notification.show("Especifica las otras actualizaciones", 4000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_WARNING); + return; + } + } + + + // Una vez que validamos todos los campos del formulario, procedemos a insertar en BD + try { + int isInserted = databaseService.insertarMantenimiento(fechaSeleccionada, tipoMantId, departamentoId, empleadoId, formaMantt, equipoId, userSignatureBase64, smtSignatureBase64, null, justificacionValue, reparacionValue); + + if (isInserted <= 0) { + Notification.show("Error al guardar el mantenimiento", 4000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_ERROR); + return; + } + + int mantenimientoId = databaseService.getUltimoMantenimientoId(); + + for (Map hw : detallesHardware) { + boolean ok = databaseService.insertarHardware( + hw.get("tipoHardwareId"), + hw.get("numSerie"), + hw.get("modelo"), + hw.get("placa"), + mantenimientoId + ); + + if (!ok) { + Notification.show("Error al insertar detalles del hardware: ", 4000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_ERROR); + return; + } + } + + for (String act : actualizacionesSeleccionadas) { + boolean ok = databaseService.insertActualizacionSeg(act, null, mantenimientoId); + if (!ok) { + Notification.show("Error al insertar actualización de seguridad", 4000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_ERROR); + return; + } + } + + if (otrasActualizaciones != null) { + boolean ok = databaseService.insertActualizacionSeg("Otras", otrasActualizaciones, mantenimientoId); + if (!ok) { + Notification.show("Error al insertar otras actualizaciones", 4000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_ERROR); + return; + } + } + + // === EXITO === + Notification.show("¡Mantenimiento guardado exitosamente!", 4000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_SUCCESS); + + try { + enviarCorreo(); + } catch (Exception e) { + Notification.show("Error al enviar el correo", 4000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_ERROR); + e.printStackTrace(); + } + + // Limpiar campos + fecha.clear(); + tipoMantt.clear(); + area.clear(); + usuario.clear(); + txtNombreEquipo.clear(); + formaGroup.clear(); + actualizaciones.clear(); + masActualizacionesGroup.clear(); + txtCuales.clear(); + userSignPad.clear(); + smtSignPad.clear(); + //gciatiSignPad.clear(); + txtReparacion.clear(); + + for (HorizontalLayout layout : hardwareLayouts) { + ((ComboBox) layout.getComponentAt(0)).clear(); + ((TextField) layout.getComponentAt(1)).clear(); + ((TextField) layout.getComponentAt(2)).clear(); + ((TextField) layout.getComponentAt(3)).clear(); + } + + UI.getCurrent().navigate("/"); + + } catch (Exception ex) { + Notification.show("Ocurrio un error inesperado: " + ex.getMessage(), 5000, Notification.Position.MIDDLE) + .addThemeVariants(NotificationVariant.LUMO_ERROR); + ex.printStackTrace(); + } + } + + + // Muestra un dialogo con el listado de los mantenimientos correctivos realizados + private void verListadoMantenimientos() { + Dialog dialog = new Dialog(); + dialog.setSizeFull(); + dialog.setCloseOnEsc(true); + dialog.setCloseOnOutsideClick(true); + dialog.setHeaderTitle("Listado de Mantenimientos Correctivos"); + + Grid grid = new Grid<>(MantCorrectivosModel.class, false); + grid.addColumn(MantCorrectivosModel::getMantenimientoId) + .setHeader("No.").setAutoWidth(true); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); + grid.addColumn(item -> item.getFecha() != null ? item.getFecha().format(formatter) : "N/A") + .setHeader("Fecha:").setAutoWidth(true); + + grid.addColumn(MantCorrectivosModel::getTipo) + .setHeader("Tipo:").setAutoWidth(true); + + grid.addColumn(MantCorrectivosModel::getArea) + .setHeader("Área:").setAutoWidth(true); + + grid.addColumn(MantCorrectivosModel::getNombre) + .setHeader("Usuario:").setAutoWidth(true); + + grid.addColumn(MantCorrectivosModel::getForma) + .setHeader("Forma:").setAutoWidth(true); + + grid.addColumn(MantCorrectivosModel::getNomequipo) + .setHeader("Equipo:").setAutoWidth(true); + + grid.setItems(databaseService.getMantenimientosCorrectivos(2)); + grid.setItemDetailsRenderer(ReparacionDetails.createReparacionesDetails()); + grid.addThemeVariants(GridVariant.LUMO_ROW_STRIPES); + + Button closeButton = new Button("Cerrar", e -> dialog.close()); + closeButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY); + + dialog.add(grid, closeButton); + dialog.open(); + } + + private static class ReparacionDetails extends FormLayout { + private final TextArea txtReparacion = new TextArea("Reparación realizada:"); + + public ReparacionDetails() { + txtReparacion.setReadOnly(true); + add(txtReparacion); + setResponsiveSteps(new ResponsiveStep("0", 1)); + setColspan(txtReparacion, 1); + } + + + public void setModel(MantCorrectivosModel model) { + txtReparacion.setValue(model.getReparacion() != null ? model.getReparacion() : ""); + } + + private static ComponentRenderer createReparacionesDetails() { + return new ComponentRenderer<>(ReparacionDetails::new, ReparacionDetails::setModel); + } + } +} \ No newline at end of file diff --git a/src/main/java/mx/gob/jumapacelaya/ui/MantenimientoView.java b/src/main/java/mx/gob/jumapacelaya/ui/MantenimientoView.java index 2b5dd8c..50cffb1 100644 --- a/src/main/java/mx/gob/jumapacelaya/ui/MantenimientoView.java +++ b/src/main/java/mx/gob/jumapacelaya/ui/MantenimientoView.java @@ -156,7 +156,7 @@ public class MantenimientoView extends VerticalLayout implements BeforeEnterObse } else if ("2".equals(tipoSeleccionado.getTipomantId())) { // 2 es para CORRECTIVO this.fecha.clear(); etiquetaLayout.setVisible(true); - correctivoLayout(); + //correctivoLayout(); } else { // Para otros tipos de mantenimiento this.fecha.clear(); @@ -216,7 +216,7 @@ public class MantenimientoView extends VerticalLayout implements BeforeEnterObse createHardwareSection(databaseService); addActualizacionesSection(); - correctivoLayout(); + //correctivoLayout(); signLayout(); buttons(); @@ -397,7 +397,7 @@ public class MantenimientoView extends VerticalLayout implements BeforeEnterObse /* Formulario para cuando el mnatenimiento es de tipo CORRECTIVO */ - private void correctivoLayout() { + /*private void correctivoLayout() { Span Titulo = new Span("Reparación Realizada al Equipo: "); // Verificar el ID del tipo de mantenimiento @@ -436,7 +436,7 @@ public class MantenimientoView extends VerticalLayout implements BeforeEnterObse } else { etiquetaLayout.setVisible(false); // Ocultar si no es correctivo } - } + }*/ @@ -580,6 +580,7 @@ public class MantenimientoView extends VerticalLayout implements BeforeEnterObse String tipoMantId = tiposMantenimiento != null ? tiposMantenimiento.getTipomantId() : null; String planAnualValue = txtPlananualID.getValue(); String justificacionValue = jsutificacion != null ? jsutificacion.getValue() : null; + String reparacionValue = null; DepartamentosModel departamentoSeleccionado = area.getValue(); String departamentoId = departamentoSeleccionado != null ? departamentoSeleccionado.getDepartamentoId().toString() : null; @@ -664,7 +665,7 @@ public class MantenimientoView extends VerticalLayout implements BeforeEnterObse // Una vez que validamos todos los campos del formulario, procedemos a insertar en BD try { - int isInserted = databaseService.insertarMantenimiento(fechaSeleccionada, tipoMantId, departamentoId, empleadoId, formaMantt, equipoId, userSignatureBase64, smtSignatureBase64, planAnualValue, justificacionValue); + int isInserted = databaseService.insertarMantenimiento(fechaSeleccionada, tipoMantId, departamentoId, empleadoId, formaMantt, equipoId, userSignatureBase64, smtSignatureBase64, planAnualValue, justificacionValue, reparacionValue); if (isInserted <= 0) { Notification.show("Error al guardar el mantenimiento", 4000, Notification.Position.MIDDLE)