Compare commits

..

No commits in common. "main" and "develop" have entirely different histories.

152 changed files with 2143 additions and 10230 deletions

View File

@ -1,377 +1,5 @@
# Changelog # Changelog
## [1.26.0] - 2026-11-04
### Added
- **Restricción Declarativa de Comandos de Plugins según Estado de Cliente y SO Activo (`PluginService`, `PluginCommand`)**:
- Incorporadas las propiedades `activeOsOnly`, `excludeClientStatus` y `requireClientStatus` en la interfaz `PluginCommand`.
- La directiva `activeOsOnly: true` exige estrictamente que el equipo esté arrancado y en ejecución en uno de los sistemas operativos declarados en `os` (ej. Windows o Linux), impidiendo que se habiliten comandos de escritorio cuando el cliente se encuentra en entorno de mantenimiento `ogLive` o apagado aunque tenga una partición con dicho SO instalada en disco.
- Soportada exclusión e inclusión explícita por estado del cliente (`excludeClientStatus: ["og-live"]`, etc.) en `isCommandSupportedForClients`.
- En `ExecuteCommandComponent`, evaluado el estado unitario (`clientState`) para garantizar que la disponibilidad de comandos en el menú contextual de cada tarjeta individual responda fielmente al estado en tiempo real.
## [1.25.1] - 2026-11-01
### Refactored
- **Modularización y Optimización de Arquitectura en `PluginService`**:
- Descompuesto el monolito de ~900 líneas en submódulos especializados bajo `src/app/services/plugin/`:
- `plugin.types.ts`: Modelos, interfaces tipadas y estructuras de datos (`PluginCommand`, `RoleDefinition`, `PluginBadgeRule`, `PluginManifest`, etc.).
- `plugin-state.service.ts`: Manejo reactivo del estado dinámico de plugins en memoria, caché de metadatos contextuales y suscripción a eventos en tiempo real vía Mercure (Server-Sent Events).
- `plugin-roles.service.ts`: Comprobación de roles y permisos granulares de usuarios y comandos, jerarquía de acceso y sincronización con `ogCore`.
- `plugin-badge.service.ts`: Resolución desacoplada de badges visuales e internacionalización de tooltips dinámicos con metadatos.
- Eliminada la duplicación completa (~100 líneas) entre `getClientBadges()` y `getPartitionBadges()`, unificando la lógica de interpolación y renderizado en una función auxiliar común (`buildBadge`).
- `PluginService` actúa ahora como una fachada limpia, liviana y 100% retrocompatible (~280 líneas), preservando sin alteraciones todas las firmas públicas y re-exportando los tipos para los componentes consumidores.
## [1.25.0] - 2026-11-01
### Added
- **Restricción Declarativa de Comandos de Plugins según Estado (`PluginService`, `ExecuteCommandComponent`)**:
- Incorporadas las propiedades opcionales `requireStatus` y `excludeStatus` en la interfaz `PluginCommand`, permitiendo a los plugins condicionar la disponibilidad de sus acciones en función del estado actual de los clientes.
- Implementado filtrado reactivo en `isCommandSupportedForClients`: los comandos solo se habilitan si el estado del equipo coincide con los estados requeridos (`requireStatus`) y no figura entre los estados excluidos (`excludeStatus`).
- Si un puesto de acceso libre (Aquarium) se encuentra desactivado (`DISABLED`), las opciones de reserva, liberación y renovación quedan deshabilitadas, permitiendo únicamente la acción de activación.
- Adaptación dinámica de etiqueta en comandos de conmutación de estado (`ogaquarium-toggle-status`): muestra "Activar puesto" o "Desactivar puesto" según el estado actual cuando se selecciona un único equipo.
- Suscripción reactiva a `statusUpdates$` en `ExecuteCommandComponent` para recalcular al instante la disponibilidad de acciones al recibir eventos Mercure en tiempo real.
## [1.24.7] - 2026-10-31
### Refactored
- **Gestión Nativa por Disco y Partición con Contrato Estandarizado en `PluginService`**:
- Eliminada la abstracción innecesaria de `subtarget`, operando directamente con las coordenadas nativas de OpenGnSys (`disk_number` y `partition_number`).
- La interfaz de usuario opera de manera 100% pasiva y desacoplada: es el plugin emisor (backend / listener Mercure / endpoint `/status`) quien suministra explícitamente tanto el estado global del cliente (`client_status` / `clientStatus`) como el estado de cada partición (`status` junto a `disk_number` y `partition_number`).
- Métodos nativos y directos en `PluginService`: `setPartitionPluginStatus`, `getPartitionPluginStatus`, `clearPartitionPluginStatus` y `getPartitionBadges(client, diskNumber, partitionNumber)`.
- Eliminadas las iteraciones o inferencias en `getClientBadges`: el badge general del cliente se consulta directamente en memoria sin realizar bucles de búsqueda sobre particiones ni calcular prioridades arbitrarias.
- Soporte completo de metadatos contextuales en tooltips tanto a nivel general del equipo como a nivel de cada partición individual.
## [1.24.6] - 2026-10-31
### Fixed
- **Desacoplamiento Estricto y Sincronización Agnóstica en `PluginService`**:
- Eliminadas todas las cadenas hardcodeadas de estados específicos de plugins (`['REMOVING', 'CHECKING', 'FREEZING', 'UNFREEZING']`, `'FREE'`, `'UNFROZEN'`).
- Implementada gestión genérica del ciclo de vida de particiones (`handlePartitionClear` y `syncGlobalStatusFromPartitions`): al recibir un estado `NONE` para una partición, se comprueba dinámicamente si al cliente le quedan otras particiones con estado activo; si no queda ninguna, se purga de forma inmediata el estado global en memoria evitando badges fantasma o residuales.
- La resolución de badges a nivel de equipo comprueba directamente contra el catálogo declarado por el plugin en su `manifest.json` (`plugin.badges`), eliminando filtros ad-hoc.
- El guardado y borrado de metadatos se gestiona de forma agnóstica según la presencia efectiva de datos contextuales en el payload.
## [1.24.5] - 2026-10-30
### Added
- **Soporte Genérico de Tooltips Dinámicos (`PluginBadgeRule.tooltipFields`)**:
- Incorporada la especificación declarativa `tooltipFields` en `PluginBadgeRule`, permitiendo a cualquier plugin declarar en su propio manifiesto qué campos de metadatos deben anexarse al tooltip (con `prefix` y `suffix` opcionales).
### Fixed
- **Actualización Reactiva en Tiempo Real y Auto-Conexión Mercure (`PluginService`, `groups.component`)**:
- La recepción de eventos SSE de Mercure en `PluginService` se ejecuta dentro de `NgZone.run()`, emitiendo a través del flujo observable reactivo `statusUpdates$`.
- Suscripción reactiva en `GroupsComponent` a `statusUpdates$`, activando la detección de cambios (`cd.markForCheck(); cd.detectChanges()`) de manera inmediata sin recargar ni salir de la pantalla.
- En `groups.component.html` y `client-details.component.html`, la expresión de seguimiento del control de flujo (`@for`) incorpora el tooltip (`track ... + (badge.tooltip || '')`), forzando la actualización instantánea de `[matTooltip]` en el DOM al cambiar los minutos restantes o datos.
- Auto-conexión garantizada de Mercure en `PluginService`: si la URL de Mercure se resuelve de forma asíncrona tras la carga de la configuración, se conecta de manera transparente al solicitar estados o badges.
### Removed
- **Desacoplamiento Total de Plugins en `PluginService`**:
- Eliminado todo código ad-hoc y variables específicas de dominio (`dni`, `remaining_minutes`, `student`, `user`, etc.) del motor genérico de `PluginService`. `oggui` pasa a ser 100% agnóstico e independiente de los plugins instalados.
- Retirado el temporizador `interval(30000)` en `GroupsComponent`. La arquitectura se mantiene 100% reactiva exclusivamente mediante los eventos push de Mercure (SSE).
## [1.24.1] - 2026-10-30
### Fixed
- **Detección Dinámica de Lenguaje y Resaltado en Editor de Scripts de Plugins (`PluginSettingsComponent`, `PluginService`)**:
- Corregido el badge de cabecera del editor de código en `plugin-settings` que mostraba estáticamente `POWERSHELL` incluso en scripts de Bash/Linux (`#!/bin/bash`).
- Incorporada la propiedad declarativa `language?: string` en `SchemaField` (`PluginService`), permitiendo a los plugins especificar directamente su sintaxis (ej. `bash`, `powershell`, `sh`).
- Detección automática inteligente como respaldo según el atributo `field.language`, el nombre de la clave (`linux`, `bash`, `ps1`, etc.) o el shebang del script (`#!/bin/bash`, `#!/bin/sh`).
- Adaptación contextual del motor de coloreado de sintaxis para comandos (`echo`, `mount`, `losetup`, `update-initramfs`, etc.), palabras clave (`if`, `fi`, `then`, `do`, `done`, etc.) y banderas de Linux (`--bind`, `-o`, etc.).
## [1.24.0] - 2026-10-28
### Added
- **Control de Acceso y Visibilidad de Funciones de Plugins por Rol (`PluginService`, `PluginSettingsComponent`, `ExecuteCommandComponent`)**:
- Incorporada especificación declarativa de roles autorizados (`roles?: string[]`) en la interfaz `PluginCommand`.
- Creada matriz interactiva de permisos en `PluginSettingsComponent` dentro de la nueva subpestaña *"Funciones y Roles"*, permitiendo a los administradores activar o revocar gráficamente el acceso a cada comando expuesto por cualquier plugin para cada rol del sistema.
- Los roles disponibles se extraen dinámicamente desde `ogcore` (`GET /user-groups`), con respaldo seguro en los roles canónicos de OpenGnSys (`ROLE_SUPER_ADMIN`, `ROLE_ORGANIZATIONAL_UNIT_ADMIN`, `ROLE_ORGANIZATIONAL_UNIT_OPERATOR`, `ROLE_ORGANIZATIONAL_UNIT_MINIMAL`).
- La personalización se persiste en la base de datos dentro de `configData.command_roles` de forma 100% desacoplada sin requerir alteraciones en el esquema backend.
- En `PluginService.getPluginGroups()`, los comandos disponibles en los menús de acción (`ExecuteCommandComponent`) se filtran reactivamente en función del rol y permisos del usuario autenticado, ocultando totalmente aquellas opciones que no le correspondan (ej. un conserje con perfil básico solo visualiza Reservar, Liberar y Renovar puesto, permaneciendo invisibles las funciones de instalación o mantenimiento).
- Total adhesión a la sintaxis moderna de control de flujo Angular (`@if`, `@for`) y diseño modular de estilos CSS sin atributos inline.
- Soporte de internacionalización integral (`@ngx-translate`) con catálogos actualizados en español (`es.json`), inglés (`en.json`) y catalán (`cat.json`) para todos los textos, pestañas, cabeceras y notificaciones toast de la configuración de roles.
## [1.23.0] - 2026-10-27
### Added
- **Enriquecimiento Contextual de Tooltips en Badges de Plugins (`PluginService`, `groups.component`)**:
- Incorporada caché reactiva de metadatos de clientes (`clientPluginMetadataMap`) en `PluginService`, extrayendo automáticamente atributos contextuales proporcionados por cualquier plugin tanto en la consulta inicial (`statusEndpoint`) como en las actualizaciones en tiempo real recibidas por Mercure.
- Al renderizar los badges (`getClientBadges`), si existen atributos contextuales como el identificador del alumno/usuario (`dni`, `user`) y el tiempo restante (`remaining_minutes`, `remainingMinutes`), se añaden dinámicamente al texto del tooltip (ej. `"Puesto reservado y en uso (DNI: 44212977P · 58 min restantes)"`), preservando el badge visualmente limpio y compacto (`Ocupado`, `A punto de expirar`).
- Limpieza automática y atómica de metadatos cuando el puesto queda libre (`FREE`) o se reinicia (`NONE`), manteniendo sincronizada la consola web en todo momento sin acoplamiento a ningún plugin en concreto.
## [1.22.0] - 2026-10-27
### Added
- **Diálogos Dinámicos de Parámetros y Confirmación en Comandos de Plugins (`PluginCommandModalComponent`, `ExecuteCommandComponent`)**:
- Incorporada especificación de parámetros interactivos (`params?: CommandParam[]`) y mensajes de confirmación (`confirm?: string; confirmKey?: string`) en la interfaz declarativa `PluginCommand`.
- Creado el componente modal genérico `PluginCommandModalComponent` que renderiza dinámicamente formularios reactivos con soporte para campos de texto, números, selectores y conmutadores (`checkbox`), respetando validaciones de obligatoriedad (`required`) e internacionalización con `@ngx-translate`.
- En `ExecuteCommandComponent`, al disparar un comando de cualquier plugin que requiera parámetros o confirmación, se abre automáticamente el modal interactivo, inyectando los valores resultantes en el cuerpo de la petición POST enviada al endpoint del plugin de forma 100% desacoplada.
- Total adhesión a la sintaxis moderna de control de flujo Angular (`@if`, `@for`, `@switch`) y separación estricta de estilos sin atributos inline.
## [1.21.1] - 2026-10-27
### Fixed
- **Desacoplamiento Total y Agnóstico en Plugins (`PluginService`, `PluginSettingsComponent`)**:
- Eliminado cualquier acoplamiento o referencia estática a nombres de plugins en la consola web (`PluginSettingsComponent`, `PluginService` y catálogos globales `locale/*.json`).
- El sistema opera de forma 100% agnóstica y dinámica: la presencia de la sub-pestaña "Historial y Registros" responde exclusivamente a la declaración de `recordsEndpoint` en el manifiesto de cualquier plugin.
- La internacionalización de plugins se carga dinámicamente en caliente mediante `@ngx-translate` consultando el endpoint `/i18n/{lang}` de cada plugin, respetando la estructura estándar de namespaces anidados como en `ogfreeze`.
## [1.21.0] - 2026-10-26
### Added
- **Sub-pestaña Genérica de Historial y Registros en Plugins (`PluginManifest`, `PluginSettingsComponent`)**:
- Incorporado soporte en `PluginManifest` para `recordsEndpoint` y `recordsColumns` (`RecordColumn`), permitiendo a cualquier plugin declarar un origen de datos tabular desacoplado.
- Añadido selector de sub-pestañas en `plugin-settings` para alternar entre "Configuración" e "Historial y Registros".
- Vista de registros completa con buscador en tiempo real (por DNI, puesto o aula), ordenación cronológica, paginación reactiva y contador de resultados.
- Soporte de exportación a archivo CSV con descarga directa desde backend (`${recordsEndpoint}/export`) y fallback automático de generación en cliente con BOM UTF-8 para compatibilidad universal.
- Renderizado adaptativo de celdas con soporte de badges semánticos para identificadores (DNI), duraciones y motivos de cierre de sesión (`TIMEOUT`, `RELEASED_BY_CONCIERGE`, `DISABLED_BY_ADMIN`).
- Total adhesión a la sintaxis moderna de control de flujo Angular (`@if`, `@for`, `@switch`) y estilos reutilizables sin atributos inline.
## [1.20.0] - 2026-10-26
### Added
- **Soporte de Estados y Badges a Nivel de Partición en Plugins (`PluginService`, `groups.component`)**:
- Incorporada gestión granular de estados por partición (`${plugin}:${clientId}:${disk}:${partition}`).
- En eventos Mercure con `status === 'NONE'` en una partición específica, se limpia la clave de la partición y cualquier estado transitorio global obsoleto (`REMOVING`, `CHECKING`, etc.), permitiendo que `getClientBadges` evalúe de inmediato y preserve el badge activo de cualquier otra partición protegida del equipo.
- Soporte de invalidación granular por disco y partición en eventos de imagen y particionado.
## [1.19.0] - 2026-10-23
### Added
- **Activación y Desactivación Dinámica de Plugins (`PluginService`, `plugins.component`, `plugin-settings.component`)**:
- Incorporada la capacidad de activar y desactivar plugins en caliente sin desinstalarlos del sistema.
- Al desactivar un plugin, sus comandos contextuales y badges se ocultan automáticamente de las tarjetas y menús de clientes en toda la consola web, preservando íntegra su configuración en base de datos.
- En la vista de administración `/plugins`, se integró un interruptor deslizante (`mat-slide-toggle`) en la cabecera de configuración para conmutar entre `Activo` e `Inactivo` con notificación toast y actualización reactiva.
- Añadido indicador visual de estado y conteo en la cabecera del panel (`X Activo(s) / Y Instalado(s)`) y badge `Inactivo` en las pestañas de los plugins deshabilitados.
## [1.18.0] - 2026-10-23
### Added
- **Desacoplamiento Total de Plugins y Eventos Mercure (`PluginService`, `groups.component`, `execute-command.component`)**:
- `PluginService`: Suscripción dinámica y agnóstica al topic genérico de Mercure `plugins`, procesando eventos de cualquier plugin de forma desacoplada y actualizando el estado de los clientes en tiempo real sin hardcoding.
- Consulta agnóstica de endpoints de estado (`statusEndpoint`) y reglas de badges (`badges`) declaradas dinámicamente en los manifiestos de los plugins.
- Inferencia dinámica de badges contextuales en clientes (`getClientBadges`) mapeados directamente desde la especificación `badges` del manifiesto del plugin.
- Limpieza de estilos en `groups.component.css`, adoptando clases semánticas universales (`.badge-info`, `.badge-neutral`, `.badge-pending`, `.badge-error`, `.badge-success`, `.badge-warning`).
- **Sistema Estandarizado de Internacionalización Dinámica de Plugins (`PluginService`, `plugins.component`, `plugin-settings.component`, `execute-command.component`)**:
- Incorporada la carga e inyección en caliente de traducciones (`i18n`) desde el endpoint `/api/plugins/{name}/i18n/{lang}` de cada plugin directamente en `@ngx-translate`, sin necesidad de alterar los ficheros de idioma en disco ni requerir recompilación.
- Soporte completo para claves semánticas (`titleKey`, `descriptionKey`, `labelKey`, `tooltipKey`) en comandos, badges y formularios de configuración de plugins, con reactividad automática ante el cambio de idioma en la cabecera.
## [1.17.2] - 2026-10-22
### Revert
- **Cancelación de Tareas (`task-logs.component`)**:
- Revertida la modificación temporal que permitía seleccionar y cancelar trazas en estado `Enviado` (`sent`). Se mantiene la regla del sistema que solo permite seleccionar y cancelar trazas en estado `pending` o `in-progress`.
## [1.17.0] - 2026-10-22
### Added
- **Encolado Inteligente por Sistema Operativo Destino (`execute-command.component`)**:
- Al ejecutar comandos de plugins específicos de un sistema operativo (como `ogfreeze` para Windows), si hay equipos apagados, desconectados o actualmente iniciados en un SO diferente (ej. `og-live`), se ofrece la confirmación de encolado (`QueueConfirmationModalComponent`) enviando el metadato `target_os`.
- La tarea encolada esperará de forma segura en `ogcore` a que el equipo arranque en el sistema operativo compatible antes de ser despachada.
## [1.16.0] - 2026-10-22
### Added
- **Soporte Dinámico para Plugins (`PluginService`, `PluginsComponent`, `PluginSettingsComponent`)**:
- Incorporada infraestructura agnóstica para descubrimiento y gestión de plugins desacoplados a través de `/api/plugins`.
- Agrupación ordenada de comandos de plugins en submenús dedicados en la consola de comandos (`execute-command`), organizados por plugin para mantener el menú limpio.
- Comprobación y filtrado dinámico de compatibilidad por Sistema Operativo (`os: ['windows']`), deshabilitando automáticamente los comandos en puestos con sistemas incompatibles.
- Estándar de Contrato y Acciones de Campos para Plugins (`PluginSettingsComponent`): Incorporado soporte para acciones declarativas por campo (`field.action`) ejecutadas contra el backend del plugin mediante el contrato estándar `{ config: ... }` -> `{ data: { [key]: value }, message: "..." }`. Los botones de asistencia (como la generación de scripts) se integran directamente en la cabecera de la caja del script y la lógica reside 100% en el backend del plugin, manteniendo el núcleo de `oggui` completamente agnóstico y desacoplado.
- Soporte de insignias de estado (badges) contextuales por cliente en las vistas de mosaico y lista de equipos (`groups.component`).
- Nuevo elemento condicional "Plugins" en el menú lateral (`sidebar`), visible únicamente cuando existen plugins activos en el sistema.
- Resaltador de sintaxis enriquecido y visor de terminal para scripts de configuración con numeración de líneas, colores semánticos (comentarios en verde itálica, comandos, parámetros, cadenas), botón de copiado rápido y alternancia entre vista coloreada y editor manual.
- Comportamiento 100% neutro e idéntico a 1.15.0 si no hay plugins instalados.
### Fixed
- **Recarga de página en Plugins (`plugins.component`, `plugin-settings.component`)**: Corregido el problema de sincronización reactiva al refrescar directamente (F5) la vista de `/plugins`, añadiendo un estado de carga visual y suscripción a `plugins$` para evitar mostrar prematuramente la pantalla de "No hay plugins instalados".
- **Rutas excluidas vacías en ogfreeze (`plugin-settings.component`)**: Corregida la regeneración de scripts cuando el campo de rutas excluidas se deja intencionadamente en blanco; ahora omite de forma limpia el bloque de exclusiones en lugar de forzar los valores predeterminados.
- **Ejecución y Validación de Comandos de Plugins (`execute-command.component`)**: Implementado el envío HTTP real de las órdenes de plugins (`POST /api/plugins/...`), validación de estado del SO activo (aviso si están ejecutando Linux u og-live cuando se requiere Windows) y diálogo de confirmación de encolado (`QueueConfirmationModalComponent`) cuando los equipos seleccionados se encuentran apagados o desconectados.
## [1.15.0] - 2026-10-20
### Added
- **Ejecución y Encolado Automático en Clientes Offline (`execute-command`, `boot-so-partition`, `queue-confirmation-modal`)**:
- Permitida la ejecución de comandos y scripts (incluyendo inicio de sesión en partición / arranque de SO) sobre equipos apagados o grupos con estados mixtos.
- El modal de confirmación detecta automáticamente equipos apagados o estados no ejecutables de inmediato, pre-seleccionando la opción de encolado y mostrando avisos visuales informativos (disponible en ES, EN y CA).
- Unificada y estandarizada la matriz de estados de todos los comandos en la consola de comandos.
### Fixed
- **Selección de Clientes en Unidades Organizativas (`groups.component.html`)**: Solucionado el problema al invocar comandos o tareas desde el menú contextual de un Aula / OU donde solo se seleccionaban los equipos mostrados en la página actual de la tabla en lugar de todos los clientes pertenecientes a la OU.
### Changed
- **Refactorización Angular (`boot-so-partition`)**: Migradas directivas estructurales (`*ngIf`, `*ngFor`) a la sintaxis moderna de control de flujo (`@if`, `@for`) y extraídos los estilos inline a clases CSS reutilizables.
## [1.14.4] - 2026-10-09
### Fixed
- **UI/UX (Componentes Genéricos)**: Solucionado un error en los componentes de añadir equipos a una subred (`add-clients-to-subnet`) y configuración de ficheros de arranque PXE (`pxe-boot-files`) introducido en versiones previas. Estos componentes enviaban un identificador URI (ej. `/organizational-units/uuid`) o el propio UUID en sus peticiones de búsqueda (GET) en lugar del ID numérico esperado por la base de datos (Doctrine), lo que impedía listar los equipos de las aulas seleccionadas. Ahora resuelven correctamente el ID numérico de la unidad seleccionada antes de realizar la petición al backend.
## [1.14.3] - 2026-10-09
### Fixed
- **UI/UX (Componentes Genéricos)**: Solucionado un problema de regresión introducido en la versión 1.14.2 donde múltiples componentes de creación y edición (Crear/Editar Tarea, Usuarios, Aula, Cliente, Crear Múltiples Clientes y Mover Clientes) enviaban un identificador numérico en el payload en lugar del identificador URI (`@id`) esperado por el backend para las relaciones de `organizationalUnit`, provocando errores al intentar guardar. Ahora, estos componentes detectan automáticamente el identificador devuelto por el selector genérico y construyen la URI correcta antes de realizar la petición HTTP.
## [1.14.2] - 2026-10-06
### Fixed
- **UI/UX (Componentes Genéricos)**: Refactorizado el comportamiento de `app-ou-select` para que devuelva siempre el identificador URI (`@id`) de la unidad organizativa en lugar de su ID numérico. Esto corrige varios errores críticos en cadena (como el error al mover clientes) provocados porque la API de Symfony (API Platform) requiere referencias URI (`/api/organizational_units/X`) para mapear entidades relacionales, en vez de identificadores enteros puros. Adicionalmente, el componente de mover clientes se ha hecho más robusto para prevenir envíos mal formateados.
## [1.14.1] - 2026-10-06
### Fixed
- **DHCP Subnets**: Solucionado un error al añadir equipos a una subred donde la petición al servidor enviaba la unidad organizativa como "undefined", impidiendo listar los equipos del aula seleccionada.
## [1.14.0] - 2026-10-05
### Added
- **UI/UX**: Añadido buscador en todos los desplegables de selección de Unidad Organizativa gracias al nuevo componente reutilizable `OuSelectComponent`.
### Changed
- **UI/UX**: Estandarizada la selección de Unidades Organizativas en toda la consola para mostrar de forma consistente la ruta jerárquica (breadcrumb) del elemento.
- **Refactor**: Extraída la lógica de selección de Unidades Organizativas a un componente genérico (`OuSelectComponent`) para cumplir con el principio DRY.
- **Refactor**: Migrada la sintaxis de plantillas (directivas estructurales `*ngIf`, `*ngFor`, `*ngSwitch`) a la nueva sintaxis de control de flujo de Angular 18 (`@if`, `@for`, `@switch`) en los componentes afectados por la refactorización.
## [1.13.0] - 2026-10-02
### Added
- **RemotePC**: Añadido un botón deslizable (toggle) en el panel de configuración de Unidades Organizativas (aulas) para habilitar el reinicio de equipos en lugar de apagado cuando son liberados por UDS.
### Fixed
- **UI/UX**: Solucionado un error de compilación y renderizado en `partition-assistant.component.css` causado por la inserción involuntaria de caracteres nulos (UTF-16) ocultos en el código fuente.
## [1.12.0] - 2026-09-30
### Added
- **UI/UX**: Implementada persistencia en localStorage para el ancho del panel lateral del árbol de jerarquías, individualizada por usuario.
- **RemotePC**: Añadida la insignia indicadora de conexión remota en la vista de lista (tabla) de clientes para unificar la experiencia con la vista de tarjetas.
### Changed
- **UI/UX**: Refinados los estilos visuales de la insignia de RemotePC (colores sutiles, bordes redondeados y tamaño reducido) para armonizar con el resto de etiquetas (ej: velocidad de red).
## [1.11.1] - 2026-09-24
### Fixed
- **UI Layout**: Corregido el problema de desbordamiento de barras de desplazamiento (scrollbars) globales forzando un diseño con flexbox en el layout principal de los clientes.
- **Jerarquía de Unidades Organizativas**: Se ha reemplazado la visualización del "padre inmediato" por una ruta recursiva completa (ej: Sede / Edificio / Planta / Aula) en los desplegables de aulas de ogDHCP y ogBoot.
- **Auto-selección de PXE**: Al elegir una partición destino en la ventana de "Despliegue de Imagen" y seleccionar "Cambiar Plantilla PXE", el sistema auto-seleccionará automáticamente la plantilla correspondiente al disco y partición (ej: `firstDisk_firstPartition`).
## [1.11.0] - 2026-09-23
### Added
- **Desplegar Imagen**: Añadidas acciones post-despliegue ("Iniciar Sistema Restaurado" y "Seleccionar Plantilla PXE") que permiten encadenar comandos de configuración de inicio y reinicio directamente tras programar el despliegue.
- **Preferencias de Usuario**: Las opciones elegidas para el despliegue (acción post-despliegue y tipo de PXE) se persisten automáticamente en el navegador de manera segura e individual por usuario.
## [1.10.2] - 2026-09-22
### Fixed
- **Crear/Desplegar Imagen**: Eliminada la dirección IP del listado de repositorios en los selectores de despliegue, mostrando únicamente el nombre del repositorio.
## [1.10.1] - 2026-09-18
### Fixed
- **Editor de Menús**: Corregida la previsualización del diseño HTML en entornos con proxy inverso (Nginx). Se delega la resolución de los 'assets' al backend proporcionándole el `baseUrl` completo, asegurando que las imágenes de los iconos se carguen correctamente tanto en la "Vista Global" como al previsualizar desde "Editar HTML".
## [1.10.0] - 2026-09-17
### Added
- **Permisos de Operador (ou-operator)**:
- Añadido permiso explícito para que los operadores de aula puedan ejecutar el comando `createImage`.
- Restringida la creación de nuevas unidades organizativas de tipo "Centro" para los usuarios con rol de operador.
## [1.9.0] - 2026-09-17
### Added
- **Visualización y Estructura Organizativa**:
- Implementados diferentes colores para las etiquetas de velocidad de las tarjetas de red en la vista de equipos, facilitando su identificación visual.
- Añadido un botón de búsqueda interactivo en el árbol organizativo (OUs) que permite ocultar/mostrar los campos de búsqueda para ahorrar espacio visual en pantalla.
- Componentes `pxe-boot-files` y `add-clients-to-subnet`: Añadido buscador en los menús desplegables (dropdowns) de selección de unidades organizativas y aulas, facilitando la búsqueda en jerarquías grandes.
- **Creación de Imágenes**:
- Permitida la creación de imágenes (`createImage`) a partir de particiones de datos que no contienen Sistema Operativo (Data partitions).
### Changed
- Refactorización de plantillas HTML en `groups`, `pxe-boot-files` y `add-clients-to-subnet` para migrar de directivas estructurales legacy (`*ngIf`, `*ngFor`) a la nueva sintaxis de control de flujo de Angular (`@if`, `@for`).
## [1.8.3] - 2026-07-31
### Added
- Inventario Hardware: Añadida visualización gráfica en la interfaz web para los nuevos campos reportados por los clientes.
- Las vistas "Tarjeta" y "Lista" de equipos muestran ahora un indicador ('badge') con la velocidad de la interfaz de red (ej. 1000 Mbps).
- El Asistente de Particionado muestra el tipo de disco físico ('SATA', 'NVMe', 'USB', etc.) junto al nombre del disco.
## [1.8.2] - 2026-07-27
### Added
- Task Logs (`task-logs.component`): Consume `output` and `finishedAt` properties from Mercure events to update trace outputs in real-time without reloading the page.
### Fixed
- Creación de imágenes (`create-image.component`): Al seleccionar la acción "Actualizar Imagen", ahora se filtran correctamente las imágenes para mostrar solo aquellas que pertenecen al repositorio objetivo asignado al cliente.
- Menú de opciones de cliente (`groups.component.html`): Unificado el menú de acciones (tres puntos verticales) usando `matMenuContent`. Se elimina la duplicidad de código que causaba divergencias de comportamiento entre la vista tarjeta y la vista lista. Ahora la opción de "Logs en tiempo real" está siempre disponible en ambas vistas, al igual que los bloqueos al sincronizar.
- Detalles de tareas (`OutputDialogComponent`): Ampliado el ancho de la ventana modal de detalles a `70vw` para facilitar la lectura de trazas largas y comandos de OGAgent/OGLive.
- Repositorios Git (`show-git-images.component`): Corregido el cierre abrupto de la ventana modal al borrar un repositorio. Ahora, la interfaz recarga la lista de repositorios, permitiendo seguir operando sin tener que volver a abrir el gestor.
## [1.8.1] - 2026-07-17
### Added
- Formulario de despliegue (`Deploy Image`): Añadido selector de repositorio origen (OG Repository) al menú de despliegue para permitir al usuario elegir desde dónde descargar la imagen.
### Changed
- Modal de partición de arranque (`boot-so-partition`): Refactorizado para usar el componente compartido `app-disk-partition-selector`, eliminando código duplicado y unificando el diseño y comportamiento de la selección de discos y particiones con el resto de modales.
### Fixed
- Detalles de tareas (`OutputDialogComponent`): Corregido el formateo de los detalles mostrados desde los agentes (OGAgent) para renderizar el texto en crudo manteniendo los saltos de línea (usando pre-wrap por CSS y <pre> tag), y dándole formato monoespaciado en lugar de intentar forzar un parseo estricto JSON que rompía la salida de comandos.
- Formulario de despliegue (`Deploy Image`): Solucionado el problema que ocultaba las comandos (instructions) cuando el despliegue era en modo caché. El código ha sido refactorizado y limpiado usando directivas estructurales estándar de Angular (`*ngIf`, `*ngFor`).
- Roles: Permisos actualizados en vistas para reflejar recientes cambios de backend en la gestión de perfiles de software.
## [1.8.0] - 2026-06-16
### Added
- Sistema de permisos por rol en la interfaz gráfica para los cuatro perfiles:
`ROLE_SUPER_ADMIN`, `ROLE_ORGANIZATIONAL_UNIT_ADMIN`,
`ROLE_ORGANIZATIONAL_UNIT_OPERATOR` y `ROLE_ORGANIZATIONAL_UNIT_MINIMAL`.
- `roleGuard`: protección de rutas según rol; ou-operator accede a operaciones
de equipos (despliegue, particionado, scripts, imagen); ou-minimal y
ou-operator son redirigidos a `/groups` si intentan acceder a rutas de
administración.
- Botones de creación/edición de infraestructura (DHCP, Boot servers,
repositorios, comandos) ocultos para ou-admin con `*ngIf`.
- Botones de creación de OU y cliente ocultos para ou-operator y ou-minimal.
- Tests unitarios de permisos: `auth.service.spec.ts` (5 roles × métodos de
rol), `role.guard.spec.ts` (matriz 26 rutas × 4 roles),
`sidebar.component.spec.ts` (visibilidad de ítems por rol).
- Infraestructura E2E con Playwright: `playwright.config.ts`, helpers de
autenticación y API, y 4 specs de permisos (super-admin, ou-admin,
ou-operator, ou-minimal) que verifican sidebar, rutas y botones.
- Botón de cerrar en la ventana de plano de aula.
### Improved
- La petición de equipos al hacer clic en un aula y la actualización de su
estado se ejecutan de forma secuencial en lugar de en paralelo, evitando
el loader general mientras se resuelven los estados individuales.
- Ficheros de idiomas (es, en, cat) ordenados alfabéticamente; revisión
completa del fichero catalán.
## [1.7.0] - 2026-05-14
### Added
- Visor de logs de disco en las páginas de estado de ogcore, ogboot, ogdhcp
y ogrepository: muestra entries del journal en tiempo real sin necesidad
de oglog/OpenSearch, con polling cada 5 segundos y modo live/pausa
- Soporte de múltiples `SYSLOG_IDENTIFIER` por componente: ogdhcp incluye
kea, ogrepository incluye samba, ogboot incluye tftpd-hpa
- Host basado en IP del servidor seleccionado para lectura del fichero de
journal remoto (`/var/log/journal/remote/<IP>.journal`)
### Changed
- `StatusLogsComponent`: `@Input() identifier` reemplazado por
`@Input() identifiers: string[]`; respuesta parseada como array de entries
JSON estructurados con formato `[timestamp] IDENTIFIER: mensaje`
## [1.6.1] - 2026-05-14
### Improved
- Modificada recepcion de mensajes de mercure durante la importación
## [1.6.0] - 2026-05-08
### Added
- Añadida opción en Administración para importar una base de datos OG 1.1 en la nueva version. Permite subir fichero .sql o .zip o usar parametros de conexión a la base de datos de OG 1.1
## [1.5.9] - 2026-05-07 ## [1.5.9] - 2026-05-07
### Fixed ### Fixed
- Asistente de particionado: en discos GPT se elimina el límite de 4 particiones primarias, se oculta la opción de añadir partición lógica/extendida y se suprime el estilo visual de partición lógica (borde amarillo e icono └) - Asistente de particionado: en discos GPT se elimina el límite de 4 particiones primarias, se oculta la opción de añadir partición lógica/extendida y se suprime el estilo visual de partición lógica (borde amarillo e icono └)
@ -802,4 +430,3 @@
### Fixed ### Fixed
- Resolved an issue that prevented editing software profiles correctly. - Resolved an issue that prevented editing software profiles correctly.
- Fixed a bug where newly created commands failed to execute in the commands section. - Fixed a bug where newly created commands failed to execute in the commands section.

View File

@ -61,19 +61,6 @@ pipeline {
} }
} }
stage('Generate Changelog (Devel)') {
when {
branch 'devel'
}
steps {
script {
def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME
def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL
generateDebianChangelog(env.BUILD_DIR, devName, devEmail, "devel")
}
}
}
stage('Build') { stage('Build') {
steps { steps {
@ -110,23 +97,11 @@ pipeline {
} }
} }
} }
stage ('Publish to Debian Repository (Devel)') {
when {
branch 'devel'
}
agent { label 'debian-repo' }
steps {
script {
def versionPattern = "-${env.BUILD_NUMBER}~devel"
publicarEnAptly('/var/tmp/opengnsys/debian-repo/oggui', 'devel', versionPattern)
}
}
}
} }
post { post {
success { success {
script { script {
// Solo lanzar cuando el build sea exitoso y en la rama main
if (env.BRANCH_NAME == 'main') { if (env.BRANCH_NAME == 'main') {
build job: 'Aptly publish nightly repository', build job: 'Aptly publish nightly repository',
wait: false, wait: false,
@ -134,14 +109,8 @@ pipeline {
string(name: 'TRIGGERED_BY', value: "${env.JOB_NAME}-${env.BUILD_NUMBER}") string(name: 'TRIGGERED_BY', value: "${env.JOB_NAME}-${env.BUILD_NUMBER}")
] ]
} }
if (env.BRANCH_NAME == 'devel') {
build job: 'Aptly publish develop repository',
wait: false,
parameters: [
string(name: 'TRIGGERED_BY', value: "${env.JOB_NAME}-${env.BUILD_NUMBER}")
]
}
} }
} }
always { always {
notifyBuildStatus('opengnsys@qindel.com') notifyBuildStatus('opengnsys@qindel.com')

View File

@ -43,5 +43,3 @@ Thumbs.db
test-results/ test-results/
.e2e-state.json
playwright-report/

View File

@ -1,7 +0,0 @@
import { setupTestUsers } from './helpers/api';
export default async function globalSetup() {
console.log('\n▶ E2E — creando usuarios de test...');
await setupTestUsers();
console.log(' ✓ Setup completado\n');
}

View File

@ -1,7 +0,0 @@
import { teardownTestUsers } from './helpers/api';
export default async function globalTeardown() {
console.log('\n▶ E2E — eliminando usuarios de test...');
await teardownTestUsers();
console.log(' ✓ Teardown completado\n');
}

View File

@ -1,139 +0,0 @@
/**
* Helpers para crear y borrar usuarios de test vía la API de ogCore.
* Se usan en globalSetup / globalTeardown de Playwright.
*/
import { Agent } from 'undici';
import * as fs from 'fs';
import * as path from 'path';
export const API_URL = process.env['API_URL'] || 'https://ogserver.local/api';
export const APP_URL = process.env['APP_URL'] || 'https://localhost:4200/oggui';
export const ADMIN_USER = process.env['ADMIN_USER'] || 'ogadmin';
export const ADMIN_PASS = process.env['ADMIN_PASS'] || '12345678';
export const TEST_PASS = 'Test1234!';
// Nombres fijos — sin timestamp para que sean consistentes entre procesos
export const TEST_USERS = {
superAdmin: { username: 'e2e-superadmin', role: 'ROLE_SUPER_ADMIN' },
ouAdmin: { username: 'e2e-ouadmin', role: 'ROLE_ORGANIZATIONAL_UNIT_ADMIN' },
operator: { username: 'e2e-operator', role: 'ROLE_ORGANIZATIONAL_UNIT_OPERATOR' },
minimal: { username: 'e2e-minimal', role: 'ROLE_ORGANIZATIONAL_UNIT_MINIMAL' },
};
// Fichero temporal para pasar IRIs del setup al teardown
const STATE_FILE = path.join(__dirname, '../../.e2e-state.json');
// undici Agent que ignora certificados autofirmados (equivalente a curl -k)
const insecureAgent = new Agent({ connect: { rejectUnauthorized: false } });
async function fetchJson(url: string, init: RequestInit): Promise<any> {
const res = await fetch(url, {
...init,
headers: { 'Content-Type': 'application/ld+json', ...(init.headers as any) },
dispatcher: insecureAgent,
} as any);
const text = await res.text();
try { return JSON.parse(text); } catch { return text; }
}
export async function getAdminToken(): Promise<string> {
const data = await fetchJson(`${API_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: ADMIN_USER, password: ADMIN_PASS }),
});
if (!data.token) throw new Error(`Login fallido: ${JSON.stringify(data)}`);
return data.token;
}
async function findUserByUsername(token: string, username: string): Promise<string | null> {
const data = await fetchJson(`${API_URL}/users?username=${encodeURIComponent(username)}`, {
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
});
const members = data['hydra:member'] ?? [];
return members.length > 0 ? members[0]['@id'] : null;
}
async function findUserGroupByName(token: string, name: string): Promise<string | null> {
const data = await fetchJson(`${API_URL}/user-groups?name=${encodeURIComponent(name)}`, {
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
});
const members = data['hydra:member'] ?? [];
return members.length > 0 ? members[0]['@id'] : null;
}
async function deleteResource(token: string, iri: string): Promise<void> {
await fetch(`${API_URL.replace('/api', '')}${iri}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` },
dispatcher: insecureAgent,
} as any);
}
async function createUserGroup(token: string, role: string, name: string): Promise<string> {
const data = await fetchJson(`${API_URL}/user-groups`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify({ name, permissions: [role], enabled: true }),
});
if (!data['@id']) throw new Error(`No se pudo crear UserGroup ${name}: ${JSON.stringify(data)}`);
return data['@id'];
}
async function createUser(token: string, username: string, ugIri: string): Promise<string> {
const data = await fetchJson(`${API_URL}/users`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify({ username, password: TEST_PASS, enabled: true, userGroups: [ugIri] }),
});
if (!data['@id']) throw new Error(`No se pudo crear usuario ${username}: ${JSON.stringify(data)}`);
return data['@id'];
}
export async function setupTestUsers(): Promise<void> {
const token = await getAdminToken();
const userIris: string[] = [];
const ugIris: string[] = [];
for (const { username, role } of Object.values(TEST_USERS)) {
const ugName = `e2e-ug-${username}`;
// Eliminar usuario previo si existe (limpia runs anteriores)
const existingUser = await findUserByUsername(token, username);
if (existingUser) {
await deleteResource(token, existingUser);
console.log(` ↺ Eliminado usuario previo: ${username}`);
}
// Eliminar UserGroup previo si existe
const existingUg = await findUserGroupByName(token, ugName);
if (existingUg) {
await deleteResource(token, existingUg);
}
const ugIri = await createUserGroup(token, role, ugName);
const userIri = await createUser(token, username, ugIri);
ugIris.push(ugIri);
userIris.push(userIri);
console.log(` ✓ ${username} [${role}]`);
}
// Guarda IRIs en fichero para que teardown pueda leerlos (env vars no siempre pasan entre procesos)
fs.writeFileSync(STATE_FILE, JSON.stringify({ userIris, ugIris }, null, 2));
}
export async function teardownTestUsers(): Promise<void> {
if (!fs.existsSync(STATE_FILE)) return;
const { userIris, ugIris } = JSON.parse(fs.readFileSync(STATE_FILE, 'utf-8'));
const token = await getAdminToken();
for (const iri of [...userIris, ...ugIris]) {
await deleteResource(token, iri);
console.log(` ✓ Eliminado: ${iri}`);
}
fs.unlinkSync(STATE_FILE);
}

View File

@ -1,39 +0,0 @@
import { Page, expect } from '@playwright/test';
import { APP_URL, TEST_PASS, TEST_USERS } from './api';
export type Role = keyof typeof TEST_USERS;
/**
* Hace login en la GUI con el usuario de test del rol indicado.
* Espera a que la redirección post-login termine (URL cambia a /groups).
*/
export async function loginAs(page: Page, role: Role): Promise<void> {
const { username } = TEST_USERS[role];
await page.goto(`${APP_URL}/auth/login`);
await page.locator('input[name="username"]').fill(username);
await page.locator('input[name="password"]').fill(TEST_PASS);
await page.locator('button[type="submit"]').click();
await expect(page).toHaveURL(/\/groups/, { timeout: 10_000 });
}
/**
* Navega a una ruta y devuelve la URL final (útil para comprobar redirecciones).
*/
export async function navigateTo(page: Page, path: string): Promise<string> {
await page.goto(`${APP_URL}${path}`);
await page.waitForLoadState('networkidle');
return page.url();
}
/** Comprueba que un enlace del sidebar ES visible */
export async function expectSidebarLink(page: Page, routerLink: string, visible: true): Promise<void>;
/** Comprueba que un enlace del sidebar NO está en el DOM */
export async function expectSidebarLink(page: Page, routerLink: string, visible: false): Promise<void>;
export async function expectSidebarLink(page: Page, routerLink: string, visible: boolean): Promise<void> {
const locator = page.locator(`[routerLink="${routerLink}"], a[href="${routerLink}"]`).first();
if (visible) {
await expect(locator).toBeVisible({ timeout: 5_000 });
} else {
await expect(locator).not.toBeAttached({ timeout: 5_000 });
}
}

View File

@ -1,75 +0,0 @@
import { test, expect } from '@playwright/test';
import { loginAs, navigateTo, expectSidebarLink } from '../helpers/auth';
import { APP_URL } from '../helpers/api';
test.describe('OU Admin — acceso a gestión sin infraestructura', () => {
test.beforeEach(async ({ page }) => {
await loginAs(page, 'ouAdmin');
});
// ── Sidebar ─────────────────────────────────────────────────────────────────
test.describe('Sidebar', () => {
test('ve /groups', async ({ page }) => expectSidebarLink(page, '/groups', true));
test('ve /dhcp-servers', async ({ page }) => expectSidebarLink(page, '/dhcp-servers', true));
test('ve /boot-servers', async ({ page }) => expectSidebarLink(page, '/boot-servers', true));
test('ve /calendars', async ({ page }) => expectSidebarLink(page, '/calendars', true));
test('ve /repositories', async ({ page }) => expectSidebarLink(page, '/repositories', true));
test('ve /menus', async ({ page }) => expectSidebarLink(page, '/menus', true));
});
// ── Rutas permitidas ─────────────────────────────────────────────────────────
test.describe('Rutas — puede acceder', () => {
const allowed = [
'/groups', '/commands', '/dhcp-servers', '/boot-servers',
'/calendars', '/repositories', '/pxe',
];
for (const route of allowed) {
test(`accede a ${route}`, async ({ page }) => {
const finalUrl = await navigateTo(page, route);
expect(finalUrl).toContain(route);
});
}
});
// ── Rutas bloqueadas (solo super-admin) ──────────────────────────────────────
test.describe('Rutas — redirige a /groups cuando accede a rutas de super-admin', () => {
const blocked = ['/users', '/roles', '/env-vars', '/import-legacy'];
for (const route of blocked) {
test(`${route} → redirige a /groups`, async ({ page }) => {
const finalUrl = await navigateTo(page, route);
expect(finalUrl).toContain('/groups');
});
}
});
// ── GUI: botones de infraestructura OCULTOS ──────────────────────────────────
test('NO ve el botón "Añadir OU" en /groups (solo ou-admin no puede crear desde aquí... wait, sí puede)', async ({ page }) => {
await page.goto(`${APP_URL}/groups`);
// ou-admin SÍ ve el botón de añadir OU (no es ou-operator ni ou-minimal)
const addOuBtn = page.locator('button.action-button').first();
await expect(addOuBtn).toBeVisible({ timeout: 5_000 });
});
test('NO ve botón crear en /dhcp-servers (solo super-admin puede crear servidores DHCP)', async ({ page }) => {
await page.goto(`${APP_URL}/dhcp-servers`);
await page.waitForLoadState('networkidle');
// El botón de añadir dhcp tiene *ngIf="auth.isSuperAdmin" → no debe aparecer
const addBtn = page.locator('button[color="primary"]').filter({ hasText: /add|añadir/i });
await expect(addBtn).not.toBeAttached({ timeout: 5_000 });
});
test('NO ve botón crear en /boot-servers (solo super-admin)', async ({ page }) => {
await page.goto(`${APP_URL}/boot-servers`);
await page.waitForLoadState('networkidle');
const addBtn = page.locator('button').filter({ hasText: /add|añadir/i }).first();
await expect(addBtn).not.toBeAttached({ timeout: 5_000 });
});
test('NO ve botón crear en /commands (solo super-admin)', async ({ page }) => {
await page.goto(`${APP_URL}/commands`);
await page.waitForLoadState('networkidle');
const addBtn = page.locator('button.action-button');
await expect(addBtn).not.toBeAttached({ timeout: 5_000 });
});
});

View File

@ -1,60 +0,0 @@
import { test, expect } from '@playwright/test';
import { loginAs, navigateTo, expectSidebarLink } from '../helpers/auth';
import { APP_URL } from '../helpers/api';
test.describe('OU Minimal — solo vista de grupos', () => {
test.beforeEach(async ({ page }) => {
await loginAs(page, 'minimal');
});
// ── Login ────────────────────────────────────────────────────────────────────
test('tras login aterriza en /groups', async ({ page }) => {
await expect(page).toHaveURL(/\/groups/);
});
// ── Sidebar: solo /groups ────────────────────────────────────────────────────
test.describe('Sidebar — solo ve /groups', () => {
test('ve /groups', async ({ page }) => expectSidebarLink(page, '/groups', true));
test('NO ve /dhcp-servers', async ({ page }) => expectSidebarLink(page, '/dhcp-servers', false));
test('NO ve /boot-servers', async ({ page }) => expectSidebarLink(page, '/boot-servers', false));
test('NO ve /calendars', async ({ page }) => expectSidebarLink(page, '/calendars', false));
test('NO ve /repositories', async ({ page }) => expectSidebarLink(page, '/repositories', false));
test('NO ve /menus', async ({ page }) => expectSidebarLink(page, '/menus', false));
});
// ── Rutas bloqueadas ─────────────────────────────────────────────────────────
test.describe('Todas las rutas protegidas redirigen a /groups', () => {
const blocked = [
'/users', '/roles', '/env-vars',
'/commands', '/dhcp-servers', '/boot-servers',
'/calendars', '/repositories', '/pxe',
'/clients/deploy-image', '/clients/partition-assistant', '/clients/run-script',
];
for (const route of blocked) {
test(`${route} → redirige a /groups`, async ({ page }) => {
const finalUrl = await navigateTo(page, route);
expect(finalUrl).toContain('/groups');
});
}
});
// ── GUI en /groups: sin botones de acción ────────────────────────────────────
test.describe('/groups — sin botones de creación ni edición', () => {
test('NO ve botones "Añadir OU" ni "Añadir cliente"', async ({ page }) => {
await page.goto(`${APP_URL}/groups`);
await page.waitForLoadState('networkidle');
const actionBtns = page.locator('button.action-button');
await expect(actionBtns).not.toBeAttached({ timeout: 5_000 });
});
test('NO ve botones de editar ni eliminar en el árbol de grupos', async ({ page }) => {
await page.goto(`${APP_URL}/groups`);
await page.waitForLoadState('networkidle');
// Los botones de editar/borrar nodo tienen *ngIf="auth.userCategory !== 'ou-minimal'"
// Se verifican a través del menú contextual que no debería aparecer con opciones de edición
const editBtns = page.locator('button').filter({ hasText: /editar|edit|modificar/i });
await expect(editBtns).not.toBeAttached({ timeout: 5_000 });
});
});
});

View File

@ -1,82 +0,0 @@
import { test, expect } from '@playwright/test';
import { loginAs, navigateTo, expectSidebarLink } from '../helpers/auth';
import { APP_URL } from '../helpers/api';
test.describe('OU Operator — solo grupos y operaciones de equipos', () => {
test.beforeEach(async ({ page }) => {
await loginAs(page, 'operator');
});
// ── Sidebar: solo /groups visible ───────────────────────────────────────────
test.describe('Sidebar — solo ve /groups', () => {
test('ve /groups', async ({ page }) => expectSidebarLink(page, '/groups', true));
test('NO ve /dhcp-servers', async ({ page }) => expectSidebarLink(page, '/dhcp-servers', false));
test('NO ve /boot-servers', async ({ page }) => expectSidebarLink(page, '/boot-servers', false));
test('NO ve /calendars', async ({ page }) => expectSidebarLink(page, '/calendars', false));
test('NO ve /repositories', async ({ page }) => expectSidebarLink(page, '/repositories', false));
test('NO ve /menus', async ({ page }) => expectSidebarLink(page, '/menus', false));
});
// ── Rutas bloqueadas: redirige a /groups ─────────────────────────────────────
test.describe('Rutas de admin → redirigen a /groups', () => {
const blocked = [
'/users', '/roles', '/env-vars',
'/commands', '/dhcp-servers', '/boot-servers',
'/calendars', '/repositories', '/pxe',
];
for (const route of blocked) {
test(`${route} → redirige a /groups`, async ({ page }) => {
const finalUrl = await navigateTo(page, route);
expect(finalUrl).toContain('/groups');
});
}
});
// ── Rutas permitidas: operaciones de equipos ─────────────────────────────────
test.describe('Rutas de operación — puede acceder', () => {
test('accede a /groups', async ({ page }) => {
const finalUrl = await navigateTo(page, '/groups');
expect(finalUrl).toContain('/groups');
});
test('accede a /clients/deploy-image', async ({ page }) => {
const finalUrl = await navigateTo(page, '/clients/deploy-image');
expect(finalUrl).toContain('/clients/deploy-image');
});
test('accede a /clients/partition-assistant', async ({ page }) => {
const finalUrl = await navigateTo(page, '/clients/partition-assistant');
expect(finalUrl).toContain('/clients/partition-assistant');
});
test('accede a /clients/run-script', async ({ page }) => {
const finalUrl = await navigateTo(page, '/clients/run-script');
expect(finalUrl).toContain('/clients/run-script');
});
test('accede a /commands-logs (trazas de sus acciones)', async ({ page }) => {
const finalUrl = await navigateTo(page, '/commands-logs');
expect(finalUrl).toContain('/commands-logs');
});
});
// ── GUI en /groups: botones de crear OU/cliente ocultos ─────────────────────
test.describe('/groups — botones de creación ocultos', () => {
test('NO ve el botón "Añadir OU"', async ({ page }) => {
await page.goto(`${APP_URL}/groups`);
await page.waitForLoadState('networkidle');
// *ngIf="auth.userCategory !== 'ou-operator' && ..."
const addOuBtn = page.locator('button.action-button').filter({ hasText: /ou|unidad/i });
await expect(addOuBtn).not.toBeAttached({ timeout: 5_000 });
});
test('NO ve el botón de menú "Añadir cliente"', async ({ page }) => {
await page.goto(`${APP_URL}/groups`);
await page.waitForLoadState('networkidle');
// Los botones de acción principales no deben aparecer para operator
const actionBtns = page.locator('button.action-button');
await expect(actionBtns).not.toBeAttached({ timeout: 5_000 });
});
});
});

View File

@ -1,66 +0,0 @@
import { test, expect } from '@playwright/test';
import { loginAs, navigateTo, expectSidebarLink } from '../helpers/auth';
import { APP_URL } from '../helpers/api';
test.describe('Super Admin — acceso total', () => {
test.beforeEach(async ({ page }) => {
await loginAs(page, 'superAdmin');
});
// ── Sidebar: todos los elementos visibles ───────────────────────────────────
test.describe('Sidebar — ve todos los enlaces', () => {
const links = [
'/groups', '/dhcp-servers', '/boot-servers',
'/calendars', '/repositories', '/menus',
];
for (const link of links) {
test(`ve el enlace a ${link}`, async ({ page }) => {
await expectSidebarLink(page, link, true);
});
}
});
// ── Rutas: acceso permitido ─────────────────────────────────────────────────
test.describe('Rutas — puede acceder a todas', () => {
const routes = [
'/users', '/roles', '/env-vars',
'/commands', '/pxe', '/dhcp-servers', '/boot-servers',
'/calendars', '/repositories',
];
for (const route of routes) {
test(`accede a ${route} sin ser redirigido`, async ({ page }) => {
const finalUrl = await navigateTo(page, route);
expect(finalUrl).toContain(route);
});
}
});
// ── GUI: botones de infraestructura visibles ────────────────────────────────
test('ve el botón "Añadir OU" en /groups', async ({ page }) => {
await page.goto(`${APP_URL}/groups`);
await expect(page.locator('button.action-button').first()).toBeVisible();
});
test('ve botones de crear/editar en /dhcp-servers', async ({ page }) => {
await page.goto(`${APP_URL}/dhcp-servers`);
await page.waitForLoadState('networkidle');
// Botón de añadir servidor (solo visible para super-admin)
const addBtn = page.locator('button').filter({ hasText: /add|añadir|nuevo/i }).first();
await expect(addBtn).toBeVisible({ timeout: 8_000 });
});
test('ve botones de crear en /commands', async ({ page }) => {
await page.goto(`${APP_URL}/commands`);
await page.waitForLoadState('networkidle');
const addBtn = page.locator('button.action-button').first();
await expect(addBtn).toBeVisible({ timeout: 8_000 });
});
test('ve botones de crear en /boot-servers', async ({ page }) => {
await page.goto(`${APP_URL}/boot-servers`);
await page.waitForLoadState('networkidle');
const addBtn = page.locator('button').filter({ hasText: /add|añadir|nuevo/i }).first();
await expect(addBtn).toBeVisible({ timeout: 8_000 });
});
});

View File

@ -1,12 +1,12 @@
{ {
"name": "og-webconsole", "name": "og-webconsole",
"version": "1.14.0", "version": "0.5.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "og-webconsole", "name": "og-webconsole",
"version": "1.14.0", "version": "0.5.0",
"dependencies": { "dependencies": {
"@angular/animations": "^18.0.0", "@angular/animations": "^18.0.0",
"@angular/cdk": "~18.0.0", "@angular/cdk": "~18.0.0",
@ -35,7 +35,6 @@
"@angular/compiler-cli": "^18.0.0", "@angular/compiler-cli": "^18.0.0",
"@angular/localize": "^18.1.0", "@angular/localize": "^18.1.0",
"@ngx-env/builder": "^18.0.1", "@ngx-env/builder": "^18.0.1",
"@playwright/test": "^1.60.0",
"@types/jasmine": "~5.1.0", "@types/jasmine": "~5.1.0",
"@types/papaparse": "^5.3.15", "@types/papaparse": "^5.3.15",
"jasmine-core": "~5.1.0", "jasmine-core": "~5.1.0",
@ -273,7 +272,6 @@
"version": "18.1.0", "version": "18.1.0",
"resolved": "https://registry.npmjs.org/@angular/animations/-/animations-18.1.0.tgz", "resolved": "https://registry.npmjs.org/@angular/animations/-/animations-18.1.0.tgz",
"integrity": "sha512-K0BhvZ/SIVoGXZVuh1KOJDdgcGlHfFGMGrs58utndndAb+gYXReMfz4GR5cQs2OObH6TKmIOY2EH7Og1CY2tsw==", "integrity": "sha512-K0BhvZ/SIVoGXZVuh1KOJDdgcGlHfFGMGrs58utndndAb+gYXReMfz4GR5cQs2OObH6TKmIOY2EH7Og1CY2tsw==",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
@ -358,7 +356,6 @@
"version": "18.0.6", "version": "18.0.6",
"resolved": "https://registry.npmjs.org/@angular/cdk/-/cdk-18.0.6.tgz", "resolved": "https://registry.npmjs.org/@angular/cdk/-/cdk-18.0.6.tgz",
"integrity": "sha512-9CmlQ8uZ0cHuj+1jDdabbFw90QpjrJzh1/cgeHN/8vAGE4ranxX3l6cqpVxuoWRLkB2ykTHt2xeoTM8y0d9ERA==", "integrity": "sha512-9CmlQ8uZ0cHuj+1jDdabbFw90QpjrJzh1/cgeHN/8vAGE4ranxX3l6cqpVxuoWRLkB2ykTHt2xeoTM8y0d9ERA==",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
@ -408,7 +405,6 @@
"version": "18.1.0", "version": "18.1.0",
"resolved": "https://registry.npmjs.org/@angular/common/-/common-18.1.0.tgz", "resolved": "https://registry.npmjs.org/@angular/common/-/common-18.1.0.tgz",
"integrity": "sha512-noHDLarQSCZZh7hyNd0HR61Fut+q4QCVq9qc/jKPglfbV/6nPujQSmSpT+rNJlNuBOrCLuvH/CNBNbiqii+x3g==", "integrity": "sha512-noHDLarQSCZZh7hyNd0HR61Fut+q4QCVq9qc/jKPglfbV/6nPujQSmSpT+rNJlNuBOrCLuvH/CNBNbiqii+x3g==",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
@ -424,7 +420,6 @@
"version": "18.1.0", "version": "18.1.0",
"resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-18.1.0.tgz", "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-18.1.0.tgz",
"integrity": "sha512-JRQzVTeJGSfRLY+dx+gwu/hPQVB8K+5pW12Z42M9x/HBgGW4in0cO2zHkeQPvImqm0nak82Us1Hyf5C+qTlMMQ==", "integrity": "sha512-JRQzVTeJGSfRLY+dx+gwu/hPQVB8K+5pW12Z42M9x/HBgGW4in0cO2zHkeQPvImqm0nak82Us1Hyf5C+qTlMMQ==",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
@ -445,7 +440,6 @@
"resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-18.1.0.tgz", "resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-18.1.0.tgz",
"integrity": "sha512-BBsogLPJwxkPh7f8RVHsxyyqNE8XpHbAanjB5fAwnU4W6Sw1kR5rFzkeZM3xaRm2MDiC8DovIl6hlf+s/mKYOw==", "integrity": "sha512-BBsogLPJwxkPh7f8RVHsxyyqNE8XpHbAanjB5fAwnU4W6Sw1kR5rFzkeZM3xaRm2MDiC8DovIl6hlf+s/mKYOw==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"@babel/core": "7.24.7", "@babel/core": "7.24.7",
"@jridgewell/sourcemap-codec": "^1.4.14", "@jridgewell/sourcemap-codec": "^1.4.14",
@ -473,7 +467,6 @@
"version": "18.1.0", "version": "18.1.0",
"resolved": "https://registry.npmjs.org/@angular/core/-/core-18.1.0.tgz", "resolved": "https://registry.npmjs.org/@angular/core/-/core-18.1.0.tgz",
"integrity": "sha512-/57/s7CD/0CwlN+3FlhVmx7ypCWXjKi5UKtnlBAUg0D1denIf6ADxwTHFZABYZcYBqOTJgeQUtUw9u/A+0CIlg==", "integrity": "sha512-/57/s7CD/0CwlN+3FlhVmx7ypCWXjKi5UKtnlBAUg0D1denIf6ADxwTHFZABYZcYBqOTJgeQUtUw9u/A+0CIlg==",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
@ -489,7 +482,6 @@
"version": "18.1.0", "version": "18.1.0",
"resolved": "https://registry.npmjs.org/@angular/forms/-/forms-18.1.0.tgz", "resolved": "https://registry.npmjs.org/@angular/forms/-/forms-18.1.0.tgz",
"integrity": "sha512-m+7m9wa+n5dEacd458eSZsZTz0B+HbOtr7/uqM0YTMQaPrhwl1epG5Y103mB6yr00JiJcLNlPLjP888cHFjldQ==", "integrity": "sha512-m+7m9wa+n5dEacd458eSZsZTz0B+HbOtr7/uqM0YTMQaPrhwl1epG5Y103mB6yr00JiJcLNlPLjP888cHFjldQ==",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
@ -508,7 +500,6 @@
"resolved": "https://registry.npmjs.org/@angular/localize/-/localize-18.1.0.tgz", "resolved": "https://registry.npmjs.org/@angular/localize/-/localize-18.1.0.tgz",
"integrity": "sha512-84D06p2Th5NxoJZzsSIn4FkTJGImj7rtNnvyTrHvHdomzzUKwiBOXDB2FiCLDstND0DsCtgjD/uBJivg77z9tg==", "integrity": "sha512-84D06p2Th5NxoJZzsSIn4FkTJGImj7rtNnvyTrHvHdomzzUKwiBOXDB2FiCLDstND0DsCtgjD/uBJivg77z9tg==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"@babel/core": "7.24.7", "@babel/core": "7.24.7",
"@types/babel__core": "7.20.5", "@types/babel__core": "7.20.5",
@ -597,7 +588,6 @@
"version": "18.1.0", "version": "18.1.0",
"resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-18.1.0.tgz", "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-18.1.0.tgz",
"integrity": "sha512-jCmxthiI4Zef54crckNht60xwfIsuciGeyZvb7SsXna2maLW9fA4uz1VhZqIWTiBnHwNynVlyfBX3/jBD7S9+g==", "integrity": "sha512-jCmxthiI4Zef54crckNht60xwfIsuciGeyZvb7SsXna2maLW9fA4uz1VhZqIWTiBnHwNynVlyfBX3/jBD7S9+g==",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
@ -619,7 +609,6 @@
"version": "18.1.0", "version": "18.1.0",
"resolved": "https://registry.npmjs.org/@angular/platform-browser-dynamic/-/platform-browser-dynamic-18.1.0.tgz", "resolved": "https://registry.npmjs.org/@angular/platform-browser-dynamic/-/platform-browser-dynamic-18.1.0.tgz",
"integrity": "sha512-D/wuOQf+gULld9DVEzn2Lw3WbTyAYf/sp3DC5k83O+DQsG3eAIsVkt0zdE+U3DrDYsiWg8M3X+ioi3ouqK0mNg==", "integrity": "sha512-D/wuOQf+gULld9DVEzn2Lw3WbTyAYf/sp3DC5k83O+DQsG3eAIsVkt0zdE+U3DrDYsiWg8M3X+ioi3ouqK0mNg==",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
@ -677,7 +666,6 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.24.7.tgz", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.24.7.tgz",
"integrity": "sha512-nykK+LEK86ahTkX/3TgauT0ikKoNCfKHEaZYTUVupJdTLzGNvrblu4u6fa7DhZONAltdf8e662t/abY8idrd/g==", "integrity": "sha512-nykK+LEK86ahTkX/3TgauT0ikKoNCfKHEaZYTUVupJdTLzGNvrblu4u6fa7DhZONAltdf8e662t/abY8idrd/g==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"@ampproject/remapping": "^2.2.0", "@ampproject/remapping": "^2.2.0",
"@babel/code-frame": "^7.24.7", "@babel/code-frame": "^7.24.7",
@ -3229,7 +3217,6 @@
"resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-5.0.7.tgz", "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-5.0.7.tgz",
"integrity": "sha512-GFcigCxJTKCH3aECzMIu4FhgLJWnFvMXzpI4CCSoELWFtkOOU2P+goYA61+OKpGrB8fPE7q6n8zAXBSlZRrHjQ==", "integrity": "sha512-GFcigCxJTKCH3aECzMIu4FhgLJWnFvMXzpI4CCSoELWFtkOOU2P+goYA61+OKpGrB8fPE7q6n8zAXBSlZRrHjQ==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"@inquirer/checkbox": "^2.3.7", "@inquirer/checkbox": "^2.3.7",
"@inquirer/confirm": "^3.1.11", "@inquirer/confirm": "^3.1.11",
@ -4531,6 +4518,7 @@
"os": [ "os": [
"aix" "aix"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4547,6 +4535,7 @@
"os": [ "os": [
"android" "android"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4563,6 +4552,7 @@
"os": [ "os": [
"android" "android"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4579,6 +4569,7 @@
"os": [ "os": [
"android" "android"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4595,6 +4586,7 @@
"os": [ "os": [
"darwin" "darwin"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4611,6 +4603,7 @@
"os": [ "os": [
"darwin" "darwin"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4627,6 +4620,7 @@
"os": [ "os": [
"freebsd" "freebsd"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4643,6 +4637,7 @@
"os": [ "os": [
"freebsd" "freebsd"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4659,6 +4654,7 @@
"os": [ "os": [
"linux" "linux"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4675,6 +4671,7 @@
"os": [ "os": [
"linux" "linux"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4691,6 +4688,7 @@
"os": [ "os": [
"linux" "linux"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4707,6 +4705,7 @@
"os": [ "os": [
"linux" "linux"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4723,6 +4722,7 @@
"os": [ "os": [
"linux" "linux"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4739,6 +4739,7 @@
"os": [ "os": [
"linux" "linux"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4755,6 +4756,7 @@
"os": [ "os": [
"linux" "linux"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4771,6 +4773,7 @@
"os": [ "os": [
"linux" "linux"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4787,6 +4790,7 @@
"os": [ "os": [
"linux" "linux"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4803,6 +4807,7 @@
"os": [ "os": [
"netbsd" "netbsd"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4819,6 +4824,7 @@
"os": [ "os": [
"openbsd" "openbsd"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4835,6 +4841,7 @@
"os": [ "os": [
"sunos" "sunos"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4851,6 +4858,7 @@
"os": [ "os": [
"win32" "win32"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4867,6 +4875,7 @@
"os": [ "os": [
"win32" "win32"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -4883,6 +4892,7 @@
"os": [ "os": [
"win32" "win32"
], ],
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -5296,22 +5306,6 @@
"node": ">=14" "node": ">=14"
} }
}, },
"node_modules/@playwright/test": {
"version": "1.60.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz",
"integrity": "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.60.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@rollup/rollup-android-arm-eabi": { "node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.18.0", "version": "4.18.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.18.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.18.0.tgz",
@ -5897,7 +5891,6 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.10.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.10.tgz",
"integrity": "sha512-MdiXf+nDuMvY0gJKxyfZ7/6UFsETO7mGKF54MVD/ekJS6HdFtpZFBgrh6Pseu64XTb2MLyFPlbW6hj8HYRQNOQ==", "integrity": "sha512-MdiXf+nDuMvY0gJKxyfZ7/6UFsETO7mGKF54MVD/ekJS6HdFtpZFBgrh6Pseu64XTb2MLyFPlbW6hj8HYRQNOQ==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"undici-types": "~5.26.4" "undici-types": "~5.26.4"
} }
@ -6195,7 +6188,6 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz",
"integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==",
"dev": true, "dev": true,
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@ -6269,7 +6261,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.16.0.tgz", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.16.0.tgz",
"integrity": "sha512-F0twR8U1ZU67JIEtekUcLkXkoO5mMMmgGD8sK/xUFzJ805jxHQl92hImFAqqXMyMYjSPOyUPAwHYhB72g5sTXw==", "integrity": "sha512-F0twR8U1ZU67JIEtekUcLkXkoO5mMMmgGD8sK/xUFzJ805jxHQl92hImFAqqXMyMYjSPOyUPAwHYhB72g5sTXw==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",
"json-schema-traverse": "^1.0.0", "json-schema-traverse": "^1.0.0",
@ -6675,7 +6666,6 @@
"url": "https://github.com/sponsors/ai" "url": "https://github.com/sponsors/ai"
} }
], ],
"peer": true,
"dependencies": { "dependencies": {
"caniuse-lite": "^1.0.30001640", "caniuse-lite": "^1.0.30001640",
"electron-to-chromium": "^1.4.820", "electron-to-chromium": "^1.4.820",
@ -7735,7 +7725,6 @@
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
"integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
@ -9821,8 +9810,7 @@
"version": "5.1.2", "version": "5.1.2",
"resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-5.1.2.tgz", "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-5.1.2.tgz",
"integrity": "sha512-2oIUMGn00FdUiqz6epiiJr7xcFyNYj3rDcfmnzfkBnHyBQ3cBQUs4mmyGsOb7TTLb9kxk7dBcmEmqhDKkBoDyA==", "integrity": "sha512-2oIUMGn00FdUiqz6epiiJr7xcFyNYj3rDcfmnzfkBnHyBQ3cBQUs4mmyGsOb7TTLb9kxk7dBcmEmqhDKkBoDyA==",
"dev": true, "dev": true
"peer": true
}, },
"node_modules/jest-worker": { "node_modules/jest-worker": {
"version": "27.5.1", "version": "27.5.1",
@ -9971,7 +9959,6 @@
"resolved": "https://registry.npmjs.org/karma/-/karma-6.4.3.tgz", "resolved": "https://registry.npmjs.org/karma/-/karma-6.4.3.tgz",
"integrity": "sha512-LuucC/RE92tJ8mlCwqEoRWXP38UMAqpnq98vktmS9SznSoUPPUJQbc91dHcxcunROvfQjdORVA/YFviH+Xci9Q==", "integrity": "sha512-LuucC/RE92tJ8mlCwqEoRWXP38UMAqpnq98vktmS9SznSoUPPUJQbc91dHcxcunROvfQjdORVA/YFviH+Xci9Q==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"@colors/colors": "1.5.0", "@colors/colors": "1.5.0",
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
@ -10272,7 +10259,6 @@
"resolved": "https://registry.npmjs.org/less/-/less-4.2.0.tgz", "resolved": "https://registry.npmjs.org/less/-/less-4.2.0.tgz",
"integrity": "sha512-P3b3HJDBtSzsXUl0im2L7gTO5Ubg8mEN6G8qoTS77iXxXX4Hvu4Qj540PZDvQ8V6DmX6iXo98k7Md0Cm1PrLaA==", "integrity": "sha512-P3b3HJDBtSzsXUl0im2L7gTO5Ubg8mEN6G8qoTS77iXxXX4Hvu4Qj540PZDvQ8V6DmX6iXo98k7Md0Cm1PrLaA==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"copy-anything": "^2.0.1", "copy-anything": "^2.0.1",
"parse-node-version": "^1.0.1", "parse-node-version": "^1.0.1",
@ -12202,53 +12188,6 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/playwright": {
"version": "1.60.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz",
"integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.60.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.60.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz",
"integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/playwright/node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.4.38", "version": "8.4.38",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.38.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.38.tgz",
@ -12268,7 +12207,6 @@
"url": "https://github.com/sponsors/ai" "url": "https://github.com/sponsors/ai"
} }
], ],
"peer": true,
"dependencies": { "dependencies": {
"nanoid": "^3.3.7", "nanoid": "^3.3.7",
"picocolors": "^1.0.0", "picocolors": "^1.0.0",
@ -12885,7 +12823,6 @@
"version": "7.8.1", "version": "7.8.1",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz",
"integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.1.0" "tslib": "^2.1.0"
} }
@ -13866,7 +13803,6 @@
"resolved": "https://registry.npmjs.org/terser/-/terser-5.29.2.tgz", "resolved": "https://registry.npmjs.org/terser/-/terser-5.29.2.tgz",
"integrity": "sha512-ZiGkhUBIM+7LwkNjXYJq8svgkd+QK3UUr0wJqY4MieaezBSAIPgbSPZyIx0idM6XWK5CMzSWa8MJIzmRcB8Caw==", "integrity": "sha512-ZiGkhUBIM+7LwkNjXYJq8svgkd+QK3UUr0wJqY4MieaezBSAIPgbSPZyIx0idM6XWK5CMzSWa8MJIzmRcB8Caw==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"@jridgewell/source-map": "^0.3.3", "@jridgewell/source-map": "^0.3.3",
"acorn": "^8.8.2", "acorn": "^8.8.2",
@ -13919,7 +13855,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"fast-deep-equal": "^3.1.1", "fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0", "fast-json-stable-stringify": "^2.0.0",
@ -14052,8 +13987,7 @@
"node_modules/tslib": { "node_modules/tslib": {
"version": "2.6.3", "version": "2.6.3",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz",
"integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==", "integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ=="
"peer": true
}, },
"node_modules/tuf-js": { "node_modules/tuf-js": {
"version": "2.2.1", "version": "2.2.1",
@ -14105,7 +14039,6 @@
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
"integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
"dev": true, "dev": true,
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
@ -14351,7 +14284,6 @@
"resolved": "https://registry.npmjs.org/vite/-/vite-5.3.2.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-5.3.2.tgz",
"integrity": "sha512-6lA7OBHBlXUxiJxbO5aAY2fsHHzDr1q7DvXYnyZycRs2Dz+dXBWuhpWHvmljTRTpQC2uvGmUFFkSHF2vGo90MA==", "integrity": "sha512-6lA7OBHBlXUxiJxbO5aAY2fsHHzDr1q7DvXYnyZycRs2Dz+dXBWuhpWHvmljTRTpQC2uvGmUFFkSHF2vGo90MA==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.21.3", "esbuild": "^0.21.3",
"postcss": "^8.4.38", "postcss": "^8.4.38",
@ -14453,7 +14385,6 @@
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.92.1.tgz", "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.92.1.tgz",
"integrity": "sha512-JECQ7IwJb+7fgUFBlrJzbyu3GEuNBcdqr1LD7IbSzwkSmIevTm8PF+wej3Oxuz/JFBUZ6O1o43zsPkwm1C4TmA==", "integrity": "sha512-JECQ7IwJb+7fgUFBlrJzbyu3GEuNBcdqr1LD7IbSzwkSmIevTm8PF+wej3Oxuz/JFBUZ6O1o43zsPkwm1C4TmA==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"@types/eslint-scope": "^3.7.3", "@types/eslint-scope": "^3.7.3",
"@types/estree": "^1.0.5", "@types/estree": "^1.0.5",
@ -14530,7 +14461,6 @@
"resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-5.0.4.tgz", "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-5.0.4.tgz",
"integrity": "sha512-dljXhUgx3HqKP2d8J/fUMvhxGhzjeNVarDLcbO/EWMSgRizDkxHQDZQaLFL5VJY9tRBj2Gz+rvCEYYvhbqPHNA==", "integrity": "sha512-dljXhUgx3HqKP2d8J/fUMvhxGhzjeNVarDLcbO/EWMSgRizDkxHQDZQaLFL5VJY9tRBj2Gz+rvCEYYvhbqPHNA==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"@types/bonjour": "^3.5.13", "@types/bonjour": "^3.5.13",
"@types/connect-history-api-fallback": "^1.5.4", "@types/connect-history-api-fallback": "^1.5.4",
@ -14720,7 +14650,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
"dev": true, "dev": true,
"peer": true,
"dependencies": { "dependencies": {
"fast-deep-equal": "^3.1.1", "fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0", "fast-json-stable-stringify": "^2.0.0",
@ -15102,8 +15031,7 @@
"node_modules/zone.js": { "node_modules/zone.js": {
"version": "0.14.7", "version": "0.14.7",
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.14.7.tgz", "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.14.7.tgz",
"integrity": "sha512-0w6DGkX2BPuiK/NLf+4A8FLE43QwBfuqz2dVgi/40Rj1WmqUskCqj329O/pwrqFJLG5X8wkeG2RhIAro441xtg==", "integrity": "sha512-0w6DGkX2BPuiK/NLf+4A8FLE43QwBfuqz2dVgi/40Rj1WmqUskCqj329O/pwrqFJLG5X8wkeG2RhIAro441xtg=="
"peer": true
} }
} }
} }

View File

@ -1,16 +1,12 @@
{ {
"name": "og-webconsole", "name": "og-webconsole",
"version": "1.26.0", "version": "0.5.0",
"scripts": { "scripts": {
"ng": "ng", "ng": "ng",
"start": "ng serve", "start": "ng serve",
"build": "ng build", "build": "ng build",
"watch": "ng build --watch --configuration development", "watch": "ng build --watch --configuration development",
"test": "ng test", "test": "ng test"
"e2e": "playwright test",
"e2e:headed": "playwright test --headed --slow-mo=400",
"e2e:ui": "playwright test --ui",
"e2e:report": "playwright show-report"
}, },
"private": true, "private": true,
"dependencies": { "dependencies": {
@ -41,7 +37,6 @@
"@angular/compiler-cli": "^18.0.0", "@angular/compiler-cli": "^18.0.0",
"@angular/localize": "^18.1.0", "@angular/localize": "^18.1.0",
"@ngx-env/builder": "^18.0.1", "@ngx-env/builder": "^18.0.1",
"@playwright/test": "^1.60.0",
"@types/jasmine": "~5.1.0", "@types/jasmine": "~5.1.0",
"@types/papaparse": "^5.3.15", "@types/papaparse": "^5.3.15",
"jasmine-core": "~5.1.0", "jasmine-core": "~5.1.0",

View File

@ -1,33 +0,0 @@
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
globalSetup: './e2e/global-setup.ts',
globalTeardown: './e2e/global-teardown.ts',
timeout: 30_000,
retries: 0,
workers: 1, // secuencial para no crear conflictos entre usuarios de test
reporter: [['list'], ['html', { outputFolder: 'playwright-report', open: 'never' }]],
use: {
baseURL: 'https://localhost:4200/oggui',
ignoreHTTPSErrors: true,
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
webServer: {
command: 'npm start',
url: 'https://localhost:4200/oggui',
reuseExistingServer: true,
ignoreHTTPSErrors: true,
timeout: 120_000,
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
});

View File

@ -34,7 +34,6 @@ import {
} from "./components/repositories/main-repository-view/main-repository-view.component"; } from "./components/repositories/main-repository-view/main-repository-view.component";
import { EnvVarsComponent } from "./components/admin/env-vars/env-vars.component"; import { EnvVarsComponent } from "./components/admin/env-vars/env-vars.component";
import { MenusComponent } from "./components/menus/menus.component"; import { MenusComponent } from "./components/menus/menus.component";
import { ImportLegacyComponent } from './components/admin/import-legacy/import-legacy.component';
import { OgDhcpSubnetsComponent } from "./components/ogdhcp/og-dhcp-subnets.component"; import { OgDhcpSubnetsComponent } from "./components/ogdhcp/og-dhcp-subnets.component";
import { DhcpServersComponent } from './components/ogdhcp/dhcp-servers/dhcp-servers.component'; import { DhcpServersComponent } from './components/ogdhcp/dhcp-servers/dhcp-servers.component';
import { BootServersComponent } from './components/ogboot/boot-servers/boot-servers.component'; import { BootServersComponent } from './components/ogboot/boot-servers/boot-servers.component';
@ -48,7 +47,6 @@ import { HardwareComponent } from './components/hardware/hardware.component';
import { HardwareProfileComponent } from './components/hardware-profile/hardware-profile.component'; import { HardwareProfileComponent } from './components/hardware-profile/hardware-profile.component';
import { HardwareTypeComponent } from './components/hardware-type/hardware-type.component'; import { HardwareTypeComponent } from './components/hardware-type/hardware-type.component';
import { BootServerDashboardComponent } from './components/ogboot/boot-server-dashboard/boot-server-dashboard.component'; import { BootServerDashboardComponent } from './components/ogboot/boot-server-dashboard/boot-server-dashboard.component';
import { PluginsComponent } from './components/plugins/plugins.component';
const routes: Routes = [ const routes: Routes = [
{ path: '', redirectTo: 'auth/login', pathMatch: 'full' }, { path: '', redirectTo: 'auth/login', pathMatch: 'full' },
{ {
@ -57,7 +55,6 @@ const routes: Routes = [
{ path: 'users', component: UsersComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin'] } }, { path: 'users', component: UsersComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin'] } },
{ path: 'env-vars', component: EnvVarsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin'] } }, { path: 'env-vars', component: EnvVarsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin'] } },
{ path: 'roles', component: RolesComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin'] } }, { path: 'roles', component: RolesComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin'] } },
{ path: 'import-legacy', component: ImportLegacyComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin'] } },
{ path: 'groups', component: GroupsComponent }, { path: 'groups', component: GroupsComponent },
{ path: 'pxe-images', component: PXEimagesComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'pxe-images', component: PXEimagesComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'pxe', component: PxeComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'pxe', component: PxeComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
@ -70,12 +67,12 @@ const routes: Routes = [
{ path: 'commands', component: CommandsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'commands', component: CommandsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'commands-groups', component: CommandsGroupsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'commands-groups', component: CommandsGroupsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'commands-task', component: CommandsTaskComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'commands-task', component: CommandsTaskComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'commands-logs', component: TaskLogsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin', 'ou-operator'] } }, { path: 'commands-logs', component: TaskLogsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'calendars', component: CalendarComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'calendars', component: CalendarComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'clients/deploy-image', component: DeployImageComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin', 'ou-operator'] } }, { path: 'clients/deploy-image', component: DeployImageComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'clients/partition-assistant', component: PartitionAssistantComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin', 'ou-operator'] } }, { path: 'clients/partition-assistant', component: PartitionAssistantComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'clients/run-script', component: RunScriptAssistantComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin', 'ou-operator'] } }, { path: 'clients/run-script', component: RunScriptAssistantComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'clients/:id/create-image', component: CreateClientImageComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin', 'ou-operator'] } }, { path: 'clients/:id/create-image', component: CreateClientImageComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'repositories', component: RepositoriesComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'repositories', component: RepositoriesComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'repository/:id', component: MainRepositoryViewComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'repository/:id', component: MainRepositoryViewComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'software', component: SoftwareComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'software', component: SoftwareComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
@ -85,7 +82,6 @@ const routes: Routes = [
{ path: 'hardware', component: HardwareComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'hardware', component: HardwareComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'hardware-profiles', component: HardwareProfileComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'hardware-profiles', component: HardwareProfileComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'hardware-types', component: HardwareTypeComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } }, { path: 'hardware-types', component: HardwareTypeComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'plugins', component: PluginsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
], ],
}, },
{ {

View File

@ -7,6 +7,5 @@
.content { .content {
padding: 16px; padding: 16px;
box-sizing: border-box;
} }

View File

@ -148,8 +148,6 @@ import { CreateSubnetComponent } from "./components/ogdhcp/create-subnet/create-
import { AddClientsToSubnetComponent } from "./components/ogdhcp/add-clients-to-subnet/add-clients-to-subnet.component"; import { AddClientsToSubnetComponent } from "./components/ogdhcp/add-clients-to-subnet/add-clients-to-subnet.component";
import { ShowClientsComponent } from './components/ogdhcp/show-clients/show-clients.component'; import { ShowClientsComponent } from './components/ogdhcp/show-clients/show-clients.component';
import { OperationResultDialogComponent } from './components/ogdhcp/operation-result-dialog/operation-result-dialog.component'; import { OperationResultDialogComponent } from './components/ogdhcp/operation-result-dialog/operation-result-dialog.component';
import { PluginsComponent } from './components/plugins/plugins.component';
import { PluginSettingsComponent } from './components/plugins/plugin-settings/plugin-settings.component';
import { ManageClientComponent } from './components/groups/shared/clients/manage-client/manage-client.component'; import { ManageClientComponent } from './components/groups/shared/clients/manage-client/manage-client.component';
import { ConvertImageComponent } from './components/repositories/convert-image/convert-image.component'; import { ConvertImageComponent } from './components/repositories/convert-image/convert-image.component';
import { DhcpServersComponent } from './components/ogdhcp/dhcp-servers/dhcp-servers.component'; import { DhcpServersComponent } from './components/ogdhcp/dhcp-servers/dhcp-servers.component';
@ -174,17 +172,14 @@ import { ShowTaskScheduleComponent } from './components/commands/commands-task/s
import { ShowTaskScriptComponent } from './components/commands/commands-task/show-task-script/show-task-script.component'; import { ShowTaskScriptComponent } from './components/commands/commands-task/show-task-script/show-task-script.component';
import { CreateTaskScriptComponent } from './components/commands/commands-task/create-task-script/create-task-script.component'; import { CreateTaskScriptComponent } from './components/commands/commands-task/create-task-script/create-task-script.component';
import { ViewParametersModalComponent } from './components/commands/commands-task/show-task-script/view-parameters-modal/view-parameters-modal.component'; import { ViewParametersModalComponent } from './components/commands/commands-task/show-task-script/view-parameters-modal/view-parameters-modal.component';
import { ViewScriptModalComponent } from './components/commands/commands-task/show-task-script/view-script-modal/view-script-modal.component';
import { OutputDialogComponent } from './components/task-logs/output-dialog/output-dialog.component'; import { OutputDialogComponent } from './components/task-logs/output-dialog/output-dialog.component';
import { ClientTaskLogsComponent } from './components/task-logs/client-task-logs/client-task-logs.component'; import { ClientTaskLogsComponent } from './components/task-logs/client-task-logs/client-task-logs.component';
import { BootSoPartitionComponent } from './components/commands/main-commands/execute-command/boot-so-partition/boot-so-partition.component'; import { BootSoPartitionComponent } from './components/commands/main-commands/execute-command/boot-so-partition/boot-so-partition.component';
import { RemoveCacheImageComponent } from './components/commands/main-commands/execute-command/remove-cache-image/remove-cache-image.component'; import { RemoveCacheImageComponent } from './components/commands/main-commands/execute-command/remove-cache-image/remove-cache-image.component';
import { ChangeParentComponent } from './components/groups/shared/change-parent/change-parent.component'; import { ChangeParentComponent } from './components/groups/shared/change-parent/change-parent.component';
import { SoftwareProfilePartitionComponent } from './components/commands/main-commands/execute-command/software-profile-partition/software-profile-partition.component'; import { SoftwareProfilePartitionComponent } from './components/commands/main-commands/execute-command/software-profile-partition/software-profile-partition.component';
import { ExecuteTaskNowComponent } from './components/commands/main-commands/execute-command/execute-task-now/execute-task-now.component';
import { ClientPendingTasksComponent } from './components/task-logs/client-pending-tasks/client-pending-tasks.component'; import { ClientPendingTasksComponent } from './components/task-logs/client-pending-tasks/client-pending-tasks.component';
import { QueueConfirmationModalComponent } from './shared/queue-confirmation-modal/queue-confirmation-modal.component'; import { QueueConfirmationModalComponent } from './shared/queue-confirmation-modal/queue-confirmation-modal.component';
import { PluginCommandModalComponent } from './shared/plugin-command-modal/plugin-command-modal.component';
import { ModalOverlayComponent } from './shared/modal-overlay/modal-overlay.component'; import { ModalOverlayComponent } from './shared/modal-overlay/modal-overlay.component';
import { ScrollToTopComponent } from './shared/scroll-to-top/scroll-to-top.component'; import { ScrollToTopComponent } from './shared/scroll-to-top/scroll-to-top.component';
import { CreateTagModalComponent } from './components/repositories/show-git-images/create-tag-modal/create-tag-modal.component'; import { CreateTagModalComponent } from './components/repositories/show-git-images/create-tag-modal/create-tag-modal.component';
@ -206,14 +201,11 @@ import { OgcoreStatusComponent } from './components/global-status/ogcore-status/
import { GlobalOgbootStatusComponent } from './components/global-status/ogboot-status/ogboot-status.component'; import { GlobalOgbootStatusComponent } from './components/global-status/ogboot-status/ogboot-status.component';
import { OgrepositoryStatusComponent } from './components/global-status/ogrepository-status/ogrepository-status.component'; import { OgrepositoryStatusComponent } from './components/global-status/ogrepository-status/ogrepository-status.component';
import { OgdhcpStatusComponent } from './components/global-status/ogdhcp-status/ogdhcp-status.component'; import { OgdhcpStatusComponent } from './components/global-status/ogdhcp-status/ogdhcp-status.component';
import { StatusLogsComponent } from './components/global-status/status-logs/status-logs.component';
export function HttpLoaderFactory(http: HttpClient) { export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './locale/', '.json'); return new TranslateHttpLoader(http, './locale/', '.json');
} }
import { ImportLegacyComponent } from './components/admin/import-legacy/import-legacy.component';
import { PageNotFoundComponent } from './shared/page-not-found/page-not-found.component'; import { PageNotFoundComponent } from './shared/page-not-found/page-not-found.component';
import { OuSelectComponent } from './components/shared/ou-select/ou-select.component';
export function initializeApp(configService: ConfigService) { export function initializeApp(configService: ConfigService) {
return () => configService.loadConfig(); return () => configService.loadConfig();
@ -240,7 +232,6 @@ registerLocaleData(localeEs, 'es-ES');
DeleteModalComponent, DeleteModalComponent,
DeleteResultsModalComponent, DeleteResultsModalComponent,
QueueConfirmationModalComponent, QueueConfirmationModalComponent,
PluginCommandModalComponent,
ClassroomViewComponent, ClassroomViewComponent,
ClientViewComponent, ClientViewComponent,
ShowOrganizationalUnitComponent, ShowOrganizationalUnitComponent,
@ -323,14 +314,12 @@ registerLocaleData(localeEs, 'es-ES');
ShowTaskScriptComponent, ShowTaskScriptComponent,
CreateTaskScriptComponent, CreateTaskScriptComponent,
ViewParametersModalComponent, ViewParametersModalComponent,
ViewScriptModalComponent,
OutputDialogComponent, OutputDialogComponent,
ClientTaskLogsComponent, ClientTaskLogsComponent,
BootSoPartitionComponent, BootSoPartitionComponent,
RemoveCacheImageComponent, RemoveCacheImageComponent,
ChangeParentComponent, ChangeParentComponent,
SoftwareProfilePartitionComponent, SoftwareProfilePartitionComponent,
ExecuteTaskNowComponent,
ClientPendingTasksComponent, ClientPendingTasksComponent,
ModalOverlayComponent, ModalOverlayComponent,
ScrollToTopComponent, ScrollToTopComponent,
@ -354,12 +343,7 @@ registerLocaleData(localeEs, 'es-ES');
GlobalOgbootStatusComponent, GlobalOgbootStatusComponent,
OgrepositoryStatusComponent, OgrepositoryStatusComponent,
OgdhcpStatusComponent, OgdhcpStatusComponent,
StatusLogsComponent, PageNotFoundComponent
ImportLegacyComponent,
PageNotFoundComponent,
OuSelectComponent,
PluginsComponent,
PluginSettingsComponent
], ],
bootstrap: [AppComponent], bootstrap: [AppComponent],
imports: [BrowserModule, imports: [BrowserModule,

View File

@ -1,146 +0,0 @@
.main-content {
padding: 20px;
width: 100%;
box-sizing: border-box;
}
.radio-group {
display: flex;
flex-direction: column;
margin-bottom: 20px;
gap: 10px;
}
.form-container {
display: flex;
flex-direction: column;
gap: 15px;
max-width: 400px;
margin-top: 15px;
}
.help-text {
font-size: 14px;
color: #666;
margin-bottom: -5px;
}
.file-input-container {
display: flex;
align-items: center;
gap: 15px;
}
.file-name {
font-style: italic;
color: #666;
}
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
padding: 40px 20px;
text-align: center;
width: 100%;
box-sizing: border-box;
}
.warning-text {
color: #f44336;
font-weight: bold;
margin-top: 10px;
}
.success-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px;
text-align: center;
gap: 15px;
}
.success-icon {
font-size: 64px;
height: 64px;
width: 64px;
color: #4caf50;
}
.error-banner {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 20px;
text-align: center;
background-color: #ffebee;
border-radius: 8px;
margin-bottom: 20px;
border: 1px solid #ef9a9a;
}
.error-banner h3 {
color: #c62828;
margin-top: 10px;
margin-bottom: 5px;
}
.error-banner p {
color: #c62828;
margin: 0;
}
.error-icon {
font-size: 48px;
height: 48px;
width: 48px;
}
.loader-box {
display: block;
text-align: center;
margin: 30px 0;
}
.loader-box mat-spinner {
margin: 0 auto;
}
.unified-log-box {
display: block;
width: 100%;
box-sizing: border-box;
text-align: left;
margin-top: 30px;
background-color: #1e1e1e;
color: #e0e0e0;
padding: 20px;
border-radius: 6px;
border: 1px solid #333;
}
.unified-log-box h4 {
margin-top: 0;
margin-bottom: 10px;
color: #4caf50;
border-bottom: 1px solid #333;
padding-bottom: 5px;
}
.unified-log-box pre {
white-space: pre-wrap;
word-wrap: break-word;
max-height: 400px;
overflow-y: auto;
font-family: 'Consolas', 'Monaco', monospace;
font-size: 13px;
margin: 0;
}
.full-width-card {
width: 100% !important;
box-sizing: border-box;
}

View File

@ -1,95 +0,0 @@
<div class="main-content">
<div class="header-container">
<div class="header-container-title">
<h2>{{ 'importLegacyDbTitle' | translate }}</h2>
</div>
</div>
<mat-card class="full-width-card">
<mat-card-header>
<mat-card-title>{{ 'importLegacyDbDesc' | translate }}</mat-card-title>
</mat-card-header>
<mat-card-content>
@if (isLoading) {
<div class="loader-box">
<mat-spinner diameter="50"></mat-spinner>
<h3>{{ 'migrationInProgress' | translate }}</h3>
<p class="warning-text">{{ 'migrationWaitWarning' | translate }}</p>
</div>
} @else if (migrationStatus === 'success') {
<div class="success-container">
<mat-icon color="primary" class="success-icon">check_circle</mat-icon>
<h3>{{ 'migrationSuccess' | translate }}</h3>
<p>Los datos han sido migrados correctamente a la nueva versión.</p>
<button mat-raised-button color="primary" (click)="resetForm()">Realizar otra importación</button>
</div>
} @else {
@if (migrationStatus === 'error') {
<div class="error-banner">
<mat-icon color="warn" class="error-icon">error</mat-icon>
<h3>{{ 'migrationError' | translate }}</h3>
<p>Revisa el log en la parte inferior para más detalles o corrige los parámetros e inténtalo de nuevo.</p>
</div>
}
<mat-radio-group [(ngModel)]="importMode" class="radio-group">
<mat-radio-button value="db">{{ 'fromRemoteDb' | translate }}</mat-radio-button>
<mat-radio-button value="file">{{ 'fromSqlFile' | translate }}</mat-radio-button>
</mat-radio-group>
@if (importMode === 'db') {
<form [formGroup]="dbForm" (ngSubmit)="onSubmit()" class="form-container">
<mat-form-field appearance="outline">
<mat-label>{{ 'hostLabel' | translate }}</mat-label>
<input matInput formControlName="legacyHost" placeholder="192.168.1.100">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>{{ 'userLabel' | translate }}</mat-label>
<input matInput formControlName="legacyUser" placeholder="root">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>{{ 'passLabel' | translate }}</mat-label>
<input matInput formControlName="legacyPassword" type="password">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>{{ 'dbLabel' | translate }}</mat-label>
<input matInput formControlName="legacyDb" placeholder="opengnsys">
</mat-form-field>
<button mat-raised-button color="primary" type="submit" [disabled]="dbForm.invalid">
<mat-icon>cloud_download</mat-icon> {{ 'importButton' | translate }}
</button>
</form>
}
@if (importMode === 'file') {
<div class="form-container">
<p class="help-text">{{ 'uploadSqlOrZip' | translate }}</p>
<div class="file-input-container">
<button mat-stroked-button type="button" (click)="fileInput.click()">
<mat-icon>attach_file</mat-icon> {{ 'sqlFileLabel' | translate }}
</button>
<input hidden (change)="onFileSelected($event)" #fileInput type="file" accept=".sql,.zip">
@if (selectedFile) {
<span class="file-name">{{ selectedFile.name }}</span>
}
</div>
<button mat-raised-button color="primary" (click)="onSubmit()" [disabled]="!selectedFile" style="margin-top: 15px;">
<mat-icon>upload_file</mat-icon> {{ 'importButton' | translate }}
</button>
</div>
}
}
@if (outputLog) {
<div class="unified-log-box">
<h4>Consola en vivo:</h4>
<pre>{{ outputLog }}</pre>
</div>
}
</mat-card-content>
</mat-card>
</div>

View File

@ -1,144 +0,0 @@
import { Component, NgZone, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { MatSnackBar } from '@angular/material/snack-bar';
import { TranslateService } from '@ngx-translate/core';
import { ConfigService } from '../../../services/config.service';
@Component({
selector: 'app-import-legacy',
templateUrl: './import-legacy.component.html',
styleUrls: ['./import-legacy.component.css']
})
export class ImportLegacyComponent {
importMode: 'file' | 'db' = 'db';
dbForm: FormGroup;
selectedFile: File | null = null;
isLoading = false;
outputLog = '';
migrationStatus: 'idle' | 'success' | 'error' = 'idle';
constructor(
private fb: FormBuilder,
private http: HttpClient,
private snackBar: MatSnackBar,
private translate: TranslateService,
private configService: ConfigService,
private ngZone: NgZone,
private cdr: ChangeDetectorRef
) {
this.dbForm = this.fb.group({
legacyHost: ['', Validators.required],
legacyUser: ['', Validators.required],
legacyPassword: [''],
legacyDb: ['', Validators.required]
});
}
ngOnInit() {
this.checkMigrationStatus();
}
checkMigrationStatus() {
this.http.get<any>(`${this.configService.apiUrl}/migration/import/status`).subscribe({
next: (response) => {
if (response.isRunning) {
this.isLoading = true;
this.outputLog = response.log || 'Recuperando estado de migración...';
this.connectToMercure();
}
},
error: (error) => {
console.error('Error checking migration status:', error);
}
});
}
private connectToMercure() {
const url = new URL(this.configService.mercureUrl);
url.searchParams.append('topic', '/migration');
const eventSource = new EventSource(url.toString());
eventSource.onmessage = (event) => {
this.ngZone.run(() => {
const data = JSON.parse(event.data);
if (data.type === 'migration_progress') {
this.outputLog = data.output;
this.cdr.detectChanges();
}
else if (data.type === 'migration_result') {
this.isLoading = false;
this.migrationStatus = data.status;
this.outputLog = data.output;
this.cdr.detectChanges();
if (data.status === 'success') {
this.snackBar.open(this.translate.instant('migrationSuccess'), 'OK', { duration: 5000 });
} else {
this.snackBar.open(this.translate.instant('migrationError'), 'OK', { duration: 5000 });
}
eventSource.close();
}
});
};
eventSource.onerror = (err) => {
console.error("Mercure connection error", err);
};
}
onFileSelected(event: any) {
const file = event.target.files[0];
if (file) {
this.selectedFile = file;
}
}
resetForm() {
this.migrationStatus = 'idle';
this.outputLog = '';
this.selectedFile = null;
this.dbForm.reset();
}
onSubmit() {
if (this.importMode === 'file' && !this.selectedFile) {
this.snackBar.open('Please select a file', 'Close', { duration: 3000 });
} else if ((this.importMode === 'db' && this.dbForm.valid) || (this.importMode === 'file' && this.selectedFile)) {
this.isLoading = true;
this.outputLog = '';
this.migrationStatus = 'idle';
let request;
if (this.importMode === 'file') {
const formData = new FormData();
formData.append('sql_file', this.selectedFile!);
request = this.http.post<any>(`${this.configService.apiUrl}/migration/import`, formData);
} else {
request = this.http.post<any>(`${this.configService.apiUrl}/migration/import`, this.dbForm.value);
}
request.subscribe({
next: (response) => {
if (response.status === 'started') {
this.outputLog = 'Proceso de migración en curso. Esperando respuesta del servidor en segundo plano...';
this.connectToMercure();
} else {
this.isLoading = false;
this.migrationStatus = 'success';
this.outputLog = response.output || response.message;
this.snackBar.open(this.translate.instant('migrationSuccess'), 'OK', { duration: 5000 });
}
},
error: (error) => {
this.isLoading = false;
this.migrationStatus = 'error';
const details = error.error?.error || error.error?.details || error.message || 'Unknown error';
this.outputLog = details;
this.snackBar.open(this.translate.instant('migrationError'), 'OK', { duration: 5000 });
}
});
}
}
}

View File

@ -15,45 +15,30 @@
<mat-form-field appearance="fill" class="full-width"> <mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'labelRole' | translate }}</mat-label> <mat-label>{{ 'labelRole' | translate }}</mat-label>
<mat-select formControlName="role" required> <mat-select formControlName="role" required>
@for (group of userGroups; track group['@id']) { <mat-option *ngFor="let group of userGroups" [value]="group['@id']">
<mat-option [value]="group['@id']">
{{ group.name }} {{ group.name }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<app-ou-select <mat-form-field appearance="fill" class="full-width">
class="full-width" <mat-label>{{ 'labelOrganizationalUnit' | translate }}</mat-label>
formControlName="organizationalUnits" <mat-select multiple formControlName="organizationalUnits">
[multiple]="true" <mat-option *ngFor="let unit of organizationalUnits" [value]="unit['@id']">
[units]="organizationalUnits" {{ unit.name }}
[label]="'labelOrganizationalUnit'"> </mat-option>
</app-ou-select> </mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width"> <mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'cardView' | translate }}</mat-label> <mat-label>{{ 'cardView' | translate }}</mat-label>
<mat-select formControlName="groupsView" required> <mat-select formControlName="groupsView" required>
@for (option of views; track option.value) { <mat-option *ngFor="let option of views" [value]="option.value">
<mat-option [value]="option.value">
{{ option.name }} {{ option.name }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'userLanguage' | translate }}</mat-label>
<mat-select formControlName="language">
@for (lang of availableLanguages; track lang.code) {
<mat-option [value]="lang.code">
{{ lang.label }}
</mat-option>
}
</mat-select>
<mat-hint>{{ 'userLanguageHint' | translate }}</mat-hint>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width"> <mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'clientsPerPage' | translate }}</mat-label> <mat-label>{{ 'clientsPerPage' | translate }}</mat-label>
<input matInput formControlName="clientsPerPage" type="number" min="1" [placeholder]="'default20' | translate"> <input matInput formControlName="clientsPerPage" type="number" min="1" [placeholder]="'default20' | translate">

View File

@ -7,7 +7,6 @@ import { ToastrService } from "ngx-toastr";
import { HttpClient } from "@angular/common/http"; import { HttpClient } from "@angular/common/http";
import { DataService } from "../data.service"; import { DataService } from "../data.service";
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
import { DataService as GroupsDataService } from '../../../../groups/services/data.service';
interface UserGroup { interface UserGroup {
'@id': string; '@id': string;
@ -37,28 +36,22 @@ export class AddUserModalComponent implements OnInit {
{ value: 'list', name: 'Listado' }, { value: 'list', name: 'Listado' },
]; ];
readonly availableLanguages: { code: string; label: string }[];
constructor( constructor(
public dialogRef: MatDialogRef<AddUserModalComponent>, public dialogRef: MatDialogRef<AddUserModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: any, @Inject(MAT_DIALOG_DATA) public data: any,
private http: HttpClient, private http: HttpClient,
private fb: FormBuilder, private fb: FormBuilder,
private dataService: DataService, private dataService: DataService,
private groupsDataService: GroupsDataService,
private toastService: ToastrService, private toastService: ToastrService,
private configService: ConfigService private configService: ConfigService
) { ) {
this.baseUrl = this.configService.apiUrl; this.baseUrl = this.configService.apiUrl;
const langs = this.configService.languages;
this.availableLanguages = Object.keys(langs).map(code => ({ code, label: langs[code] }));
this.userForm = this.fb.group({ this.userForm = this.fb.group({
username: ['', Validators.required], username: ['', Validators.required],
password: ['', Validators.required], password: ['', Validators.required],
role: ['', Validators.required], role: ['', Validators.required],
groupsView: ['card', Validators.required], groupsView: ['card', Validators.required],
clientsPerPage: [null, [Validators.min(1)]], clientsPerPage: [null, [Validators.min(1)]],
language: ['es'],
organizationalUnits: [[]] organizationalUnits: [[]]
}); });
@ -73,13 +66,7 @@ export class AddUserModalComponent implements OnInit {
}); });
this.dataService.getOrganizationalUnits().subscribe((data) => { this.dataService.getOrganizationalUnits().subscribe((data) => {
const allUnits = data['hydra:member']; this.organizationalUnits = data['hydra:member'].filter((item: any) => item.type === 'organizational-unit');
this.organizationalUnits = allUnits
.filter((item: any) => item.type === 'organizational-unit')
.map((unit: any) => ({
...unit,
path: this.groupsDataService.getOrganizationalUnitPath(unit, allUnits)
}));
}); });
if (this.data) { if (this.data) {
@ -100,8 +87,7 @@ export class AddUserModalComponent implements OnInit {
role: response.userGroups.length > 0 ? response.userGroups[0]['@id'] : null, role: response.userGroups.length > 0 ? response.userGroups[0]['@id'] : null,
organizationalUnits: organizationalUnitIds, organizationalUnits: organizationalUnitIds,
groupsView: response.groupsView, groupsView: response.groupsView,
clientsPerPage: response.clientsPerPage ?? null, clientsPerPage: response.clientsPerPage ?? null
language: response.language ?? 'es'
}); });
this.userId = response['@id']; this.userId = response['@id'];
@ -122,22 +108,13 @@ export class AddUserModalComponent implements OnInit {
onSubmit(): void { onSubmit(): void {
if (this.userForm.valid) { if (this.userForm.valid) {
const mappedOUs = (this.userForm.value.organizationalUnits || []).map((ou: any) => {
if (typeof ou === 'number' || (typeof ou === 'string' && !ou.includes('/'))) {
const selectedUnit = this.organizationalUnits.find((u: any) => u.id === Number(ou));
return selectedUnit ? (selectedUnit['@id'] || `/organizational-units/${selectedUnit.uuid}`) : ou;
}
return ou;
});
const payload: any = { const payload: any = {
username: this.userForm.value.username, username: this.userForm.value.username,
allowedOrganizationalUnits: mappedOUs, allowedOrganizationalUnits: this.userForm.value.organizationalUnits,
enabled: true, enabled: true,
userGroups: [this.userForm.value.role], userGroups: [this.userForm.value.role],
groupsView: this.userForm.value.groupsView, groupsView: this.userForm.value.groupsView,
clientsPerPage: this.userForm.value.clientsPerPage || null, clientsPerPage: this.userForm.value.clientsPerPage || null
language: this.userForm.value.language || null
}; };
if (!this.userId && this.userForm.value.password) { if (!this.userId && this.userForm.value.password) {

View File

@ -3,14 +3,10 @@
</h2> </h2>
<mat-dialog-content class="dialog-content"> <mat-dialog-content class="dialog-content">
@if (loading) { <mat-spinner class="loading-spinner" *ngIf="loading"></mat-spinner>
<mat-spinner class="loading-spinner"></mat-spinner>
}
@if (!loading) { <div class="task-form" *ngIf="!loading">
<div class="task-form"> <mat-button-toggle-group *ngIf="data?.source === 'assistant'" [(ngModel)]="taskMode" class="task-mode-selection" name="taskMode" appearance="standard">
@if (data?.source === 'assistant') {
<mat-button-toggle-group [(ngModel)]="taskMode" class="task-mode-selection" name="taskMode" appearance="standard">
<mat-button-toggle value="create"> <mat-button-toggle value="create">
<mat-icon>add_task</mat-icon> <mat-icon>add_task</mat-icon>
{{ 'labelCreateTask' | translate }} {{ 'labelCreateTask' | translate }}
@ -20,20 +16,16 @@
{{ 'addToExistingTask' | translate }} {{ 'addToExistingTask' | translate }}
</mat-button-toggle> </mat-button-toggle>
</mat-button-toggle-group> </mat-button-toggle-group>
}
</div> </div>
}
@if (taskMode === 'add') { <div *ngIf="taskMode === 'add'" class="select-task">
<div class="select-task">
<mat-form-field appearance="fill" class="full-width"> <mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectTask' | translate }}</mat-label> <mat-label>{{ 'selectTask' | translate }}</mat-label>
<mat-select [(ngModel)]="selectedExistingTask" name="existingTask"> <mat-select [(ngModel)]="selectedExistingTask" name="existingTask">
@for (task of existingTasks; track task) { <mat-option *ngFor="let task of existingTasks" [value]="task">{{ task.name }}</mat-option>
<mat-option [value]="task">{{ task.name }}</mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="fill" class="full-width"> <mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'executionOrder' | translate }}</mat-label> <mat-label>{{ 'executionOrder' | translate }}</mat-label>
<input <input
@ -46,27 +38,25 @@
> >
</mat-form-field> </mat-form-field>
</div> </div>
}
@if (taskMode === 'create' && taskForm && !loading) { <form *ngIf="taskMode === 'create' && taskForm && !loading" [formGroup]="taskForm" class="task-form">
<form [formGroup]="taskForm" class="task-form">
<mat-form-field appearance="fill" class="full-width"> <mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'labelRoleName' | translate }}</mat-label> <mat-label>{{ 'labelRoleName' | translate }}</mat-label>
<input matInput formControlName="name" [placeholder]="'nameLabel' | translate"> <input matInput formControlName="name" [placeholder]="'nameLabel' | translate">
@if (taskForm.get('name')?.invalid) { <mat-error *ngIf="taskForm.get('name')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
<mat-error>{{ 'requiredFieldError' | translate }}</mat-error>
}
</mat-form-field> </mat-form-field>
<mat-form-field appearance="fill" class="full-width"> <mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'labelNotes' | translate }}</mat-label> <mat-label>{{ 'labelNotes' | translate }}</mat-label>
<textarea matInput formControlName="notes" [placeholder]="'notesPlaceholder' | translate"></textarea> <textarea matInput formControlName="notes" [placeholder]="'notesPlaceholder' | translate"></textarea>
</mat-form-field> </mat-form-field>
@if (!editing) {
<mat-checkbox formControlName="scheduleAfterCreate" class="schedule-checkbox"> <mat-checkbox *ngIf="!editing" formControlName="scheduleAfterCreate" class="schedule-checkbox">
{{ 'scheduleAfterCreate' | translate }} {{ 'scheduleAfterCreate' | translate }}
</mat-checkbox> </mat-checkbox>
}
<mat-divider style="margin: 15px 0;"></mat-divider> <mat-divider style="margin: 15px 0;"></mat-divider>
<mat-form-field appearance="fill" class="full-width"> <mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'labelScope' | translate }}</mat-label> <mat-label>{{ 'labelScope' | translate }}</mat-label>
<mat-select formControlName="scope" (selectionChange)="onScopeChange($event.value)" <mat-select formControlName="scope" (selectionChange)="onScopeChange($event.value)"
@ -78,27 +68,29 @@
<mat-option value="clients">{{ 'labelClients' | translate }}</mat-option> <mat-option value="clients">{{ 'labelClients' | translate }}</mat-option>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
@if (taskForm.get('scope')?.value !== 'clients') {
<app-ou-select <mat-form-field *ngIf="taskForm.get('scope')?.value !== 'clients'" appearance="fill" class="full-width">
class="full-width" <mat-label>{{ 'labelOrganizationalUnit' | translate }}</mat-label>
formControlName="organizationalUnit" <mat-select formControlName="organizationalUnit">
[units]="availableOrganizationalUnits" <mat-option *ngFor="let unit of availableOrganizationalUnits" [value]="unit['@id']">
[label]="'labelOrganizationalUnit'"> <div class="unit-name">{{ unit.name }}</div>
</app-ou-select> <div style="font-size: smaller; color: gray;">{{ unit.path }}</div>
} </mat-option>
@if (taskForm.get('scope')?.value === 'clients') { </mat-select>
<div class="clients-selection"> </mat-form-field>
<div *ngIf="taskForm.get('scope')?.value === 'clients'" class="clients-selection">
<h4>{{ 'selectedClients' | translate }}</h4> <h4>{{ 'selectedClients' | translate }}</h4>
@if (data?.selectedClients && data.selectedClients.length > 0) {
<div class="pre-selected-info"> <div *ngIf="data?.selectedClients && data.selectedClients.length > 0" class="pre-selected-info">
<mat-icon>info</mat-icon> <mat-icon>info</mat-icon>
<span>{{ 'preSelectedInfo' | translate }}</span> <span>{{ 'preSelectedInfo' | translate }}</span>
</div> </div>
}
<div class="clients-list"> <div class="clients-list">
<div class="clients-grid"> <div class="clients-grid">
@for (client of clients; track client) {
<mat-card <mat-card
*ngFor="let client of clients"
class="client-card" class="client-card"
[class.pre-selected]="isClientPreSelected(client)" [class.pre-selected]="isClientPreSelected(client)"
> >
@ -117,13 +109,10 @@
</mat-icon> </mat-icon>
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
}
</div> </div>
</div> </div>
</div> </div>
}
</form> </form>
}
</mat-dialog-content> </mat-dialog-content>
<mat-dialog-actions class="action-container"> <mat-dialog-actions class="action-container">

View File

@ -10,7 +10,6 @@ import {of} from "rxjs";
import {startWith, switchMap} from "rxjs/operators"; import {startWith, switchMap} from "rxjs/operators";
import {CreateTaskScheduleComponent} from "../create-task-schedule/create-task-schedule.component"; import {CreateTaskScheduleComponent} from "../create-task-schedule/create-task-schedule.component";
import {ShowTaskScriptComponent} from "../show-task-script/show-task-script.component"; import {ShowTaskScriptComponent} from "../show-task-script/show-task-script.component";
import { DataService as GroupsDataService } from "../../../groups/services/data.service";
@Component({ @Component({
selector: 'app-create-task', selector: 'app-create-task',
@ -43,8 +42,7 @@ export class CreateTaskComponent implements OnInit {
private toastr: ToastrService, private toastr: ToastrService,
private dialog: MatDialog, private dialog: MatDialog,
public dialogRef: MatDialogRef<CreateTaskComponent>, public dialogRef: MatDialogRef<CreateTaskComponent>,
@Inject(MAT_DIALOG_DATA) public data: any, @Inject(MAT_DIALOG_DATA) public data: any
private dataService: GroupsDataService
) { ) {
this.baseUrl = this.configService.apiUrl; this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/command-tasks`; this.apiUrl = `${this.baseUrl}/command-tasks`;
@ -216,10 +214,7 @@ export class CreateTaskComponent implements OnInit {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=100`).subscribe( this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=100`).subscribe(
(data) => { (data) => {
this.allOrganizationalUnits = data['hydra:member'].map((unit: any) => ({ this.allOrganizationalUnits = data['hydra:member'];
...unit,
path: this.dataService.getOrganizationalUnitPath(unit, data['hydra:member'])
}));
this.availableOrganizationalUnits = [...this.allOrganizationalUnits]; this.availableOrganizationalUnits = [...this.allOrganizationalUnits];
resolve(); resolve();
}, },
@ -281,12 +276,7 @@ export class CreateTaskComponent implements OnInit {
payload.clients = this.selectedClients.map(client => client['@id'] ? client['@id'] : client.uuid); payload.clients = this.selectedClients.map(client => client['@id'] ? client['@id'] : client.uuid);
payload.organizationalUnit = null; payload.organizationalUnit = null;
} else { } else {
let ou = formData.organizationalUnit; payload.organizationalUnit = formData.organizationalUnit;
if (typeof ou === 'number' || (typeof ou === 'string' && !ou.includes('/'))) {
const selectedUnit = this.availableOrganizationalUnits.find((u: any) => u.id === Number(ou));
ou = selectedUnit ? (selectedUnit['@id'] || `/organizational-units/${selectedUnit.uuid}`) : ou;
}
payload.organizationalUnit = ou;
} }
if (this.editing) { if (this.editing) {

View File

@ -321,21 +321,18 @@ mat-spinner {
color: #666; color: #666;
} }
/* Vista previa del script en celda (una sola línea, altura de fila fija) */ /* Contenido del script en celda */
.script-preview-cell { .script-content-cell {
display: flex; background-color: #f5f5f5;
align-items: center; padding: 8px 12px;
gap: 4px; border: 1px solid #e0e0e0;
max-width: 260px; border-radius: 4px;
} font-family: 'Monaco', 'Menlo', monospace;
white-space: pre-wrap;
.script-preview-text { font-size: 12px;
white-space: nowrap; max-width: 300px;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
font-family: 'Monaco', 'Menlo', monospace;
font-size: 12px;
color: #555;
} }
.no-content-hint { .no-content-hint {

View File

@ -50,11 +50,8 @@
<ng-container matColumnDef="content"> <ng-container matColumnDef="content">
<th mat-header-cell *matHeaderCellDef>{{ 'labelScript' | translate }}</th> <th mat-header-cell *matHeaderCellDef>{{ 'labelScript' | translate }}</th>
<td mat-cell *matCellDef="let item"> <td mat-cell *matCellDef="let item">
<div *ngIf="item.content" class="script-preview-cell"> <div *ngIf="item.content" class="script-content-cell">
<span class="script-preview-text">{{ item.content }}</span> <code>{{ item.content }}</code>
<button mat-icon-button (click)="openScriptModal(item.content)" [matTooltip]="'viewScript' | translate">
<mat-icon>visibility</mat-icon>
</button>
</div> </div>
<span *ngIf="!item.content" class="no-content-hint"> <span *ngIf="!item.content" class="no-content-hint">
({{ 'viewParameters' | translate }}) ({{ 'viewParameters' | translate }})

View File

@ -10,7 +10,6 @@ import { CreateTaskScheduleComponent } from "../create-task-schedule/create-task
import { CreateTaskScriptComponent } from "../create-task-script/create-task-script.component"; import { CreateTaskScriptComponent } from "../create-task-script/create-task-script.component";
import { DeleteModalComponent } from "../../../../shared/delete_modal/delete-modal/delete-modal.component"; import { DeleteModalComponent } from "../../../../shared/delete_modal/delete-modal/delete-modal.component";
import { ViewParametersModalComponent } from "./view-parameters-modal/view-parameters-modal.component"; import { ViewParametersModalComponent } from "./view-parameters-modal/view-parameters-modal.component";
import { ViewScriptModalComponent } from "./view-script-modal/view-script-modal.component";
@Component({ @Component({
selector: 'app-show-task-script', selector: 'app-show-task-script',
@ -120,13 +119,6 @@ export class ShowTaskScriptComponent implements OnInit {
}); });
} }
openScriptModal(content: string): void {
this.dialog.open(ViewScriptModalComponent, {
width: '700px',
data: content
});
}
createNewScript(): void { createNewScript(): void {
const dialogRef = this.dialog.open(CreateTaskScriptComponent, { const dialogRef = this.dialog.open(CreateTaskScriptComponent, {
width: '800px', width: '800px',

View File

@ -1,12 +0,0 @@
.script-full-content {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 13px;
white-space: pre-wrap;
word-break: break-word;
background: #f5f5f5;
border: 1px solid #e0e0e0;
border-radius: 4px;
padding: 12px;
max-height: 60vh;
overflow-y: auto;
}

View File

@ -1,7 +0,0 @@
<h2 mat-dialog-title>{{ 'labelScript' | translate }}</h2>
<mat-dialog-content>
<pre class="script-full-content">{{ data }}</pre>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button (click)="close()">{{ 'buttonClose' | translate }}</button>
</mat-dialog-actions>

View File

@ -1,18 +0,0 @@
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
@Component({
selector: 'app-view-script-modal',
templateUrl: './view-script-modal.component.html',
styleUrl: './view-script-modal.component.css'
})
export class ViewScriptModalComponent {
constructor(
public dialogRef: MatDialogRef<ViewScriptModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {}
close(): void {
this.dialogRef.close();
}
}

View File

@ -6,7 +6,7 @@
<h2 joyrideStep="titleStep" text="{{ 'titleStepText' | translate }}">{{ 'CommandsTitle' | translate }}</h2> <h2 joyrideStep="titleStep" text="{{ 'titleStepText' | translate }}">{{ 'CommandsTitle' | translate }}</h2>
</div> </div>
<div class="command-button-row" joyrideStep="addCommandStep" text="{{ 'addCommandStepText' | translate }}"> <div class="command-button-row" joyrideStep="addCommandStep" text="{{ 'addCommandStepText' | translate }}">
<button *ngIf="auth.isSuperAdmin" class="action-button" (click)="openCreateCommandModal()">{{ 'addCommand' | translate }}</button> <button class="action-button" (click)="openCreateCommandModal()">{{ 'addCommand' | translate }}</button>
</div> </div>
</div> </div>
@ -44,8 +44,8 @@
<th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'actions' | translate }}</th> <th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'actions' | translate }}</th>
<td mat-cell *matCellDef="let command" style="text-align: center;" joyrideStep="actionsStep" text="{{ 'actionsStepText' | translate }}"> <td mat-cell *matCellDef="let command" style="text-align: center;" joyrideStep="actionsStep" text="{{ 'actionsStepText' | translate }}">
<button mat-icon-button color="info" (click)="viewDetails($event, command)"><mat-icon>visibility</mat-icon></button> <button mat-icon-button color="info" (click)="viewDetails($event, command)"><mat-icon>visibility</mat-icon></button>
<button *ngIf="auth.isSuperAdmin" mat-icon-button color="primary" [disabled]="command.readOnly" (click)="editCommand($event, command)"><mat-icon>edit</mat-icon></button> <button mat-icon-button color="primary" [disabled]="command.readOnly" (click)="editCommand($event, command)"><mat-icon>edit</mat-icon></button>
<button *ngIf="auth.isSuperAdmin" mat-icon-button color="warn" [disabled]="command.readOnly" (click)="deleteCommand($event, command)"><mat-icon>delete</mat-icon></button> <button mat-icon-button color="warn" [disabled]="command.readOnly" (click)="deleteCommand($event, command)"><mat-icon>delete</mat-icon></button>
</td> </td>
</ng-container> </ng-container>

View File

@ -10,7 +10,6 @@ import { DeleteModalComponent } from '../../../shared/delete_modal/delete-modal/
import { MatTableDataSource } from '@angular/material/table'; import { MatTableDataSource } from '@angular/material/table';
import { DatePipe } from '@angular/common'; import { DatePipe } from '@angular/common';
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
import { AuthService } from '@services/auth.service';
import { JoyrideService } from 'ngx-joyride'; import { JoyrideService } from 'ngx-joyride';
@Component({ @Component({
@ -20,7 +19,6 @@ import { JoyrideService } from 'ngx-joyride';
}) })
export class CommandsComponent implements OnInit { export class CommandsComponent implements OnInit {
public translate = inject(TranslateService); public translate = inject(TranslateService);
public auth = inject(AuthService);
baseUrl: string; baseUrl: string;
private apiUrl: string; private apiUrl: string;
dataSource = new MatTableDataSource<any>(); dataSource = new MatTableDataSource<any>();

View File

@ -99,10 +99,6 @@
box-shadow: 0px 0px 0px rgba(0,0,0,0.2); box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
} }
.section-divider {
margin-top: 20px;
}
@media (max-width: 600px) { @media (max-width: 600px) {
.form-field { .form-field {
width: 100%; width: 100%;

View File

@ -1,10 +1,9 @@
<h2 mat-dialog-title> {{ 'selectPartitionToBootOs' | translate }}</h2> <h2 mat-dialog-title> {{ 'selectPartitionToBootOs' | translate }}</h2>
<mat-dialog-content class="dialog-content"> <mat-dialog-content class="dialog-content">
@if (loading) { <mat-spinner class="loading-spinner" *ngIf="loading"></mat-spinner>
<mat-spinner class="loading-spinner"></mat-spinner>
} @else { <div *ngIf="!loading" class="select-container">
<div class="select-container">
<mat-expansion-panel> <mat-expansion-panel>
<mat-expansion-panel-header> <mat-expansion-panel-header>
<mat-panel-title> {{ 'labelClients' | translate }}</mat-panel-title> <mat-panel-title> {{ 'labelClients' | translate }}</mat-panel-title>
@ -20,8 +19,7 @@
</div> </div>
<div class="clients-grid"> <div class="clients-grid">
@for (client of data.clients; track client.uuid) { <div *ngFor="let client of data.clients" class="client-item">
<div class="client-item">
<div class="client-card" <div class="client-card"
(click)="toggleClientSelection(client)" (click)="toggleClientSelection(client)"
[ngClass]="{'selected-client': client.selected}" > [ngClass]="{'selected-client': client.selected}" >
@ -47,24 +45,51 @@
</mat-radio-group> </mat-radio-group>
</div> </div>
</div> </div>
}
</div> </div>
</mat-expansion-panel> </mat-expansion-panel>
</div> </div>
<mat-divider class="section-divider"></mat-divider> <mat-divider *ngIf="!loading" style="margin-top: 20px;"></mat-divider>
<div class="partition-table-container"> <div *ngIf="!loading" class="partition-table-container">
<app-disk-partition-selector <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
[(selectedPartition)]="selectedPartition" <ng-container matColumnDef="select">
[partitions]="dataSource.data" <th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: start">{{ 'buttonSelectPartition' | translate }}</th>
[columns]="columns" <td mat-cell *matCellDef="let row">
[displayedColumns]="displayedColumns" <mat-radio-group
[disableCondition]="isPartitionDisabled"> [(ngModel)]="selectedPartition"
</app-disk-partition-selector> [disabled]="!row.operativeSystem"
>
<mat-radio-button [value]="row">
</mat-radio-button>
</mat-radio-group>
</td>
</ng-container>
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header | translate }} </th>
<td mat-cell *matCellDef="let image">
<ng-container *ngIf="column.columnDef !== 'size'">
{{ column.cell(image) }}
</ng-container>
<ng-container *ngIf="column.columnDef === 'size'">
<div style="display: flex; flex-direction: column;">
<span> {{ image.size }} MB</span>
<span style="font-size: 0.75rem; color: gray;">{{ image.size / 1024 }} GB</span>
</div>
</ng-container>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div> </div>
}
</mat-dialog-content> </mat-dialog-content>
<div mat-dialog-actions class="action-container"> <div mat-dialog-actions class="action-container">

View File

@ -20,7 +20,6 @@ export class BootSoPartitionComponent implements OnInit {
clientId: string | null = null; clientId: string | null = null;
selectedClients: any[] = []; selectedClients: any[] = [];
selectedModelClient: any = null; selectedModelClient: any = null;
partitions: any[] = [];
filteredPartitions: any[] = []; filteredPartitions: any[] = [];
allSelected: boolean = false; allSelected: boolean = false;
clientData: any[] = []; clientData: any[] = [];
@ -60,10 +59,6 @@ export class BootSoPartitionComponent implements OnInit {
displayedColumns = ['select', ...this.columns.map(column => column.columnDef)]; displayedColumns = ['select', ...this.columns.map(column => column.columnDef)];
isPartitionDisabled = (partition: any): boolean => {
return !partition.operativeSystem;
};
constructor( constructor(
@Inject(MAT_DIALOG_DATA) public data: { clients: any }, @Inject(MAT_DIALOG_DATA) public data: { clients: any },
private dialogRef: MatDialogRef<BootSoPartitionComponent>, private dialogRef: MatDialogRef<BootSoPartitionComponent>,
@ -94,10 +89,9 @@ export class BootSoPartitionComponent implements OnInit {
this.http.get(url).subscribe( this.http.get(url).subscribe(
(response: any) => { (response: any) => {
if (response.partitions) { if (response.partitions) {
this.partitions = Array.isArray(response.partitions) this.dataSource.data = response.partitions.filter((partition: any) => {
? response.partitions.filter((p: any) => p.partitionCode !== 'CACHE' && p.partitionCode !== 'EMPTY') return partition.partitionNumber !== 0;
: []; });
this.dataSource.data = this.partitions;
} }
}, },
(error) => { (error) => {
@ -113,7 +107,7 @@ export class BootSoPartitionComponent implements OnInit {
updateSelectedClients() { updateSelectedClients() {
this.selectedClients = this.data.clients.filter( this.selectedClients = this.data.clients.filter(
(client: { selected: boolean }) => client.selected (client: { selected: boolean; state: string }) => client.selected && client.state === "og-live"
); );
if (!this.selectedClients.includes(this.selectedModelClient)) { if (!this.selectedClients.includes(this.selectedModelClient)) {
@ -124,10 +118,11 @@ export class BootSoPartitionComponent implements OnInit {
toggleSelectAll() { toggleSelectAll() {
this.allSelected = !this.allSelected; this.allSelected = !this.allSelected;
this.data.clients.forEach((client: { selected: boolean }) => { this.data.clients.forEach((client: { selected: boolean; status: string }) => {
if (client.status === "og-live") {
client.selected = this.allSelected; client.selected = this.allSelected;
}
}); });
this.updateSelectedClients();
} }
close() { close() {

View File

@ -1,53 +1,24 @@
@switch (buttonType) { <ng-container [ngSwitch]="buttonType">
@case ('icon') { <button *ngSwitchCase="'icon'" mat-icon-button color="primary" [matMenuTriggerFor]="commandMenu"
<button mat-icon-button color="primary" [matMenuTriggerFor]="commandMenu" [disabled]="disabled"> [disabled]="disabled">
<mat-icon>{{ icon }}</mat-icon> <mat-icon>{{ icon }}</mat-icon>
</button> </button>
}
@case ('text') { <button class="action-button" [disabled]="clientData.length === 0 || disabled" *ngSwitchCase="'text'"
<button class="action-button" [disabled]="clientData.length === 0 || disabled" [matMenuTriggerFor]="commandMenu"> [matMenuTriggerFor]="commandMenu">
{{ buttonText }} {{ buttonText }}
</button> </button>
}
@case ('menu-item') { <button mat-menu-item *ngSwitchCase="'menu-item'" [matMenuTriggerFor]="commandMenu" [disabled]="disabled">
<button mat-menu-item [matMenuTriggerFor]="commandMenu" [disabled]="disabled">
<mat-icon>{{ icon }}</mat-icon> <mat-icon>{{ icon }}</mat-icon>
<span>{{ buttonText }}</span> <span>{{ buttonText }}</span>
</button> </button>
} </ng-container>
}
<mat-menu #commandMenu="matMenu"> <mat-menu #commandMenu="matMenu">
@for (command of arrayCommands; track command.slug) { <button mat-menu-item [disabled]="command.disabled
<button mat-menu-item [disabled]="command.disabled || (command.slug === 'create-image' && clientData.length > 1)" || (command.slug === 'create-image' && clientData.length > 1)" *ngFor="let command of arrayCommands"
(click)="onCommandSelect(command.slug)"> (click)="onCommandSelect(command.slug)">
@if (command.icon) { {{ command.translationKey | translate }}
<mat-icon>{{ command.icon }}</mat-icon>
}
<span>{{ command.translationKey ? (command.translationKey | translate) : (command.label || command.slug) }}</span>
</button> </button>
}
@if (pluginGroups.length > 0) {
<mat-divider></mat-divider>
@for (group of pluginGroups; track group.plugin.name) {
<button mat-menu-item [matMenuTriggerFor]="pluginSubMenu">
@if (group.plugin.icon) {
<mat-icon>{{ group.plugin.icon }}</mat-icon>
}
<span>{{ group.plugin.titleKey ? (group.plugin.titleKey | translate) : group.plugin.title }}</span>
</button>
<mat-menu #pluginSubMenu="matMenu">
@for (cmd of group.commands; track cmd.slug) {
<button mat-menu-item [disabled]="cmd.disabled" (click)="onCommandSelect(cmd.slug)">
@if (cmd.icon) {
<mat-icon>{{ cmd.icon }}</mat-icon>
}
<span>{{ (cmd.translationKey || cmd.labelKey) ? ((cmd.translationKey || cmd.labelKey) | translate) : cmd.label }}</span>
</button>
}
</mat-menu>
}
}
</mat-menu> </mat-menu>

View File

@ -10,10 +10,6 @@ import { MatDialog } from "@angular/material/dialog";
import { RemoveCacheImageComponent } from "./remove-cache-image/remove-cache-image.component"; import { RemoveCacheImageComponent } from "./remove-cache-image/remove-cache-image.component";
import { AuthService } from '@services/auth.service'; import { AuthService } from '@services/auth.service';
import {SoftwareProfilePartitionComponent} from "./software-profile-partition/software-profile-partition.component"; import {SoftwareProfilePartitionComponent} from "./software-profile-partition/software-profile-partition.component";
import { QueueConfirmationModalComponent } from '../../../../shared/queue-confirmation-modal/queue-confirmation-modal.component';
import { PluginCommandModalComponent } from '../../../../shared/plugin-command-modal/plugin-command-modal.component';
import { ExecuteTaskNowComponent } from './execute-task-now/execute-task-now.component';
import { PluginService, PluginCommand } from '@services/plugin.service';
@Component({ @Component({
selector: 'app-execute-command', selector: 'app-execute-command',
@ -23,8 +19,6 @@ import { PluginService, PluginCommand } from '@services/plugin.service';
export class ExecuteCommandComponent implements OnInit { export class ExecuteCommandComponent implements OnInit {
public translate = inject(TranslateService); public translate = inject(TranslateService);
@Input() runScriptContext: any = null; @Input() runScriptContext: any = null;
@Input() organizationalUnit: any = null;
@Input() showOnlyDirectClients: boolean = false;
@Input() clientState: string = 'off'; @Input() clientState: string = 'off';
@Input() clientData: any[] = []; @Input() clientData: any[] = [];
@Input() buttonType: 'icon' | 'text' | 'menu-item' = 'icon'; @Input() buttonType: 'icon' | 'text' | 'menu-item' = 'icon';
@ -33,13 +27,12 @@ export class ExecuteCommandComponent implements OnInit {
@Input() disabled: boolean = false; @Input() disabled: boolean = false;
baseUrl: string; baseUrl: string;
loading: boolean = true; loading: boolean = true;
isFetchingOuClients: boolean = false;
arrayCommands: any[] = [ arrayCommands: any[] = [
{ translationKey: 'executeCommands.powerOn', slug: 'power-on', disabled: false }, { translationKey: 'executeCommands.powerOn', slug: 'power-on', disabled: false },
{ translationKey: 'executeCommands.powerOff', slug: 'power-off', disabled: false }, { translationKey: 'executeCommands.powerOff', slug: 'power-off', disabled: false },
{ translationKey: 'executeCommands.reboot', slug: 'reboot', disabled: false }, { translationKey: 'executeCommands.reboot', slug: 'reboot', disabled: false },
{ translationKey: 'executeCommands.login', slug: 'login', disabled: false }, { translationKey: 'executeCommands.login', slug: 'login', disabled: true },
{ translationKey: 'executeCommands.createImage', slug: 'create-image', disabled: false }, { translationKey: 'executeCommands.createImage', slug: 'create-image', disabled: false },
{ translationKey: 'executeCommands.deployImage', slug: 'deploy-image', disabled: false }, { translationKey: 'executeCommands.deployImage', slug: 'deploy-image', disabled: false },
{ translationKey: 'executeCommands.deleteImageCache', slug: 'remove-cache-image', disabled: false }, { translationKey: 'executeCommands.deleteImageCache', slug: 'remove-cache-image', disabled: false },
@ -49,7 +42,6 @@ export class ExecuteCommandComponent implements OnInit {
{ translationKey: 'executeCommands.runScript', slug: 'run-script', disabled: false }, { translationKey: 'executeCommands.runScript', slug: 'run-script', disabled: false },
{ translationKey: 'executeCommands.refresh', slug: 'refresh', disabled: false }, { translationKey: 'executeCommands.refresh', slug: 'refresh', disabled: false },
{ translationKey: 'executeCommands.deleteLease', slug: 'delete-lease', disabled: false }, { translationKey: 'executeCommands.deleteLease', slug: 'delete-lease', disabled: false },
{ translationKey: 'executeCommands.executeTask', slug: 'execute-task', disabled: false },
]; ];
client: any = {}; client: any = {};
@ -61,28 +53,15 @@ export class ExecuteCommandComponent implements OnInit {
private toastService: ToastrService, private toastService: ToastrService,
public auth: AuthService, public auth: AuthService,
private dialog: MatDialog, private dialog: MatDialog,
public pluginService: PluginService,
) { ) {
this.baseUrl = this.configService.apiUrl; this.baseUrl = this.configService.apiUrl;
} }
pluginGroups: any[] = [];
ngOnInit(): void { ngOnInit(): void {
this.clientData = this.clientData || []; this.clientData = this.clientData || [];
const allowed = this.getAllowedCommandsByRole(); const allowed = this.getAllowedCommandsByRole();
this.arrayCommands = this.arrayCommands.filter(c => allowed.includes(c.slug)); this.arrayCommands = this.arrayCommands.filter(c => allowed.includes(c.slug));
// Punto de anclaje reactivo para grupos de comandos aportados por plugins
this.pluginGroups = this.pluginService.getPluginGroups();
this.pluginService.plugins$.subscribe(() => {
this.pluginGroups = this.pluginService.getPluginGroups();
this.updateCommandStates();
});
this.pluginService.statusUpdates$.subscribe(() => {
this.updateCommandStates();
});
this.updateCommandStates(); this.updateCommandStates();
} }
@ -101,15 +80,13 @@ export class ExecuteCommandComponent implements OnInit {
'power-off', 'power-off',
'reboot', 'reboot',
'login', 'login',
'create-image',
'deploy-image', 'deploy-image',
'software-inventory', 'software-inventory',
'hardware-inventory', 'hardware-inventory',
'remove-cache-image', 'remove-cache-image',
'partition', 'partition',
'refresh', 'refresh',
'delete-lease', 'delete-lease'
'execute-task'
], ],
'ou-minimal': [ 'ou-minimal': [
'power-on', 'power-on',
@ -131,127 +108,40 @@ export class ExecuteCommandComponent implements OnInit {
states = [this.clientState]; states = [this.clientState];
} }
const hasClients = this.clientData.length > 0 || !!this.clientState; const allOffOrDisconnected = states.every(state => state === 'off' || state === 'disconnected');
const allSameState = states.every(state => state === states[0]);
const multipleClients = this.clientData.length > 1; const multipleClients = this.clientData.length > 1;
const hasOgLive = states.some(state => state === 'og-live');
// Acciones que admiten encolado o son independientes del estado del cliente
const queueableOrStateAgnostic = [
'power-on',
'power-off',
'reboot',
'login',
'deploy-image',
'partition',
'run-script',
'execute-task',
'delete-lease'
];
this.arrayCommands = this.arrayCommands.map(command => { this.arrayCommands = this.arrayCommands.map(command => {
if (!hasClients) { if (allOffOrDisconnected) {
command.disabled = true; command.disabled = command.slug !== 'power-on' && command.slug !== 'create-image';
return command; } else if (allSameState) {
if (states[0] === 'off' || states[0] === 'disconnected') {
command.disabled = !['power-on', 'create-image'].includes(command.slug);
} else {
command.disabled = !['power-off', 'reboot', 'login', 'create-image', 'deploy-image', 'remove-cache-image', 'partition', 'run-script', 'software-inventory', 'hardware-inventory', 'refresh'].includes(command.slug);
} }
} else {
// Restricciones lógicas estrictas if (command.slug === 'software-inventory') {
if (command.slug === 'create-image') { command.disabled = multipleClients;
command.disabled = multipleClients || !hasOgLive; } else if (
} else if (command.slug === 'hardware-inventory' || command.slug === 'software-inventory') { ['power-on', 'power-off', 'reboot', 'login', 'deploy-image', 'partition', 'remove-cache-image', 'run-script', 'create-image'].includes(command.slug)
command.disabled = multipleClients || !hasOgLive; ) {
} else if (command.slug === 'remove-cache-image') {
command.disabled = !hasOgLive;
} else if (command.slug === 'refresh') {
command.disabled = !hasOgLive;
} else if (queueableOrStateAgnostic.includes(command.slug)) {
command.disabled = false; command.disabled = false;
} else { } else {
command.disabled = false; command.disabled = true;
}
}
if (command.slug === 'refresh') {
command.disabled = !states.every(state => state === 'og-live');
} }
return command; return command;
}); });
if (this.pluginGroups && this.pluginGroups.length > 0) {
const clientsToCheck = this.clientData.length > 0
? this.clientData
: (this.clientState ? [{ status: this.clientState }] : []);
for (const group of this.pluginGroups) {
for (const cmd of group.commands) {
cmd.disabled = !hasClients || !this.pluginService.isCommandSupportedForClients(cmd, clientsToCheck, group.plugin.name);
// Adaptar dinámicamente la etiqueta de activar/desactivar en ogaquarium si hay un solo cliente seleccionado
if (cmd.slug === 'ogaquarium-toggle-status' && this.clientData.length === 1) {
const client = this.clientData[0];
const idKey = client.id ? String(client.id) : null;
const uuidKey = client.uuid || client.name;
const currentStatus = (idKey ? this.pluginService.getPluginStatus(group.plugin.name, idKey) : null)
|| (uuidKey ? this.pluginService.getPluginStatus(group.plugin.name, uuidKey) : null)
|| 'DISABLED';
if (currentStatus === 'DISABLED') {
cmd.label = this.translate.instant('ogaquarium.commands.activate') || 'Activar puesto';
} else {
cmd.label = this.translate.instant('ogaquarium.commands.deactivate') || 'Desactivar puesto';
}
cmd.labelKey = undefined;
}
}
}
}
} }
onCommandSelect(action: any): void { onCommandSelect(action: any): void {
if (this.organizationalUnit && this.organizationalUnit.id) {
this.fetchClientsForOuAndExecute(action);
return;
}
this.executeAction(action);
}
private fetchClientsForOuAndExecute(action: any): void {
if (this.isFetchingOuClients) {
return;
}
this.isFetchingOuClients = true;
const unitId = this.organizationalUnit.id;
this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${unitId}&page=1&itemsPerPage=10000`).subscribe({
next: (response) => {
this.isFetchingOuClients = false;
let allClients: any[] = response['hydra:member'] || [];
if (this.showOnlyDirectClients && this.organizationalUnit['@id']) {
allClients = allClients.filter((client: any) =>
client.organizationalUnit?.['@id'] === this.organizationalUnit['@id']
);
}
if (allClients.length === 0) {
this.toastService.warning(this.translate.instant('thisOrganizationalUnitDoesNotHave') || 'Esta unidad organizativa no tiene clientes.');
return;
}
this.clientData = allClients;
this.executeAction(action);
},
error: (error) => {
this.isFetchingOuClients = false;
this.toastService.error(this.translate.instant('errorLoadingClients1') || 'Error al cargar los clientes');
}
});
}
private executeAction(action: any): void {
// Punto de anclaje para ejecución de comandos aportados por plugins
const pluginCmd = this.pluginService.findCommand(action);
if (pluginCmd) {
this.executePluginCommand(pluginCmd);
return;
}
if (action === 'partition') { if (action === 'partition') {
this.openPartitionAssistant(); this.openPartitionAssistant();
} }
@ -303,37 +193,19 @@ export class ExecuteCommandComponent implements OnInit {
if (action === 'delete-lease') { if (action === 'delete-lease') {
this.deleteClientLease(); this.deleteClientLease();
} }
if (action === 'execute-task') {
this.openExecuteTaskModal();
}
}
openExecuteTaskModal(): void {
this.dialog.open(ExecuteTaskNowComponent, {
width: '500px',
height: 'auto',
data: { clients: this.clientData }
});
} }
rebootClient(): void { rebootClient(): void {
const dialogRef = this.dialog.open(QueueConfirmationModalComponent, {
width: '400px',
data: { clients: this.clientData }
});
dialogRef.afterClosed().subscribe((queue: boolean | undefined) => {
if (queue === undefined) return;
this.http.post(`${this.baseUrl}/clients/server/reboot`, { this.http.post(`${this.baseUrl}/clients/server/reboot`, {
clients: this.clientData.map((client: any) => client['@id']), clients: this.clientData.map((client: any) => client['@id'])
queue
}).subscribe( }).subscribe(
() => { this.toastService.success(this.translate.instant('clientUpdatedSuccessfully')); }, response => {
(error: any) => { this.toastService.error(error.error['hydra:description'] || 'Error de conexión con el cliente'); } this.toastService.success(this.translate.instant('clientUpdatedSuccessfully'));
},
error => {
this.toastService.error(error.error['hydra:description'] || 'Error de conexión con el cliente');
}
); );
});
} }
refreshClient(): void { refreshClient(): void {
@ -460,22 +332,16 @@ export class ExecuteCommandComponent implements OnInit {
} }
powerOffClient(): void { powerOffClient(): void {
const dialogRef = this.dialog.open(QueueConfirmationModalComponent, {
width: '400px',
data: { clients: this.clientData }
});
dialogRef.afterClosed().subscribe((queue: boolean | undefined) => {
if (queue === undefined) return;
this.http.post(`${this.baseUrl}/clients/server/power-off`, { this.http.post(`${this.baseUrl}/clients/server/power-off`, {
clients: this.clientData.map((client: any) => client['@id']), clients: this.clientData.map((client: any) => client['@id'])
queue
}).subscribe( }).subscribe(
() => { this.toastService.success(this.translate.instant('shutdownRequestSentCorrectly')); }, response => {
(error: any) => { this.toastService.error(error.error['hydra:description'] || 'Error de conexión con el cliente'); } this.toastService.success(this.translate.instant('shutdownRequestSentCorrectly'));
},
error => {
this.toastService.error(error.error['hydra:description'] || 'Error de conexión con el cliente');
}
); );
});
} }
openPartitionAssistant(): void { openPartitionAssistant(): void {
@ -560,102 +426,4 @@ export class ExecuteCommandComponent implements OnInit {
} }
}); });
} }
private executePluginCommand(pluginCmd: PluginCommand): void {
if (!this.clientData || this.clientData.length === 0) {
this.toastService.warning('No hay ningún equipo seleccionado para ejecutar esta acción.', pluginCmd.label);
return;
}
const hasParams = !!(pluginCmd.params && pluginCmd.params.length > 0);
const hasConfirm = !!(pluginCmd.confirm || pluginCmd.confirmKey);
if (hasParams || hasConfirm) {
const dialogRef = this.dialog.open(PluginCommandModalComponent, {
width: '450px',
data: {
command: pluginCmd,
clients: this.clientData
}
});
dialogRef.afterClosed().subscribe((result: any) => {
if (!result || !result.confirmed) {
return; // Cancelado por el usuario
}
const customParams = result.params || {};
this.promptQueueAndSendPluginCommand(pluginCmd, customParams);
});
return;
}
this.promptQueueAndSendPluginCommand(pluginCmd, {});
}
private promptQueueAndSendPluginCommand(pluginCmd: PluginCommand, extraParams: Record<string, any>): void {
const requiredOs = (pluginCmd.os || []).map(os => os.toLowerCase());
// 1. Equipos en un sistema operativo no coincidente (ej. Linux u og-live cuando se requiere Windows)
const incompatibleRunningClients = this.clientData.filter(c => {
const status = (c.status || '').toLowerCase();
const isOnline = status !== 'off' && status !== 'disconnected' && status !== '';
if (!isOnline || requiredOs.length === 0) return false;
return !requiredOs.some(req => status.includes(req));
});
// 2. Equipos apagados o desconectados
const offlineClients = this.clientData.filter(c => {
const status = (c.status || '').toLowerCase();
return !status || status === 'off' || status === 'disconnected';
});
// Si hay equipos no listos inmediatamente (apagados o en otro SO), ofrecer encolado
if (offlineClients.length > 0 || incompatibleRunningClients.length > 0) {
const dialogRef = this.dialog.open(QueueConfirmationModalComponent, {
width: '400px',
data: { clients: this.clientData }
});
dialogRef.afterClosed().subscribe((queue: boolean | undefined) => {
if (queue === undefined) {
// El usuario canceló o cerró el modal
return;
}
this.sendPluginCommandRequest(pluginCmd, queue, extraParams);
});
return;
}
// 3. Todos los equipos están en línea en el sistema operativo correcto
this.sendPluginCommandRequest(pluginCmd, false, extraParams);
}
private sendPluginCommandRequest(pluginCmd: PluginCommand, queue: boolean, extraParams: Record<string, any> = {}): void {
if (!pluginCmd.endpoint) {
this.toastService.error('El comando no especifica un endpoint de ejecución', pluginCmd.label);
return;
}
const cleanEndpoint = pluginCmd.endpoint.replace(/^\/api/, '');
const url = `${this.baseUrl}${cleanEndpoint}`;
const clientIds = this.clientData.map(c => c.id || c['@id']);
this.http.post<any>(url, {
clients: clientIds,
queue: queue,
target_os: pluginCmd.os,
...extraParams
}).subscribe({
next: (response) => {
const msg = response?.message || 'Comando procesado correctamente';
this.toastService.success(msg, pluginCmd.label);
this.pluginService.loadActivePluginsStatus().subscribe();
},
error: (error) => {
const errorMsg = error?.error?.message || error?.error?.['hydra:description'] || 'Error al comunicar con el servidor';
this.toastService.error(errorMsg, pluginCmd.label);
}
});
}
} }

View File

@ -1,41 +0,0 @@
.form-container {
display: flex;
flex-direction: column;
gap: 16px;
padding: 16px;
}
.full-width {
width: 100%;
}
.hint-text {
margin: 0;
font-size: 12px;
color: rgba(0, 0, 0, 0.6);
}
.mat-dialog-title {
font-size: 20px;
font-weight: 600;
margin-bottom: 12px;
}
.mat-dialog-content {
max-height: 60vh;
overflow-y: auto;
}
.mat-dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding: 16px;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}

View File

@ -1,34 +0,0 @@
<h2 mat-dialog-title>{{ 'executeTaskNowModalTitle' | translate }}</h2>
<mat-dialog-content class="form-container">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectTask' | translate }}</mat-label>
<input type="text" matInput [formControl]="taskControl" [matAutocomplete]="taskAuto"
[placeholder]="'labelSearchTask' | translate" #taskInput
#taskAutoTrigger="matAutocompleteTrigger">
<button type="button" mat-icon-button matSuffix tabindex="-1"
[disabled]="tasksLoading || tasks.length === 0"
(click)="taskInput.focus(); taskAutoTrigger.openPanel()">
<mat-icon>arrow_drop_down</mat-icon>
</button>
<mat-autocomplete #taskAuto="matAutocomplete"
[displayWith]="displayFn" autoActiveFirstOption
(optionSelected)="onTaskSelected($event.option.value)">
<mat-option *ngFor="let task of filteredTasks$ | async" [value]="task">
{{ task.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<p *ngIf="tasksLoading" class="hint-text">{{ 'loadingDots' | translate }}</p>
<p *ngIf="!tasksLoading && tasks.length === 0">{{ 'noTasksAvailableMessage' | translate }}</p>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="closeModal()">{{ 'buttonCancel' | translate }}</button>
<button class="submit-button" (click)="executeNow()" [disabled]="!selectedTask">
{{ 'executeButton' | translate }}
</button>
</mat-dialog-actions>

View File

@ -1,105 +0,0 @@
import { inject } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { HttpClient } from '@angular/common/http';
import { FormControl } from '@angular/forms';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { ToastrService } from 'ngx-toastr';
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-execute-task-now',
templateUrl: './execute-task-now.component.html',
styleUrls: ['./execute-task-now.component.css']
})
export class ExecuteTaskNowComponent implements OnInit {
public translate = inject(TranslateService);
baseUrl: string;
tasks: any[] = [];
tasksLoading = true;
taskControl = new FormControl();
filteredTasks$!: Observable<any[]>;
selectedTask: any = null;
private tasks$ = new BehaviorSubject<any[]>([]);
constructor(
private dialogRef: MatDialogRef<ExecuteTaskNowComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private http: HttpClient,
private configService: ConfigService,
private toastService: ToastrService,
) {
this.baseUrl = this.configService.apiUrl;
}
ngOnInit(): void {
this.loadTasks();
this.filteredTasks$ = combineLatest([
this.taskControl.valueChanges.pipe(startWith('')),
this.tasks$
]).pipe(
map(([value]) => this._filterTasks(typeof value === 'string' ? value : value?.name))
);
}
loadTasks(): void {
this.http.get<any>(`${this.baseUrl}/command-tasks?page=1&itemsPerPage=100`).subscribe(
response => {
this.tasks = response['hydra:member'] || [];
this.tasksLoading = false;
this.tasks$.next(this.tasks);
},
error => {
this.tasksLoading = false;
this.toastService.error(this.translate.instant('errorLoadingTasks'), error);
}
);
}
private _filterTasks(value: string): any[] {
const filterValue = (value || '').toLowerCase();
return this.tasks.filter(task => task.name.toLowerCase().includes(filterValue));
}
displayFn(task: any): string {
return task && task.name ? task.name : '';
}
onTaskSelected(task: any): void {
this.selectedTask = task;
}
executeNow(): void {
if (!this.selectedTask) {
return;
}
const clients = this.data?.clients || [];
if (clients.length === 0) {
this.toastService.error(this.translate.instant('noClientsSelected'));
return;
}
const payload = {
clients: clients.map((client: any) => client['@id'] || `/clients/${client.uuid}`)
};
this.http.post(`${this.baseUrl}/command-tasks/${this.selectedTask.uuid}/execute`, payload).subscribe({
next: () => {
this.toastService.success(this.translate.instant('taskExecutedSuccessfully'));
this.dialogRef.close(true);
},
error: () => {
this.toastService.error(this.translate.instant('errorExecutingTaskNow'));
}
});
}
closeModal(): void {
this.dialogRef.close(false);
}
}

View File

@ -6,13 +6,46 @@
<mat-divider *ngIf="!loading" style="margin-top: 20px;"></mat-divider> <mat-divider *ngIf="!loading" style="margin-top: 20px;"></mat-divider>
<div *ngIf="!loading" class="partition-table-container"> <div *ngIf="!loading" class="partition-table-container">
<app-disk-partition-selector <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
[(selectedPartition)]="selectedPartition" <ng-container matColumnDef="select">
[partitions]="dataSource.data" <th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: start">{{ 'buttonSelectImage' | translate }}</th>
[columns]="columns" <td mat-cell *matCellDef="let row">
[displayedColumns]="displayedColumns" <mat-radio-group
[disableCondition]="isPartitionDisabled"> [(ngModel)]="selectedPartition"
</app-disk-partition-selector> >
<mat-radio-button [value]="row">
</mat-radio-button>
</mat-radio-group>
</td>
</ng-container>
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header | translate }} </th>
<td mat-cell *matCellDef="let image">
<ng-container *ngIf="column.columnDef !== 'size' && column.columnDef !== 'operativeSystem'">
{{ column.cell(image) }}
</ng-container>
<ng-container *ngIf="column.columnDef === 'size'">
<div style="display: flex; flex-direction: column;">
<span> {{ image.size }} MB</span>
<span style="font-size: 0.75rem; color: gray;">{{ image.size / 1024 }} GB</span>
</div>
</ng-container>
<ng-container *ngIf="column.columnDef === 'operativeSystem'">
<div style="display: flex; flex-direction: column;">
<span> {{ image.operativeSystem?.name }} </span>
<span style="font-size: 0.75rem; color: gray;">{{ image.image?.name}} </span>
</div>
</ng-container>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div> </div>
</mat-dialog-content> </mat-dialog-content>

View File

@ -59,10 +59,6 @@ export class SoftwareProfilePartitionComponent implements OnInit{
displayedColumns = ['select', ...this.columns.map(column => column.columnDef)]; displayedColumns = ['select', ...this.columns.map(column => column.columnDef)];
isPartitionDisabled = (partition: any): boolean => {
return !partition.operativeSystem;
};
constructor( constructor(
@Inject(MAT_DIALOG_DATA) public data: { client: any }, @Inject(MAT_DIALOG_DATA) public data: { client: any },
private dialogRef: MatDialogRef<SoftwareProfilePartitionComponent>, private dialogRef: MatDialogRef<SoftwareProfilePartitionComponent>,
@ -83,7 +79,7 @@ export class SoftwareProfilePartitionComponent implements OnInit{
this.http.get(url).subscribe( this.http.get(url).subscribe(
(response: any) => { (response: any) => {
if (response.partitions) { if (response.partitions) {
this.dataSource.data = response.partitions.filter((p: any) => p.partitionCode !== 'CACHE' && p.partitionCode !== 'EMPTY'); this.dataSource.data = response.partitions;
} }
}, },
(error) => { (error) => {

View File

@ -4,7 +4,6 @@ import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
import { ToastrService } from "ngx-toastr"; import { ToastrService } from "ngx-toastr";
import { AuthService } from '@services/auth.service';
@Component({ @Component({
selector: 'app-global-status', selector: 'app-global-status',
@ -68,8 +67,7 @@ export class GlobalStatusComponent implements OnInit {
constructor( constructor(
private configService: ConfigService, private configService: ConfigService,
private toastService: ToastrService, private toastService: ToastrService,
private http: HttpClient, private http: HttpClient
private auth: AuthService
) { ) {
this.baseUrl = this.configService.apiUrl; this.baseUrl = this.configService.apiUrl;
this.dhcpsApiUrl = `${this.baseUrl}/dhcp-servers`; this.dhcpsApiUrl = `${this.baseUrl}/dhcp-servers`;
@ -117,18 +115,7 @@ export class GlobalStatusComponent implements OnInit {
}); });
} }
/**
* Las sincronizaciones con la infraestructura (subredes DHCP, plantillas PXE y
* ogLives) están restringidas a ROLE_SUPER_ADMIN en ogCore; para el resto de
* perfiles devuelven "Access Denied", así que ni siquiera se lanzan.
*/
private get canSyncInfrastructure(): boolean {
return this.auth.isSuperAdmin;
}
syncSubnets() { syncSubnets() {
if (!this.canSyncInfrastructure) return;
this.http.get<any>(`${this.dhcpsApiUrl}?page=1&itemsPerPage=10`).subscribe(data => { this.http.get<any>(`${this.dhcpsApiUrl}?page=1&itemsPerPage=10`).subscribe(data => {
const dhcps = data['hydra:member'] || []; const dhcps = data['hydra:member'] || [];
if (dhcps.length === 0) return; if (dhcps.length === 0) return;
@ -168,7 +155,6 @@ export class GlobalStatusComponent implements OnInit {
} }
syncTemplates() { syncTemplates() {
if (!this.canSyncInfrastructure) return;
if (this.bootServers.length === 0) return; if (this.bootServers.length === 0) return;
let pending = this.bootServers.length; let pending = this.bootServers.length;
@ -203,7 +189,6 @@ export class GlobalStatusComponent implements OnInit {
} }
syncOgLives(): void { syncOgLives(): void {
if (!this.canSyncInfrastructure) return;
if (this.bootServers.length === 0) return; if (this.bootServers.length === 0) return;
let pending = this.bootServers.length; let pending = this.bootServers.length;

View File

@ -42,13 +42,15 @@
</div> </div>
</div> </div>
<div id="ogboot-logs-section"> <div class="logs-section" id="ogboot-logs-section">
<app-status-logs <div class="logs-header">
[title]="'ogbootLogs'" <h3>{{ 'ogbootLogs' | translate }}</h3>
[identifiers]="['ogboot', 'tftpd-hpa']" <p>{{ 'realTimeOgbootLogs' | translate }}</p>
[host]="getSelectedBootServerIp()" </div>
[oglogUrl]="getBootServerIframeUrl()"> <div class="logs-container">
</app-status-logs> <iframe [src]="getBootServerIframeUrl()" width="100%" height="800" frameborder="0" class="ogboot-logs-iframe">
</iframe>
</div>
</div> </div>
</div> </div>
} }

View File

@ -1,6 +1,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { GlobalOgbootStatusComponent as OgbootStatusComponent } from './ogboot-status.component'; import { OgbootStatusComponent } from './ogboot-status.component';
describe('OgbootStatusComponent', () => { describe('OgbootStatusComponent', () => {
let component: OgbootStatusComponent; let component: OgbootStatusComponent;

View File

@ -101,11 +101,6 @@ export class GlobalOgbootStatusComponent implements OnInit {
} }
} }
getSelectedBootServerIp(): string {
const s = this.bootServers.find(s => s.uuid === this.selectedBootServerUuid);
return s ? s.ip : '';
}
getSelectedBootServerName(): string { getSelectedBootServerName(): string {
const selectedBootServer = this.bootServers.find(server => server.uuid === this.selectedBootServerUuid); const selectedBootServer = this.bootServers.find(server => server.uuid === this.selectedBootServerUuid);
return selectedBootServer ? selectedBootServer.name : ''; return selectedBootServer ? selectedBootServer.name : '';

View File

@ -1,12 +1,14 @@
<div class="section-content"> <div class="section-content">
<div class="tab-content"> <div class="tab-content">
<div id="ogcore-logs-section"> <div class="logs-section" id="ogcore-logs-section">
<app-status-logs <div class="logs-header">
[title]="'ogcoreLogs'" <h3>{{ 'ogcoreLogs' | translate }}</h3>
[identifiers]="['ogcore']" <p>{{ 'realTimeOgcoreLogs' | translate }}</p>
[host]="''" </div>
[oglogUrl]="getOgCoreIframeUrl()"> <div class="logs-container">
</app-status-logs> <iframe [src]="getOgCoreIframeUrl()" width="100%" height="800" frameborder="0" class="ogcore-logs-iframe">
</iframe>
</div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -42,13 +42,15 @@
</div> </div>
</div> </div>
<div id="dhcp-logs-section"> <div class="logs-section" id="dhcp-logs-section">
<app-status-logs <div class="logs-header">
[title]="'dhcpLogs'" <h3>{{ 'dhcpLogs' | translate }}</h3>
[identifiers]="['ogdhcp', 'kea-dhcp4', 'kea-ctrl-agent', 'DhcpLFC']" <p>{{ 'realTimeDhcpLogs' | translate }}</p>
[host]="getSelectedDhcpIp()" </div>
[oglogUrl]="getDhcpIframeUrl()"> <div class="logs-container">
</app-status-logs> <iframe [src]="getDhcpIframeUrl()" width="100%" height="800" frameborder="0" class="dhcp-logs-iframe">
</iframe>
</div>
</div> </div>
</div> </div>
} }

View File

@ -104,11 +104,6 @@ export class OgdhcpStatusComponent implements OnInit {
} }
} }
getSelectedDhcpIp(): string {
const d = this.dhcps.find(d => d.uuid === this.selectedDhcpUuid);
return d ? d.ip : '';
}
getSelectedDhcpName(): string { getSelectedDhcpName(): string {
const selectedDhcp = this.dhcps.find(dhcp => dhcp.uuid === this.selectedDhcpUuid); const selectedDhcp = this.dhcps.find(dhcp => dhcp.uuid === this.selectedDhcpUuid);
return selectedDhcp ? selectedDhcp.name : ''; return selectedDhcp ? selectedDhcp.name : '';

View File

@ -49,13 +49,16 @@
</div> </div>
</div> </div>
<div id="repository-logs-section"> <div class="repository-logs-section" id="repository-logs-section">
<app-status-logs <div class="logs-header">
[title]="'ogrepositoryLogs'" <h3>Datos del repositorio: {{ getSelectedRepositoryName() }}</h3>
[identifiers]="['ogrepo-api', 'ogrepo-api_DEBUG', '(smbd)', '(nmbd)']" <p>{{ 'specificRepoInfo' | translate }}</p>
[host]="getSelectedRepositoryIp()" </div>
[oglogUrl]="getRepositoryIframeUrl()"> <div class="logs-container">
</app-status-logs> <iframe [src]="getRepositoryIframeUrl()" width="100%" height="600" frameborder="0"
class="repository-logs-iframe">
</iframe>
</div>
</div> </div>
</div> </div>
} }

View File

@ -103,11 +103,6 @@ export class OgrepositoryStatusComponent implements OnInit {
} }
} }
getSelectedRepositoryIp(): string {
const r = this.repositories.find(r => r.uuid === this.selectedRepositoryUuid);
return r ? r.ip : '';
}
getSelectedRepositoryName(): string { getSelectedRepositoryName(): string {
const selectedRepo = this.repositories.find(repo => repo.uuid === this.selectedRepositoryUuid); const selectedRepo = this.repositories.find(repo => repo.uuid === this.selectedRepositoryUuid);
return selectedRepo ? selectedRepo.name : ''; return selectedRepo ? selectedRepo.name : '';

View File

@ -1,165 +0,0 @@
.logs-section {
background-color: var(--surface-card, #ffffff);
border-radius: 12px;
padding: 16px;
margin-top: 16px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
.logs-header {
margin-bottom: 12px;
}
.logs-header h3 {
font-size: 1.1rem;
font-weight: 600;
margin: 0;
color: var(--text-primary, #111827);
}
.logs-header p {
font-size: 0.8rem;
color: var(--text-secondary, #6b7280);
margin: 2px 0 0;
}
.logs-tabs {
margin-top: 8px;
}
.logs-container {
position: relative;
background-color: #0d1117;
border-radius: 8px;
margin-top: 8px;
display: flex;
flex-direction: column;
}
.tab-actions-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 4px 12px;
background: rgba(255, 255, 255, 0.05);
border-top-left-radius: 8px;
border-top-right-radius: 8px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.header-actions {
display: flex;
gap: 4px;
}
.header-actions button {
color: rgba(255, 255, 255, 0.7) !important;
}
.header-actions button:hover:not([disabled]) {
color: white !important;
background: rgba(255, 255, 255, 0.1);
}
.header-actions button[disabled] {
color: rgba(255, 255, 255, 0.2) !important;
}
.header-actions button[color="warn"] {
color: #ff4081 !important;
}
.live-badge {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.7rem;
font-weight: 700;
color: #ff4081;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.live-dot {
width: 6px;
height: 6px;
background-color: #ff4081;
border-radius: 50%;
animation: pulse 2s infinite;
}
.log-viewer {
margin: 0;
padding: 12px;
color: #e6edf3;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 0.8rem;
line-height: 1.4;
overflow-y: auto;
max-height: 50vh;
white-space: pre-wrap;
word-break: break-all;
}
@keyframes pulse {
0% {
transform: scale(0.95);
box-shadow: 0 0 0 0 rgba(255, 64, 129, 0.7);
}
70% {
transform: scale(1);
box-shadow: 0 0 0 8px rgba(255, 64, 129, 0);
}
100% {
transform: scale(0.95);
box-shadow: 0 0 0 0 rgba(255, 64, 129, 0);
}
}
.loading-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(13, 17, 23, 0.7);
z-index: 10;
}
.error-message {
padding: 32px;
text-align: center;
color: #f85149;
}
.error-message mat-icon {
font-size: 48px;
width: 48px;
height: 48px;
margin-bottom: 16px;
}
.logs-iframe {
border-radius: 8px;
}
.no-oglog {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 64px;
color: #8b949e;
}
.no-oglog mat-icon {
font-size: 48px;
width: 48px;
height: 48px;
margin-bottom: 16px;
}

View File

@ -1,59 +0,0 @@
<div class="logs-section">
<div class="logs-header">
<h3>{{ title | translate }}</h3>
<p>{{ 'realTimeLogs' | translate }}</p>
</div>
<mat-tab-group class="logs-tabs" animationDuration="0ms" (selectedTabChange)="onTabChange($event)">
<mat-tab [label]="'diskLogs' | translate">
<div class="logs-container disk-logs">
<div class="tab-actions-header">
<div class="header-actions">
<button mat-icon-button
(click)="toggleLive()"
[matTooltip]="(isLive ? 'diskLogsStopLive' : 'diskLogsStartLive') | translate"
[color]="isLive ? 'warn' : ''">
<mat-icon>{{ isLive ? 'pause_circle' : 'play_circle' }}</mat-icon>
</button>
<button mat-icon-button (click)="refreshLogs()" [matTooltip]="'buttonUpdateData' | translate" [disabled]="isLive">
<mat-icon>refresh</mat-icon>
</button>
</div>
<div *ngIf="isLive" class="live-badge">
<span class="live-dot"></span>
LIVE
</div>
</div>
@if (loadingDiskLogs && !diskLogsContent) {
<div class="loading-overlay">
<mat-spinner diameter="40"></mat-spinner>
</div>
}
@if (errorDiskLogs) {
<div class="error-message">
<mat-icon>error_outline</mat-icon>
<p>{{ errorDiskLogs }}</p>
<button mat-button (click)="loadDiskLogs()">{{ 'buttonRetry' | translate }}</button>
</div>
}
<pre #logContent class="log-viewer">{{ diskLogsContent }}</pre>
</div>
</mat-tab>
<mat-tab [label]="'oglogLogs' | translate">
<div class="logs-container oglog-logs">
@if (oglogUrl) {
<iframe [src]="oglogUrl" width="100%" height="600" frameborder="0" class="logs-iframe"></iframe>
} @else {
<div class="no-oglog">
<mat-icon>info_outline</mat-icon>
<p>oglog no está disponible o no se ha configurado la URL.</p>
</div>
}
</div>
</mat-tab>
</mat-tab-group>
</div>

View File

@ -1,139 +0,0 @@
import { Component, Input, OnInit, OnDestroy, inject, ViewChild, ElementRef, AfterViewChecked } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SafeResourceUrl } from '@angular/platform-browser';
import { ConfigService } from '@services/config.service';
import { TranslateService } from '@ngx-translate/core';
import { MatTabChangeEvent } from '@angular/material/tabs';
interface JournalEntry {
MESSAGE: string;
SYSLOG_IDENTIFIER?: string;
_HOSTNAME?: string;
__REALTIME_TIMESTAMP?: string;
PRIORITY?: string;
}
@Component({
selector: 'app-status-logs',
templateUrl: './status-logs.component.html',
styleUrl: './status-logs.component.css'
})
export class StatusLogsComponent implements OnInit, OnDestroy, AfterViewChecked {
@ViewChild('logContent') private logContainer!: ElementRef;
@Input() identifiers: string[] = [];
@Input() host: string = '';
@Input() oglogUrl: SafeResourceUrl | null = null;
@Input() title: string = '';
public translate = inject(TranslateService);
diskLogsContent: string = '';
loadingDiskLogs: boolean = false;
errorDiskLogs: string | null = null;
isLive: boolean = true;
private pollInterval: any;
private readonly POLL_INTERVAL_MS = 5000;
constructor(
private http: HttpClient,
private configService: ConfigService
) {}
ngOnInit(): void {
this.loadDiskLogs();
if (this.isLive) {
this.startPolling();
}
}
ngAfterViewChecked() {
this.scrollToBottom();
}
toggleLive(): void {
this.isLive = !this.isLive;
if (this.isLive) {
this.loadDiskLogs();
this.startPolling();
} else {
this.stopPolling();
}
}
onTabChange(event: MatTabChangeEvent): void {
if (event.index === 0) {
if (this.isLive) {
this.loadDiskLogs();
this.startPolling();
}
} else {
this.stopPolling();
}
}
ngOnDestroy(): void {
this.stopPolling();
}
loadDiskLogs(): void {
if (!this.identifiers.length) return;
if (!this.isLive) {
this.loadingDiskLogs = true;
}
const idParam = this.identifiers.join(',');
const hostParam = this.host ? `&host=${encodeURIComponent(this.host)}` : '';
const url = `${this.configService.apiUrl}/opengnsys/system/disk-logs?SYSLOG_IDENTIFIER=${encodeURIComponent(idParam)}${hostParam}&lines=200`;
this.http.get<{ entries: JournalEntry[] }>(url).subscribe({
next: (response) => {
this.diskLogsContent = this.formatEntries(response.entries || []);
this.loadingDiskLogs = false;
this.errorDiskLogs = null;
},
error: () => {
this.errorDiskLogs = 'Error al cargar logs de disco';
this.loadingDiskLogs = false;
}
});
}
private formatEntries(entries: JournalEntry[]): string {
return entries.map(entry => {
const ts = entry.__REALTIME_TIMESTAMP
? new Date(parseInt(entry.__REALTIME_TIMESTAMP, 10) / 1000).toISOString().replace('T', ' ').substring(0, 23)
: ' ';
const id = entry.SYSLOG_IDENTIFIER ?? '';
return `[${ts}] ${id}: ${entry.MESSAGE ?? ''}`;
}).join('\n');
}
private startPolling(): void {
this.stopPolling();
this.pollInterval = setInterval(() => {
if (this.isLive) {
this.loadDiskLogs();
}
}, this.POLL_INTERVAL_MS);
}
private stopPolling(): void {
if (this.pollInterval) {
clearInterval(this.pollInterval);
this.pollInterval = null;
}
}
refreshLogs(): void {
this.loadDiskLogs();
}
private scrollToBottom(): void {
if (this.isLive && this.logContainer) {
try {
this.logContainer.nativeElement.scrollTop = this.logContainer.nativeElement.scrollHeight;
} catch (err) {}
}
}
}

View File

@ -66,8 +66,7 @@ export class CreateClientImageComponent implements OnInit{
} }
isPartitionDisabled = (row: any): boolean => { isPartitionDisabled = (row: any): boolean => {
// Se debe permitir crear imagen de particiones de sólo datos, tan sólo evitamos partición CACHE return !row.operativeSystem;
return row.filesystem === 'CACHE';
}; };
columns = [ columns = [
@ -127,9 +126,13 @@ export class CreateClientImageComponent implements OnInit{
this.clientName = response.name; this.clientName = response.name;
this.selectedRepository = response.repository; this.selectedRepository = response.repository;
this.dataSource.data = response.partitions; const validPartitions = response.partitions.filter((partition: any) => {
return partition.partitionNumber !== 0;
});
const firstValidPartition = response.partitions.find((partition: any) => { this.dataSource.data = validPartitions;
const firstValidPartition = validPartitions.find((partition: any) => {
return partition.operativeSystem; return partition.operativeSystem;
}); });
@ -149,8 +152,7 @@ export class CreateClientImageComponent implements OnInit{
} }
loadImages() { loadImages() {
const repoFilter = this.selectedRepository ? `&repositoryId=${this.selectedRepository.id}` : ''; const url = `${this.baseUrl}/images?created=false&type=${this.imageType}&page=1&itemsPerPage=100`;
const url = `${this.baseUrl}/images?created=false&type=${this.imageType}${repoFilter}&page=1&itemsPerPage=100`;
this.http.get(url).subscribe( this.http.get(url).subscribe(
(response: any) => { (response: any) => {
this.images = response['hydra:member']; this.images = response['hydra:member'];
@ -372,8 +374,7 @@ export class CreateClientImageComponent implements OnInit{
width: '400px', width: '400px',
disableClose: true, disableClose: true,
hasBackdrop: true, hasBackdrop: true,
backdropClass: 'non-clickable-backdrop', backdropClass: 'non-clickable-backdrop'
data: { clients: this.client ? [this.client] : [] }
}); });
dialogRef.afterClosed().subscribe(result => { dialogRef.afterClosed().subscribe(result => {

View File

@ -921,13 +921,3 @@ table {
margin-top: 2px; margin-top: 2px;
} }
.post-deploy-radio-group {
margin-top: 10px;
}
.pxe-template-container {
margin-top: 15px;
display: flex;
flex-direction: column;
gap: 10px;
}

View File

@ -52,8 +52,7 @@
</div> </div>
<div class="clients-grid"> <div class="clients-grid">
@for (client of clientData; track client) { <div *ngFor="let client of clientData" class="client-item">
<div class="client-item">
<div class="client-card" (click)="toggleClientSelection(client)" <div class="client-card" (click)="toggleClientSelection(client)"
[ngClass]="{'selected-client': client.selected}" [matTooltip]="getPartitionsTooltip(client)" [ngClass]="{'selected-client': client.selected}" [matTooltip]="getPartitionsTooltip(client)"
matTooltipPosition="above" matTooltipClass="custom-tooltip"> matTooltipPosition="above" matTooltipClass="custom-tooltip">
@ -74,7 +73,6 @@
</mat-radio-group> </mat-radio-group>
</div> </div>
</div> </div>
}
</div> </div>
</mat-expansion-panel> </mat-expansion-panel>
@ -101,89 +99,49 @@
</div> </div>
<!-- Campos monolítica --> <!-- Campos monolítica -->
@if (imageType === 'monolithic') { <div class="monolithic-row" *ngIf="imageType === 'monolithic'">
<div class="monolithic-row" style="display: flex; flex-direction: column; gap: 10px;"> <mat-form-field appearance="fill" class="half-width">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectDeployMethod' | translate }}</mat-label> <mat-label>{{ 'selectDeployMethod' | translate }}</mat-label>
<mat-select [(ngModel)]="selectedMethod" name="selectedMethod" (selectionChange)="validateImageSize()"> <mat-select [(ngModel)]="selectedMethod" name="selectedMethod" (selectionChange)="validateImageSize()">
@for (method of allMethods; track method.value) { <mat-option *ngFor="let method of allMethods" [value]="method.value">{{ method.name }}</mat-option>
<mat-option [value]="method.value">{{ method.name }}</mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectRepository' | translate }}</mat-label>
<mat-select [(ngModel)]="selectedRepository" (selectionChange)="onRepositorySelected($event.value)" [compareWith]="compareRepositories" [disabled]="loadingAllRepositories">
@for (repo of allImageRepositories; track repo.uuid) {
<mat-option [value]="repo">{{ repo.name }}</mat-option>
}
</mat-select>
@if (loadingAllRepositories) {
<mat-icon matSuffix>hourglass_empty</mat-icon>
}
</mat-form-field>
<mat-form-field appearance="fill" class="full-width"> <mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectImagePrompt' | translate }}</mat-label> <mat-label>{{ 'selectImagePrompt' | translate }}</mat-label>
<mat-select [(ngModel)]="selectedImage" name="selectedImage" [disabled]="!imageType"> <mat-select [(ngModel)]="selectedImage" name="selectedImage" [disabled]="!imageType">
@for (image of images; track image.uuid || $index) { <mat-option *ngFor="let image of images" [value]="image">
<mat-option [value]="image">
<div class="unit-name"> {{ image.name }}</div> <div class="unit-name"> {{ image.name }}</div>
<div style="font-size: smaller; color: gray;">{{ image.description }}</div> <div style="font-size: smaller; color: gray;">{{ image.description }}</div>
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</div> </div>
}
<!-- Campos Git --> <!-- Campos Git -->
@if (imageType === 'git') { <div *ngIf="imageType === 'git'" class="filters-row git-gap">
<div class="git-gap" style="display: flex; flex-direction: column; gap: 10px;"> <mat-form-field appearance="fill" style="width: 300px;">
<mat-form-field appearance="fill" style="width: 100%;">
<mat-label>{{ 'selectRepository' | translate }}</mat-label>
<mat-select [(ngModel)]="selectedRepository" (selectionChange)="onRepositorySelected($event.value)" [compareWith]="compareRepositories" [disabled]="loadingAllRepositories">
@for (repo of allImageRepositories; track repo.uuid) {
<mat-option [value]="repo">{{ repo.name }}</mat-option>
}
</mat-select>
@if (loadingAllRepositories) {
<mat-icon matSuffix>hourglass_empty</mat-icon>
}
</mat-form-field>
<mat-form-field appearance="fill" style="width: 100%;">
<mat-label>{{ 'buttonSelectRepository' | translate }}</mat-label> <mat-label>{{ 'buttonSelectRepository' | translate }}</mat-label>
<mat-select [(ngModel)]="selectedGitRepository" (selectionChange)="onGitRepositoryChange($event.value)" <mat-select [(ngModel)]="selectedGitRepository" (selectionChange)="onGitRepositoryChange($event.value)"
[disabled]="loadingRepositories"> [disabled]="loadingRepositories">
@for (repo of repositories; track repo) { <mat-option *ngFor="let repo of repositories" [value]="repo">
<mat-option [value]="repo">
{{ repo }} {{ repo }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
@if (loadingRepositories) { <mat-icon matSuffix *ngIf="loadingRepositories">hourglass_empty</mat-icon>
<mat-icon matSuffix>hourglass_empty</mat-icon>
}
</mat-form-field> </mat-form-field>
<mat-form-field appearance="fill" style="width: 100%;"> <mat-form-field appearance="fill" style="width: 300px;">
<mat-label>{{ 'buttonSelectBranch' | translate }}</mat-label> <mat-label>{{ 'buttonSelectBranch' | translate }}</mat-label>
<mat-select [(ngModel)]="selectedBranch" (selectionChange)="onGitBranchChange()" <mat-select [(ngModel)]="selectedBranch" (selectionChange)="onGitBranchChange()"
[disabled]="loadingBranches || !selectedGitRepository"> [disabled]="loadingBranches || !selectedRepository">
@for (branch of branches; track branch) { <mat-option *ngFor="let branch of branches" [value]="branch">
<mat-option [value]="branch">
{{ branch }} {{ branch }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
@if (loadingBranches) { <mat-icon matSuffix *ngIf="loadingBranches">hourglass_empty</mat-icon>
<mat-icon matSuffix>hourglass_empty</mat-icon>
}
</mat-form-field> </mat-form-field>
<mat-form-field appearance="fill" style="width: 100%;"> <mat-form-field appearance="fill" style="width: 200px;">
<mat-label>{{ 'labelTag' | translate }}</mat-label> <mat-label>{{ 'labelTag' | translate }}</mat-label>
<mat-select [(ngModel)]="showOnlyTagged" (selectionChange)="onTagFilterChange()" [disabled]="!commits.length"> <mat-select [(ngModel)]="showOnlyTagged" (selectionChange)="onTagFilterChange()" [disabled]="!commits.length">
<mat-option [value]="false">{{ 'buttonNo' | translate }}</mat-option> <mat-option [value]="false">{{ 'buttonNo' | translate }}</mat-option>
@ -191,7 +149,6 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</div> </div>
}
<!-- Configuración avanzada del método (Multicast / P2P) --> <!-- Configuración avanzada del método (Multicast / P2P) -->
@if (imageType === 'monolithic' && selectedMethod && needsAdvancedConfig(selectedMethod)) { @if (imageType === 'monolithic' && selectedMethod && needsAdvancedConfig(selectedMethod)) {
@ -225,48 +182,14 @@
} }
@if (errorMessage) { <div *ngIf="errorMessage" class="error-message">
<div class="error-message">
{{ errorMessage }} {{ errorMessage }}
</div> </div>
}
</div> </div>
<!-- Columna derecha: modo de operación + partición --> <!-- Columna derecha: modo de operación + partición -->
<div class="partition-column"> <div class="partition-column">
<!-- Sección de Acciones Post-Despliegue -->
@if (deployMode !== 'update-cache') {
<div class="form-section compact-section post-deploy-section">
<div class="form-section-title">
<mat-icon>power_settings_new</mat-icon>
{{ 'postDeployAction' | translate }}
</div>
<mat-radio-group [(ngModel)]="postDeployAction" class="deploy-mode-radio-group post-deploy-radio-group">
<mat-radio-button value="none" color="primary" class="deploy-mode-radio">{{ 'postDeployNone' | translate }}</mat-radio-button>
<mat-radio-button value="bootOs" color="primary" class="deploy-mode-radio">{{ 'postDeployBootOs' | translate }}</mat-radio-button>
<mat-radio-button value="pxeTemplate" color="primary" class="deploy-mode-radio">{{ 'postDeployPxeTemplate' | translate }}</mat-radio-button>
</mat-radio-group>
@if (postDeployAction === 'pxeTemplate') {
<div class="pxe-template-container">
<mat-form-field appearance="fill">
<mat-label>{{ 'selectPxeTemplate' | translate }}</mat-label>
<mat-select [(ngModel)]="selectedPxeTemplate">
@for (template of pxeTemplates; track template.uuid) {
<mat-option [value]="template">{{ template.name }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-slide-toggle [(ngModel)]="pxePermanent" color="primary">
{{ pxePermanent ? ('pxeTemplatePermanent' | translate) : ('pxeTemplateTemporal' | translate) }}
</mat-slide-toggle>
</div>
}
</div>
}
<!-- Modo de despliegue: solo visible para métodos no-direct --> <!-- Modo de despliegue: solo visible para métodos no-direct -->
@if (imageType === 'monolithic' && selectedMethod && !isDirectMethod()) { @if (imageType === 'monolithic' && selectedMethod && !isDirectMethod()) {
@ -298,9 +221,15 @@
</div> </div>
} }
<!-- Contenedor para mostrar las instrucciones en cualquier modo --> <!-- Sección: Selección de partición (oculta en modo solo-caché) -->
@if (showInstructions) { @if (deployMode !== 'update-cache') {
<div class="instructions-box" style="margin-bottom: 20px;"> <div class="form-section compact-section partition-select-section" id="partition-selection">
<div class="form-section-title">
<mat-icon>storage</mat-icon>
{{ 'partitionSelection' | translate }}</div>
<div class="partition-table-container">
<div *ngIf="showInstructions" class="instructions-box">
<mat-card class="instructions-card"> <mat-card class="instructions-card">
<mat-card-title> <mat-card-title>
{{ 'generatedInstructions' | translate }}<button mat-icon-button (click)="showInstructions = false" style="float: right;"> {{ 'generatedInstructions' | translate }}<button mat-icon-button (click)="showInstructions = false" style="float: right;">
@ -312,16 +241,6 @@
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
</div> </div>
}
<!-- Sección: Selección de partición (oculta en modo solo-caché) -->
@if (deployMode !== 'update-cache') {
<div class="form-section compact-section partition-select-section" id="partition-selection">
<div class="form-section-title">
<mat-icon>storage</mat-icon>
{{ 'partitionSelection' | translate }}</div>
<div class="partition-table-container">
<app-disk-partition-selector <app-disk-partition-selector
[(selectedPartition)]="selectedPartition" [(selectedPartition)]="selectedPartition"
@ -355,8 +274,7 @@
</div> </div>
<!-- Tabla de commits Git (solo cuando hay commits cargados) --> <!-- Tabla de commits Git (solo cuando hay commits cargados) -->
@if (imageType === 'git' && filteredCommits.length > 0) { <div *ngIf="imageType === 'git' && filteredCommits.length > 0" class="form-section compact-section">
<div class="form-section compact-section">
<div class="form-section-title"> <div class="form-section-title">
<mat-icon>history</mat-icon> <mat-icon>history</mat-icon>
{{ 'commitSelection' | translate }}</div> {{ 'commitSelection' | translate }}</div>
@ -391,15 +309,11 @@
<th mat-header-cell *matHeaderCellDef>{{ 'labelTags' | translate }}</th> <th mat-header-cell *matHeaderCellDef>{{ 'labelTags' | translate }}</th>
<td mat-cell *matCellDef="let commit"> <td mat-cell *matCellDef="let commit">
<mat-chip-list> <mat-chip-list>
@for (tag of commit.tags; track tag) { <mat-chip *ngFor="let tag of commit.tags" color="primary" selected class="custom-tag-chip"
<mat-chip color="primary" selected class="custom-tag-chip"
style="background: rgba(102, 126, 234, 0.1) !important; color: #667eea !important; border: 1px solid rgba(102, 126, 234, 0.3) !important; border-radius: 8px !important; font-weight: 500 !important; font-size: 10px !important; padding: 2px 6px !important; margin: 1px !important; box-shadow: none !important;"> style="background: rgba(102, 126, 234, 0.1) !important; color: #667eea !important; border: 1px solid rgba(102, 126, 234, 0.3) !important; border-radius: 8px !important; font-weight: 500 !important; font-size: 10px !important; padding: 2px 6px !important; margin: 1px !important; box-shadow: none !important;">
{{ tag }} {{ tag }}
</mat-chip> </mat-chip>
} <span *ngIf="!commit.tags || commit.tags.length === 0" class="no-tags-text">{{ 'noTags' | translate }}</span>
@if (!commit.tags || commit.tags.length === 0) {
<span class="no-tags-text">{{ 'noTags' | translate }}</span>
}
</mat-chip-list> </mat-chip-list>
</td> </td>
</ng-container> </ng-container>
@ -408,7 +322,6 @@
</table> </table>
</div> </div>
</div> </div>
}
</div> </div>

View File

@ -7,7 +7,6 @@ import { HttpClient } from "@angular/common/http";
import { ToastrService } from "ngx-toastr"; import { ToastrService } from "ngx-toastr";
import { ActivatedRoute, Router } from "@angular/router"; import { ActivatedRoute, Router } from "@angular/router";
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
import { AuthService } from '@services/auth.service';
import {DeployMethodConfigDialogComponent} from "./deploy-method-config-dialog/deploy-method-config-dialog.component"; import {DeployMethodConfigDialogComponent} from "./deploy-method-config-dialog/deploy-method-config-dialog.component";
import { CreateTaskComponent } from "../../../../commands/commands-task/create-task/create-task.component"; import { CreateTaskComponent } from "../../../../commands/commands-task/create-task/create-task.component";
import { MatDialog } from "@angular/material/dialog"; import { MatDialog } from "@angular/material/dialog";
@ -20,7 +19,6 @@ import { QueueConfirmationModalComponent } from "../../../../../shared/queue-con
}) })
export class DeployImageComponent implements OnInit { export class DeployImageComponent implements OnInit {
public translate = inject(TranslateService); public translate = inject(TranslateService);
public authService = inject(AuthService);
baseUrl: string; baseUrl: string;
@Output() dataChange = new EventEmitter<any>(); @Output() dataChange = new EventEmitter<any>();
@ -65,19 +63,6 @@ export class DeployImageComponent implements OnInit {
selectedModelClient: any = null; selectedModelClient: any = null;
filteredPartitions: any[] = []; filteredPartitions: any[] = [];
private _postDeployAction: string = 'none';
get postDeployAction(): string { return this._postDeployAction; }
set postDeployAction(val: string) {
this._postDeployAction = val;
this.autoSelectPxeTemplate();
}
selectedPxeTemplate: any = null;
pxePermanent: boolean = false;
pxeTemplates: any[] = [];
allImageRepositories: any[] = [];
loadingAllRepositories: boolean = false;
selectedRepository: any = null; selectedRepository: any = null;
imageType: string = 'monolithic'; imageType: string = 'monolithic';
@ -160,74 +145,6 @@ export class DeployImageComponent implements OnInit {
this.route.queryParams.subscribe(params => { this.route.queryParams.subscribe(params => {
this.runScriptContext = params['runScriptContext'] ? JSON.parse(params['runScriptContext']) : null; this.runScriptContext = params['runScriptContext'] ? JSON.parse(params['runScriptContext']) : null;
}); });
const username = this.authService.username || 'default';
const savedAction = localStorage.getItem(`deploy_postDeployAction_${username}`);
if (savedAction) {
this.postDeployAction = savedAction;
}
const savedPxePermanent = localStorage.getItem(`deploy_pxePermanent_${username}`);
if (savedPxePermanent !== null) {
this.pxePermanent = savedPxePermanent === 'true';
}
this.loadAllRepositories();
this.loadPxeTemplates();
}
loadPxeTemplates() {
this.http.get<any>(`${this.baseUrl}/pxe-templates?page=1&itemsPerPage=10000`).subscribe(
(response: any) => {
this.pxeTemplates = response?.['hydra:member'] || [];
const username = this.authService.username || 'default';
const savedTemplateUuid = localStorage.getItem(`deploy_selectedPxeTemplateUuid_${username}`);
if (savedTemplateUuid && this.postDeployAction === 'pxeTemplate') {
const match = this.pxeTemplates.find(t => t.uuid === savedTemplateUuid);
if (match) {
this.selectedPxeTemplate = match;
}
}
},
(error) => {
console.error('Error loading PXE templates:', error);
}
);
}
loadAllRepositories() {
this.loadingAllRepositories = true;
this.http.get<any>(`${this.baseUrl}/image-repositories?page=1&itemsPerPage=10000`).subscribe(
(response: any) => {
this.allImageRepositories = response?.['hydra:member'] || [];
this.loadingAllRepositories = false;
// Si ya había un selectedRepository cargado por el cliente, asegurarse de enlazar la misma referencia del array
if (this.selectedRepository) {
const match = this.allImageRepositories.find(r => r.uuid === this.selectedRepository.uuid);
if (match) {
this.selectedRepository = match;
}
}
},
(error) => {
console.error(this.translate.instant('errorLoadingRepositories1'), error);
this.loadingAllRepositories = false;
}
);
}
compareRepositories(r1: any, r2: any): boolean {
return r1 && r2 ? r1.uuid === r2.uuid : r1 === r2;
}
onRepositorySelected(repo: any) {
this.selectedRepository = repo;
if (this.imageType === 'git') {
this.selectedGitRepository = '';
this.selectedBranch = '';
this.loadGitRepositories();
}
this.loadImages();
} }
onImageTypeSelected(event: any) { onImageTypeSelected(event: any) {
@ -300,25 +217,10 @@ export class DeployImageComponent implements OnInit {
this.filteredPartitions = fullClientData.partitions; this.filteredPartitions = fullClientData.partitions;
this.selectedRepository = fullClientData.repository ?? null; this.selectedRepository = fullClientData.repository ?? null;
if (this.selectedRepository?.uuid && this.allImageRepositories.length > 0) {
const match = this.allImageRepositories.find(r => r.uuid === this.selectedRepository.uuid);
if (match) {
this.selectedRepository = match;
}
} else if (this.selectedRepository?.uuid) {
// Fallback por si la llamada de loadAllRepositories no ha terminado
this.http.get(`${this.baseUrl}/image-repositories/${this.selectedRepository.uuid}`).subscribe(
(repository: any) => {
this.selectedRepository = repository;
},
(error) => {
console.error(this.translate.instant('errorLoadingRepositories1'), error);
}
);
}
if (fullClientData.partitions) { if (fullClientData.partitions) {
this.filteredPartitions = fullClientData.partitions; this.filteredPartitions = fullClientData.partitions.filter((partition: any) => {
return partition.partitionNumber !== 0;
});
this.p2pMode = fullClientData.organizationalUnit?.networkSettings?.p2pMode; this.p2pMode = fullClientData.organizationalUnit?.networkSettings?.p2pMode;
this.p2pTime = fullClientData.organizationalUnit?.networkSettings?.p2pTime; this.p2pTime = fullClientData.organizationalUnit?.networkSettings?.p2pTime;
this.mcastSpeed = fullClientData.organizationalUnit?.networkSettings?.mcastSpeed; this.mcastSpeed = fullClientData.organizationalUnit?.networkSettings?.mcastSpeed;
@ -354,9 +256,7 @@ export class DeployImageComponent implements OnInit {
if (this.imageType === 'monolithic') { if (this.imageType === 'monolithic') {
url = `${this.baseUrl}/image-image-repositories?status=success&repository.id=${repositoryId}&page=1&itemsPerPage=1000`; url = `${this.baseUrl}/image-image-repositories?status=success&repository.id=${repositoryId}&page=1&itemsPerPage=1000`;
} else { } else {
// Para 'git', la carga de repositorios y ramas se maneja con loadGitRepositories() y loadGitBranches() url = `${this.baseUrl}/git-image-repositories?status=success&repository.id=${repositoryId}&page=1&itemsPerPage=1000`;
this.images = [];
return;
} }
this.http.get(url).subscribe( this.http.get(url).subscribe(
@ -481,8 +381,7 @@ export class DeployImageComponent implements OnInit {
width: '400px', width: '400px',
disableClose: true, disableClose: true,
hasBackdrop: true, hasBackdrop: true,
backdropClass: 'non-clickable-backdrop', backdropClass: 'non-clickable-backdrop'
data: { clients: this.clientData }
}); });
this.toastService.info(this.translate.instant('preparingDeploymentRequest')); this.toastService.info(this.translate.instant('preparingDeploymentRequest'));
@ -532,10 +431,12 @@ export class DeployImageComponent implements OnInit {
this.http.post(url, payload) this.http.post(url, payload)
.subscribe({ .subscribe({
next: (response) => { next: (response) => {
this.enqueuePostDeployActions(); this.toastService.success(this.translate.instant('deployRequestSentCorrectly'));
this.loading = false;
this.router.navigate(['/commands-logs']);
}, },
error: (error) => { error: (error) => {
this.toastService.error(error.error['hydra:description'] || error.message, 'Se ha detectado un error en el despliegue de imágenes.', { this.toastService.error(error.error['hydra:description'], 'Se ha detectado un error en el despliegue de imágenes.', {
"closeButton": true, "closeButton": true,
"newestOnTop": false, "newestOnTop": false,
"progressBar": false, "progressBar": false,
@ -551,77 +452,12 @@ export class DeployImageComponent implements OnInit {
}); });
} }
private enqueuePostDeployActions() {
const username = this.authService.username || 'default';
localStorage.setItem(`deploy_postDeployAction_${username}`, this.postDeployAction);
localStorage.setItem(`deploy_pxePermanent_${username}`, String(this.pxePermanent));
if (this.selectedPxeTemplate?.uuid) {
localStorage.setItem(`deploy_selectedPxeTemplateUuid_${username}`, this.selectedPxeTemplate.uuid);
}
if (this.postDeployAction === 'none') {
this.toastService.success(this.translate.instant('deployRequestSentCorrectly'));
this.loading = false;
this.router.navigate(['/commands-logs']);
return;
}
const clientIds = this.selectedClients.map((c: any) => c.uuid);
if (this.postDeployAction === 'bootOs') {
const disk = this.selectedPartition?.diskNumber || 1;
const part = this.selectedPartition?.partitionNumber || 1;
const payload = {
clients: clientIds,
script: `bootOs ${disk} ${part}`,
queue: true,
runAsAdmin: true
};
this.http.post(`${this.baseUrl}/commands/run-script`, payload).subscribe({
next: () => this.finishPostDeploy(),
error: () => this.finishPostDeployWithError()
});
} else if (this.postDeployAction === 'pxeTemplate' && this.selectedPxeTemplate) {
const mode = this.pxePermanent ? 1 : 0;
const combinedScript = `setBootMode ${this.selectedPxeTemplate.name} ${mode}\nreboot`;
const setBootModePayload = {
clients: clientIds,
script: combinedScript,
queue: true,
runAsAdmin: true
};
this.http.post(`${this.baseUrl}/commands/run-script`, setBootModePayload).subscribe({
next: () => this.finishPostDeploy(),
error: () => this.finishPostDeployWithError()
});
} else {
this.finishPostDeploy();
}
}
private finishPostDeploy() {
this.toastService.success(this.translate.instant('deployRequestSentCorrectly') + ' y post-acciones encoladas.');
this.loading = false;
this.router.navigate(['/commands-logs']);
}
private finishPostDeployWithError() {
this.toastService.error('Se programó el despliegue pero falló al encolar las acciones post-despliegue.');
this.loading = false;
this.router.navigate(['/commands-logs']);
}
isFormValid(): boolean { isFormValid(): boolean {
const needsPartition = this.deployMode !== 'update-cache'; const needsPartition = this.deployMode !== 'update-cache';
if (!this.allSelected || !this.selectedModelClient || (needsPartition && !this.selectedPartition)) { if (!this.allSelected || !this.selectedModelClient || (needsPartition && !this.selectedPartition)) {
return false; return false;
} }
if (this.postDeployAction === 'pxeTemplate' && !this.selectedPxeTemplate) {
return false;
}
if (this.imageType === 'git') { if (this.imageType === 'git') {
if (!this.selectedCommit || this.filteredCommits.length === 0) { if (!this.selectedCommit || this.filteredCommits.length === 0) {
return false; return false;
@ -750,79 +586,9 @@ export class DeployImageComponent implements OnInit {
}); });
} }
generateOgInstructions() { generateOgInstructions() {
this.showInstructions = true; this.showInstructions = true;
this.ogInstructions = this.imageType === 'git' this.ogInstructions = `og-deploy-image --image ${this.selectedImage.name} --partition ${this.selectedPartition?.partitionNumber || 1} --method ${this.selectedMethod}`;
? this.buildGitOgInstructions()
: this.buildMonolithicOgInstructions();
}
private getProto(method: string | null): string {
switch (method) {
case 'uftp-direct':
case 'udpcast-direct':
return 'MULTICAST-DIRECT';
case 'multicast':
case 'uftp':
case 'udpcast':
return 'MULTICAST';
case 'unicast-direct':
return 'UNICAST-DIRECT';
case 'unicast':
return 'UNICAST';
case 'p2p':
return 'TORRENT';
default:
return (method || '').toUpperCase();
}
}
private getProtoOpt(method: string | null): string {
if (method === 'udpcast' || method === 'uftp' || method === 'udpcast-direct') {
const mcastMode = `${this.mcastMode}-duplex`;
const mcastSpeed = `${this.mcastSpeed}M`;
return `${this.mcastPort}:${mcastMode}:${this.mcastIp}:${mcastSpeed}:${this.mcastMaxClients}:${this.mcastMaxTime}`;
}
if (method === 'p2p') {
return `${this.p2pMode}:${this.p2pTime}`;
}
return '';
}
private buildMonolithicOgInstructions(): string {
const method = this.selectedMethod;
const proto = this.getProto(method);
const protoOpt = this.getProtoOpt(method);
const disk = String(this.selectedPartition?.diskNumber || 1);
const par = String(this.selectedPartition?.partitionNumber || 1);
const imgname = this.selectedImage?.name || '<image>';
const repo = this.selectedRepository?.ip || '<repository-ip>';
const effectiveDeployMode = this.isDirectMethod() ? 'deploy' : this.deployMode;
const isCache = effectiveDeployMode === 'update-cache';
const restaurarArgs = [disk, par, imgname, repo, proto, protoOpt].filter(a => a !== '').join(' ');
const scriptName = isCache ? 'ActualizarCache' : 'RestaurarImagen';
const innerCommand = isCache
? ['updateCache', repo, `/${imgname}.img`, proto, protoOpt].filter(a => a !== '').join(' ')
: ['deployImage', repo, imgname, disk, par, proto, protoOpt].filter(a => a !== '').join(' ');
return `${scriptName} ${restaurarArgs}\n ↳ ${innerCommand}`;
}
private buildGitOgInstructions(): string {
const disk = String(this.selectedPartition?.diskNumber || 1);
const par = String(this.selectedPartition?.partitionNumber || 1);
const repo = this.selectedRepository?.ip || '<repository-ip>';
const imageName = this.selectedGitRepository || '<repository-name>';
const branch = this.selectedBranch || '<branch>';
const commit = this.selectedCommit?.hexsha || '<commit>';
return `RestaurarImagenGit --disk ${disk} --partition ${par} --repository ${repo} ` +
`--image-name ${imageName} --branch ${branch} --commit ${commit}`;
} }
@ -855,32 +621,6 @@ export class DeployImageComponent implements OnInit {
set selectedPartition(value: any) { set selectedPartition(value: any) {
this._selectedPartition = value; this._selectedPartition = value;
this.autoSelectPxeTemplate();
}
private getOrdinalName(n: number): string {
const ordinals = ['first', 'second', 'third', 'fourth'];
return ordinals[n - 1] || `${n}th`;
}
private autoSelectPxeTemplate(): void {
if (this._postDeployAction !== 'pxeTemplate' || !this._selectedPartition || !this.pxeTemplates) {
return;
}
const disk = this._selectedPartition.diskNumber;
const part = this._selectedPartition.partitionNumber;
if (!disk || !part) return;
const diskOrdinal = this.getOrdinalName(disk);
const partOrdinal = this.getOrdinalName(part);
const expectedName = `${diskOrdinal}Disk_${partOrdinal}Partition`;
const match = this.pxeTemplates.find((t: any) => t.name === expectedName);
if (match) {
this.selectedPxeTemplate = match;
}
} }
loadGitRepositories() { loadGitRepositories() {

View File

@ -1336,19 +1336,6 @@
border: 2px solid; border: 2px solid;
} }
.badge-disk-type {
display: inline-flex;
align-items: center;
padding: 2px 8px;
font-size: 0.75rem;
font-weight: 600;
color: #1976d2;
background-color: #e3f2fd;
border-radius: 12px;
margin-left: 8px;
vertical-align: middle;
}
.validation-status.loading { .validation-status.loading {
color: #1976d2; color: #1976d2;
background: #e3f2fd; background: #e3f2fd;
@ -1477,6 +1464,3 @@
.badge-disk-type { display: inline-block; padding: 2px 6px; font-size: 11px; font-weight: bold; color: #fff; background-color: #607d8b; border-radius: 4px; margin-left: 8px; vertical-align: middle; }

View File

@ -104,11 +104,7 @@
<mat-option *ngFor="let disk of disks" [value]="disk.diskNumber"> <mat-option *ngFor="let disk of disks" [value]="disk.diskNumber">
<div class="disk-option"> <div class="disk-option">
<div class="disk-info"> <div class="disk-info">
<span class="disk-name">Disco {{ disk.diskNumber }} <span class="disk-name">Disco {{ disk.diskNumber }}</span>
@if (disk.diskType) {
<span class="badge-disk-type">{{ disk.diskType }}</span>
}
</span>
<span class="disk-size"> {{ (disk.totalDiskSize / 1024).toFixed(2) }} GB</span> <span class="disk-size"> {{ (disk.totalDiskSize / 1024).toFixed(2) }} GB</span>
</div> </div>
<div class="disk-details"> <div class="disk-details">

View File

@ -17,7 +17,6 @@ import { MatTableDataSource } from '@angular/material/table';
interface Partition { interface Partition {
uuid?: string; uuid?: string;
partitionNumber: number; partitionNumber: number;
diskType?: string;
size: number; size: number;
partitionCode: string; partitionCode: string;
filesystem: string; filesystem: string;
@ -47,7 +46,7 @@ export class PartitionAssistantComponent implements OnInit, AfterViewInit, OnDes
selectedDiskNumber: number | null = null; selectedDiskNumber: number | null = null;
updateRequests: any[] = []; updateRequests: any[] = [];
data: any = {}; data: any = {};
disks: { diskNumber: number; totalDiskSize: number; partitions: Partition[]; chartData: any[]; used: number; percentage: number; diskType?: string }[] = []; disks: { diskNumber: number; totalDiskSize: number; partitions: Partition[]; chartData: any[]; used: number; percentage: number }[] = [];
clientData: any = []; clientData: any = [];
loading: boolean = false; loading: boolean = false;
runScriptContext: any = null; runScriptContext: any = null;
@ -235,7 +234,7 @@ export class PartitionAssistantComponent implements OnInit, AfterViewInit, OnDes
const partitionsFromData = this.data.partitions; const partitionsFromData = this.data.partitions;
this.originalPartitions = JSON.parse(JSON.stringify(partitionsFromData)); this.originalPartitions = JSON.parse(JSON.stringify(partitionsFromData));
const disksMap = new Map<number, { totalDiskSize: number; partitions: Partition[]; diskType?: string }>(); const disksMap = new Map<number, { totalDiskSize: number; partitions: Partition[] }>();
partitionsFromData.forEach((partition: any) => { partitionsFromData.forEach((partition: any) => {
if (!disksMap.has(partition.diskNumber)) { if (!disksMap.has(partition.diskNumber)) {
@ -245,7 +244,6 @@ export class PartitionAssistantComponent implements OnInit, AfterViewInit, OnDes
const disk = disksMap.get(partition.diskNumber); const disk = disksMap.get(partition.diskNumber);
if (partition.partitionNumber === 0) { if (partition.partitionNumber === 0) {
disk!.totalDiskSize = this.convertBytesToGB(partition.size); disk!.totalDiskSize = this.convertBytesToGB(partition.size);
disk!.diskType = partition.diskType;
} else { } else {
const isFirstPartitionGPT = partition.partitionNumber === 1 && this.partitionCode === 'GPT'; const isFirstPartitionGPT = partition.partitionNumber === 1 && this.partitionCode === 'GPT';
const hasValidExistingData = partition.size > 0 && partition.partitionCode && partition.filesystem; const hasValidExistingData = partition.size > 0 && partition.partitionCode && partition.filesystem;
@ -299,8 +297,7 @@ export class PartitionAssistantComponent implements OnInit, AfterViewInit, OnDes
partitions: disk.partitions, partitions: disk.partitions,
chartData: chartData, chartData: chartData,
used: used, used: used,
percentage: percentage, percentage: percentage
diskType: disk.diskType
}); });
}); });
this.disks.forEach((disk) => { this.disks.forEach((disk) => {
@ -523,8 +520,7 @@ export class PartitionAssistantComponent implements OnInit, AfterViewInit, OnDes
width: '400px', width: '400px',
disableClose: true, disableClose: true,
hasBackdrop: true, hasBackdrop: true,
backdropClass: 'non-clickable-backdrop', backdropClass: 'non-clickable-backdrop'
data: { clients: this.clientData }
}); });
dialogRef.afterClosed().subscribe(result => { dialogRef.afterClosed().subscribe(result => {

View File

@ -195,8 +195,7 @@ export class RunScriptAssistantComponent implements OnInit{
const dialogRef = this.dialog.open(QueueConfirmationModalComponent, { const dialogRef = this.dialog.open(QueueConfirmationModalComponent, {
width: '400px', width: '400px',
disableClose: true, disableClose: true,
hasBackdrop: true, hasBackdrop: true
data: { clients: this.selectedClients }
}); });
dialogRef.afterClosed().subscribe(result => { dialogRef.afterClosed().subscribe(result => {

View File

@ -1,10 +1,3 @@
:host {
display: flex;
flex-direction: column;
flex: 1 1 auto;
min-height: 0;
}
.groups-container { .groups-container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@ -915,22 +908,21 @@ mat-tree mat-tree-node.disabled:hover {
.remote-pc-badge { .remote-pc-badge {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 4px; gap: 2px;
background-color: #e3f2fd; background-color: #1976d2;
color: #1976d2; color: white;
font-size: 0.75rem; padding: 2px 6px;
font-weight: 600; border-radius: 10px;
padding: 2px 8px; font-size: 10px;
border-radius: 12px; font-weight: bold;
width: fit-content; margin-top: 3px;
margin-top: 4px;
} }
.remote-pc-icon { .remote-pc-icon {
font-size: 14px; font-size: 12px;
width: 14px; height: 12px;
height: 14px; width: 12px;
line-height: 14px; line-height: 12px;
} }
.clients-list { .clients-list {
@ -1605,71 +1597,6 @@ mat-button-toggle-group {
opacity: 1; opacity: 1;
} }
.badge-net-speed {
display: flex;
align-items: center;
gap: 4px;
background-color: #e3f2fd;
color: #1976d2;
font-size: 0.75rem;
font-weight: 600;
padding: 2px 8px;
border-radius: 12px;
width: fit-content;
margin-top: 4px;
}
.badge-net-speed .net-speed-icon {
font-size: 14px;
width: 14px;
height: 14px;
}
/* 2. MODIFICADORES DE COLOR (Fondo claro + Texto oscuro de la misma gama) */
/* 10 Gbps - Morado (Destaca como velocidad ultra-rápida/premium) */
.badge-net-speed.speed-10000 {
background-color: #f3e5f5; /* Purple 50 */
color: #7b1fa2; /* Purple 700 */
}
/* 2.5 Gbps / 5 Gbps - Azul (El que tú ya tenías) */
.badge-net-speed.speed-5000, .badge-net-speed.speed-2500 {
background-color: #e3f2fd; /* Blue 50 */
color: #1976d2; /* Blue 700 */
}
/* 1 Gbps - Verde (El estándar de red saludable) */
.badge-net-speed.speed-1000 {
background-color: #e8f5e9; /* Green 50 */
color: #388e3c; /* Green 700 */
}
/* 100 Mbps - Naranja (Aviso de enlace inferior/cuello de botella) */
.badge-net-speed.speed-100 {
background-color: #fff3e0; /* Orange 50 */
color: #f57c00; /* Orange 700 */
}
/* 10 Mbps - Rojo (Aviso crítico / Posible cable roto) */
.badge-net-speed.speed-10 {
background-color: #ffebee; /* Red 50 */
color: #d32f2f; /* Red 700 */
}
/* Desconectado / Down - Gris (Neutro) */
.badge-net-speed.speed-down {
background-color: #f5f5f5; /* Grey 100 */
color: #616161; /* Grey 700 */
}
.list-view-badge {
display: inline-flex;
margin-top: 0;
margin-left: 8px;
vertical-align: middle;
}
.stat-icon { .stat-icon {
display: flex; display: flex;
align-items: center; align-items: center;
@ -1899,228 +1826,3 @@ mat-button-toggle-group {
height: 18px; height: 18px;
} }
/* ==========================================================================
SOLUCIÓN FINAL: EXPANSIÓN VERTICAL Y ANCHO DINÁMICO (PC Y MÓVIL)
========================================================================== */
/* 1. ESCRITORIO / PC (> 992px): Expansión vertical 100% + Ancho dinámico */
@media (min-width: 993px) {
.main-container {
flex: 1 1 auto !important;
height: 100% !important;
display: flex !important;
flex-direction: row !important;
align-items: stretch !important;
overflow: hidden !important;
}
.filters-and-tree-container {
display: flex !important;
flex-direction: column !important;
height: 100% !important;
min-height: 0 !important;
flex: 0 0 auto !important;
width: fit-content !important;
min-width: 340px !important;
max-width: 45vw !important;
}
.filters-panel {
flex: 0 0 auto !important;
}
.tree-container {
display: flex !important;
flex-direction: column !important;
flex: 1 1 auto !important; /* Estira el panel del árbol hasta abajo */
height: 100% !important;
min-height: 0 !important;
max-height: none !important;
overflow: hidden !important;
}
/* REGLA CLAVE PARA RECUPERAR LA VERTICALIDAD DEL ÁRBOL EN PC */
.modern-tree {
flex: 1 1 auto !important; /* Obliga al mat-tree a llenar el espacio vertical */
height: 100% !important;
max-height: none !important; /* Elimina cualquier límite previo de altura */
overflow-y: auto !important; /* Scrollbar vertical limpia si hay muchas aulas */
}
.clients-container {
flex: 1 1 auto !important;
min-width: 0 !important;
height: 100% !important;
display: flex !important;
flex-direction: column !important;
overflow: hidden !important;
}
/* Forzar a los hijos de clients-container a respetar el límite de altura */
.clients-view, .clients-view > div, .list-view {
display: flex !important;
flex-direction: column !important;
flex: 1 1 auto !important;
min-height: 0 !important;
height: 100% !important;
}
}
/* 2. MÓVILES Y TABLETS (<= 992px): Disposición apilada verticalmente */
@media (max-width: 992px) {
.main-container {
display: flex !important;
flex-direction: column !important;
width: 100% !important;
height: auto !important;
overflow-x: hidden !important;
overflow-y: auto !important;
}
.filters-and-tree-container {
width: 100% !important;
max-width: 100% !important;
min-width: 0 !important;
flex: none !important;
height: auto !important;
max-height: 350px !important;
}
.node-content, .node-main {
white-space: normal !important;
}
.clients-container {
width: 100% !important;
margin-left: 0 !important;
flex: none !important;
height: auto !important;
}
}
.cloning-cell {
display: flex;
flex-direction: column;
}
.image-name {
font-weight: 500;
color: #333;
}
.image-date {
font-size: 0.8em;
color: #666;
font-style: italic;
}
.multi-image-badge {
background-color: #673ab7;
color: #ffffff;
border-radius: 12px;
padding: 2px 6px;
font-size: 0.75em;
font-weight: bold;
cursor: help;
}
.tree-resizer {
width: 12px;
cursor: col-resize;
display: flex;
justify-content: center;
background-color: transparent;
z-index: 10;
transition: background-color 0.2s;
}
.tree-resizer:hover, .tree-resizer.resizing {
background-color: rgba(0, 0, 0, 0.05);
}
.resizer-line {
width: 1px;
background-color: rgba(0, 0, 0, 0.12);
height: 100%;
}
.main-container.resizing {
user-select: none;
}
.client-image-spacing {
margin-top: 0.5em;
}
.multi-image-container {
display: flex;
align-items: center;
gap: 4px;
}
.plugin-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 12px;
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.2px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
width: fit-content;
}
.plugin-badge .plugin-badge-icon {
font-size: 14px;
width: 14px;
height: 14px;
line-height: 14px;
}
.plugin-badge.badge-neutral {
background: #f1f5f9;
color: #64748b;
border: 1px solid #cbd5e1;
}
.plugin-badge.badge-pending {
background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
color: #b45309;
border: 1px solid #fcd34d;
}
.plugin-badge.badge-error {
background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
color: #b91c1c;
border: 1px solid #fca5a5;
}
.plugin-badge.badge-info {
background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
color: #1d4ed8;
border: 1px solid #93c5fd;
}
.plugin-badge.badge-success {
background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
color: #047857;
border: 1px solid #6ee7b7;
}
.plugin-badge.badge-warning {
background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
color: #b45309;
border: 1px solid #fde68a;
}
.plugin-badge.list-view-badge {
margin-top: 2px;
}

View File

@ -16,19 +16,15 @@
</div> </div>
<div class="groups-button-row"> <div class="groups-button-row">
<div joyrideStep="addStep" text="{{ 'groupsAddStepText' | translate }}" style="display: flex; gap: 8px;"> <div joyrideStep="addStep" text="{{ 'groupsAddStepText' | translate }}" style="display: flex; gap: 8px;">
@if (auth.userCategory !== 'ou-minimal') { <button class="action-button" (click)="addOU($event)" *ngIf="auth.userCategory !== 'ou-minimal'"
<button class="action-button" (click)="addOU($event)"
matTooltip="{{ 'newOrganizationalUnitTooltip' | translate }}" matTooltipShowDelay="1000"> matTooltip="{{ 'newOrganizationalUnitTooltip' | translate }}" matTooltipShowDelay="1000">
{{ 'newOrganizationalUnitButton' | translate }} {{ 'newOrganizationalUnitButton' | translate }}
</button> </button>
} <button class="action-button" [matMenuTriggerFor]="menuClients" *ngIf="auth.userCategory !== 'ou-minimal'"
@if (auth.userCategory !== 'ou-minimal') {
<button class="action-button" [matMenuTriggerFor]="menuClients"
[disabled]="!hasOrganizationalUnits()" [disabled]="!hasOrganizationalUnits()"
matTooltip="{{ hasOrganizationalUnits() ? ('newClientButtonTooltip' | translate) : ('noOrganizationalUnitsTooltip' | translate) }}" matTooltip="{{ hasOrganizationalUnits() ? ('newClientButtonTooltip' | translate) : ('noOrganizationalUnitsTooltip' | translate) }}"
matTooltipShowDelay="1000">{{ matTooltipShowDelay="1000">{{
'newClientButton' | translate }}</button> 'newClientButton' | translate }}</button>
}
<mat-menu #menuClients="matMenu"> <mat-menu #menuClients="matMenu">
<button mat-menu-item (click)="addClient($event)" [disabled]="!hasOrganizationalUnits()">{{ 'newSingleClientButton' | translate }}</button> <button mat-menu-item (click)="addClient($event)" [disabled]="!hasOrganizationalUnits()">{{ 'newSingleClientButton' | translate }}</button>
<button mat-menu-item (click)="addMultipleClients($event)" [disabled]="!hasOrganizationalUnits()">{{ 'newMultipleClientButton' | translate <button mat-menu-item (click)="addMultipleClients($event)" [disabled]="!hasOrganizationalUnits()">{{ 'newMultipleClientButton' | translate
@ -42,8 +38,7 @@
</div> </div>
<!-- Menú desplegable para pantallas pequeñas --> <!-- Menú desplegable para pantallas pequeñas -->
@if (isSmallScreen) { <div *ngIf="isSmallScreen" class="groups-menu">
<div class="groups-menu">
<button mat-icon-button [matMenuTriggerFor]="smallScreenMenu" [matTooltip]="'labelOptions' | translate" matTooltipShowDelay="1000"> <button mat-icon-button [matMenuTriggerFor]="smallScreenMenu" [matTooltip]="'labelOptions' | translate" matTooltipShowDelay="1000">
<mat-icon>menu</mat-icon> <mat-icon>menu</mat-icon>
</button> </button>
@ -62,76 +57,53 @@
</button> </button>
</mat-menu> </mat-menu>
</div> </div>
}
</div> </div>
@if (initialLoading) { <div *ngIf="initialLoading; else contentTemplate">
<div>
<app-loading [isLoading]="initialLoading"></app-loading> <app-loading [isLoading]="initialLoading"></app-loading>
</div> </div>
} @else {
<div class="main-container" [class.resizing]="isTreeResizing"> <!-- MAIN VIEW -->
<ng-template #contentTemplate>
<div class="main-container">
<!-- FILTERS AND TREE VIEW --> <!-- FILTERS AND TREE VIEW -->
<div class="filters-and-tree-container" [style.width]="treePanelWidth + 'px !important'" [style.minWidth]="treePanelWidth + 'px !important'" [style.maxWidth]="treePanelWidth + 'px !important'" style="flex: none !important;"> <div class="filters-and-tree-container">
<!-- Tree -->
<div class="tree-container" joyrideStep="treePanelStep" text="{{ 'treePanelStepText' | translate }}">
<div class="tree-header">
<h3 class="tree-title">
<mat-icon>account_tree</mat-icon>
{{ 'organizationalStructure' | translate }}
</h3>
<div class="tree-actions">
<button mat-icon-button (click)="toggleSearchFilters()" matTooltip="{{ 'search' | translate }}" matTooltipShowDelay="1000">
<mat-icon>search</mat-icon>
</button>
<button mat-icon-button (click)="toggleExpandAll()" matTooltip="{{ (isTreeExpanded ? 'collapseAll' : 'expandAll') | translate }}">
<mat-icon>{{ isTreeExpanded ? 'unfold_less' : 'unfold_more' }}</mat-icon>
</button>
</div>
</div>
<!-- Filters --> <!-- Filters -->
@if (showSearchFilters) {
<div class="filters-panel" joyrideStep="filtersPanelStep" text="{{ 'filtersPanelStepText' | translate }}"> <div class="filters-panel" joyrideStep="filtersPanelStep" text="{{ 'filtersPanelStepText' | translate }}">
<div class="filters-container"> <div class="filters-container">
<mat-form-field class="filter-form-field" appearance="outline"> <mat-form-field class="filter-form-field" appearance="outline">
<mat-label>{{ 'searchTree' | translate }}</mat-label> <mat-label>{{ 'searchTree' | translate }}</mat-label>
<input matInput #treeSearchInput (input)="onTreeFilterInput($event)" <input matInput #treeSearchInput (input)="onTreeFilterInput($event)"
[placeholder]="'placeholderOrgUnitTypes' | translate" /> [placeholder]="'placeholderOrgUnitTypes' | translate" />
@if (treeSearchInput.value) { <button *ngIf="treeSearchInput.value" mat-icon-button matSuffix [attr.aria-label]="'clearTreeSearch' | translate"
<button mat-icon-button matSuffix [attr.aria-label]="'clearTreeSearch' | translate"
(click)="clearTreeSearch(treeSearchInput)"> (click)="clearTreeSearch(treeSearchInput)">
<mat-icon>close</mat-icon> <mat-icon>close</mat-icon>
</button> </button>
}
</mat-form-field> </mat-form-field>
<mat-form-field class="filter-form-field" appearance="outline"> <mat-form-field class="filter-form-field" appearance="outline">
<mat-label>{{ 'searchClient' | translate }}</mat-label> <mat-label>{{ 'searchClient' | translate }}</mat-label>
<input matInput #clientSearchInput (input)="onClientFilterInput($event)" <input matInput #clientSearchInput (input)="onClientFilterInput($event)"
[placeholder]="'searchNameIpStatusMac' | translate" /> [placeholder]="'searchNameIpStatusMac' | translate" />
@if (clientSearchInput.value) { <button *ngIf="clientSearchInput.value" mat-icon-button matSuffix [attr.aria-label]="'clearClientSearch' | translate"
<button mat-icon-button matSuffix [attr.aria-label]="'clearClientSearch' | translate"
(click)="clearClientSearch(clientSearchInput)"> (click)="clearClientSearch(clientSearchInput)">
<mat-icon>close</mat-icon> <mat-icon>close</mat-icon>
</button> </button>
}
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field search-select" appearance="outline"> <mat-form-field class="form-field search-select" appearance="outline">
<mat-select placeholder="{{ 'searchState' | translate }}" #clientSearchStatusInput <mat-select placeholder="{{ 'searchState' | translate }}" #clientSearchStatusInput
(selectionChange)="onClientFilterStatusInput($event.value)"> (selectionChange)="onClientFilterStatusInput($event.value)">
@for (option of status; track option) { <mat-option *ngFor="let option of status" [value]="option.value">
<mat-option [value]="option.value">
{{ option.name }} {{ option.name }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
@if (clientSearchStatusInput.value) { <button *ngIf="clientSearchStatusInput.value" mat-icon-button matSuffix [attr.aria-label]="'clearTreeSearch' | translate"
<button mat-icon-button matSuffix [attr.aria-label]="'clearTreeSearch' | translate"
(click)="clearStatusFilter($event, clientSearchStatusInput)"> (click)="clearStatusFilter($event, clientSearchStatusInput)">
<mat-icon>close</mat-icon> <mat-icon>close</mat-icon>
</button> </button>
}
</mat-form-field> </mat-form-field>
<div class="direct-clients-toggle"> <div class="direct-clients-toggle">
<mat-slide-toggle <mat-slide-toggle
[(ngModel)]="showOnlyDirectClients" [(ngModel)]="showOnlyDirectClients"
@ -141,17 +113,54 @@
{{ 'directClientsToggle' | translate }} {{ 'directClientsToggle' | translate }}
</mat-slide-toggle> </mat-slide-toggle>
</div> </div>
<!-- Funcionalidad actualmente deshabilitada-->
<!-- <mat-form-field appearance="outline">
<mat-select (selectionChange)="loadSelectedFilter($event.value)" [placeholder]="'buttonLoadFilter' | translate" disabled>
<mat-option *ngFor="let savedFilter of savedFilterNames" [value]="savedFilter">
{{ savedFilter[0] }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>{{ 'filterByType' | translate }}</mat-label>
<mat-select [(value)]="selectedTreeFilter" (selectionChange)="filterTree(searchTerm, $event.value)" disabled>
<mat-option [value]=""> {{ 'all' | translate }} </mat-option>
<mat-option value="classrooms-group">{{ 'classroomsGroup' | translate }}</mat-option>
<mat-option value="classroom">{{ 'classrooms' | translate }}</mat-option>
<mat-option value="group">{{ 'computerGroups' | translate }}</mat-option>
</mat-select>
</mat-form-field> -->
</div> </div>
</div> </div>
}
<!-- Tree -->
<div class="tree-container" joyrideStep="treePanelStep" text="{{ 'treePanelStepText' | translate }}">
<div class="tree-header">
<h3 class="tree-title">
<mat-icon>account_tree</mat-icon>
{{ 'organizationalStructure' | translate }}
</h3>
<div class="tree-actions">
<button mat-icon-button (click)="expandAll()" matTooltip="{{ 'expandAll' | translate }}">
<mat-icon>unfold_more</mat-icon>
</button>
<button mat-icon-button (click)="collapseAll()" matTooltip="{{ 'collapseAll' | translate }}">
<mat-icon>unfold_less</mat-icon>
</button>
</div>
</div>
<mat-tree [dataSource]="treeDataSource" [treeControl]="treeControl" class="modern-tree"> <mat-tree [dataSource]="treeDataSource" [treeControl]="treeControl" class="modern-tree">
<mat-tree-node [ngClass]="{'selected-node': selectedNode?.id === node.id, 'tree-node': true}" <mat-tree-node [ngClass]="{'selected-node': selectedNode?.id === node.id, 'tree-node': true}"
*matTreeNodeDef="let node; when: hasChild" matTreeNodePadding (click)="onNodeClick($event, node)"> *matTreeNodeDef="let node; when: hasChild" matTreeNodePadding (click)="onNodeClick($event, node)">
<div class="node-content"> <div class="node-content">
<button mat-icon-button matTreeNodeToggle [disabled]="!node.expandable" <button mat-icon-button matTreeNodeToggle [disabled]="!node.expandable"
[ngClass]="{'disabled-toggle': !node.expandable}" class="expand-button"> [ngClass]="{'disabled-toggle': !node.expandable}" class="expand-button">
<mat-icon class="expand-icon">{{ treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right' }}</mat-icon> <mat-icon class="expand-icon">{{ treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right' }}</mat-icon>
</button> </button>
<div class="node-info"> <div class="node-info">
<div class="node-main"> <div class="node-main">
<mat-icon class="node-icon {{ node.type }}" [matTooltip]="getNodeTypeTooltip(node.type)"> <mat-icon class="node-icon {{ node.type }}" [matTooltip]="getNodeTypeTooltip(node.type)">
@ -166,15 +175,17 @@
</mat-icon> </mat-icon>
<span class="node-name" [matTooltip]="node.name">{{ node.name }}</span> <span class="node-name" [matTooltip]="node.name">{{ node.name }}</span>
</div> </div>
<div class="node-details"> <div class="node-details">
@if (node.type === 'client') { <ng-container *ngIf="node.type === 'client'">
<span class="node-ip">{{ node.ip }}</span> <span class="node-ip">{{ node.ip }}</span>
} </ng-container>
@if (node.children && node.children.length > 0) { <ng-container *ngIf="node.children && node.children.length > 0">
<span class="node-count">{{ node.children.length }} {{ getNodeCountLabel(node.children.length) }}</span> <span class="node-count">{{ node.children.length }} {{ getNodeCountLabel(node.children.length) }}</span>
} </ng-container>
</div> </div>
</div> </div>
<div class="node-actions"> <div class="node-actions">
<button mat-icon-button [matMenuTriggerFor]="menuNode" (click)="onMenuClick($event, node)" <button mat-icon-button [matMenuTriggerFor]="menuNode" (click)="onMenuClick($event, node)"
class="menu-button" matTooltip="{{ 'moreActions' | translate }}"> class="menu-button" matTooltip="{{ 'moreActions' | translate }}">
@ -183,12 +194,15 @@
</div> </div>
</div> </div>
</mat-tree-node> </mat-tree-node>
<mat-tree-node [ngClass]="{'selected-node': selectedNode?.id === node.id, 'tree-node': true}" <mat-tree-node [ngClass]="{'selected-node': selectedNode?.id === node.id, 'tree-node': true}"
*matTreeNodeDef="let node; when: isLeafNode" matTreeNodePadding (click)="onNodeClick($event, node)"> *matTreeNodeDef="let node; when: isLeafNode" matTreeNodePadding (click)="onNodeClick($event, node)">
<div class="node-content"> <div class="node-content">
<button mat-icon-button matTreeNodeToggle [disabled]="true" class="disabled-toggle expand-button"> <button mat-icon-button matTreeNodeToggle [disabled]="true" class="disabled-toggle expand-button">
<mat-icon class="expand-icon">chevron_right</mat-icon> <mat-icon class="expand-icon">chevron_right</mat-icon>
</button> </button>
<div class="node-info"> <div class="node-info">
<div class="node-main"> <div class="node-main">
<mat-icon class="node-icon {{ node.type }}" [ngClass]="{'client-status': node.type === 'client'}" <mat-icon class="node-icon {{ node.type }}" [ngClass]="{'client-status': node.type === 'client'}"
@ -204,16 +218,18 @@
</mat-icon> </mat-icon>
<span class="node-name" [matTooltip]="node.name">{{ node.name }}</span> <span class="node-name" [matTooltip]="node.name">{{ node.name }}</span>
</div> </div>
<div class="node-details"> <div class="node-details">
@if (node.type === 'client') { <ng-container *ngIf="node.type === 'client'">
<span class="node-ip">{{ node.ip }}</span> <span class="node-ip">{{ node.ip }}</span>
<span class="node-mac">{{ node.mac }}</span> <span class="node-mac">{{ node.mac }}</span>
<span class="node-status" [ngClass]="'status-' + (node.status || 'off')"> <span class="node-status" [ngClass]="'status-' + (node.status || 'off')">
{{ getStatusLabel(node.status) }} {{ getStatusLabel(node.status) }}
</span> </span>
} </ng-container>
</div> </div>
</div> </div>
<div class="node-actions"> <div class="node-actions">
<button mat-icon-button [matMenuTriggerFor]="menuNode" (click)="onMenuClick($event, node)" <button mat-icon-button [matMenuTriggerFor]="menuNode" (click)="onMenuClick($event, node)"
class="menu-button" matTooltip="{{ 'moreActions' | translate }}"> class="menu-button" matTooltip="{{ 'moreActions' | translate }}">
@ -224,55 +240,42 @@
</mat-tree-node> </mat-tree-node>
</mat-tree> </mat-tree>
</div> </div>
<!-- Tree node actions --> <!-- Tree node actions -->
<mat-menu restoreFocus=false #commandMenu="matMenu"> <mat-menu restoreFocus=false #commandMenu="matMenu">
@for (command of commands; track command) { <button mat-menu-item *ngFor="let command of commands" (click)="executeCommand(command, selectedNode)">
<button mat-menu-item (click)="executeCommand(command, selectedNode)">
<span>{{ command.name }}</span> <span>{{ command.name }}</span>
</button> </button>
}
</mat-menu> </mat-menu>
<mat-menu #menuNode="matMenu"> <mat-menu #menuNode="matMenu">
<button mat-menu-item (click)="onShowDetailsClick($event, selectedNode)"> <button mat-menu-item (click)="onShowDetailsClick($event, selectedNode)">
<mat-icon matTooltip="{{ 'viewUnitTooltip' | translate }}" matTooltipHideDelay="0">visibility</mat-icon> <mat-icon matTooltip="{{ 'viewUnitTooltip' | translate }}" matTooltipHideDelay="0">visibility</mat-icon>
<span>{{ 'viewUnitMenu' | translate }}</span> <span>{{ 'viewUnitMenu' | translate }}</span>
</button> </button>
@if (selectedNode?.type === 'classroom') { <button *ngIf="selectedNode?.type === 'classroom'" mat-menu-item (click)="onRoomMap(selectedNode)">
<button mat-menu-item (click)="onRoomMap(selectedNode)">
<mat-icon>map</mat-icon> <mat-icon>map</mat-icon>
<span>{{ 'roomMap' | translate }}</span> <span>{{ 'roomMap' | translate }}</span>
</button> </button>
} <button mat-menu-item (click)="addClient($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'" [disabled]="!hasOrganizationalUnits()">
@if (auth.userCategory !== 'ou-minimal') {
<button mat-menu-item (click)="addClient($event, selectedNode)" [disabled]="!hasOrganizationalUnits()">
<mat-icon>add</mat-icon> <mat-icon>add</mat-icon>
<span>{{ 'newSingleClientButton' | translate }}</span> <span>{{ 'newSingleClientButton' | translate }}</span>
</button> </button>
} <button mat-menu-item (click)="addMultipleClients($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'" [disabled]="!hasOrganizationalUnits()">
@if (auth.userCategory !== 'ou-minimal') {
<button mat-menu-item (click)="addMultipleClients($event, selectedNode)" [disabled]="!hasOrganizationalUnits()">
<mat-icon>playlist_add</mat-icon> <mat-icon>playlist_add</mat-icon>
<span>{{ 'newMultipleClientButton' | translate }}</span> <span>{{ 'newMultipleClientButton' | translate }}</span>
</button> </button>
} <button mat-menu-item (click)="addOU($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'">
@if (auth.userCategory !== 'ou-minimal') {
<button mat-menu-item (click)="addOU($event, selectedNode)">
<mat-icon>account_tree</mat-icon> <mat-icon>account_tree</mat-icon>
<span>{{ 'addOrganizationalUnit' | translate }}</span> <span>{{ 'addOrganizationalUnit' | translate }}</span>
</button> </button>
} <button mat-menu-item (click)="onEditNode($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'">
@if (auth.userCategory !== 'ou-minimal') {
<button mat-menu-item (click)="onEditNode($event, selectedNode)">
<mat-icon>edit</mat-icon> <mat-icon>edit</mat-icon>
<span>{{ 'buttonEdit' | translate }}</span> <span>{{ 'buttonEdit' | translate }}</span>
</button> </button>
} <button mat-menu-item (click)="onDeleteClick($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'">
@if (auth.userCategory !== 'ou-minimal' && auth.userCategory !== 'ou-operator') {
<button mat-menu-item (click)="onDeleteClick($event, selectedNode)">
<mat-icon>delete</mat-icon> <mat-icon>delete</mat-icon>
<span>{{ 'buttonDelete' | translate }}</span> <span>{{ 'buttonDelete' | translate }}</span>
</button> </button>
}
<button mat-menu-item (click)="openPartitionTypeModal($event, selectedNode)"> <button mat-menu-item (click)="openPartitionTypeModal($event, selectedNode)">
<mat-icon>storage</mat-icon> <mat-icon>storage</mat-icon>
<span>{{ 'partitions' | translate }}</span> <span>{{ 'partitions' | translate }}</span>
@ -281,21 +284,16 @@
<mat-icon>pending_actions</mat-icon> <mat-icon>pending_actions</mat-icon>
<span>{{ 'colaAcciones' | translate }}</span> <span>{{ 'colaAcciones' | translate }}</span>
</button> </button>
<app-execute-command <app-execute-command [clientData]="selectedNode?.clients || []" [buttonType]="'menu-item'"
[organizationalUnit]="selectedNode" [buttonText]="'ejecutarComandos' | translate" [icon]="'terminal'"
[showOnlyDirectClients]="showOnlyDirectClients" [disabled]="!((selectedNode?.clients ?? []).length > 0)" [runScriptContext]="selectedNode?.name || ''"
[clientData]="selectedNode?.clients || []" [runScriptContext]="getRunScriptContext(selectedNode?.clients || [])">
[buttonType]="'menu-item'"
[buttonText]="'ejecutarComandos' | translate"
[icon]="'terminal'"
[disabled]="!((selectedNode?.clients ?? []).length > 0)"
[runScriptContext]="selectedNode">
</app-execute-command> </app-execute-command>
</mat-menu> </mat-menu>
</div> </div>
<div class="tree-resizer" (mousedown)="onTreeResizeStart($event)" [class.resizing]="isTreeResizing">
<div class="resizer-line"></div> <mat-divider [vertical]="true"></mat-divider>
</div>
<!-- CLIENTS --> <!-- CLIENTS -->
<div class="clients-container"> <div class="clients-container">
<mat-divider class="clients-mat-divider"></mat-divider> <mat-divider class="clients-mat-divider"></mat-divider>
@ -306,37 +304,35 @@
<strong>{{ selectedNode?.name }}</strong> <strong>{{ selectedNode?.name }}</strong>
</span> </span>
<div class="view-type-container"> <div class="view-type-container">
@if (currentView === 'card') { <mat-checkbox *ngIf="currentView === 'card'" class="cards-select-all-inline"
<mat-checkbox class="cards-select-all-inline"
(change)="toggleAllCards()" (change)="toggleAllCards()"
[checked]="selection.hasValue() && isAllSelected()" [checked]="selection.hasValue() && isAllSelected()"
[indeterminate]="selection.hasValue() && !isAllSelected()" [indeterminate]="selection.hasValue() && !isAllSelected()"
[matTooltip]="'buttonSelectAll' | translate"> [matTooltip]="'buttonSelectAll' | translate">
</mat-checkbox> </mat-checkbox>
}
<button class="action-button" [disabled]="selection.selected.length === 0" (click)="changeParent($event)" <button class="action-button" [disabled]="selection.selected.length === 0" (click)="changeParent($event)"
matTooltip="{{ 'moveClientsTooltip' | translate }}" matTooltipShowDelay="1000"> matTooltip="{{ 'moveClientsTooltip' | translate }}" matTooltipShowDelay="1000">
{{ 'changeOU' | translate }} {{ 'changeOU' | translate }}
</button> </button>
<div joyrideStep="executeCommandStep" text="{{ 'executeCommandStepText' | translate }}"> <div joyrideStep="executeCommandStep" text="{{ 'executeCommandStepText' | translate }}">
<app-execute-command [clientData]="selection.selected" [buttonType]="'text'" <app-execute-command [clientData]="selection.selected" [buttonType]="'text'"
[buttonText]="'ejecutarComandos' | translate" [disabled]="selection.selected.length === 0" [buttonText]="'ejecutarComandos' | translate" [disabled]="selection.selected.length === 0"
[runScriptContext]="getRunScriptContext(selection.selected)"></app-execute-command> [runScriptContext]="getRunScriptContext(selection.selected)"></app-execute-command>
</div> </div>
@if (classroomCalendarUuid && !syncingUds) {
<button class="action-button sync-uds-button" (click)="syncUds($event)" <button *ngIf="classroomCalendarUuid && !syncingUds" class="action-button sync-uds-button" (click)="syncUds($event)"
[disabled]="!classroomHasRemotePc" [disabled]="!classroomHasRemotePc"
matTooltip="Sincronizar calendarios con UDS" matTooltipShowDelay="500"> matTooltip="Sincronizar calendarios con UDS" matTooltipShowDelay="500">
<mat-icon>sync</mat-icon> <mat-icon>sync</mat-icon>
</button> </button>
} <mat-spinner *ngIf="syncingUds" diameter="24" style="margin: 0 8px;"></mat-spinner>
@if (syncingUds) {
<mat-spinner diameter="24" style="margin: 0 8px;"></mat-spinner>
}
<button class="action-button delete-button" [disabled]="selection.selected.length === 0" (click)="deleteMultipleClients($event)" <button class="action-button delete-button" [disabled]="selection.selected.length === 0" (click)="deleteMultipleClients($event)"
matTooltip="{{ 'deleteMultipleClientsTooltip' | translate }}" matTooltipShowDelay="1000"> matTooltip="{{ 'deleteMultipleClientsTooltip' | translate }}" matTooltipShowDelay="1000">
<mat-icon>delete</mat-icon> <mat-icon>delete</mat-icon>
</button> </button>
<mat-button-toggle-group name="viewType" [attr.aria-label]="'viewType' | translate" [hideSingleSelectionIndicator]="true" <mat-button-toggle-group name="viewType" [attr.aria-label]="'viewType' | translate" [hideSingleSelectionIndicator]="true"
(change)="toggleView($event.value)" joyrideStep="tabsStep" text="{{ 'tabsStepText' | translate }}"> (change)="toggleView($event.value)" joyrideStep="tabsStep" text="{{ 'tabsStepText' | translate }}">
<mat-button-toggle value="list" [disabled]="currentView === 'list'"> <mat-button-toggle value="list" [disabled]="currentView === 'list'">
@ -348,15 +344,15 @@
</mat-button-toggle-group> </mat-button-toggle-group>
</div> </div>
</div> </div>
<app-loading [isLoading]="isLoadingClients"></app-loading> <app-loading [isLoading]="isLoadingClients"></app-loading>
<!-- CLIENTS VIEWS--> <!-- CLIENTS VIEWS-->
@if (!isLoadingClients) { <div class="clients-view" *ngIf="!isLoadingClients" joyrideStep="clientsViewStep"
<div class="clients-view" joyrideStep="clientsViewStep"
text="{{ 'clientsViewStepText' | translate }}"> text="{{ 'clientsViewStepText' | translate }}">
@if (hasClients) { <div *ngIf="hasClients; else noClientsTemplate">
<div>
@if (currentView === 'list') { <div class="stats-container" *ngIf="currentView === 'list'">
<div class="stats-container">
<div class="stat-card"> <div class="stat-card">
<div class="stat-icon"> <div class="stat-icon">
<mat-icon>computer</mat-icon> <mat-icon>computer</mat-icon>
@ -394,63 +390,87 @@
</div> </div>
</div> </div>
</div> </div>
}
<!-- Cards view --> <!-- Cards view -->
@if (currentView === 'card') { <div *ngIf="currentView === 'card'">
<div>
<section class="cards-view"> <section class="cards-view">
<div class="clients-grid"> <div class="clients-grid">
@for (client of arrayClients; track client) { <div *ngFor="let client of arrayClients" class="client-item" [ngClass]="'status-' + client.status">
<div class="client-item" [ngClass]="'status-' + client.status">
<div class="client-card"> <div class="client-card">
<mat-checkbox (click)="$event.stopPropagation()" (change)="toggleRow(client)" <mat-checkbox (click)="$event.stopPropagation()" (change)="toggleRow(client)"
[checked]="selection.isSelected(client)"> [checked]="selection.isSelected(client)">
</mat-checkbox> </mat-checkbox>
<img [src]="'assets/images/computer_' + client.status + '.svg'" <img style="margin-top: 0.5em;" [src]="'assets/images/computer_' + client.status + '.svg'"
alt="Client Icon" class="client-image client-image-spacing" /> alt="Client Icon" class="client-image" />
<div class="client-details"> <div class="client-details">
<span class="client-name truncate-cell-wide" [matTooltip]="client.name">{{ client.name }}</span> <span class="client-name truncate-cell-wide" [matTooltip]="client.name">{{ client.name }}</span>
<span class="client-ip">{{ client.ip }}</span> <span class="client-ip">{{ client.ip }}</span>
<span class="client-mac">{{ client.mac }}</span> <span class="client-mac">{{ client.mac }}</span>
@if (client.netSpeed) { <span *ngIf="client.isRemotePcActive" class="remote-pc-badge">
<span class="badge-net-speed speed-{{client.netSpeed}} " [matTooltip]="client.netSpeed + ' Mbps'">
<mat-icon class="net-speed-icon">speed</mat-icon> {{ client.netSpeed }} Mbps
</span>
}
@if (client.isRemotePcActive) {
<span class="remote-pc-badge">
<mat-icon class="remote-pc-icon">computer</mat-icon> <mat-icon class="remote-pc-icon">computer</mat-icon>
RemotePC RemotePC
</span> </span>
}
@for (badge of getPluginBadges(client); track badge.id + '-' + badge.type + '-' + badge.label + '-' + (badge.tooltip || '')) {
<span class="plugin-badge badge-{{badge.type}}" [matTooltip]="badge.tooltip">
<mat-icon class="plugin-badge-icon">{{ badge.icon }}</mat-icon> {{ badge.label }}
</span>
}
<div class="action-icons"> <div class="action-icons">
<app-execute-command [clientState]="client.status" [clientData]="[client]" <app-execute-command [clientState]="client.status" [clientData]="[client]"
[buttonType]="'icon'" [icon]="'terminal'" [buttonType]="'icon'" [icon]="'terminal'"
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))" [disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))"
[runScriptContext]="getRunScriptContext([client])"></app-execute-command> [runScriptContext]="getRunScriptContext([client])"></app-execute-command>
<button <button
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))" [disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))"
mat-icon-button [matMenuTriggerFor]="clientMenu" color="primary"> mat-icon-button [matMenuTriggerFor]="clientMenu" color="primary">
<mat-icon>more_vert</mat-icon> <mat-icon>more_vert</mat-icon>
</button> </button>
<mat-menu #clientMenu="matMenu">
<ng-container *ngTemplateOutlet="sharedMenuItems; context: {client: client}"></ng-container> <span class="sync-spinner" *ngIf="syncingClientIds.has(client.uuid)">
</mat-menu>
@if (syncingClientIds.has(client.uuid)) {
<span class="sync-spinner">
<mat-spinner diameter="24"></mat-spinner> <mat-spinner diameter="24"></mat-spinner>
</span> </span>
}
<mat-menu #clientMenu="matMenu">
<button mat-menu-item (click)="onEditClick($event, client.type, client.uuid)" *ngIf="auth.userCategory !== 'ou-minimal'">
<mat-icon>edit</mat-icon>
<span>{{ 'buttonEdit' | translate }}</span>
</button>
<button mat-menu-item (click)="onShowClientDetail($event, client)">
<mat-icon>visibility</mat-icon>
<span>{{ 'buttonViewDetails' | translate }}</span>
</button>
<button mat-menu-item *ngIf="!syncingClientIds.has(client.uuid)"
(click)="getStatus(client, selectedNode)">
<mat-icon>sync</mat-icon>
<span>{{ 'buttonSync' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientTaskLogs($event, client)">
<mat-icon>list_alt</mat-icon>
<span>{{ 'procedimientosCliente' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientPendingTasks($event, client)">
<mat-icon>pending_actions</mat-icon>
<span>{{ 'colaAcciones' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientLogsInNewTab($event, client)">
<mat-icon>article</mat-icon>
<span>{{ 'realTimeLogs' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientLogsModal($event, client)">
<mat-icon>analytics</mat-icon>
<span>{{ 'clientLogs' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientDiskLogsModal($event, client)">
<mat-icon>storage</mat-icon>
<span>{{ 'diskLogs' | translate }}</span>
</button>
<button mat-menu-item (click)="onDeleteClick($event, client)" *ngIf="auth.userCategory !== 'ou-minimal'">
<mat-icon>delete</mat-icon>
<span>{{ 'buttonDelete' | translate }}</span>
</button>
</mat-menu>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
}
</div> </div>
</section> </section>
<div class="paginator-container"> <div class="paginator-container">
@ -459,10 +479,9 @@
</mat-paginator> </mat-paginator>
</div> </div>
</div> </div>
}
<!-- List view mejorada --> <!-- List view mejorada -->
@if (currentView === 'list') { <div *ngIf="currentView === 'list'" class="list-view">
<div class="list-view">
<div class="table-header"> <div class="table-header">
<div class="table-info"> <div class="table-info">
<span>{{ 'showingResults' | translate: { from: getPaginationFrom(), to: getPaginationTo(), total: getPaginationTotal() } }}</span> <span>{{ 'showingResults' | translate: { from: getPaginationFrom(), to: getPaginationTo(), total: getPaginationTotal() } }}</span>
@ -476,6 +495,7 @@
</button> </button>
</div> </div>
</div> </div>
<section class="clients-table" tabindex="0"> <section class="clients-table" tabindex="0">
<table mat-table [dataSource]="selectedClients" class="mat-elevation-z8"> <table mat-table [dataSource]="selectedClients" class="mat-elevation-z8">
<ng-container matColumnDef="select"> <ng-container matColumnDef="select">
@ -505,14 +525,13 @@
<div class="client-status-container"> <div class="client-status-container">
<img [src]="'assets/images/computer_' + client.status + '.svg'" alt="Client Icon" <img [src]="'assets/images/computer_' + client.status + '.svg'" alt="Client Icon"
class="client-image" /> class="client-image" />
@if (syncingClientIds.has(client.uuid)) { <span *ngIf="syncingClientIds.has(client.uuid)">
<span>
<mat-spinner diameter="24"></mat-spinner> <mat-spinner diameter="24"></mat-spinner>
</span> </span>
}
</div> </div>
</td> </td>
</ng-container> </ng-container>
<ng-container matColumnDef="name"> <ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> <th mat-header-cell *matHeaderCellDef>
<div class="column-header"> <div class="column-header">
@ -543,25 +562,10 @@
<div class="client-cell"> <div class="client-cell">
<span class="client-ip">{{ client.ip }}</span> <span class="client-ip">{{ client.ip }}</span>
<span class="client-mac">{{ client.mac }}</span> <span class="client-mac">{{ client.mac }}</span>
@if (client.netSpeed) {
<span class="badge-net-speed speed-{{client.netSpeed}} list-view-badge" [matTooltip]="client.netSpeed + ' Mbps'">
<mat-icon class="net-speed-icon">speed</mat-icon> {{ client.netSpeed }} Mbps
</span>
}
@if (client.isRemotePcActive) {
<span class="remote-pc-badge list-view-badge">
<mat-icon class="remote-pc-icon">computer</mat-icon>
RemotePC
</span>
}
@for (badge of getPluginBadges(client); track badge.id + '-' + badge.type + '-' + badge.label + '-' + (badge.tooltip || '')) {
<span class="plugin-badge badge-{{badge.type}} list-view-badge" [matTooltip]="badge.tooltip">
<mat-icon class="plugin-badge-icon">{{ badge.icon }}</mat-icon> {{ badge.label }}
</span>
}
</div> </div>
</td> </td>
</ng-container> </ng-container>
<ng-container matColumnDef="firmwareType"> <ng-container matColumnDef="firmwareType">
<th mat-header-cell *matHeaderCellDef> <th mat-header-cell *matHeaderCellDef>
<div class="column-header"> <div class="column-header">
@ -572,44 +576,12 @@
</div> </div>
</th> </th>
<td mat-cell *matCellDef="let client"> <td mat-cell *matCellDef="let client">
@if (client.firmwareType) { <mat-chip *ngIf="client.firmwareType" class="firmware-chip">
<mat-chip class="firmware-chip">
{{ client.firmwareType }} {{ client.firmwareType }}
</mat-chip> </mat-chip>
}
</td>
</ng-container>
<ng-container matColumnDef="imageCloning">
<th mat-header-cell *matHeaderCellDef>
<div class="column-header">
<span>{{ 'imageCloning' | translate }}</span>
</div>
</th>
<td mat-cell *matCellDef="let client">
@if (getImagesFromClient(client); as images) {
@if (images.length === 1) {
<div class="cloning-cell">
<span class="image-name truncate-cell-medium" [matTooltip]="images[0].name">{{ images[0].name }}</span>
@if (images[0].date) {
<span class="image-date">{{ 'labelDeployed' | translate }}: {{ images[0].date | date:'dd/MM/yyyy HH:mm' }}</span>
}
</div>
} @else if (images.length > 1) {
<div class="cloning-cell">
<div class="multi-image-container">
<span class="image-name truncate-cell-medium" [matTooltip]="images[0].name">{{ images[0].name }}</span>
<span class="multi-image-badge" [matTooltip]="getMultiImageTooltip(images)">+{{images.length - 1}}</span>
</div>
@if (images[0].date) {
<span class="image-date">{{ 'labelDeployed' | translate }}: {{ images[0].date | date:'dd/MM/yyyy HH:mm' }}</span>
}
</div>
} @else {
<span>-</span>
}
}
</td> </td>
</ng-container> </ng-container>
<ng-container matColumnDef="oglive"> <ng-container matColumnDef="oglive">
<th mat-header-cell *matHeaderCellDef> {{ 'ogLiveTitle' | translate }}</th> <th mat-header-cell *matHeaderCellDef> {{ 'ogLiveTitle' | translate }}</th>
<td mat-cell *matCellDef="let client"> <td mat-cell *matCellDef="let client">
@ -619,6 +591,7 @@
</div> </div>
</td> </td>
</ng-container> </ng-container>
<ng-container matColumnDef="maintenace"> <ng-container matColumnDef="maintenace">
<th mat-header-cell *matHeaderCellDef> {{ 'maintenance' | translate }} </th> <th mat-header-cell *matHeaderCellDef> {{ 'maintenance' | translate }} </th>
<td mat-cell *matCellDef="let client"> {{ client.maintenance }} </td> <td mat-cell *matCellDef="let client"> {{ client.maintenance }} </td>
@ -631,10 +604,12 @@
<th mat-header-cell *matHeaderCellDef> {{ 'pxeTemplate' | translate }} </th> <th mat-header-cell *matHeaderCellDef> {{ 'pxeTemplate' | translate }} </th>
<td mat-cell *matCellDef="let client" class="truncate-cell-medium" [matTooltip]="client.pxeTemplate?.name"> {{ client.pxeTemplate?.name }} </td> <td mat-cell *matCellDef="let client" class="truncate-cell-medium" [matTooltip]="client.pxeTemplate?.name"> {{ client.pxeTemplate?.name }} </td>
</ng-container> </ng-container>
<ng-container matColumnDef="parentName"> <ng-container matColumnDef="parentName">
<th mat-header-cell *matHeaderCellDef> {{ 'labelEditOrgUnitParent' | translate }} </th> <th mat-header-cell *matHeaderCellDef> {{ 'labelEditOrgUnitParent' | translate }} </th>
<td mat-cell *matCellDef="let client" class="truncate-cell-medium" [matTooltip]="client.parentName"> {{ client.parentName }} </td> <td mat-cell *matCellDef="let client" class="truncate-cell-medium" [matTooltip]="client.parentName"> {{ client.parentName }} </td>
</ng-container> </ng-container>
<ng-container matColumnDef="actions"> <ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef> {{ 'actions' | translate }} </th> <th mat-header-cell *matHeaderCellDef> {{ 'actions' | translate }} </th>
<td mat-cell *matCellDef="let client"> <td mat-cell *matCellDef="let client">
@ -644,9 +619,6 @@
mat-icon-button [matMenuTriggerFor]="clientMenu" color="primary" matTooltip="{{ 'moreActions' | translate }}"> mat-icon-button [matMenuTriggerFor]="clientMenu" color="primary" matTooltip="{{ 'moreActions' | translate }}">
<mat-icon>more_vert</mat-icon> <mat-icon>more_vert</mat-icon>
</button> </button>
<mat-menu #clientMenu="matMenu">
<ng-container *ngTemplateOutlet="sharedMenuItems; context: {client: client}"></ng-container>
</mat-menu>
<app-execute-command [clientState]="client.status" [clientData]="[client]" [buttonType]="'icon'" <app-execute-command [clientState]="client.status" [clientData]="[client]" [buttonType]="'icon'"
[icon]="'terminal'" [icon]="'terminal'"
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))" [disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))"
@ -656,6 +628,44 @@
<mat-icon>visibility</mat-icon> <mat-icon>visibility</mat-icon>
</button> </button>
</div> </div>
<mat-menu #clientMenu="matMenu">
<button mat-menu-item (click)="onEditClick($event, client.type, client.uuid)" *ngIf="auth.userCategory !== 'ou-minimal'">
<mat-icon>edit</mat-icon>
<span>{{ 'buttonEdit' | translate }}</span>
</button>
<button mat-menu-item (click)="onShowClientDetail($event, client)">
<mat-icon>visibility</mat-icon>
<span>{{ 'buttonViewDetails' | translate }}</span>
</button>
<button mat-menu-item (click)="getStatus(client, selectedNode)">
<mat-icon>sync</mat-icon>
<span>{{ 'buttonSync' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientTaskLogs($event, client)">
<mat-icon>list_alt</mat-icon>
<span>{{ 'procedimientosCliente' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientPendingTasks($event, client)">
<mat-icon>pending_actions</mat-icon>
<span>{{ 'colaAcciones' | translate }}</span>
</button>
<button mat-menu-item *ngIf="client.status === 'og-live'" (click)="openClientLogsInNewTab($event, client)">
<mat-icon>article</mat-icon>
<span>{{ 'realTimeLogs' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientLogsModal($event, client)">
<mat-icon>analytics</mat-icon>
<span>{{ 'clientLogs' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientDiskLogsModal($event, client)">
<mat-icon>storage</mat-icon>
<span>{{ 'diskLogs' | translate }}</span>
</button>
<button mat-menu-item (click)="onDeleteClick($event, client)" *ngIf="auth.userCategory !== 'ou-minimal'">
<mat-icon>delete</mat-icon>
<span>{{ 'buttonDelete' | translate }}</span>
</button>
</mat-menu>
</td> </td>
</ng-container> </ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr> <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
@ -669,70 +679,19 @@
[pageSizeOptions]="pageSizeOptions" (page)="onPageChange($event)"> [pageSizeOptions]="pageSizeOptions" (page)="onPageChange($event)">
</mat-paginator> </mat-paginator>
</div> </div>
}
</div> </div>
} @else {
@if (!initialLoading) { <!-- No clients view -->
<div class="no-clients-info"> <ng-template #noClientsTemplate>
<div *ngIf="!initialLoading" class="no-clients-info">
<span>{{ 'noClients' | translate }}</span> <span>{{ 'noClients' | translate }}</span>
<mat-icon>error_outline</mat-icon> <mat-icon>error_outline</mat-icon>
</div> </div>
}
}
<!-- No clients view -->
</div>
}
</div>
</div>
}
<!-- MAIN VIEW -->
</div>
<!-- Shared Menu Items Template -->
<ng-template #sharedMenuItems let-client="client">
@if (auth.userCategory !== 'ou-minimal') {
<button mat-menu-item (click)="onEditClick($event, client.type, client.uuid)">
<mat-icon>edit</mat-icon>
<span>{{ 'buttonEdit' | translate }}</span>
</button>
}
<button mat-menu-item (click)="onShowClientDetail($event, client)">
<mat-icon>visibility</mat-icon>
<span>{{ 'buttonViewDetails' | translate }}</span>
</button>
@if (!syncingClientIds.has(client.uuid)) {
<button mat-menu-item (click)="getStatus(client, selectedNode)">
<mat-icon>sync</mat-icon>
<span>{{ 'buttonSync' | translate }}</span>
</button>
}
<button mat-menu-item (click)="openClientTaskLogs($event, client)">
<mat-icon>list_alt</mat-icon>
<span>{{ 'procedimientosCliente' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientPendingTasks($event, client)">
<mat-icon>pending_actions</mat-icon>
<span>{{ 'colaAcciones' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientLogsInNewTab($event, client)">
<mat-icon>article</mat-icon>
<span>{{ 'realTimeLogs' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientLogsModal($event, client)">
<mat-icon>analytics</mat-icon>
<span>{{ 'clientLogs' | translate }}</span>
</button>
<button mat-menu-item (click)="openClientDiskLogsModal($event, client)">
<mat-icon>storage</mat-icon>
<span>{{ 'diskLogs' | translate }}</span>
</button>
@if (auth.userCategory !== 'ou-minimal') {
<button mat-menu-item (click)="onDeleteClick($event, client)">
<mat-icon>delete</mat-icon>
<span>{{ 'buttonDelete' | translate }}</span>
</button>
}
</ng-template> </ng-template>
</div>
</div>
</div>
</ng-template>
</div>

View File

@ -1,6 +1,6 @@
import { inject } from '@angular/core'; import { inject } from '@angular/core';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { Component, OnInit, OnDestroy, ViewChild, QueryList, ViewChildren, ChangeDetectorRef, HostListener } from '@angular/core'; import { Component, OnInit, OnDestroy, ViewChild, QueryList, ViewChildren, ChangeDetectorRef } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http'; import { HttpClient, HttpParams } from '@angular/common/http';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
@ -36,7 +36,6 @@ import { ClientPendingTasksComponent } from '../task-logs/client-pending-tasks/c
import { ClientLogsModalComponent } from './shared/client-logs-modal/client-logs-modal.component'; import { ClientLogsModalComponent } from './shared/client-logs-modal/client-logs-modal.component';
import { ClientDiskLogsModalComponent } from './shared/client-disk-logs-modal/client-disk-logs-modal.component'; import { ClientDiskLogsModalComponent } from './shared/client-disk-logs-modal/client-disk-logs-modal.component';
import { DeleteResultsModalComponent } from './shared/delete-results-modal/delete-results-modal.component'; import { DeleteResultsModalComponent } from './shared/delete-results-modal/delete-results-modal.component';
import { PluginService, PluginBadge } from '@services/plugin.service';
enum NodeType { enum NodeType {
OrganizationalUnit = 'organizational-unit', OrganizationalUnit = 'organizational-unit',
@ -89,7 +88,6 @@ export class GroupsComponent implements OnInit, OnDestroy {
private clientFilterSubject = new Subject<string>(); private clientFilterSubject = new Subject<string>();
loading = false; loading = false;
showOnlyDirectClients: boolean = false; showOnlyDirectClients: boolean = false;
showSearchFilters: boolean = false;
// Nuevas propiedades para funcionalidades mejoradas // Nuevas propiedades para funcionalidades mejoradas
selectedClient: any = null; selectedClient: any = null;
@ -113,8 +111,6 @@ export class GroupsComponent implements OnInit, OnDestroy {
// Tipos de firmware disponibles // Tipos de firmware disponibles
firmwareTypes: string[] = []; firmwareTypes: string[] = [];
private fetchClientsSubscription?: Subscription;
protected status = [ protected status = [
{ value: 'off', name: 'Apagado' }, { value: 'off', name: 'Apagado' },
{ value: 'initializing', name: 'Inicializando' }, { value: 'initializing', name: 'Inicializando' },
@ -128,54 +124,7 @@ export class GroupsComponent implements OnInit, OnDestroy {
{ value: 'disconnected', name: 'Desconectado' } { value: 'disconnected', name: 'Desconectado' }
]; ];
displayedColumns: string[] = ['select', 'status', 'ip', 'firmwareType', 'imageCloning', 'name', 'oglive', 'subnet', 'pxeTemplate', 'actions']; displayedColumns: string[] = ['select', 'status', 'ip', 'firmwareType', 'name', 'oglive', 'subnet', 'pxeTemplate', 'actions'];
getImagesFromClient(client: any): any[] {
if (!client) return [];
const images: any[] = [];
const partitions = client.partitions ||
(client.disks ? client.disks.flatMap((d: any) => d.partitions || []) : []);
const dateKeys = ['lastRestored', 'restoredAt', 'lastCloned', 'cloningDate', 'updatedAt', 'createdAt', 'date'];
const extractDate = (obj: any): string | null => {
if (!obj) return null;
for (const key of dateKeys) {
if (obj[key]) return obj[key];
}
return null;
};
for (const part of partitions) {
const date = extractDate(part.image) || extractDate(part) || extractDate(client);
if (part.image?.name) {
images.push({ name: part.image.name, date });
} else if (typeof part.image === 'string' && part.image.trim()) {
images.push({ name: part.image, date });
} else if (part.operatingSystem?.name) {
images.push({ name: part.operatingSystem.name, date });
} else if (part.os?.name) {
images.push({ name: part.os.name, date });
}
}
return images;
}
getMultiImageTooltip(images: any[]): string {
if (!images || images.length <= 1) return '';
return images.slice(1).map(img => {
let txt = img.name;
if (img.date) {
const d = new Date(img.date);
txt += ` (Desplegada: ${d.toLocaleDateString()} ${d.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})})`;
}
return txt;
}).join('\n');
}
getPluginBadges(client: any): PluginBadge[] {
return this.pluginService.getClientBadges(client);
}
private subscriptions: Subscription = new Subscription(); private subscriptions: Subscription = new Subscription();
@ -191,7 +140,6 @@ export class GroupsComponent implements OnInit, OnDestroy {
public auth: AuthService, public auth: AuthService,
private configService: ConfigService, private configService: ConfigService,
private cd: ChangeDetectorRef, private cd: ChangeDetectorRef,
public pluginService: PluginService,
) { ) {
this.baseUrl = this.configService.apiUrl; this.baseUrl = this.configService.apiUrl;
this.mercureUrl = this.configService.mercureUrl; this.mercureUrl = this.configService.mercureUrl;
@ -213,25 +161,12 @@ export class GroupsComponent implements OnInit, OnDestroy {
if (!this.pageSizeOptions.includes(this.itemsPerPage)) { if (!this.pageSizeOptions.includes(this.itemsPerPage)) {
this.pageSizeOptions = [...this.pageSizeOptions, this.itemsPerPage].sort((a, b) => a - b); this.pageSizeOptions = [...this.pageSizeOptions, this.itemsPerPage].sort((a, b) => a - b);
} }
// Load search filters visibility state from localStorage, default false
const savedShowSearch = localStorage.getItem('showSearchFilters');
this.showSearchFilters = savedShowSearch ? JSON.parse(savedShowSearch) : false;
}
toggleSearchFilters(): void {
this.showSearchFilters = !this.showSearchFilters;
localStorage.setItem('showSearchFilters', JSON.stringify(this.showSearchFilters));
} }
ngOnInit(): void { ngOnInit(): void {
const savedWidth = localStorage.getItem('oggui_tree_panel_width_' + (this.auth.username || 'default'));
if (savedWidth) {
this.treePanelWidth = parseInt(savedWidth, 10);
}
this.updateGridCols(); this.updateGridCols();
this.refreshData(localStorage.getItem('lastSelectedOU') ?? undefined); this.refreshData();
window.addEventListener('resize', this.updateGridCols); window.addEventListener('resize', this.updateGridCols);
this.selectedClients.filterPredicate = (client: Client, filter: string): boolean => { this.selectedClients.filterPredicate = (client: Client, filter: string): boolean => {
@ -270,14 +205,7 @@ export class GroupsComponent implements OnInit, OnDestroy {
this.breakpointObserver.observe(['(max-width: 992px)']).subscribe((result) => { this.breakpointObserver.observe(['(max-width: 992px)']).subscribe((result) => {
this.isSmallScreen = result.matches; this.isSmallScreen = result.matches;
});
this.subscriptions.add(
this.pluginService.statusUpdates$.subscribe(() => {
this.cd.markForCheck();
this.cd.detectChanges();
}) })
);
} }
private updateClientStatus(clientUuid: string, status: string): void { private updateClientStatus(clientUuid: string, status: string): void {
@ -410,12 +338,12 @@ export class GroupsComponent implements OnInit, OnDestroy {
this.treeDataSource.data = [...this.originalTreeData]; this.treeDataSource.data = [...this.originalTreeData];
if (selectedNodeIdOrUuid) { if (selectedNodeIdOrUuid) {
this.selectedNode = this.findNodeByIdOrUuid(this.treeDataSource.data, selectedNodeIdOrUuid); this.selectedNode = this.findNodeByIdOrUuid(this.treeDataSource.data, selectedNodeIdOrUuid);
}
if (selectedNodeIdOrUuid && this.selectedNode) { if (this.selectedNode) {
this.treeControl.collapseAll(); this.treeControl.collapseAll();
this.expandPathToNode(this.selectedNode); this.expandPathToNode(this.selectedNode);
this.fetchClientsForNode(this.selectedNode, selectedClientsBeforeEdit); this.fetchClientsForNode(this.selectedNode, selectedClientsBeforeEdit);
}
} else { } else {
this.treeControl.collapseAll(); this.treeControl.collapseAll();
if (this.treeDataSource.data.length > 0) { if (this.treeDataSource.data.length > 0) {
@ -489,31 +417,23 @@ export class GroupsComponent implements OnInit, OnDestroy {
onNodeClick(event: MouseEvent, node: TreeNode): void { onNodeClick(event: MouseEvent, node: TreeNode): void {
event.stopPropagation(); event.stopPropagation();
this.selectedNode = node; this.selectedNode = node;
this.persistSelectedNode(node);
const selectedClientsBeforeEdit = this.selection.selected.map(client => client.uuid); const selectedClientsBeforeEdit = this.selection.selected.map(client => client.uuid);
this.fetchClientsForNode(node, selectedClientsBeforeEdit);
const checkStatusAfterLoad = node.type === NodeType.Classroom || node.type === NodeType.ClientsGroup; if (node.type === NodeType.Classroom || node.type === NodeType.ClientsGroup) {
this.fetchClientsForNode(node, selectedClientsBeforeEdit, checkStatusAfterLoad); this.getStatusForAllClientsInNode(node);
}
} }
onMenuClick(event: Event, node: any): void { onMenuClick(event: Event, node: any): void {
event.stopPropagation(); event.stopPropagation();
this.selectedNode = node; this.selectedNode = node;
this.persistSelectedNode(node);
const selectedClientsBeforeEdit = this.selection.selected.map(client => client.uuid); const selectedClientsBeforeEdit = this.selection.selected.map(client => client.uuid);
this.fetchClientsForNode(node, selectedClientsBeforeEdit); this.fetchClientsForNode(node, selectedClientsBeforeEdit);
} }
private persistSelectedNode(node: TreeNode): void {
if (node.uuid) {
localStorage.setItem('lastSelectedOU', node.uuid);
}
}
public fetchClientsForNode(node: any, selectedClientsBeforeEdit: string[] = []): void {
public fetchClientsForNode(node: any, selectedClientsBeforeEdit: string[] = [], checkStatusAfterLoad: boolean = false): void {
const params = new HttpParams({ fromObject: this.filters }); const params = new HttpParams({ fromObject: this.filters });
// Agregar parámetros de ordenamiento al backend // Agregar parámetros de ordenamiento al backend
@ -522,12 +442,8 @@ export class GroupsComponent implements OnInit, OnDestroy {
backendParams['order[' + this.sortBy + ']'] = this.sortDirection; backendParams['order[' + this.sortBy + ']'] = this.sortDirection;
} }
if (this.fetchClientsSubscription) {
this.fetchClientsSubscription.unsubscribe();
}
this.isLoadingClients = true; this.isLoadingClients = true;
this.fetchClientsSubscription = this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${node.id}&page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: backendParams }).subscribe({ this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${node.id}&page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: backendParams }).subscribe({
next: (response: any) => { next: (response: any) => {
let members = response['hydra:member']; let members = response['hydra:member'];
let total = response['hydra:totalItems']; let total = response['hydra:totalItems'];
@ -560,12 +476,6 @@ export class GroupsComponent implements OnInit, OnDestroy {
members.forEach((c: Client) => c.uuid && this.syncingClientIds.add(c.uuid)); members.forEach((c: Client) => c.uuid && this.syncingClientIds.add(c.uuid));
} }
if (checkStatusAfterLoad) {
this.getStatusForAllClientsInNode(node);
}
this.pluginService.loadActivePluginsStatus().subscribe();
// Calcular estadísticas después de cargar los clientes // Calcular estadísticas después de cargar los clientes
this.calculateLocalStats(); this.calculateLocalStats();
}, },
@ -945,19 +855,14 @@ export class GroupsComponent implements OnInit, OnDestroy {
} }
private checkStatusSubscription?: Subscription;
getStatusForAllClientsInNode(node: any): void { getStatusForAllClientsInNode(node: any): void {
if (!node.uuid) return; if (!node.uuid) return;
if (this.checkStatusSubscription) {
this.checkStatusSubscription.unsubscribe();
}
this.isCheckingNodeStatus = true; this.isCheckingNodeStatus = true;
this.selectedClients.data.forEach(c => c.uuid && this.syncingClientIds.add(c.uuid)); this.selectedClients.data.forEach(c => c.uuid && this.syncingClientIds.add(c.uuid));
this.checkStatusSubscription = this.http.post<{ results: Array<{ uuid: string; ip: string; status: string; success: boolean }> }>( this.subscriptions.add(
this.http.post<{ results: Array<{ uuid: string; ip: string; status: string; success: boolean }> }>(
`${this.baseUrl}/organizational-units/${node.uuid}/agent/status`, `${this.baseUrl}/organizational-units/${node.uuid}/agent/status`,
{} {}
).subscribe({ ).subscribe({
@ -978,7 +883,8 @@ export class GroupsComponent implements OnInit, OnDestroy {
this.selectedClients.data.forEach(c => c.uuid && this.syncingClientIds.delete(c.uuid)); this.selectedClients.data.forEach(c => c.uuid && this.syncingClientIds.delete(c.uuid));
this.toastr.error(this.translate.instant('errorCheckingStatus')); this.toastr.error(this.translate.instant('errorCheckingStatus'));
}, },
}); })
);
} }
@ -1338,39 +1244,12 @@ export class GroupsComponent implements OnInit, OnDestroy {
// Métodos para el árbol mejorado // Métodos para el árbol mejorado
isTreeResizing: boolean = false; expandAll(): void {
treePanelWidth: number = 280; // width base original ajustado
onTreeResizeStart(event: MouseEvent) {
this.isTreeResizing = true;
event.preventDefault(); // Previene la selección de texto al arrastrar
}
@HostListener('window:mousemove', ['$event'])
onTreeResizeMove(event: MouseEvent) {
if (!this.isTreeResizing) return;
this.treePanelWidth += event.movementX;
if (this.treePanelWidth < 250) this.treePanelWidth = 250;
if (this.treePanelWidth > 800) this.treePanelWidth = 800;
}
@HostListener('window:mouseup', ['$event'])
onTreeResizeEnd(event: MouseEvent) {
if (this.isTreeResizing) {
this.isTreeResizing = false;
localStorage.setItem('oggui_tree_panel_width_' + (this.auth.username || 'default'), this.treePanelWidth.toString());
}
}
isTreeExpanded: boolean = false;
toggleExpandAll(): void {
if (this.isTreeExpanded) {
this.treeControl.collapseAll();
} else {
this.treeControl.expandAll(); this.treeControl.expandAll();
} }
this.isTreeExpanded = !this.isTreeExpanded;
collapseAll(): void {
this.treeControl.collapseAll();
} }
getNodeTypeTooltip(nodeType: string): string { getNodeTypeTooltip(nodeType: string): string {

View File

@ -42,8 +42,6 @@ export interface Client {
type: string; type: string;
serialNumber: string; serialNumber: string;
netiface: string; netiface: string;
netDriver?: string;
netSpeed?: number;
organizationalUnit: OrganizationalUnit; organizationalUnit: OrganizationalUnit;
partitions: any[]; partitions: any[];
createdAt: string; createdAt: string;
@ -72,7 +70,6 @@ export interface TreeNode {
type: string; type: string;
'@id'?: string; '@id'?: string;
remotePc?: boolean; remotePc?: boolean;
remotePcRebootOnUnreserve?: boolean;
children?: TreeNode[]; children?: TreeNode[];
hasClients?: boolean; hasClients?: boolean;
clients?: Client[]; clients?: Client[];
@ -89,7 +86,6 @@ export interface FlatNode {
expandable: boolean; expandable: boolean;
hasClients?: boolean; hasClients?: boolean;
remotePc?: boolean; remotePc?: boolean;
remotePcRebootOnUnreserve?: boolean;
networkSettings?: Object; networkSettings?: Object;
ip?: string; ip?: string;
'@id'?: string; '@id'?: string;

View File

@ -1,12 +1,12 @@
<h2 mat-dialog-title>{{ 'moveClientsTo' | translate }}</h2> <h2 mat-dialog-title>{{ 'moveClientsTo' | translate }}</h2>
<mat-dialog-content> <mat-dialog-content>
<app-ou-select <mat-form-field appearance="fill" class="full-width">
class="full-width" <mat-label>{{ 'selectClassroomPrompt' | translate }}</mat-label>
[(ngModel)]="newOU" <mat-select [(ngModel)]="newOU">
[units]="units" <mat-option *ngFor="let unit of units" [value]="unit">{{ unit.name }}</mat-option>
[label]="'selectClassroomPrompt'"> </mat-select>
</app-ou-select> </mat-form-field>
</mat-dialog-content> </mat-dialog-content>
<div class="action-container"> <div class="action-container">

View File

@ -6,7 +6,6 @@ import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog";
import {ToastrService} from "ngx-toastr"; import {ToastrService} from "ngx-toastr";
import {Router} from "@angular/router"; import {Router} from "@angular/router";
import {ConfigService} from "@services/config.service"; import {ConfigService} from "@services/config.service";
import {DataService} from "../../services/data.service";
@Component({ @Component({
selector: 'app-change-parent', selector: 'app-change-parent',
@ -26,7 +25,6 @@ export class ChangeParentComponent implements OnInit {
private toastService: ToastrService, private toastService: ToastrService,
private router: Router, private router: Router,
private configService: ConfigService, private configService: ConfigService,
private dataService: DataService,
@Inject(MAT_DIALOG_DATA) public data: { clients: any} @Inject(MAT_DIALOG_DATA) public data: { clients: any}
) { ) {
this.baseUrl = this.configService.apiUrl; this.baseUrl = this.configService.apiUrl;
@ -40,11 +38,7 @@ export class ChangeParentComponent implements OnInit {
loadUnits() { loadUnits() {
this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=500`).subscribe( this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=500`).subscribe(
response => { response => {
const allUnits = response['hydra:member']; this.units = response['hydra:member'];
this.units = allUnits.map((unit: any) => ({
...unit,
path: this.dataService.getOrganizationalUnitPath(unit, allUnits)
}));
this.loading = false; this.loading = false;
}, },
error => console.error(this.translate.instant('errorFetchingOrganizationalUnits1'), error) error => console.error(this.translate.instant('errorFetchingOrganizationalUnits1'), error)
@ -52,15 +46,9 @@ export class ChangeParentComponent implements OnInit {
} }
save() { save() {
let unitIri = this.newOU;
if (typeof this.newOU === 'number' || (typeof this.newOU === 'string' && !this.newOU.includes('/'))) {
const selectedUnit = this.units.find(u => u.id === Number(this.newOU));
unitIri = selectedUnit ? (selectedUnit['@id'] || `/organizational-units/${selectedUnit.uuid}`) : this.newOU;
}
this.http.post<any>(`${this.baseUrl}/clients/change-organizational-unit`, { this.http.post<any>(`${this.baseUrl}/clients/change-organizational-unit`, {
clients: this.data.clients.map((client: any) => client['@id']), clients: this.data.clients.map((client: any) => client['@id']),
organizationalUnit: unitIri organizationalUnit: this.newOU['@id']
}).subscribe({ }).subscribe({
next: (response) => { next: (response) => {
this.toastService.success(this.translate.instant('parentChangedSuccessfully')); this.toastService.success(this.translate.instant('parentChangedSuccessfully'));

View File

@ -143,21 +143,19 @@ mat-dialog-content {
.remote-pc-badge { .remote-pc-badge {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 4px; gap: 2px;
background-color: #e3f2fd; background-color: #1976d2;
color: #1976d2; color: white;
font-size: 0.75rem; padding: 2px 6px;
font-weight: 600; border-radius: 10px;
padding: 2px 8px; font-size: 10px;
border-radius: 12px; font-weight: bold;
width: fit-content; margin-top: 3px;
margin-top: 4px;
} }
.remote-pc-icon { .remote-pc-icon {
font-size: 14px; font-size: 12px;
width: 14px; height: 12px;
height: 14px; width: 12px;
line-height: 14px; line-height: 12px;
} }

View File

@ -34,6 +34,5 @@
</button> </button>
<app-loading *ngIf="syncingUds" [isLoading]="syncingUds"></app-loading> <app-loading *ngIf="syncingUds" [isLoading]="syncingUds"></app-loading>
</ng-container> </ng-container>
<button class="ordinary-button" mat-dialog-close>{{ 'buttonCancel' | translate }}</button>
<button class="submit-button" (click)="saveDisposition()">{{ 'saveDispositionButton' | translate }}</button> <button class="submit-button" (click)="saveDisposition()">{{ 'saveDispositionButton' | translate }}</button>
</mat-dialog-actions> </mat-dialog-actions>

View File

@ -191,18 +191,6 @@ table {
color: #3f51b5; color: #3f51b5;
font-weight: bold; font-weight: bold;
} }
.badge-disk-type {
display: inline-flex;
align-items: center;
padding: 2px 8px;
font-size: 0.75rem;
font-weight: 600;
color: #1976d2;
background-color: #e3f2fd;
border-radius: 12px;
margin-left: 8px;
vertical-align: middle;
}
.disk-card-metrics-wrapper { .disk-card-metrics-wrapper {
display: flex; display: flex;
align-items: center; align-items: center;
@ -274,67 +262,3 @@ table {
font-style: italic; font-style: italic;
margin-top: 2px; margin-top: 2px;
} }
.partition-badges-row {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 4px;
}
.plugin-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 12px;
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.2px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
width: fit-content;
}
.plugin-badge .plugin-badge-icon {
font-size: 14px;
width: 14px;
height: 14px;
line-height: 14px;
}
.plugin-badge.badge-neutral {
background: #f1f5f9;
color: #64748b;
border: 1px solid #cbd5e1;
}
.plugin-badge.badge-pending {
background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
color: #b45309;
border: 1px solid #fcd34d;
}
.plugin-badge.badge-error {
background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
color: #b91c1c;
border: 1px solid #fca5a5;
}
.plugin-badge.badge-info {
background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
color: #1d4ed8;
border: 1px solid #93c5fd;
}
.plugin-badge.badge-success {
background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
color: #047857;
border: 1px solid #6ee7b7;
}
.plugin-badge.badge-warning {
background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
color: #b45309;
border: 1px solid #fde68a;
}

View File

@ -46,11 +46,7 @@
<div class="disk-card-wrapper"> <div class="disk-card-wrapper">
<mat-card class="disk-mat-card mat-elevation-z4"> <mat-card class="disk-mat-card mat-elevation-z4">
<div class="disk-card-header"> <div class="disk-card-header">
<h3 class="disk-card-title">Disco {{ disk.diskNumber }} <h3 class="disk-card-title">Disco {{ disk.diskNumber }}</h3>
@if (disk.diskType) {
<span class="badge-disk-type">{{ disk.diskType }}</span>
}
</h3>
<div class="disk-card-metrics-wrapper"> <div class="disk-card-metrics-wrapper">
<mat-chip class="disk-card-metrics-chip"> <mat-chip class="disk-card-metrics-chip">
Total: {{ disk.total.toFixed(2) }} GB &nbsp;|&nbsp; Usado: {{ (disk.used).toFixed(2) }} GB ({{ Total: {{ disk.total.toFixed(2) }} GB &nbsp;|&nbsp; Usado: {{ (disk.used).toFixed(2) }} GB ({{
@ -91,13 +87,6 @@
@if (image.deployDate) { @if (image.deployDate) {
<span class="image-date">Desplegada: {{ image.deployDate | date:'dd/MM/yyyy HH:mm' }}</span> <span class="image-date">Desplegada: {{ image.deployDate | date:'dd/MM/yyyy HH:mm' }}</span>
} }
<div class="partition-badges-row">
@for (badge of getPartitionBadges(disk.diskNumber, image.partitionNumber); track badge.id + '-' + badge.type + '-' + badge.label + '-' + (badge.tooltip || '')) {
<span class="plugin-badge badge-{{badge.type}}" [matTooltip]="badge.tooltip">
<mat-icon class="plugin-badge-icon">{{ badge.icon }}</mat-icon> {{ badge.label }}
</span>
}
</div>
} }
</div> </div>
} }

View File

@ -10,7 +10,6 @@ import { Router } from "@angular/router";
import { ToastrService } from "ngx-toastr"; import { ToastrService } from "ngx-toastr";
import { ManageClientComponent } from "../../shared/clients/manage-client/manage-client.component"; import { ManageClientComponent } from "../../shared/clients/manage-client/manage-client.component";
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
import { PluginBadge, PluginService } from '@services/plugin.service';
interface ClientInfo { interface ClientInfo {
property: string; property: string;
@ -24,7 +23,6 @@ interface ClientInfo {
}) })
export class ClientDetailsComponent { export class ClientDetailsComponent {
public translate = inject(TranslateService); public translate = inject(TranslateService);
private pluginService = inject(PluginService);
baseUrl: string; baseUrl: string;
@ViewChild('assistantContainer') assistantContainer!: ElementRef; @ViewChild('assistantContainer') assistantContainer!: ElementRef;
clientUuid: string; clientUuid: string;
@ -135,7 +133,7 @@ export class ClientDetailsComponent {
} }
calculateDiskUsage() { calculateDiskUsage() {
const diskUsageMap = new Map<number, { total: number, used: number, partitions: any[], diskType?: string }>(); const diskUsageMap = new Map<number, { total: number, used: number, partitions: any[] }>();
this.partitions.forEach((partition: any) => { this.partitions.forEach((partition: any) => {
const diskNumber = partition.diskNumber; const diskNumber = partition.diskNumber;
@ -148,14 +146,13 @@ export class ClientDetailsComponent {
if (partition.partitionNumber === 0) { if (partition.partitionNumber === 0) {
diskData!.total = Number((partition.size / 1024).toFixed(2)); diskData!.total = Number((partition.size / 1024).toFixed(2));
diskData!.diskType = partition.diskType;
} else { } else {
diskData!.used += Number((partition.size / 1024).toFixed(2)); diskData!.used += Number((partition.size / 1024).toFixed(2));
diskData!.partitions.push(partition); diskData!.partitions.push(partition);
} }
}); });
this.chartDisk = Array.from(diskUsageMap.entries()).map(([diskNumber, { total, used, partitions, diskType }]) => { this.chartDisk = Array.from(diskUsageMap.entries()).map(([diskNumber, { total, used, partitions }]) => {
const partitionData = partitions.map(partition => ({ const partitionData = partitions.map(partition => ({
name: `${this.translate.instant('labelPartition')} ${partition.partitionNumber}`, name: `${this.translate.instant('labelPartition')} ${partition.partitionNumber}`,
value: Number((partition.size / 1024).toFixed(2)) value: Number((partition.size / 1024).toFixed(2))
@ -175,8 +172,7 @@ export class ClientDetailsComponent {
total, total,
used, used,
percentage: total > 0 ? Math.round((used / total) * 100) : 0, percentage: total > 0 ? Math.round((used / total) * 100) : 0,
partitions, partitions
diskType
}; };
}); });
@ -211,10 +207,6 @@ export class ClientDetailsComponent {
}); });
} }
getPartitionBadges(diskNumber: number, partitionNumber: number): PluginBadge[] {
return this.pluginService.getPartitionBadges(this.clientData, diskNumber, partitionNumber);
}
onNoClick(): void { onNoClick(): void {
this.dialog.closeAll(); this.dialog.closeAll();
} }

View File

@ -3,59 +3,57 @@
<div class="inputs-container"> <div class="inputs-container">
<div class="mat-dialog-content" [ngClass]="{'loading': loading}"> <div class="mat-dialog-content" [ngClass]="{'loading': loading}">
@if (!loading) { <form class="client-form grid-form" *ngIf="!loading">
<form class="client-form grid-form"> <mat-form-field class="form-field">
<app-ou-select <mat-label>{{ 'labelOrganizationalUnit' | translate }}</mat-label>
class="form-field" <mat-select (selectionChange)="setOrganizationalUnit($event)" [value]="organizationalUnit">
[ngModel]="organizationalUnit" <mat-select-trigger>
[units]="parentUnitsWithPaths" {{ getSelectedParentName() }}
[label]="'labelOrganizationalUnit'" </mat-select-trigger>
(selectionChange)="setOrganizationalUnit($event)"> <mat-option *ngFor="let unit of parentUnitsWithPaths" [value]="unit.id">
</app-ou-select> <div class="unit-name">{{ unit.name }}</div>
<div style="font-size: smaller; color: gray;">{{ unit.path }}</div>
</mat-option>
</mat-select>
</mat-form-field>
</form> </form>
}
<div> <div>
<div class="upload-container"> <div class="upload-container">
<button class="action-button" (click)="fileInput.click()">{{ 'buttonUploadFile' | translate }}</button> <button class="action-button" (click)="fileInput.click()">{{ 'buttonUploadFile' | translate }}</button>
<input #fileInput type="file" (change)="onFileUpload($event)" accept="*" hidden> <input #fileInput type="file" (change)="onFileUpload($event)" accept="*" hidden>
<p>{{ 'orAddThemManually' | translate }}</p> <p>{{ 'orAddThemManually' | translate }}</p>
@if (showTextarea) { <div *ngIf="showTextarea">
<div>
<textarea #textarea matInput <textarea #textarea matInput
[placeholder]="'dhcpHostExample' | translate" [placeholder]="'dhcpHostExample' | translate"
rows="20" cols="100"></textarea> rows="20" cols="100"></textarea>
<button class="action-button" style="margin-top: 0.5em;" <button class="action-button" style="margin-top: 0.5em;"
(click)="onTextarea(textarea.value)">{{ 'buttonPreview' | translate }}</button> (click)="onTextarea(textarea.value)">{{ 'buttonPreview' | translate }}</button>
</div> </div>
}
</div> </div>
@if (uploadedClients.length > 0) { <h4 *ngIf="uploadedClients.length > 0">{{ 'importedClientsZero' | translate }}</h4>
<h4>{{ 'importedClientsZero' | translate }}</h4> <div *ngIf="uploadedClients.length > 0" class="scrollable-table">
} <table mat-table [dataSource]="uploadedClients" class="mat-elevation-z8" *ngIf="uploadedClients.length > 0">
@if (uploadedClients.length > 0) {
<div class="scrollable-table">
@if (uploadedClients.length > 0) {
<table mat-table [dataSource]="uploadedClients" class="mat-elevation-z8">
<ng-container matColumnDef="name"> <ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> {{ 'labelRoleName' | translate }}</th> <th mat-header-cell *matHeaderCellDef> {{ 'labelRoleName' | translate }}</th>
<td mat-cell *matCellDef="let client"> {{ client.name }} </td> <td mat-cell *matCellDef="let client"> {{ client.name }} </td>
</ng-container> </ng-container>
<ng-container matColumnDef="ip"> <ng-container matColumnDef="ip">
<th mat-header-cell *matHeaderCellDef> {{ 'labelIpCaps' | translate }}</th> <th mat-header-cell *matHeaderCellDef> {{ 'labelIpCaps' | translate }}</th>
<td mat-cell *matCellDef="let client"> {{ client.ip }} </td> <td mat-cell *matCellDef="let client"> {{ client.ip }} </td>
</ng-container> </ng-container>
<ng-container matColumnDef="mac"> <ng-container matColumnDef="mac">
<th mat-header-cell *matHeaderCellDef> {{ 'labelMac' | translate }}</th> <th mat-header-cell *matHeaderCellDef> {{ 'labelMac' | translate }}</th>
<td mat-cell *matCellDef="let client"> {{ client.mac }} </td> <td mat-cell *matCellDef="let client"> {{ client.mac }} </td>
</ng-container> </ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table> </table>
}
</div> </div>
}
</div> </div>
</div> </div>
</div> </div>

View File

@ -65,7 +65,10 @@ export class CreateMultipleClientComponent implements OnInit {
); );
} }
getSelectedParentName(): string | undefined {
const parentId = this.organizationalUnit;
return this.parentUnitsWithPaths.find(unit => unit.id === parentId)?.name;
}
setOrganizationalUnit(organizationalUnit: any): void { setOrganizationalUnit(organizationalUnit: any): void {
this.organizationalUnit = organizationalUnit.value; this.organizationalUnit = organizationalUnit.value;
@ -130,15 +133,9 @@ export class CreateMultipleClientComponent implements OnInit {
let successCount = 0; let successCount = 0;
let errorMessages: string[] = []; let errorMessages: string[] = [];
let ou = this.organizationalUnit;
if (typeof ou === 'number' || (typeof ou === 'string' && !ou.includes('/'))) {
const selectedUnit = this.parentUnits.find((u: any) => u.id === Number(ou));
ou = selectedUnit ? (selectedUnit['@id'] || `/organizational-units/${selectedUnit.uuid}`) : ou;
}
this.uploadedClients.forEach(client => { this.uploadedClients.forEach(client => {
const formData = { const formData = {
organizationalUnit: ou, organizationalUnit: this.organizationalUnit,
name: client.name || null, name: client.name || null,
mac: client.mac || null, mac: client.mac || null,
ip: client.ip || null, ip: client.ip || null,

View File

@ -84,21 +84,3 @@ mat-option .unit-path {
grid-template-columns: repeat(3, 1fr); grid-template-columns: repeat(3, 1fr);
column-gap: 20px; column-gap: 20px;
} }
.hardware-profile-box {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 0 12px 0;
}
.hardware-profile-box .form-field {
flex: 1;
min-width: 0;
width: auto;
}
.hardware-profile-link {
margin-left: auto;
color: #3f51b5;
}

View File

@ -1,26 +1,34 @@
<mat-dialog-content class="create-client-container"> <mat-dialog-content class="create-client-container">
<h1 mat-dialog-title>{{ dialogTitle | translate }}</h1> <h1 mat-dialog-title>{{ dialogTitle | translate }}</h1>
<div [ngClass]="{'loading': loading}"> <div [ngClass]="{'loading': loading}">
@if (loading) { <mat-spinner class="loading-spinner" *ngIf="loading"></mat-spinner>
<mat-spinner class="loading-spinner"></mat-spinner> <form *ngIf="clientForm && !loading" [formGroup]="clientForm" class="client-form grid-form">
<mat-form-field class="form-field">
<mat-label>{{ 'labelOrganizationalUnit' | translate }}</mat-label>
<mat-select formControlName="organizationalUnit" (selectionChange)="onParentChange($event)">
<mat-select-trigger>
{{ getSelectedParentName() }}
</mat-select-trigger>
@for (unit of parentUnitsWithPaths; track unit.id) {
<mat-option [value]="unit.id">
<div class="unit-name">{{ unit.name }}</div>
<div style="font-size: smaller; color: gray;">{{ unit.path }}</div>
</mat-option>
} }
@if (clientForm && !loading) { </mat-select>
<form [formGroup]="clientForm" class="client-form grid-form"> </mat-form-field>
<app-ou-select
class="form-field"
formControlName="organizationalUnit"
[units]="parentUnitsWithPaths"
[label]="'labelOrganizationalUnit'"
(selectionChange)="onParentChange($event)">
</app-ou-select>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelName' | translate }}</mat-label> <mat-label>{{ 'labelName' | translate }}</mat-label>
<input matInput formControlName="name" required> <input matInput formControlName="name" required>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelSerialNumber' | translate }}</mat-label> <mat-label>{{ 'labelSerialNumber' | translate }}</mat-label>
<input matInput formControlName="serialNumber"> <input matInput formControlName="serialNumber">
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelNetiface' | translate }}</mat-label> <mat-label>{{ 'labelNetiface' | translate }}</mat-label>
<mat-select formControlName="netiface"> <mat-select formControlName="netiface">
@ -29,16 +37,19 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelMac' | translate }}</mat-label> <mat-label>{{ 'labelMac' | translate }}</mat-label>
<input matInput formControlName="mac" required> <input matInput formControlName="mac" required>
<mat-error>{{ 'macError' | translate }}</mat-error> <mat-error>{{ 'macError' | translate }}</mat-error>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelIp' | translate }}</mat-label> <mat-label>{{ 'labelIp' | translate }}</mat-label>
<input matInput formControlName="ip" required> <input matInput formControlName="ip" required>
<mat-error>{{ 'ipError' | translate }}</mat-error> <mat-error>{{ 'ipError' | translate }}</mat-error>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelRepository' | translate }}</mat-label> <mat-label>{{ 'labelRepository' | translate }}</mat-label>
<mat-select formControlName="repository"> <mat-select formControlName="repository">
@ -47,9 +58,11 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-checkbox formControlName="maintenance"> <mat-checkbox formControlName="maintenance">
{{ 'maintenance' | translate }} {{ 'maintenance' | translate }}
</mat-checkbox> </mat-checkbox>
<!-- ===== Agrupación: Configuración del menú ===== --> <!-- ===== Agrupación: Configuración del menú ===== -->
<fieldset class="fieldset-group"> <fieldset class="fieldset-group">
<legend class="fieldset-legend">{{ 'menuConfiguration' | translate }}</legend> <legend class="fieldset-legend">{{ 'menuConfiguration' | translate }}</legend>
@ -63,6 +76,7 @@
</mat-select> </mat-select>
<mat-error>{{ 'menuError' | translate }}</mat-error> <mat-error>{{ 'menuError' | translate }}</mat-error>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelResolution' | translate }}</mat-label> <mat-label>{{ 'labelResolution' | translate }}</mat-label>
<mat-select formControlName="resolution" required> <mat-select formControlName="resolution" required>
@ -83,10 +97,12 @@
</mat-form-field> </mat-form-field>
</div> </div>
</fieldset> </fieldset>
<!-- ===== Agrupación: Configuración de arranque ===== --> <!-- ===== Agrupación: Configuración de arranque ===== -->
<fieldset class="fieldset-group"> <fieldset class="fieldset-group">
<legend class="fieldset-legend">{{ 'bootConfiguration' | translate }}</legend> <legend class="fieldset-legend">{{ 'bootConfiguration' | translate }}</legend>
<div class="fieldset-grid-3"> <div class="fieldset-grid-3">
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'bootServer' | translate }}</mat-label> <mat-label>{{ 'bootServer' | translate }}</mat-label>
<mat-select formControlName="bootServer" (selectionChange)="onBootServerChange($event)"> <mat-select formControlName="bootServer" (selectionChange)="onBootServerChange($event)">
@ -95,6 +111,7 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelOgLive' | translate }}</mat-label> <mat-label>{{ 'labelOgLive' | translate }}</mat-label>
<mat-select formControlName="ogLive"> <mat-select formControlName="ogLive">
@ -106,6 +123,7 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelTemplate' | translate }}</mat-label> <mat-label>{{ 'labelTemplate' | translate }}</mat-label>
<mat-select formControlName="pxeTemplate"> <mat-select formControlName="pxeTemplate">
@ -117,34 +135,16 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</div> </div>
</fieldset> </fieldset>
@if (isEditMode) {
<fieldset class="fieldset-group">
<legend class="fieldset-legend">{{ 'labelHardwareProfile' | translate }}</legend>
<div class="hardware-profile-box">
<mat-form-field class="form-field">
<mat-select formControlName="hardwareProfile">
<mat-option [value]="null">{{ 'noHardwareProfileAssigned' | translate }}</mat-option>
@for (profile of hardwareProfiles; track profile['@id']) {
<mat-option [value]="profile['@id']">{{ profile.description }}</mat-option>
}
</mat-select>
</mat-form-field>
<button type="button" mat-icon-button class="hardware-profile-link" (click)="goToHardwareProfiles()"
[matTooltip]="'manageHardwareProfiles' | translate">
<mat-icon>settings</mat-icon>
</button>
</div>
</fieldset>
}
<mat-form-field class="form-field full-width"> <mat-form-field class="form-field full-width">
<mat-label>{{ 'labelNotes' | translate }}</mat-label> <mat-label>{{ 'labelNotes' | translate }}</mat-label>
<textarea matInput formControlName="notes" rows="4" <textarea matInput formControlName="notes" rows="4"
[placeholder]="'notesPlaceholder' | translate"></textarea> [placeholder]="'notesPlaceholder' | translate"></textarea>
</mat-form-field> </mat-form-field>
</form> </form>
}
</div> </div>
</mat-dialog-content> </mat-dialog-content>
<mat-dialog-actions class="action-container"> <mat-dialog-actions class="action-container">

View File

@ -5,7 +5,6 @@ import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr'; import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';
import { DataService } from '../../../services/data.service'; import { DataService } from '../../../services/data.service';
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
@ -25,7 +24,6 @@ export class ManageClientComponent implements OnInit {
templates: any[] = []; templates: any[] = [];
repositories: any[] = []; repositories: any[] = [];
bootServers: any[] = []; bootServers: any[] = [];
hardwareProfiles: any[] = [];
loading: boolean = false; loading: boolean = false;
displayedColumns: string[] = ['name', 'ip']; displayedColumns: string[] = ['name', 'ip'];
dialogTitle: string; dialogTitle: string;
@ -43,7 +41,6 @@ export class ManageClientComponent implements OnInit {
private configService: ConfigService, private configService: ConfigService,
private toastService: ToastrService, private toastService: ToastrService,
private dataService: DataService, private dataService: DataService,
private router: Router,
@Inject(MAT_DIALOG_DATA) public data: any @Inject(MAT_DIALOG_DATA) public data: any
) { ) {
this.baseUrl = this.configService.apiUrl; this.baseUrl = this.configService.apiUrl;
@ -58,8 +55,7 @@ export class ManageClientComponent implements OnInit {
this.loadParentUnits(), this.loadParentUnits(),
this.loadBootServers(), this.loadBootServers(),
this.loadRepositories(), this.loadRepositories(),
this.loadMenus(), this.loadMenus()
this.loadHardwareProfiles()
]; ];
Promise.all(observables).then(() => { Promise.all(observables).then(() => {
@ -95,7 +91,6 @@ export class ManageClientComponent implements OnInit {
ogLive: [null], ogLive: [null],
repository: [null], repository: [null],
menu: [null], menu: [null],
hardwareProfile: [null],
maintenance: [false], maintenance: [false],
resolution: [null], resolution: [null],
notes: [''] notes: ['']
@ -137,6 +132,10 @@ export class ManageClientComponent implements OnInit {
}); });
} }
getSelectedParentName(): string | undefined {
const parentId = this.clientForm.get('organizationalUnit')?.value;
return this.parentUnitsWithPaths.find(unit => unit.id === parentId)?.name;
}
loadOgLivesByServer(bootServerIri: string): Promise<void> { loadOgLivesByServer(bootServerIri: string): Promise<void> {
// Extract UUID from IRI (e.g. "/boot-servers/xxxx-xxx" -> "xxxx-xxx") // Extract UUID from IRI (e.g. "/boot-servers/xxxx-xxx" -> "xxxx-xxx")
@ -223,24 +222,6 @@ export class ManageClientComponent implements OnInit {
}); });
} }
loadHardwareProfiles(): Promise<void> {
return new Promise((resolve, reject) => {
const url = `${this.baseUrl}/hardware-profiles?page=1&itemsPerPage=10000`;
this.http.get<any>(url).subscribe(
response => {
this.hardwareProfiles = response['hydra:member'];
resolve();
},
error => {
console.error(this.translate.instant('errorFetchingHardwareProfiles'), error);
this.hardwareProfiles = [];
resolve();
}
);
});
}
loadRepositories(): Promise<void> { loadRepositories(): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const url = `${this.baseUrl}/image-repositories?page=1&itemsPerPage=10000`; const url = `${this.baseUrl}/image-repositories?page=1&itemsPerPage=10000`;
@ -313,7 +294,6 @@ export class ManageClientComponent implements OnInit {
bootServer: bootServerIri, bootServer: bootServerIri,
repository: data.repository ? data.repository['@id'] : null, repository: data.repository ? data.repository['@id'] : null,
menu: data.menu ? data.menu['@id'] : null, menu: data.menu ? data.menu['@id'] : null,
hardwareProfile: data.hardwareProfile ? data.hardwareProfile['@id'] : null,
maintenance: data.maintenance, maintenance: data.maintenance,
resolution: data.resolution, resolution: data.resolution,
notes: data.notes || '' notes: data.notes || ''
@ -345,14 +325,7 @@ export class ManageClientComponent implements OnInit {
onSubmit(): void { onSubmit(): void {
if (this.clientForm.valid) { if (this.clientForm.valid) {
const formData = { ...this.clientForm.value }; const formData = this.clientForm.value;
let ou = formData.organizationalUnit;
if (typeof ou === 'number' || (typeof ou === 'string' && !ou.includes('/'))) {
const selectedUnit = this.parentUnits.find((u: any) => u.id === Number(ou));
ou = selectedUnit ? (selectedUnit['@id'] || `/organizational-units/${selectedUnit.uuid}`) : ou;
}
formData.organizationalUnit = ou;
if (this.isEditMode) { if (this.isEditMode) {
const putUrl = `${this.baseUrl}/clients/${this.data.uuid}`; const putUrl = `${this.baseUrl}/clients/${this.data.uuid}`;
@ -391,9 +364,4 @@ export class ManageClientComponent implements OnInit {
onNoClick(): void { onNoClick(): void {
this.dialogRef.close({ success: false }); this.dialogRef.close({ success: false });
} }
goToHardwareProfiles(): void {
this.dialogRef.close({ success: false });
this.router.navigate(['/hardware-profiles']);
}
} }

View File

@ -32,19 +32,6 @@
font-weight: bold; font-weight: bold;
} }
.badge-disk-type {
display: inline-flex;
align-items: center;
padding: 2px 8px;
font-size: 0.75rem;
font-weight: 600;
color: #1976d2;
background-color: #e3f2fd;
border-radius: 12px;
margin-left: 8px;
vertical-align: middle;
}
.disk-card-layout { .disk-card-layout {
display: flex; display: flex;
align-items: stretch; align-items: stretch;

View File

@ -3,11 +3,7 @@
<div class="disk-card-wrapper"> <div class="disk-card-wrapper">
<mat-card class="disk-mat-card mat-elevation-z4"> <mat-card class="disk-mat-card mat-elevation-z4">
<div class="disk-card-header"> <div class="disk-card-header">
<h3 class="disk-card-title">Disco {{ disk.diskNumber }} <h3 class="disk-card-title">Disco {{ disk.diskNumber }}</h3>
@if (disk.diskType) {
<span class="badge-disk-type">{{ disk.diskType }}</span>
}
</h3>
</div> </div>
<div class="disk-card-layout"> <div class="disk-card-layout">

View File

@ -43,12 +43,9 @@ export class DiskPartitionSelectorComponent implements OnChanges {
for (const diskNum in grouped) { for (const diskNum in grouped) {
if (grouped.hasOwnProperty(diskNum)) { if (grouped.hasOwnProperty(diskNum)) {
const diskPartitions = grouped[diskNum];
const partitionZero = diskPartitions.find((p: any) => p.partitionNumber === 0);
this.diskUsageData.push({ this.diskUsageData.push({
diskNumber: diskNum, diskNumber: diskNum,
partitions: diskPartitions.filter((p: any) => p.partitionNumber !== 0), partitions: grouped[diskNum]
diskType: partitionZero ? partitionZero.diskType : undefined
}); });
} }
} }

View File

@ -3,44 +3,43 @@
'labelOrganizationalUnit' | translate }}</h1> 'labelOrganizationalUnit' | translate }}</h1>
<div [ngClass]="{'loading': loading}"> <div [ngClass]="{'loading': loading}">
<!-- Paso 1: General --> <!-- Paso 1: General -->
@if (loading) { <mat-spinner class="loading-spinner" *ngIf="loading"></mat-spinner>
<mat-spinner class="loading-spinner"></mat-spinner> <span *ngIf="!loading" class="step-title">{{ 'labelGeneralTab' | translate }}</span>
} <form *ngIf="generalFormGroup && !loading" [formGroup]="generalFormGroup" class="grid-form">
@if (!loading) {
<span class="step-title">{{ 'labelGeneralTab' | translate }}</span>
}
@if (generalFormGroup && !loading) {
<form [formGroup]="generalFormGroup" class="grid-form">
<mat-form-field class="form-field" appearance="fill"> <mat-form-field class="form-field" appearance="fill">
<mat-label>{{ 'labelType' | translate }}</mat-label> <mat-label>{{ 'labelType' | translate }}</mat-label>
<mat-select formControlName="type" required> <mat-select formControlName="type" required>
@for (type of filteredTypes; track type) { <mat-option *ngFor="let type of filteredTypes" [value]="type">
<mat-option [value]="type">
{{ typeTranslations[type] }} {{ typeTranslations[type] }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field" appearance="fill"> <mat-form-field class="form-field" appearance="fill">
<mat-label>{{ 'labelRoleName' | translate }}</mat-label> <mat-label>{{ 'labelRoleName' | translate }}</mat-label>
<input matInput formControlName="name" required> <input matInput formControlName="name" required>
</mat-form-field> </mat-form-field>
<app-ou-select <mat-form-field class="form-field" appearance="fill">
class="form-field" <mat-label>{{ 'labelCreateOrgUnitparent' | translate }}</mat-label>
formControlName="parent" <mat-select formControlName="parent" (selectionChange)="onParentChange($event)">
[units]="parentUnitsWithPaths" <mat-select-trigger>
[label]="'labelCreateOrgUnitparent'" {{ getSelectedParentName() }}
(selectionChange)="onParentChange($event)"> </mat-select-trigger>
</app-ou-select> <mat-option *ngFor="let unit of parentUnitsWithPaths" [value]="unit.id">
<div>{{ unit.name }}</div>
<div style="font-size: smaller; color: gray;">{{ unit.path }}</div>
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="form-field description-form-field" appearance="fill"> <mat-form-field class="form-field description-form-field" appearance="fill">
<mat-label>{{ 'labelDescription' | translate }}</mat-label> <mat-label>{{ 'labelDescription' | translate }}</mat-label>
<textarea matInput formControlName="description"></textarea> <textarea matInput formControlName="description"></textarea>
</mat-form-field> </mat-form-field>
<mat-checkbox formControlName="excludeParentChanges"> <mat-checkbox formControlName="excludeParentChanges">
{{ 'excludeParentChanges' | translate }} {{ 'excludeParentChanges' | translate }}
</mat-checkbox> </mat-checkbox>
</form> </form>
}
<!-- Paso 2: Información del Aula --> <!-- Paso 2: Información del Aula -->
@if (generalFormGroup.value.type === 'classroom' && !loading) { @if (generalFormGroup.value.type === 'classroom' && !loading) {
@ -53,43 +52,35 @@
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelCapacity' | translate }}</mat-label> <mat-label>{{ 'labelCapacity' | translate }}</mat-label>
<input matInput formControlName="capacity" type="number" min="0"> <input matInput formControlName="capacity" type="number" min="0">
@if (classroomInfoFormGroup.get('capacity')?.hasError('min')) { <mat-error *ngIf="classroomInfoFormGroup.get('capacity')?.hasError('min')">
<mat-error>
{{ 'capacityWarning' | translate }} {{ 'capacityWarning' | translate }}
</mat-error> </mat-error>
}
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field" appearance="fill" style="grid-column: span 1;"> <mat-form-field class="form-field" appearance="fill" style="grid-column: span 1;">
<mat-label>{{ 'labelAssociatedCalendar' | translate }}</mat-label> <mat-label>{{ 'labelAssociatedCalendar' | translate }}</mat-label>
<mat-select formControlName="remoteCalendar" (selectionChange)="onCalendarChange($event)"> <mat-select formControlName="remoteCalendar" (selectionChange)="onCalendarChange($event)">
@for (calendar of calendars; track calendar) { <mat-option *ngFor="let calendar of calendars" [value]="calendar['@id']">
<mat-option [value]="calendar['@id']">
{{ calendar.name }} {{ calendar.name }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<div class="projector-board-field"> <div class="projector-board-field">
<mat-slide-toggle formControlName="projector">{{ 'projectorAlt' | translate }}</mat-slide-toggle> <mat-slide-toggle formControlName="projector">{{ 'projectorAlt' | translate }}</mat-slide-toggle>
<mat-slide-toggle formControlName="board">{{ 'boardToggle' | translate }}</mat-slide-toggle> <mat-slide-toggle formControlName="board">{{ 'boardToggle' | translate }}</mat-slide-toggle>
<mat-slide-toggle formControlName="remotePc">{{ 'remotePcLabel' | translate }}</mat-slide-toggle> <mat-slide-toggle formControlName="remotePc">{{ 'remotePcLabel' | translate }}</mat-slide-toggle>
@if (classroomInfoFormGroup.get('remotePc')?.value) {
<mat-slide-toggle formControlName="remotePcRebootOnUnreserve">{{ 'remotePcRebootOnUnreserveLabel' | translate }}</mat-slide-toggle>
}
</div> </div>
</form> </form>
} }
<!-- Paso 3: Configuración de Red --> <!-- Paso 3: Configuración de Red -->
@if (!loading) { <span *ngIf="!loading" class="step-title">{{ 'labelNetworkSettingsStep' | translate }}</span>
<span class="step-title">{{ 'labelNetworkSettingsStep' | translate }}</span> <form *ngIf="networkSettingsFormGroup && !loading" [formGroup]="networkSettingsFormGroup" class="grid-form">
}
@if (networkSettingsFormGroup && !loading) {
<form [formGroup]="networkSettingsFormGroup" class="grid-form">
<!-- ===== Agrupación: Configuración de arranque ===== --> <!-- ===== Agrupación: Configuración de arranque ===== -->
<fieldset class="fieldset-group"> <fieldset class="fieldset-group">
<legend class="fieldset-legend">{{ 'bootConfiguration' | translate }}</legend> <legend class="fieldset-legend">{{ 'bootConfiguration' | translate }}</legend>
<div class="fieldset-grid-3"> <div class="fieldset-grid-3">
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'bootServer' | translate }}</mat-label> <mat-label>{{ 'bootServer' | translate }}</mat-label>
<mat-select formControlName="bootServer" (selectionChange)="onBootServerChange($event)"> <mat-select formControlName="bootServer" (selectionChange)="onBootServerChange($event)">
@ -98,6 +89,7 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'ogLive' | translate }}</mat-label> <mat-label>{{ 'ogLive' | translate }}</mat-label>
<mat-select formControlName="ogLive" (selectionChange)="onOgLiveChange($event)"> <mat-select formControlName="ogLive" (selectionChange)="onOgLiveChange($event)">
@ -109,6 +101,7 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelTemplate' | translate }}</mat-label> <mat-label>{{ 'labelTemplate' | translate }}</mat-label>
<mat-select formControlName="pxeTemplate" (selectionChange)="onPxeTemplateChange($event)"> <mat-select formControlName="pxeTemplate" (selectionChange)="onPxeTemplateChange($event)">
@ -120,16 +113,16 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</div> </div>
</fieldset> </fieldset>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelRepository' | translate }}</mat-label> <mat-label>{{ 'labelRepository' | translate }}</mat-label>
<mat-select formControlName="repository" (selectionChange)="onRepositoryChange($event)"> <mat-select formControlName="repository" (selectionChange)="onRepositoryChange($event)">
@for (repository of repositories; track repository) { <mat-option *ngFor="let repository of repositories" [value]="repository['@id']">
<mat-option [value]="repository['@id']">
{{ repository.name }} {{ repository.name }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
@ -147,11 +140,9 @@
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label i18n="@@netiface-label">{{ 'labelNetiface' | translate }}</mat-label> <mat-label i18n="@@netiface-label">{{ 'labelNetiface' | translate }}</mat-label>
<mat-select formControlName="netiface"> <mat-select formControlName="netiface">
@for (type of netifaceTypes; track type) { <mat-option *ngFor="let type of netifaceTypes" [value]="type.value">
<mat-option [value]="type.value">
{{ type.name }} {{ type.name }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
@ -165,10 +156,8 @@
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelHardwareProfile' | translate }}</mat-label> <mat-label>{{ 'labelHardwareProfile' | translate }}</mat-label>
<mat-select formControlName="hardwareProfile"> <mat-select formControlName="hardwareProfile">
@for (unit of hardwareProfiles; track unit) { <mat-option *ngFor="let unit of hardwareProfiles" [value]="unit['@id']">{{ unit.description
<mat-option [value]="unit['@id']">{{ unit.description
}}</mat-option> }}</mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<!-- ===== Agrupación: Configuración de multicast ===== --> <!-- ===== Agrupación: Configuración de multicast ===== -->
@ -190,15 +179,14 @@
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelMcastMode' | translate }}</mat-label> <mat-label>{{ 'labelMcastMode' | translate }}</mat-label>
<mat-select formControlName="mcastMode"> <mat-select formControlName="mcastMode">
@for (option of multicastModeOptions; track option) { <mat-option *ngFor="let option of multicastModeOptions" [value]="option.value">
<mat-option [value]="option.value">
{{ option.name }} {{ option.name }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</div> </div>
</fieldset> </fieldset>
<!-- ===== Agrupación: Configuración de p2p ===== --> <!-- ===== Agrupación: Configuración de p2p ===== -->
<fieldset class="fieldset-group"> <fieldset class="fieldset-group">
<legend class="fieldset-legend">{{ 'p2pConfiguration' | translate }}</legend> <legend class="fieldset-legend">{{ 'p2pConfiguration' | translate }}</legend>
@ -206,21 +194,18 @@
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelP2pMode' | translate }}</mat-label> <mat-label>{{ 'labelP2pMode' | translate }}</mat-label>
<mat-select formControlName="p2pMode"> <mat-select formControlName="p2pMode">
@for (option of p2pModeOptions; track option) { <mat-option *ngFor="let option of p2pModeOptions" [value]="option.value">
<mat-option [value]="option.value">
{{ option.name }} {{ option.name }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
@if (networkSettingsFormGroup.get('p2pMode')?.value === 'seeder') { <mat-form-field class="form-field" *ngIf="networkSettingsFormGroup.get('p2pMode')?.value === 'seeder'">
<mat-form-field class="form-field">
<mat-label>{{ 'labelP2pTime' | translate }} (minutos)</mat-label> <mat-label>{{ 'labelP2pTime' | translate }} (minutos)</mat-label>
<input matInput formControlName="p2pTime" type="number"> <input matInput formControlName="p2pTime" type="number">
</mat-form-field> </mat-form-field>
}
</div> </div>
</fieldset> </fieldset>
<!-- ===== Agrupación: Configuración del menú ===== --> <!-- ===== Agrupación: Configuración del menú ===== -->
<fieldset class="fieldset-group"> <fieldset class="fieldset-group">
<legend class="fieldset-legend">{{ 'menuConfiguration' | translate }}</legend> <legend class="fieldset-legend">{{ 'menuConfiguration' | translate }}</legend>
@ -228,13 +213,12 @@
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelMenu' | translate }}</mat-label> <mat-label>{{ 'labelMenu' | translate }}</mat-label>
<mat-select formControlName="menu" (selectionChange)="onMenuChange($event)"> <mat-select formControlName="menu" (selectionChange)="onMenuChange($event)">
@for (menu of menus; track menu) { <mat-option *ngFor="let menu of menus" [value]="menu['@id']">
<mat-option [value]="menu['@id']">
{{ menu.name }} {{ menu.name }}
</mat-option> </mat-option>
}
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field class="form-field"> <mat-form-field class="form-field">
<mat-label>{{ 'labelResolution' | translate }}</mat-label> <mat-label>{{ 'labelResolution' | translate }}</mat-label>
<mat-select formControlName="resolution"> <mat-select formControlName="resolution">
@ -255,20 +239,15 @@
</div> </div>
</fieldset> </fieldset>
</form> </form>
}
<!-- Paso 4: Información Adicional --> <!-- Paso 4: Información Adicional -->
@if (!loading) { <span *ngIf="!loading" class="step-title">{{ 'labelAdditionalInfoStep' | translate }}</span>
<span class="step-title">{{ 'labelAdditionalInfoStep' | translate }}</span> <form *ngIf="additionalInfoFormGroup && !loading" [formGroup]="additionalInfoFormGroup">
}
@if (additionalInfoFormGroup && !loading) {
<form [formGroup]="additionalInfoFormGroup">
<mat-form-field class="form-field description-form-field"> <mat-form-field class="form-field description-form-field">
<mat-label>{{ 'labelComments' | translate }}</mat-label> <mat-label>{{ 'labelComments' | translate }}</mat-label>
<textarea matInput formControlName="comments"></textarea> <textarea matInput formControlName="comments"></textarea>
</mat-form-field> </mat-form-field>
</form> </form>
}
</div> </div>
</mat-dialog-content> </mat-dialog-content>
<mat-dialog-actions class="action-container"> <mat-dialog-actions class="action-container">

View File

@ -8,7 +8,6 @@ import { DataService } from "../../../services/data.service";
import { ToastrService } from "ngx-toastr"; import { ToastrService } from "ngx-toastr";
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
import { DeleteModalComponent } from '../../../../../shared/delete_modal/delete-modal/delete-modal.component'; import { DeleteModalComponent } from '../../../../../shared/delete_modal/delete-modal/delete-modal.component';
import { AuthService } from '@services/auth.service';
@Component({ @Component({
selector: 'app-manage-organizational-unit', selector: 'app-manage-organizational-unit',
@ -17,7 +16,6 @@ import { AuthService } from '@services/auth.service';
}) })
export class ManageOrganizationalUnitComponent implements OnInit { export class ManageOrganizationalUnitComponent implements OnInit {
public translate = inject(TranslateService); public translate = inject(TranslateService);
public auth = inject(AuthService);
baseUrl: string; baseUrl: string;
isLinear = true; isLinear = true;
generalFormGroup: FormGroup; generalFormGroup: FormGroup;
@ -110,7 +108,6 @@ export class ManageOrganizationalUnitComponent implements OnInit {
projector: [false], projector: [false],
board: [false], board: [false],
remotePc: [false], remotePc: [false],
remotePcRebootOnUnreserve: [false],
capacity: [null, [Validators.required, Validators.min(0)]], capacity: [null, [Validators.required, Validators.min(0)]],
remoteCalendar: [null] remoteCalendar: [null]
}); });
@ -144,15 +141,7 @@ export class ManageOrganizationalUnitComponent implements OnInit {
} }
get filteredTypes(): string[] { get filteredTypes(): string[] {
const isOperator = this.auth.userCategory === 'ou-operator'; return this.generalFormGroup.get('parent')?.value ? this.types.filter(type => type !== 'organizational-unit') : this.types;
const hasParent = !!this.generalFormGroup.get('parent')?.value;
// Si es operador de aula O ya tiene una unidad padre asignada, excluimos 'organizational-unit' (Centro)
if (isOperator || hasParent) {
return this.types.filter(type => type !== 'organizational-unit');
}
return this.types;
} }
loadParentUnits(): Promise<void> { loadParentUnits(): Promise<void> {
@ -286,7 +275,6 @@ export class ManageOrganizationalUnitComponent implements OnInit {
projector: data.projector, projector: data.projector,
board: data.board, board: data.board,
remotePc: data.remotePc ?? false, remotePc: data.remotePc ?? false,
remotePcRebootOnUnreserve: data.remotePcRebootOnUnreserve ?? false,
capacity: data.capacity, capacity: data.capacity,
remoteCalendar: data.remoteCalendar ? data.remoteCalendar['@id'] : null remoteCalendar: data.remoteCalendar ? data.remoteCalendar['@id'] : null
}); });
@ -341,11 +329,7 @@ export class ManageOrganizationalUnitComponent implements OnInit {
} }
private submitForm(propagate: boolean) { private submitForm(propagate: boolean) {
let parentValue = this.generalFormGroup.value.parent; const parentValue = this.generalFormGroup.value.parent;
if (typeof parentValue === 'number' || (typeof parentValue === 'string' && !parentValue.includes('/'))) {
const selectedUnit = this.parentUnits.find(u => u.id === Number(parentValue));
parentValue = selectedUnit ? (selectedUnit['@id'] || `/organizational-units/${selectedUnit.uuid}`) : parentValue;
}
const networkSettings = { ...this.networkSettingsFormGroup.value }; const networkSettings = { ...this.networkSettingsFormGroup.value };
@ -366,7 +350,6 @@ export class ManageOrganizationalUnitComponent implements OnInit {
projector: this.classroomInfoFormGroup.value.projector, projector: this.classroomInfoFormGroup.value.projector,
board: this.classroomInfoFormGroup.value.board, board: this.classroomInfoFormGroup.value.board,
remotePc: this.classroomInfoFormGroup.value.remotePc, remotePc: this.classroomInfoFormGroup.value.remotePc,
remotePcRebootOnUnreserve: this.classroomInfoFormGroup.value.remotePcRebootOnUnreserve,
capacity: this.classroomInfoFormGroup.value.capacity, capacity: this.classroomInfoFormGroup.value.capacity,
}; };
@ -434,7 +417,10 @@ export class ManageOrganizationalUnitComponent implements OnInit {
); );
} }
getSelectedParentName(): string | undefined {
const parentId = this.generalFormGroup.get('parent')?.value;
return this.parentUnitsWithPaths.find(unit => unit.id === parentId)?.name;
}
loadBootServers(): Promise<void> { loadBootServers(): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {

View File

@ -62,22 +62,11 @@
.client-info { .client-info {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
max-width: 220px;
} }
.client-name { .client-name {
font-weight: 500; font-weight: 500;
color: #333; color: #333;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.client-more {
font-weight: 400;
font-style: italic;
color: #666;
cursor: default;
} }
.client-details { .client-details {
@ -86,3 +75,7 @@
font-size: 0.75em; font-size: 0.75em;
color: #666; color: #666;
} }
.client-ip, .client-mac {
font-family: monospace;
}

View File

@ -47,12 +47,11 @@
</mat-icon> </mat-icon>
</ng-container> </ng-container>
<ng-container *ngIf="column.columnDef === 'clients'"> <ng-container *ngIf="column.columnDef === 'client'">
<div *ngIf="column.cell(image) !== 'N/A'; else noClientData" class="client-info"> <div *ngIf="column.cell(image) !== 'N/A'; else noClientData" class="client-info">
<div class="client-name" *ngFor="let assignedClient of getVisibleClients(column.cell(image))">{{ assignedClient.name }}</div> <div class="client-name">{{ column.cell(image).name }}</div>
<div class="client-name client-more" *ngIf="column.cell(image).length > maxVisibleClients" <div class="client-details">
[matTooltip]="getHiddenClientNames(column.cell(image))"> <span class="client-ip">{{ column.cell(image).ip }}</span>
{{ 'andMoreClients' | translate: { count: column.cell(image).length - maxVisibleClients } }}
</div> </div>
</div> </div>
<ng-template #noClientData> <ng-template #noClientData>
@ -61,7 +60,7 @@
</ng-container> </ng-container>
<ng-container <ng-container
*ngIf="column.columnDef !== 'isDefault' && column.columnDef !== 'installed' && column.columnDef !== 'downloadUrl' && column.columnDef !== 'clients'"> *ngIf="column.columnDef !== 'isDefault' && column.columnDef !== 'installed' && column.columnDef !== 'downloadUrl' && column.columnDef !== 'client'">
{{ column.cell(image) }} {{ column.cell(image) }}
</ng-container> </ng-container>
</td> </td>

View File

@ -37,7 +37,6 @@ export class HardwareProfileComponent {
filteredClients!: Observable<any[]>; filteredClients!: Observable<any[]>;
clientControl = new FormControl(); clientControl = new FormControl();
clients: any[] = []; clients: any[] = [];
maxVisibleClients: number = 3;
columns = [ columns = [
{ {
columnDef: 'id', columnDef: 'id',
@ -50,9 +49,13 @@ export class HardwareProfileComponent {
cell: (hardware: any) => hardware.description cell: (hardware: any) => hardware.description
}, },
{ {
columnDef: 'clients', columnDef: 'client',
header: 'clients', header: 'client',
cell: (hardware: any) => hardware.clients?.length ? hardware.clients : 'N/A' cell: (hardware: any) => hardware.client ? {
name: hardware.client.name || 'N/A',
ip: hardware.client.ip || 'N/A',
mac: hardware.client.mac || 'N/A'
} : 'N/A'
}, },
{ {
columnDef: 'createdAt', columnDef: 'createdAt',
@ -101,24 +104,16 @@ export class HardwareProfileComponent {
} }
onOptionClientSelected(selectedClient: any): void { onOptionClientSelected(selectedClient: any): void {
this.filters['clients.id'] = selectedClient.id; this.filters['client.id'] = selectedClient.id;
this.search(); this.search();
} }
clearClientFilter(event: Event, clientSearchClientInput: any): void { clearClientFilter(event: Event, clientSearchClientInput: any): void {
clientSearchClientInput.value = ''; clientSearchClientInput.value = '';
this.filters['clients.id'] = ''; this.filters['client.id'] = '';
this.search(); this.search();
} }
getVisibleClients(clients: any): any[] {
return (clients || []).slice(0, this.maxVisibleClients);
}
getHiddenClientNames(clients: any): string {
return (clients || []).slice(this.maxVisibleClients).map((client: any) => client.name).join(', ');
}
private _filterClients(value: string): any[] { private _filterClients(value: string): any[] {
const filterValue = value.toLowerCase(); const filterValue = value.toLowerCase();

View File

@ -32,6 +32,15 @@
<input matInput formControlName="comments" name="comments"> <input matInput formControlName="comments" name="comments">
</mat-form-field> </mat-form-field>
<mat-form-field appearance="fill" class="form-field">
<mat-label>{{ 'softwareProfile' | translate }}</mat-label>
<mat-select formControlName="softwareProfile">
<mat-option *ngFor="let profile of softwareProfiles" [value]="profile['@id']">
{{ profile.description }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-checkbox formControlName="remotePc"> <mat-checkbox formControlName="remotePc">
{{ 'labelRemotePc' | translate }} {{ 'labelRemotePc' | translate }}
</mat-checkbox> </mat-checkbox>

View File

@ -18,6 +18,7 @@ export class CreateImageComponent implements OnInit {
baseUrl: string; baseUrl: string;
imageForm: FormGroup<any>; imageForm: FormGroup<any>;
imageId: string | null = null; imageId: string | null = null;
softwareProfiles: any[] = [];
repositories: any[] = []; repositories: any[] = [];
loading: boolean = false; loading: boolean = false;
isEditMode: boolean = false; isEditMode: boolean = false;
@ -40,6 +41,7 @@ export class CreateImageComponent implements OnInit {
comments: [''], comments: [''],
remotePc: [false], remotePc: [false],
isGlobal: [false], isGlobal: [false],
softwareProfile: [''],
imageRepositories: [[], Validators.required], imageRepositories: [[], Validators.required],
}); });
} }
@ -52,6 +54,7 @@ export class CreateImageComponent implements OnInit {
} else { } else {
this.loading = false; this.loading = false;
} }
this.fetchSoftwareProfiles();
this.fetchRepositories(); this.fetchRepositories();
} }
@ -64,6 +67,7 @@ export class CreateImageComponent implements OnInit {
comments: response.comments, comments: response.comments,
remotePc: response.remotePc, remotePc: response.remotePc,
isGlobal: response.isGlobal, isGlobal: response.isGlobal,
softwareProfile: response.softwareProfile ? response.softwareProfile['@id'] : null,
imageRepositories: response.imageRepositories ? response.imageRepositories.map((r: any) => r.imageRepository['@id']) : [], imageRepositories: response.imageRepositories ? response.imageRepositories.map((r: any) => r.imageRepository['@id']) : [],
}); });
this.imageId = response['@id']; this.imageId = response['@id'];
@ -81,6 +85,18 @@ export class CreateImageComponent implements OnInit {
this.showWarning = this.imageForm.get('isGlobal')?.value; this.showWarning = this.imageForm.get('isGlobal')?.value;
} }
fetchSoftwareProfiles() {
const url = `${this.baseUrl}/software-profiles`;
this.http.get(url).subscribe({
next: (response: any) => {
this.softwareProfiles = response['hydra:member'];
},
error: (error) => {
this.toastService.error(this.translate.instant('errorGettingProfiles'));
}
});
}
fetchRepositories() { fetchRepositories() {
const url = `${this.baseUrl}/image-repositories`; const url = `${this.baseUrl}/image-repositories`;
this.http.get(url).subscribe({ this.http.get(url).subscribe({
@ -101,6 +117,7 @@ export class CreateImageComponent implements OnInit {
remotePc: this.imageForm.value.remotePc, remotePc: this.imageForm.value.remotePc,
isGlobal: this.imageForm.value.isGlobal, isGlobal: this.imageForm.value.isGlobal,
imageRepositories: this.imageForm.value.imageRepositories, imageRepositories: this.imageForm.value.imageRepositories,
...(this.imageForm.value.softwareProfile ? { softwareProfile: this.imageForm.value.softwareProfile } : {}),
}; };
if (this.imageId) { if (this.imageId) {

View File

@ -64,15 +64,11 @@ export class LoginComponent {
this.auth.refresh(); this.auth.refresh();
this.openSnackBar(false, 'Bienvenido ' + this.auth.username); this.openSnackBar(false, 'Bienvenido ' + this.auth.username);
this.router.navigateByUrl('/groups'); this.router.navigateByUrl('/groups');
// El estado global consulta y sincroniza infraestructura (ogBoot, DHCP,
// repositorios), a la que solo tienen acceso los perfiles de administración.
if (this.auth.isSuperAdmin || this.auth.isOUAdmin) {
this.dialog.open(GlobalStatusComponent, { this.dialog.open(GlobalStatusComponent, {
width: '65vw', width: '65vw',
height: '80vh', height: '80vh',
}); });
} }
}
this.isLoading = false; this.isLoading = false;
}, },
error: (err) => { error: (err) => {

View File

@ -48,8 +48,8 @@ export class CreateMenuComponent implements OnInit {
} }
updateSafeUrl(): void { updateSafeUrl(): void {
const url = `${this.baseUrl}/menu/${this.menuForm.get('publicUrl')?.value}?gui=1&baseUrl=${encodeURIComponent(this.baseUrl)}`; const url = `${this.baseUrl}/menu/${this.menuForm.get('publicUrl')?.value}`;
if (url && this.menuForm.get('publicUrl')?.value) { if (url) {
this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url); this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
} else { } else {
this.safeUrl = null; this.safeUrl = null;
@ -119,9 +119,23 @@ export class CreateMenuComponent implements OnInit {
this.fileContent = base64Content; this.fileContent = base64Content;
// Ask the backend to compile a preview using this encoded Twig // Ask the backend to compile a preview using this encoded Twig
this.dataService.previewMenuTemplate(base64Content, this.baseUrl).subscribe({ this.dataService.previewMenuTemplate(base64Content).subscribe({
next: (renderedHtml) => { next: (renderedHtml) => {
const renderedBytes = new TextEncoder().encode(renderedHtml); // Ensure relative paths work in the data URL iframe by injecting a <base> tag
const origin = new URL(this.baseUrl).origin;
const baseTag = `<base href="${origin}/">`;
let finalHtml = renderedHtml;
if (finalHtml.toLowerCase().includes('<head>')) {
finalHtml = finalHtml.replace(/<head>/i, `<head>${baseTag}`);
} else if (finalHtml.toLowerCase().includes('<html>')) {
finalHtml = finalHtml.replace(/<html>/i, `<html><head>${baseTag}</head>`);
} else {
finalHtml = `<head>${baseTag}</head>` + finalHtml;
}
// Now encode the definitively rendered HTML to Base64 to populate the iframe preview
const renderedBytes = new TextEncoder().encode(finalHtml);
const renderedBinaryStr = Array.from(renderedBytes).map(byte => String.fromCharCode(byte)).join(''); const renderedBinaryStr = Array.from(renderedBytes).map(byte => String.fromCharCode(byte)).join('');
const renderedBase64 = window.btoa(renderedBinaryStr); const renderedBase64 = window.btoa(renderedBinaryStr);

View File

@ -29,9 +29,9 @@ export class DataService {
); );
} }
previewMenuTemplate(base64Template: string, baseUrl?: string): Observable<string> { previewMenuTemplate(base64Template: string): Observable<string> {
const url = `${this.baseUrl}/menu-preview`; const url = `${this.baseUrl}/menu-preview`;
return this.http.post(url, { templateBase64: base64Template, baseUrl: baseUrl }, { responseType: 'text' }).pipe( return this.http.post(url, { templateBase64: base64Template }, { responseType: 'text' }).pipe(
catchError(error => { catchError(error => {
console.error(this.translate.instant('errorPreviewingMenuTemplate'), error); console.error(this.translate.instant('errorPreviewingMenuTemplate'), error);
return throwError(() => error); return throwError(() => error);

View File

@ -9,7 +9,7 @@
{{ 'ogbootServers' | translate }}</h2> {{ 'ogbootServers' | translate }}</h2>
</div> </div>
<div class="images-button-row"> <div class="images-button-row">
<button *ngIf="auth.isSuperAdmin" <button
class="action-button" (click)="addServer()" class="action-button" (click)="addServer()"
joyrideStep="addStep" joyrideStep="addStep"
text="Añadir Servidor Boot">{{ 'addBootServer' | translate }}</button> text="Añadir Servidor Boot">{{ 'addBootServer' | translate }}</button>
@ -51,10 +51,10 @@
<button mat-icon-button color="primary" (click)="syncServer(server)" [matTooltip]="'syncServer' | translate"> <button mat-icon-button color="primary" (click)="syncServer(server)" [matTooltip]="'syncServer' | translate">
<mat-icon>sync</mat-icon> <mat-icon>sync</mat-icon>
</button> </button>
<button *ngIf="auth.isSuperAdmin" mat-icon-button color="primary" (click)="editServer($event, server)" [matTooltip]="'editServerTitle' | translate"> <button mat-icon-button color="primary" (click)="editServer($event, server)" [matTooltip]="'editServerTitle' | translate">
<mat-icon>edit</mat-icon> <mat-icon>edit</mat-icon>
</button> </button>
<button *ngIf="auth.isSuperAdmin" mat-icon-button color="warn" (click)="deleteServer($event, server)" [matTooltip]="'buttonDeleteServer' | translate"> <button mat-icon-button color="warn" (click)="deleteServer($event, server)" [matTooltip]="'buttonDeleteServer' | translate">
<mat-icon>delete</mat-icon> <mat-icon>delete</mat-icon>
</button> </button>
</td> </td>

View File

@ -10,7 +10,6 @@ import {DeleteModalComponent} from "../../../shared/delete_modal/delete-modal/de
import { JoyrideService } from 'ngx-joyride'; import { JoyrideService } from 'ngx-joyride';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
import { AuthService } from '@services/auth.service';
import {ManageBootServerComponent} from "../manage-boot-server/manage-boot-server.component"; import {ManageBootServerComponent} from "../manage-boot-server/manage-boot-server.component";
import { forkJoin } from 'rxjs'; import { forkJoin } from 'rxjs';
@ -21,7 +20,6 @@ import { forkJoin } from 'rxjs';
}) })
export class BootServersComponent implements OnInit { export class BootServersComponent implements OnInit {
public translate = inject(TranslateService); public translate = inject(TranslateService);
public auth = inject(AuthService);
baseUrl: string; baseUrl: string;
private apiUrl: string; private apiUrl: string;
dataSource = new MatTableDataSource<any>(); dataSource = new MatTableDataSource<any>();

View File

@ -25,14 +25,15 @@
</mat-form-field> </mat-form-field>
} }
<app-ou-select <mat-form-field appearance="fill" class="search-boolean" joyrideStep="selectClassStep"
class="search-boolean" text="{{ 'selectClassDescription' | translate }}">
joyrideStep="selectClassStep" <mat-label>{{ 'labelSelectClass' | translate }}</mat-label>
text="{{ 'selectClassDescription' | translate }}" <mat-select (selectionChange)="loadChildUnits($event)">
[units]="units" @for (unit of units; track unit.id) {
[label]="'labelSelectClass'" <mat-option [value]="unit">{{ unit.name }}</mat-option>
(selectionChange)="loadChildUnits($event)"> }
</app-ou-select> </mat-select>
</mat-form-field>
</div> </div>

View File

@ -11,7 +11,6 @@ import { ActivatedRoute } from '@angular/router';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { DeleteModalComponent } from 'src/app/shared/delete_modal/delete-modal/delete-modal.component'; import { DeleteModalComponent } from 'src/app/shared/delete_modal/delete-modal/delete-modal.component';
import { forkJoin } from 'rxjs'; import { forkJoin } from 'rxjs';
import { DataService as GroupsDataService } from '../../groups/services/data.service';
@Component({ @Component({
selector: 'app-pxe-boot-files', selector: 'app-pxe-boot-files',
@ -33,7 +32,6 @@ export class PxeBootFilesComponent implements OnInit {
isFromDashboard: boolean = false; isFromDashboard: boolean = false;
ogLiveOptions: any[] = []; ogLiveOptions: any[] = [];
globalOgLive: string | null = null; globalOgLive: string | null = null;
unitSearchText: string = '';
length: number = 0; length: number = 0;
itemsPerPage: number = 10; itemsPerPage: number = 10;
page: number = 0; page: number = 0;
@ -49,8 +47,7 @@ export class PxeBootFilesComponent implements OnInit {
private configService: ConfigService, private configService: ConfigService,
private joyrideService: JoyrideService, private joyrideService: JoyrideService,
private route: ActivatedRoute, private route: ActivatedRoute,
private dialog: MatDialog, private dialog: MatDialog
private groupsDataService: GroupsDataService
) { ) {
this.baseUrl = this.configService.apiUrl; this.baseUrl = this.configService.apiUrl;
this.taskForm = this.fb.group({ this.taskForm = this.fb.group({
@ -98,27 +95,14 @@ export class PxeBootFilesComponent implements OnInit {
} }
loadUnits() { loadUnits() {
this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=500`).subscribe( this.http.get<any>(`${this.baseUrl}/organizational-units?type=classroom&page=1&itemsPerPage=50`).subscribe(
response => { response => {
const rawUnits = response['hydra:member']; this.units = response['hydra:member'];
this.units = rawUnits
.filter((unit: any) => unit.type === 'classroom')
.map((unit: any) => ({
...unit,
path: this.groupsDataService.getOrganizationalUnitPath(unit, rawUnits)
}));
this.units.sort((a, b) => {
const pathA = a.path || a.name;
const pathB = b.path || b.name;
return pathA.localeCompare(pathB);
});
}, },
error => console.error(this.translate.instant('errorFetchingOrganizationalUnits1'), error) error => console.error(this.translate.instant('errorFetchingOrganizationalUnits1'), error)
); );
} }
fetchPxeTemplates(): void { fetchPxeTemplates(): void {
this.http.get<any>(`${this.baseUrl}/pxe-templates?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }) this.http.get<any>(`${this.baseUrl}/pxe-templates?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters })
.subscribe( .subscribe(
@ -133,20 +117,7 @@ export class PxeBootFilesComponent implements OnInit {
} }
loadChildUnits(event: any) { loadChildUnits(event: any) {
let unitId = event.value; this.selectedUnit = event.value;
// Buscar la unidad organizativa seleccionada para obtener su ID numérico
const selectedUnit = this.units.find(u => (u['@id'] || u.id) === event.value);
if (selectedUnit && selectedUnit.id) {
unitId = selectedUnit.id;
} else if (typeof event.value === 'object' && event.value !== null) {
unitId = event.value.id;
} else if (typeof event.value === 'string' && event.value.includes('/')) {
// Fallback por si acaso no se encuentra
unitId = event.value.split('/').pop();
}
this.selectedUnit = this.units.find(u => u.id == unitId || u['@id'] === event.value) || event.value;
this.refreshClientList(); this.refreshClientList();
} }
@ -154,10 +125,7 @@ export class PxeBootFilesComponent implements OnInit {
if (!this.selectedUnit) return; if (!this.selectedUnit) return;
this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${this.selectedUnit.id}`).subscribe( this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${this.selectedUnit.id}`).subscribe(
response => { response => {
this.dataSource.data = response['hydra:member'].map((client: any) => ({ this.dataSource.data = response['hydra:member'];
...client,
ogLive: client.pxeTemplate ? client.pxeTemplate['@id'] : null
}));
}, },
error => console.error(this.translate.instant('errorFetchingChildUnits'), error) error => console.error(this.translate.instant('errorFetchingChildUnits'), error)
); );

View File

@ -39,3 +39,4 @@ mat-dialog-actions {
display: block; display: block;
margin-bottom: 10px; margin-bottom: 10px;
} }

View File

@ -3,13 +3,12 @@
<h2 mat-dialog-title>Añade clientes a {{data.subnetName}}</h2> <h2 mat-dialog-title>Añade clientes a {{data.subnetName}}</h2>
<mat-dialog-content> <mat-dialog-content>
<app-ou-select <mat-form-field appearance="fill" class="full-width">
class="full-width" <mat-label>{{ 'selectClassroomPrompt' | translate }}</mat-label>
[formControl]="unitControl" <mat-select [formControl]="unitControl" (selectionChange)="loadChildUnits($event)">
[units]="units" <mat-option *ngFor="let unit of units" [value]="unit">{{ unit.name }}</mat-option>
[label]="'selectClassroomPrompt'" </mat-select>
(selectionChange)="loadChildUnits($event)"> </mat-form-field>
</app-ou-select>
<div class="checkbox-group"> <div class="checkbox-group">
<label>{{ 'labelClients' | translate }}</label> <label>{{ 'labelClients' | translate }}</label>
@ -18,20 +17,16 @@
{{ allSelected ? 'Deseleccionar todos' : 'Seleccionar todos' }} {{ allSelected ? 'Deseleccionar todos' : 'Seleccionar todos' }}
</button> </button>
@if (clients.length > 0) { <div *ngIf="clients.length > 0" class="clients-grid">
<div class="clients-grid"> <mat-checkbox *ngFor="let client of clients"
@for (client of clients; track client.uuid) { (change)="toggleClientSelection(client.uuid)"
<mat-checkbox (change)="toggleClientSelection(client.uuid)"
[checked]="selectedClients.includes(client.uuid)"> [checked]="selectedClients.includes(client.uuid)">
{{ client.name }} {{ client.name }}
</mat-checkbox> </mat-checkbox>
}
</div> </div>
} @else { <div *ngIf="clients.length === 0">
<div>
<p>{{ 'noClientsMessage' | translate }}</p> <p>{{ 'noClientsMessage' | translate }}</p>
</div> </div>
}
</div> </div>
</mat-dialog-content> </mat-dialog-content>

View File

@ -7,7 +7,6 @@ import { FormControl } from '@angular/forms';
import { ToastrService } from 'ngx-toastr'; import { ToastrService } from 'ngx-toastr';
import { OperationResultDialogComponent } from "../operation-result-dialog/operation-result-dialog.component"; import { OperationResultDialogComponent } from "../operation-result-dialog/operation-result-dialog.component";
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
import { DataService as GroupsDataService } from "../../groups/services/data.service";
@Component({ @Component({
selector: 'app-add-clients-to-subnet', selector: 'app-add-clients-to-subnet',
@ -25,14 +24,12 @@ export class AddClientsToSubnetComponent implements OnInit {
childUnitControl = new FormControl(); childUnitControl = new FormControl();
allSelected: boolean = false; allSelected: boolean = false;
constructor( constructor(
private http: HttpClient, private http: HttpClient,
public dialogRef: MatDialogRef<AddClientsToSubnetComponent>, public dialogRef: MatDialogRef<AddClientsToSubnetComponent>,
private toastService: ToastrService, private toastService: ToastrService,
public dialog: MatDialog, public dialog: MatDialog,
private configService: ConfigService, private configService: ConfigService,
private groupsDataService: GroupsDataService,
@Inject(MAT_DIALOG_DATA) public data: { subnetUuid: string, subnetName: string } @Inject(MAT_DIALOG_DATA) public data: { subnetUuid: string, subnetName: string }
) { ) {
this.baseUrl = this.configService.apiUrl; this.baseUrl = this.configService.apiUrl;
@ -46,39 +43,15 @@ export class AddClientsToSubnetComponent implements OnInit {
loadUnits() { loadUnits() {
this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=500`).subscribe( this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=500`).subscribe(
response => { response => {
const rawUnits = response['hydra:member']; this.units = response['hydra:member'];
this.units = rawUnits.map((unit: any) => ({
...unit,
name: unit.name,
path: this.groupsDataService.getOrganizationalUnitPath(unit, rawUnits)
}));
this.units.sort((a, b) => {
const pathA = a.path || a.name;
const pathB = b.path || b.name;
return pathA.localeCompare(pathB);
});
this.loading = false; this.loading = false;
}, },
error => console.error(this.translate.instant('errorFetchingOrganizationalUnits1'), error) error => console.error(this.translate.instant('errorFetchingOrganizationalUnits1'), error)
); );
} }
loadChildUnits(event: any) { loadChildUnits(event: any) {
let unitId = event.value; this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${event.value.id}&exists[subnet]=false`).subscribe(
// Buscar la unidad organizativa seleccionada para obtener su ID numérico
const selectedUnit = this.units.find(u => (u['@id'] || u.id) === event.value);
if (selectedUnit && selectedUnit.id) {
unitId = selectedUnit.id;
} else if (typeof event.value === 'object' && event.value !== null) {
unitId = event.value.id;
} else if (typeof event.value === 'string' && event.value.includes('/')) {
// Fallback por si acaso no se encuentra (aunque debería)
unitId = event.value.split('/').pop();
}
this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${unitId}&exists[subnet]=false`).subscribe(
response => { response => {
this.clients = response['hydra:member']; this.clients = response['hydra:member'];
}, },

View File

@ -9,7 +9,7 @@
{{ 'dhcpServers' | translate }}</h2> {{ 'dhcpServers' | translate }}</h2>
</div> </div>
<div class="images-button-row"> <div class="images-button-row">
<button *ngIf="auth.isSuperAdmin" <button
class="action-button" (click)="addServer()" class="action-button" (click)="addServer()"
joyrideStep="addStep" joyrideStep="addStep"
text="Añadir Servidor DHCP">{{ 'addDhcpServer' | translate }}</button> text="Añadir Servidor DHCP">{{ 'addDhcpServer' | translate }}</button>
@ -54,9 +54,9 @@
<ng-container matColumnDef="actions"> <ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'actions' | translate }}</th> <th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'actions' | translate }}</th>
<td mat-cell *matCellDef="let server" style="text-align: center;" joyrideStep="actionsStep"> <td mat-cell *matCellDef="let server" style="text-align: center;" joyrideStep="actionsStep">
<button *ngIf="auth.isSuperAdmin" mat-icon-button color="primary" (click)="editServer($event, server)" [matTooltip]="'editServerTitle' | translate"> <button mat-icon-button color="primary" (click)="editServer($event, server)" [matTooltip]="'editServerTitle' | translate">
<mat-icon>edit</mat-icon></button> <mat-icon>edit</mat-icon></button>
<button *ngIf="auth.isSuperAdmin" mat-icon-button color="warn" (click)="deleteServer($event, server)" [matTooltip]="'buttonDeleteServer' | translate"> <button mat-icon-button color="warn" (click)="deleteServer($event, server)" [matTooltip]="'buttonDeleteServer' | translate">
<mat-icon>delete</mat-icon> <mat-icon>delete</mat-icon>
</button> </button>
</td> </td>

View File

@ -10,7 +10,6 @@ import {DeleteModalComponent} from "../../../shared/delete_modal/delete-modal/de
import { JoyrideService } from 'ngx-joyride'; import { JoyrideService } from 'ngx-joyride';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { ConfigService } from '@services/config.service'; import { ConfigService } from '@services/config.service';
import { AuthService } from '@services/auth.service';
import {ManageDhcpServerComponent} from "../manage-dhcp-server/manage-dhcp-server.component"; import {ManageDhcpServerComponent} from "../manage-dhcp-server/manage-dhcp-server.component";
@Component({ @Component({
@ -20,7 +19,6 @@ import {ManageDhcpServerComponent} from "../manage-dhcp-server/manage-dhcp-serve
}) })
export class DhcpServersComponent implements OnInit { export class DhcpServersComponent implements OnInit {
public translate = inject(TranslateService); public translate = inject(TranslateService);
public auth = inject(AuthService);
baseUrl: string; baseUrl: string;
private apiUrl: string; private apiUrl: string;
dataSource = new MatTableDataSource<any>(); dataSource = new MatTableDataSource<any>();

Some files were not shown because too many files have changed in this diff Show More